diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rs index 1cacb72b6..1ecbe4773 100644 --- a/crates/engine/src/boolean_regression_tests.rs +++ b/crates/engine/src/boolean_regression_tests.rs @@ -1032,3 +1032,62 @@ fn replay_value(script: &Value) -> Session { s.run_script(script).unwrap(); s } + +/// A revolved cylinder (r 24) with a sealed spherical void (r 2) on its axis, cut over its bottom +/// edge. The cut came out empty: refused for a box tool, and taken silently, the body gone, for a +/// large rotated box whose bounding box covers the target. Both keep the body and its void, and an +/// intersection with the box keeps the segment. +#[test] +fn cut_beside_a_sealed_void_keeps_the_body() { + use std::f64::consts::PI; + let r: f64 = 24.0; + // The circle's segment beyond a chord at `d` from the centre, and its integral over `d`. + let segment = |d: f64| r * r * (d / r).acos() - d * (r * r - d * d).sqrt(); + let wedge = |d: f64| r * r * (d * (d / r).acos() - (r * r - d * d).sqrt()) + (r * r - d * d).powf(1.5) / 3.0; + let sphere = 4.0 / 3.0 * PI * 8.0; + let combine = |z: [f64; 2], tool: &[(&str, Value)], operation: &str| { + let mut s = Session::default(); + s.execute("sketch.create", &json!({"plane": "YZ"})).unwrap(); + s.execute("sketch.rectangle.two_point", &json!({"p0": [0, z[0]], "p1": [r, z[1]]})).unwrap(); + s.execute("sketch.finish", &json!({})).unwrap(); + s.execute("solid.revolve", &json!({"axis": "y", "operation": "new", "body_name": "B"})).unwrap(); + let mid = (z[0] + z[1]) / 2.0; + s.execute("solid.sphere", &json!({"radius": 2, "center": [0, 0, mid], "operation": "new", "body_name": "V"})).unwrap(); + s.execute("solid.combine", &json!({"target": "B", "tools": ["V"], "operation": "cut"})).unwrap(); + for (command, params) in tool { + s.execute(command, params).unwrap(); + } + s.execute("solid.combine", &json!({"target": "B", "tools": ["K"], "operation": operation})).unwrap_or_else(|e| panic!("{e}")); + let state = s.model.state(); + let body = &state.body("B").unwrap().body; + assert_eq!(body.shell_count(), if operation == "cut" { 2 } else { 1 }); + assert!(body.validity().is_empty(), "{:?}", body.validity()); + // The revolved side's mesh stays 0.3 mm³ under its cylinder at any finer tolerance. + body.tessellate(1e-5).unwrap().measure().volume + }; + // A box over the bottom edge: the segment beyond x = 15, 5 high. + let edge_box = [("solid.box", json!({"length": 15, "width": 60, "height": 10, "corner": [15, -30, -5], "operation": "new", "body_name": "K"}))]; + let got = combine([0.0, 60.0], &edge_box, "cut"); + let want = PI * r * r * 60.0 - sphere - 5.0 * segment(15.0); + println!("box beside a void: {got:.6} mm³, expected {want:.6}"); + assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); + let got = combine([0.0, 60.0], &edge_box, "intersect"); + let want = 5.0 * segment(15.0); + println!("box beside a void, intersected: {got:.6} mm³, expected {want:.6}"); + assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); + // A 600 mm box rotated 45° about Y, its face on x - z = 116: the wedge beyond chords from + // x = 10 (z = -106) to x = 24 (z = -92). + let shift = (300.0 + 116.0 / 2f64.sqrt()) / 2f64.sqrt(); + let got = combine( + [-106.0, -43.5], + &[ + ("solid.box", json!({"length": 600, "width": 600, "height": 600, "center": [0, 0, 0], "operation": "new", "body_name": "K"})), + ("solid.move", json!({"bodies": ["K"], "axis": [0, 1, 0], "angle": -45})), + ("solid.move", json!({"bodies": ["K"], "translate": [shift, 0, -shift]})), + ], + "cut", + ); + let want = PI * r * r * 62.5 - sphere - (wedge(r) - wedge(10.0)); + println!("rotated box beside a void: {got:.6} mm³, expected {want:.6}"); + assert!((got - want).abs() < 1e-5 * want, "{got} vs {want}"); +} diff --git a/crates/kernel/src/offset.rs b/crates/kernel/src/offset.rs index b5ef68c79..264b82387 100644 --- a/crates/kernel/src/offset.rs +++ b/crates/kernel/src/offset.rs @@ -1090,6 +1090,13 @@ pub(crate) fn offset_body(b: &Body, shift: impl Fn(usize, Vec3) -> f64) -> Resul let (o, s, n) = pick(fs); let m2 = move_point(m, &o, &s, &n, size * 1e-6).ok_or_else(|| fail("an edge whose faces don't meet the same way after the move"))?; + // An arc turned round: its ends moved past its middle (next to a face it meets + // tangentially), so the arc through them goes the long way round its circle. + let (a0, c0, a1, c1) = + (from_p3(e.absolute_front().point()), from_p3(e.absolute_back().point()), from_p3(a.point()), from_p3(c.point())); + if (m - a0).cross(c0 - a0).dot((m2 - a1).cross(c1 - a1)) < 0.0 { + return Err(fail("not supported yet: the move is larger than a wall or step is thick (faces would cross)")); + } builder::circle_arc(a, c, p3(m2)) } }; diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.json index c6c7c32e8..1c882fbd0 100644 --- a/tests/robustness/goldens.json +++ b/tests/robustness/goldens.json @@ -1,7 +1,7 @@ { "about": "What each robustness seed builds (crates/engine/src/tests/robustness_goldens.rs, docs/robustness.md). Record changes with ROBUSTNESS_GOLDENS_BLESS=\"why\".", "seeds": { - "0": {"area":4785.573759,"bodies":1,"edges":78,"error":null,"faces":29,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","circular pattern","circular pattern","cut sphere","join cylinder","cut cylinder","fillet"],"unsupported":1,"volume":13461.708496}, + "0": {"area":4807.582879,"bodies":1,"edges":72,"error":null,"faces":27,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","circular pattern","circular pattern","cut sphere","join cylinder","cut cylinder","cut sphere"],"unsupported":0,"volume":13472.328916}, "1": {"area":2642.476583,"bodies":1,"edges":37,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","join cylinder"],"unsupported":0,"volume":6991.559261}, "2": {"area":2522.922626,"bodies":1,"edges":36,"error":"boolean Cut: the operation failed: no result","faces":14,"outcome":"failed","rejected":1,"shells":1,"steps":["box","cut cylinder","fillet","cut sphere","rectangular pattern"],"unsupported":2,"volume":5580.088497}, "3": {"area":6336.456143,"bodies":1,"edges":33,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box","hole","fillet","hole"],"unsupported":0,"volume":28037.146888}, @@ -46,7 +46,7 @@ "42": {"area":5486.877622,"bodies":1,"edges":51,"error":null,"faces":20,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut box","cut cylinder","rectangular pattern"],"unsupported":0,"volume":19095.106157}, "43": {"area":3492.988343,"bodies":1,"edges":72,"error":null,"faces":26,"outcome":"ok","rejected":2,"shells":1,"steps":["extruded profile","cut cylinder","rectangular pattern","fillet","hole","rectangular pattern","join cylinder"],"unsupported":1,"volume":7528.548742}, "44": {"area":7972.435566,"bodies":1,"edges":36,"error":null,"faces":15,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","shell","cut sphere"],"unsupported":0,"volume":7622.184366}, - "45": {"area":14203.130789,"bodies":1,"edges":60,"error":"boolean Union: implausible result volume ","faces":29,"outcome":"failed","rejected":0,"shells":3,"steps":["revolved section","join cylinder","fillet","shell","cut box","join box"],"unsupported":1,"volume":14081.565595}, + "45": {"area":14308.150092,"bodies":1,"edges":63,"error":"boolean Union: implausible result volume ","faces":30,"outcome":"failed","rejected":0,"shells":3,"steps":["revolved section","join cylinder","fillet","shell","hole","cut box","join box"],"unsupported":0,"volume":13544.638725}, "46": {"area":3445.162934,"bodies":1,"edges":99,"error":null,"faces":31,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","join cylinder","hole","cut cylinder","rectangular pattern","cut box","cut cylinder"],"unsupported":0,"volume":6232.317935}, "47": {"area":3098.575625,"bodies":1,"edges":42,"error":null,"faces":16,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","fillet","cut sphere","fillet"],"unsupported":0,"volume":8834.297438}, "48": {"area":9651.031297,"bodies":1,"edges":66,"error":null,"faces":28,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","hole","circular pattern","join box","shell","cut box"],"unsupported":2,"volume":7044.773463}, @@ -78,7 +78,7 @@ "74": {"area":9294.57311,"bodies":1,"edges":18,"error":null,"faces":9,"outcome":"ok","rejected":0,"shells":1,"steps":["box","hole"],"unsupported":0,"volume":55866.183074}, "75": {"area":7890.438301,"bodies":1,"edges":31,"error":null,"faces":13,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","chamfer","rectangular pattern","rectangular pattern","cut box"],"unsupported":0,"volume":38753.33959}, "76": {"area":853.668183,"bodies":1,"edges":32,"error":null,"faces":14,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","chamfer","cut cylinder"],"unsupported":1,"volume":1680.708844}, - "77": {"area":10824.299347,"bodies":1,"edges":60,"error":null,"faces":26,"outcome":"ok","rejected":3,"shells":1,"steps":["revolved section","fillet","cut cylinder","rectangular pattern","cut box","cut cylinder"],"unsupported":1,"volume":57744.413197}, + "77": {"area":9671.786688,"bodies":1,"edges":42,"error":null,"faces":19,"outcome":"ok","rejected":0,"shells":1,"steps":["revolved section","fillet","hole","circular pattern","rectangular pattern","circular pattern"],"unsupported":0,"volume":63910.630446}, "78": {"area":2423.235496,"bodies":1,"edges":34,"error":"offset: a corner whose faces don't meet the same way after t","faces":14,"outcome":"failed","rejected":0,"shells":1,"steps":["revolved section","cut cylinder","cut box","shell"],"unsupported":0,"volume":3707.429306}, "79": {"area":13585.252616,"bodies":1,"edges":27,"error":null,"faces":12,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut cylinder","join cylinder"],"unsupported":0,"volume":104810.763072}, "80": {"area":8652.533342,"bodies":1,"edges":20,"error":null,"faces":9,"outcome":"ok","rejected":0,"shells":1,"steps":["box","fillet","fillet"],"unsupported":0,"volume":37387.449469}, @@ -144,6 +144,7 @@ {"reason":"Reseam rotationally symmetric drill cutters after failed cuts (#2387): seed 86 now drills its hole, so its following pattern, shell and sphere cut complete with the fuzz validity and material checks.","seeds":[86]}, {"reason":"Rebase #2387 onto #2247: patterned pieces stay in one body. Seed 86 drills its hole, then reaches the same offset-corner shell refusal as main instead of shelling separate bodies. Completed steps still pass validity and volume-direction checks.","seeds":[86]}, {"reason":"A join whose coincident faces were pushed apart now trims the slab beyond the plane by editing faces when the boolean cut of it fails (a prism whose edge in the plane lies in the end face of a slab with rounded corners). Seed 70: the shell of a body in two lumps, refused before, now builds; its volume matches an independent offset of the profile (4120.90 vs 4120.67 mm3, the gap is the unshelled profile's own tessellation).","seeds":[70]}, - {"reason":"#1648: a face whose boundary touches itself within the tolerance is triangulated through the touching point instead of across the face, so faces that meshed with triangles missing or outside them now mesh whole. Seeds 20 and 55 build the same designs (same steps, faces, edges and shells); only the measured area, and for seed 55 the volume, of their final bodies move. Seed 55: replaying it with the old and the new triangulation gives the same final body; two curved faces measured 442.14 and 325.42 mm2 with the old triangulation at a fine tolerance, 436.29 and 305.83 mm2 with the new one, which agrees with their coarser meshes, and its volume moves from 24740.93 to 24744.18 mm3, against 24743.58 mm3 from a mesh at 1e-4 mm. Seed 20, as main now builds it, moves only in area, from 5726.92956 to 5727.102692 mm2 (3e-5 relative). Recorded from the fork CI output (Linux).","seeds":[20,55]} + {"reason":"#1648: a face whose boundary touches itself within the tolerance is triangulated through the touching point instead of across the face, so faces that meshed with triangles missing or outside them now mesh whole. Seeds 20 and 55 build the same designs (same steps, faces, edges and shells); only the measured area, and for seed 55 the volume, of their final bodies move. Seed 55: replaying it with the old and the new triangulation gives the same final body; two curved faces measured 442.14 and 325.42 mm2 with the old triangulation at a fine tolerance, 436.29 and 305.83 mm2 with the new one, which agrees with their coarser meshes, and its volume moves from 24740.93 to 24744.18 mm3, against 24743.58 mm3 from a mesh at 1e-4 mm. Seed 20, as main now builds it, moves only in area, from 5726.92956 to 5727.102692 mm2 (3e-5 relative). Recorded from the fork CI output (Linux).","seeds":[20,55]}, + {"reason":"A cut no longer comes out empty where a shell of one body meets nothing of the other (a sealed void, a body clear of the tool): truck placed such faces by their surfaces alone, which a turned body's reversed faces and a void's inward shell got wrong. Seeds 0, 45 and 77 each had a cut refused as empty that now takes what it should, and the generator builds different steps after it: seed 0 a sphere clear of the body (removes nothing), seed 45 a hole on the axis of a shelled turned body (widens its bore from r 2.5 to r 4 over 17.5 mm: 536.0 mm3), seed 77 a hole inside a turned body's bore (removes nothing; a later pattern copy drills r 1.5 through 27.5 mm: 194.4 mm3). Every step passes the validity and volume-direction checks.","seeds":[0,45,77]} ] } diff --git a/vendor/README.md b/vendor/README.md index 600e40be3..726783874 100644 --- a/vendor/README.md +++ b/vendor/README.md @@ -45,6 +45,12 @@ Changes: operand's shell meshes made beforehand (copied for each use, since the loops stores cut their edges): a large body cut down to the regions of many small ones is meshed once, which was most of each operation's time. +- `transversal/integrate/mod.rs`: in an AND, a face no intersection divides (a shell that meets + nothing of the other) is placed by the crossings of a ray with the other shell counted as each + face is oriented, not by its surface alone, and an inward shell (a void, a cut's inverted tool) + holds what lies outside it. Faces with reversed surfaces (a revolved body's) counted the wrong + way, and a void dropped every face outside it: a cut beside a sealed void came out empty or + with the body gone. An OR keeps truck's count. ## truck-geometry 0.5.0 (Apache-2.0, © RICOS Co. Ltd., https://github.com/ricosjp/truck) diff --git a/vendor/truck-shapeops/src/transversal/integrate/mod.rs b/vendor/truck-shapeops/src/transversal/integrate/mod.rs index d0f9c750b..3d9e4f796 100644 --- a/vendor/truck-shapeops/src/transversal/integrate/mod.rs +++ b/vendor/truck-shapeops/src/transversal/integrate/mod.rs @@ -61,12 +61,40 @@ pub fn meshes, S: ShapeOpsSurface>(solid: &Solid Option { + let mut volume = 0.0; + for face in shell.face_iter() { + let v = face.surface()?.volume(); + volume += if face.orientation() { v } else { -v }; + } + Some(volume < 0.0) +} + +/// SolidCraft: whether `pt` is inside the closed `shell`, by the faces a ray from it crosses. +/// For an AND (`and`) each face counts as it is oriented, and a shell facing inward (`inward`, +/// see [`faces_inward`]) holds what lies outside it: the crossings count 0 there and -1 inside. +/// An OR keeps truck's count, by the faces' surfaces alone: it folds a solid's voids in as if +/// they were solids of their own, which is no union with voids whichever way they are counted. +fn inside_shell(shell: &MeshedShell, pt: Point3, and: bool, inward: bool) -> Option { + let dir = hash::take_one_unit(pt); + let mut count = 0; + for face in shell.face_iter() { + let sign = if face.orientation() || !and { 1 } else { -1 }; + count += sign * face.surface()?.signed_crossing_faces(pt, dir); + } + Some(if inward { count >= 0 } else { count >= 1 }) +} + fn process_one_pair_of_shells, S: ShapeOpsSurface>( shell0: &Shell, meshed0: Option<&MeshedShell>, shell1: &Shell, tol: f64, lineage: &mut Lineage, + and: bool, ) -> Option<[Shell; 2]> { nonpositive_tolerance!(tol); // SolidCraft: robust meshing (boundaries from earlier operations lie on surfaces only @@ -86,15 +114,11 @@ fn process_one_pair_of_shells, S: ShapeOpsSurface>( let mut cls1 = crate::tr!(divide_face::divide_faces(shell1, &loops_store1, tol, lineage), "divide faces 1"); cls1.integrate_by_component(); let [mut and0, mut or0, unknown0] = cls0.and_or_unknown(); + let inward1 = and && !unknown0.is_empty() && faces_inward(&poly_shell1)?; unknown0.into_iter().try_for_each(|face| { // SolidCraft: no panics (wasm can't catch them). let pt = face.boundaries().first()?.vertex_iter().next()?.point(); - let dir = hash::take_one_unit(pt); - let count = poly_shell1.iter().try_fold(0, |count, face| { - let poly = face.surface()?; - Some(count + poly.signed_crossing_faces(pt, dir)) - })?; - if count >= 1 { + if inside_shell(&poly_shell1, pt, and, inward1)? { and0.push(face); } else { or0.push(face); @@ -102,15 +126,11 @@ fn process_one_pair_of_shells, S: ShapeOpsSurface>( Some(()) })?; let [mut and1, mut or1, unknown1] = cls1.and_or_unknown(); + let inward0 = and && !unknown1.is_empty() && faces_inward(&poly_shell0)?; unknown1.into_iter().try_for_each(|face| { // SolidCraft: no panics (wasm can't catch them). let pt = face.boundaries().first()?.vertex_iter().next()?.point(); - let dir = hash::take_one_unit(pt); - let count = poly_shell0.iter().try_fold(0, |count, face| { - let poly = face.surface()?; - Some(count + poly.signed_crossing_faces(pt, dir)) - })?; - if count >= 1 { + if inside_shell(&poly_shell0, pt, and, inward0)? { and1.push(face); } else { or1.push(face); @@ -128,7 +148,7 @@ pub fn and, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option> { - boolean(solid0, None, solid1, tol, |[and, _]| and).map(|(solid, _)| solid) + boolean(solid0, None, solid1, tol, true).map(|(solid, _)| solid) } /// OR operation between two solids. @@ -137,7 +157,7 @@ pub fn or, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option> { - boolean(solid0, None, solid1, tol, |[_, or]| or).map(|(solid, _)| solid) + boolean(solid0, None, solid1, tol, false).map(|(solid, _)| solid) } /// SolidCraft: AND operation between two solids, with where each face and edge of the result @@ -149,7 +169,7 @@ pub fn and_with_history, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option<(Solid, Option)> { - boolean(solid0, None, solid1, tol, |[and, _]| and) + boolean(solid0, None, solid1, tol, true) } /// SolidCraft: [`and_with_history`] with `solid0` meshed already ([`meshes`] of it, or of a @@ -160,7 +180,7 @@ pub fn and_with_history_meshed, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option<(Solid, Option)> { - boolean(solid0, Some(meshed0), solid1, tol, |[and, _]| and) + boolean(solid0, Some(meshed0), solid1, tol, true) } /// SolidCraft: OR operation between two solids, with where each face and edge of the result @@ -172,28 +192,29 @@ pub fn or_with_history, S: ShapeOpsSurface>( solid1: &Solid, tol: f64, ) -> Option<(Solid, Option)> { - boolean(solid0, None, solid1, tol, |[_, or]| or) + boolean(solid0, None, solid1, tol, false) } /// Combines the operands' first shells, then folds in their other shells one at a time -/// (`pick` chooses the AND or the OR shell of each pass). The history is `None` when a face or +/// (`and` chooses the AND or the OR shell of each pass). The history is `None` when a face or /// edge of the result was not recorded; the result stands without it. fn boolean, S: ShapeOpsSurface>( solid0: &Solid, meshed0: Option<&[MeshedShell]>, solid1: &Solid, tol: f64, - pick: fn([Shell; 2]) -> Shell, + and: bool, ) -> Option<(Solid, Option)> { + let pick = |[and_shell, or_shell]: [Shell; 2]| if and { and_shell } else { or_shell }; let mut lineage = Lineage::new([solid0, solid1]); let mut iter0 = solid0.boundaries().iter(); let mut iter1 = solid1.boundaries().iter(); let shell0 = iter0.next()?; let shell1 = iter1.next()?; let meshed0 = meshed0.filter(|m| m.len() == solid0.boundaries().len()).and_then(|m| m.first()); - let mut shell = pick(crate::tr!(process_one_pair_of_shells(shell0, meshed0, shell1, tol, &mut lineage), "first shells")); + let mut shell = pick(crate::tr!(process_one_pair_of_shells(shell0, meshed0, shell1, tol, &mut lineage, and), "first shells")); for other in iter0.chain(iter1) { - shell = pick(crate::tr!(process_one_pair_of_shells(&shell, None, other, tol, &mut lineage), "another shell")); + shell = pick(crate::tr!(process_one_pair_of_shells(&shell, None, other, tol, &mut lineage, and), "another shell")); } let solid = crate::tr!(Solid::try_new(components_in_order(&shell)).ok(), "result solid"); let history = lineage.history(&solid);