Skip to content

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

Mesh a face thinner than the tolerance instead of leaving a hole (#2712)

SiroArt71534117af4c
diff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rs
index c75130a8db..4296343780 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -132,6 +132,8 @@ mod sweep_rails_tests;
mod tangent_cylinders;
mod tess;
#[cfg(test)]
+mod thin_face_tests;
+#[cfg(test)]
mod thread_display_tests;
#[cfg(test)]
mod thread_tests;
diff --git a/crates/kernel/src/thin_face_tests.rs b/crates/kernel/src/thin_face_tests.rs
new file mode 100644
index 0000000000..105df41520
--- /dev/null
+++ b/crates/kernel/src/thin_face_tests.rs
@@ -0,0 +1,43 @@
+//! A face thinner than the tolerance still meshes: the lens of a sphere's patch that pokes out
+//! of a box's side has two edges that, sampled coarsely, run along one line in its parameters.
+//! The shell's mesh had a hole there.
+
+use std::collections::HashMap;
+
+use solidcraft_geom::Vec3;
+
+use crate::{BoolOp, build::box_solid, build::sphere, ops::boolean};
+
+/// Triangle sides in the mesh with no triangle on the other side of them, with the points
+/// within a thousandth of a millimetre taken as one.
+fn open_sides(mesh: &solidcraft_geom::Mesh) -> usize {
+ let key = |i: u32| {
+ let p = mesh.positions[i as usize];
+ [p.x, p.y, p.z].map(|c| (c * 1e3).round() as i64)
+ };
+ let mut sides: HashMap<([i64; 3], [i64; 3]), u32> = HashMap::new();
+ for t in &mesh.triangles {
+ for (a, b) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {
+ *sides.entry((key(a), key(b))).or_default() += 1;
+ }
+ }
+ sides.keys().filter(|(a, b)| !sides.contains_key(&(*b, *a))).count()
+}
+
+/// The sphere's equator lies in the box's top and its circle on the box's side x = 22.5 dips to
+/// z = 24.7, while the edge of the sphere's bottom patch bulges 0.15 mm past that side: a
+/// face of about 0.35 mm² between the two. At 1 % of the body it had no triangle.
+#[test]
+fn a_lens_thinner_than_the_tolerance_is_meshed() {
+ let a = sphere(Vec3::new(20.0, 10.0, 27.5), 3.75).unwrap();
+ let b = box_solid(Vec3::new(15.0, 0.0, 22.5), Vec3::new(22.5, 20.0, 27.5)).unwrap();
+ let union = boolean(&a, &b, BoolOp::Union).unwrap().unwrap();
+ assert!(union.validity().is_empty(), "{:?}", union.validity());
+ let size = union.size();
+ for tol in [size * 1e-2, size * 2.5e-3, size * 1e-3] {
+ let mesh = union.tessellate(tol).unwrap();
+ let faces: std::collections::HashSet<u32> = mesh.tri_face.iter().copied().collect();
+ assert_eq!(faces.len(), union.face_count(), "faces with triangles at {tol}");
+ assert_eq!(open_sides(&mesh), 0, "open sides at {tol}");
+ }
+}
diff --git a/crates/kernel/tests/boolean_props.rs b/crates/kernel/tests/boolean_props.rs
index db634b3327..064d210a4c 100644
--- a/crates/kernel/tests/boolean_props.rs
+++ b/crates/kernel/tests/boolean_props.rs
@@ -303,6 +303,15 @@ fn grid_sphere_box_union_is_sound() {
check(identity(&a, &b));
}
+/// A small sphere on the top of a thin box: a patch of the sphere sticks out of the box's side
+/// by less than the tolerance, a face of about 0.35 mm² that had no triangle when meshed at 1 % of the body.
+#[test]
+fn grid_small_sphere_thin_box_union_is_sound() {
+ let a = Prim::Sph { at: [20.0, 10.0, 27.5], r: 3.75 };
+ let b = Prim::Box { at: [15.0, 0.0, 22.5], size: [7.5, 20.0, 5.0] };
+ check(identity(&a, &b));
+}
+
/// Two crossing cylinders: the union moved 1000 mm away loses about a tenth of its volume.
#[test]
#[ignore = "kernel bug, #1649"]
diff --git a/crates/kernel/tests/tess_loop_fill.rs b/crates/kernel/tests/tess_loop_fill.rs
new file mode 100644
index 0000000000..70055f52ed
--- /dev/null
+++ b/crates/kernel/tests/tess_loop_fill.rs
@@ -0,0 +1,121 @@
+//! The fallback in the vendored tessellator that triangulates the boundary loop of a face that
+//! came out with no triangle (a lens thinner than the tolerance). Its ear clipping is checked on
+//! the polygons it can meet: convex, concave, either winding, with collinear points, and loops
+//! it must refuse.
+//!
+//! The vendored crates are outside the workspace, so their own tests never run in CI; the
+//! function is reached through the crate's `test-hooks` feature (on only for kernel tests).
+
+use truck_meshalgo::tessellation::loop_fill_test_hooks::ear_clipping;
+
+fn area2(points: &[[f64; 2]]) -> f64 {
+ points.iter().zip(points.iter().cycle().skip(1)).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum()
+}
+
+/// The triangles turn the same way as the polygon, there are `n - 2` of them, and they add up to
+/// its area: together they cover it once, with no overlap.
+fn assert_covers_once(points: &[[f64; 2]]) {
+ let triangles = ear_clipping(points).expect("a simple polygon is triangulated");
+ assert_eq!(triangles.len(), points.len() - 2);
+ let side = area2(points).signum();
+ let mut sum = 0.0;
+ for t in &triangles {
+ let t = area2(&t.map(|i| points[i]));
+ assert!(t * side > 0.0, "a triangle turns the other way, or has no area: {t}");
+ sum += t;
+ }
+ assert!((sum - area2(points)).abs() < 1e-9, "triangles cover {sum}, the polygon {}", area2(points));
+}
+
+#[test]
+fn a_triangle_is_itself() {
+ let points = [[0.0, 0.0], [1.0, 0.0], [0.0, 1.0]];
+ assert_eq!(ear_clipping(&points), Some(vec![[0, 1, 2]]));
+}
+
+#[test]
+fn a_convex_polygon_either_way_round() {
+ let square = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]];
+ assert_covers_once(&square);
+ let mut reversed = square;
+ reversed.reverse();
+ assert_covers_once(&reversed);
+}
+
+#[test]
+fn a_concave_polygon_either_way_round() {
+ // An L: the reflex corner is at (1, 1).
+ let l = [[0.0, 0.0], [2.0, 0.0], [2.0, 1.0], [1.0, 1.0], [1.0, 2.0], [0.0, 2.0]];
+ assert_covers_once(&l);
+ let mut reversed = l;
+ reversed.reverse();
+ assert_covers_once(&reversed);
+}
+
+#[test]
+fn a_thin_lens_made_of_an_arc_and_a_chord() {
+ let lens = [[0.0, 0.0], [1.0, -0.15], [2.0, 0.0]];
+ assert_covers_once(&lens);
+ let more = [[0.0, 0.0], [0.5, -0.1], [1.0, -0.15], [1.5, -0.1], [2.0, 0.0]];
+ assert_covers_once(&more);
+}
+
+#[test]
+fn collinear_points_on_a_side_are_kept_as_corners() {
+ let square = [[0.0, 0.0], [1.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0]];
+ let triangles = ear_clipping(&square).expect("triangulated");
+ assert_eq!(triangles.len(), 3);
+ let covered: f64 = triangles.iter().map(|t| area2(&t.map(|i| square[i]))).sum();
+ assert!((covered - area2(&square)).abs() < 1e-9);
+}
+
+#[test]
+fn a_loop_without_area_is_refused() {
+ assert_eq!(ear_clipping(&[[0.0, 0.0], [1.0, 0.0], [2.0, 0.0]]), None, "three collinear points");
+ assert_eq!(ear_clipping(&[[0.0, 0.0], [1.0, 1.0], [0.0, 0.0], [1.0, 1.0]]), None, "a line walked twice");
+}
+
+#[test]
+fn fewer_than_three_points_are_refused() {
+ assert_eq!(ear_clipping(&[]), None);
+ assert_eq!(ear_clipping(&[[0.0, 0.0]]), None);
+ assert_eq!(ear_clipping(&[[0.0, 0.0], [1.0, 0.0]]), None);
+}
+
+/// A loop that crosses itself (the #1648 face pinched to a point is one) would get overlapping
+/// triangles, and so a wrong mesh that hides the problem. It is refused, symmetric or not.
+#[test]
+fn a_loop_crossing_itself_is_refused() {
+ let bowtie = [[0.0, 0.0], [2.0, 2.0], [2.0, 0.0], [0.0, 2.0]];
+ assert_eq!(ear_clipping(&bowtie), None);
+ let lopsided = [[0.0, 0.0], [3.0, 2.0], [3.0, 0.0], [0.0, 1.0]];
+ assert_eq!(ear_clipping(&lopsided), None);
+ let pinched = [[0.0, 0.0], [5.0, 0.0], [5.0, 0.3], [3.0, -0.1], [2.0, -0.1], [0.0, 0.3]];
+ assert_eq!(ear_clipping(&pinched), None);
+}
+
+/// The loop of a face closes on its first point: a point given twice in a row is a corner with no
+/// area, and the polygon is still triangulated on the rest.
+#[test]
+fn a_repeated_point_is_handled_without_a_wrong_mesh() {
+ let points = [[0.0, 0.0], [2.0, 0.0], [2.0, 2.0], [0.0, 2.0], [0.0, 0.0]];
+ if let Some(triangles) = ear_clipping(&points) {
+ let covered: f64 = triangles.iter().map(|t| area2(&t.map(|i| points[i]))).sum();
+ assert!((covered - area2(&points)).abs() < 1e-9, "triangles cover {covered}");
+ }
+}
+
+/// The largest loop the fallback takes, as a circle with a bite out of it: all of it is covered
+/// exactly once.
+#[test]
+fn the_largest_loop_is_triangulated() {
+ let n = 256;
+ let points: Vec<[f64; 2]> = (0..n)
+ .map(|i| {
+ let t = std::f64::consts::TAU * i as f64 / n as f64;
+ let r = if i % 16 == 0 { 0.6 } else { 1.0 };
+ [r * t.cos(), r * t.sin()]
+ })
+ .collect();
+ assert_covers_once(&points);
+}
diff --git a/vendor/README.md b/vendor/README.md
index b4622948aa..e3a7ff2fbc 100644
--- a/vendor/README.md
+++ b/vendor/README.md
@@ -191,6 +191,17 @@ Changes:
the face, many degrees round: those triangles cut through the surface and folded over each
other (a cone face with a small hole meshed several mm² too large, and the boolean that made
it was refused for its volume).
+- `tessellation/triangulation.rs`: a face that comes out of the triangulation with no triangle
+ at all, though the points of its one boundary loop enclose an area in space, is given the
+ triangles of that loop (ears clipped on the plane of the loop, no point added, so the faces on
+ either side of its edges still meet it). Its two edges can be different curves that, sampled
+ as they are, run along the same line in the face's parameters (a lens thinner than the
+ tolerance), and the loop then has no area there. The shell's mesh had a hole. Faces that
+ mesh are untouched, and so are preview meshes (they have their own step grid). Only a face
+ with one loop of at most 256 points is filled, and not one whose loop crosses itself, whose
+ ears would overlap (the pinched face of #1648 is one): it stays as it was.
+ `crates/kernel/src/thin_face_tests.rs` holds it, `crates/kernel/tests/tess_loop_fill.rs` the
+ ear clipping (through the `test-hooks` feature).
## matext4cgmath 0.1.0 (Apache-2.0, © RICOS Co. Ltd., https://github.com/ricosjp/matext4cgmath)
diff --git a/vendor/truck-meshalgo/src/tessellation/mod.rs b/vendor/truck-meshalgo/src/tessellation/mod.rs
index 6c60fdb371..b51c098b0f 100644
--- a/vendor/truck-meshalgo/src/tessellation/mod.rs
+++ b/vendor/truck-meshalgo/src/tessellation/mod.rs
@@ -524,4 +524,4 @@ mod closed;
mod triangulation;
#[cfg(feature = "test-hooks")]
#[doc(hidden)]
-pub use triangulation::include_test_hooks;
+pub use triangulation::{include_test_hooks, loop_fill_test_hooks};
diff --git a/vendor/truck-meshalgo/src/tessellation/triangulation.rs b/vendor/truck-meshalgo/src/tessellation/triangulation.rs
index cc09e76aba..60b78731eb 100644
--- a/vendor/truck-meshalgo/src/tessellation/triangulation.rs
+++ b/vendor/truck-meshalgo/src/tessellation/triangulation.rs
@@ -967,10 +967,130 @@ fn trimming_with_steps<S: PreMeshableSurface>(surface: &S, polyboundary: &PolyBo
surface,
polyboundary,
);
+ // SolidCraft: a face that came out with no triangles at all, though its boundary encloses
+ // an area in space (a lens thinner than the tolerance: its two edges are different curves,
+ // but sampled as they are, in the face's parameters they run along the same line), left a
+ // hole in the shell's mesh. Its boundary points are triangulated as they are, so it still
+ // meets the faces on either side of it.
+ if steps.is_none() && mesh.faces().is_empty() {
+ if let Some(filled) = loop_triangles(surface, polyboundary) {
+ mesh = filled;
+ }
+ }
mesh.make_face_compatible_to_normal();
mesh
}
+/// SolidCraft: most points of a loop [`loop_triangles`] triangulates.
+const MAX_LOOP_POINTS: usize = 256;
+
+/// SolidCraft: the triangles of a face's one boundary loop, taken in space on the plane the loop
+/// lies near and with no point added, for a face whose parameters give none (see
+/// [`trimming_with_steps`]). `None` when the face has several loops, too many points, or no
+/// area in space.
+fn loop_triangles(surface: &impl ParametricSurface3D, polyline: &PolyBoundary) -> Option<PolygonMesh> {
+ let [curve] = polyline.0.as_slice() else { return None };
+ if !(3..=MAX_LOOP_POINTS).contains(&curve.len()) {
+ return None;
+ }
+ let positions: Vec<Point3> = curve.iter().map(|p| surface.subs(p.x, p.y)).collect();
+ if positions.iter().any(|p| !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite())) {
+ return None;
+ }
+ let normal = newell_normal(&positions);
+ if normal.magnitude() * 0.5 <= TOLERANCE {
+ return None;
+ }
+ // The loop seen along the axis its normal points along most.
+ let axis = (0..3).max_by(|&i, &j| normal[i].abs().total_cmp(&normal[j].abs()))?;
+ let flat: Vec<[f64; 2]> = positions
+ .iter()
+ .map(|p| match axis {
+ 0 => [p.y, p.z],
+ 1 => [p.z, p.x],
+ _ => [p.x, p.y],
+ })
+ .collect();
+ let triangles: Vec<[StandardVertex; 3]> = ear_clipping(&flat)?
+ .into_iter()
+ .filter(|&[a, b, c]| (positions[b] - positions[a]).cross(positions[c] - positions[a]).magnitude() * 0.5 > TOLERANCE)
+ .map(|corners| corners.map(|i| (i, Some(i), Some(i)).into()))
+ .collect();
+ if triangles.is_empty() {
+ return None;
+ }
+ // The normals orient the triangles ([`NormalFilters::make_face_compatible_to_normal`]).
+ let normals = curve.iter().map(|p| surface.normal(p.x, p.y)).collect();
+ let uv_coords = curve.iter().map(|p| Vector2::new(p.x, p.y)).collect();
+ Some(PolygonMesh::debug_new(
+ StandardAttributes { positions, uv_coords, normals },
+ Faces::from_tri_and_quad_faces(triangles, Vec::new()),
+ ))
+}
+
+/// SolidCraft: twice the vector area of a closed polygon: the direction of its plane, as long as
+/// it is large.
+fn newell_normal(points: &[Point3]) -> Vector3 {
+ let next = points.iter().cycle().skip(1);
+ points.iter().zip(next).fold(Vector3::zero(), |sum, (p, q)| {
+ sum + Vector3::new((p.y - q.y) * (p.z + q.z), (p.z - q.z) * (p.x + q.x), (p.x - q.x) * (p.y + q.y))
+ })
+}
+
+/// SolidCraft: twice the signed area of the triangle `a b c`: positive when it turns left.
+fn turn(a: [f64; 2], b: [f64; 2], c: [f64; 2]) -> f64 {
+ (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0])
+}
+
+/// SolidCraft: whether two sides of the closed polygon that do not share a corner cross each other.
+/// Ears of a polygon that crosses itself overlap, so it is not triangulated.
+fn crosses_itself(points: &[[f64; 2]]) -> bool {
+ let n = points.len();
+ let side = |i: usize| (points[i], points[(i + 1) % n]);
+ (0..n).any(|i| {
+ let (a, b) = side(i);
+ (i + 2..n).filter(|&j| !(i == 0 && j == n - 1)).any(|j| {
+ let (c, d) = side(j);
+ turn(a, b, c) * turn(a, b, d) < 0.0 && turn(c, d, a) * turn(c, d, b) < 0.0
+ })
+ })
+}
+
+/// SolidCraft: the triangles of a simple polygon, as indices into its points, by clipping ears.
+/// `None` when no ear is left to clip (the polygon crosses itself) or it has no area.
+fn ear_clipping(points: &[[f64; 2]]) -> Option<Vec<[usize; 3]>> {
+ if points.len() < 3 {
+ return None;
+ }
+ let next = points.iter().cycle().skip(1);
+ let area2: f64 = points.iter().zip(next).map(|(p, q)| p[0] * q[1] - q[0] * p[1]).sum();
+ if area2 == 0.0 || crosses_itself(points) {
+ return None;
+ }
+ // Every turn of an ear, and of a point inside it, is on the polygon's own side.
+ let side = area2.signum();
+ let is_ear = |left: &[usize], k: usize| {
+ let m = left.len();
+ let corner = [left[(k + m - 1) % m], left[k], left[(k + 1) % m]];
+ let [a, b, c] = corner.map(|i| points[i]);
+ turn(a, b, c) * side > 0.0
+ && left.iter().filter(|q| !corner.contains(q)).all(|&q| {
+ let p = points[q];
+ [turn(a, b, p), turn(b, c, p), turn(c, a, p)].iter().any(|t| t * side < 0.0)
+ })
+ };
+ let mut left: Vec<usize> = (0..points.len()).collect();
+ let mut triangles = Vec::with_capacity(points.len() - 2);
+ while left.len() > 3 {
+ let m = left.len();
+ let k = (0..m).find(|&k| is_ear(&left, k))?;
+ triangles.push([left[(k + m - 1) % m], left[k], left[(k + 1) % m]]);
+ left.remove(k);
+ }
+ triangles.push([left[0], left[1], left[2]]);
+ Some(triangles)
+}
+
/// Inserts parameter divisions into triangulation.
fn insert_surface(
triangulation: &mut Cdt,
@@ -1550,3 +1670,17 @@ pub mod include_test_hooks {
assert!(matches!(n, Ok(n) if n > 100_000), "{n:?}");
}
}
+
+/// SolidCraft: the fallback that triangulates a face's boundary loop when the face has no
+/// triangle, for kernel tests (the vendored crates' own tests do not run in CI).
+///
+/// Not part of the API. Built only for tests, or with the `test-hooks` feature.
+#[cfg(any(test, feature = "test-hooks"))]
+#[doc(hidden)]
+pub mod loop_fill_test_hooks {
+ /// The triangles of a closed polygon, as indices into its points, or `None` when it has no
+ /// area, fewer than three points, or crosses itself.
+ pub fn ear_clipping(points: &[[f64; 2]]) -> Option<Vec<[usize; 3]>> {
+ super::ear_clipping(points)
+ }
+}