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
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
//! Smooth camera animation with easing and momentum.
//!
//! This module provides a stateful animator used by
//! [`MapState`](crate::MapState) to drive camera transitions:
//!
//! - **`fly_to`** -- the van Wijk & Nuij (2003) "optimal path" animation
//!   matching MapLibre/Mapbox `flyTo`.  Simultaneously interpolates center,
//!   zoom, bearing, and pitch along a zoom-out-then-zoom-in arc.
//! - **`ease_to`** -- simple interpolation of center, zoom, bearing, and
//!   pitch with configurable duration and easing.
//! - **Momentum** -- inertial pan that decays over time.
//! - **Simple targets** -- independent exponential-smoothed zoom / rotation
//!   targets (legacy, still useful for scroll-zoom and keyboard rotation).
//!
//! # Design
//!
//! - Time integration is explicit via [`tick`](CameraAnimator::tick)
//!   and caller-provided `dt` (seconds).
//! - The van Wijk flight uses an easing function applied to wall-clock
//!   progress `t ? [0, 1]` to produce a path parameter `k`, then derives
//!   zoom scale `w(s)` and center factor `u(s)` from the paper's
//!   closed-form expressions.
//! - Bearing and pitch are linearly interpolated in `k` (same as MapLibre).
//! - Yaw interpolation follows the shortest angular path.
//!
//! # Reference
//!
//! Van Wijk, Jarke J.; Nuij, Wim A. A.  "Smooth and efficient zooming
//! and panning."  INFOVIS '03. pp. 15-22.
//! <https://www.win.tue.nl/~vanwijk/zoompan.pdf>

use crate::camera::Camera;
use crate::camera_projection::CameraProjection;
use crate::geo_wrap::{shortest_lon_target, wrap_lon_180};
use rustial_math::{GeoCoord, WorldCoord};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Approximate meters per degree of latitude (WGS-84 at equator).
const METERS_PER_DEGREE: f64 = 111_319.49;

/// Maximum latitude for Web Mercator validity.
const MERCATOR_MAX_LAT: f64 = 85.06;

/// Activity threshold for momentum (m/s).
const MOMENTUM_EPS: f64 = 0.01;

/// Distance convergence threshold (meters).
const DISTANCE_EPS: f64 = 0.1;

/// Angle convergence threshold (radians).
const ANGLE_EPS: f64 = 1e-4;

/// Earth's equatorial circumference in meters (2*pi * WGS-84 semi-major axis).
const WGS84_CIRCUMFERENCE: f64 = 2.0 * std::f64::consts::PI * 6_378_137.0;

/// Standard tile size in pixels.
const TILE_PX: f64 = 256.0;

// ---------------------------------------------------------------------------
// Easing
// ---------------------------------------------------------------------------

/// Evaluate a cubic bezier easing curve at parameter `t`.
///
/// Control points are `(0, 0)`, `(x1, y1)`, `(x2, y2)`, `(1, 1)`.
/// Returns the `y` value for the given `t` (time) input.
fn cubic_bezier(x1: f64, y1: f64, x2: f64, y2: f64, t: f64) -> f64 {
    // Newton-Raphson to find the bezier parameter `s` such that `x(s) = t`.
    let mut s = t;
    for _ in 0..8 {
        let x = bezier_component(x1, x2, s) - t;
        let dx = bezier_derivative(x1, x2, s);
        if dx.abs() < 1e-12 {
            break;
        }
        s -= x / dx;
        s = s.clamp(0.0, 1.0);
    }
    bezier_component(y1, y2, s)
}

fn bezier_component(p1: f64, p2: f64, t: f64) -> f64 {
    let t2 = t * t;
    let t3 = t2 * t;
    3.0 * p1 * t * (1.0 - t) * (1.0 - t) + 3.0 * p2 * t2 * (1.0 - t) + t3
}

fn bezier_derivative(p1: f64, p2: f64, t: f64) -> f64 {
    let t2 = t * t;
    3.0 * p1 * (1.0 - t) * (1.0 - t) + 6.0 * (p2 - p1) * t * (1.0 - t) + 3.0 * (1.0 - p2) * t2
}

/// MapLibre default easing: `cubic-bezier(0.25, 0.1, 0.25, 1.0)`.
fn default_easing(t: f64) -> f64 {
    cubic_bezier(0.25, 0.1, 0.25, 1.0, t)
}

// ---------------------------------------------------------------------------
// Zoom <-> distance helpers
// ---------------------------------------------------------------------------

/// Convert a fractional zoom level to camera distance (meters).
///
/// This inverts the `zoom = log2(circumference / (mpp * tile_px))` formula
/// where `mpp = visible_height / viewport_height` and
/// `visible_height = 2 * distance * tan(fov_y/2)` for perspective,
/// or `visible_height = 2 * distance` for orthographic.
fn zoom_to_distance(zoom: f64, fov_y: f64, viewport_height: u32, is_perspective: bool) -> f64 {
    let mpp = WGS84_CIRCUMFERENCE / (2.0_f64.powf(zoom) * TILE_PX);
    let visible_height = mpp * viewport_height.max(1) as f64;
    if is_perspective {
        visible_height / (2.0 * (fov_y / 2.0).tan())
    } else {
        visible_height / 2.0
    }
}

/// Convert camera distance to fractional zoom level.
fn distance_to_zoom(distance: f64, fov_y: f64, viewport_height: u32, is_perspective: bool) -> f64 {
    let visible_height = if is_perspective {
        2.0 * distance * (fov_y / 2.0).tan()
    } else {
        2.0 * distance
    };
    let mpp = visible_height / viewport_height.max(1) as f64;
    if mpp <= 0.0 || !mpp.is_finite() {
        return 22.0;
    }
    (WGS84_CIRCUMFERENCE / (mpp * TILE_PX))
        .log2()
        .clamp(0.0, 22.0)
}

// ---------------------------------------------------------------------------
// FlyToOptions
// ---------------------------------------------------------------------------

