rustial-engine 0.0.1

Framework-agnostic 2.5D map engine for rustial
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
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
//! Camera state, projection, and input controller for the 2.5D map view.
//!
//! # Coordinate conventions
//!
//! The engine uses a **camera-relative** rendering model to avoid f32
//! jitter at large Web Mercator coordinates.  All positions passed to
//! the GPU are expressed relative to `camera.target_world()`.
//!
//! ```text
//!        +Z  (up / altitude)
//!         |
//!         |   +Y  (north, Web Mercator)
//!         |  /
//!         | /
//!         O -----> +X  (east, Web Mercator)
//!
//!   Map tiles lie on the Z = 0 plane.
//! ```
//!
//! ## Spherical eye offset
//!
//! The camera orbits the target point using spherical coordinates:
//!
//! | Parameter | Range | Meaning |
//! |-----------|-------|---------|
//! | `pitch`   | `0` to `PI/2` | `0` = top-down (eye on +Z), `PI/2` = horizon |
//! | `yaw`     | any | Clockwise bearing from north (+Y) when viewed from above |
//! | `distance`| > 0 | Radius of the orbit sphere (meters) |
//!
//! # Architecture
//!
//! | Type | Role |
//! |------|------|
//! | [`Camera`] | Immutable-style state struct (target, orbit params, projection). |
//! | [`CameraConstraints`] | Clamps applied every frame (distance, pitch limits). |
//! | [`CameraController`] | Stateless helper that maps [`InputEvent`]s to camera mutations. |
//! | [`CameraMode`] | Perspective vs. orthographic projection selection. |
//!
//! The [`CameraAnimator`](crate::CameraAnimator) (in its own module) wraps
//! smooth transitions and momentum on top of these primitives.

use crate::camera_projection::CameraProjection;
use crate::input::InputEvent;
use glam::{DMat4, DVec3, DVec4};
use rustial_math::{Ellipsoid, GeoCoord, Globe, WorldCoord};

// ---------------------------------------------------------------------------
// CameraMode
// ---------------------------------------------------------------------------

/// Projection mode for the map camera.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CameraMode {
    /// Orthographic projection (2D-like, no perspective foreshortening).
    Orthographic,
    /// Perspective projection (3D depth).
    #[default]
    Perspective,
}

// ---------------------------------------------------------------------------
// Camera
// ---------------------------------------------------------------------------

/// The map camera state.
///
/// Stores the geographic target, orbital parameters (pitch / yaw / distance),
/// projection mode, and viewport dimensions.  All derived matrices are
/// computed on demand -- the struct itself is plain data.
///
/// # Invariants (enforced by setters)
///
/// | Field | Guarantee |
/// |-------|-----------|
/// | `pitch` | Clamped to `[0, PI/2 - ?]` on every write |
/// | `yaw` | Normalized to `[-?, ?]` on every write |
/// | `distance` | Always positive and finite |
/// | `fov_y` | Always positive and finite |
///
/// # Thread safety
///
/// `Camera` is `Send + Sync` (all fields are `Copy` or trivially safe).
/// It is typically owned by [`MapState`](crate::MapState) and mutated from
/// a single thread per frame.
#[derive(Debug, Clone)]
pub struct Camera {
    /// Geographic center the camera is looking at.
    target: GeoCoord,
    /// Geographic projection used by camera/world coordinate helpers.
    projection: CameraProjection,
    /// Distance from the target point, in meters.
    distance: f64,
    /// Pitch angle in radians (0 = top-down, PI/2 = horizon).
    pitch: f64,
    /// Yaw / bearing angle in radians (0 = north-up, clockwise positive).
    /// Always normalized to [-?, ?].
    yaw: f64,
    /// Projection mode.
    mode: CameraMode,
    /// Vertical field of view in radians (perspective mode only).
    fov_y: f64,
    /// Viewport width in pixels.
    viewport_width: u32,
    /// Viewport height in pixels.
    viewport_height: u32,
}

/// Hard upper limit for pitch -- just below the singularity at ?/2.
const MAX_PITCH: f64 = std::f64::consts::FRAC_PI_2 - 0.001;

/// Normalize an angle to `[-?, ?]`.
#[inline]
fn normalize_yaw(yaw: f64) -> f64 {
    let two_pi = std::f64::consts::TAU;
    let mut y = yaw % two_pi;
    if y > std::f64::consts::PI {
        y -= two_pi;
    }
    if y < -std::f64::consts::PI {
        y += two_pi;
    }
    y
}

impl Default for Camera {
    fn default() -> Self {
        Self {
            target: GeoCoord::from_lat_lon(0.0, 0.0),
            projection: CameraProjection::default(),
            distance: 10_000_000.0,
            pitch: 0.0,
            yaw: 0.0,
            mode: CameraMode::default(),
            fov_y: std::f64::consts::FRAC_PI_4,
            viewport_width: 800,
            viewport_height: 600,
        }
    }
}

impl Camera {
    fn sync_projection_state(&mut self) {
        if matches!(
            self.projection,
            CameraProjection::VerticalPerspective { .. }
        ) {
            self.projection = CameraProjection::vertical_perspective(self.target, self.distance);
        }
    }

    fn local_basis(&self) -> (DVec3, DVec3, DVec3) {
        match self.projection {
            CameraProjection::Globe => {
                let lat = self.target.lat.to_radians();
                let lon = self.target.lon.to_radians();
                let (sin_lat, cos_lat) = lat.sin_cos();
                let (sin_lon, cos_lon) = lon.sin_cos();

                let east = DVec3::new(-sin_lon, cos_lon, 0.0);
                let north = DVec3::new(-sin_lat * cos_lon, -sin_lat * sin_lon, cos_lat);
                let up = DVec3::new(cos_lat * cos_lon, cos_lat * sin_lon, sin_lat);
                (east, north, up)
            }
            _ => (DVec3::X, DVec3::Y, DVec3::Z),
        }
    }

    fn view_up_from_eye(&self, eye: DVec3, target_world: DVec3) -> DVec3 {
        const BLEND_RAD: f64 = 0.15;
        let (sy, cy) = self.yaw.sin_cos();
        let (east, north, _) = self.local_basis();

        let yaw_up = east * sy + north * cy;
        let right = east * cy - north * sy;
        let look = (target_world - eye).normalize_or_zero();
        let pitched_up = right.cross(look).normalize_or_zero();

        let t = (self.pitch / BLEND_RAD).clamp(0.0, 1.0);
        let up = (pitched_up * t + yaw_up * (1.0 - t)).normalize_or_zero();
        if up.length_squared() < 0.5 {
            DVec3::Z
        } else {
            up
        }
    }

