Skip to main content

brep_render/engine_state/
transform_gizmo.rs

1use super::*;
2
3/// Which of the two gizmos is currently armed for the feature. `Transform` shows
4/// the move/rotate gizmo; `Dimension` shows the on-canvas draggable dimension
5/// annotations (feature-dimensions FD-1). Expanding a feature arms `Dimension`;
6/// the viewport sphere/center toggle flips to `Transform` and back. The two modes
7/// are EXCLUSIVE — the transform gizmo never renders in `Dimension` mode and
8/// vice-versa.
9#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
10pub enum GizmoMode {
11    /// Neither gizmo armed (`feature_id` is `None`).
12    #[default]
13    None,
14    /// The move/rotate transform gizmo is armed.
15    Transform,
16    /// The dimension-annotation gizmo is armed (FD-1).
17    Dimension,
18}
19
20/// The transform-controls gizmo controller state (see the impl block below).
21#[derive(Default)]
22pub struct TransformArm {
23    /// The feature id whose gizmo is armed (for EITHER mode), or `None`
24    /// (disarmed → `mode == None`).
25    pub(super) feature_id: Option<String>,
26    /// Which gizmo is armed for `feature_id` (transform vs dimension). `None`
27    /// exactly when `feature_id` is `None`.
28    pub(super) mode: GizmoMode,
29    /// The live handle drag, captured on pointer-down over a gizmo handle.
30    pub(super) drag: Option<TransformDrag>,
31    /// When the armed subject is ONE SPLINE ANCHOR rather than the feature's
32    /// `transform` param: the anchor index into `persistentData.spline.points`
33    /// of `feature_id` (an SP feature). The same gizmo, press / drag / release
34    /// and live-follow apply; only the pose read and write-back differ (see
35    /// `spline_edit.rs`).
36    pub(super) anchor: Option<usize>,
37    /// When the armed subject is ONE DECLARED CONNECTION POINT: its part-local
38    /// address (`J1.VCC`). Exclusive with `feature_id` — a connection point is
39    /// data, not a feature, so there is no history row to hold — and checked
40    /// FIRST everywhere the pose is read or written, before any lookup that
41    /// goes through the history. See the section at the foot of this file.
42    pub(super) port: Option<String>,
43    /// When the armed subject is a NURBS Solid's CONTROL CAGE: the selected
44    /// points of `feature_id` and the drag's grab snapshot. The gizmo sits at
45    /// the selection's centroid; a drag moves (and turns) every selected
46    /// point. See `cage_edit.rs`.
47    pub(super) cage: Option<super::cage_edit::CageArm>,
48    /// When the armed subject is ONE PICK of a Deform Face: the pick and the
49    /// drag's grab snapshot. A drag moves the pick along its normal. See
50    /// `deform_edit.rs`.
51    pub(super) deform: Option<super::deform_edit::DeformArm>,
52}
53
54/// A grab snapshot for an in-flight transform-gizmo drag: the grabbed handle,
55/// the grab screen point, and the feature's pose AT GRAB. Every drag move
56/// resolves an absolute delta from this grab (against the pinned grab-time
57/// frame) and re-applies it to `start`, so the drag never accumulates error.
58#[derive(Clone, Copy)]
59pub(super) struct TransformDrag {
60    handle: u32,
61    sx: f32,
62    sy: f32,
63    start: TransformPose,
64    /// The delta this drag has resolved SO FAR, as the handle resolved it —
65    /// the readout's source. Taken from the drag rather than differenced out of
66    /// the pose, because the pose is the only thing the two are agreed on: a
67    /// rotation composes onto a quaternion and comes back as an Euler triple
68    /// that a subtraction cannot turn into "42.5 degrees about Y" again. `None`
69    /// until the pointer has actually moved off the grab point.
70    last: Option<TransformDelta>,
71}
72
73/// A TRS pose read from / written to a feature's `inputParams.transform`
74/// (`rotation` in DEGREES, intrinsic XYZ Euler order — the kernel `transform_bake`
75/// convention, `M = T·R·S`).
76#[derive(Clone, Copy, PartialEq, Debug)]
77pub(super) struct TransformPose {
78    pub(super) position: [f64; 3],
79    pub(super) rotation_deg: [f64; 3],
80    pub(super) scale: [f64; 3],
81}
82
83/// A world-space delta shared by feature and component gizmo controllers.
84#[derive(Clone, Copy, PartialEq, Debug)]
85pub(super) enum TransformDelta {
86    /// World-space translation, added to `position`.
87    Translate([f64; 3]),
88    /// World-axis rotation, pre-multiplied onto the pose's orientation.
89    Rotate { axis: [f64; 3], radians: f64 },
90}
91
92/// Decode widget drag JSON; unknown kinds and invalid JSON produce no delta.
93pub(super) fn parse_drag_delta(json: &str) -> Option<TransformDelta> {
94    let value: serde_json::Value = serde_json::from_str(json).ok()?;
95    match value.get("kind").and_then(|k| k.as_str()) {
96        Some("translate") => Some(TransformDelta::Translate(
97            crate::json_support::vec3_or(value.get("world"), [0.0; 3]),
98        )),
99        Some("rotate") => Some(TransformDelta::Rotate {
100            axis: crate::json_support::vec3_or(value.get("axisWorld"), [0.0; 3]),
101            radians: value.get("radians").and_then(|n| n.as_f64()).unwrap_or(0.0),
102        }),
103        _ => None,
104    }
105}
106
107impl EngineState {
108    /// Whether the TRANSFORM gizmo (move/rotate) is armed for ANY feature. False
109    /// in dimension mode — the two ◎ modes are exclusive, so the transform gizmo
110    /// arms/handles never render while dimensions are shown.
111    pub fn transform_armed(&self) -> bool {
112        matches!(self.transform_gizmo.mode, GizmoMode::Transform)
113    }
114
115    /// The transform-gizmo-armed feature id (empty unless in transform mode).
116    pub fn transform_armed_feature(&self) -> String {
117        if self.transform_armed() {
118            self.transform_gizmo.feature_id.clone().unwrap_or_default()
119        } else {
120            String::new()
121        }
122    }
123
124    /// The gizmo as the headed verifier sees it: the mode, the armed feature,
125    /// the spline anchor index when the gizmo sits on one, and `origin` — the
126    /// DRAWN move/rotate widget's frame origin (`null` when no widget is
127    /// drawn), which is the proof a handle is on screen, unlike any
128    /// params-derived pose.
129    pub fn gizmo_state_json(&self) -> String {
130        let mode = match self.transform_gizmo.mode {
131            GizmoMode::None => "none",
132            GizmoMode::Transform => "transform",
133            GizmoMode::Dimension => "dimension",
134        };
135        serde_json::json!({
136            "mode": mode,
137            "armed": self.transform_armed(),
138            "feature": self.transform_gizmo.feature_id,
139            "anchor": self.transform_gizmo.anchor,
140            "portPoint": self.transform_gizmo.port,
141            "cage": self.transform_gizmo.cage.as_ref().map(|cage| cage.selected.clone()),
142            "deformPick": self.transform_gizmo.deform.as_ref().map(|arm| arm.pick),
143            "origin": self.widgets.transform_origin(),
144            // A Transform Face turns about its stored `pivot`, and the gizmo
145            // sits at `pivot + position` — so the two coincide only while the
146            // motion is zero. The moment the user drags, the point the rotation
147            // actually happens about is no longer under the handles and was
148            // nowhere on screen at all. Published so the viewport can mark it.
149            "pivot": self.armed_face_transform_pivot(),
150        })
151        .to_string()
152    }
153
154    /// The armed feature's Transform Face pivot in WORLD space, or `None` when
155    /// the armed feature is not a Transform Face (every other transform feature
156    /// turns about its own origin, which the gizmo is already on).
157    pub fn armed_face_transform_pivot(&self) -> Option<[f64; 3]> {
158        let id = self.transform_gizmo.feature_id.as_deref()?;
159        let index = self.history.index_of(id)?;
160        if !self.is_face_transform_feature(index) {
161            return None;
162        }
163        let params = self.history.feature_params(index)?;
164        let env = brep_kernel::Env::build(&self.history.expressions(), &self.history.configurator()).ok();
165        self.face_transform_pivot(index, &params, env.as_ref())
166    }
167
168    /// What the gizmo drag is WORTH, for the chip the viewport draws on it —
169    /// and, when the motion refused, why it refused, said about the user's
170    /// model rather than about the kernel's internals.
171    ///
172    /// A gizmo drag used to be the one edit in the app that reported nothing:
173    /// the model followed the pointer, the number went into `transform`, the
174    /// form's `Transform` section is collapsed by default, and so the distance
175    /// the user had just dragged appeared NOWHERE on screen. The Extrude
176    /// distance arrow carries its value in a chip on the geometry; this is the
177    /// same answer for the gizmo.
178    ///
179    /// The readout is live in two states, and silent otherwise:
180    ///
181    /// * **while a handle is being dragged** — the distance or angle so far.
182    /// * **while the armed feature is REFUSING** — because that is the state
183    ///   the user is left in after letting go of a refused drag, and it is the
184    ///   state that most needs saying. The gizmo tracks the pointer while the
185    ///   geometry stays at its last good answer, so on a refusal the handles
186    ///   end up somewhere the model is not — measured at 15.4 mm INSIDE the
187    ///   solid — and without this the only signal was a red banner in a dock on
188    ///   the far side of the window from the pointer.
189    ///
190    /// `origin` is where to draw it: the gizmo's own frame origin, which is
191    /// where the pointer is.
192    pub fn transform_readout_json(&self) -> String {
193        let quiet = serde_json::json!({ "active": false }).to_string();
194        if !self.transform_armed() {
195            return quiet;
196        }
197        let Some(origin) = self.widgets.transform_origin() else {
198            return quiet;
199        };
200
201        // The refusal, if this feature is refusing — the armed feature's entry
202        // in the last run's report, re-said around the faces it names.
203        let refusal = self.armed_face_transform_refusal();
204        let drag = self.transform_gizmo.drag.as_ref();
205        let delta = drag.and_then(|d| d.last);
206
207        // Silent unless something is happening: no drag in flight and no
208        // refusal on the board means the model is simply sitting there.
209        if delta.is_none() && refusal.is_none() {
210            return quiet;
211        }
212
213        // What the handle resolved, on the same 0.001 grid the drag stores, so
214        // the chip and the form agree digit for digit.
215        let (kind, label, value, unit, text) = match delta {
216            Some(TransformDelta::Translate(world)) => {
217                let distance = crate::formatting::snap_drag_value(
218                    (world[0] * world[0] + world[1] * world[1] + world[2] * world[2]).sqrt(),
219                );
220                let axis = dominant_axis_label(&world);
221                let shown = crate::formatting::compact_decimal(distance, 3);
222                (
223                    "translate",
224                    axis.to_string(),
225                    distance,
226                    "mm",
227                    format!("{axis}  {shown} mm"),
228                )
229            }
230            Some(TransformDelta::Rotate { axis, radians }) => {
231                let degrees = crate::formatting::snap_drag_value(radians.to_degrees());
232                let label = dominant_axis_label(&axis);
233                let shown = crate::formatting::compact_decimal(degrees, 3);
234                (
235                    "rotate",
236                    label.to_string(),
237                    degrees,
238                    "deg",
239                    format!("{label}  {shown}\u{00b0}"),
240                )
241            }
242            // Refusing, but not mid-drag (the user has let go, or typed the
243            // value): the chip carries the refusal alone.
244            None => ("none", String::new(), 0.0, "", String::new()),
245        };
246
247        let mut out = serde_json::json!({
248            "active": true,
249            "kind": kind,
250            "axis": label,
251            "value": value,
252            "unit": unit,
253            "text": text,
254            "origin": origin,
255            "dragging": drag.is_some(),
256            "refused": refusal.is_some(),
257        });
258        if let Some(refusal) = refusal {
259            out["motion"] = serde_json::json!(refusal.motion);
260            out["reason"] = serde_json::json!(refusal.reason);
261            out["hint"] = serde_json::json!(refusal.hint);
262            out["kernel"] = serde_json::json!(refusal.kernel);
263        }
264        out.to_string()
265    }
266
267    /// The armed feature's refusal, re-said about the model — `None` when it is
268    /// not a Transform Face, or is not refusing. The face names come from the
269    /// feature's own `params.faces`, which is the thing the kernel's message
270    /// does not carry and the app does.
271    fn armed_face_transform_refusal(&self) -> Option<crate::face_transform_help::FaceTransformRefusal> {
272        let id = self.transform_gizmo.feature_id.as_deref()?;
273        let index = self.history.index_of(id)?;
274        if !self.is_face_transform_feature(index) {
275            return None;
276        }
277        let report: serde_json::Value = serde_json::from_str(&self.history_report).ok()?;
278        // The kernel records each failure as `"<feature id>: <message>"`; the
279        // delimiter after the exact id is what stops a shorter id matching a
280        // longer one (`TF1` vs `TF10`).
281        let prefix = format!("{id}: ");
282        let message = report
283            .get("featureErrors")?
284            .as_array()?
285            .iter()
286            .filter_map(serde_json::Value::as_str)
287            .find(|entry| entry.starts_with(&prefix))
288            .map(|entry| &entry[prefix.len()..])?;
289        let params = self.history.feature_params(index)?;
290        let faces = brep_kernel::reference_names(params.get("faces"));
291        let facts = crate::face_transform_help::RefusalFacts::from_report(&report, id);
292        Some(crate::face_transform_help::explain_refusal(message, facts, &faces))
293    }
294
295    /// Whether the TRANSFORM gizmo is armed for THIS feature.
296    pub fn transform_armed_for(&self, feature_id: &str) -> bool {
297        self.transform_armed() && self.transform_gizmo.feature_id.as_deref() == Some(feature_id)
298    }
299
300    /// Arm the TRANSFORM gizmo for `feature_id` and feed it at the feature's
301    /// transform frame. Re-arming a different feature moves the gizmo to it.
302    /// Clears any dimension overlay (the modes are exclusive).
303    ///
304    /// An ACOMP (assembly component) feature ROUTES to the component Move gizmo
305    /// instead: its `transform` is the component pose (`{translate,
306    /// rotateEulerDeg}`, a different shape), its gizmo attaches at the member
307    /// bbox center, commits on release, and refuses fixed instances — the
308    /// generic position/rotationEuler gizmo must never write its keys into an
309    /// ACOMP's params. This covers the history panel's arm-on-expand path too.
310    pub fn arm_transform(&mut self, feature_id: &str) {
311        let is_acomp = self
312            .history
313            .index_of(feature_id)
314            .and_then(|index| self.history.feature_type(index))
315            .is_some_and(|ty| super::components::is_acomp_feature_type(&ty));
316        if is_acomp {
317            self.component_move_arm(feature_id);
318            return;
319        }
320        self.component_move_reset();
321        self.transform_gizmo.feature_id = Some(feature_id.to_string());
322        self.transform_gizmo.mode = GizmoMode::Transform;
323        self.transform_gizmo.drag = None;
324        self.transform_gizmo.anchor = None;
325        self.transform_gizmo.port = None;
326        self.transform_gizmo.cage = None;
327        self.transform_gizmo.deform = None;
328        self.clear_feature_dimension_overlay();
329        self.sync_transform_gizmo();
330    }
331
332    /// Disarm: hide BOTH gizmos + drop any in-flight drag. Also resets the
333    /// component Move gizmo (the widget slot is shared, so a disarm clears
334    /// whichever controller was feeding it).
335    pub fn disarm_transform(&mut self) {
336        self.component_move_reset();
337        self.transform_gizmo.feature_id = None;
338        self.transform_gizmo.mode = GizmoMode::None;
339        self.transform_gizmo.drag = None;
340        self.transform_gizmo.anchor = None;
341        self.transform_gizmo.port = None;
342        self.transform_gizmo.cage = None;
343        self.transform_gizmo.deform = None;
344        let _ = self.widgets.set_transform_json("null");
345        self.clear_feature_dimension_overlay();
346        self.dirty = true;
347    }
348
349    /// The armed feature's current TRS pose (from its `inputParams.transform`),
350    /// or `None` when disarmed / the feature vanished.
351    fn armed_pose(&self) -> Option<TransformPose> {
352        // A connection point has no history row, so this must come before
353        // every lookup that needs one.
354        if let Some(address) = self.transform_gizmo.port.clone() {
355            return self.port_point_pose(&address);
356        }
357        let id = self.transform_gizmo.feature_id.as_deref()?;
358        let pmi_annotation = {
359            let state = self.pmi_state_shared();
360            state
361                .find_annotation(id)
362                .map(|(view, annotation)| (view.id.clone(), annotation.kind.clone(), annotation.params.clone()))
363        };
364        if let Some((view_id, kind, params)) = pmi_annotation {
365            if self.pmi_active_view.as_deref() != Some(view_id.as_str()) {
366                return None;
367            }
368            if let Some(row) = self.pmi_report.as_ref().and_then(|r| r.annotation(id)) {
369                // Part-way through playback the step's gizmo sits where its step
370                // has brought its bodies.
371                let fraction = self.explode_step_of(id).map_or(1.0, |step| self.explode_fraction(step));
372                if let brep_kernel::PmiGeometry::Explode {
373                    center,
374                    translate,
375                    rotate_deg,
376                    scale,
377                    ..
378                } = &super::exploded_ops::explode_at(&row.geometry, fraction)
379                {
380                    return Some(TransformPose {
381                        position: std::array::from_fn(|i| center[i] + translate[i]),
382                        rotation_deg: *rotate_deg,
383                        scale: *scale,
384                    });
385                }
386            }
387            // An explode step the kernel has not laid out (its targets are
388            // still in the picker, or the run has not landed): the gizmo
389            // stands on what the step is about to move, so the controls are
390            // there from the first pick, before Done commits it.
391            if kind == "explode" {
392                let center = self.pmi_explode_live_center(id)?;
393                let transform = params.get("transform");
394                let position = read_pose_vec3(None, transform, "position", [0.0; 3]);
395                return Some(TransformPose {
396                    position: std::array::from_fn(|axis| center[axis] + position[axis]),
397                    rotation_deg: read_pose_vec3(None, transform, "rotationEuler", [0.0; 3]),
398                    scale: read_pose_vec3(None, transform, "scale", [1.0; 3]),
399                });
400            }
401            return None;
402        }
403        let index = self.history.index_of(id)?;
404        if self.transform_gizmo.cage.is_some() {
405            // A control cage: the selection's centroid, or the live drag pose
406            // (see `cage_edit.rs`).
407            return self.cage_pose();
408        }
409        if self.transform_gizmo.deform.is_some() {
410            // A Deform Face pick: its target, or the live drag pose (see
411            // `deform_edit.rs`).
412            return self.deform_pose();
413        }
414        if let Some(anchor) = self.transform_gizmo.anchor {
415            // A spline anchor: its position + the intrinsic-XYZ Euler of its
416            // stored axis triad (see `spline_edit.rs`).
417            let (position, rotation_deg) = self.spline_anchor_pose(index, anchor)?;
418            return Some(TransformPose {
419                position,
420                rotation_deg,
421                scale: [1.0, 1.0, 1.0],
422            });
423        }
424        let params = self.history.feature_params(index)?;
425        let transform = params.get("transform");
426        // Build the history's expression environment ONCE for the vectors: a
427        // transform or pivot component may be an expression string.
428        let env =
429            brep_kernel::Env::build(&self.history.expressions(), &self.history.configurator()).ok();
430        let env = env.as_ref();
431        let pivot = if self.is_xform_feature(index) {
432            self.xform_pivot(index, &params)
433        } else if self.is_face_transform_feature(index) {
434            // No faces, no pivot, no gizmo: there is nothing to put it on yet.
435            self.face_transform_pivot(index, &params, env)?
436        } else {
437            [0.0; 3]
438        };
439        let position = read_pose_vec3(env, transform, "position", [0.0; 3]);
440        Some(TransformPose {
441            position: std::array::from_fn(|axis| position[axis] + pivot[axis]),
442            rotation_deg: read_pose_vec3(env, transform, "rotationEuler", [0.0, 0.0, 0.0]),
443            scale: read_pose_vec3(env, transform, "scale", [1.0, 1.0, 1.0]),
444        })
445    }
446
447    fn is_xform_feature(&self, index: usize) -> bool {
448        self.history.feature_type(index).is_some_and(|ty| {
449            ty.eq_ignore_ascii_case("XFORM") || ty.eq_ignore_ascii_case("TRANSFORM")
450        })
451    }
452
453    /// Whether the feature at `index` is a Transform Face — the feature whose
454    /// motion turns about a STORED `pivot` param.
455    pub fn is_face_transform_feature(&self, index: usize) -> bool {
456        self.history
457            .feature_type(index)
458            .is_some_and(|ty| is_face_transform_type(&ty))
459    }
460
461    /// The point a Transform Face turns about: its STORED `pivot`. `None` while
462    /// that is null — no face resolves yet, or the run that reports the
463    /// selection's default ([`Self::fold_face_transform_pivot`]) has not landed
464    /// — which is what keeps the gizmo off until there is somewhere to put it.
465    /// Never a history replay: this is read every frame, and a replay here runs
466    /// on the app's own thread, whose history cache is cold under a background
467    /// runner: its first replay rebuilds the whole prefix (54 s on one user's
468    /// model, which froze the app).
469    fn face_transform_pivot(
470        &self,
471        _index: usize,
472        params: &serde_json::Value,
473        env: Option<&brep_kernel::Env>,
474    ) -> Option<[f64; 3]> {
475        match params.get("pivot") {
476            Some(pivot) if !pivot.is_null() => Some(read_pose_vec3(env, Some(params), "pivot", [0.0; 3])),
477            _ => None,
478        }
479    }
480
481    /// Whether the Transform Face `feature_id` has a pivot to put its gizmo on —
482    /// stored, or the default its run reported once that lands. The history panel arms
483    /// the gizmo on the frame this first holds.
484    pub fn face_transform_has_pivot(&self, feature_id: &str) -> bool {
485        let Some(index) = self.history.index_of(feature_id) else {
486            return false;
487        };
488        let Some(params) = self.history.feature_params(index) else {
489            return false;
490        };
491        self.is_face_transform_feature(index) && self.face_transform_pivot(index, &params, None).is_some()
492    }
493
494    /// Store the DEFAULT pivot a Transform Face's own run reported for `faces`
495    /// (`brep_kernel::TRANSFORM_FACE_DEFAULT_PIVOT_KEY`, the selection's centre
496    /// over the scene the feature ran against — the same resolution and centre
497    /// [`brep_kernel::face_transform_pivot`] gives) into its `pivot`, when that is
498    /// still null and its faces are still `faces`. No undo step and no re-run:
499    /// the run that reported it already used exactly that value. Stored rather
500    /// than derived per run, so the rotation centre is a number in the document:
501    /// a re-run, a gizmo drag, or an upstream edit never moves it.
502    pub(crate) fn fold_face_transform_pivot(&mut self, id: &str, pivot: [f64; 3], faces: &[String]) {
503        let Some(index) = self.history.index_of(id) else {
504            return;
505        };
506        if !self.is_face_transform_feature(index) {
507            return;
508        }
509        let Some(params) = self.history.feature_params(index) else {
510            return;
511        };
512        if !params.get("pivot").is_none_or(serde_json::Value::is_null)
513            || brep_kernel::reference_names(params.get("faces")) != faces
514        {
515            return;
516        }
517        self.history.fold_param_no_undo(id, "pivot", serde_json::json!(pivot));
518    }
519
520    /// Prepare a Transform Face's pivot in the params about to be written for
521    /// the feature at `index`: when this write changes the face selection
522    /// without also setting a pivot, `pivot` goes back to null, and the run the
523    /// write starts reports the new selection's centre, which
524    /// [`Self::fold_face_transform_pivot`] stores when it lands. A pivot the
525    /// write sets itself is kept. Every lane that writes feature params calls
526    /// this before the write (`update_feature_params`, the batch lane, the
527    /// reference picker's Finish).
528    pub(crate) fn stamp_face_transform_pivot(&self, index: usize, params: &mut serde_json::Value) {
529        if !self.is_face_transform_feature(index) {
530            return;
531        }
532        let before = self.history.feature_params(index).unwrap_or(serde_json::Value::Null);
533        let faces_changed = brep_kernel::reference_names(before.get("faces"))
534            != brep_kernel::reference_names(params.get("faces"));
535        let pivot_set_here = before.get("pivot") != params.get("pivot");
536        if !faces_changed || pivot_set_here {
537            return;
538        }
539        if let Some(object) = params.as_object_mut() {
540            object.insert("pivot".into(), serde_json::Value::Null);
541        }
542    }
543
544    /// XFORM rotates each selected solid about its own source vertex-bbox center.
545    /// Anchor the shared controls to the first resolved solid's pivot; the same
546    /// translation/rotation delta still applies to every selected solid.
547    fn xform_pivot(&self, index: usize, params: &serde_json::Value) -> [f64; 3] {
548        if !params["pivot"]
549            .as_str()
550            .is_some_and(|p| p.eq_ignore_ascii_case("BBOX_CENTER"))
551        {
552            return [0.0; 3];
553        }
554        // Replay the warm current prefix, then fold only results BEFORE XFORM.
555        // Using the transformed scene bbox would make the pivot drift on rotation.
556        let Ok(request) = serde_json::from_value::<HistoryRequest>(self.run_request_value())
557        else {
558            return [0.0; 3];
559        };
560        let _trace = crate::run_trace::span("xform_pivot");
561        let result = self.execute_plugin_history(&request);
562        let mut handles = HashMap::new();
563        for feature in result.results.iter().take(index) {
564            for name in &feature.removed {
565                handles.remove(name);
566            }
567            for solid in &feature.added {
568                handles.insert(solid.name.clone(), solid.handle);
569            }
570        }
571        let Some(refs) = params["solids"].as_array() else {
572            return [0.0; 3];
573        };
574        for reference in refs {
575            let Some(name) = reference.as_str().or_else(|| reference["name"].as_str()) else {
576                continue;
577            };
578            let Some(handle) = handles.get(name.trim()) else {
579                continue;
580            };
581            if let Ok(center) = brep_kernel::transform_pivot_native(*handle) {
582                return center;
583            }
584        }
585        [0.0; 3]
586    }
587
588    /// (Re)feed the widget gizmo at the armed feature's frame: origin =
589    /// `position`, axes = the feature's rotated basis (intrinsic XYZ Euler order, matching
590    /// the kernel bake). Auto-disarms if the feature vanished. Called every drag
591    /// frame from `transform_drag_to` so the widget tracks the moving pose live
592    /// (Fix 3); the drag delta resolves against the frozen grab frame, so this
593    /// re-sync never feeds back into the drag math.
594    pub fn sync_transform_gizmo(&mut self) {
595        // Only the TRANSFORM mode feeds the move/rotate widget; in dimension mode
596        // the widget stays hidden (the annotations render as an overlay instead).
597        if !matches!(self.transform_gizmo.mode, GizmoMode::Transform) {
598            return;
599        }
600        let Some(pose) = self.armed_pose() else {
601            self.disarm_transform();
602            return;
603        };
604        // A cage with ONE point selected has nothing to turn about: its
605        // gizmo draws no rotation rings.
606        let show_rings = self.transform_gizmo.deform.is_none() && self.cage_shows_rings().unwrap_or(true);
607        let _ = self
608            .widgets
609            .set_transform_json(&transform_frame_json_with(&pose, show_rings));
610        self.dirty = true;
611    }
612
613    /// Whether the feature schema exposes the shared Transform controls.
614    /// Capability belongs to the schema, not to which default-valued fields
615    /// happen to have been serialized in the model.
616    pub fn feature_has_transform(&self, feature_id: &str) -> bool {
617        self.history
618            .index_of(feature_id)
619            .and_then(|i| self.history.feature_type(i))
620            .and_then(|ty| self.feature_schema(&ty))
621            .is_some_and(|schema| schema["inputParamsSchema"]["transform"]["type"] == "transform")
622    }
623
624    /// The armed gizmo origin projected to VIEWPORT-LOCAL px (the center handle
625    /// sits here). The history panel publishes it so the headed verifier can
626    /// locate + drag the gizmo. `None` when disarmed / not projectable (the ONE
627    /// [`crate::view::ViewCamera::projectable`] policy — ortho always projects).
628    pub fn transform_gizmo_anchor(&self) -> Option<(f64, f64)> {
629        let pose = self.armed_pose()?;
630        let (sx, sy, _) = self.camera.project(pose.position);
631        self.camera.projectable(pose.position).then_some((sx, sy))
632    }
633
634    /// The transform gizmo's axis-end labels as JSON:
635    /// `[{ text:"XC"|"YC"|"ZC", rgb:[r,g,b], world:[x,y,z] }]`. The app projects
636    /// each `world` point and draws the colored egui label just past the matching
637    /// cone tip (X=red, Y=green, Z=blue). `[]` unless the TRANSFORM gizmo is armed.
638    pub fn transform_axis_labels_json(&self) -> String {
639        if !matches!(self.transform_gizmo.mode, GizmoMode::Transform) {
640            return "[]".to_string();
641        }
642        let Some(pose) = self.armed_pose() else {
643            return "[]".to_string();
644        };
645        let euler = [
646            pose.rotation_deg[0].to_radians(),
647            pose.rotation_deg[1].to_radians(),
648            pose.rotation_deg[2].to_radians(),
649        ];
650        let axes = [
651            normalize3(rotate_euler_xyz_f64([1.0, 0.0, 0.0], euler)),
652            normalize3(rotate_euler_xyz_f64([0.0, 1.0, 0.0], euler)),
653            normalize3(rotate_euler_xyz_f64([0.0, 0.0, 1.0], euler)),
654        ];
655        // Just past the cone tip, screen-constant.
656        let gap_px = 12.0_f64;
657        let dist =
658            (brep_gizmos::transform::PX_AXIS_LEN as f64 + gap_px) * self.camera.world_per_pixel();
659        let labels: [(&str, [f32; 3]); 3] = [
660            ("XC", [0.92, 0.26, 0.28]), // red
661            ("YC", [0.30, 0.78, 0.36]), // green
662            ("ZC", [0.30, 0.52, 0.98]), // blue
663        ];
664        let out: Vec<serde_json::Value> = (0..3)
665            .map(|i| {
666                let o = pose.position;
667                let a = axes[i];
668                serde_json::json!({
669                    "text": labels[i].0,
670                    "rgb": labels[i].1,
671                    "world": [o[0] + a[0] * dist, o[1] + a[1] * dist, o[2] + a[2] * dist],
672                })
673            })
674            .collect();
675        serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string())
676    }
677
678    /// A press point for every AXIS ARROW and ROTATION GRAB of the drawn
679    /// transform gizmo, in VIEWPORT-LOCAL px, keyed `axis:x|y|z` and
680    /// `ring:x|y|z` (a ring is named by the frame axis it turns about). Read off
681    /// the SAME regions [`Self::transform_pick`] tests — three quarters of the way
682    /// along an arrow's capsule spine, a grab ball's centre — and kept only where
683    /// a press there picks THAT handle, so a published key can never grab a
684    /// neighbour (an arrow foreshortened onto a ring ball, say). Empty while no
685    /// transform widget is drawn. The centre handle is `gizmo/anchor`'s.
686    pub fn transform_handle_points(&self) -> Vec<(&'static str, (f64, f64))> {
687        use brep_gizmos::hit_region::HitShape;
688        use brep_gizmos::transform as gizmo;
689        let cam = gizmo_camera(&self.camera);
690        self.widgets
691            .transform_hit_regions(&cam)
692            .into_iter()
693            .filter_map(|(handle, shape)| {
694                let key = match handle {
695                    gizmo::HANDLE_AXIS_X => "axis:x",
696                    gizmo::HANDLE_AXIS_Y => "axis:y",
697                    gizmo::HANDLE_AXIS_Z => "axis:z",
698                    gizmo::HANDLE_RING_X => "ring:x",
699                    gizmo::HANDLE_RING_Y => "ring:y",
700                    gizmo::HANDLE_RING_Z => "ring:z",
701                    _ => return None,
702                };
703                let [x, y] = match shape {
704                    HitShape::Capsule { a, b, .. } => {
705                        [a[0] + 0.75 * (b[0] - a[0]), a[1] + 0.75 * (b[1] - a[1])]
706                    }
707                    HitShape::Circle { c, .. } => c,
708                };
709                let point = (f64::from(x), f64::from(y));
710                (self.transform_pick(point.0, point.1) == handle).then_some((key, point))
711            })
712            .collect()
713    }
714
715    /// Viewport-local pick regions for the debug overlay, shared by feature and
716    /// component controllers. The widget feed determines visibility; hidden
717    /// widgets return `[]`. The app offsets these circles/capsules by `rect.min`.
718    pub fn transform_hit_areas_json(&self) -> String {
719        let cam = gizmo_camera(&self.camera);
720        let regions = self.widgets.transform_hit_regions(&cam);
721        super::camera_widgets::hit_shapes_json(regions.iter().map(|(_, shape)| shape))
722    }
723
724    /// Begin a gizmo drag at viewport px `(x, y)` when the gizmo is armed AND a
725    /// handle is under the pointer. Returns whether a handle was grabbed — the
726    /// viewport routes the drag to the gizmo (not the camera) when `true`; a press
727    /// on empty space returns `false` and still orbits.
728    pub fn transform_press(&mut self, x: f64, y: f64) -> bool {
729        // Only grabbable in TRANSFORM mode — in dimension mode the dimension
730        // handles own the pointer (routed by the app), and disarmed grabs nothing.
731        if !matches!(self.transform_gizmo.mode, GizmoMode::Transform) {
732            return false;
733        }
734        let handle = self.transform_pick(x, y);
735        if handle == 0 {
736            return false;
737        }
738        let Some(pose) = self.armed_pose() else {
739            return false;
740        };
741        self.widgets.set_transform_active(handle);
742        self.transform_gizmo.drag = Some(TransformDrag {
743            handle,
744            sx: x as f32,
745            sy: y as f32,
746            start: pose,
747            last: None,
748        });
749        // A cage drag re-derives every selected point from the grab.
750        self.cage_grab_begin();
751        self.deform_grab_begin();
752        self.dirty = true;
753        true
754    }
755
756    /// Whether a gizmo handle drag is in flight.
757    pub fn transform_dragging(&self) -> bool {
758        self.transform_gizmo.drag.is_some()
759    }
760
761    /// Continue the in-flight gizmo drag to viewport px `(cx, cy)`: resolve the
762    /// world delta from the grab (against the frozen grab-time frame), apply it to
763    /// the grab pose, write it back into the feature's `transform`, and re-run so
764    /// the model follows live. Then re-sync the VISIBLE gizmo to the moved pose so
765    /// the widget tracks the pointer in real time (Fix 3) — the delta stays
766    /// anchored to `drag.start`, so this visual sync never feeds back on itself.
767    pub fn transform_drag_to(&mut self, cx: f64, cy: f64) {
768        let Some(drag) = self.transform_gizmo.drag else {
769            return;
770        };
771        let Some(delta) = self.resolve_transform_delta(&drag, cx, cy) else {
772            return;
773        };
774        let pose = apply_transform_delta(&drag.start, &delta);
775        // Remember what the handle resolved, so the readout can say it. The
776        // drag is re-resolved from `drag.start` every frame, so this is the
777        // WHOLE motion since the grab, not an increment to accumulate.
778        if let Some(live) = self.transform_gizmo.drag.as_mut() {
779            live.last = Some(delta);
780        }
781        self.write_armed_pose(&pose);
782        // Live-follow: re-feed the widget frame to the just-written pose. NB
783        // `finish_apply` skips this while a drag is in flight (drag.is_some()), so
784        // the sync happens here. The active-handle gold highlight survives (the
785        // widget only clears it on a `null` feed).
786        self.sync_transform_gizmo();
787    }
788
789    /// End the drag: clear the active-handle highlight + re-sync the gizmo to the
790    /// feature's final (moved) pose (unpin the frame).
791    pub fn transform_release(&mut self) {
792        if self.transform_gizmo.drag.take().is_some() {
793            self.widgets.set_transform_active(0);
794            // The re-sync below marks the frame only in Transform mode.
795            self.dirty = true;
796            // ONE UNDO STEP PER DRAG. `set_feature_params` coalesces on
797            // `param:{index}` so that the hundred writes a single drag makes do
798            // not become a hundred undo entries — but nothing ended the run, so
799            // the coalescing went on across drags too: two drags of the same
800            // feature were ONE entry, and a single undo after a refused drag
801            // threw away the good drag before it as well (measured
802            // 2026-09-21 — 0.9254 then 1.8508, one undo, straight to zero).
803            // Ending the run here is the same thing the sheet label drag does
804            // on release, and it is what makes "undo the drag that refused,
805            // keep the one before it" work.
806            self.history.break_coalescing();
807            self.cage_grab_end();
808            self.deform_grab_end();
809            self.sync_transform_gizmo();
810        }
811    }
812
813    /// Resolve against the grab-time frame so live widget updates cannot
814    /// feed back into the drag calculation.
815    fn resolve_transform_delta(
816        &self,
817        drag: &TransformDrag,
818        cx: f64,
819        cy: f64,
820    ) -> Option<TransformDelta> {
821        let cam = gizmo_camera(&self.camera);
822        let frame_json = transform_frame_json(&drag.start);
823        let json = self.widgets.transform_drag_json_with_frame(
824            &cam,
825            &frame_json,
826            drag.handle,
827            drag.sx,
828            drag.sy,
829            cx as f32,
830            cy as f32,
831        );
832        parse_drag_delta(&json)
833    }
834
835    /// Write `pose` into the armed feature's `inputParams.transform.{position,
836    /// rotationEuler}` (preserving every other field, incl. `scale`) and re-run.
837    fn write_armed_pose(&mut self, pose: &TransformPose) {
838        // Each number is snapped as it is STORED, after any pivot or centre is
839        // taken off: a world pose on the grid minus an off-grid pivot is not.
840        let start = self.transform_gizmo.drag.map(|drag| drag.start);
841        if let Some(address) = self.transform_gizmo.port.clone() {
842            self.write_port_point_pose(&address, pose);
843            return;
844        }
845        let Some(id) = self.transform_gizmo.feature_id.clone() else {
846            return;
847        };
848        let pmi = self.pmi_state();
849        if let Some((_, annotation)) = pmi.find_annotation(&id) {
850            if annotation.kind == "explode" {
851                let laid_out = self
852                    .pmi_report
853                    .as_ref()
854                    .and_then(|r| r.annotation(&id))
855                    .and_then(|r| match &r.geometry {
856                        brep_kernel::PmiGeometry::Explode { center, .. } => Some(*center),
857                        _ => None,
858                    });
859                // Before the kernel lays the step out (a pick still running)
860                // the gizmo stands on the live centre, and a drag there
861                // already writes the step's position.
862                let center = laid_out.or_else(|| self.pmi_explode_live_center(&id));
863                if let Some(center) = center {
864                    // The drag started from where playback showed the step and
865                    // is stored as its full delta: show the step at full (the
866                    // steps before it are already), so its bodies stay under
867                    // the gizmo.
868                    if let (true, Some(progress), Some(step)) = (laid_out.is_some(), self.explode_playback.progress, self.explode_step_of(&id)) {
869                        self.explode_playback.progress = Some(progress.max(step as f64 + 1.0));
870                    }
871                    let mut params = annotation.params.clone();
872                    let position: [f64; 3] = std::array::from_fn(|i| {
873                        drag_stored(start.map(|s| s.position[i] - center[i]), pose.position[i] - center[i])
874                    });
875                    let rotation = drag_stored_rotation(start.as_ref(), pose);
876                    params["transform"] = serde_json::json!({ "position": position, "rotationEuler": rotation, "scale": pose.scale });
877                    let _ = self.pmi_update_annotation(&id, &params.to_string());
878                }
879                return;
880            }
881        }
882        let Some(index) = self.history.index_of(&id) else {
883            return;
884        };
885        if self.transform_gizmo.cage.is_some() {
886            self.write_cage_pose(pose);
887            return;
888        }
889        if self.transform_gizmo.deform.is_some() {
890            self.write_deform_pose(pose);
891            return;
892        }
893        if let Some(anchor) = self.transform_gizmo.anchor {
894            let position = std::array::from_fn(|i| drag_stored(start.map(|s| s.position[i]), pose.position[i]));
895            let rotation = drag_stored_rotation(start.as_ref(), pose);
896            self.write_spline_anchor_pose(&id, anchor, position, rotation);
897            return;
898        }
899        let mut params = self
900            .history
901            .feature_params(index)
902            .unwrap_or_else(|| serde_json::json!({}));
903        let pivot = if self.is_xform_feature(index) {
904            self.xform_pivot(index, &params)
905        } else if self.is_face_transform_feature(index) {
906            let env =
907                brep_kernel::Env::build(&self.history.expressions(), &self.history.configurator())
908                    .ok();
909            let Some(pivot) = self.face_transform_pivot(index, &params, env.as_ref()) else {
910                return;
911            };
912            pivot
913        } else {
914            [0.0; 3]
915        };
916        let position: [f64; 3] = std::array::from_fn(|axis| {
917            drag_stored(start.map(|s| s.position[axis] - pivot[axis]), pose.position[axis] - pivot[axis])
918        });
919        let rotation = drag_stored_rotation(start.as_ref(), pose);
920        // Ensure `transform` is an object, then set the two edited vectors.
921        if !params
922            .get("transform")
923            .map(|t| t.is_object())
924            .unwrap_or(false)
925        {
926            if let Some(object) = params.as_object_mut() {
927                object.insert("transform".into(), serde_json::json!({}));
928            }
929        }
930        if let Some(transform) = params.get_mut("transform").and_then(|t| t.as_object_mut()) {
931            transform.insert("position".into(), serde_json::json!(position));
932            transform.insert("rotationEuler".into(), serde_json::json!(rotation));
933        }
934        let _ = self.update_feature_params(&id, &params.to_string());
935    }
936}
937
938/// The number to store for one pose value: on the drag grid during a drag
939/// (`before` is its value at the grab), untouched for any other write.
940fn drag_stored(before: Option<f64>, after: f64) -> f64 {
941    match before {
942        Some(before) => crate::formatting::snap_drag_moved(before, after),
943        None => after,
944    }
945}
946
947/// [`drag_stored`] for a pose's Euler triple.
948fn drag_stored_rotation(start: Option<&TransformPose>, pose: &TransformPose) -> [f64; 3] {
949    std::array::from_fn(|i| drag_stored(start.map(|s| s.rotation_deg[i]), pose.rotation_deg[i]))
950}
951
952/// Name the axis a world vector lies along — `X`, `Y` or `Z` when it lies along
953/// one to within a thousandth of its length, and the neutral `\u{0394}` when it
954/// does not.
955///
956/// The neutral case is not a fallback, it is the honest answer: the X ARROW OF
957/// A TURNED FRAME points along the turned X, which has two non-zero world
958/// components, and calling that motion "X" would name a world axis the face is
959/// not moving along. A zero-length vector is `\u{0394}` too — there is no axis
960/// to name yet.
961fn dominant_axis_label(v: &[f64; 3]) -> &'static str {
962    let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
963    if length < 1e-12 {
964        return "\u{0394}";
965    }
966    const NAMES: [&str; 3] = ["X", "Y", "Z"];
967    for axis in 0..3 {
968        if v[axis].abs() >= length * 0.999 {
969            return NAMES[axis];
970        }
971    }
972    "\u{0394}"
973}
974
975/// The type strings a Transform Face answers to — the kernel dispatch's alias
976/// set, case-insensitively.
977pub fn is_face_transform_type(feature_type: &str) -> bool {
978    matches!(
979        feature_type.trim().to_ascii_uppercase().as_str(),
980        "TF" | "TRANSFORM FACE" | "TRANSFORMFACE"
981    )
982}
983
984/// Apply translation or world-axis rotation to the grab pose, retaining scale.
985fn apply_transform_delta(start: &TransformPose, delta: &TransformDelta) -> TransformPose {
986    match delta {
987        TransformDelta::Translate(world) => TransformPose {
988            position: [
989                start.position[0] + world[0],
990                start.position[1] + world[1],
991                start.position[2] + world[2],
992            ],
993            ..*start
994        },
995        TransformDelta::Rotate { axis, radians } => {
996            let q0 = quat_from_euler_xyz_deg(start.rotation_deg);
997            let dq = quat_from_axis_angle(*axis, *radians);
998            let nq = quat_mul(dq, q0);
999            TransformPose {
1000                rotation_deg: euler_xyz_deg_from_quat(nq),
1001                ..*start
1002            }
1003        }
1004    }
1005}
1006
1007/// Read a `[x, y, z]` from a transform sub-field (numbers only; missing / short
1008/// arrays keep the per-index default).
1009fn read_pose_vec3(
1010    env: Option<&brep_kernel::Env>,
1011    transform: Option<&serde_json::Value>,
1012    key: &str,
1013    default: [f64; 3],
1014) -> [f64; 3] {
1015    let array = transform
1016        .and_then(|t| t.get(key))
1017        .and_then(|v| v.as_array());
1018    let mut out = default;
1019    if let Some(array) = array {
1020        for (index, slot) in out.iter_mut().enumerate() {
1021            match array.get(index) {
1022                Some(serde_json::Value::Number(number)) => {
1023                    if let Some(number) = number.as_f64() {
1024                        *slot = number;
1025                    }
1026                }
1027                // A component may be an EXPRESSION (`"boxW/2"`) — the kernel
1028                // evaluates it when it builds, so the gizmo must arm at the same
1029                // place. Reading it as 0 parked the handles at the world origin
1030                // while the solid sat elsewhere, and the first drag wrote that
1031                // wrong origin back as a literal, teleporting the solid.
1032                Some(serde_json::Value::String(source)) => {
1033                    if let Some(number) = env
1034                        .and_then(|env| env.eval(source).ok())
1035                        .filter(|number| number.is_finite())
1036                    {
1037                        *slot = number;
1038                    }
1039                }
1040                _ => {}
1041            }
1042        }
1043    }
1044    out
1045}
1046
1047/// The gizmo frame feed (`set_transform_json` shape) for a pose: origin =
1048/// `position`, axes = the feature's rotated basis (intrinsic XYZ Euler order, matching
1049/// the kernel bake), with the center free-move handle shown.
1050fn transform_frame_json(pose: &TransformPose) -> String {
1051    transform_frame_json_with(pose, true)
1052}
1053
1054/// [`transform_frame_json`] with the rotation rings shown or hidden.
1055fn transform_frame_json_with(pose: &TransformPose, show_rings: bool) -> String {
1056    let euler = [
1057        pose.rotation_deg[0].to_radians(),
1058        pose.rotation_deg[1].to_radians(),
1059        pose.rotation_deg[2].to_radians(),
1060    ];
1061    let x = normalize3(rotate_euler_xyz_f64([1.0, 0.0, 0.0], euler));
1062    let y = normalize3(rotate_euler_xyz_f64([0.0, 1.0, 0.0], euler));
1063    let z = normalize3(rotate_euler_xyz_f64([0.0, 0.0, 1.0], euler));
1064    serde_json::json!({
1065        "origin": pose.position,
1066        "x": x,
1067        "y": y,
1068        "z": z,
1069        "showCenter": true,
1070        "showAxes": true,
1071        "showRings": show_rings,
1072    })
1073    .to_string()
1074}
1075
1076pub(super) fn normalize3(v: [f64; 3]) -> [f64; 3] {
1077    let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
1078    if length < 1e-12 {
1079        [0.0, 0.0, 1.0]
1080    } else {
1081        [v[0] / length, v[1] / length, v[2] / length]
1082    }
1083}
1084
1085/// Apply an intrinsic XYZ Euler (radians) to a vector — the EXACT matrix the kernel
1086/// bake (`transform_bake` / `datum::rotate_euler_xyz`) uses, so the fed gizmo
1087/// frame aligns with the baked solid.
1088pub(crate) fn rotate_euler_xyz_f64(v: [f64; 3], euler: [f64; 3]) -> [f64; 3] {
1089    let (c1, s1) = (euler[0].cos(), euler[0].sin());
1090    let (c2, s2) = (euler[1].cos(), euler[1].sin());
1091    let (c3, s3) = (euler[2].cos(), euler[2].sin());
1092    let m00 = c2 * c3;
1093    let m01 = -c2 * s3;
1094    let m02 = s2;
1095    let m10 = c1 * s3 + c3 * s1 * s2;
1096    let m11 = c1 * c3 - s1 * s2 * s3;
1097    let m12 = -c2 * s1;
1098    let m20 = s1 * s3 - c1 * c3 * s2;
1099    let m21 = c3 * s1 + c1 * s2 * s3;
1100    let m22 = c1 * c2;
1101    [
1102        m00 * v[0] + m01 * v[1] + m02 * v[2],
1103        m10 * v[0] + m11 * v[1] + m12 * v[2],
1104        m20 * v[0] + m21 * v[1] + m22 * v[2],
1105    ]
1106}
1107
1108// --- quaternion helpers (ported from CombinedTransformControls) -----
1109
1110pub(super) type Quat = [f64; 4]; // [x, y, z, w]
1111
1112pub(super) fn quat_from_axis_angle(axis: [f64; 3], angle: f64) -> Quat {
1113    let n = normalize3(axis);
1114    let half = angle * 0.5;
1115    let s = half.sin();
1116    [n[0] * s, n[1] * s, n[2] * s, half.cos()]
1117}
1118
1119/// Quaternion from an intrinsic XYZ Euler (degrees in).
1120pub(super) fn quat_from_euler_xyz_deg(deg: [f64; 3]) -> Quat {
1121    let (c1, s1) = (
1122        (deg[0].to_radians() * 0.5).cos(),
1123        (deg[0].to_radians() * 0.5).sin(),
1124    );
1125    let (c2, s2) = (
1126        (deg[1].to_radians() * 0.5).cos(),
1127        (deg[1].to_radians() * 0.5).sin(),
1128    );
1129    let (c3, s3) = (
1130        (deg[2].to_radians() * 0.5).cos(),
1131        (deg[2].to_radians() * 0.5).sin(),
1132    );
1133    [
1134        s1 * c2 * c3 + c1 * s2 * s3,
1135        c1 * s2 * c3 - s1 * c2 * s3,
1136        c1 * c2 * s3 + s1 * s2 * c3,
1137        c1 * c2 * c3 - s1 * s2 * s3,
1138    ]
1139}
1140
1141/// Quaternion product `a * b`.
1142pub(super) fn quat_mul(a: Quat, b: Quat) -> Quat {
1143    [
1144        a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
1145        a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
1146        a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
1147        a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],
1148    ]
1149}
1150
1151/// Intrinsic XYZ Euler from a quaternion (via the rotation matrix) → the
1152/// 'XYZ' Euler in DEGREES. Uses the SAME matrix element naming as
1153/// `rotate_euler_xyz_f64`, so the round-trip is consistent with the kernel bake.
1154pub(super) fn euler_xyz_deg_from_quat(q: Quat) -> [f64; 3] {
1155    let [x, y, z, w] = q;
1156    let (x2, y2, z2) = (x + x, y + y, z + z);
1157    let (xx, xy, xz) = (x * x2, x * y2, x * z2);
1158    let (yy, yz, zz) = (y * y2, y * z2, z * z2);
1159    let (wx, wy, wz) = (w * x2, w * y2, w * z2);
1160    // Rotation matrix elements (m<row><col> naming).
1161    let m11 = 1.0 - (yy + zz);
1162    let m12 = xy - wz;
1163    let m13 = xz + wy;
1164    let m22 = 1.0 - (xx + zz);
1165    let m23 = yz - wx;
1166    let m32 = yz + wx;
1167    let m33 = 1.0 - (xx + yy);
1168    let ey = m13.clamp(-1.0, 1.0).asin();
1169    let (ex, ez) = if m13.abs() < 0.9999999 {
1170        ((-m23).atan2(m33), (-m12).atan2(m11))
1171    } else {
1172        (m32.atan2(m22), 0.0)
1173    };
1174    [ex.to_degrees(), ey.to_degrees(), ez.to_degrees()]
1175}
1176
1177// ===========================================================================
1178// The gizmo on a CONNECTION POINT
1179// ===========================================================================
1180//
1181// A connection point is not a feature: it has no history row and no id, so
1182// every read and write above that goes through `history.index_of` misses it.
1183// What it has instead is a SEAT — the frame its declared `transform` is an
1184// offset in (`brep_kernel::ports`) — and the gizmo lane is exactly that seat
1185// applied and un-applied:
1186//
1187//   pose  = seat  o  declaration      (what the handles are drawn at)
1188//   write = seat⁻¹ o  dragged pose    (what the block is given back)
1189//
1190// The seat comes from the LAST APPLIED RUN's report and the declaration from
1191// the block as it stands NOW. That split is deliberate and it is what keeps a
1192// drag smooth: `set_ports_block` re-runs on the NEXT frame, so a pose read
1193// from the run's resolved position would lag the pointer by a frame and
1194// oscillate. The seat does not move while the offset is dragged — only the
1195// reference geometry moves it — so reading it from the last run is exact.
1196
1197impl EngineState {
1198    /// Whether the transform gizmo is armed on a connection point, and which.
1199    pub fn transform_armed_port_point(&self) -> Option<&str> {
1200        self.transform_armed()
1201            .then(|| self.transform_gizmo.port.as_deref())
1202            .flatten()
1203    }
1204
1205    /// Arm the TRANSFORM gizmo on the connection point at `address`, or refuse
1206    /// and say why ([`Self::port_point_gizmo_refusal`]).
1207    pub fn arm_transform_for_port_point(&mut self, address: &str) -> bool {
1208        if let Some(reason) = self.port_point_gizmo_refusal(address) {
1209            self.push_notice(format!("no handles on {address}: {reason}"));
1210            return false;
1211        }
1212        self.component_move_reset();
1213        self.transform_gizmo.feature_id = None;
1214        self.transform_gizmo.anchor = None;
1215        self.transform_gizmo.cage = None;
1216        self.transform_gizmo.deform = None;
1217        self.transform_gizmo.port = Some(address.to_string());
1218        self.transform_gizmo.mode = GizmoMode::Transform;
1219        self.transform_gizmo.drag = None;
1220        self.clear_feature_dimension_overlay();
1221        self.sync_transform_gizmo();
1222        true
1223    }
1224
1225    /// Why the gizmo will not arm on this point, in words, or `None` when it
1226    /// will. There are two reasons, and both are cases where the handles would
1227    /// LIE — draw somewhere a drag cannot write to:
1228    ///
1229    /// * the point **maps down**. Its placement is its target's: the kernel's
1230    ///   `resolve_point` returns on `mapsTo` before it ever reads the
1231    ///   transform, so handles would sit on the descendant's geometry and a
1232    ///   drag would write numbers nothing reads, leaving the point where it
1233    ///   was while the handles walked away from it;
1234    /// * an **expression** places it. The gizmo writes numbers, and replacing
1235    ///   `width/2` with `12.5` because a user dragged something is a loss the
1236    ///   document cannot show them. Typing in the panel still works, which is
1237    ///   where an expression belongs.
1238    ///
1239    /// Public because the panel must say the same thing the arm decides rather
1240    /// than inferring a reason from the gizmo not being armed: it is drawn a
1241    /// moment BEFORE the arm runs, so an inference would flash a refusal on
1242    /// the frame a perfectly armable point is selected.
1243    pub fn port_point_gizmo_refusal(&self, address: &str) -> Option<String> {
1244        let point = self.declared_point_value(address)?;
1245        if let Some(target) = point
1246            .get("mapsTo")
1247            .and_then(serde_json::Value::as_str)
1248            .map(str::trim)
1249            .filter(|target| !target.is_empty())
1250        {
1251            return Some(format!(
1252                "it maps to '{target}', and that point's placement is this one's"
1253            ));
1254        }
1255        let transform = point.get("transform")?;
1256        for key in ["position", "rotationEuler"] {
1257            let Some(components) = transform.get(key).and_then(serde_json::Value::as_array) else {
1258                continue;
1259            };
1260            for component in components {
1261                if let Some(expression) = component.as_str() {
1262                    return Some(format!(
1263                        "'{expression}' places it, and a drag writes numbers"
1264                    ));
1265                }
1266            }
1267        }
1268        None
1269    }
1270
1271    /// The seat a connection point's placement is an offset in: the last
1272    /// applied run's, or the WORLD seat for a point no run has resolved yet
1273    /// (one just added, which must still be draggable).
1274    fn port_point_seat(&self, address: &str) -> brep_kernel::Frame {
1275        self.port_point_row(address)
1276            .map(|row| row.seat.to_frame())
1277            .unwrap_or_else(brep_kernel::world_seat)
1278    }
1279
1280    /// The armed connection point's pose in WORLD space — the seat applied to
1281    /// the declaration, per this section's opening note.
1282    pub(super) fn port_point_pose(&self, address: &str) -> Option<TransformPose> {
1283        let point = self.declared_point_value(address)?;
1284        let transform = point.get("transform");
1285        let local_position = read_pose_vec3(None, transform, "position", [0.0; 3]);
1286        let local_rotation = read_pose_vec3(None, transform, "rotationEuler", [0.0; 3]);
1287        let seat = self.port_point_seat(address);
1288        let world_axes = super::spline_edit::axes_from_euler_deg(local_rotation)
1289            .map(|axis| seat_axis(&seat, axis));
1290        Some(TransformPose {
1291            position: array3(brep_kernel::seat_point(&seat, vec3(local_position))),
1292            rotation_deg: super::spline_edit::euler_xyz_deg_from_axes(
1293                world_axes[0],
1294                world_axes[1],
1295                world_axes[2],
1296            ),
1297            scale: [1.0, 1.0, 1.0],
1298        })
1299    }
1300
1301    /// Write a dragged WORLD pose back as the point's offset in its seat.
1302    /// Coalesced per address, so a whole drag is one undo step.
1303    pub(super) fn write_port_point_pose(&mut self, address: &str, pose: &TransformPose) {
1304        let seat = self.port_point_seat(address);
1305        let local = |pose: &TransformPose| {
1306            let local_axes = super::spline_edit::axes_from_euler_deg(pose.rotation_deg)
1307                .map(|axis| unseat_axis(&seat, axis));
1308            (
1309                array3(brep_kernel::unseat_point(&seat, vec3(pose.position))),
1310                super::spline_edit::euler_xyz_deg_from_axes(local_axes[0], local_axes[1], local_axes[2]),
1311            )
1312        };
1313        let (position, rotation) = local(pose);
1314        let before = self.transform_gizmo.drag.map(|drag| local(&drag.start));
1315        let position: [f64; 3] = std::array::from_fn(|i| drag_stored(before.map(|b| b.0[i]), position[i]));
1316        let rotation: [f64; 3] = std::array::from_fn(|i| drag_stored(before.map(|b| b.1[i]), rotation[i]));
1317        let key = format!("port-point-pose:{address}");
1318        self.edit_port_point(address, Some(&key), |point| {
1319            point.insert(
1320                "transform".into(),
1321                serde_json::json!({ "position": position, "rotationEuler": rotation }),
1322            );
1323        });
1324    }
1325}
1326
1327fn vec3(a: [f64; 3]) -> brep_kernel::Vec3 {
1328    brep_kernel::Vec3::new(a[0], a[1], a[2])
1329}
1330
1331fn array3(v: brep_kernel::Vec3) -> [f64; 3] {
1332    [v.x, v.y, v.z]
1333}
1334
1335/// A local axis carried out through the seat's basis.
1336fn seat_axis(seat: &brep_kernel::Frame, axis: [f64; 3]) -> [f64; 3] {
1337    array3(brep_kernel::seat_vector(seat, vec3(axis)))
1338}
1339
1340/// The same axis read back in the seat's basis.
1341fn unseat_axis(seat: &brep_kernel::Frame, axis: [f64; 3]) -> [f64; 3] {
1342    array3(brep_kernel::unseat_vector(seat, vec3(axis)))
1343}
1344