BREP_gizmos 0.2.0

BREP in-scene gizmos and overlay widgets (transform gizmo, ViewCube, datum/axis visuals, dimension leaders). Pure geometry + hit-testing, no kernel or GPU dependency — the render engine consumes the emitted overlay geometry. A CPU rasterizer is provided for headless demo/verification.
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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
//! Transform gizmo — the move + rotate widget for the Rust rendering
//! engine. This is the pure-geometry + hit-testing reimplementation of the
//! app's `CombinedTransformControls`:
//! 3 axis translate arrows, 3 planar translate quads, 3 rotation rings, and an
//! optional center free-move handle. It holds NO interaction state and touches
//! neither the kernel nor the GPU — it consumes a [`GizmoCamera`] and emits an
//! [`Overlay`], answers [`Gizmo::hit`], and computes frame-space drag deltas.
//!
//! ## Integration contract (engine / wasm / host)
//!
//! Everything below is what the surrounding engine must feed the gizmo and what
//! it gets back. The serial wiring into `brep-render`'s overlay pass + the wasm
//! API is mechanical — no gizmo logic changes.
//!
//! FEED, every frame:
//!   * `GizmoCamera` — build from the live engine camera (view_proj, eye,
//!     forward, viewport, orthographic). Same struct the engine already mirrors.
//!   * The FEATURE FRAME — call [`TransformGizmo::set_frame`] with the selected
//!     feature's origin + 3 orthonormal axes (R28: drags happen in the feature's
//!     frame, +Z-up world convention). Defaults to world XYZ at the origin.
//!
//! FEED, on hover / pick (pointer move & down):
//!   * The screen point (CSS px, top-left origin, y down). Call
//!     [`Gizmo::hit`] → `Option<HandleId>`. The host keeps this as the "hovered"
//!     handle; on pointer-down it becomes the "active" (dragged) handle.
//!
//! FEED, each drag move:
//!   * The active `HandleId` (echoed back from the host), the START ray and the
//!     CURRENT ray. Build rays with `camera.ray_from_screen(x, y)` at the
//!     pointer-down point and the current pointer point. Call
//!     [`TransformGizmo::drag_delta`].
//!
//! GET BACK:
//!   * From [`Gizmo::geometry`] — an [`Overlay`] (world-space colored line
//!     segments + triangles) to convert into the engine's overlay vertex
//!     buffers. Pass the hovered/active handle so the highlighted handle draws
//!     gold.
//!   * From [`Gizmo::hit`] — the `HandleId` under the pointer (or `None`).
//!   * From [`TransformGizmo::drag_delta`] — a [`DragDelta`] in the gizmo's
//!     FRAME: `Translate(v)` where `v`'s components are distances along
//!     `ex/ey/ez` (world delta = `ex*v.x + ey*v.y + ez*v.z`), or
//!     `Rotate { axis_index, radians }` (signed rotation about that frame axis).
//!     The host turns this into the feature-edit commit callback (translate the datum,
//!     rotate the sketch plane, etc.). For a continuous drag either feed the
//!     original pointer-down ray as `start` (absolute delta from grab) or the
//!     previous-frame ray (incremental) — both are supported; rotation uses a
//!     signed-angle so incremental feeding avoids the ±180° wrap.

use crate::{Gizmo, GizmoCamera, HandleId, Overlay};
use crate::hit_region::{point_region, segment_region, HitShape};
use crate::math::{Ray, Vec3};

// --- stable handle ids -----------------------------------------------------

/// Body / no specific handle (contract convention).
pub const HANDLE_NONE: HandleId = 0;
/// Axis translate arrows.
pub const HANDLE_AXIS_X: HandleId = 1;
pub const HANDLE_AXIS_Y: HandleId = 2;
pub const HANDLE_AXIS_Z: HandleId = 3;
/// Planar translate quads (named by the two in-plane axes).
pub const HANDLE_PLANE_XY: HandleId = 4;
pub const HANDLE_PLANE_YZ: HandleId = 5;
pub const HANDLE_PLANE_ZX: HandleId = 6;
/// Rotation rings (named by the axis they turn about).
pub const HANDLE_RING_X: HandleId = 7;
pub const HANDLE_RING_Y: HandleId = 8;
pub const HANDLE_RING_Z: HandleId = 9;
/// Center free-move / uniform handle (screen-plane translate).
pub const HANDLE_CENTER: HandleId = 10;

// --- colors (linear RGBA) --------------------------------------------------

// Restyled gizmo look (matches the reference transform-controls image): an
// ORANGE center sphere, silver-grey axis shafts drawn as solid 3D rods (tubes)
// with orange CONE tips, three light-grey ROTATION ARCS joining adjacent axis
// tips (the rounded-triangle silhouette), and orange grab SPHERES for rotation.
// Colors are display sRGB values written ~directly by the overlay shader (with a
// per-face shade for depth), so use hex/255 — no linear conversion.
const C_ROD: [f32; 4] = [0.80, 0.81, 0.82, 1.0]; // silver-grey rod shafts (~0xccced1)
const C_ARROW: [f32; 4] = [0.961, 0.651, 0.137, 1.0]; // orange cone tips (#F5A623)
const C_RING: [f32; 4] = [0.91, 0.91, 0.91, 1.0]; // light-grey rotation arcs (~0xe8e8e8)
const C_DOT: [f32; 4] = [0.961, 0.651, 0.137, 1.0]; // orange rotation grab spheres (#F5A623)
const C_GOLD: [f32; 4] = [1.00, 0.85, 0.35, 1.0]; // hover/active highlight (amber)
const C_CENTER: [f32; 4] = [0.961, 0.651, 0.137, 1.0]; // orange center sphere (#F5A623)

// --- pixel sizing (screen-constant; multiplied by world_per_pixel) ---------

/// Arrow tip distance from the origin (CSS px). Public so the app can place the
/// egui axis labels (`XC`/`YC`/`ZC`) just past each cone tip. Chosen so the cone
/// BASE (`PX_AXIS_LEN - PX_HEAD_LEN` = 72) sits a few px OUTSIDE the rotation arc
/// (`PX_ARC_RAD` = 64): the arcs join the shafts and the cones poke past them, so
/// the white arcs never cut through the orange arrowheads.
pub const PX_AXIS_LEN: f32 = 90.0;
const PX_SHAFT_START: f32 = 8.0; // shaft begins this far out (emerges from the center sphere)
const PX_HEAD_LEN: f32 = 18.0; // arrowhead cone length
const PX_HEAD_RAD: f32 = 7.0; // arrowhead cone base radius
const PX_SHAFT_RAD: f32 = 2.2; // silver-rod shaft radius (thick, reads as a 3D rod)
const PX_ARC_RAD: f32 = 64.0; // rotation-arc radius (arcs join the SHAFTS, inside the cone bases)
/// Center free-move sphere radius (CSS px). Public so a debug overlay can outline
/// the exact pickable disc without re-deriving it.
pub const PX_CENTER_RAD: f32 = 7.0;
/// Orange rotation grab-sphere radius (CSS px). Public for the same reason.
pub const PX_RING_GRAB_RAD: f32 = 5.0;