    fn screen_to_geo_on_globe(&self, px: f64, py: f64) -> Option<GeoCoord> {
        let (origin, dir) = self.screen_to_ray(px, py);
        let radius = Ellipsoid::WGS84.a;
        let a = dir.dot(dir);
        let b = 2.0 * origin.dot(dir);
        let c = origin.dot(origin) - radius * radius;
        let disc = b * b - 4.0 * a * c;
        if disc < 0.0 {
            return None;
        }
        let sqrt_disc = disc.sqrt();
        let t0 = (-b - sqrt_disc) / (2.0 * a);
        let t1 = (-b + sqrt_disc) / (2.0 * a);
        let t = [t0, t1]
            .into_iter()
            .filter(|t| *t >= 0.0)
            .min_by(|a, b| a.total_cmp(b))?;
        let hit = origin + dir * t;
        Some(Globe::unproject(&WorldCoord::new(hit.x, hit.y, hit.z)))
    }

    /// Camera-relative up vector matching [`view_matrix`](Self::view_matrix).
    pub fn view_up_vector(&self) -> DVec3 {
        let eye = self.eye_offset();
        self.view_up_from_eye(eye, DVec3::ZERO)
    }

    // -- Getters -----------------------------------------------------------

    /// Geographic center the camera is looking at.
    #[inline]
    pub fn target(&self) -> &GeoCoord {
        &self.target
    }

    /// Distance from the target point, in meters.
    #[inline]
    pub fn distance(&self) -> f64 {
        self.distance
    }

    /// Geographic projection used by camera/world coordinate helpers.
    #[inline]
    pub fn projection(&self) -> CameraProjection {
        self.projection
    }

    /// Pitch angle in radians (0 = top-down, ??/2 = horizon).
    #[inline]
    pub fn pitch(&self) -> f64 {
        self.pitch
    }

    /// Yaw / bearing angle in radians, normalized to `[-?, ?]`.
    #[inline]
    pub fn yaw(&self) -> f64 {
        self.yaw
    }

    /// Projection mode.
    #[inline]
    pub fn mode(&self) -> CameraMode {
        self.mode
    }

    /// Vertical field of view in radians (perspective mode only).
    #[inline]
    pub fn fov_y(&self) -> f64 {
        self.fov_y
    }

    /// Viewport width in pixels.
    #[inline]
    pub fn viewport_width(&self) -> u32 {
        self.viewport_width
    }

    /// Viewport height in pixels.
    #[inline]
    pub fn viewport_height(&self) -> u32 {
        self.viewport_height
    }

    // -- Setters (validated) ----------------------------------------------

    /// Set the camera target coordinate.
    #[inline]
    pub fn set_target(&mut self, target: GeoCoord) {
        self.target = target;
        self.sync_projection_state();
    }

    /// Set the camera's geographic projection.
    #[inline]
    pub fn set_projection(&mut self, projection: CameraProjection) {
        self.projection = projection;
        self.sync_projection_state();
    }

    /// Set camera distance in meters.  Non-finite or non-positive values
    /// are rejected in debug builds and ignored in release builds.
    pub fn set_distance(&mut self, d: f64) {
        debug_assert!(
            d.is_finite() && d > 0.0,
            "Camera::set_distance: invalid {d}"
        );
        if d.is_finite() && d > 0.0 {
            self.distance = d;
        }
    }

    /// Set pitch in radians.  Hard-clamped to `[0, MAX_PITCH]`.
    /// Non-finite values are rejected.
    pub fn set_pitch(&mut self, p: f64) {
        debug_assert!(p.is_finite(), "Camera::set_pitch: non-finite {p}");
        if p.is_finite() {
            self.pitch = p.clamp(0.0, MAX_PITCH);
        }
    }

    /// Set yaw / bearing in radians.  Normalized to `[-?, ?]`.
    /// Non-finite values are rejected.
    pub fn set_yaw(&mut self, y: f64) {
        debug_assert!(y.is_finite(), "Camera::set_yaw: non-finite {y}");
        if y.is_finite() {
            self.yaw = normalize_yaw(y);
        }
    }

    /// Set the projection mode.
    ///
    /// Adjusts `distance` so that
    /// [`meters_per_pixel`](Self::meters_per_pixel) (and therefore the
    /// displayed zoom level) stays constant across the transition.
    ///
    /// The visible ground height formulas are:
    ///
    /// - **Perspective**: `2 * distance * tan(fov_y / 2)`
    /// - **Orthographic**: `2 * distance`
    ///
    /// Equating the two gives the conversion factor `tan(fov_y / 2)`.
    pub fn set_mode(&mut self, mode: CameraMode) {
        if mode == self.mode {
            return;
        }
        let half_tan = (self.fov_y / 2.0).tan();
        match (self.mode, mode) {
            (CameraMode::Perspective, CameraMode::Orthographic) => {
                self.distance *= half_tan;
            }
            (CameraMode::Orthographic, CameraMode::Perspective) => {
                if half_tan.abs() > 1e-12 {
                    self.distance /= half_tan;
                }
            }
            _ => {}
        }
        self.mode = mode;
    }

    /// Set vertical field-of-view in radians.  Non-finite or non-positive
    /// values are rejected.
    pub fn set_fov_y(&mut self, fov: f64) {
        debug_assert!(
            fov.is_finite() && fov > 0.0,
            "Camera::set_fov_y: invalid {fov}"
        );
        if fov.is_finite() && fov > 0.0 {
            self.fov_y = fov;
        }
    }

    /// Set the viewport dimensions in pixels.
    #[inline]
    pub fn set_viewport(&mut self, width: u32, height: u32) {
        self.viewport_width = width;
        self.viewport_height = height;
    }

    // -- Orbital geometry -------------------------------------------------

