SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Interference: clear apart pairs from their meshes, intersect the rest in parallel, time budget (#2895)
SS-EN771f62be7124
diff --git a/crates/engine/src/cmd/interference.rs b/crates/engine/src/cmd/interference.rsnew file mode 100644index 0000000000..06c5c1bfce--- /dev/null+++ b/crates/engine/src/cmd/interference.rs@@ -0,0 +1,439 @@+//! Interference (`inspect.interference`): the pairs of bodies that share volume, and how much.+//!+//! Pairs are pruned in three steps before anything exact runs. Their boxes first (sort and+//! sweep), then their display meshes: a mesh lies within its chord tolerance of the faces, so+//! two meshes farther apart than a margin over both tolerances belong to bodies whose boundaries+//! don't meet, and unless one body sits inside the other (a point of each face of one tested+//! against the other's mesh) the pair is clear without a boolean. The pairs left are intersected+//! exactly and measured, in parallel on desktop (one after another in the browser), the slowest+//! first, under a time budget: pairs not finished when it runs out are listed as not checked+//! rather than holding the call. The shared part is measured as `solidcraft_kernel::measure`+//! measures it (its mass properties alone).++use std::collections::HashSet;+use std::sync::Arc;++use serde_json::{Value, json};+use solidcraft_geom::mesh_distance::TriangleSet;+use solidcraft_geom::{Aabb3, Mesh, Vec3};+use solidcraft_kernel::Body;+use solidcraft_kernel::profile::KernelTimes;++use crate::params::{bad, num, string_list};+use crate::{Result, Session};++/// Most pairs with overlapping bounding boxes one call intersects.+pub(crate) const MAX_INTERFERENCE_PAIRS: usize = 20_000;+/// The time budget when the call gives none (s): under the 300 s an MCP client waits for a tool.+pub(crate) const DEFAULT_BUDGET_S: f64 = 240.0;+/// The longest time budget a call may ask for (s).+const MAX_BUDGET_S: f64 = 86_400.0;+/// How many chord tolerances apart (of both meshes together) two meshes must be to clear a pair+/// without intersecting it: twice what the tolerances allow, for meshers that sag a little more.+const MESH_MARGIN: f64 = 4.0;+/// Most pairs listed under `slowest`.+const SLOWEST: usize = 8;++/// One pair to intersect exactly: the bodies (cheap clones sharing the solids) and their names.+struct Job {+ pair: usize,+ a: Body,+ b: Body,+ names: (String, String),+ /// Faces of one times faces of the other: the slowest pairs start first.+ cost: usize,+}++/// What an exact check of one pair came to.+enum Outcome {+ Hit(Value),+ Clear,+ Unchecked(String),+}++/// One pair's answer and where its time went.+struct Done {+ outcome: Outcome,+ /// Unverified boolean results are listed as unchecked and still reported as a hit.+ note: Option<String>,+ ms: f64,+ kernel: KernelTimes,+}++pub(super) fn interference(s: &mut Session, p: &Value) -> Result<Value> {+ let cmd = "inspect.interference";+ let started = web_time::Instant::now();+ let budget_s = match p.get("budget_s") {+ None | Some(Value::Null) => DEFAULT_BUDGET_S,+ Some(_) => match num(p, "budget_s") {+ Some(v) if v > 0.0 && v <= MAX_BUDGET_S => v,+ _ => return Err(bad(cmd, format!("`budget_s` must be a number of seconds above 0, at most {MAX_BUDGET_S}"))),+ },+ };+ let budget = std::time::Duration::from_secs_f64(budget_s);+ let want = string_list(p, "bodies");+ let st = s.world_state();+ let bodies: Vec<&solidcraft_doc::ModelBody> =+ st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).filter(|b| !b.body.is_mesh()).collect();++ // The bodies' display meshes, made once (in parallel) and kept on the bodies: a design open+ // in the app has them already.+ let meshes: Vec<Arc<Mesh>> = {+ let made = solidcraft_kernel::map_with_local_pools(&bodies, usize::MAX, |b| Ok(b.mesh()));+ made.into_iter().map(|m| m.unwrap_or_default()).collect()+ };+ // Prune by bounding boxes first (sort and sweep), so the cost follows the pairs that can+ // touch rather than the square of the body count.+ // Each mesh lies within its chord of the faces, inside a round one: grown by that, the boxes+ // of bodies a hundredth of a millimetre into each other still meet (an arm's round end into a+ // rounded rim, its facets clear of the rim's).+ let chords: Vec<f64> = bodies.iter().map(|b| b.display_tol()).collect();+ let boxes: Vec<Aabb3> = meshes+ .iter()+ .zip(&chords)+ .map(|(m, &chord)| {+ let (bx, g) = (m.bounds(), 2.0 * chord);+ if bx.is_empty() { bx } else { Aabb3 { min: bx.min - Vec3::new(g, g, g), max: bx.max + Vec3::new(g, g, g) } }+ })+ .collect();+ let (pairs, skipped) = super::joints::overlapping_pairs(&boxes, MAX_INTERFERENCE_PAIRS);++ // Then by the meshes: pairs whose meshes stay apart (and neither holds the other) are clear.+ let used: Vec<bool> = {+ let mut u = vec![false; bodies.len()];+ for &(i, j) in &pairs {+ for k in [i, j] {+ if let Some(x) = u.get_mut(k) {+ *x = true;+ }+ }+ }+ u+ };+ let sets: Vec<Option<TriangleSet>> = {+ let idx: Vec<usize> = (0..bodies.len()).filter(|&i| used.get(i).copied().unwrap_or(false)).collect();+ let made = solidcraft_kernel::map_with_local_pools(&idx, usize::MAX, |&i| Ok(meshes.get(i).map(|m| TriangleSet::new(m))));+ let mut out: Vec<Option<TriangleSet>> = std::iter::repeat_with(|| None).take(bodies.len()).collect();+ for (&i, set) in idx.iter().zip(made) {+ if let (Some(slot), Ok(set)) = (out.get_mut(i), set) {+ *slot = set;+ }+ }+ out+ };+ let need_exact = solidcraft_kernel::map_with_local_pools(&pairs, usize::MAX, |&(i, j)| {+ let (Some(Some(sa)), Some(Some(sb)), Some(ma), Some(mb)) = (sets.get(i), sets.get(j), meshes.get(i), meshes.get(j)) else {+ return Ok(true);+ };+ let margin = MESH_MARGIN * (chords.get(i).copied().unwrap_or(0.0) + chords.get(j).copied().unwrap_or(0.0));+ Ok(!meshes_apart(ma, sa, mb, sb, margin))+ });+ let mut jobs = Vec::new();+ let mut cleared = 0usize;+ for (k, (&(i, j), exact)) in pairs.iter().zip(need_exact).enumerate() {+ if !exact.unwrap_or(true) {+ cleared += 1;+ continue;+ }+ let (Some(a), Some(b)) = (bodies.get(i), bodies.get(j)) else { continue };+ jobs.push(Job {+ pair: k,+ a: a.body.clone(),+ b: b.body.clone(),+ names: (a.name.clone(), b.name.clone()),+ cost: a.body.face_count().saturating_mul(b.body.face_count()),+ });+ }+ let intersected = jobs.len();+ jobs.sort_by(|x, y| y.cost.cmp(&x.cost).then(x.pair.cmp(&y.pair)));++ let left = budget.saturating_sub(started.elapsed());+ let waited = web_time::Instant::now();+ let (done, threads) = run_jobs(jobs, left);+ let waited_ms = waited.elapsed().as_secs_f64() * 1000.0;++ let (mut hits, mut unchecked, mut timed) = (Vec::new(), Vec::new(), Vec::new());+ let (mut not_checked, mut boolean_ms, mut tessellate_ms) = (0usize, 0.0, 0.0);+ for ((a, b), d) in done {+ let Some(d) = d else {+ not_checked += 1;+ unchecked.push(json!({"a": a, "b": b, "reason": format!("not checked: the time budget of {budget_s} s ran out (budget_s)")}));+ continue;+ };+ boolean_ms += d.kernel.boolean_ms;+ tessellate_ms += d.kernel.tessellate_ms;+ timed.push((+ d.ms,+ json!({"a": a, "b": b, "ms": round_ms(d.ms), "boolean_ms": round_ms(d.kernel.boolean_ms),+ "tessellate_ms": round_ms(d.kernel.tessellate_ms)}),+ ));+ if let Some(reason) = d.note {+ unchecked.push(json!({"a": a, "b": b, "reason": reason}));+ }+ match d.outcome {+ Outcome::Hit(v) => hits.push(v),+ Outcome::Clear => {}+ Outcome::Unchecked(reason) => unchecked.push(json!({"a": a, "b": b, "reason": reason})),+ }+ }+ // A timing profile of the command (`--profile`) counts the kernel time the workers spent,+ // shared out over the time this thread waited for them (on the calling thread it is counted+ // already).+ if threads > 0 && boolean_ms + tessellate_ms > 0.0 {+ let share = (waited_ms / (boolean_ms + tessellate_ms)).min(1.0);+ solidcraft_kernel::profile::credit(KernelTimes { boolean_ms: boolean_ms * share, tessellate_ms: tessellate_ms * share });+ }+ timed.sort_by(|x, y| y.0.total_cmp(&x.0));+ let slowest: Vec<Value> = timed.into_iter().take(SLOWEST).map(|t| t.1).collect();+ Ok(json!({+ "interferences": hits, "count": hits.len(), "checked": bodies.len(), "unchecked": unchecked,+ "truncated": skipped > 0, "skipped_pairs": skipped,+ "pairs_candidate": pairs.len(), "pairs_cleared": cleared, "pairs_intersected": intersected,+ "pairs_not_checked": not_checked, "budget_s": budget_s, "budget_exceeded": not_checked > 0,+ "threads": threads, "boolean_ms": round_ms(boolean_ms), "tessellate_ms": round_ms(tessellate_ms),+ "slowest": slowest, "ms": round_ms(started.elapsed().as_secs_f64() * 1000.0),+ }))+}++fn round_ms(ms: f64) -> f64 {+ (ms * 1000.0).round() / 1000.0+}++/// Are two bodies' meshes farther apart than `margin` with neither body inside the other? Then+/// their boundaries don't meet (each mesh is within its chord tolerance of its faces, which the+/// margin covers), so the bodies share no volume. Conservative: an empty mesh, nested boxes or+/// a point of one inside the other answer no.+fn meshes_apart(ma: &Mesh, sa: &TriangleSet, mb: &Mesh, sb: &TriangleSet, margin: f64) -> bool {+ if ma.triangles.is_empty() || mb.triangles.is_empty() || !margin.is_finite() {+ return false;+ }+ if sa.closest(sb, margin).is_some() {+ return false;+ }+ // Apart boundaries: either the bodies are apart, or one holds the other (or a piece of it).+ let (ba, bb) = (ma.bounds(), mb.bounds());+ if nested(&ba, &bb) || nested(&bb, &ba) {+ return false;+ }+ !(any_inside(&face_points(ma), mb) || any_inside(&face_points(mb), ma))+}++/// Is `inner` inside `outer`?+fn nested(inner: &Aabb3, outer: &Aabb3) -> bool {+ !inner.is_empty()+ && outer.min.x <= inner.min.x+ && outer.min.y <= inner.min.y+ && outer.min.z <= inner.min.z+ && inner.max.x <= outer.max.x+ && inner.max.y <= outer.max.y+ && inner.max.z <= outer.max.z+}++/// A corner of each face's first triangle (every piece of a body in several pieces has a face).+fn face_points(m: &Mesh) -> Vec<Vec3> {+ let mut seen = HashSet::new();+ let mut out = Vec::new();+ for (k, t) in m.triangles.iter().enumerate() {+ let face = m.tri_face.get(k).copied().unwrap_or(0);+ if seen.insert(face)+ && let Some(p) = m.positions.get(t[0] as usize)+ {+ out.push(*p);+ }+ }+ out+}++/// Is any of `points` inside the closed mesh `outer`?+fn any_inside(points: &[Vec3], outer: &Mesh) -> bool {+ let b = outer.bounds();+ let within = |p: &&Vec3| b.min.x <= p.x && p.x <= b.max.x && b.min.y <= p.y && p.y <= b.max.y && b.min.z <= p.z && p.z <= b.max.z;+ let candidates: Vec<&Vec3> = points.iter().filter(within).collect();+ match candidates.len() {+ 0 => false,+ 1..=4 => candidates.iter().any(|p| outer.contains(**p)),+ _ => {+ let index = outer.inside_index();+ candidates.iter().any(|p| index.contains(**p))+ }+ }+}++/// The exact check of one pair: a pin a hair off the axis of its hole by the walls' crescent,+/// otherwise the intersection measured.+fn check(job: &Job) -> Done {+ let started = web_time::Instant::now();+ let ((outcome, note), kernel) = solidcraft_kernel::profile::capture(|| check_pair(&job.a, &job.b, &job.names));+ Done { outcome, note, ms: started.elapsed().as_secs_f64() * 1000.0, kernel }+}++fn check_pair(a: &Body, b: &Body, (na, nb): &(String, String)) -> (Outcome, Option<String>) {+ let threshold = 1e-9 * a.size().max(1.0).powi(3);+ // A pin a hair off the axis of its hole: the crescent the walls share, which the boolean+ // can't intersect.+ if let Some(o) = solidcraft_kernel::coaxial_overlap(a, b) {+ if o.volume > threshold {+ let hit = json!({"a": na, "b": nb, "volume_mm3": o.volume, "area_mm2": o.area, "center": o.centroid,+ "bbox": {"min": o.bbox.min, "max": o.bbox.max}, "near_coaxial": {"offset_mm": o.offset, "length_mm": o.length}});+ return (Outcome::Hit(hit), None);+ }+ return (Outcome::Clear, None);+ }+ // A pair whose shared part can't be worked out is reported, not passed as clear.+ let (shared, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(a, b, solidcraft_kernel::BoolOp::Intersect));+ let shared = match shared {+ Ok(o) => o,+ Err(e) => return (Outcome::Unchecked(e.to_string()), None),+ };+ let mut note = report.unverified();+ let pieces = match shared {+ Some(o) => vec![o],+ // A body in several pieces, one of them wholly inside the other body: the whole bodies'+ // boolean can come out empty, so the pieces are intersected one by one.+ None if a.shell_count() > 1 || b.shell_count() > 1 => match by_pieces(a, b) {+ Ok((pieces, unverified)) => {+ note = note.or(unverified);+ pieces+ }+ Err(e) => return (Outcome::Unchecked(e), note),+ },+ None => return (Outcome::Clear, note),+ };+ // The shared parts measured together: volumes and areas add, the centre is the volumes'.+ let mut measured = Vec::new();+ for o in &pieces {+ match solidcraft_kernel::measure_mass(o) {+ Ok(m) => measured.push(m),+ Err(e) => return (Outcome::Unchecked(e.to_string()), note),+ }+ }+ let volume: f64 = measured.iter().map(|m| m.volume).sum();+ if volume > threshold {+ let area: f64 = measured.iter().map(|m| m.area).sum();+ let bbox = measured.iter().fold(Aabb3::EMPTY, |b, m| b.union(&m.bbox));+ let center = match measured.as_slice() {+ [m] => m.centroid,+ _ => measured.iter().fold(Vec3::ZERO, |c, m| c + m.centroid * m.volume) / volume,+ };+ let hit = json!({"a": na, "b": nb, "volume_mm3": volume, "area_mm2": area, "center": center, "bbox": {"min": bbox.min, "max": bbox.max}});+ return (Outcome::Hit(hit), note);+ }+ (Outcome::Clear, note)+}++/// Most pairs of pieces [`by_pieces`] intersects.+const MAX_PIECE_PAIRS: usize = 256;++/// The shared parts of two bodies, a piece of each at a time, and why any of them is unverified.+fn by_pieces(a: &Body, b: &Body) -> std::result::Result<(Vec<Body>, Option<String>), String> {+ let (la, lb) = (a.lumps().map_err(|e| e.to_string())?, b.lumps().map_err(|e| e.to_string())?);+ if la.len() < 2 && lb.len() < 2 {+ return Ok((Vec::new(), None));+ }+ if la.len().saturating_mul(lb.len()) > MAX_PIECE_PAIRS {+ return Err(format!("not checked: {} by {} pieces are more than {MAX_PIECE_PAIRS} pairs of pieces", la.len(), lb.len()));+ }+ let (mut out, mut note) = (Vec::new(), None);+ for x in &la {+ for y in &lb {+ let (r, report) =+ solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(x, y, solidcraft_kernel::BoolOp::Intersect));+ note = note.or(report.unverified());+ if let Some(o) = r.map_err(|e| e.to_string())? {+ out.push(o);+ }+ }+ }+ Ok((out, note))+}++/// Each job's answer (in pair order, with the pair's names; `None`: not finished within+/// `budget`) and how many worker threads ran them (0: this thread did).+fn run_jobs(jobs: Vec<Job>, budget: std::time::Duration) -> (Vec<((String, String), Option<Done>)>, usize) {+ let mut order: Vec<(usize, usize, (String, String))> = jobs.iter().enumerate().map(|(k, j)| (j.pair, k, j.names.clone())).collect();+ order.sort_unstable_by_key(|o| o.0);+ let (mut results, threads) = run_ordered(jobs, budget);+ let out = order.into_iter().map(|(_, k, names)| (names, results.get_mut(k).and_then(Option::take))).collect();+ (out, threads)+}++/// Each job's answer in job order, and the threads used. On desktop the jobs run on worker+/// threads of their own, which the call does not wait for once `budget` is spent: a pair still+/// running then finishes in the background and is dropped (a kernel boolean can't be stopped+/// part way).+#[cfg(not(target_arch = "wasm32"))]+fn run_ordered(jobs: Vec<Job>, budget: std::time::Duration) -> (Vec<Option<Done>>, usize) {+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+ use std::sync::mpsc;++ let n = jobs.len();+ let mut out: Vec<Option<Done>> = std::iter::repeat_with(|| None).take(n).collect();+ if n == 0 || budget.is_zero() {+ return (out, 0);+ }+ let deadline = web_time::Instant::now() + budget;+ // The workers outlive the call when the budget runs out, so they own what they work on.+ let jobs = Arc::new(jobs);+ let next = Arc::new(AtomicUsize::new(0));+ let stop = Arc::new(AtomicBool::new(false));+ let (tx, rx) = mpsc::channel::<(usize, Done)>();+ let want = std::thread::available_parallelism().map(usize::from).unwrap_or(1).min(n).max(1);+ let mut threads = 0;+ for _ in 0..want {+ let (jobs, next, stop, tx) = (jobs.clone(), next.clone(), stop.clone(), tx.clone());+ let spawned = std::thread::Builder::new().name("solidcraft-interference".into()).spawn(move || {+ while !stop.load(Ordering::Relaxed) {+ let k = next.fetch_add(1, Ordering::Relaxed);+ let Some(job) = jobs.get(k) else { break };+ let done = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| check(job))).unwrap_or_else(|_| Done {+ outcome: Outcome::Unchecked("internal error while checking this pair".into()),+ note: None,+ ms: 0.0,+ kernel: KernelTimes::default(),+ });+ if tx.send((k, done)).is_err() {+ break;+ }+ }+ });+ if spawned.is_ok() {+ threads += 1;+ }+ }+ drop(tx);+ if threads == 0 {+ // No thread could be started: one pair after another here.+ return (run_here(&jobs, deadline), 0);+ }+ let mut received = 0;+ while received < n {+ let left = deadline.saturating_duration_since(web_time::Instant::now());+ match rx.recv_timeout(left) {+ Ok((k, done)) => {+ if let Some(slot) = out.get_mut(k) {+ *slot = Some(done);+ }+ received += 1;+ }+ // Out of time, or every worker gone (none is left with work then).+ Err(_) => break,+ }+ }+ stop.store(true, Ordering::Relaxed);+ (out, threads)+}++/// The browser has no threads: one pair after another, none started once the budget is spent.+#[cfg(target_arch = "wasm32")]+fn run_ordered(jobs: Vec<Job>, budget: std::time::Duration) -> (Vec<Option<Done>>, usize) {+ (run_here(&jobs, web_time::Instant::now() + budget), 0)+}++/// The jobs one after another on this thread, none started past `deadline`.+fn run_here(jobs: &[Job], deadline: web_time::Instant) -> Vec<Option<Done>> {+ jobs.iter().map(|job| (web_time::Instant::now() < deadline).then(|| check(job))).collect()+}++#[cfg(test)]+#[path = "interference_tests.rs"]+mod tests;diff --git a/crates/engine/src/cmd/interference_tests.rs b/crates/engine/src/cmd/interference_tests.rsnew file mode 100644index 0000000000..9d65ee89ae--- /dev/null+++ b/crates/engine/src/cmd/interference_tests.rs@@ -0,0 +1,110 @@+//! `inspect.interference`: the mesh pre-filter, the bodies it must not clear, and the budget.++use serde_json::{Value, json};++use crate::Session;++fn run(s: &mut Session, id: &str, p: Value) -> Value {+ match s.execute(id, &p) {+ Ok(v) => v,+ Err(e) => panic!("{id} {p}: {e}"),+ }+}++fn f(v: &Value) -> f64 {+ v.as_f64().unwrap_or(f64::NAN)+}++/// Curved bodies whose boxes overlap but which stay apart are answered from their meshes: no+/// boolean runs. Two cylinders on a diagonal (centres 12.7 mm apart, radii 5), and a torus+/// beside a sphere that sits in the corner of its box.+#[test]+fn separated_curved_bodies_are_cleared_without_a_boolean() {+ let mut s = Session::default();+ run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [0, 0, 0], "body_name": "C1"}));+ run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [9, 9, 0], "operation": "new", "body_name": "C2"}));+ run(&mut s, "solid.torus", json!({"major": 20, "minor": 3, "center": [60, 0, 0], "body_name": "Torus"}));+ // In the torus box's corner (the box reaches 23 out on each axis), 1.66 mm clear of the tube.+ run(&mut s, "solid.sphere", json!({"radius": 3, "center": [80, 19, 1], "operation": "new", "body_name": "Ball"}));+ let i = run(&mut s, "inspect.interference", json!({}));+ assert_eq!(i["count"], 0, "{i}");+ assert_eq!(i["pairs_candidate"], 2, "{i}");+ assert_eq!(i["pairs_cleared"], 2, "{i}");+ assert_eq!(i["pairs_intersected"], 0, "{i}");+ assert_eq!(f(&i["boolean_ms"]), 0.0, "{i}");+ assert_eq!(i["unchecked"].as_array().map(Vec::len), Some(0), "{i}");+ // Moved into each other, the same pairs are intersected and overlap.+ run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 10, "base": [7, 0, 0], "operation": "new", "body_name": "C3"}));+ let i = run(&mut s, "inspect.interference", json!({"bodies": ["C1", "C3"]}));+ assert_eq!(i["count"], 1, "{i}");+ assert_eq!(i["pairs_intersected"], 1, "{i}");+ // The lens of two r5 circles 7 apart, 10 high.+ let (r, d): (f64, f64) = (5.0, 7.0);+ let lens = 2.0 * r * r * (d / (2.0 * r)).acos() - d / 2.0 * (4.0 * r * r - d * d).sqrt();+ let got = f(&i["interferences"][0]["volume_mm3"]);+ assert!((got - 10.0 * lens).abs() < 1e-3 * 10.0 * lens, "{got} against {}: {i}", 10.0 * lens);+}++/// A body wholly inside another has meshes that never meet: it is still intersected, and its+/// whole volume is the overlap.+#[test]+fn a_body_inside_another_is_still_found() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 40, "corner": [-20, -20, -20], "body_name": "Block"}));+ run(&mut s, "solid.sphere", json!({"radius": 5, "center": [3, -2, 1], "operation": "new", "body_name": "Ball"}));+ let i = run(&mut s, "inspect.interference", json!({}));+ assert_eq!(i["count"], 1, "{i}");+ assert_eq!(i["pairs_cleared"], 0, "{i}");+ let want = 4.0 / 3.0 * std::f64::consts::PI * 125.0;+ let got = f(&i["interferences"][0]["volume_mm3"]);+ assert!((got - want).abs() < 1e-3 * want, "{got} against {want}: {i}");+}++/// A body in two pieces, one of them wholly inside a block and the other outside it: the boxes+/// are not nested and the meshes never meet, but a point of the inner piece's faces is inside+/// the block, so the pair is intersected. The whole bodies' boolean comes out empty there, so+/// the pieces are intersected one by one.+#[test]+fn a_piece_of_a_body_inside_another_is_still_found() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Block"}));+ run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [5, 5, 5], "operation": "new", "body_name": "Pieces"}));+ run(&mut s, "solid.box", json!({"length": 2, "width": 2, "height": 2, "corner": [30, 5, 5], "operation": "join", "targets": ["Pieces"]}));+ let st = s.world_state();+ let pieces = st.bodies.iter().find(|b| b.name == "Pieces").map(|b| b.body.shell_count());+ assert_eq!(pieces, Some(2), "the two cubes are one body in two pieces");+ let i = run(&mut s, "inspect.interference", json!({}));+ assert_eq!(i["count"], 1, "{i}");+ assert_eq!(i["pairs_cleared"], 0, "{i}");+ assert!((f(&i["interferences"][0]["volume_mm3"]) - 8.0).abs() < 1e-6, "{i}");+}++/// A budget spent before any pair could start lists every pair as not checked (and the call+/// returns); bad budgets are refused.+#[test]+fn pairs_left_when_the_budget_runs_out_are_listed_not_checked() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [0, 0, 0], "body_name": "A"}));+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [5, 0, 0], "operation": "new", "body_name": "B"}));+ run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [12, 0, 0], "operation": "new", "body_name": "C"}));+ let i = run(&mut s, "inspect.interference", json!({"budget_s": 1e-12}));+ assert_eq!(i["count"], 0, "{i}");+ assert_eq!(i["budget_exceeded"], true, "{i}");+ assert_eq!(i["pairs_not_checked"], 2, "{i}");+ let unchecked = i["unchecked"].as_array().cloned().unwrap_or_default();+ assert_eq!(unchecked.len(), 2, "{i}");+ assert!(unchecked.iter().all(|u| u["reason"].as_str().is_some_and(|r| r.starts_with("not checked") && r.contains("time budget"))), "{i}");+ // The default budget checks both pairs: 500 and 300 mm³.+ let i = run(&mut s, "inspect.interference", json!({}));+ assert_eq!(i["budget_exceeded"], false, "{i}");+ assert_eq!(i["budget_s"], 240.0, "{i}");+ assert_eq!(i["count"], 2, "{i}");+ let mut v: Vec<f64> = i["interferences"].as_array().into_iter().flatten().map(|h| f(&h["volume_mm3"])).collect();+ v.sort_by(f64::total_cmp);+ assert!((v[0] - 300.0).abs() < 1e-6 && (v[1] - 500.0).abs() < 1e-6, "{i}");+ // Answers come in pair order whatever order they finished in.+ assert_eq!((i["interferences"][0]["a"].as_str(), i["interferences"][0]["b"].as_str()), (Some("A"), Some("B")), "{i}");+ for bad in [json!(0), json!(-1), json!("soon"), json!(f64::MAX), json!(1e6)] {+ assert!(s.execute("inspect.interference", &json!({"budget_s": bad})).is_err(), "{bad}");+ }+}diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rsindex 2dbe97540d..aca98ef1d3 100644--- a/crates/engine/src/cmd/joints.rs+++ b/crates/engine/src/cmd/joints.rs@@ -12,7 +12,7 @@ use solidcraft_doc::joints::{self, Coupling, Joint, JointExprs, JointKind, Jointuse solidcraft_geom::{Aabb3, Vec3};use super::CommandSpec;-use crate::params::{bad, bool_, num, str_, string_list, vec3};+use crate::params::{bad, bool_, num, str_, vec3};use crate::{EngineError, Result, Session};pub static COMMANDS: &[CommandSpec] = &[@@ -77,8 +77,8 @@ pub static COMMANDS: &[CommandSpec] = &[(joint chains joined to nothing grounded: the solver places none of them, so driving them moves nothing)",),CommandSpec::new("joint.solve", "Solve Joints", solve_cmd).icon("compute").params("re-place the occurrences from the joints → conflicts, errors, dof"),- CommandSpec::new("inspect.interference", "Interference", interference).at("SOLID", "INSPECT").icon("interference").noundo().params(- "bodies?: [names] (default: all, in world placement) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: pairs that could not be checked, with the reason. Bodies are pruned by bounding box first, so any number of bodies is fine; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out)",+ CommandSpec::new("inspect.interference", "Interference", super::interference::interference).at("SOLID", "INSPECT").icon("interference").noundo().params(+ "bodies?: [names] (default: all, in world placement); budget_s?: seconds (default 240, at most 86400: pairs not finished by then are listed in unchecked as \"not checked: the time budget … ran out\" and the call returns) → interferences: pairs that overlap with the overlap volume, area, bounding box and centre (a pin a hair off the axis of a hole of its size also has near_coaxial: {offset_mm, length_mm}, its volume the crescent the walls share); unchecked: pairs that could not be checked, with the reason. Bodies are pruned by bounding box first, then by their display meshes (pairs whose meshes stay apart by more than their chord tolerances, neither inside the other, are clear without a boolean), so any number of bodies is fine; the pairs left are intersected exactly, in parallel on desktop, the slowest first; at most 20000 pairs whose boxes overlap are intersected per call (truncated: true and skipped_pairs: n say when more were left out). Also: pairs_candidate (boxes overlap), pairs_cleared (by the meshes), pairs_intersected, pairs_not_checked, budget_exceeded, threads (worker threads; 0: on the calling thread), boolean_ms and tessellate_ms (kernel time summed over the pairs), slowest: [{a, b, ms, boolean_ms, tessellate_ms}] and ms",),];@@ -1320,61 +1320,6 @@ fn solve_cmd(s: &mut Session, p: &Value) -> Result<Value> {Ok(sol_json(&sol, p))}-fn interference(s: &mut Session, p: &Value) -> Result<Value> {- let want = string_list(p, "bodies");- let st = s.world_state();- let bodies: Vec<&solidcraft_doc::ModelBody> =- st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).filter(|b| !b.body.is_mesh()).collect();- // Prune by bounding boxes first (sort and sweep), so the cost follows the pairs that can- // touch rather than the square of the body count.- let boxes: Vec<Aabb3> = bodies.iter().map(|b| b.mesh().bounds()).collect();- let (pairs, skipped) = overlapping_pairs(&boxes, MAX_INTERFERENCE_PAIRS);- let (mut hits, mut unchecked) = (Vec::new(), Vec::new());- for (i, j) in pairs {- let (Some(a), Some(b)) = (bodies.get(i), bodies.get(j)) else { continue };- let threshold = 1e-9 * a.body.size().max(1.0).powi(3);- // A pin a hair off the axis of its hole: the crescent the walls share, which the- // boolean can't intersect.- if let Some(o) = solidcraft_kernel::coaxial_overlap(&a.body, &b.body) {- if o.volume > threshold {- hits.push(json!({"a": a.name, "b": b.name, "volume_mm3": o.volume, "area_mm2": o.area, "center": o.centroid,- "bbox": {"min": o.bbox.min, "max": o.bbox.max}, "near_coaxial": {"offset_mm": o.offset, "length_mm": o.length}}));- }- continue;- }- // A pair whose shared part can't be worked out is reported, not passed as clear.- let (shared, report) =- solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(&a.body, &b.body, solidcraft_kernel::BoolOp::Intersect));- let mut skip = |reason: String| unchecked.push(json!({"a": a.name, "b": b.name, "reason": reason}));- let shared = match shared {- Ok(o) => o,- Err(e) => {- skip(e.to_string());- continue;- }- };- if let Some(reason) = report.unverified() {- skip(reason);- }- let Some(o) = shared else { continue };- let m = match solidcraft_kernel::measure(&o) {- Ok(m) => m,- Err(e) => {- skip(e.to_string());- continue;- }- };- if m.volume > threshold {- hits.push(json!({"a": a.name, "b": b.name, "volume_mm3": m.volume, "area_mm2": m.area, "center": m.centroid, "bbox": {"min": m.bbox.min, "max": m.bbox.max}}));- }- }- Ok(json!({"interferences": hits, "count": hits.len(), "checked": bodies.len(), "unchecked": unchecked,- "truncated": skipped > 0, "skipped_pairs": skipped}))-}--/// Most pairs with overlapping bounding boxes `inspect.interference` intersects in one call.-const MAX_INTERFERENCE_PAIRS: usize = 20_000;-/// Index pairs `(i, j)`, `i < j`, whose boxes overlap or touch (sort and sweep along X), at most/// `limit` of them, plus how many more there were.pub(crate) fn overlapping_pairs(boxes: &[Aabb3], limit: usize) -> (Vec<(usize, usize)>, usize) {diff --git a/crates/engine/src/cmd/mod.rs b/crates/engine/src/cmd/mod.rsindex e0a4e34e83..d02c971485 100644--- a/crates/engine/src/cmd/mod.rs+++ b/crates/engine/src/cmd/mod.rs@@ -39,6 +39,7 @@ mod component_link;mod config;mod file;mod inspect;+mod interference;pub(crate) mod joints;mod libraries;mod material_properties;diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rsindex 4296343780..0555849959 100644--- a/crates/kernel/src/lib.rs+++ b/crates/kernel/src/lib.rs@@ -176,7 +176,7 @@ pub use iges_out::iges_export_bodies;pub use lip::raise_band;pub use loft_blend::loft_blend;pub use matchsurf::{match_surface, seam_continuity};-pub use measure::{BodyMeasure, measure};+pub use measure::{BodyMeasure, MassMeasure, measure, measure_mass};pub use mesh_convert::convert_prismatic_mesh;pub use meshbody::{MAX_TRIANGLES, mesh_body};pub use native::{decode_native_body, encode_native_body, native_preview_mesh};diff --git a/crates/kernel/src/measure.rs b/crates/kernel/src/measure.rsindex 0f2e2e78a6..febcf6f791 100644--- a/crates/kernel/src/measure.rs+++ b/crates/kernel/src/measure.rs@@ -55,6 +55,16 @@ fn min_edge_radius(m: &Mesh) -> Option<f64> {best}+/// Volume, area, centre and box of a body, as [`measure`] works them out, without the topology+/// counts (and the tessellation they take).+#[derive(Clone, Copy, Debug, Serialize)]+pub struct MassMeasure {+ pub volume: f64,+ pub area: f64,+ pub centroid: Vec3,+ pub bbox: Aabb3,+}+/// Measure a body from a fine tessellation (chord tolerance 5e-5 of the body size, finer for/// small radii down to 5e-6). Faces whose fine tessellation disagrees with a coarse one (a/// meshing failure) use the coarse result.@@ -78,14 +88,69 @@ pub fn measure(b: &Body) -> Result<BodyMeasure> {merged,});}+ let (m, topo) = mass(b, true)?;+ let topo = match topo {+ Some(t) => t,+ None => b.tessellate((b.size() * 1e-3).max(1e-3))?,+ };+ Ok(BodyMeasure {+ volume: m.volume,+ area: m.area,+ centroid: m.centroid,+ bbox: m.bbox,+ faces: b.face_count(),+ edges: b.edge_count(),+ vertices: b.vertex_count(),+ shells: b.shell_count(),+ merged: merged_topology(b, &topo)?,+ })+}++/// [`measure`]'s volume, area, centre and box alone: the same numbers, a tessellation fewer+/// (for callers that need no topology counts, such as an interference check).+pub fn measure_mass(b: &Body) -> Result<MassMeasure> {+ if b.triangle_mesh().is_some() {+ let m = measure(b)?;+ return Ok(MassMeasure { volume: m.volume, area: m.area, centroid: m.centroid, bbox: m.bbox });+ }+ Ok(mass(b, false)?.0)+}++/// The mass properties of a B-rep body from three tessellations: a coarse one (which sets how+/// fine the others go), then a fine and a medium one at once on desktop (one after the other+/// in the browser). With `topology`, also the coarse unrefined mesh the topology counts take,+/// made alongside them.+fn mass(b: &Body, topology: bool) -> Result<(MassMeasure, Option<Mesh>)> {let size = b.size();- let coarse = b.tessellate_with((size * 1e-3).max(1e-3), true)?;+ let coarse_tol = (size * 1e-3).max(1e-3);+ let coarse = b.tessellate_with(coarse_tol, true)?;// Chord error relative to a radius sets the volume error: keep it near 3e-4 of the// smallest radius (thin tubes, small fillets).let tight = min_edge_radius(&coarse).map(|r| r * 3e-4).unwrap_or(f64::INFINITY);let fine_tol = (size * 5e-5).min(tight).max(size * 5e-6).max(1e-4);- let fine = b.tessellate_with(fine_tol, true)?;- let medium = b.tessellate_with((fine_tol * 5.0).max(2e-4), true)?;+ let mut jobs = vec![(fine_tol, true), ((fine_tol * 5.0).max(2e-4), true)];+ if topology {+ jobs.push((coarse_tol, false));+ }+ // Independent tessellations of one body: each on its own thread, the calling thread's+ // profile counting their wall time once as tessellation. Not from inside a worker pool: a+ // pool thread blocked on threads of its own could leave their meshing (which runs on the+ // shared pool) without a worker.+ #[cfg(not(target_arch = "wasm32"))]+ let threads = if rayon::current_thread_index().is_none() { jobs.len() } else { 1 };+ #[cfg(target_arch = "wasm32")]+ let threads = 1;+ let made = crate::profile::timed(crate::profile::Kind::Tessellate, || {+ crate::par::map_on_threads(&jobs, threads, |&(tol, refine)| b.tessellate_with(tol, refine))+ });+ let mut made = made.into_iter().map(|m| m.unwrap_or_else(|| Err(crate::KernelError::Internal("tessellation failed".into()))));+ let missing = || crate::KernelError::Internal("tessellation missing".into());+ let fine = made.next().ok_or_else(missing)??;+ let medium = made.next().ok_or_else(missing)??;+ let topo = match made.next() {+ Some(m) => Some(m?),+ None => None,+ };let nf = b.face_count();let (sf, sm, sc) = (face_sums(&fine, nf), face_sums(&medium, nf), face_sums(&coarse, nf));let close = |x: f64, y: f64| (x - y).abs() <= 0.01 * x.abs().max(y.abs()) + 1e-9;@@ -105,15 +170,31 @@ pub fn measure(b: &Body) -> Result<BodyMeasure> {}let volume = v6 / 6.0;let centroid = if v6.abs() > 1e-12 { mom / (4.0 * v6) } else { fine.bounds().center() };- Ok(BodyMeasure {- volume,- area,- centroid,- bbox: coarse.bounds().union(&fine.bounds()),- faces: b.face_count(),- edges: b.edge_count(),- vertices: b.vertex_count(),- shells: b.shell_count(),- merged: merged_topology(b, &b.tessellate((size * 1e-3).max(1e-3))?)?,- })+ Ok((MassMeasure { volume, area, centroid, bbox: coarse.bounds().union(&fine.bounds()) }, topo))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{BoolOp, boolean, cylinder, torus};++ /// The mass properties alone are [`measure`]'s, to the bit, with the tessellations made at+ /// once; and on a curved intersection they are the textbook ones.+ #[test]+ fn mass_alone_is_the_full_measure() {+ let ring = torus(Vec3::ZERO, 10.0, 2.0).unwrap();+ let post = cylinder(Vec3::new(10.0, 0.0, -5.0), Vec3::Z, 1.5, 10.0).unwrap();+ let shared = boolean(&ring, &post, BoolOp::Intersect).unwrap().unwrap();+ for b in [&ring, &shared] {+ let (full, mass) = (measure(b).unwrap(), measure_mass(b).unwrap());+ assert_eq!(full.volume.to_bits(), mass.volume.to_bits());+ assert_eq!(full.area.to_bits(), mass.area.to_bits());+ assert_eq!(full.centroid, mass.centroid);+ assert_eq!((full.bbox.min, full.bbox.max), (mass.bbox.min, mass.bbox.max));+ }+ let want = 2.0 * std::f64::consts::PI.powi(2) * 10.0 * 4.0;+ let got = measure_mass(&ring).unwrap().volume;+ assert!((got - want).abs() < 1e-3 * want, "{got} against {want}");+ assert!(measure(&ring).unwrap().merged.faces > 0);+ }}diff --git a/crates/kernel/src/profile.rs b/crates/kernel/src/profile.rsindex 5d1cea894e..bd40bd4994 100644--- a/crates/kernel/src/profile.rs+++ b/crates/kernel/src/profile.rs@@ -59,6 +59,21 @@ pub fn capture<T>(f: impl FnOnce() -> T) -> (T, KernelTimes) {(r, times)}+/// Count kernel time spent on other threads for this thread's running capture (when one runs+/// and no timed call does): work this thread handed out and waited for. The caller keeps the+/// sum within the wall time it waited, so the totals still never pass what the command took.+pub fn credit(times: KernelTimes) {+ let ok = |x: f64| if x.is_finite() && x > 0.0 { x } else { 0.0 };+ STATE.with(|s| {+ let mut st = s.get();+ if st.on && !st.busy {+ st.times.boolean_ms += ok(times.boolean_ms);+ st.times.tessellate_ms += ok(times.tessellate_ms);+ s.set(st);+ }+ });+}+/// Time `f` as `kind` when a capture is running and no timed call is.pub(crate) fn timed<T>(kind: Kind, f: impl FnOnce() -> T) -> T {let st = STATE.with(Cell::get);@@ -122,6 +137,19 @@ mod tests {assert!(t.boolean_ms + t.tessellate_ms <= elapsed + 1e-6, "{t:?} in {elapsed} ms");}+ #[test]+ fn time_credited_from_other_threads_counts_only_inside_a_capture() {+ let t = KernelTimes { boolean_ms: 4.0, tessellate_ms: 1.0 };+ credit(t);+ let ((), got) = capture(|| {+ credit(t);+ credit(KernelTimes { boolean_ms: f64::NAN, tessellate_ms: -3.0 });+ // Inside a timed call it would count twice: it is the call's time already.+ timed(Kind::Boolean, || credit(t));+ });+ assert_eq!((got.boolean_ms >= 4.0, got.boolean_ms < 8.0, got.tessellate_ms), (true, true, 1.0), "{got:?}");+ }+#[test]fn inner_captures_add_to_the_outer_one_and_a_panic_restores_it() {let ((), outer) = capture(|| {diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.mdindex 5c20f1d9cc..f60701c1c9 100644--- a/docs/book/src/guide/assemblies.md+++ b/docs/book/src/guide/assemblies.md@@ -62,7 +62,10 @@ body in `bodies` and the other in `against`, and `skip_within` leaves out pairsoccurrence (`"occurrence"`) or one placed component, its subcomponents included(`"component"`): the parts of a bought component that touch by design. Distances are measured onthe exact faces and edges; the meshes only rule out pairs that are too far apart, and the pairs-left are checked in parallel. `inspect.interference` remains for the overlaps alone.+left are checked in parallel. `inspect.interference` remains for the overlaps alone: it clears+pairs whose meshes stay apart without intersecting them, intersects the rest in parallel, and+returns after `budget_s` seconds (default 240) at most, listing the pairs it had no time for as+not checked.**Gear**, **Rack and Pinion** and **Screw** (on the **ASSEMBLE** panel) are motion links whoseratio comes from the parts rather than a typed number: