diff --git a/crates/engine/src/cmd/face.rs b/crates/engine/src/cmd/face.rs index baac95b5f..882d60d39 100644 --- a/crates/engine/src/cmd/face.rs +++ b/crates/engine/src/cmd/face.rs @@ -26,8 +26,7 @@ pub(super) fn face_normal(s: &Session, p: Vec3) -> Option { /// The outward normal of the planar face at `p` of `body` (any body when `None`). pub(super) fn face_normal_in(s: &Session, p: Vec3, body: Option<&str>) -> Option { let (m, f, d, _) = face_at_in(s, p, body).ok().flatten()?; - let tol = (m.bounds().diagonal() * 1e-3).max(1e-3); - if d > tol * 10.0 { + if !near_face(&m, d) { return None; } m.triangles @@ -38,11 +37,79 @@ pub(super) fn face_normal_in(s: &Session, p: Vec3, body: Option<&str>) -> Option .find_map(|[a, b, c]| (b - a).cross(c - a).normalized()) } +/// Is a face `d` from a point near enough to hold it: within a thousandth of the body's +/// size (at least 1 µm), ten times over, as picks placed on faces are taken. +fn near_face(m: &Mesh, d: f64) -> bool { + let tol = (m.bounds().diagonal() * 1e-3).max(1e-3); + d <= tol * 10.0 +} + +/// Does `p` lie on a face of a body (planar or curved), as features placed on a face need? +/// Where flush bodies' faces are equally near, it lies on each of them. A point in the opening +/// of a planar face (the mouth of an existing bore, which a counterbore is centred on) is on +/// that face too. +pub(super) fn on_a_face(s: &Session, p: Vec3) -> bool { + let on_one = match face_at_in(s, p, None) { + Ok(Some((m, _, d, _))) => near_face(&m, d), + Ok(None) => false, + Err(tied) => tied.first().is_some_and(|b| matches!(face_at_in(s, p, Some(b)), Ok(Some((m, _, d, _))) if near_face(&m, d))), + }; + on_one || s.model.state().bodies.iter().any(|b| in_a_planar_face_outline(&b.mesh(), p)) +} + +/// Does `p` lie in the plane of a planar face of `m`, inside the hull of that face's corners +/// (so over its openings, not past its edge)? +fn in_a_planar_face_outline(m: &Mesh, p: Vec3) -> bool { + let mut faces: std::collections::BTreeMap> = std::collections::BTreeMap::new(); + for (t, f) in m.triangles.iter().zip(&m.tri_face) { + if let Some(tri) = m.tri(t) { + faces.entry(*f).or_default().push(tri); + } + } + faces.values().any(|tris| { + let Some([a, b, c]) = tris.first().copied() else { return false }; + let Some(n) = (b - a).cross(c - a).normalized() else { return false }; + let planar = tris.iter().all(|[a, b, c]| (*b - *a).cross(*c - *a).normalized().is_some_and(|k| k.dot(n) > 1.0 - 1e-6)); + if !planar || !near_face(m, (p - a).dot(n).abs()) { + return false; + } + let reference = if n.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) }; + let Some(u) = n.cross(reference).normalized() else { return false }; + let v = n.cross(u); + let flat = |q: Vec3| (q.dot(u), q.dot(v)); + let mut corners: Vec<(f64, f64)> = tris.iter().flatten().map(|q| flat(*q)).collect(); + corners.sort_by(|x, y| x.partial_cmp(y).unwrap_or(std::cmp::Ordering::Equal)); + corners.dedup(); + inside_hull(&corners, flat(p)) + }) +} + +/// Is `q` inside (or on) the convex hull of `sorted` points (sorted by x, then y)? +fn inside_hull(sorted: &[(f64, f64)], q: (f64, f64)) -> bool { + let cross = |o: (f64, f64), a: (f64, f64), b: (f64, f64)| (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0); + let chain = |points: &mut dyn Iterator| { + let mut h: Vec<(f64, f64)> = Vec::new(); + for &pt in points { + while h.len() >= 2 && cross(h[h.len() - 2], h[h.len() - 1], pt) <= 0.0 { + h.pop(); + } + h.push(pt); + } + h + }; + let mut hull = chain(&mut sorted.iter()); + hull.pop(); + let mut upper = chain(&mut sorted.iter().rev()); + upper.pop(); + hull.extend(upper); + let eps = 1e-9; + hull.len() >= 3 && (0..hull.len()).all(|i| cross(hull[i], hull[(i + 1) % hull.len()], q) >= -eps) +} + /// Is the body face at `p` planar (`None`: no face there)? pub(super) fn face_is_planar(s: &Session, p: Vec3) -> Option { let (m, f, d, _) = face_at(s, p)?; - let tol = (m.bounds().diagonal() * 1e-3).max(1e-3); - if d > tol * 10.0 { + if !near_face(&m, d) { return None; } let ns: Vec = m diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rs index cf41441f9..c1ea4a5a7 100644 --- a/crates/engine/src/cmd/features.rs +++ b/crates/engine/src/cmd/features.rs @@ -2127,6 +2127,14 @@ fn hole(s: &mut Session, p: &Value) -> Result { (_, Some(x)) => x, (None, None) => return Err(bad(cmd, "`position` must be [x, y, z], numbers or length expressions (or give `sketch` and `points`)")), }; + // A hole starts on a face: a point off every face (past a body's edge) would drill a hole + // nobody picked, and cutting across an edge that way is slow. + if points.is_none() && !super::face::on_a_face(s, position) { + return Err(bad( + cmd, + format!("`position` [{}, {}, {}] is not on a face of a body; pick a point on the face to drill", position.x, position.y, position.z), + )); + } let direction = match (p.get("direction").and_then(vec3), &points) { (None, Some((sp, _, d))) if !sp.single => *d, (d, _) => match d { diff --git a/crates/engine/src/hole_face_tests.rs b/crates/engine/src/hole_face_tests.rs index 582a71253..6fe936d37 100644 --- a/crates/engine/src/hole_face_tests.rs +++ b/crates/engine/src/hole_face_tests.rs @@ -415,3 +415,38 @@ fn face_sketch_holes_through_all_stay_in_their_body_unless_targets_say_otherwise run(&mut s, "solid.hole", json!({"sketch": "Pts", "points": ["in"], "diameter": 5, "targets": ["Back"], "name": "H"})); assert!(solid_at(&s, 20.0, 20.0, 15.0) && !solid_at(&s, 20.0, 20.0, 3.0)); } + +/// A hole starts on a face: a position off every face (here 1 mm past the box's side) is +/// refused at once, instead of drilling where nobody picked; a point on the face still drills. +#[test] +fn a_hole_position_off_every_face_is_refused() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + let v0 = volume(&mut s); + let started = std::time::Instant::now(); + let hole = |x: f64| json!({"position": [x, 15, 20], "diameter": 8, "depth": 10, "type": "drilled", "tip_angle": 118}); + let e = s.execute("solid.hole", &hole(-1.0)).unwrap_err().to_string(); + assert!(e.contains("is not on a face of a body"), "{e}"); + assert!(started.elapsed().as_secs_f64() < 2.0, "refusing took {:?}", started.elapsed()); + // Above the top face, and given a direction: still not on a face. + let e = s.execute("solid.hole", &json!({"position": [20, 15, 25], "direction": [0, 0, -1], "diameter": 8})).unwrap_err().to_string(); + assert!(e.contains("is not on a face of a body"), "{e}"); + assert_eq!(volume(&mut s), v0, "the refused holes changed nothing"); + run(&mut s, "solid.hole", hole(20.0)); + assert!(volume(&mut s) < v0, "a hole on the face drills"); + assert!(!solid_at(&s, 20.0, 15.0, 15.0)); +} + +#[test] +fn a_hole_may_start_over_the_mouth_of_an_existing_bore() { + let mut s = Session::default(); + run(&mut s, "solid.box", json!({"length": 40, "width": 30, "height": 20})); + run(&mut s, "solid.hole", json!({"position": [20, 15, 20], "diameter": 8, "depth": 10, "type": "drilled", "tip_angle": 118})); + // A counterbore centred on the bore starts in its mouth, which is in the top face's plane. + let v1 = volume(&mut s); + run(&mut s, "solid.hole", json!({"position": [20, 15, 20], "diameter": 12, "depth": 3, "type": "drilled", "tip_angle": 118})); + assert!(volume(&mut s) < v1, "the wider hole cuts round the bore"); + // Past the face's edge is still off the face. + let e = s.execute("solid.hole", &json!({"position": [-1, 15, 20], "diameter": 8})).unwrap_err().to_string(); + assert!(e.contains("is not on a face of a body"), "{e}"); +}