BREP_gizmos 0.2.1

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
//! ViewCube navigation gizmo — a small orientation cube that mirrors the main
//! camera and, when a face / edge / corner is clicked, hands back the standard
//! view the engine's camera animation should snap to. A Rust re-implementation
//! of the original `ViewCube` for the Rust rendering engine.
//!
//! # Convention (world = app convention, +Y up, right-handed)
//! Each cube region has an outward direction built from the sign of each axis it
//! is extreme on. A **face** is extreme on one axis, an **edge** on two, a
//! **corner** on three. The region's outward normal is `normalize(sx, sy, sz)`,
//! and the view the camera snaps to looks *inward* along `-normal` (eye placed on
//! the `+normal` side, looking at the model) — exactly the Y-up direction the
//! engine's `standard_view` buttons use, so a face click == its named button. So:
//! - FRONT face normal `+Z` → `target_view` = `-Z` (eye at +Z looking toward the
//!   model's front), matching the FRONT button (`dir +Z, up +Y`).
//! - BACK `-Z`→`+Z`, RIGHT `+X`→`-X`, LEFT `-X`→`+X`, TOP `+Y`→`-Y`,
//!   BOTTOM `-Y`→`+Y`.
//! - Edges = 45° blends of two faces, corners = iso (all three components set).
//!
//! Face letters (stroked as overlay line-glyphs, no SDF text):
//! `F`=Front(+Z), `BK`=Back(−Z), `R`=Right(+X), `L`=Left(−X), `T`=Top(+Y),
//! `B`=Bottom(−Y).
//!
//! # HandleId encoding
//! A region is identified by the base-3 packing of its axis signs
//! `id = (sx+1) + (sy+1)*3 + (sz+1)*9 + 1` (see [`ViewCube::region_id`]). `0` is
//! reserved for "no handle" (the trait convention); the all-zero packing (`14`)
//! never occurs because a surface point is always extreme on at least one axis.
//! Valid ids are `1..=27` minus `14`, one per hit region (6 faces + 12 edges +
//! 8 corners = 26). [`ViewCube::target_view`] / [`ViewCube::target_up`] decode an
//! id straight back to the snap direction and up hint.
//!
//! # Cube orientation (mirrors the model)
//! The cube geometry lives in world axes (FRONT quad at +Z, TOP at +Y, etc.).
//! Orientation is carried entirely by a *mini-camera* ([`ViewCube::mini_camera`])
//! whose rotation copies the main camera's WHOLE rotation: `forward` =
//! `main.forward` AND `up` = `main.up` (re-orthonormalized). The engine camera
//! is a free arcball — its up vector rolls arbitrarily (drags, the roll arrows,
//! the TOP/BOTTOM buttons' ∓Z ups) — so copying only forward and reconstructing
//! up from a world-up heuristic would leave the cube un-rolled relative to the
//! model (the classic "cube doesn't match the view" bug). Only when the supplied
//! up is degenerate (near-parallel to forward) does [`cube_up`] fall back to the
//! Y-up rule. Because the mini-camera views the same world axes from the same
//! orientation as the main camera views the model, the cube always shows exactly
//! the face — at exactly the roll — the model shows. `geometry` also culls the
//! back-facing faces/edges/glyphs so the CPU-rasterized demo (whose overlay lines
//! ignore depth) and the GPU overlay pass both read cleanly.
//!
//! # Integration (engine wiring)
//! - **Corner viewport sub-rect.** The gizmo owns a fixed `size`×`size` pixel
//!   square in the bottom-right corner, `margin` px in from the edges — see
//!   [`ViewCube::sub_rect`] (returns `[x, y, w, h]`, top-left origin). The engine
//!   renders the ViewCube overlay in its own scissor pass using
//!   [`ViewCube::mini_camera`] (NOT the main camera's `view_proj`), exactly like
//!   the retired renderer rendered the cube into a scissored corner.
//! - **Pointer forwarding.** The host maps a pointer event into cube-local pixels
//!   `local = (pointer.x - rect.x, pointer.y - rect.y)` in `0..size`
//!   (top-left origin, y down) and calls [`Gizmo::hit`] with those coords — this
//!   mirrors the original `ViewCube`'s `_pickObjectAtEvent`. Events outside `sub_rect` are
//!   not forwarded.
//! - **Snap.** On click, the engine takes the returned [`HandleId`] and drives
//!   the *shared* camera (same path the orbit controls use) toward
//!   `target_view(id)` (eye→target direction), keeping the current pivot
//!   distance. The up is snapped to a discrete, minimal-rotation "level" roll
//!   (the engine's `snap_view_up`): a face lands flat-on with a horizontal
//!   bottom edge, a corner on the nearest axis-up isometric. `target_up(id)` is
//!   only the degenerate fallback used when that projection is undefined.

use crate::{Gizmo, GizmoCamera, HandleId, Overlay, Ray, Vec3};

/// Outer fraction of a face (measured from the edge, as a share of the half-size)
/// that hit-tests as the neighbouring edge / corner region rather than the face.
const EDGE_BAND: f32 = 0.30;

// Overlay colors (linear RGBA).
const COL_HOVER: [f32; 4] = [0.42, 0.64, 0.96, 1.0];
const COL_ACTIVE: [f32; 4] = [0.60, 0.82, 1.0, 1.0];
const COL_EDGE: [f32; 4] = [0.255, 0.275, 0.310, 1.0]; // gray tube edges (~#41464f)
const COL_EDGE_HI: [f32; 4] = [0.62, 0.86, 1.0, 1.0];
const COL_GLYPH: [f32; 4] = [1.0, 1.0, 1.0, 1.0]; // white labels
const COL_MARK: [f32; 4] = [0.58, 0.82, 1.0, 1.0];
const COL_CORNER: [f32; 4] = [0.306, 0.439, 0.643, 1.0]; // muted-blue corner spheres (~#4e70a4)
// Navigation arrows (2D, screen-fixed): light-gray triangles/arcs like the old
// renderer's ViewCube (fill ~#d6d9de, dark outline ~#161a20), brighter on hover.
const COL_ARROW: [f32; 4] = [0.840, 0.851, 0.871, 1.0];
const COL_ARROW_HI: [f32; 4] = [0.965, 0.975, 1.000, 1.0];
const COL_ARROW_LINE: [f32; 4] = [0.086, 0.102, 0.125, 1.0];

/// Lift a color toward white by `amt` (0..1) — the face touch/glow highlight.
fn brighten_by(c: [f32; 4], amt: f32) -> [f32; 4] {
    [
        c[0] + (1.0 - c[0]) * amt,
        c[1] + (1.0 - c[1]) * amt,
        c[2] + (1.0 - c[2]) * amt,
        c[3],
    ]
}

/// The ViewCube gizmo. Cheap to construct; holds only its pixel footprint.
#[derive(Debug, Clone, Copy)]
pub struct ViewCube {
    /// Edge length of the square corner viewport, in CSS pixels.
    pub size: f32,
    /// Inset from the bottom-right corner, in CSS pixels.
    pub margin: f32,
}

impl Default for ViewCube {
    fn default() -> Self {
        Self::new()
    }
}

impl ViewCube {
    /// The default on-screen edge length of the corner viewport, in CSS pixels —
    /// the ONE source of the cube's default size. `RenderSettings::viewcube_size_px`
    /// defaults to this so "settings default == widget default" holds even when no
    /// saved settings exist (the boot path that never runs `apply_settings_json`).
    pub const DEFAULT_SIZE_PX: f32 = 135.0;

