BREP_render 0.1.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
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
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>,
}

/// 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 resolved gizmo drag delta in WORLD space (the ported drag-delta mapping).
#[derive(Clone, Copy, PartialEq, Debug)]
enum TransformDelta {
    /// World-space translation, added to `position`.
    Translate([f64; 3]),
    /// Rotation about a WORLD axis by `radians`, pre-multiplied onto the pose's
    /// orientation (so it spins about the feature's own axis).
    Rotate { axis: [f64; 3], radians: f64 },
    /// No usable delta (unknown handle / degenerate drag).
    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()
        }
    }

    /// 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).
    pub fn arm_transform(&mut self, feature_id: &str) {
        self.transform_gizmo.feature_id = Some(feature_id.to_string());
        self.transform_gizmo.mode = GizmoMode::Transform;
        self.transform_gizmo.drag = None;
        self.clear_feature_dimension_overlay();
        self.sync_transform_gizmo();
    }

    /// Disarm: hide BOTH gizmos + drop any in-flight drag.
    pub fn disarm_transform(&mut self) {
        self.transform_gizmo.feature_id = None;
        self.transform_gizmo.mode = GizmoMode::None;
        self.transform_gizmo.drag = 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)?;
        let params = self.history.feature_params(index)?;
        let transform = params.get("transform");
        Some(TransformPose {
            position: read_pose_vec3(transform, "position", [0.0, 0.0, 0.0]),
            rotation_deg: read_pose_vec3(transform, "rotationEuler", [0.0, 0.0, 0.0]),
            scale: read_pose_vec3(transform, "scale", [1.0, 1.0, 1.0]),
        })
    }

    /// (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 feature `feature_id` carries a `transform` param (a Transform
    /// group), so it CAN show a transform gizmo. The panel's auto-arm-on-expand
    /// uses this: a feature with NO dimension gizmo but WITH a transform
    /// (datum/helix/pattern/port) arms the TRANSFORM gizmo directly on expand,
    /// instead of being left with no gizmo at all now that the ◎ arm button is
    /// gone. (`armed_pose` alone can't gate this — it defaults to identity for a
    /// transform-less feature, so a boolean/fillet would show a spurious gizmo.)
    pub fn feature_has_transform(&self, feature_id: &str) -> bool {
        self.history
            .index_of(feature_id)
            .and_then(|i| self.history.feature_params(i))
            .map(|params| params.get("transform").is_some())
            .unwrap_or(false)
    }

    /// 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 / behind the camera.
    pub fn transform_gizmo_anchor(&self) -> Option<(f64, f64)> {
        let pose = self.armed_pose()?;
        let (sx, sy, depth) = self.camera.project(pose.position);
        (depth > 0.0).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())
    }

    /// 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 delta = self.resolve_transform_delta(&drag, cx, cy);
        if matches!(delta, TransformDelta::None) {
            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 the widget gizmo's frame delta for a drag from the grab to
    /// `(cx, cy)` into a world-space [`TransformDelta`] — via
    /// `WidgetRegistry::transform_drag_json_with_frame` + the ported commit mapping.
    ///
    /// The delta is resolved against the FROZEN grab-time frame (rebuilt from
    /// `drag.start`), NOT the live widget gizmo — so `transform_drag_to` can
    /// re-sync the VISIBLE gizmo to the moving pose every frame (Fix 3 live-follow)
    /// without the visual sync feeding back into the drag math. Since a param
    /// change outside a drag always flows through `finish_apply` → `sync`, the grab
    /// pose is exactly the frame the widget held at grab, so this is behaviorally
    /// identical to the old pinned-widget-frame math — plus the live visual sync.
    fn resolve_transform_delta(&self, drag: &TransformDrag, cx: f64, cy: f64) -> 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,
        );
        let value: serde_json::Value =
            serde_json::from_str(&json).unwrap_or(serde_json::Value::Null);
        match value.get("kind").and_then(|k| k.as_str()) {
            Some("translate") => {
                TransformDelta::Translate(json_vec3(value.get("world").and_then(|a| a.as_array())))
            }
            Some("rotate") => TransformDelta::Rotate {
                axis: json_vec3(value.get("axisWorld").and_then(|a| a.as_array())),
                radians: value.get("radians").and_then(|n| n.as_f64()).unwrap_or(0.0),
            },
            _ => TransformDelta::None,
        }
    }

    /// 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;
        };
        let mut params = self
            .history
            .feature_params(index)
            .unwrap_or_else(|| serde_json::json!({}));
        // 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!(pose.position));
            transform.insert("rotationEuler".into(), serde_json::json!(pose.rotation_deg));
        }
        let _ = self.update_feature_params(&id, &params.to_string());
    }
}

