Wave 95/509: kernel: measure through SMLib's exact mass properties, checked against the mesh (and 3 more)
4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop. - 714475b84 bherbruck: kernel: measure through SMLib's exact mass properties, checked against the mesh - 07c36cfd0 bherbruck: solidcraft-smlib: Brep::chamfer_sides, and Error::Unsupported for a radius law with a corner - ae1d746ae bherbruck: kernel: chamfers with two setbacks through SMLib - a043e4ae2 bherbruck: kernel: an SMLib blend's corner patch comes from the edges meeting there Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
@@ -91,6 +91,8 @@ pub fn measure_json(b: &solidcraft_doc::ModelBody) -> Value {
|
||||
"vertices": m.merged.vertices,
|
||||
"face_types": m.merged.face_types,
|
||||
"kernel": {"faces": m.faces, "edges": m.edges, "vertices": m.vertices, "shells": m.shells},
|
||||
"measured_by": m.measured_by,
|
||||
"notes": m.notes,
|
||||
})
|
||||
}
|
||||
Err(e) => json!({"name": b.name, "error": e.to_string()}),
|
||||
|
||||
@@ -2343,11 +2343,7 @@ pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, fl
|
||||
return Err(KernelError::Invalid("select 1…1000 edges".into()));
|
||||
}
|
||||
if crate::blend_smlib::selected()? {
|
||||
// SMLib has no solver for unequal setbacks: equal ones are its equal-distance chamfer.
|
||||
return match side {
|
||||
ChamferSide::Distance(d2) if d2 == d1 => crate::blend_smlib::chamfer(body, edges, d1),
|
||||
_ => Err(crate::blend_smlib::unsupported("a chamfer with two different setbacks (two distances, or a distance and an angle)")),
|
||||
};
|
||||
return crate::blend_smlib::chamfer_sides(body, edges, d1, side, flip);
|
||||
}
|
||||
let size = crate::blend_fit::Size::Sides(d1, side, flip);
|
||||
let counts = record::counts(&[body]);
|
||||
|
||||
@@ -57,6 +57,12 @@ pub(crate) fn chamfer(body: &Body, edges: &[Vec3], distance: f64) -> Result<Body
|
||||
imp::blend(body, "chamfer", Kind::Chamfer, edges, &vec![distance; edges.len()])
|
||||
}
|
||||
|
||||
/// A chamfer `d1` back along the face facing up most (down most with `flip`), the other side by
|
||||
/// `side` ([`crate::chamfer_sides`]).
|
||||
pub(crate) fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: crate::ChamferSide, flip: bool) -> Result<Body> {
|
||||
imp::sides(body, edges, d1, side, flip)
|
||||
}
|
||||
|
||||
/// One edge rounded with the radius `spline` (checked by the caller) along it from the end
|
||||
/// nearest `start` ([`crate::fillet_variable_spline`]).
|
||||
pub(crate) fn fillet_variable(body: &Body, edge_at: Vec3, start: Vec3, spline: &RadiusSpline) -> Result<Body> {
|
||||
@@ -76,12 +82,12 @@ mod imp {
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use solidcraft_geom::Vec3;
|
||||
use solidcraft_smlib::{Blend, Brep, CheckLevel};
|
||||
use solidcraft_smlib::{Blend, Brep, ChamferSecond, CheckLevel, Error as SmError};
|
||||
|
||||
use super::Kind;
|
||||
use crate::blend_variable::RadiusSpline;
|
||||
use crate::body::Body;
|
||||
use crate::history::{BodyHistory, EdgeOrigin, History};
|
||||
use crate::history::{BodyHistory, Change, EdgeOrigin, FaceOrigin, History};
|
||||
use crate::native::{body_from_smlib_ordered, smlib_body_ordered};
|
||||
use crate::{KernelError, Result, guard, record};
|
||||
|
||||
@@ -166,6 +172,19 @@ mod imp {
|
||||
run(body, what, &picked.edges, |b| b.blend(kind, &picked.points, sizes, tol))
|
||||
}
|
||||
|
||||
pub(super) fn sides(body: &Body, edges: &[Vec3], d1: f64, side: crate::ChamferSide, flip: bool) -> Result<Body> {
|
||||
body.require_brep("chamfer")?;
|
||||
sizes_ok("chamfer", &vec![d1; edges.len()])?;
|
||||
let picked = resolve(body, edges)?;
|
||||
let second = match side {
|
||||
crate::ChamferSide::Distance(d) => ChamferSecond::Distance(d),
|
||||
crate::ChamferSide::Angle(a) => ChamferSecond::Angle(a),
|
||||
};
|
||||
let up = if flip { [0.0, 0.0, -1.0] } else { [0.0, 0.0, 1.0] };
|
||||
let tol = pick_tolerance(body);
|
||||
run(body, "chamfer", &picked.edges, |b| b.chamfer_sides(&picked.points, tol, d1, second, up))
|
||||
}
|
||||
|
||||
pub(super) fn variable(body: &Body, edge_at: Vec3, start: Vec3, spline: &RadiusSpline) -> Result<Body> {
|
||||
body.require_brep("fillet")?;
|
||||
if !start.is_finite() {
|
||||
@@ -184,7 +203,10 @@ mod imp {
|
||||
guard(what, || {
|
||||
let (sb, order) = smlib_body_ordered(body)?;
|
||||
let tagged = sb.tagged(0).map_err(|e| failed(what, "tag", e))?;
|
||||
let r = op(&tagged).map_err(|e| failed(what, "operation", e))?;
|
||||
let r = op(&tagged).map_err(|e| match e {
|
||||
SmError::Unsupported => super::unsupported(&format!("this {what}, which SMLib cannot build exactly")),
|
||||
e => failed(what, "operation", e),
|
||||
})?;
|
||||
let check = r.check(CheckLevel::All).map_err(|e| failed(what, "check", e))?;
|
||||
if !check.is_valid() {
|
||||
let input_fails = sb.check(CheckLevel::All).is_ok_and(|c| !c.is_valid());
|
||||
@@ -199,7 +221,7 @@ mod imp {
|
||||
let operand = History::identity(body).edges;
|
||||
let replaced = blended(body, edges, &h);
|
||||
solidcraft_smlib::history::blends(&mut h, &operand, &replaced);
|
||||
Some(h)
|
||||
Some(with_corners(h))
|
||||
}
|
||||
Err(e) => {
|
||||
log::debug!(target: "smlib", "{what} history: {e}");
|
||||
@@ -212,6 +234,43 @@ mod imp {
|
||||
})
|
||||
}
|
||||
|
||||
/// `h` with each blend face still without origin (a corner patch where blends meet) made in
|
||||
/// place of all the edges of the blend faces next to it, as truck records a corner, and every
|
||||
/// edge of a face new to the blend recorded as where its faces meet (two chamfers' mitre is
|
||||
/// where the two chamfers meet).
|
||||
fn with_corners(mut h: History) -> History {
|
||||
let mut corners: Vec<(usize, BTreeSet<FaceOrigin>)> = Vec::new();
|
||||
for (i, f) in h.faces.iter().enumerate() {
|
||||
if f.change != Change::Generated || !f.origins.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let around: BTreeSet<FaceOrigin> = h
|
||||
.edges
|
||||
.iter()
|
||||
.filter(|e| e.faces.contains(&i))
|
||||
.flat_map(|e| e.faces.iter().filter(|g| **g != i))
|
||||
.filter_map(|g| h.faces.get(*g))
|
||||
.flat_map(|g| g.origins.iter().copied())
|
||||
.filter(|o| matches!(o, FaceOrigin::Edge { .. }))
|
||||
.collect();
|
||||
if !around.is_empty() {
|
||||
corners.push((i, around));
|
||||
}
|
||||
}
|
||||
for (i, origins) in corners {
|
||||
if let Some(f) = h.faces.get_mut(i) {
|
||||
*f = record::generated(origins.into_iter().collect());
|
||||
}
|
||||
}
|
||||
let faces = h.faces.clone();
|
||||
for e in &mut h.edges {
|
||||
if e.faces.iter().any(|f| faces.get(*f).is_some_and(|f| f.change == Change::Generated)) {
|
||||
e.origins = record::meeting(&e.faces, &faces);
|
||||
}
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// The operand's edges the blend replaced: each picked edge, and every edge no result edge
|
||||
/// comes from (the rest of the tangent chains), in the operand's edge order.
|
||||
fn blended(body: &Body, picked: &[usize], h: &History) -> Vec<usize> {
|
||||
@@ -250,6 +309,10 @@ mod imp {
|
||||
pub(super) fn variable(_: &Body, _: Vec3, _: Vec3, _: &RadiusSpline) -> Result<Body> {
|
||||
Err(not_built())
|
||||
}
|
||||
|
||||
pub(super) fn sides(_: &Body, _: &[Vec3], _: f64, _: crate::ChamferSide, _: bool) -> Result<Body> {
|
||||
Err(not_built())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "smlib"))]
|
||||
@@ -342,6 +405,28 @@ mod tests {
|
||||
assert!((volume(&back) - volume(&r)).abs() < 1e-6 * 8000.0);
|
||||
}
|
||||
|
||||
/// A chamfer 5 back along the top and 2 down the side of the cube's edge y = 20, z = 20 (or
|
||||
/// 2 along the top and 5 down with `flip`): a 5 × 2 / 2 triangle along the 20 mm edge, its
|
||||
/// face coming from the edge.
|
||||
#[test]
|
||||
fn a_chamfer_takes_its_two_setbacks() {
|
||||
let b = cube();
|
||||
let at = Vec3::new(10.0, 20.0, 20.0);
|
||||
for flip in [false, true] {
|
||||
let r = imp::sides(&b, &[at], 5.0, crate::ChamferSide::Distance(2.0), flip).unwrap();
|
||||
assert!(near(volume(&r), 8000.0 - 100.0), "{}", volume(&r));
|
||||
let top = if flip { 18.0 } else { 15.0 };
|
||||
assert!(
|
||||
r.edges(0.01).unwrap().iter().any(|e| e.points.iter().all(|p| (p.y - top).abs() < 1e-6 && (p.z - 20.0).abs() < 1e-6)),
|
||||
"flip {flip}"
|
||||
);
|
||||
let h = r.history().unwrap();
|
||||
assert!(h.faces.iter().any(|f| f.origins == [crate::history::FaceOrigin::Edge { operand: 0, edge: edge_at(&b, at) }]));
|
||||
}
|
||||
let r = imp::sides(&b, &[at], 5.0, crate::ChamferSide::Angle(45f64.to_radians()), false).unwrap();
|
||||
assert!(near(volume(&r), 8000.0 - 12.5 * 20.0), "{}", volume(&r));
|
||||
}
|
||||
|
||||
/// The ladder's 08/006: a 2 mm chamfer of a cylinder's top rim. SMLib's cone and rail lie some
|
||||
/// 2e-5 mm off the faces they bound, more than the kernel's working tolerance; the body keeps
|
||||
/// the tolerances SMLib's record gave them, so its own record (and the saved body's) is valid
|
||||
@@ -366,6 +451,10 @@ mod tests {
|
||||
fn options_smlib_cannot_build_are_refused() {
|
||||
assert!(unsupported("x").to_string().contains("not supported yet"));
|
||||
let b = cube();
|
||||
// A radius law with a corner (4 → 2 → 4, straight on both halves).
|
||||
let corner = RadiusSpline { degree: 1, knots: vec![0.0, 0.0, 0.5, 1.0, 1.0], radii: vec![4.0, 2.0, 4.0] };
|
||||
let e = imp::variable(&b, Vec3::new(10.0, 20.0, 20.0), Vec3::new(0.0, 20.0, 20.0), &corner).unwrap_err();
|
||||
assert!(e.to_string().contains("not supported yet"), "{e}");
|
||||
assert!(imp::blend(&b, "fillet", Kind::Round, &[Vec3::new(10.0, 20.0, 20.0)], &[f64::NAN]).is_err());
|
||||
assert!(imp::blend(&b, "fillet", Kind::Round, &[Vec3::new(f64::NAN, 20.0, 20.0)], &[1.0]).is_err());
|
||||
assert!(imp::blend(&b, "fillet", Kind::Round, &[], &[]).is_err());
|
||||
|
||||
@@ -92,6 +92,7 @@ mod loft_region_tests;
|
||||
mod loopblend;
|
||||
mod matchsurf;
|
||||
mod measure;
|
||||
mod measure_backend;
|
||||
mod mesh_convert;
|
||||
mod meshbody;
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -20,6 +20,13 @@ pub struct BodyMeasure {
|
||||
/// Counts after merging split pieces of the same analytic surface/curve (comparable with
|
||||
/// systems that use periodic faces and edges).
|
||||
pub merged: TopoCounts,
|
||||
/// What volume, area and centre come from: `smlib` (exact, integrated on the surfaces, with
|
||||
/// the kernel setting SMLib) or `mesh` (a fine tessellation).
|
||||
pub measured_by: &'static str,
|
||||
/// Why a measurement is not what the kernel setting asks for (SMLib refused the body, or
|
||||
/// disagreed with the mesh).
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Per-face sums: area, 6 × signed volume and 24 × first moments (divergence theorem), taken
|
||||
@@ -63,12 +70,17 @@ fn min_edge_radius(m: &Mesh) -> Option<f64> {
|
||||
|
||||
/// Volume, area, centre and box of a body, as [`measure`] works them out, without the topology
|
||||
/// counts (and the tessellation they take).
|
||||
#[derive(Clone, Copy, Debug, Serialize)]
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct MassMeasure {
|
||||
pub volume: f64,
|
||||
pub area: f64,
|
||||
pub centroid: Vec3,
|
||||
pub bbox: Aabb3,
|
||||
/// As [`BodyMeasure::measured_by`].
|
||||
pub measured_by: &'static str,
|
||||
/// As [`BodyMeasure::notes`].
|
||||
#[serde(skip_serializing_if = "Vec::is_empty")]
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Measure a body from a fine tessellation (chord tolerance 5e-5 of the body size, finer for
|
||||
@@ -92,9 +104,12 @@ pub fn measure(b: &Body) -> Result<BodyMeasure> {
|
||||
vertices: pos.len(),
|
||||
shells: 1,
|
||||
merged,
|
||||
measured_by: "mesh",
|
||||
notes: Vec::new(),
|
||||
});
|
||||
}
|
||||
let (m, topo) = mass(b, true)?;
|
||||
let (mut m, topo) = mass(b, true)?;
|
||||
let chosen = crate::measure_backend::choose(b, &mut m);
|
||||
let topo = match topo {
|
||||
Some(t) => t,
|
||||
None => b.tessellate((b.size() * 1e-3).max(1e-3))?,
|
||||
@@ -109,6 +124,8 @@ pub fn measure(b: &Body) -> Result<BodyMeasure> {
|
||||
vertices: b.vertex_count(),
|
||||
shells: b.shell_count(),
|
||||
merged: merged_topology(b, &topo)?,
|
||||
measured_by: chosen.by,
|
||||
notes: chosen.notes,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -117,9 +134,13 @@ pub fn measure(b: &Body) -> Result<BodyMeasure> {
|
||||
pub fn measure_mass(b: &Body) -> Result<MassMeasure> {
|
||||
if b.triangle_mesh().is_some() {
|
||||
let m = measure(b)?;
|
||||
return Ok(MassMeasure { volume: m.volume, area: m.area, centroid: m.centroid, bbox: m.bbox });
|
||||
return Ok(MassMeasure { volume: m.volume, area: m.area, centroid: m.centroid, bbox: m.bbox, measured_by: m.measured_by, notes: m.notes });
|
||||
}
|
||||
Ok(mass(b, false)?.0)
|
||||
let mut m = mass(b, false)?.0;
|
||||
let chosen = crate::measure_backend::choose(b, &mut m);
|
||||
m.measured_by = chosen.by;
|
||||
m.notes = chosen.notes;
|
||||
Ok(m)
|
||||
}
|
||||
|
||||
/// The mass properties of a B-rep body from three tessellations: a coarse one (which sets how
|
||||
@@ -189,7 +210,7 @@ fn mass(b: &Body, topology: bool) -> Result<(MassMeasure, Option<Mesh>)> {
|
||||
let mom = o * (4.0 * v6) + mom;
|
||||
let volume = v6 / 6.0;
|
||||
let centroid = if v6.abs() > 1e-12 { mom / (4.0 * v6) } else { fine.bounds().center() };
|
||||
Ok((MassMeasure { volume, area, centroid, bbox: coarse.bounds().union(&fine.bounds()) }, topo))
|
||||
Ok((MassMeasure { volume, area, centroid, bbox: coarse.bounds().union(&fine.bounds()), measured_by: "mesh", notes: Vec::new() }, topo))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Mass properties through SMLib, when [`crate::backend`] is SMLib: the body goes to SMLib as its
|
||||
//! schema 4 record and SMLib integrates its volume, area and centroid on the exact surfaces
|
||||
//! (`solidcraft_smlib::Brep::mass_properties`). The mesh measure is always made too, as an
|
||||
//! independent check: where SMLib disagrees with it beyond the mesh's own accuracy
|
||||
//! (tangency-labs/solidcore#384), or can't take the body, the mesh measure stands and the
|
||||
//! measurement says why in its notes.
|
||||
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
use crate::body::Body;
|
||||
use crate::measure::MassMeasure;
|
||||
|
||||
/// The mesh measure's own accuracy (relative, for volume and area; of the body's size, for the
|
||||
/// centroid): SMLib must agree with it this closely for its numbers to be used.
|
||||
const AGREE: f64 = 1e-3;
|
||||
|
||||
/// Exact volume, area and centroid.
|
||||
pub(crate) struct Exact {
|
||||
pub volume: f64,
|
||||
pub area: f64,
|
||||
pub centroid: Vec3,
|
||||
}
|
||||
|
||||
/// What the measurement comes from, and what it says about it.
|
||||
pub(crate) struct Choice {
|
||||
pub by: &'static str,
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
/// SMLib's mass properties of `b`, or why there are none.
|
||||
#[cfg(feature = "smlib")]
|
||||
fn exact(b: &Body) -> Result<Exact, String> {
|
||||
let sb = crate::native::smlib_body(b).map_err(|e| e.to_string())?;
|
||||
let m = sb.mass_properties(solidcraft_smlib::MEASURE_ACCURACY).map_err(|e| format!("SMLib mass properties: {e}"))?;
|
||||
let [x, y, z] = m.centroid;
|
||||
Ok(Exact { volume: m.volume, area: m.area, centroid: Vec3::new(x, y, z) })
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "smlib"))]
|
||||
fn exact(_: &Body) -> Result<Exact, String> {
|
||||
Err("this build has no SMLib".into())
|
||||
}
|
||||
|
||||
/// Where the kernel setting is SMLib, replaces `mesh`'s volume, area and centroid with SMLib's
|
||||
/// exact ones when they agree with it; otherwise keeps the mesh measure and notes why. The box
|
||||
/// stays the mesh's.
|
||||
pub(crate) fn choose(b: &Body, mesh: &mut MassMeasure) -> Choice {
|
||||
if !matches!(crate::backend(), Ok(crate::Backend::Smlib)) {
|
||||
return Choice { by: "mesh", notes: Vec::new() };
|
||||
}
|
||||
let e = match crate::guard("SMLib mass properties", || Ok(exact(b))) {
|
||||
Ok(Ok(e)) => e,
|
||||
Ok(Err(why)) | Err(crate::KernelError::Internal(why)) => {
|
||||
return Choice { by: "mesh", notes: vec![format!("measured from the mesh: SMLib could not measure this body ({why})")] };
|
||||
}
|
||||
Err(e) => return Choice { by: "mesh", notes: vec![format!("measured from the mesh: SMLib could not measure this body ({e})")] },
|
||||
};
|
||||
match disagreement(&e, mesh, b.size()) {
|
||||
None => {
|
||||
mesh.volume = e.volume;
|
||||
mesh.area = e.area;
|
||||
mesh.centroid = e.centroid;
|
||||
Choice { by: "smlib", notes: Vec::new() }
|
||||
}
|
||||
Some(what) => Choice {
|
||||
by: "mesh",
|
||||
notes: vec![format!("measured from the mesh: SMLib's exact mass properties disagree with it ({what}; tangency-labs/solidcore#384)")],
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Where SMLib's numbers and the mesh's differ by more than the mesh's accuracy, which and by how
|
||||
/// much.
|
||||
fn disagreement(e: &Exact, m: &MassMeasure, size: f64) -> Option<String> {
|
||||
let rel = |a: f64, b: f64| (a - b).abs() / a.abs().max(b.abs()).max(1e-12);
|
||||
let finite = e.volume.is_finite() && e.area.is_finite() && [e.centroid.x, e.centroid.y, e.centroid.z].iter().all(|x| x.is_finite());
|
||||
if !finite {
|
||||
return Some("SMLib's numbers are not finite".into());
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
if rel(e.volume, m.volume) > AGREE {
|
||||
out.push(format!("volume {:.6} against {:.6}", e.volume, m.volume));
|
||||
}
|
||||
if rel(e.area, m.area) > AGREE {
|
||||
out.push(format!("area {:.6} against {:.6}", e.area, m.area));
|
||||
}
|
||||
let d = e.centroid.dist(m.centroid);
|
||||
if d > AGREE * size.max(1e-9) {
|
||||
out.push(format!("centroid {d:.6} mm apart"));
|
||||
}
|
||||
(!out.is_empty()).then(|| out.join(", "))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use solidcraft_geom::Aabb3;
|
||||
|
||||
fn mesh(volume: f64, area: f64, centroid: Vec3) -> MassMeasure {
|
||||
MassMeasure { volume, area, centroid, bbox: Aabb3::EMPTY, measured_by: "mesh", notes: Vec::new() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agreement_is_within_the_mesh_accuracy() {
|
||||
let e = Exact { volume: 1000.0, area: 600.0, centroid: Vec3::new(5.0, 5.0, 5.0) };
|
||||
assert!(disagreement(&e, &mesh(1000.4, 600.2, Vec3::new(5.0, 5.0, 5.001)), 17.3).is_none());
|
||||
let off = disagreement(&e, &mesh(1015.0, 600.0, Vec3::new(5.0, 5.0, 5.0)), 17.3).unwrap();
|
||||
assert!(off.contains("volume 1000.000000 against 1015.000000"), "{off}");
|
||||
let moved = disagreement(&e, &mesh(1000.0, 600.0, Vec3::new(5.0, 5.0, 6.0)), 17.3).unwrap();
|
||||
assert!(moved.contains("centroid"), "{moved}");
|
||||
let nan = Exact { volume: f64::NAN, area: 600.0, centroid: Vec3::ZERO };
|
||||
assert!(disagreement(&nan, &mesh(1000.0, 600.0, Vec3::ZERO), 17.3).is_some());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The operations block of `capi/include/smlib.h` (`smlib_boolean`, `smlib_fillet`,
|
||||
//! `smlib_chamfer`, `smlib_blend`, `smlib_fillet_variable`, `smlib_shell`, `smlib_offset_faces`,
|
||||
//! `smlib_chamfer`, `smlib_blend`, `smlib_fillet_variable`, `smlib_chamfer_sides`, `smlib_shell`, `smlib_offset_faces`,
|
||||
//! `smlib_thicken`, `smlib_brep_solid_count`, `smlib_imprint`; the fork's `capi/src/smlib_ops.cpp`), declared by
|
||||
//! hand. Part of the FFI boundary, like its parent: called only through
|
||||
//! [`crate::ops`].
|
||||
@@ -17,6 +17,7 @@ pub const ERR_PICK_NONE: i32 = -1101;
|
||||
pub const ERR_PICK_AMBIGUOUS: i32 = -1102;
|
||||
pub const ERR_NO_ROOM: i32 = -1103;
|
||||
pub const ERR_NO_CUT: i32 = -1104;
|
||||
pub const ERR_UNSUPPORTED: i32 = -1105;
|
||||
|
||||
pub const BOOLEAN_UNION: i32 = 0;
|
||||
pub const BOOLEAN_SUBTRACT: i32 = 1;
|
||||
@@ -88,6 +89,18 @@ unsafe extern "C" {
|
||||
n_radii: i64,
|
||||
out: *mut *mut RawBrep,
|
||||
) -> i32;
|
||||
fn smlib_chamfer_sides(
|
||||
brep: *const RawBrep,
|
||||
points: *const f64,
|
||||
n_points: i64,
|
||||
tolerance: f64,
|
||||
distance: f64,
|
||||
second: f64,
|
||||
second_is_angle: i32,
|
||||
first: *const f64,
|
||||
out: *mut *mut RawBrep,
|
||||
out_failed_point: *mut i64,
|
||||
) -> i32;
|
||||
fn smlib_shell(
|
||||
brep: *const RawBrep,
|
||||
points: *const f64,
|
||||
@@ -189,6 +202,32 @@ pub fn fillet_variable(
|
||||
})
|
||||
}
|
||||
|
||||
/// `smlib_chamfer_sides`.
|
||||
#[cfg(feature = "native")]
|
||||
pub fn chamfer_sides(
|
||||
b: &Handle,
|
||||
points: &[[f64; 3]],
|
||||
tolerance: f64,
|
||||
distance: f64,
|
||||
second: f64,
|
||||
angle: bool,
|
||||
first: &[f64; 3],
|
||||
) -> Result<Handle, PickError> {
|
||||
let n = i64::try_from(points.len()).map_err(|_| (ERR_ARG, None))?;
|
||||
let flat = points.as_ptr().cast::<f64>();
|
||||
let mut failed = -1i64;
|
||||
new_brep(|out| unsafe { smlib_chamfer_sides(b.raw(), flat, n, tolerance, distance, second, i32::from(angle), first.as_ptr(), out, &mut failed) })
|
||||
.map_err(|s| {
|
||||
let at = (s == ERR_PICK_NONE || s == ERR_PICK_AMBIGUOUS).then(|| usize::try_from(failed).ok()).flatten();
|
||||
(s, at)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub fn chamfer_sides(_: &Handle, _: &[[f64; 3]], _: f64, _: f64, _: f64, _: bool, _: &[f64; 3]) -> Result<Handle, PickError> {
|
||||
Err((NOT_BUILT, None))
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "native"))]
|
||||
pub fn blend(_: i32, _: &Handle, _: &[[f64; 3]], _: &[f64], _: f64) -> Result<Handle, PickError> {
|
||||
Err((NOT_BUILT, None))
|
||||
|
||||
@@ -28,7 +28,7 @@ pub mod sweeps;
|
||||
|
||||
pub use check::{CheckLevel, CheckReport};
|
||||
pub use measure::{MEASURE_ACCURACY, MassProperties};
|
||||
pub use ops::{Blend, BooleanOp, MAX_POINTS};
|
||||
pub use ops::{Blend, BooleanOp, ChamferSecond, MAX_POINTS};
|
||||
|
||||
/// Why an SMLib call failed.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -47,6 +47,8 @@ pub enum Error {
|
||||
Ambiguous { point: usize },
|
||||
/// An inward offset (a shell's wall, faces moved in) leaves no room inside the body.
|
||||
NoRoom,
|
||||
/// SMLib cannot build this exactly yet (a variable radius whose law has a corner).
|
||||
Unsupported,
|
||||
/// A C++ exception (most likely out of memory) was caught at the boundary.
|
||||
Exception,
|
||||
/// The C API is a different version from the one this crate was written against.
|
||||
@@ -68,6 +70,7 @@ impl std::fmt::Display for Error {
|
||||
Error::NoMatch { point } => write!(f, "selection point {} is not near any edge or face", point + 1),
|
||||
Error::Ambiguous { point } => write!(f, "selection point {} is equally near to two edges or faces", point + 1),
|
||||
Error::NoRoom => write!(f, "the offset leaves no room inside the body"),
|
||||
Error::Unsupported => write!(f, "not supported yet: SMLib cannot build this exactly"),
|
||||
Error::Exception => write!(f, "SMLib raised an internal exception"),
|
||||
Error::Version(v) => write!(f, "SMLib C API version {v}, expected {}", ffi::ABI_VERSION),
|
||||
Error::NotBuilt => write!(f, "not supported yet: this build has no SMLib"),
|
||||
@@ -86,6 +89,7 @@ fn error(s: i32) -> Error {
|
||||
ffi::ERR_EMPTY => Error::Empty,
|
||||
ffi::ops::ERR_NOT_SOLID => Error::NotSolid,
|
||||
ffi::ops::ERR_NO_ROOM => Error::NoRoom,
|
||||
ffi::ops::ERR_UNSUPPORTED => Error::Unsupported,
|
||||
ffi::ERR_EXCEPTION => Error::Exception,
|
||||
ffi::NOT_BUILT => Error::NotBuilt,
|
||||
s => Error::Status(s),
|
||||
|
||||
@@ -32,6 +32,15 @@ pub enum Blend {
|
||||
Chamfer,
|
||||
}
|
||||
|
||||
/// The second side of [`Brep::chamfer_sides`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum ChamferSecond {
|
||||
/// The setback along the other face.
|
||||
Distance(f64),
|
||||
/// The angle (radians) the chamfer makes with the first face.
|
||||
Angle(f64),
|
||||
}
|
||||
|
||||
/// Most points one selection may hold (the C API's limit).
|
||||
pub const MAX_POINTS: usize = 4096;
|
||||
|
||||
@@ -122,6 +131,22 @@ impl Brep {
|
||||
})
|
||||
}
|
||||
|
||||
/// The edges nearest to `edges` (each within `tolerance`), with their tangent chains, cut by
|
||||
/// a chamfer `distance` back along the face whose outward normal leans most along `first`,
|
||||
/// and by `second` on the other, with bevelled corners (setbacks measured at each edge's
|
||||
/// midpoint).
|
||||
pub fn chamfer_sides(&self, edges: &[[f64; 3]], tolerance: f64, distance: f64, second: ChamferSecond, first: [f64; 3]) -> Result<Brep> {
|
||||
init()?;
|
||||
if edges.is_empty() || edges.len() > MAX_POINTS {
|
||||
return Err(Error::Argument);
|
||||
}
|
||||
let (value, angle) = match second {
|
||||
ChamferSecond::Distance(d) => (d, false),
|
||||
ChamferSecond::Angle(a) => (a, true),
|
||||
};
|
||||
ffi::ops::chamfer_sides(&self.0, edges, tolerance, distance, value, angle, &first).map(Brep).map_err(pick_error)
|
||||
}
|
||||
|
||||
/// Hollowed to a wall of `thickness` (negative: inside the original surface, positive:
|
||||
/// outside), open at the faces nearest to `open_faces` (each within `tolerance`); none gives
|
||||
/// a closed hollow body. An inward wall that leaves no room inside is [`Error::NoRoom`].
|
||||
|
||||
@@ -274,6 +274,53 @@ fn a_variable_round_follows_its_law() {
|
||||
assert_close(volume(&back), volume(&r), 1e-7, "reversed");
|
||||
assert!(c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &[0.0, 0.5, 1.0, 1.0], &[3.0, 1.0]).is_err());
|
||||
assert!(matches!(c.fillet_variable([90.0, 90.0, 90.0], 0.1, [0.0; 3], 1, &knots, &[3.0, 1.0]), Err(Error::NoMatch { .. })));
|
||||
// A quadratic law with control radii 4, 1, 4: r(t) = 4(1 − t)² + 2t(1 − t) + 4t².
|
||||
let law = |t: f64| 4.0 * (1.0 - t).powi(2) + 2.0 * t * (1.0 - t) + 4.0 * t * t;
|
||||
let n = 4000;
|
||||
let r2 = (0..n).map(|i| law((i as f64 + 0.5) / n as f64).powi(2)).sum::<f64>() / n as f64;
|
||||
let quad = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 2, &[0.0, 0.0, 0.0, 1.0, 1.0, 1.0], &[4.0, 1.0, 4.0]).unwrap();
|
||||
shot(&quad, "variable-quadratic");
|
||||
assert_close(volume(&quad), 8000.0 - q * 20.0 * r2, 1e-5, "quadratic law");
|
||||
// Down to zero at the far end: the round closes to the edge's end point.
|
||||
let zero = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &knots, &[4.0, 0.0]).unwrap();
|
||||
shot(&zero, "variable-to-zero");
|
||||
assert_close(volume(&zero), 8000.0 - q * 20.0 * 16.0 / 3.0, 1e-5, "down to zero");
|
||||
// A law with a corner (4 → 2 → 4, straight on both halves): SMLib's section fit runs across
|
||||
// the corner and misses it, so it is refused; the same points joined smoothly (C1 cubic
|
||||
// pieces, as RadiusSpline::through makes them) are built.
|
||||
let corner = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 1, &[0.0, 0.0, 0.5, 1.0, 1.0], &[4.0, 2.0, 4.0]);
|
||||
assert_eq!(corner.unwrap_err(), Error::Unsupported);
|
||||
let smooth_knots = [0.0, 0.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 1.0, 1.0, 1.0];
|
||||
let smooth = c.fillet_variable([10.0, 20.0, 20.0], 0.1, [0.0, 20.0, 20.0], 3, &smooth_knots, &[4.0, 10.0 / 3.0, 2.0, 2.0, 2.0, 10.0 / 3.0, 4.0]);
|
||||
shot(&smooth.unwrap(), "variable-smooth-4-2-4");
|
||||
}
|
||||
|
||||
/// Unequal chamfers of a cube's top edge y = 20: 5 back along the face facing `first` most and 2
|
||||
/// along the other take away a triangle 5 × 2 / 2 along the 20 mm edge, either way round; 5 at
|
||||
/// 30° to the first face is 5 and 5 tan 30°.
|
||||
#[test]
|
||||
fn chamfers_with_two_setbacks() {
|
||||
let c = cube(20.0);
|
||||
let top = [[10.0, 20.0, 20.0]];
|
||||
let up = c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Distance(2.0), [0.0, 0.0, 1.0]).unwrap();
|
||||
shot(&up, "chamfer-5-2");
|
||||
assert_close(volume(&up), 8000.0 - 5.0 * 20.0, 1e-9, "5 and 2");
|
||||
let flipped = c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Distance(2.0), [0.0, 0.0, -1.0]).unwrap();
|
||||
assert_close(volume(&flipped), volume(&up), 1e-9, "flipped");
|
||||
// Which face took the 5: the removed prism's centroid lies a third of each setback in from
|
||||
// the edge, so the result's centroid moves away from it.
|
||||
let centroid = |b: &Brep| b.mass_properties(ACC).unwrap().centroid;
|
||||
let left = |dy: f64, dz: f64| [10.0, (8000.0 * 10.0 - 100.0 * (20.0 - dy / 3.0)) / 7900.0, (8000.0 * 10.0 - 100.0 * (20.0 - dz / 3.0)) / 7900.0];
|
||||
for (b, want, what) in [(&up, left(5.0, 2.0), "5 along the top"), (&flipped, left(2.0, 5.0), "5 down the side")] {
|
||||
let got = centroid(b);
|
||||
assert!((0..3).all(|i| (got[i] - want[i]).abs() < 1e-6), "{what}: centroid {got:?}, want {want:?}");
|
||||
}
|
||||
let angle = c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Angle(30f64.to_radians()), [0.0, 0.0, 1.0]).unwrap();
|
||||
shot(&angle, "chamfer-5-at-30");
|
||||
assert_close(volume(&angle), 8000.0 - 5.0 * 5.0 * 30f64.to_radians().tan() / 2.0 * 20.0, 1e-9, "5 at 30 degrees");
|
||||
assert_eq!(c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Angle(4.0), [0.0, 0.0, 1.0]).unwrap_err(), Error::Argument);
|
||||
assert_eq!(c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Distance(2.0), [0.0; 3]).unwrap_err(), Error::Argument);
|
||||
assert_eq!(c.chamfer_sides(&top, 0.1, 5.0, ChamferSecond::Distance(-2.0), [0.0, 0.0, 1.0]).unwrap_err(), Error::Argument);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in New Issue
Block a user