/// Screen-pixel half-width of the axis-arrow (and rotation-arc) hit test: a
/// cursor within this many px of a handle's projected drawn segment grabs it (see
/// [`TransformGizmo::hit`]). Public so a debug overlay can outline the EXACT
/// pickable region (a stadium of this radius around the projected axis segment)
/// without re-deriving — the drawn radius can never drift from the hit radius.
pub const AXIS_HIT_THRESH_PX: f32 = 7.0;

const RING_SEGMENTS: usize = 24; // samples per quarter rotation arc
const CONE_SEGMENTS: usize = 16; // radial facets of an arrowhead cone
const TUBE_SEGMENTS: usize = 8; // radial facets of a shaft rod
const SPHERE_RINGS: usize = 6; // latitude bands of a handle sphere
const SPHERE_SECTORS: usize = 10; // longitude sectors of a handle sphere

/// The three rotation arcs as `(rotation-axis index, in-plane axis i, in-plane
/// axis j)`. Each arc sweeps from tip `i` to tip `j` in the plane whose normal
/// is the rotation axis, so grabbing it rotates about that axis.
const ARCS: [(usize, usize, usize); 3] = [(2, 0, 1), (0, 1, 2), (1, 2, 0)];

/// Screen-constant handle sizes in world units at the gizmo origin.
#[derive(Debug, Clone, Copy)]
struct Sizes {
    px: f32,
    axis_len: f32,
    shaft_start: f32,
    head_len: f32,
    head_rad: f32,
    shaft_rad: f32,
    arc_rad: f32,
    center_rad: f32,
    grab_rad: f32,
}

/// The result of a drag, expressed in the gizmo's FRAME (see module docs).
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DragDelta {
    /// Translation whose components are distances along `ex`, `ey`, `ez`.
    /// World delta = `ex*v.x + ey*v.y + ez*v.z`.
    Translate(Vec3),
    /// Signed rotation about frame axis `axis_index` (0=ex, 1=ey, 2=ez).
    Rotate { axis_index: usize, radians: f32 },
    /// No usable delta (unknown handle or a degenerate ray/plane).
    None,
}

/// A move + rotate gizmo positioned at an origin with an orientation frame.
#[derive(Debug, Clone, Copy)]
pub struct TransformGizmo {
    /// Gizmo origin in world space.
    pub origin: Vec3,
    /// Frame X axis (unit, world space).
    pub ex: Vec3,
    /// Frame Y axis (unit, world space).
    pub ey: Vec3,
    /// Frame Z axis (unit, world space).
    pub ez: Vec3,
    /// Whether to draw + hit-test the center free-move handle.
    pub show_center: bool,
    /// Whether to draw + hit-test the three axis translate ARROWS. Off for a
    /// rotate-only gizmo (the component Move toggle's "rotate" step).
    pub show_axes: bool,
    /// Whether to draw + hit-test the three rotation ARCS + their grab spheres.
    /// Off for a translate-only gizmo (the component Move toggle's "translate"
    /// step).
    pub show_rings: bool,
}

impl Default for TransformGizmo {
    fn default() -> Self {
        Self {
            origin: Vec3::ZERO,
            ex: Vec3::X,
            ey: Vec3::Y,
            ez: Vec3::Z,
            show_center: true,
            show_axes: true,
            show_rings: true,
        }
    }
}

impl TransformGizmo {
    /// A gizmo at `origin` with the world XYZ frame.
    pub fn at(origin: Vec3) -> Self {
        Self { origin, ..Self::default() }
    }

    /// Set the origin + orientation frame (the feature's frame). The axes are
    /// re-orthonormalized defensively (ex kept, ez = ex×ey, ey = ez×ex).
    pub fn set_frame(&mut self, origin: Vec3, ex: Vec3, ey: Vec3, ez: Vec3) {
        self.origin = origin;
        let ex = ex.normalized();
        let mut ez = ez.normalized();
        if ez.length() < 1e-6 {
            ez = ex.cross(ey).normalized();
        }
        let ey = ez.cross(ex).normalized();
        let ez = ex.cross(ey).normalized();
        self.ex = ex;
        self.ey = ey;
        self.ez = ez;
    }

    /// World-space unit axis for `i` (0=ex, 1=ey, 2=ez).
    pub fn axis(&self, i: usize) -> Vec3 {
        match i {
            0 => self.ex,
            1 => self.ey,
            _ => self.ez,
        }
    }

    fn sizes(&self, camera: &GizmoCamera) -> Sizes {
        let px = camera.world_per_pixel(self.origin).max(1e-6);
        Sizes {
            px,
            axis_len: PX_AXIS_LEN * px,
            shaft_start: PX_SHAFT_START * px,
            head_len: PX_HEAD_LEN * px,
            head_rad: PX_HEAD_RAD * px,
            shaft_rad: PX_SHAFT_RAD * px,
            arc_rad: PX_ARC_RAD * px,
            center_rad: PX_CENTER_RAD * px,
            grab_rad: PX_RING_GRAB_RAD * px,
        }
    }

    /// The world-space (shaft-start, tip) endpoints of axis arrow `i`. Exposed
    /// so callers/tests can locate a handle without duplicating the sizing.
    pub fn axis_seg(&self, camera: &GizmoCamera, i: usize) -> (Vec3, Vec3) {
        let s = self.sizes(camera);
        let a = self.axis(i);
        (
            self.origin.add(a.scale(s.shaft_start)),
            self.origin.add(a.scale(s.axis_len)),
        )
    }

    /// The world-space center free-move / origin sphere point (the `HANDLE_CENTER`
    /// ball), or `None` when the center handle is hidden. Exposed so a debug
    /// overlay can outline the exact pickable disc (radius [`PX_CENTER_RAD`]).
    pub fn center_grab_point(&self) -> Option<Vec3> {
        self.show_center.then_some(self.origin)
    }

    /// The three rotation grab-sphere world points (one per rotation arc, in
    /// `ARCS` order), at the drawn arc-midpoint radius. Exposed so a debug overlay
    /// can outline each ball (radius [`PX_RING_GRAB_RAD`]).
    pub fn ring_grab_points(&self, camera: &GizmoCamera) -> [Vec3; 3] {
        let s = self.sizes(camera);
        let mut out = [Vec3::ZERO; 3];
        for (idx, (_, i, j)) in ARCS.iter().enumerate() {
            out[idx] = self.arc_grab_point(*i, *j, &s);
        }
        out
    }

    // -- drag math (pure; no state) -----------------------------------------

