Merge ws/innershell: a region of several shells converts, its enclosing shell first (solidcore#1473)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNXLXkZLQ6T7TSi4wswcmk
This commit is contained in:
Brett LawsonandClaude Opus 5.5 committed 2026-10-29 10:29:29 +01:00
commit f628ef64c4
3 files changed
+256 -10

No files matched your search

+71 -9
View File
@@ -13,8 +13,11 @@
//!
//! Where solidcore has no port of an SMLib call the C++ makes, the conversion fails with
//! "not supported yet" naming the call: `SmSurface::ApproximateSurface` (a face whose surface is
//! not a B-spline kind) and `SmShell::IsInnerShellOf` (`PutEnclosingShellsFirst`, a region of
//! several shells).
//! not a B-spline kind).
//!
//! [`from_arrays`] also runs the capi's `PutEnclosingShellsFirst` ([`put_enclosing_shells_first`],
//! an addition to SmuConvert): a bounded region of several shells starts its list at the shell
//! `SmShell::IsInnerShellOf` shows enclosing the others, whatever order the arrays gave.
// The SmBrepData records are filled field by field, as FlatToBrepData fills them after ReSet.
#![allow(clippy::field_reassign_with_default)]
@@ -2501,18 +2504,77 @@ fn brep_from_flat(k: &mut Kernel, f: &In<'_>, s: &Shape) -> Result<Brep> {
healer_enabled: true,
};
make_topology_from_data(k, &mut b, &mut data, &mut env, options).map_err(sc("SmBrep::MakeTopologyFromData"))?;
put_enclosing_shells_first(&b)?;
put_enclosing_shells_first(k, &mut b)?;
Ok(b)
}
/// `PutEnclosingShellsFirst`: SMLib takes a bounded region's first shell as the one enclosing
/// the others. Deciding which does takes `SmShell::IsInnerShellOf`, which solidcore has no port
/// of: a bounded region of several shells is refused.
fn put_enclosing_shells_first(b: &Brep) -> Result<()> {
/// The most `SmShell::IsInnerShellOf` calls one conversion makes; a body that would need more
/// is refused instead of ray casting without end.
const MAX_CONTAINMENT_TESTS: usize = 1 << 16;
/// `PutEnclosingShellsFirst` (capi `smlib_flat.cpp`): SMLib takes the first shell of every region
/// but the infinite one as the shell that encloses the region, the others lying inside it
/// (`SmBrep::AssertValid` test 12). The arrays may list a region's shells in any order, so the one
/// that encloses all the others is put first, decided by `SmShell::IsInnerShellOf`
/// ([`shell::is_inner_shell_of`]). Candidates are the closed face-use shells whose bounding box
/// can be computed, largest box first (a stable sort: equal boxes keep the arrays' order). Only
/// `SM_TRUE` counts as inside: `SM_FALSE` and `SM_UNSURE` rule the candidate out, as the capi's
/// `== TRUE`, and a region where no candidate is shown to enclose the others keeps its order.
/// solidcore errors the C++ has no counterpart for (a call without a port, a dangling id) refuse
/// the conversion, as does a body needing more than [`MAX_CONTAINMENT_TESTS`] containment tests.
fn put_enclosing_shells_first(k: &mut Kernel, b: &mut Brep) -> Result<()> {
use solidcore::query::face::p1::calculate_shell_bounding_box;
let infinite = b.infinite_region();
let mut tests = 0usize;
for r in bl::regions(b, None).map_err(sc("GetRegions"))? {
if Some(r) != infinite && b.region(r).map_err(sc("GetShells"))?.shells.len() > 1 {
return Err(unported("SmShell::IsInnerShellOf (a region of several shells)"));
if Some(r) == infinite {
continue;
}
let shells = b.region(r).map_err(sc("GetShells"))?.shells.clone();
if shells.len() < 2 {
continue;
}
let mut candidates: Vec<(f64, ShellId)> = Vec::new();
for &s in &shells {
let rec = b.shell(s).map_err(sc("GetShells"))?;
if !rec.is_faceuse_shell() || !rec.is_closed(b, s).map_err(sc("SmShell::IsClosed"))? {
continue;
}
match calculate_shell_bounding_box(k, b, s, false) {
Ok(bx) => {
let size = bx.size();
candidates.push((size.x * size.y * size.z, s));
}
Err(e) if e.is_unported() => return Err(sc("SmShell::CalculateBoundingBox")(e)),
// != SM_SUCCESS: not a candidate
Err(_) => {}
}
}
// stable: equal boxes keep the arrays' order
candidates.sort_by(|a, c| c.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));
for &(_, candidate) in &candidates {
let mut encloses = true;
for &s in &shells {
if s == candidate {
continue;
}
tests += 1;
if tests > MAX_CONTAINMENT_TESTS {
return Err(bad("too many shells to order (SmShell::IsInnerShellOf)"));
}
if shell::is_inner_shell_of(k, b, s, Some(candidate)).map_err(sc("SmShell::IsInnerShellOf"))? != shell::SM_TRUE {
encloses = false;
break;
}
}
if encloses {
// SmRegion::SetList(candidate): the circular list now starts at it
let list = &mut b.region_mut(r).map_err(sc("SmRegion::SetList"))?.shells;
if let Some(at) = list.iter().position(|&s| s == candidate) {
list.rotate_left(at);
}
break;
}
}
}
Ok(())
+132 -1
View File
@@ -1,12 +1,15 @@
//! solidcore's primitives through the flat arrays: each exports to a valid record of the right
//! volume, the record comes back to an equal body, and (with SMLib built) the arrays are the C++
//! kernel's own.
//! kernel's own. A body with a sealed void crosses with each region's enclosing shell first,
//! whatever order its arrays list the shells in (the capi's `PutEnclosingShellsFirst`).
use std::f64::consts::PI;
use solidcraft_geom::brep as b;
use super::boolean::boolean;
use super::{Body, from_arrays, make_box, make_cone, make_cylinder, make_sphere, make_torus, to_arrays, volume};
use crate::BooleanOp;
use crate::export::native;
use crate::import::{self, Arrays};
@@ -235,3 +238,131 @@ fn tolerances_cross_the_arrays_per_entity() {
}
}
}
/// A 20 mm box minus a centred 10 mm box: a sealed void, so its solid region has two shells.
fn sealed_void() -> Body {
boolean(&make_box([-10.0; 3], [20.0; 3]).unwrap(), &make_box([-5.0; 3], [10.0; 3]).unwrap(), BooleanOp::Subtract).unwrap().unwrap()
}
/// 20³ − 10³.
const SEALED_VOID_VOLUME: f64 = 8000.0 - 1000.0;
/// Each bounded region's shells, as each shell's reach: the largest |coordinate| of its vertices
/// (10 for the 20 mm box, 5 for the 10 mm one).
fn reaches(rec: &b::Brep) -> Vec<Vec<f64>> {
let reach = |s: u32| {
let Some(b::Shell::Faces { faces, .. }) = rec.shells.get(s as usize) else { panic!("shell {s}") };
let mut r = 0.0f64;
for f in faces {
for l in &rec.faces[f.face as usize].loops {
let b::Loop::Edges { edges } = l else { continue };
for e in edges {
for &v in &rec.edges[e.edge as usize].vertices {
r = rec.vertices[v as usize].point.iter().fold(r, |r, c| r.max(c.abs()));
}
}
}
}
r
};
rec.regions.iter().skip(1).map(|r| r.shells.iter().map(|&s| reach(s)).collect()).collect()
}
/// The sealed void's record: the solid region lists the outer box first, then the void's box;
/// the void region its box alone.
fn outer_first(a: &Arrays, at: &str) {
let mut got = reaches(&record(a));
got.sort_by_key(|x| std::cmp::Reverse(x.len()));
assert_eq!(got, [vec![10.0, 5.0], vec![5.0]], "{at}");
}
/// The arrays with every region's shells listed in reverse: each shell's block (its counts and
/// its face uses) moved, nothing else touched.
fn shells_reversed(a: &Arrays) -> Arrays {
use crate::flat::{FACEUSE_FACE, FACEUSE_ORIENTATION, REGION_SHELL_COUNT, SHELL_FACEUSE_COUNT, SHELL_POINT_TYPE, SHELL_WIRE_EDGE_COUNT};
let mut p = a.clone();
let blocks = [SHELL_FACEUSE_COUNT, SHELL_WIRE_EDGE_COUNT, SHELL_POINT_TYPE, FACEUSE_FACE, FACEUSE_ORIENTATION];
for id in blocks {
p.ints.get_mut(&id).unwrap().clear();
}
let (mut shell, mut fu) = (0usize, 0usize);
for &n in &a.ints[&REGION_SHELL_COUNT] {
let mut region = Vec::new();
for _ in 0..n {
let uses = usize::try_from(a.ints[&SHELL_FACEUSE_COUNT][shell]).unwrap();
region.push((shell, fu..fu + uses));
shell += 1;
fu += uses;
}
for (s, uses) in region.into_iter().rev() {
for id in [SHELL_FACEUSE_COUNT, SHELL_WIRE_EDGE_COUNT, SHELL_POINT_TYPE] {
let v = a.ints[&id][s];
p.ints.get_mut(&id).unwrap().push(v);
}
for id in [FACEUSE_FACE, FACEUSE_ORIENTATION] {
p.ints.get_mut(&id).unwrap().extend_from_slice(&a.ints[&id][uses.clone()]);
}
}
}
assert_ne!(p.ints, a.ints, "nothing to reverse");
p
}
/// solidcore's sealed void exports with its outer shell first, comes back through the arrays
/// with it first, and keeps its volume.
#[test]
fn a_sealed_void_crosses_the_arrays_outer_shell_first() {
let body = sealed_void();
let v = volume(&body, 1e-9).unwrap();
assert!(rel(v, SEALED_VOID_VOLUME) < 1e-9, "{v}");
let a = to_arrays(&body).unwrap();
outer_first(&a, "export");
let back = from_arrays(&import::arrays(&record(&a), true).unwrap()).unwrap();
outer_first(&to_arrays(&back).unwrap(), "round trip");
let v = volume(&back, 1e-9).unwrap();
assert!(rel(v, SEALED_VOID_VOLUME) < 1e-9, "round trip: {v}");
}
/// Arrays listing the solid region's void shell before the box around it import with the box
/// first (SMLib takes a region's first shell as its enclosing one), the volume unchanged.
#[test]
fn shells_listed_inner_first_import_outer_first() {
let a = shells_reversed(&to_arrays(&sealed_void()).unwrap());
let back = from_arrays(&a).unwrap();
outer_first(&to_arrays(&back).unwrap(), "inner first");
let v = volume(&back, 1e-9).unwrap();
assert!(rel(v, SEALED_VOID_VOLUME) < 1e-9, "inner first: {v}");
}
/// The C++ kernel's sealed void: solidcore imports its arrays with the outer shell first, in
/// either shell order, at the C++ kernel's volume, and the C++ kernel reads solidcore's arrays
/// (either order) back as a body that passes its checks at that volume.
#[cfg(feature = "native")]
#[test]
fn a_sealed_void_matches_the_cpp_kernel() {
use crate::{Brep, ffi};
crate::init().unwrap();
let make = |o: f64, s: f64| ffi::make_box(&[o; 3], &[s; 3]).map(Brep::made).unwrap();
let (outer, inner) = (make(-10.0, 20.0), make(-5.0, 10.0));
let cpp = Brep::made(ffi::ops::boolean(outer.cpp().unwrap(), inner.cpp().unwrap(), ffi::ops::BOOLEAN_SUBTRACT).unwrap());
let theirs = ffi::volume(cpp.cpp().unwrap(), 1e-9).unwrap();
assert!(rel(theirs, SEALED_VOID_VOLUME) < 1e-9, "C++ {theirs}");
let arrays = cpp.cpp_arrays().unwrap();
outer_first(&arrays, "C++ export");
for (at, a) in [("C++ arrays", arrays.clone()), ("C++ arrays, inner first", shells_reversed(&arrays))] {
let body = from_arrays(&a).unwrap();
outer_first(&to_arrays(&body).unwrap(), at);
let v = volume(&body, 1e-9).unwrap();
assert!(rel(v, theirs) < 1e-9, "{at}: solidcore {v} vs C++ {theirs}");
}
let ours = to_arrays(&sealed_void()).unwrap();
for (at, a) in [("solidcore arrays", ours.clone()), ("solidcore arrays, inner first", shells_reversed(&ours))] {
let h = crate::flat::Flat::from_arrays(&a).unwrap().import().unwrap();
let v = ffi::volume(h.cpp().unwrap(), 1e-9).unwrap();
assert!(rel(v, theirs) < 1e-9, "{at}: C++ {v} vs {theirs}");
let mut buf = vec![0u8; 1 << 16];
let (len, failures) = ffi::check::check(h.cpp().unwrap(), 2, &mut buf).unwrap();
assert_eq!(failures, 0, "{at}: {}", String::from_utf8_lossy(&buf[..len]));
outer_first(&h.cpp_arrays().unwrap(), &format!("{at}, C++ export"));
}
}
+53
View File
@@ -292,3 +292,56 @@ fn hostile_numbers_are_refused() {
assert!(rel(mass_properties(&b, 1e-30).unwrap().volume, 6000.0) < TOL);
assert!(rel(mass_properties(&b, 10.0).unwrap().volume, 6000.0) < TOL);
}
/// A 20 mm box minus a centred 10 mm box (a sealed void), as solidcore's boolean makes it and as
/// it comes back from arrays listing its solid region's shells inner first.
fn sealed_voids() -> [(&'static str, Body); 2] {
use crate::BooleanOp;
use crate::flat::{FACEUSE_FACE, FACEUSE_ORIENTATION, REGION_SHELL_COUNT, SHELL_FACEUSE_COUNT};
let body = super::boolean::boolean(&make_box([-10.0; 3], [20.0; 3]).unwrap(), &make_box([-5.0; 3], [10.0; 3]).unwrap(), BooleanOp::Subtract)
.unwrap()
.unwrap();
// The bounded solid region of two shells: swap their blocks (the shell counts match, as do
// the face-use counts, six faces each), so only the face uses move.
let mut a = super::to_arrays(&body).unwrap();
let regions = &a.ints[&REGION_SHELL_COUNT];
let first = regions.iter().position(|&n| n == 2).unwrap();
let shell: usize = regions[..first].iter().map(|&n| usize::try_from(n).unwrap()).sum();
let counts = &a.ints[&SHELL_FACEUSE_COUNT];
assert_eq!((counts[shell], counts[shell + 1]), (6, 6));
let fu: usize = counts[..shell].iter().map(|&n| usize::try_from(n).unwrap()).sum();
for id in [FACEUSE_FACE, FACEUSE_ORIENTATION] {
let v = a.ints.get_mut(&id).unwrap();
let (x, y) = v[fu..fu + 12].split_at_mut(6);
x.swap_with_slice(y);
}
let reordered = super::from_arrays(&a).unwrap();
[("solidcore's", body), ("inner first", reordered)]
}
/// The sealed void's mass properties: 8000 − 1000 to 1e-9, centroid at the origin, one solid,
/// in either shell order; with SMLib built, the C++ kernel's own.
#[test]
fn a_sealed_void_measures_its_volume() {
let want = 8000.0 - 1000.0;
// Ixx of a cube of side s about its centre: s⁵ / 6.
let moment = (20.0f64.powi(5) - 10.0f64.powi(5)) / 6.0;
#[cfg(feature = "native")]
let theirs = {
use crate::{Brep, ffi};
crate::init().unwrap();
let make = |o: f64, s: f64| ffi::make_box(&[o; 3], &[s; 3]).map(Brep::made).unwrap();
let (outer, inner) = (make(-10.0, 20.0), make(-5.0, 10.0));
let h = ffi::ops::boolean(outer.cpp().unwrap(), inner.cpp().unwrap(), ffi::ops::BOOLEAN_SUBTRACT).unwrap();
ffi::volume(&h, 1e-9).unwrap()
};
for (at, b) in sealed_voids() {
let m = mass_properties(&b, MEASURE_ACCURACY).unwrap();
assert!(rel(m.volume, want) < TOL, "{at}: volume {}", m.volume);
assert!(m.centroid.iter().all(|c| c.abs() < TOL * 20.0), "{at}: centroid {:?}", m.centroid);
assert!(m.moments.iter().all(|&i| rel(i, moment) < TOL), "{at}: moments {:?} vs {moment}", m.moments);
assert_eq!(solid_count(&b).unwrap(), 1, "{at}");
#[cfg(feature = "native")]
same(m.volume, theirs, theirs, &format!("{at} volume"));
}
}