BREP_render 0.4.0

BREP Rust rendering engine: kernel-fed scene store + wgpu renderer (headless artifact, desktop window, and wasm canvas shells).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
use super::*;

/// Which of the two gizmos is currently armed for the feature. `Transform` shows
/// the move/rotate gizmo; `Dimension` shows the on-canvas draggable dimension
/// annotations (feature-dimensions FD-1). Expanding a feature arms `Dimension`;
/// the viewport sphere/center toggle flips to `Transform` and back. The two modes
/// are EXCLUSIVE — the transform gizmo never renders in `Dimension` mode and
/// vice-versa.
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
pub enum GizmoMode {
    /// Neither gizmo armed (`feature_id` is `None`).
    #[default]
    None,
    /// The move/rotate transform gizmo is armed.
    Transform,
    /// The dimension-annotation gizmo is armed (FD-1).
    Dimension,
}

/// The transform-controls gizmo controller state (see the impl block below).
#[derive(Default)]
pub struct TransformArm {
    /// The feature id whose gizmo is armed (for EITHER mode), or `None`
    /// (disarmed → `mode == None`).
    pub(super) feature_id: Option<String>,
    /// Which gizmo is armed for `feature_id` (transform vs dimension). `None`
    /// exactly when `feature_id` is `None`.
    pub(super) mode: GizmoMode,
    /// The live handle drag, captured on pointer-down over a gizmo handle.
    pub(super) drag: Option<TransformDrag>,
    /// When the armed subject is ONE SPLINE ANCHOR rather than the feature's
    /// `transform` param: the anchor index into `persistentData.spline.points`
    /// of `feature_id` (an SP feature). The same gizmo, press / drag / release
    /// and live-follow apply; only the pose read and write-back differ (see
    /// `spline_edit.rs`).
    pub(super) anchor: Option<usize>,
}

/// A grab snapshot for an in-flight transform-gizmo drag: the grabbed handle,
/// the grab screen point, and the feature's pose AT GRAB. Every drag move
/// resolves an absolute delta from this grab (against the pinned grab-time
/// frame) and re-applies it to `start`, so the drag never accumulates error.
#[derive(Clone, Copy)]
pub(super) struct TransformDrag {
    handle: u32,
    sx: f32,
    sy: f32,
    start: TransformPose,
}

/// A TRS pose read from / written to a feature's `inputParams.transform`
/// (`rotation` in DEGREES, intrinsic XYZ Euler order — the kernel `transform_bake`
/// convention, `M = T·R·S`).
#[derive(Clone, Copy, PartialEq, Debug)]
struct TransformPose {
    position: [f64; 3],
    rotation_deg: [f64; 3],
    scale: [f64; 3],
}

/// A world-space delta shared by feature and component gizmo controllers.
#[derive(Clone, Copy, PartialEq, Debug)]
pub(super) enum TransformDelta {
    /// World-space translation, added to `position`.
    Translate([f64; 3]),
    /// World-axis rotation, pre-multiplied onto the pose's orientation.
    Rotate { axis: [f64; 3], radians: f64 },
}

/// Decode widget drag JSON; unknown kinds and invalid JSON produce no delta.
pub(super) fn parse_drag_delta(json: &str) -> Option<TransformDelta> {
    let value: serde_json::Value = serde_json::from_str(json).ok()?;
    match value.get("kind").and_then(|k| k.as_str()) {
        Some("translate") => Some(TransformDelta::Translate(
            crate::json_support::vec3_or(value.get("world"), [0.0; 3]),
        )),
        Some("rotate") => Some(TransformDelta::Rotate {
            axis: crate::json_support::vec3_or(value.get("axisWorld"), [0.0; 3]),
            radians: value.get("radians").and_then(|n| n.as_f64()).unwrap_or(0.0),
        }),
        _ => None,
    }
}

