Skip to content

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

Wave 228/509: kernel: how a body's material regions meet, read from the record (and 3 more)

jyvikoc7ead5658d72
diff --git a/crates/geom/src/brep/part.rs b/crates/geom/src/brep/part.rs
index b6c946c3e5..5520b36fe5 100644
--- a/crates/geom/src/brep/part.rs
+++ b/crates/geom/src/brep/part.rs
@@ -3,6 +3,8 @@
//! of its faces, edges and vertices was in the whole. A lump of a body is the part of one of its
//! material regions; material inside one of its voids (an island) is a lump of its own. Records
//! of bodies apart from each other join into one by [`Brep::compound`].
+use serde::{Deserialize, Serialize};
+
use super::{Brep, EdgeUseRef, Invalid, Loop, OrientedFace, Region, Result, Shell, require};
/// A record cut from a larger one, and the source index of each of its items.
@@ -14,6 +16,26 @@ pub struct Part {
pub vertices: Vec<u32>,
}
+/// The most two material regions of a record share, least first: a point, a curve, an area.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Contact {
+ /// A vertex and no edge or face: they touch at a point.
+ Vertex,
+ /// An edge and no face: they touch along a curve.
+ Edge,
+ /// A face: they meet over an area.
+ Face,
+}
+
+/// Two material regions that meet (positions in [`Brep::material_regions`], the lower first),
+/// and the most they share.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct RegionContact {
+ pub regions: [usize; 2],
+ pub contact: Contact,
+}
+
/// First-appearance numbering of a subset of `n` source items.
struct Renumber {
new: Vec<Option<u32>>,
@@ -45,6 +67,79 @@ impl Brep {
self.regions.iter().enumerate().skip(1).filter(|(_, r)| !r.void).map(|(i, _)| i).collect()
}
+ /// How the material regions meet, read from the record: each pair of regions that shares a
+ /// face, an edge or a vertex, with the most they share. `regions` index
+ /// [`Brep::material_regions`] (so a body's lumps); pairs not listed are apart. Regions share
+ /// an edge where it is used by faces of both (more than two faces), a vertex where edges or
+ /// vertex loops of both end at it. Sorted by pair.
+ pub fn region_contacts(&self) -> Result<Vec<RegionContact>> {
+ let material = self.material_regions();
+ // The material regions (positions in `material`) each face, edge and vertex belongs to.
+ let mut on_face: Vec<Vec<usize>> = vec![Vec::new(); self.faces.len()];
+ let mut on_edge: Vec<Vec<usize>> = vec![Vec::new(); self.edges.len()];
+ let mut on_vertex: Vec<Vec<usize>> = vec![Vec::new(); self.vertices.len()];
+ let mark = |list: &mut Vec<Vec<usize>>, i: u32, k: usize| -> Result<()> {
+ let owners = list.get_mut(i as usize).ok_or(Invalid("contact reference"))?;
+ if owners.last() != Some(&k) {
+ owners.push(k);
+ }
+ Ok(())
+ };
+ for (k, &r) in material.iter().enumerate() {
+ let region = self.regions.get(r).ok_or(Invalid("region reference"))?;
+ for &s in &region.shells {
+ match self.shells.get(s as usize).ok_or(Invalid("shell reference"))? {
+ Shell::Faces { faces, wires } => {
+ for f in faces {
+ mark(&mut on_face, f.face, k)?;
+ for l in &self.faces.get(f.face as usize).ok_or(Invalid("face reference"))?.loops {
+ match l {
+ Loop::Edges { edges } => {
+ for u in edges {
+ mark(&mut on_edge, u.edge, k)?;
+ }
+ }
+ Loop::Vertex { vertex } => mark(&mut on_vertex, *vertex, k)?,
+ }
+ }
+ }
+ for &e in wires {
+ mark(&mut on_edge, e, k)?;
+ }
+ }
+ Shell::Wire { edges } => {
+ for &e in edges {
+ mark(&mut on_edge, e, k)?;
+ }
+ }
+ Shell::Vertex { vertex } => mark(&mut on_vertex, *vertex, k)?,
+ }
+ }
+ }
+ for (e, owners) in on_edge.iter().enumerate() {
+ for &v in &self.edges.get(e).ok_or(Invalid("edge reference"))?.vertices {
+ for &k in owners {
+ let list = on_vertex.get_mut(v as usize).ok_or(Invalid("contact reference"))?;
+ if !list.contains(&k) {
+ list.push(k);
+ }
+ }
+ }
+ }
+ let mut pairs = std::collections::BTreeMap::<[usize; 2], Contact>::new();
+ for (owners, contact) in [(&on_face, Contact::Face), (&on_edge, Contact::Edge), (&on_vertex, Contact::Vertex)] {
+ for list in owners.iter().filter(|l| l.len() > 1) {
+ for (i, &a) in list.iter().enumerate() {
+ for &b in list.iter().skip(i + 1) {
+ let most = pairs.entry([a.min(b), a.max(b)]).or_insert(contact);
+ *most = (*most).max(contact);
+ }
+ }
+ }
+ }
+ Ok(pairs.into_iter().map(|(regions, contact)| RegionContact { regions, contact }).collect())
+ }
+
/// The part made of the material regions `regions` (indices into `self.regions`, bounded,
/// not voids): each with its outer shell, its open and wire shells, and a void for each
/// closed inner shell. An island inside one of those voids is in the part, inside it, when
diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs
index 3e383323bb..ae9189f559 100644
--- a/crates/kernel/src/body.rs
+++ b/crates/kernel/src/body.rs
@@ -1209,11 +1209,33 @@ impl Body {
if self.is_mesh() || regions.len() < 2 {
return Ok(vec![self.clone()]);
}
+ self.parts(&(0..regions.len()).map(|k| vec![k]).collect::<Vec<_>>())
+ }
+
+ /// How the body's lumps meet (positions as in [`Body::lumps`]): each pair that shares a face,
+ /// an edge or a vertex, with the most it shares, read from the record. Pairs not listed are
+ /// apart. Empty for a mesh body or a body in one piece.
+ pub fn region_contacts(&self) -> Result<Vec<brep::part::RegionContact>> {
+ if self.is_mesh() {
+ return Ok(Vec::new());
+ }
+ self.record.region_contacts().map_err(|e| KernelError::Invalid(format!("region contacts: {e}")))
+ }
+
+ /// The body cut into parts: one per group of its lumps (positions as in [`Body::lumps`]),
+ /// each the lumps listed with the voids inside them. The parts carry their history over
+ /// `[self]`, as lumps do.
+ pub fn parts(&self, groups: &[Vec<usize>]) -> Result<Vec<Body>> {
+ let regions = self.record.material_regions();
let counts = [(self.face_count(), self.edge_count())];
- regions
- .into_iter()
- .map(|r| {
- let part = self.record.part(&[r]).map_err(|e| KernelError::Failed(format!("lump: {e}")))?;
+ groups
+ .iter()
+ .map(|group| {
+ let picked = group
+ .iter()
+ .map(|&k| regions.get(k).copied().ok_or_else(|| KernelError::Invalid(format!("no lump {k}"))))
+ .collect::<Result<Vec<_>>>()?;
+ let part = self.record.part(&picked).map_err(|e| KernelError::Failed(format!("lump: {e}")))?;
let sources = self
.face_sources
.as_ref()
diff --git a/crates/kernel/src/record.rs b/crates/kernel/src/record.rs
index 774b36429e..1fa9ba3822 100644
--- a/crates/kernel/src/record.rs
+++ b/crates/kernel/src/record.rs
@@ -52,7 +52,8 @@ pub(crate) fn pieces_of(operand: usize, edges: impl IntoIterator<Item = usize>)
/// `faces` (an operand face shared by several result faces is marked Split), and whose edges come
/// from `edges` (by result edge index) where the building code knows them: an operand edge it
/// kept or re-made ([`pieces_of`]). Every other edge separates two faces that met nowhere before,
-/// so it comes from their meeting ([`meeting`]).
+/// so it comes from their meeting ([`meeting`]); an operation with no operands (a body built
+/// from a sketch) makes every face and edge new, so its edges have no origins.
pub(crate) fn of_faces(result: &Brep, operands: usize, mut faces: Vec<FaceProv>, edges: &[Vec<EdgeOrigin>]) -> History {
mark_shared_split(&mut faces);
let edges = edge_faces(result)
@@ -61,6 +62,7 @@ pub(crate) fn of_faces(result: &Brep, operands: usize, mut faces: Vec<FaceProv>,
.map(|(i, between)| {
let origins = match edges.get(i) {
Some(known) if !known.is_empty() => known.clone(),
+ _ if operands == 0 => Vec::new(),
_ => meeting(&between, &faces),
};
EdgeProv { faces: between, origins }
diff --git a/crates/kernel/src/smooth_edges.rs b/crates/kernel/src/smooth_edges.rs
index e0d73ccbcb..cc1e7fd50c 100644
--- a/crates/kernel/src/smooth_edges.rs
+++ b/crates/kernel/src/smooth_edges.rs
@@ -111,6 +111,57 @@ fn ruled(u_knots: &[f64], v_knots: &[f64], controls: &[Vec<[f64; 3]>], orientati
None
}
+/// How a face's outward normal along one of its straight edges is known: the two ruling
+/// boundaries of a ruled patch, or the closed form of a plane, cylinder or cone.
+enum Normals {
+ Ruled([Boundary; 2]),
+ Analytic { surface: Surface, orientation: bool },
+}
+
+/// The face's outward normal along the straight edge from `a` to `b`: a ruled patch's along its
+/// boundary ruling there, an analytic face's from its closed form at both ends (their difference
+/// is the uncertainty, so an edge that is no ruling, where the normal turns, certifies nothing).
+fn normal_along(normals: &Normals, a: Vec3, b: Vec3) -> Option<Boundary> {
+ match normals {
+ Normals::Ruled(boundaries) => on_boundary(boundaries, a, b),
+ Normals::Analytic { surface, orientation } => {
+ let sign = if *orientation { 1. } else { -1. };
+ let at = |p: Vec3| analytic_normal(surface, p).map(|n| n * sign);
+ let (na, nb) = (at(a)?, at(b)?);
+ let error = na.dist(nb) + roundoff(&[a, b]);
+ (na.dot(nb) > 0. && error.is_finite()).then_some(Boundary { a, b, normal: na, error })
+ }
+ }
+}
+
+/// The natural (unit) normal of a plane, cylinder or cone at a point on it: the plane's u × v;
+/// away from the axis for a cylinder; for a cone, away from the axis and back along it by its
+/// half angle (the record's (u, v): radius `radius_at_origin + v tan a` at height v).
+fn analytic_normal(surface: &Surface, p: Vec3) -> Option<Vec3> {
+ let v3 = |x: [f64; 3]| Vec3::new(x[0], x[1], x[2]);
+ let radial = |frame: &solidcraft_geom::brep::Frame| -> Option<(Vec3, Vec3)> {
+ let z = v3(frame.x_axis).cross(v3(frame.y_axis)).normalized()?;
+ let d = p - v3(frame.origin);
+ Some(((d - z * d.dot(z)).normalized()?, z))
+ };
+ match surface {
+ Surface::Plane { u_axis, v_axis, .. } => v3(*u_axis).cross(v3(*v_axis)).normalized(),
+ Surface::Cylinder { frame, .. } => radial(frame).map(|(r, _)| r),
+ Surface::Cone { frame, half_angle, .. } => radial(frame).and_then(|(r, z)| (r * half_angle.cos() - z * half_angle.sin()).normalized()),
+ _ => None,
+ }
+}
+
+/// A straight edge: a line, or a B-spline of degree 1 with two control points (as SMLib gives
+/// an extrusion's rulings).
+fn straight(c: &Curve) -> bool {
+ match c {
+ Curve::Line { .. } => true,
+ Curve::Spline { knots, points } => points.len() == 2 && knots.len() == 4,
+ _ => false,
+ }
+}
+
fn on_boundary(boundaries: &[Boundary; 2], a: Vec3, b: Vec3) -> Option<Boundary> {
boundaries.iter().find_map(|boundary| {
let tolerance = roundoff(&[a, b, boundary.a, boundary.b]);
@@ -161,11 +212,14 @@ fn classify(body: &Body, mesh: &Mesh, mut work: usize) -> (Vec<bool>, Vec<bool>)
boundaries.push(None);
continue;
}
- let ruling = match (&face.surface, orientation) {
- (Surface::Spline { u_knots, v_knots, points }, Some(o)) => ruled(u_knots, v_knots, points, *o, &mut work),
+ let normals = match (&face.surface, orientation) {
+ (Surface::Spline { u_knots, v_knots, points }, Some(o)) => ruled(u_knots, v_knots, points, *o, &mut work).map(Normals::Ruled),
+ (s @ (Surface::Plane { .. } | Surface::Cylinder { .. } | Surface::Cone { .. }), Some(o)) => {
+ Some(Normals::Analytic { surface: s.clone(), orientation: *o })
+ }
_ => None,
};
- boundaries.push(ruling);
+ boundaries.push(normals);
}
let mut out = vec![false; mesh.edges.len()];
let mut sharp = vec![false; mesh.edges.len()];
@@ -192,10 +246,12 @@ fn classify(body: &Body, mesh: &Mesh, mut work: usize) -> (Vec<bool>, Vec<bool>)
let (Some(Some(ba)), Some(Some(bb))) = (boundaries.get(*a as usize), boundaries.get(*b as usize)) else { continue };
// Only exact straight rulings qualify; a bowed/twisted edge with matching endpoints
// must remain visible.
- let Curve::Line { .. } = edge.curve else { continue };
+ if !straight(&edge.curve) {
+ 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 (Some(na), Some(nb)) = (normal_along(ba, p, q), normal_along(bb, p, q)) else { continue };
let uncertainty = na.error + nb.error;
let cross = na.normal.cross(nb.normal).len();
if na.normal.dot(nb.normal) > 0.
@@ -252,7 +308,7 @@ mod tests {
},
)
.unwrap();
- let ring: Vec<Seg2> = circle(4., 8).segs;
+ let ring: Vec<Seg2> = Loop2::circle(Vec2::ZERO, 4.).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!(crate::native::brep_record(&holed).unwrap().edges.iter().any(|e| e.vertices[0] == e.vertices[1]), "a closed edge");
@@ -369,3 +425,4 @@ mod tests {
assert!(ruled_of(straight, true, &mut 0).is_none());
}
}
+
diff --git a/crates/kernel/src/step_in/tests.rs b/crates/kernel/src/step_in/tests.rs
index ed6e0f1b40..e9d3c173cd 100644
--- a/crates/kernel/src/step_in/tests.rs
+++ b/crates/kernel/src/step_in/tests.rs
@@ -465,11 +465,13 @@ fn cube_entities() -> String {
for (i, (x, y, z)) in pts.iter().enumerate() {
s += &format!("#{}=CARTESIAN_POINT('',({x}.,{y}.,{z}.));\n#{}=VERTEX_POINT('',#{});\n", 200 + i, 210 + i, 200 + i);
}
- // 12 edges as lines (direction vector filler; trimmed by vertices).
+ // 12 edges, each on the line through its two vertices (trimmed by them).
let edges = [(0, 1), (1, 2), (2, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)];
- s += "#290=DIRECTION('',(1.,0.,0.));\n#291=VECTOR('',#290,1.);\n";
for (k, (a, b)) in edges.iter().enumerate() {
- s += &format!("#{}=LINE('',#{},#291);\n#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n", 300 + k, 200 + a, 320 + k, 210 + a, 210 + b, 300 + k);
+ let (p, q) = (pts[*a], pts[*b]);
+ let d = (q.0 - p.0, q.1 - p.1, q.2 - p.2);
+ s += &format!("#{}=DIRECTION('',({}.,{}.,{}.));\n#{}=VECTOR('',#{},1.);\n", 600 + 2 * k, d.0, d.1, d.2, 601 + 2 * k, 600 + 2 * k);
+ s += &format!("#{}=LINE('',#{},#{});\n#{}=EDGE_CURVE('',#{},#{},#{},.T.);\n", 300 + k, 200 + a, 601 + 2 * k, 320 + k, 210 + a, 210 + b, 300 + k);
}
// Faces: (edge, forward?) loops counter-clockwise seen from outside, and plane frames.
let faces: [(&[(usize, bool)], (i32, i32, i32), (i32, i32, i32)); 6] = [