/// Options for the [`fly_to`](CameraAnimator::start_fly_to) animation.
///
/// Mirrors the MapLibre/Mapbox `FlyToOptions` API.
///
/// All fields are optional.  When omitted, the animation retains the
/// camera's current value for that property.
#[derive(Debug, Clone)]
pub struct FlyToOptions {
    /// Target geographic center.  If `None`, the center does not change.
    pub center: Option<GeoCoord>,
    /// Target zoom level.  If `None`, the zoom does not change.
    pub zoom: Option<f64>,
    /// Target bearing (yaw) in **radians**.  If `None`, bearing does not change.
    ///
    /// The animation always takes the shortest angular path.
    pub bearing: Option<f64>,
    /// Target pitch in **radians**.  If `None`, pitch does not change.
    pub pitch: Option<f64>,
    /// The zooming "curve" (? in the van Wijk paper).
    ///
    /// Higher values produce more exaggerated zoom-out.
    /// Default: `1.42` (the user-study average from van Wijk 2003).
    pub curve: f64,
    /// Average speed in ?-screenfulls per second.  Default: `1.2`.
    ///
    /// Ignored when `duration` is set explicitly.
    pub speed: f64,
    /// Average speed in screenfulls per second (overrides `speed`).
    ///
    /// Ignored when `duration` is set explicitly.
    pub screen_speed: Option<f64>,
    /// Explicit animation duration in **seconds**.
    ///
    /// When set, `speed` / `screen_speed` are ignored and the animation
    /// runs for exactly this duration.
    pub duration: Option<f64>,
    /// The zoom level at the peak of the flight path.
    ///
    /// When set, `curve` is overridden to produce a zoom-out that reaches
    /// this zoom level.
    pub min_zoom: Option<f64>,
    /// Maximum allowed duration in **seconds**.
    ///
    /// If the auto-computed duration exceeds this, the animation
    /// degrades to an instant `jump_to`.
    pub max_duration: Option<f64>,
    /// Easing function `f(t) -> k` where `t` and `k` are both in `[0, 1]`.
    ///
    /// Default: `cubic-bezier(0.25, 0.1, 0.25, 1.0)` (MapLibre default).
    pub easing: Option<fn(f64) -> f64>,
}

impl Default for FlyToOptions {
    fn default() -> Self {
        Self {
            center: None,
            zoom: None,
            bearing: None,
            pitch: None,
            curve: 1.42,
            speed: 1.2,
            screen_speed: None,
            duration: None,
            min_zoom: None,
            max_duration: None,
            easing: None,
        }
    }
}

// ---------------------------------------------------------------------------
// EaseToOptions
// ---------------------------------------------------------------------------

/// Options for the [`ease_to`](CameraAnimator::start_ease_to) animation.
///
/// Simple linear interpolation of all camera properties over a fixed
/// duration, matching MapLibre's `easeTo`.
#[derive(Debug, Clone)]
pub struct EaseToOptions {
    /// Target geographic center.
    pub center: Option<GeoCoord>,
    /// Target zoom level.
    pub zoom: Option<f64>,
    /// Target bearing (yaw) in radians.
    pub bearing: Option<f64>,
    /// Target pitch in radians.
    pub pitch: Option<f64>,
    /// Duration in seconds.  Default: `0.5`.
    pub duration: f64,
    /// Easing function.  Default: `cubic-bezier(0.25, 0.1, 0.25, 1.0)`.
    pub easing: Option<fn(f64) -> f64>,
}

impl Default for EaseToOptions {
    fn default() -> Self {
        Self {
            center: None,
            zoom: None,
            bearing: None,
            pitch: None,
            duration: 0.5,
            easing: None,
        }
    }
}

// ---------------------------------------------------------------------------
// Internal flight state
// ---------------------------------------------------------------------------

/// Active van Wijk fly-to animation state.
struct FlyToState {
    // -- End state --
    end_center: GeoCoord,
    end_zoom: f64,
    end_bearing: f64,
    end_pitch: f64,

    // -- Start state (needed for per-frame interpolation) --
    start_zoom: f64,
    start_bearing: f64,
    start_pitch: f64,

    // -- Van Wijk parameters --
    /// Projected start position (world coords at initial scale).
    from_x: f64,
    from_y: f64,
    /// Projected delta (end - start in world coords at initial scale).
    delta_x: f64,
    delta_y: f64,
    /// w0: initial visible span in pixels.
    w0: f64,
    /// u1: ground-plane path length in pixels at initial scale.
    u1: f64,
    /// ?: zoom curve parameter.
    rho: f64,
    /// r?: zoom-out factor during ascent.
    r0: f64,
    /// S: total path length in ?-screenfulls.
    path_length: f64,
    /// Whether u? ? 0 (same-location zoom-only path).
    zoom_only: bool,
    /// k = w1 < w0 ? -1 : 1  (used in zoom-only fallback).
    zoom_only_sign: f64,

    // -- Timing --
    duration: f64,
    elapsed: f64,
    easing: fn(f64) -> f64,

    // -- Projection used for world-space interpolation --
    projection: CameraProjection,
    is_perspective: bool,
    fov_y: f64,
    viewport_height: u32,
}

