BREP_offset 0.27.0

Solid offsets, shells and thickening of the BREP kernel.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! A body grown by at least the radius of a straight bore through it
//! (`BREP_OFFSET_BORE_DIMPLES`, default on; `=0` leaves the growth filled).
//!
//! The parallel body closes the bore, but not flat: each end keeps a dimple
//! where the rolling ball about the bore's rim reaches the axis, at
//! `√(d² − r²)` past the end face instead of `d`. The sharp offset loses the
//! bore once its offset radius `r − d` reaches zero, so the rim edge the
//! rounding would have rolled is gone and the grown body comes out filled
//! (a tube R 5 r 2 h 10 grown by 2: 2084.442 for 2079.6231064). The fill is
//! the parallel body of the bore-filled solid exactly, so each dimple is
//! carved from it: the solid of revolution between the rim's torus and the
//! grown end plane.
//!
//! The carve is exact only where nothing but the rim is within `d` of the
//! dimple. A bore qualifies when its cylinder faces are concave of radius at
//! most `d`, each end it opens at (both of a through bore, the mouth of a
//! blind one) is an end plane square to its axis that is material around the rim, every other face and edge
//! stands at least `d` from both dimples (a box test in the bore's frame,
//! conservative), and the grown body still fills the dimple. Anything else
//! leaves the grown body as it was.
use super::debug_enabled;
use crate::analytic_surface::AnalyticSurface;
use crate::topology::{BrepSolid, FaceRecord};
use crate::{boolean_operation, classify_point, make_arc, make_line, revolve_profile_brep, BooleanOperation, BooleanOptions, PointClass, Vec3};
use std::f64::consts::PI;

pub(super) fn bore_dimples_enabled() -> bool {
    switch!("BREP_OFFSET_BORE_DIMPLES", true)
}

/// A straight bore: a point on its axis, the unit axis, its radius and the
/// axial span its cylinder faces cover (from the point).
struct Bore {
    origin: Vec3,
    axis: Vec3,
    radius: f64,
    span: [f64; 2],
    /// Whether the bore opens past the end at `span[0]` and at `span[1]`. A
    /// blind bore is closed at its floor, where no rim rolls and no dimple is.
    open: [bool; 2],
    faces: Vec<u64>,
}

/// The cylinder `surface` lies on, as (point on axis, unit axis, radius).
fn cylinder_of(surface: &crate::NurbsSurface) -> Option<(Vec3, Vec3, f64)> {
    match surface.analytic()? {
        AnalyticSurface::RuledRevolution { frame, rho0, rho1, .. } => {
            ((rho0 - rho1).abs() <= 1e-9 * rho0.abs().max(1.0)).then_some((frame.origin, frame.axis, *rho0))
        }
        AnalyticSurface::Revolution { frame, generatrix, .. } => {
            // A partial sweep of a straight generatrix parallel to the axis.
            let mut radius: Option<f64> = None;
            for control in &generatrix.control_points {
                let p = control.point().ok()?;
                let d = p.sub(frame.origin);
                let rho = d.sub(frame.axis.scale(d.dot(frame.axis))).length();
                match radius {
                    None => radius = Some(rho),
                    Some(r) if (r - rho).abs() <= 1e-9 * r.max(1.0) => {}
                    _ => return None,
                }
            }
            radius.map(|r| (frame.origin, frame.axis, r))
        }
        _ => None,
    }
}

fn classify(solid: &BrepSolid, point: Vec3, scale: f64) -> Option<PointClass> {
    classify_point(point, solid, 1e-9 * scale).ok().map(|c| c.class)
}

/// Two unit vectors square to `axis` and to each other.
fn across(axis: Vec3) -> (Vec3, Vec3) {
    let seed = if axis.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
    let first = seed.sub(axis.scale(seed.dot(axis)));
    let first = first.scale(1.0 / first.length());
    (first, axis.cross(first))
}