impl EngineState {
    /// Whether the TRANSFORM gizmo (move/rotate) is armed for ANY feature. False
    /// in dimension mode — the two ◎ modes are exclusive, so the transform gizmo
    /// arms/handles never render while dimensions are shown.
    pub fn transform_armed(&self) -> bool {
        matches!(self.transform_gizmo.mode, GizmoMode::Transform)
    }

    /// The transform-gizmo-armed feature id (empty unless in transform mode).
    pub fn transform_armed_feature(&self) -> String {
        if self.transform_armed() {
            self.transform_gizmo.feature_id.clone().unwrap_or_default()
        } else {
            String::new()
        }
    }

    /// The gizmo as the headed verifier sees it: the mode, the armed feature,
    /// the spline anchor index when the gizmo sits on one, and `origin` — the
    /// DRAWN move/rotate widget's frame origin (`null` when no widget is
    /// drawn), which is the proof a handle is on screen, unlike any
    /// params-derived pose.
    pub fn gizmo_state_json(&self) -> String {
        let mode = match self.transform_gizmo.mode {
            GizmoMode::None => "none",
            GizmoMode::Transform => "transform",
            GizmoMode::Dimension => "dimension",
        };
        serde_json::json!({
            "mode": mode,
            "armed": self.transform_armed(),
            "feature": self.transform_gizmo.feature_id,
            "anchor": self.transform_gizmo.anchor,
            "origin": self.widgets.transform_origin(),
        })
        .to_string()
    }

    /// Whether the TRANSFORM gizmo is armed for THIS feature.
    pub fn transform_armed_for(&self, feature_id: &str) -> bool {
        self.transform_armed() && self.transform_gizmo.feature_id.as_deref() == Some(feature_id)
    }

    /// Arm the TRANSFORM gizmo for `feature_id` and feed it at the feature's
    /// transform frame. Re-arming a different feature moves the gizmo to it.
    /// Clears any dimension overlay (the modes are exclusive).
    ///
    /// An ACOMP (assembly component) feature ROUTES to the component Move gizmo
    /// instead: its `transform` is the component pose (`{translate,
    /// rotateEulerDeg}`, a different shape), its gizmo attaches at the member
    /// bbox center, commits on release, and refuses fixed instances — the
    /// generic position/rotationEuler gizmo must never write its keys into an
    /// ACOMP's params. This covers the history panel's arm-on-expand path too.
    pub fn arm_transform(&mut self, feature_id: &str) {
        let is_acomp = self
            .history
            .index_of(feature_id)
            .and_then(|index| self.history.feature_type(index))
            .is_some_and(|ty| super::components::is_acomp_feature_type(&ty));
        if is_acomp {
            self.component_move_arm(feature_id);
            return;
        }
        self.component_move_reset();
        self.transform_gizmo.feature_id = Some(feature_id.to_string());
        self.transform_gizmo.mode = GizmoMode::Transform;
        self.transform_gizmo.drag = None;
        self.transform_gizmo.anchor = None;
        self.clear_feature_dimension_overlay();
        self.sync_transform_gizmo();
    }

    /// Disarm: hide BOTH gizmos + drop any in-flight drag. Also resets the
    /// component Move gizmo (the widget slot is shared, so a disarm clears
    /// whichever controller was feeding it).
    pub fn disarm_transform(&mut self) {
        self.component_move_reset();
        self.transform_gizmo.feature_id = None;
        self.transform_gizmo.mode = GizmoMode::None;
        self.transform_gizmo.drag = None;
        self.transform_gizmo.anchor = None;
        let _ = self.widgets.set_transform_json("null");
        self.clear_feature_dimension_overlay();
        self.dirty = true;
    }

