STEP import: orient each instanced part once (#2814) (#2875)

Thanks @bherbruck.
This commit is contained in:
bherbruck authored and GitHub committed 2026-10-19 04:07:39 -04:00
1 parent 5122b98af3
commit 5997d28de7
5 files changed
+134 -15

No files matched your search

+40 -5
View File
@@ -492,6 +492,12 @@ fn polyline_mid(pts: &[Vec3]) -> (Vec3, f64) {
(pts.first().copied().unwrap_or_default(), len)
}
#[cfg(test)]
thread_local! {
/// Solids [`Body::new`] meshed on this thread to orient them (tests count the work an import does).
pub(crate) static ORIENTED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
/// Deflection the orientation mesh uses: coarse enough for a large solid, fine enough that a
/// small one still tessellates. `unmeshed_faces` counts at the same value, so the count the
/// orientation mesh produced is reused instead of meshing the body again.
@@ -559,13 +565,17 @@ impl Body {
Ok((volume, missing))
})
};
let (mut v, mut missing) = orient(tol)?;
#[cfg(test)]
ORIENTED.with(|n| n.set(n.get() + 1));
// The faces missing from the coarse mesh are the same whichever way the solid turns out
// to face, so the count is kept for `unmeshed_faces` either way.
let (mut v, missing) = orient(tol)?;
// A long thin round part (a through hole's tool: a cylinder whose vertices all lie on
// its seam, so they span its length only) meshed that coarsely can come out with a
// negative volume when it is outward already: check finely before turning it inside out.
let fine = (tol * 0.02).max(1e-4);
if v < 0.0 && fine < tol {
(v, missing) = orient(fine)?;
(v, _) = orient(fine)?;
}
if v < 0.0 {
solid.not();
@@ -574,7 +584,7 @@ impl Body {
solid: std::sync::Arc::new(solid),
size: if span.is_finite() && span > 0.0 { span } else { 0.0 },
volume: Some(std::sync::Arc::new(std::sync::Mutex::new(None))),
coarse_missing: (v >= 0.0).then_some((tol, missing)),
coarse_missing: Some((tol, missing)),
mesh: None,
color: None,
paint: None,
@@ -595,7 +605,15 @@ impl Body {
if solid.boundaries().is_empty() {
return Err(KernelError::Failed("empty result".into()));
}
let mut solid = rephase_revolved(solid);
Body::placed_as_is(rephase_revolved(solid), flip, coarse)
}
/// [`Body::new_placed`] for a solid whose revolved faces were already turned away from
/// their seam (a placement of an oriented body keeps them where they were).
fn placed_as_is(mut solid: Solid, flip: bool, coarse: Option<(f64, usize)>) -> Result<Body> {
if solid.boundaries().is_empty() {
return Err(KernelError::Failed("empty result".into()));
}
let span = span_of(&solid);
if flip {
solid.not();
@@ -616,6 +634,23 @@ impl Body {
})
}
/// This oriented body's solid moved by `m` (an affine placement), as [`Body::new_placed`]
/// makes it: the orientation comes from the matrix, so a part placed many times (assembly
/// instances) is meshed to orient it only once. Topology only; appearance is the caller's.
pub(crate) fn placed(&self, m: &mt::Matrix4) -> Result<Body> {
use mt::SquareMatrix as _;
if *m == mt::Matrix4::from_scale(1.0) {
return Ok(self.clone());
}
let a = [[m.x.x, m.x.y, m.x.z, m.x.w], [m.y.x, m.y.y, m.y.z, m.y.w], [m.z.x, m.z.y, m.z.z, m.z.w], [m.w.x, m.w.y, m.w.z, m.w.w]];
let det = m.determinant();
if !det.is_finite() || det.abs() < 1e-12 {
return Err(KernelError::Invalid("degenerate placement".into()));
}
let rigid = crate::ops::rigid_placement(&a);
Body::placed_as_is(mt::builder::transformed(&*self.solid, *m), det < 0.0, rigid.then_some(self.coarse_missing).flatten())
}
pub(crate) fn inherit_regularization_protection(mut self, input: &Body) -> Self {
self.regularization_protected |= input.regularization_protected;
self
@@ -1254,7 +1289,7 @@ impl Body {
if self.is_mesh() {
return 0;
}
let tol = (self.size() * 1e-2).max(1e-3);
let tol = orientation_tolerance(self.size());
if let Some((cached_tol, missing)) = self.coarse_missing
&& cached_tol == tol
{
+1 -1
View File
@@ -1686,7 +1686,7 @@ fn det3(m: &[[f64; 4]; 4]) -> f64 {
}
/// Whether the linear part is a rigid motion (rotation or reflection: no scale or shear).
fn rigid_placement(m: &[[f64; 4]; 4]) -> bool {
pub(crate) fn rigid_placement(m: &[[f64; 4]; 4]) -> bool {
let r = [Vec3::new(m[0][0], m[0][1], m[0][2]), Vec3::new(m[1][0], m[1][1], m[1][2]), Vec3::new(m[2][0], m[2][1], m[2][2])];
(0..3).all(|i| (r[i].dot(r[i]) - 1.0).abs() < 1e-9) && r[0].dot(r[1]).abs() < 1e-9 && r[0].dot(r[2]).abs() < 1e-9 && r[1].dot(r[2]).abs() < 1e-9
}
+13 -2
View File
@@ -270,6 +270,9 @@ struct Reader {
/// An item placed more than once: its first instance's display, shared by the later ones
/// (with the placement that first instance had), so the part is meshed once.
shown: HashMap<u64, (Arc<crate::body::SharedDisplay>, mt::Matrix4)>,
/// An item placed more than once: its body oriented where the file defines it, so each
/// later instance is only placed (orienting meshes the whole part).
oriented: HashMap<u64, Body>,
used_items: HashSet<u64>,
/// Items already instanced for the product being read.
node_items: HashSet<u64>,
@@ -312,6 +315,7 @@ impl Reader {
solids: HashMap::new(),
once: HashSet::new(),
shown: HashMap::new(),
oriented: HashMap::new(),
used_items: HashSet::new(),
node_items: HashSet::new(),
visits: 0,
@@ -743,7 +747,11 @@ impl Reader {
Err(shared) => (*shared).clone(),
};
sources.push((i, item, closed, file_faces, face_origin));
solids.push(parallel::Job { solid, check_mesh: !self.unmeshed_checked.contains(&item) });
let source = match self.oriented.get(&item) {
Some(body) => parallel::Source::Oriented(body.clone()),
None => parallel::Source::Solid(solid),
};
solids.push(parallel::Job { source, check_mesh: !self.unmeshed_checked.contains(&item) });
}
let Some(batch) = self.batches.get(id) else { return true };
let (m, path, product, instance) = (batch.m, batch.path.clone(), batch.product.clone(), batch.instance.clone());
@@ -751,7 +759,10 @@ impl Reader {
for ((i, item, closed, file_faces, face_origin), body) in sources.into_iter().zip(prepared) {
let Some(e) = ex.get(item) else { continue };
match body {
Ok((body, missing)) => {
Ok((body, missing, oriented)) => {
if !self.once.contains(&item) {
self.oriented.entry(item).or_insert(oriented);
}
let own = e.params().first().and_then(Param::as_str).unwrap_or("").trim().to_string();
let name = if own.is_empty() { product.clone() } else { own };
// Faces the mesher gives up on (or that the budget cut short) are reported.
+22 -6
View File
@@ -2,11 +2,20 @@
use super::{Body, Result, guard, mt};
pub(super) struct Job {
pub solid: mt::Solid,
pub source: Source,
pub check_mesh: bool,
}
type Prepared = Result<(Body, usize)>;
/// What a job places: a solid read from the file (oriented here), or a body an earlier
/// instance of the same item already oriented.
pub(super) enum Source {
Solid(mt::Solid),
Oriented(Body),
}
/// The placed body, its faces the mesher missed, and the body oriented where the file defines
/// it (for later instances of the same item).
type Prepared = Result<(Body, usize, Body)>;
pub(super) fn workers() -> usize {
#[cfg(not(target_arch = "wasm32"))]
@@ -21,10 +30,17 @@ pub(super) fn workers() -> usize {
fn prepare(job: &Job, placement: &mt::Matrix4) -> Prepared {
guard("STEP body preparation", || {
let solid = if *placement == mt::Matrix4::from_scale(1.0) { job.solid.clone() } else { mt::builder::transformed(&job.solid, *placement) };
let body = Body::new(solid)?;
let missing = if job.check_mesh { body.unmeshed_faces() } else { 0 };
Ok((body, missing))
// Orient once where the file defines the solid; each placement then takes its
// orientation from the matrix instead of meshing the whole part again.
let oriented = match &job.source {
Source::Solid(solid) => Body::new(solid.clone())?,
Source::Oriented(body) => body.clone(),
};
let body = oriented.placed(placement)?;
// Counted where the orientation mesh already counted them (a placement meshes the
// same faces).
let missing = if job.check_mesh { oriented.unmeshed_faces() } else { 0 };
Ok((body, missing, oriented))
})
}
+58 -1
View File
@@ -242,7 +242,7 @@ fn parallel_body_preparation_reports_errors_in_place_and_preserves_placement() {
let body = cylinder(Vec3::new(2.0, 2.0, 0.0), Vec3::Z, 2.0, 4.0).unwrap();
let solids = vec![body.solid.as_ref().clone(), mt::Solid::new(Vec::new()), body.solid.as_ref().clone(), body.solid.as_ref().clone()];
let placement = mt::Matrix4::from_translation(mt::Vector3::new(10.0, 20.0, 30.0));
let jobs: Vec<_> = solids.into_iter().map(|solid| parallel::Job { solid, check_mesh: true }).collect();
let jobs: Vec<_> = solids.into_iter().map(|solid| parallel::Job { source: parallel::Source::Solid(solid), check_mesh: true }).collect();
let serial = parallel::bodies(&jobs, &placement, 1);
let threaded = parallel::bodies(&jobs, &placement, 4);
assert_eq!(serial.len(), 4);
@@ -653,6 +653,63 @@ fn hand_written_assembly() {
assert!((root.children[1].transform[3][0] - 100.0).abs() < 1e-9);
}
/// The cube part (in cm) placed `n` times in a millimetre assembly, each instance moved along X
/// and turned about Z.
fn instanced_assembly(n: u64) -> String {
let mut t = String::from(HEAD);
t += "#8=PRODUCT_DEFINITION_CONTEXT('part definition',#9,'design');\n#9=APPLICATION_CONTEXT('');\n";
t += &cube_entities();
t += &context(20, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.CENTI.,.METRE.))");
t += &context(30, "(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))");
t += &product(50, "Block");
t += &product(70, "Assembly");
t += "#60=ADVANCED_BREP_SHAPE_REPRESENTATION('',(#101,#65),#20);\n#61=SHAPE_DEFINITION_REPRESENTATION(#54,#60);\n";
t += "#65=AXIS2_PLACEMENT_3D('',#66,$,$);\n#66=CARTESIAN_POINT('',(0.,0.,0.));\n";
let items: Vec<String> = (0..n).map(|k| format!("#{}", 3000 + k * 10)).collect();
t += &format!("#80=SHAPE_REPRESENTATION('',({}),#30);\n#88=SHAPE_DEFINITION_REPRESENTATION(#74,#80);\n", items.join(","));
for k in 0..n {
let (a, turn) = (3000 + k * 10, k as f64 * 0.7);
t += &format!("#{a}=AXIS2_PLACEMENT_3D('',#{},#{},#{});\n", a + 1, a + 2, a + 3);
t += &format!("#{}=CARTESIAN_POINT('',({}.,0.,0.));\n", a + 1, 50 * k);
t += &format!("#{}=DIRECTION('',(0.,0.,1.));\n#{}=DIRECTION('',({},{},0.));\n", a + 2, a + 3, turn.cos(), turn.sin());
let u = 6000 + k * 10;
t += &format!("#{u}=NEXT_ASSEMBLY_USAGE_OCCURRENCE('{k}','Block:{k}','',#70,#50,$);\n");
t += &format!("#{}=PRODUCT_DEFINITION_SHAPE('','',#{u});\n", u + 1);
t += &format!("#{}=ITEM_DEFINED_TRANSFORMATION('','',#65,#{a});\n", u + 2);
t += &format!(
"#{}=(REPRESENTATION_RELATIONSHIP('','',#60,#80)REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{})SHAPE_REPRESENTATION_RELATIONSHIP());\n",
u + 3,
u + 2
);
t += &format!("#{}=CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{},#{});\n", u + 4, u + 3, u + 1);
}
t += TAIL;
t
}
/// A part placed many times is oriented (meshed whole) once, not once per instance (#2814:
/// an assembly with hundreds of instances spent most of an hour re-meshing the same parts),
/// and every instance still comes out outward-facing at its own place.
#[test]
fn instanced_parts_are_oriented_once() {
let n = 24;
let t = instanced_assembly(n);
crate::body::ORIENTED.with(|c| c.set(0));
let imp = step_import_with_workers(&t, 1).unwrap();
assert_eq!(crate::body::ORIENTED.with(|c| c.get()), 1, "one distinct part");
assert_eq!(imp.bodies.len(), n as usize);
assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
for (k, b) in imp.bodies.iter().enumerate() {
let m = measure(&b.body).unwrap();
assert!(rel(m.volume, 1000.0) < 1e-9, "instance {k}: {}", m.volume);
let centre = (m.bbox.min + m.bbox.max) * 0.5;
let turn = k as f64 * 0.7;
let expected = Vec3::new(50.0 * k as f64 + 5.0 * (turn.cos() - turn.sin()), 5.0 * (turn.sin() + turn.cos()), 5.0);
assert!(centre.dist(expected) < 1e-6, "instance {k}: {centre:?} vs {expected:?}");
}
assert_same_import(&imp, &step_import_with_workers(&t, 8).unwrap());
}
/// A part an assembly places twice is meshed once: the second instance shows the first one's
/// display mesh, placed (the same triangles and faces, at its own place), and keeps its own
/// placed geometry for everything else.