diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rs index 2ef36228f..902005f53 100644 --- a/crates/engine/src/cmd/clearance.rs +++ b/crates/engine/src/cmd/clearance.rs @@ -19,13 +19,13 @@ use crate::params::{bad, num, str_, string_list}; use crate::{Result, Session}; pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "Clearance", clearance).icon("interference").noundo().params( - "bodies?: [names] (default: every solid body, in world placement, but those in `against`); against?: [names] (only pairs with one body in `bodies` and the other here); \ + "bodies?: [names] (default: every solid body, in world placement, but those in `against`; mesh bodies are not measured); against?: [names] (only pairs with one body in `bodies` and the other here); \ min_volume?: mm³ (default 0.01: smaller overlaps count as contact); clearance?: mm (default 0: report pairs closer than this); \ nearest?: n (each body of `bodies` gets its n nearest others); skip_within?: \"occurrence\" (pairs of bodies of one occurrence) | \ \"component\" (pairs of bodies inside one placed component, its subcomponents included) | null; tolerance?: mm (default 1e-6: a gap \ below it is contact, 0) → overlaps: [{a, b, volume_mm3, area_mm2, bbox, center}]; near: [{a, b, distance_mm, from, to, overlap_mm3?: \ a contact's shared volume below min_volume, exact?: false when measured on the meshes}], nearest by body (the same for pairs that overlap: 0); \ - nearest: {body: [{body, distance_mm}]}; unchecked: [{a, b, reason}] (pairs whose overlap could not be worked out); pairs_checked; \ + nearest: {body: [{body, distance_mm}]}; unchecked: [{a, b, reason}] (pairs whose overlap could not be worked out; each mesh body, STL/3MF/OBJ import, is not measured and is listed as {a: name, b: null, reason: \"mesh body: not checked\"}, also when named in `bodies` or `against`; the result's `bodies` counts the solid bodies only); pairs_checked; \ pairs_reused (of those, measured by an earlier call: neither body changed or moved since); pairs_pruned (ruled out by their boxes); ms. Distances are measured on the exact faces and edges, the meshes only rule pairs out", )]; @@ -92,12 +92,19 @@ fn clearance(s: &mut Session, p: &Value) -> Result { }; let st = s.world_state(); - let solid: Vec<&solidcraft_doc::ModelBody> = st.bodies.iter().filter(|b| !b.body.is_mesh()).collect(); + let (mesh_bodies, solid): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) = st.bodies.iter().partition(|b| b.body.is_mesh()); + // Mesh bodies are not measured. A mesh body named in `bodies` or `against` is left out of the + // pairs and listed as unchecked, rather than refused as "no solid body". let named = |key: &str| -> Result> { let names = string_list(p, key); let mut out = Vec::new(); for n in &names { - let i = solid.iter().position(|b| &b.name == n).ok_or_else(|| bad(cmd, format!("no solid body `{n}`")))?; + let Some(i) = solid.iter().position(|b| &b.name == n) else { + if mesh_bodies.iter().any(|b| &b.name == n) { + continue; + } + return Err(bad(cmd, format!("no solid body `{n}`"))); + }; if !out.contains(&i) { out.push(i); } @@ -249,7 +256,15 @@ fn clearance(s: &mut Session, p: &Value) -> Result { let results = results.into_iter().map(|r| r.unwrap_or_else(|| Ok(PairResult::default()))); let mut known: HashMap<(usize, usize), f64> = HashMap::new(); - let (mut overlaps, mut near, mut unchecked) = (Vec::new(), Vec::new(), Vec::new()); + let (mut overlaps, mut near) = (Vec::new(), Vec::new()); + // The mesh bodies the call was about (every one without `bodies`, else those named in + // `bodies` or `against`) come first, so "nothing found" is not read as "no overlap". + let asked: Vec = ["bodies", "against"].iter().flat_map(|k| string_list(p, k)).collect(); + let mut unchecked: Vec = mesh_bodies + .iter() + .filter(|b| p.get("bodies").is_none_or(Value::is_null) || asked.contains(&b.name)) + .map(|b| json!({"a": b.name, "b": null, "reason": super::interference::MESH_NOT_CHECKED})) + .collect(); let name = |i: usize| solid.get(i).map_or("", |b| b.name.as_str()); for (&(i, j), r) in close.iter().zip(results) { let r = match r { diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rs index 16bc3fda7..5cfa44b66 100644 --- a/crates/engine/src/cmd/clearance_tests.rs +++ b/crates/engine/src/cmd/clearance_tests.rs @@ -474,6 +474,57 @@ fn a_roller_pressed_into_a_large_plate_is_reported() { assert!((f(&overlaps[0]["volume_mm3"]) - want).abs() < 0.01 * want, "{want} {res}"); } +/// Two STL copies of a cube inserted into a design. Returns the names of the two mesh bodies. +fn insert_two_mesh_cubes(s: &mut Session, tag: &str) -> Vec { + let dir = std::env::temp_dir().join(format!("solidcraft-mesh-unchecked-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let stl = dir.join("cube.stl"); + let mut cube = Session::default(); + run(&mut cube, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Cube"})); + run(&mut cube, "file.export", json!({"path": stl.to_string_lossy()})); + for _ in 0..2 { + run(s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); + } + let _ = std::fs::remove_dir_all(&dir); + s.world_state().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() +} + +/// #3249: mesh bodies are not measured, and used to vanish from the answer (`bodies: 0`, nothing +/// unchecked). They are listed in `unchecked` with a reason, and naming one in `bodies` or +/// `against` is not "no solid body". +#[test] +fn mesh_bodies_are_listed_as_unchecked_and_can_be_named() { + let mut s = Session::default(); + let meshes = insert_two_mesh_cubes(&mut s, "clearance"); + assert_eq!(meshes.len(), 2, "{meshes:?}"); + let r = run(&mut s, "inspect.clearance", json!({"clearance": 1})); + assert_eq!((r["bodies"].as_u64(), r["pairs_checked"].as_u64()), (Some(0), Some(0)), "{r}"); + let unchecked = r["unchecked"].as_array().cloned().unwrap_or_default(); + assert_eq!(unchecked.len(), 2, "{r}"); + for (u, name) in unchecked.iter().zip(&meshes) { + assert_eq!(u["a"].as_str(), Some(name.as_str()), "{r}"); + assert!(u["b"].is_null(), "{r}"); + assert_eq!(u["reason"], "mesh body: not checked", "{r}"); + } + // Beside solid bodies: those are measured, the meshes are still listed. + cube(&mut s, "A", 10.0, [100.0, 0.0, 0.0]); + cube(&mut s, "B", 10.0, [105.0, 0.0, 0.0]); + let r = run(&mut s, "inspect.clearance", json!({})); + assert_eq!(r["bodies"], 2, "{r}"); + assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(1), "{r}"); + assert_eq!(r["unchecked"].as_array().map(Vec::len), Some(2), "{r}"); + // A mesh body named in `bodies` or `against` is listed, not refused; an unknown name still is. + for params in [json!({"bodies": ["A", meshes[0]]}), json!({"bodies": ["A"], "against": [meshes[0]]})] { + let r = run(&mut s, "inspect.clearance", params.clone()); + let unchecked = r["unchecked"].as_array().cloned().unwrap_or_default(); + assert_eq!(unchecked.len(), 1, "{params}: {r}"); + assert_eq!(unchecked[0]["a"].as_str(), Some(meshes[0].as_str()), "{params}: {r}"); + } + let e = s.execute("inspect.clearance", &json!({"bodies": ["Nope"]})).unwrap_err().to_string(); + assert!(e.contains("`Nope`"), "{e}"); +} + /// A pin turned from a profile (its wall in three faces) in the bore of a tube of its own size /// (in two faces), its end inside the bore, a hair off the axis, and a slit tube with the pin /// through it: touching, not overlapping. Their facets cross where one body's faces end on the diff --git a/crates/engine/src/cmd/interference.rs b/crates/engine/src/cmd/interference.rs index 06c5c1bfc..43781bb66 100644 --- a/crates/engine/src/cmd/interference.rs +++ b/crates/engine/src/cmd/interference.rs @@ -31,6 +31,8 @@ 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; +/// Why a mesh body is listed under `unchecked` (here and in `inspect.clearance`). +pub(super) const MESH_NOT_CHECKED: &str = "mesh body: not checked"; /// Most pairs listed under `slowest`. const SLOWEST: usize = 8; @@ -73,8 +75,8 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result { 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(); + let (meshes_left, bodies): (Vec<&solidcraft_doc::ModelBody>, Vec<&solidcraft_doc::ModelBody>) = + st.bodies.iter().filter(|b| want.is_empty() || want.contains(&b.name)).partition(|b| b.body.is_mesh()); // The bodies' display meshes, made once (in parallel) and kept on the bodies: a design open // in the app has them already. @@ -152,7 +154,9 @@ pub(super) fn interference(s: &mut Session, p: &Value) -> Result { 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()); + // Mesh bodies are not intersected: say so, rather than let `count: 0` read as "no overlap". + let mut unchecked: Vec = meshes_left.iter().map(|b| json!({"a": b.name, "b": null, "reason": MESH_NOT_CHECKED})).collect(); + let (mut hits, mut timed) = (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 { diff --git a/crates/engine/src/cmd/interference_tests.rs b/crates/engine/src/cmd/interference_tests.rs index 9d65ee89a..2be9c0383 100644 --- a/crates/engine/src/cmd/interference_tests.rs +++ b/crates/engine/src/cmd/interference_tests.rs @@ -108,3 +108,51 @@ fn pairs_left_when_the_budget_runs_out_are_listed_not_checked() { assert!(s.execute("inspect.interference", &json!({"budget_s": bad})).is_err(), "{bad}"); } } + +/// Two STL copies of a cube inserted into a design. Returns the names of the two mesh bodies. +pub(super) fn insert_two_mesh_cubes(s: &mut Session, tag: &str) -> Vec { + let dir = std::env::temp_dir().join(format!("solidcraft-mesh-unchecked-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let stl = dir.join("cube.stl"); + let mut cube = Session::default(); + run(&mut cube, "solid.box", json!({"length": 20, "width": 20, "height": 20, "corner": [0, 0, 0], "body_name": "Cube"})); + run(&mut cube, "file.export", json!({"path": stl.to_string_lossy()})); + for _ in 0..2 { + run(s, "file.insert_mesh", json!({"path": stl.to_string_lossy()})); + } + let _ = std::fs::remove_dir_all(&dir); + s.world_state().bodies.iter().filter(|b| b.body.is_mesh()).map(|b| b.name.clone()).collect() +} + +/// #3249: mesh bodies (STL, 3MF, OBJ imports) are not intersected, but they used to vanish from +/// the answer: `count: 0, unchecked: []` read as "no collision". Each is now listed in `unchecked` +/// with a reason, and the solid bodies are checked as before. +#[test] +fn mesh_bodies_are_listed_as_unchecked_not_dropped() { + let mut s = Session::default(); + let meshes = insert_two_mesh_cubes(&mut s, "interference"); + assert_eq!(meshes.len(), 2, "{meshes:?}"); + // Only meshes: nothing is checked, and both are said to be left out. + let i = run(&mut s, "inspect.interference", json!({})); + assert_eq!((i["count"].as_u64(), i["checked"].as_u64()), (Some(0), Some(0)), "{i}"); + let unchecked = i["unchecked"].as_array().cloned().unwrap_or_default(); + assert_eq!(unchecked.len(), 2, "{i}"); + for (u, name) in unchecked.iter().zip(&meshes) { + assert_eq!(u["a"].as_str(), Some(name.as_str()), "{i}"); + assert!(u["b"].is_null(), "{i}"); + assert_eq!(u["reason"], "mesh body: not checked", "{i}"); + } + // With solid bodies beside them: those are checked, the meshes are still listed. + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [100, 0, 0], "operation": "new", "body_name": "A"})); + run(&mut s, "solid.box", json!({"length": 10, "width": 10, "height": 10, "corner": [105, 0, 0], "operation": "new", "body_name": "B"})); + let i = run(&mut s, "inspect.interference", json!({})); + assert_eq!((i["count"].as_u64(), i["checked"].as_u64()), (Some(1), Some(2)), "{i}"); + assert_eq!(i["unchecked"].as_array().map(Vec::len), Some(2), "{i}"); + // Naming only solid bodies lists no mesh; naming a mesh body lists just that one. + let i = run(&mut s, "inspect.interference", json!({"bodies": ["A", "B"]})); + assert_eq!(i["unchecked"].as_array().map(Vec::len), Some(0), "{i}"); + let i = run(&mut s, "inspect.interference", json!({"bodies": ["A", meshes[0]]})); + assert_eq!(i["checked"], 1, "{i}"); + assert_eq!(i["unchecked"][0]["a"].as_str(), Some(meshes[0].as_str()), "{i}"); +} diff --git a/crates/engine/src/cmd/joints.rs b/crates/engine/src/cmd/joints.rs index bac77a780..9917c5dd2 100644 --- a/crates/engine/src/cmd/joints.rs +++ b/crates/engine/src/cmd/joints.rs @@ -94,7 +94,7 @@ pub static COMMANDS: &[CommandSpec] = &[ ), 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", 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", + "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: [{a, b, reason}], the pairs that could not be checked, with the reason, and each mesh body (STL, 3MF or OBJ import: not intersected) as {a: name, b: null, reason: \"mesh body: not checked\"}, so count: 0 is not read as no overlap (checked counts the solid bodies). 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", ), ]; diff --git a/docs/book/src/guide/assemblies.md b/docs/book/src/guide/assemblies.md index e7888b56d..f7a5a0452 100644 --- a/docs/book/src/guide/assemblies.md +++ b/docs/book/src/guide/assemblies.md @@ -89,6 +89,10 @@ pairs whose meshes stay apart without intersecting them, intersects the rest in returns after `budget_s` seconds (default 240) at most, listing the pairs it had no time for as not checked. +Mesh bodies (STL, 3MF and OBJ imports) are not checked by either command: each is listed in +`unchecked` as `{a: name, b: null, reason: "mesh body: not checked"}`, so `count: 0` or an empty +`overlaps` is not mistaken for "no overlap" when a mesh body was in the design. + **Gear**, **Rack and Pinion** and **Screw** (on the **ASSEMBLE** panel) are motion links whose ratio comes from the parts rather than a typed number: