mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
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
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
//! The gesture recognizers for one map, ported from Orbis's orb-camera
//! `input/mod.rs` onto the map's camera calls
//! ([`GestureCamera`]).

use std::time::Duration;

use glam::DVec2;
use mln_style::unitbezier::UnitBezier;

use crate::camera::{
    AnchoredMomentum, AnimationOptions, CameraDelta, CameraMomentum, CameraOptions, CameraUpdate, CameraUpdateMode,
    CameraVelocity, GesturePhase, MomentumGlide, TransitionOutcome,
};
use crate::geo::ScreenCoordinate;
use crate::gestures::camera::{GestureCamera, PendingEnd};
use crate::gestures::input::{DragAction, Fling, GestureEvent, Input, Modes, PointerFlags, PointerKind};
use crate::gestures::notches::NotchWatch;
use crate::gestures::options::{AxisOptions, GestureAnchor, GestureOptions, InvalidGestureOptions};
use crate::gestures::velocity::VelocityTracker;

/// The control points of the recognizer's eases: a curve that starts
/// briskly and settles gently (CSS's `ease`).
const EASE_X1: f64 = 0.25;
const EASE_Y1: f64 = 0.1;
const EASE_X2: f64 = 0.25;
const EASE_Y2: f64 = 1.0;
const EASE: UnitBezier = UnitBezier::new(EASE_X1, EASE_Y1, EASE_X2, EASE_Y2);
/// A pinch whose last finger lifted this long ago still lends its release
/// its motion; until then the remaining finger's motion doesn't count, as it
/// belongs to lifting the other (Compose's `ContactReleaseMillis`).
const STAGED_RELEASE_MS: f64 = 100.0;
/// Two fingers decide they are not tilting once one alone has moved past the
/// pitch slop for this long without the other moving.
const PITCH_DECIDE_MS: f64 = 100.0;
/// How far a retargeted step ease's first control point lies from the
/// curve's origin, along the slope of the speed the ease carries on.
const STEP_EASE_HANDLE: f64 = 0.27;
/// A step ease that has this little left to move has arrived.
const STEP_EASE_DONE: f64 = 1e-9;
/// The parts a delta moves, in [`DeltaGesture::eases`] and the arrays of
/// amounts: pan x and y, zoom, bearing, pitch.
const DELTA_PARTS: usize = 5;
const DELTA_ZOOM: usize = 2;
const DELTA_BEARING: usize = 3;

fn to_vec2(p: ScreenCoordinate) -> DVec2 {
    DVec2::new(p.x, p.y)
}

fn to_screen(v: DVec2) -> ScreenCoordinate {
    ScreenCoordinate::new(v.x, v.y)
}

#[derive(Clone, Copy, Debug)]
struct Pointer {
    id: u32,
    kind: PointerKind,
    position: DVec2,
    down: DVec2,
    down_at: f64,
    drag_action: DragAction,
    flags: PointerFlags,
}

#[derive(Clone, Copy, Debug)]
struct Pinch {
    last: [DVec2; 2],
    start_distance: f64,
    start_vector: DVec2,
    min_diameter: f64,
    /// Whether both pointers opted into pinch/twist/tilt transforms.
    can_transform: bool,
    zooming: bool,
    rotating: bool,
    /// Whether the fingers move up or down together: undecided at first.
    pitch: Option<bool>,
    single_since: Option<f64>,
    panning: bool,
    /// Started within the tap interval and not moved: a two-finger tap so
    /// far.
    tap: bool,
}

#[derive(Clone, Copy, Debug)]
enum Mode {
    Idle,
    /// Pressed and not moved past the slop; held long enough, it is a long
    /// press, which makes no tap.
    Pressed {
        long_pressed: bool,
    },
    /// A pointer with [`DragAction::Defer`] crossed slop and waits for
    /// [`Input::DragDecision`]. Moves are buffered without moving the camera.
    PendingDrag,
    Pan,
    /// Shift-drag: the box from `origin` to the pointer is where the map
    /// zooms on release.
    BoxZoom {
        origin: DVec2,
    },
    /// Single-pointer rotation and tilt.
    Rotate {
        origin: DVec2,
    },
    Pinch(Pinch),
    /// The second press of a double tap, held: dragging zooms, and held
    /// still it can be a long press, which makes no double tap.
    TapDrag {
        origin: DVec2,
        moved: bool,
        long_pressed: bool,
    },
    /// Single pointer moved past slop without an active drag: neither taps nor
    /// drags, but remains eligible to start a two-pointer gesture. When
    /// `staged_release` is true, lifting finishes with the pinch's staged
    /// release instead of dropping it.
    NoDrag {
        staged_release: bool,
    },
    /// Buttons or pointers the map doesn't track for gestures (3+ pointers or
    /// post-cancel pointers).
    Ignored,
}

/// One applied gesture step, for the release velocity.
#[derive(Clone, Copy, Debug, Default)]
struct Step {
    pan: DVec2,
    zoom: f64,
    bearing: f64,
    pitch: f64,
    zoom_around: Option<DVec2>,
    bearing_around: Option<DVec2>,
    pitch_around: Option<DVec2>,
}

/// Per second, at release.
#[derive(Clone, Copy, Debug, Default)]
struct Release {
    pan: Option<DVec2>,
    zoom: Option<f64>,
    bearing: Option<f64>,
    pitch: Option<f64>,
    zoom_anchor: Option<DVec2>,
    bearing_anchor: Option<DVec2>,
    pitch_anchor: Option<DVec2>,
}

/// What a gesture has moved so far, and how fast.
#[derive(Debug, Default)]
struct Tracking {
    /// Totals since the gesture began: pixels, levels, degrees.
    pan: DVec2,
    zoom: f64,
    bearing: f64,
    pitch: f64,
    /// Pan x and y, zoom, bearing, pitch.
    trackers: [VelocityTracker; 5],
    zoom_anchor: Option<DVec2>,
    bearing_anchor: Option<DVec2>,
    pitch_anchor: Option<DVec2>,
    /// A pinch's release, staged when it continued as a one-finger pan,
    /// and when.
    staged: Option<(f64, Release)>,
    /// Motion before this doesn't count toward the release.
    not_before: f64,
}

impl Tracking {
    fn reset(&mut self, now: f64) {
        *self = Self::default();
        self.record(now, Step::default());
    }

    /// Adds a step's samples: to each part it moves, and to each part the
    /// gesture moves already, which stands still otherwise.
    fn record(&mut self, now: f64, step: Step) {
        self.pan += step.pan;
        self.zoom += step.zoom;
        self.bearing += step.bearing;
        self.pitch += step.pitch;
        if step.zoom != 0.0 {
            self.zoom_anchor = step.zoom_around;
        }
        if step.bearing != 0.0 {
            self.bearing_anchor = step.bearing_around;
        }
        if step.pitch != 0.0 {
            self.pitch_anchor = step.pitch_around;
        }
        if now < self.not_before {
            return;
        }
        let values = [self.pan.x, self.pan.y, self.zoom, self.bearing, self.pitch];
        let moved = [
            step.pan != DVec2::ZERO,
            step.pan != DVec2::ZERO,
            step.zoom != 0.0,
            step.bearing != 0.0,
            step.pitch != 0.0,
        ];
        let start = self.trackers.iter().all(VelocityTracker::is_empty);
        for ((tracker, value), moved) in self.trackers.iter_mut().zip(values).zip(moved) {
            if moved || start || !tracker.is_empty() {
                tracker.add(now, value);
            }
        }
    }