/// The straight bores of `source` whose radius `keep` admits, open at an end.
fn bores(source: &BrepSolid, scale: f64, keep: impl Fn(f64) -> bool) -> Vec<Bore> {
    let mut found: Vec<Bore> = Vec::new();
    for face in source.shells.iter().flat_map(|shell| &shell.faces) {
        let Some((origin, axis, radius)) = cylinder_of(&face.surface) else { continue };
        if !(radius > 0.0 && keep(radius)) {
            continue;
        }
        let axial = |p: Vec3| p.sub(origin).dot(axis);
        let mut span = [f64::INFINITY, f64::NEG_INFINITY];
        // The face's extent along the axis, read at its edges' vertices (an edge's curve may
        // run past them, a seam on its untrimmed generator).
        for edge in face_edges(source, face) {
            for id in [edge.start_vertex_id, edge.end_vertex_id] {
                if let Some(vertex) = source.vertices.iter().find(|vertex| vertex.id == id) {
                    span = [span[0].min(axial(vertex.point)), span[1].max(axial(vertex.point))];
                }
            }
        }
        if !(span[1] > span[0]) {
            continue;
        }
        let same = found.iter_mut().find(|bore| {
            let off = origin.sub(bore.origin);
            bore.axis.cross(axis).length() <= 1e-9
                && off.sub(bore.axis.scale(off.dot(bore.axis))).length() <= 1e-9 * scale
                && (bore.radius - radius).abs() <= 1e-9 * scale
        });
        match same {
            Some(bore) => {
                let shift = origin.sub(bore.origin).dot(bore.axis);
                let sign = bore.axis.dot(axis).signum();
                let (a, b) = (shift + sign * span[0], shift + sign * span[1]);
                bore.span = [bore.span[0].min(a.min(b)), bore.span[1].max(a.max(b))];
                bore.faces.push(face.id);
            }
            None => found.push(Bore { origin, axis, radius, span, open: [false; 2], faces: vec![face.id] }),
        }
    }
    // Hollow along its whole length (concave): the axis is outside the body at
    // the middle, the body is material just outside the cylinder there, and
    // each end either opens (the axis is outside just past it) or is a blind
    // bore's floor (material just past it). At least one end opens.
    found.retain_mut(|bore| {
        let (x, y) = across(bore.axis);
        let at = |t: f64| bore.origin.add(bore.axis.scale(t));
        let middle = 0.5 * (bore.span[0] + bore.span[1]);
        let length = bore.span[1] - bore.span[0];
        let eps = 1e-3 * length.min(bore.radius);
        let out = |p: Vec3| classify(source, p, scale) == Some(PointClass::Out);
        let inside = |p: Vec3| classify(source, p, scale) == Some(PointClass::In);
        let (low, high) = (at(bore.span[0] - eps), at(bore.span[1] + eps));
        bore.open = [out(low), out(high)];
        out(at(middle))
            && (bore.open[0] || inside(low))
            && (bore.open[1] || inside(high))
            && (bore.open[0] || bore.open[1])
            && [x, y, x.scale(-1.0), y.scale(-1.0)].iter().all(|r| inside(at(middle).add(r.scale(bore.radius + eps))))
    });
    found
}

fn face_edges<'a>(source: &'a BrepSolid, face: &FaceRecord) -> Vec<&'a crate::topology::EdgeRecord> {
    face.loops
        .iter()
        .flat_map(|lp| &lp.coedges)
        .filter_map(|coedge| source.edges.iter().find(|edge| edge.id == coedge.edge_id))
        .collect()
}

/// Whether the end of `bore` at axial `t` (outward `out` along the axis) is
/// flat at the rim: material just inside the end plane around it, empty just
/// past it.
fn flat_end(source: &BrepSolid, bore: &Bore, t: f64, out: Vec3, distance: f64, scale: f64) -> bool {
    let (x, y) = across(bore.axis);
    let centre = bore.origin.add(bore.axis.scale(t));
    let eps = 1e-4 * bore.radius.min(distance);
    // Local flatness at the rim; what lies further out is the clearance test's.
    for k in 1..=2 {
        let rho = bore.radius + 0.25 * bore.radius.min(distance) * k as f64 / 2.0;
        for direction in [x, y, x.scale(-1.0), y.scale(-1.0), x.add(y).scale(0.5f64.sqrt()), x.sub(y).scale(0.5f64.sqrt())] {
            let foot = centre.add(direction.scale(rho));
            if classify(source, foot.sub(out.scale(eps)), scale) != Some(PointClass::In)
                || classify(source, foot.add(out.scale(eps)), scale) != Some(PointClass::Out)
            {
                return false;
            }
        }
    }
    true
}