    /// Eye position relative to the target (camera-relative origin).
    ///
    /// Computed from spherical coordinates with the conventions documented
    /// in the [module-level docs](self).
    ///
    /// ```text
    /// eye.x = d * sin(pitch) * sin(yaw)   -- east component
    /// eye.y = d * sin(pitch) * cos(yaw)   -- north component
    /// eye.z = d * cos(pitch)              -- altitude
    /// ```
    ///
    /// At `yaw = 0` the camera sits on the +Y (north) side of the target.
    pub fn eye_offset(&self) -> DVec3 {
        let (sp, cp) = self.pitch.sin_cos();
        let (sy, cy) = self.yaw.sin_cos();
        let (east, north, up) = self.local_basis();
        east * (-self.distance * sp * sy)
            + north * (-self.distance * sp * cy)
            + up * (self.distance * cp)
    }

    // -- Matrix builders --------------------------------------------------

    /// Build a view matrix (world -> camera clip space, right-handed).
    ///
    /// # Up-vector derivation
    ///
    /// The up-hint is computed from the orbital geometry in two regimes:
    ///
    /// **Pitched** (`pitch > threshold`): the camera's "screen-right"
    /// vector is the orbit-sphere tangent in the yaw direction:
    ///
    /// ```text
    /// right = (cos(yaw), -sin(yaw), 0)
    /// ```
    ///
    /// This is always horizontal, always perpendicular to the look
    /// direction, and independent of pitch.  The up-hint is then
    /// `right x look` (normalised), which is guaranteed to point
    /// "above the horizon" from the camera's perspective and is never
    /// degenerate.
    ///
    /// **Top-down** (`pitch <= threshold`): the look direction is nearly
    /// `-Z`, and the horizontal right vector is degenerate (the orbit
    /// tangent's magnitude approaches zero).  Instead the up-hint is set
    /// to `(sin(yaw), cos(yaw), 0)` so the yaw bearing controls which
    /// map direction appears at the top of the screen.
    ///
    /// The two regimes are smoothly blended over `0..threshold` using
    /// `t = pitch / threshold` so there is no visible discontinuity.
    ///
    /// Key properties:
    ///
    /// - At any yaw and any pitch, the up-hint is never parallel to the
    ///   look direction (no gimbal-lock or north/south flip).
    /// - At `pitch = 0`, screen-up follows the yaw bearing.
    /// - At high pitch, screen-up is always world-Z (natural horizon).
    pub fn view_matrix(&self, target_world: DVec3) -> DMat4 {
        let eye = target_world + self.eye_offset();
        let up = self.view_up_from_eye(eye, target_world);

        DMat4::look_at_rh(eye, target_world, up)
    }

    /// Build a perspective projection matrix (right-handed, depth [0, 1]).
    ///
    /// # Depth range
    ///
    /// - **Near plane**: `distance * 0.001` -- close enough for objects at
    ///   the camera target, far enough to preserve depth precision.
    /// - **Far plane**: `distance * 10 * pitch_factor` -- when pitched
    ///   toward the horizon the visible ground extends well beyond the
    ///   orbit distance.  `pitch_factor = min(1/cos(pitch), 100)` scales
    ///   the far plane to avoid clipping.
    pub fn perspective_matrix(&self) -> DMat4 {
        let aspect = self.viewport_width as f64 / self.viewport_height.max(1) as f64;
        let near = self.distance * 0.001;
        let pitch_far_scale = if self.pitch > 0.01 {
            (1.0 / self.pitch.cos().abs().max(0.05)).min(100.0)
        } else {
            1.0
        };
        let far = self.distance * 10.0 * pitch_far_scale;
        DMat4::perspective_rh(self.fov_y, aspect, near, far)
    }

    /// Build an orthographic projection matrix (right-handed).
    ///
    /// Half-height equals `distance`, so zooming works identically to
    /// perspective mode (increase distance = see more ground).  The near /
    /// far range is `+/-distance * 100` to accommodate terrain elevation.
    pub fn orthographic_matrix(&self) -> DMat4 {
        let half_h = self.distance;
        let aspect = self.viewport_width as f64 / self.viewport_height.max(1) as f64;
        let half_w = half_h * aspect;
        let near = -self.distance * 100.0;
        let far = self.distance * 100.0;
        DMat4::orthographic_rh(-half_w, half_w, -half_h, half_h, near, far)
    }

    /// Build the projection matrix based on the current [`mode`](Self::mode).
    pub fn projection_matrix(&self) -> DMat4 {
        match self.mode {
            CameraMode::Perspective => self.perspective_matrix(),
            CameraMode::Orthographic => self.orthographic_matrix(),
        }
    }

    // -- Coordinate helpers -----------------------------------------------

    /// Target position in projected world space (meters).
    pub fn target_world(&self) -> DVec3 {
        self.projection.project(&self.target).position
    }

    /// Combined view-projection matrix (camera-relative origin).
    pub fn view_projection_matrix(&self) -> DMat4 {
        let target_world = self.target_world();
        self.projection_matrix() * self.view_matrix(target_world)
    }

    /// Combined view-projection matrix in **absolute** world space.
    ///
    /// Unlike [`view_projection_matrix`](Self::view_projection_matrix),
    /// which places the target at the origin (camera-relative), this
    /// computes the VP with world coordinates left as-is.  The resulting
    /// frustum planes therefore live in the same coordinate space as
    /// [`tile_bounds_world`](rustial_math::tile_bounds_world) and can be
    /// used directly for frustum-based tile culling.
    pub fn absolute_view_projection_matrix(&self) -> DMat4 {
        let target_world = self.target_world();
        self.projection_matrix() * self.view_matrix(target_world)
    }

    /// Export the current camera as a [`CoveringCamera`](rustial_math::CoveringCamera)
    /// suitable for the MapLibre-equivalent covering-tiles traversal with
    /// per-tile variable zoom.
    ///
    /// Returns `None` for orthographic mode or non-Mercator projections.
    pub fn covering_camera(&self, fractional_zoom: f64) -> Option<rustial_math::CoveringCamera> {
        if self.projection != CameraProjection::WebMercator {
            return None;
        }
        if self.mode != CameraMode::Perspective {
            return None;
        }

        let world_size = rustial_math::WebMercator::world_size();
        let target_world = self.target_world();
        let eye = target_world + self.eye_offset();

        // Convert from Mercator meters to normalised [0..1] coords.
        let half = world_size * 0.5;
        let cam_x = (eye.x + half) / world_size;
        let cam_y = (half - eye.y) / world_size;
        let center_x = (target_world.x + half) / world_size;
        let center_y = (half - target_world.y) / world_size;

        let cam_to_center_z = eye.z / world_size;

        Some(rustial_math::CoveringCamera {
            camera_x: cam_x,
            camera_y: cam_y,
            camera_to_center_z: cam_to_center_z.abs(),
            center_x,
            center_y,
            pitch_rad: self.pitch,
            fov_deg: self.fov_y.to_degrees(),
            zoom: fractional_zoom,
            display_tile_size: 256,
        })
    }

