Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

Strict catches single-shell self-intersection; inward extrude is a pocket; tube path cleanup (issue #24)

finalpantasyb0debf810666
diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rs
index d7f5aba..39683b0 100644
--- a/crates/forma-core/src/boolean.rs
+++ b/crates/forma-core/src/boolean.rs
@@ -1770,43 +1770,82 @@ pub fn boolean_op(
}
/// Safety net against a boolean that silently returns operand A untouched (or nothing) although
-/// B measurably penetrates A. Only runs when the result looks unchanged, so it is free otherwise.
+/// the geometry contradicts it. Only runs when the result looks unchanged or empty, so it is
+/// free otherwise.
fn silent_noop_reason(a: &PolyMesh, b: &PolyMesh, op: BoolOp, res: &PolyMesh) -> Option<String> {
- let unchanged = match op {
- BoolOp::Difference | BoolOp::Union => {
- res.verts.len() == a.verts.len() && res.faces.len() <= a.faces.len().max(1) * 2 && {
- let (va, vr) = (a.signed_volume(), res.signed_volume());
- (va - vr).abs() <= 1e-12 * va.abs()
- }
- }
- BoolOp::Intersect => res.faces.is_empty(),
- };
- if !unchanged || a.faces.is_empty() || b.faces.is_empty() {
+ if a.faces.is_empty() || b.faces.is_empty() {
return None;
}
- let (bb_a, bb_b) = (a.aabb(), b.aabb());
- if !bb_a.is_valid() || !bb_b.is_valid() || b.signed_volume().abs() <= 0.0 {
+ if res.faces.is_empty() {
+ return match op {
+ // Everything removed: wrong if some of A lies measurably outside B.
+ BoolOp::Difference => surface_sample_decisive(b, a, false).map(|_| {
+ "cut: removed the whole part although it extends outside the cutter (boolean failed; rescale or split the operation)".to_string()
+ }),
+ BoolOp::Intersect => surface_sample_decisive(a, b, true).map(|ratio| {
+ format!("intersect: returned nothing although the operands overlap (size ratio {ratio:.1e} is beyond what the boolean tolerance resolves; rescale or split the operation)")
+ }),
+ BoolOp::Union => None,
+ };
+ }
+ let unchanged = !matches!(op, BoolOp::Intersect)
+ && res.verts.len() == a.verts.len()
+ && res.faces.len() <= a.faces.len().max(1) * 2
+ && {
+ let (va, vr) = (a.signed_volume(), res.signed_volume());
+ (va - vr).abs() <= 1e-12 * va.abs()
+ };
+ if !unchanged {
return None;
}
- let sb = bb_b.size();
- let b_max = sb.x.max(sb.y).max(sb.z);
- if !(b_max > 0.0) || !b_max.is_finite() {
+ // For cut the evidence is a point of B well inside A; for union, well outside A.
+ let want_inside = matches!(op, BoolOp::Difference);
+ let ratio = surface_sample_decisive(a, b, want_inside)?;
+ let (name, what) = if want_inside {
+ ("cut", "removed no material although the cutter penetrates the part")
+ } else {
+ ("add", "added nothing although the tool extends outside the part")
+ };
+ Some(format!(
+ "{name}: {what} (part/tool size ratio {ratio:.1e} is beyond what the boolean tolerance resolves; rescale or split the operation)"
+ ))
+}
+
+/// Looks for a surface sample of `probe` (vertices and face centroids) that is decisively inside
+/// (`want_inside`) or outside `container`: on the wanted side and at least 0.1% of the probe's
+/// thinnest dimension away from the container's surface, so touching or coincident surfaces
+/// never count. Returns the container/probe size ratio when such a sample exists.
+fn surface_sample_decisive(container: &PolyMesh, probe: &PolyMesh, want_inside: bool) -> Option<f64> {
+ let (bb_c, bb_p) = (container.aabb(), probe.aabb());
+ if !bb_c.is_valid() || !bb_p.is_valid() || probe.signed_volume().abs() <= 0.0 || container.signed_volume().abs() <= 0.0 {
+ return None;
+ }
+ let sp = bb_p.size();
+ let p_max = sp.x.max(sp.y).max(sp.z);
+ if !(p_max > 0.0) || !p_max.is_finite() {
return None;
}
- let mut b_min = b_max;
- for d in [sb.x, sb.y, sb.z] {
- if d > b_max * 1e-12 && d < b_min {
- b_min = d;
+ let mut p_min = p_max;
+ for d in [sp.x, sp.y, sp.z] {
+ if d > p_max * 1e-12 && d < p_min {
+ p_min = d;
}
}
- // Work in B-sized coordinates so the ray tolerances are small against the cutter.
- let c = bb_b.center();
- let inv = 1.0 / b_min;
+ // Work in probe-sized coordinates so the ray tolerances are small against the probe.
+ let c = bb_p.center();
+ let inv = 1.0 / p_min;
let to_local = |p: Vec3| (p - c) * inv;
- let mut tris: Vec<Tri> = Vec::with_capacity(a.faces.len() * 2);
- for fi in 0..a.faces.len() {
- for [i, j, k] in a.triangulate_face(fi) {
- if let Some(t) = Tri::from_verts(to_local(a.verts[i]), to_local(a.verts[j]), to_local(a.verts[k]), 0, 0, 0) {
+ let mut tris: Vec<Tri> = Vec::with_capacity(container.faces.len() * 2);
+ for fi in 0..container.faces.len() {
+ for [i, j, k] in container.triangulate_face(fi) {
+ if let Some(t) = Tri::from_verts(
+ to_local(container.verts[i]),
+ to_local(container.verts[j]),
+ to_local(container.verts[k]),
+ 0,
+ 0,
+ 0,
+ ) {
tris.push(t);
}
}
@@ -1814,26 +1853,19 @@ fn silent_noop_reason(a: &PolyMesh, b: &PolyMesh, op: BoolOp, res: &PolyMesh) ->
let bvh = TriBvh::build(&tris);
let delta = 1e-3;
let mut near: Vec<u32> = Vec::new();
- // For cut/intersect the evidence is a B vertex well inside A; for union, well outside A.
- let want_inside = !matches!(op, BoolOp::Union);
- // Sample B's surface: vertices plus face centroids (a long cutter can have every vertex
- // outside the part while its walls pass straight through it).
- let v_stride = (b.verts.len() / 48).max(1);
- let f_stride = (b.faces.len() / 48).max(1);
- let samples = b
+ let v_stride = (probe.verts.len() / 48).max(1);
+ let f_stride = (probe.faces.len() / 48).max(1);
+ let samples = probe
.verts
.iter()
.step_by(v_stride)
.copied()
- .chain((0..b.faces.len()).step_by(f_stride).map(|fi| b.face_centroid(fi)));
- let mut evidence = false;
+ .chain((0..probe.faces.len()).step_by(f_stride).map(|fi| probe.face_centroid(fi)));
for p in samples {
if !p.is_finite() {
continue;
}
let q = to_local(p);
- // Decisive only when the sample is on the wanted side of A and at least `delta` away
- // from A's surface (coincident or touching surfaces are legitimate no-ops).
if bvh.point_inside(&tris, q) != want_inside {
continue;
}
@@ -1843,23 +1875,11 @@ fn silent_noop_reason(a: &PolyMesh, b: &PolyMesh, op: BoolOp, res: &PolyMesh) ->
(crate::spatial::closest_pt_on_tri(q, t.v[0], t.v[1], t.v[2]) - q).len_sq() > delta * delta
});
if clear {
- evidence = true;
- break;
+ let sc = bb_c.size();
+ return Some(sc.x.max(sc.y).max(sc.z) / p_min);
}
}
- if !evidence {
- return None;
- }
- let sa = bb_a.size();
- let ratio = sa.x.max(sa.y).max(sa.z) / b_min;
- let (name, what) = match op {
- BoolOp::Difference => ("cut", "removed no material although the cutter penetrates the part"),
- BoolOp::Union => ("add", "added nothing although the tool extends outside the part"),
- BoolOp::Intersect => ("intersect", "returned nothing although the operands overlap"),
- };
- Some(format!(
- "{name}: {what} (part/tool size ratio {ratio:.1e} is beyond what the boolean tolerance resolves; rescale or split the operation)"
- ))
+ None
}
fn boolean_op_unchecked(
@@ -1963,6 +1983,12 @@ fn boolean_op_unchecked(
if bad0 == 0 && !res.faces.is_empty() {
return Ok(unnormalize(res));
}
+ // A clean empty result is a real answer for cut/intersect (the tool swallows the part, or the
+ // operands only touch). Perturbing the tool here would leave a zero-thickness skin behind.
+ // `silent_noop_reason` separately rejects an empty result that the geometry contradicts.
+ if bad0 == 0 && res.faces.is_empty() && !matches!(op, BoolOp::Union) {
+ return Ok(res);
+ }
// Deterministic perturbation retry on grazing curved seams (only reached when exact pass has bad/unoriented edges)
let perturbations = [
@@ -1987,6 +2013,18 @@ fn boolean_op_unchecked(
let (cand, _) = run_bvh_csg(a_ref, &bp, op, tag_str.as_deref(), op_id);
let bad = count_bad_or_unoriented_edges(&cand);
if bad == 0 && !cand.faces.is_empty() {
+ // The tool was nudged by up to ~1e-4 of its size. A cut/intersect result no thicker
+ // than that nudge is the nudge itself (coincident or merely touching operands), not
+ // geometry: the true result is empty.
+ if !matches!(op, BoolOp::Union) {
+ let area: f64 = (0..cand.faces.len()).map(|fi| cand.face_area(fi)).sum();
+ let bs = bp.aabb().size();
+ let b_ext = bs.x.max(bs.y).max(bs.z);
+ let thickness = 2.0 * cand.signed_volume().abs() / area.max(1e-300);
+ if thickness < 5e-4 * b_ext + 1e-4 {
+ return Ok(PolyMesh::new());
+ }
+ }
return Ok(unnormalize(cand));
}
if bad < best_bad {
@@ -2564,12 +2602,38 @@ fn overlap_pass(
/// Checks every pair of non-adjacent triangles (sharing zero vertex indices and no coincident
/// vertex coordinates) whose AABBs overlap, returning `true` if any pair crosses or overlaps in 3D.
pub fn has_self_intersections(mesh: &PolyMesh) -> bool {
+ check_self_intersections(mesh, u64::MAX) == OverlapCheck::Overlap
+}
+
+/// Candidate triangle-pair visits the strict/observe self-intersection check may spend.
+pub const SELF_INTERSECTION_BUDGET: u64 = 40_000_000;
+
+/// `has_self_intersections` with a work budget (candidate triangle pairs visited). Returns
+/// `Unverified` when the budget runs out before the mesh could be cleared.
+pub fn check_self_intersections(mesh: &PolyMesh, budget: u64) -> OverlapCheck {
+ // World axes first; thin diagonal geometry that defeats axis-aligned boxes gets a second
+ // pass in the mesh's dominant edge frame before the check gives up.
+ let first = self_intersection_pass(mesh, None, budget.min(OVERLAP_WORLD_BUDGET));
+ if first != OverlapCheck::Unverified || budget <= OVERLAP_WORLD_BUDGET {
+ return first;
+ }
+ self_intersection_pass(mesh, Some(dominant_edge_frame(mesh)), budget)
+}
+
+fn self_intersection_pass(mesh: &PolyMesh, frame: Option<[Vec3; 3]>, budget: u64) -> OverlapCheck {
+ let mut work: u64 = 0;
+ let xf = |p: Vec3| -> Vec3 {
+ match &frame {
+ Some(f) => Vec3::new(p.dot(f[0]), p.dot(f[1]), p.dot(f[2])),
+ None => p,
+ }
+ };
if mesh.faces.len() < 2 {
- return false;
+ return OverlapCheck::Clear;
}
let bb = mesh.aabb();
if !bb.is_valid() {
- return false;
+ return OverlapCheck::Clear;
}
let mesh_scale = bb.size().x.max(bb.size().y).max(bb.size().z).max(1e-9);
let aabb_eps = 1e-6 * mesh_scale;
@@ -2582,7 +2646,7 @@ pub fn has_self_intersections(mesh: &PolyMesh) -> bool {
if a == b || b == c || c == a {
continue;
}
- if let Some(t) = Tri::from_verts(mesh.verts[a], mesh.verts[b], mesh.verts[c], 0, 0, 0) {
+ if let Some(t) = Tri::from_verts(xf(mesh.verts[a]), xf(mesh.verts[b]), xf(mesh.verts[c]), 0, 0, 0) {
tris.push(t);
tri_v.push([a, b, c]);
}
@@ -2590,7 +2654,7 @@ pub fn has_self_intersections(mesh: &PolyMesh) -> bool {
}
let nt = tris.len();
if nt < 2 {
- return false;
+ return OverlapCheck::Clear;
}
let bvh = TriBvh::build(&tris);
let mut hits: Vec<u32> = Vec::with_capacity(32);
@@ -2599,6 +2663,10 @@ pub fn has_self_intersections(mesh: &PolyMesh) -> bool {
let vi = tri_v[i];
let ti = &tris[i];
bvh.query_aabb(&ti.aabb, aabb_eps, &mut hits);
+ work = work.saturating_add(hits.len() as u64 + 1);
+ if work > budget {
+ return OverlapCheck::Unverified;
+ }
for &j_u32 in &hits {
let j = j_u32 as usize;
if j <= i {
@@ -2627,9 +2695,9 @@ pub fn has_self_intersections(mesh: &PolyMesh) -> bool {
continue;
}
if tris_overlap_3d(ti, tj, mesh_scale) {
- return true;
+ return OverlapCheck::Overlap;
}
}
}
- false
+ OverlapCheck::Clear
}
diff --git a/crates/forma-core/src/ops.rs b/crates/forma-core/src/ops.rs
index cd3e35c..92d7674 100644
--- a/crates/forma-core/src/ops.rs
+++ b/crates/forma-core/src/ops.rs
@@ -37,6 +37,20 @@ pub fn extrude_faces(
return Err("extrude: selected faces have zero average normal".into());
}
let offset = avg_normal * dist;
+ if !offset.is_finite() {
+ return Err(format!("extrude: distance must be finite (got {dist})"));
+ }
+
+ // Inward extrusion (offset against the selected faces' own normals) cannot be built by
+ // stitching walls: they would fold back through the solid and the moved cap would pass
+ // through it. It is a pocket: subtract the swept prism from the part instead.
+ let mut own_normal = Vec3::ZERO;
+ for &fi in &selected {
+ own_normal = own_normal + mesh.face_normal(fi) * mesh.face_area(fi);
+ }
+ if offset.dot(own_normal) < 0.0 {
+ return extrude_inward_pocket(mesh, &selected, offset, dist, op_id);
+ }
let mut out = mesh.clone();
// Collect boundary directed edges of the selected region
@@ -86,6 +100,68 @@ pub fn extrude_faces(
Ok(out)
}
+/// Inward `extrude`: removes the prism swept by the selected faces along `offset`.
+fn extrude_inward_pocket(
+ mesh: &PolyMesh,
+ selected: &HashSet<usize>,
+ offset: Vec3,
+ dist: f64,
+ op_id: u32,
+) -> Result<PolyMesh, String> {
+ let mut sel_sorted: Vec<usize> = selected.iter().copied().collect();
+ sel_sorted.sort_unstable();
+ let mut tool = PolyMesh::new();
+ let mut top: HashMap<usize, usize> = HashMap::new();
+ let mut bot: HashMap<usize, usize> = HashMap::new();
+ let mut dir_edges: HashSet<(usize, usize)> = HashSet::new();
+ for &fi in &sel_sorted {
+ let fv = &mesh.faces[fi].verts;
+ let n = fv.len();
+ for i in 0..n {
+ let v = fv[i];
+ if !top.contains_key(&v) {
+ let t = tool.add_vert(mesh.verts[v]);
+ let b = tool.add_vert(mesh.verts[v] + offset);
+ top.insert(v, t);
+ bot.insert(v, b);
+ }
+ dir_edges.insert((v, fv[(i + 1) % n]));
+ }
+ }
+ for &fi in &sel_sorted {
+ let fv = &mesh.faces[fi].verts;
+ let up: SmallVec<[usize; 4]> = fv.iter().map(|v| top[v]).collect();
+ let down: SmallVec<[usize; 4]> = fv.iter().rev().map(|v| bot[v]).collect();
+ tool.add_face(up, op_id, None);
+ tool.add_face(down, op_id, None);
+ }
+ let mut walls: Vec<(usize, usize)> = dir_edges.iter().copied().filter(|&(u, v)| !dir_edges.contains(&(v, u))).collect();
+ walls.sort_unstable();
+ for (u, v) in walls {
+ tool.add_face(smallvec![top[&v], top[&u], bot[&u], bot[&v]], op_id, None);
+ }
+ let tool_vol = tool.signed_volume();
+ if !tool_vol.is_finite() || tool_vol.abs() < 1e-300 {
+ return Err(format!("extrude: distance {dist} sweeps no volume (selected faces are parallel to the extrusion direction)"));
+ }
+ if tool_vol < 0.0 {
+ tool.flip_winding();
+ }
+ let mut out = crate::boolean::boolean_op(mesh, &tool, crate::boolean::BoolOp::Difference, Some("extrude"), op_id)
+ .map_err(|e| format!("extrude: inward distance {dist} could not be cut as a pocket ({e})"))?;
+ if out.faces.is_empty() {
+ return Err(format!("extrude: inward distance {dist} pushes the selected faces through the whole part (nothing would remain)"));
+ }
+ let dir = offset.normalized();
+ for fi in 0..out.faces.len() {
+ if out.faces[fi].has_tag("bool:extrude") {
+ let tag = if out.face_normal(fi).dot(dir) < -0.5 { "cap" } else { "wall" };
+ out.faces[fi].add_tag(tag);
+ }
+ }
+ Ok(out)
+}
+
/// Inset each selected face toward its centroid by `amount` (metric distance clamped safely),
/// optionally offsetting the inner face along its normal by `depth`.
pub fn inset_faces(
diff --git a/crates/forma-core/src/primitives.rs b/crates/forma-core/src/primitives.rs
index 74b4d93..c29bbd1 100644
--- a/crates/forma-core/src/primitives.rs
+++ b/crates/forma-core/src/primitives.rs
@@ -289,6 +289,30 @@ pub fn make_tube(points: &[Vec3], radius: f64, ring_segs: usize, closed: bool, o
if points.len() > 256 {
return Err("tube path exceeds maximum of 256 points".into());
}
+ if let Some(bad) = points.iter().position(|p| !p.is_finite()) {
+ return Err(format!("tube: path point {bad} is not finite"));
+ }
+ // Repeated consecutive points carry no direction and would stack two rings on one spot;
+ // a path that returns to its first point is a closed loop (no caps), not two overlapping ends.
+ let same_tol_sq = (radius * 1e-6).powi(2);
+ let mut cleaned: Vec<Vec3> = Vec::with_capacity(points.len());
+ for &p in points {
+ if cleaned.last().map_or(true, |q| (p - *q).len_sq() > same_tol_sq) {
+ cleaned.push(p);
+ }
+ }
+ let mut closed = closed;
+ if cleaned.len() >= 3 && (cleaned[0] - cleaned[cleaned.len() - 1]).len_sq() <= same_tol_sq {
+ cleaned.pop();
+ closed = true;
+ }
+ if cleaned.len() < 2 || (closed && cleaned.len() < 3) {
+ return Err(format!(
+ "tube: path has only {} distinct point(s) after removing repeats (need 2, or 3 for a closed loop)",
+ cleaned.len()
+ ));
+ }
+ let points: &[Vec3] = &cleaned;
let ring_segs = ring_segs.clamp(6, 64);
let n = points.len();
let mut tangents = Vec::with_capacity(n);
@@ -365,6 +389,11 @@ pub fn make_tube(points: &[Vec3], radius: f64, ring_segs: usize, closed: bool, o
m.add_face(end_cap, op_id, Some("cap_end"));
}
m.ensure_outward_winding();
+ if crate::boolean::has_self_intersections(&m) {
+ return Err(format!(
+ "tube: sweep self-intersects (the path folds back or turns tighter than radius {radius} allows; widen the turn or reduce r)"
+ ));
+ }
Ok(m)
}
diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rs
index 6cc89cc..e7b6f4c 100644
--- a/crates/forma-core/src/scene.rs
+++ b/crates/forma-core/src/scene.rs
@@ -250,6 +250,12 @@ impl Scene {
inv = MeshInvariants::compute(&mesh);
}
if self.strict_manifold {
+ if mesh.faces.is_empty() {
+ return Err(SceneError::InvariantViolation {
+ part: name,
+ reason: "empty result: no geometry is left (for cut/intersect the tool contains the part, the operands do not overlap, or what remains is thinner than the boolean tolerance)".into(),
+ });
+ }
if !inv.watertight || !inv.consistent_winding || inv.non_manifold_edges > 0 || inv.nan_verts > 0 {
return Err(SceneError::InvariantViolation {
part: name,
@@ -292,6 +298,21 @@ impl Scene {
),
});
}
+ match crate::boolean::check_self_intersections(&mesh, crate::boolean::SELF_INTERSECTION_BUDGET) {
+ crate::boolean::OverlapCheck::Clear => {}
+ crate::boolean::OverlapCheck::Overlap => {
+ return Err(SceneError::InvariantViolation {
+ part: name,
+ reason: "self-intersecting surface (faces of one shell pass through each other)".into(),
+ });
+ }
+ crate::boolean::OverlapCheck::Unverified => {
+ return Err(SceneError::InvariantViolation {
+ part: name,
+ reason: "self-intersection check exceeded its work budget (mesh too dense to verify; simplify or run without --strict)".into(),
+ });
+ }
+ }
}
self.last_modified = Some(name.clone());
self.parts.insert(name, Arc::new(mesh));
@@ -582,6 +603,18 @@ impl Scene {
inv.components
));
}
+ if overlap == crate::boolean::OverlapCheck::Clear {
+ match crate::boolean::check_self_intersections(mesh, crate::boolean::SELF_INTERSECTION_BUDGET) {
+ crate::boolean::OverlapCheck::Clear => {}
+ crate::boolean::OverlapCheck::Overlap => {
+ all_manifold = false;
+ warnings.push(format!("part '{name}' has a self-intersecting surface (faces pass through each other)"));
+ }
+ crate::boolean::OverlapCheck::Unverified => {
+ warnings.push(format!("part '{name}': self-intersection check skipped, work budget exceeded"));
+ }
+ }
+ }
if inv.degenerate_faces > 0 {
warnings.push(format!("part '{name}' has {} micro-sliver faces", inv.degenerate_faces));
}
diff --git a/crates/forma-core/tests/issue_regressions.rs b/crates/forma-core/tests/issue_regressions.rs
index b5fa8a4..9351e47 100644
--- a/crates/forma-core/tests/issue_regressions.rs
+++ b/crates/forma-core/tests/issue_regressions.rs
@@ -194,3 +194,117 @@ fn issue23_unresolvable_ratio_fails_loudly_never_silently() {
}
}
}
+
+// ---------------------------------------------------------------------------------------------
+// Issue #24: strict missed single-shell self-intersection (negative extrude, tube paths).
+// ---------------------------------------------------------------------------------------------
+
+#[test]
+fn issue24_strict_rejects_single_shell_self_intersection() {
+ use forma_core::boolean::has_self_intersections;
+ // One closed, consistently wound shell whose corner is dragged through the opposite faces.
+ let mut m = forma_core::primitives::make_box(2.0, 2.0, 2.0, 1);
+ let corner = m
+ .verts
+ .iter()
+ .position(|v| v.x > 0.0 && v.y > 0.0 && v.z > 0.0)
+ .unwrap();
+ m.verts[corner] = Vec3::new(-3.0, -3.0, -0.2);
+ let inv = MeshInvariants::compute(&m);
+ assert!(inv.watertight && inv.non_manifold_edges == 0 && inv.components == 1);
+ assert!(has_self_intersections(&m));
+
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ let err = s.set_part("p", m.clone()).expect_err("strict must reject a self-intersecting shell").to_string();
+ assert!(err.contains("self-intersecting"), "{err}");
+
+ // Non-strict keeps the part but must warn.
+ let mut loose = Scene::new();
+ loose.strict_manifold = false;
+ loose.set_part("p", m).unwrap();
+ let obs = loose.observe(0.0, None);
+ assert!(obs.warnings.iter().any(|w| w.contains("self-intersecting")), "{:?}", obs.warnings);
+}
+
+#[test]
+fn issue24_negative_extrude_cuts_a_pocket_instead_of_folding_walls() {
+ use forma_core::boolean::has_self_intersections;
+ use forma_core::selector::FaceSelector;
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ s.add_box("p", 2.0, 2.0, 1.0, Vec3::ZERO).unwrap();
+ let inv = s.extrude("p", &FaceSelector::Top, -0.5, None).expect("push the top face down by 0.5");
+ assert!((inv.volume - 2.0).abs() < 1e-6, "vol {}", inv.volume);
+ assert!((inv.bbox_max[2] - 0.0).abs() < 1e-9, "top must now sit at z=0, got {}", inv.bbox_max[2]);
+ assert!((inv.bbox_min[2] + 0.5).abs() < 1e-9);
+ assert!(!has_self_intersections(s.get_part("p").unwrap()));
+
+ // Past the opposite face nothing would remain: a named error, never a folded solid.
+ let mut s2 = Scene::new();
+ s2.strict_manifold = true;
+ s2.add_box("p", 2.0, 2.0, 1.0, Vec3::ZERO).unwrap();
+ let err = s2.extrude("p", &FaceSelector::Top, -2.0, None).expect_err("extrude through the part").to_string();
+ assert!(err.contains("extrude") && err.contains("-2"), "{err}");
+
+ // Same rule without strict: the kernel op itself refuses.
+ let b = forma_core::primitives::make_box(2.0, 2.0, 1.0, 1);
+ assert!(forma_core::ops::extrude_faces(&b, &FaceSelector::Top, -2.0, None, 2).is_err());
+ let pocket = forma_core::ops::extrude_faces(&b, &FaceSelector::Top, -0.25, None, 2).unwrap();
+ assert!(!has_self_intersections(&pocket));
+ assert!((pocket.signed_volume() - 3.0).abs() < 1e-6);
+}
+
+#[test]
+fn issue24_tube_repeated_closing_and_foldback_paths() {
+ use forma_core::boolean::has_self_intersections;
+ use forma_core::primitives::make_tube;
+ let p = |x: f64, y: f64| Vec3::new(x, y, 0.0);
+ // Repeated point: same solid as the path without it.
+ let dup = make_tube(&[p(0.0, 0.0), p(1.0, 0.0), p(1.0, 0.0), p(1.0, 1.0)], 0.1, 12, false, 1).unwrap();
+ let plain = make_tube(&[p(0.0, 0.0), p(1.0, 0.0), p(1.0, 1.0)], 0.1, 12, false, 1).unwrap();
+ assert_eq!(dup.verts.len(), plain.verts.len());
+ assert!(!has_self_intersections(&dup));
+ // End == start: a closed loop without caps (genus 1), not two overlapping end caps.
+ let ring = make_tube(&[p(0.0, 0.0), p(1.0, 0.0), p(1.0, 1.0), p(0.0, 0.0)], 0.1, 12, false, 1).unwrap();
+ let inv = MeshInvariants::compute(&ring);
+ assert!(inv.watertight && inv.genus == 1, "closed loop must be a torus-like shell: {inv:?}");
+ assert!(!has_self_intersections(&ring));
+ // Fold-back tighter than the radius: named error.
+ let err = make_tube(&[p(0.0, 0.0), p(1.0, 0.0), p(0.0, 0.05)], 0.2, 12, false, 1).unwrap_err();
+ assert!(err.starts_with("tube:") && err.contains("self-intersects"), "{err}");
+ // All points identical.
+ assert!(make_tube(&[p(1.0, 1.0), p(1.0, 1.0), p(1.0, 1.0)], 0.1, 12, false, 1).is_err());
+ // Controls stay valid.
+ for path in [
+ vec![p(0.0, 0.0), p(1.0, 0.0), p(2.0, 1.0)],
+ vec![p(0.0, 0.0), p(2.0, 0.0)],
+ vec![p(0.0, 0.0), p(1.0, 0.0), p(1.0, 1.0), p(0.0, 1.0)],
+ ] {
+ let t = make_tube(&path, 0.1, 12, false, 1).unwrap();
+ assert!(!has_self_intersections(&t));
+ }
+}
+
+// New bug found while fixing #24: a cut or intersect whose true result is empty returned the
+// perturbation skin (a watertight zero-thickness shell) and strict accepted it.
+#[test]
+fn hunt_cut_or_intersect_with_empty_true_result_never_returns_a_skin() {
+ use forma_core::boolean::{boolean_op, BoolOp};
+ let a = forma_core::primitives::make_box(2.0, 2.0, 2.0, 1);
+ let same = boolean_op(&a, &a.clone(), BoolOp::Difference, None, 2).unwrap();
+ assert!(same.faces.is_empty(), "box minus itself is empty, got {} faces", same.faces.len());
+ let bigger = forma_core::primitives::make_box(3.0, 3.0, 3.0, 1);
+ assert!(boolean_op(&a, &bigger, BoolOp::Difference, None, 2).unwrap().faces.is_empty());
+ let mut touching = a.clone();
+ touching.translate(Vec3::new(2.0, 0.0, 0.0));
+ let t = boolean_op(&a, &touching, BoolOp::Intersect, None, 2).unwrap();
+ assert!(t.faces.is_empty(), "face-touching boxes share no volume, got {} faces", t.faces.len());
+
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ s.add_box("a", 2.0, 2.0, 2.0, Vec3::ZERO).unwrap();
+ s.add_box("b", 2.0, 2.0, 2.0, Vec3::ZERO).unwrap();
+ let err = s.boolean_parts("a", "b", BoolOp::Difference, true).expect_err("empty cut").to_string();
+ assert!(err.contains("empty result"), "{err}");
+}