SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
perf: hovering a large body never waits for its pick index or plan mesh (#3745) (#3766)
bherbruck754eb56e5bd3
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex fecbe34d75..fdea27a9ca 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -163,6 +163,40 @@ impl ModelBody {.clone()}+ /// [`ModelBody::plan_mesh`] if it is made already; otherwise it is made on a worker thread+ /// (once, however often this is asked) and `None` comes back meanwhile, so a caller drawing a+ /// frame (a face highlighted under the pointer) is not held up by a large body's plan+ /// (#3745): the plan mesh of a long modelled thread takes most of a second. The browser+ /// build has no threads: there it is made now.+ pub fn plan_mesh_soon(&self) -> Option<Arc<Mesh>> {+ let q = crate::display_quality::current();+ let cell = self.plan_mesh.get(q.index())?;+ if let Some(mesh) = cell.get() {+ return mesh.clone();+ }+ #[cfg(not(target_arch = "wasm32"))]+ {+ static WARMING: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());+ let key = Arc::as_ptr(&self.plan_mesh) as usize + q.index();+ let Ok(mut warming) = WARMING.lock() else { return None };+ if warming.contains(&key) {+ return None;+ }+ let body = self.clone();+ let started = std::thread::Builder::new().name("plan-mesh".into()).spawn(move || {+ let _ = body.plan_mesh_at(q);+ if let Ok(mut warming) = WARMING.lock() {+ warming.retain(|k| *k != key);+ }+ });+ if started.is_ok() {+ warming.push(key);+ return None;+ }+ }+ self.plan_mesh_at(q)+ }+/// The display plan and its mesh `k` steps finer than `q` (view-dependent refinement, #1320;/// see [`crate::display_quality::refinement_for`]). Step 0 is the cached plan at `q`; finer/// steps are made on each call and kept by the viewport, which evicts them when it runs overdiff --git a/crates/doc/src/placed_mesh.rs b/crates/doc/src/placed_mesh.rsindex f07d48e0c0..6da3c4e083 100644--- a/crates/doc/src/placed_mesh.rs+++ b/crates/doc/src/placed_mesh.rs@@ -201,6 +201,23 @@ mod tests {}}+ /// #3745: a highlight never waits for a body's plan mesh: the first ask starts it on a+ /// worker and answers `None`, and once made it is the plan mesh, in the body's own cell.+ #[test]+ fn plan_mesh_soon_makes_it_on_a_worker() {+ let body = ModelBody::new("Pin".into(), kernel::cylinder(Vec3::ZERO, Vec3::Z, 2., 8.).unwrap(), 1);+ assert!(body.plan_mesh_soon().is_none(), "not made in the asking frame");+ let began = std::time::Instant::now();+ let soon = loop {+ if let Some(mesh) = body.plan_mesh_soon() {+ break mesh;+ }+ assert!(began.elapsed() < std::time::Duration::from_secs(30), "the worker made it");+ std::thread::sleep(std::time::Duration::from_millis(2));+ };+ assert!(Arc::ptr_eq(&soon, &body.plan_mesh().unwrap()), "the same mesh, in the body's cell");+ }+#[test]fn world_instances_warm_one_definition_and_an_edit_replaces_it() {let mut doc = crate::Document::new("instances");diff --git a/crates/ui-egui/src/pick_index.rs b/crates/ui-egui/src/pick_index.rsindex f19c44eafe..8ff6956b2b 100644--- a/crates/ui-egui/src/pick_index.rs+++ b/crates/ui-egui/src/pick_index.rs@@ -2,7 +2,9 @@//! triangles and edge segments in hierarchies), made the first time a pick reaches the body and//! kept while the mesh is. The viewport's picker asks it for the nearest triangle along the//! cursor's ray and for the edge segments near that ray, then runs its exact screen tests on-//! those alone.+//! those alone. A large mesh's index takes a while to make (a third of a second for a long+//! modelled thread, #3745), so it is made on a worker thread, and picks scan the mesh until it+//! is there: a scan takes a few milliseconds, the index a frame never waits for.use std::collections::HashMap;use std::sync::{Arc, Mutex};@@ -12,21 +14,47 @@ use solidcraft_engine::geom::{Mesh, MeshIndex, Vec3};use crate::viewport::Proj;-/// Indexes by mesh address, each with its mesh held (so the address stays its own).+/// Indexes by mesh address, each with its mesh held (so the address stays its own); `None`+/// while a worker is still making it.#[derive(Default)]-pub(crate) struct PickIndexes(Mutex<HashMap<usize, (Arc<Mesh>, Arc<MeshIndex>)>>);+pub(crate) struct PickIndexes(Arc<Mutex<Indexes>>);++type Indexes = HashMap<usize, (Arc<Mesh>, Option<Arc<MeshIndex>>)>;++/// Meshes up to this many triangles and edge points get their index at once (it takes well under+/// a millisecond); larger ones on a worker.+#[cfg_attr(target_arch = "wasm32", allow(dead_code))]+const AT_ONCE: usize = 20_000;impl PickIndexes {- /// The index of `mesh`, made now when there is none yet.- pub(crate) fn of(&self, mesh: &Arc<Mesh>) -> Arc<MeshIndex> {+ /// The index of `mesh`, or `None` while it is being made (the caller scans the mesh).+ pub(crate) fn of(&self, mesh: &Arc<Mesh>) -> Option<Arc<MeshIndex>> {let key = Arc::as_ptr(mesh) as usize;- let Ok(mut map) = self.0.lock() else { return Arc::new(MeshIndex::new(mesh)) };+ let Ok(mut map) = self.0.lock() else { return Some(Arc::new(MeshIndex::new(mesh))) };if let Some((_, index)) = map.get(&key) {return index.clone();}+ let size = mesh.triangles.len() + mesh.edges.iter().map(Vec::len).sum::<usize>();+ #[cfg(not(target_arch = "wasm32"))]+ if size > AT_ONCE {+ map.insert(key, (mesh.clone(), None));+ let (indexes, source) = (self.0.clone(), mesh.clone());+ let started = std::thread::Builder::new().name("pick-index".into()).spawn(move || {+ let index = Arc::new(MeshIndex::new(&source));+ if let Ok(mut map) = indexes.lock()+ && let Some(slot) = map.get_mut(&key)+ {+ slot.1 = Some(index);+ }+ });+ if started.is_ok() {+ return None;+ }+ }+ let _ = size;let index = Arc::new(MeshIndex::new(mesh));- map.insert(key, (mesh.clone(), index.clone()));- index+ map.insert(key, (mesh.clone(), Some(index.clone())));+ Some(index)}/// Drops the indexes of meshes `keep` no longer names (a new model state).@@ -59,25 +87,25 @@ pub(crate) fn reach(proj: &Proj, pos: Pos2, px: f32) -> (f64, f64) {/// The edge segments of `index` that may come within reach of the ray, as (edge, first point),/// in edge order and then along each edge: the order a scan of every edge would meet them in.-pub(crate) fn segments_near(index: &MeshIndex, mesh: &Mesh, o: Vec3, d: Vec3, (a, b): (f64, f64)) -> Vec<(usize, usize)> {+pub(crate) fn segments_near(index: Option<&MeshIndex>, mesh: &Mesh, o: Vec3, d: Vec3, (a, b): (f64, f64)) -> Vec<(usize, usize)> {let mut v = Vec::new();- if scanning() {+ let Some(index) = index.filter(|_| !scanning()) else {for (ei, e) in mesh.edges.iter().enumerate() {v.extend((0..e.len().max(2) - 1).map(|si| (ei, si)));}return v;- }+ };index.segments_near(o, d, a, b, |e, s| v.push((e, s)));v.sort_unstable();v}/// The nearest triangle of `mesh` along the ray, through its index.-pub(crate) fn raycast(index: &MeshIndex, mesh: &Mesh, o: Vec3, d: Vec3) -> Option<(f64, usize)> {- if scanning() {- return mesh.raycast(o, d);+pub(crate) fn raycast(index: Option<&MeshIndex>, mesh: &Mesh, o: Vec3, d: Vec3) -> Option<(f64, usize)> {+ match index.filter(|_| !scanning()) {+ Some(index) => index.raycast(mesh, o, d),+ None => mesh.raycast(o, d),}- index.raycast(mesh, o, d)}#[cfg(test)]diff --git a/crates/ui-egui/src/preselect_tests.rs b/crates/ui-egui/src/preselect_tests.rsindex 05ff9861af..c2af87bf0b 100644--- a/crates/ui-egui/src/preselect_tests.rs+++ b/crates/ui-egui/src/preselect_tests.rs@@ -2118,3 +2118,58 @@ fn convert_mesh_asks_for_the_body_and_converts_the_selected_one() {let state = h.app.session.model.state();assert!(!state.body("Mesh").unwrap().body.is_mesh(), "rebuilt as faces");}++/// #3745: hovering a large body never waits for its pick index. A long modelled thread's mesh+/// has a quarter of a million triangles and its index took a third of a second to make, on the+/// first hover, in the frame. Now the index is made on a worker and the first hovers scan the+/// mesh: the first hover takes a small part of what making the index takes, and still finds+/// the face under the pointer.+#[test]+fn hovering_a_large_body_does_not_wait_for_its_pick_index() {+ // A closed ball of 300 000 triangles, inserted as a mesh body.+ let (rings, segments) = (500usize, 300usize);+ let at = |i: usize, j: usize| {+ let (theta, phi) = (std::f64::consts::PI * i as f64 / rings as f64, std::f64::consts::TAU * j as f64 / segments as f64);+ [20.0 * theta.sin() * phi.cos(), 20.0 * theta.sin() * phi.sin(), 20.0 * theta.cos()]+ };+ let mut stl = vec![0u8; 80];+ let mut tris: Vec<[[f64; 3]; 3]> = Vec::new();+ for i in 0..rings {+ for j in 0..segments {+ let (a, b, c, d) = (at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1));+ if i > 0 {+ tris.push([a, b, d]);+ }+ if i + 1 < rings {+ tris.push([b, c, d]);+ }+ }+ }+ stl.extend((tris.len() as u32).to_le_bytes());+ for t in &tris {+ stl.extend([0u8; 12]);+ for p in t {+ for c in p {+ stl.extend((*c as f32).to_le_bytes());+ }+ }+ stl.extend([0u8; 2]);+ }+ let mut h = crate::scenario::Harness::new();+ let path = h.dir.join("ball.stl");+ std::fs::write(&path, stl).unwrap();+ h.app.run("file.insert_mesh", json!({"path": path.to_string_lossy()})).unwrap();+ let mesh = h.app.session.world_state().bodies[0].mesh();+ assert!(mesh.triangles.len() > 250_000, "{}", mesh.triangles.len());+ let t = std::time::Instant::now();+ let _ = solidcraft_engine::geom::MeshIndex::new(&mesh);+ let index_ms = t.elapsed().as_secs_f64() * 1000.0;+ h.app.fit_view();+ h.frames(3);+ let at = h.at(&json!({"world": [0.0, -20.0, 0.0]})).unwrap();+ let t = std::time::Instant::now();+ h.step(&json!({"move": at})).unwrap();+ let hover_ms = t.elapsed().as_secs_f64() * 1000.0;+ assert!(matches!(h.app.viewport.hover, Some(crate::viewport::Hit::Face { .. })), "{:?}", h.app.viewport.hover);+ assert!(hover_ms < index_ms / 3.0, "the first hover took {hover_ms:.1} ms; making the index takes {index_ms:.1} ms");+}diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rsindex f9eb81915f..7260a695fa 100644--- a/crates/ui-egui/src/viewport.rs+++ b/crates/ui-egui/src/viewport.rs@@ -468,7 +468,9 @@ fn shown_mesh((app.viewport.gpu.is_some_and(|g| g.tess) && opaque()).then(|| drawn_plan(app, b, true)).flatten()- .and_then(|_| b.plan_mesh())+ // A large body's plan mesh is made on a worker: until then its faces are lit on the+ // mesh drawn here (#3745).+ .and_then(|_| b.plan_mesh_soon()).unwrap_or_else(|| drawn_mesh(app, b))}@@ -1343,7 +1345,7 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool,}}let m = b.mesh();- if let Some((t, ti)) = crate::pick_index::raycast(&app.viewport.pick_index.of(&m), &m, o, d) {+ if let Some((t, ti)) = crate::pick_index::raycast(app.viewport.pick_index.of(&m).as_deref(), &m, o, d) {let fi = m.tri_face.get(ti).copied().unwrap_or(0) as usize;let hit = Hit::Face { body: b.name.clone(), index: fi, point: o + d * t };if bestf.as_ref().is_none_or(|(bt, _)| t < *bt) {@@ -1381,7 +1383,7 @@ fn pick_hits(app: &SolveApp, proj: &Proj, pos: Pos2, other_sketch_points: bool,// them, so ties go the same way.let near = match &seen {Some(seen) => seen.segments(i, &m),- None => crate::pick_index::segments_near(&app.viewport.pick_index.of(&m), &m, o, d, reach),+ None => crate::pick_index::segments_near(app.viewport.pick_index.of(&m).as_deref(), &m, o, d, reach),};let mut last_edge = None;for (ei, si) in near {