    // --- named face regions (edges/corners via `region_id`) ------------------
    // Y-up (matches the world + `standard_view` buttons): FRONT/BACK on the Z
    // axis, TOP/BOTTOM on the Y axis, RIGHT/LEFT on X.
    pub const RIGHT: HandleId = Self::region_id(1, 0, 0);
    pub const LEFT: HandleId = Self::region_id(-1, 0, 0);
    pub const FRONT: HandleId = Self::region_id(0, 0, 1);
    pub const BACK: HandleId = Self::region_id(0, 0, -1);
    pub const TOP: HandleId = Self::region_id(0, 1, 0);
    pub const BOTTOM: HandleId = Self::region_id(0, -1, 0);

    // --- 2D navigation arrows (screen-fixed, OUTSIDE the 1..=27 cube ids) -----
    // Four pan/orbit triangles on the cube's sides + two roll arcs at the top
    // corners. These are UI controls pinned to the corner viewport (they do NOT
    // rotate with the cube); clicking one applies a RELATIVE camera rotation.
    pub const ARROW_UP: HandleId = 101;
    pub const ARROW_DOWN: HandleId = 102;
    pub const ARROW_LEFT: HandleId = 103;
    pub const ARROW_RIGHT: HandleId = 104;
    pub const ROLL_CW: HandleId = 105;
    pub const ROLL_CCW: HandleId = 106;

    /// True when `id` is one of the six screen-fixed navigation arrows (pan
    /// triangles / roll arcs) rather than a cube face/edge/corner region. The
    /// engine branches on this to apply a relative rotation instead of a snap.
    pub fn is_arrow(id: HandleId) -> bool {
        (Self::ARROW_UP..=Self::ROLL_CCW).contains(&id)
    }

    pub fn new() -> Self {
        Self { size: Self::DEFAULT_SIZE_PX, margin: 12.0 }
    }

    /// A ViewCube with a custom pixel footprint (used by the demo to render big).
    pub fn with_size(size: f32) -> Self {
        Self { size, margin: 12.0 }
    }

    pub fn size(&self) -> f32 {
        self.size
    }

    /// Pack axis signs (each in `-1,0,1`, not all zero) into a [`HandleId`].
    pub const fn region_id(sx: i32, sy: i32, sz: i32) -> HandleId {
        ((sx + 1) + (sy + 1) * 3 + (sz + 1) * 9 + 1) as HandleId
    }

    /// `1` = face, `2` = edge, `3` = corner. Navigation arrows are not cube
    /// regions, so they classify as `0` (never a face/edge/corner highlight).
    pub fn region_kind(id: HandleId) -> u8 {
        if Self::is_arrow(id) {
            return 0;
        }
        decode(id).iter().filter(|&&x| x != 0).count() as u8
    }

    /// The world-space eye→target direction the main camera should look along to
    /// view `id` (the negated region normal — see the module docs).
    pub fn target_view(id: HandleId) -> Vec3 {
        if Self::is_arrow(id) {
            // Arrows carry no absolute snap direction (the engine applies a
            // relative rotation); return a harmless front-view default (look -Z).
            return Vec3::new(0.0, 0.0, -1.0);
        }
        let s = decode(id);
        Vec3::new(s[0] as f32, s[1] as f32, s[2] as f32)
            .normalized()
            .scale(-1.0)
    }

    /// A world-space up hint for the snapped view: `+Y`, or the button's Z-based
    /// up for the straight top / bottom views where `+Y` is degenerate (TOP looks
    /// `-Y` → up `-Z`; BOTTOM looks `+Y` → up `+Z`). This matches the engine's
    /// Y-up `standard_view` so a face click and its named button agree exactly.
    pub fn target_up(id: HandleId) -> Vec3 {
        let v = Self::target_view(id);
        if v.y.abs() > 0.9 {
            // Straight top/bottom: up follows the look direction's Y sign, so
            // TOP (look -Y) → -Z and BOTTOM (look +Y) → +Z, as the buttons do.
            Vec3::new(0.0, 0.0, v.y.signum())
        } else {
            Vec3::Y
        }
    }

    /// Human-readable region name, e.g. `"TOP-FRONT-RIGHT"` (handy for tooltips /
    /// logging at integration time).
    pub fn region_name(id: HandleId) -> String {
        if Self::is_arrow(id) {
            return match id {
                Self::ARROW_UP => "ARROW-UP",
                Self::ARROW_DOWN => "ARROW-DOWN",
                Self::ARROW_LEFT => "ARROW-LEFT",
                Self::ARROW_RIGHT => "ARROW-RIGHT",
                Self::ROLL_CW => "ROLL-CW",
                Self::ROLL_CCW => "ROLL-CCW",
                _ => "ARROW",
            }
            .to_string();
        }
        let s = decode(id);
        let mut parts: Vec<&str> = Vec::new();
        // Y-up: TOP/BOTTOM on the Y axis, FRONT/BACK on the Z axis, RIGHT/LEFT on X.
        match s[1] {
            1 => parts.push("TOP"),
            -1 => parts.push("BOTTOM"),
            _ => {}
        }
        match s[2] {
            1 => parts.push("FRONT"),
            -1 => parts.push("BACK"),
            _ => {}
        }
        match s[0] {
            1 => parts.push("RIGHT"),
            -1 => parts.push("LEFT"),
            _ => {}
        }
        parts.join("-")
    }

    /// The bottom-right corner rect this gizmo owns: `[x, y, w, h]`, top-left
    /// origin, y down, in CSS pixels. The host uses it to decide whether to forward a
    /// pointer event and to offset it into cube-local coords.
    pub fn sub_rect(&self, viewport: [f32; 2]) -> [f32; 4] {
        let w = self.size.min(viewport[0]);
        let h = self.size.min(viewport[1]);
        let x = (viewport[0] - w - self.margin).max(0.0);
        let y = (viewport[1] - h - self.margin).max(0.0);
        [x, y, w, h]
    }

    /// The mini-camera that renders the cube: same rotation as `main` — forward
    /// AND up, so the cube mirrors the camera's roll exactly (see the module
    /// docs) — positioned a fixed distance back looking at the cube origin,
    /// orthographic, viewport = `size`×`size`. The engine renders the ViewCube
    /// overlay with THIS camera.
    pub fn mini_camera(&self, main: &GizmoCamera) -> GizmoCamera {
        let f = main.forward.normalized();
        let up = cube_up(f, main.up);
        let dist = 4.0;
        let eye = f.scale(-dist);
        // Frame with margin so the corner spheres + tube edges (~0.82 at the
        // diagonal) AND the pan/roll nav arrows (pushed out to ~1.18 so they clear
        // the cube's clickable region) both fit without clipping.
        let half = 1.25;
        let view_proj = ortho_view_proj(eye, f, up, half, self.size, self.size);
        GizmoCamera {
            view_proj,
            eye,
            forward: f,
            up,
            viewport: [self.size, self.size],
            orthographic: true,
        }
    }

