From 30b01e8d796e4fbdc78a18f63fd91454b6a2d237 Mon Sep 17 00:00:00 2001 From: Artem Sushchev Date: Fri, 23 Oct 2026 22:53:42 +0000 Subject: [PATCH] A spherical shell revolves into a solid with a void, and cuts and joins with hollow tools work (#451) (#4182) --- crates/engine/src/boolean_regression_tests.rs | 48 +++++++++ crates/kernel/src/body.rs | 51 +++++---- crates/kernel/src/build.rs | 94 ++++++++++------ crates/kernel/src/face_source_tests.rs | 33 ++++++ crates/kernel/src/ops.rs | 100 ++++++++++++++++-- 5 files changed, 266 insertions(+), 60 deletions(-) diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index af5135924..f69fb1dd0 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -1298,3 +1298,51 @@ fn intersect_with_every_body_still_drops_the_ones_it_misses() -> crate::Result<( assert!((volume(&s, "Near") - 500.0).abs() < 1e-6); Ok(()) } + +/// #451: a spherical shell (r 18.5 to 40, revolved on XY) cut from a block, or joined with it. +/// Swept with its two radial lines, the shell had zero-area faces on the axis joining the outer +/// sphere to the inner one, and a cut through the inner sphere's pole failed. As a solid with a +/// void, the boolean took its shells one at a time: a cut through both spheres kept only the piece +/// in the hollow, and a join failed. +#[test] +fn spherical_shell_cuts_and_joins_a_block_crossing_its_hollow() { + let r: f64 = 18.5; + // ∫∫ √(R² − y² − z²) dy dz over the blocks' 8 × 8 section, the inner integral in closed form, + // the outer by Simpson's rule. + let under = |big: f64| { + let inner = |y: f64| { + let a2 = big * big - y * y; + let f = |z: f64| 0.5 * (z * (a2 - z * z).sqrt() + a2 * (z / a2.sqrt()).asin()); + f(4.0) - f(-4.0) + }; + let n = 200; + let h = 8.0 / n as f64; + (0..n / 2).map(|i| -4.0 + 2.0 * i as f64 * h).map(|y| inner(y) + 4.0 * inner(y + h) + inner(y + 2.0 * h)).sum::() * h / 3.0 + }; + // From x = 8 to the inner sphere, and from the outer sphere to x = 50. + let (hollow, beyond) = (under(r) - 8.0 * 64.0, 50.0 * 64.0 - under(40.0)); + let shell = 4.0 / 3.0 * std::f64::consts::PI * (40.0f64.powi(3) - r.powi(3)); + for (x0, length, operation, want) in [ + (-4.0, 8.0, "cut", 512.0), + (8.0, 12.0, "cut", hollow), + (8.0, 42.0, "cut", hollow + beyond), + (8.0, 12.0, "join", shell + hollow), + (8.0, 42.0, "join", shell + hollow + beyond), + ] { + let mut s = Session::default(); + let mut run = |c: &str, p: Value| s.execute(c, &p).unwrap(); + run("solid.box", json!({"corner": [x0, -4, -4], "length": length, "width": 8, "height": 8, "body_name": "Block"})); + run("sketch.create", json!({"plane": "XY", "name": "Ring"})); + run("sketch.line", json!({"points": [[-40, 0], [40, 0]]})); + run("sketch.arc.center_point", json!({"center": [0, 0], "start": [40, 0], "end": [-40, 0]})); + run("sketch.arc.center_point", json!({"center": [0, 0], "start": [r, 0], "end": [-r, 0]})); + run("sketch.finish", json!({})); + run("solid.revolve", json!({"sketch": "Ring", "profiles": [{"point": [0, 30]}], "axis": "l1", "operation": operation, "targets": ["Block"]})); + // A cut through both spheres leaves two pieces, one each side of the shell. + let state = s.model.state(); + let got: f64 = state.bodies.iter().map(|b| solidcraft_kernel::measure(&b.body).unwrap().volume).sum(); + println!("#451 {operation} of the block from x = {x0} to {}: {got:.6} mm³ in {} bodies, expected {want:.6}", x0 + length, state.bodies.len()); + assert!((got - want).abs() < 1e-4 * want, "{operation} from x = {x0} to {}: {got} vs {want}", x0 + length); + assert!(state.bodies.iter().all(|b| b.body.validity().is_empty())); + } +} diff --git a/crates/kernel/src/body.rs b/crates/kernel/src/body.rs index 81887545f..9ea0627e7 100644 --- a/crates/kernel/src/body.rs +++ b/crates/kernel/src/body.rs @@ -562,6 +562,36 @@ pub(crate) fn shell_volume(shell: &mt::Shell) -> Option { v.is_finite().then_some(v) } +/// A solid's volume off a mesh at `tol`, negative when it faces inwards, and how many faces that +/// mesh left out. +fn signed_volume(solid: &Solid, tol: f64) -> Result<(f64, usize)> { + let orient = |tol: f64| { + guard("orient", || { + let shells = mesh_shells(solid, tol); + let volume = shells.iter().map(|s| s.to_polygon().volume()).sum::(); + let missing = + shells.iter().flat_map(|s| s.face_iter()).filter(|f| f.surface().is_none_or(|m| m.faces().triangle_iter().next().is_none())).count(); + Ok((volume, missing)) + }) + }; + let (mut v, missing) = orient(tol)?; + // A long thin round part (a through hole's tool: a cylinder whose vertices all lie on + // its seam, so they span its length only) meshed that coarsely can come out with a + // negative volume when it is outward already: check finely before turning it inside out. + let fine = (tol * 0.02).max(1e-4); + if v < 0.0 && fine < tol { + (v, _) = orient(fine)?; + } + Ok((v, missing)) +} + +/// Whether a closed shell faces inwards (a void), by the check [`Body::new`] orients a solid by. +/// Unlike [`shell_volume`], a negative coarse volume is checked again on a finer mesh. +pub(crate) fn faces_inward(shell: &mt::Shell) -> Result { + let solid = guard("shell", || Solid::try_new(vec![shell.clone()]).map_err(|e| KernelError::Failed(format!("shell: {e}"))))?; + Ok(signed_volume(&solid, orientation_tolerance(span_of(&solid)))?.0 < 0.0) +} + /// Deflection the orientation mesh uses: coarse enough for a large solid, fine enough that a /// small one still tessellates. `unmeshed_faces` counts at the same value, so the count the /// orientation mesh produced is reused instead of meshing the body again. @@ -616,30 +646,11 @@ impl Body { // every face comes out: a face missing from a coarse mesh can flip the sign). let span = span_of(&solid); let tol = orientation_tolerance(span); - let orient = |tol: f64| { - guard("orient", || { - let shells = mesh_shells(&solid, tol); - let volume = shells.iter().map(|s| s.to_polygon().volume()).sum::(); - let missing = shells - .iter() - .flat_map(|s| s.face_iter()) - .filter(|f| f.surface().is_none_or(|m| m.faces().triangle_iter().next().is_none())) - .count(); - Ok((volume, missing)) - }) - }; #[cfg(test)] ORIENTED.with(|n| n.set(n.get() + 1)); // The faces missing from the coarse mesh are the same whichever way the solid turns out // to face, so the count is kept for `unmeshed_faces` either way. - let (mut v, missing) = orient(tol)?; - // A long thin round part (a through hole's tool: a cylinder whose vertices all lie on - // its seam, so they span its length only) meshed that coarsely can come out with a - // negative volume when it is outward already: check finely before turning it inside out. - let fine = (tol * 0.02).max(1e-4); - if v < 0.0 && fine < tol { - (v, _) = orient(fine)?; - } + let (v, missing) = signed_volume(&solid, tol)?; if v < 0.0 { solid.not(); } diff --git a/crates/kernel/src/build.rs b/crates/kernel/src/build.rs index 994a73ef8..6f3ce61d9 100644 --- a/crates/kernel/src/build.rs +++ b/crates/kernel/src/build.rs @@ -434,40 +434,9 @@ fn revolved(plane: &Plane, regions: &[Region2], axis_origin: Vec2, axis_dir: Vec }; let given = numbered_region(r)?.map_loops(|l| reseam(snap_loop(l).merged_lines(axis_run))); let r = &given.region(); - // A half disc on the axis revolved fully is a sphere: build it without poles. Every - // patch is swept from the half disc's arcs. if angle.abs() >= std::f64::consts::TAU - 1e-9 && r.holes.is_empty() - && let Some((c, rad)) = half_disc(&r.outer, axis_origin, d) - { - let arcs: Vec = r - .outer - .segs - .iter() - .enumerate() - .filter(|(_, s)| matches!(s, Seg2::Arc { .. })) - .flat_map(|(i, _)| given.outer.numbers(i).to_vec()) - .collect(); - out.push(sphere_solid(plane.to_world(c), rad, [Vec3::X, Vec3::Y, Vec3::Z], &arcs)?); - continue; - } - // A full turn of a profile that comes back to the axis along a curve (a half slot about - // its centreline, a dome at the far end): truck's cone gives the faces - // swept from it the wrong region (their pole is at the end of their curve), and cuts with - // such a body failed (#1853). It is built as part turns are, a third of a turn at a time. - if angle.abs() >= std::f64::consts::TAU - 1e-9 - && r.holes.is_empty() - && pole_at_end(&r.outer, axis_origin, d) - && let Some(b) = revolve_on_axis(plane, &given.outer, axis_origin, d, angle)? - { - out.push(b); - continue; - } - // A full revolution of a profile with one edge on the axis: sweep the rest of the loop - // as a cone-like shell (no zero-area faces, which booleans can't handle). - if angle.abs() >= std::f64::consts::TAU - 1e-9 - && r.holes.is_empty() - && let Some(b) = revolve_touching_axis(plane, &given.outer, axis_origin, d)? + && let Some(b) = full_turn_on_axis(plane, &given.outer, axis_origin, d, angle)? { out.push(b); continue; @@ -1407,6 +1376,67 @@ fn half_disc(lp: &Loop2, axis_origin: Vec2, d: Vec2) -> Option<(Vec2, f64)> { (same && (total - std::f64::consts::PI).abs() < 1e-6).then_some((c, r)) } +/// A full turn of a loop with edges on the axis, built without the zero-area faces truck sweeps +/// from them (booleans can't handle those). `None` when no builder here takes the loop. +fn full_turn_on_axis(plane: &Plane, nl: &NumberedLoop, axis_origin: Vec2, d: Vec2, angle: f64) -> Result> { + let lp = &nl.lp; + // A half disc on the axis revolved fully is a sphere: build it without poles. Every + // patch is swept from the half disc's arcs. + if let Some((c, rad)) = half_disc(lp, axis_origin, d) { + let arcs: Vec = + lp.segs.iter().enumerate().filter(|(_, s)| matches!(s, Seg2::Arc { .. })).flat_map(|(i, _)| nl.numbers(i).to_vec()).collect(); + return sphere_solid(plane.to_world(c), rad, [Vec3::X, Vec3::Y, Vec3::Z], &arcs).map(Some); + } + // A full turn of a profile that comes back to the axis along a curve (a half slot about + // its centreline, a dome at the far end): truck's cone gives the faces + // swept from it the wrong region (their pole is at the end of their curve), and cuts with + // such a body failed (#1853). It is built as part turns are, a third of a turn at a time. + if pole_at_end(lp, axis_origin, d) + && let Some(b) = revolve_on_axis(plane, nl, axis_origin, d, angle)? + { + return Ok(Some(b)); + } + // A full revolution of a profile with one edge on the axis: sweep the rest of the loop + // as a cone-like shell (no zero-area faces, which booleans can't handle). + if let Some(b) = revolve_touching_axis(plane, nl, axis_origin, d)? { + return Ok(Some(b)); + } + // Several edges on the axis (a spherical shell's two radial lines): each run of the loop + // from the axis back to it, closed along the axis, turns into a shell of its own, a solid + // where it runs the way the loop does and a void where it runs the other way. Swept whole, + // the edges on the axis became zero-area faces joining the shells, and a cut through a pole + // there failed (#451). + let on_axis = |s: &Seg2| matches!(*s, Seg2::Line { a, b } if d.cross(a - axis_origin).abs() < 1e-9 && d.cross(b - axis_origin).abs() < 1e-9); + let n = lp.segs.len(); + let axis_segs: Vec = (0..n).filter(|i| lp.segs.get(*i).is_some_and(on_axis)).collect(); + let [k0, _, ..] = axis_segs[..] else { return Ok(None) }; + let mut parts = Vec::new(); + for (i, &k) in axis_segs.iter().enumerate() { + let run: Vec = (k + 1..axis_segs.get(i + 1).copied().unwrap_or(k0 + n)).map(|j| j % n).collect(); + let mut segs: Vec = run.iter().filter_map(|j| lp.segs.get(*j).copied()).collect(); + let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return Ok(None) }; + segs.push(Seg2::Line { a: last.end(), b: first.start() }); + let sub = NumberedLoop { lp: Loop2 { segs }, from: run.iter().map(|j| nl.numbers(*j).to_vec()).chain([Vec::new()]).collect() }; + let void = sub.lp.is_ccw() != lp.is_ccw(); + let Some(b) = full_turn_on_axis(plane, &if void { sub.reversed() } else { sub }, axis_origin, d, angle)? else { return Ok(None) }; + parts.push((b, void)); + } + let faces: Option> = + parts.iter().map(|(b, _)| b.history().map(|h| h.faces.clone())).collect::>>().map(|f| f.concat()); + let solid = guard("revolve", || { + let mut shells = Vec::new(); + for (b, void) in &parts { + let mut s = b.solid.as_ref().clone(); + if *void { + s.not(); + } + shells.extend(s.boundaries().iter().cloned()); + } + Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("revolve: {e}"))) + })?; + record::attach(Body::new(solid)?, &[], faces, Default::default()).map(Some) +} + /// Whether the loop has one edge on the axis and comes back to it along a curve (the segment /// before the axis edge is not a line). A line there (a drill point) sweeps a cone, which /// truck's cone builds right. diff --git a/crates/kernel/src/face_source_tests.rs b/crates/kernel/src/face_source_tests.rs index 506b31086..59a1dd834 100644 --- a/crates/kernel/src/face_source_tests.rs +++ b/crates/kernel/src/face_source_tests.rs @@ -309,3 +309,36 @@ fn constructed_large_arc_split_and_reversal_preserve_one_source_segment() { } } } + +/// A certified block cut by, or joined with, a spherical shell (r 18.5 to 40) through both its +/// spheres: booleans with a tool that has a void (#451) keep the sources of the block's ends, +/// which they leave as they were. +#[test] +fn hollow_tool_booleans_keep_planar_support_certificates() { + use std::f64::consts::{PI, TAU}; + let ring = Region2 { + outer: Loop2 { + segs: vec![ + Seg2::Line { a: Vec2::new(18.5, 0.), b: Vec2::new(40., 0.) }, + Seg2::Arc { center: Vec2::ZERO, radius: 40., start: 0., sweep: PI }, + Seg2::Line { a: Vec2::new(-40., 0.), b: Vec2::new(-18.5, 0.) }, + Seg2::Arc { center: Vec2::ZERO, radius: 18.5, start: PI, sweep: -PI }, + ], + }, + holes: vec![], + }; + let shell = crate::revolve(&Plane::XY, &[ring], Vec2::ZERO, Vec2::X, TAU).unwrap().remove(0); + assert_eq!(shell.shell_count(), 2, "a solid with a void"); + let block = crate::box_solid(Vec3::new(8., -4., -4.), Vec3::new(50., 4., 4.)).unwrap().with_box_certificate(42).unwrap(); + for op in [crate::BoolOp::Cut, crate::BoolOp::Union] { + let r = crate::boolean(&block, &shell, op).unwrap().unwrap(); + let ends: Vec = (0..r.face_count()) + .filter(|i| { + matches!(r.face_sources().and_then(|s| s.get(*i)).and_then(Option::as_ref), Some(FaceSource::Box { producer: Some(42), axis: 0, .. })) + }) + .map(|i| r.planar_face(i).unwrap().origin.x) + .collect(); + assert!([8., 50.].iter().all(|x| ends.iter().any(|e| (e - x).abs() < 1e-9)), "{op:?}: {ends:?}"); + assert_exact_planes(&r); + } +} diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs index 49df105d7..37891c4ca 100644 --- a/crates/kernel/src/ops.rs +++ b/crates/kernel/src/ops.rs @@ -921,6 +921,9 @@ pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result> { } fn boolean_untimed(a: &Body, b: &Body, op: BoolOp) -> Result> { + if let Some(r) = with_hollow_tool(a, b, op) { + return finished(a, b, op, Ok(r)); + } // Earlier coarse bores can leave a junction a later pattern copy cannot intersect. // Resolve conical-cut junctions from the first copy, while the operands are unchanged. if op == BoolOp::Cut && !APART.with(|c| c.get()) && conical_cut_junction(a, b) { @@ -1008,14 +1011,7 @@ fn boolean_via(a: &Body, b: &Body, op: BoolOp, whole: &dyn Fn(&Body, &Body, Bool )), }; } - r = r.map(|result| result.map(|body| body.inherit_regularization_protection(a).inherit_regularization_protection(b))); - match op { - BoolOp::Cut => r = r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()), - BoolOp::Union => r = r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), - // Every face of an intersection lies on one operand's face, as a union's does: the same - // roles carry over (#565). - BoolOp::Intersect => r = r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), - } + r = finished(a, b, op, r); // A retry's result is held to what the operation can do at all; one that fails is refused // rather than returned wrong (issue #616). if (!diagnostics.events.is_empty() || diagnostics.truncated) @@ -1034,6 +1030,19 @@ fn boolean_via(a: &Body, b: &Body, op: BoolOp, whole: &dyn Fn(&Body, &Body, Bool r } +/// What a boolean's result keeps of its operands: their regularization protection, and the +/// sources of the planar faces it keeps. +fn finished(a: &Body, b: &Body, op: BoolOp, r: Result>) -> Result> { + let r = r.map(|result| result.map(|body| body.inherit_regularization_protection(a).inherit_regularization_protection(b))); + match op { + BoolOp::Cut => r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()), + BoolOp::Union => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), + // Every face of an intersection lies on one operand's face, as a union's does: the same + // roles carry over (#565). + BoolOp::Intersect => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()), + } +} + /// The most shells [`cut_around_voids`] takes apart. const MAX_VOID_SHELLS: usize = 64; @@ -1100,6 +1109,81 @@ fn cut_around_voids(a: &Body, b: &Body, whole: &dyn Fn(&Body, &Body, BoolOp) -> Ok(Some(guard("voids back", || Body::new(Solid::try_new(all).map_err(|e| KernelError::Failed(format!("voids back: {e}")))?))?)) } +/// A cut or union with `b` when `b` is one outer shell with sealed voids, from booleans with the +/// outer shell and with the solids the voids are: `a` cut by `b` is `a` cut by the outer shell +/// beside `a` within each void, and `a` joined with `b` is `a` joined with the outer shell, with +/// what of each void `a` does not fill as a void. truck takes a tool's shells one at a time, each +/// as if it were a body of its own, which is neither: such cuts came out empty, or kept only what +/// lies in the void (a block crossing both spheres of a spherical shell, #451). Planar tools are +/// left to the exact paths. `None` for other operations and tools, a void not inside the outer +/// shell, and a result that fails the membership samples the general way's results are held to +/// (a piece that failed or came out empty): the bodies then go the general way. +fn with_hollow_tool(a: &Body, b: &Body, op: BoolOp) -> Option> { + let shells = b.solid.boundaries(); + if op == BoolOp::Intersect || b.is_mesh() || shells.len() < 2 || shells.len() > MAX_VOID_SHELLS || is_planar(b) { + return None; + } + let (mut outer, mut voids) = (None, Vec::new()); + for sh in shells { + if crate::body::faces_inward(sh).ok()? { + voids.push(sh.clone()); + } else if outer.replace(sh.clone()).is_some() { + return None; + } + } + // Each shell a body of its own, a void turned outwards: the solid it holds. + let parts: Vec = std::iter::once(outer?) + .chain(voids) + .map(|sh| guard("hollow tool", || Body::new(Solid::try_new(vec![sh]).map_err(|e| KernelError::Failed(format!("hollow tool: {e}")))?))) + .collect::>() + .ok()?; + let t = a.size().max(b.size()) * 5e-4; + let (shell, holes) = parts.split_first()?; + let mesh = shell.tessellate(t).ok()?; + let inside = mesh.inside_index(); + if !holes.iter().all(|h| h.solid.vertex_iter().all(|v| inside.contains(from_p3(v.point())))) { + return None; + } + let r = by_outer_and_voids(a, b, parts, op).ok()?; + let mr = match &r { + Some(r) => r.tessellate_with(t, true).ok()?, + None => solidcraft_geom::Mesh::default(), + }; + mismatch(&a.tessellate_with(t, true).ok()?, &b.tessellate_with(t, true).ok()?, &mr, op).is_some_and(|f| f < 0.004).then_some(r) +} + +/// [`with_hollow_tool`]'s booleans, with `b` as its outer shell's solid, then its voids'. +fn by_outer_and_voids(a: &Body, b: &Body, parts: Vec, op: BoolOp) -> Result> { + let counts = record::counts(&[a, b]); + let traced: Vec = recorded::parts_of(&parts, b).into_iter().zip(parts).map(|(h, p)| (p, recorded::placed(h, 1, 2))).collect(); + let pair = |(x, hx): &Traced, (y, hy): &Traced, op: BoolOp| -> Result> { + Ok(boolean(x, y, op)?.map(|r| { + let h = recorded::of_pair(&r, hx, hy); + (r, h) + })) + }; + let a = (a.clone(), recorded::kept(a, 0, 2)); + let Some((shell, voids)) = traced.split_first() else { return Ok(None) }; + if op == BoolOp::Cut { + let mut pieces: Vec = pair(&a, shell, BoolOp::Cut)?.into_iter().collect(); + for v in voids { + pieces.extend(pair(&a, v, BoolOp::Intersect)?); + } + return recorded::join(pieces, &counts); + } + let Some(mut joined) = pair(&a, shell, BoolOp::Union)? else { return Ok(None) }; + // What of a void `a` leaves empty lies inside the outer shell, clear of the outside: a void again. + for v in voids { + if let Some((left, hl)) = pair(v, &a, BoolOp::Cut)? + && let Some(r) = void(&joined.0, &left, &record::counts(&[&joined.0, &left]))? + { + let h = recorded::of_pair(&r, &joined.1, &hl); + joined = (r, h); + } + } + Ok(Some(joined.0.with_checked_history(joined.1, &counts))) +} + /// Every face of an all-planar union must remain on an operand's original plane. /// Curved operands keep their existing surface-specific boolean handling. fn preserves_planar_surfaces(a: &Body, b: &Body, result: &Body) -> bool {