    /// The armed feature's current TRS pose (from its `inputParams.transform`),
    /// or `None` when disarmed / the feature vanished.
    fn armed_pose(&self) -> Option<TransformPose> {
        let id = self.transform_gizmo.feature_id.as_deref()?;
        let index = self.history.index_of(id)?;
        if let Some(anchor) = self.transform_gizmo.anchor {
            // A spline anchor: its position + the intrinsic-XYZ Euler of its
            // stored axis triad (see `spline_edit.rs`).
            let (position, rotation_deg) = self.spline_anchor_pose(index, anchor)?;
            return Some(TransformPose {
                position,
                rotation_deg,
                scale: [1.0, 1.0, 1.0],
            });
        }
        let params = self.history.feature_params(index)?;
        let transform = params.get("transform");
        let pivot = if self.is_xform_feature(index) {
            self.xform_pivot(index, &params)
        } else {
            [0.0; 3]
        };
        // Build the history's expression environment ONCE for the three vectors:
        // a transform component may be an expression string.
        let env = brep_kernel::Env::build(&self.history.expressions(), &self.history.configurator())
            .ok();
        let env = env.as_ref();
        let position = read_pose_vec3(env, transform, "position", [0.0; 3]);
        Some(TransformPose {
            position: std::array::from_fn(|axis| position[axis] + pivot[axis]),
            rotation_deg: read_pose_vec3(env, transform, "rotationEuler", [0.0, 0.0, 0.0]),
            scale: read_pose_vec3(env, transform, "scale", [1.0, 1.0, 1.0]),
        })
    }

    fn is_xform_feature(&self, index: usize) -> bool {
        self.history.feature_type(index).is_some_and(|ty| {
            ty.eq_ignore_ascii_case("XFORM") || ty.eq_ignore_ascii_case("TRANSFORM")
        })
    }

    /// XFORM rotates each selected solid about its own source vertex-bbox center.
    /// Anchor the shared controls to the first resolved solid's pivot; the same
    /// translation/rotation delta still applies to every selected solid.
    fn xform_pivot(&self, index: usize, params: &serde_json::Value) -> [f64; 3] {
        if !params["pivot"]
            .as_str()
            .is_some_and(|p| p.eq_ignore_ascii_case("BBOX_CENTER"))
        {
            return [0.0; 3];
        }
        // Replay the warm current prefix, then fold only results BEFORE XFORM.
        // Using the transformed scene bbox would make the pivot drift on rotation.
        let Ok(request) = serde_json::from_value::<HistoryRequest>(self.history.prefix_request())
        else {
            return [0.0; 3];
        };
        let result = brep_kernel::execute_history(&request);
        let mut handles = HashMap::new();
        for feature in result.results.iter().take(index) {
            for name in &feature.removed {
                handles.remove(name);
            }
            for solid in &feature.added {
                handles.insert(solid.name.clone(), solid.handle);
            }
        }
        let Some(refs) = params["solids"].as_array() else {
            return [0.0; 3];
        };
        for reference in refs {
            let Some(name) = reference.as_str().or_else(|| reference["name"].as_str()) else {
                continue;
            };
            let Some(handle) = handles.get(name.trim()) else {
                continue;
            };
            if let Ok(center) = brep_kernel::transform_pivot_native(*handle) {
                return center;
            }
        }
        [0.0; 3]
    }

    /// (Re)feed the widget gizmo at the armed feature's frame: origin =
    /// `position`, axes = the feature's rotated basis (intrinsic XYZ Euler order, matching
    /// the kernel bake). Auto-disarms if the feature vanished. Called every drag
    /// frame from `transform_drag_to` so the widget tracks the moving pose live
    /// (Fix 3); the drag delta resolves against the frozen grab frame, so this
    /// re-sync never feeds back into the drag math.
    pub fn sync_transform_gizmo(&mut self) {
        // Only the TRANSFORM mode feeds the move/rotate widget; in dimension mode
        // the widget stays hidden (the annotations render as an overlay instead).
        if !matches!(self.transform_gizmo.mode, GizmoMode::Transform) {
            return;
        }
        let Some(pose) = self.armed_pose() else {
            self.disarm_transform();
            return;
        };
        let _ = self
            .widgets
            .set_transform_json(&transform_frame_json(&pose));
        self.dirty = true;
    }