    /// Export the current perspective camera as flat-tile selection parameters.
    ///
    /// Returns `None` for orthographic mode because footprint-aware flat-tile
    /// filtering is only needed for pitched perspective views.
    pub fn flat_tile_view(&self) -> Option<rustial_math::FlatTileView> {
        if self.projection != CameraProjection::WebMercator {
            return None;
        }

        match self.mode {
            CameraMode::Perspective => Some(rustial_math::FlatTileView::new(
                rustial_math::WorldCoord::new(
                    self.target_world().x,
                    self.target_world().y,
                    self.target_world().z,
                ),
                self.distance,
                self.pitch,
                self.yaw,
                self.fov_y,
                self.viewport_width,
                self.viewport_height,
            )),
            CameraMode::Orthographic => None,
        }
    }

    // -- Picking / unprojection -------------------------------------------

    /// Unproject a screen-space pixel coordinate to a world-space ray.
    ///
    /// Returns `(origin, direction)` in **absolute** world space
    /// (Web Mercator metres).  The direction is normalised.
    ///
    /// `px`, `py` are in logical pixels with `(0, 0)` at the top-left
    /// corner of the viewport.
    ///
    /// Returns `(DVec3::ZERO, -DVec3::Z)` for degenerate viewports
    /// (width or height of zero) to avoid NaN propagation.
    pub fn screen_to_ray(&self, px: f64, py: f64) -> (DVec3, DVec3) {
        let w = self.viewport_width.max(1) as f64;
        let h = self.viewport_height.max(1) as f64;

        let target_world = self.target_world();
        let view = self.view_matrix(target_world);
        let proj = self.projection_matrix();
        let vp_inv = (proj * view).inverse();

        // Convert pixel to NDC: x in [-1, 1], y in [-1, 1] (top = +1).
        let ndc_x = (2.0 * px / w) - 1.0;
        let ndc_y = 1.0 - (2.0 * py / h);

        let near_ndc = DVec4::new(ndc_x, ndc_y, -1.0, 1.0);
        let far_ndc = DVec4::new(ndc_x, ndc_y, 1.0, 1.0);

        let near_world = vp_inv * near_ndc;
        let far_world = vp_inv * far_ndc;

        // Guard against degenerate inverse (w ~= 0).
        if near_world.w.abs() < 1e-12 || far_world.w.abs() < 1e-12 {
            return (DVec3::ZERO, -DVec3::Z);
        }

        let near = DVec3::new(
            near_world.x / near_world.w,
            near_world.y / near_world.w,
            near_world.z / near_world.w,
        );
        let far = DVec3::new(
            far_world.x / far_world.w,
            far_world.y / far_world.w,
            far_world.z / far_world.w,
        );

        let dir = (far - near).normalize();
        if dir.is_nan() {
            return (DVec3::ZERO, -DVec3::Z);
        }
        (near, dir)
    }

    /// Intersect the unprojected ray with the ground plane (Z = 0) and
    /// return the geographic coordinate at the hit point.
    ///
    /// Returns `None` if the ray is parallel to the ground or points
    /// away from it (sky).
    pub fn screen_to_geo(&self, px: f64, py: f64) -> Option<GeoCoord> {
        if matches!(self.projection, CameraProjection::Globe) {
            return self.screen_to_geo_on_globe(px, py);
        }

        let (origin, dir) = self.screen_to_ray(px, py);

        // Ray-plane intersection: t = -origin.z / dir.z
        if dir.z.abs() < 1e-12 {
            return None; // Parallel to ground.
        }
        let t = -origin.z / dir.z;
        if t < 0.0 {
            return None; // Behind the camera.
        }

        let hit = origin + dir * t;
        let world = rustial_math::WorldCoord::new(hit.x, hit.y, 0.0);
        Some(self.projection.unproject(&world))
    }

    /// Project a geographic coordinate to a screen-space pixel position.
    ///
    /// Returns `(px, py)` in logical pixels with `(0, 0)` at the
    /// top-left corner of the viewport, or `None` if the point is
    /// behind the camera.
    pub fn geo_to_screen(&self, geo: &GeoCoord) -> Option<(f64, f64)> {
        let w = self.viewport_width.max(1) as f64;
        let h = self.viewport_height.max(1) as f64;

        let world_pos = self.projection.project(geo);
        let target_world = self.target_world();
        let view = self.view_matrix(target_world);
        let proj = self.projection_matrix();
        let vp = proj * view;

        let clip = vp
            * DVec4::new(
                world_pos.position.x,
                world_pos.position.y,
                world_pos.position.z,
                1.0,
            );

        // Behind the camera.
        if clip.w <= 0.0 {
            return None;
        }

        let ndc_x = clip.x / clip.w;
        let ndc_y = clip.y / clip.w;

        // NDC to pixel: x in [0, w], y in [0, h] (top-left origin).
        let px = (ndc_x + 1.0) * 0.5 * w;
        let py = (1.0 - ndc_y) * 0.5 * h;

        Some((px, py))
    }

    // -- Resolution helpers -----------------------------------------------

    /// Approximate meters-per-pixel at the current zoom level (screen center).
    ///
    /// For perspective mode this is the ground-plane resolution at the
    /// target point (not at the edges, which varies with pitch).  For
    /// orthographic mode the resolution is uniform across the viewport.
    pub fn meters_per_pixel(&self) -> f64 {
        let visible_height = match self.mode {
            CameraMode::Perspective => 2.0 * self.distance * (self.fov_y / 2.0).tan(),
            CameraMode::Orthographic => 2.0 * self.distance,
        };
        visible_height / self.viewport_height.max(1) as f64
    }