    /// Frame-space delta for the active `handle` given the drag's start & current
    /// rays (build both with `camera.ray_from_screen`). See [`DragDelta`].
    pub fn drag_delta(
        &self,
        camera: &GizmoCamera,
        handle: HandleId,
        start: Ray,
        current: Ray,
    ) -> DragDelta {
        match handle {
            HANDLE_AXIS_X => DragDelta::Translate(self.axis_translate(camera, 0, start, current)),
            HANDLE_AXIS_Y => DragDelta::Translate(self.axis_translate(camera, 1, start, current)),
            HANDLE_AXIS_Z => DragDelta::Translate(self.axis_translate(camera, 2, start, current)),
            HANDLE_PLANE_XY => DragDelta::Translate(self.plane_translate(0, 1, start, current)),
            HANDLE_PLANE_YZ => DragDelta::Translate(self.plane_translate(1, 2, start, current)),
            HANDLE_PLANE_ZX => DragDelta::Translate(self.plane_translate(2, 0, start, current)),
            HANDLE_RING_X => DragDelta::Rotate { axis_index: 0, radians: self.ring_rotate(0, start, current) },
            HANDLE_RING_Y => DragDelta::Rotate { axis_index: 1, radians: self.ring_rotate(1, start, current) },
            HANDLE_RING_Z => DragDelta::Rotate { axis_index: 2, radians: self.ring_rotate(2, start, current) },
            HANDLE_CENTER => DragDelta::Translate(self.center_translate(camera, start, current)),
            _ => DragDelta::None,
        }
    }

    /// Axis translate: project the camera-facing-plane movement onto the axis.
    /// Returns a frame-local vector with only component `i` set.
    pub fn axis_translate(&self, camera: &GizmoCamera, i: usize, start: Ray, current: Ray) -> Vec3 {
        let n = camera.forward.normalized();
        let (p0, p1) = match (
            plane_point(&start, self.origin, n),
            plane_point(&current, self.origin, n),
        ) {
            (Some(a), Some(b)) => (a, b),
            _ => return Vec3::ZERO,
        };
        let d = p1.sub(p0).dot(self.axis(i));
        let mut out = Vec3::ZERO;
        match i {
            0 => out.x = d,
            1 => out.y = d,
            _ => out.z = d,
        }
        out
    }

    /// Planar translate: intersect both rays with the plane spanned by frame
    /// axes `i` and `j` (normal = the third axis) through the origin. Returns a
    /// frame-local vector with components `i` and `j` set.
    pub fn plane_translate(&self, i: usize, j: usize, start: Ray, current: Ray) -> Vec3 {
        let k = 3 - i - j; // the remaining index → plane normal
        let n = self.axis(k);
        let (p0, p1) = match (
            plane_point(&start, self.origin, n),
            plane_point(&current, self.origin, n),
        ) {
            (Some(a), Some(b)) => (a, b),
            _ => return Vec3::ZERO,
        };
        let delta = p1.sub(p0);
        let a = delta.dot(self.axis(i));
        let b = delta.dot(self.axis(j));
        let mut out = Vec3::ZERO;
        set_comp(&mut out, i, a);
        set_comp(&mut out, j, b);
        out
    }

    /// Ring rotate: signed angle about frame axis `i` between the start & current
    /// ray intersections with the plane through the origin perpendicular to `i`.
    pub fn ring_rotate(&self, i: usize, start: Ray, current: Ray) -> f32 {
        let n = self.axis(i);
        let (p0, p1) = match (
            plane_point(&start, self.origin, n),
            plane_point(&current, self.origin, n),
        ) {
            (Some(a), Some(b)) => (a, b),
            _ => return 0.0,
        };
        let v0 = p0.sub(self.origin);
        let v1 = p1.sub(self.origin);
        if v0.length() < 1e-9 || v1.length() < 1e-9 {
            return 0.0;
        }
        let v0 = v0.normalized();
        let v1 = v1.normalized();
        let cross = v0.cross(v1).dot(n);
        let dot = v0.dot(v1).clamp(-1.0, 1.0);
        cross.atan2(dot)
    }

    /// Center free-move: screen-plane translate, returned in full frame-local
    /// coordinates (all three components may be set).
    pub fn center_translate(&self, camera: &GizmoCamera, start: Ray, current: Ray) -> Vec3 {
        let n = camera.forward.normalized();
        let (p0, p1) = match (
            plane_point(&start, self.origin, n),
            plane_point(&current, self.origin, n),
        ) {
            (Some(a), Some(b)) => (a, b),
            _ => return Vec3::ZERO,
        };
        let delta = p1.sub(p0);
        Vec3::new(delta.dot(self.ex), delta.dot(self.ey), delta.dot(self.ez))
    }

    // -- geometry helpers ---------------------------------------------------

    /// A point on the rotation arc that sweeps from tip `i` to tip `j` (in the
    /// plane whose normal is the third frame axis), parameter `t` in `0..=1`.
    fn arc_point(&self, i: usize, j: usize, t: f32, radius: f32) -> Vec3 {
        let ang = t * std::f32::consts::FRAC_PI_2;
        self.origin
            .add(self.axis(i).scale(ang.cos() * radius))
            .add(self.axis(j).scale(ang.sin() * radius))
    }

    /// The orange grab sphere position for the arc `(i, j)`: the MIDPOINT of the
    /// quarter arc (`t = 0.5`, the 45° bisector angle) at the arc radius, so the
    /// handle sits ON the drawn arc curve.
    fn arc_grab_point(&self, i: usize, j: usize, s: &Sizes) -> Vec3 {
        self.arc_point(i, j, 0.5, s.arc_rad)
    }

    fn draw_axis_arrow(
        &self,
        ov: &mut Overlay,
        s: &Sizes,
        i: usize,
        shaft_color: [f32; 4],
        head_color: [f32; 4],
    ) {
        let a = self.axis(i);
        let shaft_a = self.origin.add(a.scale(s.shaft_start));
        let base = self.origin.add(a.scale(s.axis_len - s.head_len));
        let tip = self.origin.add(a.scale(s.axis_len));
        // Silver rod shaft as a solid 3D tube (thick; per-element geometry since
        // the overlay line width is a single per-pass value).
        push_tube(ov, shaft_a, base, s.shaft_rad, shaft_color);
        // Orange arrowhead cone (side + base cap).
        push_cone(ov, base, tip, s.head_rad, head_color);
    }

    fn draw_arc(&self, ov: &mut Overlay, i: usize, j: usize, s: &Sizes, color: [f32; 4]) {
        let mut prev = self.arc_point(i, j, 0.0, s.arc_rad);
        for k in 1..=RING_SEGMENTS {
            let t = k as f32 / RING_SEGMENTS as f32;
            let cur = self.arc_point(i, j, t, s.arc_rad);
            ov.line(prev, cur, color);
            prev = cur;
        }
    }

    fn draw_center(&self, ov: &mut Overlay, s: &Sizes, color: [f32; 4]) {
        push_sphere(ov, self.origin, s.center_rad, color);
    }

    fn highlight(id: HandleId, base: [f32; 4], hovered: Option<HandleId>, active: Option<HandleId>) -> [f32; 4] {
        if active == Some(id) || hovered == Some(id) {
            C_GOLD
        } else {
            base
        }
    }
}

