Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Assembly: deeply nested body selection no longer stalls the window (#7502) (#7694)

Dahak Buildsebdc0bc07e72
diff --git a/crates/engine/src/cmd/occurrence_tests.rs b/crates/engine/src/cmd/occurrence_tests.rs
index 5b3c2df45a..94d6bd928a 100644
--- a/crates/engine/src/cmd/occurrence_tests.rs
+++ b/crates/engine/src/cmd/occurrence_tests.rs
@@ -1383,3 +1383,67 @@ fn a_body_seen_in_another_placement_copies_from_there() {
let state = s.model.state();
assert_eq!(s.doc.model_body_component(state.body("Cube (2)").unwrap()), 0);
}
+
+/// A nested assembly's body listing, and the indexed placement agreeing with the plain walk
+/// (#7502: listing a subtree must cost the subtree, not the subtree times the design).
+#[test]
+fn occurrence_bodies_lists_a_nested_assembly() {
+ let mut s = Session::default();
+ let (_outer, outer) = created(&mut s, "Outer");
+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "body_name": "Shell"}));
+ let (_middle, middle) = created(&mut s, "Middle");
+ run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "body_name": "Plate"}));
+ let (_inner, inner) = created(&mut s, "Inner");
+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Pin"}));
+ let deep = [outer, middle, inner];
+ let sorted = |v: Vec<String>| {
+ let mut v = v;
+ v.sort();
+ v
+ };
+ assert_eq!(sorted(s.occurrence_bodies(&deep, true).unwrap()), ["Pin"]);
+ assert_eq!(sorted(s.occurrence_bodies(&[outer, middle], true).unwrap()), ["Pin", "Plate"]);
+ assert_eq!(sorted(s.occurrence_bodies(&[outer], true).unwrap()), ["Pin", "Plate", "Shell"]);
+ assert_eq!(sorted(s.occurrence_bodies(&[outer, middle], false).unwrap()), ["Plate"]);
+ // The indexed placement answers exactly what the plain walk does.
+ for path in [&deep[..], &[outer, middle][..], &[outer][..]] {
+ let (indexed, walked) = (s.occurrence_placement(path).unwrap(), s.occurrence_placement_walk(path).unwrap());
+ assert_eq!(indexed.component, walked.component);
+ assert_eq!(indexed.name, walked.name);
+ assert_eq!(indexed.world, walked.world);
+ assert_eq!(indexed.bodies.len(), walked.bodies.len());
+ for (a, b) in indexed.bodies.iter().zip(&walked.bodies) {
+ assert_eq!((a.source.as_str(), a.world.as_str()), (b.source.as_str(), b.world.as_str()));
+ }
+ }
+}
+
+/// A burst of other paths retires single remembered answers instead of clearing the whole
+/// cache, so the active occurrence's listing survives and needn't re-expand (#7502).
+#[test]
+fn occurrence_bodies_cache_retires_one_answer_when_full() {
+ let mut s = Session::default();
+ let (_assembly, assembly) = created(&mut s, "Assembly");
+ let (part, _) = created(&mut s, "Part");
+ run(&mut s, "solid.box", json!({"length": 1, "width": 1, "height": 1, "body_name": "Part"}));
+ let mut copies = Vec::new();
+ for i in 0..130 {
+ let o = run(&mut s, "occurrence.copy", json!({"component": part, "translate": [i as f64 * 10.0, 0.0, 0.0]}))["occurrence"].as_u64().unwrap();
+ copies.push(o);
+ }
+ // The active listing (the whole assembly) is asked first and remembered.
+ let root = vec![assembly];
+ assert_eq!(s.occurrence_bodies(&root, true).unwrap().len(), 131);
+ // Then a burst of per-copy queries: 260 more keys, over the cache's 256-entry limit.
+ for o in &copies {
+ let path = vec![assembly, *o];
+ assert_eq!(s.occurrence_bodies(&path, false).unwrap().len(), 1);
+ assert_eq!(s.occurrence_bodies(&path, true).unwrap().len(), 1);
+ }
+ let guard = s.occurrence_bodies_cache.lock().unwrap();
+ let cache = guard.as_ref().unwrap();
+ assert!(cache.bodies.contains_key(&(root.clone(), true)), "the active listing survives a burst of other paths");
+ assert!(cache.bodies.len() <= 256, "the cache stays bounded at its limit");
+ drop(guard);
+ assert_eq!(s.occurrence_bodies(&root, true).unwrap().len(), 131);
+}
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 85600713be..4f7207088f 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -386,6 +386,7 @@ pub struct Session {
occurrence_visibility_cache: std::sync::Mutex<Option<occurrences::VisibilityCache>>,
removed_later_cache: std::sync::Mutex<Option<occurrences::RemovedLaterCache>>,
occurrence_bodies_cache: std::sync::Mutex<Option<occurrences::OccurrenceBodiesCache>>,
+ placement_index_cache: std::sync::Mutex<Option<occurrences::PlacementIndex>>,
/// Pairs `inspect.clearance` measured, by the bodies' geometry where they stood (shared with
/// scratch copies): a body that did not change or move is not measured again.
clearance_cache: std::sync::Arc<std::sync::Mutex<cmd::clearance::PairCache>>,
@@ -575,6 +576,7 @@ impl Session {
occurrence_visibility_cache: Default::default(),
removed_later_cache: Default::default(),
occurrence_bodies_cache: Default::default(),
+ placement_index_cache: Default::default(),
clearance_cache: Default::default(),
body_renames: Vec::new(),
contact_meshes: Default::default(),
@@ -721,6 +723,12 @@ impl Session {
/// Mutable document (copy-on-write).
pub fn doc_mut(&mut self) -> &mut Document {
+ // The placement index keeps the document alive with its answers; let it go before an
+ // in-place edit, so the edit stays in place (a shared handle would clone the document
+ // to a new address behind the crash journal's back, #7502) and no stale lookup outlives it.
+ if let Ok(mut index) = self.placement_index_cache.lock() {
+ *index = None;
+ }
Arc::make_mut(&mut self.doc)
}
@@ -1106,6 +1114,9 @@ impl Session {
}
// Checked first: storing makes the document unique (a copy when the undo step shares it).
if self.model.edited_sketches(&self.doc).next().is_some() {
+ if let Ok(mut index) = self.placement_index_cache.lock() {
+ *index = None;
+ }
self.model.adopt_solved_sketches(Arc::make_mut(&mut self.doc));
}
Ok(())
@@ -1357,6 +1368,7 @@ impl Session {
occurrence_visibility_cache: Default::default(),
removed_later_cache: Default::default(),
occurrence_bodies_cache: Default::default(),
+ placement_index_cache: Default::default(),
clearance_cache: self.clearance_cache.clone(),
body_renames: self.body_renames.clone(),
contact_meshes: self.contact_meshes.clone(),
diff --git a/crates/engine/src/occurrences.rs b/crates/engine/src/occurrences.rs
index a07b4a3052..e635047778 100644
--- a/crates/engine/src/occurrences.rs
+++ b/crates/engine/src/occurrences.rs
@@ -39,12 +39,84 @@ pub(crate) struct OccurrenceBodiesCache {
doc: std::sync::Arc<solidcraft_doc::Document>,
model: std::sync::Arc<solidcraft_doc::ModelState>,
pending_moves: std::collections::BTreeMap<u64, Mat>,
- bodies: std::collections::HashMap<(Vec<u64>, bool), std::sync::Arc<[String]>>,
+ pub(crate) bodies: std::collections::HashMap<(Vec<u64>, bool), std::sync::Arc<[String]>>,
}
-/// How many placements' answers [`OccurrenceBodiesCache`] keeps before it starts again.
+/// How many placements' answers [`OccurrenceBodiesCache`] keeps before retiring one for each
+/// new one.
const OCCURRENCE_BODIES_CACHED: usize = 256;
+/// Placement identity for one document and evaluated model, worked out once per design:
+/// occurrences by (parent, id), children per parent, bodies per component, and each placement
+/// path already named. Listing a subtree then costs the subtree, not the subtree times the
+/// design (#7502). Pending moves change a placement's matrices but never its component or its
+/// bodies' names, so the index is keyed on the document and model alone.
+pub(crate) struct PlacementIndex {
+ doc: std::sync::Arc<solidcraft_doc::Document>,
+ state: std::sync::Arc<solidcraft_doc::ModelState>,
+ /// The index into `doc.occurrences` of each (parent component, occurrence id).
+ by_parent_id: std::collections::HashMap<(u64, u64), usize>,
+ /// The occurrence ids of each parent component's children, in document order.
+ children: std::collections::HashMap<u64, Vec<u64>>,
+ /// The source body names of each component.
+ bodies: std::collections::HashMap<u64, Vec<String>>,
+ /// The ids of the design's components.
+ components: std::collections::HashSet<u64>,
+ /// Each placement path already named: its bodies' world names.
+ placed: std::collections::HashMap<Vec<u64>, std::sync::Arc<[OccurrenceBody]>>,
+}
+
+/// How many placement paths [`PlacementIndex`] names before it stops remembering more.
+const PLACEMENT_PATHS_CACHED: usize = solidcraft_doc::MAX_PLACEMENTS;
+
+impl PlacementIndex {
+ fn new(doc: &std::sync::Arc<solidcraft_doc::Document>, state: &std::sync::Arc<solidcraft_doc::ModelState>) -> PlacementIndex {
+ let mut by_parent_id = std::collections::HashMap::with_capacity(doc.occurrences.len());
+ let mut children: std::collections::HashMap<u64, Vec<u64>> = std::collections::HashMap::new();
+ for (i, o) in doc.occurrences.iter().enumerate() {
+ by_parent_id.insert((o.parent, o.id), i);
+ children.entry(o.parent).or_default().push(o.id);
+ }
+ let mut bodies: std::collections::HashMap<u64, Vec<String>> = std::collections::HashMap::new();
+ for b in &state.bodies {
+ bodies.entry(doc.model_body_component(b)).or_default().push(b.name.clone());
+ }
+ PlacementIndex {
+ doc: doc.clone(),
+ state: state.clone(),
+ by_parent_id,
+ children,
+ bodies,
+ components: doc.components.iter().map(|c| c.id).collect(),
+ placed: std::collections::HashMap::new(),
+ }
+ }
+
+ fn matches(&self, session: &Session, model: &std::sync::Arc<solidcraft_doc::ModelState>) -> bool {
+ std::sync::Arc::ptr_eq(&self.doc, &session.doc) && std::sync::Arc::ptr_eq(&self.state, model)
+ }
+
+ /// The component's bodies named at `path`, remembered until the index is replaced.
+ fn bodies_at(&mut self, path: &[u64], component: u64) -> std::sync::Arc<[OccurrenceBody]> {
+ if let Some(bodies) = self.placed.get(path) {
+ return bodies.clone();
+ }
+ let names = solidcraft_doc::WorldNames::new(&self.doc, &self.state);
+ let empty = Vec::new();
+ let bodies: std::sync::Arc<[OccurrenceBody]> = self
+ .bodies
+ .get(&component)
+ .unwrap_or(&empty)
+ .iter()
+ .map(|source| OccurrenceBody { source: source.clone(), world: names.name(source, component, path) })
+ .collect();
+ if self.placed.len() < PLACEMENT_PATHS_CACHED {
+ self.placed.insert(path.to_vec(), bodies.clone());
+ }
+ bodies
+ }
+}
+
impl OccurrenceBodiesCache {
fn matches(&self, session: &Session, model: &std::sync::Arc<solidcraft_doc::ModelState>) -> bool {
std::sync::Arc::ptr_eq(&self.doc, &session.doc) && std::sync::Arc::ptr_eq(&self.model, model) && self.pending_moves == session.pending_moves
@@ -139,8 +211,72 @@ impl Session {
}
std::borrow::Cow::Owned(doc)
}
- /// Resolve only the supplied path, never an exponentially expanded assembly.
+ /// Resolve only the supplied path, never an exponentially expanded assembly. The placement
+ /// index answers from lookups; the plain walk stays as the fallback and the error reporter.
pub fn occurrence_placement(&self, path: &[u64]) -> Result<OccurrencePlacement> {
+ if path.is_empty() || path.len() > 64 {
+ return Err(invalid("occurrence path must contain 1..64 ids"));
+ }
+ if let Some(placement) = self.occurrence_placement_indexed(path) {
+ return Ok(placement);
+ }
+ self.occurrence_placement_walk(path)
+ }
+
+ /// [`Self::occurrence_placement`] through [`PlacementIndex`]: the path walk multiplies
+ /// transforms as the plain walk does, but occurrences, components and body names are
+ /// lookups. `None` for any path the index can't answer, so the walk reports the exact error.
+ fn occurrence_placement_indexed(&self, path: &[u64]) -> Option<OccurrencePlacement> {
+ let mut guard = self.placement_index()?;
+ let index = guard.as_mut()?;
+ let mut component = 0;
+ let mut world = IDENTITY;
+ let mut parent_world = IDENTITY;
+ let mut leaf = None;
+ for id in path {
+ let i = *index.by_parent_id.get(&(component, *id))?;
+ let o = &index.doc.occurrences[i];
+ if !index.components.contains(&o.component) {
+ return None;
+ }
+ parent_world = world;
+ world = mat_mul(&world, self.pending_moves.get(id).unwrap_or(&o.transform));
+ if world.iter().flatten().any(|x| !x.is_finite()) {
+ return None;
+ }
+ leaf = Some(i);
+ component = o.component;
+ }
+ let leaf = leaf?;
+ let bodies = index.bodies_at(path, component).to_vec();
+ let leaf = &index.doc.occurrences[leaf];
+ Some(OccurrencePlacement {
+ occurrence: leaf.id,
+ component,
+ path: path.to_vec(),
+ name: leaf.name.clone(),
+ world,
+ local: self.pending_moves.get(&leaf.id).copied().unwrap_or(leaf.transform),
+ parent_world,
+ grounded: leaf.grounded,
+ bodies,
+ })
+ }
+
+ /// The placement index for the current document and model, built on first use.
+ fn placement_index(&self) -> Option<std::sync::MutexGuard<'_, Option<PlacementIndex>>> {
+ let model = self.model.state();
+ let mut guard = self.placement_index_cache.lock().ok()?;
+ let index = guard.get_or_insert_with(|| PlacementIndex::new(&self.doc, &model));
+ if !index.matches(self, &model) {
+ *index = PlacementIndex::new(&self.doc, &model);
+ }
+ Some(guard)
+ }
+
+ /// The plain walk over `doc.occurrences`, kept as the fallback for paths the index can't
+ /// answer and as the reference the indexed answers are checked against (#7502).
+ pub(crate) fn occurrence_placement_walk(&self, path: &[u64]) -> Result<OccurrencePlacement> {
if path.is_empty() || path.len() > 64 {
return Err(invalid("occurrence path must contain 1..64 ids"));
}
@@ -223,7 +359,7 @@ impl Session {
}
let bodies: std::sync::Arc<[String]> = self.expand_occurrence_bodies(path, descendants)?.into();
if let Ok(mut cache) = self.occurrence_bodies_cache.lock() {
- if cache.as_ref().is_none_or(|c| !c.matches(self, &model) || c.bodies.len() >= OCCURRENCE_BODIES_CACHED) {
+ if cache.as_ref().is_none_or(|c| !c.matches(self, &model)) {
*cache = Some(OccurrenceBodiesCache {
doc: self.doc.clone(),
model,
@@ -232,6 +368,15 @@ impl Session {
});
}
if let Some(cache) = cache.as_mut() {
+ if !cache.bodies.contains_key(&key) && cache.bodies.len() >= OCCURRENCE_BODIES_CACHED {
+ // Retire one remembered answer, not the whole cache: a burst of other
+ // paths (a Browser reveal, a hover) no longer evicts the active
+ // occurrence's entry and forces a full re-expansion on the next
+ // highlight build (#7502).
+ if let Some(evict) = cache.bodies.keys().next().cloned() {
+ cache.bodies.remove(&evict);
+ }
+ }
cache.bodies.insert(key, bodies.clone());
}
}
@@ -239,6 +384,9 @@ impl Session {
}
fn expand_occurrence_bodies(&self, path: &[u64], descendants: bool) -> Result<Vec<String>> {
+ if let Some(out) = self.expand_occurrence_bodies_indexed(path, descendants) {
+ return Ok(out);
+ }
let mut stack = vec![self.occurrence_placement(path)?];
let mut out = Vec::new();
let mut count = 0;
@@ -255,6 +403,63 @@ impl Session {
Ok(out)
}
+ /// [`Self::expand_occurrence_bodies`] through [`PlacementIndex`]: children and bodies are
+ /// lookups and each path is named once, so a listing costs the subtree's size, not the
+ /// subtree times the design (#7502). `None` when the index can't answer (a lock miss, an
+ /// invalid path, a cycle or a design over the limits), so the walk reports the exact error.
+ fn expand_occurrence_bodies_indexed(&self, path: &[u64], descendants: bool) -> Option<Vec<String>> {
+ if path.is_empty() {
+ return None;
+ }
+ let mut guard = self.placement_index()?;
+ let index = guard.as_mut()?;
+ let mut component = 0;
+ let mut world = IDENTITY;
+ for id in path {
+ let i = *index.by_parent_id.get(&(component, *id))?;
+ let o = &index.doc.occurrences[i];
+ if !index.components.contains(&o.component) {
+ return None;
+ }
+ world = mat_mul(&world, self.pending_moves.get(id).unwrap_or(&o.transform));
+ if world.iter().flatten().any(|x| !x.is_finite()) {
+ return None;
+ }
+ component = o.component;
+ }
+ let mut stack = vec![(path.to_vec(), component, world)];
+ let mut out = Vec::new();
+ let mut count = 0;
+ while let Some((path, component, world)) = stack.pop() {
+ count += 1;
+ let bodies = index.bodies_at(&path, component);
+ if count > 100_000 || out.len() + bodies.len() > 100_000 {
+ return None;
+ }
+ out.extend(bodies.iter().map(|b| b.world.clone()));
+ if descendants && path.len() < 64 {
+ for child in index.children.get(&component).into_iter().flatten() {
+ if path.contains(child) {
+ return None;
+ }
+ let i = *index.by_parent_id.get(&(component, *child))?;
+ let o = &index.doc.occurrences[i];
+ if !index.components.contains(&o.component) {
+ return None;
+ }
+ let child_world = mat_mul(&world, self.pending_moves.get(child).unwrap_or(&o.transform));
+ if child_world.iter().flatten().any(|x| !x.is_finite()) {
+ return None;
+ }
+ let mut next = path.clone();
+ next.push(*child);
+ stack.push((next, o.component, child_world));
+ }
+ }
+ }
+ Some(out)
+ }
+
/// The world names of the bodies `features` made (#5099), in every placement of their
/// component, or only in `placement` (a component and the path of one of its placements).
pub fn feature_bodies(&self, features: &[u64], placement: Option<(u64, &[u64])>) -> Vec<String> {
diff --git a/crates/ui-egui/src/browser.rs b/crates/ui-egui/src/browser.rs
index f2fb8de10c..a8720eb4a5 100644
--- a/crates/ui-egui/src/browser.rs
+++ b/crates/ui-egui/src/browser.rs
@@ -731,9 +731,13 @@ pub(crate) fn reveal_pick(app: &mut SolveApp) {
}
}
-/// Whether the body being revealed is in this placement or one below it: it opens.
-fn reveals_in_occurrence(app: &SolveApp, path: &[u64]) -> bool {
- app.tree.reveal.as_ref().is_some_and(|r| app.session.occurrence_bodies(path, true).is_ok_and(|bodies| bodies.contains(r)))
+/// The placement path of the body being revealed, resolved once per model: a row opens when
+/// the body's path runs through it, instead of every row expanding its subtree to test
+/// containment (#7502). `None` when nothing is revealed or the body is a top-level design body.
+fn reveal_path(app: &mut SolveApp) -> Option<Vec<u64>> {
+ let body = app.tree.reveal.clone()?;
+ prepare_model(app);
+ app.tree.model.as_mut()?.body_path(&app.session, &body)
}
pub(crate) fn is_open(app: &SolveApp, key: &str, default: bool) -> bool {
@@ -1358,10 +1362,13 @@ fn component_rows_inner(
root: &mut cache::Node,
) {
let key = &root.key;
- if let Some(body) = app.tree.reveal.as_ref()
- && (cache.root_bodies.contains(body) || root.children.iter().any(|path| reveals_in_occurrence(app, path)))
- {
- app.tree.collapsed.remove(key);
+ let reveal = app.tree.reveal.clone();
+ if let Some(body) = reveal.as_ref() {
+ let reveals =
+ cache.root_bodies.contains(body) || reveal_path(app).is_some_and(|rp| root.children.iter().any(|path| rp.starts_with(path.as_slice())));
+ if reveals {
+ app.tree.collapsed.remove(key);
+ }
}
let open = is_open(app, key, true);
let active = app.session.active_component == id;
@@ -1497,7 +1504,7 @@ fn occurrence_rows_inner(
placement: &mut cache::Node,
) {
let key = &placement.key;
- if reveals_in_occurrence(app, path) {
+ if reveal_path(app).is_some_and(|rp| rp.starts_with(path)) {
app.tree.collapsed.remove(key);
}
let open = is_open(app, key, true);