Skip to main content

brep_solvers/solvers/
assembly_resolve.rs

1//! Assembly selection resolution — a selection reference
2//! resolved to an ANALYTIC frame read from the exact BREP surfaces/curves,
3//! never from tessellation (the retired app's polyline-PCA approximation is
4//! the wart this module kills):
5//!
6//! - planar face → plane (origin + OUTWARD unit normal, plane-z convention)
7//! - cylindrical/conical face → axis (origin + direction), radius when the
8//!   radius is constant (a genuine cylinder)
9//! - spherical face → center + radius
10//! - circular/arc edge → center + axis + radius
11//! - straight edge → the INFINITE carrier line
12//! - vertex → point
13//! - whole component → representative point (aggregate bbox center)
14//!
15//! Anything without an analytic frame is a typed [`ResolveError`] mapping onto
16//! the constraint status vocabulary (`unsupported-selection` /
17//! `invalid-selection`), never a panic.
18//!
19//! # Coordinate space — read this before marshaling mates
20//!
21//! Every resolver reads the geometry EXACTLY as stored on the given
22//! [`BrepSolid`], so the resolved frame is in the SOLID'S OWN space. A
23//! component instance whose resident solids are world-posed (the ACOMP feature
24//! bakes its placement into the geometry) must pass the component's
25//! world→local INVERSE transform to [`SelectionGeometry::transformed`] to
26//! obtain the COMPONENT-LOCAL frame the assembly solver's mate inputs require
27//! ([`MateKind`](crate::MateKind): `*_a`/`*_b` geometry is local to the owning
28//! body, which the solver poses).
29//!
30//! # Lane seam — component lookup
31//!
32//! [`split_component_namespace`] only PARSES the `ACOMP…:` prefix chain off a
33//! namespaced topology name. Mapping that chain to the owning component's
34//! resident solids and its world→local inverse transform is the scene
35//! component registry's job (built in parallel); the resolvers here
36//! deliberately take `(solid, entity)` plus a transform argument instead of a
37//! registry. Vertices carry no kernel names (the renderer's `VertexRef`
38//! convention is owning solid + position), so vertex selections arrive as a
39//! position and snap to the nearest topology vertex.
40
41use crate::topology::{BrepSolid, EdgeRecord, FaceRecord};
42use crate::{AffineTransform, AnalyticSurface, MateAxis, MatePlane, NurbsCurve, Vec3};
43use serde::Serialize;
44
45/// Scale-relative acceptance for the straight/circular edge verification —
46/// the analytic-surface recognition tolerance, for the same reason: exact
47/// kernel-built geometry verifies at machine precision, anything else fails
48/// by orders of magnitude.
49const RESOLVE_TOLERANCE: f64 = 1e-9;
50/// Scale-relative snap distance for vertex-by-position resolution (positions
51/// round-trip through the app as f64 but may be re-serialized).
52const VERTEX_SNAP_TOLERANCE: f64 = 1e-6;
53/// Circle acceptance samples across the edge's trimmed span.
54const CIRCLE_VERIFY_SAMPLES: usize = 16;
55
56// ---------------------------------------------------------------------------
57// Result / error types
58// ---------------------------------------------------------------------------
59
60/// A resolved analytic selection frame, in the coordinate space of the solid
61/// it was resolved from (module docs: pass the component's world→local inverse
62/// to [`Self::transformed`] for the solver's component-local mate inputs).
63///
64/// Cross-lane invariant: [`SelectionGeometry::Axis`]`::radius` is `Some` IFF
65/// the face is a genuine constant-radius cylinder — the gate for the
66/// `tangent_cylinder_plane` mate. Cones, tori, and general revolution faces
67/// resolve with `radius: None`.
68#[derive(Clone, Copy, Debug, Serialize)]
69#[serde(tag = "kind", rename_all = "snake_case")]
70pub enum SelectionGeometry {
71    /// Planar face: origin on the plane (the centre of the face boundary's
72    /// bounding box in the face's own in-plane basis — a fixed point of the
73    /// body, see `planar_face`) + OUTWARD unit normal (face sense respected,
74    /// per the one plane-z direction convention).
75    Plane { origin: Vec3, normal: Vec3 },
76    /// Axis-bearing face (cylinder / cone / torus / general revolution):
77    /// a point on the axis + unit direction.
78    Axis {
79        origin: Vec3,
80        direction: Vec3,
81        radius: Option<f64>,
82    },
83    /// Spherical face.
84    Sphere { center: Vec3, radius: f64 },
85    /// Circular or arc edge; `axis` follows the right-hand rule along the
86    /// edge's increasing-parameter direction.
87    Circle { center: Vec3, axis: Vec3, radius: f64 },
88    /// Straight edge: the INFINITE carrier line (origin = chord midpoint,
89    /// unit direction start→end). Distance mates measure against the carrier,
90    /// never the clamped finite segment.
91    Line { origin: Vec3, direction: Vec3 },
92    /// Vertex (or whole-component representative point).
93    Point { position: Vec3 },
94}
95
96/// Typed resolution failure. [`Self::status`] maps each variant onto the
97/// constraint status vocabulary so the constraint lifecycle
98/// reports it without string-matching messages.
99#[derive(Clone, Debug, PartialEq, Serialize)]
100pub enum ResolveError {
101    /// No such entity on the solid (or no vertex within snap distance).
102    NotFound { name: String },
103    /// The entity exists but carries no analytic frame (freeform surface,
104    /// spline edge, degenerate edge).
105    Unsupported { name: String, detail: String },
106    /// The entity's geometry failed to evaluate.
107    Geometry { name: String, detail: String },
108}
109
110impl ResolveError {
111    /// The constraint-status word this failure maps to.
112    pub fn status(&self) -> &'static str {
113        match self {
114            ResolveError::NotFound { .. } | ResolveError::Geometry { .. } => "invalid-selection",
115            ResolveError::Unsupported { .. } => "unsupported-selection",
116        }
117    }
118}
119
120impl std::fmt::Display for ResolveError {
121    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122        match self {
123            ResolveError::NotFound { name } => write!(formatter, "selection '{name}' not found"),
124            ResolveError::Unsupported { name, detail } => {
125                write!(formatter, "selection '{name}' has no analytic frame: {detail}")
126            }
127            ResolveError::Geometry { name, detail } => {
128                write!(formatter, "selection '{name}' failed to resolve: {detail}")
129            }
130        }
131    }
132}
133
134impl SelectionGeometry {
135    /// The solver's plane input, for planar-face selections.
136    pub fn mate_plane(&self) -> Option<MatePlane> {
137        match *self {
138            SelectionGeometry::Plane { origin, normal } => Some(MatePlane {
139                origin: triple(origin),
140                normal: triple(normal),
141            }),
142            _ => None,
143        }
144    }
145
146    /// The solver's axis input, for every axis-bearing selection: an axis
147    /// face, a circular edge (center + circle axis), or a straight edge's
148    /// carrier line.
149    pub fn mate_axis(&self) -> Option<MateAxis> {
150        let (origin, direction) = match *self {
151            SelectionGeometry::Axis {
152                origin, direction, ..
153            }
154            | SelectionGeometry::Line { origin, direction } => (origin, direction),
155            SelectionGeometry::Circle { center, axis, .. } => (center, axis),
156            _ => return None,
157        };
158        Some(MateAxis {
159            origin: triple(origin),
160            direction: triple(direction),
161        })
162    }
163
164    /// The per-kind anchor point: plane / axis / line origin, sphere / circle
165    /// center, the point itself.
166    pub fn representative_point(&self) -> Vec3 {
167        match *self {
168            SelectionGeometry::Plane { origin, .. }
169            | SelectionGeometry::Axis { origin, .. }
170            | SelectionGeometry::Line { origin, .. } => origin,
171            SelectionGeometry::Sphere { center, .. }
172            | SelectionGeometry::Circle { center, .. } => center,
173            SelectionGeometry::Point { position } => position,
174        }
175    }
176
177    /// Map the frame through `transform` — pass the owning component's
178    /// world→local inverse to express a world-resolved frame in the
179    /// component-local coordinates the solver's mate inputs require. Rigid /
180    /// uniform-similarity matrices only (component poses are rigid by spec):
181    /// radii scale by the uniform factor; a shearing or non-uniformly scaling
182    /// matrix is refused (it has no analytic image for circles/cylinders).
183    pub fn transformed(&self, transform: &AffineTransform) -> Result<Self, ResolveError> {
184        let scale = uniform_scale(transform).ok_or_else(|| ResolveError::Unsupported {
185            name: "transform".into(),
186            detail: "selection frames transform only by rigid/uniform-scale matrices".into(),
187        })?;
188        let direction = |vector: Vec3| {
189            linear(transform, vector)
190                .normalized()
191                .map_err(|error| ResolveError::Geometry {
192                    name: "transform".into(),
193                    detail: error,
194                })
195        };
196        Ok(match *self {
197            SelectionGeometry::Plane { origin, normal } => SelectionGeometry::Plane {
198                origin: transform.point(origin),
199                normal: direction(normal)?,
200            },
201            SelectionGeometry::Axis {
202                origin,
203                direction: axis,
204                radius,
205            } => SelectionGeometry::Axis {
206                origin: transform.point(origin),
207                direction: direction(axis)?,
208                radius: radius.map(|radius| radius * scale),
209            },
210            SelectionGeometry::Sphere { center, radius } => SelectionGeometry::Sphere {
211                center: transform.point(center),
212                radius: radius * scale,
213            },
214            SelectionGeometry::Circle {
215                center,
216                axis,
217                radius,
218            } => SelectionGeometry::Circle {
219                center: transform.point(center),
220                axis: direction(axis)?,
221                radius: radius * scale,
222            },
223            SelectionGeometry::Line {
224                origin,
225                direction: axis,
226            } => SelectionGeometry::Line {
227                origin: transform.point(origin),
228                direction: direction(axis)?,
229            },
230            SelectionGeometry::Point { position } => SelectionGeometry::Point {
231                position: transform.point(position),
232            },
233        })
234    }
235}
236
237fn triple(vector: Vec3) -> [f64; 3] {
238    [vector.x, vector.y, vector.z]
239}
240
241/// The linear (rotation/scale) part of the transform applied to a vector.
242pub fn linear(transform: &AffineTransform, vector: Vec3) -> Vec3 {
243    let m = transform.elements;
244    Vec3::new(
245        m[0] * vector.x + m[1] * vector.y + m[2] * vector.z,
246        m[4] * vector.x + m[5] * vector.y + m[6] * vector.z,
247        m[8] * vector.x + m[9] * vector.y + m[10] * vector.z,
248    )
249}
250
251/// The uniform scale factor of a rigid/similarity matrix: columns of equal
252/// length AND pairwise orthogonal (equal lengths alone admit shear).
253fn uniform_scale(transform: &AffineTransform) -> Option<f64> {
254    let m = transform.elements;
255    let columns = [
256        Vec3::new(m[0], m[4], m[8]),
257        Vec3::new(m[1], m[5], m[9]),
258        Vec3::new(m[2], m[6], m[10]),
259    ];
260    let lengths = [
261        columns[0].length(),
262        columns[1].length(),
263        columns[2].length(),
264    ];
265    let scale = (lengths[0] + lengths[1] + lengths[2]) / 3.0;
266    if !(scale > 0.0) {
267        return None;
268    }
269    if lengths
270        .iter()
271        .any(|length| (length - scale).abs() > 1e-9 * scale)
272    {
273        return None;
274    }
275    let orthogonality = 1e-9 * scale * scale;
276    if columns[0].dot(columns[1]).abs() > orthogonality
277        || columns[1].dot(columns[2]).abs() > orthogonality
278        || columns[0].dot(columns[2]).abs() > orthogonality
279    {
280        return None;
281    }
282    Some(scale)
283}
284
285// ---------------------------------------------------------------------------
286// Namespace parsing
287// ---------------------------------------------------------------------------
288
289/// Split a possibly-namespaced topology name into its `ACOMP…:` component-id
290/// chain (outermost first) and the remaining component-LOCAL name. A segment
291/// is peeled only when it matches `ACOMP<digits>` AND is followed by `:`, so a
292/// bare whole-component reference stays in the LOCAL position — callers detect
293/// it with [`is_component_reference`]:
294///
295/// - `"ACOMP2:Extrude1|Extrude1_top[0]"` → `(["ACOMP2"], "Extrude1|…")`
296/// - `"ACOMP3:ACOMP1:S1:G20"` → `(["ACOMP3", "ACOMP1"], "S1:G20")`
297/// - `"ACOMP2"` → `([], "ACOMP2")` (whole-component selection)
298/// - `"ACOMP3:ACOMP1"` → `(["ACOMP3"], "ACOMP1")` (nested whole-component)
299/// - `"S1:G20"` → `([], "S1:G20")` (sketch-child names never namespace)
300pub fn split_component_namespace(name: &str) -> (Vec<&str>, &str) {
301    let mut chain = Vec::new();
302    let mut local = name;
303    while let Some((head, tail)) = local.split_once(':') {
304        if !is_component_reference(head) {
305            break;
306        }
307        chain.push(head);
308        local = tail;
309    }
310    (chain, local)
311}
312
313/// `ACOMP<digits>` — an ACOMP feature id, i.e. a whole-component selection or
314/// one namespace segment of a nested chain — or a Pattern Component instance
315/// id (`APAT1.ACOMP3.i4`), which namespaces its geometry the same way.
316pub fn is_component_reference(name: &str) -> bool {
317    name.strip_prefix("ACOMP")
318        .map(|digits| !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()))
319        .unwrap_or(false)
320        || crate::assembly_ids::parse_instance_id(name).is_some()
321}
322
323/// The component ids a document's names may be namespaced by, level by level
324/// (owner 2026-11-27): the document's own components, and under each the
325/// components of THAT component's part document, so a nested chain
326/// `Motor:Shaft:F1_PZ` is read one level at a time. A segment is a component
327/// when it is registered at its level or has the `ACOMP<n>` / pattern-instance
328/// shape ([`is_component_reference`]), so every name that split before splits
329/// exactly as it did; a registered id frees a component from the shape.
330#[derive(Clone, Debug, Default, PartialEq, Eq)]
331pub struct ComponentNamespace {
332    children: std::collections::BTreeMap<String, ComponentNamespace>,
333}
334
335impl ComponentNamespace {
336    /// An empty namespace: only the shape rule applies.
337    pub fn new() -> Self {
338        Self::default()
339    }
340    /// Register component `id` at this level, its part's own components as `inner`.
341    pub fn insert(&mut self, id: impl Into<String>, inner: ComponentNamespace) {
342        self.children.insert(id.into(), inner);
343    }
344    /// The components registered at this level.
345    pub fn ids(&self) -> impl Iterator<Item = &str> {
346        self.children.keys().map(String::as_str)
347    }
348    /// The namespace of component `id`'s part, when `id` is registered here.
349    pub fn inner(&self, id: &str) -> Option<&ComponentNamespace> {
350        self.children.get(id)
351    }
352    /// Whether `name` is a component at this level: registered, or of the shape.
353    pub fn is_component(&self, name: &str) -> bool {
354        self.children.contains_key(name) || is_component_reference(name)
355    }
356    /// [`split_component_namespace`] read against this namespace: each segment
357    /// is checked at its own level (a registered component's part's ids below
358    /// it; past a shape-only segment, the shape rule alone).
359    pub fn split<'a>(&self, name: &'a str) -> (Vec<&'a str>, &'a str) {
360        static EMPTY: std::sync::OnceLock<ComponentNamespace> = std::sync::OnceLock::new();
361        let empty = EMPTY.get_or_init(ComponentNamespace::default);
362        let mut level = self;
363        let mut chain = Vec::new();
364        let mut local = name;
365        while let Some((head, tail)) = local.split_once(':') {
366            if !level.is_component(head) {
367                break;
368            }
369            chain.push(head);
370            level = level.children.get(head).unwrap_or(empty);
371            local = tail;
372        }
373        (chain, local)
374    }
375    /// Whether `name` names a whole component (a bare id, or a nested chain
376    /// ending in one): what [`is_component_reference`] answers for the local
377    /// part of a split by shape.
378    pub fn names_component(&self, name: &str) -> bool {
379        let (chain, local) = self.split(name);
380        let mut level = self;
381        for head in chain {
382            match level.children.get(head) {
383                Some(inner) => level = inner,
384                None => return is_component_reference(local),
385            }
386        }
387        level.is_component(local)
388    }
389}
390
391// ---------------------------------------------------------------------------
392// Entity resolution
393// ---------------------------------------------------------------------------
394
395/// Resolve a component-LOCAL topology name (already namespace-stripped)
396/// against one solid: faces first, then edges. Names never collide across the
397/// two kinds under the deterministic-naming scheme; the order only settles
398/// pathological ties.
399pub fn resolve_named_selection(
400    solid: &BrepSolid,
401    name: &str,
402) -> Result<SelectionGeometry, ResolveError> {
403    if let Some(record) = solid
404        .shells
405        .iter()
406        .flat_map(|shell| &shell.faces)
407        .find(|face| face.name.as_deref() == Some(name))
408    {
409        return resolve_face_record(solid, record);
410    }
411    if let Some(record) = solid
412        .edges
413        .iter()
414        .find(|edge| edge.name.as_deref() == Some(name))
415    {
416        return resolve_edge_record(record);
417    }
418    Err(ResolveError::NotFound { name: name.into() })
419}
420
421/// Resolve a face by topology id (the scene-map `FaceRef` lane: the caller
422/// already resolved the selection name to `(handle, face_id)`).
423pub fn resolve_face_selection(
424    solid: &BrepSolid,
425    face_id: u64,
426) -> Result<SelectionGeometry, ResolveError> {
427    let record = solid
428        .shells
429        .iter()
430        .flat_map(|shell| &shell.faces)
431        .find(|face| face.id == face_id)
432        .ok_or_else(|| ResolveError::NotFound {
433            name: format!("face {face_id}"),
434        })?;
435    resolve_face_record(solid, record)
436}
437
438/// Resolve an edge by topology id (the `EdgeRef` lane).
439pub fn resolve_edge_selection(
440    solid: &BrepSolid,
441    edge_id: u64,
442) -> Result<SelectionGeometry, ResolveError> {
443    let record = solid
444        .edges
445        .iter()
446        .find(|edge| edge.id == edge_id)
447        .ok_or_else(|| ResolveError::NotFound {
448            name: format!("edge {edge_id}"),
449        })?;
450    resolve_edge_record(record)
451}
452
453/// Resolve a vertex selection by position (vertices have no kernel names; the
454/// renderer references them by owning solid + position). Nearest topology
455/// vertex wins — deterministic when two vertices are close — then the
456/// scale-relative snap tolerance gates acceptance; the returned point is the
457/// EXACT vertex position, not the query.
458pub fn resolve_vertex_selection(
459    solid: &BrepSolid,
460    position: Vec3,
461) -> Result<SelectionGeometry, ResolveError> {
462    let mut best: Option<(f64, Vec3)> = None;
463    for vertex in &solid.vertices {
464        let distance = vertex.point.sub(position).length();
465        if best
466            .map(|(best_distance, _)| distance < best_distance)
467            .unwrap_or(true)
468        {
469            best = Some((distance, vertex.point));
470        }
471    }
472    match best {
473        Some((distance, point))
474            if distance <= VERTEX_SNAP_TOLERANCE * crate::solid_scale(solid) =>
475        {
476            Ok(SelectionGeometry::Point { position: point })
477        }
478        _ => Err(ResolveError::NotFound {
479            name: format!(
480                "vertex near ({}, {}, {})",
481                position.x, position.y, position.z
482            ),
483        }),
484    }
485}
486
487/// Whole-component representative point: the center of the aggregate AABB of
488/// every face surface's control-point hull (plus topology vertices) across the
489/// component's solids. The hull BOUNDS the exact surfaces (convex-hull
490/// property) without touching tessellation; it overshoots curved faces, so
491/// this is a representative anchor for coincident/parallel-with-component
492/// semantics, not an exact bounding box.
493pub fn resolve_component_point(solids: &[&BrepSolid]) -> Result<SelectionGeometry, ResolveError> {
494    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
495    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
496    let mut any = false;
497    let mut include = |point: Vec3| {
498        low = Vec3::new(low.x.min(point.x), low.y.min(point.y), low.z.min(point.z));
499        high = Vec3::new(high.x.max(point.x), high.y.max(point.y), high.z.max(point.z));
500        any = true;
501    };
502    for solid in solids {
503        for vertex in &solid.vertices {
504            include(vertex.point);
505        }
506        for shell in &solid.shells {
507            for face in &shell.faces {
508                for row in &face.surface.control_points {
509                    for control in row {
510                        let point = control.point().map_err(|error| ResolveError::Geometry {
511                            name: "component".into(),
512                            detail: error,
513                        })?;
514                        include(point);
515                    }
516                }
517            }
518        }
519    }
520    if !any {
521        return Err(ResolveError::Geometry {
522            name: "component".into(),
523            detail: "component has no geometry to anchor".into(),
524        });
525    }
526    Ok(SelectionGeometry::Point {
527        position: low.add(high).scale(0.5),
528    })
529}
530
531// ---------------------------------------------------------------------------
532// Face resolution
533// ---------------------------------------------------------------------------
534
535fn face_label(record: &FaceRecord) -> String {
536    record
537        .name
538        .clone()
539        .unwrap_or_else(|| format!("face {}", record.id))
540}
541
542fn resolve_face_record(
543    solid: &BrepSolid,
544    record: &FaceRecord,
545) -> Result<SelectionGeometry, ResolveError> {
546    match record.surface.analytic() {
547        Some(AnalyticSurface::RuledRevolution {
548            frame, rho0, rho1, ..
549        }) => {
550            // Meridional generatrix (reconstruction-verified), so equal end
551            // radii already mean a constant radius: a genuine cylinder.
552            let span = rho0.abs().max(rho1.abs());
553            let radius = ((rho0 - rho1).abs() <= RESOLVE_TOLERANCE * (1.0 + span))
554                .then_some(0.5 * (rho0 + rho1));
555            Ok(SelectionGeometry::Axis {
556                origin: frame.origin,
557                direction: frame.axis,
558                radius,
559            })
560        }
561        Some(AnalyticSurface::Sphere { frame, radius }) => Ok(SelectionGeometry::Sphere {
562            center: frame.origin,
563            radius: *radius,
564        }),
565        Some(AnalyticSurface::Torus { frame, .. }) => Ok(SelectionGeometry::Axis {
566            origin: frame.origin,
567            direction: frame.axis,
568            radius: None,
569        }),
570        Some(AnalyticSurface::Revolution {
571            frame, generatrix, ..
572        }) => Ok(SelectionGeometry::Axis {
573            origin: frame.origin,
574            direction: frame.axis,
575            radius: revolution_cylinder_radius(frame, generatrix),
576        }),
577        // Exact plane, or unrecognized (imported) geometry that may still be
578        // planar — one shared sampled-planarity lane, `face_frame` parity.
579        Some(AnalyticSurface::Plane { .. }) | None => planar_face(solid, record),
580    }
581}
582
583/// `Some(radius)` when a general-revolution generatrix is a straight line at
584/// CONSTANT radial distance from the axis — a partial cylinder (e.g. a 180°
585/// revolve wall). Equal END radii alone are not enough: a line skew to the
586/// axis revolves into a hyperboloid whose radius dips between equal ends. But
587/// squared radial distance along a straight line is a QUADRATIC function of
588/// arc length, so three equal samples (ends + midpoint) force it constant.
589fn revolution_cylinder_radius(
590    frame: &crate::RevolutionFrame,
591    generatrix: &NurbsCurve,
592) -> Option<f64> {
593    if !control_net_is_colinear(generatrix) {
594        return None;
595    }
596    let [t0, t1] = generatrix.domain().ok()?;
597    let radial = |t: f64| -> Option<f64> {
598        let point = generatrix.evaluate(t).ok()?;
599        let delta = point.sub(frame.origin);
600        Some(delta.sub(frame.axis.scale(delta.dot(frame.axis))).length())
601    };
602    let rho0 = radial(t0)?;
603    let rho_mid = radial(0.5 * (t0 + t1))?;
604    let rho1 = radial(t1)?;
605    let span = rho0.abs().max(rho1.abs());
606    let tolerance = RESOLVE_TOLERANCE * (1.0 + span);
607    ((rho0 - rho1).abs() <= tolerance && (rho_mid - rho0).abs() <= tolerance)
608        .then_some((rho0 + rho_mid + rho1) / 3.0)
609}
610
611/// Planar-face resolution: sampled-constant-normal acceptance (the established
612/// `face_frame` planarity test, densified to a 3×3 grid), OUTWARD normal via
613/// the face sense, origin = the centre of the face boundary's bounding box
614/// taken in the face's OWN in-plane basis, projected onto the plane.
615///
616/// The basis is the surface's u-tangent at the patch midpoint (its normal
617/// component removed) and the normal's cross with it. A component pose moves
618/// the control net rigidly and that basis with it, so the box of the same
619/// boundary samples is the same box and the anchor is a FIXED point of the
620/// body. A world-axis box is not: on a face with no centre of symmetry (a
621/// triangle, an L) its centre slides over the face as the body turns — and the
622/// assembly angle gizmo, hinged on the two face anchors, slid with it on
623/// every edit (`planar_face_anchor_is_a_fixed_body_point_on_an_asymmetric_face`).
624/// For a centrally symmetric face (rectangle, disc) both rules name the same
625/// point. The tangent test is scale-free (a stretched knot domain shrinks the
626/// partials without moving the plane); the v-partial is the body-fixed
627/// fallback, and a face whose partials both vanish at the midpoint cannot
628/// reach this code — its normal would have failed above.
629fn planar_face(solid: &BrepSolid, record: &FaceRecord) -> Result<SelectionGeometry, ResolveError> {
630    let geometry = (|| -> Result<Option<SelectionGeometry>, String> {
631        let [u0, u1] = record.surface.domain_u()?;
632        let [v0, v1] = record.surface.domain_v()?;
633        let (um, vm) = ((u0 + u1) * 0.5, (v0 + v1) * 0.5);
634        let center_normal = record.surface.normal(um, vm)?;
635        for u in [u0, um, u1] {
636            for v in [v0, vm, v1] {
637                if record.surface.normal(u, v)?.dot(center_normal) < 1.0 - 1e-6 {
638                    return Ok(None);
639                }
640            }
641        }
642        let normal = if record.same_sense {
643            center_normal
644        } else {
645            center_normal.scale(-1.0)
646        }
647        .normalized()?;
648
649        // The face's own in-plane basis (body-fixed, see the doc above). The
650        // test is SCALE-FREE — the in-plane part must carry the derivative's
651        // own magnitude, whatever that magnitude is — because a knot domain
652        // can be stretched arbitrarily without moving a point of the plane,
653        // and an absolute floor would send such a face to a pose-dependent
654        // rule (`planar_anchor_is_body_fixed_whatever_the_parameter_scale`).
655        // Both partials are tried; both are body-fixed. Neither can fail for
656        // a face that got here: `normal(um, vm)` above succeeded, so
657        // |∂u × ∂v| > 1e-12 at the midpoint — both partials are non-zero —
658        // and the accepted constant normal is their cross, so each lies in
659        // the plane. The error is the unreachable branch, not a world axis.
660        let plane_point = record.surface.evaluate(um, vm)?;
661        let partials = record.surface.derivatives(um, vm, 1)?;
662        let in_plane = |partial: Vec3| -> Option<Vec3> {
663            let tangent = partial.sub(normal.scale(partial.dot(normal)));
664            let length = tangent.length();
665            (length.is_finite() && length > 1e-6 * partial.length() && length > 0.0)
666                .then(|| tangent.scale(1.0 / length))
667        };
668        let e1 = in_plane(partials[1][0])
669            .or_else(|| in_plane(partials[0][1]))
670            .ok_or_else(|| {
671                "planar face: both surface partials degenerate at the patch midpoint".to_string()
672            })?;
673        let e2 = normal.cross(e1).normalized()?;
674        // Boundary bounding box in that basis, from the face loops'
675        // non-degenerate edges; the patch midpoint for loop-less faces.
676        let mut low = [f64::INFINITY; 2];
677        let mut high = [f64::NEG_INFINITY; 2];
678        let mut any = false;
679        for loop_record in &record.loops {
680            for coedge in &loop_record.coedges {
681                let Some(edge) = solid.edges.iter().find(|edge| edge.id == coedge.edge_id) else {
682                    continue;
683                };
684                if edge.degenerate {
685                    continue;
686                }
687                for step in 0..=4 {
688                    let t = edge.t0 + (edge.t1 - edge.t0) * (step as f64 / 4.0);
689                    let offset = edge.curve.evaluate(t)?.sub(plane_point);
690                    let (a, b) = (offset.dot(e1), offset.dot(e2));
691                    low = [low[0].min(a), low[1].min(b)];
692                    high = [high[0].max(a), high[1].max(b)];
693                    any = true;
694                }
695            }
696        }
697        let center = if any {
698            plane_point
699                .add(e1.scale((low[0] + high[0]) * 0.5))
700                .add(e2.scale((low[1] + high[1]) * 0.5))
701        } else {
702            plane_point
703        };
704        // Project onto the plane so the origin lies exactly on it (the basis
705        // is in-plane; this clears rounding).
706        let signed = center.sub(plane_point).dot(normal);
707        let origin = center.sub(normal.scale(signed));
708        Ok(Some(SelectionGeometry::Plane { origin, normal }))
709    })();
710    match geometry {
711        Ok(Some(frame)) => Ok(frame),
712        Ok(None) => Err(ResolveError::Unsupported {
713            name: face_label(record),
714            detail: "face carries no analytic frame (freeform surface)".into(),
715        }),
716        Err(error) => Err(ResolveError::Geometry {
717            name: face_label(record),
718            detail: error,
719        }),
720    }
721}
722
723// ---------------------------------------------------------------------------
724// Edge resolution
725// ---------------------------------------------------------------------------
726
727fn edge_label(record: &EdgeRecord) -> String {
728    record
729        .name
730        .clone()
731        .unwrap_or_else(|| format!("edge {}", record.id))
732}
733
734fn resolve_edge_record(record: &EdgeRecord) -> Result<SelectionGeometry, ResolveError> {
735    if record.degenerate {
736        return Err(ResolveError::Unsupported {
737            name: edge_label(record),
738            detail: "degenerate edge".into(),
739        });
740    }
741    match edge_geometry(record) {
742        Ok(Some(frame)) => Ok(frame),
743        Ok(None) => Err(ResolveError::Unsupported {
744            name: edge_label(record),
745            detail: "edge is neither straight nor circular".into(),
746        }),
747        Err(error) => Err(ResolveError::Geometry {
748            name: edge_label(record),
749            detail: error,
750        }),
751    }
752}
753
754fn edge_geometry(record: &EdgeRecord) -> Result<Option<SelectionGeometry>, String> {
755    if let Some(line) = straight_edge_line(record)? {
756        return Ok(Some(line));
757    }
758    circular_edge_circle(record)
759}
760
761/// The whole curve's extent, for scale-relative acceptance.
762fn control_net_extent(curve: &NurbsCurve) -> f64 {
763    let mut extent = 0.0_f64;
764    for control in &curve.control_points {
765        if let Ok(point) = control.point() {
766            extent = extent
767                .max(point.x.abs())
768                .max(point.y.abs())
769                .max(point.z.abs());
770        }
771    }
772    extent
773}
774
775/// A colinear control net is EXACT proof of a straight curve (convex-hull
776/// property), and every straight curve this kernel builds — `make_line`
777/// products through any split/degree change — keeps its net colinear.
778fn control_net_is_colinear(curve: &NurbsCurve) -> bool {
779    let points: Vec<Vec3> = curve
780        .control_points
781        .iter()
782        .filter_map(|control| control.point().ok())
783        .collect();
784    let Some((&first, rest)) = points.split_first() else {
785        return false;
786    };
787    let tolerance = RESOLVE_TOLERANCE * (1.0 + control_net_extent(curve));
788    let Some(direction) = rest
789        .iter()
790        .map(|point| point.sub(first))
791        .max_by(|a, b| a.length().total_cmp(&b.length()))
792        .and_then(|chord| chord.normalized().ok())
793    else {
794        return false;
795    };
796    points.iter().all(|point| {
797        let offset = point.sub(first);
798        offset.sub(direction.scale(offset.dot(direction))).length() <= tolerance
799    })
800}
801
802/// Straight edge → its infinite carrier line, oriented start→end over the
803/// trimmed span, origin at the chord midpoint.
804fn straight_edge_line(record: &EdgeRecord) -> Result<Option<SelectionGeometry>, String> {
805    if !control_net_is_colinear(&record.curve) {
806        return Ok(None);
807    }
808    let start = record.curve.evaluate(record.t0)?;
809    let end = record.curve.evaluate(record.t1)?;
810    let chord = end.sub(start);
811    if chord.length() <= RESOLVE_TOLERANCE * (1.0 + control_net_extent(&record.curve)) {
812        // Zero-length trim of a straight curve — nothing to orient by.
813        return Ok(None);
814    }
815    Ok(Some(SelectionGeometry::Line {
816        origin: start.add(end).scale(0.5),
817        direction: chord.normalized()?,
818    }))
819}
820
821/// Circular/arc edge → center + axis + radius: a candidate circle from three
822/// interior samples (distinct even on a closed full circle), then VERIFIED at
823/// [`CIRCLE_VERIFY_SAMPLES`] points — equidistant from the center and coplanar
824/// — so ellipses, splines, and helices fail cleanly while exact kernel arcs
825/// pass at machine precision.
826fn circular_edge_circle(record: &EdgeRecord) -> Result<Option<SelectionGeometry>, String> {
827    let span = record.t1 - record.t0;
828    if !(span > 0.0) {
829        return Ok(None);
830    }
831    let at = |fraction: f64| record.curve.evaluate(record.t0 + span * fraction);
832    let (a, b, c) = (at(1.0 / 6.0)?, at(0.5)?, at(5.0 / 6.0)?);
833    let Some(center) = crate::analytic_surface::circumcenter(a, b, c) else {
834        return Ok(None);
835    };
836    // Right-hand rule along the increasing-parameter direction.
837    let Ok(axis) = b.sub(a).cross(c.sub(b)).normalized() else {
838        return Ok(None);
839    };
840    let radius = a.sub(center).length();
841    let tolerance = RESOLVE_TOLERANCE * (1.0 + control_net_extent(&record.curve));
842    for step in 0..=CIRCLE_VERIFY_SAMPLES {
843        let point = at(step as f64 / CIRCLE_VERIFY_SAMPLES as f64)?;
844        let delta = point.sub(center);
845        if (delta.length() - radius).abs() > tolerance || delta.dot(axis).abs() > tolerance {
846            return Ok(None);
847        }
848    }
849    Ok(Some(SelectionGeometry::Circle {
850        center,
851        axis,
852        radius,
853    }))
854}
855
856// ---------------------------------------------------------------------------
857// Tests
858// ---------------------------------------------------------------------------
859