/// Apply a resolved drag delta to the grab pose → the new pose. PURE (the unit
/// test drives it directly). Translation adds the world delta to `position`;
/// rotation pre-multiplies a world-axis quaternion onto the pose's orientation
/// and re-extracts the intrinsic XYZ Euler order (degrees). `scale` is a documented seam
/// (no scale handle exists in the gizmo yet), so it is carried through unchanged.
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
            }
        }
        TransformDelta::None => *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(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() {
            if let Some(number) = array.get(index).and_then(|v| v.as_f64()) {
                *slot = number;
            }
        }
    }
    out
}

/// A `[f64; 3]` from a JSON number array (zero-filled past the end).
fn json_vec3(array: Option<&Vec<serde_json::Value>>) -> [f64; 3] {
    let mut out = [0.0; 3];
    if let Some(array) = array {
        for (index, slot) in out.iter_mut().enumerate() {
            if let Some(number) = array.get(index).and_then(|v| v.as_f64()) {
                *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()
}

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) -----

type Quat = [f64; 4]; // [x, y, z, w]

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).
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`.
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.
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()]
}

#[cfg(test)]
mod transform_gizmo_tests {
    use super::*;

    /// A one-feature history document: a `P.CU` cube `name` at the origin with an
    /// identity transform (so the gizmo arms at [0,0,0], world XYZ frame).
    fn cube_request(name: &str, size: f64) -> String {
        serde_json::json!({
            "expressions": "",
            "configurator": {},
            "features": [{
                "type": "P.CU",
                "inputParams": {
                    "id": name,
                    "sizeX": size, "sizeY": size, "sizeZ": size,
                    "transform": {
                        "position": [0.0, 0.0, 0.0],
                        "rotationEuler": [0.0, 0.0, 0.0],
                        "scale": [1.0, 1.0, 1.0]
                    },
                    "boolean": { "targets": [], "operation": "NONE" }
                },
                "persistentData": {}
            }]
        })
        .to_string()
    }

    fn ident() -> TransformPose {
        TransformPose {
            position: [1.0, 2.0, 3.0],
            rotation_deg: [0.0, 0.0, 0.0],
            scale: [1.0, 1.0, 1.0],
        }
    }

    #[test]
    fn translate_delta_adds_world_to_position() {
        let pose = apply_transform_delta(&ident(), &TransformDelta::Translate([4.0, -1.0, 0.5]));
        assert_eq!(pose.position, [5.0, 1.0, 3.5]);
        assert_eq!(pose.rotation_deg, [0.0, 0.0, 0.0]);
        assert_eq!(pose.scale, [1.0, 1.0, 1.0]);
    }

    #[test]
    fn rotate_delta_about_z_yields_z_euler() {
        // +90° about world +Z from identity orientation → rotationEuler [0,0,90].
        let pose = apply_transform_delta(
            &ident(),
            &TransformDelta::Rotate {
                axis: [0.0, 0.0, 1.0],
                radians: std::f64::consts::FRAC_PI_2,
            },
        );
        assert!((pose.rotation_deg[0]).abs() < 1e-6, "{:?}", pose.rotation_deg);
        assert!((pose.rotation_deg[1]).abs() < 1e-6, "{:?}", pose.rotation_deg);
        assert!((pose.rotation_deg[2] - 90.0).abs() < 1e-4, "{:?}", pose.rotation_deg);
        // Rotation pivots about the origin → position holds.
        assert_eq!(pose.position, [1.0, 2.0, 3.0]);
    }

    #[test]
    fn euler_quat_roundtrip_is_identity() {
        // A non-gimbal compound rotation round-trips euler→quat→euler.
        let deg = [30.0, 45.0, 60.0];
        let back = euler_xyz_deg_from_quat(quat_from_euler_xyz_deg(deg));
        for k in 0..3 {
            assert!((back[k] - deg[k]).abs() < 1e-4, "axis {k}: {back:?} vs {deg:?}");
        }
    }

    #[test]
    fn rotate_about_local_axis_composes_onto_existing_orientation() {
        // Start already rotated 90° about Z; add 90° about the (world) Z axis →
        // 180° about Z. Pre-multiplying the world-Z delta gives a valid euler for
        // a 180°-about-Z orientation (±180 about Z is equivalent).
        let start = TransformPose {
            rotation_deg: [0.0, 0.0, 90.0],
            ..ident()
        };
        let pose = apply_transform_delta(
            &start,
            &TransformDelta::Rotate {
                axis: [0.0, 0.0, 1.0],
                radians: std::f64::consts::FRAC_PI_2,
            },
        );
        // Compare orientations via the quaternion (euler triples for 180°-Z can
        // be [0,0,180] or [180,0,-180]…; the quaternion is unambiguous up to sign).
        let got = quat_from_euler_xyz_deg(pose.rotation_deg);
        let want = quat_from_euler_xyz_deg([0.0, 0.0, 180.0]);
        let dot = got[0] * want[0] + got[1] * want[1] + got[2] * want[2] + got[3] * want[3];
        assert!(dot.abs() > 0.9999, "orientation mismatch: {got:?} vs {want:?}");
    }

    #[test]
    fn arm_press_drag_moves_the_feature_then_disarms() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_request("Pin", 10.0)).unwrap();
        engine.resize(800.0, 600.0);
        engine.camera.eye = [0.0, 0.0, 40.0];
        engine.camera.target = [0.0, 0.0, 0.0];
        engine.camera.up = [0.0, 1.0, 0.0];
        engine.camera.projection = crate::view::Projection::Orthographic { half_height: 20.0 };

        assert!(!engine.transform_armed());
        engine.arm_transform("Pin");
        assert!(engine.transform_armed() && engine.transform_armed_for("Pin"));
        assert!(engine.widgets.has_transform(), "arming feeds the widget gizmo");

        // The gizmo origin (= Pin position [0,0,0]) projects to the viewport
        // center; the center free-move handle sits there.
        let (ax, ay) = engine.transform_gizmo_anchor().expect("armed anchor");
        assert!((ax - 400.0).abs() < 1.0 && (ay - 300.0).abs() < 1.0, "anchor {ax},{ay}");

        // The VISIBLE gizmo origin starts at the grab pose (Pin at the world origin).
        let origin_before = engine.widgets.transform_origin().expect("gizmo shown");
        assert!(origin_before[0].abs() < 1e-4, "gizmo starts at x=0: {origin_before:?}");

        // Press the handle + drag screen-right → +X world translate.
        assert!(engine.transform_press(ax, ay), "press grabs a handle");
        assert!(engine.transform_dragging());
        engine.transform_drag_to(ax + 60.0, ay);

        let index = engine.history.index_of("Pin").unwrap();
        let params = engine.history.feature_params(index).unwrap();
        let moved_x = params["transform"]["position"][0].as_f64().unwrap();
        assert!(moved_x > 0.0, "Pin moved +X, got {:?}", params["transform"]["position"]);

        // Fix 3 live-follow: MID-DRAG (before release) the VISIBLE gizmo has already
        // re-synced to the moved pose — its origin tracks the feature's new +X
        // position, so the widget follows the pointer in real time. And it matches
        // the just-written param (no drift between widget + feature).
        let origin_mid = engine.widgets.transform_origin().expect("gizmo still shown");
        assert!(
            origin_mid[0] > 0.0 && (origin_mid[0] as f64 - moved_x).abs() < 1e-3,
            "gizmo should follow to x={moved_x} mid-drag, got {origin_mid:?}"
        );
        // The active-handle gold highlight survives the per-frame re-sync.
        assert!(engine.transform_dragging(), "still dragging after the live re-sync");

        engine.transform_release();
        assert!(!engine.transform_dragging());

        engine.disarm_transform();
        assert!(!engine.transform_armed());
        assert!(!engine.widgets.has_transform(), "disarm hides the gizmo");
    }

    #[test]
    fn deleting_the_armed_feature_auto_disarms() {
        let mut engine = EngineState::new();
        engine.set_history_json(&cube_request("Pin", 10.0)).unwrap();
        engine.arm_transform("Pin");
        assert!(engine.transform_armed());
        // Removing the feature and re-running should drop the gizmo (the sync
        // hook in `rerun_history` finds no pose and disarms).
        engine.delete_feature("Pin");
        assert!(!engine.transform_armed(), "armed feature gone → auto-disarm");
        assert!(!engine.widgets.has_transform());
    }
}

// ============================================================================
// Modeling selection UX — hover highlight + multi-select toggle + the
// "candidates under the cursor" list. Appended as its OWN `impl` block (purely
// additive over the existing pick/selection API) so concurrent edits to the
// primary block + the transform-gizmo block don't conflict.
//
// The three are tied together through the SAME filter-respecting engine pick
// (`pick::pick` / `pick::pick_filtered` with the selection filter's enabled
// kinds), so hover, a plain/Ctrl click, and the candidate list all agree on
// what is under the cursor and in what order.
//
// Ports the retired viewer's selection methods:
//   * hover      — `_updateHover` → `SelectionFilter.setHoverRef(primary)` /
//                  `clearHover()`; `hover_at` sets the top admitted pick HOVERED.
//   * multi-sel  — the ref-store `toggleRef` (Ctrl/Cmd add) vs `setHoverRef`
//                  replace; `select_toggle_at` adds/removes without clearing.
//   * candidates — `_collectSelectionCandidates` builds the ranked pick list and
//                  its FINAL sort (see the note on `candidates_filtered_at`).
// ============================================================================