    /// Whether the feature schema exposes the shared Transform controls.
    /// Capability belongs to the schema, not to which default-valued fields
    /// happen to have been serialized in the model.
    pub fn feature_has_transform(&self, feature_id: &str) -> bool {
        self.history
            .index_of(feature_id)
            .and_then(|i| self.history.feature_type(i))
            .and_then(|ty| crate::features::feature_schema(&ty))
            .is_some_and(|schema| schema["inputParamsSchema"]["transform"]["type"] == "transform")
    }

    /// The armed gizmo origin projected to VIEWPORT-LOCAL px (the center handle
    /// sits here). The history panel publishes it so the headed verifier can
    /// locate + drag the gizmo. `None` when disarmed / not projectable (the ONE
    /// [`crate::view::ViewCamera::projectable`] policy — ortho always projects).
    pub fn transform_gizmo_anchor(&self) -> Option<(f64, f64)> {
        let pose = self.armed_pose()?;
        let (sx, sy, _) = self.camera.project(pose.position);
        self.camera.projectable(pose.position).then_some((sx, sy))
    }

    /// The transform gizmo's axis-end labels as JSON:
    /// `[{ text:"XC"|"YC"|"ZC", rgb:[r,g,b], world:[x,y,z] }]`. The app projects
    /// each `world` point and draws the colored egui label just past the matching
    /// cone tip (X=red, Y=green, Z=blue). `[]` unless the TRANSFORM gizmo is armed.
    pub fn transform_axis_labels_json(&self) -> String {
        if !matches!(self.transform_gizmo.mode, GizmoMode::Transform) {
            return "[]".to_string();
        }
        let Some(pose) = self.armed_pose() else {
            return "[]".to_string();
        };
        let euler = [
            pose.rotation_deg[0].to_radians(),
            pose.rotation_deg[1].to_radians(),
            pose.rotation_deg[2].to_radians(),
        ];
        let axes = [
            normalize3(rotate_euler_xyz_f64([1.0, 0.0, 0.0], euler)),
            normalize3(rotate_euler_xyz_f64([0.0, 1.0, 0.0], euler)),
            normalize3(rotate_euler_xyz_f64([0.0, 0.0, 1.0], euler)),
        ];
        // Just past the cone tip, screen-constant.
        let gap_px = 12.0_f64;
        let dist =
            (brep_gizmos::transform::PX_AXIS_LEN as f64 + gap_px) * self.camera.world_per_pixel();
        let labels: [(&str, [f32; 3]); 3] = [
            ("XC", [0.92, 0.26, 0.28]), // red
            ("YC", [0.30, 0.78, 0.36]), // green
            ("ZC", [0.30, 0.52, 0.98]), // blue
        ];
        let out: Vec<serde_json::Value> = (0..3)
            .map(|i| {
                let o = pose.position;
                let a = axes[i];
                serde_json::json!({
                    "text": labels[i].0,
                    "rgb": labels[i].1,
                    "world": [o[0] + a[0] * dist, o[1] + a[1] * dist, o[2] + a[2] * dist],
                })
            })
            .collect();
        serde_json::to_string(&out).unwrap_or_else(|_| "[]".to_string())
    }

    /// Viewport-local pick regions for the debug overlay, shared by feature and
    /// component controllers. The widget feed determines visibility; hidden
    /// widgets return `[]`. The app offsets these circles/capsules by `rect.min`.
    pub fn transform_hit_areas_json(&self) -> String {
        let cam = gizmo_camera(&self.camera);
        let regions = self.widgets.transform_hit_regions(&cam);
        super::camera_widgets::hit_shapes_json(regions.iter().map(|(_, shape)| shape))
    }

