inspect.clearance: mesh each body once per check instead of once per pair (#2867)

* inspect.clearance: pairs whose bodies did not change are not measured again

Each clearance check measured every close pair again, though between two
checks usually only a few bodies change or move. Results are now kept per pair,
keyed by both bodies' geometry and placement and the check's settings; a pair
whose two bodies are unchanged is taken from that cache. With 40 overlapping
parts, a check after moving one of them took 0.8 s instead of 23 s (741 of 780
pairs reused). Pairs that could not be worked out are tried again each time.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* inspect.clearance: boxes and placed keys exactly as before the reuse

The pair boxes are taken over the mesh's triangles with finite corners, as a
distance shape's are, so pruning is unchanged. A placed body's identity now
includes its model body's own frame, so two placements are never mistaken for
one another.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* inspect.clearance: a large body is meshed once for all its pairs

Each pair that touches cuts the larger body down to the pair's region with a
kernel boolean, and that boolean meshed the whole body twice: once for its
checks and once inside the intersection. A sheet with 600 faces paid about
2.5 s per pair for meshes that were the same every time.

A body can now keep its meshes for reuse (Body::keeping_meshes); its booleans
take the meshes from there, and the intersection takes its shell meshes
from there too (truck-shapeops: and_with_history_meshed). Clearance uses such
copies for one check. Results are unchanged to the bit. On a 3 x 2 m sheet
with bends and 300 holes, the clip took 0.23 s per pair instead of 2.6 s, and
24 rivets took 5.6 s instead of 16.5 s.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Co-authored-by: bherbruck <brennen.herbruck@gmail.com>
This commit is contained in:
NOWN-DEV
2026-10-19 22:14:24 +02:00
committed by GitHub
parent 77c3b1e765
commit 02c77df5f7
18 changed files with 346 additions and 31 deletions
+1 -1
View File
@@ -472,7 +472,7 @@ copied into SolidCraft.
|---|---|---|---|
| vendor/truck-meshalgo | truck-meshalgo 0.4.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | meshing: bounded parameter searches, collapsed-boundary projection, subdivision and provisional fixed-grid previews (vendor/README.md) |
| vendor/truck-stepio | truck-stepio 0.3.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | STEP writer: intersection-curve surfaces written at unique ids (vendor/README.md) |
| vendor/truck-shapeops | truck-shapeops 0.4.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | robust meshing and nearest-parameter fallback in booleans; degenerate intersection-curve rejection; face and edge history of booleans; trace macro; corner choice at vertices several intersection curves end on (vendor/README.md) |
| vendor/truck-shapeops | truck-shapeops 0.4.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | robust meshing and nearest-parameter fallback in booleans; degenerate intersection-curve rejection; face and edge history of booleans; trace macro; corner choice at vertices several intersection curves end on; reuse of an operand's meshes (vendor/README.md) |
| vendor/truck-geometry | truck-geometry 0.5.0, https://github.com/ricosjp/truck (RICOS Co. Ltd.) | Apache-2.0 | intersection curves divided from their neighbours' surface parameters; surface second derivatives (vendor/README.md) |
| vendor/matext4cgmath | matext4cgmath 0.1.0, https://github.com/ricosjp/matext4cgmath (RICOS Co. Ltd.) | Apache-2.0 | root refinement stops after 100 Newton steps (vendor/README.md) |
+22
View File
@@ -55,6 +55,8 @@ pub struct ModelBody {
/// [`Body::retained_bytes`] of `body`, measured when a feature made or changed it (0: not
/// measured), so the evaluation cache's budget does not walk every body after every feature.
bytes: usize,
/// In a world state: the [`ModelBody::geometry_key`] of the model body this one places (0: none).
source_key: u64,
}
impl ModelBody {
@@ -76,8 +78,24 @@ impl ModelBody {
transferred: false,
imported: None,
bytes: 0,
source_key: 0,
}
}
/// Identity of this body's geometry where it stands: the same for a body evaluated or
/// placed again from the same inputs at the same place, so work measured on it can be
/// reused (none for a body the evaluation cache does not key).
pub fn geometry_key(&self) -> Option<u64> {
use std::hash::{Hash, Hasher};
let key = if self.key != 0 { self.key } else { self.source_key };
if key == 0 {
return None;
}
let mut h = std::collections::hash_map::DefaultHasher::new();
key.hash(&mut h);
self.source_transform.iter().flatten().for_each(|v| v.to_bits().hash(&mut h));
Some(h.finish())
}
pub fn definition_name(&self) -> &str {
self.source_name.as_deref().unwrap_or(&self.name)
}
@@ -5843,6 +5861,8 @@ pub fn world_state_reusing(doc: &Document, st: &ModelState, placed_before: &mut
};
// World states keep their previous display-only evaluation-key semantics.
placed.key = 0;
// With the model body's own frame, so its place is told apart from the placement's.
placed.source_key = b.geometry_key().unwrap_or(0);
placed.source_name = Some(b.definition_name().to_string());
placed.source_transform = crate::mat_mul(&bm, &b.source_transform);
placed.component = comp;
@@ -5951,6 +5971,8 @@ mod world_placement_cache_tests {
assert!(Arc::ptr_eq(&source.mesh, &first.mesh), "unchanged geometry must retain the shared display mesh cell");
assert_eq!(first.key, 0);
assert_eq!(placed.key, 0);
// Each placement has its own geometry identity, for work measured on it.
assert!(first.geometry_key().is_some() && first.geometry_key() != placed.geometry_key());
assert!(!Arc::ptr_eq(&source.mesh, &placed.mesh), "a transformed mesh cannot be reused without mapping coordinates");
assert_eq!(first.source_name.as_deref(), Some("Block"));
assert_eq!(placed.source_name.as_deref(), Some("Block"));
+79 -14
View File
@@ -3,7 +3,8 @@
//! by bounding boxes grown by the clearance, then by the bodies' meshes (which lie within their
//! chord tolerance of the faces); distances are measured on the exact faces and edges
//! ([`solidcraft_kernel::body_distance`]) and overlaps by intersecting the bodies. The pairs
//! that are left run in parallel.
//! that are left run in parallel. A pair whose bodies have not changed or moved since a call
//! with the same settings measured it is not measured again ([`PairCache`]).
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
@@ -25,7 +26,7 @@ pub static COMMANDS: &[CommandSpec] = &[CommandSpec::new("inspect.clearance", "C
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; \
pairs_pruned (ruled out by their boxes); ms. Distances are measured on the exact faces and edges, the meshes only rule pairs out",
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",
)];
/// Most bodies one call takes.
@@ -44,8 +45,17 @@ enum SkipWithin {
Component,
}
/// What one pair came to.
/// Most pairs [`PairCache`] keeps; it starts over when full.
const MAX_CACHED: usize = 2 * MAX_PAIRS;
/// Pairs measured before, by the two bodies' geometry where they stood
/// ([`solidcraft_doc::ModelBody::geometry_key`]) and the settings that shape the result
/// (clearance, smallest overlap, tolerance).
#[derive(Default)]
pub(crate) struct PairCache(HashMap<(u64, u64, [u64; 3]), PairResult>);
/// What one pair came to.
#[derive(Clone, Default)]
struct PairResult {
/// Shared volume, area, box and centre.
overlap: Option<(f64, f64, Aabb3, solidcraft_geom::Vec3)>,
@@ -152,20 +162,40 @@ fn clearance(s: &mut Session, p: &Value) -> Result<Value> {
}
out
};
let shapes: Vec<Option<DistanceShape>> = (0..n)
// The distance shapes are made only for bodies a pair or a nearest list measures; the boxes
// come from the meshes, grown by the chord tolerance as a shape's are.
let shapes: Vec<std::sync::OnceLock<Option<DistanceShape>>> = (0..n).map(|_| std::sync::OnceLock::new()).collect();
let shape = |i: usize| {
shapes
.get(i)?
.get_or_init(|| match (solid.get(i), meshes.get(i).and_then(Option::as_ref)) {
(Some(b), Some(m)) if flag(&used, i) => Some(DistanceShape::new(&b.body, m, b.display_tol())),
_ => None,
})
.as_ref()
};
let boxes: Vec<Aabb3> = (0..n)
.map(|i| match (solid.get(i), meshes.get(i).and_then(Option::as_ref)) {
(Some(b), Some(m)) if flag(&used, i) => Some(DistanceShape::new(&b.body, m, b.display_tol())),
_ => None,
(Some(b), Some(m)) if flag(&used, i) => {
// Over the triangles with finite corners, as a shape's set of them is.
let mut bx = Aabb3::EMPTY;
for p in m.triangles.iter().filter_map(|t| m.tri(t)).filter(|p| p.iter().all(|v| v.is_finite())) {
p.into_iter().for_each(|v| bx.add(v));
}
let chord = b.display_tol();
let g = solidcraft_geom::Vec3::new(1.0, 1.0, 1.0) * if chord.is_finite() && chord > 0.0 { chord } else { 0.0 };
if bx.is_empty() { bx } else { Aabb3 { min: bx.min - g, max: bx.max + g } }
}
_ => Aabb3::EMPTY,
})
.collect();
let shape = |i: usize| shapes.get(i).and_then(Option::as_ref);
let boxes: Vec<Aabb3> = (0..n).map(|i| shape(i).map_or(Aabb3::EMPTY, DistanceShape::bounds)).collect();
// Pairs whose boxes, grown by half the clearance each, meet.
let half = solidcraft_geom::Vec3::new(1.0, 1.0, 1.0) * (gap / 2.0);
let grown: Vec<Aabb3> = boxes.iter().map(|b| if b.is_empty() { *b } else { Aabb3 { min: b.min - half, max: b.max + half } }).collect();
let (close, truncated) = super::joints::overlapping_pairs(&grown, MAX_PAIRS);
let close: Vec<(usize, usize)> = close.into_iter().filter(|&(i, j)| allowed(i, j) && shape(i).is_some() && shape(j).is_some()).collect();
let has_mesh = |i: usize| meshes.get(i).is_some_and(Option::is_some);
let close: Vec<(usize, usize)> = close.into_iter().filter(|&(i, j)| allowed(i, j) && has_mesh(i) && has_mesh(j)).collect();
let mut total = 0usize;
for i in 0..n {
for j in i + 1..n {
@@ -175,11 +205,45 @@ fn clearance(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let results = solidcraft_kernel::map_with_local_pools(&close, usize::MAX, |&(i, j)| {
// Pairs measured before come from the cache; the rest are measured and kept.
let settings = [gap.to_bits(), min_volume.to_bits(), tolerance.to_bits()];
let cache_key = |i: usize, j: usize| Some((solid.get(i)?.geometry_key()?, solid.get(j)?.geometry_key()?, settings));
let mut results: Vec<Option<solidcraft_kernel::Result<PairResult>>> = {
let cache = s.clearance_cache.lock().ok();
close.iter().map(|&(i, j)| cache.as_ref().and_then(|c| c.0.get(&cache_key(i, j)?)).cloned().map(Ok)).collect()
};
let todo: Vec<usize> = (0..close.len()).filter(|&k| results.get(k).is_some_and(Option::is_none)).collect();
let reused = close.len() - todo.len();
// A body in many pairs is cut down to each pair's region from the same mesh of it.
let kept: Vec<std::sync::OnceLock<Option<solidcraft_kernel::Body>>> = (0..n).map(|_| std::sync::OnceLock::new()).collect();
let kept_body = |i: usize| kept.get(i)?.get_or_init(|| solid.get(i).map(|b| b.body.keeping_meshes())).as_ref();
let measured = solidcraft_kernel::map_with_local_pools(&todo, usize::MAX, |&k| {
let Some(&(i, j)) = close.get(k) else { return Ok(PairResult::default()) };
let (Some(a), Some(b)) = (shape(i), shape(j)) else { return Ok(PairResult::default()) };
let (Some(ba), Some(bb)) = (solid.get(i), solid.get(j)) else { return Ok(PairResult::default()) };
Ok(measure_pair(ba, a, bb, b, gap, min_volume, tolerance))
let (Some(ka), Some(kb)) = (kept_body(i), kept_body(j)) else { return Ok(PairResult::default()) };
Ok(measure_pair((ba, ka), a, (bb, kb), b, gap, min_volume, tolerance))
});
if let Ok(mut cache) = s.clearance_cache.lock() {
for (&k, r) in todo.iter().zip(&measured) {
// A pair that could not be worked out is tried again next time.
let (Ok(r), Some(&(i, j))) = (r, close.get(k)) else { continue };
if r.unchecked.is_some() {
continue;
}
let Some(key) = cache_key(i, j) else { continue };
if cache.0.len() >= MAX_CACHED {
cache.0.clear();
}
cache.0.insert(key, r.clone());
}
}
for (k, r) in todo.into_iter().zip(measured) {
if let Some(slot) = results.get_mut(k) {
*slot = Some(r);
}
}
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());
@@ -240,6 +304,7 @@ fn clearance(s: &mut Session, p: &Value) -> Result<Value> {
"unchecked": unchecked,
"bodies": subjects.len(),
"pairs_checked": close.len(),
"pairs_reused": reused,
"pairs_pruned": total.saturating_sub(close.len()),
"truncated": truncated > 0,
"ms": started.elapsed().as_secs_f64() * 1000.0,
@@ -249,9 +314,9 @@ fn clearance(s: &mut Session, p: &Value) -> Result<Value> {
/// One pair: its overlap when the meshes meet or one holds the other, otherwise its distance
/// when it may be closer than `gap`.
fn measure_pair(
ba: &solidcraft_doc::ModelBody,
(ba, ka): (&solidcraft_doc::ModelBody, &solidcraft_kernel::Body),
a: &DistanceShape,
bb: &solidcraft_doc::ModelBody,
(bb, kb): (&solidcraft_doc::ModelBody, &solidcraft_kernel::Body),
b: &DistanceShape,
gap: f64,
min_volume: f64,
@@ -275,7 +340,7 @@ fn measure_pair(
if touching || holds(ba, bb) || holds(bb, ba) {
// A pair whose shared part can't be worked out is reported, not passed as clear.
let region = shared_region(a, b);
let (ca, cb) = (clipped(&ba.body, region), clipped(&bb.body, region));
let (ca, cb) = (clipped(ka, region), clipped(kb, region));
let (shared, report) = solidcraft_kernel::capture_boolean_diagnostics(|| {
solidcraft_kernel::boolean(ca.as_ref().unwrap_or(&ba.body), cb.as_ref().unwrap_or(&bb.body), solidcraft_kernel::BoolOp::Intersect)
});
+53
View File
@@ -252,6 +252,59 @@ fn a_small_gap_past_a_corner_is_not_contact() {
}
}
/// A second call measures only the pairs with a body that changed or moved since the first.
#[test]
fn pairs_whose_bodies_did_not_change_or_move_are_not_measured_again() {
let mut s = Session::default();
run(&mut s, "component.create", json!({"name": "Bought"}));
cube(&mut s, "Housing", 10.0, [0.0, 0.0, 0.0]);
cube(&mut s, "Insert", 4.0, [8.0, 3.0, 3.0]);
run(&mut s, "component.activate", json!({"component": "root"}));
let bracket = run(&mut s, "component.create", json!({"name": "Bracket"}))["component"].as_u64().unwrap();
cube(&mut s, "Plate", 10.0, [-9.5, 0.0, 0.0]);
let settings = json!({"clearance": 1});
let first = run(&mut s, "inspect.clearance", settings.clone());
assert_eq!((first["pairs_checked"].as_u64(), first["pairs_reused"].as_u64()), (Some(2), Some(0)), "{first}");
let again = run(&mut s, "inspect.clearance", settings.clone());
assert_eq!(again["pairs_reused"], 2, "{again}");
for k in ["overlaps", "near", "unchecked"] {
assert_eq!(again[k], first[k], "{k}");
}
// Other settings are measured afresh.
assert_eq!(run(&mut s, "inspect.clearance", json!({"clearance": 2}))["pairs_reused"], 0);
// The bracket moves 1 mm away: only its pair is measured again, and it is now near, not over.
let o = s.doc.occurrence_of(bracket).unwrap().id;
run(&mut s, "occurrence.move", json!({"occurrence": o, "translate": [-1, 0, 0], "capture": true}));
let moved = run(&mut s, "inspect.clearance", settings.clone());
assert_eq!((moved["pairs_checked"].as_u64(), moved["pairs_reused"].as_u64()), (Some(2), Some(1)), "{moved}");
let overlaps: Vec<[String; 2]> = moved["overlaps"].as_array().into_iter().flatten().map(pair).collect();
assert_eq!(overlaps, vec![["Housing".to_string(), "Insert".to_string()]], "{moved}");
assert!((f(&moved["near"][0]["distance_mm"]) - 0.5).abs() < 1e-6, "{moved}");
let still = run(&mut s, "inspect.clearance", settings);
assert_eq!(still["pairs_reused"], 2, "nothing changed since: {still}");
assert_eq!(still["near"], moved["near"]);
}
/// A body rebuilt with other geometry is measured again, not taken from an earlier call.
#[test]
fn a_body_that_changed_shape_is_measured_again() {
let mut s = Session::default();
cube(&mut s, "A", 10.0, [0.0, 0.0, 0.0]);
cube(&mut s, "B", 10.0, [10.5, 0.0, 0.0]);
let r = run(&mut s, "inspect.clearance", json!({"clearance": 1}));
assert!((f(&r["near"][0]["distance_mm"]) - 0.5).abs() < 1e-6, "{r}");
let list = run(&mut s, "parameters.list", json!({"filter": "feature"}));
let length = list["parameters"][0]["name"].as_str().unwrap().to_string();
run(&mut s, "parameters.change", json!({"name": length, "expression": "10.2 mm"}));
let r = run(&mut s, "inspect.clearance", json!({"clearance": 1}));
assert_eq!(r["pairs_reused"], 0, "{r}");
assert!((f(&r["near"][0]["distance_mm"]) - 0.3).abs() < 1e-6, "{r}");
// Set back, the first shape's result is the right one again.
run(&mut s, "parameters.change", json!({"name": length, "expression": "10 mm"}));
let r = run(&mut s, "inspect.clearance", json!({"clearance": 1}));
assert!((f(&r["near"][0]["distance_mm"]) - 0.5).abs() < 1e-6, "{r}");
}
/// The shared volume is checked against the bodies and their union: two 10 mm cubes sharing a
/// 3 mm corner cube agree at 27 mm³, and a shared part read as three times that (as a mirrored
/// pair once was) does not.
+1 -1
View File
@@ -22,7 +22,7 @@ macro_rules! planned {
mod bom;
mod browser;
mod clearance;
pub(crate) mod clearance;
mod clipboard;
mod compare;
mod component;
+5
View File
@@ -232,6 +232,9 @@ pub struct Session {
world_cache: std::sync::Mutex<Option<WorldCache>>,
occurrence_visibility_cache: std::sync::Mutex<Option<occurrences::VisibilityCache>>,
removed_later_cache: std::sync::Mutex<Option<occurrences::RemovedLaterCache>>,
/// 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>>,
/// Features copied with `timeline.copy` (pasted by `timeline.paste`).
pub clipboard: Vec<solidcraft_doc::Feature>,
/// Sketch geometry copied with `sketch.copy` (pasted by `sketch.paste`).
@@ -370,6 +373,7 @@ impl Session {
world_cache: Default::default(),
occurrence_visibility_cache: Default::default(),
removed_later_cache: Default::default(),
clearance_cache: Default::default(),
clipboard: Vec::new(),
sketch_clipboard: None,
section: None,
@@ -841,6 +845,7 @@ impl Session {
world_cache: std::sync::Mutex::new(self.world_cache.lock().ok().and_then(|cache| cache.clone())),
occurrence_visibility_cache: Default::default(),
removed_later_cache: Default::default(),
clearance_cache: self.clearance_cache.clone(),
clipboard: self.clipboard.clone(),
sketch_clipboard: self.sketch_clipboard.clone(),
section: None,
+62 -2
View File
@@ -50,8 +50,24 @@ pub struct Body {
/// part is tessellated once rather than once per instance. Dropped by anything that changes
/// what the body shows (its geometry is never changed in place).
pub(crate) display_of: Option<std::sync::Arc<(std::sync::Arc<SharedDisplay>, [[f64; 4]; 4])>>,
/// Meshes of this solid kept for reuse, set by [`Body::keeping_meshes`]: a check that
/// intersects one large body with many small ones meshes it at the same tolerance each time.
pub(crate) meshes: Option<std::sync::Arc<MeshMemo>>,
}
/// The meshes made of one solid (see [`Body::keeping_meshes`]), by tolerance, angle and
/// refinement. They answer only for that solid: a copy whose solid was replaced makes its own.
#[derive(Debug)]
pub(crate) struct MeshMemo {
solid: std::sync::Arc<Solid>,
made: std::sync::Mutex<Vec<((u64, u64, bool), std::sync::Arc<Mesh>)>>,
/// The meshes a boolean makes of the solid's shells, by tolerance.
shells: std::sync::Mutex<Vec<(u64, std::sync::Arc<Vec<truck_shapeops::MeshedShell>>)>>,
}
/// Meshes a [`MeshMemo`] keeps at most (the oldest goes first).
const MEMO_MESHES: usize = 4;
/// The display mesh of a body that several placed copies show (see `Body::display_of`): the
/// body, and its mesh once made.
#[derive(Debug)]
@@ -62,7 +78,7 @@ pub(crate) struct SharedDisplay {
impl SharedDisplay {
pub(crate) fn new(original: Body) -> Self {
SharedDisplay { original: Body { display_of: None, ..original }, mesh: std::sync::OnceLock::new() }
SharedDisplay { original: Body { display_of: None, meshes: None, ..original }, mesh: std::sync::OnceLock::new() }
}
}
@@ -593,6 +609,7 @@ impl Body {
regularization_protected: false,
history: None,
display_of: None,
meshes: None,
})
}
@@ -631,6 +648,7 @@ impl Body {
regularization_protected: false,
history: None,
display_of: None,
meshes: None,
})
}
@@ -1073,7 +1091,45 @@ impl Body {
/// [`Body::tessellate_with`] in which no facet turns more than `angle` radians either
/// (infinite: the chord tolerance alone).
fn tessellate_within(&self, tol: f64, angle: f64, refine: bool) -> Result<Mesh> {
crate::profile::timed(crate::profile::Kind::Tessellate, || self.tessellate_within_untimed(tol, angle, refine))
let mesh = || crate::profile::timed(crate::profile::Kind::Tessellate, || self.tessellate_within_untimed(tol, angle, refine));
let memo = self.meshes.as_ref().filter(|m| std::sync::Arc::ptr_eq(&m.solid, &self.solid));
// Held while meshing: threads asking for the same mesh wait for it rather than make it too.
let Some(Ok(mut made)) = memo.map(|m| m.made.lock()) else { return mesh() };
let key = (tol.to_bits(), angle.to_bits(), refine);
if let Some((_, m)) = made.iter().find(|(k, _)| *k == key) {
return Ok(Mesh::clone(m));
}
let m = mesh()?;
if made.len() >= MEMO_MESHES {
made.remove(0);
}
made.push((key, std::sync::Arc::new(m.clone())));
Ok(m)
}
/// A copy of this body that keeps the meshes made of it for reuse, for as long as the copy
/// (or a clone of it) lives: for many operations on one large body at the same tolerance,
/// such as cutting it down to the region of each of many contacts.
pub fn keeping_meshes(&self) -> Body {
let (made, shells) = (std::sync::Mutex::new(Vec::new()), std::sync::Mutex::new(Vec::new()));
Body { meshes: Some(std::sync::Arc::new(MeshMemo { solid: self.solid.clone(), made, shells })), ..self.clone() }
}
/// The meshes of this body's shells a boolean at `tol` makes, when the body keeps its meshes
/// ([`Body::keeping_meshes`]); `None` otherwise.
pub(crate) fn boolean_meshes(&self, tol: f64) -> Option<std::sync::Arc<Vec<truck_shapeops::MeshedShell>>> {
let memo = self.meshes.as_ref().filter(|m| std::sync::Arc::ptr_eq(&m.solid, &self.solid))?;
// Held while meshing, as in `tessellate_within`.
let mut shells = memo.shells.lock().ok()?;
if let Some((_, m)) = shells.iter().find(|(k, _)| *k == tol.to_bits()) {
return Some(m.clone());
}
let made = std::sync::Arc::new(guard("boolean meshes", || Ok(truck_shapeops::meshes(&*self.solid, tol))).ok()?);
if shells.len() >= MEMO_MESHES {
shells.remove(0);
}
shells.push((tol.to_bits(), made.clone()));
Some(made)
}
fn tessellate_within_untimed(&self, tol: f64, angle: f64, refine: bool) -> Result<Mesh> {
@@ -1710,6 +1766,10 @@ impl Body {
#[path = "body_lump_tests.rs"]
mod lump_tests;
#[cfg(test)]
#[path = "mesh_memo_tests.rs"]
mod mesh_memo_tests;
#[cfg(test)]
#[path = "refine_cache_tests.rs"]
mod refine_cache_tests;
+65
View File
@@ -0,0 +1,65 @@
use super::*;
use crate::{BoolOp, boolean, box_solid, cylinder, measure};
/// A plate with a row of holes and a rounded rim along one edge (so that it is no prism the 2D
/// route would take), as a large body many small regions are cut from.
fn plate() -> Body {
let rim = cylinder(Vec3::new(0.0, 0.0, 3.0), Vec3::X, 4.0, 300.0).unwrap();
let mut plate = box_solid(Vec3::ZERO, Vec3::new(300.0, 200.0, 3.0)).unwrap();
plate = boolean(&plate, &rim, BoolOp::Union).unwrap().unwrap();
for k in 0..12 {
let hole = cylinder(Vec3::new(20.0 + 22.0 * k as f64, 100.0, -1.0), Vec3::Z, 2.6, 5.0).unwrap();
plate = boolean(&plate, &hole, BoolOp::Cut).unwrap().unwrap();
}
plate
}
/// Regions cut from a body that keeps its meshes come out as from the body itself, to the bit,
/// and the body is meshed once for all of them.
#[test]
fn regions_cut_from_a_body_keeping_its_meshes_are_unchanged() {
let plate = plate();
let kept = plate.keeping_meshes();
for k in [0.0, 3.0, 7.0] {
let x = 20.0 + 22.0 * k;
let region = box_solid(Vec3::new(x - 8.0, 92.0, -2.0), Vec3::new(x + 8.0, 108.0, 5.0)).unwrap();
let want = boolean(&plate, &region, BoolOp::Intersect).unwrap().unwrap();
let got = boolean(&kept, &region, BoolOp::Intersect).unwrap().unwrap();
let (w, g) = (measure(&want).unwrap(), measure(&got).unwrap());
assert_eq!(got.face_count(), want.face_count(), "region at {x}");
assert_eq!(g.volume.to_bits(), w.volume.to_bits(), "region at {x}");
let cut = boolean(&kept, &region, BoolOp::Cut).unwrap().unwrap();
assert_eq!(
measure(&cut).unwrap().volume.to_bits(),
measure(&boolean(&plate, &region, BoolOp::Cut).unwrap().unwrap()).unwrap().volume.to_bits()
);
}
let memo = kept.meshes.as_ref().unwrap();
assert_eq!(memo.shells.lock().unwrap().len(), 1, "one tolerance, one meshing");
assert!(!memo.made.lock().unwrap().is_empty());
// A mesh from the memo is the mesh made afresh.
let (a, b) = (kept.tessellate_with(0.05, true).unwrap(), plate.tessellate_with(0.05, true).unwrap());
let (a2, _) = (kept.tessellate_with(0.05, true).unwrap(), ());
for m in [&a, &a2] {
assert_eq!(m.triangles, b.triangles);
assert!(
m.positions
.iter()
.zip(&b.positions)
.all(|(p, q)| p.x.to_bits() == q.x.to_bits() && p.y.to_bits() == q.y.to_bits() && p.z.to_bits() == q.z.to_bits())
);
}
}
/// A copy whose solid was replaced does not take meshes of the solid it replaced.
#[test]
fn a_copy_with_another_solid_makes_its_own_meshes() {
let kept = plate().keeping_meshes();
let other = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).unwrap();
let mut swapped = kept.clone();
swapped.solid = other.solid.clone();
let _ = kept.tessellate_with(0.5, true).unwrap();
let m = swapped.tessellate_with(0.5, true).unwrap();
assert_eq!(m.triangles.len(), other.tessellate_with(0.5, true).unwrap().triangles.len());
assert!(swapped.boolean_meshes(0.01).is_none());
}
+2
View File
@@ -113,6 +113,7 @@ pub fn mesh_body(positions: &[Vec3], triangles: &[[u32; 3]]) -> Result<Body> {
face_sources: None,
history: None,
display_of: None,
meshes: None,
regularization_protected: false,
})
}
@@ -210,6 +211,7 @@ impl Body {
face_sources: None,
history: None,
display_of: None,
meshes: None,
regularization_protected: self.regularization_protected,
})
}
+1
View File
@@ -94,6 +94,7 @@ pub fn decode_native_body(bytes: &[u8]) -> Result<Body> {
face_sources: None,
history: None,
display_of: None,
meshes: None,
regularization_protected: false,
};
metadata::apply(&mut body, saved.metadata)?;
+8 -2
View File
@@ -1515,13 +1515,19 @@ pub(crate) fn truck_boolean(a: &Body, b: &Body, op: BoolOp, shift: Option<mt::Ve
sb = mt::builder::translated(&sb, shift);
}
let tool_edges = (op == BoolOp::Cut).then(|| record::edge_origins(&sb, 1));
// A body that keeps its meshes is meshed once for all its booleans at this tolerance.
let meshed = shift.is_none().then(|| a.boolean_meshes(tol)).flatten();
let and = |sa: &Solid, sb: &Solid| match &meshed {
Some(m) => truck_shapeops::and_with_history_meshed(sa, m, sb, tol),
None => truck_shapeops::and_with_history(sa, sb, tol),
};
let res = match op {
BoolOp::Union => truck_shapeops::or_with_history(&sa, &sb, tol),
BoolOp::Cut => {
sb.not();
truck_shapeops::and_with_history(&sa, &sb, tol)
and(&sa, &sb)
}
BoolOp::Intersect => truck_shapeops::and_with_history(&sa, &sb, tol),
BoolOp::Intersect => and(&sa, &sb),
};
let (s, h) = res.ok_or_else(|| KernelError::Failed("no result".into()))?;
let h = h.and_then(|h| recorded::shapeops(&h, &sb, tool_edges.as_ref()));
+1
View File
@@ -513,6 +513,7 @@ fn divided(body: &Body, faces: &[usize], other: &[(mt::Edge, Piece)], fr: &Frame
history: None,
regularization_protected: true,
display_of: None,
meshes: None,
};
Ok(Some(record::rebuilt_body(split, &[&body.solid], &rec)))
}
+2
View File
@@ -645,6 +645,7 @@ pub(crate) fn split_edges_at(body: &Body, points: &[Vec3]) -> Result<Body> {
face_sources: None,
history: None,
display_of: None,
meshes: None,
regularization_protected: true,
};
Ok(crate::record::rebuilt_body(split, &[&body.solid], &rec))
@@ -1180,6 +1181,7 @@ pub(crate) fn split_any(body: &Body, faces: &[usize], tool: &SplitTool) -> Resul
face_sources: None,
history: None,
display_of: None,
meshes: None,
regularization_protected: true,
};
Ok((crate::record::rebuilt_body(split, &[&body.solid], &imp.rec), imp))
+1
View File
@@ -42,6 +42,7 @@ fn surface_of(shell: mt::Shell) -> Body {
face_sources: None,
history: None,
display_of: None,
meshes: None,
regularization_protected: false,
}
}
+4
View File
@@ -41,6 +41,10 @@ Changes:
a moved vertex), across the passes that fold in the operands' extra shells. `and` / `or` are
wrappers that drop the history; the `*_with_history` forms return the same solid with the
history as an `Option` (`None` where a face or edge went unrecorded).
- `transversal/integrate/mod.rs`: `meshes` and `and_with_history_meshed` take the first
operand's shell meshes made beforehand (copied for each use, since the loops stores cut their
edges): a large body cut down to the regions of many small ones is meshed once, which was most
of each operation's time.
## truck-geometry 0.5.0 (Apache-2.0, © RICOS Co. Ltd., https://github.com/ricosjp/truck)
+2 -2
View File
@@ -34,8 +34,8 @@ mod healing;
pub use healing::{RobustSplitClosedEdgesAndFaces, SplitClosedEdgesAndFaces};
mod transversal;
pub use transversal::{
and, and_with_history, or, or_with_history, EdgeOrigin, FaceIndex, FaceOrigin, History, ShapeOpsCurve,
ShapeOpsSurface,
and, and_with_history, and_with_history_meshed, meshes, or, or_with_history, EdgeOrigin, FaceIndex, FaceOrigin,
History, MeshedShell, ShapeOpsCurve, ShapeOpsSurface,
};
// SolidCraft: exercised by kernel regressions in the workspace CI.
#[doc(hidden)]
+36 -8
View File
@@ -50,16 +50,31 @@ impl<C, S: ShapeOpsSurface> ShapeOpsCurve<S> for C where C: ParametricCurve3D
{
}
/// SolidCraft: the meshed form of a shell that a set operation works on (see [`meshes`]).
pub type MeshedShell = Shell<Point3, PolylineCurve<Point3>, Option<PolygonMesh>>;
/// SolidCraft: the meshes of `solid`'s shells at `tol`, as a set operation makes them: an
/// operand used in many operations at one tolerance (a large body cut down to many small
/// regions) is meshed once and handed to [`and_with_history_meshed`], which is most of what
/// such an operation costs. They fit any copy of `solid` with its faces in the same order.
pub fn meshes<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(solid: &Solid<Point3, C, S>, tol: f64) -> Vec<MeshedShell> {
solid.boundaries().iter().map(|shell| shell.robust_triangulation(tol)).collect()
}
fn process_one_pair_of_shells<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(
shell0: &Shell<Point3, C, S>,
meshed0: Option<&MeshedShell>,
shell1: &Shell<Point3, C, S>,
tol: f64,
lineage: &mut Lineage<C, S>,
) -> Option<[Shell<Point3, C, S>; 2]> {
nonpositive_tolerance!(tol);
// SolidCraft: robust meshing (boundaries from earlier operations lie on surfaces only
// within tolerance).
let poly_shell0 = shell0.robust_triangulation(tol);
// within tolerance). A mesh made before is copied: the loops stores cut its edges.
let poly_shell0 = match meshed0 {
Some(m) if m.len() == shell0.len() => m.mapped(|p| *p, |c| c.clone(), |s| s.clone()),
_ => shell0.robust_triangulation(tol),
};
let poly_shell1 = shell1.robust_triangulation(tol);
let loops_store::LoopsStoreQuadruple {
geom_loops_store0: loops_store0,
@@ -113,7 +128,7 @@ pub fn and<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(
solid1: &Solid<Point3, C, S>,
tol: f64,
) -> Option<Solid<Point3, C, S>> {
boolean(solid0, solid1, tol, |[and, _]| and).map(|(solid, _)| solid)
boolean(solid0, None, solid1, tol, |[and, _]| and).map(|(solid, _)| solid)
}
/// OR operation between two solids.
@@ -122,7 +137,7 @@ pub fn or<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(
solid1: &Solid<Point3, C, S>,
tol: f64,
) -> Option<Solid<Point3, C, S>> {
boolean(solid0, solid1, tol, |[_, or]| or).map(|(solid, _)| solid)
boolean(solid0, None, solid1, tol, |[_, or]| or).map(|(solid, _)| solid)
}
/// SolidCraft: AND operation between two solids, with where each face and edge of the result
@@ -134,7 +149,18 @@ pub fn and_with_history<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(
solid1: &Solid<Point3, C, S>,
tol: f64,
) -> Option<(Solid<Point3, C, S>, Option<History>)> {
boolean(solid0, solid1, tol, |[and, _]| and)
boolean(solid0, None, solid1, tol, |[and, _]| and)
}
/// SolidCraft: [`and_with_history`] with `solid0` meshed already ([`meshes`] of it, or of a
/// copy of it, at `tol`): the same result.
pub fn and_with_history_meshed<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(
solid0: &Solid<Point3, C, S>,
meshed0: &[MeshedShell],
solid1: &Solid<Point3, C, S>,
tol: f64,
) -> Option<(Solid<Point3, C, S>, Option<History>)> {
boolean(solid0, Some(meshed0), solid1, tol, |[and, _]| and)
}
/// SolidCraft: OR operation between two solids, with where each face and edge of the result
@@ -146,7 +172,7 @@ pub fn or_with_history<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(
solid1: &Solid<Point3, C, S>,
tol: f64,
) -> Option<(Solid<Point3, C, S>, Option<History>)> {
boolean(solid0, solid1, tol, |[_, or]| or)
boolean(solid0, None, solid1, tol, |[_, or]| or)
}
/// Combines the operands' first shells, then folds in their other shells one at a time
@@ -154,6 +180,7 @@ pub fn or_with_history<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(
/// edge of the result was not recorded; the result stands without it.
fn boolean<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(
solid0: &Solid<Point3, C, S>,
meshed0: Option<&[MeshedShell]>,
solid1: &Solid<Point3, C, S>,
tol: f64,
pick: fn([Shell<Point3, C, S>; 2]) -> Shell<Point3, C, S>,
@@ -163,9 +190,10 @@ fn boolean<C: ShapeOpsCurve<S>, S: ShapeOpsSurface>(
let mut iter1 = solid1.boundaries().iter();
let shell0 = iter0.next()?;
let shell1 = iter1.next()?;
let mut shell = pick(crate::tr!(process_one_pair_of_shells(shell0, shell1, tol, &mut lineage), "first shells"));
let meshed0 = meshed0.filter(|m| m.len() == solid0.boundaries().len()).and_then(|m| m.first());
let mut shell = pick(crate::tr!(process_one_pair_of_shells(shell0, meshed0, shell1, tol, &mut lineage), "first shells"));
for other in iter0.chain(iter1) {
shell = pick(crate::tr!(process_one_pair_of_shells(&shell, other, tol, &mut lineage), "another shell"));
shell = pick(crate::tr!(process_one_pair_of_shells(&shell, None, other, tol, &mut lineage), "another shell"));
}
let solid = crate::tr!(Solid::try_new(components_in_order(&shell)).ok(), "result solid");
let history = lineage.history(&solid);
+1 -1
View File
@@ -9,4 +9,4 @@ pub use intersection_curve::IntersectionCurveWithParameters;
mod loops_store;
mod polyline_construction;
pub use history::{EdgeOrigin, FaceIndex, FaceOrigin, History};
pub use integrate::{and, and_with_history, or, or_with_history, ShapeOpsCurve, ShapeOpsSurface};
pub use integrate::{and, and_with_history, and_with_history_meshed, meshes, or, or_with_history, MeshedShell, ShapeOpsCurve, ShapeOpsSurface};