/// Whether every face and edge of `source` that is not the bore's own stands
/// at least `distance` from the dimple at the end `t` (outward `out`): the
/// dimple lies in the cylinder `ρ ≤ r`, `0 ≤ z ≤ d` past the end plane, and
/// each face is read on its whole untrimmed surface at dense samples, a sample
/// near the bar refined by a local search. The end face that owns the rim is
/// read by its edges other than the rim: the rim is the dimple's cause, and the
/// face's region is the end plane itself, at height zero under the dimple.
fn clear_of_others(source: &BrepSolid, bore: &Bore, t: f64, out: Vec3, distance: f64, scale: f64) -> bool {
    reach_of_others(source, bore, t, out, distance, scale, false)
}

/// [`clear_of_others`], except that, where `beside` is set, a straight edge
/// of the end face lying in the end plane (a plate's outer edge beside the
/// bore), and a planar side square to the end plane, wholly on the body's
/// side of it and within the span of its own end-plane edge, are passed over
/// however near: neither is ever nearer a dimple point than the rim is. A
/// dimple point lies over the rim's disc (ρ < r) at height h > 0; such an
/// edge's points lie in the end plane outside the rim (ρ ≥ r), so their
/// horizontal distance is at least r − ρ and their height the same h, and a
/// side's nearest point past the plane is on its end-plane edge. So the
/// dimple is the growth's void whatever they are. Anything else within
/// `distance` declines.
fn reach_of_others(source: &BrepSolid, bore: &Bore, t: f64, out: Vec3, distance: f64, scale: f64, beside: bool) -> bool {
    let (x, y) = across(bore.axis);
    let centre = bore.origin.add(bore.axis.scale(t));
    let gap = |p: Vec3| {
        let d = p.sub(centre);
        let (a, b, z) = (d.dot(x), d.dot(y), d.dot(out));
        let radial = ((a * a + b * b).sqrt() - bore.radius).max(0.0);
        let axial = (-z).max(z - distance).max(0.0);
        radial.hypot(axial)
    };
    let enough = distance * (1.0 - 1e-9);
    // The rim circle itself: every sampled point at the rim radius in the end plane.
    let on_rim = |edge: &crate::topology::EdgeRecord| {
        let Ok([t0, t1]) = edge.curve.domain() else { return false };
        (0..=16).all(|k| {
            edge.curve.evaluate(t0 + (t1 - t0) * k as f64 / 16.0).is_ok_and(|p| {
                let d = p.sub(centre);
                let (a, b, z) = (d.dot(x), d.dot(y), d.dot(out));
                z.abs() <= 1e-9 * scale && ((a * a + b * b).sqrt() - bore.radius).abs() <= 1e-9 * scale
            })
        })
    };
    // Each sample within reach of a violation (its gap under the bar plus the largest sample
    // spacing) is refined by a local search over its neighbouring parameter cell, so a face or
    // edge exactly `d` away (a plate's side at the dimple's reach) reads as clear.
    let edge_clear = |edge: &crate::topology::EdgeRecord| -> bool {
        let Ok([t0, t1]) = edge.curve.domain() else { return false };
        let n = 256;
        let step = (t1 - t0) / n as f64;
        let read = |t: f64| edge.curve.evaluate(t.clamp(t0, t1)).map_or(f64::NEG_INFINITY, gap);
        let points: Vec<Vec3> = (0..=n).filter_map(|k| edge.curve.evaluate(t0 + step * k as f64).ok()).collect();
        if points.len() != n + 1 {
            return false;
        }
        let spacing = points.windows(2).map(|pair| pair[1].sub(pair[0]).length()).fold(0.0f64, f64::max);
        (0..=n).all(|k| {
            let here = gap(points[k]);
            if here - spacing >= enough {
                return true;
            }
            // Golden section over the two neighbouring cells.
            let (mut a, mut b) = (t0 + step * (k as f64 - 1.0), t0 + step * (k as f64 + 1.0));
            let ratio = 0.5 * (5f64.sqrt() - 1.0);
            let mut best = here;
            for _ in 0..80 {
                let (c, d) = (b - ratio * (b - a), a + ratio * (b - a));
                let (fc, fd) = (read(c), read(d));
                best = best.min(fc).min(fd);
                if fc < fd { b = d } else { a = c }
            }
            best >= enough
        })
    };
    let surface_clear = |surface: &crate::NurbsSurface| -> bool {
        let (Ok([u0, u1]), Ok([v0, v1])) = (surface.domain_u(), surface.domain_v()) else { return false };
        let n = 64;
        let (du, dv) = ((u1 - u0) / n as f64, (v1 - v0) / n as f64);
        let read = |u: f64, v: f64| surface.evaluate(u.clamp(u0, u1), v.clamp(v0, v1)).map_or(f64::NEG_INFINITY, gap);
        let mut grid = Vec::with_capacity((n + 1) * (n + 1));
        for i in 0..=n {
            for j in 0..=n {
                match surface.evaluate(u0 + du * i as f64, v0 + dv * j as f64) {
                    Ok(p) => grid.push(p),
                    Err(_) => return false,
                }
            }
        }
        let at = |i: usize, j: usize| grid[i * (n + 1) + j];
        let mut spacing = 0.0f64;
        for i in 0..n {
            for j in 0..n {
                spacing = spacing.max(at(i, j).sub(at(i + 1, j + 1)).length()).max(at(i + 1, j).sub(at(i, j + 1)).length());
            }
        }
        (0..=n).all(|i| {
            (0..=n).all(|j| {
                let here = gap(at(i, j));
                if here - spacing >= enough {
                    return true;
                }
                // Pattern search from the sample, its step halving down to 1e-12 of a cell.
                let (mut u, mut v, mut best) = (u0 + du * i as f64, v0 + dv * j as f64, here);
                let (mut su, mut sv) = (du, dv);
                while su > 1e-12 * du {
                    let mut moved = false;
                    for (a, b) in [(su, 0.0), (-su, 0.0), (0.0, sv), (0.0, -sv)] {
                        let value = read(u + a, v + b);
                        if value < best {
                            best = value;
                            u = (u + a).clamp(u0, u1);
                            v = (v + b).clamp(v0, v1);
                            moved = true;
                        }
                    }
                    if !moved {
                        su *= 0.5;
                        sv *= 0.5;
                    }
                }
                best >= enough
            })
        })
    };
    // A straight edge in the end plane: its two ends, both at height zero
    // (and its middle, so a curve through them is not read as one).
    let height = |p: Vec3| p.sub(centre).dot(out);
    // The segment is the edge's own, between its vertices (its carrier may
    // run past them).
    let in_plane_segment = |edge: &crate::topology::EdgeRecord| -> Option<(Vec3, Vec3)> {
        edge.curve.straight_segment(1e-9 * scale)?;
        let vertex = |id: u64| source.vertices.iter().find(|v| v.id == id).map(|v| v.point);
        let segment = (vertex(edge.start_vertex_id)?, vertex(edge.end_vertex_id)?);
        let middle = edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).ok()?;
        let on_chord = {
            let (a, b) = segment;
            let along = b.sub(a);
            let length = along.length();
            length > 0.0 && middle.sub(a).sub(along.scale(middle.sub(a).dot(along) / (length * length))).length() <= 1e-9 * scale
        };
        (on_chord && [segment.0, segment.1, middle].iter().all(|p| height(*p).abs() <= 1e-9 * scale)).then_some(segment)
    };
    for face in source.shells.iter().flat_map(|shell| &shell.faces) {
        if bore.faces.contains(&face.id) {
            continue;
        }
        // The end face that owns this rim lies in the end plane, so its patch covers the bore's
        // mouth; it is read by its other edges (its region past the rim is plane at height 0 under
        // the dimple, and its boundary elsewhere is what could come near). Every other face is
        // read by its whole untrimmed surface, which holds the face.
        let edges = face_edges(source, face);
        let planar = matches!(face.surface.analytic(), Some(AnalyticSurface::Plane { .. }));
        let owns_rim = planar && edges.iter().any(|edge| on_rim(edge));
        if owns_rim {
            for edge in edges.iter().filter(|edge| !on_rim(edge)) {
                if edge_clear(edge) {
                    continue;
                }
                if !(beside && in_plane_segment(edge).is_some()) {
                    os_debug!("bore dimples: edge {} of the end face stands within {distance} of the dimple at {t}", edge.id);
                    return false;
                }
            }
            continue;
        }
        if surface_clear(&face.surface) {
            continue;
        }
        // A side: planar, square to the end plane, wholly at or below it,
        // with exactly one edge in it, straight, whose span (along it) holds
        // the whole face. Its nearest point to anything past the plane is on
        // that edge.
        let side = beside && planar && {
            let corners: Vec<Vec3> = edges.iter().flat_map(|edge| [edge.start_vertex_id, edge.end_vertex_id]).filter_map(|id| source.vertices.iter().find(|v| v.id == id)).map(|v| v.point).collect();
            let normal = match (face.surface.domain_u(), face.surface.domain_v()) {
                (Ok([u0, u1]), Ok([v0, v1])) => face.surface.normal(0.5 * (u0 + u1), 0.5 * (v0 + v1)).ok(),
                _ => None,
            };
            let square = normal.is_some_and(|n| n.dot(out).abs() <= 1e-9);
            let below = corners.iter().all(|p| height(*p) <= 1e-9 * scale);
            let top: Vec<(Vec3, Vec3)> = edges.iter().filter_map(|edge| in_plane_segment(edge)).collect();
            let within = top.len() == 1 && {
                let (a, b) = top[0];
                let along = b.sub(a);
                let length = along.length();
                length > 0.0 && corners.iter().all(|p| {
                    let s = p.sub(a).dot(along) / (length * length);
                    (-1e-9..=1.0 + 1e-9).contains(&s)
                })
            };
            let straight = edges.iter().all(|edge| edge.curve.straight_segment(1e-9 * scale).is_some());
            square && below && within && straight
        };
        if !side {
            os_debug!("bore dimples: face {} stands within {distance} of the dimple at {t}", face.id);
            return false;
        }
    }
    true
}

