Skip to main content

brep_construction/construction/
mill_faces.rs

1//! The block a ball-end mill leaves: the box below the mill's lower envelope
2//! (the third piece of the ball-end raster construction).
3//!
4//! The top is the plan's regions ([`crate::mill_plan`]), each a face on its
5//! part's own surface: a tube's cylinder (its seam along the top of the
6//! cylinder, which the underside never reaches), a ball's sphere (its poles
7//! on a level diameter and its seam over the top), or the stock's top plane.
8//! The regions come from the plan's graph: each edge twice, once with the
9//! region on its left; each region's boundary cycles walked by the next edge
10//! clockwise at every vertex; a counter-clockwise cycle (in plan, from above)
11//! an outer boundary and a clockwise one a hole, in the smallest outer
12//! boundary of its part that holds it.
13//!
14//! Each edge's curve is cubic through its points again (about a 32nd of the
15//! radius apart, each on the curve where its parts meet), and each face's
16//! image of it in its surface's parameters is cubic through the same points
17//! inverted onto the surface at the same parameters, never fitted. The four
18//! walls are planes under the envelope's section along the box's sides, the
19//! floor a plane. The plan names every edge's two faces, so the solid is
20//! assembled directly (no sewing): each edge one record, used once each way;
21//! each face's sense set so its normal points out of the stock; the result
22//! validated.
23
24use crate::mill_envelope::BallEnvelope;
25use crate::mill_plan::{ball_field, Field, Part, Plan};
26use crate::topology::{CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord};
27use crate::{interpolate_curve, make_line, make_plane, make_revolution, make_sphere_surface_framed, BodyKind, BrepSolid, KernelRefusal, KernelStage, NurbsCurve, NurbsSurface, Vec3};
28
29/// The prefix of every refusal of this module.
30pub const MILL_FACES_REFUSAL: &str = "millFaces";
31
32fn refuse(what: &'static str, message: String) -> KernelRefusal {
33    KernelRefusal::unsupported(KernelStage::Collect, what, format!("{MILL_FACES_REFUSAL}: {message}"))
34}
35
36/// One use of a plan edge: the edge, and whether it runs the edge's way
37/// (its region then on the edge's left).
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39struct Half {
40    edge: usize,
41    forward: bool,
42}
43
44/// An edge's points again (in the chart and in space) and its curve, at the
45/// curve's parameters.
46struct EdgeCurve {
47    chart: Vec<Vec3>,
48    points: Vec<Vec3>,
49    parameters: Vec<f64>,
50    curve: NurbsCurve,
51}
52
53/// A cubic through `points` at `parameters` (a line through two, a
54/// quadratic through three).
55fn through(points: &[Vec3], parameters: &[f64]) -> Result<NurbsCurve, String> {
56    match points.len() {
57        0 | 1 => Err("a curve needs two points".into()),
58        2 => make_line(points[0], points[1]),
59        n => interpolate_curve(points, (n - 1).min(3), parameters),
60    }
61}
62
63/// The surfaces a plan's parts lie on: each part's surface, which way is out
64/// of the stock at a point of it, and a chart point (x, y, height) lifted
65/// into space.
66pub trait Faces {
67    fn surface(&self, part: Part) -> Result<NurbsSurface, String>;
68    fn outward(&self, part: Part, at: Vec3) -> Vec3;
69    fn lift(&self, chart: Vec3) -> Vec3;
70}
71
72/// What closes a plan's top below: four upright walls over a level floor at
73/// `bottom` (a block milled over level ground: the chart is the plan), or one
74/// floor on the plane through `origin` square to `normal` (which points out
75/// of the stock) that every side of the box lifts onto (a dome's base).
76#[derive(Clone, Copy, Debug)]
77pub enum Sides {
78    Walls { bottom: f64 },
79    Floor { origin: Vec3, normal: Vec3 },
80}
81
82/// A mill's capsules over level ground: tubes about their runs, balls about
83/// their centres, the top plane; the chart is the plan.
84struct BallFaces<'a> {
85    envelope: &'a BallEnvelope,
86    plan: &'a Plan,
87}
88
89impl<'a> BallFaces<'a> {
90    fn run(&self, run: usize) -> (Vec3, Vec3) {
91        let moves = &self.plan.runs[run];
92        (self.envelope.segments()[moves[0]].0, self.envelope.segments()[*moves.last().unwrap()].1)
93    }
94}
95
96impl<'a> Faces for BallFaces<'a> {
97    fn surface(&self, part: Part) -> Result<NurbsSurface, String> {
98        let r = self.envelope.radius();
99        let [x0, x1, y0, y1] = self.plan.bounds;
100        match part {
101            // the seam along the top of the cylinder, which the underside never reaches
102            Part::Tube(run) => {
103                let (a, b) = self.run(run);
104                let axis = b.sub(a);
105                let u = axis.scale(1.0 / axis.length());
106                let up = Vec3::new(0.0, 0.0, 1.0);
107                let over = up.sub(u.scale(up.dot(u))).normalized()?;
108                let start = a.add(over.scale(r));
109                make_revolution(a, u, &make_line(start, start.add(axis))?, std::f64::consts::TAU)
110            }
111            Part::Ball(c) => make_sphere_surface_framed(self.plan.centres[c], r, Vec3::new(0.0, 1.0, 0.0), Some(Vec3::new(0.0, 0.0, 1.0))),
112            Part::Top => make_plane(Vec3::new(x0, y0, self.plan.top), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), x1 - x0, y1 - y0),
113            Part::Outside => Err("no surface outside".into()),
114        }
115    }
116
117    /// Up, out of the stock: toward a tube's axis or a ball's centre.
118    fn outward(&self, part: Part, at: Vec3) -> Vec3 {
119        match part {
120            Part::Tube(run) => {
121                let (a, b) = self.run(run);
122                let u = b.sub(a).scale(1.0 / b.sub(a).length());
123                let w = a.sub(at);
124                w.sub(u.scale(w.dot(u)))
125            }
126            Part::Ball(c) => self.plan.centres[c].sub(at),
127            _ => Vec3::new(0.0, 0.0, 1.0),
128        }
129    }
130
131    fn lift(&self, chart: Vec3) -> Vec3 {
132        chart
133    }
134}
135
136/// The solid of the box `plan.bounds` × [`bottom`, the plan's top] below
137/// `envelope`, its top read by `plan`.
138pub fn milled_block(envelope: &BallEnvelope, plan: &Plan, bottom: f64) -> Result<BrepSolid, KernelRefusal> {
139    let r = envelope.radius();
140    let [x0, x1, y0, y1] = plan.bounds;
141    // The floor below everything the envelope reaches over the box: each
142    // capsule whose plan box meets it reaches no lower than its segment's
143    // lower end less the radius (cross review: the vertices alone miss a
144    // ball's bottom inside a face).
145    let reach = envelope
146        .segments()
147        .iter()
148        .filter(|(a, b)| a.x.min(b.x) - r <= x1 && a.x.max(b.x) + r >= x0 && a.y.min(b.y) - r <= y1 && a.y.max(b.y) + r >= y0)
149        .map(|(a, b)| a.z.min(b.z) - r)
150        .fold(f64::INFINITY, f64::min);
151    if !(bottom < plan.top && bottom < reach) {
152        return Err(refuse("mill_floor", format!("the floor at {bottom} must lie below everything the mill reaches over the box (down to {reach})")));
153    }
154    let field = ball_field(envelope, plan.top);
155    block_from_plan(&field, &BallFaces { envelope, plan }, plan, Sides::Walls { bottom }, r / 32.0)
156}
157
158/// The solid below `plan`'s top (each region a face on its part's surface,
159/// read through `faces`), closed by `sides`; each edge's points again about
160/// `spacing` apart in the chart.
161pub fn block_from_plan(field: &dyn Field, faces: &dyn Faces, plan: &Plan, sides: Sides, spacing: f64) -> Result<BrepSolid, KernelRefusal> {
162    let r = field.scale();
163    let [x0, x1, y0, y1] = plan.bounds;
164    // The edges' curves.
165    let mut curves = Vec::with_capacity(plan.edges.len());
166    for index in 0..plan.edges.len() {
167        let resampled = plan.edge_points_in(field, index, spacing).map_err(|e| refuse("mill_edge", e))?;
168        // points one in space (1e-12 of the radius) kept once, the ends kept
169        let (mut chart, mut points): (Vec<Vec3>, Vec<Vec3>) = (Vec::with_capacity(resampled.len()), Vec::with_capacity(resampled.len()));
170        for (k, &c) in resampled.iter().enumerate() {
171            let p = faces.lift(c);
172            let last = k + 1 == resampled.len();
173            if points.last().is_some_and(|q: &Vec3| q.sub(p).length() <= 1e-12 * r) {
174                if last {
175                    *chart.last_mut().unwrap() = c;
176                    *points.last_mut().unwrap() = p;
177                }
178                continue;
179            }
180            chart.push(c);
181            points.push(p);
182        }
183        if points.len() < 2 {
184            let e = &plan.edges[index];
185            return Err(refuse("mill_edge", format!("the edge {index} ({:?}|{:?}, {} to {}) is one point: {:?}", e.left, e.right, e.from, e.to, resampled)));
186        }
187        let mut parameters = vec![0.0f64];
188        for w in points.windows(2) {
189            parameters.push(parameters.last().unwrap() + w[1].sub(w[0]).length());
190        }
191        let total = *parameters.last().unwrap();
192        if !(total > 0.0) {
193            return Err(refuse("mill_edge", format!("the edge {index} has no length")));
194        }
195        for p in &mut parameters {
196            *p /= total;
197        }
198        *parameters.last_mut().unwrap() = 1.0;
199        let curve = through(&points, &parameters).map_err(|e| refuse("mill_edge", format!("the edge {index}: {e}")))?;
200        curves.push(EdgeCurve { chart, points, parameters, curve });
201    }
202    let leave = 1e-3 * r / field.length();
203    // Every half-edge out of each vertex, by the angle it leaves at.
204    let leaving = |half: Half| -> f64 {
205        let points = &curves[half.edge].chart;
206        let (start, rest): (Vec3, Box<dyn Iterator<Item = &Vec3>>) = if half.forward { (points[0], Box::new(points.iter().skip(1))) } else { (*points.last().unwrap(), Box::new(points.iter().rev().skip(1))) };
207        // the first point a thousandth of the radius away (or the far end)
208        let mut toward = start;
209        for p in rest {
210            toward = *p;
211            if ((p.x - start.x).powi(2) + (p.y - start.y).powi(2)).sqrt() >= leave {
212                break;
213            }
214        }
215        (toward.y - start.y).atan2(toward.x - start.x)
216    };
217    let mut out: Vec<Vec<(f64, Half)>> = vec![Vec::new(); plan.vertices.len()];
218    for (edge, e) in plan.edges.iter().enumerate() {
219        for forward in [true, false] {
220            let half = Half { edge, forward };
221            out[if forward { e.from } else { e.to }].push((leaving(half), half));
222        }
223    }
224    for list in &mut out {
225        list.sort_by(|a, b| a.0.total_cmp(&b.0));
226    }
227    let end_of = |h: Half| if h.forward { plan.edges[h.edge].to } else { plan.edges[h.edge].from };
228    let part_of = |h: Half| if h.forward { plan.edges[h.edge].left } else { plan.edges[h.edge].right };
229    // The cycles: from each unused half-edge, the next clockwise from its twin at each end.
230    let mut used = vec![[false; 2]; plan.edges.len()];
231    let mut cycles: Vec<(Part, Vec<Half>)> = Vec::new();
232    for edge in 0..plan.edges.len() {
233        for forward in [true, false] {
234            let first = Half { edge, forward };
235            if used[edge][forward as usize] || part_of(first) == Part::Outside {
236                continue;
237            }
238            let mut cycle = Vec::new();
239            let mut half = first;
240            loop {
241                if used[half.edge][half.forward as usize] {
242                    if half == first {
243                        break;
244                    }
245                    return Err(refuse("mill_cycle", format!("the boundary walk from edge {edge} meets a used edge {}", half.edge)));
246                }
247                used[half.edge][half.forward as usize] = true;
248                cycle.push(half);
249                let vertex = end_of(half);
250                let twin = Half { edge: half.edge, forward: !half.forward };
251                let list = &out[vertex];
252                let at = list.iter().position(|(_, h)| *h == twin).ok_or_else(|| refuse("mill_cycle", "a half-edge is missing at its vertex".into()))?;
253                half = list[(at + list.len() - 1) % list.len()].1;
254                if part_of(half) != part_of(first) {
255                    let around: Vec<String> = list.iter().map(|(angle, h)| { let e = &plan.edges[h.edge]; format!("{angle:.6} e{} {:?}|{:?} fwd {} {}->{} n{} {:?}", h.edge, e.left, e.right, h.forward, e.from, e.to, e.points.len(), &e.points[..e.points.len().min(4)]) }).collect();
256                    return Err(refuse("mill_cycle", format!("the boundary of {:?} runs on into {:?} at the vertex {vertex} {:?}: {around:?}", part_of(first), part_of(half), plan.vertices[vertex].point)));
257                }
258                if cycle.len() > plan.edges.len() * 2 {
259                    return Err(refuse("mill_cycle", "a boundary walk does not close".into()));
260                }
261            }
262            cycles.push((part_of(first), cycle));
263        }
264    }
265    // Outer boundaries and holes, by the area each cycle bounds in plan.
266    let polygon = |cycle: &[Half]| -> Vec<[f64; 2]> {
267        let mut ring = Vec::new();
268        for h in cycle {
269            let points = &curves[h.edge].chart;
270            let ordered: Box<dyn Iterator<Item = &Vec3>> = if h.forward { Box::new(points.iter()) } else { Box::new(points.iter().rev()) };
271            for p in ordered.skip(1) {
272                ring.push([p.x, p.y]);
273            }
274        }
275        ring
276    };
277    let area = |ring: &[[f64; 2]]| 0.5 * (0..ring.len()).map(|k| { let (a, b) = (ring[k], ring[(k + 1) % ring.len()]); a[0] * b[1] - b[0] * a[1] }).sum::<f64>();
278    let holds = |ring: &[[f64; 2]], p: [f64; 2]| {
279        let mut inside = false;
280        for k in 0..ring.len() {
281            let (a, b) = (ring[k], ring[(k + 1) % ring.len()]);
282            if (a[1] > p[1]) != (b[1] > p[1]) && p[0] < a[0] + (p[1] - a[1]) * (b[0] - a[0]) / (b[1] - a[1]) {
283                inside = !inside;
284            }
285        }
286        inside
287    };
288    let rings: Vec<Vec<[f64; 2]>> = cycles.iter().map(|(_, c)| polygon(c)).collect();
289    let areas: Vec<f64> = rings.iter().map(|ring| area(ring)).collect();
290    let mut faces_of: Vec<(Part, Vec<usize>)> = Vec::new();
291    let mut face_of = vec![usize::MAX; cycles.len()];
292    for k in 0..cycles.len() {
293        if areas[k] > 0.0 {
294            face_of[k] = faces_of.len();
295            faces_of.push((cycles[k].0, vec![k]));
296        }
297    }
298    for k in 0..cycles.len() {
299        if areas[k] > 0.0 {
300            continue;
301        }
302        let probe = rings[k][0];
303        let host = (0..cycles.len())
304            .filter(|&o| areas[o] > 0.0 && cycles[o].0 == cycles[k].0 && holds(&rings[o], probe))
305            .min_by(|&a, &b| areas[a].total_cmp(&areas[b]))
306            .ok_or_else(|| refuse("mill_hole", format!("a hole in {:?} lies in no outer boundary of its part", cycles[k].0)))?;
307        faces_of[face_of[host]].1.push(k);
308    }
309    // The records: the plan's vertices, then the floor's corners; the plan's
310    // edges, then the walls' uprights and the floor's sides.
311    let corners = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
312    let corner_vertex = |c: [f64; 2]| plan.vertices.iter().position(|v| v.point.x == c[0] && v.point.y == c[1]).ok_or_else(|| refuse("mill_wall", "a corner of the box is missing".into()));
313    let top_corners = [corner_vertex(corners[0])?, corner_vertex(corners[1])?, corner_vertex(corners[2])?, corner_vertex(corners[3])?];
314    let bottom = match sides { Sides::Walls { bottom } => bottom, Sides::Floor { .. } => f64::NAN };
315    let low = |k: usize| Vec3::new(corners[k][0], corners[k][1], bottom);
316    let mut vertices: Vec<VertexRecord> = plan.vertices.iter().enumerate().map(|(k, v)| VertexRecord { id: k as u64 + 1, point: faces.lift(v.point) }).collect();
317    let low_vertex = |k: usize| (plan.vertices.len() + k) as u64 + 1;
318    let walls = matches!(sides, Sides::Walls { .. });
319    if walls {
320        for k in 0..4 {
321            vertices.push(VertexRecord { id: low_vertex(k), point: low(k) });
322        }
323    }
324    let mut next = vertices.len() as u64;
325    let mut id = || {
326        next += 1;
327        next
328    };
329    let mut edges: Vec<EdgeRecord> = Vec::with_capacity(plan.edges.len() + 8);
330    let record = |curve: NurbsCurve, from: u64, to: u64, edges: &mut Vec<EdgeRecord>, id: u64| -> Result<usize, KernelRefusal> {
331        let [t0, t1] = curve.domain().map_err(|e| refuse("mill_edge", e))?;
332        edges.push(EdgeRecord { id, curve, t0, t1, start_vertex_id: from, end_vertex_id: to, degenerate: false, name: None });
333        Ok(edges.len() - 1)
334    };
335    for (k, e) in plan.edges.iter().enumerate() {
336        let curve = curves[k].curve.clone();
337        let edge_id = id();
338        record(curve, e.from as u64 + 1, e.to as u64 + 1, &mut edges, edge_id)?;
339    }
340    // uprights from each floor corner to the top's corner; floor sides corner k to k + 1
341    let mut upright = [0usize; 4];
342    let mut floor_side = [0usize; 4];
343    if walls {
344        for k in 0..4 {
345            let curve = make_line(low(k), faces.lift(plan.vertices[top_corners[k]].point)).map_err(|e| refuse("mill_wall", e))?;
346            let edge_id = id();
347            upright[k] = record(curve, low_vertex(k), top_corners[k] as u64 + 1, &mut edges, edge_id)?;
348        }
349        for k in 0..4 {
350            let curve = make_line(low(k), low((k + 1) % 4)).map_err(|e| refuse("mill_floor", e))?;
351            let edge_id = id();
352            floor_side[k] = record(curve, low_vertex(k), low_vertex((k + 1) % 4), &mut edges, edge_id)?;
353        }
354    }
355    // Each side's chain of edges with Outside on the right, corner to corner.
356    let mut chains: Vec<Vec<usize>> = Vec::with_capacity(4);
357    for side in 0..4 {
358        let (start, finish) = (top_corners[side], top_corners[(side + 1) % 4]);
359        let mut chain = Vec::new();
360        let mut at = start;
361        while at != finish {
362            let next = plan.edges.iter().position(|e| e.right == Part::Outside && e.from == at).ok_or_else(|| refuse("mill_wall", format!("the side {side} breaks off")))?;
363            chain.push(next);
364            at = plan.edges[next].to;
365            if chain.len() > plan.edges.len() {
366                return Err(refuse("mill_wall", format!("the side {side} does not reach its corner")));
367            }
368        }
369        chains.push(chain);
370    }
371    // A face: its surface, its outward direction at a point of it, and its
372    // loops of (edge index, forward) counter-clockwise about the outward normal.
373    let mut face_records: Vec<FaceRecord> = Vec::with_capacity(faces_of.len() + 5);
374    let mut make_face = |surface: NurbsSurface, outward: &dyn Fn(Vec3) -> Vec3, loops: Vec<Vec<(usize, bool)>>, id: &mut dyn FnMut() -> u64| -> Result<(), KernelRefusal> {
375        let mut loop_records = Vec::with_capacity(loops.len());
376        let mut same_sense = None;
377        for uses in loops {
378            let mut coedges = Vec::with_capacity(uses.len());
379            for (edge, forward) in uses {
380                // the edge's points (a line's two ends) inverted onto the surface, at the curve's parameters
381                let (points, parameters): (Vec<Vec3>, Vec<f64>) = if edge < curves.len() {
382                    (curves[edge].points.clone(), curves[edge].parameters.clone())
383                } else {
384                    let curve = &edges[edge].curve;
385                    (vec![curve.evaluate(edges[edge].t0).map_err(|e| refuse("mill_edge", e))?, curve.evaluate(edges[edge].t1).map_err(|e| refuse("mill_edge", e))?], vec![edges[edge].t0, edges[edge].t1])
386                };
387                let mut uv = Vec::with_capacity(points.len());
388                for p in &points {
389                    let (at, distance) = crate::pcurve::invert_checked(&surface, *p).map_err(|err| refuse("mill_invert", err))?;
390                    if !(distance <= 1e-6 * r) {
391                        return Err(refuse("mill_invert", format!("a point {p:?} of the edge {edge} ({:?}|{:?}) lies {distance:e} off its face's surface (at {at:?})", plan.edges.get(edge).map(|e| e.left), plan.edges.get(edge).map(|e| e.right))));
392                    }
393                    uv.push(Vec3::new(at[0], at[1], 0.0));
394                }
395                if same_sense.is_none() {
396                    let (u, w) = (uv[uv.len() / 2].x, uv[uv.len() / 2].y);
397                    let normal = surface.normal(u, w).map_err(|e| refuse("mill_normal", e))?;
398                    same_sense = Some(normal.dot(outward(points[points.len() / 2])) > 0.0);
399                }
400                let pcurve = through(&uv, &parameters).map_err(|err| refuse("mill_pcurve", err))?;
401                let pcurve = if forward { pcurve } else { pcurve.reversed().map_err(|err| refuse("mill_reverse", err))? };
402                coedges.push(CoedgeRecord { id: id(), edge_id: edges[edge].id, forward, pcurve });
403            }
404            loop_records.push(LoopRecord { id: id(), coedges });
405        }
406        face_records.push(FaceRecord { id: id(), surface, same_sense: same_sense.unwrap_or(true), loops: loop_records, name: None });
407        Ok(())
408    };
409    // The top's faces, each sensed out of the stock.
410    for (part, loops) in &faces_of {
411        let surface = faces.surface(*part).map_err(|e| refuse("mill_surface", format!("{part:?}: {e}")))?;
412        let part = *part;
413        let loops = loops.iter().map(|&k| cycles[k].1.iter().map(|h| (h.edge, h.forward)).collect()).collect();
414        make_face(surface, &move |at: Vec3| faces.outward(part, at), loops, &mut id)?;
415    }
416    match sides {
417        // The walls, seen from outside: the floor's side along, up the far
418        // upright, back along the top's side (its edges run the other way),
419        // down the near upright. The floor, seen from below.
420        Sides::Walls { bottom } => {
421            for side in 0..4 {
422                let mut uses = vec![(floor_side[side], true), (upright[(side + 1) % 4], true)];
423                uses.extend(chains[side].iter().rev().map(|&e| (e, false)));
424                uses.push((upright[side], false));
425                let along = low((side + 1) % 4).sub(low(side));
426                let unit = along.normalized().map_err(|e| refuse("mill_wall", e))?;
427                let plane = make_plane(low(side), unit, Vec3::new(0.0, 0.0, 1.0), along.length(), plan.top - bottom).map_err(|e| refuse("mill_wall", e))?;
428                let out_of = Vec3::new(unit.y, -unit.x, 0.0);
429                make_face(plane, &move |_| out_of, vec![uses], &mut id)?;
430            }
431            let floor = make_plane(low(0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0), x1 - x0, y1 - y0).map_err(|e| refuse("mill_floor", e))?;
432            make_face(floor, &|_| Vec3::new(0.0, 0.0, -1.0), vec![vec![(floor_side[3], false), (floor_side[2], false), (floor_side[1], false), (floor_side[0], false)]], &mut id)?;
433        }
434        // One floor under the whole boundary, seen from outside it: the
435        // sides' edges the other way, last first.
436        Sides::Floor { origin, normal } => {
437            let normal = normal.normalized().map_err(|e| refuse("mill_floor", e))?;
438            let u = normal.perpendicular().map_err(|e| refuse("mill_floor", e))?;
439            let w = normal.cross(u);
440            let reach = curves.iter().flat_map(|c| c.points.iter()).map(|p| p.sub(origin).length()).fold(0.0f64, f64::max) * 1.01 + r;
441            let floor = make_plane(origin.sub(u.scale(reach)).sub(w.scale(reach)), u, w, 2.0 * reach, 2.0 * reach).map_err(|e| refuse("mill_floor", e))?;
442            let uses: Vec<(usize, bool)> = chains.iter().flatten().rev().map(|&e| (e, false)).collect();
443            make_face(floor, &move |_| normal, vec![uses], &mut id)?;
444        }
445    }
446    let shell = ShellRecord { id: id(), faces: face_records };
447    let solid = BrepSolid {
448        mass_properties_cache: Default::default(),
449        id: id(),
450        vertices,
451        edges,
452        shells: vec![shell],
453        genus: 0,
454        kind: BodyKind::Solid,
455        cells: Default::default(),
456    };
457    let issues = solid.validate();
458    if let Some(issue) = issues.first() {
459        return Err(refuse("mill_invalid", format!("the block is not a valid solid: {issue:?}")));
460    }
461    Ok(solid)
462}
463