Skip to main content

brep_construction/construction/
mill_plan.rs

1//! The plan of a ball-end mill's lower envelope over a box: which surface is
2//! lowest where, as a graph of exact boundary curves (the second piece of the
3//! ball-end raster construction; the faces are built on it next).
4//!
5//! The envelope ([`BallEnvelope`]) over each point of the box is the lowest
6//! of the capsules' parts, read by SURFACE: one cylinder for every run of
7//! moves along one line ([`Part::Tube`], the run's moves joined end to end),
8//! one sphere for every distinct ball centre ([`Part::Ball`], the ball two
9//! moves share at their joint once), and the stock's top ([`Part::Top`])
10//! wherever nothing reaches below it. A ball is never lower than a tube of its
11//! own (a move ending at its centre) where that tube's foot lies on the move,
12//! so there the tube is read: the boundary between a tube and its own ball is
13//! the plane square to the move through the ball's centre, found exactly, and
14//! no rounding tie at the joint makes a ball region of no width.
15//!
16//! The plan is read on a grid of the given cell: each node labelled by its
17//! part, each grid edge whose ends differ crossed where its two parts trade
18//! places (bisected to rounding on the pair's own comparison), and the
19//! crossings linked through the cells they bound. A cell of two parts and two
20//! crossings links them; a cell of two parts crossed four times is read by
21//! its centre. A cell where three or more parts meet holds a VERTEX: it is
22//! solved by Newton on the pairs' equations (the difference of two heights;
23//! for a tube and its own ball the plane between them), or the cell is
24//! quartered until it is (down to 1e-11 of the cell, where its centre is
25//! taken). A part met inside a grid edge whose ends agree (a region narrower
26//! than the cell where the grid crosses it) is refused, never guessed: the
27//! caller reads again at a smaller cell. A region the grid misses whole (no
28//! node in it, no side through it) is caught where it holds a witness: each
29//! move's lowest line (below its centres, at half the cell's spacing) and
30//! each ball's lowest point; a part lowest at one that the plan does not
31//! name is refused the same way. The cell is the caller's: a region that
32//! holds no witness and is narrower than the cell everywhere is not seen.
33//!
34//! The result is checked before it is returned: at every crossing the two
35//! parts' heights agree to 1e-9 of the radius and nothing else is lower
36//! there; at every vertex its parts' heights agree and nothing else is lower.
37
38use crate::mill_envelope::{ball_underside, BallEnvelope};
39use crate::Vec3;
40use std::collections::HashMap;
41
42/// A surface the envelope lies on over part of the plan.
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
44pub enum Part {
45    /// The cylinder about a run of moves along one line (the run's index).
46    Tube(usize),
47    /// The sphere about one ball centre (the centre's index).
48    Ball(usize),
49    /// The stock's top, where nothing cuts below it.
50    Top,
51    /// Beyond the box (the right side of a wall edge).
52    Outside,
53}
54
55/// A point where three or more parts meet, or where a boundary meets the
56/// box's side, or a corner of the box (lifted to the envelope there).
57#[derive(Clone, Debug)]
58pub struct PlanVertex {
59    pub point: Vec3,
60}
61
62/// A boundary curve of the plan from one vertex to another: `left` lies to
63/// its left in plan (looking down), `right` to its right (`Outside` along
64/// the box's sides, which run counter-clockwise). `points` are on the curve,
65/// lifted to the envelope, the vertices' own points first and last.
66#[derive(Clone, Debug)]
67pub struct PlanEdge {
68    pub from: usize,
69    pub to: usize,
70    pub left: Part,
71    pub right: Part,
72    pub points: Vec<Vec3>,
73}
74
75/// The plan's graph, and the surfaces its parts name.
76#[derive(Clone, Debug)]
77pub struct Plan {
78    pub vertices: Vec<PlanVertex>,
79    pub edges: Vec<PlanEdge>,
80    /// Each tube's run: the moves (indices into the envelope's segments) along
81    /// its line, in order.
82    pub runs: Vec<Vec<usize>>,
83    /// Each ball's centre.
84    pub centres: Vec<Vec3>,
85    /// The box [x0, x1] × [y0, y1] and the stock's top.
86    pub bounds: [f64; 4],
87    pub top: f64,
88}
89
90/// What a plan reads: over each point (x, y) of its chart, the part lowest
91/// there and its height (the stock's top where nothing cuts below it), and
92/// each part's own height and surface (continued past where it is read).
93/// A mill's envelope over level ground reads in plan (x, y) and height z; a
94/// dome's reads directions in a chart of the sphere, and the distance along
95/// each ray.
96pub trait Field {
97    /// The length the tolerances are shares of (the ball's radius).
98    fn scale(&self) -> f64;
99    /// The length one unit of the chart spans, about (1 in plan).
100    fn length(&self) -> f64;
101    /// The stock's top: the height read where nothing cuts below it.
102    fn top(&self) -> f64;
103    /// The lowest part over (x, y) and its height; ties to the lesser part.
104    fn lowest(&self, x: f64, y: f64) -> (f64, Part);
105    /// The part's height over (x, y), +∞ where it is not read.
106    fn height(&self, part: Part, x: f64, y: f64) -> f64;
107    /// The part's surface continued past where it is read (NaN past its
108    /// reach), for the boundary equations.
109    fn continued(&self, part: Part, x: f64, y: f64) -> f64;
110    /// For two parts that meet where one of them stops being read (a tube
111    /// and its own ball, two stretches of one surface), the signed distance
112    /// of the point from the surface they meet on; None for parts that meet
113    /// where their heights agree.
114    fn plane(&self, p: Part, q: Part, x: f64, y: f64) -> Option<f64>;
115    /// Points (in the chart) each part that is lowest anywhere is lowest at
116    /// or near, read at a grid of `cell`: a part lowest at one that the plan
117    /// does not name is narrower than the cell.
118    fn witnesses(&self, cell: f64) -> Vec<[f64; 2]>;
119    /// Points (in the chart) where a boundary turns a corner that no third
120    /// part marks (two parts meeting at a point of both their centre
121    /// curves): each is made a vertex of the plan, its cell read down to it.
122    fn seeds(&self) -> Vec<[f64; 2]> {
123        Vec::new()
124    }
125
126    /// Whether `p` is read below `q` at (x, y) (the pair's own comparison,
127    /// ties to the lesser part).
128    fn below(&self, p: Part, q: Part, x: f64, y: f64) -> bool {
129        let (hp, hq) = (self.height(p, x, y), self.height(q, x, y));
130        hp < hq || (hp == hq && p < q)
131    }
132
133    /// The equation of the boundary between `p` and `q` at (x, y): zero on it.
134    fn equation(&self, p: Part, q: Part, x: f64, y: f64) -> f64 {
135        self.plane(p, q, x, y).unwrap_or_else(|| self.continued(p, x, y) - self.continued(q, x, y))
136    }
137
138    /// Whether (x, y) lies on the curve where `p` and `q` meet, to
139    /// `tolerance`: their surfaces at one height there, and on the surface
140    /// they meet on where they have one.
141    fn meets(&self, p: Part, q: Part, x: f64, y: f64, tolerance: f64) -> bool {
142        self.plane(p, q, x, y).is_none_or(|d| d.abs() <= tolerance) && (self.continued(p, x, y) - self.continued(q, x, y)).abs() <= tolerance
143    }
144}
145
146/// The mill's envelope over level ground as a field over its plan, cut at
147/// `top`.
148pub fn ball_field(envelope: &BallEnvelope, top: f64) -> impl Field + '_ {
149    Parts::new(envelope, top)
150}
151
152/// The parts of an envelope, by surface.
153struct Parts<'a> {
154    envelope: &'a BallEnvelope,
155    run_of: Vec<usize>,
156    runs: Vec<Vec<usize>>,
157    /// Each move's start and end centre's index.
158    centre_of: Vec<[usize; 2]>,
159    centres: Vec<Vec3>,
160    top: f64,
161}
162
163impl<'a> Parts<'a> {
164    fn new(envelope: &'a BallEnvelope, top: f64) -> Self {
165        let segments = envelope.segments();
166        // Centres equal to the bit are one ball.
167        let mut index: HashMap<[u64; 3], usize> = HashMap::new();
168        let mut centres = Vec::new();
169        let mut centre = |p: Vec3| {
170            *index.entry([p.x.to_bits(), p.y.to_bits(), p.z.to_bits()]).or_insert_with(|| {
171                centres.push(p);
172                centres.len() - 1
173            })
174        };
175        let centre_of: Vec<[usize; 2]> = segments.iter().map(|&(a, b)| [centre(a), centre(b)]).collect();
176        // A move joins the run before it where it starts at that run's end and
177        // runs along its line the same way (directions within 1e-12).
178        let mut runs: Vec<Vec<usize>> = Vec::new();
179        let mut run_of = Vec::with_capacity(segments.len());
180        for (k, &(a, b)) in segments.iter().enumerate() {
181            let joins = k > 0 && {
182                let (pa, pb) = segments[k - 1];
183                let (d0, d1) = (pb.sub(pa), b.sub(a));
184                let (l0, l1) = (d0.length(), d1.length());
185                l0 > 0.0 && l1 > 0.0 && centre_of[k - 1][1] == centre_of[k][0] && {
186                    let (u0, u1) = (d0.scale(1.0 / l0), d1.scale(1.0 / l1));
187                    u0.dot(u1) > 0.0 && u0.cross(u1).length() <= 1e-12
188                }
189            };
190            if !joins {
191                runs.push(Vec::new());
192            }
193            runs.last_mut().unwrap().push(k);
194            run_of.push(runs.len() - 1);
195        }
196        Parts { envelope, run_of, runs, centre_of, centres, top }
197    }
198
199    fn radius(&self) -> f64 {
200        self.envelope.radius()
201    }
202
203    /// Whether `centre` is an end of the run `run` (its ball is the run's own).
204    fn own(&self, run: usize, centre: usize) -> bool {
205        let moves = &self.runs[run];
206        self.centre_of[moves[0]][0] == centre || self.centre_of[*moves.last().unwrap()][1] == centre
207    }
208
209    /// The lowest part over (x, y) and its height (`Top` at the top where
210    /// nothing reaches below it). A ball is passed over where a tube of its
211    /// own reaches; ties go to the lesser part (a tube before a ball).
212    fn lowest(&self, x: f64, y: f64) -> (f64, Part) {
213        let mut best = (self.top, Part::Top);
214        let mut take = |z: f64, part: Part| {
215            if z < best.0 || (z == best.0 && part < best.1) {
216                best = (z, part);
217            }
218        };
219        let candidates = self.envelope.candidates(x, y);
220        let read: Vec<[Option<f64>; 3]> = candidates.iter().map(|&k| self.envelope.capsule_parts(k, x, y)).collect();
221        // the centres a tube of their own covers here
222        let covered: Vec<usize> = candidates.iter().zip(&read).filter(|(_, r)| r[2].is_some()).flat_map(|(&k, _)| self.centre_of[k]).collect();
223        for (&k, [start, end, tube]) in candidates.iter().zip(&read) {
224            if let Some(z) = tube {
225                take(*z, Part::Tube(self.run_of[k]));
226            }
227            for (z, c) in [(start, self.centre_of[k][0]), (end, self.centre_of[k][1])] {
228                if let Some(z) = z {
229                    if !covered.contains(&c) {
230                        take(*z, Part::Ball(c));
231                    }
232                }
233            }
234        }
235        best
236    }
237
238    /// Whether a tube of the ball `c`'s own (a move ending at it) reaches over
239    /// (x, y), where that tube is never above the ball.
240    fn covered(&self, c: usize, x: f64, y: f64, candidates: &[usize]) -> bool {
241        candidates.iter().any(|&k| self.centre_of[k].contains(&c) && self.envelope.capsule_parts(k, x, y)[2].is_some())
242    }
243
244    /// The part's height over (x, y), +∞ where it does not reach (a ball
245    /// covered by its own tube counted as not reaching).
246    fn height(&self, part: Part, x: f64, y: f64) -> f64 {
247        match part {
248            Part::Top => self.top,
249            Part::Outside => f64::INFINITY,
250            Part::Tube(run) => self.runs[run].iter().filter_map(|&k| self.envelope.capsule_parts(k, x, y)[2]).fold(f64::INFINITY, f64::min),
251            Part::Ball(c) => {
252                let candidates = self.envelope.candidates(x, y);
253                if self.covered(c, x, y, candidates) {
254                    f64::INFINITY
255                } else {
256                    ball_underside(self.centres[c], self.radius(), x, y).unwrap_or(f64::INFINITY)
257                }
258            }
259        }
260    }
261
262    /// The part's surface continued past where it is read (a tube's whole
263    /// line's cylinder, a ball inside its rim), for the vertex equations.
264    fn continued(&self, part: Part, x: f64, y: f64) -> f64 {
265        match part {
266            Part::Top => self.top,
267            Part::Outside => f64::NAN,
268            Part::Tube(run) => self.envelope.tube_root(self.runs[run][0], x, y).map_or(f64::NAN, |(z, _)| z),
269            Part::Ball(c) => ball_underside(self.centres[c], self.radius(), x, y).unwrap_or(f64::NAN),
270        }
271    }
272
273    /// A tube and its own ball meet on the plane through the ball's centre
274    /// square to the run: the signed distance of the ball's underside point
275    /// from it (NaN where the ball does not reach).
276    fn own_plane(&self, p: Part, q: Part, x: f64, y: f64) -> Option<f64> {
277        let ((Part::Tube(tube), Part::Ball(ball)) | (Part::Ball(ball), Part::Tube(tube))) = (p, q) else {
278            return None;
279        };
280        if !self.own(tube, ball) {
281            return None;
282        }
283        let moves = &self.runs[tube];
284        let (a, b) = (self.envelope.segments()[moves[0]].0, self.envelope.segments()[*moves.last().unwrap()].1);
285        let Ok(axis) = b.sub(a).normalized() else { return Some(f64::NAN) };
286        let c = self.centres[ball];
287        Some(ball_underside(c, self.radius(), x, y).map_or(f64::NAN, |z| Vec3::new(x - c.x, y - c.y, z - c.z).dot(axis)))
288    }
289}
290
291impl<'a> Field for Parts<'a> {
292    fn scale(&self) -> f64 {
293        self.radius()
294    }
295    fn length(&self) -> f64 {
296        1.0
297    }
298    fn top(&self) -> f64 {
299        self.top
300    }
301    fn lowest(&self, x: f64, y: f64) -> (f64, Part) {
302        Parts::lowest(self, x, y)
303    }
304    fn height(&self, part: Part, x: f64, y: f64) -> f64 {
305        Parts::height(self, part, x, y)
306    }
307    fn continued(&self, part: Part, x: f64, y: f64) -> f64 {
308        Parts::continued(self, part, x, y)
309    }
310    fn plane(&self, p: Part, q: Part, x: f64, y: f64) -> Option<f64> {
311        self.own_plane(p, q, x, y)
312    }
313    /// Each run's lowest line (below its moves, at half the cell's spacing)
314    /// and each ball's lowest point.
315    fn witnesses(&self, cell: f64) -> Vec<[f64; 2]> {
316        let mut points: Vec<[f64; 2]> = self.centres.iter().map(|c| [c.x, c.y]).collect();
317        for &(a, b) in self.envelope.segments() {
318            let length = ((b.x - a.x).powi(2) + (b.y - a.y).powi(2)).sqrt();
319            let count = ((2.0 * length / cell).ceil() as usize).min(1 << 20);
320            for k in 1..count {
321                let t = k as f64 / count as f64;
322                points.push([a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t]);
323            }
324        }
325        points
326    }
327}
328
329/// A point where a grid edge's two parts trade places.
330#[derive(Clone, Debug)]
331struct Crossing {
332    point: Vec3,
333    /// The edge's ends and their parts.
334    ends: [([f64; 2], Part); 2],
335    /// On a side of the box: 0 bottom, 1 right, 2 top, 3 left.
336    wall: Option<u8>,
337}
338
339/// A side of a cell: its crossings in order along it, and the parts
340/// between them (one more than the crossings).
341#[derive(Clone, Debug)]
342struct Side {
343    crossings: Vec<usize>,
344    labels: Vec<Part>,
345}
346
347fn mid(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
348    [0.5 * (a[0] + b[0]), 0.5 * (a[1] + b[1])]
349}
350
351/// A node of the link graph: a crossing, or a solved vertex.
352#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
353enum Node {
354    Crossing(usize),
355    Vertex(usize),
356}
357
358struct Builder<'a> {
359    parts: &'a dyn Field,
360    crossings: Vec<Crossing>,
361    /// Solved vertices: the point and its parts.
362    vertices: Vec<(Vec3, Vec<Part>)>,
363    links: HashMap<Node, Vec<Node>>,
364    tolerance: f64,
365    cell: f64,
366    /// A length in the chart small enough to be one point (1e-12 of the scale).
367    near: f64,
368    seeds: Vec<[f64; 2]>,
369}
370
371/// The finest cell a vertex is sought in, as a share of the grid's cell.
372const FINEST: f64 = 1e-11;
373
374impl<'a> Builder<'a> {
375    fn link(&mut self, a: Node, b: Node) {
376        self.links.entry(a).or_default().push(b);
377        self.links.entry(b).or_default().push(a);
378    }
379
380    /// The crossing between `a` (labelled `p`) and `b` (labelled `q`), and
381    /// whether nothing else is lower there.
382    fn crossing(&mut self, a: [f64; 2], p: Part, b: [f64; 2], q: Part, wall: Option<u8>) -> (Crossing, bool) {
383        let at = |t: f64| [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t];
384        let (mut lo, mut hi) = (0.0f64, 1.0f64);
385        for _ in 0..64 {
386            let m = 0.5 * (lo + hi);
387            if m <= lo || m >= hi {
388                break;
389            }
390            let [x, y] = at(m);
391            if self.parts.below(p, q, x, y) { lo = m } else { hi = m }
392        }
393        let [x, y] = at(0.5 * (lo + hi));
394        let z = self.parts.height(p, x, y).min(self.parts.height(q, x, y));
395        // the point is on the curve where the two parts meet (not where one
396        // of them merely stops being read), and nothing else is lower
397        let clear = self.parts.meets(p, q, x, y, self.tolerance) && self.parts.lowest(x, y).0 >= z - self.tolerance;
398        (Crossing { point: Vec3::new(x, y, z), ends: [(a, p), (b, q)], wall }, clear)
399    }
400
401    /// The side from `a` (labelled `p`) to `b` (labelled `q`): one crossing
402    /// where its ends differ and nothing else is lower there; else halved at
403    /// its midpoint (the point a quartered cell reads too) until each piece's
404    /// crossing is clear (down to `finest`). Ends that agree give no crossing:
405    /// a part met only inside such a side is found, if at all, when a cell
406    /// reads the side's midpoint (and is then refused).
407    fn side(&mut self, a: [f64; 2], p: Part, b: [f64; 2], q: Part, wall: Option<u8>, finest: f64) -> Side {
408        // near a seed a part may pass inside a side whatever its ends read:
409        // the side is read at 63 points more there, and in pieces between
410        // the points where it changes
411        let length = (b[0] - a[0]).abs().max((b[1] - a[1]).abs());
412        if length > 64.0 * finest && self.near_seed(a, b) {
413            let mut from = (a, p);
414            let mut pieces: Vec<([f64; 2], Part, [f64; 2], Part)> = Vec::new();
415            for k in 1..=64 {
416                let t = k as f64 / 64.0;
417                let m = if k == 64 { b } else { [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t] };
418                let lm = if k == 64 { q } else { self.parts.lowest(m[0], m[1]).1 };
419                if lm != from.1 || k == 64 {
420                    pieces.push((from.0, from.1, m, lm));
421                    from = (m, lm);
422                }
423            }
424            if pieces.len() > 1 || pieces[0].0 != a || pieces[0].2 != b {
425                let mut side = Side { crossings: Vec::new(), labels: vec![p] };
426                for (u, lu, w, lw) in pieces {
427                    let piece = self.side_plain(u, lu, w, lw, wall, finest);
428                    side.crossings.extend(piece.crossings);
429                    side.labels.extend_from_slice(&piece.labels[1..]);
430                }
431                return side;
432            }
433        }
434        self.side_plain(a, p, b, q, wall, finest)
435    }
436
437    /// [`Builder::side`] without the reading near seeds.
438    fn side_plain(&mut self, a: [f64; 2], p: Part, b: [f64; 2], q: Part, wall: Option<u8>, finest: f64) -> Side {
439        if p == q {
440            return Side { crossings: Vec::new(), labels: vec![p] };
441        }
442        let (crossing, clear) = self.crossing(a, p, b, q, wall);
443        let length = (b[0] - a[0]).abs().max((b[1] - a[1]).abs());
444        let m = mid(a, b);
445        // at the finest, or where rounding no longer moves the midpoint, the
446        // crossing is kept as it is (and the check refuses it if it is wrong)
447        if clear || length <= finest || m == a || m == b {
448            self.crossings.push(crossing);
449            return Side { crossings: vec![self.crossings.len() - 1], labels: vec![p, q] };
450        }
451        let lm = self.parts.lowest(m[0], m[1]).1;
452        let mut first = self.side_plain(a, p, m, lm, wall, finest);
453        let second = self.side_plain(m, lm, b, q, wall, finest);
454        first.crossings.extend(second.crossings);
455        first.labels.extend_from_slice(&second.labels[1..]);
456        first
457    }
458
459    /// Whether a seed lies within eight times the side's length of it (or
460    /// two cells).
461    fn near_seed(&self, a: [f64; 2], b: [f64; 2]) -> bool {
462        let length = (4.0 * (b[0] - a[0]).abs().max((b[1] - a[1]).abs())).max(self.cell);
463        self.seeds.iter().any(|s| {
464            let (lo, hi) = ([a[0].min(b[0]) - 2.0 * length, a[1].min(b[1]) - 2.0 * length], [a[0].max(b[0]) + 2.0 * length, a[1].max(b[1]) + 2.0 * length]);
465            s[0] >= lo[0] && s[0] <= hi[0] && s[1] >= lo[1] && s[1] <= hi[1]
466        })
467    }
468
469    /// The halves of the side `side` from `from` to `to` at its midpoint
470    /// `middle` (labelled `lm`, which must be the label of the stretch it lies
471    /// in), along the axis `axis`.
472    fn split(&self, side: &Side, from: [f64; 2], to: [f64; 2], middle: [f64; 2], lm: Part, axis: usize) -> Result<[Side; 2], String> {
473        let sense = (to[axis] - from[axis]).signum();
474        let along = |p: f64| (p - from[axis]) * sense;
475        let place = |k: usize| along(if axis == 0 { self.crossings[k].point.x } else { self.crossings[k].point.y });
476        let mut before = side.crossings.iter().take_while(|&&k| place(k) <= along(middle[axis])).count();
477        // a crossing at the midpoint itself (a boundary through the grid's
478        // point, read either side by rounding) goes to the half its label says
479        let near = |k: usize| (place(k) - along(middle[axis])).abs() <= 1e-12 * (to[axis] - from[axis]).abs();
480        if side.labels[before] != lm {
481            if before > 0 && near(side.crossings[before - 1]) && side.labels[before - 1] == lm {
482                before -= 1;
483            } else if before < side.crossings.len() && near(side.crossings[before]) && side.labels[before + 1] == lm {
484                before += 1;
485            }
486        }
487        if side.labels[before] != lm {
488            return Err(format!(
489                "a part ({lm:?}) inside a cell side read as {:?} near ({:.6}, {:.6}): read at a smaller cell [{from:?} {to:?} crossings {:?}]",
490                side.labels, middle[0], middle[1], side.crossings.iter().map(|&k| (self.crossings[k].point.x, self.crossings[k].point.y)).collect::<Vec<_>>()
491            ));
492        }
493        Ok([
494            Side { crossings: side.crossings[..before].to_vec(), labels: side.labels[..=before].to_vec() },
495            Side { crossings: side.crossings[before..].to_vec(), labels: side.labels[before..].to_vec() },
496        ])
497    }
498
499    /// Reads the cell with corners `c` (counter-clockwise from its low
500    /// corner) labelled `l`, and its sides `s` (bottom and top running along
501    /// +x, right and left along +y).
502    fn cell(&mut self, c: [[f64; 2]; 4], l: [Part; 4], s: [Side; 4], size: f64, finest: f64) -> Result<(), String> {
503        let mut distinct: Vec<Part> = Vec::new();
504        for part in l.iter().chain(s.iter().flat_map(|side| side.labels.iter())) {
505            if !distinct.contains(part) {
506                distinct.push(*part);
507            }
508        }
509        let crossed: Vec<usize> = s.iter().flat_map(|side| side.crossings.iter().copied()).collect();
510        let seed = self.seeds.iter().copied().find(|p| p[0] >= c[0][0] && p[0] <= c[2][0] && p[1] >= c[0][1] && p[1] <= c[2][1]);
511        if let Some(seed) = seed {
512            if size <= 1e-6 * self.cell {
513                // the seed itself is the cell's vertex
514                let mut parts = distinct;
515                let (z, at) = self.parts.lowest(seed[0], seed[1]);
516                if !parts.contains(&at) {
517                    parts.push(at);
518                }
519                return self.place(Vec3::new(seed[0], seed[1], z), parts, &crossed);
520            }
521        }
522        if seed.is_none() && distinct.len() == 1 {
523            return Ok(());
524        }
525        if seed.is_none() && distinct.len() == 2 && crossed.len() == 2 {
526            self.link(Node::Crossing(crossed[0]), Node::Crossing(crossed[1]));
527            return Ok(());
528        }
529        let centre = mid(c[0], c[2]);
530        if seed.is_none() && distinct.len() == 2 && crossed.len() == 4 && s.iter().all(|side| side.crossings.len() == 1) {
531            let (_, middle) = self.parts.lowest(centre[0], centre[1]);
532            let [b, r, t, lft] = [s[0].crossings[0], s[1].crossings[0], s[2].crossings[0], s[3].crossings[0]];
533            if middle == l[0] {
534                // corners 1 and 3 cut off
535                self.link(Node::Crossing(b), Node::Crossing(r));
536                self.link(Node::Crossing(t), Node::Crossing(lft));
537                return Ok(());
538            }
539            if middle == l[1] {
540                self.link(Node::Crossing(b), Node::Crossing(lft));
541                self.link(Node::Crossing(r), Node::Crossing(t));
542                return Ok(());
543            }
544        }
545        // Three or more parts: a vertex, solved here or in a quarter.
546        if seed.is_none() && distinct.len() == 3 && crossed.len() == 3 {
547            if let Some(point) = self.solve(&distinct, c, centre) {
548                return self.place(point, distinct, &crossed);
549            }
550        }
551        if seed.is_none() && size <= finest {
552            let (z, _) = self.parts.lowest(centre[0], centre[1]);
553            return self.place(Vec3::new(centre[0], centre[1], z), distinct, &crossed);
554        }
555        // Quarter the cell: the sides' midpoints and its centre.
556        let (m0, m1, m2, m3) = (mid(c[0], c[1]), mid(c[1], c[2]), mid(c[3], c[2]), mid(c[0], c[3]));
557        let label = |p: [f64; 2]| self.parts.lowest(p[0], p[1]).1;
558        let (k0, k1, k2, k3, kc) = (label(m0), label(m1), label(m2), label(m3), label(centre));
559        let halves = (|| -> Result<_, String> {
560            Ok((
561                self.split(&s[0], c[0], c[1], m0, k0, 0)?,
562                self.split(&s[1], c[1], c[2], m1, k1, 1)?,
563                self.split(&s[2], c[3], c[2], m2, k2, 0)?,
564                self.split(&s[3], c[0], c[3], m3, k3, 1)?,
565            ))
566        })();
567        let ([b0, b1], [r0, r1], [t0, t1], [l0, l1]) = match halves {
568            Ok(halves) => halves,
569            // a part met inside a side this small is rounding at a vertex:
570            // the cell's centre is that vertex
571            Err(_) if size <= 1e-5 * self.cell || (size <= 1e-4 * self.cell && self.near_seed(c[0], c[2])) => {
572                let mut parts = distinct;
573                for k in [k0, k1, k2, k3, kc] {
574                    if !parts.contains(&k) {
575                        parts.push(k);
576                    }
577                }
578                // solved on its parts' equations near the cell where it can be
579                let grown = [[c[0][0] - size, c[0][1] - size], c[1], [c[2][0] + size, c[2][1] + size], c[3]];
580                let point = if parts.len() >= 3 { self.solve(&parts, grown, centre) } else { None };
581                let point = point.unwrap_or_else(|| Vec3::new(centre[0], centre[1], self.parts.lowest(centre[0], centre[1]).0));
582                return self.place(point, parts, &crossed);
583            }
584            Err(error) => return Err(error),
585        };
586        // inner sides: m0–centre, centre–m2 (along +y); m3–centre, centre–m1 (along +x)
587        let down = self.side(m0, k0, centre, kc, None, finest);
588        let up = self.side(centre, kc, m2, k2, None, finest);
589        let west = self.side(m3, k3, centre, kc, None, finest);
590        let east = self.side(centre, kc, m1, k1, None, finest);
591        let half = 0.5 * size;
592        self.cell([c[0], m0, centre, m3], [l[0], k0, kc, k3], [b0, down.clone(), west.clone(), l0], half, finest)?;
593        self.cell([m0, c[1], m1, centre], [k0, l[1], k1, kc], [b1, r0, east.clone(), down], half, finest)?;
594        self.cell([centre, m1, c[2], m2], [kc, k1, l[2], k2], [east, r1, t1, up.clone()], half, finest)?;
595        self.cell([m3, centre, m2, c[3]], [k3, kc, k2, l[3]], [west, up, t0, l1], half, finest)
596    }
597
598    /// Newton on the three parts' two boundary equations from the cell's
599    /// centre; the point if it converges inside the cell.
600    fn solve(&self, parts: &[Part], c: [[f64; 2]; 4], start: [f64; 2]) -> Option<Vec3> {
601        // Of the three pairs' equations, the two most nearly square to each
602        // other at the start (a tube and its own ball meet tangent, as do two
603        // tubes at a joint's lowest point, so some pairs run tangent at the
604        // vertex; the plane between a tube and its own ball never does).
605        let mut pairs = Vec::new();
606        for (i, &a) in parts.iter().enumerate() {
607            for &b in &parts[i + 1..] {
608                pairs.push((a, b));
609            }
610        }
611        let gradient = |(a, b): (Part, Part)| {
612            let h = 1e-6 * self.parts.scale() / self.parts.length();
613            let f = self.parts.equation(a, b, start[0], start[1]);
614            [(self.parts.equation(a, b, start[0] + h, start[1]) - f) / h, (self.parts.equation(a, b, start[0], start[1] + h) - f) / h]
615        };
616        let grads: Vec<[f64; 2]> = pairs.iter().map(|&pair| gradient(pair)).collect();
617        let mut choice = (0usize, 1usize);
618        let mut best = -1.0f64;
619        for (i, j) in (0..pairs.len()).flat_map(|i| (i + 1..pairs.len()).map(move |j| (i, j))) {
620            let (u, w) = (grads[i], grads[j]);
621            let sine = (u[0] * w[1] - u[1] * w[0]).abs() / ((u[0] * u[0] + u[1] * u[1]).sqrt() * (w[0] * w[0] + w[1] * w[1]).sqrt());
622            if sine.is_finite() && sine > best {
623                best = sine;
624                choice = (i, j);
625            }
626        }
627        let (first, second) = (pairs[choice.0], pairs[choice.1]);
628        let g = |x: f64, y: f64| [self.parts.equation(first.0, first.1, x, y), self.parts.equation(second.0, second.1, x, y)];
629        let scale = self.parts.scale();
630        let step = 1e-7 * scale / self.parts.length();
631        let [mut x, mut y] = start;
632        for _ in 0..40 {
633            let [f0, f1] = g(x, y);
634            if !(f0.is_finite() && f1.is_finite()) {
635                return None;
636            }
637            if f0.abs().max(f1.abs()) <= 1e-13 * scale {
638                let inside = x >= c[0][0] && x <= c[2][0] && y >= c[0][1] && y <= c[2][1];
639                if !inside {
640                    return None;
641                }
642                let (z, _) = self.parts.lowest(x, y);
643                return Some(Vec3::new(x, y, z));
644            }
645            let [ax, ay] = g(x + step, y);
646            let [bx, by] = g(x, y + step);
647            let (j00, j10, j01, j11) = ((ax - f0) / step, (ay - f1) / step, (bx - f0) / step, (by - f1) / step);
648            let det = j00 * j11 - j01 * j10;
649            if !(det.is_finite() && det != 0.0) {
650                return None;
651            }
652            x -= (f0 * j11 - f1 * j01) / det;
653            y -= (j00 * f1 - j10 * f0) / det;
654        }
655        None
656    }
657
658    fn place(&mut self, point: Vec3, parts: Vec<Part>, crossed: &[usize]) -> Result<(), String> {
659        // a vertex on a side two cells share is solved in both: one vertex
660        let near = 100.0 * self.near;
661        // a vertex solved this close to a seed is the seed's
662        let point = match self.seeds.iter().find(|s| ((s[0] - point.x).powi(2) + (s[1] - point.y).powi(2)).sqrt() <= 2e-4 * self.cell) {
663            Some(s) => Vec3::new(s[0], s[1], self.parts.lowest(s[0], s[1]).0),
664            None => point,
665        };
666        let found = self.vertices.iter().position(|(p, _)| p.sub(point).length() <= near);
667        let vertex = match found {
668            Some(k) => {
669                for part in parts {
670                    if !self.vertices[k].1.contains(&part) {
671                        self.vertices[k].1.push(part);
672                    }
673                }
674                Node::Vertex(k)
675            }
676            None => {
677                self.vertices.push((point, parts));
678                Node::Vertex(self.vertices.len() - 1)
679            }
680        };
681        for &k in crossed {
682            self.link(vertex, Node::Crossing(k));
683        }
684        Ok(())
685    }
686}
687
688impl BallEnvelope {
689    /// The plan of the envelope over the box [x0, x1] × [y0, y1] cut below
690    /// `top`, read on a grid of about `cell` (see the module's notes). Refuses
691    /// (saying where) a part the grid passes over between two nodes of one
692    /// part, a box or cell outside the envelope's reach (every bound within 1e6
693    /// radii of the origin, the cell at least 1e-6 radii, at most 1e8 nodes),
694    /// and a result its own check rejects.
695    pub fn plan(&self, x0: f64, x1: f64, y0: f64, y1: f64, top: f64, cell: f64) -> Result<Plan, String> {
696        let r = self.radius();
697        let bound = 1e6 * r;
698        if !(cell.is_finite() && cell >= 1e-6 * r) || ![x0, x1, y0, y1, top].iter().all(|c| c.is_finite() && c.abs() <= bound) || !(x1 > x0 && y1 > y0) {
699            return Err("the box or the cell lies outside the envelope's reach".into());
700        }
701        let parts = Parts::new(self, top);
702        let mut plan = plan_field(&parts, [x0, x1, y0, y1], cell)?;
703        plan.runs = parts.runs.clone();
704        plan.centres = parts.centres.clone();
705        Ok(plan)
706    }
707}
708
709/// The plan of `field` over the box `bounds` = [x0, x1] × [y0, y1] of its
710/// chart, read on a grid of about `cell` (see the module's notes).
711pub fn plan_field(field: &dyn Field, bounds: [f64; 4], cell: f64) -> Result<Plan, String> {
712    {
713        let [x0, x1, y0, y1] = bounds;
714        let top = field.top();
715        let r = field.scale();
716        if !(cell.is_finite() && cell > 0.0 && x1 > x0 && y1 > y0) {
717            return Err("the box or the cell is empty".into());
718        }
719        let (fx, fy) = (((x1 - x0) / cell).ceil().max(1.0), ((y1 - y0) / cell).ceil().max(1.0));
720        if !((fx + 1.0) * (fy + 1.0) <= 1e8) {
721            return Err("more than 1e8 grid nodes".into());
722        }
723        let (nx, ny) = (fx as usize, fy as usize);
724        let node = |i: usize, j: usize| [if i == nx { x1 } else { x0 + (x1 - x0) * i as f64 / nx as f64 }, if j == ny { y1 } else { y0 + (y1 - y0) * j as f64 / ny as f64 }];
725        let parts = field;
726        let labels: Vec<Part> = (0..=nx).flat_map(|i| (0..=ny).map(move |j| (i, j))).map(|(i, j)| { let p = node(i, j); parts.lowest(p[0], p[1]).1 }).collect();
727        let label = |i: usize, j: usize| labels[i * (ny + 1) + j];
728        let near = 1e-12 * r / field.length();
729        let seeds = field.seeds();
730        let mut builder = Builder { parts, crossings: Vec::new(), vertices: Vec::new(), links: HashMap::new(), tolerance: 1e-9 * r, cell, near, seeds };
731        // The grid's edges' crossings: horizontal (i, j)–(i + 1, j), vertical (i, j)–(i, j + 1).
732        let finest = FINEST * cell;
733        let empty = Side { crossings: Vec::new(), labels: Vec::new() };
734        let mut horizontal = vec![empty.clone(); nx * (ny + 1)];
735        let mut vertical = vec![empty; (nx + 1) * ny];
736        for i in 0..=nx {
737            for j in 0..=ny {
738                if i < nx {
739                    let wall = if j == 0 { Some(0) } else if j == ny { Some(2) } else { None };
740                    horizontal[i * (ny + 1) + j] = builder.side(node(i, j), label(i, j), node(i + 1, j), label(i + 1, j), wall, finest);
741                }
742                if j < ny {
743                    let wall = if i == 0 { Some(3) } else if i == nx { Some(1) } else { None };
744                    vertical[i * ny + j] = builder.side(node(i, j), label(i, j), node(i, j + 1), label(i, j + 1), wall, finest);
745                }
746            }
747        }
748        for i in 0..nx {
749            for j in 0..ny {
750                let corners = [node(i, j), node(i + 1, j), node(i + 1, j + 1), node(i, j + 1)];
751                let l = [label(i, j), label(i + 1, j), label(i + 1, j + 1), label(i, j + 1)];
752                let s = [horizontal[i * (ny + 1) + j].clone(), vertical[(i + 1) * ny + j].clone(), horizontal[i * (ny + 1) + j + 1].clone(), vertical[i * ny + j].clone()];
753                let size = (corners[1][0] - corners[0][0]).max(corners[3][1] - corners[0][1]);
754                builder.cell(corners, l, s, size, finest)?;
755            }
756        }
757        // The plan's vertices: solved vertices, crossings on the box's sides,
758        // the box's corners, and crossings not linked twice.
759        let mut vertices: Vec<PlanVertex> = Vec::new();
760        let mut vertex_of: HashMap<Node, usize> = HashMap::new();
761        for (k, (point, _)) in builder.vertices.iter().enumerate() {
762            vertex_of.insert(Node::Vertex(k), vertices.len());
763            vertices.push(PlanVertex { point: *point });
764        }
765        for (k, crossing) in builder.crossings.iter().enumerate() {
766            let degree = builder.links.get(&Node::Crossing(k)).map_or(0, Vec::len);
767            if crossing.wall.is_some() || degree != 2 {
768                if crossing.wall.is_none() {
769                    return Err(format!("a boundary ends at ({:.6}, {:.6}) inside the box (linked {degree} times)", crossing.point.x, crossing.point.y));
770                }
771                if degree != 1 {
772                    return Err(format!("a boundary meeting the box's side at ({:.6}, {:.6}) is linked {degree} times", crossing.point.x, crossing.point.y));
773                }
774                vertex_of.insert(Node::Crossing(k), vertices.len());
775                vertices.push(PlanVertex { point: crossing.point });
776            }
777        }
778        // Chains between vertices; then loops of crossings with none.
779        let mut edges: Vec<PlanEdge> = Vec::new();
780        let mut walked: std::collections::HashSet<(Node, Node)> = std::collections::HashSet::new();
781        let mut starts: Vec<Node> = vertex_of.keys().copied().collect();
782        starts.sort_by_key(|n| vertex_of[n]);
783        let point_of = |b: &Builder, n: Node| match n {
784            Node::Crossing(k) => b.crossings[k].point,
785            Node::Vertex(k) => b.vertices[k].0,
786        };
787        let mut chains: Vec<Vec<Node>> = Vec::new();
788        for &start in &starts {
789            for &first in builder.links.get(&start).map_or(&[][..], |v| &v[..]) {
790                if walked.contains(&(start, first)) {
791                    continue;
792                }
793                let mut chain = vec![start, first];
794                walked.insert((start, first));
795                while !vertex_of.contains_key(chain.last().unwrap()) {
796                    let (here, back) = (chain[chain.len() - 1], chain[chain.len() - 2]);
797                    let links = &builder.links[&here];
798                    let next = if links[0] == back { links[1] } else { links[0] };
799                    walked.insert((here, next));
800                    chain.push(next);
801                }
802                let (end, before) = (chain[chain.len() - 1], chain[chain.len() - 2]);
803                walked.insert((end, before));
804                chains.push(chain);
805            }
806        }
807        let mut on_chain: std::collections::HashSet<Node> = chains.iter().flatten().copied().collect();
808        for k in 0..builder.crossings.len() {
809            let start = Node::Crossing(k);
810            if vertex_of.contains_key(&start) || on_chain.contains(&start) || !builder.links.contains_key(&start) {
811                continue;
812            }
813            // a closed boundary: its first crossing is its vertex
814            vertex_of.insert(start, vertices.len());
815            vertices.push(PlanVertex { point: builder.crossings[k].point });
816            let mut chain = vec![start, builder.links[&start][0]];
817            walked.insert((start, chain[1]));
818            while chain.last() != Some(&start) {
819                let (here, back) = (chain[chain.len() - 1], chain[chain.len() - 2]);
820                let links = &builder.links[&here];
821                let next = if links[0] == back { links[1] } else { links[0] };
822                walked.insert((here, next));
823                chain.push(next);
824            }
825            walked.insert((start, chain[chain.len() - 2]));
826            on_chain.extend(chain.iter().copied());
827            chains.push(chain);
828        }
829        for chain in chains {
830            // the sides from a crossing on the chain: its edge's ends against the chain's direction there
831            // The sides from the chain's crossing most square to its grid
832            // edge: the edge's start lies left of the chain's direction there
833            // when (direction × edge) < 0, read on the edge's own direction so
834            // a crossing at a grid node reads as well as any.
835            let mut best: Option<(f64, f64, Part, Part)> = None;
836            for i in 0..chain.len() {
837                let Node::Crossing(k) = chain[i] else { continue };
838                // the nearest points either side that stand apart from it
839                let here = point_of(&builder, chain[i]);
840                let apart = |n: &Node| { let p = point_of(&builder, *n); p.x != here.x || p.y != here.y };
841                let before = chain[..i].iter().rev().find(|n| apart(n)).map_or(here, |&n| point_of(&builder, n));
842                let after = chain[i + 1..].iter().find(|n| apart(n)).map_or(here, |&n| point_of(&builder, n));
843                let (dx, dy) = (after.x - before.x, after.y - before.y);
844                let [(a, pa), (b, pb)] = builder.crossings[k].ends;
845                let (ex, ey) = (b[0] - a[0], b[1] - a[1]);
846                let cross = dx * ey - dy * ex;
847                let square = cross.abs() / ((dx * dx + dy * dy).sqrt() * (ex * ex + ey * ey).sqrt());
848                if square.is_finite() && best.is_none_or(|(s, _, _, _)| square > s) {
849                    best = Some((square, cross, pa, pb));
850                }
851            }
852            // a boundary of no length (from a vertex to itself through a
853            // crossing at it) bounds nothing
854            let start_point = point_of(&builder, chain[0]);
855            let plan_gap = |a: Vec3, b: Vec3| ((a.x - b.x).powi(2) + (a.y - b.y).powi(2)).sqrt();
856            // (or round a loop through one vertex and back narrower than the
857            // tolerance: a crossing linked twice to one vertex)
858            let small = (1e3 * near).max(4e-4 * cell);
859            if chain.iter().all(|&n| plan_gap(point_of(&builder, n), start_point) <= near) || (chain[0] == *chain.last().unwrap() && chain.iter().all(|&n| plan_gap(point_of(&builder, n), start_point) <= small)) {
860                continue;
861            }
862            let Some((square, side, pa, pb)) = best else {
863                let at = point_of(&builder, chain[0]);
864                let detail: Vec<String> = chain.iter().map(|&n| { let p = point_of(&builder, n); match n { Node::Crossing(k) => format!("C{k}({:e}, {:e}) ends {:?}", p.x, p.y, builder.crossings[k].ends), Node::Vertex(k) => format!("V{k}({:e}, {:e}) {:?}", p.x, p.y, builder.vertices[k].1) } }).collect();
865                return Err(format!("a boundary of no length at ({:.9}, {:.9}), {} nodes: {detail:?}", at.x, at.y, chain.len()));
866            };
867            if !(square > 1e-6) {
868                let at = point_of(&builder, chain[0]);
869                return Err(format!("a boundary's sides are not read near ({:.6}, {:.6})", at.x, at.y));
870            }
871            // the start `a` is left when the edge runs from left to right of the direction
872            let side = -side;
873            let (left, right) = if side > 0.0 { (pa, pb) } else { (pb, pa) };
874            let mut points: Vec<Vec3> = Vec::with_capacity(chain.len());
875            for &n in &chain {
876                let p = point_of(&builder, n);
877                if points.last().is_none_or(|q: &Vec3| q.sub(p).length() > near) {
878                    points.push(p);
879                }
880            }
881            // the end vertex's own point last, in place of one too near it
882            let end = point_of(&builder, *chain.last().unwrap());
883            if points.len() > 1 && points.last().unwrap().sub(end).length() <= near {
884                *points.last_mut().unwrap() = end;
885            } else {
886                points.push(end);
887            }
888            edges.push(PlanEdge { from: vertex_of[&chain[0]], to: vertex_of[chain.last().unwrap()], left, right, points });
889        }
890        // The box's sides, counter-clockwise: the corners and the sides' crossings in order.
891        let corners = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
892        let mut corner_vertex = [0usize; 4];
893        for (k, c) in corners.iter().enumerate() {
894            let (z, _) = builder.parts.lowest(c[0], c[1]);
895            // a boundary meeting the box at its corner: that crossing is the corner
896            let at = builder.crossings.iter().enumerate().find(|(_, x)| x.wall.is_some() && ((x.point.x - c[0]).powi(2) + (x.point.y - c[1]).powi(2)).sqrt() <= 1e3 * near).map(|(j, _)| vertex_of[&Node::Crossing(j)]);
897            match at {
898                Some(v) => {
899                    vertices[v].point = Vec3::new(c[0], c[1], z);
900                    corner_vertex[k] = v;
901                }
902                None => {
903                    corner_vertex[k] = vertices.len();
904                    vertices.push(PlanVertex { point: Vec3::new(c[0], c[1], z) });
905                }
906            }
907        }
908        for edge in &mut edges {
909            // the ends of the boundaries that met it, at the corner itself
910            if let Some(&k) = corner_vertex.iter().find(|&&k| k == edge.from) {
911                edge.points[0] = vertices[k].point;
912            }
913            if let Some(&k) = corner_vertex.iter().find(|&&k| k == edge.to) {
914                *edge.points.last_mut().unwrap() = vertices[k].point;
915            }
916        }
917        for side in 0..4u8 {
918            let (from, to) = (corners[side as usize], corners[(side as usize + 1) % 4]);
919            let along = |p: [f64; 2]| (p[0] - from[0]) * (to[0] - from[0]) + (p[1] - from[1]) * (to[1] - from[1]);
920            let mut stops: Vec<(f64, usize)> = builder.crossings.iter().enumerate().filter(|(_, c)| c.wall == Some(side)).map(|(k, c)| (along([c.point.x, c.point.y]), vertex_of[&Node::Crossing(k)])).collect();
921            stops.sort_by(|a, b| a.0.total_cmp(&b.0));
922            let mut chain = vec![(f64::NEG_INFINITY, corner_vertex[side as usize])];
923            chain.extend(stops);
924            chain.push((f64::INFINITY, corner_vertex[(side as usize + 1) % 4]));
925            for w in chain.windows(2) {
926                if w[0].1 == w[1].1 {
927                    continue;
928                }
929                let (a, b) = (vertices[w[0].1].point, vertices[w[1].1].point);
930                // the part along this stretch, read at its middle; points at the grid's spacing
931                let (mx, my) = (0.5 * (a.x + b.x), 0.5 * (a.y + b.y));
932                let (_, part) = builder.parts.lowest(mx, my);
933                let length = ((b.x - a.x).powi(2) + (b.y - a.y).powi(2)).sqrt();
934                let count = ((length / cell).ceil() as usize).max(1);
935                let mut points = vec![a];
936                for k in 1..count {
937                    let t = k as f64 / count as f64;
938                    let (x, y) = (a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
939                    points.push(Vec3::new(x, y, builder.parts.height(part, x, y)));
940                }
941                points.push(b);
942                edges.push(PlanEdge { from: w[0].1, to: w[1].1, left: part, right: Part::Outside, points });
943            }
944        }
945        let plan = Plan { vertices, edges, runs: Vec::new(), centres: Vec::new(), bounds: [x0, x1, y0, y1], top };
946        builder.check(&plan)?;
947        Ok(plan)
948    }
949}
950
951impl Plan {
952    /// The points of the plan's edge `index` again, about `spacing` apart in
953    /// plan and each on the curve where its two parts meet: the edge's
954    /// polyline cut evenly by length, each cut point moved square to its
955    /// stretch of the polyline onto the curve (by the secant on the pair's
956    /// equation; a side of the box keeps its line and takes its part's
957    /// height). Its two ends are its vertices' own points. Refuses a point
958    /// the secant does not bring onto the curve (to 1e-9 of the radius)
959    /// within half a spacing of the polyline.
960    pub fn edge_points(&self, envelope: &BallEnvelope, index: usize, spacing: f64) -> Result<Vec<Vec3>, String> {
961        self.edge_points_in(&Parts::new(envelope, self.top), index, spacing)
962    }
963
964    /// [`Plan::edge_points`] on any field, `spacing` in its chart.
965    pub fn edge_points_in(&self, field: &dyn Field, index: usize, spacing: f64) -> Result<Vec<Vec3>, String> {
966        let edge = &self.edges[index];
967        let parts = field;
968        let r = field.scale();
969        let points = &edge.points;
970        let mut along = vec![0.0f64];
971        for w in points.windows(2) {
972            along.push(along.last().unwrap() + ((w[1].x - w[0].x).powi(2) + (w[1].y - w[0].y).powi(2)).sqrt());
973        }
974        let length = *along.last().unwrap();
975        if !(spacing.is_finite() && spacing > 0.0) {
976            return Err("the spacing must be positive".into());
977        }
978        // a closed edge at least 16 stretches round (cross review: a short rim
979        // came back two coincident points), an open one at least 4
980        let fewest = if edge.from == edge.to { 16 } else { 4 };
981        let count = ((length / spacing).ceil() as usize).clamp(fewest, 1 << 20);
982        let mut out = vec![points[0]];
983        let mut stretch = 0usize;
984        for k in 1..count {
985            let s = length * k as f64 / count as f64;
986            while stretch + 1 < points.len() - 1 && along[stretch + 1] < s {
987                stretch += 1;
988            }
989            let (a, b) = (points[stretch], points[stretch + 1]);
990            let span = along[stretch + 1] - along[stretch];
991            let t = if span > 0.0 { (s - along[stretch]) / span } else { 0.0 };
992            let (x, y) = (a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t);
993            if edge.right == Part::Outside {
994                out.push(Vec3::new(x, y, parts.height(edge.left, x, y).min(self.top)));
995                continue;
996            }
997            // square to the stretch, onto the curve
998            let (nx, ny) = if span > 0.0 { (-(b.y - a.y) / span, (b.x - a.x) / span) } else { (0.0, 0.0) };
999            let g = |l: f64| parts.equation(edge.left, edge.right, x + nx * l, y + ny * l);
1000            let (mut l0, mut l1) = (0.0f64, 1e-6 * r / field.length());
1001            let (mut g0, mut g1) = (g(l0), g(l1));
1002            for _ in 0..50 {
1003                if !(g1.is_finite() && g0.is_finite()) || g1 == g0 || g1.abs() <= 1e-15 * r {
1004                    break;
1005                }
1006                let l2 = l1 - g1 * (l1 - l0) / (g1 - g0);
1007                (l0, g0, l1) = (l1, g1, l2);
1008                g1 = g(l1);
1009            }
1010            let (px, py) = (x + nx * l1, y + ny * l1);
1011            if !(l1.abs() <= 0.5 * spacing && parts.meets(edge.left, edge.right, px, py, 1e-9 * r)) {
1012                return Err(format!("a point of the boundary between {:?} and {:?} near ({x:.6}, {y:.6}) is not brought onto it", edge.left, edge.right));
1013            }
1014            let z = parts.height(edge.left, px, py).min(parts.height(edge.right, px, py)).min(self.top);
1015            let z = if z.is_finite() { z } else { parts.continued(edge.left, px, py) };
1016            out.push(Vec3::new(px, py, z));
1017        }
1018        out.push(*points.last().unwrap());
1019        Ok(out)
1020    }
1021}
1022
1023impl<'a> Builder<'a> {
1024    /// The plan's own check: at every crossing the two parts' heights agree
1025    /// (read just either side of the crossing, where each is read) and
1026    /// nothing is lower; at every solved vertex its parts' surfaces meet and
1027    /// nothing is lower.
1028    fn check(&self, plan: &Plan) -> Result<(), String> {
1029        let tolerance = self.tolerance;
1030        for crossing in &self.crossings {
1031            let [(a, p), (b, q)] = crossing.ends;
1032            let at = crossing.point;
1033            if !self.parts.meets(p, q, at.x, at.y, tolerance) {
1034                return Err(format!(
1035                    "the crossing ({:.9}, {:.9}) is not where {p:?} and {q:?} meet (they read {} and {}; edge from {a:?} to {b:?})",
1036                    at.x, at.y, self.parts.continued(p, at.x, at.y), self.parts.continued(q, at.x, at.y)
1037                ));
1038            }
1039            let (lowest, part) = self.parts.lowest(at.x, at.y);
1040            if lowest < at.z - tolerance {
1041                return Err(format!("at the crossing ({:.9}, {:.9}) of {p:?} and {q:?} at {} the part {part:?} is lower, at {lowest}", at.x, at.y, at.z));
1042            }
1043        }
1044        for (point, parts) in &self.vertices {
1045            for &part in parts {
1046                let z = self.parts.continued(part, point.x, point.y);
1047                if !((z - point.z).abs() <= tolerance) {
1048                    return Err(format!("at the vertex ({:.9}, {:.9}) the part {part:?} reads {z}, not {}", point.x, point.y, point.z));
1049                }
1050            }
1051            for (i, &a) in parts.iter().enumerate() {
1052                for &b in &parts[i + 1..] {
1053                    if let Some(d) = self.parts.plane(a, b, point.x, point.y).filter(|d| !(d.abs() <= tolerance)) {
1054                        return Err(format!("the vertex ({:.9}, {:.9}) of {parts:?} is {d:e} off the surface {a:?} and {b:?} meet on", point.x, point.y));
1055                    }
1056                }
1057            }
1058            let (lowest, part) = self.parts.lowest(point.x, point.y);
1059            if lowest < point.z - tolerance {
1060                return Err(format!("at the vertex ({:.9}, {:.9}) the part {part:?} is lower, at {lowest}", point.x, point.y));
1061            }
1062        }
1063        for edge in &plan.edges {
1064            if edge.left == edge.right {
1065                return Err(format!("a boundary has {:?} on both sides", edge.left));
1066            }
1067        }
1068        // Witnesses of parts the grid may pass over: each run's lowest line
1069        // (below its moves, at half the cell's spacing) and each ball's
1070        // lowest point, inside the box. A part lowest at one of them that the
1071        // plan does not name is a region narrower than the cell.
1072        let [x0, x1, y0, y1] = plan.bounds;
1073        let mut named: std::collections::HashSet<Part> = plan.edges.iter().flat_map(|e| [e.left, e.right]).collect();
1074        for vertex in &plan.vertices {
1075            named.insert(self.parts.lowest(vertex.point.x, vertex.point.y).1);
1076        }
1077        let inside = |x: f64, y: f64| x >= x0 && x <= x1 && y >= y0 && y <= y1;
1078        for [x, y] in self.parts.witnesses(self.cell) {
1079            if inside(x, y) {
1080                let (_, part) = self.parts.lowest(x, y);
1081                if !named.contains(&part) {
1082                    return Err(format!("the part {part:?}, lowest at ({x:.6}, {y:.6}), is narrower than the cell: read at a smaller cell"));
1083                }
1084            }
1085        }
1086        Ok(())
1087    }
1088}
1089