    /// Emit the oriented cube geometry, back-faces culled to the given view
    /// direction, with the hovered / active region highlighted.
    fn build(&self, view_forward: Vec3, hovered: Option<HandleId>, active: Option<HandleId>) -> Overlay {
        let mut o = Overlay::new();
        let h = 0.5f32;
        let fwd = view_forward.normalized();
        let hi = active.or(hovered);
        let hi_kind = hi.map(ViewCube::region_kind);

        // Faces (front-facing only) + stroked letters.
        for face in faces() {
            if face.n.dot(fwd) >= -1e-3 {
                continue; // back-facing
            }
            let (fa, fsgn) = face_axis_sign(face.n);
            let touches = hi.map_or(false, |hid| decode(hid)[fa] == fsgn);
            let col = if active == Some(face.id) {
                COL_ACTIVE
            } else if hovered == Some(face.id) {
                COL_HOVER
            } else if touches && matches!(hi_kind, Some(2) | Some(3)) {
                brighten_by(face.color, 0.16)
            } else {
                face.color
            };
            let c = face.n.scale(h);
            let corner = |su: f32, sv: f32| {
                c.add(face.u.scale(su * h)).add(face.v.scale(sv * h))
            };
            let p00 = corner(-1.0, -1.0);
            let p10 = corner(1.0, -1.0);
            let p11 = corner(1.0, 1.0);
            let p01 = corner(-1.0, 1.0);
            o.tri(p00, p10, p11, col);
            o.tri(p00, p11, p01, col);

            // Letter(s), lifted just proud of the face so they read on top.
            // Multi-char labels (e.g. "BK") are laid out in equal horizontal slots.
            let gc = face.n.scale(h + 0.012);
            let chars: Vec<char> = face.glyph.chars().collect();
            let nch = chars.len().max(1) as f32;
            for (i, ch) in chars.iter().enumerate() {
                let slot = |p: [f32; 2]| [(i as f32 + p[0]) / nch, p[1]];
                for stroke in letter_strokes(*ch) {
                    for seg in stroke.windows(2) {
                        let a = glyph_point(gc, face.u, face.v, slot(seg[0]));
                        let b = glyph_point(gc, face.u, face.v, slot(seg[1]));
                        o.line(a, b, COL_GLYPH);
                    }
                }
            }
        }

        // The 12 edges (only those touching a front-facing face), drawn as
        // thick camera-facing ribbons — the original view cube's tube edges.
        const TUBE_W: f32 = 0.052; // half-thickness of the edge tube (cube units)
        for (es, a, b) in edges() {
            let front = (0..3).any(|axis| {
                es[axis] != 0 && axis_vec(axis, es[axis] as f32).dot(fwd) < -1e-3
            });
            if !front {
                continue;
            }
            let eid = ViewCube::region_id(es[0], es[1], es[2]);
            let hot = hi == Some(eid)
                || (hi_kind == Some(3) && region_contains(hi.unwrap(), es));
            let col = if hot { COL_EDGE_HI } else { COL_EDGE };
            // Ribbon perpendicular to the edge in screen space (a "tube" facing
            // the camera). Falls back to a line when the edge points at the eye.
            let perp = b.sub(a).cross(fwd);
            if perp.length() > 1e-5 {
                let w = perp.normalized().scale(TUBE_W);
                o.tri(a.add(w), b.add(w), b.sub(w), col);
                o.tri(a.add(w), b.sub(w), a.sub(w), col);
            } else {
                o.line(a, b, col);
            }
        }

        // Blue corner spheres (billboarded quads) at the visible corners — the
        // rounded corner nodes of the original view cube.
        let right0 = fwd.any_perp();
        let up0 = fwd.cross(right0).normalized();
        let cr = 0.11f32;
        const CORNER_SEGS: usize = 12;
        for (sx, sy, sz) in [
            (-1.0, -1.0, -1.0), (1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (-1.0, 1.0, -1.0),
            (-1.0, -1.0, 1.0), (1.0, -1.0, 1.0), (1.0, 1.0, 1.0), (-1.0, 1.0, 1.0),
        ] {
            let visible = axis_vec(0, sx).dot(fwd) < -1e-3
                || axis_vec(1, sy).dot(fwd) < -1e-3
                || axis_vec(2, sz).dot(fwd) < -1e-3;
            if !visible {
                continue;
            }
            // Round node (camera-facing disc) so it reads as a corner sphere.
            let c = Vec3::new(sx * h, sy * h, sz * h);
            let mut prev = c.add(right0.scale(cr));
            for k in 1..=CORNER_SEGS {
                let a = (k as f32 / CORNER_SEGS as f32) * std::f32::consts::TAU;
                let cur = c
                    .add(right0.scale(a.cos() * cr))
                    .add(up0.scale(a.sin() * cr));
                o.tri(c, prev, cur, COL_CORNER);
                prev = cur;
            }
        }

        // Bright marker for a hovered/active edge or corner.
        if let Some(hid) = hi {
            match ViewCube::region_kind(hid) {
                2 => edge_bevel(&mut o, decode(hid), COL_MARK),
                3 => corner_cap(&mut o, decode(hid), COL_MARK, fwd),
                _ => {}
            }
        }

        o
    }

    /// Ray-cast the cube (unit box `[-0.5, 0.5]^3`) and classify the entry point
    /// into a face / edge / corner region.
    fn raycast(&self, ray: &Ray) -> Option<HandleId> {
        let h = 0.5f32;
        let o = [ray.origin.x, ray.origin.y, ray.origin.z];
        let d = [ray.dir.x, ray.dir.y, ray.dir.z];
        let mut tmin = f32::NEG_INFINITY;
        let mut tmax = f32::INFINITY;
        for a in 0..3 {
            if d[a].abs() < 1e-9 {
                if o[a] < -h || o[a] > h {
                    return None;
                }
            } else {
                let mut t1 = (-h - o[a]) / d[a];
                let mut t2 = (h - o[a]) / d[a];
                if t1 > t2 {
                    std::mem::swap(&mut t1, &mut t2);
                }
                tmin = tmin.max(t1);
                tmax = tmax.min(t2);
                if tmin > tmax {
                    return None;
                }
            }
        }
        let t = if tmin >= 0.0 {
            tmin
        } else if tmax >= 0.0 {
            tmax
        } else {
            return None;
        };
        Some(classify(ray.at(t)))
    }

    // --- navigation arrows (screen-fixed 2D controls) -----------------------

    /// Draw the four pan/orbit triangles (N/S/E/W) and two roll arcs (top
    /// corners). Vertices are placed at `right*sx + up*sy` where `right`/`up`
    /// are the mini-camera's screen axes, so every arrow projects to the SAME
    /// spot in the corner sub-rect regardless of cube orientation. `sx,sy` are
    /// in ~[-1,1]; the cube silhouette lives within |s| ≲ 0.82, so the pan
    /// triangles sit just outside it and the roll arcs hug the top corners.
    fn draw_arrows(&self, o: &mut Overlay, fwd: Vec3, cam_up: Vec3, hovered: Option<HandleId>) {
        let (right, up) = screen_axes(fwd, cam_up);
        let w2 = |sx: f32, sy: f32| right.scale(sx).add(up.scale(sy));

        // Pan/orbit triangles, tip pointing outward.
        const RB: f32 = 0.98; // base ring radius (pushed clear of the cube's
        // clickable region so the arrows don't steal cube clicks)
        const RT: f32 = 1.18; // tip radius (inside the widened sub-rect edge)
        const HW: f32 = 0.135; // half base width
        for (id, dx, dy) in PAN_ARROWS {
            let col = if hovered == Some(id) { COL_ARROW_HI } else { COL_ARROW };
            let (px, py) = (-dy, dx); // in-plane perpendicular
            let tip = w2(dx * RT, dy * RT);
            let b0 = w2(dx * RB + px * HW, dy * RB + py * HW);
            let b1 = w2(dx * RB - px * HW, dy * RB - py * HW);
            o.tri(tip, b0, b1, col);
            o.line(tip, b0, COL_ARROW_LINE);
            o.line(b0, b1, COL_ARROW_LINE);
            o.line(b1, tip, COL_ARROW_LINE);
        }

        // Roll arcs at the top corners (curved ribbon + arrowhead).
        for (id, cx, cy, spin) in ROLL_ARROWS {
            let col = if hovered == Some(id) { COL_ARROW_HI } else { COL_ARROW };
            draw_roll_arc(o, &w2, [cx, cy], spin, col);
        }
    }

    /// Hit-test the screen-fixed nav arrows: project each arrow's fixed anchor
    /// to sub-rect pixels via the mini-camera and pick the nearest one within a
    /// small radius of the incoming (cube-local px) `screen` point. Returns the
    /// arrow handle, or None to fall through to the cube raycast.
    fn arrow_hit(&self, mini: &GizmoCamera, screen: [f32; 2]) -> Option<HandleId> {
        let (right, up) = screen_axes(mini.forward, mini.up);
        let w2 = |sx: f32, sy: f32| right.scale(sx).add(up.scale(sy));
        let mut best: Option<(f32, HandleId)> = None;
        let mut consider = |id: HandleId, anchor: Vec3, radius: f32| {
            if let Some(px) = mini.world_to_screen(anchor) {
                let d = ((px[0] - screen[0]).powi(2) + (px[1] - screen[1]).powi(2)).sqrt();
                if d <= radius && best.map_or(true, |(bd, _)| d < bd) {
                    best = Some((d, id));
                }
            }
        };
        // Pan triangles: click target at the triangle centroid.
        const RC: f32 = (1.18 + 2.0 * 0.98) / 3.0; // (RT + 2*RB)/3
        let pan_r = self.size * 0.13;
        for (id, dx, dy) in PAN_ARROWS {
            consider(id, w2(dx * RC, dy * RC), pan_r);
        }
        // Roll arcs: click target at the arc apex (straight up from the center).
        let roll_r = self.size * 0.18;
        for (id, cx, cy, _spin) in ROLL_ARROWS {
            consider(id, w2(cx, cy + ROLL_ARC_R), roll_r);
        }
        best.map(|(_, id)| id)
    }
}

/// The cube's render-up: the MAIN camera's up re-orthonormalized against the
/// view forward, so the cube mirrors the camera's roll exactly. Falls back to
/// the Y-up rule (+Y, or +Z when looking straight up/down the Y axis) only when
/// the supplied up is degenerate — near-parallel to `f` (never for a valid
/// camera). Shared by [`ViewCube::mini_camera`] and [`screen_axes`] so the cube
/// render, the cube raycast and the nav-arrow anchors all live in ONE frame.
fn cube_up(f: Vec3, up: Vec3) -> Vec3 {
    let right = f.cross(up);
    if right.length() > 1e-4 {
        return right.normalized().cross(f).normalized();
    }
    let up_hint = if f.y.abs() > 0.9 { Vec3::Z } else { Vec3::Y };
    f.cross(up_hint).normalized().cross(f).normalized()
}

/// The mini-camera's screen axes (right, up) derived from the view forward + the
/// main camera's up — identical to the axes [`ViewCube::mini_camera`] builds its
/// view matrix from, so a point at `right*sx + up*sy` lands at a fixed sub-rect
/// screen position no matter how the camera is oriented or rolled.
fn screen_axes(fwd: Vec3, cam_up: Vec3) -> (Vec3, Vec3) {
    let f = fwd.normalized();
    let up = cube_up(f, cam_up);
    let right = f.cross(up).normalized();
    (right, up)
}

/// Pan/orbit triangles: `(handle, outward_x, outward_y)` in screen-axis space.
const PAN_ARROWS: [(HandleId, f32, f32); 4] = [
    (ViewCube::ARROW_UP, 0.0, 1.0),
    (ViewCube::ARROW_DOWN, 0.0, -1.0),
    (ViewCube::ARROW_RIGHT, 1.0, 0.0),
    (ViewCube::ARROW_LEFT, -1.0, 0.0),
];

/// Roll arcs: `(handle, center_x, center_y, spin)` (spin +1 = CCW, -1 = CW).
const ROLL_ARROWS: [(HandleId, f32, f32, f32); 2] = [
    (ViewCube::ROLL_CCW, -0.78, 0.78, 1.0),
    (ViewCube::ROLL_CW, 0.78, 0.78, -1.0),
];

/// Radius of the roll arc (screen-axis units); the click apex sits `+ROLL_ARC_R`
/// above the arc center.
const ROLL_ARC_R: f32 = 0.19;

/// Draw one roll arrow as a thick circular ribbon spanning ~171° over the top
/// of `center`, with a triangular arrowhead at the swept end pointing along the
/// direction of rotation (`spin` +1 = CCW, -1 = CW).
fn draw_roll_arc<F: Fn(f32, f32) -> Vec3>(
    o: &mut Overlay,
    w2: &F,
    center: [f32; 2],
    spin: f32,
    col: [f32; 4],
) {
    let r = ROLL_ARC_R;
    let th = 0.05f32; // ribbon half-thickness
    let sweep = std::f32::consts::PI * 0.95; // ~171°, centered on straight-up
    let mid = std::f32::consts::FRAC_PI_2;
    let a0 = mid - spin * sweep * 0.5;
    let a1 = mid + spin * sweep * 0.5;
    let pt = |ang: f32, rad: f32| w2(center[0] + rad * ang.cos(), center[1] + rad * ang.sin());
    const SEGS: usize = 12;
    let mut prev = a0;
    for k in 1..=SEGS {
        let ang = a0 + (a1 - a0) * (k as f32 / SEGS as f32);
        let i0 = pt(prev, r - th);
        let o0 = pt(prev, r + th);
        let i1 = pt(ang, r - th);
        let o1 = pt(ang, r + th);
        o.tri(i0, o0, o1, col);
        o.tri(i0, o1, i1, col);
        prev = ang;
    }
    // Arrowhead at the swept end (a1), pointing along the travel tangent.
    let (s1, c1) = a1.sin_cos();
    let rad_dir = [c1, s1];
    let tangent = [-s1 * spin, c1 * spin];
    let hl = 0.15f32; // head length
    let hw = 0.11f32; // head half-width
    let tip = w2(
        center[0] + r * rad_dir[0] + tangent[0] * hl,
        center[1] + r * rad_dir[1] + tangent[1] * hl,
    );
    let base0 = w2(center[0] + (r + hw) * rad_dir[0], center[1] + (r + hw) * rad_dir[1]);
    let base1 = w2(center[0] + (r - hw) * rad_dir[0], center[1] + (r - hw) * rad_dir[1]);
    o.tri(tip, base0, base1, col);
}

impl Gizmo for ViewCube {
    fn geometry(&self, camera: &GizmoCamera, hovered: Option<HandleId>, active: Option<HandleId>) -> Overlay {
        // Orientation comes from the camera's rotation (mini_camera mirrors
        // forward AND up); cube vertex positions are world-axis-fixed, so the
        // face/edge geometry consumes only forward (culling), while the
        // screen-pinned nav arrows need the full (forward, up) frame.
        let mut o = self.build(camera.forward, hovered, active);
        // The nav arrows are 2D controls pinned to the corner viewport — they
        // are placed along the mini-camera's screen axes so they stay fixed no
        // matter how the cube is oriented, and are drawn on top of the cube.
        self.draw_arrows(&mut o, camera.forward, camera.up, hovered);
        o
    }