    /// The release at `now`.
    fn release(&mut self, now: f64) -> Release {
        let [x, y, zoom, bearing, pitch] = self.trackers.each_ref().map(|t| t.velocity(now));
        // Every velocity that reaches a release is finite and moving.
        let some = |v: f64| (v != 0.0 && v.is_finite()).then_some(v);
        let mut release = Release {
            pan: ((x != 0.0 || y != 0.0) && x.is_finite() && y.is_finite()).then_some(DVec2::new(x, y)),
            zoom: some(zoom),
            bearing: some(bearing),
            pitch: some(pitch),
            zoom_anchor: self.zoom_anchor,
            bearing_anchor: self.bearing_anchor,
            pitch_anchor: self.pitch_anchor,
        };
        // A pinch that ended moments ago keeps what it had, as Compose's
        // contact changes do; a pan carried on longer than the velocity
        // horizon has left it behind.
        if let Some((at, staged)) = self.staged.take()
            && now - at <= STAGED_RELEASE_MS
        {
            if release.pan.is_none() {
                release.pan = staged.pan;
            }
            if release.zoom.is_none() {
                release.zoom = staged.zoom;
                release.zoom_anchor = staged.zoom_anchor;
            }
            if release.bearing.is_none() {
                release.bearing = staged.bearing;
                release.bearing_anchor = staged.bearing_anchor;
            }
            if release.pitch.is_none() {
                release.pitch = staged.pitch;
                release.pitch_anchor = staged.pitch_anchor;
            }
        }
        release
    }

    /// A pinch continues as a one-finger pan: its release so far is kept,
    /// and the next 100 ms of motion, which belongs to lifting the finger,
    /// don't count.
    fn stage(&mut self, now: f64) {
        let release = self.release(now);
        self.staged = Some((now, release));
        for tracker in &mut self.trackers {
            tracker.reset();
        }
        self.not_before = now + STAGED_RELEASE_MS;
    }
}

impl Release {
    /// The momentum this release continues with: glides from its velocities
    /// by the options' decays, and the options' snaps, which the camera
    /// applies only to the parts the gesture changed. A part without a decay
    /// or with its axis disabled doesn't glide. A glide that the gesture's
    /// press caught adds to each part that releases its way and clears its
    /// minimum speed, as Compose's `resolveGestureMomentum` adds it; the
    /// decay's maximum speed still caps the sum.
    fn into_momentum(self, caught_glide: Option<CameraVelocity>, options: &GestureOptions) -> CameraMomentum {
        let caught = caught_glide.unwrap_or_default();
        let pan = options.axes.pan.enabled.then_some(options.axes.pan.momentum).flatten().and_then(|decay| {
            let velocity = self.pan.filter(|v| v.length() >= decay.min_speed)?;
            let caught = to_vec2(caught.pan);
            let velocity = if velocity.dot(caught) > 0.0 { velocity + caught } else { velocity };
            Some(MomentumGlide { velocity: to_screen(velocity), decay })
        });
        let scalar = |part: &AxisOptions, release: Option<f64>, anchor: Option<DVec2>, caught: f64| AnchoredMomentum {
            glide: part.enabled.then_some(part.momentum).flatten().and_then(|decay| {
                let velocity = release.filter(|v| v.abs() >= decay.min_speed)?;
                let velocity =
                    if caught != 0.0 && caught.signum() == velocity.signum() { velocity + caught } else { velocity };
                Some(MomentumGlide { velocity, decay })
            }),
            anchor: anchor.map(to_screen),
            snap: part.enabled.then_some(part.snap).flatten(),
        };
        CameraMomentum {
            pan,
            zoom: scalar(&options.axes.zoom, self.zoom, self.zoom_anchor, caught.zoom),
            bearing: scalar(&options.axes.bearing, self.bearing, self.bearing_anchor, caught.bearing),
            pitch: scalar(&options.axes.pitch, self.pitch, self.pitch_anchor, caught.pitch),
        }
    }
}

/// Deltas under way: one gesture from the first until they idle.
#[derive(Clone, Copy, Debug)]
struct DeltaGesture {
    /// The gesture ends after this: a while after its last delta and after
    /// its last ease (`deltas.idle`).
    idle_until: f64,
    /// The eases of discrete deltas, per part ([`DELTA_PARTS`]).
    eases: [Option<StepEase>; DELTA_PARTS],
}

/// The eased change of a run of discrete deltas to one part.
#[derive(Clone, Copy, Debug)]
struct StepEase {
    start: f64,
    /// How far to move from the ease's start, and how far it has moved.
    distance: f64,
    applied: f64,
    /// Where this eased part is anchored (`None` = padded camera center).
    anchor: Option<DVec2>,
    /// The first control point of its curve; the second is [`EASE`]'s.
    x1: f64,
    y1: f64,
}

impl StepEase {
    /// An ease that moves `step` more than what `ease`, if any, hasn't moved
    /// yet, within `limit`. One still running retargets at its current speed,
    /// so a quick run speeds up without a stutter: the new curve starts at
    /// the old one's speed, in units per second.
    fn retarget(
        ease: Option<StepEase>,
        step: f64,
        anchor: Option<DVec2>,
        now: f64,
        duration: f64,
        limit: impl Fn(f64) -> f64,
    ) -> StepEase {
        let (distance, (x1, y1)) = match ease {
            Some(ease) if ease.progress(now, duration) < 1.0 => {
                // Whatever the ease hasn't applied yet carries over.
                let distance = limit(ease.distance - ease.applied + step);
                // The new curve's starting slope, dy/dx = y1/x1, times
                // distance / duration is the current speed; its first control
                // point stays STEP_EASE_HANDLE from the origin.
                let slope = if distance == 0.0 { 0.0 } else { ease.speed(now, duration) * duration / distance };
                let x1 = STEP_EASE_HANDLE / (1.0 + slope * slope).sqrt();
                (distance, (x1, slope * x1))
            }
            Some(ease) => (limit(ease.distance - ease.applied + step), (EASE_X1, EASE_Y1)),
            None => (limit(step), (EASE_X1, EASE_Y1)),
        };
        StepEase { start: now, distance, applied: 0.0, anchor, x1, y1 }
    }

    fn curve(&self) -> UnitBezier {
        UnitBezier::new(self.x1, self.y1, EASE_X2, EASE_Y2)
    }

    /// The share of the ease's time elapsed at `now`.
    fn progress(&self, now: f64, duration: f64) -> f64 {
        ((now - self.start) / duration).clamp(0.0, 1.0)
    }

    /// How far it has moved by `now`.
    fn value(&self, now: f64, duration: f64) -> f64 {
        let t = self.progress(now, duration);
        self.distance * if t >= 1.0 { 1.0 } else { self.curve().solve(t, 1e-6) }
    }

    /// Units per millisecond at `now`.
    fn speed(&self, now: f64, duration: f64) -> f64 {
        let dt = 1.0;
        (self.value(now + dt, duration) - self.value(now, duration)) / dt
    }
}

/// When a recognizer next needs [`GestureRecognizer::tick`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum NextTick {
    /// Every display frame, while a delta eases or a gesture may reach a
    /// notch.
    Frame,
    /// At this time, on the inputs' clock: when a press becomes a long press,
    /// or idle deltas end.
    At(f64),
}

/// How a gesture finishes once its last pointer lifts.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Finish {
    /// The platform took it away: nothing continues, and the camera's
    /// animations stop (the `Cancel` phase).
    Cancel,
    /// Ended without a release to continue: a box, input the map ignores.
    Stop,
    /// Released without a fling (a tap): only the snaps of what it changed.
    Settle,
    /// Released: it glides on, and settles.
    Glide,
}

/// Recognizes gestures for one map and continues their releases with the
/// map's momentum.
///
/// - Drag to pan, or with a pointer's [`DragAction`] or held [`Modes`], rotate
///   and tilt or zoom to a box.
/// - Two-finger pinch, twist and vertical tilt.
/// - Double-tap-and-drag to zoom.
/// - Deltas from wheels, trackpads, dials, keys, and the pinches and pans the
///   platform recognized ([`Input::Delta`]), which glide on when the platform
///   ends them ([`Input::DeltaEnd`]).
/// - Taps, double taps and two-finger taps, which it reports for the host to
///   answer.
///
/// Every change goes through the map's camera calls with its gesture phase,
/// so the camera reports it as a gesture: a press begins a gesture, each move
/// updates it, and the release ends it with momentum (the average velocity of
/// its last 100 ms, glided by the options' decays), during which the gesture
/// stays in progress.
///
/// Hosts feed it [`Input`]s with their timestamps, in milliseconds on any
/// clock that only goes forward, and call [`tick`](Self::tick) when it asks.
/// A completed tap waiting either to pair with a second tap or to confirm as
/// a [`GestureEvent::SingleTap`].
#[derive(Clone, Copy, Debug)]
struct PendingTap {
    id: u32,
    position: DVec2,
    at: f64,
    kind: PointerKind,
    /// Host time at which this tap confirms as a [`GestureEvent::SingleTap`];
    /// `None` once a candidate second press has cancelled confirmation.
    confirm_at: Option<f64>,
}

