Skip to main content

brep_construction/construction/
mill_dome.rs

1//! A ball-end mill held square to a dome: what its finishing passes leave,
2//! read along rays from the dome's centre.
3//!
4//! A five-axis finish holds a ball-end mill of radius `r` along the dome's
5//! normal with its ball touching the dome of radius `R`: every ball centre
6//! lies on the sphere of radius `R + r` about the dome's centre (here the
7//! origin), and the mill's shank reaches away from it. Along the ray from
8//! the origin in the direction `d`, a ball whose centre lies at the angle θ
9//! from `d` is first met at
10//!
11//! `t(θ) = (R + r) cos θ − √(r² − (R + r)² sin² θ)`,
12//!
13//! which grows with θ. So the surface the balls leave is `t` of the angle
14//! from `d` to the nearest centre: the passes enter only through the curves
15//! their centres run on the unit sphere ([`Centres`]: great-circle arcs, as
16//! a pass turned about a line through the origin runs, and circles about an
17//! axis through it, as a pass turned about the table's axis runs).
18
19use crate::Vec3;
20
21/// A curve the ball centres' directions run on the unit sphere.
22#[derive(Clone, Copy, Debug)]
23pub enum CentreCurve {
24    /// From the unit direction `from` turned right-handed about the unit
25    /// `axis` (square to `from`) by `angle`: a great-circle arc.
26    Arc { from: Vec3, axis: Vec3, angle: f64 },
27    /// The whole circle of the directions at the angle `polar` from the unit
28    /// `axis`.
29    Circle { axis: Vec3, polar: f64 },
30    /// One direction.
31    Point(Vec3),
32}
33
34impl CentreCurve {
35    /// The angle from the unit direction `d` to the nearest point of the curve.
36    pub fn angle_to(&self, d: Vec3) -> f64 {
37        let between = |a: Vec3, b: Vec3| a.cross(b).length().atan2(a.dot(b));
38        match *self {
39            CentreCurve::Point(c) => between(d, c),
40            CentreCurve::Circle { axis, polar } => {
41                let off = between(d, axis);
42                (off - polar).abs()
43            }
44            CentreCurve::Arc { from, axis, angle } => {
45                // d's projection on the arc's plane, read as an angle from `from`
46                let side = axis.cross(from);
47                let (x, y) = (d.dot(from), d.dot(side));
48                // the turn from `from`, read the arc's way round, in [0, 2π)
49                let at = (y.atan2(x) * angle.signum()).rem_euclid(std::f64::consts::TAU);
50                let within = at <= angle.abs();
51                if within {
52                    let height = d.dot(axis);
53                    height.abs().atan2((x * x + y * y).sqrt())
54                } else {
55                    let end = from.scale(angle.cos()).add(side.scale(angle.sin()));
56                    between(d, from).min(between(d, end))
57                }
58            }
59        }
60    }
61}
62
63/// The finishing passes: the balls' radius, the dome's, and the curves their
64/// centres' directions run (an arc turning by at most a whole turn).
65#[derive(Clone, Debug)]
66pub struct Centres {
67    pub ball: f64,
68    pub dome: f64,
69    pub curves: Vec<CentreCurve>,
70}
71
72impl Centres {
73    /// Where the ray from the origin along the unit `d` first meets a ball
74    /// at the angle `theta` from it; None past the ball's reach.
75    pub fn reach(&self, theta: f64) -> Option<f64> {
76        let c = self.dome + self.ball;
77        let s = c * theta.sin();
78        (theta.abs() <= std::f64::consts::FRAC_PI_2 && s.abs() <= self.ball).then(|| c * theta.cos() - (self.ball * self.ball - s * s).sqrt())
79    }
80
81    /// The surface the balls leave along the unit `d`: the nearest centre
82    /// curve and where its balls first meet the ray; None where none reaches.
83    pub fn surface(&self, d: Vec3) -> Option<(f64, usize)> {
84        let (index, theta) = self.curves.iter().enumerate().map(|(k, c)| (k, c.angle_to(d))).min_by(|a, b| a.1.total_cmp(&b.1))?;
85        self.reach(theta).map(|t| (t, index))
86    }
87}
88
89/// The chart of the upper half of the sphere of directions: the square
90/// [-1, 1]² onto the unit disc (each side onto a quarter of its circle, by
91/// the elliptical grid map), then the disc onto the half sphere by the
92/// stereographic projection from the lower pole. The square's sides are the
93/// directions of the level plane z = 0.
94pub fn chart_direction(x: f64, y: f64) -> Vec3 {
95    let (u, w) = (x * (1.0 - 0.5 * y * y).max(0.0).sqrt(), y * (1.0 - 0.5 * x * x).max(0.0).sqrt());
96    let rho = u * u + w * w;
97    let d = Vec3::new(2.0 * u, 2.0 * w, 1.0 - rho).scale(1.0 / (1.0 + rho));
98    if x.abs() >= 1.0 || y.abs() >= 1.0 {
99        // on the square's side: level, exactly
100        let flat = Vec3::new(d.x, d.y, 0.0);
101        return flat.scale(1.0 / flat.length());
102    }
103    d.scale(1.0 / d.length())
104}
105
106/// The chart point of the unit direction `d` (z ≥ 0): [`chart_direction`]'s
107/// inverse.
108pub fn direction_chart(d: Vec3) -> [f64; 2] {
109    let (u, w) = (d.x / (1.0 + d.z), d.y / (1.0 + d.z));
110    let r2 = 2.0f64.sqrt();
111    let root = |a: f64| a.max(0.0).sqrt();
112    let x = 0.5 * root(2.0 + u * u - w * w + 2.0 * r2 * u) - 0.5 * root(2.0 + u * u - w * w - 2.0 * r2 * u);
113    let y = 0.5 * root(2.0 - u * u + w * w + 2.0 * r2 * w) - 0.5 * root(2.0 - u * u + w * w - 2.0 * r2 * w);
114    [x.clamp(-1.0, 1.0), y.clamp(-1.0, 1.0)]
115}
116
117/// A finishing program's balls over the dome's upper half, as a field over
118/// [`chart_direction`]'s chart: the height is the distance along the ray
119/// from the origin. Its tubes are the arcs' tori (about each arc's axis) and
120/// each circle's torus about its axis cut into `sectors` stretches (so no
121/// face goes all the way round); its balls are each arc's start (an arc's end
122/// on a circle lies inside that circle's torus) and each point.
123pub struct DomeField {
124    centres: Centres,
125    arcs: Vec<(Vec3, Vec3, f64)>,
126    circles: Vec<(Vec3, f64)>,
127    sectors: usize,
128    balls: Vec<(Vec3, Option<usize>)>,
129    top: f64,
130    /// The parts that may be lowest in each degree of latitude (from -10°)
131    /// and longitude: those within reach of the bin's middle and its spread.
132    bins: Vec<(Vec<usize>, Vec<usize>)>,
133}
134
135const BIN_LATITUDES: usize = 101;
136
137use crate::mill_plan::{Field, Part};
138
139impl DomeField {
140    /// The field of `centres` (each circle about the z axis), cut at `top`.
141    /// Refuses a circle about another axis.
142    pub fn new(centres: Centres, sectors: usize, top: f64) -> Result<Self, String> {
143        let (mut arcs, mut circles, mut balls) = (Vec::new(), Vec::new(), Vec::new());
144        for curve in &centres.curves {
145            match *curve {
146                CentreCurve::Arc { from, axis, angle } => {
147                    if !(angle > 0.0 && angle <= std::f64::consts::TAU) {
148                        return Err("an arc must turn by a positive angle, at most a whole turn".into());
149                    }
150                    arcs.push((from, axis, angle));
151                }
152                CentreCurve::Circle { axis, polar } => {
153                    if !(axis.x == 0.0 && axis.y == 0.0 && axis.z > 0.0) {
154                        return Err("a circle must be about the z axis".into());
155                    }
156                    circles.push((axis, polar));
157                }
158                CentreCurve::Point(c) => balls.push((c, None)),
159            }
160        }
161        let points = balls.len();
162        // each arc's start, its own; an end on a circle is inside that circle's torus
163        let mut starts: Vec<(Vec3, Option<usize>)> = arcs.iter().enumerate().map(|(k, &(from, _, _))| (from, Some(k))).collect();
164        starts.extend(balls.drain(..points));
165        for (k, &(from, axis, angle)) in arcs.iter().enumerate() {
166            let end = from.scale(angle.cos()).add(axis.cross(from).scale(angle.sin()));
167            if !circles.iter().any(|&(c, polar)| (end.dot(c).clamp(-1.0, 1.0).acos() - polar).abs() < 1e-12) {
168                starts.push((end, Some(k)));
169            }
170        }
171        let mut field = DomeField { centres, arcs, circles, sectors: sectors.max(1), balls: starts, top, bins: Vec::new() };
172        let mut bins = Vec::with_capacity(BIN_LATITUDES * 360);
173        for i in 0..BIN_LATITUDES {
174            for j in 0..360 {
175                let (lat, lon) = ((i as f64 - 10.0 + 0.5).to_radians(), (j as f64 + 0.5).to_radians());
176                let d = Vec3::new(lat.cos() * lon.cos(), lat.cos() * lon.sin(), lat.sin());
177                // a bin's points lie within a degree of its middle
178                bins.push(field.scan(d, 1f64.to_radians()));
179            }
180        }
181        field.bins = bins;
182        Ok(field)
183    }
184
185    /// The finishing passes it reads (fixed when it is made: its index of
186    /// the parts in reach is built from them).
187    pub fn centres(&self) -> &Centres {
188        &self.centres
189    }
190
191    fn sphere(&self) -> f64 {
192        self.centres.dome + self.centres.ball
193    }
194
195    /// The arc `k`'s foot angle of `d` (from its start, about its axis) and
196    /// the angle of `d` from its plane.
197    fn arc_angles(&self, k: usize, d: Vec3) -> (f64, f64) {
198        let (from, axis, _) = self.arcs[k];
199        let side = axis.cross(from);
200        let (x, y) = (d.dot(from), d.dot(side));
201        // the foot's turn from the start, in [0, 2π)
202        (y.atan2(x).rem_euclid(std::f64::consts::TAU), d.dot(axis).abs().atan2((x * x + y * y).sqrt()))
203    }
204
205    fn sector_of(&self, d: Vec3) -> usize {
206        let phi = d.y.atan2(d.x).rem_euclid(std::f64::consts::TAU);
207        ((phi / std::f64::consts::TAU * self.sectors as f64) as usize).min(self.sectors - 1)
208    }
209
210    /// The tube `index`'s height along `d` and whether it is read there.
211    fn tube(&self, index: usize, d: Vec3) -> (f64, bool) {
212        if index < self.arcs.len() {
213            let (foot, off) = self.arc_angles(index, d);
214            let t = self.centres.reach(off).unwrap_or(f64::NAN);
215            (t, (0.0..=self.arcs[index].2).contains(&foot))
216        } else {
217            let k = (index - self.arcs.len()) / self.sectors;
218            let sector = (index - self.arcs.len()) % self.sectors;
219            let (axis, polar) = self.circles[k];
220            let off = (d.dot(axis).clamp(-1.0, 1.0).acos() - polar).abs();
221            (self.centres.reach(off).unwrap_or(f64::NAN), self.sector_of(d) == sector)
222        }
223    }
224
225    fn ball(&self, index: usize, d: Vec3) -> (f64, bool) {
226        let (c, own) = self.balls[index];
227        let angle = d.cross(c).length().atan2(d.dot(c));
228        let t = self.centres.reach(angle).unwrap_or(f64::NAN);
229        let covered = own.is_some_and(|k| self.tube(k, d).1);
230        (t, !covered)
231    }
232
233    /// The parts that may be lowest along `d`: the arcs and starts within a
234    /// few of the nearest's longitude, every circle and point near the pole.
235    fn candidates(&self, d: Vec3) -> (Vec<usize>, Vec<usize>) {
236        let lat = d.z.clamp(-1.0, 1.0).asin().to_degrees();
237        let lon = d.y.atan2(d.x).to_degrees().rem_euclid(360.0);
238        let i = ((lat + 10.0).floor().max(0.0) as usize).min(BIN_LATITUDES - 1);
239        let j = (lon.floor() as usize).min(359);
240        if lat >= -10.0 {
241            return self.bins[i * 360 + j].clone();
242        }
243        self.scan(d, 0.0)
244    }
245
246    /// The parts within reach of `d`, and `spread` more.
247    fn scan(&self, d: Vec3, spread: f64) -> (Vec<usize>, Vec<usize>) {
248        let reach = (self.centres.ball / self.sphere()).asin() + 1e-9 + spread;
249        let tubes: Vec<usize> = (0..self.arcs.len() + self.circles.len() * self.sectors)
250            .filter(|&i| {
251                if i < self.arcs.len() {
252                    let (foot, off) = self.arc_angles(i, d);
253                    off <= reach && (foot <= self.arcs[i].2 + reach || foot >= std::f64::consts::TAU - reach)
254                } else {
255                    let (axis, polar) = self.circles[(i - self.arcs.len()) / self.sectors];
256                    (d.dot(axis).clamp(-1.0, 1.0).acos() - polar).abs() <= reach
257                }
258            })
259            .collect();
260        let balls: Vec<usize> = (0..self.balls.len()).filter(|&j| { let c = self.balls[j].0; d.cross(c).length().atan2(d.dot(c)) <= reach }).collect();
261        (tubes, balls)
262    }
263
264    /// The point on the centre curve of `part` nearest `p` (the axis of the
265    /// tube there, or the ball's centre).
266    fn core(&self, part: Part, p: Vec3) -> Vec3 {
267        let c = self.sphere();
268        match part {
269            Part::Tube(i) if i < self.arcs.len() => {
270                let axis = self.arcs[i].1;
271                let q = p.sub(axis.scale(p.dot(axis)));
272                q.scale(c / q.length())
273            }
274            Part::Tube(i) => {
275                let (_, polar) = self.circles[(i - self.arcs.len()) / self.sectors];
276                let plan = (p.x * p.x + p.y * p.y).sqrt();
277                let (cx, cy) = if plan > 0.0 { (p.x / plan, p.y / plan) } else { (1.0, 0.0) };
278                Vec3::new(c * polar.sin() * cx, c * polar.sin() * cy, c * polar.cos())
279            }
280            Part::Ball(j) => self.balls[j].0.scale(c),
281            _ => p,
282        }
283    }
284}
285
286impl Field for DomeField {
287    fn scale(&self) -> f64 {
288        self.centres.ball
289    }
290    fn length(&self) -> f64 {
291        self.centres.dome
292    }
293    fn top(&self) -> f64 {
294        self.top
295    }
296    fn lowest(&self, x: f64, y: f64) -> (f64, Part) {
297        let d = chart_direction(x, y);
298        let (tubes, balls) = self.candidates(d);
299        let mut best = (self.top, Part::Top);
300        let mut take = |z: f64, part: Part| {
301            if z < best.0 || (z == best.0 && part < best.1) {
302                best = (z, part);
303            }
304        };
305        for i in tubes {
306            let (t, read) = self.tube(i, d);
307            if read && t.is_finite() {
308                take(t, Part::Tube(i));
309            }
310        }
311        for j in balls {
312            let (t, read) = self.ball(j, d);
313            if read && t.is_finite() {
314                take(t, Part::Ball(j));
315            }
316        }
317        best
318    }
319    fn height(&self, part: Part, x: f64, y: f64) -> f64 {
320        let d = chart_direction(x, y);
321        let (t, read) = match part {
322            Part::Tube(i) => self.tube(i, d),
323            Part::Ball(j) => self.ball(j, d),
324            Part::Top => (self.top, true),
325            Part::Outside => (f64::INFINITY, false),
326        };
327        if read && t.is_finite() { t } else { f64::INFINITY }
328    }
329    fn continued(&self, part: Part, x: f64, y: f64) -> f64 {
330        let d = chart_direction(x, y);
331        match part {
332            Part::Tube(i) => self.tube(i, d).0,
333            Part::Ball(j) => self.ball(j, d).0,
334            Part::Top => self.top,
335            Part::Outside => f64::NAN,
336        }
337    }
338    /// An arc and its own start meet on the plane through the origin square
339    /// to the arc there; two stretches of a circle's torus on the plane
340    /// through the z axis between them.
341    fn plane(&self, p: Part, q: Part, x: f64, y: f64) -> Option<f64> {
342        let d = chart_direction(x, y);
343        match (p, q) {
344            (Part::Tube(i), Part::Ball(j)) | (Part::Ball(j), Part::Tube(i)) if self.balls[j].1 == Some(i) => {
345                let (from, axis, angle) = self.arcs[i];
346                let at = if self.balls[j].0.sub(from).length() < 1e-12 { 0.0 } else { angle };
347                let tangent = axis.cross(from.scale(at.cos()).add(axis.cross(from).scale(at.sin())));
348                Some(self.ball(j, d).0 * d.dot(tangent))
349            }
350            (Part::Tube(i), Part::Tube(k)) if i >= self.arcs.len() && k >= self.arcs.len() && (i - self.arcs.len()) / self.sectors == (k - self.arcs.len()) / self.sectors => {
351                let (a, b) = ((i - self.arcs.len()) % self.sectors, (k - self.arcs.len()) % self.sectors);
352                // the boundary between neighbouring stretches (the later's start)
353                let later = if (a + 1) % self.sectors == b { b } else { a };
354                let phi = std::f64::consts::TAU * later as f64 / self.sectors as f64;
355                Some(self.tube(i, d).0 * (d.y * phi.cos() - d.x * phi.sin()))
356            }
357            _ => None,
358        }
359    }
360    /// Each arc's end on a circle: the arc's torus and the circle's meet
361    /// there, at the dome itself, and their boundary turns a corner.
362    fn seeds(&self) -> Vec<[f64; 2]> {
363        let mut seeds = Vec::new();
364        for &(from, axis, angle) in &self.arcs {
365            let end = from.scale(angle.cos()).add(axis.cross(from).scale(angle.sin()));
366            if self.circles.iter().any(|&(c, polar)| (end.dot(c).clamp(-1.0, 1.0).acos() - polar).abs() < 1e-12) {
367                seeds.push(direction_chart(end));
368            }
369        }
370        seeds
371    }
372
373    fn witnesses(&self, cell: f64) -> Vec<[f64; 2]> {
374        let mut points = Vec::new();
375        let step = 0.5 * cell;
376        for &(from, axis, angle) in &self.arcs {
377            let count = ((angle / step).ceil() as usize).max(1);
378            for k in 0..=count {
379                let a = angle * k as f64 / count as f64;
380                points.push(direction_chart(from.scale(a.cos()).add(axis.cross(from).scale(a.sin()))));
381            }
382        }
383        for &(_, polar) in &self.circles {
384            let count = ((std::f64::consts::TAU * polar.sin() / step).ceil() as usize).max(8);
385            for k in 0..count {
386                let phi = std::f64::consts::TAU * (k as f64 + 0.5) / count as f64;
387                points.push(direction_chart(Vec3::new(polar.sin() * phi.cos(), polar.sin() * phi.sin(), polar.cos())));
388            }
389        }
390        for &(c, _) in &self.balls {
391            if c.z >= 0.0 {
392                points.push(direction_chart(c));
393            }
394        }
395        points
396    }
397}
398
399use crate::mill_faces::Faces;
400use crate::{make_arc, make_revolution, make_sphere_surface_framed, NurbsSurface};
401
402impl Faces for DomeField {
403    fn surface(&self, part: Part) -> Result<NurbsSurface, String> {
404        let (c, r) = (self.sphere(), self.centres.ball);
405        let origin = Vec3::new(0.0, 0.0, 0.0);
406        match part {
407            // the side of each torus toward the origin: its section within
408            // 100° (an arc's) or less (a circle's, kept off its axis) of the
409            // inward direction, turned through its arc or stretch
410            Part::Tube(i) if i < self.arcs.len() => {
411                let (from, axis, angle) = self.arcs[i];
412                let section = make_arc(from.scale(c), from.scale(-1.0), axis, r, -100f64.to_radians(), 100f64.to_radians())?;
413                make_revolution(origin, axis, &section, angle)
414            }
415            Part::Tube(i) => {
416                let k = (i - self.arcs.len()) / self.sectors;
417                let sector = (i - self.arcs.len()) % self.sectors;
418                let (axis, polar) = self.circles[k];
419                let phi = std::f64::consts::TAU * sector as f64 / self.sectors as f64;
420                let n = Vec3::new(polar.sin() * phi.cos(), polar.sin() * phi.sin(), polar.cos());
421                let north = Vec3::new(-polar.cos() * phi.cos(), -polar.cos() * phi.sin(), polar.sin());
422                // within 100° of inward, short of the axis by a tenth of the
423                // centre circle's radius (a spindle torus's section is kept
424                // off the axis it would cross; a point past it is refused by
425                // the inversion, not built wrong)
426                let off = c * polar.sin();
427                let clear = |beta: f64| (0..=40).all(|k| {
428                    let b = -beta + 2.0 * beta * k as f64 / 40.0;
429                    let q = n.scale(c).add(n.scale(-r * b.cos())).add(north.scale(r * b.sin()));
430                    (q.x * q.x + q.y * q.y).sqrt() >= 0.1 * off
431                });
432                let mut limit = 100f64.to_radians();
433                while limit > 1f64.to_radians() && !clear(limit) {
434                    limit -= 0.5f64.to_radians();
435                }
436                let section = make_arc(n.scale(c), n.scale(-1.0), north, r, -limit, limit)?;
437                make_revolution(origin, axis, &section, std::f64::consts::TAU / self.sectors as f64)
438            }
439            Part::Ball(j) => {
440                let centre = self.balls[j].0;
441                let side = centre.perpendicular()?;
442                make_sphere_surface_framed(centre.scale(c), r, side, Some(centre))
443            }
444            Part::Top => Err("the dome's top is not cut".into()),
445            Part::Outside => Err("no surface outside".into()),
446        }
447    }
448
449    fn outward(&self, part: Part, at: Vec3) -> Vec3 {
450        self.core(part, at).sub(at)
451    }
452
453    fn lift(&self, chart: Vec3) -> Vec3 {
454        chart_direction(chart.x, chart.y).scale(chart.z)
455    }
456}
457