Skip to content

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

Wave 103/509: kernel: a curved strip straight across and narrower than a side is its boundary nodes alone (and 3 more)

jyviko24df37a65356
diff --git a/crates/kernel/src/native/smlib_import_tests.rs b/crates/kernel/src/native/smlib_import_tests.rs
index 28dc86de2b..c52ea5266a 100644
--- a/crates/kernel/src/native/smlib_import_tests.rs
+++ b/crates/kernel/src/native/smlib_import_tests.rs
@@ -125,3 +125,38 @@ fn a_cone_apex_comes_back_measuring_as_it_went() {
assert!((m1.area - m0.area).abs() < 1e-5 * m0.area, "area {} -> {}", m0.area, m1.area);
assert!((m1.volume - m0.volume).abs() < 1e-5 * m0.volume, "volume {} -> {}", m0.volume, m1.volume);
}
+
+/// A revolved cap's dome comes back from SMLib as a rational spline closed around the axis,
+/// bounded by its rim, its seam both ways and the pole; a ball centred on the dome near the seam
+/// cuts a hole in it. Opened at the pole the outer loop spans v in [-1, 0] while the hole
+/// projects into [0, 1]: the mesh covered the hole as well (+1694 mm³) until the hole is moved
+/// a period to lie inside the outer loop (tangency-labs/solidcore#433).
+#[test]
+fn a_hole_in_a_dome_by_its_seam_measures_as_smlib_cuts_it() {
+ use solidcraft_smlib::sweeps::Curve;
+ let a0 = 6.9f64.atan2(26.0);
+ let line = |a: [f64; 2], b: [f64; 2]| Curve::Line { start: [a[0], 0.0, a[1]], end: [b[0], 0.0, b[1]] };
+ let profile = [
+ line([0., 0.], [7., 0.]),
+ line([7., 0.], [7., 20.]),
+ line([7., 20.], [26., 39.]),
+ Curve::Arc { center: [0., 0., 32.1], axis: [0., -1., 0.], reference: [1., 0., 0.], radius: 26.9, start: a0, end: PI / 2.0 },
+ line([0., 59.], [0., 0.]),
+ ];
+ // Turned about -z, as the engine revolves the sketch (its normal is -y): the dome's v runs
+ // clockwise seen from above, which puts the hole at v near 1.
+ let revolved = solidcraft_smlib::Brep::revolve(&profile, [0.; 3], [0., 0., -1.], std::f64::consts::TAU, true).unwrap();
+ let cap = super::smlib_body(&super::body_from_smlib(&revolved).unwrap()).unwrap();
+ let ball = super::smlib_body(&sphere(v(17.38629136, 4.658642729, 52.090595805), 4.0).unwrap()).unwrap();
+ let cut = cap.tagged(0).unwrap().boolean(&ball.tagged(1).unwrap(), solidcraft_smlib::BooleanOp::Subtract).unwrap().unwrap();
+ // The cap less the lens of two spheres, radii 4 and 26.9 at 26.9 apart.
+ let (big, small) = (26.9f64, 4.0f64);
+ let cap_volume = PI * (49.0 * 20.0 + (26f64.powi(3) - 343.0) / 3.0 + big * big * 20.0 - (big.powi(3) - 6.9f64.powi(3)) / 3.0);
+ let lens = PI * small.powi(2) * (8.0 * big * small - 3.0 * small * small) / (12.0 * big);
+ let exact = cap_volume - lens;
+ let got = cut.volume(1e-7).unwrap();
+ assert!((got - exact).abs() <= 1e-6 * exact, "SMLib volume {got}, exact {exact}");
+ let back = super::body_from_smlib(&cut).unwrap();
+ let m = crate::measure(&back).unwrap();
+ assert!((m.volume - exact).abs() <= 2e-4 * exact, "mesh volume {} ({}), exact {exact}", m.volume, m.measured_by);
+}
diff --git a/crates/kernel/src/tess/cdt.rs b/crates/kernel/src/tess/cdt.rs
index c2d3c387ec..15bf7487f1 100644
--- a/crates/kernel/src/tess/cdt.rs
+++ b/crates/kernel/src/tess/cdt.rs
@@ -332,13 +332,36 @@ fn region(cdt: &Cdt) -> Vec<bool> {
/// out) and at least [`CLEARANCE`] of a side from the boundary in the metric `scale`.
pub(crate) fn lattice(bbox: [(f64, f64); 2], step: [f64; 2], polys: &[&[[f64; 2]]], scale: [f64; 2]) -> Vec<[f64; 2]> {
let mut out = Vec::new();
+ scan(bbox, step, polys, scale, &mut |q| {
+ out.push(q);
+ true
+ });
+ out
+}
+
+/// Whether the face has room for a seed of [`lattice`]: somewhere inside it lies a lattice point
+/// clear of its boundary. A face narrower than the side everywhere (a thin strip) has none.
+/// `true` too when the lattice is more than [`MAX_SEEDS`] points (or the box or step is not
+/// finite), which [`lattice`] does not look through.
+pub(crate) fn has_room(bbox: [(f64, f64); 2], step: [f64; 2], polys: &[&[[f64; 2]]], scale: [f64; 2]) -> bool {
+ let mut found = false;
+ let scanned = scan(bbox, step, polys, scale, &mut |_| {
+ found = true;
+ false
+ });
+ found || !scanned
+}
+
+/// Visit the points of [`lattice`] in turn until `visit` returns `false`. Returns whether the
+/// lattice was looked through (it is not when it is too large or ill-formed).
+fn scan(bbox: [(f64, f64); 2], step: [f64; 2], polys: &[&[[f64; 2]]], scale: [f64; 2], visit: &mut dyn FnMut([f64; 2]) -> bool) -> bool {
if !step.iter().all(|s| s.is_finite() && *s > 0.0) || !bbox.iter().all(|(a, b)| a.is_finite() && b.is_finite() && b > a) {
- return out;
+ return false;
}
let row = step[1] * 3f64.sqrt() * 0.5;
let (rows, cols) = (((bbox[1].1 - bbox[1].0) / row).ceil(), ((bbox[0].1 - bbox[0].0) / step[0]).ceil());
if !(rows * cols <= MAX_SEEDS as f64) {
- return out;
+ return false;
}
let near = Clearance::new(polys, scale, CLEARANCE * step[0] * scale[0]);
let mut xs: Vec<f64> = Vec::new();
@@ -358,12 +381,12 @@ pub(crate) fn lattice(bbox: [(f64, f64); 2], step: [f64; 2], polys: &[&[[f64; 2]
let shift = if j % 2 == 1 { 0.5 * step[0] } else { 0.0 };
for i in 0..=cols as usize {
let u = bbox[0].0 + shift + step[0] * i as f64;
- if u < bbox[0].1 && xs.partition_point(|x| *x < u) % 2 == 1 && !near.within([u, v]) {
- out.push([u, v]);
+ if u < bbox[0].1 && xs.partition_point(|x| *x < u) % 2 == 1 && !near.within([u, v]) && !visit([u, v]) {
+ return true;
}
}
}
- out
+ true
}
/// Most lattice seeds of one face.
diff --git a/crates/kernel/src/tess/cutgrid.rs b/crates/kernel/src/tess/cutgrid.rs
index 5c8f11099b..64db1a54ba 100644
--- a/crates/kernel/src/tess/cutgrid.rs
+++ b/crates/kernel/src/tess/cutgrid.rs
@@ -86,8 +86,20 @@ pub(crate) fn cut_grid(
// Traces on u = c (axis 0) are lines in u; on v = c, lines in v.
let tu: Vec<&Trace> = traces.iter().filter(|t| t.axis == 0).collect();
let tv: Vec<&Trace> = traces.iter().filter(|t| t.axis == 1).collect();
- let (lu, pu) = lines(us, &tu.iter().map(|t| t.at).collect::<Vec<_>>())?;
- let (lv, pv) = lines(vs, &tv.iter().map(|t| t.at).collect::<Vec<_>>())?;
+ // Room for the traces' lines among the grid's: the full lines are thinned (as the face's
+ // grid is) until the cells fit, rather than the face falling through to Delaunay, whose
+ // refinement budget a grid this size is past.
+ let (mut us, mut vs) = (us.to_vec(), vs.to_vec());
+ let cells = |us: &[f64], vs: &[f64]| (us.len() + tu.len()).saturating_sub(1).saturating_mul((vs.len() + tv.len()).saturating_sub(1));
+ for _ in 0..64 {
+ if cells(&us, &vs) <= super::grid::MAX_FACE_GRID || (us.len() <= 2 && vs.len() <= 2) {
+ break;
+ }
+ let cap = us.len().saturating_mul(vs.len()).saturating_mul(9) / 10;
+ super::grid::thin(&mut us, &mut vs, cap);
+ }
+ let (lu, pu) = lines(&us, &tu.iter().map(|t| t.at).collect::<Vec<_>>())?;
+ let (lv, pv) = lines(&vs, &tv.iter().map(|t| t.at).collect::<Vec<_>>())?;
let (nu, nv) = (lu.at.len(), lv.at.len());
let (cu, cv) = (nu - 1, nv - 1);
let cells = cu.checked_mul(cv)?;
diff --git a/crates/kernel/src/tess/grid.rs b/crates/kernel/src/tess/grid.rs
index 9502a1a9bd..1da7da3923 100644
--- a/crates/kernel/src/tess/grid.rs
+++ b/crates/kernel/src/tess/grid.rs
@@ -6,6 +6,37 @@
/// Most grid points of one face.
pub(crate) const MAX_FACE_GRID: usize = 150_000;
+/// Keep at most `cap` grid points (`us` × `vs`) by taking evenly spaced lines in both
+/// directions, the ends kept.
+pub(crate) fn thin(us: &mut Vec<f64>, vs: &mut Vec<f64>, cap: usize) {
+ let total = us.len().saturating_mul(vs.len());
+ if total <= cap {
+ return;
+ }
+ let f = (total as f64 / cap.max(4) as f64).sqrt();
+ // At least the two ends in each direction (never more lines than there are).
+ let keep = |len: usize| ((len as f64 / f).floor() as usize).max(2).min(len);
+ let (mut nu, mut nv) = (keep(us.len()), keep(vs.len()));
+ // Rounding can leave the product a little over: the longer direction gives up the rest.
+ while nu.saturating_mul(nv) > cap.max(4) {
+ if nu >= nv && nu > 2 {
+ nu -= 1;
+ } else if nv > 2 {
+ nv -= 1;
+ } else {
+ break;
+ }
+ }
+ let pick = |d: &mut Vec<f64>, n: usize| {
+ if d.len() > n && n >= 2 {
+ let len = d.len();
+ *d = (0..n).filter_map(|i| d.get(i * (len - 1) / (n - 1)).copied()).collect();
+ }
+ };
+ pick(us, nu);
+ pick(vs, nv);
+}
+
/// The four sides of a parameter box, in counter-clockwise order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Side {
diff --git a/crates/kernel/src/tess/mod.rs b/crates/kernel/src/tess/mod.rs
index 685ac608c3..d5799717e5 100644
--- a/crates/kernel/src/tess/mod.rs
+++ b/crates/kernel/src/tess/mod.rs
@@ -61,8 +61,10 @@ const PARALLEL_FACES: usize = 4;
const PARALLEL_CURVES: usize = 2;
const PARALLEL_EDGES: usize = 256;
-/// Most lines a curved face's grid gets in one direction.
-const MAX_LINES: usize = 1024;
+/// Most lines a curved face's grid gets in one direction: a turn's worth for each of the many
+/// turns a coil's or a thread's wall winds (the grid as a whole stays within
+/// [`grid::MAX_FACE_GRID`]).
+const MAX_LINES: usize = 8192;
/// Most points Ruppert refinement may add to one face, beyond its seeds.
const MAX_REFINE: usize = 20_000;
/// Two boundary nodes this close together on the surface (mm) are one node. Far below any
@@ -603,6 +605,33 @@ fn open_at_pole(s: &EvalSurface, dom: &uv::Domain, l: &mut seam::Loop) {
}
}
+/// Each loop is projected on its own, so along a closed direction a hole can come out a whole
+/// period away from the outer loop: a dome's outer loop opened at its pole spans v in [-1, 0]
+/// while the hole projects into [0, 1], outside it (tangency-labs/solidcore#433). Every other
+/// loop is moved by whole periods to the copy whose middle is nearest the outer loop's (the
+/// loop of largest area); a face that does not wind lies within one period, so that is the
+/// copy inside it.
+fn holes_beside_outer(dom: &uv::Domain, loops: &mut [seam::Loop]) {
+ let Some(outer) = loops.iter().map(|l| area2(&l.uv).abs()).enumerate().max_by(|a, b| a.1.total_cmp(&b.1)).map(|(i, _)| i) else { return };
+ let middle = |l: &seam::Loop, d: usize| {
+ let (lo, hi) = l.uv.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), q| (a.min(q[d]), b.max(q[d])));
+ 0.5 * (lo + hi)
+ };
+ for d in 0..2 {
+ let Some(per) = dom.period[d] else { continue };
+ let Some(centre) = loops.get(outer).map(|l| middle(l, d)) else { continue };
+ for (i, l) in loops.iter_mut().enumerate() {
+ let k = ((middle(l, d) - centre) / per).round();
+ if i == outer || !k.is_finite() || k == 0.0 {
+ continue;
+ }
+ for q in &mut l.uv {
+ q[d] -= k * per;
+ }
+ }
+ }
+}
+
/// One face: boundary loops in 3D (shared edge nodes) to parameters and triangles.
/// `size`: the face's target side length (mm) and the surface's mean speed along u and v.
fn plan_face(
@@ -681,6 +710,7 @@ fn plan_face(
for l in projected.iter_mut() {
open_pole_to_pole(s, &dom, l);
}
+ holes_beside_outer(&dom, &mut projected);
}
// Split poles.
let mut fixed: Vec<Vec3> = Vec::new();
@@ -727,9 +757,10 @@ fn plan_face(
// Constrained Delaunay in (u, v) scaled to millimetres: equilateral seeds of side `h`,
// refined where triangles leave the surface, are too long or bend too much, then shaped by
// Ruppert refinement.
+ let polys: Vec<&[[f64; 2]]> = ranges.iter().filter_map(|r| uvs.get(r.clone())).collect();
+ let step = [h / speed[0], h / speed[1]];
let delaunay = || {
- let polys: Vec<&[[f64; 2]]> = ranges.iter().filter_map(|r| uvs.get(r.clone())).collect();
- let seeds = cdt::lattice(bbox, [h / speed[0], h / speed[1]], &polys, speed);
+ let seeds = cdt::lattice(bbox, step, &polys, speed);
let eval = |u: f64, v: f64| s.derivs(u, v).map(|(p, su, sv)| (p, su.cross(sv).normalized()));
let sag = cdt::Sag { eval: &eval, tol, h, turn: rules.turn, scale: speed };
let fill = cdt::Fill { seeds: &seeds, refine: Some((sag, MAX_REFINE)), shape: !matches!(s, EvalSurface::Plane { .. }), lenient: false };
@@ -741,7 +772,7 @@ fn plan_face(
let (extra, triangles) = {
let mut us = uv::divide(s, 0, bbox[0], bbox[1], rules, h, MAX_LINES);
let mut vs = uv::divide(s, 1, bbox[1], bbox[0], rules, h, MAX_LINES);
- thin(&mut us, &mut vs, grid::MAX_FACE_GRID);
+ grid::thin(&mut us, &mut vs, grid::MAX_FACE_GRID);
let structured = match (ranges.len(), if seamed { None } else { grid::quad(&uvs) }) {
(1, Some(q)) => {
// Interior lines: the boundary's own where opposite sides agree (refined where the
@@ -787,8 +818,16 @@ fn plan_face(
// the iso-line grid cut along its motorcycle traces and trimmed by its boundary,
// else Delaunay. A plane: the butterfly of a round face, else Delaunay (a plane
// is shaded the same by any triangles, and its Delaunay needs no refinement).
+ // A curved strip, straight and within a side across one parameter (its division
+ // there has no line inside) and with no room for a point of its own (a thread's
+ // root band, which runs out obliquely so it has no four corners), is its boundary
+ // nodes alone, refined where the surface leaves them: patches and grid lines
+ // across it would only crowd it (the butterfly's cuts run lengthwise through a
+ // long strip, seeded the whole way). A strip curved across (a fillet narrower
+ // than a side) keeps the layouts that follow its curvature.
let face = Region { s, uvs: &uvs, fixed: &fixed, ranges: &ranges, rules, h, speed, us: &us, vs: &vs };
- let trimmed = if seamed {
+ let strip = !planar && (us.len() <= 2 || vs.len() <= 2) && !cdt::has_room(bbox, step, &polys, speed);
+ let trimmed = if seamed || strip {
None
} else if planar {
if ranges.len() == 1 { plan_pieces(&face) } else { None }
@@ -1080,23 +1119,5 @@ fn closed_boundary(ranges: &[std::ops::Range<usize>], fixed: &[Vec3], triangles:
})
}
-/// Keep at most `cap` grid points by taking every k-th line in both directions (ends kept).
-fn thin(us: &mut Vec<f64>, vs: &mut Vec<f64>, cap: usize) {
- let total = us.len().saturating_mul(vs.len());
- if total <= cap {
- return;
- }
- let f = (total as f64 / cap.max(4) as f64).sqrt();
- let pick = |d: &mut Vec<f64>| {
- let n = ((d.len() as f64 / f).ceil() as usize).max(2);
- if d.len() > n {
- let len = d.len();
- *d = (0..n).filter_map(|i| d.get(i * (len - 1) / (n - 1)).copied()).collect();
- }
- };
- pick(us);
- pick(vs);
-}
-
#[cfg(test)]
mod tests;
diff --git a/crates/kernel/src/tess/seam.rs b/crates/kernel/src/tess/seam.rs
index 1982cb67c8..307fcfb02f 100644
--- a/crates/kernel/src/tess/seam.rs
+++ b/crates/kernel/src/tess/seam.rs
@@ -385,29 +385,18 @@ fn seam_nodes(s: &EvalSurface, swap: bool, x: f64, y0: f64, y1: f64, rules: &Rul
Some(inner.iter().map(|&y| (y, s.eval(uv(y)[0], uv(y)[1]).0)).collect())
}
-/// Whether a face of `solid` lies on a B-spline surface that joins itself (a lofted tube).
-/// Truck meshes a face in its surface's parameters and treats only a revolved surface's
-/// rotation as periodic, so a face that runs across such a join comes out folded over itself or
-/// with a hole in it. The reference mesh of such a body is made from the display plan,
-/// which knows the join is periodic.
-pub(crate) fn closes_on_itself(solid: &crate::body::Solid) -> bool {
- solid.face_iter().any(|f| matches!(super::surface::eval_surface(&f.surface()), Some(EvalSurface::Nurbs { closed, .. }) if closed[0] || closed[1]))
-}
-
-/// Whether a face of `solid` lies on a surface of revolution and has a boundary loop turning
-/// more than once around its axis (a helical trim). Truck's mesher cannot mesh such a face (its
-/// triangles cut across the solid), so the reference mesh is made from the display plan instead.
+/// Whether a face of `solid` has a boundary loop turning more than once around the axis its
+/// surface turns about (a helical trim): a surface of revolution's own axis, or the axis a
+/// spline's iso-line winds around (the flank of a screw sweep, as SMLib writes a modelled
+/// thread's groove, whose bore or shaft it splits into one face per turn). Truck's mesher cannot
+/// mesh such a face (its triangles cut across the solid, or its triangulation fails), so the
+/// reference mesh is made from the display plan instead.
pub(crate) fn turns_more_than_once(solid: &crate::body::Solid) -> bool {
use truck_meshalgo::prelude::*;
use truck_modeling as mt;
let tau = std::f64::consts::TAU;
for face in solid.face_iter() {
- let mt::Surface::RevolutedCurve(proc) = face.surface() else { continue };
- let rev = proc.entity();
- let m = *proc.transform();
- let o = crate::body::from_p3(m.transform_point(rev.origin()));
- let a = m.transform_vector(rev.axis());
- let Some(k) = Vec3::new(a.x, a.y, a.z).normalized() else { continue };
+ let Some((o, k)) = winding_axis(&face.surface()) else { continue };
let e1 = k.cross(if k.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).normalized().unwrap_or(Vec3::X);
let e2 = k.cross(e1);
let angle = |p: mt::Point3| {
@@ -424,7 +413,7 @@ pub(crate) fn turns_more_than_once(solid: &crate::body::Solid) -> bool {
let mut n = 16usize;
let steps = loop {
let xs: Vec<f64> = (0..=n).map(|i| angle(c.subs(t0 + (t1 - t0) * i as f64 / n as f64))).collect();
- let ok = xs.windows(2).all(|w| ((w[1] - w[0] + std::f64::consts::PI).rem_euclid(tau) - std::f64::consts::PI).abs() < 1.0);
+ let ok = xs.windows(2).all(|w| half_turn(w[1] - w[0]).abs() < 1.0);
if ok || n >= 4096 {
break xs;
}
@@ -432,7 +421,7 @@ pub(crate) fn turns_more_than_once(solid: &crate::body::Solid) -> bool {
};
for x in steps {
if let Some(p) = prev {
- total += (x - p + std::f64::consts::PI).rem_euclid(tau) - std::f64::consts::PI;
+ total += half_turn(x - p);
lo = lo.min(total);
hi = hi.max(total);
}
@@ -446,3 +435,67 @@ pub(crate) fn turns_more_than_once(solid: &crate::body::Solid) -> bool {
}
false
}
+
+/// An angle step taken the short way round, in (−π, π].
+fn half_turn(x: f64) -> f64 {
+ let pi = std::f64::consts::PI;
+ (x + pi).rem_euclid(std::f64::consts::TAU) - pi
+}
+
+/// Samples per knot span of a spline's iso-line in [`winding_axis`], and their bounds.
+const ISO_SPAN_SAMPLES: usize = 4;
+const ISO_MIN_SAMPLES: usize = 64;
+const ISO_MAX_SAMPLES: usize = 8192;
+
+/// The axis (a point on it, its unit direction) a face's surface turns about, if it turns at
+/// all: a surface of revolution's own axis; for a spline, the axis an iso-line through the
+/// middle of the other parameter winds more than once around (a screw sweep's flank, a coil's
+/// wall). That axis is the mean binormal of the iso-line (each pair of successive tangents
+/// turns about it), through the mean of its samples; `None` for a spline neither iso-line of
+/// which turns more than once about it.
+fn winding_axis(surface: &truck_modeling::Surface) -> Option<(Vec3, Vec3)> {
+ use truck_meshalgo::prelude::*;
+ use truck_modeling as mt;
+ if let mt::Surface::RevolutedCurve(proc) = surface {
+ let rev = proc.entity();
+ let m = *proc.transform();
+ let o = crate::body::from_p3(m.transform_point(rev.origin()));
+ let a = m.transform_vector(rev.axis());
+ return Vec3::new(a.x, a.y, a.z).normalized().map(|k| (o, k));
+ }
+ if matches!(surface, mt::Surface::Plane(_)) {
+ return None;
+ }
+ let s = super::surface::eval_surface(surface)?;
+ let EvalSurface::Nurbs { knots, .. } = &s else { return None };
+ let dom = super::uv::domain(&s);
+ let tau = std::f64::consts::TAU;
+ (0..2).find_map(|d| {
+ let (a, b) = dom.range[d]?;
+ let (c0, c1) = dom.range[1 - d]?;
+ let across = 0.5 * (c0 + c1);
+ let n = knots.get(d).map_or(0, |k| k.len()).saturating_mul(ISO_SPAN_SAMPLES).clamp(ISO_MIN_SAMPLES, ISO_MAX_SAMPLES);
+ let pts: Vec<Vec3> = (0..=n)
+ .filter_map(|i| {
+ let t = a + (b - a) * i as f64 / n as f64;
+ s.derivs(if d == 0 { t } else { across }, if d == 0 { across } else { t }).map(|(p, _, _)| p)
+ })
+ .collect();
+ if pts.len() != n + 1 {
+ return None;
+ }
+ let tangents: Vec<Vec3> = pts.windows(2).filter_map(|w| (w[1] - w[0]).normalized()).collect();
+ let binormal = tangents.windows(2).fold(Vec3::ZERO, |acc, w| acc + w[0].cross(w[1]));
+ let k = binormal.normalized()?;
+ let o = pts.iter().fold(Vec3::ZERO, |acc, p| acc + *p) * (1.0 / pts.len() as f64);
+ let e1 = k.cross(if k.x.abs() < 0.9 { Vec3::X } else { Vec3::Y }).normalized()?;
+ let e2 = k.cross(e1);
+ let angles: Vec<f64> = pts.iter().map(|p| (*p - o).dot(e2).atan2((*p - o).dot(e1))).collect();
+ // Too coarse to follow the turns (a step of a radian or more): not taken as winding.
+ let steps: Vec<f64> = angles.windows(2).map(|w| half_turn(w[1] - w[0])).collect();
+ if steps.iter().any(|x| x.abs() >= 1.0) {
+ return None;
+ }
+ (steps.iter().sum::<f64>().abs() > tau * 1.01).then_some((o, k))
+ })
+}
diff --git a/crates/kernel/src/tess/tests.rs b/crates/kernel/src/tess/tests.rs
index 82d202f03b..7ce933745f 100644
--- a/crates/kernel/src/tess/tests.rs
+++ b/crates/kernel/src/tess/tests.rs
@@ -549,3 +549,186 @@ fn an_smlib_torus_stays_within_the_chord_tolerance() {
assert!(chord <= tol * 1.05, "SMLib torus at {tol}: chord {chord}");
}
}
+
+// Modelled threads from SMLib: a screw-swept groove cut from a bore or a shaft. The groove's
+// walls are splines winding once per pitch for the thread's whole length, and they split the
+// bore or shaft into one face per turn.
+
+/// A groove of trapezoid `section` (radius, axial offset) in the plane through the z axis along
+/// y, carried `turns` turns of `pitch` about z from `base`, as an SMLib solid.
+#[cfg(feature = "smlib")]
+fn smlib_groove(section: [(f64, f64); 4], base: f64, pitch: f64, turns: f64) -> solidcraft_smlib::Brep {
+ use solidcraft_geom::{Loop2, Vec2};
+ smlib_screw(Loop2::polygon(&section.map(|(r, z)| Vec2::new(r, z))), base, pitch, turns)
+}
+
+/// The `section` (radius, axial offset) in the plane through the z axis along y, carried
+/// `turns` turns of `pitch` about z from `base`, as an SMLib solid.
+#[cfg(feature = "smlib")]
+fn smlib_screw(section: solidcraft_geom::Loop2, base: f64, pitch: f64, turns: f64) -> solidcraft_smlib::Brep {
+ use solidcraft_geom::{Plane, Region2};
+ let origin = Vec3::new(0.0, 0.0, base);
+ let plane = Plane { origin, x: Vec3::Y, y: Vec3::Z };
+ let region = Region2 { outer: section, holes: Vec::new() };
+ let Some(numbered) = crate::numbered::number_regions(std::slice::from_ref(&region)).pop() else { panic!("profile") };
+ let profile = numbered.outer.oriented(false);
+ let groove = ok(crate::smlib_sweeps::screw(&plane, &crate::smlib_sweeps::pieces([&profile]), origin, Vec3::Z, pitch, turns));
+ ok(crate::native::smlib_body(&groove))
+}
+
+#[cfg(feature = "smlib")]
+fn smlib_cut(a: &solidcraft_smlib::Brep, b: &solidcraft_smlib::Brep) -> solidcraft_smlib::Brep {
+ match a.boolean(b, solidcraft_smlib::BooleanOp::Subtract) {
+ Ok(Some(r)) => r,
+ other => panic!("cut: {other:?}"),
+ }
+}
+
+/// The ISO basic profile's groove for pitch `p` and major diameter `d`: internal, from 0.1 p
+/// inside the hole wall of radius `wall` out to the major radius; external, from the root out
+/// past the shaft's surface (radius `wall`).
+#[cfg(feature = "smlib")]
+fn iso_groove(p: f64, d: f64, wall: f64, internal: bool) -> [(f64, f64); 4] {
+ let h = p * 3f64.sqrt() / 2.0;
+ let slope = (PI / 6.0).tan();
+ let (r0, w0, r1, w1) = if internal {
+ let r_in = wall.min(d / 2.0 - 5.0 * h / 8.0) - 0.1 * p;
+ (r_in, (p / 8.0 + 2.0 * (d / 2.0 - r_in) * slope) / 2.0, d / 2.0, p / 16.0)
+ } else {
+ let (r_root, r_out) = (d / 2.0 - 5.0 * h / 8.0, wall.max(d / 2.0) + 0.05 * p);
+ (r_root, p / 8.0, r_out, (p / 4.0 + 2.0 * (r_out - r_root) * slope) / 2.0)
+ };
+ [(r0, -w0), (r1, -w1), (r1, w1), (r0, w0)]
+}
+
+/// Each face's triangles, in 3D, cover as much area as its surface over the triangles' own
+/// parameters, within 5% (a coarse tolerance on a small curved face, a few percent): nothing
+/// zigzags across the face, which multiplies its area. The surface's area by the midpoint rule
+/// on sixteen pieces of each parameter triangle.
+#[cfg(feature = "smlib")]
+fn assert_faces_lie_flat(name: &str, plan: &solidcraft_geom::tess::TessPlan) {
+ for fp in &plan.faces {
+ let Some(s) = fp.surface.and_then(|i| plan.surfaces.get(i as usize)) else { continue };
+ let at = |i: u32| {
+ fp.fixed.get(i as usize).copied().unwrap_or_else(|| {
+ let q = fp.uv[i as usize];
+ s.eval(q[0], q[1]).0
+ })
+ };
+ let (mut flat, mut surface) = (0.0, 0.0);
+ for t in &fp.triangles {
+ let [a, b, c] = t.map(|i| fp.uv[i as usize]);
+ let area = 0.5 * ((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])).abs();
+ flat += 0.5 * (at(t[1]) - at(t[0])).cross(at(t[2]) - at(t[0])).len();
+ const N: usize = 4;
+ for i in 0..N {
+ for j in 0..N - i {
+ // The upright piece, and the inverted one beside it where there is one.
+ let pieces: &[(f64, f64)] =
+ if i + j + 1 < N { &[(1.0 / 3.0, 1.0 / 3.0), (2.0 / 3.0, 2.0 / 3.0)] } else { &[(1.0 / 3.0, 1.0 / 3.0)] };
+ for &(di, dj) in pieces {
+ let (x, y) = ((i as f64 + di) / N as f64, (j as f64 + dj) / N as f64);
+ let q = [a[0] + (b[0] - a[0]) * x + (c[0] - a[0]) * y, a[1] + (b[1] - a[1]) * x + (c[1] - a[1]) * y];
+ if let Some((_, su, sv)) = s.derivs(q[0], q[1]) {
+ surface += su.cross(sv).len() * area / (N * N) as f64;
+ }
+ }
+ }
+ }
+ }
+ assert!((flat - surface).abs() <= 0.05 * surface, "{name}: face {} has {flat} mm² of triangles over {surface} mm² of surface", fp.face);
+ }
+}
+
+/// #1995: an M8x1 thread through a 7 mm hole in a 20 mm block, both ends open. Truck meshed the
+/// groove's winding walls with triangles reaching past both ends of the block; the body's mesh
+/// now comes from the display plan, inside the block and with the analytic volume.
+#[cfg(feature = "smlib")]
+#[test]
+fn a_modelled_thread_in_a_bore_meshes_inside_its_block() {
+ use solidcraft_smlib::Brep as S;
+ let (Ok(block), Ok(bore)) = (S::make_box([-10.0, -10.0, 0.0], [20.0, 20.0, 10.0]), S::make_cylinder([0.0, 0.0, -1.0], 3.5, 12.0)) else {
+ panic!("stock")
+ };
+ let threaded = smlib_cut(&smlib_cut(&block, &bore), &smlib_groove(iso_groove(1.0, 8.0, 3.5, true), -1.0, 1.0, 12.0));
+ let body = ok(crate::native::body_from_smlib(&threaded));
+ assert!(seam::turns_more_than_once(&body.solid), "the groove's walls wind round the bore");
+ let m = ok(body.tessellate(0.01));
+ let (lo, hi) = m
+ .positions
+ .iter()
+ .fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
+ assert!(lo.z > -1e-6 && hi.z < 10.0 + 1e-6 && lo.x > -10.0 - 1e-6 && hi.x < 10.0 + 1e-6, "mesh outside the block: {lo:?} {hi:?}");
+ // Block less the bore less ten turns of the groove where it is in the material (as the
+ // kernel case works it out from the ISO profile).
+ let volume = m.measure().volume;
+ assert!((volume - 3567.1757).abs() < 0.002 * 3567.1757, "volume {volume}");
+ for tol in [0.1, 0.01] {
+ let m = closed_display_mesh("thread in a bore", &body, tol);
+ let chord = max_chord(&body, &m);
+ assert!(chord <= tol * 1.05, "thread in a bore at {tol}: chord {chord}");
+ assert_faces_lie_flat("thread in a bore", &ok(body.display_plan_angular(tol, crate::DISPLAY_ANGLE)));
+ }
+}
+
+/// An M10 thread over the lower half of a 30 mm shaft. The groove's root band leaves the shaft's
+/// end face obliquely: a strip a quarter pitch wide winding ten turns, narrower everywhere than
+/// a triangle's side, with no four corners to blend. The butterfly of a round face made it a
+/// grid of ~200 000 points whose triangles zigzagged along the strip (six times the band's area,
+/// and off the surface by more than the tolerance); it is its boundary nodes alone now.
+#[cfg(feature = "smlib")]
+#[test]
+fn a_thread_root_band_running_out_through_an_end_face_lies_on_its_surface() {
+ let Ok(shaft) = solidcraft_smlib::Brep::make_cylinder([0.0; 3], 5.0, 30.0) else { panic!("shaft") };
+ let threaded = smlib_cut(&shaft, &smlib_groove(iso_groove(1.5, 10.0, 5.0, false), -1.5, 1.5, 11.0));
+ let body = ok(crate::native::body_from_smlib(&threaded));
+ let m = ok(body.tessellate(0.01));
+ let (lo, hi) = m
+ .positions
+ .iter()
+ .fold((Vec3::new(f64::MAX, f64::MAX, f64::MAX), Vec3::new(f64::MIN, f64::MIN, f64::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)));
+ assert!(lo.z > -1e-6 && hi.z < 30.0 + 1e-6 && hi.x < 5.0 + 1e-6, "mesh outside the shaft: {lo:?} {hi:?}");
+ for tol in [0.1, 0.01] {
+ let m = closed_display_mesh("thread run out", &body, tol);
+ let chord = max_chord(&body, &m);
+ assert!(chord <= tol * 1.05, "thread run out at {tol}: chord {chord}");
+ assert!(m.triangles.len() < 60_000, "thread run out at {tol}: {} triangles", m.triangles.len());
+ assert_faces_lie_flat("thread run out", &ok(body.display_plan_angular(tol, crate::DISPLAY_ANGLE)));
+ }
+}
+
+/// #793: a coil (a 1 mm wire at 20 mm, six turns of pitch 4) cut in two across its axis. Its
+/// halves go to the display plan for their mesh; at the measuring tolerance a half's wall wants
+/// more cells than a grid may have, and its cut grid gave up for an under-refined Delaunay (the
+/// halves measured 1.5% short of the whole). The cut grid now thins its lines to fit.
+#[cfg(feature = "smlib")]
+#[test]
+fn the_halves_of_a_split_smlib_coil_measure_as_the_whole() {
+ use solidcraft_geom::{Loop2, Vec2};
+ use solidcraft_smlib::{BooleanOp, Brep as S};
+ let coil = smlib_screw(Loop2::circle(Vec2::new(20.0, 0.0), 1.0), 0.0, 4.0, 6.0);
+ let Ok(top) = S::make_box([-30.0, -30.0, 12.5], [60.0, 60.0, 30.0]) else { panic!("box") };
+ let (Ok(Some(upper)), Ok(Some(lower))) = (coil.boolean(&top, BooleanOp::Intersect), coil.boolean(&top, BooleanOp::Subtract)) else {
+ panic!("split")
+ };
+ let volume = |b: &S| ok(crate::measure(&ok(crate::native::body_from_smlib(b)))).volume;
+ // π r² · 2πR · turns; SMLib's wall is a spline within a ten-thousandth of the pitch.
+ let (whole, analytic) = (volume(&coil), PI * 2.0 * PI * 20.0 * 6.0);
+ assert!((whole - analytic).abs() < 3e-3 * analytic, "coil {whole} vs {analytic}");
+ let halves = volume(&upper) + volume(&lower);
+ assert!((halves - whole).abs() < 1e-3 * whole, "halves {halves} vs the whole {whole}");
+}
+
+/// Thinning keeps a grid within its cap whatever the rounding, both ends of each direction,
+/// and never fewer than two lines a direction (a cap below four points takes four).
+#[test]
+fn thinned_grid_lines_stay_within_the_cap() {
+ let lines = |n: usize| (0..n).map(|i| i as f64 / (n - 1) as f64).collect::<Vec<f64>>();
+ for (nu, nv, cap) in [(1237, 122, 150_000), (8192, 3, 1000), (3, 8192, 10), (2, 2, 1), (5000, 5000, 4)] {
+ let (mut us, mut vs) = (lines(nu), lines(nv));
+ grid::thin(&mut us, &mut vs, cap);
+ assert!(us.len() * vs.len() <= cap.max(4), "{nu}x{nv} to {cap}: {}x{}", us.len(), vs.len());
+ assert!(us.len() >= 2 && vs.len() >= 2);
+ assert!(us.first() == Some(&0.0) && us.last() == Some(&1.0) && vs.first() == Some(&0.0) && vs.last() == Some(&1.0));
+ }
+}