impl Gizmo for TransformGizmo {
    fn geometry(
        &self,
        camera: &GizmoCamera,
        hovered: Option<HandleId>,
        active: Option<HandleId>,
    ) -> Overlay {
        let s = self.sizes(camera);
        let mut ov = Overlay::new();

        let hl = |id, base| Self::highlight(id, base, hovered, active);

        // Rotation arcs — light-grey quarter arcs joining adjacent axis shafts
        // (the rounded-triangle silhouette), each with an orange grab sphere ON
        // the arc midpoint. Arc `(k, i, j)` rotates about axis `k`.
        if self.show_rings {
            for (k, i, j) in ARCS {
                let id = ring_handle(k);
                self.draw_arc(&mut ov, i, j, &s, hl(id, C_RING));
                push_sphere(&mut ov, self.arc_grab_point(i, j, &s), s.grab_rad, hl(id, C_DOT));
            }
        }

        // Axis translate arrows — silver rod shaft, orange cone head.
        if self.show_axes {
            for (i, id) in [(0, HANDLE_AXIS_X), (1, HANDLE_AXIS_Y), (2, HANDLE_AXIS_Z)] {
                self.draw_axis_arrow(&mut ov, &s, i, hl(id, C_ROD), hl(id, C_ARROW));
            }
        }

        // Center free-move handle — orange sphere.
        if self.show_center {
            self.draw_center(&mut ov, &s, hl(HANDLE_CENTER, C_CENTER));
        }

        ov
    }

    fn hit(&self, camera: &GizmoCamera, screen: [f32; 2]) -> Option<HandleId> {
        // Test the cursor against the SAME screen-space regions the debug outline
        // draws ([`hit_regions`]): a 2D point-in-region test, so the grabbable
        // area IS the drawn outline. Rank breaks ambiguous overlaps — axis arrows
        // and the center handle are RANK 0 (arrows are always the top drag
        // priority), the rotation rings RANK 1, so an arrow beats a ring where
        // both contain the cursor; within a rank the nearest spine wins.
        let mut best: Option<(u8, f32, HandleId)> = None;
        for (id, shape) in self.hit_regions(camera) {
            let d = shape.spine_distance(screen);
            if d > shape.radius() {
                continue;
            }
            let rank = if is_ring(id) { 1 } else { 0 };
            match best {
                Some((br, bd, _)) if (br, bd) <= (rank, d) => {}
                _ => best = Some((rank, d, id)),
            }
        }
        best.map(|(_, _, id)| id)
    }
}

impl TransformGizmo {
    /// The authoritative screen-space pickable region of every draggable handle,
    /// each paired with its [`HandleId`]. The SINGLE source both [`Gizmo::hit`]
    /// (which 2D-tests the cursor against these) and the debug outline
    /// (`transform_hit_areas_json`, which strokes these) consume — so the
    /// grabbable area can never drift from the drawn outline. Projection + the
    /// perspective front-clip happen ONCE, in [`crate::hit_region`]. Kinds match
    /// the drawn handles exactly:
    ///   * center free-move sphere → CIRCLE (`PX_CENTER_RAD + 2`).
    ///   * 3 axis arrows → CAPSULE on the drawn `axis_seg` (`AXIS_HIT_THRESH_PX`).
    ///   * 3 rotation grab spheres → CIRCLE (`PX_RING_GRAB_RAD + 3`) — the ring's
    ///     ONLY hit region, matching its ONLY drawn outline (the grab sphere).
    /// The CENTER is emitted first so that on an EXACT tie it beats a coincident
    /// axis — when the view looks straight down an axis, that axis foreshortens
    /// onto the origin, and the (undraggable, screen-perpendicular) axis must not
    /// steal the center free-move handle (see [`Gizmo::hit`]'s first-wins tie).
    pub fn hit_regions(&self, camera: &GizmoCamera) -> Vec<(HandleId, HitShape)> {
        let s = self.sizes(camera);
        let mut out: Vec<(HandleId, HitShape)> = Vec::with_capacity(7);
        // Center free-move ball (FIRST — wins an exact tie with a coincident axis).
        if self.show_center {
            if let Some(shape) = point_region(camera, v3(self.origin), PX_CENTER_RAD + 2.0) {
                out.push((HANDLE_CENTER, shape));
            }
        }
        // Axis arrows — capsule on the drawn (shaft-start, tip) segment.
        if self.show_axes {
            for (i, id) in [(0, HANDLE_AXIS_X), (1, HANDLE_AXIS_Y), (2, HANDLE_AXIS_Z)] {
                let (a, b) = self.axis_seg(camera, i);
                if let Some(shape) = segment_region(camera, v3(a), v3(b), AXIS_HIT_THRESH_PX) {
                    out.push((id, shape));
                }
            }
        }
        // Rotation grab balls (one per arc, at the arc midpoint).
        if self.show_rings {
            for (k, i, j) in ARCS {
                let grab = self.arc_grab_point(i, j, &s);
                if let Some(shape) = point_region(camera, v3(grab), PX_RING_GRAB_RAD + 3.0) {
                    out.push((ring_handle(k), shape));
                }
            }
        }
        out
    }
}

/// A world point as `[f64; 3]` for the (f64) screen-space region builder.
fn v3(v: Vec3) -> [f64; 3] {
    [v.x as f64, v.y as f64, v.z as f64]
}

/// Whether `id` is a rotation-ring handle (ranked below the axis arrows).
fn is_ring(id: HandleId) -> bool {
    matches!(id, HANDLE_RING_X | HANDLE_RING_Y | HANDLE_RING_Z)
}

// --- free helpers ----------------------------------------------------------

fn plane_point(ray: &Ray, p0: Vec3, n: Vec3) -> Option<Vec3> {
    ray.intersect_plane(p0, n).map(|t| ray.at(t))
}

fn set_comp(v: &mut Vec3, i: usize, val: f32) {
    match i {
        0 => v.x = val,
        1 => v.y = val,
        _ => v.z = val,
    }
}

/// The rotation-ring handle id for rotation about frame axis `k`.
fn ring_handle(k: usize) -> HandleId {
    match k {
        0 => HANDLE_RING_X,
        1 => HANDLE_RING_Y,
        _ => HANDLE_RING_Z,
    }
}

/// A radially-symmetric perpendicular basis `(u, v)` for a unit `axis`.
fn axis_basis(axis: Vec3) -> (Vec3, Vec3) {
    let u = axis.any_perp();
    let v = axis.cross(u).normalized();
    (u, v)
}

/// Push a solid 3D rod (open-ended tube) from `a` to `b` with world `radius`.
/// Used for the silver axis shafts — thick per-element geometry, since the
/// overlay line width is a single per-pass value and can't be varied per shaft.
fn push_tube(ov: &mut Overlay, a: Vec3, b: Vec3, radius: f32, color: [f32; 4]) {
    let axis = b.sub(a);
    if axis.length() < 1e-9 || radius <= 0.0 {
        return;
    }
    let (u, v) = axis_basis(axis.normalized());
    let ring = |center: Vec3, k: usize| -> Vec3 {
        let ang = (k as f32 / TUBE_SEGMENTS as f32) * std::f32::consts::TAU;
        center
            .add(u.scale(ang.cos() * radius))
            .add(v.scale(ang.sin() * radius))
    };
    for k in 0..TUBE_SEGMENTS {
        let a0 = ring(a, k);
        let a1 = ring(a, k + 1);
        let b0 = ring(b, k);
        let b1 = ring(b, k + 1);
        ov.tri(a0, b0, b1, color);
        ov.tri(a0, b1, a1, color);
    }
}