/// Maximum buffered moves kept while [`Mode::PendingDrag`] waits for a host
/// decision, bounding memory if a host never responds.
const MAX_PENDING_MOVES: usize = 256;

/// Every move goes through the `GestureCamera`.
#[derive(Debug)]
pub struct GestureRecognizer<C> {
    /// The map's camera, which every move goes through.
    camera: C,
    options: GestureOptions,
    pointers: Vec<Pointer>,
    mode: Mode,
    tracking: Tracking,
    /// Whether the recognizer's gesture has begun in the camera and not
    /// ended: a pointer gesture, a scroll, or both.
    begun: bool,
    /// The end of the recognizer's last release, whose glide a press may
    /// stop.
    release_end: Option<PendingEnd>,
    /// The end of the glide that this gesture's press stopped, whose speed
    /// its release carries (`carry_caught_glide`) if the press cancelled it.
    caught_glide: Option<PendingEnd>,
    /// The last tap, for double-tap pairing and single-tap confirmation.
    last_tap: Option<PendingTap>,
    /// The modes that held keys select.
    modes: Modes,
    deltas: Option<DeltaGesture>,
    /// The notches of the gesture under way, until it, its glide and its
    /// snap end.
    notch_watch: Option<NotchWatch>,
    /// `(timestamp, position)` samples buffered while [`Mode::PendingDrag`]
    /// waits for [`Input::DragDecision`], starting with `(down_at, down)`.
    pending_moves: Vec<(f64, DVec2)>,
    events: Vec<GestureEvent>,
}

impl<C: GestureCamera> GestureRecognizer<C> {
    /// A recognizer that moves `camera`, with the default options.
    pub fn new(camera: C) -> Self {
        GestureRecognizer::with(camera, GestureOptions::default())
    }

    /// A recognizer that moves `camera`, with `options`, which must be in
    /// range.
    pub fn with_options(camera: C, options: GestureOptions) -> Result<Self, InvalidGestureOptions> {
        options.validate()?;
        Ok(GestureRecognizer::with(camera, options))
    }

    fn with(camera: C, options: GestureOptions) -> Self {
        GestureRecognizer {
            camera,
            options,
            pointers: Vec::new(),
            mode: Mode::Idle,
            tracking: Tracking::default(),
            begun: false,
            release_end: None,
            caught_glide: None,
            last_tap: None,
            modes: Modes::default(),
            deltas: None,
            notch_watch: None,
            pending_moves: Vec::new(),
            events: Vec::new(),
        }
    }

    #[must_use]
    pub fn options(&self) -> &GestureOptions {
        &self.options
    }

    /// Takes effect with the next input (and for gesture recognition, the next
    /// gesture), if the options are in range.
    pub fn set_options(&mut self, options: GestureOptions) -> Result<(), InvalidGestureOptions> {
        options.validate()?;
        self.options = options;
        Ok(())
    }