impl FlyToState {
    fn new(camera: &Camera, opts: &FlyToOptions) -> Option<Self> {
        let projection = camera.projection();
        let is_perspective = camera.mode() == crate::camera::CameraMode::Perspective;
        let fov_y = camera.fov_y();
        let viewport_height = camera.viewport_height();
        let viewport_width = camera.viewport_width();

        let start_center = *camera.target();
        let start_zoom =
            distance_to_zoom(camera.distance(), fov_y, viewport_height, is_perspective);
        let start_bearing = camera.yaw();
        let start_pitch = camera.pitch();

        let end_center = opts.center.unwrap_or(start_center);
        let end_zoom = opts.zoom.unwrap_or(start_zoom);
        let end_bearing = match opts.bearing {
            Some(b) => shortest_bearing_target(start_bearing, b),
            None => start_bearing,
        };
        let end_pitch = opts.pitch.unwrap_or(start_pitch);

        // Project start and end centers to world coordinates.
        let from_world = projection.project(&start_center);
        let to_world = projection.project(&end_center);

        // World-size at the *initial* zoom level, used to convert between
        // "world pixels" (MapLibre's coordinate space) and meters.
        // At zoom z, world_size = tile_px * 2^z  (in pixels).
        // We need a pixel-space path length: divide meters by mpp.
        let pixels_per_meter = 2.0_f64.powf(start_zoom) * TILE_PX / WGS84_CIRCUMFERENCE;

        let from_px_x = from_world.position.x * pixels_per_meter;
        let from_px_y = from_world.position.y * pixels_per_meter;
        let to_px_x = to_world.position.x * pixels_per_meter;
        let to_px_y = to_world.position.y * pixels_per_meter;

        let delta_x = to_px_x - from_px_x;
        let delta_y = to_px_y - from_px_y;

        // u1: ground-plane path length in pixels at initial scale.
        let u1 = (delta_x * delta_x + delta_y * delta_y).sqrt();

        // w0: initial visible span (max of width, height) in pixels.
        let w0 = viewport_width.max(viewport_height).max(1) as f64;

        // scale = 2^(endZoom - startZoom)  (MapLibre: zoomScale(zoom - startZoom))
        let scale_of_zoom = 2.0_f64.powf(end_zoom - start_zoom);

        // w1: final visible span measured in pixels at the *initial* scale.
        // MapLibre: w1 = w0 / scale
        let w1 = w0 / scale_of_zoom;

        // rho: curve parameter.
        let mut rho = opts.curve;

        // If minZoom is specified, override rho.
        // MapLibre: const minZoom = clamp(Math.min(options.minZoom, startZoom, zoom), ...)
        if let Some(min_z) = opts.min_zoom {
            let min_z = min_z.min(start_zoom).min(end_zoom);
            let scale_of_min_zoom = 2.0_f64.powf(min_z - start_zoom);
            let w_max = w0 / scale_of_min_zoom;
            if u1 > 0.0 {
                rho = (w_max / u1 * 2.0).sqrt();
            }
        }

        let rho2 = rho * rho;

        // r(i): zoom-out factor at one end of the animation.
        // MapLibre/Mapbox:
        //   function r(i) {
        //     const b = (w1*w1 - w0*w0 + (i ? -1 : 1) * rho2*rho2 * u1*u1)
        //               / (2 * (i ? w1 : w0) * rho2 * u1);
        //     return Math.log(Math.sqrt(b*b + 1) - b);
        //   }
        // descent=true corresponds to i=1 (descent), descent=false to i=0 (ascent).
        let zoom_out_factor = |descent: bool| -> f64 {
            let (w, sign) = if descent { (w1, -1.0) } else { (w0, 1.0) };
            let b = (w1 * w1 - w0 * w0 + sign * rho2 * rho2 * u1 * u1) / (2.0 * w * rho2 * u1);
            ((b * b + 1.0).sqrt() - b).ln()
        };

        let r0;
        let path_length;
        let zoom_only;
        let zoom_only_sign;

        // Check if the ground-plane path is effectively zero or if the
        // full van Wijk formula produces a non-finite result.
        // MapLibre/Mapbox: if (Math.abs(u1) < 0.000001 || !isFinite(S))
        let is_degenerate = if u1.abs() < 0.000001 {
            true
        } else {
            let trial_r0 = zoom_out_factor(false);
            let trial_r1 = zoom_out_factor(true);
            let trial_s = (trial_r1 - trial_r0) / rho;
            !trial_s.is_finite()
        };

        if is_degenerate {
            // Same-location or degenerate path.
            // MapLibre/Mapbox: if (Math.abs(w0 - w1) < 0.000001) return this.easeTo(...)
            if (w0 - w1).abs() < 0.000001 {
                // No zoom change and no center change -- nothing to animate
                // unless bearing or pitch changed.
                if (end_bearing - start_bearing).abs() < ANGLE_EPS
                    && (end_pitch - start_pitch).abs() < ANGLE_EPS
                {
                    return None;
                }
            }

            // MapLibre/Mapbox: const k = w1 < w0 ? -1 : 1;
            //                  S = Math.abs(Math.log(w1 / w0)) / rho;
            //                  w = function(s) { return Math.exp(k * rho * s); };
            zoom_only = true;
            zoom_only_sign = if w1 < w0 { -1.0 } else { 1.0 };
            r0 = 0.0;
            path_length = if w1 > 0.0 && w0 > 0.0 {
                (w1 / w0).ln().abs() / rho
            } else {
                0.0
            };
        } else {
            zoom_only = false;
            zoom_only_sign = 0.0;
            // MapLibre/Mapbox: r0 = r(0);  S = (r(1) - r0) / rho;
            r0 = zoom_out_factor(false);
            let r1 = zoom_out_factor(true);
            path_length = (r1 - r0) / rho;
        }

        // Compute duration.
        // MapLibre/Mapbox: duration = 1000 * S / V  (milliseconds)
        // We store duration in seconds.
        let duration = if let Some(d) = opts.duration {
            d
        } else {
            let v = if let Some(ss) = opts.screen_speed {
                ss / rho
            } else {
                opts.speed
            };
            if v > 0.0 {
                path_length / v
            } else {
                1.0
            }
        };

        // Check max_duration.
        // MapLibre/Mapbox: if (options.maxDuration && options.duration > options.maxDuration)
        //                      options.duration = 0;
        if let Some(max_dur) = opts.max_duration {
            if duration > max_dur {
                return None; // Degrade to instant jump.
            }
        }

        let easing = opts.easing.unwrap_or(default_easing);

        Some(FlyToState {
            start_zoom,
            start_bearing,
            start_pitch,
            end_center,
            end_zoom,
            end_bearing,
            end_pitch,
            from_x: from_px_x,
            from_y: from_px_y,
            delta_x,
            delta_y,
            w0,
            u1,
            rho,
            r0,
            path_length,
            zoom_only,
            zoom_only_sign,
            duration,
            elapsed: 0.0,
            easing,
            projection,
            is_perspective,
            fov_y,
            viewport_height,
        })
    }

    /// Evaluate the van Wijk w(s) function -- visible span at path distance s.
    fn w(&self, s: f64) -> f64 {
        if self.zoom_only {
            (self.zoom_only_sign * self.rho * s).exp()
        } else {
            self.r0.cosh() / (self.r0 + self.rho * s).cosh()
        }
    }

    /// Evaluate the van Wijk u(s) function -- center interpolation factor.
    fn u(&self, s: f64) -> f64 {
        if self.zoom_only {
            0.0
        } else {
            let rho2 = self.rho * self.rho;
            self.w0 * ((self.r0.cosh() * (self.r0 + self.rho * s).tanh() - self.r0.sinh()) / rho2)
                / self.u1
        }
    }