/// Push a filled arrowhead cone: apex at `tip`, base circle of world `radius`
/// centered at `base`, radially symmetric about `tip - base` (side + base cap).
fn push_cone(ov: &mut Overlay, base: Vec3, tip: Vec3, radius: f32, color: [f32; 4]) {
    let axis = tip.sub(base);
    if axis.length() < 1e-9 || radius <= 0.0 {
        return;
    }
    let (u, v) = axis_basis(axis.normalized());
    let ring = |k: usize| -> Vec3 {
        let ang = (k as f32 / CONE_SEGMENTS as f32) * std::f32::consts::TAU;
        base.add(u.scale(ang.cos() * radius))
            .add(v.scale(ang.sin() * radius))
    };
    let mut prev = ring(0);
    for k in 1..=CONE_SEGMENTS {
        let cur = ring(k);
        ov.tri(tip, prev, cur, color); // side
        ov.tri(base, cur, prev, color); // base cap
        prev = cur;
    }
}

/// Push a filled UV sphere of world `radius` at `center`. Flat-shaded facets;
/// the overlay shader's per-face shade gives the 3D read.
fn push_sphere(ov: &mut Overlay, center: Vec3, radius: f32, color: [f32; 4]) {
    if radius <= 0.0 {
        return;
    }
    let point = |ring: usize, sector: usize| -> Vec3 {
        let lat = std::f32::consts::PI * (ring as f32 / SPHERE_RINGS as f32) - std::f32::consts::FRAC_PI_2;
        let lon = std::f32::consts::TAU * (sector as f32 / SPHERE_SECTORS as f32);
        center.add(Vec3::new(
            lat.cos() * lon.cos() * radius,
            lat.cos() * lon.sin() * radius,
            lat.sin() * radius,
        ))
    };
    for r in 0..SPHERE_RINGS {
        for sct in 0..SPHERE_SECTORS {
            let p00 = point(r, sct);
            let p01 = point(r, sct + 1);
            let p10 = point(r + 1, sct);
            let p11 = point(r + 1, sct + 1);
            ov.tri(p00, p10, p11, color);
            ov.tri(p00, p11, p01, color);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::raster;

    /// Oblique orthographic camera so axes/rings are visually separated (avoids
    /// the axis-aligned degeneracy where an axis and a ring project to the same
    /// screen line).
    fn oblique_cam(vp: f32) -> GizmoCamera {
        let eye = [8.0, -10.0, 7.0];
        let view_proj = raster::test_view_proj(eye, [0.0, 0.0, 0.0], vp, vp);
        let fwd = Vec3::new(-eye[0], -eye[1], -eye[2]).normalized();
        GizmoCamera {
            view_proj,
            eye: Vec3::from(eye),
            forward: fwd,
            // test_view_proj's up for this oblique pose (Z-up heuristic).
            up: Vec3::Z,
            viewport: [vp, vp],
            orthographic: true,
        }
    }

    /// A PERSPECTIVE camera (wgpu clip, z in 0..1) from `eye` toward `target`
    /// with a controllable `fov_y_deg` + square `vp`. Perspective is REQUIRED to
    /// reproduce the depth-dependent picking bug: only here does world_per_pixel
    /// vary with depth, so an axis arrow pointing toward/away from the eye has a
    /// tip at a very different scale than its origin. `orthographic: false` so
    /// pick rays emanate from the eye.
    fn persp_cam(eye: [f32; 3], target: [f32; 3], fov_y_deg: f32, vp: f32) -> GizmoCamera {
        let eye = Vec3::from(eye);
        let target = Vec3::from(target);
        let fwd = target.sub(eye).normalized();
        let up_hint = if fwd.z.abs() > 0.9 { Vec3::Y } else { Vec3::Z };
        let right = fwd.cross(up_hint).normalized();
        let u = right.cross(fwd).normalized();
        // world→view (camera looks down -Z), column-major [col][row].
        let view = [
            [right.x, u.x, -fwd.x, 0.0],
            [right.y, u.y, -fwd.y, 0.0],
            [right.z, u.z, -fwd.z, 0.0],
            [-right.dot(eye), -u.dot(eye), fwd.dot(eye), 1.0],
        ];
        let f = 1.0 / (fov_y_deg.to_radians() * 0.5).tan();
        let aspect = 1.0_f32;
        let (near, far) = (0.05_f32, 100.0_f32);
        // wgpu perspective, z in 0..1, column-major [col][row]; w_clip = -z_view
        // (>0 in front) → matches `world_to_screen`'s in-front test.
        let proj = [
            [f / aspect, 0.0, 0.0, 0.0],
            [0.0, f, 0.0, 0.0],
            [0.0, 0.0, far / (near - far), -1.0],
            [0.0, 0.0, (near * far) / (near - far), 0.0],
        ];
        let view_proj = mat_mul_cols(&proj, &view);
        GizmoCamera {
            view_proj,
            eye,
            forward: fwd,
            up: u,
            viewport: [vp, vp],
            orthographic: false,
        }
    }

    /// Column-major (`[col][row]`) 4x4 multiply, matching `mat_mul_point`'s layout.
    fn mat_mul_cols(a: &[[f32; 4]; 4], b: &[[f32; 4]; 4]) -> [[f32; 4]; 4] {
        let mut out = [[0.0f32; 4]; 4];
        for col in 0..4 {
            for row in 0..4 {
                let mut sum = 0.0;
                for k in 0..4 {
                    sum += a[k][row] * b[col][k];
                }
                out[col][row] = sum;
            }
        }
        out
    }

    /// Straight-down (-Z) orthographic camera: world +X → screen right, world
    /// +Y → screen up. Handy for deterministic drag-math tests.
    fn topdown_cam(vp: f32) -> GizmoCamera {
        let eye = [0.0, 0.0, 10.0];
        let view_proj = raster::test_view_proj(eye, [0.0, 0.0, 0.0], vp, vp);
        GizmoCamera {
            view_proj,
            eye: Vec3::from(eye),
            forward: Vec3::new(0.0, 0.0, -1.0),
            // test_view_proj's up for the near-vertical -Z pose (+Y fallback).
            up: Vec3::Y,
            viewport: [vp, vp],
            orthographic: true,
        }
    }

    #[test]
    fn hit_picks_the_axis_the_ray_passes_near() {
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        // Point on the +X arrow shaft out past the rings, projected to screen
        // (a mid-shaft sample can coincide with a ring crossing).
        let (a, b) = gz.axis_seg(&cam, 0);
        let p = a.lerp(b, 0.82);
        let s = cam.world_to_screen(p).unwrap();
        assert_eq!(gz.hit(&cam, s), Some(HANDLE_AXIS_X), "screen {s:?}");

        // And the +Y arrow.
        let (a, b) = gz.axis_seg(&cam, 1);
        let p = a.lerp(b, 0.82);
        let s = cam.world_to_screen(p).unwrap();
        assert_eq!(gz.hit(&cam, s), Some(HANDLE_AXIS_Y));
    }

    #[test]
    fn hit_is_none_in_empty_space() {
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        // Far corner — well outside the ~90px gizmo centered at the viewport.
        assert_eq!(gz.hit(&cam, [6.0, 6.0]), None);
        assert_eq!(gz.hit(&cam, [234.0, 234.0]), None);
    }

    #[test]
    fn hit_picks_a_ring() {
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        // The Z-rotation arc joins the X and Y tips (in the XY plane); sample a
        // point midway along it.
        let s = gz.sizes(&cam);
        let p = gz.arc_point(0, 1, 0.5, s.arc_rad);
        let sp = cam.world_to_screen(p).unwrap();
        assert_eq!(gz.hit(&cam, sp), Some(HANDLE_RING_Z));
    }

    #[test]
    fn axis_translate_moves_positive_x_for_a_positive_x_drag() {
        let cam = topdown_cam(200.0);
        let gz = TransformGizmo::default();
        let center = [100.0, 100.0];
        let start = cam.ray_from_screen(center[0], center[1]);
        // Move the pointer 40px to screen-right (world +X for this camera).
        let current = cam.ray_from_screen(center[0] + 40.0, center[1]);
        let d = gz.axis_translate(&cam, 0, start, current);
        assert!(d.x > 0.0, "expected +X translate, got {d:?}");
        assert!(d.y.abs() < 1e-3 && d.z.abs() < 1e-3, "off-axis leak {d:?}");
        // Magnitude should be ~ 40px * world_per_pixel.
        let expect = 40.0 * cam.world_per_pixel(gz.origin);
        assert!((d.x - expect).abs() < 0.05 * expect.max(1.0), "d.x={} expect={}", d.x, expect);
    }

    #[test]
    fn plane_translate_reports_both_in_plane_components() {
        let cam = topdown_cam(200.0);
        let gz = TransformGizmo::default();
        let center = [100.0, 100.0];
        let start = cam.ray_from_screen(center[0], center[1]);
        // +30px right (world +X), -20px screen-y (world +Y, since y is down).
        let current = cam.ray_from_screen(center[0] + 30.0, center[1] - 20.0);
        let d = gz.plane_translate(0, 1, start, current);
        assert!(d.x > 0.0 && d.y > 0.0, "expected +X,+Y in-plane move, got {d:?}");
        assert!(d.z.abs() < 1e-3, "no normal-axis component expected {d:?}");
    }

    #[test]
    fn ring_rotate_returns_expected_angle() {
        let cam = topdown_cam(200.0);
        let gz = TransformGizmo::default();
        let center = [100.0, 100.0];
        // Start ray hits +X, current ray hits +Y → +90° about +Z.
        let start = cam.ray_from_screen(center[0] + 40.0, center[1]);
        let current = cam.ray_from_screen(center[0], center[1] - 40.0);
        let ang = gz.ring_rotate(2, start, current);
        assert!(
            (ang - std::f32::consts::FRAC_PI_2).abs() < 1e-2,
            "expected +pi/2, got {ang}"
        );
        // Reverse pair → -90°.
        let ang2 = gz.ring_rotate(2, current, start);
        assert!((ang2 + std::f32::consts::FRAC_PI_2).abs() < 1e-2, "got {ang2}");
    }

    #[test]
    fn drag_delta_dispatches_by_handle() {
        let cam = topdown_cam(200.0);
        let gz = TransformGizmo::default();
        let c = [100.0, 100.0];
        let start = cam.ray_from_screen(c[0], c[1]);
        let cur = cam.ray_from_screen(c[0] + 20.0, c[1]);
        match gz.drag_delta(&cam, HANDLE_AXIS_X, start, cur) {
            DragDelta::Translate(v) => assert!(v.x > 0.0),
            other => panic!("expected translate, got {other:?}"),
        }
        let cur_rot = cam.ray_from_screen(c[0], c[1] - 20.0);
        let start_rot = cam.ray_from_screen(c[0] + 20.0, c[1]);
        match gz.drag_delta(&cam, HANDLE_RING_Z, start_rot, cur_rot) {
            DragDelta::Rotate { axis_index, radians } => {
                assert_eq!(axis_index, 2);
                assert!(radians > 0.0);
            }
            other => panic!("expected rotate, got {other:?}"),
        }
        assert_eq!(gz.drag_delta(&cam, HANDLE_NONE, start, cur), DragDelta::None);
    }

    #[test]
    fn geometry_emits_lines_and_tris() {
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        let ov = gz.geometry(&cam, Some(HANDLE_AXIS_X), None);
        assert!(!ov.lines.is_empty(), "expected line geometry (rotation arcs)");
        assert!(!ov.tris.is_empty(), "expected triangle geometry (shafts/cones/spheres)");
        // The hovered X axis shaft + cone are now solid geometry, so its gold
        // highlight lands on TRIS (the arcs are the only line geometry).
        let gold = ov
            .tris
            .iter()
            .any(|v| (v.color[0] - C_GOLD[0]).abs() < 1e-3 && (v.color[1] - C_GOLD[1]).abs() < 1e-3);
        assert!(gold, "hovered handle should be highlighted gold");
    }

    #[test]
    fn handles_are_screen_constant_across_zoom() {
        // Two "zoom" levels simulated via viewport size: with the same world
        // view volume, a larger viewport halves world_per_pixel, so the gizmo's
        // WORLD size shrinks to keep its SCREEN size fixed. Use a top-down
        // camera so the +X arrow lies in the screen plane (no foreshortening),
        // making the projected span equal the target arrow pixel length.
        let cam_a = topdown_cam(240.0);
        let cam_b = topdown_cam(480.0);
        let gz = TransformGizmo::default();

        let span = |cam: &GizmoCamera| {
            let (_a, tip) = gz.axis_seg(cam, 0);
            let o = cam.world_to_screen(gz.origin).unwrap();
            let t = cam.world_to_screen(tip).unwrap();
            ((t[0] - o[0]).powi(2) + (t[1] - o[1]).powi(2)).sqrt()
        };
        let sa = span(&cam_a);
        let sb = span(&cam_b);
        assert!((sa - sb).abs() < 1.0, "screen span not constant: {sa} vs {sb}");
        // And it should be near our target arrow pixel length.
        assert!((sa - PX_AXIS_LEN).abs() < 3.0, "arrow span {sa}px");
    }

    #[test]
    fn cone_base_sits_outside_the_rotation_arc() {
        // Fix 1: the arrowhead cone must start OUTSIDE the rotation arcs so the
        // white arcs never cut through the orange cones. The cone BASE is at
        // `axis_len - head_len`; the arc is at `arc_rad`. The base must clear the
        // arc with a few px of gap.
        let cam = topdown_cam(240.0);
        let gz = TransformGizmo::default();
        let s = gz.sizes(&cam);
        let cone_base_dist = s.axis_len - s.head_len; // where the cone begins
        assert!(
            cone_base_dist > s.arc_rad + 4.0 * s.px,
            "cone base ({cone_base_dist}) must clear the arc ({}) by >4px",
            s.arc_rad
        );
        // The cone TIP is past the base (the cone pokes outward beyond the arc).
        assert!(s.axis_len > cone_base_dist, "cone tip past its base");
    }

    #[test]
    fn rotation_grab_sphere_sits_on_the_arc() {
        // Fix 2: each rotation grab sphere sits at the MIDPOINT of its quarter arc
        // — on the drawn arc curve (radius = arc_rad), not floating on the inner
        // bisector.
        let cam = oblique_cam(240.0);
        let gz = TransformGizmo::default();
        let s = gz.sizes(&cam);
        for (_, i, j) in ARCS {
            let grab = gz.arc_grab_point(i, j, &s);
            // On the arc curve: identical to the arc's mid-sweep sample…
            let mid = gz.arc_point(i, j, 0.5, s.arc_rad);
            assert!(grab.sub(mid).length() < 1e-5, "grab off the arc mid: {grab:?}");
            // …and exactly `arc_rad` from the origin (a point on the circle).
            let r = grab.sub(gz.origin).length();
            assert!((r - s.arc_rad).abs() < 1e-4, "grab radius {r} != arc_rad {}", s.arc_rad);
        }
        // A click on a grab sphere's screen projection still resolves to its ring.
        let s = gz.sizes(&cam);
        let grab = gz.arc_grab_point(0, 1, &s); // the Z-rotation arc (about ez)
        let sp = cam.world_to_screen(grab).unwrap();
        assert_eq!(gz.hit(&cam, sp), Some(HANDLE_RING_Z), "grab-sphere click picks its ring");
    }

    /// Translate-only / rotate-only gating (the component Move toggle's two
    /// steps): hiding the rings drops their drawn arcs AND their hit regions;
    /// hiding the axes likewise — draw==hit stays exact under both flags.
    #[test]
    fn show_flags_gate_both_geometry_and_hit_regions() {
        let cam = oblique_cam(240.0);

        // Translate-only: no ring regions, arcs gone from the line geometry.
        let translate_only = TransformGizmo {
            show_rings: false,
            ..TransformGizmo::default()
        };
        let regions = translate_only.hit_regions(&cam);
        assert!(
            regions.iter().all(|(id, _)| !is_ring(*id)),
            "no ring hit regions when rings are hidden"
        );
        assert_eq!(
            regions.iter().filter(|(id, _)| matches!(*id, HANDLE_AXIS_X | HANDLE_AXIS_Y | HANDLE_AXIS_Z)).count(),
            3,
            "axis capsules stay"
        );
        let ov = translate_only.geometry(&cam, None, None);
        assert!(ov.lines.is_empty(), "the arcs are the only line geometry — hidden rings draw none");
        // A click where the (hidden) Z grab ball would sit no longer picks a ring.
        let s = translate_only.sizes(&cam);
        let grab = translate_only.arc_grab_point(0, 1, &s);
        let sp = cam.world_to_screen(grab).unwrap();
        assert_ne!(translate_only.hit(&cam, sp), Some(HANDLE_RING_Z));

        // Rotate-only: no axis capsules; rings + their grabs remain pickable.
        let rotate_only = TransformGizmo {
            show_axes: false,
            show_center: false,
            ..TransformGizmo::default()
        };
        let regions = rotate_only.hit_regions(&cam);
        assert!(
            regions.iter().all(|(id, _)| is_ring(*id)),
            "only ring regions when axes + center are hidden: {:?}",
            regions.iter().map(|(id, _)| *id).collect::<Vec<_>>()
        );
        let s = rotate_only.sizes(&cam);
        let grab = rotate_only.arc_grab_point(0, 1, &s);
        let sp = cam.world_to_screen(grab).unwrap();
        assert_eq!(rotate_only.hit(&cam, sp), Some(HANDLE_RING_Z), "ring grab still picks");
    }

    /// A 5px-perpendicular probe off the projected arrow direction, at the tip.
    fn probe_off_tip(cam: &GizmoCamera, gz: &TransformGizmo, i: usize, off_px: f32) -> [f32; 2] {
        let (a, b) = gz.axis_seg(cam, i);
        let sa = cam.world_to_screen(a).unwrap();
        let sb = cam.world_to_screen(b).unwrap(); // projected tip
        let dir = [sb[0] - sa[0], sb[1] - sa[1]];
        let len = (dir[0] * dir[0] + dir[1] * dir[1]).sqrt().max(1e-6);
        let perp = [-dir[1] / len, dir[0] / len];
        [sb[0] + perp[0] * off_px, sb[1] + perp[1] * off_px]
    }

    #[test]
    fn foreshortened_arrow_stays_grabbable_screen_space() {
        // REGRESSION PIN. A perspective camera aimed roughly along +X so the +X
        // arrow points mostly AWAY from the eye: its tip sits at a MUCH larger
        // depth than the origin, so world_per_pixel at the tip ≫ at the origin. A
        // pixel a few px off the (visible, on-screen) tip is only a few px away in
        // SCREEN space, but the OLD `ray.distance_to_segment / origin_wpp` metric
        // blows that up past the 7px threshold → the arrow was un-grabbable in
        // this orientation. The new screen-space test grabs it.
        let cam = persp_cam([-6.0, -2.0, 1.5], [0.0, 0.0, 0.0], 90.0, 100.0);
        let gz = TransformGizmo::default();
        let probe = probe_off_tip(&cam, &gz, 0, 5.0);

        // NEW (screen-space) hit grabs the arrow…
        assert_eq!(gz.hit(&cam, probe), Some(HANDLE_AXIS_X), "probe {probe:?}");

        // …while the OLD world-distance / origin-wpp metric would have MISSED it.
        let (a, b) = gz.axis_seg(&cam, 0);
        let ray = cam.ray_from_screen(probe[0], probe[1]);
        let old_px = ray.distance_to_segment(a, b) / cam.world_per_pixel(gz.origin);
        assert!(
            old_px > 7.0,
            "old metric {old_px}px should exceed the 7px threshold (pins the bug)"
        );
    }

    #[test]
    fn arrow_grabbable_at_extreme_zoom() {
        // Extreme zoom-in (huge viewport → many px per world unit) with the same
        // foreshortened pose. The arrow head must still resolve to its axis when
        // the pointer is on its on-screen pixels.
        let cam = persp_cam([-6.0, -2.0, 1.5], [0.0, 0.0, 0.0], 90.0, 4000.0);
        let gz = TransformGizmo::default();
        let probe = probe_off_tip(&cam, &gz, 0, 4.0);
        assert_eq!(gz.hit(&cam, probe), Some(HANDLE_AXIS_X), "probe {probe:?}");
    }

    /// A pixel `off_px` perpendicular to the on-screen direction `pa → pm`, taken
    /// at `pm` (both endpoints must project — i.e. be in front of the eye).
    fn probe_perp(
        cam: &GizmoCamera,
        pa_world: Vec3,
        pm_world: Vec3,
        off_px: f32,
    ) -> [f32; 2] {
        let pa = cam.world_to_screen(pa_world).unwrap();
        let pm = cam.world_to_screen(pm_world).unwrap();
        let dir = [pm[0] - pa[0], pm[1] - pa[1]];
        let len = (dir[0] * dir[0] + dir[1] * dir[1]).sqrt().max(1e-6);
        let perp = [-dir[1] / len, dir[0] / len];
        [pm[0] + perp[0] * off_px, pm[1] + perp[1] * off_px]
    }

    #[test]
    fn arrow_with_far_end_behind_the_eye_is_grabbable_on_its_visible_shaft() {
        // REGRESSION PIN (the reported sizeY failure, transform variant). A
        // perspective camera looking toward the origin from +Y so the +Y arrow
        // grows AWAY past the eye plane: its shaft-start is in front but its TIP
        // crosses BEHIND the eye. The region builder front-CLIPS the capsule to the
        // eye-plane crossing, so it covers the VISIBLE shaft and the arrow is
        // grabbable wherever that shaft is under the cursor.
        let cam = persp_cam([0.0, 2.0, 0.3], [0.0, 0.0, 0.0], 90.0, 100.0);
        let gz = TransformGizmo::default();
        let (a, b) = gz.axis_seg(&cam, 1); // +Y arrow (shaft-start, tip)

        // The pin: the tip is behind the eye, the shaft-start is in front.
        assert!(cam.view_depth(b) < 0.0, "tip must be behind the eye: {}", cam.view_depth(b));
        assert!(cam.view_depth(a) > 0.0, "shaft-start must be in front: {}", cam.view_depth(a));

        // A cursor a few px off the VISIBLE part of the shaft grabs the +Y arrow.
        let visible = a.lerp(b, 0.3); // still in front (crossing is ~t=0.52)
        assert!(cam.view_depth(visible) > 0.0, "probe point must be visible");
        let probe = probe_perp(&cam, a, visible, 3.0);
        assert_eq!(gz.hit(&cam, probe), Some(HANDLE_AXIS_Y), "probe {probe:?}");

        // No regression: the +X arrow (fully in front for this pose) still hits.
        let (xa, xb) = gz.axis_seg(&cam, 0);
        assert!(cam.view_depth(xa) > 0.0 && cam.view_depth(xb) > 0.0, "+X fully in front");
        let xprobe = probe_perp(&cam, xa, xa.lerp(xb, 0.6), 3.0);
        assert_eq!(gz.hit(&cam, xprobe), Some(HANDLE_AXIS_X), "xprobe {xprobe:?}");
    }

    #[test]
    fn handle_entirely_behind_the_eye_is_not_grabbable() {
        // A gizmo whose whole extent is behind the eye is invisible in
        // perspective → every handle's region is omitted (both segment endpoints
        // behind, or a ball behind), so `hit_regions` is empty and nothing grabs.
        let cam = persp_cam([0.0, -0.5, 0.0], [0.0, -1.0, 0.0], 90.0, 100.0);
        let gz = TransformGizmo::default();
        // The gizmo sits at the origin, wholly behind this eye plane.
        assert!(cam.view_depth(gz.origin) < 0.0, "gizmo behind the eye");
        // No region projects, so a cursor at screen center grabs nothing.
        assert_eq!(gz.hit(&cam, [50.0, 50.0]), None);
    }

    /// An edge-on ORTHO camera looking down -Y at the origin (world +X → screen
    /// left, world +Z → screen up, world +Y → into the screen). Because the whole
    /// gizmo XY plane collapses onto the screen X axis here, the Z-rotation grab
    /// ball (at the 45° bisector in the XY plane) projects ONTO the +X arrow's
    /// screen line — the one pose where a ring region and an arrow region overlap.
    fn edge_on_y_cam(vp: f32) -> GizmoCamera {
        let eye = [0.0, 20.0, 0.0];
        let view_proj = raster::test_view_proj(eye, [0.0, 0.0, 0.0], vp, vp);
        GizmoCamera {
            view_proj,
            eye: Vec3::from(eye),
            forward: Vec3::new(0.0, -1.0, 0.0),
            up: Vec3::Z,
            viewport: [vp, vp],
            orthographic: true,
        }
    }

    #[test]
    fn axis_arrow_beats_ring_when_both_regions_contain_the_cursor() {
        // Arrow heads are ALWAYS the top drag priority: where an axis arrow region
        // and a rotation grab-ball region BOTH contain the cursor, the ARROW must
        // win (rank 0 < ring rank 1). Under the edge-on camera the Z grab ball
        // projects onto the +X shaft line, making a genuine 2-region overlap.
        let cam = edge_on_y_cam(240.0);
        let gz = TransformGizmo::default();
        let s = gz.sizes(&cam);
        let grab = gz.arc_grab_point(0, 1, &s); // the Z-rotation grab ball
        let sp = cam.world_to_screen(grab).unwrap();

        // Prove the overlap is real: BOTH the +X axis capsule and the Z ring
        // circle contain this pixel.
        let regions = gz.hit_regions(&cam);
        let x_axis = regions.iter().find(|(id, _)| *id == HANDLE_AXIS_X).unwrap().1;
        let ring_z = regions.iter().find(|(id, _)| *id == HANDLE_RING_Z).unwrap().1;
        assert!(x_axis.contains(sp), "the +X axis region must contain the cursor");
        assert!(ring_z.contains(sp), "the Z ring region must contain the cursor");

        // …and the arrow wins the overlap.
        assert_eq!(
            gz.hit(&cam, sp),
            Some(HANDLE_AXIS_X),
            "arrow must beat the ring at {sp:?}"
        );
    }

    #[test]
    fn draw_equals_hit_regions_pick_their_own_handle() {
        // The draw==hit invariant, transform side: for a handful of camera poses,
        // every region the outline draws resolves — via the SAME `hit` the engine
        // uses — to a handle whose region contains the cursor, and a pixel well
        // OUTSIDE a uniquely-owned region does not resolve to that handle. (Regions
        // overlap by design — the center ball sits at the arrow origins — so the
        // invariant is "the picked handle's region contains the cursor," and the
        // just-outside check uses the arrow TIP cap, which no other region covers.)
        for cam in [oblique_cam(240.0), edge_on_y_cam(240.0), topdown_cam(240.0)] {
            let gz = TransformGizmo::default();
            let regions = gz.hit_regions(&cam);
            for (id, shape) in &regions {
                // A cursor at the region's own reference point picks SOME handle
                // whose region contains it (may be a higher-priority overlapper).
                let probe = match shape {
                    HitShape::Circle { c, .. } => *c,
                    HitShape::Capsule { a, b, .. } => [(a[0] + b[0]) * 0.5, (a[1] + b[1]) * 0.5],
                };
                let picked = gz.hit(&cam, probe).expect("a handle under its own region");
                let picked_shape = regions.iter().find(|(pid, _)| *pid == picked).unwrap().1;
                assert!(
                    picked_shape.contains(probe),
                    "picked handle {picked}'s region must contain the cursor {probe:?}"
                );
                let _ = id;
            }
            // A pixel just past an axis arrow TIP cap (uniquely owned — no ball or
            // other capsule reaches the far tip) grabs nothing there.
            if let Some((_, HitShape::Capsule { a, b, r })) =
                regions.iter().find(|(id, _)| *id == HANDLE_AXIS_X)
            {
                let seg = [b[0] - a[0], b[1] - a[1]];
                let len = (seg[0] * seg[0] + seg[1] * seg[1]).sqrt().max(1e-3);
                let past = [b[0] + seg[0] / len * (r + 4.0), b[1] + seg[1] / len * (r + 4.0)];
                assert_ne!(
                    gz.hit(&cam, past),
                    Some(HANDLE_AXIS_X),
                    "a pixel past the +X tip cap is outside its region"
                );
            }
        }
    }
}