Skip to main content

brep_topology/brep/
boundary_query.rs

1//! Point queries against a solid's boundary, on its exact geometry: the
2//! boundary points nearest a point, the outward normal there, and the
3//! principal curvatures there; and the least box with sides square to the
4//! axes round the solid.
5//!
6//! The nearest boundary point is the least of three kinds of foot: each
7//! face's surface foot where it lies inside the face's trim, each edge's curve
8//! foot within the edge's range, and each vertex. A face foot outside its trim
9//! is no candidate: the face's nearest trimmed point then lies on its
10//! boundary, which the edge and vertex feet cover.
11
12use crate::{
13    classify_point, project_point_to_curve, project_point_to_surface, BrepSolid, FaceRecord,
14    KernelRefusal, KernelStage, PointClass, PolygonClass, Vec2, Vec3,
15};
16
17/// Where a boundary foot lies: inside one face, on one edge, or at a vertex.
18#[derive(Clone, Copy, Debug, PartialEq)]
19pub enum BoundaryPlace {
20    /// Inside the trim of the face with this id, at `(u, v)` on its surface.
21    Face { face: u64, uv: [f64; 2] },
22    /// On the edge with this id, at curve parameter `t`.
23    Edge { edge: u64, t: f64 },
24    /// At the vertex with this id.
25    Vertex { vertex: u64 },
26}
27
28/// A point of the boundary near a query point.
29#[derive(Clone, Copy, Debug)]
30pub struct BoundaryFoot {
31    pub point: Vec3,
32    pub distance: f64,
33    pub place: BoundaryPlace,
34}
35
36fn refusal(code: &'static str, message: String) -> KernelRefusal {
37    KernelRefusal::internal(KernelStage::Classify, code, message)
38}
39
40/// The trim tolerance in a face's parameters for a 3D `tolerance` at `uv`:
41/// the 3D band over the larger of the two parameter speeds there.
42fn parameter_tolerance(face: &FaceRecord, uv: [f64; 2], tolerance: f64) -> f64 {
43    match face.surface.deriv1(uv[0], uv[1]) {
44        Ok((_, su, sv)) => {
45            let speed = su.length().max(sv.length());
46            if speed > 0.0 && speed.is_finite() { tolerance / speed } else { tolerance }
47        }
48        Err(_) => tolerance,
49    }
50}
51
52/// Where the parameter point lies against the face's trim, its boundary a
53/// band of `tolerance` (3D).
54fn trim_class(face: &FaceRecord, uv: [f64; 2], tolerance: f64) -> Result<PolygonClass, KernelRefusal> {
55    let band = parameter_tolerance(face, uv, tolerance);
56    crate::parameter_point_in_face(face, Vec2 { x: uv[0], y: uv[1] }, band).map_err(|e| refusal("boundary_trim", e))
57}
58
59/// Whether the parameter point lies inside the face's trim, its boundary
60/// within `tolerance` (3D) included.
61fn inside_trim(face: &FaceRecord, uv: [f64; 2], tolerance: f64) -> Result<bool, KernelRefusal> {
62    Ok(trim_class(face, uv, tolerance)? != PolygonClass::Outside)
63}
64
65/// Whether a surface foot is a true foot: the point lies along the surface's
66/// normal from it. A foot the projector clamped to the surface's domain (the
67/// true nearest point lies past it) leaves a residual along the surface; its
68/// place on the boundary is an edge's or a vertex's, which those feet give.
69fn is_true_foot(face: &FaceRecord, uv: [f64; 2], foot: Vec3, point: Vec3, tolerance: f64) -> bool {
70    let residual = point.sub(foot);
71    let length = residual.length();
72    if length <= tolerance {
73        return true;
74    }
75    let Some(normal) = outward_normal(face, uv) else { return false };
76    let along = residual.sub(normal.scale(residual.dot(normal))).length();
77    along <= tolerance.max(1e-9 * length)
78}
79
80/// Samples per direction of the grid a face's trimmed region is searched from
81/// when the surface's global foot lies outside the trim.
82const TRIM_SEED_GRID: usize = 16;
83
84/// The face's feet of `point` that lie on its trimmed region: the surface's
85/// global foot, and the local foot Newton reaches from the nearest sample of a
86/// grid over the trimmed region (a minimum inside the trim that is not the
87/// surface's global one), each kept when it lies inside the trim (its band
88/// included) and is a true foot.
89#[doc(hidden)]
90pub fn face_feet(face: &FaceRecord, point: Vec3, tolerance: f64) -> Result<Vec<(Vec3, f64, [f64; 2], bool)>, KernelRefusal> {
91    let mut feet = Vec::new();
92    let mut take = |foot: crate::SurfaceProjection| -> Result<bool, KernelRefusal> {
93        let uv = [foot.u, foot.v];
94        let class = trim_class(face, uv, tolerance)?;
95        let inside = class != PolygonClass::Outside && is_true_foot(face, uv, foot.point, point, tolerance);
96        if inside {
97            feet.push((foot.point, foot.distance, uv, class == PolygonClass::Boundary));
98        }
99        Ok(inside)
100    };
101    let global = project_point_to_surface(&face.surface, point).map_err(|e| refusal("boundary_face_foot", e))?;
102    // A plane holds no foot but its global one: the distance is convex over it,
103    // so with that foot outside the trim the nearest point of the trimmed
104    // region lies on its boundary, which the edge and vertex feet give.
105    if take(global)? || matches!(face.surface.analytic(), Some(crate::AnalyticSurface::Plane { .. })) {
106        return Ok(feet);
107    }
108    let surface = &face.surface;
109    let ([u0, u1], [v0, v1]) = match (surface.domain_u(), surface.domain_v()) {
110        (Ok(u), Ok(v)) => (u, v),
111        _ => return Ok(feet),
112    };
113    let mut nearest: Option<(f64, [f64; 2])> = None;
114    for i in 0..=TRIM_SEED_GRID {
115        for j in 0..=TRIM_SEED_GRID {
116            let uv = [u0 + (u1 - u0) * i as f64 / TRIM_SEED_GRID as f64, v0 + (v1 - v0) * j as f64 / TRIM_SEED_GRID as f64];
117            if trim_class(face, uv, tolerance)? == PolygonClass::Outside {
118                continue;
119            }
120            let Ok(at) = surface.evaluate(uv[0], uv[1]) else { continue };
121            let distance = at.sub(point).length();
122            if nearest.is_none_or(|(best, _)| distance < best) {
123                nearest = Some((distance, uv));
124            }
125        }
126    }
127    if let Some((_, seed)) = nearest {
128        // The surface's own Newton from the seed (the closed forms of the analytic
129        // carriers answer the global foot, the one already rejected).
130        if let Ok(local) = crate::projection::project_point_to_surface_seeded(surface, point, seed[0], seed[1]) {
131            take(local)?;
132        }
133    }
134    Ok(feet)
135}
136
137/// Every face foot of `point` on its face's trimmed region ([`face_feet`]), and
138/// every edge and vertex foot, each with its distance; and whether each face
139/// foot lies on its trim's boundary band.
140fn boundary_feet(solid: &BrepSolid, point: Vec3, tolerance: f64) -> Result<Vec<(BoundaryFoot, bool)>, KernelRefusal> {
141    let mut feet = Vec::new();
142    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
143        for (foot, distance, uv, on_band) in face_feet(face, point, tolerance)? {
144            feet.push((BoundaryFoot { point: foot, distance, place: BoundaryPlace::Face { face: face.id, uv } }, on_band));
145        }
146    }
147    for edge in solid.edges.iter().filter(|edge| !edge.degenerate) {
148        let foot = project_point_to_curve(&edge.curve, point).map_err(|e| refusal("boundary_edge_foot", e))?;
149        let (low, high) = (edge.t0.min(edge.t1), edge.t0.max(edge.t1));
150        if foot.u >= low && foot.u <= high {
151            feet.push((BoundaryFoot { point: foot.point, distance: foot.distance, place: BoundaryPlace::Edge { edge: edge.id, t: foot.u } }, false));
152        }
153    }
154    for vertex in &solid.vertices {
155        feet.push((
156            BoundaryFoot {
157                point: vertex.point,
158                distance: vertex.point.sub(point).length(),
159                place: BoundaryPlace::Vertex { vertex: vertex.id },
160            },
161            false,
162        ));
163    }
164    Ok(feet)
165}
166
167/// The boundary point nearest `point`, on the solid's exact geometry, and
168/// where it lies. `tolerance` (mm) is the band a face foot may stand past its
169/// trim and still count as inside it. `None` for a solid with no boundary.
170/// A face foot on its trim's boundary band gives way to an edge or vertex foot
171/// within `tolerance` of it: the point lies on that edge (or vertex) within the
172/// tolerance, where the faces' normals decide crease or smooth.
173pub fn nearest_boundary_point(solid: &BrepSolid, point: Vec3, tolerance: f64) -> Result<Option<BoundaryFoot>, KernelRefusal> {
174    let feet = boundary_feet(solid, point, tolerance)?;
175    let Some(&(best, on_band)) = feet.iter().min_by(|a, b| a.0.distance.total_cmp(&b.0.distance)) else { return Ok(None) };
176    if on_band {
177        let edge_or_vertex = feet
178            .iter()
179            .filter(|(foot, _)| !matches!(foot.place, BoundaryPlace::Face { .. }))
180            .filter(|(foot, _)| foot.point.sub(best.point).length() <= tolerance)
181            .min_by(|a, b| a.0.distance.total_cmp(&b.0.distance));
182        if let Some(&(foot, _)) = edge_or_vertex {
183            return Ok(Some(foot));
184        }
185    }
186    Ok(Some(best))
187}
188
189/// The point of the solid nearest each point: the point itself where the
190/// solid holds it (inside or on its boundary, at `tolerance`), otherwise its
191/// nearest boundary point.
192pub fn solid_closest_points(solid: &BrepSolid, points: &[Vec3], tolerance: f64) -> Result<Vec<Vec3>, KernelRefusal> {
193    points
194        .iter()
195        .map(|&point| {
196            let class = classify_point(point, solid, tolerance).map_err(|e| refusal("closest_classify", e))?.class;
197            if class != PointClass::Out {
198                return Ok(point);
199            }
200            nearest_boundary_point(solid, point, tolerance)?
201                .map(|foot| foot.point)
202                .ok_or_else(|| refusal("closest_empty", "the solid has no boundary".into()))
203        })
204        .collect()
205}
206
207fn face_by_id(solid: &BrepSolid, id: u64) -> Option<&FaceRecord> {
208    solid.shells.iter().flat_map(|shell| &shell.faces).find(|face| face.id == id)
209}
210
211/// The outward unit normal of `face` at `uv`. At a pole (a side of the patch
212/// collapsed to a point) the surface has no normal of its own, and it is read
213/// a millionth of the way in, where it has one (as the face thicken does).
214fn outward_normal(face: &FaceRecord, uv: [f64; 2]) -> Option<Vec3> {
215    let surface = &face.surface;
216    let normal = match surface.normal(uv[0], uv[1]) {
217        Ok(normal) => normal,
218        Err(_) => pole_normal(surface, uv)?,
219    };
220    Some(if face.same_sense { normal } else { normal.scale(-1.0) })
221}
222
223/// The normal at a degenerate point (a pole, an apex), read a millionth inside
224/// along both parameters at five positions round it: their common normal when
225/// they agree (a ball's pole), `None` when they do not (a cone's apex has no
226/// tangent plane).
227fn pole_normal(surface: &crate::NurbsSurface, uv: [f64; 2]) -> Option<Vec3> {
228    let [u0, u1] = surface.domain_u().ok()?;
229    let [v0, v1] = surface.domain_v().ok()?;
230    let inward = |at: f64, low: f64, high: f64| at + (0.5 * (low + high) - at) * 1e-6;
231    let (u, v) = (inward(uv[0], u0, u1), inward(uv[1], v0, v1));
232    let first = surface.normal(u, v).ok()?;
233    let round = [0.2, 0.4, 0.6, 0.8].map(|f| [(u0 + (u1 - u0) * f, v), (u, v0 + (v1 - v0) * f)]);
234    for (ru, rv) in round.into_iter().flatten() {
235        // Only the positions that stay at the degenerate point: those whose
236        // 3D point is the same as the pole's.
237        let (Ok(at), Ok(pole)) = (surface.evaluate(ru, rv), surface.evaluate(u, v)) else { continue };
238        if at.sub(pole).length() > 1e-6 * (1.0 + pole.length()) {
239            continue;
240        }
241        let normal = surface.normal(ru, rv).ok()?;
242        if normal.dot(first) < POLE_AGREEMENT {
243            return None;
244        }
245    }
246    Some(first)
247}
248
249/// Two normals read a millionth from one degenerate point agree when their
250/// cosine is at least this (a ball's pole reads within about 1e-6 rad).
251const POLE_AGREEMENT: f64 = 0.999_999;
252
253/// Two outward normals within this angle (radians) are one tangent plane: an
254/// edge between them is smooth, not a crease.
255const SMOOTH_ANGLE: f64 = 1e-6;
256
257/// The outward unit normals the boundary has at `point`, one per face whose
258/// trim holds the point within `tolerance`; empty off the boundary.
259fn normals_at(solid: &BrepSolid, point: Vec3, tolerance: f64) -> Result<Vec<Vec3>, KernelRefusal> {
260    let mut normals = Vec::new();
261    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
262        let foot = project_point_to_surface(&face.surface, point).map_err(|e| refusal("normal_face_foot", e))?;
263        if foot.distance <= tolerance && inside_trim(face, [foot.u, foot.v], tolerance)? {
264            if let Some(normal) = outward_normal(face, [foot.u, foot.v]) {
265                normals.push(normal);
266            }
267        }
268    }
269    Ok(normals)
270}
271
272/// The outward unit normal at each point of the solid's boundary (within
273/// `tolerance`, mm), where the boundary has a tangent plane there: `None` at a
274/// crease, where faces meet at an angle, or off the boundary. A point on a
275/// smooth edge, where the faces meet tangentially, has the faces' common
276/// normal.
277pub fn solid_outward_normals(solid: &BrepSolid, points: &[Vec3], tolerance: f64) -> Result<Vec<Option<Vec3>>, KernelRefusal> {
278    points
279        .iter()
280        .map(|&point| {
281            let normals = normals_at(solid, point, tolerance)?;
282            let Some(&first) = normals.first() else { return Ok(None) };
283            let cos = SMOOTH_ANGLE.cos();
284            Ok(normals.iter().all(|normal| normal.dot(first) >= cos).then_some(first))
285        })
286        .collect()
287}
288
289/// The principal curvatures `[k1, k2]`, `k1 >= k2`, at the boundary point
290/// nearest each point: positive where the boundary bends away from its
291/// outward normal, as on a ball (`1 / r` both ways); `None` where that point
292/// lies on a crease. A nearest point on an edge or at a vertex is a crease
293/// unless every face there shares one tangent plane, and then the curvatures
294/// are read on the first of them.
295pub fn solid_principal_curvatures(solid: &BrepSolid, points: &[Vec3], tolerance: f64) -> Result<Vec<Option<[f64; 2]>>, KernelRefusal> {
296    points
297        .iter()
298        .map(|&point| {
299            let Some(foot) = nearest_boundary_point(solid, point, tolerance)? else { return Ok(None) };
300            // The face the curvatures are read on: the foot's own, or on an edge
301            // or a vertex the faces there when they share one tangent plane.
302            let (face, uv) = match foot.place {
303                BoundaryPlace::Face { face, uv } => match face_by_id(solid, face) {
304                    Some(record) => (record, uv),
305                    None => return Ok(None),
306                },
307                _ => {
308                    let normals = normals_at(solid, foot.point, tolerance)?;
309                    let Some(&first) = normals.first() else { return Ok(None) };
310                    if !normals.iter().all(|normal| normal.dot(first) >= SMOOTH_ANGLE.cos()) {
311                        return Ok(None);
312                    }
313                    let mut found = None;
314                    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
315                        let at = project_point_to_surface(&face.surface, foot.point).map_err(|e| refusal("curvature_face_foot", e))?;
316                        if at.distance <= tolerance && inside_trim(face, [at.u, at.v], tolerance)? {
317                            found = Some((face, [at.u, at.v]));
318                            break;
319                        }
320                    }
321                    match found {
322                        Some(found) => found,
323                        None => return Ok(None),
324                    }
325                }
326            };
327            // At a pole the parametrization is degenerate. A ball's pole has its
328            // ball's curvature, signed against the surface's own normal there
329            // (the kernel's convention: -1/r for a normal away from the centre);
330            // any other pole is read a millionth inside, as the normal is.
331            let surface = &face.surface;
332            let curvatures = surface.principal_curvatures(uv[0], uv[1]).or_else(|error| {
333                if let Some(crate::AnalyticSurface::Sphere { frame, radius }) = surface.analytic() {
334                    let own = outward_normal(face, uv).map(|n| if face.same_sense { n } else { n.scale(-1.0) });
335                    let away = own.is_some_and(|n| n.dot(foot.point.sub(frame.origin)) > 0.0);
336                    let k = if away { -1.0 / radius } else { 1.0 / radius };
337                    return Ok::<(f64, f64), String>((k, k));
338                }
339                let _ = error;
340                pole_normal(surface, uv).ok_or_else(|| "a degenerate point with no tangent plane".to_string())?;
341                let ([u0, u1], [v0, v1]) = (surface.domain_u()?, surface.domain_v()?);
342                let inward = |at: f64, low: f64, high: f64| at + (0.5 * (low + high) - at) * 1e-6;
343                surface.principal_curvatures(inward(uv[0], u0, u1), inward(uv[1], v0, v1))
344            });
345            let Ok((kappa_min, kappa_max)) = curvatures else { return Ok(None) };
346            // The surface's curvatures are signed against its own normal (an
347            // outward-facing cylinder reads -1/r); the protocol's are positive
348            // where the boundary bends away from its OUTWARD normal.
349            let sign = if face.same_sense { -1.0 } else { 1.0 };
350            let (a, b) = (sign * kappa_min, sign * kappa_max);
351            Ok(Some([a.max(b), a.min(b)]))
352        })
353        .collect()
354}
355
356/// Samples per knot span along an edge from which its extremes along each
357/// axis are sought, and at most this many along the whole edge.
358const BOX_EDGE_SAMPLES_PER_SPAN: usize = 8;
359const BOX_EDGE_SAMPLES_MAX: usize = 256;
360/// Samples per knot span each way over a face's trim box, at most this many
361/// each way and at least the least (a small trim on a large surface).
362const BOX_FACE_SAMPLES_PER_SPAN: usize = 4;
363const BOX_FACE_SAMPLES_MAX: usize = 48;
364const BOX_FACE_SAMPLES_LEAST: usize = 8;
365
366/// Parameters from `low` to `high`: the knots between them and `per` steps
367/// across each knot span; fewer steps per span when that would pass `cap`,
368/// but never fewer than one, so that every knot stays a sample (a feature of
369/// the spline lies across its knots); `least` even steps when there would be
370/// fewer.
371fn span_samples(knots: &[f64], low: f64, high: f64, per: usize, cap: usize, least: usize) -> Vec<f64> {
372    let mut breaks = vec![low];
373    for &knot in knots {
374        if knot > low && knot < high && knot > *breaks.last().unwrap() {
375            breaks.push(knot);
376        }
377    }
378    breaks.push(high);
379    let spans = breaks.len() - 1;
380    if spans * per < least {
381        return (0..=least).map(|i| low + (high - low) * i as f64 / least as f64).collect();
382    }
383    let per = if spans * per > cap { (cap / spans).max(1) } else { per };
384    let mut samples = Vec::with_capacity((breaks.len() - 1) * per + 1);
385    for pair in breaks.windows(2) {
386        for i in 0..per {
387            samples.push(pair[0] + (pair[1] - pair[0]) * i as f64 / per as f64);
388        }
389    }
390    samples.push(high);
391    samples
392}
393
394/// The low and high corners of a box growing round the points it is given.
395struct GrowingBox(Option<[Vec3; 2]>);
396
397impl GrowingBox {
398    fn take(&mut self, point: Vec3) {
399        if !(point.x.is_finite() && point.y.is_finite() && point.z.is_finite()) {
400            return;
401        }
402        let [low, high] = self.0.get_or_insert([point, point]);
403        *low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
404        *high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
405    }
406}
407
408fn axis_of(point: Vec3, axis: usize) -> f64 {
409    [point.x, point.y, point.z][axis]
410}
411
412/// The parameter in `[a, b]` where `f` is greatest, `f` having one peak
413/// there: golden-section search down to the parameter's own precision.
414fn golden_peak(f: impl Fn(f64) -> f64, mut a: f64, mut b: f64) -> f64 {
415    const RATIO: f64 = 0.618_033_988_749_894_9;
416    let mut c = b - RATIO * (b - a);
417    let mut d = a + RATIO * (b - a);
418    let (mut fc, mut fd) = (f(c), f(d));
419    for _ in 0..200 {
420        if (b - a).abs() <= 4.0 * f64::EPSILON * (a.abs() + b.abs()).max(f64::MIN_POSITIVE) {
421            break;
422        }
423        if fc >= fd {
424            (b, d, fd) = (d, c, fc);
425            c = b - RATIO * (b - a);
426            fc = f(c);
427        } else {
428            (a, c, fc) = (c, d, fd);
429            d = a + RATIO * (b - a);
430            fd = f(d);
431        }
432    }
433    if fc >= fd { c } else { d }
434}
435
436/// The edge's points where a coordinate is greatest or least along it: its
437/// samples, and each sampled peak of `±x`, `±y`, `±z` sharpened by
438/// golden-section search between the samples beside it (an end's peak
439/// between the end and its neighbour, which may lie inside the edge).
440fn edge_extremes(edge: &crate::topology::EdgeRecord, into: &mut GrowingBox) {
441    let curve = &edge.curve;
442    let (low, high) = (edge.t0.min(edge.t1), edge.t0.max(edge.t1));
443    let ts = span_samples(&curve.knots, low, high, BOX_EDGE_SAMPLES_PER_SPAN, BOX_EDGE_SAMPLES_MAX, BOX_EDGE_SAMPLES_PER_SPAN);
444    let points: Vec<Option<Vec3>> = ts.iter().map(|&t| curve.evaluate(t).ok()).collect();
445    points.iter().flatten().for_each(|&p| into.take(p));
446    for axis in 0..3 {
447        for sign in [1.0, -1.0] {
448            let value = |i: usize| points[i].map(|p| sign * axis_of(p, axis));
449            let last = ts.len().saturating_sub(1);
450            for i in 0..ts.len() {
451                let (before, after) = (i.saturating_sub(1), (i + 1).min(last));
452                let (Some(here), Some(b), Some(a)) = (value(i), value(before), value(after)) else { continue };
453                if here >= b && here >= a && before < after {
454                    let f = |t: f64| curve.evaluate(t).map_or(f64::NEG_INFINITY, |p| sign * axis_of(p, axis));
455                    let t = golden_peak(f, ts[before], ts[after]);
456                    if let Ok(p) = curve.evaluate(t) {
457                        into.take(p);
458                    }
459                }
460            }
461        }
462    }
463}
464
465/// From `seed`, the point of the surface where `sign` times coordinate `axis`
466/// is greatest near it: damped Newton ascent on the coordinate over the
467/// parameters, kept inside the domain. A ridge (a line of equal peaks, as
468/// along a cylinder's side) has a flat direction, which the damping steps over.
469fn surface_peak(surface: &crate::NurbsSurface, seed: [f64; 2], axis: usize, sign: f64, domain: [[f64; 2]; 2]) -> Option<[f64; 2]> {
470    let clamp = |uv: [f64; 2]| [uv[0].clamp(domain[0][0], domain[0][1]), uv[1].clamp(domain[1][0], domain[1][1])];
471    let value = |uv: [f64; 2]| surface.evaluate(uv[0], uv[1]).ok().map(|p| sign * axis_of(p, axis));
472    let mut uv = seed;
473    let mut here = value(uv)?;
474    let span = (domain[0][1] - domain[0][0]).abs().max((domain[1][1] - domain[1][0]).abs());
475    for _ in 0..60 {
476        let d = surface.derivatives(uv[0], uv[1], 2).ok()?;
477        let g = [sign * axis_of(d[1][0], axis), sign * axis_of(d[0][1], axis)];
478        let h = [[sign * axis_of(d[2][0], axis), sign * axis_of(d[1][1], axis)], [sign * axis_of(d[1][1], axis), sign * axis_of(d[0][2], axis)]];
479        let scale = g[0].abs().max(g[1].abs()).max(h[0][0].abs()).max(h[1][1].abs()).max(h[0][1].abs());
480        // Relative tests only: the parameters' own scale is arbitrary.
481        if scale == 0.0 || g[0].abs().max(g[1].abs()) <= 1e-15 * scale {
482            break;
483        }
484        // The Hessian shifted down until it is negative definite, so the step
485        // climbs: its largest eigenvalue, plus a sliver of the scale.
486        let mean = 0.5 * (h[0][0] + h[1][1]);
487        let largest = mean + (0.25 * (h[0][0] - h[1][1]).powi(2) + h[0][1].powi(2)).sqrt();
488        let mut shift = largest.max(0.0) + 1e-9 * scale;
489        let mut moved = false;
490        for _ in 0..40 {
491            let a = [[h[0][0] - shift, h[0][1]], [h[0][1], h[1][1] - shift]];
492            let det = a[0][0] * a[1][1] - a[0][1] * a[1][0];
493            if det == 0.0 || !det.is_finite() {
494                shift = shift * 4.0 + scale;
495                continue;
496            }
497            let step = [-(a[1][1] * g[0] - a[0][1] * g[1]) / det, -(a[0][0] * g[1] - a[1][0] * g[0]) / det];
498            let next = clamp([uv[0] + step[0], uv[1] + step[1]]);
499            match value(next) {
500                Some(there) if there >= here => {
501                    let small = (next[0] - uv[0]).abs().max((next[1] - uv[1]).abs()) <= 1e-15 * span;
502                    uv = next;
503                    here = there;
504                    moved = !small;
505                    break;
506                }
507                _ => shift = shift * 4.0 + scale,
508            }
509        }
510        if !moved {
511            break;
512        }
513    }
514    Some(uv)
515}
516
517/// The box in a face's parameters holding its trim: the control points of its
518/// loops' pcurves (a pcurve lies in their hull), within the surface's domain;
519/// the whole domain where the face has no loops or they fall outside it.
520fn trim_box(face: &FaceRecord, du: [f64; 2], dv: [f64; 2]) -> ([f64; 2], [f64; 2]) {
521    let mut bounds: Option<[f64; 4]> = None;
522    for coedge in face.loops.iter().flat_map(|l| &l.coedges) {
523        for c in &coedge.pcurve.control_points {
524            if c.w == 0.0 {
525                continue;
526            }
527            let (u, v) = (c.x / c.w, c.y / c.w);
528            let b = bounds.get_or_insert([u, u, v, v]);
529            *b = [b[0].min(u), b[1].max(u), b[2].min(v), b[3].max(v)];
530        }
531    }
532    match bounds {
533        Some([u0, u1, v0, v1]) => {
534            let u = [u0.max(du[0]), u1.min(du[1])];
535            let v = [v0.max(dv[0]), v1.min(dv[1])];
536            if u[0] < u[1] && v[0] < v[1] { (u, v) } else { (du, dv) }
537        }
538        None => (du, dv),
539    }
540}
541
542/// The face's points where a coordinate is greatest or least on its trimmed
543/// region away from its edges: a grid over its trim's box ([`trim_box`]), each grid
544/// point inside the trim that is a peak of `±x`, `±y`, `±z` among its grid
545/// neighbours climbed to the surface's peak ([`surface_peak`]), kept when the
546/// peak lies inside the trim (its band of `tolerance` included). A peak the
547/// climb takes outside the trim lies, on the trimmed face, on its boundary,
548/// which the edges answer.
549fn face_extremes(face: &FaceRecord, tolerance: f64, into: &mut GrowingBox) -> Result<(), KernelRefusal> {
550    let surface = &face.surface;
551    let (Ok(du), Ok(dv)) = (surface.domain_u(), surface.domain_v()) else { return Ok(()) };
552    let (bu, bv) = trim_box(face, du, dv);
553    let us = span_samples(&surface.knots_u, bu[0], bu[1], BOX_FACE_SAMPLES_PER_SPAN, BOX_FACE_SAMPLES_MAX, BOX_FACE_SAMPLES_LEAST);
554    let vs = span_samples(&surface.knots_v, bv[0], bv[1], BOX_FACE_SAMPLES_PER_SPAN, BOX_FACE_SAMPLES_MAX, BOX_FACE_SAMPLES_LEAST);
555    let mut grid: Vec<Vec<Option<Vec3>>> = vec![vec![None; vs.len()]; us.len()];
556    for (i, &u) in us.iter().enumerate() {
557        for (j, &v) in vs.iter().enumerate() {
558            if trim_class(face, [u, v], tolerance)? != PolygonClass::Outside {
559                grid[i][j] = surface.evaluate(u, v).ok();
560            }
561        }
562    }
563    grid.iter().flatten().flatten().for_each(|&p| into.take(p));
564    for axis in 0..3 {
565        for sign in [1.0, -1.0] {
566            for i in 0..us.len() {
567                for j in 0..vs.len() {
568                    let Some(here) = grid[i][j].map(|p| sign * axis_of(p, axis)) else { continue };
569                    let mut peak = true;
570                    'neighbours: for a in i.saturating_sub(1)..(i + 2).min(us.len()) {
571                        for b in j.saturating_sub(1)..(j + 2).min(vs.len()) {
572                            if let Some(there) = grid[a][b] {
573                                if sign * axis_of(there, axis) > here {
574                                    peak = false;
575                                    break 'neighbours;
576                                }
577                            }
578                        }
579                    }
580                    if !peak {
581                        continue;
582                    }
583                    let Some(uv) = surface_peak(surface, [us[i], vs[j]], axis, sign, [du, dv]) else { continue };
584                    if trim_class(face, uv, tolerance)? != PolygonClass::Outside {
585                        if let Ok(p) = surface.evaluate(uv[0], uv[1]) {
586                            into.take(p);
587                        }
588                    }
589                }
590            }
591        }
592    }
593    Ok(())
594}
595
596/// The least box with sides square to the axes that holds the solid, as its
597/// low and high corners, on its exact geometry (not its control nets): the
598/// box round its vertices, the points along each edge where a coordinate is
599/// greatest or least, and the points inside each face's trim where one is (a
600/// ball's or a ring's side). `tolerance` (mm) is the band a face's point may
601/// stand past its trim and still count as on the face.
602pub fn solid_least_box(solid: &BrepSolid, tolerance: f64) -> Result<[Vec3; 2], KernelRefusal> {
603    let mut boxed = GrowingBox(None);
604    solid.vertices.iter().for_each(|vertex| boxed.take(vertex.point));
605    for edge in solid.edges.iter().filter(|edge| !edge.degenerate) {
606        edge_extremes(edge, &mut boxed);
607    }
608    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
609        face_extremes(face, tolerance, &mut boxed)?;
610    }
611    boxed.0.ok_or_else(|| refusal("least_box_empty", "the solid has no boundary".into()))
612}
613
614/// The distance from `point` to the boundary of `solid`, and the unit vector
615/// from its foot to the point (`None` where the point lies on it).
616fn boundary_distance(solid: &BrepSolid, point: Vec3, tolerance: f64) -> Result<Option<(f64, Option<Vec3>)>, KernelRefusal> {
617    Ok(nearest_boundary_point(solid, point, tolerance)?.map(|foot| {
618        let away = point.sub(foot.point);
619        let length = away.length();
620        (foot.distance, (length > 0.0).then(|| away.scale(1.0 / length)))
621    }))
622}
623
624/// The parameter in `[a, b]` where `f` is least, `f` having one dip there.
625fn golden_dip(f: impl Fn(f64) -> f64, a: f64, b: f64) -> f64 {
626    golden_peak(|t| -f(t), a, b)
627}
628
629/// From `seed`, the point of `face` nearest `other` near it: Newton on the
630/// distance over the face's parameters, its gradient `(S_u·n, S_v·n)` from the
631/// unit vector `n` the other's foot points along (the distance to a set
632/// changes along `n` alone), its Hessian by differences of that gradient,
633/// damped so each step goes downhill and kept inside the domain. It stops
634/// where the gradient across the whole domain changes the distance by no more
635/// than `flat`, the round-off of the distances themselves.
636fn surface_dip(face: &FaceRecord, other: &BrepSolid, seed: [f64; 2], domain: [[f64; 2]; 2], tolerance: f64, flat: f64) -> Result<Option<[f64; 2]>, KernelRefusal> {
637    let surface = &face.surface;
638    let clamp = |uv: [f64; 2]| [uv[0].clamp(domain[0][0], domain[0][1]), uv[1].clamp(domain[1][0], domain[1][1])];
639    let span = (domain[0][1] - domain[0][0]).abs().max((domain[1][1] - domain[1][0]).abs());
640    let at = |uv: [f64; 2]| -> Result<Option<(f64, [f64; 2])>, KernelRefusal> {
641        let Ok((p, su, sv)) = surface.deriv1(uv[0], uv[1]) else { return Ok(None) };
642        Ok(boundary_distance(other, p, tolerance)?.map(|(d, n)| (d, n.map_or([0.0, 0.0], |n| [su.dot(n), sv.dot(n)]))))
643    };
644    let mut uv = seed;
645    let Some((mut here, mut g)) = at(uv)? else { return Ok(None) };
646    let h = 1e-6 * span;
647    for _ in 0..40 {
648        if here == 0.0 || g[0].hypot(g[1]) * span <= flat || h == 0.0 {
649            break;
650        }
651        // The gradient's differences, one each way, for the Hessian.
652        let (Some((_, gu)), Some((_, gv))) = (at(clamp([uv[0] + h, uv[1]]))?, at(clamp([uv[0], uv[1] + h]))?) else { break };
653        let (du, dv) = (clamp([uv[0] + h, uv[1]])[0] - uv[0], clamp([uv[0], uv[1] + h])[1] - uv[1]);
654        if du == 0.0 || dv == 0.0 {
655            break;
656        }
657        let hxx = (gu[0] - g[0]) / du;
658        let hyy = (gv[1] - g[1]) / dv;
659        let hxy = 0.5 * ((gu[1] - g[1]) / du + (gv[0] - g[0]) / dv);
660        let scale = hxx.abs().max(hyy.abs()).max(hxy.abs()).max(g[0].abs()).max(g[1].abs());
661        let mean = 0.5 * (hxx + hyy);
662        let least = mean - (0.25 * (hxx - hyy).powi(2) + hxy * hxy).sqrt();
663        // Shifted up until positive definite, so the step goes down.
664        let mut shift = (-least).max(0.0) + 1e-9 * scale;
665        let mut moved = false;
666        for _ in 0..40 {
667            let a = [[hxx + shift, hxy], [hxy, hyy + shift]];
668            let det = a[0][0] * a[1][1] - a[0][1] * a[1][0];
669            if det == 0.0 || !det.is_finite() {
670                shift = shift * 4.0 + scale;
671                continue;
672            }
673            let step = [-(a[1][1] * g[0] - a[0][1] * g[1]) / det, -(a[0][0] * g[1] - a[1][0] * g[0]) / det];
674            let next = clamp([uv[0] + step[0], uv[1] + step[1]]);
675            match at(next)? {
676                Some((there, gn)) if there <= here => {
677                    let small = (next[0] - uv[0]).abs().max((next[1] - uv[1]).abs()) <= 1e-15 * span;
678                    (uv, here, g) = (next, there, gn);
679                    moved = !small;
680                    break;
681                }
682                _ => shift = shift * 4.0 + scale,
683            }
684        }
685        if !moved {
686            break;
687        }
688    }
689    Ok(Some(uv))
690}
691
692/// The least distance between the boundaries of `a` and `b` (0 where they
693/// touch or cross), on their exact geometry: the lesser of the searches from
694/// each side ([`gap_from`]), once one reads more than round-off. `tolerance`
695/// (mm) is the trim band.
696pub fn solid_gap(a: &BrepSolid, b: &BrepSolid, tolerance: f64) -> Result<f64, KernelRefusal> {
697    let flat = 1e-11 * crate::solid_scale(a).max(crate::solid_scale(b));
698    let there = gap_from(a, b, tolerance, flat)?;
699    if there <= flat {
700        return Ok(there);
701    }
702    Ok(there.min(gap_from(b, a, tolerance, flat)?))
703}
704
705/// The least, over the points of `a`'s boundary, of the distance to `b`'s
706/// ([`nearest_boundary_point`]), sought at `a`'s vertices, along its edges
707/// (sampled per knot span, each dip sharpened by golden-section search) and
708/// inside its faces' trims (grid seeds, each dip refined by Newton, kept
709/// inside the trim); `b`'s vertices are read against `a` as well. A sample
710/// whose neighbours all lie within `flat` of it sits on a level stretch
711/// (faces or edges parallel to the other's), which it already reads; only a
712/// dip below its neighbours is sharpened, and a feature of `b` between such
713/// samples is the search from `b`'s side.
714fn gap_from(a: &BrepSolid, b: &BrepSolid, tolerance: f64, flat: f64) -> Result<f64, KernelRefusal> {
715    let mut least = f64::INFINITY;
716    let take = |least: &mut f64, d: Option<(f64, Option<Vec3>)>| {
717        if let Some((d, _)) = d {
718            *least = least.min(d);
719        }
720    };
721    for vertex in &a.vertices {
722        take(&mut least, boundary_distance(b, vertex.point, tolerance)?);
723    }
724    for vertex in &b.vertices {
725        take(&mut least, boundary_distance(a, vertex.point, tolerance)?);
726    }
727    for edge in a.edges.iter().filter(|edge| !edge.degenerate) {
728        if least <= flat {
729            return Ok(least);
730        }
731        let curve = &edge.curve;
732        let (low, high) = (edge.t0.min(edge.t1), edge.t0.max(edge.t1));
733        let ts = span_samples(&curve.knots, low, high, BOX_EDGE_SAMPLES_PER_SPAN, BOX_EDGE_SAMPLES_MAX, BOX_EDGE_SAMPLES_PER_SPAN);
734        let mut values = Vec::with_capacity(ts.len());
735        for &t in &ts {
736            let d = match curve.evaluate(t) {
737                Ok(p) => boundary_distance(b, p, tolerance)?.map(|(d, _)| d),
738                Err(_) => None,
739            };
740            values.push(d);
741        }
742        values.iter().flatten().for_each(|&d| least = least.min(d));
743        let last = ts.len().saturating_sub(1);
744        for i in 0..ts.len() {
745            let (before, after) = (i.saturating_sub(1), (i + 1).min(last));
746            let (Some(here), Some(x), Some(y)) = (values[i], values[before], values[after]) else { continue };
747            if here <= x && here <= y && before < after && here > 0.0 && x.max(y) - here > flat {
748                let f = |t: f64| match curve.evaluate(t) {
749                    Ok(p) => nearest_boundary_point(b, p, tolerance).ok().flatten().map_or(f64::INFINITY, |foot| foot.distance),
750                    Err(_) => f64::INFINITY,
751                };
752                let t = golden_dip(f, ts[before], ts[after]);
753                least = least.min(f(t));
754            }
755        }
756    }
757    for face in a.shells.iter().flat_map(|shell| &shell.faces) {
758        if least <= flat {
759            return Ok(least);
760        }
761        let surface = &face.surface;
762        let (Ok(du), Ok(dv)) = (surface.domain_u(), surface.domain_v()) else { continue };
763        let (bu, bv) = trim_box(face, du, dv);
764        let us = span_samples(&surface.knots_u, bu[0], bu[1], BOX_FACE_SAMPLES_PER_SPAN, BOX_FACE_SAMPLES_MAX, BOX_FACE_SAMPLES_LEAST);
765        let vs = span_samples(&surface.knots_v, bv[0], bv[1], BOX_FACE_SAMPLES_PER_SPAN, BOX_FACE_SAMPLES_MAX, BOX_FACE_SAMPLES_LEAST);
766        let mut grid: Vec<Vec<Option<f64>>> = vec![vec![None; vs.len()]; us.len()];
767        for (i, &u) in us.iter().enumerate() {
768            for (j, &v) in vs.iter().enumerate() {
769                if trim_class(face, [u, v], tolerance)? == PolygonClass::Outside {
770                    continue;
771                }
772                if let Ok(p) = surface.evaluate(u, v) {
773                    grid[i][j] = boundary_distance(b, p, tolerance)?.map(|(d, _)| d);
774                }
775            }
776        }
777        grid.iter().flatten().flatten().for_each(|&d| least = least.min(d));
778        for i in 0..us.len() {
779            for j in 0..vs.len() {
780                let Some(here) = grid[i][j] else { continue };
781                if here == 0.0 {
782                    continue;
783                }
784                let around: Vec<f64> = (i.saturating_sub(1)..(i + 2).min(us.len()))
785                    .flat_map(|x| (j.saturating_sub(1)..(j + 2).min(vs.len())).map(move |y| (x, y)))
786                    .filter_map(|(x, y)| grid[x][y])
787                    .collect();
788                let dip = around.iter().all(|&there| there >= here) && around.iter().any(|&there| there - here > flat);
789                if !dip {
790                    continue;
791                }
792                let Some(uv) = surface_dip(face, b, [us[i], vs[j]], [du, dv], tolerance, flat)? else { continue };
793                if trim_class(face, uv, tolerance)? == PolygonClass::Outside {
794                    continue;
795                }
796                if let Ok(p) = surface.evaluate(uv[0], uv[1]) {
797                    take(&mut least, boundary_distance(b, p, tolerance)?);
798                }
799            }
800        }
801    }
802    if least.is_finite() { Ok(least) } else { Err(refusal("gap_empty", "a solid has no boundary".into())) }
803}