    fn hit(&self, camera: &GizmoCamera, screen: [f32; 2]) -> Option<HandleId> {
        // `screen` is cube-local (0..size, top-left origin) — see module docs.
        let mini = self.mini_camera(camera);
        // Screen-fixed nav arrows sit outside the cube silhouette; test them
        // first so a click on an arrow never falls through to the cube.
        if let Some(id) = self.arrow_hit(&mini, screen) {
            return Some(id);
        }
        let ray = mini.ray_from_screen(screen[0], screen[1]);
        // The corner spheres protrude past the box, so hit-test them directly —
        // the whole sphere is clickable and selects that corner region. Nearest
        // (front-most) visible sphere wins over the box hit.
        let fwd = mini.forward.normalized();
        let h = 0.5f32;
        let cr = 0.135f32; // corner-node radius + a little click tolerance
        let mut best: Option<(f32, HandleId)> = None;
        for (sx, sy, sz) in [
            (-1.0f32, -1.0f32, -1.0f32), (1.0, -1.0, -1.0), (1.0, 1.0, -1.0), (-1.0, 1.0, -1.0),
            (-1.0, -1.0, 1.0), (1.0, -1.0, 1.0), (1.0, 1.0, 1.0), (-1.0, 1.0, 1.0),
        ] {
            let visible = axis_vec(0, sx).dot(fwd) < -1e-3
                || axis_vec(1, sy).dot(fwd) < -1e-3
                || axis_vec(2, sz).dot(fwd) < -1e-3;
            if !visible {
                continue;
            }
            let c = Vec3::new(sx * h, sy * h, sz * h);
            if ray.distance_to_point(c) <= cr {
                let t = c.sub(ray.origin).dot(ray.dir);
                if best.map_or(true, |(bt, _)| t < bt) {
                    best = Some((t, ViewCube::region_id(sx as i32, sy as i32, sz as i32)));
                }
            }
        }
        if let Some((_, id)) = best {
            return Some(id);
        }
        self.raycast(&ray)
    }
}

// --- region math -----------------------------------------------------------

fn decode(id: HandleId) -> [i32; 3] {
    let v = id as i32 - 1;
    [v % 3 - 1, (v / 3) % 3 - 1, (v / 9) % 3 - 1]
}

/// Classify a point on the box surface into a region by counting how many axes
/// are "extreme" (within [`EDGE_BAND`] of a face). One extreme → face, two →
/// edge, three → corner.
fn classify(p: Vec3) -> HandleId {
    let h = 0.5f32;
    let band = h * EDGE_BAND;
    let c = [p.x, p.y, p.z];
    let mut s = [0i32; 3];
    for a in 0..3 {
        if c[a] >= h - band {
            s[a] = 1;
        } else if c[a] <= -(h - band) {
            s[a] = -1;
        }
    }
    if s == [0, 0, 0] {
        // Interior of a face: snap to the dominant (entry) axis.
        let mut da = 0usize;
        for a in 1..3 {
            if c[a].abs() > c[da].abs() {
                da = a;
            }
        }
        s[da] = if c[da] >= 0.0 { 1 } else { -1 };
    }
    ViewCube::region_id(s[0], s[1], s[2])
}

/// True if the edge (signs `es`, two nonzero) lies on the corner `corner_id`.
fn region_contains(corner_id: HandleId, es: [i32; 3]) -> bool {
    let cs = decode(corner_id);
    (0..3).all(|a| es[a] == 0 || cs[a] == es[a])
}

fn face_axis_sign(n: Vec3) -> (usize, i32) {
    if n.x.abs() > 0.5 {
        (0, if n.x > 0.0 { 1 } else { -1 })
    } else if n.y.abs() > 0.5 {
        (1, if n.y > 0.0 { 1 } else { -1 })
    } else {
        (2, if n.z > 0.0 { 1 } else { -1 })
    }
}

fn axis_vec(axis: usize, s: f32) -> Vec3 {
    match axis {
        0 => Vec3::new(s, 0.0, 0.0),
        1 => Vec3::new(0.0, s, 0.0),
        _ => Vec3::new(0.0, 0.0, s),
    }
}

// --- cube geometry tables --------------------------------------------------

struct Face {
    id: HandleId,
    /// Outward normal.
    n: Vec3,
    /// In-plane axis that is screen-right when viewing the face head-on.
    u: Vec3,
    /// In-plane axis that is screen-up (`u × v == n`, so quads wind outward).
    v: Vec3,
    glyph: &'static str,
    /// Base face fill color (the original view-cube color scheme).
    color: [f32; 4],
}

fn faces() -> [Face; 6] {
    // Y-up cube: FRONT/BACK live on ±Z, TOP/BOTTOM on ±Y, RIGHT/LEFT on ±X, so
    // each face matches the same-named `standard_view` button. Per face, `u`/`v`
    // are the screen-right / screen-up axes when viewing head-on from that
    // button's vantage (world +Y up, with TOP/BOTTOM using the button's ∓Z/±Z
    // up), so the letters read upright; `u × v == n` keeps the quad wound
    // outward. Glyphs + hues stay bound to each named face.
    [
        // Original view-cube per-face hues (ff4d4d/005eff/55ff00/ffea00/ff0084/00e5ff).
        Face { id: ViewCube::RIGHT, n: Vec3::new(1.0, 0.0, 0.0), u: Vec3::new(0.0, 0.0, -1.0), v: Vec3::new(0.0, 1.0, 0.0), glyph: "R", color: [1.000, 0.302, 0.302, 1.0] },
        Face { id: ViewCube::LEFT, n: Vec3::new(-1.0, 0.0, 0.0), u: Vec3::new(0.0, 0.0, 1.0), v: Vec3::new(0.0, 1.0, 0.0), glyph: "L", color: [0.000, 0.369, 1.000, 1.0] },
        Face { id: ViewCube::BACK, n: Vec3::new(0.0, 0.0, -1.0), u: Vec3::new(-1.0, 0.0, 0.0), v: Vec3::new(0.0, 1.0, 0.0), glyph: "BK", color: [0.000, 0.898, 1.000, 1.0] },
        Face { id: ViewCube::FRONT, n: Vec3::new(0.0, 0.0, 1.0), u: Vec3::new(1.0, 0.0, 0.0), v: Vec3::new(0.0, 1.0, 0.0), glyph: "F", color: [1.000, 0.000, 0.518, 1.0] },
        Face { id: ViewCube::TOP, n: Vec3::new(0.0, 1.0, 0.0), u: Vec3::new(1.0, 0.0, 0.0), v: Vec3::new(0.0, 0.0, -1.0), glyph: "T", color: [0.333, 1.000, 0.000, 1.0] },
        Face { id: ViewCube::BOTTOM, n: Vec3::new(0.0, -1.0, 0.0), u: Vec3::new(1.0, 0.0, 0.0), v: Vec3::new(0.0, 0.0, 1.0), glyph: "B", color: [1.000, 0.918, 0.000, 1.0] },
    ]
}

/// The 12 edges as `(signs, endpoint_a, endpoint_b)`.
fn edges() -> Vec<([i32; 3], Vec3, Vec3)> {
    let h = 0.5f32;
    let mut out = Vec::with_capacity(12);
    // (i, j) are the two extreme axes; k is the axis the edge runs along.
    for &(i, j, k) in &[(0usize, 1usize, 2usize), (0, 2, 1), (1, 2, 0)] {
        for &si in &[-1i32, 1] {
            for &sj in &[-1i32, 1] {
                let mut s = [0i32; 3];
                s[i] = si;
                s[j] = sj;
                let mut e0 = [0.0f32; 3];
                e0[i] = si as f32 * h;
                e0[j] = sj as f32 * h;
                e0[k] = h;
                let mut e1 = e0;
                e1[k] = -h;
                out.push((s, Vec3::from(e0), Vec3::from(e1)));
            }
        }
    }
    out
}

/// Map a letter-space point (`[0,1]^2`, origin bottom-left) onto a face plane.
fn glyph_point(center: Vec3, u: Vec3, v: Vec3, p: [f32; 2]) -> Vec3 {
    const SCALE: f32 = 0.60; // letter spans 60% of the 1.0-wide face
    let du = (p[0] - 0.5) * SCALE;
    let dv = (p[1] - 0.5) * SCALE;
    center.add(u.scale(du)).add(v.scale(dv))
}

/// Stroked line-glyphs (polylines in `[0,1]^2`, origin bottom-left) for the six
/// face letters. Blocky approximations — enough to orient, no font needed.
fn letter_strokes(glyph: char) -> Vec<Vec<[f32; 2]>> {
    match glyph {
        'F' => vec![
            vec![[0.18, 0.10], [0.18, 0.90]],
            vec![[0.18, 0.90], [0.78, 0.90]],
            vec![[0.18, 0.52], [0.64, 0.52]],
        ],
        'B' => vec![
            vec![[0.18, 0.10], [0.18, 0.90]],
            vec![[0.18, 0.90], [0.62, 0.90], [0.74, 0.78], [0.74, 0.64], [0.62, 0.52], [0.18, 0.52]],
            vec![[0.18, 0.52], [0.66, 0.52], [0.80, 0.40], [0.80, 0.22], [0.66, 0.10], [0.18, 0.10]],
        ],
        'R' => vec![
            vec![[0.18, 0.10], [0.18, 0.90]],
            vec![[0.18, 0.90], [0.62, 0.90], [0.74, 0.78], [0.74, 0.64], [0.62, 0.52], [0.18, 0.52]],
            vec![[0.42, 0.52], [0.78, 0.10]],
        ],
        'L' => vec![vec![[0.24, 0.90], [0.24, 0.10], [0.78, 0.10]]],
        'K' => vec![
            vec![[0.20, 0.10], [0.20, 0.90]],
            vec![[0.20, 0.48], [0.80, 0.90]],
            vec![[0.20, 0.48], [0.80, 0.10]],
        ],
        'T' => vec![
            vec![[0.12, 0.90], [0.88, 0.90]],
            vec![[0.50, 0.90], [0.50, 0.10]],
        ],
        'D' => vec![
            vec![[0.20, 0.10], [0.20, 0.90]],
            vec![[0.20, 0.90], [0.55, 0.90], [0.76, 0.72], [0.82, 0.50], [0.76, 0.28], [0.55, 0.10], [0.20, 0.10]],
        ],
        _ => Vec::new(),
    }
}

// --- highlight markers -----------------------------------------------------

/// A bright chamfer strip straddling a hovered/active edge.
fn edge_bevel(o: &mut Overlay, es: [i32; 3], col: [f32; 4]) {
    let h = 0.5f32;
    let eps = 0.014f32;
    let d = 0.16f32;
    let k = (0..3).find(|&a| es[a] == 0).unwrap();
    let rest: Vec<usize> = (0..3).filter(|&a| a != k).collect();
    let (i, j) = (rest[0], rest[1]);
    let si = es[i] as f32;
    let sj = es[j] as f32;
    let mk = |ival: f32, jval: f32, kval: f32| {
        let mut arr = [0.0f32; 3];
        arr[i] = ival;
        arr[j] = jval;
        arr[k] = kval;
        Vec3::from(arr)
    };
    let a0 = mk(si * (h + eps), sj * (h - d), h);
    let a1 = mk(si * (h + eps), sj * (h - d), -h);
    let b0 = mk(si * (h - d), sj * (h + eps), h);
    let b1 = mk(si * (h - d), sj * (h + eps), -h);
    o.tri(a0, a1, b1, col);
    o.tri(a0, b1, b0, col);
}

/// A bright cap (one small triangle per adjacent front-facing face) at a
/// hovered/active corner.
fn corner_cap(o: &mut Overlay, cs: [i32; 3], col: [f32; 4], fwd: Vec3) {
    let h = 0.5f32;
    let eps = 0.016f32;
    let d = 0.20f32;
    for a in 0..3 {
        let sa = cs[a] as f32;
        if axis_vec(a, sa).dot(fwd) >= -1e-3 {
            continue; // this face is back-facing
        }
        let rest: Vec<usize> = (0..3).filter(|&x| x != a).collect();
        let (b, cc) = (rest[0], rest[1]);
        let sb = cs[b] as f32;
        let sc = cs[cc] as f32;
        let mk = |av: f32, bv: f32, cv: f32| {
            let mut arr = [0.0f32; 3];
            arr[a] = av;
            arr[b] = bv;
            arr[cc] = cv;
            Vec3::from(arr)
        };
        let p0 = mk(sa * (h + eps), sb * h, sc * h);
        let p1 = mk(sa * (h + eps), sb * (h - d), sc * h);
        let p2 = mk(sa * (h + eps), sb * h, sc * (h - d));
        o.tri(p0, p1, p2, col);
    }
}

// --- ortho mini-camera matrix (matches raster::test_view_proj's layout) -----

fn ortho_view_proj(eye: Vec3, fwd: Vec3, up_hint: Vec3, half: f32, w: f32, h: f32) -> [[f32; 4]; 4] {
    let fwd = fwd.normalized();
    let right = fwd.cross(up_hint).normalized();
    let up = right.cross(fwd).normalized();
    let view = [
        [right.x, up.x, -fwd.x, 0.0],
        [right.y, up.y, -fwd.y, 0.0],
        [right.z, up.z, -fwd.z, 0.0],
        [-right.dot(eye), -up.dot(eye), fwd.dot(eye), 1.0],
    ];
    let aspect = w / h;
    let (l, r, b, t) = (-half * aspect, half * aspect, -half, half);
    let (near, far) = (0.01f32, 100.0f32);
    let ortho = [
        [2.0 / (r - l), 0.0, 0.0, 0.0],
        [0.0, 2.0 / (t - b), 0.0, 0.0],
        [0.0, 0.0, -1.0 / (far - near), 0.0],
        [-(r + l) / (r - l), -(t + b) / (t - b), -near / (far - near), 1.0],
    ];
    mat_mul4(&ortho, &view)
}

fn mat_mul4(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
}

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