    /// Advance the flight by `dt` seconds.  Returns `true` when complete.
    fn tick(&mut self, camera: &mut Camera, dt: f64) -> bool {
        self.elapsed += dt;
        let t = (self.elapsed / self.duration.max(1e-9)).clamp(0.0, 1.0);
        let k = (self.easing)(t);

        let done = t >= 1.0;

        if done {
            // Snap to final state.
            camera.set_target(self.end_center);
            camera.set_distance(zoom_to_distance(
                self.end_zoom,
                self.fov_y,
                self.viewport_height,
                self.is_perspective,
            ));
            camera.set_yaw(self.end_bearing);
            camera.set_pitch(self.end_pitch);
            return true;
        }

        // Path distance in ?-screenfulls.
        let s = k * self.path_length;

        // Scale factor: 1/w(s).
        let scale = 1.0 / self.w(s);

        // Center interpolation factor.
        let center_factor = self.u(s);

        // Interpolate zoom via scale.
        let zoom = self.start_zoom + scale.log2();
        camera.set_distance(zoom_to_distance(
            zoom,
            self.fov_y,
            self.viewport_height,
            self.is_perspective,
        ));

        // Interpolate center in projected pixel space, then unproject.
        let pixels_per_meter = 2.0_f64.powf(self.start_zoom) * TILE_PX / WGS84_CIRCUMFERENCE;
        let cx_px = self.from_x + self.delta_x * center_factor;
        let cy_px = self.from_y + self.delta_y * center_factor;
        // Convert from "initial-scale pixels" back to meters, then to the
        // current-scale center (the scale multiplication here accounts for
        // the zoom change and corresponds to MapLibre's
        // `from.add(delta.mult(centerFactor)).mult(scale)` followed by
        // `unprojectFromWorldCoordinates(tr.worldSize, ...)`).
        //
        // In MapLibre, `tr.worldSize` changes with zoom, which is why they
        // multiply by `scale` before unprojecting.  We achieve the same
        // result by converting from initial-scale pixels to meters (dividing
        // by the initial pixels_per_meter) and then letting the projection
        // unproject from meter-space.
        let cx_m = cx_px / pixels_per_meter;
        let cy_m = cy_px / pixels_per_meter;
        let new_center = self.projection.unproject(&WorldCoord::new(cx_m, cy_m, 0.0));
        camera.set_target(new_center);

        // Interpolate bearing (shortest path).
        let bearing = self.start_bearing + (self.end_bearing - self.start_bearing) * k;
        camera.set_yaw(bearing);

        // Interpolate pitch linearly.
        let pitch = self.start_pitch + (self.end_pitch - self.start_pitch) * k;
        camera.set_pitch(pitch);

        false
    }
}

// ---------------------------------------------------------------------------
// Internal ease-to state
// ---------------------------------------------------------------------------

/// Active ease-to animation state.
struct EaseToState {
    start_center: GeoCoord,
    start_zoom: f64,
    start_bearing: f64,
    start_pitch: f64,

    end_center: GeoCoord,
    end_zoom: f64,
    end_bearing: f64,
    end_pitch: f64,

    duration: f64,
    elapsed: f64,
    easing: fn(f64) -> f64,

    is_perspective: bool,
    fov_y: f64,
    viewport_height: u32,
}

impl EaseToState {
    fn new(camera: &Camera, opts: &EaseToOptions) -> Self {
        let is_perspective = camera.mode() == crate::camera::CameraMode::Perspective;
        let start_zoom = distance_to_zoom(
            camera.distance(),
            camera.fov_y(),
            camera.viewport_height(),
            is_perspective,
        );
        let start_bearing = camera.yaw();

        let end_center = opts.center.unwrap_or(*camera.target());
        let wrapped_end_center = GeoCoord::from_lat_lon(
            end_center.lat,
            shortest_lon_target(camera.target().lon, end_center.lon),
        );

        Self {
            start_center: *camera.target(),
            start_zoom,
            start_bearing,
            start_pitch: camera.pitch(),
            end_center: wrapped_end_center,
            end_zoom: opts.zoom.unwrap_or(start_zoom),
            end_bearing: match opts.bearing {
                Some(b) => shortest_bearing_target(start_bearing, b),
                None => start_bearing,
            },
            end_pitch: opts.pitch.unwrap_or(camera.pitch()),
            duration: opts.duration,
            elapsed: 0.0,
            easing: opts.easing.unwrap_or(default_easing),
            is_perspective,
            fov_y: camera.fov_y(),
            viewport_height: camera.viewport_height(),
        }
    }

    fn tick(&mut self, camera: &mut Camera, dt: f64) -> bool {
        self.elapsed += dt;
        let t = (self.elapsed / self.duration.max(1e-9)).clamp(0.0, 1.0);
        let k = (self.easing)(t);
        let done = t >= 1.0;

        if done {
            camera.set_target(self.end_center);
            camera.set_distance(zoom_to_distance(
                self.end_zoom,
                self.fov_y,
                self.viewport_height,
                self.is_perspective,
            ));
            camera.set_yaw(self.end_bearing);
            camera.set_pitch(self.end_pitch);
            return true;
        }

        // Center: lerp in geographic space.
        let lat = self.start_center.lat + (self.end_center.lat - self.start_center.lat) * k;
        let lon = self.start_center.lon + (self.end_center.lon - self.start_center.lon) * k;
        camera.set_target(GeoCoord::from_lat_lon(lat, wrap_lon_180(lon)));

        // Zoom.
        let zoom = self.start_zoom + (self.end_zoom - self.start_zoom) * k;
        camera.set_distance(zoom_to_distance(
            zoom,
            self.fov_y,
            self.viewport_height,
            self.is_perspective,
        ));

        // Bearing (shortest path, already normalized).
        camera.set_yaw(self.start_bearing + (self.end_bearing - self.start_bearing) * k);

        // Pitch.
        camera.set_pitch(self.start_pitch + (self.end_pitch - self.start_pitch) * k);

        false
    }
}

// ---------------------------------------------------------------------------
// CameraAnimator
// ---------------------------------------------------------------------------

/// Drives smooth camera transitions.
///
/// Supports three animation modes that may be active simultaneously:
///
/// 1. **Fly-to / ease-to** -- a coordinated multi-property transition
///    (only one may be active at a time; starting one cancels the other).
/// 2. **Simple targets** -- independent exponential-smoothed zoom / yaw /
///    pitch targets (useful for scroll-zoom, keyboard rotation).
/// 3. **Momentum** -- inertial pan that decays over time.
///
/// Call [`tick`](Self::tick) every frame with the elapsed `dt`.
pub struct CameraAnimator {
    // -- Coordinated flight / ease state --
    fly_to: Option<FlyToState>,
    ease_to: Option<EaseToState>,