    /// Approximate meters-per-pixel at the **near ground** (bottom of
    /// the screen).
    ///
    /// When the camera is pitched toward the horizon, the ground
    /// closest to the viewer (bottom of the viewport) has a much finer
    /// resolution than the target point.  Using this value for zoom
    /// selection ensures tiles near the camera are sharp.
    ///
    /// The result is clamped so the zoom level increases by at most
    /// three steps (factor of 8) relative to
    /// [`meters_per_pixel`](Self::meters_per_pixel).  When the covering-
    /// tiles variable-zoom path is active, the per-tile zoom heuristic
    /// automatically assigns lower zoom levels to distant tiles, so this
    /// generous ceiling does not cause excessive tile counts.
    ///
    /// Returns the same value as `meters_per_pixel` when `pitch` is
    /// below ~30 degrees or the camera is orthographic.
    pub fn near_meters_per_pixel(&self) -> f64 {
        let center_mpp = self.meters_per_pixel();

        if self.pitch.abs() < 0.01 {
            return center_mpp;
        }

        match self.mode {
            CameraMode::Orthographic => center_mpp,
            CameraMode::Perspective => {
                // Camera height above the ground plane.
                let h = self.distance * self.pitch.cos();
                if h <= 0.0 {
                    return center_mpp;
                }

                // The bottom-of-screen ray's angle from vertical.
                // pitch = angle from vertical to look direction.
                // Bottom-of-screen = pitch - fov_y/2  (closer to vertical = nearer ground).
                let half_fov = self.fov_y / 2.0;
                let near_angle = (self.pitch - half_fov).max(0.01);

                // Ground-plane resolution per radian at angle theta from vertical:
                //   dr/rad = h / cos^2(theta)
                // One pixel subtends fov_y / viewport_height radians.
                let rad_per_px = self.fov_y / self.viewport_height.max(1) as f64;
                let cos_near = near_angle.cos();
                let near_mpp = h * rad_per_px / (cos_near * cos_near);

                // Clamp: at most three extra zoom levels (factor of 8).
                // The covering-tiles variable-zoom heuristic keeps distant
                // tiles at lower zoom, so this generous ceiling does not
                // cause excessive tile counts.
                near_mpp.clamp(center_mpp * 0.125, center_mpp)
            }
        }
    }

    // -- Test helper (not public API) -------------------------------------
}

// ---------------------------------------------------------------------------
// CameraConstraints
// ---------------------------------------------------------------------------

/// Per-frame clamps applied to the camera by [`CameraController`].
///
/// Prevents the user from zooming too close (sub-meter), too far
/// (beyond Earth's radius), or pitching past the horizon.
#[derive(Debug, Clone)]
pub struct CameraConstraints {
    /// Minimum camera distance in meters.
    pub min_distance: f64,
    /// Maximum camera distance in meters.
    pub max_distance: f64,
    /// Minimum pitch in radians (typically 0 = top-down).
    pub min_pitch: f64,
    /// Maximum pitch in radians (typically just below PI/2).
    pub max_pitch: f64,
}

impl Default for CameraConstraints {
    fn default() -> Self {
        Self {
            min_distance: 1.0,
            max_distance: 40_000_000.0,
            min_pitch: 0.0,
            max_pitch: std::f64::consts::FRAC_PI_2 - 0.01,
        }
    }
}

// ---------------------------------------------------------------------------
// CameraController
// ---------------------------------------------------------------------------

/// Stateless helper that maps [`InputEvent`]s to camera mutations.
///
/// All methods are associated functions (no `self`) because the
/// controller carries no state -- it is a pure function namespace.
/// The actual state lives in [`Camera`] and [`CameraConstraints`].
pub struct CameraController;

impl CameraController {
    fn retarget_for_screen_anchor(camera: &mut Camera, desired: GeoCoord, actual: GeoCoord) {
        if matches!(
            camera.projection(),
            CameraProjection::Globe | CameraProjection::VerticalPerspective { .. }
        ) {
            let mut target = *camera.target();
            target.lat = (target.lat + (desired.lat - actual.lat)).clamp(-90.0, 90.0);
            let lon_delta = desired.lon - actual.lon;
            let mut lon = target.lon + lon_delta;
            lon = ((lon + 180.0) % 360.0 + 360.0) % 360.0 - 180.0;
            target.lon = lon;
            camera.set_target(target);
            return;
        }

        let desired = camera.projection().project(&desired);
        let actual = camera.projection().project(&actual);
        let current = camera.projection().project(camera.target());

        let shift_x = actual.position.x - desired.position.x;
        let shift_y = actual.position.y - desired.position.y;

        let extent = camera.projection().max_extent();
        let full = camera.projection().world_size();
        let mut new_x = current.position.x - shift_x;
        let new_y = (current.position.y - shift_y).clamp(-extent, extent);
        new_x = ((new_x + extent) % full + full) % full - extent;

        camera.set_target(camera.projection().unproject(&WorldCoord::new(
            new_x,
            new_y,
            current.position.z,
        )));
    }

    /// Zoom by a multiplicative factor (>1 zooms in, <1 zooms out).
    ///
    /// Non-finite, zero, and negative factors are silently ignored.
    pub fn zoom(
        camera: &mut Camera,
        factor: f64,
        cursor_x: Option<f64>,
        cursor_y: Option<f64>,
        constraints: &CameraConstraints,
    ) {
        if !factor.is_finite() || factor <= 0.0 {
            return;
        }

        let anchor = match (cursor_x, cursor_y) {
            (Some(x), Some(y)) => camera.screen_to_geo(x, y).map(|geo| (x, y, geo)),
            _ => None,
        };

        camera.set_distance(
            (camera.distance() / factor).clamp(constraints.min_distance, constraints.max_distance),
        );

        if let Some((x, y, desired)) = anchor {
            if let Some(actual) = camera.screen_to_geo(x, y) {
                Self::retarget_for_screen_anchor(camera, desired, actual);
            }
        }
    }

    /// Rotate the camera by delta yaw and delta pitch (radians).
    ///
    /// Pitch is clamped to [`CameraConstraints`]; yaw wraps freely
    /// (normalized to `[-?, ?]` by the setter).
    pub fn rotate(
        camera: &mut Camera,
        delta_yaw: f64,
        delta_pitch: f64,
        constraints: &CameraConstraints,
    ) {
        camera.set_yaw(camera.yaw() + delta_yaw);
        camera.set_pitch(
            (camera.pitch() + delta_pitch).clamp(constraints.min_pitch, constraints.max_pitch),
        );
    }