    /// A gesture is under way: hosts keep pointer capture and scrolling off.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn is_active(&self) -> bool {
        !matches!(self.mode, Mode::Idle) || self.deltas.is_some()
    }

    /// The box a box-zoom drag zooms to, corner to corner in logical pixels,
    /// while it is drawn: hosts show it.
    #[must_use]
    pub fn box_zoom(&self) -> Option<[ScreenCoordinate; 2]> {
        if !(self.options.gestures.box_zoom.enabled && self.options.axes.zoom.enabled) {
            return None;
        }
        match self.mode {
            Mode::BoxZoom { origin } => Some([to_screen(origin), to_screen(self.pointers.first()?.position)]),
            _ => None,
        }
    }

    fn slop(&self, kind: PointerKind) -> f64 {
        match kind {
            PointerKind::Touch => self.options.metrics.touch_slop,
            PointerKind::Mouse | PointerKind::Pen => self.options.metrics.pointer_slop,
        }
    }

    fn double_tap_interval_ms(&self) -> f64 {
        self.options.metrics.double_tap_interval.as_secs_f64() * 1000.0
    }

    fn long_press_ms(&self) -> f64 {
        self.options.metrics.long_press.as_secs_f64() * 1000.0
    }

    fn step_duration_ms(&self) -> f64 {
        self.options.gestures.deltas.step_duration.as_secs_f64() * 1000.0
    }

    fn delta_idle_ms(&self) -> f64 {
        self.options.gestures.deltas.idle.as_secs_f64() * 1000.0
    }

    fn resolve_anchor(anchor: GestureAnchor, focal: DVec2) -> Option<DVec2> {
        match anchor {
            GestureAnchor::FocalPoint => Some(focal),
            GestureAnchor::CameraCenter => None,
        }
    }

    /// When the recognizer next needs [`tick`](Self::tick): every display
    /// frame while a delta eases or a gesture, its glide and its snap may
    /// reach a notch; at a time for a pending long press, a pending single-tap
    /// confirmation, or the end of idle deltas; or `None`.
    #[must_use]
    pub fn next_tick(&self) -> Option<NextTick> {
        let easing = self.deltas.is_some_and(|deltas| deltas.eases.iter().any(Option::is_some));
        // A pointer held still moves nothing that could reach a notch.
        let held_still =
            matches!(self.mode, Mode::Pressed { .. } | Mode::PendingDrag | Mode::TapDrag { moved: false, .. });
        if easing || (self.notch_watch.is_some() && !held_still) {
            return Some(NextTick::Frame);
        }
        let long_press = match self.pointers[..] {
            [pointer] if self.awaits_long_press() => Some(pointer.down_at + self.long_press_ms()),
            _ => None,
        };
        let single_tap = self.last_tap.and_then(|tap| tap.confirm_at);
        let idle = self.deltas.map(|deltas| deltas.idle_until);
        long_press.into_iter().chain(single_tap).chain(idle).min_by(f64::total_cmp).map(NextTick::At)
    }

    /// Whether a press held still may yet become a long press.
    fn awaits_long_press(&self) -> bool {
        matches!(
            self.mode,
            Mode::Pressed { long_pressed: false } | Mode::TapDrag { moved: false, long_pressed: false, .. }
        )
    }

    /// Taps, long presses and notches recognized since the last call.
    pub fn take_events(&mut self) -> Vec<GestureEvent> {
        std::mem::take(&mut self.events)
    }

    /// A host's own command to an absolute camera, such as resetting the
    /// bearing, through the recognizer: it stops the recognizer's eases of the
    /// parts it sets, which would otherwise take them back, and is an update
    /// of a gesture under way or a gesture of its own. `update.phase` is
    /// ignored.
    pub fn step_to(&mut self, update: &CameraUpdate) {
        let set = &update.camera;
        let center = set.center.is_some();
        self.stop_step_eases([center, center, set.zoom.is_some(), set.bearing.is_some(), set.pitch.is_some()]);
        // Outside a gesture it takes over from the last gesture's glide,
        // whose notches end: host commands report none.
        if !self.begun {
            self.notch_watch = None;
        }
        let phase = if self.begun { GesturePhase::Update } else { GesturePhase::End };
        self.camera.update_camera(&CameraUpdate { phase, ..*update });
    }

    /// Times long presses and single-tap confirmations, steps the eases of
    /// discrete deltas, ends deltas once they idle, and samples the camera for
    /// notches, at `now` on the inputs' clock. Call it when
    /// [`next_tick`](Self::next_tick) says, which it also returns; a call at
    /// any other time does no harm.
    pub fn tick(&mut self, now: f64) -> Option<NextTick> {
        self.confirm_single_tap(now);
        self.long_press(now);
        self.delta_frame(now);
        if let Some(watch) = &mut self.notch_watch {
            watch.sample(&self.camera.camera(), &self.options, now, &mut self.events);
            // The gesture ended, and so did its glide and snap: its command
            // has ended (a gesture cancelled outright has none).
            if !self.begun && self.release_end.as_ref().is_none_or(PendingEnd::has_ended) {
                self.notch_watch = None;
            }
        }
        self.next_tick()
    }

    /// Reports a pending tap as a [`GestureEvent::SingleTap`] once its
    /// double-tap window has elapsed.
    fn confirm_single_tap(&mut self, now: f64) {
        if let Some(tap) = self.last_tap
            && tap.confirm_at.is_some_and(|at| now >= at)
        {
            self.last_tap = None;
            self.events.push(GestureEvent::SingleTap { id: tap.id, position: to_screen(tap.position) });
        }
    }

    /// Reports a press held still for the long-press time, once.
    fn long_press(&mut self, now: f64) {
        if self.awaits_long_press()
            && let [pointer] = self.pointers[..]
            && now - pointer.down_at >= self.long_press_ms()
        {
            match &mut self.mode {
                Mode::Pressed { long_pressed } | Mode::TapDrag { long_pressed, .. } => *long_pressed = true,
                _ => {}
            }
            self.last_tap = None;
            self.events.push(GestureEvent::LongPress { id: pointer.id, position: to_screen(pointer.position) });
        }
    }

    /// The deltas' part of [`Self::tick`].
    fn delta_frame(&mut self, now: f64) -> bool {
        let Some(mut gesture) = self.deltas else {
            return false;
        };
        let duration = self.step_duration_ms();
        let max_zoom = self.options.gestures.deltas.max_step_zoom;
        let idle_ms = self.delta_idle_ms();
        let axes = &self.options.axes;
        let on = [axes.pan.enabled, axes.pan.enabled, axes.zoom.enabled, axes.bearing.enabled, axes.pitch.enabled];
        let mut pending: [(f64, Option<DVec2>); DELTA_PARTS] = [(0.0, None); DELTA_PARTS];
        for ((part, slot), enabled) in gesture.eases.iter_mut().enumerate().zip(on) {
            let Some(mut ease) = *slot else { continue };
            if !enabled {
                *slot = None;
                continue;
            }
            let mut amount = if duration > 0.0 { ease.value(now, duration) } else { ease.distance } - ease.applied;
            if part == DELTA_ZOOM && duration > 0.0 {
                amount = amount.clamp(-max_zoom, max_zoom);
            }
            ease.applied += amount;
            pending[part] = (amount, ease.anchor);
            let done = (duration == 0.0 || ease.progress(now, duration) >= 1.0)
                && (ease.distance - ease.applied).abs() <= STEP_EASE_DONE;
            *slot = (!done).then_some(ease);
            if done {
                gesture.idle_until = gesture.idle_until.max(now + idle_ms);
            }
        }
        // Eases that outlive the pointer gesture they joined carry on as a
        // gesture of their own, which keeps the release's glide.
        if !self.begun && pending.iter().any(|(amount, _)| *amount != 0.0) {
            self.begun = true;
            self.tracking.reset(now);
            self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..CameraDelta::default() });
        }
        // Apply each eased part at its own anchor, coalescing parts that share
        // the same anchor into one delta.
        for i in 0..DELTA_PARTS {
            let (amount, anchor) = pending[i];
            if amount == 0.0 {
                continue;
            }
            let mut group = [0.0; DELTA_PARTS];
            for j in i..DELTA_PARTS {
                if pending[j].0 != 0.0 && pending[j].1 == anchor {
                    group[j] = pending[j].0;
                    pending[j].0 = 0.0;
                }
            }
            self.move_by(group, anchor);
        }
        if gesture.eases.iter().all(Option::is_none) && now >= gesture.idle_until {
            self.deltas = None;
            if matches!(self.mode, Mode::Idle) {
                self.end_phase(None);
            }
            return false;
        }
        self.deltas = Some(gesture);
        true
    }

    /// Handles one input at host time `now`, in milliseconds. Returns whether
    /// the map used it, so hosts can stop the platform's default.
    pub fn handle(&mut self, input: Input, now: f64) -> bool {
        match input {
            Input::PointerDown { id, kind, position, drag_action, flags } => {
                let position = to_vec2(position);
                self.down(Pointer { id, kind, position, down: position, down_at: now, drag_action, flags })
            }
            Input::PointerMove { id, position } => self.moved(id, to_vec2(position), now),
            Input::PointerUp { id, position } => self.up(id, Some(to_vec2(position)), now),
            Input::PointerCancel { id } => self.up(id, None, now),
            // Modes only change what later drags do: the platform's default
            // for the keys stands.
            Input::Modes(modes) => {
                self.modes = modes;
                false
            }
            Input::Delta { anchor, discrete, pan, zoom, bearing, pitch } => {
                self.delta(anchor.map(to_vec2), discrete, [pan.x, pan.y, zoom, bearing, pitch], now)
            }
            Input::DeltaEnd { fling } => self.delta_end(fling, now),
            Input::DeltaCancel => self.delta_cancel(now),
            Input::DragDecision { id, drag_action } => self.drag_decision(id, drag_action),
        }
    }

    /// The animation options of the recognizer's eased steps.
    fn animation(&self, duration: Duration, easing: UnitBezier) -> AnimationOptions {
        AnimationOptions {
            duration: Some(duration),
            easing: Some(easing),
            transition_id: Some(self.options.transition_id),
            ..AnimationOptions::default()
        }
    }

    /// Begins the gesture, unless it has begun: the `Begin` phase stops the
    /// camera's animations, so that the map holds still under a press.
    /// Without `interrupt_animations`, it stops only the recognizer's
    /// own, and begins with `Update`, which keeps the others. A glide that
    /// this stops is caught: the release may carry its speed, which the
    /// glide's end reports.
    fn begin(&mut self) {
        if self.begun {
            return;
        }
        self.begun = true;
        // Only a glide still running can be caught: one that has ended, as
        // when a command cancelled it, carries nothing.
        self.caught_glide = self.release_end.take().filter(|end| end.take().is_none());
        let notches = [&self.options.axes.zoom, &self.options.axes.bearing, &self.options.axes.pitch]
            .iter()
            .any(|part| part.enabled && !part.notches.is_empty());
        self.notch_watch = notches.then(|| NotchWatch::new(&self.camera.camera(), &self.options));
        let phase = if self.options.interrupt_animations {
            GesturePhase::Begin
        } else {
            self.camera.cancel_transitions_with_id(self.options.transition_id);
            GesturePhase::Update
        };
        self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
    }

    /// One step of the gesture, at once.
    fn update(&mut self, delta: &CameraDelta) {
        self.begin();
        self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..*delta });
    }

    /// Ends the gesture, with the momentum it continues with: the gesture
    /// stays in progress until the momentum ends.
    fn end_phase(&mut self, momentum: Option<&CameraMomentum>) {
        if !std::mem::replace(&mut self.begun, false) {
            return;
        }
        let animation =
            AnimationOptions { transition_id: Some(self.options.transition_id), ..AnimationOptions::default() };
        let phase = GesturePhase::End;
        let delta = CameraDelta { momentum: momentum.copied(), animation, phase, ..CameraDelta::default() };
        let end = self.camera.release(&delta);
        // The end of a release that may glide, which a press may catch; a
        // gesture that ends without momentum leaves the last one's.
        if momentum.is_some() {
            self.release_end = Some(end);
        }
    }

    /// The platform cancelled the gesture: it ends, and the `Cancel` phase
    /// stops the camera's animations (only the recognizer's own, without
    /// `interrupt_animations`).
    fn cancel_phase(&mut self) {
        self.notch_watch = None;
        if !std::mem::replace(&mut self.begun, false) {
            return;
        }
        let phase = if self.options.interrupt_animations {
            GesturePhase::Cancel
        } else {
            self.camera.cancel_transitions_with_id(self.options.transition_id);
            GesturePhase::End
        };
        self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
    }

    /// Stops the step eases of the parts in `parts` ([`DELTA_PARTS`]).
    fn stop_step_eases(&mut self, parts: [bool; DELTA_PARTS]) {
        if let Some(gesture) = self.deltas.as_mut() {
            for (ease, stop) in gesture.eases.iter_mut().zip(parts) {
                if stop {
                    *ease = None;
                }
            }
        }
    }

    /// Whether the remaining single pointer can pan.
    fn can_pan_drag(&self, pointer: Pointer) -> bool {
        pointer.drag_action == DragAction::Pan && self.options.gestures.drag.pan && self.options.axes.pan.enabled
    }

    /// Resolves `drag_action` for a single pointer whose press started at
    /// `down`.
    fn resolve_drag_mode(&self, drag_action: DragAction, down: DVec2) -> Mode {
        let box_zoom_allowed = self.options.gestures.box_zoom.enabled && self.options.axes.zoom.enabled;
        match drag_action {
            DragAction::None => Mode::NoDrag { staged_release: false },
            DragAction::Defer => Mode::PendingDrag,
            DragAction::Rotate => Mode::Rotate { origin: down },
            DragAction::BoxZoom => {
                if box_zoom_allowed {
                    Mode::BoxZoom { origin: down }
                } else {
                    Mode::NoDrag { staged_release: false }
                }
            }
            DragAction::Pan => {
                if self.modes.rotate {
                    Mode::Rotate { origin: down }
                } else if self.modes.box_zoom {
                    if box_zoom_allowed {
                        Mode::BoxZoom { origin: down }
                    } else {
                        Mode::NoDrag { staged_release: false }
                    }
                } else if self.options.gestures.drag.pan && self.options.axes.pan.enabled {
                    Mode::Pan
                } else {
                    Mode::NoDrag { staged_release: false }
                }
            }
        }
    }

    /// Applies the host's decision for a [`DragAction::Defer`] pointer, either
    /// before it crosses slop or while it waits in [`Mode::PendingDrag`].
    fn drag_decision(&mut self, id: u32, drag_action: DragAction) -> bool {
        if drag_action == DragAction::Defer {
            return false;
        }
        let [pointer] = self.pointers.as_mut_slice() else {
            return false;
        };
        if pointer.id != id || pointer.drag_action != DragAction::Defer {
            return false;
        }
        match self.mode {
            Mode::Pressed { .. } => {
                pointer.drag_action = drag_action;
                true
            }
            Mode::PendingDrag => {
                let (down, position) = (pointer.down, pointer.position);
                pointer.drag_action = drag_action;
                let moves = std::mem::take(&mut self.pending_moves);
                self.mode = self.resolve_drag_mode(drag_action, down);
                if matches!(self.mode, Mode::Pan | Mode::Rotate { .. }) {
                    if position != down
                        && let Some((camera, _)) = self.drag_motion(down, position)
                    {
                        self.update(&camera);
                    }
                    if let Some(&(first_at, mut prev)) = moves.first() {
                        self.tracking.reset(first_at);
                        for &(at, pos) in &moves[1..] {
                            if let Some((_, step)) = self.drag_motion(prev, pos) {
                                self.tracking.record(at, step);
                            }
                            prev = pos;
                        }
                    }
                }
                true
            }
            _ => false,
        }
    }

    /// A press of `pointer`, at its position and at its `down_at` time.
    fn down(&mut self, pointer: Pointer) -> bool {
        let Pointer { id, kind, position, down_at: now, .. } = pointer;
        if self.pointers.iter().any(|p| p.id == id) {
            return false;
        }
        let touch = kind == PointerKind::Touch;
        if !touch && !self.pointers.is_empty() {
            return false;
        }
        self.pointers.push(pointer);
        // A press takes over from deltas, and stops their easing.
        self.deltas = None;
        self.begin();
        self.confirm_single_tap(now);
        match (self.mode, self.pointers.len()) {
            (Mode::Idle, 1) => {
                let follows = self.follows_tap(kind, position, now);
                if follows {
                    if let Some(tap) = &mut self.last_tap {
                        tap.confirm_at = None;
                    }
                } else if let Some(tap) = self.last_tap.take()
                    && tap.confirm_at.is_some()
                {
                    self.events.push(GestureEvent::SingleTap { id: tap.id, position: to_screen(tap.position) });
                }
                let can_tap_drag = self.options.gestures.tap_drag.enabled
                    && self.options.axes.zoom.enabled
                    && pointer.flags.allow_tap_drag
                    && follows;
                self.mode = if can_tap_drag {
                    Mode::TapDrag { origin: position, moved: false, long_pressed: false }
                } else {
                    Mode::Pressed { long_pressed: false }
                };
                self.tracking.reset(now);
            }
            (
                Mode::Pressed { .. }
                | Mode::PendingDrag
                | Mode::Pan
                | Mode::TapDrag { .. }
                | Mode::NoDrag { .. }
                | Mode::Rotate { .. }
                | Mode::BoxZoom { .. },
                2,
            ) if touch
                && (!matches!(self.mode, Mode::Rotate { .. } | Mode::BoxZoom { .. })
                    || (self.pointers[0].flags.allow_pinch && self.pointers[1].flags.allow_pinch)) =>
            {
                self.last_tap = None;
                self.pending_moves.clear();
                let [a, b] = [self.pointers[0].position, self.pointers[1].position];
                let vector = b - a;
                let can_transform = self.pointers[0].flags.allow_pinch && self.pointers[1].flags.allow_pinch;
                let pitch_enabled =
                    can_transform && self.options.axes.pitch.enabled && self.options.gestures.pinch.pitch;
                self.mode = Mode::Pinch(Pinch {
                    last: [a, b],
                    start_distance: vector.length(),
                    start_vector: vector,
                    min_diameter: vector.length(),
                    can_transform,
                    zooming: false,
                    rotating: false,
                    // Fingers above one another can't tilt.
                    pitch: (!pitch_enabled || vector.y.abs() > vector.x.abs()).then_some(false),
                    single_since: None,
                    panning: false,
                    tap: now - self.pointers[0].down_at < self.double_tap_interval_ms()
                        && matches!(self.mode, Mode::Pressed { .. }),
                });
                self.tracking.record(now, Step::default());
            }
            _ => {
                self.pending_moves.clear();
                self.mode = Mode::Ignored;
            }
        }
        true
    }

    fn moved(&mut self, id: u32, position: DVec2, now: f64) -> bool {
        let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
            return false;
        };
        let last = self.pointers[index].position;
        let kind = self.pointers[index].kind;
        let slop = self.slop(kind);
        self.pointers[index].position = position;
        match &mut self.mode {
            Mode::Pressed { .. } => {
                let pointer = self.pointers[index];
                let down = pointer.down;
                if position.distance(down) > slop {
                    self.last_tap = None;
                    self.mode = self.resolve_drag_mode(pointer.drag_action, down);
                    match self.mode {
                        Mode::PendingDrag => {
                            self.pending_moves.clear();
                            self.pending_moves.push((pointer.down_at, down));
                            self.pending_moves.push((now, position));
                            self.events.push(GestureEvent::DragPending {
                                id: pointer.id,
                                origin: to_screen(down),
                                position: to_screen(position),
                            });
                        }
                        Mode::Pan | Mode::Rotate { .. } => {
                            // The jump past the slop counts toward the release: it
                            // is motion over the time since the press.
                            self.drag_step(down, position, now);
                        }
                        _ => {}
                    }
                }
            }
            Mode::PendingDrag => {
                if self.pending_moves.len() >= MAX_PENDING_MOVES {
                    self.pending_moves.drain(..MAX_PENDING_MOVES / 2);
                }
                self.pending_moves.push((now, position));
            }
            Mode::Pan | Mode::Rotate { .. } => self.drag_step(last, position, now),
            Mode::TapDrag { origin, moved, .. } => {
                let (origin, dy) = (*origin, position.y - last.y);
                *moved = *moved || position.distance(origin) > slop;
                if *moved && self.options.axes.zoom.enabled && self.options.gestures.tap_drag.enabled {
                    let zoom = dy * self.options.gestures.tap_drag.zoom_per_px;
                    let around = Self::resolve_anchor(self.options.gestures.tap_drag.anchor, origin);
                    let delta = CameraDelta {
                        scale: Some(zoom.exp2()),
                        anchor: around.map(to_screen),
                        ..CameraDelta::default()
                    };
                    self.update(&delta);
                    self.tracking.record(now, Step { zoom, zoom_around: around, ..Step::default() });
                }
            }
            Mode::Pinch(_) if self.pointers.len() < 2 => {
                // The other finger of a two-finger tap lifted, and this one
                // moves on: a pan if allowed.
                if self.can_pan_drag(self.pointers[0]) {
                    self.mode = Mode::Pan;
                    self.drag_step(last, position, now);
                } else {
                    self.mode = Mode::NoDrag { staged_release: false };
                }
            }
            Mode::Pinch(pinch) => {
                if index > 1 {
                    return true;
                }
                let mut pinch = *pinch;
                let points = [self.pointers[0].position, self.pointers[1].position];
                self.pinch_step(&mut pinch, points, now);
                self.mode = Mode::Pinch(pinch);
            }
            Mode::BoxZoom { .. } | Mode::NoDrag { .. } | Mode::Idle | Mode::Ignored => {}
        }
        true
    }

    /// One pan or single-pointer rotate/tilt step from `from` to `to`.
    fn drag_step(&mut self, from: DVec2, to: DVec2, now: f64) {
        if let Some((camera, step)) = self.drag_motion(from, to) {
            self.update(&camera);
            self.tracking.record(now, step);
        }
    }

    /// Computes the camera delta and velocity step for one pan or rotate drag
    /// move from `from` to `to`.
    fn drag_motion(&self, from: DVec2, to: DVec2) -> Option<(CameraDelta, Step)> {
        let delta = to - from;
        match self.mode {
            Mode::Rotate { origin } => {
                let bearing = if self.options.axes.bearing.enabled {
                    delta.x * self.options.gestures.drag.rotate_bearing_per_px
                } else {
                    0.0
                };
                let pitch = if self.options.axes.pitch.enabled {
                    delta.y * self.options.gestures.drag.rotate_pitch_per_px
                } else {
                    0.0
                };
                if bearing == 0.0 && pitch == 0.0 {
                    return None;
                }
                let around = Self::resolve_anchor(self.options.gestures.drag.rotate_anchor, origin);
                let camera = CameraDelta {
                    bearing: (bearing != 0.0).then_some(bearing),
                    pitch: (pitch != 0.0).then_some(pitch),
                    anchor: around.map(to_screen),
                    ..CameraDelta::default()
                };
                let step = Step { bearing, pitch, bearing_around: around, pitch_around: around, ..Step::default() };
                Some((camera, step))
            }
            Mode::Pan if self.options.axes.pan.enabled && self.options.gestures.drag.pan => {
                // The pointer is the point the drag holds, which the globe
                // turns to keep under it.
                let camera = CameraDelta {
                    offset: Some(to_screen(delta)),
                    anchor: Some(to_screen(to)),
                    ..CameraDelta::default()
                };
                let step = Step { pan: delta, ..Step::default() };
                Some((camera, step))
            }
            _ => None,
        }
    }

    fn pinch_step(&mut self, pinch: &mut Pinch, points: [DVec2; 2], now: f64) {
        let [a, b] = points;
        let [la, lb] = pinch.last;
        let (va, vb) = (a - la, b - lb);
        let vector = b - a;
        let tap_slop = self.options.metrics.double_tap_slop;
        if pinch.tap && (a.distance(self.pointers[0].down) > tap_slop || b.distance(self.pointers[1].down) > tap_slop) {
            pinch.tap = false;
        }
        if !pinch.can_transform {
            pinch.last = points;
            return;
        }
        let pinch_opts = self.options.gestures.pinch;
        let pitch_on = self.options.axes.pitch.enabled && pinch_opts.pitch;
        if !pitch_on {
            pinch.pitch = Some(false);
        }
        // Two fingers moving up or down together tilt, and do nothing else.
        if pinch.pitch.is_none() {
            let pitch_slop = self.options.metrics.pinch_pitch_slop;
            let moved = |v: DVec2| {
                let len = v.length();
                len > 0.0 && len >= pitch_slop
            };
            let (moved_a, moved_b) = (moved(va), moved(vb));
            if moved_a && moved_b {
                let vertical = |v: DVec2| v.y.abs() > v.x.abs();
                pinch.pitch = Some(vertical(va) && vertical(vb) && (va.y > 0.0) == (vb.y > 0.0));
            } else if moved_a || moved_b {
                let since = *pinch.single_since.get_or_insert(now);
                if now - since >= PITCH_DECIDE_MS {
                    pinch.pitch = Some(false);
                }
            }
            if pinch.pitch.is_none() {
                return;
            }
        }
        if pinch.pitch == Some(true) {
            pinch.last = points;
            pinch.tap = false;
            let pitch = f64::midpoint(va.y, vb.y) * pinch_opts.pitch_per_px;
            self.update(&CameraDelta { pitch: Some(pitch), ..CameraDelta::default() });
            self.tracking.record(now, Step { pitch, ..Step::default() });
            return;
        }
        let (mid, last_mid) = ((a + b) / 2.0, (la + lb) / 2.0);
        let distance = vector.length();
        let last_distance = (lb - la).length();
        pinch.min_diameter = pinch.min_diameter.min(distance);
        let zoom_on = self.options.axes.zoom.enabled && pinch_opts.zoom;
        if !zoom_on {
            pinch.zooming = false;
        } else if !pinch.zooming
            && (distance / pinch.start_distance).log2().abs() >= self.options.metrics.pinch_zoom_threshold
        {
            pinch.zooming = true;
        }
        let rotate_on =
            self.options.axes.bearing.enabled && pinch_opts.rotate && (pinch_opts.rotate_during_zoom || !pinch.zooming);
        if !rotate_on {
            if std::mem::replace(&mut pinch.rotating, false) {
                self.tracking.trackers[DELTA_BEARING].reset();
            }
        } else if !pinch.rotating {
            let threshold =
                self.options.metrics.pinch_rotate_threshold / (std::f64::consts::PI * pinch.min_diameter) * 360.0;
            if angle(pinch.start_vector, vector).abs() >= threshold {
                pinch.rotating = true;
            }
        }
        let pan_on = self.options.axes.pan.enabled && pinch_opts.pan;
        if !pan_on {
            pinch.panning = false;
        } else if !pinch.panning
            && (pinch.zooming
                || pinch.rotating
                || (mid - (self.pointers[0].down + self.pointers[1].down) / 2.0).length()
                    > self.slop(PointerKind::Touch))
        {
            pinch.panning = true;
        }
        let pan = if pinch.panning { mid - last_mid } else { DVec2::ZERO };
        let zoom = if pinch.zooming && last_distance > 0.0 { (distance / last_distance).log2() } else { 0.0 };
        // Fingers turning clockwise turn the map clockwise.
        let bearing = if pinch.rotating { -angle(lb - la, vector) } else { 0.0 };
        pinch.last = points;
        if pan == DVec2::ZERO && zoom == 0.0 && bearing == 0.0 {
            return;
        }
        let zoom_around = Self::resolve_anchor(pinch_opts.zoom_anchor, mid);
        let rotate_around = Self::resolve_anchor(pinch_opts.rotate_anchor, mid);
        // Apply parts anchored at the fingers' midpoint together, then any
        // parts anchored at the padded camera center.
        let mid_zoom = (zoom != 0.0 && zoom_around.is_some()).then(|| zoom.exp2());
        let mid_bearing = (bearing != 0.0 && rotate_around.is_some()).then_some(bearing);
        if pan != DVec2::ZERO || mid_zoom.is_some() || mid_bearing.is_some() {
            self.update(&CameraDelta {
                offset: (pan != DVec2::ZERO).then_some(to_screen(pan)),
                scale: mid_zoom,
                bearing: mid_bearing,
                anchor: Some(to_screen(mid)),
                ..CameraDelta::default()
            });
        }
        let center_zoom = (zoom != 0.0 && zoom_around.is_none()).then(|| zoom.exp2());
        let center_bearing = (bearing != 0.0 && rotate_around.is_none()).then_some(bearing);
        if center_zoom.is_some() || center_bearing.is_some() {
            self.update(&CameraDelta {
                scale: center_zoom,
                bearing: center_bearing,
                anchor: None,
                ..CameraDelta::default()
            });
        }
        pinch.tap = false;
        self.tracking
            .record(now, Step { pan, zoom, bearing, zoom_around, bearing_around: rotate_around, ..Step::default() });
    }

    fn up(&mut self, id: u32, position: Option<DVec2>, now: f64) -> bool {
        let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
            return false;
        };
        let pointer = self.pointers.remove(index);
        let cancelled = position.is_none();
        // A cancelled pointer cancels its whole gesture, and the pointers
        // still down make no tap and no release until they all lift.
        if cancelled && !self.pointers.is_empty() {
            self.finish(now, Finish::Cancel);
            self.mode = Mode::Ignored;
            return true;
        }
        // A cancelled pointer finishes its gesture with `Cancel`, whatever
        // its release would have been.
        let unless_cancelled = |finish: Finish| if cancelled { Finish::Cancel } else { finish };
        match self.mode {
            Mode::Pinch(pinch) => {
                if !self.pointers.is_empty() {
                    // Lifting one finger continues as a one-finger pan;
                    // lifting the second ends a two-finger tap.
                    let tap = pinch.tap && now - pointer.down_at < self.double_tap_interval_ms();
                    self.mode = if tap {
                        Mode::Pinch(pinch)
                    } else {
                        self.tracking.stage(now);
                        if self.can_pan_drag(self.pointers[0]) {
                            Mode::Pan
                        } else {
                            Mode::NoDrag { staged_release: true }
                        }
                    };
                    return true;
                }
                self.finish(now, unless_cancelled(if pinch.tap { Finish::Settle } else { Finish::Glide }));
                if pinch.tap && !cancelled {
                    let mid = (pinch.last[0] + pinch.last[1]) / 2.0;
                    self.events.push(GestureEvent::TwoFingerTap { position: to_screen(mid) });
                    let two_finger = self.options.gestures.two_finger_tap;
                    if two_finger.enabled {
                        self.tap_zoom(mid, two_finger.zoom_levels, two_finger.anchor, now);
                    }
                }
            }
            Mode::Pan if !self.pointers.is_empty() => {}
            Mode::Pressed { long_pressed } => {
                if self.pointers.is_empty() {
                    self.finish(now, unless_cancelled(Finish::Settle));
                    // A long press that no frame timed reports as it lifts.
                    if !cancelled && !long_pressed && now - pointer.down_at >= self.long_press_ms() {
                        let position = to_screen(pointer.position);
                        self.events.push(GestureEvent::LongPress { id: pointer.id, position });
                        self.last_tap = None;
                    } else if !cancelled && !long_pressed {
                        self.tap(pointer, now);
                    }
                }
            }
            Mode::BoxZoom { origin } => {
                self.finish(now, unless_cancelled(Finish::Stop));
                if !cancelled && self.options.gestures.box_zoom.enabled && self.options.axes.zoom.enabled {
                    self.zoom_to_box(origin, position.unwrap_or(pointer.position));
                }
            }
            Mode::TapDrag { origin, moved, long_pressed } => {
                if self.pointers.is_empty() {
                    self.last_tap = None;
                    self.finish(now, unless_cancelled(if moved { Finish::Glide } else { Finish::Settle }));
                    if !moved && !cancelled && !long_pressed {
                        let (id, position) = (pointer.id, to_screen(origin));
                        // A long press that no frame timed reports as it lifts.
                        if now - pointer.down_at >= self.long_press_ms() {
                            self.events.push(GestureEvent::LongPress { id, position });
                        } else {
                            self.events
                                .extend([GestureEvent::Tap { id, position }, GestureEvent::DoubleTap { id, position }]);
                            self.double_tap_zoom(pointer, origin, now);
                        }
                    }
                }
            }
            Mode::Pan | Mode::Rotate { .. } => {
                self.finish(now, unless_cancelled(Finish::Glide));
            }
            Mode::NoDrag { staged_release } => {
                if self.pointers.is_empty() {
                    let finish = if staged_release { Finish::Glide } else { Finish::Stop };
                    self.finish(now, unless_cancelled(finish));
                }
            }
            Mode::PendingDrag => {
                self.pending_moves.clear();
                if self.pointers.is_empty() {
                    self.finish(now, unless_cancelled(Finish::Stop));
                }
            }
            Mode::Ignored | Mode::Idle => {
                if self.pointers.is_empty() {
                    self.finish(now, unless_cancelled(Finish::Stop));
                }
            }
        }
        true
    }

    /// A press released without moving before a long press: a tap, perhaps
    /// the second of a double tap.
    fn tap(&mut self, pointer: Pointer, now: f64) {
        let (id, position) = (pointer.id, pointer.position);
        self.events.push(GestureEvent::Tap { id, position: to_screen(position) });
        if self.follows_tap(pointer.kind, pointer.down, pointer.down_at) {
            self.last_tap = None;
            self.events.push(GestureEvent::DoubleTap { id, position: to_screen(position) });
            self.double_tap_zoom(pointer, position, now);
        } else {
            let interval = self.double_tap_interval_ms();
            if interval == 0.0 {
                self.last_tap = None;
                self.events.push(GestureEvent::SingleTap { id, position: to_screen(position) });
            } else {
                self.last_tap =
                    Some(PendingTap { id, position, at: now, kind: pointer.kind, confirm_at: Some(now + interval) });
            }
        }
    }

    /// A double tap's zoom at `at`: in, or out with the zoom-out flag or mode.
    fn double_tap_zoom(&mut self, pointer: Pointer, at: DVec2, now: f64) {
        let double_tap = self.options.gestures.double_tap;
        if !double_tap.enabled {
            return;
        }
        let levels = double_tap.zoom_levels;
        let out = pointer.flags.zoom_out || self.modes.zoom_out;
        self.tap_zoom(at, if out { -levels } else { levels }, double_tap.anchor, now);
    }

    /// Zooms `levels` anchored per `anchor` around `at` as a discrete delta
    /// does, unless zoom is off or `levels` is 0.
    fn tap_zoom(&mut self, at: DVec2, levels: f64, anchor: GestureAnchor, now: f64) {
        if levels != 0.0 {
            self.delta(Self::resolve_anchor(anchor, at), true, [0.0, 0.0, levels, 0.0, 0.0], now);
        }
    }

    /// Ends the gesture with every pointer up: a release glides on with the
    /// speed its last moves had, and settles what it changed.
    fn finish(&mut self, now: f64, finish: Finish) {
        self.pending_moves.clear();
        match finish {
            Finish::Cancel => {
                self.mode = Mode::Idle;
                self.caught_glide = None;
                self.deltas = None;
                self.last_tap = None;
                self.cancel_phase();
            }
            Finish::Stop => {
                self.mode = Mode::Idle;
                self.caught_glide = None;
                self.end_phase(None);
            }
            Finish::Settle => self.release(Release::default()),
            Finish::Glide => {
                let release = self.tracking.release(now);
                self.release(release);
            }
        }
    }

    /// Ends the gesture with `release`, which glides on, and settles what the
    /// gesture changed.
    fn release(&mut self, release: Release) {
        self.mode = Mode::Idle;
        let caught_glide = self
            .caught_glide
            .take()
            .and_then(|end| end.take())
            .filter(|end| self.options.carry_caught_glide && end.outcome == TransitionOutcome::Cancelled)
            .map(|end| end.velocity);
        let momentum = release.into_momentum(caught_glide, &self.options);
        self.end_phase(Some(&momentum));
    }

    /// Whether a press of `kind` at `position` is the second of a double tap.
    fn follows_tap(&self, kind: PointerKind, position: DVec2, now: f64) -> bool {
        self.last_tap.is_some_and(|tap| {
            tap.kind == kind
                && now - tap.at < self.double_tap_interval_ms()
                && tap.position.distance(position) < self.options.metrics.double_tap_slop
        })
    }

    /// Zooms so the box from `a` to `b` fills the view, centred on its
    /// middle; a box without area does nothing.
    fn zoom_to_box(&mut self, a: DVec2, b: DVec2) {
        let size = (b - a).abs();
        if size.x < 1.0 || size.y < 1.0 {
            return;
        }
        let Some(center) = self.camera.lat_lng_for_pixel(to_screen((a + b) / 2.0)) else {
            return;
        };
        let viewport = to_vec2(self.camera.viewport());
        let zoom = (viewport.x / size.x).min(viewport.y / size.y).log2();
        // The box is what the user sees now: setting the zoom stops a
        // running notch ease.
        let target = clamp_zoom(&self.camera, zoom_of(&self.camera) + zoom);
        let duration = self.options.gestures.box_zoom.duration;
        let (mode, animation) = if duration.is_zero() {
            (CameraUpdateMode::Jump, AnimationOptions::default())
        } else {
            (CameraUpdateMode::Ease, self.animation(duration, EASE))
        };
        let update = CameraUpdate {
            mode,
            camera: CameraOptions { center: Some(center), zoom: Some(target), ..Default::default() },
            animation,
            phase: GesturePhase::None,
        };
        self.step_to(&update);
    }

    /// Camera movement from a delta anchored at `anchor` (`None` = padded
    /// camera center), in `amounts` per [`DELTA_PARTS`], of the parts that are
    /// on; nothing moves when none is. A continuous delta moves at once; a
    /// discrete one eases (or applies immediately when `step_duration` is 0),
    /// retargeting the ease of each part it moves.
    fn delta(&mut self, anchor: Option<DVec2>, discrete: bool, mut amounts: [f64; DELTA_PARTS], now: f64) -> bool {
        let axes = &self.options.axes;
        let on = [axes.pan.enabled, axes.pan.enabled, axes.zoom.enabled, axes.bearing.enabled, axes.pitch.enabled];
        for (amount, on) in amounts.iter_mut().zip(on) {
            if !on || !amount.is_finite() {
                *amount = 0.0;
            }
        }
        if amounts.iter().all(|amount| *amount == 0.0) {
            return false;
        }
        let duration = self.step_duration_ms();
        let max_zoom = self.options.gestures.deltas.max_step_zoom;
        let idle_ms = self.delta_idle_ms();
        let mut gesture = self.deltas.unwrap_or(DeltaGesture { idle_until: now, eases: [None; DELTA_PARTS] });
        gesture.idle_until = now + idle_ms;
        // Deltas that begin a gesture of their own measure its release.
        if !self.begun {
            self.tracking.reset(now);
        }
        self.begin();
        if discrete && duration > 0.0 {
            for (part, amount) in amounts.into_iter().enumerate() {
                if amount == 0.0 {
                    continue;
                }
                let ease = gesture.eases[part];
                // The zoom stops at its range: levels past a limit would hold
                // the zoom there once the input turns back, until it undid
                // them.
                gesture.eases[part] = Some(if part == DELTA_ZOOM {
                    StepEase::retarget(ease, amount, anchor, now, duration, |levels| {
                        within_zoom_range(&self.camera, levels)
                    })
                } else {
                    StepEase::retarget(ease, amount, anchor, now, duration, |amount| amount)
                });
            }
        } else {
            if discrete {
                amounts[DELTA_ZOOM] = within_zoom_range(&self.camera, amounts[DELTA_ZOOM]);
            } else {
                amounts[DELTA_ZOOM] = amounts[DELTA_ZOOM].clamp(-max_zoom, max_zoom);
            }
            self.move_by(amounts, anchor);
            // A pointer gesture that the deltas joined releases at the
            // pointers' speed; immediate discrete deltas don't glide.
            if !discrete && matches!(self.mode, Mode::Idle) {
                let [x, y, zoom, bearing, pitch] = amounts;
                let step = Step {
                    pan: DVec2::new(x, y),
                    zoom,
                    bearing,
                    pitch,
                    zoom_around: anchor,
                    bearing_around: anchor,
                    pitch_around: anchor,
                };
                self.tracking.record(now, step);
            }
        }
        self.deltas = Some(gesture);
        true
    }

    /// The platform ended the deltas under way ([`Input::DeltaEnd`]): they
    /// glide on at `fling`, or at their continuous deltas' speed. A fling
    /// without deltas under way is a gesture of its own.
    fn delta_end(&mut self, fling: Option<Fling>, now: f64) -> bool {
        if !matches!(self.mode, Mode::Idle) {
            return false;
        }
        let under_way = self.begun && self.deltas.is_some();
        let release = match fling {
            Some(fling) => self.fling_release(fling),
            None if under_way => self.tracking.release(now),
            None => return false,
        };
        if !under_way {
            if release.pan.is_none() && release.zoom.is_none() && release.bearing.is_none() && release.pitch.is_none() {
                return false;
            }
            self.begin();
        }
        // Discrete deltas still easing finish as a gesture of their own.
        if self.deltas.is_some_and(|deltas| deltas.eases.iter().all(Option::is_none)) {
            self.deltas = None;
        }
        self.release(release);
        true
    }

    /// The release of a fling the platform measured, in the parts that are
    /// on.
    fn fling_release(&self, fling: Fling) -> Release {
        let axes = &self.options.axes;
        let part = |on: bool, speed: f64| (on && speed != 0.0 && speed.is_finite()).then_some(speed);
        let pan = to_vec2(fling.pan);
        let anchor = fling.anchor.map(to_vec2);
        Release {
            pan: (axes.pan.enabled && pan != DVec2::ZERO && pan.is_finite()).then_some(pan),
            zoom: part(axes.zoom.enabled, fling.zoom),
            bearing: part(axes.bearing.enabled, fling.bearing),
            pitch: part(axes.pitch.enabled, fling.pitch),
            zoom_anchor: anchor,
            bearing_anchor: anchor,
            pitch_anchor: anchor,
        }
    }

    /// The platform took the deltas under way away ([`Input::DeltaCancel`]).
    fn delta_cancel(&mut self, now: f64) -> bool {
        if !matches!(self.mode, Mode::Idle) || self.deltas.is_none() {
            return false;
        }
        self.finish(now, Finish::Cancel);
        true
    }

    /// Moves each part by its amount per [`DELTA_PARTS`] at once, holding
    /// the ground under `anchor` (or the padded camera center when `None`).
    fn move_by(&mut self, amounts: [f64; DELTA_PARTS], anchor: Option<DVec2>) {
        let [x, y, zoom, bearing, pitch] = amounts;
        if amounts.iter().all(|amount| *amount == 0.0) {
            return;
        }
        let delta = CameraDelta {
            offset: (x != 0.0 || y != 0.0).then(|| ScreenCoordinate::new(x, y)),
            scale: (zoom != 0.0).then(|| zoom.exp2()),
            bearing: (bearing != 0.0).then_some(bearing),
            pitch: (pitch != 0.0).then_some(pitch),
            anchor: anchor.map(to_screen),
            ..CameraDelta::default()
        };
        self.update(&delta);
    }
}

fn zoom_of(camera: &impl GestureCamera) -> f64 {
    camera.camera().zoom.unwrap_or(0.0)
}

fn clamp_zoom(camera: &impl GestureCamera, zoom: f64) -> f64 {
    let (min, max) = camera.zoom_range();
    zoom.max(min).min(max)
}

/// `levels` of zoom from the camera's zoom, cut at its zoom range. A zoom
/// outside the range may still move toward it.
fn within_zoom_range(camera: &impl GestureCamera, levels: f64) -> f64 {
    let zoom = zoom_of(camera);
    let (min, max) = camera.zoom_range();
    levels.clamp((min - zoom).min(0.0), (max - zoom).max(0.0))
}

/// The clockwise angle from `a` to `b` on screen, in degrees.
fn angle(a: DVec2, b: DVec2) -> f64 {
    a.perp_dot(b).atan2(a.dot(b)).to_degrees()
}

#[cfg(test)]
#[path = "recognizer_test.rs"]
mod recognizer_test;