//! Edge fillets and chamfers. SMLib blends exactly the picked edges in one call //! ([`crate::blend_smlib`]): the blend faces, the corners where blends meet (a sphere, a patch, a //! bevel or a mitre, as its fillet corners choose) and the end faces rebuilt round them. A blend //! whose contact lines would leave the faces it rolls on is SMLib's refusal, reported as //! [`KernelError::TooLarge`]. A tangent chain is the caller's to select ([`tangent_chain`]). //! //! The helpers here read a body's schema 4 record: planar faces' outward normals, the direction //! into a face across an edge, an edge's tangent at its ends. use std::collections::BTreeSet; use solidcraft_geom::Vec3; use solidcraft_geom::brep::eval::{CurveEval, SurfaceEval}; use solidcraft_geom::brep::{Brep, Curve, Loop, OrientedEdge, Shell, Surface}; use crate::body::Body; use crate::{KernelError, Result}; pub(crate) fn unsupported(msg: &str) -> KernelError { KernelError::Failed(format!("not supported yet: {msg}")) } /// A blend too large for the faces around it. pub(crate) fn too_large(msg: &str) -> KernelError { KernelError::TooLarge(msg.into()) } fn v3(p: [f64; 3]) -> Vec3 { Vec3::new(p[0], p[1], p[2]) } /// A body's record as the blends' checks read it: the record and each face's side in its shell. pub(crate) struct Faces { pub(crate) rec: Brep, /// Whether each face's outward normal is its surface's natural normal (`None`: in no face shell). forward: Vec>, } impl Faces { pub(crate) fn of(body: &Body) -> Result { let rec = crate::native::brep_record(body)?; let mut forward = vec![None; rec.faces.len()]; for sh in &rec.shells { if let Shell::Faces { faces, .. } = sh { for f in faces { if let Some(slot) = forward.get_mut(f.face as usize) { *slot = Some(f.forward); } } } } Ok(Faces { rec, forward }) } pub(crate) fn point(&self, v: u32) -> Option { self.rec.vertices.get(v as usize).map(|v| v3(v.point)).filter(|p| p.is_finite()) } /// The points of the edge's start and end vertices. pub(crate) fn ends(&self, e: usize) -> Option<(Vec3, Vec3)> { let [a, b] = self.rec.edges.get(e)?.vertices; Some((self.point(a)?, self.point(b)?)) } /// Whether the edge's curve is a straight line. pub(crate) fn straight(&self, e: usize) -> bool { self.rec.edges.get(e).is_some_and(|x| matches!(x.curve, Curve::Line { .. })) } /// The unit natural normal of a planar face's surface. fn natural_plane_normal(&self, f: usize) -> Option { let (du, dv) = match &self.rec.faces.get(f)?.surface { Surface::Plane { u_axis, v_axis, .. } => (v3(*u_axis), v3(*v_axis)), Surface::PlaneThrough { origin, u_point, v_point } => (v3(*u_point) - v3(*origin), v3(*v_point) - v3(*origin)), _ => return None, }; du.cross(dv).normalized().filter(|n| n.is_finite()) } /// The side of the face in its shell: 1 where its outward normal is its surface's natural one. fn side(&self, f: usize) -> Option { self.forward.get(f).copied().flatten().map(|fw| if fw { 1.0 } else { -1.0 }) } /// The outward unit normal of a planar face, if planar. pub(crate) fn plane_normal(&self, f: usize) -> Option { Some(self.natural_plane_normal(f)? * self.side(f)?) } /// The outward unit normal of face `f` at `p` (a point within `accept` of its surface). pub(crate) fn normal_at(&self, f: usize, p: Vec3, accept: f64) -> Option { let s = SurfaceEval::new(self.rec.faces.get(f)?.parameters()).ok()?; let uv = s.project(p, None, accept)?; let (_, su, sv) = s.derivs(uv[0], uv[1])?; Some(su.cross(sv).normalized()? * self.side(f)?) } /// Every edge use in the face's loops. pub(crate) fn uses(&self, f: usize) -> impl Iterator { self.rec.faces.get(f).into_iter().flat_map(|face| face.loops.iter()).flat_map(|l| match l { Loop::Edges { edges } => edges.as_slice(), Loop::Vertex { .. } => &[], }) } /// The faces that use the edge, each once. pub(crate) fn faces_of(&self, e: usize) -> BTreeSet { self.rec.edges.get(e).map(|x| x.uses.iter().map(|u| u.face).collect()).unwrap_or_default() } /// The unit direction into planar face `f` across the straight edge of `u`, square to the /// edge: the face lies to the left of its loop seen from its surface's natural normal. pub(crate) fn direction_into_face(&self, f: usize, u: &OrientedEdge) -> Option { let (a, b) = self.ends(u.edge as usize)?; let dir = if u.forward { b - a } else { a - b }; self.natural_plane_normal(f)?.cross(dir.normalized()?).normalized() } /// The edge's unit tangent along its interval (start to end vertex) at its start or end. pub(crate) fn tangent(&self, e: usize, at_end: bool) -> Option { let edge = self.rec.edges.get(e)?; curve_tangent(edge.parameters(), if at_end { edge.interval[1] } else { edge.interval[0] }) } } /// The unit tangent of a record curve at `t`, along increasing `t`. pub(crate) fn curve_tangent(c: &Curve, t: f64) -> Option { curve_derivative(c, t)?.normalized().filter(|d| d.is_finite()) } /// The first derivative of a record curve at `t` (of an intersection curve: its unit tangent). pub(crate) fn curve_derivative(c: &Curve, t: f64) -> Option { if !t.is_finite() { return None; } let d = match c { Curve::Line { start, end } => v3(*end) - v3(*start), Curve::Circle { frame, radius } => { let (s, co) = t.sin_cos(); (v3(frame.y_axis) * co - v3(frame.x_axis) * s) * *radius } Curve::Ellipse { frame, radii } => { let (s, co) = t.sin_cos(); v3(frame.y_axis) * (radii[1] * co) - v3(frame.x_axis) * (radii[0] * s) } Curve::Polyline { points } => { let last = points.len().checked_sub(2)?; let i = (t.max(0.0).floor() as usize).min(last); v3(*points.get(i + 1)?) - v3(*points.get(i)?) } Curve::Spline { .. } | Curve::RationalSpline { .. } => match CurveEval::new(c).ok()? { CurveEval::Spline(s) => s.eval(t)?.1, _ => return None, }, Curve::SurfaceIntersection { surfaces, leader, .. } => { // Along both surfaces: square to both normals, on the leader's side. let p = CurveEval::new(c).ok()?.point(t)?; let normal = |s: &Surface| -> Option { let e = SurfaceEval::new(s).ok()?; let uv = e.project(p, None, f64::INFINITY)?; let (_, su, sv) = e.derivs(uv[0], uv[1])?; Some(su.cross(sv)) }; let along = normal(&surfaces[0])?.cross(normal(&surfaces[1])?); let along = along.normalized()?; if along.dot(curve_tangent(leader, t)?) < 0.0 { along * -1.0 } else { along } } }; d.is_finite().then_some(d) } /// Curvature-continuous (G2) fillets: each section is SMLib's G2 blend curve between the contact /// lines the round of `radius` has (zero curvature at the contacts on planar faces), not a /// circle. A configuration SMLib cannot blend so is refused, never given a circular round. pub fn fillet_g2(body: &Body, edges: &[Vec3], radius: f64) -> Result { let _span = solidcraft_profile::span("kernel", "fillet_g2"); body.require_brep("G2 fillet")?; if !(radius.is_finite() && radius > 1e-6 && radius < 1e6) { return Err(KernelError::Invalid("G2 fillet size must be positive and finite".into())); } if edges.is_empty() || edges.len() > 1000 || edges.iter().any(|p| ![p.x, p.y, p.z].into_iter().all(f64::is_finite)) { return Err(KernelError::Invalid("G2 fillet needs 1 to 1000 finite edge points".into())); } let out = crate::blend_smlib::fillet_g2(body, edges, radius)?; closed(body, out) } /// A fillet's result, refused when a face's boundary crosses itself (#871): rounds that /// overlap where a wall is thinner than both leave such faces, which the topology checks /// don't see but which show as holes in the model. A fillet either closes the solid or is /// refused. Faces of `input` that crossed already and that the fillet carried over unchanged /// (a sliver an earlier boolean left far from the rounds, #1488) are not the fillet's doing. fn closed(input: &Body, b: Body) -> Result { let after = b.crossed_faces()?; if after.is_empty() { return Ok(b); } let before = input.crossed_faces()?; let tol = (input.size().max(b.size()) * 1e-6).max(1e-9); match after.iter().filter(|p| !before.iter().any(|q| q.dist(**p) <= tol)).count() { 0 => Ok(b), _ => Err(KernelError::Failed( "fillet: the rounds would leave openings in the surface (they overlap where a wall or a face is narrower than both)".into(), )), } } /// Constant-radius fillet of the edges nearest to the given points. A radius too large for the /// faces around the edges is refused with [`KernelError::TooLarge`] ([`fillet_max`] finds the /// largest that works). pub fn fillet(body: &Body, edges: &[Vec3], radius: f64) -> Result { let _span = solidcraft_profile::span("kernel", "fillet"); body.require_brep("fillet")?; crate::blend_smlib::fillet(body, edges, radius).and_then(|b| closed(body, b)) } /// [`fillet`] with corner setbacks: each `(at, distance)` sets back the corner at the vertex /// nearest `at`, a vertex where every edge is rounded, so its patch starts `distance` along /// each of its edges from the vertex (one distance for all of a corner's edges: SMLib keeps one /// per corner). The rounds run whole up to their sections there, and the patch between them /// meets each face in a curve from one round's contact line to the next. The distance must reach /// past where the rounds would meet without it (past the radius at a square corner); a corner /// where some edge is not rounded is refused as not supported, a setback as long as an edge at /// its corner as too large. pub fn fillet_setback(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result { let _span = solidcraft_profile::span("kernel", "fillet_setback"); body.require_brep("fillet")?; setbacks_reach(body, edges, radius, setbacks)?; crate::blend_smlib::fillet_setback(body, edges, radius, setbacks).and_then(|b| closed(body, b)) } /// Refuses a setback that does not reach past where its corner's rounds meet without one /// ([`setback_minimum`]), naming the least it must exceed, at a corner where every edge is one /// of `edges` (the others are SMLib's to refuse). SMLib fails there with its own status /// (smlib_blend_setback): its patch does not join contact lines that already cross. fn setbacks_reach(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result<()> { let faces = Faces::of(body)?; let (picked, _) = crate::blend_smlib::picked_edges(body, edges)?; let picked: BTreeSet = picked.into_iter().collect(); for (at, distance) in setbacks { let Some(v) = corner_vertex(body, &faces, *at) else { continue }; let all_rounded = (0..faces.rec.edges.len()) .filter(|e| faces.rec.edges.get(*e).is_some_and(|x| !x.uses.is_empty() && x.vertices.contains(&v))) .all(|e| picked.contains(&e)); if !all_rounded { continue; } let Some(least) = setback_minimum(&faces, v, radius) else { continue }; if *distance <= least * (1.0 + 1e-9) { let p = faces.point(v).unwrap_or(*at); let shown = format!("{:.4}", least).trim_end_matches('0').trim_end_matches('.').to_string(); let why = if (least - radius).abs() <= radius * 1e-9 { format!("more than the radius ({shown} mm)") } else { format!("more than {shown} mm") }; return Err(KernelError::Invalid(format!( "the setback must be {why} at the corner ({:.3}, {:.3}, {:.3}): the rounds' contact lines meet {shown} mm from it along its edges, \ and the corner's patch starts past that", p.x, p.y, p.z ))); } } Ok(()) } /// The least setback the corner at the vertex nearest `at` takes with rounds of `radius` /// ([`setback_minimum`]): a setback there must be more than this, or [`fillet_setback`] and /// [`fillet_g2_corners`] refuse it. `None` where no vertex is near `at`, or at a corner whose /// least SMLib decides (one with a curved face or edge). pub fn fillet_least_setback(body: &Body, at: Vec3, radius: f64) -> Result> { body.require_brep("fillet")?; let faces = Faces::of(body)?; Ok(corner_vertex(body, &faces, at).and_then(|v| setback_minimum(&faces, v, radius))) } /// The vertex a setback at `at` names: the nearest, within the reach the setbacks take. fn corner_vertex(body: &Body, faces: &Faces, at: Vec3) -> Option { let reach = body.size() * 0.05 + 1e-3; (0..faces.rec.vertices.len()) .filter_map(|v| u32::try_from(v).ok()) .filter_map(|v| faces.point(v).map(|p| (p.dist(at), v))) .filter(|(d, _)| *d <= reach) .min_by(|a, b| a.0.total_cmp(&b.0)) .map(|(_, v)| v) } /// The least setback a corner of rounds of `radius` at `vertex` takes: on each face at the /// corner, the contact lines (rails) of the two rounded edges beside it cross, and a setback /// must reach past that crossing along both edges (smlib_blend_setback). A rail lies /// r tan(psi / 2) from its edge, psi the angle between the outward normals of the edge's two /// faces (r on faces square to each other); the rails of edges at angle alpha on a face, d1 and /// d2 from them, cross (d2 + d1 cos alpha) / sin alpha along the first edge from the vertex. /// Exact for planar faces and straight edges; `None` for a corner with any other (left to SMLib) /// or one it cannot read. fn setback_minimum(faces: &Faces, vertex: u32, radius: f64) -> Option { let at: Vec = (0..faces.rec.edges.len()).filter(|e| faces.rec.edges.get(*e).is_some_and(|x| !x.uses.is_empty() && x.vertices.contains(&vertex))).collect(); if at.len() < 3 { return None; } // Each edge's direction away from the vertex and its rail's distance from it. let mut away = Vec::with_capacity(at.len()); let mut rail = Vec::with_capacity(at.len()); for e in &at { let [a, b] = faces.rec.edges.get(*e)?.vertices; if a == b || !faces.straight(*e) { return None; } let (pa, pb) = faces.ends(*e)?; away.push(if a == vertex { (pb - pa).normalized()? } else { (pa - pb).normalized()? }); let [f, g]: [u32; 2] = faces.faces_of(*e).into_iter().collect::>().try_into().ok()?; let cos = faces.plane_normal(f as usize)?.dot(faces.plane_normal(g as usize)?).clamp(-1.0, 1.0); rail.push(radius * (cos.acos() / 2.0).tan()); } let mut least: f64 = 0.0; let around: BTreeSet = at.iter().flat_map(|e| faces.faces_of(*e)).collect(); for f in around { let beside: Vec = (0..at.len()).filter(|i| at.get(*i).is_some_and(|e| faces.faces_of(*e).contains(&f))).collect(); let [i, j] = beside[..] else { return None }; let cos = away.get(i)?.dot(*away.get(j)?).clamp(-1.0, 1.0); let sin = (1.0 - cos * cos).sqrt(); if sin <= 1e-9 { return None; } let (di, dj) = (*rail.get(i)?, *rail.get(j)?); least = least.max((dj + di * cos) / sin).max((di + dj * cos) / sin); } (least.is_finite() && least > 0.0).then_some(least) } /// [`fillet`] whose corners where three or more rounded edges meet are G2 patches /// ([`crate::corner_g2`]): each such corner is set back, `setbacks` naming a corner by a point at /// its vertex and the distance its patch starts along each edge there (the others take /// [`crate::DEFAULT_SETBACK_FACTOR`] times the radius), SMLib leaves it open, and a patch that /// meets the rounds and the faces round it to the second order fills it. The faces are sewn /// into one solid, convex corners and concave ones alike. Without such a corner this is /// [`fillet`]. Refused: a corner where an edge is not rounded, or whose edges are not all of one /// convexity (SMLib sets back only corners where all are rounded, alike), a setback that does not reach past /// where the rounds would meet, a hole that is no height field over its plane or a patch that /// does not meet its neighbours within the tolerances. pub fn fillet_g2_corners(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result { g2_corners(body, edges, radius, setbacks, false) } /// [`fillet_g2`] (curvature-continuous sections) whose corners where three or more rounded edges /// meet are G2 patches, as [`fillet_g2_corners`] builds them: SMLib's own patch at such a corner /// is only tangent to the rounds (its curvature jumps across their seams), which no /// curvature-continuous fillet may leave. Without such a corner this is [`fillet_g2`]. Refused /// as [`fillet_g2_corners`] is. pub fn fillet_g2_with_g2_corners(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)]) -> Result { g2_corners(body, edges, radius, setbacks, true) } /// [`fillet_g2_corners`] (circular sections) or [`fillet_g2_with_g2_corners`] (`curvature`). fn g2_corners(body: &Body, edges: &[Vec3], radius: f64, setbacks: &[(Vec3, f64)], curvature: bool) -> Result { let _span = solidcraft_profile::span("kernel", "fillet_g2_corners"); body.require_brep("fillet")?; if !(radius.is_finite() && radius > 0.0) { return Err(KernelError::Invalid("the blend radius must be finite and positive".into())); } let (picked, _) = crate::blend_smlib::picked_edges(body, edges)?; let rec = body.record(); let picked: BTreeSet = picked.into_iter().collect(); // Each vertex's edges (a closed edge's one vertex once). let mut at: std::collections::BTreeMap> = std::collections::BTreeMap::new(); for (i, e) in rec.edges.iter().enumerate() { if e.uses.is_empty() { continue; } for v in e.vertices { at.entry(v).or_default().insert(i); } } let point = |v: u32| rec.vertices.get(v as usize).map(|x| v3(x.point)); let mut corners: Vec = Vec::new(); for (v, around) in &at { let rounded = around.iter().filter(|e| picked.contains(e)).count(); if rounded < 3 { continue; } let p = point(*v).ok_or_else(|| KernelError::Failed("fillet: a vertex reference".into()))?; if rounded < around.len() { return Err(unsupported(&format!( "a G2 corner at ({:.3}, {:.3}, {:.3}) where an edge is not rounded (the corner is set back, and SMLib sets back only a corner where every edge is)", p.x, p.y, p.z ))); } corners.push(p); } if corners.is_empty() { return if curvature { fillet_g2(body, edges, radius) } else { fillet(body, edges, radius) }; } // Each corner's setback: the one given at its vertex, else the default. let reach = body.size() * 0.05 + 1e-3; let mut distance = vec![crate::corner_g2::DEFAULT_SETBACK_FACTOR * radius; corners.len()]; for (p, d) in setbacks { let k = corners .iter() .enumerate() .map(|(k, c)| (c.dist(*p), k)) .filter(|(d, _)| *d <= reach) .min_by(|a, b| a.0.total_cmp(&b.0)) .map(|(_, k)| k) .ok_or_else(|| { KernelError::Invalid(format!( "the setback at ({:.3}, {:.3}, {:.3}) names no G2 corner (a vertex where three or more rounded edges meet)", p.x, p.y, p.z )) })?; if let Some(slot) = distance.get_mut(k) { *slot = *d; } } let set_back: Vec<(Vec3, f64)> = corners.iter().copied().zip(distance).collect(); setbacks_reach(body, edges, radius, &set_back)?; let open = crate::blend_smlib::fillet_setback_open(body, edges, radius, &set_back, curvature)?; let mut patches = Vec::with_capacity(open.holes.len()); for hole in &open.holes { let (patch, _) = crate::corner_g2::corner_patch(&open.sheet, hole, radius)?; patches.push(patch); } let mut parts: Vec<&Body> = vec![&open.sheet]; parts.extend(patches.iter()); let sewn = crate::stitch(&parts, 0.0)?; let open_shells = sewn.validity(); if !open_shells.is_empty() { return Err(KernelError::Failed(format!("fillet: the G2 corners do not close the body: {}", open_shells.join("; ")))); } let history = corner_history(&sewn, body, &open.sheet, &patches); closed(body, sewn.with_checked_history(history, &crate::record::counts(&[body]))) } /// The history of the sewn G2-cornered fillet over `[body]`: the sewing's history (over the /// sheet and the patches) carried through the sheet's (over the body); each patch face made from /// the edges whose rounds meet at its corner, as SMLib's own corner patch is, each of its edges /// the sheet's. fn corner_history(sewn: &Body, body: &Body, sheet: &Body, patches: &[Body]) -> Option { use crate::history::{EdgeOrigin, FaceOrigin}; let outer = sewn.history()?.clone(); let inner = sheet.history()?; let mut parts = vec![inner.clone()]; for patch in patches { let own = patch.history()?; // The patch's face comes from the rounded edges the sheet's faces beside it come from. let mut origins: BTreeSet = BTreeSet::new(); for e in &own.edges { for o in &e.origins { let EdgeOrigin::Edge { edge, .. } = o else { continue }; for f in inner.edges.get(*edge).map(|x| x.faces.as_slice()).unwrap_or_default() { let beside = inner.faces.get(*f).map(|x| x.origins.as_slice()).unwrap_or_default(); origins.extend(beside.iter().copied().filter(|g| matches!(g, FaceOrigin::Edge { .. }))); } } } let mut h = own.clone().substituted(0, inner).ok()?; for f in &mut h.faces { *f = crate::record::generated(origins.iter().copied().collect()); } parts.push(h); } let h = outer.over(&parts.iter().collect::>()).ok()?; h.check_counts((sewn.face_count(), sewn.edge_count()), &crate::record::counts(&[body])).ok()?; Some(h) } /// The step of the radius search: three significant digits of the requested radius. fn radius_step(radius: f64) -> f64 { 10f64.powf(radius.log10().floor() - 3.0) } /// The largest radius below `radius` (to three significant digits) at which the fillet of /// these edges works, with its result; `Ok(None)` when none does. Each candidate is a real fillet /// of the edges, so the radius returned is one that was built; the search runs up to 16 of /// them (a refusal of a fillet feature's exact fit runs it to name the largest that fits, and /// so does `fit: reduce`). Only a refusal as too large /// ([`KernelError::TooLarge`]) narrows the search: any other failure of a candidate is the /// search's error, since a smaller radius would not be the largest that fits. pub fn fillet_max(body: &Body, edges: &[Vec3], radius: f64) -> Result> { let _span = solidcraft_profile::span("kernel", "fillet_max"); largest_that_fits(radius, |r| fillet(body, edges, r)) } /// [`fillet_max`] for an equal-distance chamfer of these edges: the largest distance below /// `distance` (to three significant digits) at which it works, with its result. pub fn chamfer_max(body: &Body, edges: &[Vec3], distance: f64) -> Result> { let _span = solidcraft_profile::span("kernel", "chamfer_max"); largest_that_fits(distance, |d| chamfer(body, edges, d)) } /// The largest size n·q below `size` (q: three significant digits of it) at which `blend` works, /// by bisection over at most 16 blends; only [`KernelError::TooLarge`] narrows the search. fn largest_that_fits(size: f64, blend: impl Fn(f64) -> Result) -> Result> { if !(size.is_finite() && size > 1e-6) { return Ok(None); } let q = radius_step(size); // Sizes n·q for n in [0, hi): hi is too large (it is the request, or above it), lo works. let mut hi = (size / q).ceil() as u64; let mut lo = 0u64; let mut best: Option = None; // log2(10⁴) steps reach the step size; the cap keeps a slow body from stalling. for _ in 0..16 { if hi - lo <= 1 { break; } let mid = lo + (hi - lo) / 2; match blend(mid as f64 * q) { Ok(b) => { lo = mid; best = Some(b); } Err(KernelError::TooLarge(_)) => hi = mid, Err(e) => return Err(e), } } Ok(best.map(|b| (lo as f64 * q, b))) } /// [`fillet_max`] for each group of the edges that may limit each other's radius (sharing a /// face or a vertex, directly or through other edges in the group), so a round that fits isn't /// reduced for a tight edge elsewhere. The radius per edge (in `edges`' order) and the result, /// `Ok(None)` when no radius fits. One radius for all (as [`fillet_max`]) when the groups, /// each reduced to fit, are too large together, or there are too many to search (each search is /// up to 16 fillets, and this runs in the live preview). Any failure other than a refusal as too /// large is the error. pub fn fillet_max_each(body: &Body, edges: &[Vec3], radius: f64) -> Result, Body)>> { let _span = solidcraft_profile::span("kernel", "fillet_max_each"); const MAX_GROUPS: usize = 8; const MAX_SEARCHES: usize = 2; let one = || -> Result, Body)>> { Ok(fillet_max(body, edges, radius)?.map(|(r, b)| (vec![r; edges.len()], b))) }; let Some(groups) = interacting_groups(body, edges).filter(|g| g.len() > 1 && g.len() <= MAX_GROUPS) else { return one() }; let mut radii = vec![radius; edges.len()]; let mut searches = 0; for g in &groups { let pts: Vec = g.iter().filter_map(|i| edges.get(*i).copied()).collect(); let r = match fillet(body, &pts, radius) { Ok(_) => continue, Err(KernelError::TooLarge(_)) if searches < MAX_SEARCHES => { searches += 1; match fillet_max(body, &pts, radius)? { Some((r, _)) => r, None => return one(), } } Err(KernelError::TooLarge(_)) => return one(), Err(e) => return Err(e), }; for i in g { if let Some(x) = radii.get_mut(*i) { *x = r; } } } match fillet_each(body, edges, &radii) { Ok(b) => Ok(Some((radii, b))), Err(KernelError::TooLarge(_)) => one(), Err(e) => Err(e), } } /// The fillet of each edge at its own radius (`radii` in `edges`' order), all in one SMLib /// blend. pub fn fillet_each(body: &Body, edges: &[Vec3], radii: &[f64]) -> Result { let _span = solidcraft_profile::span("kernel", "fillet_each"); if radii.len() != edges.len() { return Err(KernelError::Invalid("one radius per edge".into())); } if let Some(r) = radii.first().filter(|r| radii.iter().all(|x| x.to_bits() == r.to_bits())) { return fillet(body, edges, *r); } body.require_brep("fillet")?; crate::blend_smlib::fillet_each(body, edges, radii).and_then(|b| closed(body, b)) } /// The points' edges (each the edge a blend's pick there takes) grouped where they share a face /// or a vertex, directly or through other points' edges: indices into `pts`. `None` when a point /// has no edge near it. fn interacting_groups(body: &Body, pts: &[Vec3]) -> Option>> { let rec = Faces::of(body).ok()?; let (picked, _) = crate::blend_smlib::picked_edges(body, pts).ok()?; // What each point's edge touches: its faces and its ends. let mut groups: Vec<(BTreeSet, BTreeSet, Vec)> = Vec::new(); for (i, idx) in picked.into_iter().enumerate() { let mut faces = rec.faces_of(idx); let mut ends: BTreeSet = rec.rec.edges.get(idx)?.vertices.into_iter().collect(); let mut members = vec![i]; // Join every group touching one of these faces or ends. let (meet, rest): (Vec<_>, Vec<_>) = groups.into_iter().partition(|(fs, vs, _)| !fs.is_disjoint(&faces) || !vs.is_disjoint(&ends)); for (fs, vs, ms) in meet { faces.extend(fs); ends.extend(vs); members.extend(ms); } groups = rest; groups.push((faces, ends, members)); } Some( groups .into_iter() .map(|(_, _, mut ms)| { ms.sort_unstable(); ms }) .collect(), ) } /// Equal-distance chamfer of the edges nearest to the given points, `distance` back along each /// face, neighbouring chamfers meeting in a mitre. pub fn chamfer(body: &Body, edges: &[Vec3], distance: f64) -> Result { let _span = solidcraft_profile::span("kernel", "chamfer"); body.require_brep("chamfer")?; if !(distance.is_finite() && distance > 1e-6 && distance < 1e6) { return Err(KernelError::Invalid("chamfer size must be positive".into())); } if edges.is_empty() || edges.len() > 1000 { return Err(KernelError::Invalid("select 1…1000 edges".into())); } crate::blend_smlib::chamfer(body, edges, distance) } /// The second side of an unequal chamfer: a distance along the other face, or the angle the /// chamfer makes with the first face. #[derive(Clone, Copy, Debug, PartialEq)] pub enum ChamferSide { Distance(f64), Angle(f64), } /// A chamfer with different setbacks on the two faces of each edge: `d1` along the first face /// (the one facing up most, the other with `flip`), the second side by distance or angle. pub fn chamfer_sides(body: &Body, edges: &[Vec3], d1: f64, side: ChamferSide, flip: bool) -> Result { let _span = solidcraft_profile::span("kernel", "chamfer_sides"); body.require_brep("chamfer")?; let ok = |x: f64| x.is_finite() && x > 1e-6 && x < 1e6; let valid = ok(d1) && match side { ChamferSide::Distance(d) => ok(d), ChamferSide::Angle(a) => a.is_finite() && a > 1e-3 && a < std::f64::consts::PI - 1e-3, }; if !valid { return Err(KernelError::Invalid("chamfer sizes must be positive (the angle within 0°…180°)".into())); } if edges.is_empty() || edges.len() > 1000 { return Err(KernelError::Invalid("select 1…1000 edges".into())); } crate::blend_smlib::chamfer_sides(body, edges, d1, side, flip) } /// The edge each pick takes, as a blend takes it (an index in the body's edge order, the order /// of its mesh's edges): the nearest, and at a vertex where a seam or a smooth join meets a sharp /// edge (a cylinder's seam at its rim), the sharp edge. Picks that find no edge are refused. pub fn blend_edges(body: &Body, picks: &[Vec3]) -> Result> { crate::blend_smlib::picked_edges(body, picks).map(|(edges, _)| edges) } /// The picked edges' tangent chains, for a blend that is to run along them: `picks` (each the /// nearest edge of `body` to it), then a point on every other edge that continues one of them /// tangentially (within 0.5° at a shared vertex), until no more do. Each pick takes its edge as a /// blend does (a pick at a vertex where a seam meets a rim takes the rim). An edge only one face /// uses ends a chain, and so do a seam and a smooth edge (its two faces meet tangentially, within /// 0.5°): they have no corner to round. A chain does not run on into an edge of the other /// convexity (a boss's concave base running on tangentially as the convex rim of its overhang): /// a round cannot pass from one side of the faces to the other, so it ends at that vertex. /// Picks that find no edge are refused. pub fn tangent_chain(body: &Body, picks: &[Vec3]) -> Result> { if picks.is_empty() || picks.len() > 1000 || picks.iter().any(|p| !p.is_finite()) { return Err(KernelError::Invalid("select 1…1000 edges by finite points".into())); } let rec = Faces::of(body)?; let (seeds, hidden) = crate::blend_smlib::picked_edges(body, picks)?; let mut picked: Vec = Vec::new(); for e in seeds { if !picked.contains(&e) { picked.push(e); } } let chain = chain_of(&rec, &picked, &hidden); let mut out = picks.to_vec(); for e in chain.into_iter().skip(picked.len()) { out.push(edge_middle(&rec, e).ok_or_else(|| KernelError::Failed("a point on a chain edge".into()))?); } Ok(out) } /// Edges meeting at an angle below this continue one another; faces meeting at an angle below /// it meet tangentially. const TANGENT_DEGREES: f64 = 0.5; /// The point halfway along edge `e`. fn edge_middle(rec: &Faces, e: usize) -> Option { let edge = rec.rec.edges.get(e)?; CurveEval::new(edge.parameters()).ok().and_then(|c| c.point(0.5 * (edge.interval[0] + edge.interval[1]))) } /// How far from a face's surface a point may lie for its normal there. fn normal_reach(rec: &Faces) -> f64 { rec.rec.tolerance.max(1e-7) * 10.0 } /// Stations along an edge, as fractions of its interval, where [`smooth_join`] compares its /// faces' normals: its ends, and between them. const SMOOTH_STATIONS: [f64; 5] = [0.0, 0.25, 0.5, 0.75, 1.0]; /// Whether edge `e`'s two faces meet tangentially (within [`TANGENT_DEGREES`]) all along it: a /// smooth edge, with no corner to blend. An edge whose faces are tangent at one end only (a /// round running into a wall it is tangent to where the wall meets its face) is a crease /// everywhere else, which is not smooth. fn smooth_join(rec: &Faces, e: usize) -> bool { let cos = TANGENT_DEGREES.to_radians().cos(); let accept = normal_reach(rec); let faces: Vec = rec.faces_of(e).into_iter().collect(); let ([a, b], Some(edge)) = (faces.as_slice(), rec.rec.edges.get(e)) else { return false }; let Ok(curve) = CurveEval::new(edge.parameters()) else { return false }; let [t0, t1] = edge.interval; SMOOTH_STATIONS.iter().all(|s| { let Some(p) = curve.point(t0 + (t1 - t0) * s) else { return false }; match (rec.normal_at(*a as usize, p, accept), rec.normal_at(*b as usize, p, accept)) { (Some(na), Some(nb)) => na.dot(nb) > cos, _ => false, } }) } /// `seeds` (edges in the record's order, each once), then every other edge that continues one /// of them tangentially, as [`tangent_chain`] follows them; `hidden` marks the edges a pick /// passes over. fn chain_of(rec: &Faces, seeds: &[usize], hidden: &[bool]) -> Vec { let mut chain = seeds.to_vec(); // The unit direction edge `e` leaves its end `v` in. let leaving = |e: usize, v: u32| -> Option { let [a, b] = rec.rec.edges.get(e)?.vertices; if a == b { return None; } if a == v { rec.tangent(e, false) } else { rec.tangent(e, true).map(|t| t * -1.0) } }; let cos = TANGENT_DEGREES.to_radians().cos(); let accept = normal_reach(rec); // Whether edge `e` is convex at its end `v` (its faces meet at less than 180° inside the // body): the direction into its second face, square to it, points against its first face's // outward normal. A face lies to the left of its loop seen from its surface's natural normal. // None for an edge without exactly two uses, or where a normal cannot be found. let convex = |e: usize, v: u32| -> Option { let edge = rec.rec.edges.get(e)?; let [ua, ub] = edge.uses.as_slice() else { return None }; let forward_b = match rec.rec.faces.get(ub.face as usize)?.loops.get(ub.r#loop as usize)? { Loop::Edges { edges } => edges.get(ub.position as usize)?.forward, Loop::Vertex { .. } => return None, }; let p = rec.point(v)?; let along = rec.tangent(e, edge.vertices[0] != v)?; let natural_b = rec.normal_at(ub.face as usize, p, accept)? * rec.side(ub.face as usize)?; let into_b = natural_b.cross(if forward_b { along } else { along * -1.0 }); Some(into_b.dot(rec.normal_at(ua.face as usize, p, accept)?) < 0.0) }; let mut k = 0; while k < chain.len() { let Some(&e) = chain.get(k) else { break }; k += 1; let Some(edge) = rec.rec.edges.get(e) else { continue }; for v in edge.vertices { let Some(d) = leaving(e, v) else { continue }; for (f, other) in rec.rec.edges.iter().enumerate() { let passed_over = hidden.get(f).copied().unwrap_or(false); if passed_over || chain.contains(&f) || other.uses.len() < 2 || !other.vertices.contains(&v) || smooth_join(rec, f) { continue; } let turns_over = matches!((convex(e, v), convex(f, v)), (Some(a), Some(b)) if a != b); if !turns_over && leaving(f, v).is_some_and(|g| d.dot(g) < -cos) { chain.push(f); } } } } chain } /// Before blending exactly `edges` (the record's edges `picks` took, in order): refuses an edge /// whose faces meet tangentially (a smooth edge, nothing to round), and names the first edge a /// picked one runs on into tangentially without being blended with it, if any (tangent /// propagation off). SMLib blends the picked edges alone where it can end a blend there (a round /// ending on the round it runs into); where it can't, [`with_continuation`] says why. pub(crate) fn unfinished_chain(body: &Body, picks: &[Vec3], edges: &[usize], hidden: &[bool]) -> Result> { let rec = Faces::of(body)?; let at = |i: usize| picks.get(i).map(|p| format!("({:.3}, {:.3}, {:.3})", p.x, p.y, p.z)).unwrap_or_default(); for (i, &e) in edges.iter().enumerate() { if smooth_join(&rec, e) { return Err(KernelError::Invalid(format!("the edge at {} is smooth: its faces meet tangentially, so there is nothing to round", at(i)))); } } let mut seeds: Vec = Vec::new(); for &e in edges { if !seeds.contains(&e) { seeds.push(e); } } Ok(chain_of(&rec, &seeds, hidden).get(seeds.len()).and_then(|&next| edge_middle(&rec, next))) } /// A blend's failure where a picked edge continues tangentially into `next`, an edge left out /// ([`unfinished_chain`]): SMLib rounds a tangent chain as one sequence and could not end the /// blend there, so the reason and the way out are named. pub(crate) fn with_continuation(e: KernelError, next: Option) -> KernelError { let Some(p) = next else { return e }; let why = format!( " (a picked edge continues tangentially into the edge at ({:.3}, {:.3}, {:.3}), which is not blended with it, and the blend \ cannot end there: with tangent propagation on, tangent_chain: true, its tangent chain is blended as one)", p.x, p.y, p.z ); match e { KernelError::Invalid(m) => KernelError::Invalid(m + &why), KernelError::Failed(m) => KernelError::Failed(m + &why), KernelError::TooLarge(m) => KernelError::TooLarge(m + &why), e => e, } } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; use solidcraft_geom::{Loop2, Plane, Region2, Vec2}; /// A round (`round`) or an equal-distance chamfer of the edges nearest `pts`. fn blend(body: &Body, pts: &[Vec3], size: f64, round: bool) -> Result { if round { fillet(body, pts, size) } else { chamfer(body, pts, size) } } fn vol(b: &Body) -> f64 { b.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume } /// Whether a vertex of `b` lies within `tol` of `p`. fn has_vertex(b: &Body, p: Vec3, tol: f64) -> bool { crate::native::brep_record(b).unwrap().vertices.iter().any(|v| v3(v.point).dist(p) < tol) } /// The ladder's 08-chamfers/008: a boss on a block, rounded where it meets the block, picked /// at the top of its seam. The pick takes the top rim, and the chain keeps to it: it never /// runs down the seam into the round's own seam, which continues it tangentially. #[test] fn a_chain_picked_where_a_seam_meets_a_rim_keeps_to_the_rim() { let block = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); let boss = crate::build::cylinder(Vec3::new(15.0, 15.0, 20.0), Vec3::Z, 8.0, 10.0).unwrap(); let joined = crate::boolean(&block, &boss, crate::BoolOp::Union).unwrap().unwrap(); let rec = joined.record(); // The seam: the edge both of whose uses lie on the boss's side. let seam = rec.edges.iter().find(|e| e.uses.len() == 2 && e.uses[0].face == e.uses[1].face).unwrap(); let ends = seam.vertices.map(|v| v3(rec.vertices[v as usize].point)); let (foot, top) = if ends[0].z < ends[1].z { (ends[0], ends[1]) } else { (ends[1], ends[0]) }; let rounded = fillet(&joined, &[foot], 1.0).unwrap(); let chain = tangent_chain(&rounded, &[top]).unwrap(); assert_eq!(chain, vec![top], "the chain left the top rim"); assert!(chamfer(&rounded, &chain, 1.0).is_ok()); // Even from a pick on the seam itself, the chain takes no seam: the round's continues // the boss's tangentially but has no corner to blend. let side = (top + Vec3::new(top.x, top.y, 21.0)) * 0.5; assert_eq!(tangent_chain(&rounded, &[side]).unwrap(), vec![side], "the chain ran into the round's seam"); } #[test] fn g2_fillet_has_the_quintics_area() { let body = crate::build::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); let out = fillet_g2(&body, &[Vec3::new(20.0, 0.0, 10.0)], 2.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.face_count(), body.face_count() + 1); // Independent analytic area: integrating x(t) y'(t) for the quintic // gives 113/756 times setback² for a right-angle corner. let volume = out.mesh(&crate::MeshTolerance::chord(0.0001)).unwrap().measure().volume; let expected = 8000.0 - (113.0 / 756.0) * 4.0 * 20.0; assert!((volume - expected).abs() < 0.02, "{volume} vs {expected}"); } #[test] fn g2_fillet_handles_concave_edges_and_separate_edges() { let lp = Loop2::polygon(&[ Vec2::new(0.0, 0.0), Vec2::new(20.0, 0.0), Vec2::new(20.0, 10.0), Vec2::new(10.0, 10.0), Vec2::new(10.0, 20.0), Vec2::new(0.0, 20.0), ]); let body = crate::build::extrude(&Plane::XY, &[Region2 { outer: lp, holes: vec![] }], 0.0, 20.0).unwrap().remove(0); let out = fillet_g2(&body, &[Vec3::new(10.0, 10.0, 10.0)], 2.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); let volume = out.mesh(&crate::MeshTolerance::chord(0.0001)).unwrap().measure().volume; let expected = 6000.0 + (113.0 / 756.0) * 4.0 * 20.0; assert!((volume - expected).abs() < 0.02, "{volume} vs {expected}"); let body = crate::build::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); let out = fillet_g2(&body, &[Vec3::new(20.0, 0.0, 10.0), Vec3::new(0.0, 20.0, 10.0)], 2.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.face_count(), body.face_count() + 2); } #[test] fn g2_fillet_refuses_sections_crossing_a_cap_hole() { // The hole lies inside the setback without touching either side face. let region = Region2 { outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(20.0, 0.0), Vec2::new(20.0, 20.0), Vec2::new(0.0, 20.0)]), holes: vec![Loop2::circle(Vec2::new(0.5, 0.5), 0.15)], }; for plane in [Plane::XY, Plane::XZ] { let body = crate::extrude(&plane, std::slice::from_ref(®ion), 0.0, 20.0).unwrap().remove(0); let pick = plane.to_world(Vec2::ZERO) + plane.normal() * 10.0; assert_eq!(body.crossed_face_loops().unwrap(), 0); let out = fillet_g2(&body, &[pick], 0.5).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.crossed_face_loops().unwrap(), 0); assert_eq!(out.face_count(), body.face_count() + 1); assert!(fillet_g2(&body, &[pick], 2.0).is_err()); } } #[test] fn g2_fillet_meets_sloped_planar_ends() { // Inward and outward sloping ends, and one square end, in two orientations (#2708). for plane in [Plane::XY, Plane::XZ] { for (left, right) in [(-0.5, -0.5), (0.5, 0.5), (0.0, 0.5), (-0.25, 0.5)] { let region = Region2 { outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(40.0, 0.0), Vec2::new(40.0 - right * 20.0, 20.0), Vec2::new(left * 20.0, 20.0)]), holes: vec![], }; let body = crate::extrude(&plane, &[region], 0.0, 20.0).unwrap().pop().unwrap(); let pick = plane.to_world(Vec2::new(20.0, 0.0)) + plane.normal() * 20.0; let out = fillet_g2(&body, &[pick], 5.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.crossed_face_loops().unwrap(), 0); assert_eq!(out.face_count(), 7); // Analytic volume: the removed section has area 113 r² / 756 // and first moment ∫y dA = 13711 r³ / 486486. Axial length is 40−(left+right)y. let removed = 40.0 * 113.0 / 756.0 * 25.0 - (left + right) * 13711.0 / 486486.0 * 125.0; let expected = 16000.0 - 4000.0 * (left + right) - removed; let volume = out.mesh(&crate::MeshTolerance::chord(0.0001)).unwrap().measure().volume; assert!((volume - expected).abs() < 0.05, "{volume} vs {expected}"); } } } #[test] fn g2_fillet_on_concave_edge_meets_caps_sloped_in_both_directions() { let region = Region2 { outer: Loop2::polygon(&[ Vec2::ZERO, Vec2::new(20.0, 0.0), Vec2::new(20.0, 10.0), Vec2::new(10.0, 10.0), Vec2::new(10.0, 20.0), Vec2::new(0.0, 20.0), ]), holes: vec![], }; let body = crate::extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().pop().unwrap(); // z -> z + 0.3x + 0.4y tilts both caps while leaving the vertical edge // and its side planes unchanged. This shear preserves volume. let body = crate::transform_matrix(&body, [[1.0, 0.0, 0.3, 0.0], [0.0, 1.0, 0.4, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]).unwrap(); let out = fillet_g2(&body, &[Vec3::new(10.0, 10.0, 17.0)], 2.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.crossed_face_loops().unwrap(), 0); let volume = out.mesh(&crate::MeshTolerance::chord(0.0001)).unwrap().measure().volume; let expected = 6000.0 + 113.0 / 756.0 * 4.0 * 20.0; assert!((volume - expected).abs() < 0.02, "{volume} vs {expected}"); } #[test] fn g2_fillet_refuses_invalid_geometry() { let body = crate::build::box_solid(Vec3::ZERO, Vec3::new(20.0, 20.0, 20.0)).unwrap(); let edge = [Vec3::new(20.0, 0.0, 10.0)]; for radius in [0.0, -1.0, f64::NAN, f64::INFINITY, 1e7] { assert!(fillet_g2(&body, &edge, radius).is_err()); } assert!(fillet_g2(&body, &[], 2.0).is_err()); assert!(fillet_g2(&body, &[Vec3::new(f64::NAN, 0.0, 0.0)], 2.0).is_err()); assert!(fillet_g2(&body, &[Vec3::new(1000.0, 0.0, 0.0)], 2.0).is_err()); // Wider than the faces (20), over their far edges, cliffs: cut as if they went on. The // section is the quintic from 25 out on each face, its inner control points a third and // two thirds of the way to the corner; it takes the region between it and the corner // inside the 20 x 20 section (clipped polygon of the curve, 2e5 pieces), along 20. let wide = fillet_g2(&body, &edge, 25.0).unwrap(); let v = crate::measure(&wide).unwrap().volume; assert!((v - 6138.1606889014).abs() < 1e-6 * 6138.1606889014, "{v}"); assert!(wide.validity().is_empty()); } /// A box with a cylinder joined across one side (#556): the bottom edge of that side runs /// into the cylinder, which is curved where the edge ends. fn box_and_boss() -> Body { let b = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 20.0)).unwrap(); let c = crate::build::cylinder(Vec3::new(40.0, 20.0, 0.0), Vec3::Z, 12.0, 40.0).unwrap(); crate::ops::boolean(&b, &c, crate::BoolOp::Union).unwrap().unwrap() } #[test] fn a_blend_runs_into_a_cylinder_at_its_end() { let body = box_and_boss(); let v0 = vol(&body); // The edge (40, 0..8, 0) ends in the cylinder wall at y = 8. let len = 20.0 - (144.0f64 - 0.0).sqrt(); for (round, size, area) in [(true, 0.5, (1.0 - std::f64::consts::PI / 4.0) * 0.25), (false, 0.5, 0.125)] { let out = blend(&body, &[Vec3::new(40.0, 4.0, 0.0)], size, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); let removed = v0 - vol(&out); // The section runs on a little past y = 8 under the cylinder wall. assert!(removed > area * len * 0.99 && removed < area * (len + 0.02), "{removed} vs {}", area * len); assert_eq!(out.face_count(), body.face_count() + 1); } } #[test] fn a_blend_ends_on_a_hole_wall() { // A plate with a hole cutting through the middle of its top front edge: each piece of // that edge ends on the hole's wall. let plate = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 20.0, 10.0)).unwrap(); let hole = crate::build::cylinder(Vec3::new(20.0, 0.0, -1.0), Vec3::Z, 5.0, 12.0).unwrap(); let body = crate::ops::boolean(&plate, &hole, crate::BoolOp::Cut).unwrap().unwrap(); let v0 = vol(&body); for (round, area) in [(true, (1.0 - std::f64::consts::PI / 4.0)), (false, 0.5)] { let out = blend(&body, &[Vec3::new(5.0, 0.0, 10.0)], 1.0, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); let removed = v0 - vol(&out); assert!(removed > area * 14.0 && removed < area * 15.2, "{removed}"); } } #[test] fn a_chamfer_of_a_hole_corner_is_one_bevel() { let plate = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 10.0)).unwrap(); let pocket = crate::build::box_solid(Vec3::new(10.0, 10.0, -1.0), Vec3::new(30.0, 30.0, 12.0)).unwrap(); let body = crate::ops::boolean(&plate, &pocket, crate::BoolOp::Cut).unwrap().unwrap(); let v0 = vol(&body); let one = chamfer(&body, &[Vec3::new(10.0, 10.0, 5.0)], 2.0).unwrap(); assert!(one.validity().is_empty(), "{:?}", one.validity()); assert_eq!(one.unmeshed_faces(), 0); let added = vol(&one) - v0; // The bevel fills the hole corner: a right triangle of legs 2 mm, times the 10 mm edge. assert!(added > 19.0 && added < 21.0, "added {added}, want 20"); assert_eq!(one.face_count(), body.face_count() + 1, "one bevel face"); let corners = [Vec3::new(10.0, 10.0, 5.0), Vec3::new(30.0, 10.0, 5.0), Vec3::new(30.0, 30.0, 5.0), Vec3::new(10.0, 30.0, 5.0)]; let all = chamfer(&body, &corners, 2.0).unwrap(); assert!(all.validity().is_empty(), "{:?}", all.validity()); let added = vol(&all) - v0; assert!(added > 76.0 && added < 84.0, "added {added}, want 80"); assert_eq!(all.face_count(), body.face_count() + 4, "one bevel face per corner"); } #[test] fn a_chamfer_ends_across_two_faces() { // A plate's outline chamfered, then the mitre at a corner chamfered: its low end meets // both side faces, and the chamfer plane cuts back the vertical edge between them. let k = 5.0; let b = crate::build::box_solid(Vec3::ZERO, Vec3::new(100.0, 50.0, 20.0)).unwrap(); let outline = [Vec3::new(50.0, 0.0, 20.0), Vec3::new(100.0, 25.0, 20.0), Vec3::new(50.0, 50.0, 20.0), Vec3::new(0.0, 25.0, 20.0)]; let c = chamfer(&b, &outline, k).unwrap(); let out = chamfer(&c, &[Vec3::new(k / 2.0, k / 2.0, 20.0 - k / 2.0)], 1.0).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.lumps().unwrap().len(), 1); assert_eq!(out.face_count(), c.face_count() + 1); // About the triangle (sides 1 and 1 at 120°) along the mitre; its ends slant. let removed = vol(&c) - vol(&out); let along = 0.5 * 120f64.to_radians().sin() * k * 3f64.sqrt(); assert!(removed > along * 0.8 && removed < along * 1.2, "{removed} vs {along}"); } #[test] fn a_curved_edge_blend_ends_in_a_face_at_an_angle() { // A groove of radius 8 along y with its axis 4 below the top: the arcs where it meets the // front and back faces end in the top face at 60° to it. let b = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 20.0, 20.0)).unwrap(); let c = crate::build::cylinder(Vec3::new(20.0, -1.0, 16.0), Vec3::Y, 8.0, 22.0).unwrap(); let body = crate::ops::boolean(&b, &c, crate::BoolOp::Cut).unwrap().unwrap(); let v0 = vol(&body); for round in [true, false] { let out = blend(&body, &[Vec3::new(20.0, 0.0, 8.0)], 0.5, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); // About the section along the arc (240°, at the section's distance from the axis). let area = if round { (1.0 - std::f64::consts::PI / 4.0) * 0.25 } else { 0.125 }; let along = 8.2 * 240f64.to_radians(); let removed = v0 - vol(&out); assert!(removed > area * along * 0.9 && removed < area * along * 1.1, "{removed} vs {}", area * along); } } #[test] fn a_blend_of_an_edge_running_into_a_rounded_corner_follows_it() { // A box with one vertical edge rounded: a top edge meeting that round smoothly is blended // with the round's top arc and the next top edge, as one smooth chain (its tangent chain, // as the Fillet and Chamfer features ask for it). let b = crate::build::box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 20.0)).unwrap(); let rounded = fillet(&b, &[Vec3::new(40.0, 30.0, 10.0)], 5.0).unwrap(); let chain = tangent_chain(&rounded, &[Vec3::new(20.0, 30.0, 20.0)]).unwrap(); assert_eq!(chain.len(), 3, "the top edge, the round's top arc and the next top edge"); for round in [true, false] { let out = blend(&rounded, &chain, 1.0, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); assert_eq!(out.face_count(), rounded.face_count() + 3); } } #[test] fn a_blend_along_a_boss_ends_on_the_box_side_beside_it() { // The boss's bottom edge outside the box (a half circle) ends at the box's side, square to // it: the side face takes the end section. let body = box_and_boss(); let v0 = vol(&body); for (round, area, c) in [ (true, (1.0 - std::f64::consts::PI / 4.0) * 0.64, 0.8 * (10.0 - 3.0 * std::f64::consts::PI) / (3.0 * (4.0 - std::f64::consts::PI))), (false, 0.32, 0.8 / 3.0), ] { // The half circle's tangent chain, as the Fillet and Chamfer features ask for it. let out = blend(&body, &tangent_chain(&body, &[Vec3::new(52.0, 20.0, 0.0)]).unwrap(), 0.8, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); // Pappus: the section turned half round the axis at its centroid's radius. let want = area * std::f64::consts::PI * (12.0 - c); let removed = v0 - vol(&out); assert!((removed - want).abs() < want * 2e-3, "{removed} vs {want}"); // The app's planned mesh must also close, with the same analytic removal. let planned = crate::issue_851_tests::planned_volume(&body) - crate::issue_851_tests::planned_volume(&out); assert!((planned - want).abs() < want * 2e-3, "display mesh: {planned} vs {want}"); } } #[test] fn a_blend_ends_on_a_face_running_along_its_seam_twice() { // #691: a pocket's floor edge along its straight wall ends on a boss's cylinder, which a // STEP file gives as one face running along its seam edge twice. let b = crate::build::box_solid(Vec3::new(-55.0, -20.0, -30.0), Vec3::new(55.0, 50.0, 0.0)).unwrap(); let boss = crate::build::cylinder(Vec3::new(55.0, 15.0, -50.0), Vec3::Z, 25.0, 50.0).unwrap(); let b = crate::ops::boolean(&b, &boss, crate::BoolOp::Union).unwrap().unwrap(); let pocket = crate::build::box_solid(Vec3::new(-45.0, -21.0, -15.0), Vec3::new(55.0, 10.0, 1.0)).unwrap(); let wall = crate::build::cylinder(Vec3::new(55.0, 15.0, -20.0), Vec3::Z, 25.0, 30.0).unwrap(); let pocket = crate::ops::boolean(&pocket, &wall, crate::BoolOp::Cut).unwrap().unwrap(); let made = crate::ops::boolean(&b, &pocket, crate::BoolOp::Cut).unwrap().unwrap(); let body = crate::step_import(&crate::step_export(&[&made], "test").unwrap()).unwrap().bodies.remove(0).body; let rec = crate::native::brep_record(&body).unwrap(); let seam_twice = rec.faces.iter().flat_map(|f| f.loops.iter()).any(|l| match l { Loop::Edges { edges } => edges.iter().enumerate().any(|(k, x)| edges.iter().skip(k + 1).any(|y| y.edge == x.edge)), Loop::Vertex { .. } => false, }); assert!(seam_twice); let v0 = vol(&body); // The edge runs from x = −45 to where the wall meets the cylinder, x = 55 − √(25² − 5²). let len = 45.0 + 55.0 - (600f64).sqrt(); for (round, area) in [(true, 1.0 - std::f64::consts::PI / 4.0), (false, 0.5)] { let out = blend(&body, &[Vec3::new(0.0, 10.0, -15.0)], 1.0, round).unwrap(); assert!(out.validity().is_empty(), "{:?}", out.validity()); // A concave edge: the blend adds material. let added = vol(&out) - v0; assert!((added - area * len).abs() < area * len * 0.01, "{added} vs {}", area * len); } } #[test] fn a_chamfer_meets_sloped_end_planes() { for slope in [-0.5, 0.5] { let region = Region2 { outer: Loop2::polygon(&[Vec2::ZERO, Vec2::new(40.0, 0.0), Vec2::new(40.0 - slope * 20.0, 20.0), Vec2::new(slope * 20.0, 20.0)]), holes: vec![], }; let body = crate::extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().pop().unwrap(); let pick = [Vec3::new(20.0, 0.0, 20.0)]; let result = chamfer(&body, &pick, 2.0).unwrap(); let removed = 2.0 * (40.0 - 2.0 * slope * 2.0 / 3.0); let actual = crate::measure(&body).unwrap().volume - crate::measure(&result).unwrap().volume; assert!((actual - removed).abs() < 1e-6, "{actual} vs {removed}"); assert!(result.validity().is_empty()); // The new corner vertices lie on both original end planes. for point in [Vec3::new(slope * 2.0, 2.0, 20.0), Vec3::new(40.0 - slope * 2.0, 2.0, 20.0)] { assert!(has_vertex(&result, point, 1e-8)); } // Past the faces (20 deep, 20 high), over their far edges, cliffs: cut as if the // faces and the sloped end planes went on. The plane 25 back on each face takes, of // the section, z >= y - 5 (y, z in [0, 20]), each line of it 40 - 2 slope y long // between the end planes: 11500 - 4625 slope. let past = chamfer(&body, &pick, 25.0).unwrap(); let removed = 11500.0 - 4625.0 * slope; let actual = crate::measure(&body).unwrap().volume - crate::measure(&past).unwrap().volume; assert!((actual - removed).abs() < 1e-6 * removed, "{actual} vs {removed}"); assert!(past.validity().is_empty()); // A fillet ends in each sloped end plane along an ellipse: the removed section's // length is taken at its centroid, c from the edge. let rounded = fillet(&body, &pick, 2.0).unwrap(); let (area, c) = ((1.0 - std::f64::consts::PI / 4.0) * 4.0, 2.0 * (10.0 - 3.0 * std::f64::consts::PI) / (3.0 * (4.0 - std::f64::consts::PI))); let removed = area * (40.0 - 2.0 * slope * c); let actual = crate::measure(&body).unwrap().volume - crate::measure(&rounded).unwrap().volume; assert!((actual - removed).abs() < 1e-3 * removed, "{actual} vs {removed}"); assert!(rounded.validity().is_empty()); } } /// A pin standing in a socket, 3.5 mm from two of its walls, in a large block. The cutters /// for its tip reach several times the chamfer's size past each edge (more on a larger part), /// into the walls, and their union took bites out of them: 7.2 mm³ instead of the tip's. /// A cutter whose far corners are in the material is not used; the tip alone is chamfered. #[test] fn chamfering_a_pin_in_a_socket_leaves_the_socket_walls() { let block = crate::build::box_solid(Vec3::new(0.0, 0.0, -135.0), Vec3::new(82.0, 41.0, 19.0)).unwrap(); let socket = crate::build::box_solid(Vec3::new(6.0, 11.5, 0.0), Vec3::new(21.0, 35.5, 25.0)).unwrap(); let pin = crate::build::box_solid(Vec3::new(9.5, 30.5, -1.0), Vec3::new(12.5, 32.0, 10.0)).unwrap(); let cut = crate::boolean(&block, &socket, crate::BoolOp::Cut).unwrap().unwrap(); let body = crate::boolean(&cut, &pin, crate::BoolOp::Union).unwrap().unwrap(); let tip = [Vec3::new(11.0, 30.5, 10.0), Vec3::new(9.5, 31.25, 10.0), Vec3::new(11.0, 32.0, 10.0), Vec3::new(12.5, 31.25, 10.0)]; let d = 0.5; let out = chamfer(&body, &tip, d).unwrap(); // Four wedges along the tip's edges, less the four corner pyramids each pair shares. let removed = 0.5 * d * d * 2.0 * (3.0 + 1.5) - 4.0 * d * d * d / 3.0; let actual = crate::measure(&body).unwrap().volume - crate::measure(&out).unwrap().volume; assert!((actual - removed).abs() < 1e-3, "{actual} vs {removed}"); assert_eq!(out.face_count(), body.face_count() + 4); assert!(out.validity().is_empty(), "{:?}", out.validity()); } } #[cfg(test)] #[path = "curvecorner_tests.rs"] mod corner_tests;