Skip to main content

mln_engine/gestures/
recognizer.rs

1//! The gesture recognizers for one map, ported from Orbis's orb-camera
2//! `input/mod.rs` onto the map's camera calls
3//! ([`GestureCamera`]).
4
5use std::ops::{Add, AddAssign, Div, Mul, Sub};
6use std::time::Duration;
7
8use mln_style::unitbezier::UnitBezier;
9
10use crate::camera::{
11    AnchoredMomentum, AnimationOptions, CameraDelta, CameraMomentum, CameraOptions, CameraUpdate, CameraUpdateMode,
12    CameraVelocity, GesturePhase, MomentumGlide, TransitionOutcome,
13};
14use crate::geo::ScreenCoordinate;
15use crate::gestures::camera::{GestureCamera, PendingEnd};
16use crate::gestures::input::{GestureEvent, Input, Modes, PinchPhase, PointerKind};
17use crate::gestures::notches::NotchWatch;
18use crate::gestures::options::{AxisOptions, GestureOptions, InvalidGestureOptions};
19use crate::gestures::velocity::VelocityTracker;
20
21/// The ease of a box zoom (GL JS).
22const BOX_EASE: Duration = Duration::from_millis(500);
23/// GL JS's `defaultEasing` and `easeOut`.
24const EASE_X1: f64 = 0.25;
25const EASE_Y1: f64 = 0.1;
26const EASE_X2: f64 = 0.25;
27const EASE_Y2: f64 = 1.0;
28const EASE: UnitBezier = UnitBezier::new(EASE_X1, EASE_Y1, EASE_X2, EASE_Y2);
29/// A pinch whose last finger lifted this long ago still lends its release
30/// its motion; until then the remaining finger's motion doesn't count, as it
31/// belongs to lifting the other (Compose's `ContactReleaseMillis`).
32const STAGED_RELEASE_MS: f64 = 100.0;
33/// Two fingers decide whether they tilt once both have moved this far
34/// (pixels), or once one alone has moved for this long (GL JS
35/// `TwoFingersTouchPitchHandler`).
36const PITCH_DECIDE_PX: f64 = 2.0;
37const PITCH_DECIDE_MS: f64 = 100.0;
38/// The length of a retargeted step ease's first control point from the
39/// curve's origin, as GL JS's `_smoothOutEasing` keeps it.
40const STEP_EASE_HANDLE: f64 = 0.27;
41/// A step ease that has this little left to move has arrived.
42const STEP_EASE_DONE: f64 = 1e-9;
43/// The parts a delta moves, in [`DeltaGesture::eases`] and the arrays of
44/// amounts: pan x and y, zoom, bearing, pitch.
45const DELTA_PARTS: usize = 5;
46const DELTA_ZOOM: usize = 2;
47
48/// A screen point or offset, for the arithmetic `ScreenCoordinate` lacks.
49#[derive(Clone, Copy, Debug, Default, PartialEq)]
50struct V2 {
51    x: f64,
52    y: f64,
53}
54
55impl V2 {
56    const ZERO: V2 = V2 { x: 0.0, y: 0.0 };
57
58    fn new(x: f64, y: f64) -> V2 {
59        V2 { x, y }
60    }
61
62    fn length(self) -> f64 {
63        self.x.hypot(self.y)
64    }
65
66    fn distance(self, other: V2) -> f64 {
67        (self - other).length()
68    }
69
70    fn dot(self, other: V2) -> f64 {
71        self.x * other.x + self.y * other.y
72    }
73
74    fn abs(self) -> V2 {
75        V2::new(self.x.abs(), self.y.abs())
76    }
77}
78
79impl From<ScreenCoordinate> for V2 {
80    fn from(p: ScreenCoordinate) -> V2 {
81        V2::new(p.x, p.y)
82    }
83}
84
85impl From<V2> for ScreenCoordinate {
86    fn from(v: V2) -> ScreenCoordinate {
87        ScreenCoordinate::new(v.x, v.y)
88    }
89}
90
91impl Add for V2 {
92    type Output = V2;
93    fn add(self, o: V2) -> V2 {
94        V2::new(self.x + o.x, self.y + o.y)
95    }
96}
97
98impl AddAssign for V2 {
99    fn add_assign(&mut self, o: V2) {
100        *self = *self + o;
101    }
102}
103
104impl Sub for V2 {
105    type Output = V2;
106    fn sub(self, o: V2) -> V2 {
107        V2::new(self.x - o.x, self.y - o.y)
108    }
109}
110
111impl Mul<f64> for V2 {
112    type Output = V2;
113    fn mul(self, s: f64) -> V2 {
114        V2::new(self.x * s, self.y * s)
115    }
116}
117
118impl Div<f64> for V2 {
119    type Output = V2;
120    fn div(self, s: f64) -> V2 {
121        V2::new(self.x / s, self.y / s)
122    }
123}
124
125#[derive(Clone, Copy, Debug)]
126struct Pointer {
127    id: u32,
128    kind: PointerKind,
129    position: V2,
130    down: V2,
131    down_at: f64,
132    /// The modes of its held buttons.
133    modes: Modes,
134}
135
136#[derive(Clone, Copy, Debug)]
137struct Pinch {
138    last: [V2; 2],
139    start_distance: f64,
140    start_vector: V2,
141    min_diameter: f64,
142    zooming: bool,
143    rotating: bool,
144    /// Whether the fingers move up or down together: undecided at first.
145    pitch: Option<bool>,
146    single_since: Option<f64>,
147    panning: bool,
148    /// Started within the tap interval and not moved: a two-finger tap so
149    /// far.
150    tap: bool,
151}
152
153#[derive(Clone, Copy, Debug)]
154enum Mode {
155    Idle,
156    /// Pressed and not moved past the click tolerance; held long enough,
157    /// it is a long press, which makes no tap.
158    Pressed {
159        long_pressed: bool,
160    },
161    Pan,
162    /// Shift-drag: the box from `origin` to the pointer is where the map
163    /// zooms on release.
164    BoxZoom {
165        origin: V2,
166    },
167    /// Mouse rotation and tilt.
168    Rotate,
169    Pinch(Pinch),
170    /// The second press of a double tap, held: dragging zooms, and held
171    /// still it can be a long press, which makes no double tap.
172    TapDrag {
173        origin: V2,
174        moved: bool,
175        long_pressed: bool,
176    },
177    /// A pinch the platform recognized ([`Input::Pinch`]).
178    Platform,
179    /// Buttons or pointers the map doesn't use are down.
180    Ignored,
181}
182
183/// One applied gesture step, for the release velocity.
184#[derive(Clone, Copy, Debug, Default)]
185struct Step {
186    pan: V2,
187    zoom: f64,
188    bearing: f64,
189    pitch: f64,
190    around: Option<V2>,
191}
192
193/// Per second, at release.
194#[derive(Clone, Copy, Debug, Default)]
195struct Release {
196    pan: Option<V2>,
197    zoom: Option<f64>,
198    bearing: Option<f64>,
199    pitch: Option<f64>,
200    zoom_anchor: Option<V2>,
201    bearing_anchor: Option<V2>,
202}
203
204/// What a gesture has moved so far, and how fast.
205#[derive(Debug, Default)]
206struct Tracking {
207    /// Totals since the gesture began: pixels, levels, degrees.
208    pan: V2,
209    zoom: f64,
210    bearing: f64,
211    pitch: f64,
212    /// Pan x and y, zoom, bearing, pitch.
213    trackers: [VelocityTracker; 5],
214    zoom_anchor: Option<V2>,
215    bearing_anchor: Option<V2>,
216    /// A pinch's release, staged when it continued as a one-finger pan,
217    /// and when.
218    staged: Option<(f64, Release)>,
219    /// Motion before this doesn't count toward the release.
220    not_before: f64,
221}
222
223impl Tracking {
224    fn reset(&mut self, now: f64) {
225        *self = Self::default();
226        self.record(now, Step::default());
227    }
228
229    /// Adds a step's samples: to each part it moves, and to each part the
230    /// gesture moves already, which stands still otherwise.
231    fn record(&mut self, now: f64, step: Step) {
232        self.pan += step.pan;
233        self.zoom += step.zoom;
234        self.bearing += step.bearing;
235        self.pitch += step.pitch;
236        if step.zoom != 0.0 {
237            self.zoom_anchor = step.around;
238        }
239        if step.bearing != 0.0 {
240            self.bearing_anchor = step.around;
241        }
242        if now < self.not_before {
243            return;
244        }
245        let values = [self.pan.x, self.pan.y, self.zoom, self.bearing, self.pitch];
246        let moved =
247            [step.pan != V2::ZERO, step.pan != V2::ZERO, step.zoom != 0.0, step.bearing != 0.0, step.pitch != 0.0];
248        let start = self.trackers.iter().all(VelocityTracker::is_empty);
249        for ((tracker, value), moved) in self.trackers.iter_mut().zip(values).zip(moved) {
250            if moved || start || !tracker.is_empty() {
251                tracker.add(now, value);
252            }
253        }
254    }
255
256    /// The release at `now`.
257    fn release(&mut self, now: f64) -> Release {
258        let [x, y, zoom, bearing, pitch] = self.trackers.each_ref().map(|t| t.velocity(now));
259        // Every velocity that reaches a release is finite and moving.
260        let some = |v: f64| (v != 0.0 && v.is_finite()).then_some(v);
261        let mut release = Release {
262            pan: ((x != 0.0 || y != 0.0) && x.is_finite() && y.is_finite()).then_some(V2::new(x, y)),
263            zoom: some(zoom),
264            bearing: some(bearing),
265            pitch: some(pitch),
266            zoom_anchor: self.zoom_anchor,
267            bearing_anchor: self.bearing_anchor,
268        };
269        // A pinch that ended moments ago keeps what it had, as Compose's
270        // contact changes do; a pan carried on longer than the velocity
271        // horizon has left it behind.
272        if let Some((at, staged)) = self.staged.take()
273            && now - at <= STAGED_RELEASE_MS
274        {
275            if release.pan.is_none() {
276                release.pan = staged.pan;
277            }
278            if release.zoom.is_none() {
279                release.zoom = staged.zoom;
280                release.zoom_anchor = staged.zoom_anchor;
281            }
282            if release.bearing.is_none() {
283                release.bearing = staged.bearing;
284                release.bearing_anchor = staged.bearing_anchor;
285            }
286            if release.pitch.is_none() {
287                release.pitch = staged.pitch;
288            }
289        }
290        release
291    }
292
293    /// A pinch continues as a one-finger pan: its release so far is kept,
294    /// and the next 100 ms of motion, which belongs to lifting the finger,
295    /// don't count.
296    fn stage(&mut self, now: f64) {
297        let release = self.release(now);
298        self.staged = Some((now, release));
299        for tracker in &mut self.trackers {
300            tracker.reset();
301        }
302        self.not_before = now + STAGED_RELEASE_MS;
303    }
304}
305
306impl Release {
307    /// The momentum this release continues with: glides from its velocities
308    /// by the options' decays, and the options' snaps, which the camera
309    /// applies only to the parts the gesture changed. A part without a decay
310    /// doesn't glide. A glide that the gesture's press caught adds to each
311    /// part that releases its way and clears its minimum speed, as Compose's
312    /// `resolveGestureMomentum` adds it; the decay's maximum speed still caps
313    /// the sum.
314    fn into_momentum(self, caught_glide: Option<CameraVelocity>, options: &GestureOptions) -> CameraMomentum {
315        let caught = caught_glide.unwrap_or_default();
316        let pan = options.pan.momentum.and_then(|decay| {
317            let velocity = self.pan.filter(|v| v.length() >= decay.min_speed)?;
318            let caught = V2::from(caught.pan);
319            let velocity = if velocity.dot(caught) > 0.0 { velocity + caught } else { velocity };
320            Some(MomentumGlide { velocity: velocity.into(), decay })
321        });
322        let scalar = |part: &AxisOptions, release: Option<f64>, anchor: Option<V2>, caught: f64| AnchoredMomentum {
323            glide: part.momentum.and_then(|decay| {
324                let velocity = release.filter(|v| v.abs() >= decay.min_speed)?;
325                let velocity =
326                    if caught != 0.0 && caught.signum() == velocity.signum() { velocity + caught } else { velocity };
327                Some(MomentumGlide { velocity, decay })
328            }),
329            anchor: anchor.map(ScreenCoordinate::from),
330            snap: part.snap,
331        };
332        CameraMomentum {
333            pan,
334            zoom: scalar(&options.zoom, self.zoom, self.zoom_anchor, caught.zoom),
335            bearing: scalar(&options.bearing, self.bearing, self.bearing_anchor, caught.bearing),
336            pitch: scalar(&options.pitch, self.pitch, None, caught.pitch),
337        }
338    }
339}
340
341/// Deltas under way: one gesture from the first until they idle.
342#[derive(Clone, Copy, Debug)]
343struct DeltaGesture {
344    /// Where the latest delta was: zooms and turns hold the ground there, so
345    /// that moving the pointer while scrolling zooms around where it is now
346    /// (GL JS keeps the burst's first point; Apple and Google Maps follow
347    /// the cursor).
348    anchor: V2,
349    /// The gesture ends after this: 200 ms after its last delta and after its
350    /// last ease, as GL JS's zoom ends 200 ms after its last frame.
351    idle_until: f64,
352    /// The eases of discrete deltas, per part ([`DELTA_PARTS`]).
353    eases: [Option<StepEase>; DELTA_PARTS],
354}
355
356/// The eased change of a run of discrete deltas to one part.
357#[derive(Clone, Copy, Debug)]
358struct StepEase {
359    start: f64,
360    /// How far to move from the ease's start, and how far it has moved.
361    distance: f64,
362    applied: f64,
363    /// The first control point of its curve; the second is [`EASE`]'s.
364    x1: f64,
365    y1: f64,
366}
367
368impl StepEase {
369    /// An ease that moves `step` more than what `ease`, if any, hasn't moved
370    /// yet, within `limit`. One still running retargets at its current speed,
371    /// so a quick run speeds up without a stutter: GL JS's
372    /// `_smoothOutEasing` approximates that speed from the previous curve's
373    /// shape, and this matches it in units per second.
374    fn retarget(ease: Option<StepEase>, step: f64, now: f64, duration: f64, limit: impl Fn(f64) -> f64) -> StepEase {
375        let (distance, (x1, y1)) = match ease {
376            Some(ease) if ease.progress(now, duration) < 1.0 => {
377                // Whatever the ease hasn't applied yet carries over.
378                let distance = limit(ease.distance - ease.applied + step);
379                // The new curve's starting slope, dy/dx = y1/x1, times
380                // distance / duration is the current speed; its first control
381                // point stays STEP_EASE_HANDLE from the origin, as GL JS's
382                // does.
383                let slope = if distance == 0.0 { 0.0 } else { ease.speed(now, duration) * duration / distance };
384                let x1 = STEP_EASE_HANDLE / (1.0 + slope * slope).sqrt();
385                (distance, (x1, slope * x1))
386            }
387            Some(ease) => (limit(ease.distance - ease.applied + step), (EASE_X1, EASE_Y1)),
388            None => (limit(step), (EASE_X1, EASE_Y1)),
389        };
390        StepEase { start: now, distance, applied: 0.0, x1, y1 }
391    }
392
393    fn curve(&self) -> UnitBezier {
394        UnitBezier::new(self.x1, self.y1, EASE_X2, EASE_Y2)
395    }
396
397    /// The share of the ease's time elapsed at `now`.
398    fn progress(&self, now: f64, duration: f64) -> f64 {
399        ((now - self.start) / duration).clamp(0.0, 1.0)
400    }
401
402    /// How far it has moved by `now`.
403    fn value(&self, now: f64, duration: f64) -> f64 {
404        let t = self.progress(now, duration);
405        self.distance * if t >= 1.0 { 1.0 } else { self.curve().solve(t, 1e-6) }
406    }
407
408    /// Units per millisecond at `now`.
409    fn speed(&self, now: f64, duration: f64) -> f64 {
410        let dt = 1.0;
411        (self.value(now + dt, duration) - self.value(now, duration)) / dt
412    }
413}
414
415/// When a recognizer next needs [`GestureRecognizer::tick`].
416#[derive(Clone, Copy, Debug, PartialEq)]
417pub enum NextTick {
418    /// Every display frame, while a delta eases or a gesture may reach a
419    /// notch.
420    Frame,
421    /// At this time, on the inputs' clock: when a press becomes a long press,
422    /// or idle deltas end.
423    At(f64),
424}
425
426/// How a gesture finishes once its last pointer lifts.
427#[derive(Clone, Copy, Debug, PartialEq, Eq)]
428enum Finish {
429    /// The platform took it away: nothing continues, and the camera's
430    /// animations stop (the `Cancel` phase).
431    Cancel,
432    /// Ended without a release to continue: a box, input the map ignores.
433    Stop,
434    /// Released without a fling (a tap): only the snaps of what it changed.
435    Settle,
436    /// Released: it glides on, and settles.
437    Glide,
438}
439
440/// Recognizes gestures for one map and continues their releases with the
441/// map's momentum.
442///
443/// - Drag to pan, or with the [`Modes`] the host selects, rotate and tilt or
444///   zoom to a box.
445/// - Two-finger pinch, twist and vertical tilt, and pinches the platform
446///   recognized ([`Input::Pinch`]).
447/// - Double-tap-and-drag to zoom.
448/// - Deltas from wheels, trackpads, dials and keys ([`Input::Delta`]).
449/// - Taps, double taps and two-finger taps, which it reports for the host to
450///   answer.
451///
452/// Every change goes through the map's camera calls with its gesture phase,
453/// so the camera reports it as a gesture: a press begins a gesture, each move
454/// updates it, and the release ends it with momentum (the average velocity of
455/// its last 100 ms, glided by the options' decays), during which the gesture
456/// stays in progress.
457///
458/// Hosts feed it [`Input`]s with their timestamps, in milliseconds on any
459/// clock that only goes forward, and call [`tick`](Self::tick) when it asks.
460/// Every move goes through the `GestureCamera`.
461#[derive(Debug)]
462pub struct GestureRecognizer<C> {
463    /// The map's camera, which every move goes through.
464    camera: C,
465    options: GestureOptions,
466    pointers: Vec<Pointer>,
467    mode: Mode,
468    tracking: Tracking,
469    /// Whether the recognizer's gesture has begun in the camera and not
470    /// ended: a pointer gesture, a scroll, or both.
471    begun: bool,
472    /// The end of the recognizer's last release, whose glide a press may
473    /// stop.
474    release_end: Option<PendingEnd>,
475    /// The end of the glide that this gesture's press stopped, whose speed
476    /// its release carries (`carry_caught_glide`) if the press cancelled it.
477    caught_glide: Option<PendingEnd>,
478    /// The last tap, for double taps: where and when.
479    last_tap: Option<(V2, f64, PointerKind)>,
480    /// The modes that held keys select.
481    modes: Modes,
482    deltas: Option<DeltaGesture>,
483    /// The notches of the gesture under way, until it, its glide and its
484    /// snap end.
485    notch_watch: Option<NotchWatch>,
486    events: Vec<GestureEvent>,
487}
488
489impl<C: GestureCamera> GestureRecognizer<C> {
490    /// A recognizer that moves `camera`, with the default options.
491    pub fn new(camera: C) -> Self {
492        GestureRecognizer::with(camera, GestureOptions::default())
493    }
494
495    /// A recognizer that moves `camera`, with `options`, which must be in
496    /// range.
497    pub fn with_options(camera: C, options: GestureOptions) -> Result<Self, InvalidGestureOptions> {
498        options.validate()?;
499        Ok(GestureRecognizer::with(camera, options))
500    }
501
502    fn with(camera: C, options: GestureOptions) -> Self {
503        GestureRecognizer {
504            camera,
505            options,
506            pointers: Vec::new(),
507            mode: Mode::Idle,
508            tracking: Tracking::default(),
509            begun: false,
510            release_end: None,
511            caught_glide: None,
512            last_tap: None,
513            modes: Modes::default(),
514            deltas: None,
515            notch_watch: None,
516            events: Vec::new(),
517        }
518    }
519
520    /// The camera it moves.
521    #[must_use]
522    pub fn camera(&self) -> &C {
523        &self.camera
524    }
525
526    #[must_use]
527    pub fn options(&self) -> &GestureOptions {
528        &self.options
529    }
530
531    /// Takes effect with the next input, if the options are in range.
532    pub fn set_options(&mut self, options: GestureOptions) -> Result<(), InvalidGestureOptions> {
533        options.validate()?;
534        self.options = options;
535        Ok(())
536    }
537
538    /// A gesture is under way: hosts keep pointer capture and scrolling off.
539    #[cfg(test)]
540    #[must_use]
541    pub(crate) fn is_active(&self) -> bool {
542        !matches!(self.mode, Mode::Idle) || self.deltas.is_some()
543    }
544
545    /// The box a box-zoom drag zooms to, corner to corner in logical pixels,
546    /// while it is drawn: hosts show it.
547    #[must_use]
548    pub fn box_zoom(&self) -> Option<[ScreenCoordinate; 2]> {
549        match self.mode {
550            Mode::BoxZoom { origin } => Some([origin.into(), self.pointers.first()?.position.into()]),
551            _ => None,
552        }
553    }
554
555    /// When the recognizer next needs [`tick`](Self::tick): every display
556    /// frame while a delta eases or a gesture, its glide and its snap may
557    /// reach a notch; at a time for a pending long press or the end of idle
558    /// deltas; or `None`.
559    #[must_use]
560    pub fn next_tick(&self) -> Option<NextTick> {
561        let easing = self.deltas.is_some_and(|deltas| deltas.eases.iter().any(Option::is_some));
562        // A pointer held still moves nothing that could reach a notch.
563        let held_still = matches!(self.mode, Mode::Pressed { .. } | Mode::TapDrag { moved: false, .. });
564        if easing || (self.notch_watch.is_some() && !held_still) {
565            return Some(NextTick::Frame);
566        }
567        let long_press = match self.pointers[..] {
568            [pointer] if self.awaits_long_press() => Some(pointer.down_at + self.options.long_press_ms),
569            _ => None,
570        };
571        let idle = self.deltas.map(|deltas| deltas.idle_until);
572        long_press.into_iter().chain(idle).min_by(f64::total_cmp).map(NextTick::At)
573    }
574
575    /// Whether a press held still may yet become a long press.
576    fn awaits_long_press(&self) -> bool {
577        matches!(
578            self.mode,
579            Mode::Pressed { long_pressed: false } | Mode::TapDrag { moved: false, long_pressed: false, .. }
580        )
581    }
582
583    /// Taps, long presses and notches recognized since the last call.
584    pub fn take_events(&mut self) -> Vec<GestureEvent> {
585        std::mem::take(&mut self.events)
586    }
587
588    /// A host's own command to an absolute camera, such as resetting the
589    /// bearing, through the recognizer: it stops the recognizer's eases of the
590    /// parts it sets, which would otherwise take them back, and is an update
591    /// of a gesture under way or a gesture of its own. `update.phase` is
592    /// ignored.
593    pub fn step_to(&mut self, update: &CameraUpdate) {
594        let set = &update.camera;
595        let center = set.center.is_some();
596        self.stop_step_eases([center, center, set.zoom.is_some(), set.bearing.is_some(), set.pitch.is_some()]);
597        // Outside a gesture it takes over from the last gesture's glide,
598        // whose notches end: host commands report none.
599        if !self.begun {
600            self.notch_watch = None;
601        }
602        let phase = if self.begun { GesturePhase::Update } else { GesturePhase::End };
603        self.camera.update_camera(&CameraUpdate { phase, ..*update });
604    }
605
606    /// Times long presses, steps the eases of discrete deltas, ends deltas
607    /// once they idle, and samples the camera for notches, at `now` on the
608    /// inputs' clock. Call it when [`next_tick`](Self::next_tick) says, which
609    /// it also returns; a call at any other time does no harm.
610    pub fn tick(&mut self, now: f64) -> Option<NextTick> {
611        self.long_press(now);
612        self.delta_frame(now);
613        if let Some(watch) = &mut self.notch_watch {
614            watch.sample(&self.camera.camera(), &self.options, now, &mut self.events);
615            // The gesture ended, and so did its glide and snap: its command
616            // has ended (a gesture cancelled outright has none).
617            if !self.begun && self.release_end.as_ref().is_none_or(PendingEnd::has_ended) {
618                self.notch_watch = None;
619            }
620        }
621        self.next_tick()
622    }
623
624    /// Reports a press held still for the long-press time, once.
625    fn long_press(&mut self, now: f64) {
626        if self.awaits_long_press()
627            && let [pointer] = self.pointers[..]
628            && now - pointer.down_at >= self.options.long_press_ms
629        {
630            match &mut self.mode {
631                Mode::Pressed { long_pressed } | Mode::TapDrag { long_pressed, .. } => *long_pressed = true,
632                _ => {}
633            }
634            self.last_tap = None;
635            self.events.push(GestureEvent::LongPress { id: pointer.id, position: pointer.position.into() });
636        }
637    }
638
639    /// The deltas' part of [`Self::frame`].
640    fn delta_frame(&mut self, now: f64) -> bool {
641        let Some(mut gesture) = self.deltas else {
642            return false;
643        };
644        let duration = self.options.step_duration_ms;
645        let max_zoom = self.options.max_step_zoom;
646        let mut amounts = [0.0; DELTA_PARTS];
647        for (part, slot) in gesture.eases.iter_mut().enumerate() {
648            let Some(mut ease) = *slot else { continue };
649            let mut amount = ease.value(now, duration) - ease.applied;
650            if part == DELTA_ZOOM {
651                amount = amount.clamp(-max_zoom, max_zoom);
652            }
653            ease.applied += amount;
654            amounts[part] = amount;
655            let done = ease.progress(now, duration) >= 1.0 && (ease.distance - ease.applied).abs() <= STEP_EASE_DONE;
656            *slot = (!done).then_some(ease);
657            if done {
658                gesture.idle_until = gesture.idle_until.max(now + self.options.delta_idle_ms);
659            }
660        }
661        // Eases that outlive the pointer gesture they joined carry on as a
662        // gesture of their own, which keeps the release's glide.
663        if !self.begun && amounts.iter().any(|amount| *amount != 0.0) {
664            self.begun = true;
665            self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..CameraDelta::default() });
666        }
667        self.move_by(amounts, gesture.anchor);
668        if gesture.eases.iter().all(Option::is_none) && now >= gesture.idle_until {
669            self.deltas = None;
670            if matches!(self.mode, Mode::Idle) {
671                self.end_phase(None);
672            }
673            return false;
674        }
675        self.deltas = Some(gesture);
676        true
677    }
678
679    /// Handles one input at host time `now`, in milliseconds. Returns whether
680    /// the map used it, so hosts can stop the platform's default.
681    pub fn handle(&mut self, input: Input, now: f64) -> bool {
682        match input {
683            Input::PointerDown { id, kind, position, modes } => {
684                let position = position.into();
685                self.down(Pointer { id, kind, position, down: position, down_at: now, modes })
686            }
687            Input::PointerMove { id, position } => self.moved(id, position.into(), now),
688            Input::PointerUp { id, position } => self.up(id, Some(position.into()), now),
689            Input::PointerCancel { id } => self.up(id, None, now),
690            // Modes only change what later drags do: the platform's default
691            // for the keys stands.
692            Input::Modes(modes) => {
693                self.modes = modes;
694                false
695            }
696            Input::Delta { position, discrete, pan, zoom, bearing, pitch } => {
697                self.delta(position.into(), discrete, [pan.x, pan.y, zoom, bearing, pitch], now)
698            }
699            Input::Pinch { center, scale, rotation, phase } => {
700                self.platform_pinch(center.into(), scale, rotation, phase, now)
701            }
702        }
703    }
704
705    /// The animation options of the recognizer's eased steps.
706    fn animation(&self, duration: Duration, easing: UnitBezier) -> AnimationOptions {
707        AnimationOptions {
708            duration: Some(duration),
709            easing: Some(easing),
710            transition_id: Some(self.options.transition_id),
711            ..AnimationOptions::default()
712        }
713    }
714
715    /// Begins the gesture, unless it has begun: the `Begin` phase stops the
716    /// camera's animations, as GL JS and the MapLibre Native SDKs do on a
717    /// press. Without `interrupt_animations`, it stops only the recognizer's
718    /// own, and begins with `Update`, which keeps the others. A glide that
719    /// this stops is caught: the release may carry its speed, which the
720    /// glide's end reports.
721    fn begin(&mut self) {
722        if self.begun {
723            return;
724        }
725        self.begun = true;
726        // Only a glide still running can be caught: one that has ended, as
727        // when a command cancelled it, carries nothing.
728        self.caught_glide = self.release_end.take().filter(|end| end.take().is_none());
729        let notches = [&self.options.zoom, &self.options.bearing, &self.options.pitch]
730            .iter()
731            .any(|part| part.enabled && !part.notches.is_empty());
732        self.notch_watch = notches.then(|| NotchWatch::new(&self.camera.camera(), &self.options));
733        let phase = if self.options.interrupt_animations {
734            GesturePhase::Begin
735        } else {
736            self.camera.cancel_transitions_with_id(self.options.transition_id);
737            GesturePhase::Update
738        };
739        self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
740    }
741
742    /// One step of the gesture, at once.
743    fn update(&mut self, delta: &CameraDelta) {
744        self.begin();
745        self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..*delta });
746    }
747
748    /// Ends the gesture, with the momentum it continues with: the gesture
749    /// stays in progress until the momentum ends.
750    fn end_phase(&mut self, momentum: Option<&CameraMomentum>) {
751        if !std::mem::replace(&mut self.begun, false) {
752            return;
753        }
754        let animation =
755            AnimationOptions { transition_id: Some(self.options.transition_id), ..AnimationOptions::default() };
756        let phase = GesturePhase::End;
757        let delta = CameraDelta { momentum: momentum.copied(), animation, phase, ..CameraDelta::default() };
758        let end = self.camera.release(&delta);
759        // The end of a release that may glide, which a press may catch; a
760        // gesture that ends without momentum leaves the last one's.
761        if momentum.is_some() {
762            self.release_end = Some(end);
763        }
764    }
765
766    /// The platform cancelled the gesture: it ends, and the `Cancel` phase
767    /// stops the camera's animations (only the recognizer's own, without
768    /// `interrupt_animations`).
769    fn cancel_phase(&mut self) {
770        self.notch_watch = None;
771        if !std::mem::replace(&mut self.begun, false) {
772            return;
773        }
774        let phase = if self.options.interrupt_animations {
775            GesturePhase::Cancel
776        } else {
777            self.camera.cancel_transitions_with_id(self.options.transition_id);
778            GesturePhase::End
779        };
780        self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
781    }
782
783    /// Stops the step eases of the parts in `parts` ([`DELTA_PARTS`]).
784    fn stop_step_eases(&mut self, parts: [bool; DELTA_PARTS]) {
785        if let Some(gesture) = self.deltas.as_mut() {
786            for (ease, stop) in gesture.eases.iter_mut().zip(parts) {
787                if stop {
788                    *ease = None;
789                }
790            }
791        }
792    }
793
794    /// A press of `pointer`, at its position and at its `down_at` time.
795    fn down(&mut self, pointer: Pointer) -> bool {
796        let Pointer { id, kind, position, down_at: now, .. } = pointer;
797        if self.pointers.iter().any(|p| p.id == id) {
798            return false;
799        }
800        let touch = kind == PointerKind::Touch;
801        if !touch && !self.pointers.is_empty() {
802            return false;
803        }
804        if matches!(self.mode, Mode::Platform) {
805            // A press during a platform pinch takes over from it.
806            self.finish(now, Finish::Cancel);
807        }
808        self.pointers.push(pointer);
809        // A press takes over from deltas, and stops their easing.
810        self.deltas = None;
811        self.begin();
812        match (self.mode, self.pointers.len()) {
813            (Mode::Idle, 1) => {
814                self.mode = if touch && self.follows_tap(kind, position, now) {
815                    Mode::TapDrag { origin: position, moved: false, long_pressed: false }
816                } else {
817                    Mode::Pressed { long_pressed: false }
818                };
819                self.tracking.reset(now);
820            }
821            (Mode::Pressed { .. } | Mode::Pan | Mode::TapDrag { .. }, 2) if touch => {
822                let [a, b] = [self.pointers[0].position, self.pointers[1].position];
823                let vector = b - a;
824                self.mode = Mode::Pinch(Pinch {
825                    last: [a, b],
826                    start_distance: vector.length(),
827                    start_vector: vector,
828                    min_diameter: vector.length(),
829                    zooming: false,
830                    rotating: false,
831                    // Fingers above one another can't tilt.
832                    pitch: (!self.options.pitch.enabled || vector.y.abs() > vector.x.abs()).then_some(false),
833                    single_since: None,
834                    panning: false,
835                    tap: now - self.pointers[0].down_at < self.options.tap_interval_ms
836                        && matches!(self.mode, Mode::Pressed { .. }),
837                });
838                self.tracking.record(now, Step::default());
839            }
840            _ => self.mode = Mode::Ignored,
841        }
842        true
843    }
844
845    fn moved(&mut self, id: u32, position: V2, now: f64) -> bool {
846        let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
847            return false;
848        };
849        let last = self.pointers[index].position;
850        self.pointers[index].position = position;
851        match &mut self.mode {
852            Mode::Pressed { .. } => {
853                let pointer = self.pointers[index];
854                let down = pointer.down;
855                if position.distance(down) > self.options.click_tolerance {
856                    // The drag reads its modes as it starts.
857                    let modes = pointer.modes | self.modes;
858                    self.mode = if modes.rotate {
859                        Mode::Rotate
860                    } else if modes.box_zoom && self.options.zoom.enabled {
861                        Mode::BoxZoom { origin: down }
862                    } else {
863                        Mode::Pan
864                    };
865                    // The jump past the click tolerance counts toward the
866                    // release: it is motion over the time since the press.
867                    // Compose resets its tracker here, which protects its
868                    // least-squares fit; an average needs no protecting, and
869                    // dropping the jump loses the start of a short flick.
870                    self.drag_step(down, position, now);
871                }
872            }
873            Mode::Pan | Mode::Rotate => self.drag_step(last, position, now),
874            Mode::TapDrag { origin, moved, .. } => {
875                let (origin, dy) = (*origin, position.y - last.y);
876                *moved = *moved || position.distance(origin) > self.options.click_tolerance;
877                if *moved && self.options.zoom.enabled {
878                    let zoom = dy * self.options.tap_drag_zoom;
879                    let delta =
880                        CameraDelta { scale: Some(zoom.exp2()), anchor: Some(origin.into()), ..CameraDelta::default() };
881                    self.update(&delta);
882                    self.tracking.record(now, Step { zoom, around: Some(origin), ..Step::default() });
883                }
884            }
885            Mode::Pinch(_) if self.pointers.len() < 2 => {
886                // The other finger of a two-finger tap lifted, and this one
887                // moves on: a pan.
888                self.mode = Mode::Pan;
889                self.drag_step(last, position, now);
890            }
891            Mode::Pinch(pinch) => {
892                if index > 1 {
893                    return true;
894                }
895                let mut pinch = *pinch;
896                let points = [self.pointers[0].position, self.pointers[1].position];
897                self.pinch_step(&mut pinch, points, now);
898                self.mode = Mode::Pinch(pinch);
899            }
900            Mode::BoxZoom { .. } | Mode::Idle | Mode::Ignored | Mode::Platform => {}
901        }
902        true
903    }
904
905    /// One pan or mouse-rotate step from `from` to `to`.
906    fn drag_step(&mut self, from: V2, to: V2, now: f64) {
907        let delta = to - from;
908        match self.mode {
909            Mode::Rotate => {
910                let bearing = if self.options.bearing.enabled { delta.x * self.options.drag_rotate } else { 0.0 };
911                let pitch = if self.options.pitch.enabled { -delta.y * self.options.drag_pitch } else { 0.0 };
912                let step = CameraDelta { bearing: Some(bearing), pitch: Some(pitch), ..CameraDelta::default() };
913                self.update(&step);
914                self.tracking.record(now, Step { bearing, pitch, ..Step::default() });
915            }
916            Mode::BoxZoom { .. } => {}
917            _ if !self.options.pan.enabled => {}
918            _ => {
919                // The pointer is the point the drag holds, which the globe
920                // turns to keep under it.
921                let step =
922                    CameraDelta { offset: Some(delta.into()), anchor: Some(to.into()), ..CameraDelta::default() };
923                self.update(&step);
924                self.tracking.record(now, Step { pan: delta, ..Step::default() });
925            }
926        }
927    }
928
929    fn pinch_step(&mut self, pinch: &mut Pinch, points: [V2; 2], now: f64) {
930        let [a, b] = points;
931        let [la, lb] = pinch.last;
932        let (va, vb) = (a - la, b - lb);
933        let vector = b - a;
934        let tap_tolerance = self.options.tap_tolerance;
935        if pinch.tap
936            && (a.distance(self.pointers[0].down) > tap_tolerance || b.distance(self.pointers[1].down) > tap_tolerance)
937        {
938            pinch.tap = false;
939        }
940        // Two fingers moving up or down together tilt, and do nothing else
941        // (GL JS `TwoFingersTouchPitchHandler`).
942        if pinch.pitch.is_none() {
943            let (moved_a, moved_b) = (va.length() >= PITCH_DECIDE_PX, vb.length() >= PITCH_DECIDE_PX);
944            if moved_a && moved_b {
945                let vertical = |v: V2| v.y.abs() > v.x.abs();
946                pinch.pitch = Some(vertical(va) && vertical(vb) && (va.y > 0.0) == (vb.y > 0.0));
947            } else if moved_a || moved_b {
948                let since = *pinch.single_since.get_or_insert(now);
949                if now - since >= PITCH_DECIDE_MS {
950                    pinch.pitch = Some(false);
951                }
952            }
953            if pinch.pitch.is_none() {
954                return;
955            }
956        }
957        if pinch.pitch == Some(true) {
958            let pitch = f64::midpoint(va.y, vb.y) * -self.options.drag_pitch;
959            self.update(&CameraDelta { pitch: Some(pitch), ..CameraDelta::default() });
960            pinch.last = points;
961            pinch.tap = false;
962            self.tracking.record(now, Step { pitch, ..Step::default() });
963            return;
964        }
965        let (mid, last_mid) = ((a + b) / 2.0, (la + lb) / 2.0);
966        let distance = vector.length();
967        let last_distance = (lb - la).length();
968        pinch.min_diameter = pinch.min_diameter.min(distance);
969        if !pinch.zooming
970            && self.options.zoom.enabled
971            && (distance / pinch.start_distance).log2().abs() >= self.options.pinch_zoom_threshold
972        {
973            pinch.zooming = true;
974        }
975        if !pinch.rotating && self.options.bearing.enabled {
976            let threshold = self.options.rotate_threshold / (std::f64::consts::PI * pinch.min_diameter) * 360.0;
977            if angle(pinch.start_vector, vector).abs() >= threshold {
978                pinch.rotating = true;
979            }
980        }
981        if !pinch.panning
982            && self.options.pan.enabled
983            && (mid - (self.pointers[0].down + self.pointers[1].down) / 2.0).length() > self.options.click_tolerance
984        {
985            pinch.panning = true;
986        }
987        let pan = if pinch.panning { mid - last_mid } else { V2::ZERO };
988        let zoom = if pinch.zooming && last_distance > 0.0 { (distance / last_distance).log2() } else { 0.0 };
989        // Fingers turning clockwise turn the map clockwise.
990        let bearing = if pinch.rotating { -angle(lb - la, vector) } else { 0.0 };
991        pinch.last = points;
992        if pan == V2::ZERO && zoom == 0.0 && bearing == 0.0 {
993            return;
994        }
995        // The pan applies first, holding the fingers' middle, then the zoom
996        // and turn hold it in place.
997        let anchored = zoom != 0.0 || bearing != 0.0 || pan != V2::ZERO;
998        self.update(&CameraDelta {
999            offset: (pan != V2::ZERO).then_some(pan.into()),
1000            scale: (zoom != 0.0).then_some(zoom.exp2()),
1001            bearing: (bearing != 0.0).then_some(bearing),
1002            anchor: anchored.then_some(mid.into()),
1003            ..CameraDelta::default()
1004        });
1005        pinch.tap = false;
1006        self.tracking.record(now, Step { pan, zoom, bearing, around: Some(mid), ..Step::default() });
1007    }
1008
1009    fn up(&mut self, id: u32, position: Option<V2>, now: f64) -> bool {
1010        let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
1011            return false;
1012        };
1013        let pointer = self.pointers.remove(index);
1014        let cancelled = position.is_none();
1015        // A cancelled pointer cancels its whole gesture, and the pointers
1016        // still down make no tap and no release until they all lift.
1017        if cancelled && !self.pointers.is_empty() {
1018            self.finish(now, Finish::Cancel);
1019            self.mode = Mode::Ignored;
1020            return true;
1021        }
1022        // A cancelled pointer finishes its gesture with `Cancel`, whatever
1023        // its release would have been.
1024        let unless_cancelled = |finish: Finish| if cancelled { Finish::Cancel } else { finish };
1025        match self.mode {
1026            Mode::Pinch(pinch) => {
1027                if !self.pointers.is_empty() {
1028                    // Lifting one finger continues as a one-finger pan;
1029                    // lifting the second ends a two-finger tap.
1030                    let tap = pinch.tap && now - pointer.down_at < self.options.tap_interval_ms;
1031                    self.mode = if tap {
1032                        Mode::Pinch(pinch)
1033                    } else {
1034                        self.tracking.stage(now);
1035                        Mode::Pan
1036                    };
1037                    return true;
1038                }
1039                self.finish(now, unless_cancelled(if pinch.tap { Finish::Settle } else { Finish::Glide }));
1040                if pinch.tap && !cancelled {
1041                    let mid = (pinch.last[0] + pinch.last[1]) / 2.0;
1042                    self.events.push(GestureEvent::TwoFingerTap { position: mid.into() });
1043                    self.tap_zoom(mid, self.options.two_finger_tap_zoom, now);
1044                }
1045            }
1046            Mode::Pan if !self.pointers.is_empty() => {}
1047            Mode::Pressed { long_pressed } => {
1048                if self.pointers.is_empty() {
1049                    self.finish(now, unless_cancelled(Finish::Settle));
1050                    // A long press that no frame timed reports as it lifts.
1051                    if !cancelled && !long_pressed && now - pointer.down_at >= self.options.long_press_ms {
1052                        let position = pointer.position.into();
1053                        self.events.push(GestureEvent::LongPress { id: pointer.id, position });
1054                        self.last_tap = None;
1055                    } else if !cancelled && !long_pressed {
1056                        self.tap(pointer, now);
1057                    }
1058                }
1059            }
1060            Mode::BoxZoom { origin } => {
1061                self.finish(now, unless_cancelled(Finish::Stop));
1062                if !cancelled {
1063                    self.zoom_to_box(origin, position.unwrap_or(pointer.position));
1064                }
1065            }
1066            Mode::TapDrag { origin, moved, long_pressed } => {
1067                if self.pointers.is_empty() {
1068                    self.last_tap = None;
1069                    self.finish(now, unless_cancelled(if moved { Finish::Glide } else { Finish::Settle }));
1070                    if !moved && !cancelled && !long_pressed {
1071                        let (id, position) = (pointer.id, origin.into());
1072                        // A long press that no frame timed reports as it lifts.
1073                        if now - pointer.down_at >= self.options.long_press_ms {
1074                            self.events.push(GestureEvent::LongPress { id, position });
1075                        } else {
1076                            self.events
1077                                .extend([GestureEvent::Tap { id, position }, GestureEvent::DoubleTap { id, position }]);
1078                            self.double_tap_zoom(pointer, origin, now);
1079                        }
1080                    }
1081                }
1082            }
1083            Mode::Pan | Mode::Rotate => {
1084                self.finish(now, unless_cancelled(Finish::Glide));
1085            }
1086            Mode::Ignored | Mode::Idle | Mode::Platform => {
1087                if self.pointers.is_empty() {
1088                    self.finish(now, unless_cancelled(Finish::Stop));
1089                }
1090            }
1091        }
1092        true
1093    }
1094
1095    /// A press released without moving before a long press: a tap, perhaps
1096    /// the second of a double tap.
1097    fn tap(&mut self, pointer: Pointer, now: f64) {
1098        let (id, position) = (pointer.id, pointer.position);
1099        self.events.push(GestureEvent::Tap { id, position: position.into() });
1100        if self.follows_tap(pointer.kind, position, now) {
1101            self.last_tap = None;
1102            self.events.push(GestureEvent::DoubleTap { id, position: position.into() });
1103            self.double_tap_zoom(pointer, position, now);
1104        } else {
1105            self.last_tap = Some((position, now, pointer.kind));
1106        }
1107    }
1108
1109    /// A double tap's zoom at `at`: in, or out with the zoom-out mode.
1110    fn double_tap_zoom(&mut self, pointer: Pointer, at: V2, now: f64) {
1111        let levels = self.options.double_tap_zoom;
1112        let out = (pointer.modes | self.modes).zoom_out;
1113        self.tap_zoom(at, if out { -levels } else { levels }, now);
1114    }
1115
1116    /// Zooms `levels` around `at` as a discrete delta does, unless the zoom
1117    /// is off or `levels` is 0.
1118    fn tap_zoom(&mut self, at: V2, levels: f64, now: f64) {
1119        if levels != 0.0 {
1120            self.delta(at, true, [0.0, 0.0, levels, 0.0, 0.0], now);
1121        }
1122    }
1123
1124    /// Ends the gesture with every pointer up: a release glides on with the
1125    /// speed its last moves had, and settles what it changed.
1126    fn finish(&mut self, now: f64, finish: Finish) {
1127        self.mode = Mode::Idle;
1128        let caught_glide = self
1129            .caught_glide
1130            .take()
1131            .and_then(|end| end.take())
1132            .filter(|end| self.options.carry_caught_glide && end.outcome == TransitionOutcome::Cancelled)
1133            .map(|end| end.velocity);
1134        match finish {
1135            Finish::Cancel => {
1136                self.deltas = None;
1137                self.cancel_phase();
1138            }
1139            Finish::Stop => self.end_phase(None),
1140            Finish::Settle | Finish::Glide => {
1141                let release = if finish == Finish::Glide { self.tracking.release(now) } else { Release::default() };
1142                let momentum = release.into_momentum(caught_glide, &self.options);
1143                self.end_phase(Some(&momentum));
1144            }
1145        }
1146    }
1147
1148    /// Whether a press of `kind` at `position` is the second of a double tap.
1149    fn follows_tap(&self, kind: PointerKind, position: V2, now: f64) -> bool {
1150        self.last_tap.is_some_and(|(at, time, k)| {
1151            k == kind && now - time < self.options.tap_interval_ms && at.distance(position) < self.options.tap_tolerance
1152        })
1153    }
1154
1155    /// Zooms so the box from `a` to `b` fills the view, centred on its
1156    /// middle (GL JS `BoxZoomHandler`); a box without area does nothing.
1157    fn zoom_to_box(&mut self, a: V2, b: V2) {
1158        let size = (b - a).abs();
1159        if size.x < 1.0 || size.y < 1.0 {
1160            return;
1161        }
1162        let Some(center) = self.camera.lat_lng_for_pixel(((a + b) / 2.0).into()) else {
1163            return;
1164        };
1165        let viewport = V2::from(self.camera.viewport());
1166        let zoom = (viewport.x / size.x).min(viewport.y / size.y).log2();
1167        // The box is what the user sees now: setting the zoom stops a
1168        // running notch ease.
1169        let target = clamp_zoom(&self.camera, zoom_of(&self.camera) + zoom);
1170        let update = CameraUpdate {
1171            mode: CameraUpdateMode::Ease,
1172            camera: CameraOptions { center: Some(center), zoom: Some(target), ..Default::default() },
1173            animation: self.animation(BOX_EASE, EASE),
1174            phase: GesturePhase::None,
1175        };
1176        self.step_to(&update);
1177    }
1178
1179    /// Camera movement from a delta at `position`, in `amounts` per
1180    /// [`DELTA_PARTS`], of the parts that are on; nothing moves when none is.
1181    /// A continuous delta moves at once; a discrete one eases, retargeting
1182    /// the ease of each part it moves.
1183    fn delta(&mut self, position: V2, discrete: bool, mut amounts: [f64; DELTA_PARTS], now: f64) -> bool {
1184        let options = &self.options;
1185        let on = [
1186            options.pan.enabled,
1187            options.pan.enabled,
1188            options.zoom.enabled,
1189            options.bearing.enabled,
1190            options.pitch.enabled,
1191        ];
1192        for (amount, on) in amounts.iter_mut().zip(on) {
1193            if !on || !amount.is_finite() {
1194                *amount = 0.0;
1195            }
1196        }
1197        if amounts.iter().all(|amount| *amount == 0.0) {
1198            return false;
1199        }
1200        let (duration, max_zoom) = (options.step_duration_ms, options.max_step_zoom);
1201        let mut gesture =
1202            self.deltas.unwrap_or(DeltaGesture { anchor: position, idle_until: now, eases: [None; DELTA_PARTS] });
1203        gesture.anchor = position;
1204        gesture.idle_until = now + options.delta_idle_ms;
1205        self.begin();
1206        if discrete {
1207            for (part, amount) in amounts.into_iter().enumerate() {
1208                if amount == 0.0 {
1209                    continue;
1210                }
1211                let ease = gesture.eases[part];
1212                // The zoom stops at its range, as GL JS's target does: levels
1213                // past a limit would hold the zoom there once the input
1214                // turns back, until it undid them.
1215                gesture.eases[part] = Some(if part == DELTA_ZOOM {
1216                    StepEase::retarget(ease, amount, now, duration, |levels| within_zoom_range(&self.camera, levels))
1217                } else {
1218                    StepEase::retarget(ease, amount, now, duration, |amount| amount)
1219                });
1220            }
1221        } else {
1222            amounts[DELTA_ZOOM] = amounts[DELTA_ZOOM].clamp(-max_zoom, max_zoom);
1223            self.move_by(amounts, position);
1224        }
1225        self.deltas = Some(gesture);
1226        true
1227    }
1228
1229    /// Moves each part by its amount per [`DELTA_PARTS`] at once, holding
1230    /// the ground under `at`.
1231    fn move_by(&mut self, amounts: [f64; DELTA_PARTS], at: V2) {
1232        let [x, y, zoom, bearing, pitch] = amounts;
1233        if amounts.iter().all(|amount| *amount == 0.0) {
1234            return;
1235        }
1236        let delta = CameraDelta {
1237            offset: (x != 0.0 || y != 0.0).then(|| ScreenCoordinate::new(x, y)),
1238            scale: (zoom != 0.0).then(|| zoom.exp2()),
1239            bearing: (bearing != 0.0).then_some(bearing),
1240            pitch: (pitch != 0.0).then_some(pitch),
1241            anchor: Some(at.into()),
1242            ..CameraDelta::default()
1243        };
1244        self.update(&delta);
1245    }
1246
1247    /// A pinch the platform recognized: it zooms and turns around its center
1248    /// as a touch pinch does, and glides on when it ends.
1249    fn platform_pinch(&mut self, center: V2, scale: f64, rotation: f64, phase: PinchPhase, now: f64) -> bool {
1250        let pinching = matches!(self.mode, Mode::Platform);
1251        match phase {
1252            PinchPhase::End | PinchPhase::Cancel => {
1253                if !pinching {
1254                    return false;
1255                }
1256                let finish = if phase == PinchPhase::End { Finish::Glide } else { Finish::Cancel };
1257                self.finish(now, finish);
1258                return true;
1259            }
1260            PinchPhase::Begin | PinchPhase::Update if !pinching => {
1261                if !matches!(self.mode, Mode::Idle) {
1262                    return false;
1263                }
1264                // A pinch takes over from deltas, and stops their easing.
1265                self.deltas = None;
1266                self.begin();
1267                self.tracking.reset(now);
1268                self.mode = Mode::Platform;
1269            }
1270            PinchPhase::Begin | PinchPhase::Update => {}
1271        }
1272        let zoom = if scale > 0.0 && scale.is_finite() && self.options.zoom.enabled { scale.log2() } else { 0.0 };
1273        // Fingers turning clockwise turn the map clockwise.
1274        let bearing = if rotation.is_finite() && self.options.bearing.enabled { -rotation } else { 0.0 };
1275        if zoom == 0.0 && bearing == 0.0 {
1276            return true;
1277        }
1278        self.update(&CameraDelta {
1279            scale: (zoom != 0.0).then_some(scale),
1280            bearing: (bearing != 0.0).then_some(bearing),
1281            anchor: Some(center.into()),
1282            ..CameraDelta::default()
1283        });
1284        self.tracking.record(now, Step { zoom, bearing, around: Some(center), ..Step::default() });
1285        true
1286    }
1287}
1288
1289fn zoom_of(camera: &impl GestureCamera) -> f64 {
1290    camera.camera().zoom.unwrap_or(0.0)
1291}
1292
1293fn clamp_zoom(camera: &impl GestureCamera, zoom: f64) -> f64 {
1294    let (min, max) = camera.zoom_range();
1295    zoom.max(min).min(max)
1296}
1297
1298/// `levels` of zoom from the camera's zoom, cut at its zoom range. A zoom
1299/// outside the range may still move toward it.
1300fn within_zoom_range(camera: &impl GestureCamera, levels: f64) -> f64 {
1301    let zoom = zoom_of(camera);
1302    let (min, max) = camera.zoom_range();
1303    levels.clamp((min - zoom).min(0.0), (max - zoom).max(0.0))
1304}
1305
1306/// The clockwise angle from `a` to `b` on screen, in degrees.
1307fn angle(a: V2, b: V2) -> f64 {
1308    (a.x * b.y - a.y * b.x).atan2(a.dot(b)).to_degrees()
1309}
1310
1311#[cfg(test)]
1312#[path = "recognizer_test.rs"]
1313mod recognizer_test;