Skip to main content

brep_kernel/feature_pipeline/assembly/
mapping.rs

1//! Constraint → mate mapping SHARED MACHINERY: selection-ref resolution
2//! against the scene's component registry, the [`map_constraint`] dispatch,
3//! the explicit mate facing (`facing`: aligned / opposed, see
4//! [`effective_align`]), first-solve initialization, and the rigid-pose math
5//! shared with the write-back lane. The PER-TYPE `map` functions live with
6//! their constraints ([`super::constraints`], one module per type).
7//!
8//! # Selection-ref conventions (cross-lane contract)
9//!
10//! - Face/edge refs are the NAMESPACED scene names (`ACOMP2:Extrude1_top`).
11//! - A whole-component ref is the bare feature id (`ACOMP2`), or a nested
12//!   chain (`ACOMP3:ACOMP1`) owned by the OUTERMOST component at this level.
13//! - A vertex ref is `{solidName}@x,y,z` with the position in COMPONENT-LOCAL
14//!   coordinates (stable under pose changes; kernel vertices carry no names).
15//!   The picker builds it as `world_pick · component_transform⁻¹`.
16
17use super::ConstraintEntry;
18use crate::feature_pipeline::component::ComponentRecord;
19use crate::feature_pipeline::{Env, SceneMap};
20use crate::{
21    resolve_edge_selection, resolve_face_selection, resolve_named_selection,
22    resolve_vertex_selection, AffineTransform, MateAlign, MateKind, SelectionGeometry, Vec3,
23};
24
25/// A per-constraint failure carrying the requirements-§5 status word.
26#[derive(Debug, Clone)]
27pub(super) struct ConstraintFailure {
28    pub status: &'static str,
29    pub message: String,
30}
31
32impl ConstraintFailure {
33    pub fn new(status: &'static str, message: impl Into<String>) -> Self {
34        Self {
35            status,
36            message: message.into(),
37        }
38    }
39    pub(super) fn unsupported(message: impl Into<String>) -> Self {
40        Self::new("unsupported-selection", message)
41    }
42    pub(super) fn invalid(message: impl Into<String>) -> Self {
43        Self::new("invalid-selection", message)
44    }
45}
46
47// ===========================================================================
48// Element resolution
49// ===========================================================================
50
51/// One resolved constraint element: the owning component plus the analytic
52/// frame in WORLD space (as stored on the resident, world-posed solids) and in
53/// the component's LOCAL space (the solver's mate-input space).
54#[derive(Debug, Clone)]
55pub(super) struct ResolvedElement {
56    pub name: String,
57    pub component: String,
58    pub world: SelectionGeometry,
59    pub local: SelectionGeometry,
60    pub transform: AffineTransform,
61    /// An edge selection's carrier over its range, component-LOCAL — what the
62    /// curve mates (path) follow. `None` for anything but an edge.
63    pub curve: Option<crate::MateCurve>,
64    /// The edge is neither straight nor circular: it resolves (as its chord
65    /// midpoint) only so a curve mate can follow it; every other type refuses
66    /// it with `refusal`, as before.
67    pub freeform: Option<ConstraintFailure>,
68}
69
70/// Resolve one selection ref (conventions in the module doc). Every failure is
71/// a typed status — never a panic; non-component geometry is fenced here
72/// (requirements: solids from ordinary modeling features do not participate).
73pub(super) fn resolve_element(
74    scene: &SceneMap,
75    name: &str,
76) -> Result<ResolvedElement, ConstraintFailure> {
77    let record = scene.owning_component(name).ok_or_else(|| {
78        ConstraintFailure::invalid(format!(
79            "selection '{name}' does not belong to an assembly component — only component geometry participates in constraints"
80        ))
81    })?;
82    if let Some(follow) = &record.pattern {
83        return Err(ConstraintFailure::invalid(format!(
84            "'{}' is instance {} of pattern {}: it follows its seed {} and takes no mates of its own — mate {} instead",
85            record.id, follow.key, follow.pattern_id, follow.seed, follow.seed
86        )));
87    }
88    let curve = edge_curve(scene, name, &record.transform)?;
89    let (world, freeform) = match resolve_world_geometry(scene, name, record) {
90        Ok(world) => (world, None),
91        Err(failure) if failure.status == "unsupported-selection" && curve.is_some() => {
92            let chord = curve.as_ref().and_then(|c| {
93                let mid = c.curve.evaluate(0.5 * (c.t0 + c.t1)).ok()?;
94                Some(record.transform.point(mid))
95            });
96            match chord {
97                Some(position) => (SelectionGeometry::Point { position }, Some(failure)),
98                None => return Err(failure),
99            }
100        }
101        Err(failure) => return Err(failure),
102    };
103    let inverse = record.transform.rigid_inverse().map_err(|error| {
104        ConstraintFailure::new(
105            "error",
106            format!("component '{}': non-rigid pose: {error}", record.id),
107        )
108    })?;
109    let local = world.transformed(&inverse).map_err(|error| {
110        ConstraintFailure::new("error", format!("selection '{name}': {error}"))
111    })?;
112    Ok(ResolvedElement {
113        curve,
114        freeform,
115        name: name.to_string(),
116        component: record.id.clone(),
117        world,
118        local,
119        transform: record.transform,
120    })
121}
122
123/// An edge selection's carrier over its range, in the component's LOCAL
124/// frame; `None` when `name` is not an edge.
125fn edge_curve(
126    scene: &SceneMap,
127    name: &str,
128    transform: &AffineTransform,
129) -> Result<Option<crate::MateCurve>, ConstraintFailure> {
130    let Some(edge) = scene.resolve_edge(name) else { return Ok(None) };
131    let inverse = transform.rigid_inverse().map_err(ConstraintFailure::invalid)?;
132    crate::with_registered_solid_str(edge.handle, |solid| {
133        let Some(record) = solid.edges.iter().find(|record| record.id == edge.edge_id) else {
134            return Ok(None);
135        };
136        let curve = crate::transform_topology::transform_curve(&record.curve, inverse)?;
137        Ok(Some(crate::MateCurve { curve, t0: record.t0, t1: record.t1 }))
138    })
139    .map_err(ConstraintFailure::invalid)
140}
141
142fn resolve_world_geometry(
143    scene: &SceneMap,
144    name: &str,
145    record: &ComponentRecord,
146) -> Result<SelectionGeometry, ConstraintFailure> {
147    // Vertex ref: `{solid}@x,y,z`, component-local position.
148    if let Some((solid_name, coords)) = name.split_once('@') {
149        let handle = scene.resolve_solid(solid_name).ok_or_else(|| {
150            ConstraintFailure::invalid(format!("vertex ref '{name}': unknown solid '{solid_name}'"))
151        })?;
152        let local = parse_triple(coords).ok_or_else(|| {
153            ConstraintFailure::invalid(format!(
154                "vertex ref '{name}': position must be 'x,y,z' numbers"
155            ))
156        })?;
157        let world_query = record.transform.point(local);
158        return crate::with_registered_solid_str(handle, |solid| {
159            Ok(resolve_vertex_selection(solid, world_query))
160        })
161        .map_err(ConstraintFailure::invalid)?
162        .map_err(|error| ConstraintFailure::new(error.status(), error.to_string()));
163    }
164
165    // Whole-component ref: the bare id, or a nested `ACOMP3:ACOMP1` chain
166    // (representative point over the OUTER record's members under that
167    // prefix). `owning_component` already proved the outermost segment.
168    if scene.namespace.names_component(name) {
169        let prefix = format!("{name}:");
170        let members: Vec<(String, u32)> = scene
171            .component_solids(&record.id)
172            .into_iter()
173            .filter(|(member, _)| record.id == name || member.starts_with(&prefix))
174            .collect();
175        if members.is_empty() {
176            return Err(ConstraintFailure::invalid(format!(
177                "component ref '{name}' has no member solids"
178            )));
179        }
180        return component_point(&members);
181    }
182
183    // Named topology: faces first, then edges (the deterministic-naming scheme
184    // never collides across the kinds).
185    if let Some(face) = scene.resolve_face(name) {
186        return crate::with_registered_solid_str(face.handle, |solid| {
187            Ok(resolve_face_selection(solid, face.face_id))
188        })
189        .map_err(ConstraintFailure::invalid)?
190        .map_err(|error| ConstraintFailure::new(error.status(), error.to_string()));
191    }
192    if let Some(edge) = scene.resolve_edge(name) {
193        return crate::with_registered_solid_str(edge.handle, |solid| {
194            Ok(resolve_edge_selection(solid, edge.edge_id))
195        })
196        .map_err(ConstraintFailure::invalid)?
197        .map_err(|error| ConstraintFailure::new(error.status(), error.to_string()));
198    }
199    // A member-solid name (rare — the app selects components, not solids):
200    // resolve like a whole-component anchor over that one solid.
201    if let Some(handle) = scene.resolve_solid(name) {
202        return component_point(&[(name.to_string(), handle)]);
203    }
204    // Last resort: an unregistered per-solid name (should not happen for an
205    // intact scene) — search the component's members by exact name.
206    for (_member, handle) in scene.component_solids(&record.id) {
207        let found = crate::with_registered_solid_str(handle, |solid| {
208            Ok(resolve_named_selection(solid, name).ok())
209        })
210        .map_err(ConstraintFailure::invalid)?;
211        if let Some(geometry) = found {
212            return Ok(geometry);
213        }
214    }
215    Err(ConstraintFailure::invalid(format!(
216        "selection '{name}' not found in the scene"
217    )))
218}
219
220/// Representative anchor of a solid set: center of the aggregate AABB over
221/// topology vertices + surface control-point hulls (bounds the exact surfaces
222/// without tessellation — same construction as `resolve_component_point`,
223/// evaluated per resident member under one short borrow each).
224fn component_point(members: &[(String, u32)]) -> Result<SelectionGeometry, ConstraintFailure> {
225    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
226    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
227    let mut any = false;
228    for (member, handle) in members {
229        let (lo, hi, non_empty) = crate::with_registered_solid_str(*handle, |solid| {
230            let mut lo = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
231            let mut hi = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
232            let mut non_empty = false;
233            let mut include = |point: Vec3| {
234                lo = Vec3::new(lo.x.min(point.x), lo.y.min(point.y), lo.z.min(point.z));
235                hi = Vec3::new(hi.x.max(point.x), hi.y.max(point.y), hi.z.max(point.z));
236                non_empty = true;
237            };
238            for vertex in &solid.vertices {
239                include(vertex.point);
240            }
241            for shell in &solid.shells {
242                for face in &shell.faces {
243                    for row in &face.surface.control_points {
244                        for control in row {
245                            include(control.point()?);
246                        }
247                    }
248                }
249            }
250            Ok((lo, hi, non_empty))
251        })
252        .map_err(|error| {
253            ConstraintFailure::invalid(format!("component member '{member}': {error}"))
254        })?;
255        if non_empty {
256            low = Vec3::new(low.x.min(lo.x), low.y.min(lo.y), low.z.min(lo.z));
257            high = Vec3::new(high.x.max(hi.x), high.y.max(hi.y), high.z.max(hi.z));
258            any = true;
259        }
260    }
261    if !any {
262        return Err(ConstraintFailure::invalid(
263            "component has no geometry to anchor",
264        ));
265    }
266    Ok(SelectionGeometry::Point {
267        position: low.add(high).scale(0.5),
268    })
269}
270
271fn parse_triple(coords: &str) -> Option<Vec3> {
272    let mut parts = coords.split(',').map(str::trim);
273    let x = parts.next()?.parse::<f64>().ok()?;
274    let y = parts.next()?.parse::<f64>().ok()?;
275    let z = parts.next()?.parse::<f64>().ok()?;
276    if parts.next().is_some() {
277        return None;
278    }
279    Some(Vec3::new(x, y, z))
280}
281
282// ===========================================================================
283// Mate construction
284// ===========================================================================
285
286/// One mapped mate: local geometry sides keyed by owning component id.
287#[derive(Debug, Clone)]
288pub(super) struct MappedMate {
289    pub body_a: String,
290    pub body_b: String,
291    /// The third component a three-body mate reads (a symmetric mate's
292    /// mirror plane); `None` for every two-body mate.
293    pub body_c: Option<String>,
294    pub kind: MateKind,
295}
296
297/// A constraint's whole mapping: its mates, the `inputParams` /
298/// `persistentData` write-backs to commit ON SOLVE SUCCESS (first-solve
299/// initialization), and the current measured value for the overlay label.
300#[derive(Debug, Clone, Default)]
301pub(super) struct MappedConstraint {
302    pub mates: Vec<MappedMate>,
303    pub pending_params: Vec<(String, serde_json::Value)>,
304    pub pending_persistent: Vec<(String, serde_json::Value)>,
305    /// `(value, unit)` — the measured current quantity (`"mm"` model units or
306    /// `"deg"`), when the type has a natural scalar.
307    pub measured: Option<(f64, &'static str)>,
308    /// The evaluated target (distance/angle), for the overlay label suffix.
309    pub target: Option<f64>,
310    /// Persistent angle reference in world space for the viewport arc.
311    pub angle_axis: Option<Vec3>,
312    /// The element ROLES a multi-element type inferred, as index groups into
313    /// the entry's `elements` (center: `[width pair, tab]`) — the overlay lane
314    /// draws by role, not by pick order. Empty for the pairing types.
315    pub groups: Vec<Vec<usize>>,
316    /// A per-type sentence appended to the solved status message (center
317    /// names the roles it inferred: "X centred between Y and Z"), so the
318    /// panel shows what the constraint decided from the selection.
319    pub note: Option<String>,
320}
321
322/// Map one validated, resolved constraint onto kernel mates. `resolved` is
323/// the entry's elements in entry order (the lifecycle has already checked the
324/// count against the type's range). `persistent` is the entry's live
325/// `persistentData`; an unset `facing` is captured into `inputParams` here
326/// ([`effective_align`]).
327pub(super) fn map_constraint(
328    entry: &mut ConstraintEntry,
329    resolved: &[ResolvedElement],
330    env: &Env,
331) -> Result<MappedConstraint, ConstraintFailure> {
332    // The pairing types take exactly two; center reads the whole slice.
333    let pair = || -> Result<(&ResolvedElement, &ResolvedElement), ConstraintFailure> {
334        match resolved {
335            [a, b] => Ok((a, b)),
336            _ => Err(ConstraintFailure::invalid(format!(
337                "{} takes exactly two elements ({} given)",
338                entry.constraint_type,
339                resolved.len()
340            ))),
341        }
342    };
343    // A freeform (spline) edge resolves only for the curve-following types.
344    if !matches!(entry.constraint_type.as_str(), "path" | "cam") {
345        if let Some(refusal) = resolved.iter().find_map(|element| element.freeform.clone()) {
346            return Err(refusal);
347        }
348    }
349    match entry.constraint_type.as_str() {
350        "coincident" => {
351            let (a, b) = pair()?;
352            super::constraints::coincident::map_entry(entry, a, b)
353        }
354        "touch_align" => {
355            let (a, b) = pair()?;
356            super::constraints::touch_align::map(entry, a, b)
357        }
358        "parallel" => {
359            let (a, b) = pair()?;
360            super::constraints::parallel::map(entry, a, b)
361        }
362        "distance" => {
363            let (a, b) = pair()?;
364            let mut mapped = super::constraints::distance::map(entry, a, b, env)?;
365            super::constraints::apply_limit(entry, &mut mapped, env, |value| value)?;
366            Ok(mapped)
367        }
368        "angle" => {
369            let (a, b) = pair()?;
370            let mut mapped = super::constraints::angle::map(entry, a, b, env)?;
371            let exterior = entry.flag("exteriorAngle");
372            super::constraints::apply_limit(entry, &mut mapped, env, |value| {
373                if exterior { 180.0 - value } else { value }
374            })?;
375            Ok(mapped)
376        }
377        "concentric" => {
378            let (a, b) = pair()?;
379            super::constraints::concentric::map(entry, a, b)
380        }
381        "perpendicular" => pair().and_then(|(a, b)| super::constraints::perpendicular::map(a, b)),
382        "tangent" => pair().and_then(|(a, b)| super::constraints::tangent::map(a, b)),
383        "center" => super::constraints::center::map(entry, resolved),
384        "symmetric" => super::constraints::symmetric::map(resolved),
385        "gear" => {
386            let (a, b) = pair()?;
387            super::constraints::gear::map(entry, a, b, env)
388        }
389        "rack_pinion" => {
390            let (a, b) = pair()?;
391            super::constraints::rack_pinion::map(entry, a, b, env)
392        }
393        "screw" => {
394            let (a, b) = pair()?;
395            super::constraints::screw::map(entry, a, b, env)
396        }
397        "path" => {
398            let (a, b) = pair()?;
399            super::constraints::path::map(entry, a, b, env)
400        }
401        "slot" => super::constraints::slot::map(entry, resolved, env),
402        "cam" => {
403            let (a, b) = pair()?;
404            super::constraints::cam::map(entry, a, b, env)
405        }
406        other => Err(ConstraintFailure::new(
407            "error",
408            format!("Unknown constraint type: {other}"),
409        )),
410    }
411}
412
413pub(super) fn mate(a: &ResolvedElement, b: &ResolvedElement, kind: MateKind) -> MappedMate {
414    MappedMate {
415        body_a: a.component.clone(),
416        body_b: b.component.clone(),
417        body_c: None,
418        kind,
419    }
420}
421
422/// The world direction a selection carries, if any (plane normal, axis/line
423/// direction, circle axis).
424pub(super) fn direction_of(geometry: &SelectionGeometry) -> Option<Vec3> {
425    match *geometry {
426        SelectionGeometry::Plane { normal, .. } => Some(normal),
427        SelectionGeometry::Axis { direction, .. } | SelectionGeometry::Line { direction, .. } => {
428            Some(direction)
429        }
430        SelectionGeometry::Circle { axis, .. } => Some(axis),
431        SelectionGeometry::Sphere { .. } | SelectionGeometry::Point { .. } => None,
432    }
433}
434
435pub(super) fn local_point(element: &ResolvedElement) -> [f64; 3] {
436    let p = element.local.representative_point();
437    [p.x, p.y, p.z]
438}
439
440pub(super) fn require_direction(element: &ResolvedElement) -> Result<(Vec3, Vec3), ConstraintFailure> {
441    let world = direction_of(&element.world).ok_or_else(|| {
442        ConstraintFailure::unsupported(format!(
443            "selection '{}' carries no direction (needs a planar face, straight edge, axis face, or circular edge)",
444            element.name
445        ))
446    })?;
447    let local = direction_of(&element.local).expect("local mirrors world kind");
448    Ok((world, local))
449}
450
451pub(super) fn require_axis(element: &ResolvedElement) -> Result<crate::MateAxis, ConstraintFailure> {
452    element.local.mate_axis().ok_or_else(|| {
453        ConstraintFailure::unsupported(format!(
454            "selection '{}' carries no axis (needs a cylindrical/conical face, circular edge, or straight edge)",
455            element.name
456        ))
457    })
458}
459
460pub(super) fn require_plane(element: &ResolvedElement) -> Result<crate::MatePlane, ConstraintFailure> {
461    element.local.mate_plane().ok_or_else(|| {
462        ConstraintFailure::unsupported(format!(
463            "selection '{}' is not a planar face",
464            element.name
465        ))
466    })
467}
468
469/// The order-independent selection-pair signature (duplicate detection AND the
470/// orientation-preference recapture key).
471pub(super) fn pair_signature(elements: &[String]) -> String {
472    let mut pair: Vec<&str> = elements.iter().map(String::as_str).collect();
473    pair.sort_unstable();
474    pair.join("\n")
475}
476
477/// The mate's facing: the constraint's own `facing` param (`aligned` /
478/// `opposed`, a dropdown in its form; Flip toggles it). Nothing hidden decides
479/// it (owner 2026-11-05).
480///
481/// A constraint with no `facing` yet — a new one, or one saved before it
482/// existed — takes the facing it is assembled with: the old rule, the
483/// `preferredOppose` cache (or, without one, the current directions) XOR its
484/// `legacy` toggle (`reverse` / `opposeNormals`), so no part moves. That
485/// facing is then WRITTEN into `facing` and the hidden pieces are dropped:
486/// from the first solve on, the form shows what the mate holds.
487pub(super) fn effective_align(
488    entry: &mut ConstraintEntry,
489    dir_a: Vec3,
490    dir_b: Vec3,
491    legacy: &str,
492) -> MateAlign {
493    let dot = dir_a.dot(dir_b);
494    entry.set_persistent("lastOrientationDot", serde_json::json!(dot));
495    match entry.input_params.get(FACING).and_then(|value| value.as_str()) {
496        Some(OPPOSED) => return MateAlign::AntiAligned,
497        Some(_) => return MateAlign::Aligned,
498        None => {}
499    }
500    let signature = pair_signature(&entry.elements());
501    let cached = entry
502        .persistent("preferredOpposeSignature")
503        .and_then(|value| value.as_str())
504        .map(|stored| stored == signature)
505        .unwrap_or(false)
506        .then(|| entry.persistent("preferredOppose").and_then(|v| v.as_bool()))
507        .flatten();
508    let opposed = cached.unwrap_or(dot < 0.0) != entry.flag(legacy);
509    if let Some(params) = entry.input_params.as_object_mut() {
510        params.remove(legacy);
511        params.insert(FACING.into(), serde_json::json!(if opposed { OPPOSED } else { ALIGNED }));
512    }
513    entry.remove_persistent("preferredOppose");
514    entry.remove_persistent("preferredOpposeSignature");
515    if opposed {
516        MateAlign::AntiAligned
517    } else {
518        MateAlign::Aligned
519    }
520}
521
522/// The facing param and its two values.
523pub(super) const FACING: &str = "facing";
524pub(super) const ALIGNED: &str = "aligned";
525pub(super) const OPPOSED: &str = "opposed";
526
527/// The `facing` schema field: a dropdown of the two facings; unset (null)
528/// on a new constraint, which takes the facing it is assembled with.
529pub(super) fn facing_field(hint: &str) -> serde_json::Value {
530    serde_json::json!({
531        "type": "options",
532        "options": [ALIGNED, OPPOSED],
533        "default_value": null,
534        "label": "Facing",
535        "hint": hint,
536    })
537}
538
539
540
541
542
543/// First-solve initialization: when `flag_key` is not yet
544/// set in `persistentData` and the constraint was created WITHOUT `param_key`,
545/// the target ADOPTS the current measurement and both the param and the flag
546/// are queued for commit on solve success. A value given at creation (a
547/// script, the MCP, a dialog) is what was asked for: it drives the parts
548/// there, and only the flag is queued.
549#[allow(clippy::type_complexity)]
550pub(super) fn first_solve_target(
551    entry: &ConstraintEntry,
552    param_key: &str,
553    flag_key: &str,
554    configured: f64,
555    current: f64,
556) -> (
557    f64,
558    (Vec<(String, serde_json::Value)>, Vec<(String, serde_json::Value)>),
559) {
560    let initialized = entry
561        .persistent(flag_key)
562        .and_then(|value| value.as_bool())
563        .unwrap_or(false);
564    let given = entry.input_params.get(param_key).is_some_and(|value| !value.is_null());
565    if initialized {
566        (configured, (Vec::new(), Vec::new()))
567    } else if given {
568        (configured, (Vec::new(), vec![(flag_key.to_string(), serde_json::Value::Bool(true))]))
569    } else {
570        (
571            current,
572            (
573                vec![(param_key.to_string(), serde_json::json!(current))],
574                vec![(flag_key.to_string(), serde_json::Value::Bool(true))],
575            ),
576        )
577    }
578}
579
580
581
582
583
584// ===========================================================================
585// World-space measures (overlay labels + tolerance scaling)
586// ===========================================================================
587
588pub(super) fn angle_between_deg(a: Vec3, b: Vec3) -> f64 {
589    let denominator = a.length() * b.length();
590    if denominator <= 0.0 {
591        return 0.0;
592    }
593    (a.dot(b) / denominator).clamp(-1.0, 1.0).acos().to_degrees()
594}
595
596pub(super) fn point_line_distance(point: Vec3, origin: Vec3, direction: Vec3) -> f64 {
597    let offset = point.sub(origin);
598    let along = offset.dot(direction) / direction.dot(direction).max(1e-300);
599    offset.sub(direction.scale(along)).length()
600}
601
602/// Closest approach between two infinite lines (point-to-line when nearly
603/// parallel — the skew formula degenerates there).
604pub(super) fn line_line_distance(oa: Vec3, da: Vec3, ob: Vec3, db: Vec3) -> f64 {
605    let cross = da.cross(db);
606    let denominator = cross.length();
607    if denominator < 1e-9 * da.length().max(db.length()).max(1.0) {
608        return point_line_distance(ob, oa, da);
609    }
610    (ob.sub(oa).dot(cross) / denominator).abs()
611}
612
613/// The largest coordinate magnitude a constraint's resolved elements span —
614/// the model-scale estimate behind the satisfied-vs-adjusted tolerance.
615pub(super) fn elements_scale(elements: &[ResolvedElement]) -> f64 {
616    let mut scale = 1.0f64;
617    for point in elements.iter().map(|element| element.world.representative_point()) {
618        scale = scale
619            .max(point.x.abs())
620            .max(point.y.abs())
621            .max(point.z.abs());
622    }
623    scale
624}
625
626// ===========================================================================
627// Rigid-pose math (bodies + write-back)
628// ===========================================================================
629
630/// Unit quaternion `[w,x,y,z]` from the rotation rows of a rigid transform
631/// (Shepperd's method — numerically stable for every sign pattern).
632pub(super) fn matrix_to_quaternion(transform: &AffineTransform) -> [f64; 4] {
633    let m = &transform.elements;
634    let (r00, r01, r02) = (m[0], m[1], m[2]);
635    let (r10, r11, r12) = (m[4], m[5], m[6]);
636    let (r20, r21, r22) = (m[8], m[9], m[10]);
637    let trace = r00 + r11 + r22;
638    let q = if trace > 0.0 {
639        let s = (trace + 1.0).sqrt() * 2.0;
640        [s / 4.0, (r21 - r12) / s, (r02 - r20) / s, (r10 - r01) / s]
641    } else if r00 > r11 && r00 > r22 {
642        let s = (1.0 + r00 - r11 - r22).sqrt() * 2.0;
643        [(r21 - r12) / s, s / 4.0, (r01 + r10) / s, (r02 + r20) / s]
644    } else if r11 > r22 {
645        let s = (1.0 + r11 - r00 - r22).sqrt() * 2.0;
646        [(r02 - r20) / s, (r01 + r10) / s, s / 4.0, (r12 + r21) / s]
647    } else {
648        let s = (1.0 + r22 - r00 - r11).sqrt() * 2.0;
649        [(r10 - r01) / s, (r02 + r20) / s, (r12 + r21) / s, s / 4.0]
650    };
651    normalize_quaternion(q)
652}
653
654pub(super) fn normalize_quaternion(q: [f64; 4]) -> [f64; 4] {
655    let norm = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();
656    if norm <= 0.0 || !norm.is_finite() {
657        return [1.0, 0.0, 0.0, 0.0];
658    }
659    [q[0] / norm, q[1] / norm, q[2] / norm, q[3] / norm]
660}
661
662/// Rigid transform from a solver pose. The quaternion is RENORMALIZED first —
663/// the write-back contract (`component.rs` rejects non-rigid at 1e-8; a unit
664/// quaternion's matrix is orthonormal to machine precision).
665pub(super) fn pose_to_transform(
666    rotation: [f64; 4],
667    translation: [f64; 3],
668) -> Result<AffineTransform, String> {
669    let [w, x, y, z] = normalize_quaternion(rotation);
670    AffineTransform::new([
671        1.0 - 2.0 * (y * y + z * z), 2.0 * (x * y - w * z), 2.0 * (x * z + w * y), translation[0],
672        2.0 * (x * y + w * z), 1.0 - 2.0 * (x * x + z * z), 2.0 * (y * z - w * x), translation[1],
673        2.0 * (x * z - w * y), 2.0 * (y * z + w * x), 1.0 - 2.0 * (x * x + y * y), translation[2],
674        0.0, 0.0, 0.0, 1.0,
675    ])
676}
677
678/// The read-side half of [`transform_to_pose_params`]: `{translate,
679/// rotateEulerDeg}` composed exactly as the ACOMP feature composes it (literal
680/// numbers only — expressions are the feature's business).
681pub fn pose_params_to_transform(pose: &serde_json::Value) -> Result<AffineTransform, String> {
682    let triple = |key: &str| -> Result<[f64; 3], String> {
683        let values = pose.get(key).and_then(|value| value.as_array());
684        let Some(values) = values else { return Ok([0.0; 3]) };
685        let mut out = [0.0; 3];
686        for (slot, value) in out.iter_mut().zip(values) {
687            *slot = value.as_f64().ok_or_else(|| format!("pose {key}: not a number"))?;
688        }
689        Ok(out)
690    };
691    let translate = triple("translate")?;
692    let degrees = triple("rotateEulerDeg")?;
693    AffineTransform::new(crate::feature_pipeline::features::common::compose_trs_matrix(
694        translate,
695        [degrees[0].to_radians(), degrees[1].to_radians(), degrees[2].to_radians()],
696        [1.0, 1.0, 1.0],
697        [0.0, 0.0, 0.0],
698    ))
699}
700
701/// The generic `inputParams.transform` pose write-back JSON: `{translate,
702/// rotateEulerDeg}` with degrees in the intrinsic `XYZ` order (`R = Rx·Ry·Rz`
703/// — `features::common::compose_trs_matrix`). This is the write-side half of
704/// the ACOMP feature's reader contract (`assembly_component.rs` reads exactly
705/// `transform.translate` + `transform.rotateEulerDeg`; a mismatched key would
706/// silently zero the pose on the next history run).
707///
708/// `pub` (re-exported as `brep_kernel::transform_to_pose_params`) because it is
709/// the ONE matrix → intrinsic-XYZ-Euler-degrees decomposition in the tree — the
710/// solver write-back and the out-of-crate seams that author ACOMP poses share
711/// it rather than re-deriving the convention (and its gimbal-lock branch), which
712/// the readers on the other side (`assembly_component.rs`, `transform_bake`)
713/// would then silently disagree with.
714pub fn transform_to_pose_params(transform: &AffineTransform) -> serde_json::Value {
715    let m = &transform.elements;
716    // R = Rx(a)·Ry(b)·Rz(c) ⇒ m02 = sin b; a = atan2(−m12, m22);
717    // c = atan2(−m01, m00); gimbal lock at |sin b| → 1 pins c = 0.
718    let sb = m[2].clamp(-1.0, 1.0);
719    let (a, b, c) = if sb.abs() < 1.0 - 1e-9 {
720        (
721            (-m[6]).atan2(m[10]),
722            sb.asin(),
723            (-m[1]).atan2(m[0]),
724        )
725    } else {
726        (m[9].atan2(m[5]), sb.asin(), 0.0)
727    };
728    serde_json::json!({
729        "translate": [m[3], m[7], m[11]],
730        "rotateEulerDeg": [a.to_degrees(), b.to_degrees(), c.to_degrees()],
731    })
732}