Skip to main content

brep_kernel/blending/
fillet_tangent_chains.rs

1//! A fillet of edges and every edge their G1 tangent chains continue into:
2//! the fillet feature's "Follow tangent" selection, as one public call; and
3//! the fillet with the caller's options (follow tangents, refuse a pinch).
4use crate::{fillet_edges, BrepSolid, KernelRefusal, KernelStage, Vec3};
5
6/// [`fillet_edges`] of `edge_points`' edges and every unselected edge on the
7/// tangent chains through them (closed loops included: picking one straight
8/// edge of a prism whose upright corners are rounded rounds its whole top
9/// loop). The chains are walked as the fillet feature walks them
10/// (`tangent_chain_expansion`: from each end vertex the single edge whose
11/// tangent continues the chain within 1e-6, stopping at a sharp or ambiguous
12/// junction). `edge_names`, when given, names the picked edges; the edges the
13/// chains add carry their own names.
14pub fn fillet_edges_tangent_chains(
15    solid: &BrepSolid,
16    edge_points: &[Vec3],
17    edge_names: Option<&[String]>,
18    radius: f64,
19    name: Option<&str>,
20) -> Result<BrepSolid, KernelRefusal> {
21    let seeds = edge_points
22        .iter()
23        .map(|point| brep_blend::fillet::edges::resolve_edge_by_point(solid, *point))
24        .collect::<Result<Vec<u64>, KernelRefusal>>()?;
25    let added = crate::feature_pipeline::features::common::tangent_chain_expansion(solid, &seeds, &seeds)
26        .map_err(|error| KernelRefusal::internal(KernelStage::Collect, "tangent_chain", error))?;
27    if added.is_empty() {
28        return fillet_edges(solid, edge_points, edge_names, radius, false, name);
29    }
30    let mut points = edge_points.to_vec();
31    points.extend(added.iter().map(|(_, point, _)| *point));
32    let names = edge_names.map(|names| {
33        let mut all = names.to_vec();
34        all.extend(added.iter().map(|(_, _, name)| name.clone()));
35        all
36    });
37    fillet_edges(solid, &points, names.as_deref(), radius, false, name)
38}
39
40/// How [`fillet_edges_with_options`] reads a selection.
41#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
42pub struct FilletOptions {
43    /// Also fillet every edge the picked edges' tangent chains continue into
44    /// ([`fillet_edges_tangent_chains`]).
45    pub follow_tangent_chains: bool,
46    /// Refuse (InvalidInput) a selection whose blends overlap on a face lying
47    /// between two parallel picked edges with parallel walls beyond, unless
48    /// the radius is half the walls' distance (the full round). By default
49    /// the kernel builds such a pair as two balls each tangent to its own
50    /// faces, pinching to a ridge where they meet; a caller that wants every
51    /// ball to touch both faces it rolls on asks for the refusal
52    /// (`brep_blend::fillet::pinch_refusal`).
53    pub refuse_pinch: bool,
54}
55
56/// [`fillet_edges`] read with `options`: the selection widened along its
57/// tangent chains first when asked, and the pinch refused when asked (judged
58/// on the widened selection).
59pub fn fillet_edges_with_options(
60    solid: &BrepSolid,
61    edge_points: &[Vec3],
62    edge_names: Option<&[String]>,
63    radius: f64,
64    options: FilletOptions,
65    name: Option<&str>,
66) -> Result<BrepSolid, KernelRefusal> {
67    let mut points = edge_points.to_vec();
68    let mut names = edge_names.map(|names| names.to_vec());
69    if options.follow_tangent_chains {
70        let seeds = edge_points
71            .iter()
72            .map(|point| brep_blend::fillet::edges::resolve_edge_by_point(solid, *point))
73            .collect::<Result<Vec<u64>, KernelRefusal>>()?;
74        let added = crate::feature_pipeline::features::common::tangent_chain_expansion(solid, &seeds, &seeds)
75            .map_err(|error| KernelRefusal::internal(KernelStage::Collect, "tangent_chain", error))?;
76        points.extend(added.iter().map(|(_, point, _)| *point));
77        if let Some(names) = names.as_mut() {
78            names.extend(added.iter().map(|(_, _, name)| name.clone()));
79        }
80    }
81    if options.refuse_pinch {
82        if let Some(refusal) = brep_blend::fillet::pinch_refusal(solid, &points, radius) {
83            return Err(refusal);
84        }
85    }
86    let refused = match fillet_edges(solid, &points, names.as_deref(), radius, false, name) {
87        Ok(built) => return Ok(built),
88        Err(refused) => refused,
89    };
90    // A sliver the round swallows: answered where the plain build refuses.
91    match swallowed_face_route(solid, &points, names.as_deref(), radius, name) {
92        Some(Ok(built)) => Ok(built),
93        _ => Err(refused),
94    }
95}
96
97fn is_plane(face: &crate::topology::FaceRecord) -> bool {
98    let s = &face.surface;
99    s.degree_u == 1 && s.degree_v == 1 && s.control_points.len() == 2 && s.control_points[0].len() == 2 && face.surface.analytic().is_some_and(|a| matches!(a, crate::AnalyticSurface::Plane { .. }))
100}
101
102/// A SWALLOWED FACE: two parallel straight picked edges bound a planar strip
103/// between two planar faces that meet at a convex angle beyond it (a corner
104/// cut back by a sliver), and the round of that corner (its contacts
105/// `r · cot(φ/2)` from the corner along each face, φ the angle inside the
106/// material) reaches past both of the strip's edges: a ball of the radius
107/// cannot touch the strip, it rolls on the two faces beyond, and the strip
108/// goes. Every such strip is deleted in one heal (its neighbours extended to
109/// their meeting edge) and those edges filleted with the rest of the
110/// selection, each corner taking the first of its pair's names. `None`
111/// where no such pair is picked, or the heal refuses.
112fn swallowed_face_route(solid: &BrepSolid, edge_points: &[Vec3], edge_names: Option<&[String]>, radius: f64, name: Option<&str>) -> Option<Result<BrepSolid, KernelRefusal>> {
113    let ids: Vec<u64> = edge_points.iter().map(|p| brep_blend::fillet::edges::resolve_edge_by_point(solid, *p).ok()).collect::<Option<_>>()?;
114    let mut taken = vec![false; ids.len()];
115    let mut strips: Vec<u64> = Vec::new();
116    let mut corners: Vec<(usize, Vec3)> = Vec::new(); // (the pair's first index, a point on its corner edge)
117    for i in 0..ids.len() {
118        for j in i + 1..ids.len() {
119            if taken[i] || taken[j] {
120                continue;
121            }
122            let Ok((ea, fa)) = brep_blend::fillet::analyze::edge_and_faces(solid, ids[i]) else { continue };
123            let Ok((eb, fb)) = brep_blend::fillet::analyze::edge_and_faces(solid, ids[j]) else { continue };
124            if ea.curve.degree != 1 || eb.curve.degree != 1 || fa.len() != 2 || fb.len() != 2 {
125                continue;
126            }
127            let ends = |e: &crate::topology::EdgeRecord| -> Option<(Vec3, Vec3)> { Some((e.curve.evaluate(e.t0).ok()?, e.curve.evaluate(e.t1).ok()?)) };
128            let (Some((a0, a1)), Some((b0, b1))) = (ends(ea), ends(eb)) else { continue };
129            let (Ok(da), Ok(db)) = (a1.sub(a0).normalized(), b1.sub(b0).normalized()) else { continue };
130            if da.cross(db).length() > 1e-9 {
131                continue;
132            }
133            // The strip: the face both edges bound, its one loop of four.
134            let Some(strip) = fa.iter().find(|f| fb.iter().any(|g| g.id == f.id)) else { continue };
135            if !is_plane(strip) || strip.loops.len() != 1 || strip.loops[0].coedges.len() != 4 || strips.contains(&strip.id) {
136                continue;
137            }
138            let (pa, pb) = (a0.add(a1).scale(0.5), b0.add(b1).scale(0.5));
139            // The faces beyond, planar, meeting at a convex angle (not parallel).
140            let (Some(beyond_a), Some(beyond_b)) = (fa.iter().find(|f| f.id != strip.id), fb.iter().find(|f| f.id != strip.id)) else { continue };
141            if !is_plane(beyond_a) || !is_plane(beyond_b) {
142                continue;
143            }
144            let (Ok((on_a, na)), Ok((on_b, nb))) = (brep_blend::fillet::analyze::face_plane_normal(beyond_a, pa), brep_blend::fillet::analyze::face_plane_normal(beyond_b, pb)) else { continue };
145            if na.cross(nb).length() < 1e-9 {
146                continue;
147            }
148            // Their meeting line, at the strip's middle along the edges.
149            let middle = pa.add(pb).scale(0.5);
150            let det = na.dot(nb.cross(da));
151            if det.abs() < 1e-12 {
152                continue;
153            }
154            let corner = nb.cross(da).scale(na.dot(on_a)).add(da.cross(na).scale(nb.dot(on_b))).add(na.cross(nb).scale(da.dot(middle))).scale(1.0 / det);
155            // Convex: the strip's edges lie inside the material's wedge,
156            // behind both outward normals from the corner.
157            if !(pa.sub(corner).dot(nb) < 0.0 && pb.sub(corner).dot(na) < 0.0) {
158                continue;
159            }
160            // Swallowed: the corner's round reaches past both strip edges.
161            let inside = std::f64::consts::PI - na.dot(nb).clamp(-1.0, 1.0).acos();
162            if !(inside > 1e-9 && inside < std::f64::consts::PI - 1e-9) {
163                continue;
164            }
165            let setback = radius / (0.5 * inside).tan();
166            let from_corner = |p: Vec3| {
167                let off = p.sub(corner);
168                off.sub(da.scale(off.dot(da))).length()
169            };
170            if !(setback >= from_corner(pa) && setback >= from_corner(pb)) {
171                continue;
172            }
173            taken[i] = true;
174            taken[j] = true;
175            strips.push(strip.id);
176            corners.push((i, corner));
177        }
178    }
179    if strips.is_empty() {
180        return None;
181    }
182    let healed = crate::delete_faces_and_heal(solid, &strips).ok()?;
183    let mut points: Vec<Vec3> = Vec::new();
184    let mut names: Vec<String> = Vec::new();
185    for (k, point) in edge_points.iter().enumerate() {
186        if !taken[k] {
187            points.push(*point);
188            if let Some(given) = edge_names {
189                names.push(given.get(k).cloned().unwrap_or_default());
190            }
191        }
192    }
193    for &(first, corner) in &corners {
194        points.push(corner);
195        if let Some(given) = edge_names {
196            names.push(given.get(first).cloned().unwrap_or_default());
197        }
198    }
199    Some(fillet_edges(&healed, &points, edge_names.map(|_| names.as_slice()), radius, false, name))
200}
201