/// The dimple at a rim of radius `r` (centre `centre`, end plane's outward
/// normal `out`) for a growth `d >= r`: between the rim's torus and the grown
/// end plane, revolved about the bore's axis.
fn dimple(centre: Vec3, out: Vec3, r: f64, d: f64) -> Result<BrepSolid, String> {
    let (x, _) = across(out);
    let at = |rho: f64, z: f64| centre.add(x.scale(rho)).add(out.scale(z));
    let low = (d * d - r * r).max(0.0).sqrt();
    let on_axis = make_line(at(0.0, low), at(0.0, d))?;
    let lid = make_line(at(0.0, d), at(r, d))?;
    // The rim's torus in this half-plane: about (r, 0) from straight up to the axis.
    let end = PI - (r / d).min(1.0).acos();
    let arc = make_arc(at(r, 0.0), x, out, d, 0.5 * PI, end)?;
    revolve_profile_brep(&[on_axis, lid, arc], centre, out, 2.0 * PI)
}

/// `grown` (`source` grown by `distance`) with the dimple at each end of every
/// qualifying bore carved, or `None` when there is none to carve or any step
/// declines.
pub(super) fn carve_bore_dimples(source: &BrepSolid, grown: &BrepSolid, distance: f64) -> Option<BrepSolid> {
    if !bore_dimples_enabled() || !(distance > 0.0) {
        return None;
    }
    let scale = crate::solid_scale(source).max(1.0);
    let mut voids = Vec::new();
    let found = bores(source, scale, |radius| radius <= distance * (1.0 + 1e-9));
    os_debug!("bore dimples: {} bore(s) of radius at most {distance}", found.len());
    for bore in found {
        for (t, out, open) in [(bore.span[1], bore.axis, bore.open[1]), (bore.span[0], bore.axis.scale(-1.0), bore.open[0])] {
            if !open {
                continue;
            }
            if !flat_end(source, &bore, t, out, distance, scale) {
                os_debug!("bore dimples: the end at {t} is not flat at its rim");
                return None;
            }
            if !reach_of_others(source, &bore, t, out, distance, scale, true) {
                os_debug!("bore dimples: a bore of radius {} declined at its end {t}", bore.radius);
                return None;
            }
            let centre = bore.origin.add(bore.axis.scale(t));
            // Still filled: the dimple's middle on the axis is inside the growth.
            let low = (distance * distance - bore.radius * bore.radius).max(0.0).sqrt();
            let probe = centre.add(out.scale(0.5 * (low + distance)));
            if classify(grown, probe, scale) != Some(PointClass::In) {
                os_debug!("bore dimples: the growth is already carved at {probe:?}");
                return None;
            }
            let void = dimple(centre, out, bore.radius, distance).ok()?;
            voids.push(void);
        }
    }
    if voids.is_empty() {
        return None;
    }
    let mut carved = grown.clone();
    for void in &voids {
        carved = match boolean_operation(&carved, void, BooleanOperation::Subtract, &BooleanOptions::default()) {
            Ok(next) => next,
            Err(error) => {
                os_debug!("bore dimples: the carve declined: {}", error.message);
                return None;
            }
        };
    }
    carved.validate().is_empty().then_some(carved)
}

