diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rs index 803b18bf8..e41355a75 100644 --- a/crates/doc/src/eval.rs +++ b/crates/doc/src/eval.rs @@ -3659,10 +3659,11 @@ pub fn hole_on_surface(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) -> /// The faces of the model near `p`: for each, how far `p` is from it, the outward normal there /// (the surface's own normal for planes, cylinders and spheres, turned the way the face looks out /// of its body; the nearest mesh facet's otherwise) and, for a plane, how far `p` is from the -/// plane itself. Only faces within `reach` of `p`, nearest first. -fn faces_through(st: &ModelState, p: Vec3, reach: f64) -> Vec<(f64, Vec3, Option)> { +/// plane itself. Only faces within `reach` of `p`, nearest first, of the bodies in `scope` +/// (every body when it is empty). +fn faces_through(st: &ModelState, p: Vec3, reach: f64, scope: &[String]) -> Vec<(f64, Vec3, Option)> { let mut out: Vec<(f64, Vec3, Option)> = Vec::new(); - for b in st.bodies.iter().filter(|b| !b.body.is_mesh()) { + for b in st.bodies.iter().filter(|b| !b.body.is_mesh() && in_hole_scope(scope, b)) { let m = b.mesh(); // The nearest facet of each face of this body. let mut near: BTreeMap = BTreeMap::new(); @@ -3708,13 +3709,29 @@ fn faces_through(st: &ModelState, p: Vec3, reach: f64) -> Vec<(f64, Vec3, Option out } +/// The faces near `p` a hole placed there goes by (as [`faces_through`]): those of the bodies in +/// `scope`, the hole's own, when one of them passes within `on` of `p`, else those of every body. +/// Where a plate's face touches another body both faces pass through `p`, and a hole that drills +/// the plate goes by the plate's face, never the other body's (#12066). A hole placed on another +/// body's face, to drill through it into its own body behind, still goes by that face. +fn hole_faces_through(st: &ModelState, p: Vec3, reach: f64, on: f64, scope: &[String]) -> Vec<(f64, Vec3, Option)> { + if !scope.is_empty() { + let own = faces_through(st, p, reach, scope); + if own.first().is_some_and(|(d, _, _)| *d <= on) { + return own; + } + } + faces_through(st, p, reach, &[]) +} + /// The way a hole placed at `p` drills: into the material, against the outward normal of the /// face `p` lies on. A point on no face (a planar face's centroid outside it, say) takes the /// nearest planar face whose plane it lies in, else the face nearest it within its body's pick -/// tolerance. None when no face is near. -pub fn hole_direction_at(st: &ModelState, p: Vec3) -> Option { +/// tolerance. None when no face is near. Where the faces of several bodies pass through `p`, those +/// of the bodies in `scope` (the bodies the hole drills; empty for every body) decide. +pub fn hole_direction_at(st: &ModelState, p: Vec3, scope: &[String]) -> Option { let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max); - let faces = faces_through(st, p, f64::INFINITY); + let faces = hole_faces_through(st, p, f64::INFINITY, size * 1e-4, scope); if let Some((d, n, _)) = faces.first() && *d <= size * 1e-4 { @@ -3731,10 +3748,13 @@ pub fn hole_direction_at(st: &ModelState, p: Vec3) -> Option { /// starts on (as designs saved before format 18 can say: their direction was taken from any face /// whose plane passed near the point, such as the other side of a thin plate or a face of another /// body at the same height), it is mirrored in the face it starts on, so it goes in at the same -/// angle. A direction that enters a face there, or a spot on no face, is kept. -fn hole_dir_into_face(st: &ModelState, p: Vec3, dir: Vec3) -> Vec3 { +/// angle. A direction that enters a face there, or a spot on no face, is kept. Where the faces of +/// the hole's own bodies (`scope`, see [`hole_drill_scope`]) pass through the spot, only they +/// count: a hole that names the plate it drills, saved with the direction into a body touching +/// the plate there, drills the plate (#12066). +fn hole_dir_into_face(st: &ModelState, p: Vec3, dir: Vec3, scope: &[String]) -> Vec3 { let size = st.bodies.iter().map(|b| b.body.size()).fold(1.0, f64::max); - let faces = faces_through(st, p, size * 1e-5); + let faces = hole_faces_through(st, p, size * 1e-5, size * 1e-5, scope); if faces.is_empty() || faces.iter().any(|(_, n, _)| n.dot(dir) < -1e-9) { return dir; } @@ -4353,6 +4373,13 @@ fn hole_scope(f: &Feature) -> &[String] { } } +/// The bodies whose faces decide which way a hole placed at a position drills, where they pass +/// through it: the bodies it cuts when it names them, so a body touching the face there can't +/// turn it round (#12066). Empty (every body) otherwise, and for `["*"]`. +fn hole_drill_scope(f: &Feature) -> &[String] { + if f.participants.iter().any(|b| b == "*") { &[] } else { &f.participants } +} + fn in_hole_scope(scope: &[String], b: &ModelBody) -> bool { scope.is_empty() || scope.contains(&b.name) } @@ -4378,7 +4405,7 @@ fn hole_spots(vals: &BTreeMap, st: &ModelState, f: &Feature) -> R let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; let at = hole_on_surface(st, single_hole_position(vals, st, position, at, points)?, dir, &[]); let at = with_references(vals, st, f, at, dir, true)?; - let dir = hole_dir_into_face(st, at, dir); + let dir = hole_dir_into_face(st, at, dir, hole_drill_scope(f)); return Ok((vec![hole_on_surface(st, at, dir, &[])], dir)); } }; @@ -4426,7 +4453,7 @@ fn hole_spots_raw(vals: &BTreeMap, st: &ModelState, f: &Feature) let dir = direction.normalized().ok_or_else(|| DocError::Invalid("hole direction".into()))?; let p = single_hole_position(vals, st, position, at, points)?; let p = if hole_references(f).is_empty() { p } else { with_references(vals, st, f, hole_on_surface(st, p, dir, &[]), dir, false)? }; - Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir, &[]), dir))) + Ok((vec![p], hole_dir_into_face(st, hole_on_surface(st, p, dir, &[]), dir, hole_drill_scope(f)))) } } } diff --git a/crates/doc/src/format/pending/hole-direction-own-faces.rs b/crates/doc/src/format/pending/hole-direction-own-faces.rs new file mode 100644 index 000000000..481269c22 --- /dev/null +++ b/crates/doc/src/format/pending/hole-direction-own-faces.rs @@ -0,0 +1,12 @@ +//! Nothing new is saved for holes, but a hole placed on a face that names the bodies it drills +//! (`participants`: its `targets`, or the body of another component it was picked on) now finds +//! the face it starts on among those bodies' faces, where one of them passes through its position +//! (#12066). Where another body touched that face at the hole, older designs could save a +//! `direction` taken from the other body's face, pointing out of the drilled body; such a hole cut +//! only a shallow pocket. It is now mirrored into the drilled body's face when the design is +//! evaluated, as format 18 does for a direction taken from the far side of a thin plate, and +//! drills through. Holes whose direction enters one of their own bodies' faces there, holes whose +//! own bodies have no face at their position (placed on another body's face to drill through it), +//! holes that name no bodies, and holes at several sketch points (already limited to their bodies, +//! #2882) build as before. No rewrite is needed. The last release refuses a design with this +//! change (the newer format number) instead of building the pocket again. diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index 68d44dc17..daab687ec 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -105,7 +105,7 @@ pub static COMMANDS: &[CommandSpec] = &[ .at("SOLID", "CREATE") .icon("hole") .key("H") - .params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole, drilled with the tap maker's tabulated drill: ISO metric (a custom metric size: major minus pitch), UNC/UNF, G, Rp, Rc 1/16 to 4, NPT 1/16 to 3; a `diameter` given with it chooses another drill, from the thread's minor diameter to 5% over the tap maker's) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); references?: [{edge: [x,y,z] on a straight edge of the face, distance: expr}] (at most two; the centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric position only); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?, bridge?: length (counterbore: two 3D-printing bridge layers this thick below its floor, a slot along X then a square; e.g. 0.2 mm); cs_diameter?, cs_angle?; thread?: \"M6\", \"1/4-20 UNC\", \"G 1/4\", \"Rp 1/4\", \"Rc 1/4\" or \"1/4-18 NPT\" (cosmetic unless modeled); hand?: right|left (the tapped thread's hand; default right; needs thread); thread_depth?: positive length independent of drill depth (default: full useful cylindrical wall; must fit that wall); modeled?: bool (needs thread: the tapped thread cut into the wall, the groove between its teeth, as solid.thread's modelled one; default false: listed only); ease_out?: expr|standard|short (modelled tapped threads: the inner end, towards the bottom, fades out over this length, ISO 3508's runout, standard 2.5 P, short 1.25 P; without it the groove stops square at thread_depth, or clear of a blind hole's bottom); targets?: [body] (the bodies to drill; holes at the points of a sketch on a body's face default to that body, found along the holes' direction on it alone; explicit targets or participants override, [\"*\"] every body)"), + .params("position: [x,y,z] on a face (numbers, or length expressions the hole follows) | sketch + points: [sketch point ids] (one hole each, perpendicular to the sketch, into the material on whichever side of the sketch plane it is) | sketch alone (every sketch point: standalone points and circle centres); flip?: bool (sketch points: drill to the other side); single?: bool (with one sketch point: a Single hole that follows the point, drilled into the face there); direction?: [x,y,z] (default: into the face, against its outward normal; where faces of several bodies meet there, the face of a body in `targets`; one that leaves the face is mirrored into it; ignored with sketch points unless single); diameter | thread (a tapped hole, drilled with the tap maker's tabulated drill: ISO metric (a custom metric size: major minus pitch), UNC/UNF, G, Rp, Rc 1/16 to 4, NPT 1/16 to 3; a `diameter` given with it chooses another drill, from the thread's minor diameter to 5% over the tap maker's) | clearance: \"M6\" with fit?: close|normal|loose (ISO 273); depth? (default through all) | to?: [x,y,z] (To Object: drill to that face or point); references?: [{edge: [x,y,z] on a straight edge of the face, distance: expr}] (at most two; the centre goes that far from each edge's line, in the face's plane, and follows the edges; with a numeric position only); type?: simple|drilled|counterbore|countersink; tip_angle?; cb_diameter?, cb_depth?, bridge?: length (counterbore: two 3D-printing bridge layers this thick below its floor, a slot along X then a square; e.g. 0.2 mm); cs_diameter?, cs_angle?; thread?: \"M6\", \"1/4-20 UNC\", \"G 1/4\", \"Rp 1/4\", \"Rc 1/4\" or \"1/4-18 NPT\" (cosmetic unless modeled); hand?: right|left (the tapped thread's hand; default right; needs thread); thread_depth?: positive length independent of drill depth (default: full useful cylindrical wall; must fit that wall); modeled?: bool (needs thread: the tapped thread cut into the wall, the groove between its teeth, as solid.thread's modelled one; default false: listed only); ease_out?: expr|standard|short (modelled tapped threads: the inner end, towards the bottom, fades out over this length, ISO 3508's runout, standard 2.5 P, short 1.25 P; without it the groove stops square at thread_depth, or clear of a blind hole's bottom); targets?: [body] (the bodies to drill; holes at the points of a sketch on a body's face default to that body, found along the holes' direction on it alone; explicit targets or participants override, [\"*\"] every body)"), CommandSpec::new("solid.pipe", "Pipe", crate::checked!("solid.pipe", pipe)) .at("SOLID", "CREATE") .icon("pipe") @@ -2827,9 +2827,16 @@ fn hole(s: &mut Session, p: &Value) -> Result { Some(d) => d.normalized().ok_or_else(|| bad(cmd, "`direction` must be non-zero"))?, None => { // Into the face the position lies on: against the outward normal of the face - // nearest it (planar or curved), as it faces out of its own body. + // nearest it (planar or curved), as it faces out of its own body. A hole that + // names the bodies it drills goes by the face of one of them where one passes + // through the position, never that of a body touching it there (#12066). + let named = match string_list(cmd, p, "participants")? { + v if v.is_empty() => string_list(cmd, p, "targets")?, + v => v, + }; + let scope: &[String] = if named.iter().any(|b| b == "*") { &[] } else { &named }; let st = s.model.state(); - solidcraft_doc::hole_direction_at(&st, position).ok_or_else(|| bad(cmd, "no face at `position`; give `direction`"))? + solidcraft_doc::hole_direction_at(&st, position, scope).ok_or_else(|| bad(cmd, "no face at `position`; give `direction`"))? } }, }; diff --git a/crates/engine/src/hole_face_tests.rs b/crates/engine/src/hole_face_tests.rs index 115bc8ca2..431d8109c 100644 --- a/crates/engine/src/hole_face_tests.rs +++ b/crates/engine/src/hole_face_tests.rs @@ -493,3 +493,86 @@ fn a_hole_wider_than_the_part_says_it_removes_all_of_it() { change(&mut s, "hd", "5 mm"); assert_eq!(said(&s, "H1"), ""); } + +/// The volume of one body. +fn body_volume(s: &mut Session, name: &str) -> f64 { + let m = run(s, "inspect.measure", json!({})); + let b = m["bodies"].as_array().unwrap().iter().find(|b| b["name"] == name).unwrap_or_else(|| panic!("no body {name}: {m}")); + b["volume_mm3"].as_f64().unwrap() +} + +/// A Block (x 0…20) made first, then a 3 mm Plate (x −3…0) whose front face touches the Block's +/// back face round (0, 30, 20). +fn plate_behind_block(s: &mut Session) { + run(s, "solid.box", json!({"length": 20, "width": 40, "height": 30, "corner": [0, 10, 5], "body_name": "Block", "operation": "new"})); + run(s, "solid.box", json!({"length": 3, "width": 60, "height": 40, "corner": [-3, 0, 0], "body_name": "Plate", "operation": "new"})); +} + +/// The Plate with a 3.4 mm hole through it at (y 30, z 20), and the Block untouched. +fn plate_drilled_through(s: &mut Session) { + near(body_volume(s, "Plate"), 7200.0 - pi() * 1.7 * 1.7 * 3.0); + near(body_volume(s, "Block"), 24_000.0); + assert!(!solid_at(s, -2.5, 30.0, 20.0), "the hole comes out of the Plate's back"); + assert!(solid_at(s, 0.5, 30.0, 20.0), "the Block is not drilled"); +} + +/// #12066: a hole on a face that another part touches there drills the part it names. Both faces +/// pass through the point, and the Block, made first, used to win: the hole drilled away from +/// the Plate and cut only a shallow pocket into it, without a word. +#[test] +fn a_hole_on_a_face_another_part_touches_drills_the_part_it_names() { + let mut s = Session::default(); + plate_behind_block(&mut s); + run(&mut s, "solid.hole", json!({"position": [0, 30, 20], "targets": ["Plate"], "diameter": 3.4, "name": "H"})); + assert!(hole_direction(&s, "H").x < -0.999, "drills along -X: {:?}", hole_direction(&s, "H")); + assert_eq!(said(&s, "H"), ""); + plate_drilled_through(&mut s); +} + +/// #12066: a design saved with that hole's direction pointing into the Block (as older builds +/// saved it) drills the Plate when it is opened: the direction is mirrored into the Plate's face, +/// as format 18 does for one taken from a thin plate's far side. +#[test] +fn a_saved_hole_turned_towards_a_touching_part_drills_its_own_part_when_opened() { + let mut s = Session::default(); + plate_behind_block(&mut s); + run(&mut s, "solid.hole", json!({"position": [0, 30, 20], "targets": ["Plate"], "diameter": 3.4, "name": "H"})); + let mut saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + let hole = saved["features"].as_array_mut().unwrap().iter_mut().find(|f| f["name"] == "H").unwrap(); + hole["direction"] = json!([1.0, 0.0, 0.0]); + let mut opened = Session::new(solidcraft_doc::Document::from_json(&saved.to_string()).unwrap()); + assert!((hole_direction(&opened, "H").x - 1.0).abs() < 1e-9, "the design keeps the direction it was saved with"); + assert_eq!(said(&opened, "H"), ""); + plate_drilled_through(&mut opened); +} + +fn hole_direction(s: &Session, name: &str) -> Vec3 { + match &s.doc.find_feature(name).unwrap().kind { + solidcraft_doc::FeatureKind::Hole { direction, .. } => direction.0, + other => panic!("{name} is not a hole: {}", other.type_name()), + } +} + +/// A hole placed on a Cover's top to drill the Base under it (`targets` leaves the Cover out) +/// still goes by the Cover's face, the only face there: it drills down through the Base, made +/// now or opened from a design that saved the direction up (as format 18 repairs). +#[test] +fn a_hole_placed_on_another_parts_face_drills_its_own_part_behind_it() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 10, "body_name": "Base"})); + run(&mut s, "solid.box", json!({"corner": [10, 10, 10], "length": 20, "width": 20, "height": 4, "body_name": "Cover", "operation": "new"})); + run(&mut s, "solid.hole", json!({"position": [20, 20, 14], "targets": ["Base"], "diameter": 5, "name": "H"})); + let drilled_base_only = |s: &mut Session| { + assert_eq!(said(s, "H"), ""); + near(body_volume(s, "Base"), 16_000.0 - pi() * 6.25 * 10.0); + near(body_volume(s, "Cover"), 1600.0); + }; + assert!(hole_direction(&s, "H").z < -0.999, "{:?}", hole_direction(&s, "H")); + drilled_base_only(&mut s); + let mut saved: Value = serde_json::from_str(&s.doc.to_json()).unwrap(); + let hole = saved["features"].as_array_mut().unwrap().iter_mut().find(|f| f["name"] == "H").unwrap(); + hole["direction"] = json!([0.0, 0.0, 1.0]); + let mut opened = Session::new(solidcraft_doc::Document::from_json(&saved.to_string()).unwrap()); + assert!(hole_direction(&opened, "H").z > 0.999); + drilled_base_only(&mut opened); +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 1bed89a68..4f05a5306 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -98,7 +98,7 @@ pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { } // A hole on a curved face drills against the face's normal where it was picked. Kind::Hole { .. } if matches!(first, Sel::Face { .. }) => { - (at, normal.or_else(|| solidcraft_engine::doc::hole_direction_at(&st, at).map(|d| -d))) + (at, normal.or_else(|| solidcraft_engine::doc::hole_direction_at(&st, at, &[]).map(|d| -d))) } // Holes at sketch points go into the part the sketch touches (or away, flipped): the // arrow shows which way. @@ -120,7 +120,7 @@ pub fn anchor(app: &SolveApp, d: &Dialog) -> Option<(Vec3, Option)> { (at, normal.or(dir.map(|d| -d))) } // A curved face offsets along its outward normal where it was picked. - Kind::OffsetFaces { .. } => (at, normal.or_else(|| solidcraft_engine::doc::hole_direction_at(&st, at).map(|d| -d))), + Kind::OffsetFaces { .. } => (at, normal.or_else(|| solidcraft_engine::doc::hole_direction_at(&st, at, &[]).map(|d| -d))), Kind::Section { .. } | Kind::OffsetPlane { .. } => (at, normal), // Fillet radii and chamfer distances grow the way `blend_grow_dir` gives (into the body // on an outside edge, into the open corner on an inside one); shell thickness grows into diff --git a/crates/ui-egui/src/hole_refs.rs b/crates/ui-egui/src/hole_refs.rs index 411198145..833517436 100644 --- a/crates/ui-egui/src/hole_refs.rs +++ b/crates/ui-egui/src/hole_refs.rs @@ -169,7 +169,7 @@ fn direction(s: &Session, d: &Dialog, at: Vec3) -> Option { if let Kind::Primitive { at: Some((_, normal)), .. } = &d.kind { return normal.map(|n| -n); } - d.extra.get("direction").and_then(vec3).or_else(|| solidcraft_engine::doc::hole_direction_at(&crate::open_meshing::session_world(s), at)) + d.extra.get("direction").and_then(vec3).or_else(|| solidcraft_engine::doc::hole_direction_at(&crate::open_meshing::session_world(s), at, &[])) } /// The face's frame at the place for the picked edges (and which reference inputs they are), found