Skip to content

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

Wave 301/509: STEP import: a part's later instances in a window wait for its first, not end the window (and 3 more)

jyviko6d5a12789e1b
diff --git a/crates/geom/src/tess.rs b/crates/geom/src/tess.rs
index 6276fdbbf4..92598a9376 100644
--- a/crates/geom/src/tess.rs
+++ b/crates/geom/src/tess.rs
@@ -70,6 +70,13 @@ pub struct FacePlan {
pub triangles: Vec<[u32; 3]>,
}
+impl FacePlan {
+ /// Triangle `t` is on this face's own nodes (the evaluated mesh keeps only those).
+ fn has_nodes(&self, t: &[u32; 3]) -> bool {
+ t.iter().all(|&i| (i as usize) < self.uv.len())
+ }
+}
+
/// A body's display tessellation, ready to evaluate.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TessPlan {
@@ -98,9 +105,8 @@ impl TessPlan {
out.positions.push(p);
out.normals.push(if f.flip { -n } else { n });
}
- let n = f.uv.len();
for t in &f.triangles {
- if t.iter().all(|&i| (i as usize) < n) {
+ if f.has_nodes(t) {
let at = |i: u32| u32::try_from(base + i as usize).unwrap_or(u32::MAX);
out.triangles.push([at(t[0]), at(t[1]), at(t[2])]);
out.tri_face.push(f.face);
@@ -112,6 +118,20 @@ impl TessPlan {
out
}
+ /// Which of the body's `faces` faces have triangles in [`TessPlan::evaluate`]'s mesh,
+ /// without evaluating it.
+ pub fn faces_with_triangles(&self, faces: usize) -> Vec<bool> {
+ let mut has = vec![false; faces];
+ for f in &self.faces {
+ if f.triangles.iter().any(|t| f.has_nodes(t))
+ && let Some(h) = has.get_mut(f.face as usize)
+ {
+ *h = true;
+ }
+ }
+ has
+ }
+
/// Vertices across all faces.
pub fn vertex_count(&self) -> usize {
self.faces.iter().map(|f| f.uv.len()).sum()
@@ -772,5 +792,19 @@ mod tests {
assert_eq!(m.triangles, vec![[0, 1, 2]]);
assert_eq!(m.tri_face, vec![3]);
assert!(m.normals.iter().all(|n| close(*n, -Vec3::Z, 1e-12)));
+ // Faces with triangles, counted without evaluating, are the faces the mesh has: not a
+ // face whose only triangle is off its nodes, nor one with none, nor one out of range.
+ let mut plan = plan;
+ let only = |face: u32, triangles: Vec<[u32; 3]>| FacePlan { face, uv: vec![[0.0, 0.0]; 3], triangles, ..Default::default() };
+ plan.faces.extend([only(0, vec![[0, 1, 9]]), only(1, vec![]), only(2, vec![[2, 1, 0]]), only(7, vec![[0, 1, 2]])]);
+ let has = plan.faces_with_triangles(5);
+ let mut evaluated = vec![false; 5];
+ for f in plan.evaluate().tri_face {
+ if let Some(h) = evaluated.get_mut(f as usize) {
+ *h = true;
+ }
+ }
+ assert_eq!(has, evaluated);
+ assert_eq!(has, vec![false, false, true, true, false]);
}
}
diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs
index c428e0dd73..d987204142 100644
--- a/crates/kernel/src/body.rs
+++ b/crates/kernel/src/body.rs
@@ -68,13 +68,13 @@ pub(crate) struct MeshMemo {
/// Meshes a [`MeshMemo`] keeps at most (the oldest goes first).
const MEMO_MESHES: usize = 4;
-/// Meshes kept for reuse, by tolerance (see [`remembered`]).
-type Remembered = std::sync::Mutex<Vec<((u64, u64), std::sync::Arc<Mesh>)>>;
+/// Meshes (or their plans) kept for reuse, by tolerance (see [`remembered`]).
+type Remembered<T = Mesh> = std::sync::Mutex<Vec<((u64, u64), std::sync::Arc<T>)>>;
-/// The mesh at `t` from `kept`, made by `make` and kept (at most [`MEMO_MESHES`]) if it isn't
-/// there. The lock is held while meshing: threads asking for the same mesh wait for it rather
-/// than make it too.
-fn remembered(kept: &Remembered, t: &MeshTolerance, make: impl FnOnce() -> Result<Mesh>) -> Result<std::sync::Arc<Mesh>> {
+/// The mesh (or plan) at `t` from `kept`, made by `make` and kept (at most [`MEMO_MESHES`]) if
+/// it isn't there. The lock is held while meshing: threads asking for the same mesh wait for it
+/// rather than make it too.
+fn remembered<T>(kept: &Remembered<T>, t: &MeshTolerance, make: impl FnOnce() -> Result<T>) -> Result<std::sync::Arc<T>> {
let Ok(mut made) = kept.lock() else { return make().map(std::sync::Arc::new) };
let key = t.key();
if let Some((_, m)) = made.iter().find(|(k, _)| *k == key) {
@@ -89,16 +89,21 @@ fn remembered(kept: &Remembered, t: &MeshTolerance, make: impl FnOnce() -> Resul
}
/// The display mesh of a body that several placed copies show (see `Body::display_of`): the
-/// body, and its mesh once made.
+/// body, and its mesh and plan once made.
#[derive(Debug)]
pub(crate) struct SharedDisplay {
pub(crate) original: Body,
meshes: Remembered,
+ plans: Remembered<solidcraft_geom::tess::TessPlan>,
}
impl SharedDisplay {
pub(crate) fn new(original: Body) -> Self {
- SharedDisplay { original: Body { display_of: None, meshes: None, ..original }, meshes: std::sync::Mutex::new(Vec::new()) }
+ SharedDisplay {
+ original: Body { display_of: None, meshes: None, ..original },
+ meshes: std::sync::Mutex::new(Vec::new()),
+ plans: std::sync::Mutex::new(Vec::new()),
+ }
}
}
@@ -1028,6 +1033,13 @@ impl Body {
if self.is_mesh() {
return Err(KernelError::Invalid("a mesh body has no surfaces to mesh".into()));
}
+ // A placed copy is planned as its original, moved (as `Body::mesh` shows the original's
+ // mesh): the part is planned once for every copy.
+ if let Some((shared, m)) = self.display_of.as_deref()
+ && brep::placement::Rigid::of_matrix(m).is_some()
+ {
+ return Ok(remembered(&shared.plans, t, || shared.original.mesh_plan_untimed(t))?.transformed(m));
+ }
let (tol, turn) = t.rules(self.size());
let (plan, stats) = guard("mesh", || crate::tess::plan(&self.record, tol, turn))?;
// A face filled leniently has no hole on screen, but its pcurves or seams are still wrong:
@@ -1124,13 +1136,14 @@ impl Body {
Ok(crossed)
}
- /// Faces with no triangles in a coarse mesh (the mesher failed or gave up).
+ /// Faces with no triangles in a coarse mesh (the mesher failed or gave up), counted on the
+ /// mesh's plan: the mesh itself is not made.
pub fn unmeshed_faces(&self) -> usize {
if self.is_mesh() {
return 0;
}
- let Ok(m) = self.mesh(&MeshTolerance::chord(coarse_tolerance(self.size()))) else { return self.face_count() };
- self.faces_without_triangles(&m)
+ let Ok(plan) = self.mesh_plan(&MeshTolerance::chord(coarse_tolerance(self.size()))) else { return self.face_count() };
+ plan.faces_with_triangles(self.face_count()).iter().filter(|h| !**h).count()
}
/// Faces of the body with no triangles in its mesh `m` (left out by the mesher).
diff --git a/crates/kernel/src/mesh_memo_tests.rs b/crates/kernel/src/mesh_memo_tests.rs
index 10ea9f3ab3..18a627ffc8 100644
--- a/crates/kernel/src/mesh_memo_tests.rs
+++ b/crates/kernel/src/mesh_memo_tests.rs
@@ -62,3 +62,27 @@ fn a_copy_with_another_solid_makes_its_own_meshes() {
let m = swapped.mesh(&crate::MeshTolerance::chord(0.5)).unwrap();
assert_eq!(m.triangles.len(), other.mesh(&crate::MeshTolerance::chord(0.5)).unwrap().triangles.len());
}
+
+/// A placed copy that shows its original's display is planned as the original, moved: the same
+/// triangles on every face, its points the original's placed (so within the original's chord of
+/// the copy's surfaces), and the original planned once for every copy.
+#[test]
+fn a_placed_copy_is_planned_as_its_original_moved() {
+ let part = plate();
+ let share = DisplayShare::new(part.clone());
+ let (angle, shift) = (0.7f64, Vec3::new(50.0, -20.0, 5.0));
+ let (c, s) = (angle.cos(), angle.sin());
+ let t = [[c, s, 0., 0.], [-s, c, 0., 0.], [0., 0., 1., 0.], [shift.x, shift.y, shift.z, 1.]];
+ let copies: Vec<Body> = (0..2).map(|_| crate::transform(&part, shift, Vec3::ZERO, Vec3::Z, angle).unwrap().with_display_share(&share, t)).collect();
+ let tol = crate::MeshTolerance::display_of(part.size());
+ let original = part.mesh_plan(&tol).unwrap().evaluate();
+ for copy in &copies {
+ let m = copy.mesh_of(&copy.mesh_plan(&tol).unwrap()).unwrap();
+ assert_eq!(m.triangles, original.triangles);
+ assert_eq!(m.tri_face, original.tri_face);
+ let placed = placed_mesh(&original, &t).unwrap();
+ let far = m.positions.iter().zip(&placed.positions).map(|(p, q)| p.dist(*q)).fold(0.0, f64::max);
+ assert!(far < 1e-9, "{far}");
+ }
+ assert_eq!(share.0.plans.lock().unwrap().len(), 1, "planned once for both copies");
+}
diff --git a/crates/kernel/src/step_in/mod.rs b/crates/kernel/src/step_in/mod.rs
index 49443180f5..ba1d39545b 100644
--- a/crates/kernel/src/step_in/mod.rs
+++ b/crates/kernel/src/step_in/mod.rs
@@ -764,27 +764,24 @@ impl Reader {
let first = self.converted;
// The next solids, across instances and parts, converted together: parts still to
// orient are shared out between the workers. A part that comes back within the window
- // waits for the next one, which places the orientation its first instance found.
- let mut last = first + 1;
- if !single {
- let mut fresh: HashSet<u64> = self.plan.get(first).map(|p| p.item).into_iter().collect();
- while let Some(p) = self.plan.get(last)
- && last - first < MAX_WINDOW
- {
- if !self.oriented.contains_key(&p.item) && !fresh.insert(p.item) {
- break;
- }
- last += 1;
- }
- }
+ // is placed once its first instance is read, from the orientation that instance found.
+ let last = if single { first + 1 } else { (first + MAX_WINDOW).min(self.plan.len()) };
self.converted = last;
let ex = self.ex.clone();
+ // Each planned solid of the window, with its job (`None`: a later instance of a part an
+ // earlier job of the window reads, placed after it).
let mut sources = Vec::new();
let mut jobs = Vec::new();
+ let mut reading = HashSet::new();
for i in first..last {
self.made.push(None);
let Some(p) = self.plan.get(i) else { continue };
let (item, units) = (p.item, p.units);
+ let placement = self.batches.get(p.batch).map_or(IDENTITY, |b| b.m);
+ if reading.contains(&item) {
+ sources.push((i, item, placement, None));
+ continue;
+ }
if let Some(again) = self.unreadable.get(&item) {
if let Some(msg) = again.clone() {
let label = self.label(item);
@@ -794,15 +791,42 @@ impl Reader {
}
let source = match self.oriented.get(&item) {
Some(part) => parallel::Source::Oriented(part.clone()),
- None => parallel::Source::Item { item, units },
+ None => {
+ reading.insert(item);
+ parallel::Source::Item { item, units }
+ }
};
- let placement = self.batches.get(p.batch).map_or(IDENTITY, |b| b.m);
- sources.push((i, item));
+ sources.push((i, item, placement, Some(jobs.len())));
jobs.push(parallel::Job { source, placement, check_mesh: !self.unmeshed_checked.contains(&item) });
}
// Reading and orienting new parts is shared out between the workers.
- let prepared = parallel::bodies(&ex, &jobs, self.workers);
- for ((i, item), made) in sources.into_iter().zip(prepared) {
+ let mut prepared: Vec<Option<_>> = parallel::bodies(&ex, &jobs, self.workers).into_iter().map(Some).collect();
+ for (i, item, placement, job) in sources {
+ let made = match job {
+ Some(j) => match prepared.get_mut(j).and_then(Option::take) {
+ Some(made) => made,
+ None => continue,
+ },
+ // A later instance of a part read in this window: as it would be in the next
+ // window, after its first instance.
+ None => {
+ if let Some(again) = self.unreadable.get(&item) {
+ if let Some(msg) = again.clone() {
+ let label = self.label(item);
+ self.warn(format!("{label}: not imported: {msg}"));
+ }
+ continue;
+ }
+ let source = match self.oriented.get(&item) {
+ Some(part) => parallel::Source::Oriented(part.clone()),
+ None => match self.plan.get(i) {
+ Some(p) => parallel::Source::Item { item, units: p.units },
+ None => continue,
+ },
+ };
+ parallel::prepare(&ex, &parallel::Job { source, placement, check_mesh: !self.unmeshed_checked.contains(&item) })
+ }
+ };
let Some(e) = ex.get(item) else { continue };
let Some(batch) = self.plan.get(i).and_then(|p| self.batches.get(p.batch)) else { continue };
let (m, path, product, instance) = (batch.m, batch.path.clone(), batch.product.clone(), batch.instance.clone());
diff --git a/crates/kernel/src/step_in/parallel.rs b/crates/kernel/src/step_in/parallel.rs
index b29a42730d..0761251a1b 100644
--- a/crates/kernel/src/step_in/parallel.rs
+++ b/crates/kernel/src/step_in/parallel.rs
@@ -70,7 +70,7 @@ pub(super) fn workers() -> usize {
}
}
-fn prepare(ex: &Exchange, job: &Job) -> Prepared {
+pub(super) fn prepare(ex: &Exchange, job: &Job) -> Prepared {
let _span = solidcraft_profile::span("import", "step.body");
let (part, read) = match &job.source {
Source::Oriented(part) => (part.clone(), None),
diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs
index 3481fa9ef0..e7d78ea3e4 100644
--- a/crates/kernel/src/step_in/tests.rs
+++ b/crates/kernel/src/step_in/tests.rs
@@ -772,9 +772,9 @@ fn instanced_parts_are_oriented_once() {
}
/// Distinct parts are oriented together, not one occurrence at a time: an assembly placing
-/// two parts in turn converts in a few steps of many solids (the first finds both parts'
-/// orientations side by side on the workers, the next places every other instance), where
-/// converting instance by instance took one step each.
+/// two parts in turn converts in one step (both parts' orientations found side by side on the
+/// workers, every other instance placed after its part's first), where converting instance by
+/// instance took one step each, and stopping the step at a part's second instance two.
#[test]
fn distinct_parts_convert_together_across_instances() {
let n = 24;
@@ -784,7 +784,7 @@ fn distinct_parts_convert_together_across_instances() {
while reading.step() {
steps += 1;
}
- assert_eq!(steps, 2, "both parts in the first step, every other instance in the second");
+ assert_eq!(steps, 1, "both parts and every other instance in one step");
let threaded = reading.finish().unwrap();
assert_eq!(threaded.bodies.len(), n as usize);
assert!(threaded.warnings.is_empty(), "{:?}", threaded.warnings);
diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs
index abdcef1f8b..752a2c691e 100644
--- a/crates/ui-egui/src/viewport.rs
+++ b/crates/ui-egui/src/viewport.rs
@@ -3352,6 +3352,8 @@ pub(crate) fn build_highlight(app: &SolveApp) -> GpuScene {
// selection's outline.
for (body, face) in &app.viewport.refused_ring {
let Some(b) = st.body(body).filter(|_| app.session.body_visible(body)) else { continue };
+ // The face itself tinted (a face whose edges are two small circles still reads as one).
+ face_tris(&mut sc, &shown(b), *face, c4(t.error.gamma_multiply(0.35)), false);
let m = drawn_mesh(app, b);
let hidden = sc.color(c4(t.error.gamma_multiply(0.45)));
for (ei, e) in m.edges.iter().enumerate() {