/// An end of a bore wider than the growth, whose sharp offset keeps the bore
/// (radius `r − d`) with a sharp rim at the grown end plane: the rim the
/// rounding would roll a ball of radius `d` round, a ring torus about the
/// source rim (major `r`, minor `d`). Its centre on the source end plane, the
/// end's outward axis and the source bore's radius.
pub(super) struct WideRim {
    pub centre: Vec3,
    pub out: Vec3,
    pub radius: f64,
}

impl WideRim {
    /// Whether `p` lies on this rim's sharp edge in the grown body: the circle
    /// of radius `r − d` at `d` past the end plane.
    pub fn holds(&self, p: Vec3, distance: f64, tolerance: f64) -> bool {
        let rel = p.sub(self.centre);
        let along = rel.dot(self.out);
        let rho = rel.sub(self.out.scale(along)).length();
        (along - distance).abs() <= tolerance && (rho - (self.radius - distance)).abs() <= tolerance
    }
}

/// The open ends of `source`'s straight bores wider than `distance` (the
/// growth keeps them, narrowed to `r − d`), each flat at its rim and clear of
/// every other face and edge within `d` of the cusp (the region the rim's
/// torus leaves between the narrowed bore and the grown end plane): the
/// rims whose rounding is the torus exactly. Ends that do not qualify are
/// left out (their rims are rounded as any other join).
pub(super) fn wide_bore_rims(source: &BrepSolid, distance: f64) -> Vec<WideRim> {
    if !bore_dimples_enabled() || !(distance > 0.0) {
        return Vec::new();
    }
    let scale = crate::solid_scale(source).max(1.0);
    let mut rims = Vec::new();
    for bore in bores(source, scale, |radius| radius > distance * (1.0 + 1e-9)) {
        for (t, out, open) in [(bore.span[1], bore.axis, bore.open[1]), (bore.span[0], bore.axis.scale(-1.0), bore.open[0])] {
            if !open || !flat_end(source, &bore, t, out, distance, scale) || !clear_of_others(source, &bore, t, out, distance, scale) {
                os_debug!("bore cusps: the end at {t} of a bore of radius {} does not qualify", bore.radius);
                continue;
            }
            rims.push(WideRim { centre: bore.origin.add(bore.axis.scale(t)), out, radius: bore.radius });
        }
    }
    os_debug!("bore cusps: {} rim(s) of bores wider than {distance}", rims.len());
    rims
}

