Viewport: faster highlight with many bodies selected (#10204)

* claim: faster highlight with many bodies selected

* Viewport: find selected bodies by name once per highlight build

With every body of a large assembly selected, each hover change built the
highlight again and looked every selected body up along the world's bodies
(`ModelState::body` scans them), which is quadratic: about 2.2 million name
comparisons on 2,116 bodies, some 3 ms of every hover change.

The selected bodies, faces and edges are now found in a map by name, made at
the first lookup. A name held by more than one body finds the first, as the
scan did, so the same bodies are lit in the same order.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Viewport: measure hover changes with many bodies selected

An ignored scale test: every body of a design selected (a file named by
SOLIDCRAFT_SCALE_DESIGN, else a generated grid of 1,440 boxes), the pointer
moving from face to face, timing each hover change's highlight build headless
and as the app builds it on a GPU (bodies drawn from their plans, and from the
model scene's blocks). Run with `--ignored --nocapture`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Markus Kaltenbrunner <kaltenbrunnermarkus@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-10-31 23:14:05 +00:00
1 parent beb35029a4
commit a5c8fa7be7
2 files changed
+128 -4

No files matched your search

+60
View File
@@ -609,3 +609,63 @@ fn zoomed_view_frame_cost() {
"ZOOMED whole_ms={whole:.2} whole_triangles={whole_tris} zoomed_ms={zoomed:.2} zoomed_triangles={zoomed_tris} zoomed_orbit_ms={orbit:.2}"
);
}
/// Every body of a design selected (`SOLIDCRAFT_SCALE_DESIGN`, or a generated grid of 1,440
/// boxes), the pointer moving from face to face: the time of each hover
/// change's highlight build, headless and as the app builds it on a GPU (bodies drawn from their
/// plans, and from the model's own blocks). Run with `--ignored --nocapture`.
#[test]
#[ignore = "manual highlight measurement"]
fn many_selected_bodies_hover_cost() {
use solidcraft_engine::geom::Vec3;
let mut h = match std::env::var_os("SOLIDCRAFT_SCALE_DESIGN") {
Some(path) => {
let mut h = Harness::new();
h.app.run("doc.open", json!({"path": path.to_string_lossy()})).unwrap();
h.frames(3);
h
}
None => grid(1440),
};
let st = h.app.session.world_state();
st.warm_meshes(|| true);
for b in &st.bodies {
let _ = b.display_plan();
}
let bodies: Vec<(String, usize)> = st.bodies.iter().map(|b| (b.name.clone(), b.body.face_count())).collect();
drop(st);
let big = (0..bodies.len()).max_by_key(|&i| bodies[i].1).unwrap_or(0);
let median = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
let modes: [(&str, Option<bool>); 3] = [("headless", None), ("gpu_plans", Some(true)), ("gpu_blocks", Some(false))];
for (mode, tess) in modes {
h.app.viewport.gpu =
tess.map(|tess| crate::gpu::GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess, oit: false });
drop(crate::viewport::build_scene(&h.app));
for (selected, biggest) in [(false, false), (true, false), (false, true), (true, true)] {
h.app.session.selection =
if selected { bodies.iter().map(|(name, _)| solidcraft_engine::Sel::Body { name: name.clone() }).collect() } else { Vec::new() };
let hover = |h: &mut Harness, i: usize| {
let (name, faces) = if biggest { &bodies[big] } else { &bodies[(i * 37) % bodies.len()] };
h.app.viewport.hover = Some(crate::viewport::Hit::Face { body: name.clone(), index: (i * 7) % (*faces).max(1), point: Vec3::ZERO });
};
hover(&mut h, 0);
drop(crate::viewport::build_highlight(&h.app));
let loops = std::env::var("SOLIDCRAFT_SCALE_LOOP").ok().and_then(|v| v.parse().ok()).unwrap_or(31);
let changes: Vec<f64> = (1..=loops)
.map(|i| {
hover(&mut h, i);
ms(|| drop(crate::viewport::build_highlight(&h.app)))
})
.collect();
println!(
"MANYSEL bodies={} mode={mode} all_selected={selected} hovering_biggest_body={biggest} hover_change_median_ms={:.3} hover_change_max_ms={:.3}",
bodies.len(),
median(changes.clone()),
changes.iter().copied().fold(0.0, f64::max)
);
}
}
}
+68 -4
View File
@@ -3635,6 +3635,29 @@ fn highlight_block_tris(app: &SolveApp, b: &solidcraft_engine::doc::ModelBody) -
map.get(&b.name).cloned()
}
/// The world's bodies by name, the map made at the first lookup: [`ModelState::body`] looks along
/// every body, so a highlight with thousands of bodies selected looked up each of them that way.
/// A name held by more than one body finds the first, as `ModelState::body` does.
///
/// [`ModelState::body`]: solidcraft_engine::doc::ModelState::body
struct BodiesByName<'a> {
state: &'a solidcraft_engine::doc::ModelState,
map: Option<std::collections::HashMap<&'a str, &'a solidcraft_engine::doc::ModelBody>>,
}
impl<'a> BodiesByName<'a> {
fn new(state: &'a solidcraft_engine::doc::ModelState) -> Self {
Self { state, map: None }
}
fn get(&mut self, name: &str) -> Option<&'a solidcraft_engine::doc::ModelBody> {
let state = self.state;
// Last inserted wins: the bodies go in from the last, so the first of a name is kept.
let map = self.map.get_or_insert_with(|| state.bodies.iter().rev().map(|b| (b.name.as_str(), b)).collect());
map.get(name).copied()
}
}
/// How a whole body is lit: hovered or selected, and in which colour (where the model's own
/// colour is not kept: placements, and faded or see-through bodies).
#[derive(Clone, Copy)]
@@ -3875,18 +3898,21 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
}
}
}
// Selected things.
// Selected things. Their bodies are found by name in a map made once, at the first lookup:
// looking each one up along the world's bodies made Select All on an assembly of thousands
// of bodies quadratic (millions of name comparisons on every hover change).
let mut by_name = BodiesByName::new(&st);
for x in &sel {
match x {
Sel::Face { body, index, .. } => {
// A live preview stands in for the body: its old faces would fight with it.
if let Some(b) = st.body(body).filter(|_| app.body_visible(body) && !replaced(body)) {
if let Some(b) = by_name.get(body).filter(|_| app.body_visible(body) && !replaced(body)) {
face_tris(&mut feedback, &shown(b), *index, c4(t.sel_face), false);
hidden_face_outline(&mut feedback, &drawn(b), *index, t.sel_edge);
}
}
Sel::Body { name } => {
if let Some(b) = st.body(name)
if let Some(b) = by_name.get(name)
&& app.body_visible(name)
{
let lit = WholeBody { selected: true, colour: c4(t.body_selected) };
@@ -3898,7 +3924,7 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
}
}
Sel::Edge { body, index, point } => {
if let Some(b) = st.body(body)
if let Some(b) = by_name.get(body)
&& app.body_visible(body)
&& !moving(body)
{
@@ -9497,6 +9523,44 @@ mod tests {
}
}
/// Every body selected (Select All on an assembly) looks each body up by name in a map, not
/// along the world's bodies: the map finds the same body a scan finds for every name (the
/// first one, were a name held twice) and none for a name no body has, and the highlight
/// lights every selected body once, with a selected face and edge as before.
#[test]
fn selected_bodies_found_by_name_are_the_bodies_a_scan_finds() {
let mut app = cylinder_app();
app.viewport.gpu = Some(GpuTarget { format: egui_wgpu::wgpu::TextureFormat::Rgba8Unorm, depth: None, samples: 1, tess: true, oit: false });
app.run("solid.box", json!({"length": 4, "width": 4, "height": 4, "center": [40, 0, 2], "operation": "new", "name": "Seed"})).unwrap();
app.run("solid.pattern.rectangular", json!({"features": ["Seed"], "dir1": [1, 0, 0], "count1": 6, "spacing1": 6, "name": "Row"})).unwrap();
let st = app.session.world_state();
assert_eq!(st.bodies.len(), 7);
let mut by_name = BodiesByName::new(&st);
for b in &st.bodies {
let found = by_name.get(&b.name).expect("every body is found by its name");
assert!(std::ptr::eq(found, st.body(&b.name).unwrap()), "{}: the body a scan finds", b.name);
}
assert!(by_name.get("No such body").is_none());
let mut twice = (*st).clone();
let mut copy = twice.bodies[1].clone();
copy.name = twice.bodies[0].name.clone();
twice.bodies.push(copy);
let mut by_name = BodiesByName::new(&twice);
assert!(std::ptr::eq(by_name.get(&twice.bodies[0].name).unwrap(), &twice.bodies[0]), "a name held twice finds the first body");
let names: Vec<String> = st.bodies.iter().map(|b| b.name.clone()).collect();
let first = st.bodies[0].clone();
drop(st);
let mut selection: Vec<Sel> = names.iter().map(|name| Sel::Body { name: name.clone() }).collect();
selection.push(Sel::Face { body: first.name.clone(), index: 0, point: Vec3::ZERO });
selection.push(Sel::Edge { body: first.name.clone(), index: 0, point: Vec3::ZERO });
app.session.selection = selection;
let lit = build_highlight(&app);
assert_eq!(lit.selected_planned.len() + lit.selected_blocks.len(), names.len(), "every selected body is lit once");
let merged = lit.merged();
assert!(!merged.tris.is_empty(), "the selected face is lit");
assert!(!merged.lines.is_empty() || !merged.overlay.is_empty() || !merged.hidden.is_empty(), "the selected edge is lit");
}
/// A whole highlighted body is lit from the model's own triangles, not by copying every one
/// of them onto the CPU (a whole assembly lit that way took most of a second a frame): from
/// its display plan where the model draws one, else from its vertices in the model scene's