Wave 127/509: brep: a record moved rigidly, exactly (and 3 more)

4 commits, squashed; the originals stay reachable from tag archive/merge-main-develop.

- b11433bc5 jyviko: kernel: smooth display edges classified on the schema 4 record
- 3ca3638c5 jyviko: kernel: the curve, loop and vertex blend modules are gone from the crate root
- b0cc84b28 jyviko: brep: a record moved rigidly, exactly
- fa3d914af jyviko: kernel: SMLib measures mass properties at its documented 1e-4

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DtL5M41G8Nua7HvuFPZkmJ
This commit is contained in:
jyviko
2026-10-22 00:49:57 -04:00
parent 6a7581deaa
commit e92a411dd7
6 changed files with 228 additions and 84 deletions
+1
View File
@@ -15,6 +15,7 @@ pub mod eval;
pub mod geometry;
pub mod history;
pub mod pcurve;
pub mod placement;
mod topology;
pub use curve2::Curve2;
+151
View File
@@ -0,0 +1,151 @@
//! A record moved by a rigid motion: a rotation and a translation. Every point, axis and control
//! point moves; every parameter, pcurve, tolerance, orientation and the canonical order stay as
//! they are, because a rigid motion keeps distances, angles and handedness. The moved record is
//! the same B-rep in other coordinates, exactly. Reflections and scalings change parameters or
//! geometry kinds; they are a kernel operation, not this.
use super::{Brep, Curve, Frame, Surface};
/// A rotation (rows of an orthonormal matrix with determinant +1) and a translation:
/// `p ↦ rotation · p + translation`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rigid {
pub rotation: [[f64; 3]; 3],
pub translation: [f64; 3],
}
/// How far the rotation may be from orthonormal (per entry of RᵀR − I) and its determinant from 1.
const ORTHONORMAL: f64 = 1e-9;
impl Rigid {
/// The rigid motion of a column-major affine matrix (columns 0–2 the images of x, y and z,
/// column 3 the translation), or `None` when its linear part scales, shears or reflects.
pub fn of_matrix(m: &[[f64; 4]; 4]) -> Option<Rigid> {
if m.iter().flatten().any(|x| !x.is_finite()) || m[0][3] != 0.0 || m[1][3] != 0.0 || m[2][3] != 0.0 || m[3][3] != 1.0 {
return None;
}
let rotation = [[m[0][0], m[1][0], m[2][0]], [m[0][1], m[1][1], m[2][1]], [m[0][2], m[1][2], m[2][2]]];
let column = |j: usize| [rotation[0][j], rotation[1][j], rotation[2][j]];
let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
for i in 0..3 {
for j in 0..3 {
let want = if i == j { 1.0 } else { 0.0 };
if (dot(column(i), column(j)) - want).abs() > ORTHONORMAL {
return None;
}
}
}
let [a, b, c] = rotation;
let det = a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0]) + a[2] * (b[0] * c[1] - b[1] * c[0]);
((det - 1.0).abs() <= ORTHONORMAL).then_some(Rigid { rotation, translation: [m[3][0], m[3][1], m[3][2]] })
}
fn direction(&self, d: [f64; 3]) -> [f64; 3] {
self.rotation.map(|row| row[0] * d[0] + row[1] * d[1] + row[2] * d[2])
}
fn point(&self, p: [f64; 3]) -> [f64; 3] {
let r = self.direction(p);
[r[0] + self.translation[0], r[1] + self.translation[1], r[2] + self.translation[2]]
}
/// A homogeneous control point `[x w, y w, z w, w]`: the point moves, its weight stays.
fn homogeneous(&self, h: [f64; 4]) -> [f64; 4] {
let r = self.direction([h[0], h[1], h[2]]);
let w = h[3];
[r[0] + w * self.translation[0], r[1] + w * self.translation[1], r[2] + w * self.translation[2], w]
}
/// The column-major affine matrix of this motion.
fn matrix(&self) -> [[f64; 4]; 4] {
let (r, t) = (self.rotation, self.translation);
[[r[0][0], r[1][0], r[2][0], 0.0], [r[0][1], r[1][1], r[2][1], 0.0], [r[0][2], r[1][2], r[2][2], 0.0], [t[0], t[1], t[2], 1.0]]
}
fn frame(&self, f: &Frame) -> Frame {
Frame { origin: self.point(f.origin), x_axis: self.direction(f.x_axis), y_axis: self.direction(f.y_axis) }
}
fn curve(&self, c: &Curve) -> Curve {
match c {
Curve::Line { start, end } => Curve::Line { start: self.point(*start), end: self.point(*end) },
Curve::Circle { frame, radius } => Curve::Circle { frame: self.frame(frame), radius: *radius },
Curve::Ellipse { frame, radii } => Curve::Ellipse { frame: self.frame(frame), radii: *radii },
Curve::Polyline { points } => Curve::Polyline { points: points.iter().map(|p| self.point(*p)).collect() },
Curve::Spline { knots, points } => Curve::Spline { knots: knots.clone(), points: points.iter().map(|p| self.point(*p)).collect() },
Curve::RationalSpline { knots, homogeneous } => {
Curve::RationalSpline { knots: knots.clone(), homogeneous: homogeneous.iter().map(|h| self.homogeneous(*h)).collect() }
}
Curve::SurfaceIntersection { surfaces, leader, tolerance } => Curve::SurfaceIntersection {
surfaces: [Box::new(self.surface(&surfaces[0])), Box::new(self.surface(&surfaces[1]))],
leader: Box::new(self.curve(leader)),
tolerance: *tolerance,
},
}
}
fn surface(&self, s: &Surface) -> Surface {
match s {
Surface::Plane { origin, u_axis, v_axis } => {
Surface::Plane { origin: self.point(*origin), u_axis: self.direction(*u_axis), v_axis: self.direction(*v_axis) }
}
Surface::PlaneThrough { origin, u_point, v_point } => {
Surface::PlaneThrough { origin: self.point(*origin), u_point: self.point(*u_point), v_point: self.point(*v_point) }
}
Surface::Cylinder { frame, radius } => Surface::Cylinder { frame: self.frame(frame), radius: *radius },
Surface::Cone { frame, radius_at_origin, half_angle } => {
Surface::Cone { frame: self.frame(frame), radius_at_origin: *radius_at_origin, half_angle: *half_angle }
}
Surface::Sphere { frame, radius } => Surface::Sphere { frame: self.frame(frame), radius: *radius },
Surface::Torus { frame, major_radius, minor_radius } => {
Surface::Torus { frame: self.frame(frame), major_radius: *major_radius, minor_radius: *minor_radius }
}
Surface::Spline { u_knots, v_knots, points } => Surface::Spline {
u_knots: u_knots.clone(),
v_knots: v_knots.clone(),
points: points.iter().map(|row| row.iter().map(|p| self.point(*p)).collect()).collect(),
},
Surface::RationalSpline { u_knots, v_knots, homogeneous } => Surface::RationalSpline {
u_knots: u_knots.clone(),
v_knots: v_knots.clone(),
homogeneous: homogeneous.iter().map(|row| row.iter().map(|h| self.homogeneous(*h)).collect()).collect(),
},
// The revolution's own placement is composed with the motion; profile and axis stay
// where the producer put them.
Surface::PlacedRevolution { profile, origin, axis, matrix, forward } => Surface::PlacedRevolution {
profile: profile.clone(),
origin: *origin,
axis: *axis,
matrix: compose(&self.matrix(), matrix),
forward: *forward,
},
}
}
}
/// `a · b` of column-major 4×4 matrices.
fn compose(a: &[[f64; 4]; 4], b: &[[f64; 4]; 4]) -> [[f64; 4]; 4] {
let mut out = [[0.0; 4]; 4];
for (col, out_col) in out.iter_mut().enumerate() {
for (row, cell) in out_col.iter_mut().enumerate() {
*cell = (0..4).map(|k| a[k][row] * b[col][k]).sum();
}
}
out
}
impl Brep {
/// This record moved by `motion` (module docs): topology, parameters and pcurves unchanged.
pub fn moved(&self, motion: &Rigid) -> Brep {
let mut out = self.clone();
for f in &mut out.faces {
f.surface = motion.surface(&f.surface);
}
for e in &mut out.edges {
e.curve = motion.curve(&e.curve);
}
for v in &mut out.vertices {
v.point = motion.point(v.point);
}
out
}
}
-3
View File
@@ -18,7 +18,6 @@ mod blend_corner;
mod blend_fit;
mod blend_smlib;
mod blend_variable;
mod blend_vertex;
#[cfg(test)]
mod blend_wrong_way_tests;
mod body;
@@ -38,7 +37,6 @@ mod coaxial_overlap;
mod continuity;
mod coplanar;
mod corner_g2;
mod curveblend;
mod delete_face;
mod distance;
mod emboss;
@@ -87,7 +85,6 @@ mod loft_rails;
mod loft_rails_tests;
#[cfg(test)]
mod loft_region_tests;
mod loopblend;
mod matchsurf;
mod measure;
mod measure_backend;
+8 -1
View File
@@ -14,6 +14,13 @@ use crate::measure::MassMeasure;
/// centroid): SMLib must agree with it this closely for its numbers to be used.
const AGREE: f64 = 1e-3;
/// The relative accuracy SMLib integrates at: the finest of SmApiBrepComputeMassProperties'
/// documented range ("clamped to [1e-4, 1e-1]", SmApiQueries.h), ten times inside the 1e-3 the
/// measure is held to ([`AGREE`], and the regression rig's volume and area tolerance). Its cost is
/// "governed by dRelativeAccuracy": the finest the integrator allows, 1e-8, took tens of seconds
/// on a modelled thread's faces.
const ACCURACY: f64 = 1e-4;
/// Exact volume, area and centroid.
pub(crate) struct Exact {
pub volume: f64,
@@ -31,7 +38,7 @@ pub(crate) struct Choice {
#[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 m = sb.mass_properties(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) })
}
+67 -79
View File
@@ -1,8 +1,8 @@
//! Display-only tangent joins. Unknown geometry retains its existing presentation.
use solidcraft_geom::brep::{Curve, Loop, Shell, Surface};
use solidcraft_geom::{Mesh, Vec3};
use truck_modeling as mt;
use crate::body::{Body, from_p3};
use crate::body::Body;
const MAX_FACES: usize = 50_000;
const MAX_EDGES: usize = 200_000;
@@ -26,19 +26,17 @@ fn roundoff(points: &[Vec3]) -> f64 {
points.iter().flat_map(|p| [p.x.abs(), p.y.abs(), p.z.abs()]).fold(1., f64::max) * f64::EPSILON * 64.
}
/// Only a clamped Bezier profile swept by one common linear translation.
/// Its whole ruling normal is bounded from the linear cross derivative, not sampled.
fn ruled(surface: &mt::Surface, orientation: bool, work: &mut usize) -> Option<[Boundary; 2]> {
let mt::Surface::BSplineSurface(surface) = surface else { return None };
let controls = surface.control_points();
/// Only a clamped Bezier profile swept by one common linear translation (a B-spline surface
/// record: `points[i][j]`, i along u). Its whole ruling normal is bounded from the linear cross
/// derivative, not sampled. `orientation`: the face's outward normal is the natural one.
fn ruled(u_knots: &[f64], v_knots: &[f64], controls: &[Vec<[f64; 3]>], orientation: bool, work: &mut usize) -> Option<[Boundary; 2]> {
let rows = controls.len();
let cols = controls.first()?.len();
if !(2..=33).contains(&rows) || !(2..=33).contains(&cols) || controls.iter().any(|row| row.len() != cols) {
return None;
}
charge(work, rows.checked_mul(cols)?.checked_mul(4)?)?;
let (ku, kv) = surface.knot_vecs();
let clamped = |knots: &mt::KnotVec, count: usize| {
let clamped = |knots: &[f64], count: usize| {
let (Some(first), Some(last)) = (knots.first(), knots.last()) else { return false };
knots.len() == count * 2
&& first.is_finite()
@@ -47,7 +45,7 @@ fn ruled(surface: &mt::Surface, orientation: bool, work: &mut usize) -> Option<[
&& knots.iter().take(count).all(|k| k == first)
&& knots.iter().skip(count).all(|k| k == last)
};
if !clamped(ku, rows) || !clamped(kv, cols) {
if !clamped(u_knots, rows) || !clamped(v_knots, cols) {
return None;
}
for transpose in [false, true] {
@@ -57,7 +55,7 @@ fn ruled(surface: &mt::Surface, orientation: bool, work: &mut usize) -> Option<[
}
let at = |i: usize, j: usize| {
let p = if transpose { controls.get(j)?.get(i)? } else { controls.get(i)?.get(j)? };
let p = from_p3(*p);
let p = Vec3::new(p[0], p[1], p[2]);
p.is_finite().then_some(p)
};
let a = at(0, 0)?;
@@ -126,7 +124,8 @@ pub(crate) fn flags(body: &Body, mesh: &Mesh) -> (Vec<bool>, Vec<bool>) {
}
fn classify(body: &Body, mesh: &Mesh, mut work: usize) -> (Vec<bool>, Vec<bool>) {
if body.solid.face_iter().take(MAX_FACES + 1).count() > MAX_FACES || mesh.edges.len() > MAX_EDGES {
let Ok(rec) = crate::native::brep_record(body) else { return (Vec::new(), Vec::new()) };
if rec.faces.len() > MAX_FACES || mesh.edges.len() > MAX_EDGES {
return (Vec::new(), Vec::new());
}
let mut split_points = 0usize;
@@ -137,46 +136,44 @@ fn classify(body: &Body, mesh: &Mesh, mut work: usize) -> (Vec<bool>, Vec<bool>)
let Some(total) = split_points.checked_add(line.len()) else { return (Vec::new(), Vec::new()) };
split_points = total;
}
let mut boundaries = Vec::new();
for face in body.solid.face_iter() {
// Borrow the geometry through mapping, avoiding a deep clone of an
// unknown/hostile surface before inspecting its control-net bounds.
let wires = face.absolute_boundaries();
if wires.len() > 16 {
// Each face's outward normal is its surface's natural one.
let mut forward = vec![None; rec.faces.len()];
for sh in &rec.shells {
if let Shell::Faces { faces, .. } = sh {
for f in faces {
if let Some(slot) = forward.get_mut(f.face as usize) {
*slot = Some(f.forward);
}
}
}
}
let mut boundaries = Vec::with_capacity(rec.faces.len());
for (face, orientation) in rec.faces.iter().zip(&forward) {
let edge_count = face
.loops
.iter()
.map(|l| match l {
Loop::Edges { edges } => edges.len(),
Loop::Vertex { .. } => 0,
})
.fold(0usize, usize::saturating_add);
if face.loops.len() > 16 || edge_count > 16 || charge(&mut work, edge_count + 1).is_none() {
boundaries.push(None);
continue;
}
let edge_count = wires.iter().fold(0usize, |sum, wire| sum.saturating_add(wire.len()));
if edge_count > 16 || charge(&mut work, edge_count + 1).is_none() {
boundaries.push(None);
continue;
}
// Mapping rebuilds each edge through a check that refuses one starting and ending at
// the same vertex (a loop of one closed edge: a hole a closed curve cut).
if wires.iter().flat_map(|w| w.edge_iter()).any(|e| e.front().id() == e.back().id()) {
boundaries.push(None);
continue;
}
let mapped = face.try_mapped(|_| Some(()), |_| Some(()), |surface| ruled(surface, face.orientation(), &mut work));
boundaries.push(mapped.map(|face| face.surface()));
let ruling = match (&face.surface, orientation) {
(Surface::Spline { u_knots, v_knots, points }, Some(o)) => ruled(u_knots, v_knots, points, *o, &mut work),
_ => None,
};
boundaries.push(ruling);
}
let mut out = vec![false; mesh.edges.len()];
let mut sharp = vec![false; mesh.edges.len()];
// Same first-occurrence order as tessellate().edges; never remove/reindex it.
let mut seen = std::collections::HashSet::new();
let mut index = 0usize;
for edge in body.solid.edge_iter() {
if index >= mesh.edges.len() || seen.len() >= MAX_EDGES {
break;
}
// The mesh's edges are the record's, in its order.
for (current, edge) in rec.edges.iter().enumerate().take(mesh.edges.len().min(MAX_EDGES)) {
if charge(&mut work, 1).is_none() {
break;
}
if !seen.insert(edge.id()) {
continue;
}
let current = index;
index += 1;
let Some([a, b]) = mesh.edge_faces.get(current).map(Vec::as_slice) else { continue };
if a == b {
continue;
@@ -193,17 +190,11 @@ fn classify(body: &Body, mesh: &Mesh, mut work: usize) -> (Vec<bool>, Vec<bool>)
continue;
}
let (Some(Some(ba)), Some(Some(bb))) = (boundaries.get(*a as usize), boundaries.get(*b as usize)) else { continue };
// Curve is inspected by borrowing. Only exact straight rulings qualify;
// a bowed/twisted edge with matching endpoints must remain visible.
let mapped = edge.try_mapped(
|_| Some(()),
|curve| match curve {
mt::Curve::Line(line) => Some((from_p3(line.0), from_p3(line.1))),
_ => None,
},
);
let Some(mapped) = mapped else { continue };
let (p, q) = mapped.curve();
// Only exact straight rulings qualify; a bowed/twisted edge with matching endpoints
// must remain visible.
let Curve::Line { .. } = edge.curve else { continue };
let ends = |v: u32| rec.vertices.get(v as usize).map(|x| Vec3::new(x.point[0], x.point[1], x.point[2]));
let (Some(p), Some(q)) = (ends(edge.vertices[0]), ends(edge.vertices[1])) else { continue };
let (Some(na), Some(nb)) = (on_boundary(ba, p, q), on_boundary(bb, p, q)) else { continue };
let uncertainty = na.error + nb.error;
let cross = na.normal.cross(nb.normal).len();
@@ -264,7 +255,7 @@ mod tests {
let ring: Vec<Seg2> = circle(4., 8).segs;
let tool = crate::SplitTool::Curves { plane: Plane::XY, curves: vec![ring], along: None };
let holed = crate::trim(&sheet, &tool, Vec3::new(9., 9., 0.)).unwrap();
assert!(holed.solid.edge_iter().any(|e| e.front().id() == e.back().id()), "a closed edge");
assert!(crate::native::brep_record(&holed).unwrap().edges.iter().any(|e| e.vertices[0] == e.vertices[1]), "a closed edge");
let mesh = holed.mesh(&crate::MeshTolerance::chord(0.02)).unwrap();
let (smooth, sharp) = classify(&holed, &mesh, WORK);
assert_eq!((smooth.len(), sharp.len()), (mesh.edges.len(), mesh.edges.len()));
@@ -307,15 +298,6 @@ mod tests {
unknown.edge_faces[index].push(999);
assert!(!flags(&body, &unknown).0[index]);
assert!(classify(&body, &mesh, 0).0.iter().all(|f| !*f));
// Matching endpoints alone cannot authorize a bowed current edge.
let changed = Body::new(body.deep_copy()).unwrap();
let edges = Body::unique_edges(&changed.solid);
let edge = &edges[index];
let (a, b) = (edge.front().point(), edge.back().point());
let mid = mt::Point3::new((a.x + b.x) / 2. + 0.1, (a.y + b.y) / 2., (a.z + b.z) / 2.);
edge.set_curve(mt::Curve::BSplineCurve(mt::BSplineCurve::new(mt::KnotVec::bezier_knot(2), vec![a, mid, b])));
let (smooth, sharp) = flags(&changed, &mesh);
assert!(!smooth[index] && !sharp[index]);
}
#[test]
@@ -345,10 +327,14 @@ mod tests {
#[test]
fn actual_authored_split_of_a_curved_ruled_wall_stays_visible() {
let body = ring(4);
let face = body
.solid
.face_iter()
.position(|face| face.try_mapped(|_| Some(()), |_| Some(()), |surface| ruled(surface, face.orientation(), &mut { WORK })).is_some())
let face = crate::native::brep_record(&body)
.unwrap()
.faces
.iter()
.position(|face| match &face.surface {
Surface::Spline { u_knots, v_knots, points } => ruled(u_knots, v_knots, points, true, &mut { WORK }).is_some(),
_ => false,
})
.unwrap();
let tool = crate::SplitTool::Plane(Plane::new(Vec3::new(7., 0., 0.), Vec3::Y, Vec3::Z).unwrap());
let split = crate::split_faces(&body, &[face], &tool).unwrap();
@@ -366,18 +352,20 @@ mod tests {
#[test]
fn singular_twisted_and_reversed_normal_certificates_are_conservative() {
let surface = |points: Vec<Vec<mt::Point3>>| {
mt::Surface::BSplineSurface(mt::BSplineSurface::new((mt::KnotVec::bezier_knot(points.len() - 1), mt::KnotVec::bezier_knot(1)), points))
// A Bezier surface of `points[i][j]`, i along u, one span each way.
let ruled_of = |points: Vec<Vec<[f64; 3]>>, orientation: bool, work: &mut usize| {
let knots = |n: usize| [vec![0.0; n], vec![1.0; n]].concat();
ruled(&knots(points.len()), &knots(points.first().map_or(0, Vec::len)), &points, orientation, work)
};
let p = |x, y, z| mt::Point3::new(x, y, z);
let straight = surface(vec![vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(1., 0., 0.), p(1., 0., 3.)]]);
let forward = ruled(&straight, true, &mut { WORK }).unwrap();
let backward = ruled(&straight, false, &mut { WORK }).unwrap();
let p = |x: f64, y: f64, z: f64| [x, y, z];
let straight = vec![vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(1., 0., 0.), p(1., 0., 3.)]];
let forward = ruled_of(straight.clone(), true, &mut { WORK }).unwrap();
let backward = ruled_of(straight.clone(), false, &mut { WORK }).unwrap();
assert!(forward[0].normal.dot(backward[0].normal) < -0.99);
let twisted = surface(vec![vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(1., 0., 0.), p(1., 1., 3.)]]);
assert!(ruled(&twisted, true, &mut { WORK }).is_none());
let singular = surface(vec![vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(1., 0., 0.), p(1., 0., 3.)]]);
assert!(ruled(&singular, true, &mut { WORK }).is_none());
assert!(ruled(&straight, true, &mut 0).is_none());
let twisted = vec![vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(1., 0., 0.), p(1., 1., 3.)]];
assert!(ruled_of(twisted, true, &mut { WORK }).is_none());
let singular = vec![vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(0., 0., 0.), p(0., 0., 3.)], vec![p(1., 0., 0.), p(1., 0., 3.)]];
assert!(ruled_of(singular, true, &mut { WORK }).is_none());
assert!(ruled_of(straight, true, &mut 0).is_none());
}
}
+1 -1
View File
@@ -1 +1 @@
f6f428bfa2588f9d163ea06dfcf05c3777d9ce57
a6a0c024fd455adc9f98c6076806db7ea7164e2d