Skip to main content

brep_kernel/feature_pipeline/
ports_contact.rs

1//! A connection point's CONTACT BODY: a pin that is a whole solid of the part
2//! (an XLR pin, a barrel jack's centre pin or sleeve, a JST crimp, a square
3//! header post, a spade blade, a pin bent along a curve), which a face pick
4//! cannot express ("A contact body").
5//!
6//! The body is one more SEAT source, below the explicit references: it
7//! supplies the origin when `pointRef` does not, and the direction when
8//! neither `directionRef` nor `pointRef` does. What it supplies is its two
9//! ENDS, each with the direction a wire leaves along there, found by the
10//! first rule that applies:
11//!
12//! * the AXIS rule: the body's axis-bearing analytic faces (cylinder, cone,
13//!   torus, general revolution) grouped by collinear axis, and exactly one
14//!   group. The ends are the axis points at the extremes of the body's extent
15//!   along it (its edges, and a sphere face centred on the axis, so a rounded
16//!   tip ends at its pole); the wire leaves along the axis, out of the body;
17//! * the END-CAP rule, for a body with no single axis (a square post, a
18//!   blade, a pin swept along a curve, a pin with a cross hole): its TERMINAL
19//!   faces are the planar faces the whole body lies behind, and the tip of a
20//!   rounded or pointed end (a sphere's pole, or the axis point at the end of
21//!   a fillet's torus or a cone). A flat end opposite a tip is read on the
22//!   tip's axis line, so a scooped solder cup's off-centre half-ring still
23//!   attaches on the pin's axis. The
24//!   two ends are the pair of terminal faces farthest apart, when no other
25//!   pair comes close (a cube has three such pairs and no distinct ends). A
26//!   body whose only planar faces are two caps (a pin swept round a bend of
27//!   more than a right angle) takes those two, unless both lie at one end (a
28//!   cup's floor behind its rim). A wire attaches at a cap's
29//!   centroid and leaves along its outward normal, which for a swept pin is
30//!   the path's end tangent; on a straight round pin the two rules agree;
31//! * the DIRECTION rule, for a body with no distinct ends (a cube, a block
32//!   terminal) when the point names a Direction (`directionRef`: a face's
33//!   normal, an edge, an axis, a datum): the end is the body's extreme along
34//!   that direction (the centroid of a face normal to it, else the middle of
35//!   the extreme points) and the wire leaves along it. With no Direction such
36//!   a body is refused by name, and the message says to pick one.
37//!
38//! The WIRE END is the end farther from the centre of the rest of the part,
39//! or the `+axis` end (the chord between the ends in its canonical sense:
40//! largest component positive) when the body is the only solid or the two
41//! are equally far; under the direction rule it is the end the Direction
42//! points to. `reverseDirection` takes the other one. The wire leaves OUTWARD
43//! from the chosen end.
44//!
45//! [`contact_body_solid`] and [`contact_body_end`] are public so the board's
46//! pad check finds the same solid and the same end the router does.
47
48use serde::{Deserialize, Serialize};
49
50use super::{SceneMap, SelectionGeometry, Vec3};
51
52/// Samples per edge for the axial extent. The extremes of a cylinder, cone or
53/// planar face along the axis lie on its boundary, so the edges carry them; a
54/// circle's axial coordinate is constant, so any sample is exact for it.
55const EDGE_SAMPLES: usize = 16;
56/// Grid samples per direction over a sphere face's surface: a rounded tip's
57/// pole is at a domain boundary, which the grid includes exactly.
58const SPHERE_SAMPLES: usize = 16;
59/// Directions closer than this (|d1 x d2|) are parallel.
60const PARALLEL: f64 = 1e-6;
61/// A terminal face lies within this of the body's extreme along its normal,
62/// scaled by the body's size (edge samples are chords of curved edges).
63const TERMINAL_TOLERANCE: f64 = 1e-4;
64/// Two pairs of terminal faces whose distances are within this ratio are a
65/// tie: the body has no distinct ends.
66const DISTINCT_ENDS: f64 = 0.85;
67/// Lengths below this, scaled by the body's size, are the same point.
68const RELATIVE_TOLERANCE: f64 = 1e-6;
69
70/// Which rule found a contact body's ends (see the module docs).
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72pub enum ContactRule {
73    /// The body's one axis.
74    Axis,
75    /// Its two terminal faces.
76    Caps,
77    /// The point's Direction, on a body with no distinct ends.
78    Direction,
79}
80
81impl ContactRule {
82    /// The word the report shows.
83    pub fn as_str(self) -> &'static str {
84        match self {
85            ContactRule::Axis => "axis",
86            ContactRule::Caps => "caps",
87            ContactRule::Direction => "direction",
88        }
89    }
90}
91
92/// What a contact body derives: its two ends, the direction a wire leaves
93/// along at each, and the end a wire leaves from.
94#[derive(Debug, Clone, Copy)]
95pub struct ContactAxis {
96    /// The axis direction in its canonical sense (largest component
97    /// positive): the body's axis, or under the cap rule the chord from the
98    /// `-axis` end to the `+axis` end, or the Direction.
99    pub axis: Vec3,
100    /// The `+axis` end.
101    pub plus_end: Vec3,
102    /// The `-axis` end.
103    pub minus_end: Vec3,
104    /// The direction a wire leaves along at the `+axis` end (out of the body).
105    pub plus_outward: Vec3,
106    /// The direction a wire leaves along at the `-axis` end.
107    pub minus_outward: Vec3,
108    /// Whether the wire leaves from the `+axis` end.
109    pub wire_at_plus: bool,
110    /// The rule that found the ends.
111    pub rule: ContactRule,
112}
113
114impl ContactAxis {
115    /// The end a wire attaches at.
116    pub fn wire_end(&self) -> Vec3 {
117        if self.wire_at_plus {
118            self.plus_end
119        } else {
120            self.minus_end
121        }
122    }
123
124    /// The other end (the mating end, on a pin whose wire side is right).
125    pub fn other_end(&self) -> Vec3 {
126        if self.wire_at_plus {
127            self.minus_end
128        } else {
129            self.plus_end
130        }
131    }
132
133    /// The direction a wire leaves along: OUT of the body at the wire end.
134    pub fn outward(&self) -> Vec3 {
135        if self.wire_at_plus {
136            self.plus_outward
137        } else {
138            self.minus_outward
139        }
140    }
141}
142
143/// The contact body as the tail's report shows it, so a wrong default end is
144/// visible next to the one-click flip (`reverseDirection`).
145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
146#[serde(rename_all = "camelCase")]
147pub struct PortContactRow {
148    /// The solid named by `contactBody`.
149    pub body: String,
150    /// `"+axis"` or `"-axis"`: which end the wire took, in the axis's
151    /// canonical sense.
152    pub end: String,
153    /// The canonical axis direction.
154    pub axis: [f64; 3],
155    /// Where the wire attaches.
156    pub wire_end: [f64; 3],
157    /// The other end.
158    pub other_end: [f64; 3],
159    /// Whether the body SEATED the origin (no `pointRef`). With a `pointRef`
160    /// the body is reported, but the origin is the reference's.
161    pub seats_origin: bool,
162    /// `"axis"`, `"caps"` or `"direction"`: the rule that found the ends.
163    #[serde(default)]
164    pub rule: String,
165}
166
167/// The resident solid a contact body names, by the same lookup every seat
168/// reference uses ([`SceneMap::resolve_solid`]): its handle, or `None` when
169/// the scene holds no solid of that name.
170pub fn contact_body_solid(scene: &SceneMap, name: &str) -> Option<u32> {
171    let name = name.trim();
172    if name.is_empty() {
173        return None;
174    }
175    scene.resolve_solid(name)
176}
177
178/// The ends and the wire end of the contact body `name`, by the axis or the
179/// end-cap rule. `reverse` (a point's `reverseDirection`) takes the other end.
180/// A body with no distinct ends is refused; [`contact_body_end`] takes a
181/// Direction for it.
182pub fn contact_body_axis(scene: &SceneMap, name: &str, reverse: bool) -> Result<ContactAxis, String> {
183    contact_body_end(scene, name, reverse, None)
184}
185
186/// The ends and the wire end of the contact body `name`. `reverse` (a point's
187/// `reverseDirection`) takes the other end; `direction` (the point's resolved
188/// `directionRef`) picks the end of a body that has no distinct ends.
189///
190/// `Err` names why nothing is derived: no such solid, a body with no length,
191/// or one with no distinct ends and no Direction to pick one by.
192pub fn contact_body_end(
193    scene: &SceneMap,
194    name: &str,
195    reverse: bool,
196    direction: Option<Vec3>,
197) -> Result<ContactAxis, String> {
198    let name = name.trim();
199    let handle = contact_body_solid(scene, name)
200        .ok_or_else(|| format!("contact body '{name}' is not a solid of this part"))?;
201    let (ends, scale) = crate::with_registered_solid_str(handle, |solid| body_ends(solid, name, direction))?;
202    let mut wire_at_plus = match ends.toward {
203        // The direction rule: the end the Direction points to.
204        Some(toward) => toward,
205        // Otherwise the end farther from the rest of the part.
206        None => {
207            let mut plus_side = true;
208            if let Some(centre) = rest_of_part_centre(scene, handle) {
209                let plus = ends.plus_end.sub(centre).length();
210                let minus = ends.minus_end.sub(centre).length();
211                if (plus - minus).abs() > RELATIVE_TOLERANCE * scale {
212                    plus_side = plus > minus;
213                }
214            }
215            plus_side
216        }
217    };
218    if reverse {
219        wire_at_plus = !wire_at_plus;
220    }
221    Ok(ContactAxis {
222        axis: ends.axis,
223        plus_end: ends.plus_end,
224        minus_end: ends.minus_end,
225        plus_outward: ends.plus_outward,
226        minus_outward: ends.minus_outward,
227        wire_at_plus,
228        rule: ends.rule,
229    })
230}
231
232/// A body's two ends before the wire side is chosen.
233struct Ends {
234    axis: Vec3,
235    plus_end: Vec3,
236    minus_end: Vec3,
237    plus_outward: Vec3,
238    minus_outward: Vec3,
239    rule: ContactRule,
240    /// Under the direction rule, whether the Direction points to the `+axis`
241    /// end; `None` leaves the side to the rest of the part.
242    toward: Option<bool>,
243}
244
245/// The body's ends by the first rule that applies, and its size scale.
246fn body_ends(solid: &crate::BrepSolid, name: &str, direction: Option<Vec3>) -> Result<(Ends, f64), String> {
247    let scale = solid_scale(solid);
248    let points = body_points(solid);
249    if points.is_empty() {
250        return Err(format!("contact body '{name}' has no geometry to measure"));
251    }
252    let tolerance = RELATIVE_TOLERANCE * scale;
253
254    // Every axis-bearing face's axis, grouped by collinearity; planar faces
255    // and sphere faces for the end caps.
256    let mut groups: Vec<(Vec3, Vec3)> = Vec::new();
257    let mut spheres: Vec<(&crate::FaceRecord, Vec3, f64)> = Vec::new();
258    let mut planes: Vec<(&crate::FaceRecord, Vec3)> = Vec::new();
259    // Round faces that are not cylinders (a fillet's torus, a cone, a general
260    // revolution): a rounded or pointed tip, with its axis.
261    let mut round_tips: Vec<(&crate::FaceRecord, Vec3, Vec3)> = Vec::new();
262    for shell in &solid.shells {
263        for face in &shell.faces {
264            match crate::resolve_face_selection(solid, face.id) {
265                Ok(SelectionGeometry::Axis { origin, direction, radius }) => {
266                    let Ok(direction) = direction.normalized() else { continue };
267                    let direction = canonical(direction);
268                    if radius.is_none() {
269                        round_tips.push((face, origin, direction));
270                    }
271                    let known = groups
272                        .iter()
273                        .any(|(o, d)| collinear(*o, *d, origin, direction, tolerance));
274                    if !known {
275                        groups.push((origin, direction));
276                    }
277                }
278                Ok(SelectionGeometry::Sphere { center, radius }) => spheres.push((face, center, radius)),
279                Ok(SelectionGeometry::Plane { normal, .. }) => {
280                    if let Ok(normal) = normal.normalized() {
281                        planes.push((face, normal));
282                    }
283                }
284                _ => {}
285            }
286        }
287    }
288
289    if let [(origin, axis)] = groups.as_slice() {
290        let (origin, axis) = (*origin, *axis);
291        let (low, high) = axial_extent(&points, &spheres, origin, axis, tolerance);
292        if high - low <= RELATIVE_TOLERANCE * scale {
293            return Err(format!("contact body '{name}' has no length along its axis"));
294        }
295        let ends = Ends {
296            axis,
297            plus_end: origin.add(axis.scale(high)),
298            minus_end: origin.add(axis.scale(low)),
299            plus_outward: axis,
300            minus_outward: axis.scale(-1.0),
301            rule: ContactRule::Axis,
302            toward: None,
303        };
304        return Ok((ends, scale));
305    }
306
307    // The end caps: planar faces the whole body lies behind, and the tips of
308    // rounded or pointed ends. A tip carries its axis line, so the end at the
309    // other side can be read on the same line.
310    let slack = TERMINAL_TOLERANCE * scale;
311    let behind = |centre: Vec3, outward: Vec3| points.iter().all(|p| p.sub(centre).dot(outward) <= slack);
312    let body_centre = bbox_centre(&points);
313    let mut caps: Vec<Cap> = Vec::new();
314    for (face, normal) in &planes {
315        if let Some(centre) = boundary_centroid(solid, face) {
316            if behind(centre, *normal) {
317                caps.push(Cap { point: centre, outward: *normal, line: None });
318            }
319        }
320    }
321    for (face, center, _) in &spheres {
322        if let Some(pole) = sphere_tip(face, body_centre) {
323            if let Ok(outward) = pole.sub(*center).normalized() {
324                if behind(pole, outward) {
325                    caps.push(Cap { point: pole, outward, line: Some((*center, outward)) });
326                }
327            }
328        }
329    }
330    for (face, origin, axis) in &round_tips {
331        if let Some(tip) = axial_tip(face, *origin, *axis, body_centre) {
332            if behind(tip.point, tip.outward) {
333                caps.push(tip);
334            }
335        }
336    }
337    // One end found twice (a partly filleted tip: its torus's top and the
338    // flat disc left inside it are the same point) is one end.
339    let mut ends: Vec<Cap> = Vec::new();
340    for cap in caps {
341        match ends.iter_mut().find(|end| end.point.sub(cap.point).length() <= slack) {
342            Some(end) => {
343                if end.line.is_none() {
344                    end.line = cap.line;
345                }
346            }
347            None => ends.push(cap),
348        }
349    }
350    if ends.len() < 2 && planes.len() == 2 {
351        // A pin swept round a sharp bend: its two caps are its only planes,
352        // unless both lie at ONE end (a cup's floor behind its rim), which
353        // says nothing about where the other end is.
354        let two: Vec<Cap> = planes
355            .iter()
356            .filter_map(|(face, normal)| {
357                boundary_centroid(solid, face).map(|centre| Cap { point: centre, outward: *normal, line: None })
358            })
359            .collect();
360        if two.len() == 2 && !same_end(&two[0], &two[1]) {
361            ends = two;
362        }
363    }
364    if let Some((a, b)) = distinct_ends(&ends, tolerance) {
365        let (mut a, mut b) = (ends[a], ends[b]);
366        // A flat end opposite a tip is read on the tip's line: a scooped
367        // solder cup's half-ring has its centroid off the pin's axis.
368        a.point = on_line_of(a, &b);
369        b.point = on_line_of(b, &a);
370        if let Ok(chord) = a.point.sub(b.point).normalized() {
371            let axis = canonical(chord);
372            let (plus, minus) = if a.point.dot(axis) >= b.point.dot(axis) { (a, b) } else { (b, a) };
373            let ends = Ends {
374                axis,
375                plus_end: plus.point,
376                minus_end: minus.point,
377                plus_outward: plus.outward,
378                minus_outward: minus.outward,
379                rule: ContactRule::Caps,
380                toward: None,
381            };
382            return Ok((ends, scale));
383        }
384    }
385
386    // No distinct ends: the point's Direction picks one.
387    let Some(direction) = direction.and_then(|d| d.normalized().ok()) else {
388        return Err(format!(
389            "contact body '{name}' has no distinct ends to take a wire end from; pick a Direction (a face, an edge or an axis) to say which way the wire leaves"
390        ));
391    };
392    let axis = canonical(direction);
393    let extreme = |toward: Vec3| -> Vec3 {
394        // A terminal face normal to the direction: its centroid.
395        for (face, normal) in &planes {
396            if normal.dot(toward) >= 1.0 - PARALLEL {
397                if let Some(centre) = boundary_centroid(solid, face) {
398                    if behind(centre, *normal) {
399                        return centre;
400                    }
401                }
402            }
403        }
404        // Else the middle of the points at the extreme.
405        let top = points.iter().map(|p| p.dot(toward)).fold(f64::NEG_INFINITY, f64::max);
406        let at_top: Vec<Vec3> = points.iter().copied().filter(|p| top - p.dot(toward) <= slack).collect();
407        bbox_centre(&at_top)
408    };
409    let plus_end = extreme(axis);
410    let minus_end = extreme(axis.scale(-1.0));
411    if plus_end.sub(minus_end).dot(axis) <= RELATIVE_TOLERANCE * scale {
412        return Err(format!("contact body '{name}' has no length along its Direction"));
413    }
414    let ends = Ends {
415        axis,
416        plus_end,
417        minus_end,
418        plus_outward: axis,
419        minus_outward: axis.scale(-1.0),
420        rule: ContactRule::Direction,
421        toward: Some(direction.dot(axis) > 0.0),
422    };
423    Ok((ends, scale))
424}
425
426/// The body's extent `[low, high]` along an axis through `origin`, measured
427/// from it: its vertices, its edges, and any sphere face centred on the axis
428/// (a rounded tip, whose pole is the end).
429fn axial_extent(
430    points: &[Vec3],
431    spheres: &[(&crate::FaceRecord, Vec3, f64)],
432    origin: Vec3,
433    axis: Vec3,
434    tolerance: f64,
435) -> (f64, f64) {
436    let mut low = f64::INFINITY;
437    let mut high = f64::NEG_INFINITY;
438    let mut include = |point: Vec3| {
439        let t = point.sub(origin).dot(axis);
440        low = low.min(t);
441        high = high.max(t);
442    };
443    for point in points {
444        include(*point);
445    }
446    for (face, center, _) in spheres {
447        if off_axis(origin, axis, *center) > tolerance {
448            continue;
449        }
450        for point in sphere_samples(face) {
451            include(point);
452        }
453    }
454    (low, high)
455}
456
457/// The body's vertices and samples along its edges: the extremes of a
458/// cylinder, cone or planar face along any direction lie on its boundary.
459fn body_points(solid: &crate::BrepSolid) -> Vec<Vec3> {
460    let mut points: Vec<Vec3> = solid.vertices.iter().map(|vertex| vertex.point).collect();
461    for edge in &solid.edges {
462        if edge.degenerate {
463            continue;
464        }
465        for i in 0..=EDGE_SAMPLES {
466            let t = edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64);
467            if let Ok(point) = edge.curve.evaluate(t) {
468                points.push(point);
469            }
470        }
471    }
472    points
473}
474
475/// A grid of points over a sphere face (its pole lies on a domain boundary,
476/// which the grid includes exactly).
477fn sphere_samples(face: &crate::FaceRecord) -> Vec<Vec3> {
478    let (Ok(u), Ok(v)) = (face.surface.domain_u(), face.surface.domain_v()) else { return Vec::new() };
479    let mut out = Vec::new();
480    for i in 0..=SPHERE_SAMPLES {
481        for j in 0..=SPHERE_SAMPLES {
482            let s = u[0] + (u[1] - u[0]) * (i as f64 / SPHERE_SAMPLES as f64);
483            let t = v[0] + (v[1] - v[0]) * (j as f64 / SPHERE_SAMPLES as f64);
484            if let Ok(point) = face.surface.evaluate(s, t) {
485                out.push(point);
486            }
487        }
488    }
489    out
490}
491
492/// A rounded tip's pole: the sphere face's point farthest from the body's
493/// centre.
494fn sphere_tip(face: &crate::FaceRecord, body_centre: Vec3) -> Option<Vec3> {
495    sphere_samples(face)
496        .into_iter()
497        .max_by(|a, b| a.sub(body_centre).length().total_cmp(&b.sub(body_centre).length()))
498}
499
500/// The centroid of a face's boundary, each edge sample weighted by the length
501/// it stands for: the centre of a cap's rectangle, disc or ring.
502fn boundary_centroid(solid: &crate::BrepSolid, face: &crate::FaceRecord) -> Option<Vec3> {
503    let mut sum = Vec3::new(0.0, 0.0, 0.0);
504    let mut length = 0.0;
505    for edge_id in face.loops.iter().flat_map(|l| l.coedges.iter().map(|c| c.edge_id)) {
506        let Some(edge) = solid.edges.iter().find(|edge| edge.id == edge_id) else { continue };
507        if edge.degenerate {
508            continue;
509        }
510        let samples: Vec<Vec3> = (0..=EDGE_SAMPLES)
511            .filter_map(|i| edge.curve.evaluate(edge.t0 + (edge.t1 - edge.t0) * (i as f64 / EDGE_SAMPLES as f64)).ok())
512            .collect();
513        for pair in samples.windows(2) {
514            let piece = pair[1].sub(pair[0]).length();
515            sum = sum.add(pair[0].add(pair[1]).scale(0.5 * piece));
516            length += piece;
517        }
518    }
519    (length > 0.0).then(|| sum.scale(1.0 / length))
520}
521
522/// The pair of caps farthest apart, when no other pair comes within
523/// [`DISTINCT_ENDS`] of it (a cube's three opposite pairs tie).
524fn distinct_ends(caps: &[Cap], tolerance: f64) -> Option<(usize, usize)> {
525    let mut pairs: Vec<(f64, usize, usize)> = Vec::new();
526    for i in 0..caps.len() {
527        for j in i + 1..caps.len() {
528            pairs.push((caps[i].point.sub(caps[j].point).length(), i, j));
529        }
530    }
531    pairs.sort_by(|a, b| b.0.total_cmp(&a.0));
532    let &(best, i, j) = pairs.first()?;
533    if best <= tolerance {
534        return None;
535    }
536    let rival = pairs.iter().skip(1).any(|&(d, k, l)| (k, l) != (i, j) && d >= DISTINCT_ENDS * best);
537    (!rival).then_some((i, j))
538}
539
540/// One candidate end: where a wire attaches, the direction it leaves along,
541/// and for a tip its axis line (a point on it and its direction).
542#[derive(Debug, Clone, Copy)]
543pub(super) struct Cap {
544    pub(super) point: Vec3,
545    pub(super) outward: Vec3,
546    pub(super) line: Option<(Vec3, Vec3)>,
547}
548
549/// A round non-cylindrical face's tip (a fillet's torus, a cone), when it is
550/// at an end: the axis point at the face's extreme along its axis on the side
551/// away from the body's centre, leaving along the axis.
552fn axial_tip(face: &crate::FaceRecord, origin: Vec3, axis: Vec3, body_centre: Vec3) -> Option<Cap> {
553    let samples = sphere_samples(face);
554    if samples.is_empty() {
555        return None;
556    }
557    let along: Vec<f64> = samples.iter().map(|p| p.sub(origin).dot(axis)).collect();
558    let mean = along.iter().sum::<f64>() / along.len() as f64;
559    let centre = body_centre.sub(origin).dot(axis);
560    let (t, outward) = if mean >= centre {
561        (along.iter().copied().fold(f64::NEG_INFINITY, f64::max), axis)
562    } else {
563        (along.iter().copied().fold(f64::INFINITY, f64::min), axis.scale(-1.0))
564    };
565    Some(Cap { point: origin.add(axis.scale(t)), outward, line: Some((origin, axis)) })
566}
567
568/// `end`'s point, moved onto `other`'s tip line when `end` faces along that
569/// line (a flat end opposite a tip); unchanged otherwise.
570fn on_line_of(end: Cap, other: &Cap) -> Vec3 {
571    let (Some((origin, direction)), None) = (other.line, end.line) else { return end.point };
572    let Ok(direction) = direction.normalized() else { return end.point };
573    if end.outward.dot(direction).abs() < 1.0 - PARALLEL {
574        return end.point;
575    }
576    origin.add(direction.scale(end.point.sub(origin).dot(direction)))
577}
578
579/// Whether two flat caps lie at ONE end of a body: they face the same way and
580/// one stands behind the other along that way (a cup's floor behind its rim),
581/// rather than side by side (the two legs of a hairpin).
582pub(super) fn same_end(a: &Cap, b: &Cap) -> bool {
583    let apart = a.point.sub(b.point);
584    let length = apart.length();
585    a.outward.dot(b.outward) > 0.9 && (length == 0.0 || apart.dot(a.outward).abs() >= 0.9 * length)
586}
587
588/// The centre of the points' bounding box.
589fn bbox_centre(points: &[Vec3]) -> Vec3 {
590    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
591    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
592    for p in points {
593        low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
594        high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
595    }
596    low.add(high).scale(0.5)
597}
598
599/// The centre of the bounding box of every OTHER resident solid of the scene:
600/// what "the rest of the part" a pin sticks out of is. `None` when the body is
601/// the only solid.
602fn rest_of_part_centre(scene: &SceneMap, body: u32) -> Option<Vec3> {
603    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
604    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
605    let mut any = false;
606    let mut handles: Vec<u32> = scene.solids.values().copied().filter(|h| *h != body).collect();
607    handles.sort_unstable();
608    handles.dedup();
609    for handle in handles {
610        let Ok((a, b)) = crate::feature_pipeline::pmi::resolve::solid_bbox(handle) else { continue };
611        low = Vec3::new(low.x.min(a.x), low.y.min(a.y), low.z.min(a.z));
612        high = Vec3::new(high.x.max(b.x), high.y.max(b.y), high.z.max(b.z));
613        any = true;
614    }
615    any.then(|| low.add(high).scale(0.5))
616}
617
618/// The direction with its largest component positive: one sense for an axis,
619/// whichever way a face happens to report it.
620fn canonical(direction: Vec3) -> Vec3 {
621    let [x, y, z] = [direction.x, direction.y, direction.z];
622    let largest = if x.abs() >= y.abs() && x.abs() >= z.abs() {
623        x
624    } else if y.abs() >= z.abs() {
625        y
626    } else {
627        z
628    };
629    if largest < 0.0 {
630        direction.scale(-1.0)
631    } else {
632        direction
633    }
634}
635
636/// Whether two axes are one line.
637fn collinear(o1: Vec3, d1: Vec3, o2: Vec3, d2: Vec3, tolerance: f64) -> bool {
638    d1.cross(d2).length() <= PARALLEL && off_axis(o1, d1, o2) <= tolerance.max(1e-9)
639}
640
641/// How far `point` is from the line through `origin` along unit `axis`.
642fn off_axis(origin: Vec3, axis: Vec3, point: Vec3) -> f64 {
643    let offset = point.sub(origin);
644    offset.sub(axis.scale(offset.dot(axis))).length()
645}
646
647/// A size for the body: its vertex bounding-box diagonal, at least 1.
648fn solid_scale(solid: &crate::BrepSolid) -> f64 {
649    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
650    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
651    for vertex in &solid.vertices {
652        let p = vertex.point;
653        low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
654        high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
655    }
656    if solid.vertices.is_empty() {
657        return 1.0;
658    }
659    high.sub(low).length().max(1.0)
660}