    /// Begin a gizmo drag at viewport px `(x, y)` when the gizmo is armed AND a
    /// handle is under the pointer. Returns whether a handle was grabbed — the
    /// viewport routes the drag to the gizmo (not the camera) when `true`; a press
    /// on empty space returns `false` and still orbits.
    pub fn transform_press(&mut self, x: f64, y: f64) -> bool {
        // Only grabbable in TRANSFORM mode — in dimension mode the dimension
        // handles own the pointer (routed by the app), and disarmed grabs nothing.
        if !matches!(self.transform_gizmo.mode, GizmoMode::Transform) {
            return false;
        }
        let handle = self.transform_pick(x, y);
        if handle == 0 {
            return false;
        }
        let Some(pose) = self.armed_pose() else {
            return false;
        };
        self.widgets.set_transform_active(handle);
        self.transform_gizmo.drag = Some(TransformDrag {
            handle,
            sx: x as f32,
            sy: y as f32,
            start: pose,
        });
        self.dirty = true;
        true
    }

    /// Whether a gizmo handle drag is in flight.
    pub fn transform_dragging(&self) -> bool {
        self.transform_gizmo.drag.is_some()
    }

    /// Continue the in-flight gizmo drag to viewport px `(cx, cy)`: resolve the
    /// world delta from the grab (against the frozen grab-time frame), apply it to
    /// the grab pose, write it back into the feature's `transform`, and re-run so
    /// the model follows live. Then re-sync the VISIBLE gizmo to the moved pose so
    /// the widget tracks the pointer in real time (Fix 3) — the delta stays
    /// anchored to `drag.start`, so this visual sync never feeds back on itself.
    pub fn transform_drag_to(&mut self, cx: f64, cy: f64) {
        let Some(drag) = self.transform_gizmo.drag else {
            return;
        };
        let Some(delta) = self.resolve_transform_delta(&drag, cx, cy) else {
            return;
        };
        let pose = apply_transform_delta(&drag.start, &delta);
        self.write_armed_pose(&pose);
        // Live-follow: re-feed the widget frame to the just-written pose. NB
        // `finish_apply` skips this while a drag is in flight (drag.is_some()), so
        // the sync happens here. The active-handle gold highlight survives (the
        // widget only clears it on a `null` feed).
        self.sync_transform_gizmo();
    }

    /// End the drag: clear the active-handle highlight + re-sync the gizmo to the
    /// feature's final (moved) pose (unpin the frame).
    pub fn transform_release(&mut self) {
        if self.transform_gizmo.drag.take().is_some() {
            self.widgets.set_transform_active(0);
            self.sync_transform_gizmo();
        }
    }

    /// Resolve against the grab-time frame so live widget updates cannot
    /// feed back into the drag calculation.
    fn resolve_transform_delta(
        &self,
        drag: &TransformDrag,
        cx: f64,
        cy: f64,
    ) -> Option<TransformDelta> {
        let cam = gizmo_camera(&self.camera);
        let frame_json = transform_frame_json(&drag.start);
        let json = self.widgets.transform_drag_json_with_frame(
            &cam,
            &frame_json,
            drag.handle,
            drag.sx,
            drag.sy,
            cx as f32,
            cy as f32,
        );
        parse_drag_delta(&json)
    }

    /// Write `pose` into the armed feature's `inputParams.transform.{position,
    /// rotationEuler}` (preserving every other field, incl. `scale`) and re-run.
    fn write_armed_pose(&mut self, pose: &TransformPose) {
        let Some(id) = self.transform_gizmo.feature_id.clone() else {
            return;
        };
        let Some(index) = self.history.index_of(&id) else {
            return;
        };
        if let Some(anchor) = self.transform_gizmo.anchor {
            self.write_spline_anchor_pose(&id, anchor, pose.position, pose.rotation_deg);
            return;
        }
        let mut params = self
            .history
            .feature_params(index)
            .unwrap_or_else(|| serde_json::json!({}));
        let pivot = if self.is_xform_feature(index) {
            self.xform_pivot(index, &params)
        } else {
            [0.0; 3]
        };
        let position: [f64; 3] = std::array::from_fn(|axis| pose.position[axis] - pivot[axis]);
        // Ensure `transform` is an object, then set the two edited vectors.
        if !params
            .get("transform")
            .map(|t| t.is_object())
            .unwrap_or(false)
        {
            if let Some(object) = params.as_object_mut() {
                object.insert("transform".into(), serde_json::json!({}));
            }
        }
        if let Some(transform) = params.get_mut("transform").and_then(|t| t.as_object_mut()) {
            transform.insert("position".into(), serde_json::json!(position));
            transform.insert("rotationEuler".into(), serde_json::json!(pose.rotation_deg));
        }
        let _ = self.update_feature_params(&id, &params.to_string());
    }
}