    /// Pan the camera by a screen-space pixel delta.
    pub fn pan(
        camera: &mut Camera,
        dx: f64,
        dy: f64,
        cursor_x: Option<f64>,
        cursor_y: Option<f64>,
    ) {
        let px = cursor_x.unwrap_or(camera.viewport_width() as f64 * 0.5);
        let py = cursor_y.unwrap_or(camera.viewport_height() as f64 * 0.5);

        if matches!(
            camera.projection(),
            CameraProjection::Globe | CameraProjection::VerticalPerspective { .. }
        ) {
            if let (Some(geo_a), Some(geo_b)) = (
                camera.screen_to_geo(px, py),
                camera.screen_to_geo(px + dx, py + dy),
            ) {
                Self::retarget_for_screen_anchor(camera, geo_a, geo_b);
                return;
            }
        }

        if let (Some(geo_a), Some(geo_b)) = (
            camera.screen_to_geo(px, py),
            camera.screen_to_geo(px + dx, py + dy),
        ) {
            Self::retarget_for_screen_anchor(camera, geo_a, geo_b);
            return;
        }

        // Fallback: center-based approximation.
        let mpp = camera.meters_per_pixel();
        let (sy, cy) = camera.yaw().sin_cos();

        let world_dx = (dx * cy + dy * sy) * mpp;
        let world_dy = (-dx * sy + dy * cy) * mpp;

        let current = camera.projection.project(camera.target());
        let mut new_x = current.position.x - world_dx;
        let mut new_y = current.position.y + world_dy;

        let extent = camera.projection.max_extent();
        let full = camera.projection.world_size();
        new_x = ((new_x + extent) % full + full) % full - extent;
        new_y = new_y.clamp(-extent, extent);

        camera.set_target(camera.projection.unproject(&WorldCoord::new(
            new_x,
            new_y,
            current.position.z,
        )));
    }