    // -- Simple independent targets (legacy) --
    target_distance: Option<f64>,
    target_yaw: Option<f64>,
    target_pitch: Option<f64>,

    // -- Momentum --
    momentum: (f64, f64),

    /// Momentum decay factor per second (0..1, 0 = instant stop).
    pub momentum_decay: f64,
    /// Smoothing factor for simple zoom/rotate targets
    /// (0 = instant, higher = smoother).
    pub smoothing: f64,
}

impl Default for CameraAnimator {
    fn default() -> Self {
        Self {
            fly_to: None,
            ease_to: None,
            target_distance: None,
            target_yaw: None,
            target_pitch: None,
            momentum: (0.0, 0.0),
            momentum_decay: 0.05,
            smoothing: 8.0,
        }
    }
}

impl CameraAnimator {
    /// Create a new camera animator with default settings.
    pub fn new() -> Self {
        Self::default()
    }

    // -- Coordinated animations -------------------------------------------

    /// Start a van Wijk fly-to animation.
    ///
    /// This implements the "optimal path" algorithm from van Wijk & Nuij
    /// (2003), matching MapLibre/Mapbox `flyTo` behavior.  The camera
    /// simultaneously interpolates center, zoom, bearing, and pitch along
    /// a zoom-out-then-zoom-in arc.
    ///
    /// Cancels any active fly-to, ease-to, simple targets, and momentum.
    ///
    /// If the requested transition is degenerate (no change or exceeds
    /// `max_duration`), a `jump_to` is performed instead.
    pub fn start_fly_to(&mut self, camera: &mut Camera, options: &FlyToOptions) {
        self.cancel();

        match FlyToState::new(camera, options) {
            Some(state) => {
                self.fly_to = Some(state);
            }
            None => {
                // Degenerate: apply final state immediately.
                Self::apply_jump(
                    camera,
                    options.center,
                    options.zoom,
                    options.bearing,
                    options.pitch,
                );
            }
        }
    }

    /// Start a simple ease-to animation.
    ///
    /// Linearly interpolates center, zoom, bearing, and pitch over the
    /// specified duration with configurable easing.
    ///
    /// Cancels any active fly-to, ease-to, simple targets, and momentum.
    pub fn start_ease_to(&mut self, camera: &mut Camera, options: &EaseToOptions) {
        self.cancel();

        if options.duration <= 0.0 {
            Self::apply_jump(
                camera,
                options.center,
                options.zoom,
                options.bearing,
                options.pitch,
            );
            return;
        }

        self.ease_to = Some(EaseToState::new(camera, options));
    }

    /// Apply final state immediately (jump_to helper).
    fn apply_jump(
        camera: &mut Camera,
        center: Option<GeoCoord>,
        zoom: Option<f64>,
        bearing: Option<f64>,
        pitch: Option<f64>,
    ) {
        if let Some(c) = center {
            camera.set_target(c);
        }
        if let Some(z) = zoom {
            let is_perspective = camera.mode() == crate::camera::CameraMode::Perspective;
            camera.set_distance(zoom_to_distance(
                z,
                camera.fov_y(),
                camera.viewport_height(),
                is_perspective,
            ));
        }
        if let Some(b) = bearing {
            camera.set_yaw(b);
        }
        if let Some(p) = pitch {
            camera.set_pitch(p);
        }
    }

    // -- Simple independent targets (legacy) ------------------------------

    /// Set a zoom animation target (distance in meters).
    ///
    /// Non-finite or non-positive distances are ignored.
    pub fn animate_zoom(&mut self, target_distance: f64) {
        if target_distance.is_finite() && target_distance > 0.0 {
            self.target_distance = Some(target_distance);
        }
    }

    /// Set rotation animation targets.
    ///
    /// Non-finite angles are ignored independently.
    pub fn animate_rotate(&mut self, target_yaw: f64, target_pitch: f64) {
        if target_yaw.is_finite() {
            self.target_yaw = Some(target_yaw);
        }
        if target_pitch.is_finite() {
            self.target_pitch = Some(target_pitch);
        }
    }

    /// Apply pan momentum in world meters/second.
    ///
    /// Non-finite inputs are ignored.
    pub fn apply_momentum(&mut self, vx: f64, vy: f64) {
        if vx.is_finite() && vy.is_finite() {
            self.momentum = (vx, vy);
        }
    }

    /// Cancel all animations and momentum.
    pub fn cancel(&mut self) {
        self.fly_to = None;
        self.ease_to = None;
        self.target_distance = None;
        self.target_yaw = None;
        self.target_pitch = None;
        self.momentum = (0.0, 0.0);
    }

    /// Whether any animation or momentum is active.
    pub fn is_active(&self) -> bool {
        self.fly_to.is_some()
            || self.ease_to.is_some()
            || self.target_distance.is_some()
            || self.target_yaw.is_some()
            || self.target_pitch.is_some()
            || self.momentum.0.abs() > MOMENTUM_EPS
            || self.momentum.1.abs() > MOMENTUM_EPS
    }

    /// Whether a coordinated fly-to or ease-to animation is active.
    pub fn is_flying(&self) -> bool {
        self.fly_to.is_some()
    }

    /// Whether a coordinated ease-to animation is active.
    pub fn is_easing(&self) -> bool {
        self.ease_to.is_some()
    }

