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`, or — while
462    /// that is still null — the kernel's default, the selection's centre over
463    /// the scene the feature runs against. `None` when neither exists (no face
464    /// resolves), which is what keeps the gizmo off an empty selection.
465    fn face_transform_pivot(
466        &self,
467        index: usize,
468        params: &serde_json::Value,
469        env: Option<&brep_kernel::Env>,
470    ) -> Option<[f64; 3]> {
471        match params.get("pivot") {
472            Some(pivot) if !pivot.is_null() => Some(read_pose_vec3(env, Some(params), "pivot", [0.0; 3])),
473            _ => self.face_transform_default_pivot(index, params),
474        }
475    }
476
477    /// Whether the Transform Face `feature_id` has a pivot to put its gizmo on —
478    /// a stored one, or faces that resolve to a default. The history panel arms
479    /// the gizmo on the frame this first holds.
480    pub fn face_transform_has_pivot(&self, feature_id: &str) -> bool {
481        let Some(index) = self.history.index_of(feature_id) else {
482            return false;
483        };
484        let Some(params) = self.history.feature_params(index) else {
485            return false;
486        };
487        self.is_face_transform_feature(index) && self.face_transform_pivot(index, &params, None).is_some()
488    }
489
490    /// Transform Face's DEFAULT pivot for `params.faces`: the prefix BEFORE the
491    /// feature is replayed (warm, like [`Self::xform_pivot`]'s) and handed to
492    /// [`brep_kernel::face_transform_pivot`] — the same resolution and centre the
493    /// feature itself falls back to, so the stored value and the kernel agree by
494    /// construction.
495    fn face_transform_default_pivot(
496        &self,
497        index: usize,
498        params: &serde_json::Value,
499    ) -> Option<[f64; 3]> {
500        let names = brep_kernel::reference_names(params.get("faces"));
501        if names.is_empty() {
502            return None;
503        }
504        let request: HistoryRequest =
505            serde_json::from_value(self.history.request_before(index)?).ok()?;
506        let _trace = crate::run_trace::span("face_transform_pivot");
507        let result = self.execute_plugin_history(&request);
508        brep_kernel::face_transform_pivot(&result.results, &names)
509    }
510
511    /// STORE a Transform Face's pivot into the params about to be written for
512    /// the feature at `index`: when this write changes the face selection
513    /// without also setting a pivot, or leaves the pivot null, `pivot` becomes the
514    /// new selection's centre (null again when nothing resolves). A pivot the
515    /// write sets itself is kept. Stored rather than derived per run, so the
516    /// rotation centre is a number in the document: a re-run, a gizmo drag, or an
517    /// upstream edit never moves it. Every lane that writes feature params calls
518    /// this before the write (`update_feature_params`, the batch lane, the
519    /// reference picker's Finish).
520    pub(crate) fn stamp_face_transform_pivot(&self, index: usize, params: &mut serde_json::Value) {
521        if !self.is_face_transform_feature(index) {
522            return;
523        }
524        let before = self.history.feature_params(index).unwrap_or(serde_json::Value::Null);
525        let faces_changed = brep_kernel::reference_names(before.get("faces"))
526            != brep_kernel::reference_names(params.get("faces"));
527        let pivot_set_here = before.get("pivot") != params.get("pivot");
528        let unset = params.get("pivot").is_none_or(serde_json::Value::is_null);
529        if !(unset || (faces_changed && !pivot_set_here)) {
530            return;
531        }
532        let pivot = self.face_transform_default_pivot(index, params);
533        if let Some(object) = params.as_object_mut() {
534            object.insert(
535                "pivot".into(),
536                pivot.map_or(serde_json::Value::Null, |pivot| serde_json::json!(pivot)),
537            );
538        }
539    }
540
541    /// XFORM rotates each selected solid about its own source vertex-bbox center.
542    /// Anchor the shared controls to the first resolved solid's pivot; the same
543    /// translation/rotation delta still applies to every selected solid.
544    fn xform_pivot(&self, index: usize, params: &serde_json::Value) -> [f64; 3] {
545        if !params["pivot"]
546            .as_str()
547            .is_some_and(|p| p.eq_ignore_ascii_case("BBOX_CENTER"))
548        {
549            return [0.0; 3];
550        }
551        // Replay the warm current prefix, then fold only results BEFORE XFORM.
552        // Using the transformed scene bbox would make the pivot drift on rotation.
553        let Ok(request) = serde_json::from_value::<HistoryRequest>(self.run_request_value())
554        else {
555            return [0.0; 3];
556        };
557        let _trace = crate::run_trace::span("xform_pivot");
558        let result = self.execute_plugin_history(&request);
559        let mut handles = HashMap::new();
560        for feature in result.results.iter().take(index) {
561            for name in &feature.removed {
562                handles.remove(name);
563            }
564            for solid in &feature.added {
565                handles.insert(solid.name.clone(), solid.handle);
566            }
567        }
568        let Some(refs) = params["solids"].as_array() else {
569            return [0.0; 3];
570        };
571        for reference in refs {
572            let Some(name) = reference.as_str().or_else(|| reference["name"].as_str()) else {
573                continue;
574            };
575            let Some(handle) = handles.get(name.trim()) else {
576                continue;
577            };
578            if let Ok(center) = brep_kernel::transform_pivot_native(*handle) {
579                return center;
580            }
581        }
582        [0.0; 3]
583    }
584
585    /// (Re)feed the widget gizmo at the armed feature's frame: origin =
586    /// `position`, axes = the feature's rotated basis (intrinsic XYZ Euler order, matching
587    /// the kernel bake). Auto-disarms if the feature vanished. Called every drag
588    /// frame from `transform_drag_to` so the widget tracks the moving pose live
589    /// (Fix 3); the drag delta resolves against the frozen grab frame, so this
590    /// re-sync never feeds back into the drag math.
591    pub fn sync_transform_gizmo(&mut self) {
592        // Only the TRANSFORM mode feeds the move/rotate widget; in dimension mode
593        // the widget stays hidden (the annotations render as an overlay instead).
594        if !matches!(self.transform_gizmo.mode, GizmoMode::Transform) {
595            return;
596        }
597        let Some(pose) = self.armed_pose() else {
598            self.disarm_transform();
599            return;
600        };
601        // A cage with ONE point selected has nothing to turn about: its
602        // gizmo draws no rotation rings.
603        let show_rings = self.transform_gizmo.deform.is_none() && self.cage_shows_rings().unwrap_or(true);
604        let _ = self
605            .widgets
606            .set_transform_json(&transform_frame_json_with(&pose, show_rings));
607        self.dirty = true;
608    }
609
610    /// Whether the feature schema exposes the shared Transform controls.
611    /// Capability belongs to the schema, not to which default-valued fields
612    /// happen to have been serialized in the model.
613    pub fn feature_has_transform(&self, feature_id: &str) -> bool {
614        self.history
615            .index_of(feature_id)
616            .and_then(|i| self.history.feature_type(i))
617            .and_then(|ty| self.feature_schema(&ty))
618            .is_some_and(|schema| schema["inputParamsSchema"]["transform"]["type"] == "transform")
619    }
620
621    /// The armed gizmo origin projected to VIEWPORT-LOCAL px (the center handle
622    /// sits here). The history panel publishes it so the headed verifier can
623    /// locate + drag the gizmo. `None` when disarmed / not projectable (the ONE
624    /// [`crate::view::ViewCamera::projectable`] policy — ortho always projects).
625    pub fn transform_gizmo_anchor(&self) -> Option<(f64, f64)> {
626        let pose = self.armed_pose()?;
627        let (sx, sy, _) = self.camera.project(pose.position);
628        self.camera.projectable(pose.position).then_some((sx, sy))
629    }
630
631    /// The transform gizmo's axis-end labels as JSON:
632    /// `[{ text:"XC"|"YC"|"ZC", rgb:[r,g,b], world:[x,y,z] }]`. The app projects
633    /// each `world` point and draws the colored egui label just past the matching
634    /// cone tip (X=red, Y=green, Z=blue). `[]` unless the TRANSFORM gizmo is armed.
635    pub fn transform_axis_labels_json(&self) -> String {
636        if !matches!(self.transform_gizmo.mode, GizmoMode::Transform) {
637            return "[]".to_string();
638        }
639        let Some(pose) = self.armed_pose() else {
640            return "[]".to_string();
641        };
642        let euler = [
643            pose.rotation_deg[0].to_radians(),
644            pose.rotation_deg[1].to_radians(),
645            pose.rotation_deg[2].to_radians(),
646        ];
647        let axes = [
648            normalize3(rotate_euler_xyz_f64([1.0, 0.0, 0.0], euler)),
649            normalize3(rotate_euler_xyz_f64([0.0, 1.0, 0.0], euler)),
650            normalize3(rotate_euler_xyz_f64([0.0, 0.0, 1.0], euler)),
651        ];
652        // Just past the cone tip, screen-constant.
653        let gap_px = 12.0_f64;
654        let dist =
655            (brep_gizmos::transform::PX_AXIS_LEN as f64 + gap_px) * self.camera.world_per_pixel();
656        let labels: [(&str, [f32; 3]); 3] = [
657            ("XC", [0.92, 0.26, 0.28]), // red
658            ("YC", [0.30, 0.78, 0.36]), // green
659            ("ZC", [0.30, 0.52, 0.98]), // blue
660        ];
661        let out: Vec<serde_json::Value> = (0..3)
662            .map(|i| {
663                let o = pose.position;
664                let a = axes[i];
665                serde_json::json!({
666                    "text": labels[i].0,
667                    "rgb": labels[i].1,
668                    "world": [o[0] + a[0] * dist, o[1] + a[1] * dist, o[2] + a[2] * dist],
669                })
670            })
671            .collect();
672        serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string())
673    }
674
675    /// A press point for every AXIS ARROW and ROTATION GRAB of the drawn
676    /// transform gizmo, in VIEWPORT-LOCAL px, keyed `axis:x|y|z` and
677    /// `ring:x|y|z` (a ring is named by the frame axis it turns about). Read off
678    /// the SAME regions [`Self::transform_pick`] tests — three quarters of the way
679    /// along an arrow's capsule spine, a grab ball's centre — and kept only where
680    /// a press there picks THAT handle, so a published key can never grab a
681    /// neighbour (an arrow foreshortened onto a ring ball, say). Empty while no
682    /// transform widget is drawn. The centre handle is `gizmo/anchor`'s.
683    pub fn transform_handle_points(&self) -> Vec<(&'static str, (f64, f64))> {
684        use brep_gizmos::hit_region::HitShape;
685        use brep_gizmos::transform as gizmo;
686        let cam = gizmo_camera(&self.camera);
687        self.widgets
688            .transform_hit_regions(&cam)
689            .into_iter()
690            .filter_map(|(handle, shape)| {
691                let key = match handle {
692                    gizmo::HANDLE_AXIS_X => "axis:x",
693                    gizmo::HANDLE_AXIS_Y => "axis:y",
694                    gizmo::HANDLE_AXIS_Z => "axis:z",
695                    gizmo::HANDLE_RING_X => "ring:x",
696                    gizmo::HANDLE_RING_Y => "ring:y",
697                    gizmo::HANDLE_RING_Z => "ring:z",
698                    _ => return None,
699                };
700                let [x, y] = match shape {
701                    HitShape::Capsule { a, b, .. } => {
702                        [a[0] + 0.75 * (b[0] - a[0]), a[1] + 0.75 * (b[1] - a[1])]
703                    }
704                    HitShape::Circle { c, .. } => c,
705                };
706                let point = (f64::from(x), f64::from(y));
707                (self.transform_pick(point.0, point.1) == handle).then_some((key, point))
708            })
709            .collect()
710    }
711
712    /// Viewport-local pick regions for the debug overlay, shared by feature and
713    /// component controllers. The widget feed determines visibility; hidden
714    /// widgets return `[]`. The app offsets these circles/capsules by `rect.min`.
715    pub fn transform_hit_areas_json(&self) -> String {
716        let cam = gizmo_camera(&self.camera);
717        let regions = self.widgets.transform_hit_regions(&cam);
718        super::camera_widgets::hit_shapes_json(regions.iter().map(|(_, shape)| shape))
719    }
720
721    /// Begin a gizmo drag at viewport px `(x, y)` when the gizmo is armed AND a
722    /// handle is under the pointer. Returns whether a handle was grabbed — the
723    /// viewport routes the drag to the gizmo (not the camera) when `true`; a press
724    /// on empty space returns `false` and still orbits.
725    pub fn transform_press(&mut self, x: f64, y: f64) -> bool {
726        // Only grabbable in TRANSFORM mode — in dimension mode the dimension
727        // handles own the pointer (routed by the app), and disarmed grabs nothing.
728        if !matches!(self.transform_gizmo.mode, GizmoMode::Transform) {
729            return false;
730        }
731        let handle = self.transform_pick(x, y);
732        if handle == 0 {
733            return false;
734        }
735        let Some(pose) = self.armed_pose() else {
736            return false;
737        };
738        self.widgets.set_transform_active(handle);
739        self.transform_gizmo.drag = Some(TransformDrag {
740            handle,
741            sx: x as f32,
742            sy: y as f32,
743            start: pose,
744            last: None,
745        });
746        // A cage drag re-derives every selected point from the grab.
747        self.cage_grab_begin();
748        self.deform_grab_begin();
749        self.dirty = true;
750        true
751    }
752
753    /// Whether a gizmo handle drag is in flight.
754    pub fn transform_dragging(&self) -> bool {
755        self.transform_gizmo.drag.is_some()
756    }
757
758    /// Continue the in-flight gizmo drag to viewport px `(cx, cy)`: resolve the
759    /// world delta from the grab (against the frozen grab-time frame), apply it to
760    /// the grab pose, write it back into the feature's `transform`, and re-run so
761    /// the model follows live. Then re-sync the VISIBLE gizmo to the moved pose so
762    /// the widget tracks the pointer in real time (Fix 3) — the delta stays
763    /// anchored to `drag.start`, so this visual sync never feeds back on itself.
764    pub fn transform_drag_to(&mut self, cx: f64, cy: f64) {
765        let Some(drag) = self.transform_gizmo.drag else {
766            return;
767        };
768        let Some(delta) = self.resolve_transform_delta(&drag, cx, cy) else {
769            return;
770        };
771        let pose = apply_transform_delta(&drag.start, &delta);
772        // Remember what the handle resolved, so the readout can say it. The
773        // drag is re-resolved from `drag.start` every frame, so this is the
774        // WHOLE motion since the grab, not an increment to accumulate.
775        if let Some(live) = self.transform_gizmo.drag.as_mut() {
776            live.last = Some(delta);
777        }
778        self.write_armed_pose(&pose);
779        // Live-follow: re-feed the widget frame to the just-written pose. NB
780        // `finish_apply` skips this while a drag is in flight (drag.is_some()), so
781        // the sync happens here. The active-handle gold highlight survives (the
782        // widget only clears it on a `null` feed).
783        self.sync_transform_gizmo();
784    }
785
786    /// End the drag: clear the active-handle highlight + re-sync the gizmo to the
787    /// feature's final (moved) pose (unpin the frame).
788    pub fn transform_release(&mut self) {
789        if self.transform_gizmo.drag.take().is_some() {
790            self.widgets.set_transform_active(0);
791            // The re-sync below marks the frame only in Transform mode.
792            self.dirty = true;
793            // ONE UNDO STEP PER DRAG. `set_feature_params` coalesces on
794            // `param:{index}` so that the hundred writes a single drag makes do
795            // not become a hundred undo entries — but nothing ended the run, so
796            // the coalescing went on across drags too: two drags of the same
797            // feature were ONE entry, and a single undo after a refused drag
798            // threw away the good drag before it as well (measured
799            // 2026-09-21 — 0.9254 then 1.8508, one undo, straight to zero).
800            // Ending the run here is the same thing the sheet label drag does
801            // on release, and it is what makes "undo the drag that refused,
802            // keep the one before it" work.
803            self.history.break_coalescing();
804            self.cage_grab_end();
805            self.deform_grab_end();
806            self.sync_transform_gizmo();
807        }
808    }
809
810    /// Resolve against the grab-time frame so live widget updates cannot
811    /// feed back into the drag calculation.
812    fn resolve_transform_delta(
813        &self,
814        drag: &TransformDrag,
815        cx: f64,
816        cy: f64,
817    ) -> Option<TransformDelta> {
818        let cam = gizmo_camera(&self.camera);
819        let frame_json = transform_frame_json(&drag.start);
820        let json = self.widgets.transform_drag_json_with_frame(
821            &cam,
822            &frame_json,
823            drag.handle,
824            drag.sx,
825            drag.sy,
826            cx as f32,
827            cy as f32,
828        );
829        parse_drag_delta(&json)
830    }
831
832    /// Write `pose` into the armed feature's `inputParams.transform.{position,
833    /// rotationEuler}` (preserving every other field, incl. `scale`) and re-run.
834    fn write_armed_pose(&mut self, pose: &TransformPose) {
835        // Each number is snapped as it is STORED, after any pivot or centre is
836        // taken off: a world pose on the grid minus an off-grid pivot is not.
837        let start = self.transform_gizmo.drag.map(|drag| drag.start);
838        if let Some(address) = self.transform_gizmo.port.clone() {
839            self.write_port_point_pose(&address, pose);
840            return;
841        }
842        let Some(id) = self.transform_gizmo.feature_id.clone() else {
843            return;
844        };
845        let pmi = self.pmi_state();
846        if let Some((_, annotation)) = pmi.find_annotation(&id) {
847            if annotation.kind == "explode" {
848                let laid_out = self
849                    .pmi_report
850                    .as_ref()
851                    .and_then(|r| r.annotation(&id))
852                    .and_then(|r| match &r.geometry {
853                        brep_kernel::PmiGeometry::Explode { center, .. } => Some(*center),
854                        _ => None,
855                    });
856                // Before the kernel lays the step out (a pick still running)
857                // the gizmo stands on the live centre, and a drag there
858                // already writes the step's position.
859                let center = laid_out.or_else(|| self.pmi_explode_live_center(&id));
860                if let Some(center) = center {
861                    // The drag started from where playback showed the step and
862                    // is stored as its full delta: show the step at full (the
863                    // steps before it are already), so its bodies stay under
864                    // the gizmo.
865                    if let (true, Some(progress), Some(step)) = (laid_out.is_some(), self.explode_playback.progress, self.explode_step_of(&id)) {
866                        self.explode_playback.progress = Some(progress.max(step as f64 + 1.0));
867                    }
868                    let mut params = annotation.params.clone();
869                    let position: [f64; 3] = std::array::from_fn(|i| {
870                        drag_stored(start.map(|s| s.position[i] - center[i]), pose.position[i] - center[i])
871                    });
872                    let rotation = drag_stored_rotation(start.as_ref(), pose);
873                    params["transform"] = serde_json::json!({ "position": position, "rotationEuler": rotation, "scale": pose.scale });
874                    let _ = self.pmi_update_annotation(&id, &params.to_string());
875                }
876                return;
877            }
878        }
879        let Some(index) = self.history.index_of(&id) else {
880            return;
881        };
882        if self.transform_gizmo.cage.is_some() {
883            self.write_cage_pose(pose);
884            return;
885        }
886        if self.transform_gizmo.deform.is_some() {
887            self.write_deform_pose(pose);
888            return;
889        }
890        if let Some(anchor) = self.transform_gizmo.anchor {
891            let position = std::array::from_fn(|i| drag_stored(start.map(|s| s.position[i]), pose.position[i]));
892            let rotation = drag_stored_rotation(start.as_ref(), pose);
893            self.write_spline_anchor_pose(&id, anchor, position, rotation);
894            return;
895        }
896        let mut params = self
897            .history
898            .feature_params(index)
899            .unwrap_or_else(|| serde_json::json!({}));
900        let pivot = if self.is_xform_feature(index) {
901            self.xform_pivot(index, &params)
902        } else if self.is_face_transform_feature(index) {
903            let env =
904                brep_kernel::Env::build(&self.history.expressions(), &self.history.configurator())
905                    .ok();
906            let Some(pivot) = self.face_transform_pivot(index, &params, env.as_ref()) else {
907                return;
908            };
909            pivot
910        } else {
911            [0.0; 3]
912        };
913        let position: [f64; 3] = std::array::from_fn(|axis| {
914            drag_stored(start.map(|s| s.position[axis] - pivot[axis]), pose.position[axis] - pivot[axis])
915        });
916        let rotation = drag_stored_rotation(start.as_ref(), pose);
917        // Ensure `transform` is an object, then set the two edited vectors.
918        if !params
919            .get("transform")
920            .map(|t| t.is_object())
921            .unwrap_or(false)
922        {
923            if let Some(object) = params.as_object_mut() {
924                object.insert("transform".into(), serde_json::json!({}));
925            }
926        }
927        if let Some(transform) = params.get_mut("transform").and_then(|t| t.as_object_mut()) {
928            transform.insert("position".into(), serde_json::json!(position));
929            transform.insert("rotationEuler".into(), serde_json::json!(rotation));
930        }
931        let _ = self.update_feature_params(&id, &params.to_string());
932    }
933}
934
935/// The number to store for one pose value: on the drag grid during a drag
936/// (`before` is its value at the grab), untouched for any other write.
937fn drag_stored(before: Option<f64>, after: f64) -> f64 {
938    match before {
939        Some(before) => crate::formatting::snap_drag_moved(before, after),
940        None => after,
941    }
942}
943
944/// [`drag_stored`] for a pose's Euler triple.
945fn drag_stored_rotation(start: Option<&TransformPose>, pose: &TransformPose) -> [f64; 3] {
946    std::array::from_fn(|i| drag_stored(start.map(|s| s.rotation_deg[i]), pose.rotation_deg[i]))
947}
948
949/// Name the axis a world vector lies along — `X`, `Y` or `Z` when it lies along
950/// one to within a thousandth of its length, and the neutral `\u{0394}` when it
951/// does not.
952///
953/// The neutral case is not a fallback, it is the honest answer: the X ARROW OF
954/// A TURNED FRAME points along the turned X, which has two non-zero world
955/// components, and calling that motion "X" would name a world axis the face is
956/// not moving along. A zero-length vector is `\u{0394}` too — there is no axis
957/// to name yet.
958fn dominant_axis_label(v: &[f64; 3]) -> &'static str {
959    let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
960    if length < 1e-12 {
961        return "\u{0394}";
962    }
963    const NAMES: [&str; 3] = ["X", "Y", "Z"];
964    for axis in 0..3 {
965        if v[axis].abs() >= length * 0.999 {
966            return NAMES[axis];
967        }
968    }
969    "\u{0394}"
970}
971
972/// The type strings a Transform Face answers to — the kernel dispatch's alias
973/// set, case-insensitively.
974pub fn is_face_transform_type(feature_type: &str) -> bool {
975    matches!(
976        feature_type.trim().to_ascii_uppercase().as_str(),
977        "TF" | "TRANSFORM FACE" | "TRANSFORMFACE"
978    )
979}
980
981/// Apply translation or world-axis rotation to the grab pose, retaining scale.
982fn apply_transform_delta(start: &TransformPose, delta: &TransformDelta) -> TransformPose {
983    match delta {
984        TransformDelta::Translate(world) => TransformPose {
985            position: [
986                start.position[0] + world[0],
987                start.position[1] + world[1],
988                start.position[2] + world[2],
989            ],
990            ..*start
991        },
992        TransformDelta::Rotate { axis, radians } => {
993            let q0 = quat_from_euler_xyz_deg(start.rotation_deg);
994            let dq = quat_from_axis_angle(*axis, *radians);
995            let nq = quat_mul(dq, q0);
996            TransformPose {
997                rotation_deg: euler_xyz_deg_from_quat(nq),
998                ..*start
999            }
1000        }
1001    }
1002}
1003
1004/// Read a `[x, y, z]` from a transform sub-field (numbers only; missing / short
1005/// arrays keep the per-index default).
1006fn read_pose_vec3(
1007    env: Option<&brep_kernel::Env>,
1008    transform: Option<&serde_json::Value>,
1009    key: &str,
1010    default: [f64; 3],
1011) -> [f64; 3] {
1012    let array = transform
1013        .and_then(|t| t.get(key))
1014        .and_then(|v| v.as_array());
1015    let mut out = default;
1016    if let Some(array) = array {
1017        for (index, slot) in out.iter_mut().enumerate() {
1018            match array.get(index) {
1019                Some(serde_json::Value::Number(number)) => {
1020                    if let Some(number) = number.as_f64() {
1021                        *slot = number;
1022                    }
1023                }
1024                // A component may be an EXPRESSION (`"boxW/2"`) — the kernel
1025                // evaluates it when it builds, so the gizmo must arm at the same
1026                // place. Reading it as 0 parked the handles at the world origin
1027                // while the solid sat elsewhere, and the first drag wrote that
1028                // wrong origin back as a literal, teleporting the solid.
1029                Some(serde_json::Value::String(source)) => {
1030                    if let Some(number) = env
1031                        .and_then(|env| env.eval(source).ok())
1032                        .filter(|number| number.is_finite())
1033                    {
1034                        *slot = number;
1035                    }
1036                }
1037                _ => {}
1038            }
1039        }
1040    }
1041    out
1042}
1043
1044/// The gizmo frame feed (`set_transform_json` shape) for a pose: origin =
1045/// `position`, axes = the feature's rotated basis (intrinsic XYZ Euler order, matching
1046/// the kernel bake), with the center free-move handle shown.
1047fn transform_frame_json(pose: &TransformPose) -> String {
1048    transform_frame_json_with(pose, true)
1049}
1050
1051/// [`transform_frame_json`] with the rotation rings shown or hidden.
1052fn transform_frame_json_with(pose: &TransformPose, show_rings: bool) -> String {
1053    let euler = [
1054        pose.rotation_deg[0].to_radians(),
1055        pose.rotation_deg[1].to_radians(),
1056        pose.rotation_deg[2].to_radians(),
1057    ];
1058    let x = normalize3(rotate_euler_xyz_f64([1.0, 0.0, 0.0], euler));
1059    let y = normalize3(rotate_euler_xyz_f64([0.0, 1.0, 0.0], euler));
1060    let z = normalize3(rotate_euler_xyz_f64([0.0, 0.0, 1.0], euler));
1061    serde_json::json!({
1062        "origin": pose.position,
1063        "x": x,
1064        "y": y,
1065        "z": z,
1066        "showCenter": true,
1067        "showAxes": true,
1068        "showRings": show_rings,
1069    })
1070    .to_string()
1071}
1072
1073pub(super) fn normalize3(v: [f64; 3]) -> [f64; 3] {
1074    let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
1075    if length < 1e-12 {
1076        [0.0, 0.0, 1.0]
1077    } else {
1078        [v[0] / length, v[1] / length, v[2] / length]
1079    }
1080}
1081
1082/// Apply an intrinsic XYZ Euler (radians) to a vector — the EXACT matrix the kernel
1083/// bake (`transform_bake` / `datum::rotate_euler_xyz`) uses, so the fed gizmo
1084/// frame aligns with the baked solid.
1085pub(crate) fn rotate_euler_xyz_f64(v: [f64; 3], euler: [f64; 3]) -> [f64; 3] {
1086    let (c1, s1) = (euler[0].cos(), euler[0].sin());
1087    let (c2, s2) = (euler[1].cos(), euler[1].sin());
1088    let (c3, s3) = (euler[2].cos(), euler[2].sin());
1089    let m00 = c2 * c3;
1090    let m01 = -c2 * s3;
1091    let m02 = s2;
1092    let m10 = c1 * s3 + c3 * s1 * s2;
1093    let m11 = c1 * c3 - s1 * s2 * s3;
1094    let m12 = -c2 * s1;
1095    let m20 = s1 * s3 - c1 * c3 * s2;
1096    let m21 = c3 * s1 + c1 * s2 * s3;
1097    let m22 = c1 * c2;
1098    [
1099        m00 * v[0] + m01 * v[1] + m02 * v[2],
1100        m10 * v[0] + m11 * v[1] + m12 * v[2],
1101        m20 * v[0] + m21 * v[1] + m22 * v[2],
1102    ]
1103}
1104
1105// --- quaternion helpers (ported from CombinedTransformControls) -----
1106
1107pub(super) type Quat = [f64; 4]; // [x, y, z, w]
1108
1109pub(super) fn quat_from_axis_angle(axis: [f64; 3], angle: f64) -> Quat {
1110    let n = normalize3(axis);
1111    let half = angle * 0.5;
1112    let s = half.sin();
1113    [n[0] * s, n[1] * s, n[2] * s, half.cos()]
1114}
1115
1116/// Quaternion from an intrinsic XYZ Euler (degrees in).
1117pub(super) fn quat_from_euler_xyz_deg(deg: [f64; 3]) -> Quat {
1118    let (c1, s1) = (
1119        (deg[0].to_radians() * 0.5).cos(),
1120        (deg[0].to_radians() * 0.5).sin(),
1121    );
1122    let (c2, s2) = (
1123        (deg[1].to_radians() * 0.5).cos(),
1124        (deg[1].to_radians() * 0.5).sin(),
1125    );
1126    let (c3, s3) = (
1127        (deg[2].to_radians() * 0.5).cos(),
1128        (deg[2].to_radians() * 0.5).sin(),
1129    );
1130    [
1131        s1 * c2 * c3 + c1 * s2 * s3,
1132        c1 * s2 * c3 - s1 * c2 * s3,
1133        c1 * c2 * s3 + s1 * s2 * c3,
1134        c1 * c2 * c3 - s1 * s2 * s3,
1135    ]
1136}
1137
1138/// Quaternion product `a * b`.
1139pub(super) fn quat_mul(a: Quat, b: Quat) -> Quat {
1140    [
1141        a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
1142        a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
1143        a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
1144        a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],
1145    ]
1146}
1147
1148/// Intrinsic XYZ Euler from a quaternion (via the rotation matrix) → the
1149/// 'XYZ' Euler in DEGREES. Uses the SAME matrix element naming as
1150/// `rotate_euler_xyz_f64`, so the round-trip is consistent with the kernel bake.
1151pub(super) fn euler_xyz_deg_from_quat(q: Quat) -> [f64; 3] {
1152    let [x, y, z, w] = q;
1153    let (x2, y2, z2) = (x + x, y + y, z + z);
1154    let (xx, xy, xz) = (x * x2, x * y2, x * z2);
1155    let (yy, yz, zz) = (y * y2, y * z2, z * z2);
1156    let (wx, wy, wz) = (w * x2, w * y2, w * z2);
1157    // Rotation matrix elements (m<row><col> naming).
1158    let m11 = 1.0 - (yy + zz);
1159    let m12 = xy - wz;
1160    let m13 = xz + wy;
1161    let m22 = 1.0 - (xx + zz);
1162    let m23 = yz - wx;
1163    let m32 = yz + wx;
1164    let m33 = 1.0 - (xx + yy);
1165    let ey = m13.clamp(-1.0, 1.0).asin();
1166    let (ex, ez) = if m13.abs() < 0.9999999 {
1167        ((-m23).atan2(m33), (-m12).atan2(m11))
1168    } else {
1169        (m32.atan2(m22), 0.0)
1170    };
1171    [ex.to_degrees(), ey.to_degrees(), ez.to_degrees()]
1172}
1173
1174// ===========================================================================
1175// The gizmo on a CONNECTION POINT
1176// ===========================================================================
1177//
1178// A connection point is not a feature: it has no history row and no id, so
1179// every read and write above that goes through `history.index_of` misses it.
1180// What it has instead is a SEAT — the frame its declared `transform` is an
1181// offset in (`brep_kernel::ports`) — and the gizmo lane is exactly that seat
1182// applied and un-applied:
1183//
1184//   pose  = seat  o  declaration      (what the handles are drawn at)
1185//   write = seat⁻¹ o  dragged pose    (what the block is given back)
1186//
1187// The seat comes from the LAST APPLIED RUN's report and the declaration from
1188// the block as it stands NOW. That split is deliberate and it is what keeps a
1189// drag smooth: `set_ports_block` re-runs on the NEXT frame, so a pose read
1190// from the run's resolved position would lag the pointer by a frame and
1191// oscillate. The seat does not move while the offset is dragged — only the
1192// reference geometry moves it — so reading it from the last run is exact.
1193
1194impl EngineState {
1195    /// Whether the transform gizmo is armed on a connection point, and which.
1196    pub fn transform_armed_port_point(&self) -> Option<&str> {
1197        self.transform_armed()
1198            .then(|| self.transform_gizmo.port.as_deref())
1199            .flatten()
1200    }
1201
1202    /// Arm the TRANSFORM gizmo on the connection point at `address`, or refuse
1203    /// and say why ([`Self::port_point_gizmo_refusal`]).
1204    pub fn arm_transform_for_port_point(&mut self, address: &str) -> bool {
1205        if let Some(reason) = self.port_point_gizmo_refusal(address) {
1206            self.push_notice(format!("no handles on {address}: {reason}"));
1207            return false;
1208        }
1209        self.component_move_reset();
1210        self.transform_gizmo.feature_id = None;
1211        self.transform_gizmo.anchor = None;
1212        self.transform_gizmo.cage = None;
1213        self.transform_gizmo.deform = None;
1214        self.transform_gizmo.port = Some(address.to_string());
1215        self.transform_gizmo.mode = GizmoMode::Transform;
1216        self.transform_gizmo.drag = None;
1217        self.clear_feature_dimension_overlay();
1218        self.sync_transform_gizmo();
1219        true
1220    }
1221
1222    /// Why the gizmo will not arm on this point, in words, or `None` when it
1223    /// will. There are two reasons, and both are cases where the handles would
1224    /// LIE — draw somewhere a drag cannot write to:
1225    ///
1226    /// * the point **maps down**. Its placement is its target's: the kernel's
1227    ///   `resolve_point` returns on `mapsTo` before it ever reads the
1228    ///   transform, so handles would sit on the descendant's geometry and a
1229    ///   drag would write numbers nothing reads, leaving the point where it
1230    ///   was while the handles walked away from it;
1231    /// * an **expression** places it. The gizmo writes numbers, and replacing
1232    ///   `width/2` with `12.5` because a user dragged something is a loss the
1233    ///   document cannot show them. Typing in the panel still works, which is
1234    ///   where an expression belongs.
1235    ///
1236    /// Public because the panel must say the same thing the arm decides rather
1237    /// than inferring a reason from the gizmo not being armed: it is drawn a
1238    /// moment BEFORE the arm runs, so an inference would flash a refusal on
1239    /// the frame a perfectly armable point is selected.
1240    pub fn port_point_gizmo_refusal(&self, address: &str) -> Option<String> {
1241        let point = self.declared_point_value(address)?;
1242        if let Some(target) = point
1243            .get("mapsTo")
1244            .and_then(serde_json::Value::as_str)
1245            .map(str::trim)
1246            .filter(|target| !target.is_empty())
1247        {
1248            return Some(format!(
1249                "it maps to '{target}', and that point's placement is this one's"
1250            ));
1251        }
1252        let transform = point.get("transform")?;
1253        for key in ["position", "rotationEuler"] {
1254            let Some(components) = transform.get(key).and_then(serde_json::Value::as_array) else {
1255                continue;
1256            };
1257            for component in components {
1258                if let Some(expression) = component.as_str() {
1259                    return Some(format!(
1260                        "'{expression}' places it, and a drag writes numbers"
1261                    ));
1262                }
1263            }
1264        }
1265        None
1266    }
1267
1268    /// The seat a connection point's placement is an offset in: the last
1269    /// applied run's, or the WORLD seat for a point no run has resolved yet
1270    /// (one just added, which must still be draggable).
1271    fn port_point_seat(&self, address: &str) -> brep_kernel::Frame {
1272        self.port_point_row(address)
1273            .map(|row| row.seat.to_frame())
1274            .unwrap_or_else(brep_kernel::world_seat)
1275    }
1276
1277    /// The armed connection point's pose in WORLD space — the seat applied to
1278    /// the declaration, per this section's opening note.
1279    pub(super) fn port_point_pose(&self, address: &str) -> Option<TransformPose> {
1280        let point = self.declared_point_value(address)?;
1281        let transform = point.get("transform");
1282        let local_position = read_pose_vec3(None, transform, "position", [0.0; 3]);
1283        let local_rotation = read_pose_vec3(None, transform, "rotationEuler", [0.0; 3]);
1284        let seat = self.port_point_seat(address);
1285        let world_axes = super::spline_edit::axes_from_euler_deg(local_rotation)
1286            .map(|axis| seat_axis(&seat, axis));
1287        Some(TransformPose {
1288            position: array3(brep_kernel::seat_point(&seat, vec3(local_position))),
1289            rotation_deg: super::spline_edit::euler_xyz_deg_from_axes(
1290                world_axes[0],
1291                world_axes[1],
1292                world_axes[2],
1293            ),
1294            scale: [1.0, 1.0, 1.0],
1295        })
1296    }
1297
1298    /// Write a dragged WORLD pose back as the point's offset in its seat.
1299    /// Coalesced per address, so a whole drag is one undo step.
1300    pub(super) fn write_port_point_pose(&mut self, address: &str, pose: &TransformPose) {
1301        let seat = self.port_point_seat(address);
1302        let local = |pose: &TransformPose| {
1303            let local_axes = super::spline_edit::axes_from_euler_deg(pose.rotation_deg)
1304                .map(|axis| unseat_axis(&seat, axis));
1305            (
1306                array3(brep_kernel::unseat_point(&seat, vec3(pose.position))),
1307                super::spline_edit::euler_xyz_deg_from_axes(local_axes[0], local_axes[1], local_axes[2]),
1308            )
1309        };
1310        let (position, rotation) = local(pose);
1311        let before = self.transform_gizmo.drag.map(|drag| local(&drag.start));
1312        let position: [f64; 3] = std::array::from_fn(|i| drag_stored(before.map(|b| b.0[i]), position[i]));
1313        let rotation: [f64; 3] = std::array::from_fn(|i| drag_stored(before.map(|b| b.1[i]), rotation[i]));
1314        let key = format!("port-point-pose:{address}");
1315        self.edit_port_point(address, Some(&key), |point| {
1316            point.insert(
1317                "transform".into(),
1318                serde_json::json!({ "position": position, "rotationEuler": rotation }),
1319            );
1320        });
1321    }
1322}
1323
1324fn vec3(a: [f64; 3]) -> brep_kernel::Vec3 {
1325    brep_kernel::Vec3::new(a[0], a[1], a[2])
1326}
1327
1328fn array3(v: brep_kernel::Vec3) -> [f64; 3] {
1329    [v.x, v.y, v.z]
1330}
1331
1332/// A local axis carried out through the seat's basis.
1333fn seat_axis(seat: &brep_kernel::Frame, axis: [f64; 3]) -> [f64; 3] {
1334    array3(brep_kernel::seat_vector(seat, vec3(axis)))
1335}
1336
1337/// The same axis read back in the seat's basis.
1338fn unseat_axis(seat: &brep_kernel::Frame, axis: [f64; 3]) -> [f64; 3] {
1339    array3(brep_kernel::unseat_vector(seat, vec3(axis)))
1340}
1341