    /// Dispatch an [`InputEvent`] to the appropriate handler.
    ///
    /// [`Touch`](InputEvent::Touch) events are ignored here — they
    /// should be routed through the
    /// [`GestureRecognizer`](crate::gesture::GestureRecognizer) first,
    /// which produces derived Pan/Zoom/Rotate events.
    pub fn handle_event(camera: &mut Camera, event: InputEvent, constraints: &CameraConstraints) {
        match event {
            InputEvent::Pan { dx, dy, x, y } => Self::pan(camera, dx, dy, x, y),
            InputEvent::Zoom { factor, x, y } => Self::zoom(camera, factor, x, y, constraints),
            InputEvent::Rotate {
                delta_yaw,
                delta_pitch,
            } => Self::rotate(camera, delta_yaw, delta_pitch, constraints),
            InputEvent::Resize { width, height } => {
                camera.set_viewport(width, height);
            }
            InputEvent::Touch(_) => {
                // Raw touch events are handled by GestureRecognizer in
                // MapState::handle_input, not here.
            }
        }
    }
}

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

    // -- Eye offset -------------------------------------------------------

    #[test]
    fn default_camera_top_down() {
        let cam = Camera::default();
        let offset = cam.eye_offset();
        assert!(offset.x.abs() < 1e-6);
        assert!(offset.y.abs() < 1e-6);
        assert!((offset.z - cam.distance()).abs() < 1e-6);
    }

    #[test]
    fn eye_offset_pitched_yaw_zero() {
        let mut cam = Camera::default();
        cam.set_pitch(std::f64::consts::FRAC_PI_4);
        cam.set_distance(100.0);
        let offset = cam.eye_offset();
        assert!(offset.x.abs() < 1e-6, "x should be ~0, got {}", offset.x);
        assert!(offset.y < -1.0, "y should be negative, got {}", offset.y);
        assert!(offset.z > 1.0, "z should be positive, got {}", offset.z);
    }

    #[test]
    fn eye_offset_pitched_yaw_90() {
        let mut cam = Camera::default();
        cam.set_pitch(std::f64::consts::FRAC_PI_4);
        cam.set_yaw(std::f64::consts::FRAC_PI_2);
        cam.set_distance(100.0);
        let offset = cam.eye_offset();
        assert!(offset.x < -1.0, "x should be negative for east-facing");
        assert!(offset.y.abs() < 1e-6, "y should be ~0");
        assert!(offset.z > 1.0, "z should be positive");
    }

    // -- View matrix stability --------------------------------------------

    #[test]
    fn view_matrix_no_flip_through_pitch_range() {
        let mut cam = Camera::default();
        cam.set_distance(1000.0);

        let target = DVec3::ZERO;
        let steps = 100;
        let max_pitch = std::f64::consts::FRAC_PI_2 - 0.02;

        for i in 0..=steps {
            cam.set_pitch(max_pitch * (i as f64 / steps as f64));
            let view = cam.view_matrix(target);
            let eye = target + cam.eye_offset();
            assert!(
                eye.z > 0.0,
                "eye should be above ground at pitch={:.3}",
                cam.pitch()
            );
            for col in 0..4 {
                let c = view.col(col);
                assert!(
                    c.x.is_finite() && c.y.is_finite() && c.z.is_finite() && c.w.is_finite(),
                    "non-finite view matrix at pitch={:.3}",
                    cam.pitch()
                );
            }
        }
    }

    #[test]
    fn view_matrix_stable_through_yaw_range() {
        let mut cam = Camera::default();
        cam.set_distance(1000.0);
        cam.set_pitch(0.5);

        let target = DVec3::ZERO;
        for i in 0..=36 {
            cam.set_yaw((i as f64 / 36.0) * std::f64::consts::TAU);
            let view = cam.view_matrix(target);
            for col in 0..4 {
                let c = view.col(col);
                assert!(
                    c.x.is_finite() && c.y.is_finite() && c.z.is_finite() && c.w.is_finite(),
                    "non-finite view matrix at yaw={:.3}",
                    cam.yaw()
                );
            }
        }
    }

    #[test]
    fn view_matrix_no_north_south_flip_at_yaw_pi() {
        let mut cam = Camera::default();
        cam.set_distance(1000.0);
        cam.set_yaw(std::f64::consts::PI);

        let target = DVec3::ZERO;
        let steps = 50;
        let max_pitch = std::f64::consts::FRAC_PI_2 - 0.05;
        let mut prev_right_x: Option<f64> = None;

        for i in 0..=steps {
            cam.set_pitch(max_pitch * (i as f64 / steps as f64));
            let view = cam.view_matrix(target);
            let right_x = view.col(0).x;
            if let Some(prev) = prev_right_x {
                assert!(
                    right_x * prev > -1e-6,
                    "screen-right flipped sign at pitch={:.3}: was {prev:.4}, now {right_x:.4}",
                    cam.pitch()
                );
            }
            prev_right_x = Some(right_x);
        }
    }

    // -- Zoom / constraints -----------------------------------------------

    #[test]
    fn zoom_clamp() {
        let mut cam = Camera::default();
        let constraints = CameraConstraints::default();
        CameraController::zoom(&mut cam, 1e20, None, None, &constraints);
        assert!(cam.distance() >= constraints.min_distance);
        CameraController::zoom(&mut cam, 1e-20, None, None, &constraints);
        assert!(cam.distance() <= constraints.max_distance);
    }

    #[test]
    fn zoom_nan_ignored() {
        let mut cam = Camera::default();
        let original = cam.distance();
        let constraints = CameraConstraints::default();
        CameraController::zoom(&mut cam, f64::NAN, None, None, &constraints);
        assert_eq!(cam.distance(), original);
    }

    #[test]
    fn zoom_zero_ignored() {
        let mut cam = Camera::default();
        let original = cam.distance();
        let constraints = CameraConstraints::default();
        CameraController::zoom(&mut cam, 0.0, None, None, &constraints);
        assert_eq!(cam.distance(), original);
    }

    #[test]
    fn zoom_negative_ignored() {
        let mut cam = Camera::default();
        let original = cam.distance();
        let constraints = CameraConstraints::default();
        CameraController::zoom(&mut cam, -2.0, None, None, &constraints);
        assert_eq!(cam.distance(), original);
    }

    #[test]
    fn zoom_infinity_ignored() {
        let mut cam = Camera::default();
        let original = cam.distance();
        let constraints = CameraConstraints::default();
        CameraController::zoom(&mut cam, f64::INFINITY, None, None, &constraints);
        assert_eq!(cam.distance(), original);
    }

    #[test]
    fn zoom_around_center_keeps_target_stable() {
        let mut cam = Camera::default();
        cam.set_target(GeoCoord::from_lat_lon(51.1, 17.0));
        cam.set_distance(100_000.0);
        cam.set_viewport(800, 600);
        let before = *cam.target();
        let constraints = CameraConstraints::default();

        CameraController::zoom(&mut cam, 1.1, Some(400.0), Some(300.0), &constraints);

        let after = *cam.target();
        assert!((after.lat - before.lat).abs() < 1e-6);
        assert!((after.lon - before.lon).abs() < 1e-6);
    }

    #[test]
    fn zoom_around_cursor_preserves_anchor_location() {
        let mut cam = Camera::default();
        cam.set_target(GeoCoord::from_lat_lon(51.1, 17.0));
        cam.set_distance(100_000.0);
        cam.set_viewport(800, 600);
        let constraints = CameraConstraints::default();
        let desired = cam.screen_to_geo(650.0, 420.0).expect("anchor before zoom");

        CameraController::zoom(&mut cam, 1.1, Some(650.0), Some(420.0), &constraints);

        let actual = cam.screen_to_geo(650.0, 420.0).expect("anchor after zoom");
        assert!((actual.lat - desired.lat).abs() < 1e-4);
        assert!((actual.lon - desired.lon).abs() < 1e-4);
        assert!((cam.target().lat - 51.1).abs() > 1e-5 || (cam.target().lon - 17.0).abs() > 1e-5);
    }

    // -- Projection matrices ----------------------------------------------

    #[test]
    fn perspective_matrix_not_zero() {
        let cam = Camera::default();
        let m = cam.perspective_matrix();
        assert!(m.col(0).x.abs() > 0.0);
    }

    #[test]
    fn orthographic_matrix_not_zero() {
        let mut cam = Camera::default();
        cam.set_mode(CameraMode::Orthographic);
        let m = cam.orthographic_matrix();
        assert!(m.col(0).x.abs() > 0.0);
    }

    #[test]
    fn projection_matrix_matches_mode() {
        let mut cam = Camera::default();
        cam.set_mode(CameraMode::Perspective);
        let p = cam.projection_matrix();
        assert_eq!(p, cam.perspective_matrix());

        cam.set_mode(CameraMode::Orthographic);
        let o = cam.projection_matrix();
        assert_eq!(o, cam.orthographic_matrix());
    }

    #[test]
    fn far_plane_grows_with_pitch() {
        let mut cam = Camera::default();
        cam.set_distance(10_000.0);
        let m0 = cam.perspective_matrix();

        cam.set_pitch(1.2);
        let m1 = cam.perspective_matrix();

        let depth0 = m0.col(2).z;
        let depth1 = m1.col(2).z;
        assert!(
            (depth1 - depth0).abs() > 1e-6,
            "far plane should differ with pitch"
        );
    }

    #[test]
    fn perspective_matrix_finite_at_max_pitch() {
        let mut cam = Camera::default();
        cam.set_pitch(std::f64::consts::FRAC_PI_2 - 0.01);
        cam.set_distance(10_000.0);
        let m = cam.perspective_matrix();
        for col in 0..4 {
            let c = m.col(col);
            assert!(
                c.x.is_finite() && c.y.is_finite() && c.z.is_finite() && c.w.is_finite(),
                "perspective matrix should be finite at max pitch"
            );
        }
    }

    // -- Screen-to-geo / screen-to-ray ------------------------------------

    #[test]
    fn screen_to_geo_center_returns_target() {
        let mut cam = Camera::default();
        cam.set_target(GeoCoord::from_lat_lon(51.1, 17.0));
        cam.set_distance(100_000.0);
        cam.set_viewport(800, 600);
        let geo = cam.screen_to_geo(400.0, 300.0);
        assert!(geo.is_some(), "center of screen should hit ground");
        let geo = geo.expect("center hit");
        assert!(
            (geo.lat - 51.1).abs() < 0.1,
            "lat should be near 51.1, got {}",
            geo.lat
        );
        assert!(
            (geo.lon - 17.0).abs() < 0.1,
            "lon should be near 17.0, got {}",
            geo.lon
        );
    }

    #[test]
    fn screen_to_geo_off_center_differs() {
        let mut cam = Camera::default();
        cam.set_distance(100_000.0);
        cam.set_viewport(800, 600);
        let center = cam.screen_to_geo(400.0, 300.0).expect("center");
        let corner = cam.screen_to_geo(0.0, 0.0).expect("corner");
        let dist = ((center.lat - corner.lat).powi(2) + (center.lon - corner.lon).powi(2)).sqrt();
        assert!(dist > 0.01, "corner and center should differ");
    }

    #[test]
    fn screen_to_ray_direction_is_normalized() {
        let cam = Camera::default();
        let (_, dir) = cam.screen_to_ray(400.0, 300.0);
        assert!(
            (dir.length() - 1.0).abs() < 1e-6,
            "direction should be unit length"
        );
    }

    #[test]
    fn screen_to_ray_degenerate_viewport() {
        let mut cam = Camera::default();
        cam.set_viewport(0, 0);
        let (origin, dir) = cam.screen_to_ray(0.0, 0.0);
        assert!(origin.x.is_finite());
        assert!(dir.z.is_finite());
    }

    #[test]
    fn screen_to_geo_horizon_returns_none() {
        let mut cam = Camera::default();
        cam.set_pitch(std::f64::consts::FRAC_PI_2 - 0.02);
        cam.set_distance(10_000.0);
        cam.set_viewport(800, 600);
        let result = cam.screen_to_geo(400.0, 0.0);
        if let Some(geo) = result {
            assert!(geo.lat.is_finite());
            assert!(geo.lon.is_finite());
        }
    }

    // -- Meters per pixel -------------------------------------------------

    #[test]
    fn meters_per_pixel_positive() {
        let cam = Camera::default();
        assert!(cam.meters_per_pixel() > 0.0);
    }

    #[test]
    fn meters_per_pixel_decreases_with_zoom() {
        let mut cam = Camera::default();
        let mpp_far = cam.meters_per_pixel();
        cam.set_distance(1_000.0);
        let mpp_close = cam.meters_per_pixel();
        assert!(mpp_close < mpp_far);
    }

    #[test]
    fn meters_per_pixel_ortho_vs_perspective() {
        let mut cam = Camera::default();
        cam.set_mode(CameraMode::Perspective);
        let mpp_persp = cam.meters_per_pixel();
        cam.set_mode(CameraMode::Orthographic);
        let mpp_ortho = cam.meters_per_pixel();
        assert!(mpp_persp > 0.0 && mpp_persp.is_finite());
        assert!(mpp_ortho > 0.0 && mpp_ortho.is_finite());
    }

    #[test]
    fn set_mode_preserves_meters_per_pixel() {
        let mut cam = Camera::default();
        cam.set_distance(100_000.0);
        cam.set_viewport(1280, 720);

        cam.set_mode(CameraMode::Perspective);
        let mpp_before = cam.meters_per_pixel();

        cam.set_mode(CameraMode::Orthographic);
        let mpp_after = cam.meters_per_pixel();

        assert!(
            (mpp_before - mpp_after).abs() / mpp_before < 1e-10,
            "meters_per_pixel should be preserved: perspective={mpp_before}, orthographic={mpp_after}"
        );

        // Round-trip back to perspective should also preserve.
        cam.set_mode(CameraMode::Perspective);
        let mpp_roundtrip = cam.meters_per_pixel();
        assert!(
            (mpp_before - mpp_roundtrip).abs() / mpp_before < 1e-10,
            "meters_per_pixel should survive round-trip: original={mpp_before}, roundtrip={mpp_roundtrip}"
        );
    }

    #[test]
    fn target_world_uses_selected_projection() {
        let mut cam = Camera::default();
        cam.set_target(GeoCoord::from_lat_lon(45.0, 10.0));

        let merc = cam.target_world();
        cam.set_projection(CameraProjection::Equirectangular);
        let eq = cam.target_world();

        assert!((merc.x - eq.x).abs() < 1e-6);
        assert!((merc.y - eq.y).abs() > 1_000.0);
    }

    #[test]
    fn screen_to_geo_center_respects_equirectangular_projection() {
        let mut cam = Camera::default();
        cam.set_projection(CameraProjection::Equirectangular);
        cam.set_target(GeoCoord::from_lat_lon(30.0, 20.0));
        cam.set_distance(100_000.0);
        cam.set_viewport(800, 600);

        let geo = cam.screen_to_geo(400.0, 300.0).expect("center hit");
        assert!((geo.lat - 30.0).abs() < 0.1);
        assert!((geo.lon - 20.0).abs() < 0.1);
    }

    #[test]
    fn screen_to_geo_center_respects_globe_projection() {
        let mut cam = Camera::default();
        cam.set_projection(CameraProjection::Globe);
        cam.set_target(GeoCoord::from_lat_lon(30.0, 20.0));
        cam.set_distance(3_000_000.0);
        cam.set_viewport(800, 600);

        let geo = cam.screen_to_geo(400.0, 300.0).expect("center hit");
        assert!((geo.lat - 30.0).abs() < 0.1);
        assert!((geo.lon - 20.0).abs() < 0.1);
    }

    #[test]
    fn screen_to_geo_center_respects_vertical_perspective_projection() {
        let mut cam = Camera::default();
        cam.set_target(GeoCoord::from_lat_lon(30.0, 20.0));
        cam.set_distance(3_000_000.0);
        cam.set_projection(CameraProjection::vertical_perspective(
            *cam.target(),
            cam.distance(),
        ));
        cam.set_viewport(800, 600);

        let geo = cam.screen_to_geo(400.0, 300.0).expect("center hit");
        assert!((geo.lat - 30.0).abs() < 0.1);
        assert!((geo.lon - 20.0).abs() < 0.1);
    }

    #[test]
    fn pan_moves_target_under_globe_projection() {
        let mut cam = Camera::default();
        cam.set_projection(CameraProjection::Globe);
        cam.set_target(GeoCoord::from_lat_lon(10.0, 10.0));
        cam.set_distance(3_000_000.0);
        cam.set_viewport(800, 600);

        let before = *cam.target();
        CameraController::pan(&mut cam, 100.0, 0.0, None, None);
        let after = *cam.target();

        assert!((after.lon - before.lon).abs() > 0.0 || (after.lat - before.lat).abs() > 0.0);
    }
}