    /// Advance the animation by `dt` seconds, mutating the camera.
    ///
    /// Non-finite or non-positive `dt` values are ignored.
    pub fn tick(&mut self, camera: &mut Camera, dt: f64) {
        if !dt.is_finite() || dt <= 0.0 {
            return;
        }

        // Coordinated fly-to takes priority.
        if let Some(ref mut state) = self.fly_to {
            if state.tick(camera, dt) {
                self.fly_to = None;
            }
            return;
        }

        // Coordinated ease-to.
        if let Some(ref mut state) = self.ease_to {
            if state.tick(camera, dt) {
                self.ease_to = None;
            }
            return;
        }

        // Simple independent targets.
        let smoothing = self.smoothing.max(0.0);
        let t = 1.0 - (-smoothing * dt).exp();

        if let Some(target) = self.target_distance {
            let d = camera.distance() + (target - camera.distance()) * t;
            camera.set_distance(d);
            if (camera.distance() - target).abs() < DISTANCE_EPS {
                camera.set_distance(target);
                self.target_distance = None;
            }
        }

        if let Some(target) = self.target_yaw {
            let delta = shortest_angle_delta(camera.yaw(), target);
            camera.set_yaw(camera.yaw() + delta * t);
            if delta.abs() < ANGLE_EPS {
                camera.set_yaw(target);
                self.target_yaw = None;
            }
        }

        if let Some(target) = self.target_pitch {
            let p = camera.pitch() + (target - camera.pitch()) * t;
            camera.set_pitch(p);
            if (camera.pitch() - target).abs() < ANGLE_EPS {
                camera.set_pitch(target);
                self.target_pitch = None;
            }
        }

        // Pan momentum.
        if self.momentum.0.abs() > MOMENTUM_EPS || self.momentum.1.abs() > MOMENTUM_EPS {
            let dx_deg = self.momentum.0 * dt
                / (METERS_PER_DEGREE * camera.target().lat.to_radians().cos().max(0.001));
            let dy_deg = self.momentum.1 * dt / METERS_PER_DEGREE;

            let mut target = *camera.target();
            target.lon += dx_deg;
            target.lat += dy_deg;

            target.lat = target.lat.clamp(-MERCATOR_MAX_LAT, MERCATOR_MAX_LAT);
            if target.lon > 180.0 {
                target.lon -= 360.0;
            }
            if target.lon < -180.0 {
                target.lon += 360.0;
            }
            camera.set_target(target);

            let decay = self.momentum_decay.clamp(0.0, 1.0).powf(dt);
            self.momentum.0 *= decay;
            self.momentum.1 *= decay;
        }
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Smallest signed angular delta from `from` to `to` in radians.
///
/// Result is in `[-PI, PI]`.
fn shortest_angle_delta(from: f64, to: f64) -> f64 {
    let two_pi = std::f64::consts::TAU;
    let mut d = (to - from) % two_pi;
    if d > std::f64::consts::PI {
        d -= two_pi;
    }
    if d < -std::f64::consts::PI {
        d += two_pi;
    }
    d
}

/// Normalize target bearing so that interpolation takes the shortest path.
///
/// Returns a target value numerically close to `from` that yields the
/// same final bearing modulo 2?.
fn shortest_bearing_target(from: f64, to: f64) -> f64 {
    from + shortest_angle_delta(from, to)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- Legacy simple animation tests ------------------------------------

    #[test]
    fn zoom_converges() {
        let mut cam = Camera::default();
        cam.set_distance(10_000_000.0);
        let mut anim = CameraAnimator::new();
        anim.animate_zoom(1_000_000.0);

        for _ in 0..60 {
            anim.tick(&mut cam, 1.0 / 60.0);
        }
        assert!((cam.distance() - 1_000_000.0).abs() < 100_000.0);

        for _ in 0..240 {
            anim.tick(&mut cam, 1.0 / 60.0);
        }
        assert!((cam.distance() - 1_000_000.0).abs() < 1.0);
        assert!(!anim.is_active());
    }

    #[test]
    fn momentum_decays() {
        let mut cam = Camera::default();
        let mut anim = CameraAnimator::new();
        anim.apply_momentum(100_000.0, 0.0);

        assert!(anim.is_active());

        for _ in 0..600 {
            anim.tick(&mut cam, 1.0 / 60.0);
        }

        assert!(!anim.is_active());
    }

    #[test]
    fn cancel_stops_all() {
        let mut anim = CameraAnimator::new();
        anim.animate_zoom(100.0);
        anim.apply_momentum(10.0, 10.0);
        assert!(anim.is_active());
        anim.cancel();
        assert!(!anim.is_active());
    }

    #[test]
    fn shortest_angle_delta_wraps() {
        let from = std::f64::consts::PI - 0.0174533;
        let to = -std::f64::consts::PI + 0.0174533;
        let d = shortest_angle_delta(from, to);
        assert!(d.abs() < 0.1);
    }

    #[test]
    fn rotate_uses_shortest_path() {
        let mut cam = Camera::default();
        cam.set_yaw(std::f64::consts::PI - 0.01);
        let mut anim = CameraAnimator::new();
        anim.animate_rotate(-std::f64::consts::PI + 0.01, cam.pitch());

        let before = cam.yaw();
        anim.tick(&mut cam, 1.0 / 60.0);
        let moved = (cam.yaw() - before).abs();
        assert!(
            moved < 0.2,
            "yaw moved too far; likely long-path interpolation"
        );
    }

    #[test]
    fn tick_ignores_invalid_dt() {
        let mut cam = Camera::default();
        let mut anim = CameraAnimator::new();
        anim.animate_zoom(1000.0);
        let before = cam.distance();

        anim.tick(&mut cam, f64::NAN);
        assert_eq!(cam.distance(), before);

        anim.tick(&mut cam, 0.0);
        assert_eq!(cam.distance(), before);

        anim.tick(&mut cam, -1.0);
        assert_eq!(cam.distance(), before);
    }

    #[test]
    fn animate_zoom_rejects_invalid_values() {
        let mut anim = CameraAnimator::new();
        anim.animate_zoom(f64::NAN);
        assert!(!anim.is_active());
        anim.animate_zoom(-10.0);
        assert!(!anim.is_active());
        anim.animate_zoom(0.0);
        assert!(!anim.is_active());
    }

    #[test]
    fn animate_rotate_rejects_non_finite_independently() {
        let mut anim = CameraAnimator::new();
        anim.animate_rotate(f64::NAN, 0.1);
        assert!(anim.is_active());
        anim.cancel();

        anim.animate_rotate(0.2, f64::NAN);
        assert!(anim.is_active());
    }

    #[test]
    fn momentum_clamps_and_wraps_geo() {
        let mut cam = Camera::default();
        cam.set_target(GeoCoord::from_lat_lon(85.0, 179.9));
        let mut anim = CameraAnimator::new();
        anim.apply_momentum(100_000.0, 100_000.0);

        anim.tick(&mut cam, 1.0);

        assert!(cam.target().lat <= MERCATOR_MAX_LAT);
        assert!(cam.target().lon >= -180.0 && cam.target().lon <= 180.0);
    }

    #[test]
    fn decay_is_clamped_to_valid_range() {
        let mut cam = Camera::default();
        let mut anim = CameraAnimator::new();
        anim.apply_momentum(100.0, 0.0);
        anim.momentum_decay = 2.0;

        let before = cam.target().lon;
        anim.tick(&mut cam, 1.0);
        let after = cam.target().lon;
        assert!(after != before);
        let after2_before = cam.target().lon;
        anim.tick(&mut cam, 1.0);
        assert!((cam.target().lon - after2_before).abs() < 1.0);
    }

    // -- Fly-to tests -----------------------------------------------------

    #[test]
    fn fly_to_changes_center_and_zoom() {
        let mut cam = Camera::default();
        cam.set_target(GeoCoord::from_lat_lon(0.0, 0.0));
        cam.set_distance(10_000_000.0);
        cam.set_viewport(800, 600);

        let mut anim = CameraAnimator::new();
        anim.start_fly_to(
            &mut cam,
            &FlyToOptions {
                center: Some(GeoCoord::from_lat_lon(48.8566, 2.3522)), // Paris
                zoom: Some(12.0),
                ..Default::default()
            },
        );

        assert!(anim.is_active());
        assert!(anim.is_flying());

        // Run for a long time to ensure completion.
        for _ in 0..6000 {
            anim.tick(&mut cam, 1.0 / 60.0);
        }

        assert!(!anim.is_active());
        assert!(
            (cam.target().lat - 48.8566).abs() < 0.01,
            "lat={}",
            cam.target().lat
        );
        assert!(
            (cam.target().lon - 2.3522).abs() < 0.01,
            "lon={}",
            cam.target().lon
        );
    }

    #[test]
    fn fly_to_animates_bearing_shortest_path() {
        let mut cam = Camera::default();
        cam.set_distance(1_000_000.0);
        cam.set_viewport(800, 600);
        cam.set_yaw(std::f64::consts::PI - 0.1);

        let target_yaw = -std::f64::consts::PI + 0.1;
        let mut anim = CameraAnimator::new();
        anim.start_fly_to(
            &mut cam,
            &FlyToOptions {
                bearing: Some(target_yaw),
                zoom: Some(5.0),
                ..Default::default()
            },
        );

        // The first frame should take the short path (< 0.3 radians of
        // total delta, so any individual step should be small).
        let before = cam.yaw();
        anim.tick(&mut cam, 1.0 / 60.0);
        let step = (cam.yaw() - before).abs();
        assert!(step < 0.5, "yaw step too large: {step}");
    }

    #[test]
    fn fly_to_same_location_different_zoom_works() {
        let mut cam = Camera::default();
        cam.set_distance(10_000_000.0);
        cam.set_viewport(800, 600);
        let start = *cam.target();

        let mut anim = CameraAnimator::new();
        anim.start_fly_to(
            &mut cam,
            &FlyToOptions {
                zoom: Some(14.0),
                ..Default::default()
            },
        );

        assert!(anim.is_active());

        for _ in 0..6000 {
            anim.tick(&mut cam, 1.0 / 60.0);
        }

        assert!(!anim.is_active());
        // Center should not have moved significantly.
        assert!((cam.target().lat - start.lat).abs() < 0.01);
        assert!((cam.target().lon - start.lon).abs() < 0.01);
    }

    #[test]
    fn fly_to_cancel_stops_animation() {
        let mut cam = Camera::default();
        cam.set_distance(10_000_000.0);
        cam.set_viewport(800, 600);

        let mut anim = CameraAnimator::new();
        anim.start_fly_to(
            &mut cam,
            &FlyToOptions {
                center: Some(GeoCoord::from_lat_lon(51.5, -0.12)),
                zoom: Some(10.0),
                ..Default::default()
            },
        );

        anim.tick(&mut cam, 0.1);
        assert!(anim.is_active());
        anim.cancel();
        assert!(!anim.is_active());
    }

    #[test]
    fn fly_to_explicit_duration() {
        let mut cam = Camera::default();
        cam.set_distance(10_000_000.0);
        cam.set_viewport(800, 600);

        let mut anim = CameraAnimator::new();
        anim.start_fly_to(
            &mut cam,
            &FlyToOptions {
                center: Some(GeoCoord::from_lat_lon(35.6762, 139.6503)),
                zoom: Some(10.0),
                duration: Some(2.0),
                ..Default::default()
            },
        );

        // Run for slightly more than 2 seconds to account for floating point.
        for _ in 0..130 {
            anim.tick(&mut cam, 1.0 / 60.0);
        }
        assert!(!anim.is_active());
        assert!((cam.target().lat - 35.6762).abs() < 0.01);
    }

    #[test]
    fn fly_to_max_duration_degrades_to_jump() {
        let mut cam = Camera::default();
        cam.set_distance(10_000_000.0);
        cam.set_viewport(800, 600);

        let mut anim = CameraAnimator::new();
        anim.start_fly_to(
            &mut cam,
            &FlyToOptions {
                center: Some(GeoCoord::from_lat_lon(35.6762, 139.6503)),
                zoom: Some(10.0),
                max_duration: Some(0.001), // Very short max => instant jump.
                ..Default::default()
            },
        );

        // Should have jumped immediately.
        assert!(!anim.is_active());
        assert!((cam.target().lat - 35.6762).abs() < 0.01);
    }

    // -- Ease-to tests ----------------------------------------------------

    #[test]
    fn ease_to_basic() {
        let mut cam = Camera::default();
        cam.set_distance(10_000_000.0);
        cam.set_viewport(800, 600);

        let mut anim = CameraAnimator::new();
        anim.start_ease_to(
            &mut cam,
            &EaseToOptions {
                center: Some(GeoCoord::from_lat_lon(40.7128, -74.0060)),
                zoom: Some(12.0),
                duration: 0.5,
                ..Default::default()
            },
        );

        assert!(anim.is_active());
        assert!(anim.is_easing());

        for _ in 0..60 {
            anim.tick(&mut cam, 1.0 / 60.0);
        }

        assert!(!anim.is_active());
        assert!((cam.target().lat - 40.7128).abs() < 0.01);
    }

    #[test]
    fn ease_to_zero_duration_is_instant() {
        let mut cam = Camera::default();
        cam.set_distance(10_000_000.0);
        cam.set_viewport(800, 600);

        let mut anim = CameraAnimator::new();
        anim.start_ease_to(
            &mut cam,
            &EaseToOptions {
                center: Some(GeoCoord::from_lat_lon(51.5, -0.12)),
                duration: 0.0,
                ..Default::default()
            },
        );

        // Should have jumped immediately.
        assert!(!anim.is_active());
        assert!((cam.target().lat - 51.5).abs() < 0.01);
    }

    // -- Easing function test ---------------------------------------------

    #[test]
    fn default_easing_endpoints() {
        assert!((default_easing(0.0)).abs() < 1e-6);
        assert!((default_easing(1.0) - 1.0).abs() < 1e-6);
    }

    #[test]
    fn default_easing_monotonic() {
        let mut prev = 0.0;
        for i in 1..=100 {
            let t = i as f64 / 100.0;
            let v = default_easing(t);
            assert!(v >= prev - 1e-9, "non-monotonic at t={t}: {v} < {prev}");
            prev = v;
        }
    }

    // -- Van Wijk algorithm correctness -----------------------------------

    #[test]
    fn fly_to_zooms_out_then_in() {
        // The van Wijk algorithm should zoom out during the middle of the
        // flight (lower zoom = higher distance) and then zoom back in.
        let mut cam = Camera::default();
        cam.set_target(GeoCoord::from_lat_lon(0.0, 0.0));
        cam.set_distance(zoom_to_distance(
            5.0,
            cam.fov_y(),
            cam.viewport_height(),
            true,
        ));
        cam.set_viewport(800, 600);

        let start_dist = cam.distance();
        let end_zoom = 5.0; // Same zoom, different center => pure zoom-out arc.

        let mut anim = CameraAnimator::new();
        anim.start_fly_to(
            &mut cam,
            &FlyToOptions {
                center: Some(GeoCoord::from_lat_lon(40.0, 30.0)),
                zoom: Some(end_zoom),
                duration: Some(4.0),
                easing: Some(|t| t), // Linear easing for predictable sampling.
                ..Default::default()
            },
        );

        // Sample distance at mid-flight.  With same start/end zoom and a
        // large center displacement, the camera should be farther away
        // (zoomed out) at the midpoint.
        let mut max_dist: f64 = 0.0;
        for _ in 0..240 {
            anim.tick(&mut cam, 1.0 / 60.0);
            max_dist = max_dist.max(cam.distance());
        }
        // Complete the rest.
        for _ in 0..300 {
            anim.tick(&mut cam, 1.0 / 60.0);
        }

        assert!(
            max_dist > start_dist * 1.5,
            "mid-flight distance ({max_dist:.0}) should be well above start ({start_dist:.0})"
        );
        // Final distance should be back near the start (same zoom).
        let final_dist = cam.distance();
        assert!(
            (final_dist - start_dist).abs() < start_dist * 0.05,
            "final distance ({final_dist:.0}) should be near start ({start_dist:.0})"
        );
    }

    #[test]
    fn fly_to_van_wijk_r_function_matches_maplibre() {
        // Direct unit test of the zoom_out_factor (r) function against
        // known MapLibre values.
        //
        // For w0=800, w1=400 (zoom in by 1 level), u1=1000, rho=1.42:
        //   rho2 = 2.0164
        //   r(0) = ln(sqrt(b0^2+1) - b0)  where b0 = (w1^2-w0^2+rho2^2*u1^2) / (2*w0*rho2*u1)
        //   r(1) = ln(sqrt(b1^2+1) - b1)  where b1 = (w1^2-w0^2-rho2^2*u1^2) / (2*w1*rho2*u1)
        let w0: f64 = 800.0;
        let w1: f64 = 400.0;
        let u1: f64 = 1000.0;
        let rho: f64 = 1.42;
        let rho2 = rho * rho;

        let r = |descent: bool| -> f64 {
            let (w, sign) = if descent { (w1, -1.0) } else { (w0, 1.0) };
            let b = (w1 * w1 - w0 * w0 + sign * rho2 * rho2 * u1 * u1) / (2.0 * w * rho2 * u1);
            ((b * b + 1.0).sqrt() - b).ln()
        };

        let r0 = r(false);
        let r1 = r(true);
        let s = (r1 - r0) / rho;

        assert!(r0.is_finite(), "r0 should be finite");
        assert!(r1.is_finite(), "r1 should be finite");
        assert!(s > 0.0, "path length S should be positive, got {s}");
        assert!(s.is_finite(), "path length S should be finite");

        // Verify that w(0) = cosh(r0)/cosh(r0) = 1.0 (unit visible span at start).
        let w_at_0 = r0.cosh() / (r0 + rho * 0.0).cosh();
        assert!(
            (w_at_0 - 1.0).abs() < 1e-10,
            "w(0) should be 1.0, got {w_at_0}"
        );

        // Verify that w(S) = w1/w0 (MapLibre: scale = 1/w(S), so zoom = startZoom + log2(scale)).
        let w_at_s = r0.cosh() / (r0 + rho * s).cosh();
        let expected_w_at_s = w1 / w0; // 0.5
        assert!(
            (w_at_s - expected_w_at_s).abs() < 0.01,
            "w(S) should be {expected_w_at_s}, got {w_at_s}"
        );
    }

    #[test]
    fn fly_to_degenerate_same_center_uses_w1_not_zoom() {
        // Regression: the degenerate path should compare w0 vs w1 (pixel
        // spans), not w0 vs end_zoom (a zoom level number).
        let mut cam = Camera::default();
        cam.set_target(GeoCoord::from_lat_lon(10.0, 20.0));
        cam.set_distance(zoom_to_distance(
            3.0,
            cam.fov_y(),
            cam.viewport_height(),
            true,
        ));
        cam.set_viewport(800, 600);

        let start_dist = cam.distance();

        let mut anim = CameraAnimator::new();
        anim.start_fly_to(
            &mut cam,
            &FlyToOptions {
                // Same center, different zoom => zoom-only degenerate path.
                zoom: Some(10.0),
                duration: Some(1.0),
                ..Default::default()
            },
        );

        assert!(
            anim.is_active(),
            "animation should be active for zoom-only flight"
        );

        // Run to completion.
        for _ in 0..70 {
            anim.tick(&mut cam, 1.0 / 60.0);
        }

        assert!(!anim.is_active());
        // Should have zoomed in significantly.
        assert!(
            cam.distance() < start_dist * 0.01,
            "should have zoomed in: start={start_dist:.0}, end={:.0}",
            cam.distance()
        );
    }
}