    fn main_cam(eye: Vec3) -> GizmoCamera {
        let forward = eye.scale(-1.0).normalized();
        // The engine's Y-up default (falling to +Z when looking straight up /
        // down the Y axis) — the up an un-rolled Y-up camera at this pose has,
        // so the pre-existing pinned expectations keep their meaning.
        let up = if forward.y.abs() > 0.9 { Vec3::Z } else { Vec3::Y };
        main_cam_up(eye, up)
    }

    /// A main camera at `eye` → origin with an EXPLICIT up (rolled poses).
    fn main_cam_up(eye: Vec3, up: Vec3) -> GizmoCamera {
        GizmoCamera {
            view_proj: crate::raster::test_view_proj([eye.x, eye.y, eye.z], [0.0, 0.0, 0.0], 110.0, 110.0),
            eye,
            forward: eye.scale(-1.0).normalized(),
            up,
            viewport: [800.0, 600.0],
            orthographic: true,
        }
    }

    #[test]
    fn front_region_targets_minus_z() {
        // Y-up: FRONT is the +Z face → snap looks along -Z with +Y up, exactly
        // like the FRONT standard-view button (dir +Z, up +Y).
        let v = ViewCube::target_view(ViewCube::FRONT);
        assert!(v.z < -0.9, "front snap should look along -Z: {:?}", v);
        assert!(v.x.abs() < 1e-5 && v.y.abs() < 1e-5, "front snap axis-aligned: {:?}", v);
        assert_eq!(ViewCube::target_up(ViewCube::FRONT), Vec3::Y);
    }