/// Apply translation or world-axis rotation to the grab pose, retaining scale.
fn apply_transform_delta(start: &TransformPose, delta: &TransformDelta) -> TransformPose {
    match delta {
        TransformDelta::Translate(world) => TransformPose {
            position: [
                start.position[0] + world[0],
                start.position[1] + world[1],
                start.position[2] + world[2],
            ],
            ..*start
        },
        TransformDelta::Rotate { axis, radians } => {
            let q0 = quat_from_euler_xyz_deg(start.rotation_deg);
            let dq = quat_from_axis_angle(*axis, *radians);
            let nq = quat_mul(dq, q0);
            TransformPose {
                rotation_deg: euler_xyz_deg_from_quat(nq),
                ..*start
            }
        }
    }
}

/// Read a `[x, y, z]` from a transform sub-field (numbers only; missing / short
/// arrays keep the per-index default).
fn read_pose_vec3(
    env: Option<&brep_kernel::Env>,
    transform: Option<&serde_json::Value>,
    key: &str,
    default: [f64; 3],
) -> [f64; 3] {
    let array = transform
        .and_then(|t| t.get(key))
        .and_then(|v| v.as_array());
    let mut out = default;
    if let Some(array) = array {
        for (index, slot) in out.iter_mut().enumerate() {
            match array.get(index) {
                Some(serde_json::Value::Number(number)) => {
                    if let Some(number) = number.as_f64() {
                        *slot = number;
                    }
                }
                // A component may be an EXPRESSION (`"boxW/2"`) — the kernel
                // evaluates it when it builds, so the gizmo must arm at the same
                // place. Reading it as 0 parked the handles at the world origin
                // while the solid sat elsewhere, and the first drag wrote that
                // wrong origin back as a literal, teleporting the solid.
                Some(serde_json::Value::String(source)) => {
                    if let Some(number) = env
                        .and_then(|env| env.eval(source).ok())
                        .filter(|number| number.is_finite())
                    {
                        *slot = number;
                    }
                }
                _ => {}
            }
        }
    }
    out
}

/// The gizmo frame feed (`set_transform_json` shape) for a pose: origin =
/// `position`, axes = the feature's rotated basis (intrinsic XYZ Euler order, matching
/// the kernel bake), with the center free-move handle shown.
fn transform_frame_json(pose: &TransformPose) -> String {
    let euler = [
        pose.rotation_deg[0].to_radians(),
        pose.rotation_deg[1].to_radians(),
        pose.rotation_deg[2].to_radians(),
    ];
    let x = normalize3(rotate_euler_xyz_f64([1.0, 0.0, 0.0], euler));
    let y = normalize3(rotate_euler_xyz_f64([0.0, 1.0, 0.0], euler));
    let z = normalize3(rotate_euler_xyz_f64([0.0, 0.0, 1.0], euler));
    serde_json::json!({
        "origin": pose.position,
        "x": x,
        "y": y,
        "z": z,
        "showCenter": true,
    })
    .to_string()
}

pub(super) fn normalize3(v: [f64; 3]) -> [f64; 3] {
    let length = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
    if length < 1e-12 {
        [0.0, 0.0, 1.0]
    } else {
        [v[0] / length, v[1] / length, v[2] / length]
    }
}