/// The cusp at a wide rim: between the end plane grown by `d`, the narrowed
/// bore and the rim's torus (about `(r, 0)` from straight up to the bore,
/// radius `d`), run in to the axis across the empty bore, revolved.
fn cusp(rim: &WideRim, d: f64) -> Result<BrepSolid, String> {
    let (x, _) = across(rim.out);
    let at = |rho: f64, z: f64| rim.centre.add(x.scale(rho)).add(rim.out.scale(z));
    let r = rim.radius;
    let on_axis = make_line(at(0.0, 0.0), at(0.0, d))?;
    let lid = make_line(at(0.0, d), at(r, d))?;
    let arc = make_arc(at(r, 0.0), x, rim.out, d, 0.5 * PI, PI)?;
    let floor = make_line(at(r - d, 0.0), at(0.0, 0.0))?;
    revolve_profile_brep(&[on_axis, lid, arc, floor], rim.centre, rim.out, 2.0 * PI)
}

/// `body` (the growth with each wide rim left sharp) with each rim's cusp
/// carved, or a refusal naming what declined.
pub(super) fn carve_wide_rims(body: &BrepSolid, rims: &[WideRim], distance: f64) -> Result<BrepSolid, String> {
    let scale = crate::solid_scale(body).max(1.0);
    let mut carved = body.clone();
    for rim in rims {
        let (x, _) = across(rim.out);
        // The cusp is still material before the carve (a point in it, off the
        // torus by a tenth of the growth).
        let probe = rim.centre.add(x.scale(rim.radius - 0.5 * distance)).add(rim.out.scale(0.95 * distance));
        if classify(&carved, probe, scale) != Some(PointClass::In) {
            return Err(format!("the cusp at the rim about {:?} is not material in the growth", rim.centre));
        }
        let tool = cusp(rim, distance)?;
        carved = boolean_operation(&carved, &tool, BooleanOperation::Subtract, &BooleanOptions::default()).map_err(|error| format!("the cusp carve declined: {}", error.message))?;
    }
    let issues = carved.validate();
    if !issues.is_empty() {
        return Err(format!("the carved growth is not valid: {issues:?}"));
    }
    Ok(carved)
}