    #[test]
    fn right_region_targets_minus_x() {
        let v = ViewCube::target_view(ViewCube::RIGHT);
        assert!(v.x < -0.9, "right snap should look along -X: {:?}", v);
        assert_eq!(ViewCube::target_up(ViewCube::RIGHT), Vec3::Y);
    }

    /// Ground-truth proof that every named face's snap matches the same-named
    /// engine `standard_view` button. `standard_view` sets `eye = target +
    /// dir*dist, up`; the ViewCube snap sets `eye = target - target_view*dist`
    /// with `target_up`. So the eye matches iff `target_view == -dir`, and the
    /// up matches iff `target_up == up`. Both must hold for all six faces.
    #[test]
    fn face_snaps_match_standard_view_buttons() {
        // (face, standard_view dir, standard_view up) — copied verbatim from
        // brep-render `ViewCamera::standard_view` (the CORRECT Y-up buttons).
        let cases: [(HandleId, Vec3, Vec3); 6] = [
            (ViewCube::FRONT, Vec3::new(0.0, 0.0, 1.0), Vec3::new(0.0, 1.0, 0.0)),
            (ViewCube::BACK, Vec3::new(0.0, 0.0, -1.0), Vec3::new(0.0, 1.0, 0.0)),
            (ViewCube::RIGHT, Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)),
            (ViewCube::LEFT, Vec3::new(-1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)),
            (ViewCube::TOP, Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.0, 0.0, -1.0)),
            (ViewCube::BOTTOM, Vec3::new(0.0, -1.0, 0.0), Vec3::new(0.0, 0.0, 1.0)),
        ];
        for (face, dir, up) in cases {
            // eye equality: target_view == -dir.
            let want_view = dir.scale(-1.0);
            let got_view = ViewCube::target_view(face);
            assert!(
                got_view.sub(want_view).length() < 1e-6,
                "{}: target_view {:?} != -dir {:?}",
                ViewCube::region_name(face),
                got_view,
                want_view
            );
            // up equality: target_up == the button's up.
            assert_eq!(
                ViewCube::target_up(face),
                up,
                "{}: target_up != button up",
                ViewCube::region_name(face)
            );
        }
    }

    #[test]
    fn corner_region_is_iso() {
        let id = ViewCube::region_id(1, 1, 1);
        assert_eq!(ViewCube::region_kind(id), 3);
        let v = ViewCube::target_view(id);
        assert!(
            v.x.abs() > 0.1 && v.y.abs() > 0.1 && v.z.abs() > 0.1,
            "iso direction must have all components non-zero: {:?}",
            v
        );
        assert!((v.length() - 1.0).abs() < 1e-5, "normalized: {:?}", v);
        // Only the straight top/bottom fall back to a Z-based up; an iso keeps
        // the world +Y up (matching the ISO button).
        assert_eq!(ViewCube::target_up(id), Vec3::Y);
    }

    #[test]
    fn region_id_roundtrips() {
        for sx in -1..=1 {
            for sy in -1..=1 {
                for sz in -1..=1 {
                    if (sx, sy, sz) == (0, 0, 0) {
                        continue;
                    }
                    let id = ViewCube::region_id(sx, sy, sz);
                    assert_eq!(decode(id), [sx, sy, sz]);
                }
            }
        }
    }

    #[test]
    fn centered_ray_hits_front_face() {
        let cube = ViewCube::new();
        let cam = main_cam(Vec3::new(0.0, 0.0, 10.0)); // looking at the +Z (front) face
        let hit = cube.hit(&cam, [cube.size() / 2.0, cube.size() / 2.0]);
        assert_eq!(hit, Some(ViewCube::FRONT), "centered front-view ray → FRONT, got {:?}", hit);
    }

    #[test]
    fn centered_iso_ray_hits_a_corner() {
        let cube = ViewCube::new();
        let cam = main_cam(Vec3::new(6.0, 6.0, 6.0)); // +X+Y+Z octant
        let hit = cube.hit(&cam, [cube.size() / 2.0, cube.size() / 2.0]).expect("ray hits cube");
        assert_eq!(ViewCube::region_kind(hit), 3, "iso-centered ray → corner, got {}", ViewCube::region_name(hit));
        // The snapped view for that corner is the direction we were looking from.
        let want = cam.forward;
        let got = ViewCube::target_view(hit);
        assert!(got.sub(want).length() < 1e-3, "snap {:?} ≈ look dir {:?}", got, want);
    }

    #[test]
    fn geometry_non_empty_and_culls_back_faces() {
        let cube = ViewCube::new();
        let cam = main_cam(Vec3::new(0.0, 0.0, 10.0)); // straight-on FRONT (+Z) view
        let o = cube.geometry(&cam, Some(ViewCube::FRONT), None);
        assert!(!o.tris.is_empty(), "expected face tris");
        assert!(!o.lines.is_empty(), "expected edge/glyph lines");
        // Straight-on front view: one face survives culling (not all six). An
        // oblique view (3 front faces) must draw strictly more face+corner tris.
        let oblique = cube.geometry(&main_cam(Vec3::new(6.0, 8.0, 7.0)), Some(ViewCube::FRONT), None);
        assert!(o.tris.len() < oblique.tris.len(), "straight-on culls more than oblique");
    }

    #[test]
    fn arrows_are_out_of_region_range_and_classify_as_kind_zero() {
        for id in [
            ViewCube::ARROW_UP,
            ViewCube::ARROW_DOWN,
            ViewCube::ARROW_LEFT,
            ViewCube::ARROW_RIGHT,
            ViewCube::ROLL_CW,
            ViewCube::ROLL_CCW,
        ] {
            assert!(ViewCube::is_arrow(id), "id {id} should be an arrow");
            assert_eq!(ViewCube::region_kind(id), 0, "arrows are not cube regions");
            assert!(id > 27, "arrow ids sit outside the 1..=27 cube-region range");
        }
        // Cube regions are not arrows.
        assert!(!ViewCube::is_arrow(ViewCube::FRONT));
        assert!(!ViewCube::is_arrow(ViewCube::region_id(1, 1, 1)));
    }

    #[test]
    fn arrow_geometry_is_orientation_independent() {
        let cube = ViewCube::new();
        // The nav arrows must draw the SAME number of tris no matter how the
        // cube is oriented (they are screen-fixed, never culled).
        let a = cube.geometry(&main_cam(Vec3::new(0.0, 10.0, 0.0)), None, None);
        let b = cube.geometry(&main_cam(Vec3::new(6.0, 8.0, 7.0)), None, None);
        // Both include the constant arrow tri block; the oblique view still has
        // strictly more cube tris (regression guard on the shared count logic).
        assert!(a.tris.len() < b.tris.len(), "oblique draws more cube tris");
        assert!(a.tris.len() > 12, "arrows contribute a fixed tri block");
    }

    #[test]
    fn clicking_fixed_arrow_positions_hits_each_arrow() {
        let cube = ViewCube::new();
        let s = cube.size();
        // Fixed sub-rect local px for each arrow (derived from its screen-axis
        // anchor: local = ((0.5 + 0.5*sx)*s, (0.5 - 0.5*sy)*s)).
        let rc = (0.99 + 2.0 * 0.80) / 3.0_f32; // pan centroid radius
        let loc = |sx: f32, sy: f32| [(0.5 + 0.5 * sx) * s, (0.5 - 0.5 * sy) * s];
        let cases = [
            (loc(0.0, rc), ViewCube::ARROW_UP),
            (loc(0.0, -rc), ViewCube::ARROW_DOWN),
            (loc(rc, 0.0), ViewCube::ARROW_RIGHT),
            (loc(-rc, 0.0), ViewCube::ARROW_LEFT),
            (loc(-0.66, 0.66 + 0.19), ViewCube::ROLL_CCW),
            (loc(0.66, 0.66 + 0.19), ViewCube::ROLL_CW),
        ];
        // The arrow positions are screen-fixed, so they hit the same handle from
        // any cube orientation.
        for cam in [main_cam(Vec3::new(0.0, 10.0, 0.0)), main_cam(Vec3::new(6.0, 8.0, 7.0))] {
            for (px, want) in cases {
                assert_eq!(cube.hit(&cam, px), Some(want), "px {px:?} → {want}");
            }
        }
        // A click at the cube center still hits a cube region, not an arrow.
        // Looking straight down +Y centers the TOP (+Y) face.
        let center = cube.hit(&main_cam(Vec3::new(0.0, 10.0, 0.0)), [s / 2.0, s / 2.0]);
        assert_eq!(center, Some(ViewCube::TOP));
    }

    /// The cube must mirror the main camera's UP, not a forward-derived guess.
    /// TOP standard view: the engine's TOP button sets up = -Z (look -Y), so on
    /// the cube's mini screen world -Z must point UP. The old forward-only
    /// heuristic picked up = +Z here — a 180° roll error.
    #[test]
    fn mini_camera_mirrors_the_main_cameras_up_for_top_view() {
        let cube = ViewCube::new();
        let cam = main_cam_up(Vec3::new(0.0, 10.0, 0.0), Vec3::new(0.0, 0.0, -1.0));
        let mini = cube.mini_camera(&cam);
        let c = mini.world_to_screen(Vec3::ZERO).unwrap();
        let z_minus = mini.world_to_screen(Vec3::new(0.0, 0.0, -0.4)).unwrap();
        assert!(
            z_minus[1] < c[1] - 1.0,
            "-Z must project screen-UP in the TOP view (up=-Z): center {c:?}, -Z {z_minus:?}"
        );
        assert!((z_minus[0] - c[0]).abs() < 1e-2, "-Z projects straight up, no sideways drift");
    }

    /// A ROLLED camera (up rotated about the view axis): the cube's mini screen
    /// must roll with it — the camera's own up always projects straight up.
    #[test]
    fn mini_camera_follows_camera_roll() {
        let cube = ViewCube::new();
        // FRONT view (eye +Z, forward -Z) rolled 30°: up in the XY plane.
        let (s, c30) = (30.0f32.to_radians().sin(), 30.0f32.to_radians().cos());
        let up = Vec3::new(s, c30, 0.0);
        let cam = main_cam_up(Vec3::new(0.0, 0.0, 10.0), up);
        let mini = cube.mini_camera(&cam);
        let c = mini.world_to_screen(Vec3::ZERO).unwrap();
        let u = mini.world_to_screen(up.scale(0.4)).unwrap();
        assert!(u[1] < c[1] - 1.0, "camera up projects screen-UP: {c:?} vs {u:?}");
        assert!((u[0] - c[0]).abs() < 1e-2, "camera up projects straight up (no drift)");
        // And world +Y is now tilted off screen-vertical by the roll angle.
        let y = mini.world_to_screen(Vec3::new(0.0, 0.4, 0.0)).unwrap();
        let dy = [(y[0] - c[0]), (y[1] - c[1])];
        let ang = dy[0].atan2(-dy[1]).abs().to_degrees();
        assert!((ang - 30.0).abs() < 0.5, "world +Y tilted by the 30° roll, got {ang}°");
    }

    /// The screen-fixed nav arrows must stay at their corner positions (and hit
    /// the same handles) under camera ROLL — they anchor to the mini-camera's
    /// screen axes, which now follow the true camera up.
    #[test]
    fn arrows_stay_screen_fixed_under_roll() {
        let cube = ViewCube::new();
        let s = cube.size();
        let (rs, rc) = (35.0f32.to_radians().sin(), 35.0f32.to_radians().cos());
        let cam = main_cam_up(Vec3::new(0.0, 0.0, 10.0), Vec3::new(rs, rc, 0.0));
        let centroid = (1.18 + 2.0 * 0.98) / 3.0_f32;
        // Exact anchor→pixel mapping of the mini-camera (ortho half = 1.25):
        // a screen-axis point at (sx, sy) lands at ndc (sx/1.25, sy/1.25).
        let loc = |sx: f32, sy: f32| {
            [(0.5 + 0.5 * sx / 1.25) * s, (0.5 - 0.5 * sy / 1.25) * s]
        };
        for (px, want) in [
            (loc(0.0, centroid), ViewCube::ARROW_UP),
            (loc(0.0, -centroid), ViewCube::ARROW_DOWN),
            (loc(centroid, 0.0), ViewCube::ARROW_RIGHT),
            (loc(-centroid, 0.0), ViewCube::ARROW_LEFT),
        ] {
            assert_eq!(cube.hit(&cam, px), Some(want), "rolled cam: px {px:?} → {want}");
        }
    }

    #[test]
    fn sub_rect_is_bottom_right() {
        let cube = ViewCube::new();
        let [x, y, w, h] = cube.sub_rect([800.0, 600.0]);
        assert!((w - 135.0).abs() < 1e-3 && (h - 135.0).abs() < 1e-3);
        assert!((x - (800.0 - 135.0 - 12.0)).abs() < 1e-3, "x={x}");
        assert!((y - (600.0 - 135.0 - 12.0)).abs() < 1e-3, "y={y}");
    }
}