/// Apply an intrinsic XYZ Euler (radians) to a vector — the EXACT matrix the kernel
/// bake (`transform_bake` / `datum::rotate_euler_xyz`) uses, so the fed gizmo
/// frame aligns with the baked solid.
pub(crate) fn rotate_euler_xyz_f64(v: [f64; 3], euler: [f64; 3]) -> [f64; 3] {
    let (c1, s1) = (euler[0].cos(), euler[0].sin());
    let (c2, s2) = (euler[1].cos(), euler[1].sin());
    let (c3, s3) = (euler[2].cos(), euler[2].sin());
    let m00 = c2 * c3;
    let m01 = -c2 * s3;
    let m02 = s2;
    let m10 = c1 * s3 + c3 * s1 * s2;
    let m11 = c1 * c3 - s1 * s2 * s3;
    let m12 = -c2 * s1;
    let m20 = s1 * s3 - c1 * c3 * s2;
    let m21 = c3 * s1 + c1 * s2 * s3;
    let m22 = c1 * c2;
    [
        m00 * v[0] + m01 * v[1] + m02 * v[2],
        m10 * v[0] + m11 * v[1] + m12 * v[2],
        m20 * v[0] + m21 * v[1] + m22 * v[2],
    ]
}

// --- quaternion helpers (ported from CombinedTransformControls) -----

pub(super) type Quat = [f64; 4]; // [x, y, z, w]

pub(super) fn quat_from_axis_angle(axis: [f64; 3], angle: f64) -> Quat {
    let n = normalize3(axis);
    let half = angle * 0.5;
    let s = half.sin();
    [n[0] * s, n[1] * s, n[2] * s, half.cos()]
}

/// Quaternion from an intrinsic XYZ Euler (degrees in).
pub(super) fn quat_from_euler_xyz_deg(deg: [f64; 3]) -> Quat {
    let (c1, s1) = (
        (deg[0].to_radians() * 0.5).cos(),
        (deg[0].to_radians() * 0.5).sin(),
    );
    let (c2, s2) = (
        (deg[1].to_radians() * 0.5).cos(),
        (deg[1].to_radians() * 0.5).sin(),
    );
    let (c3, s3) = (
        (deg[2].to_radians() * 0.5).cos(),
        (deg[2].to_radians() * 0.5).sin(),
    );
    [
        s1 * c2 * c3 + c1 * s2 * s3,
        c1 * s2 * c3 - s1 * c2 * s3,
        c1 * c2 * s3 + s1 * s2 * c3,
        c1 * c2 * c3 - s1 * s2 * s3,
    ]
}

/// Quaternion product `a * b`.
pub(super) fn quat_mul(a: Quat, b: Quat) -> Quat {
    [
        a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
        a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
        a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
        a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],
    ]
}

/// Intrinsic XYZ Euler from a quaternion (via the rotation matrix) → the
/// 'XYZ' Euler in DEGREES. Uses the SAME matrix element naming as
/// `rotate_euler_xyz_f64`, so the round-trip is consistent with the kernel bake.
pub(super) fn euler_xyz_deg_from_quat(q: Quat) -> [f64; 3] {
    let [x, y, z, w] = q;
    let (x2, y2, z2) = (x + x, y + y, z + z);
    let (xx, xy, xz) = (x * x2, x * y2, x * z2);
    let (yy, yz, zz) = (y * y2, y * z2, z * z2);
    let (wx, wy, wz) = (w * x2, w * y2, w * z2);
    // Rotation matrix elements (m<row><col> naming).
    let m11 = 1.0 - (yy + zz);
    let m12 = xy - wz;
    let m13 = xz + wy;
    let m22 = 1.0 - (xx + zz);
    let m23 = yz - wx;
    let m32 = yz + wx;
    let m33 = 1.0 - (xx + yy);
    let ey = m13.clamp(-1.0, 1.0).asin();
    let (ex, ez) = if m13.abs() < 0.9999999 {
        ((-m23).atan2(m33), (-m12).atan2(m11))
    } else {
        (m32.atan2(m22), 0.0)
    };
    [ex.to_degrees(), ey.to_degrees(), ez.to_degrees()]
}

// BREP private tests: a433bd9d8292ab45