Skip to main content

draftwright/
radius.rs

1//! Radius leader evidence and geometry, independent of the router's chosen sites.
2use std::collections::BTreeMap;
3
4use serde::{Deserialize, Serialize};
5
6use crate::arc::{ProfileArc, Span};
7use crate::bridge::Feature;
8use crate::model::Analysis;
9
10type P = [f64; 2];
11
12pub(crate) const TOLERANCE: f64 = 0.002;
13pub(crate) const RADIAL_DEGREES: f64 = 15.0;
14
15/// A trimmed cylinder section or toroidal meridian, with the material side from its face normal.
16#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
17#[serde(deny_unknown_fields)]
18pub struct RadiusArc {
19    pub arc: ProfileArc,
20    pub axis: [f64; 3],
21    pub centre_open: bool,
22    /// Proven points in the middle half of the trimmed face, used by candidate generation.
23    pub tips: Vec<[f64; 3]>,
24}
25
26pub fn evidence(part: &haecceity::Part, features: &[Feature]) -> BTreeMap<String, Vec<RadiusArc>> {
27    let mut out = BTreeMap::new();
28    for f in features
29        .iter()
30        .filter(|f| matches!(f.kind.as_str(), "blend" | "fillet" | "cylindrical_profile"))
31    {
32        let Some(r) = f.parameters.get("radius").and_then(|v| v.as_f64()) else {
33            continue;
34        };
35        let mut arcs = Vec::new();
36        for &face in &f.faces {
37            let Some(data) = part.faces.get(face) else {
38                continue;
39            };
40            use haecceity::geom::Surface;
41            let radius = match &data.surface {
42                Surface::Cylinder { radius, .. } => *radius,
43                Surface::Torus { major, minor, .. } if major > minor => *minor,
44                _ => continue,
45            };
46            if (radius - r).abs() > TOLERANCE {
47                continue;
48            }
49            let (Some(domain), Some((u0, u1, v0, v1))) = (part.domain(face), part.uv_bounds(face))
50            else {
51                continue;
52            };
53            if ![u0, u1, v0, v1].iter().all(|x| x.is_finite()) || u1 - u0 <= 1e-9 {
54                continue;
55            }
56            let mut sections = Vec::new();
57            match &data.surface {
58                Surface::Cylinder { frame, .. } => sections.push((
59                    ProfileArc {
60                        centre: frame.origin,
61                        radius,
62                        u: frame.x,
63                        v: frame.y,
64                        start: u0,
65                        sweep: u1 - u0,
66                    },
67                    frame.z,
68                    None,
69                )),
70                Surface::Torus { frame, major, .. } if v1 - v0 > 1e-9 => {
71                    // A proven meridian is a real minor-radius circle. Only sections whose
72                    // plane is square to the drawn view will be used; oblique views remain
73                    // explicitly unverifiable. Do not invent stations on the major trim ends.
74                    for fraction in [0.25, 0.5, 0.75] {
75                        let u = u0 + fraction * (u1 - u0);
76                        let radial = [0, 1, 2].map(|k| frame.x[k] * u.cos() + frame.y[k] * u.sin());
77                        let axis = [
78                            radial[1] * frame.z[2] - radial[2] * frame.z[1],
79                            radial[2] * frame.z[0] - radial[0] * frame.z[2],
80                            radial[0] * frame.z[1] - radial[1] * frame.z[0],
81                        ];
82                        sections.push((
83                            ProfileArc {
84                                centre: [0, 1, 2].map(|k| frame.origin[k] + major * radial[k]),
85                                radius,
86                                u: radial,
87                                v: frame.z,
88                                start: v0,
89                                sweep: v1 - v0,
90                            },
91                            axis,
92                            Some(u),
93                        ));
94                    }
95                }
96                _ => {}
97            }
98            for (arc, axis, meridian) in sections {
99                let mut tips = Vec::new();
100                for i in 4..=12 {
101                    let angle = arc.start + arc.sweep * i as f64 / 16.0;
102                    if let Some(u) = meridian {
103                        if domain.contains(u, angle) {
104                            tips.push(data.surface.value(u, angle));
105                        }
106                    } else {
107                        for fraction in [0.5, 0.25, 0.75] {
108                            let v = v0 + (v1 - v0) * fraction;
109                            if domain.contains(angle, v) {
110                                tips.push(data.surface.value(angle, v));
111                                break; // One proven axial copy per end-on angular station.
112                            }
113                        }
114                    }
115                }
116                if !tips.is_empty() {
117                    arcs.push(RadiusArc {
118                        arc,
119                        axis,
120                        centre_open: data.reversed,
121                        tips,
122                    });
123                }
124            }
125        }
126        if !arcs.is_empty() {
127            out.insert(f.id.clone(), arcs);
128        }
129    }
130    out
131}
132
133#[derive(Clone, Debug)]
134pub(crate) struct Projected {
135    pub centre: P,
136    pub radius: f64,
137    pub span: Span,
138    pub tips: Vec<P>,
139}
140
141impl Projected {
142    pub fn on_arc(&self, tip: P) -> bool {
143        let d = [tip[0] - self.centre[0], tip[1] - self.centre[1]];
144        (d[0].hypot(d[1]) - self.radius).abs() <= TOLERANCE
145            && self
146                .span
147                .contains(d[1].atan2(d[0]), TOLERANCE / self.radius.max(1e-9))
148    }
149
150    pub fn middle(&self, tip: P) -> bool {
151        Span {
152            start: self.span.start + self.span.sweep * 0.25,
153            sweep: self.span.sweep * 0.5,
154        }
155        .contains(
156            (tip[1] - self.centre[1]).atan2(tip[0] - self.centre[0]),
157            TOLERANCE / self.radius.max(1e-9),
158        )
159    }
160
161    /// One radial direction; its opposite is equally valid, independent of material side.
162    pub fn radial_direction(&self, tip: P) -> P {
163        [0, 1].map(|k| self.centre[k] - tip[k])
164    }
165
166    pub fn violation(&self, [tip, elbow]: [P; 2]) -> Option<&'static str> {
167        if !self.on_arc(tip) {
168            return Some("the tip misses the named trimmed arc");
169        }
170        if !self.middle(tip) {
171            return Some("the tip is outside the middle 25–75% of the sweep, near a tangent end");
172        }
173        let u = self.radial_direction(tip);
174        let v = [elbow[0] - tip[0], elbow[1] - tip[1]];
175        let norm = u[0].hypot(u[1]) * v[0].hypot(v[1]);
176        let dot = (u[0] * v[0] + u[1] * v[1]).abs();
177        if norm <= 1e-12 {
178            Some("the shaft has zero length")
179        } else if dot < RADIAL_DEGREES.to_radians().cos() * norm - 1e-9 {
180            Some("the shaft is more than 15 degrees off radial")
181        } else {
182            None
183        }
184    }
185
186    pub fn accepts(&self, shaft: [P; 2]) -> bool {
187        self.violation(shaft).is_none()
188    }
189
190    /// Whether a compliant shaft is also well placed: its tip in the middle quarter of the
191    /// sweep (37.5–62.5%) and within 7.5 degrees of radial. The planner prefers such a route
192    /// to a merely compliant one (maintainer 2026-10-25: point at the arc's middle).
193    pub fn centred(&self, [tip, elbow]: [P; 2]) -> bool {
194        let middle = Span {
195            start: self.span.start + self.span.sweep * 0.375,
196            sweep: self.span.sweep * 0.25,
197        };
198        let u = self.radial_direction(tip);
199        let v = [elbow[0] - tip[0], elbow[1] - tip[1]];
200        let norm = u[0].hypot(u[1]) * v[0].hypot(v[1]);
201        self.accepts([tip, elbow])
202            && middle.contains(
203                (tip[1] - self.centre[1]).atan2(tip[0] - self.centre[0]),
204                TOLERANCE / self.radius.max(1e-9),
205            )
206            && (u[0] * v[0] + u[1] * v[1]).abs() >= 7.5f64.to_radians().cos() * norm - 1e-9
207    }
208}
209
210/// A profile feature's proven arcs seen end-on (an obround slot's ends), as radius evidence:
211/// sampled tips span the middle half of each sweep, as [`evidence`]'s do.
212pub(crate) fn profile(
213    a: &Analysis,
214    id: &str,
215    toward: [f64; 3],
216    page: impl Fn([f64; 3]) -> P,
217) -> Vec<Projected> {
218    a.profile_arcs
219        .get(id)
220        .into_iter()
221        .flatten()
222        .filter(|arc| {
223            let [u, v] = [arc.u, arc.v];
224            seen_end_on(
225                [
226                    u[1] * v[2] - u[2] * v[1],
227                    u[2] * v[0] - u[0] * v[2],
228                    u[0] * v[1] - u[1] * v[0],
229                ],
230                toward,
231            )
232        })
233        .map(|arc| {
234            let (centre, radius, span) = arc.projected(&page);
235            let tips = (4..=12)
236                .map(|i| page(arc.point(arc.start + arc.sweep * i as f64 / 16.0)))
237                .collect();
238            Projected {
239                centre,
240                radius,
241                span,
242                tips,
243            }
244        })
245        .collect()
246}
247
248/// Whether a view looking along *toward* sees an arc about *axis* end-on (the planner's arc
249/// sites and lint's arc evidence share this test).
250pub(crate) fn seen_end_on(axis: [f64; 3], toward: [f64; 3]) -> bool {
251    let n = axis.iter().map(|x| x * x).sum::<f64>().sqrt();
252    n > 1e-12 && (axis.iter().zip(toward).map(|(a, b)| a * b).sum::<f64>() / n).abs() > 1.0 - 1e-9
253}
254
255/// Read end-on cylinder profiles and proven end-on minor-circle meridians of tori.
256/// Older analyses can still prove a straight blend from its rolling axis and trimmed samples.
257pub(crate) fn projected(
258    a: &Analysis,
259    id: &str,
260    toward: [f64; 3],
261    page: impl Fn([f64; 3]) -> P,
262) -> Result<Vec<Projected>, String> {
263    let end_on = |axis: [f64; 3]| seen_end_on(axis, toward);
264    if let Some(arcs) = a.radius_arcs.get(id) {
265        let shown: Vec<_> = arcs
266            .iter()
267            .filter(|arc| end_on(arc.axis))
268            .map(|arc| {
269                let (centre, radius, span) = arc.arc.projected(&page);
270                let mut tips: Vec<P> = Vec::new();
271                for p in arc.tips.iter().map(|q| page(*q)) {
272                    if !tips.iter().any(|q| (p[0] - q[0]).hypot(p[1] - q[1]) < 1e-8) {
273                        tips.push(p);
274                    }
275                }
276                Projected {
277                    centre,
278                    radius,
279                    span,
280                    tips,
281                }
282            })
283            .collect();
284        return if shown.is_empty() {
285            Err("the view does not show a proven circular radius section end-on".into())
286        } else {
287            Ok(shown)
288        };
289    }
290    let f = a
291        .features
292        .iter()
293        .find(|f| f.id == id)
294        .ok_or("the radius feature is absent")?;
295    let path = f
296        .parameters
297        .get("path")
298        .ok_or("no cylindrical arc centre and trim evidence is recorded for this fillet")?;
299    if path.get("normal").is_some() {
300        return Err("a circular-path/toroidal blend has no single projected minor-arc centre; radial direction cannot be verified from its sampled points".into());
301    }
302    let frame = crate::bridge::holes::frame(a);
303    let axis = crate::bridge::holes::point(path.get("direction"))
304        .map(|d| crate::bridge::holes::dir_to_part(&frame, d))
305        .ok_or("the radius path has no direction")?;
306    if !end_on(axis) {
307        return Err("the view does not show the radius end-on".into());
308    }
309    let at = crate::bridge::holes::point(path.get("at"))
310        .map(|q| crate::bridge::holes::to_part(&frame, q))
311        .ok_or("the radius path has no centre")?;
312    let r = f
313        .parameters
314        .get("radius")
315        .and_then(|v| v.as_f64())
316        .filter(|r| r.is_finite() && *r > 0.0)
317        .ok_or("the radius is unreadable")?;
318    let sites = a
319        .blend_sites
320        .get(id)
321        .filter(|s| !s.is_empty())
322        .ok_or("the radius has no proven trimmed-surface points")?;
323    let centre = page(at);
324    let tips: Vec<_> = sites.iter().map(|q| page(*q)).collect();
325    let angle = |p: P| (p[1] - centre[1]).atan2(p[0] - centre[0]);
326    let reference = angle(tips[0]);
327    let (lo, hi) = tips
328        .iter()
329        .map(|q| crate::arc::turn(angle(*q), reference))
330        .fold((0.0f64, 0.0f64), |(lo, hi), t| (lo.min(t), hi.max(t)));
331    if hi - lo <= 1e-6 {
332        return Err("a lone angular sample cannot prove the arc's tangent ends".into());
333    }
334    // Scale is isotropic; choose a part direction perpendicular to the line of sight.
335    let seed = if axis[0].abs() < 0.9 {
336        [1.0, 0.0, 0.0]
337    } else {
338        [0.0, 1.0, 0.0]
339    };
340    let norm = axis.iter().map(|x| x * x).sum::<f64>();
341    let along = seed.iter().zip(axis).map(|(x, y)| x * y).sum::<f64>() / norm;
342    let u = [0, 1, 2].map(|k| seed[k] - along * axis[k]);
343    let n = u.iter().map(|x| x * x).sum::<f64>().sqrt();
344    let edge = page([0, 1, 2].map(|k| at[k] + r * u[k] / n));
345    Ok(vec![Projected {
346        centre,
347        radius: (edge[0] - centre[0]).hypot(edge[1] - centre[1]),
348        span: Span {
349            start: reference + lo - (hi - lo) * 0.5,
350            sweep: (hi - lo) * 2.0,
351        },
352        tips,
353    }])
354}
355
356#[cfg(test)]
357mod tests {
358    use super::*;
359    use std::f64::consts::PI;
360
361    fn quarter() -> Projected {
362        Projected {
363            centre: [0.0, 0.0],
364            radius: 3.0,
365            span: Span {
366                start: 0.0,
367                sweep: PI / 2.0,
368            },
369            tips: Vec::new(),
370        }
371    }
372
373    fn shaft(degrees: f64, deviation: f64) -> [P; 2] {
374        let angle = degrees.to_radians();
375        let tip = [3.0 * angle.cos(), 3.0 * angle.sin()];
376        let direction = angle + PI + deviation.to_radians();
377        [
378            tip,
379            [
380                tip[0] + 10.0 * direction.cos(),
381                tip[1] + 10.0 * direction.sin(),
382            ],
383        ]
384    }
385
386    #[test]
387    fn radial_radius_from_either_side_and_tolerance_boundaries() {
388        let arc = quarter();
389        for angle in [22.5, 45.0, 67.5] {
390            for deviation in [-15.0, 0.0, 15.0, 165.0, 180.0, 195.0] {
391                assert!(arc.accepts(shaft(angle, deviation)));
392            }
393        }
394    }
395
396    #[test]
397    fn tangent_ends_are_not_radius_targets() {
398        for angle in [0.0, 10.0, 80.0, 90.0] {
399            assert!(!quarter().accepts(shaft(angle, 0.0)));
400        }
401    }
402
403    #[test]
404    fn off_radial_shafts_are_rejected() {
405        for deviation in [-16.0, 16.0, 32.0, 90.0] {
406            assert!(!quarter().accepts(shaft(45.0, deviation)));
407        }
408    }
409
410    #[test]
411    fn zero_length_shafts_are_rejected() {
412        let arc = quarter();
413        let tip = shaft(45.0, 0.0)[0];
414        assert!(!arc.accepts([tip, tip]));
415    }
416}