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    #[must_use]
521    pub fn options(&self) -> &GestureOptions {
522        &self.options
523    }
524
525    /// Takes effect with the next input, if the options are in range.
526    pub fn set_options(&mut self, options: GestureOptions) -> Result<(), InvalidGestureOptions> {
527        options.validate()?;
528        self.options = options;
529        Ok(())
530    }
531
532    /// A gesture is under way: hosts keep pointer capture and scrolling off.
533    #[cfg(test)]
534    #[must_use]
535    pub(crate) fn is_active(&self) -> bool {
536        !matches!(self.mode, Mode::Idle) || self.deltas.is_some()
537    }
538
539    /// The box a box-zoom drag zooms to, corner to corner in logical pixels,
540    /// while it is drawn: hosts show it.
541    #[must_use]
542    pub fn box_zoom(&self) -> Option<[ScreenCoordinate; 2]> {
543        match self.mode {
544            Mode::BoxZoom { origin } => Some([origin.into(), self.pointers.first()?.position.into()]),
545            _ => None,
546        }
547    }
548
549    /// When the recognizer next needs [`tick`](Self::tick): every display
550    /// frame while a delta eases or a gesture, its glide and its snap may
551    /// reach a notch; at a time for a pending long press or the end of idle
552    /// deltas; or `None`.
553    #[must_use]
554    pub fn next_tick(&self) -> Option<NextTick> {
555        let easing = self.deltas.is_some_and(|deltas| deltas.eases.iter().any(Option::is_some));
556        // A pointer held still moves nothing that could reach a notch.
557        let held_still = matches!(self.mode, Mode::Pressed { .. } | Mode::TapDrag { moved: false, .. });
558        if easing || (self.notch_watch.is_some() && !held_still) {
559            return Some(NextTick::Frame);
560        }
561        let long_press = match self.pointers[..] {
562            [pointer] if self.awaits_long_press() => Some(pointer.down_at + self.options.long_press_ms),
563            _ => None,
564        };
565        let idle = self.deltas.map(|deltas| deltas.idle_until);
566        long_press.into_iter().chain(idle).min_by(f64::total_cmp).map(NextTick::At)
567    }
568
569    /// Whether a press held still may yet become a long press.
570    fn awaits_long_press(&self) -> bool {
571        matches!(
572            self.mode,
573            Mode::Pressed { long_pressed: false } | Mode::TapDrag { moved: false, long_pressed: false, .. }
574        )
575    }
576
577    /// Taps, long presses and notches recognized since the last call.
578    pub fn take_events(&mut self) -> Vec<GestureEvent> {
579        std::mem::take(&mut self.events)
580    }
581
582    /// A host's own command to an absolute camera, such as resetting the
583    /// bearing, through the recognizer: it stops the recognizer's eases of the
584    /// parts it sets, which would otherwise take them back, and is an update
585    /// of a gesture under way or a gesture of its own. `update.phase` is
586    /// ignored.
587    pub fn step_to(&mut self, update: &CameraUpdate) {
588        let set = &update.camera;
589        let center = set.center.is_some();
590        self.stop_step_eases([center, center, set.zoom.is_some(), set.bearing.is_some(), set.pitch.is_some()]);
591        // Outside a gesture it takes over from the last gesture's glide,
592        // whose notches end: host commands report none.
593        if !self.begun {
594            self.notch_watch = None;
595        }
596        let phase = if self.begun { GesturePhase::Update } else { GesturePhase::End };
597        self.camera.update_camera(&CameraUpdate { phase, ..*update });
598    }
599
600    /// Times long presses, steps the eases of discrete deltas, ends deltas
601    /// once they idle, and samples the camera for notches, at `now` on the
602    /// inputs' clock. Call it when [`next_tick`](Self::next_tick) says, which
603    /// it also returns; a call at any other time does no harm.
604    pub fn tick(&mut self, now: f64) -> Option<NextTick> {
605        self.long_press(now);
606        self.delta_frame(now);
607        if let Some(watch) = &mut self.notch_watch {
608            watch.sample(&self.camera.camera(), &self.options, now, &mut self.events);
609            // The gesture ended, and so did its glide and snap: its command
610            // has ended (a gesture cancelled outright has none).
611            if !self.begun && self.release_end.as_ref().is_none_or(PendingEnd::has_ended) {
612                self.notch_watch = None;
613            }
614        }
615        self.next_tick()
616    }
617
618    /// Reports a press held still for the long-press time, once.
619    fn long_press(&mut self, now: f64) {
620        if self.awaits_long_press()
621            && let [pointer] = self.pointers[..]
622            && now - pointer.down_at >= self.options.long_press_ms
623        {
624            match &mut self.mode {
625                Mode::Pressed { long_pressed } | Mode::TapDrag { long_pressed, .. } => *long_pressed = true,
626                _ => {}
627            }
628            self.last_tap = None;
629            self.events.push(GestureEvent::LongPress { id: pointer.id, position: pointer.position.into() });
630        }
631    }
632
633    /// The deltas' part of [`Self::frame`].
634    fn delta_frame(&mut self, now: f64) -> bool {
635        let Some(mut gesture) = self.deltas else {
636            return false;
637        };
638        let duration = self.options.step_duration_ms;
639        let max_zoom = self.options.max_step_zoom;
640        let mut amounts = [0.0; DELTA_PARTS];
641        for (part, slot) in gesture.eases.iter_mut().enumerate() {
642            let Some(mut ease) = *slot else { continue };
643            let mut amount = ease.value(now, duration) - ease.applied;
644            if part == DELTA_ZOOM {
645                amount = amount.clamp(-max_zoom, max_zoom);
646            }
647            ease.applied += amount;
648            amounts[part] = amount;
649            let done = ease.progress(now, duration) >= 1.0 && (ease.distance - ease.applied).abs() <= STEP_EASE_DONE;
650            *slot = (!done).then_some(ease);
651            if done {
652                gesture.idle_until = gesture.idle_until.max(now + self.options.delta_idle_ms);
653            }
654        }
655        // Eases that outlive the pointer gesture they joined carry on as a
656        // gesture of their own, which keeps the release's glide.
657        if !self.begun && amounts.iter().any(|amount| *amount != 0.0) {
658            self.begun = true;
659            self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..CameraDelta::default() });
660        }
661        self.move_by(amounts, gesture.anchor);
662        if gesture.eases.iter().all(Option::is_none) && now >= gesture.idle_until {
663            self.deltas = None;
664            if matches!(self.mode, Mode::Idle) {
665                self.end_phase(None);
666            }
667            return false;
668        }
669        self.deltas = Some(gesture);
670        true
671    }
672
673    /// Handles one input at host time `now`, in milliseconds. Returns whether
674    /// the map used it, so hosts can stop the platform's default.
675    pub fn handle(&mut self, input: Input, now: f64) -> bool {
676        match input {
677            Input::PointerDown { id, kind, position, modes } => {
678                let position = position.into();
679                self.down(Pointer { id, kind, position, down: position, down_at: now, modes })
680            }
681            Input::PointerMove { id, position } => self.moved(id, position.into(), now),
682            Input::PointerUp { id, position } => self.up(id, Some(position.into()), now),
683            Input::PointerCancel { id } => self.up(id, None, now),
684            // Modes only change what later drags do: the platform's default
685            // for the keys stands.
686            Input::Modes(modes) => {
687                self.modes = modes;
688                false
689            }
690            Input::Delta { position, discrete, pan, zoom, bearing, pitch } => {
691                self.delta(position.into(), discrete, [pan.x, pan.y, zoom, bearing, pitch], now)
692            }
693            Input::Pinch { center, scale, rotation, phase } => {
694                self.platform_pinch(center.into(), scale, rotation, phase, now)
695            }
696        }
697    }
698
699    /// The animation options of the recognizer's eased steps.
700    fn animation(&self, duration: Duration, easing: UnitBezier) -> AnimationOptions {
701        AnimationOptions {
702            duration: Some(duration),
703            easing: Some(easing),
704            transition_id: Some(self.options.transition_id),
705            ..AnimationOptions::default()
706        }
707    }
708
709    /// Begins the gesture, unless it has begun: the `Begin` phase stops the
710    /// camera's animations, as GL JS and the MapLibre Native SDKs do on a
711    /// press. Without `interrupt_animations`, it stops only the recognizer's
712    /// own, and begins with `Update`, which keeps the others. A glide that
713    /// this stops is caught: the release may carry its speed, which the
714    /// glide's end reports.
715    fn begin(&mut self) {
716        if self.begun {
717            return;
718        }
719        self.begun = true;
720        // Only a glide still running can be caught: one that has ended, as
721        // when a command cancelled it, carries nothing.
722        self.caught_glide = self.release_end.take().filter(|end| end.take().is_none());
723        let notches = [&self.options.zoom, &self.options.bearing, &self.options.pitch]
724            .iter()
725            .any(|part| part.enabled && !part.notches.is_empty());
726        self.notch_watch = notches.then(|| NotchWatch::new(&self.camera.camera(), &self.options));
727        let phase = if self.options.interrupt_animations {
728            GesturePhase::Begin
729        } else {
730            self.camera.cancel_transitions_with_id(self.options.transition_id);
731            GesturePhase::Update
732        };
733        self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
734    }
735
736    /// One step of the gesture, at once.
737    fn update(&mut self, delta: &CameraDelta) {
738        self.begin();
739        self.camera.apply_camera_delta(&CameraDelta { phase: GesturePhase::Update, ..*delta });
740    }
741
742    /// Ends the gesture, with the momentum it continues with: the gesture
743    /// stays in progress until the momentum ends.
744    fn end_phase(&mut self, momentum: Option<&CameraMomentum>) {
745        if !std::mem::replace(&mut self.begun, false) {
746            return;
747        }
748        let animation =
749            AnimationOptions { transition_id: Some(self.options.transition_id), ..AnimationOptions::default() };
750        let phase = GesturePhase::End;
751        let delta = CameraDelta { momentum: momentum.copied(), animation, phase, ..CameraDelta::default() };
752        let end = self.camera.release(&delta);
753        // The end of a release that may glide, which a press may catch; a
754        // gesture that ends without momentum leaves the last one's.
755        if momentum.is_some() {
756            self.release_end = Some(end);
757        }
758    }
759
760    /// The platform cancelled the gesture: it ends, and the `Cancel` phase
761    /// stops the camera's animations (only the recognizer's own, without
762    /// `interrupt_animations`).
763    fn cancel_phase(&mut self) {
764        self.notch_watch = None;
765        if !std::mem::replace(&mut self.begun, false) {
766            return;
767        }
768        let phase = if self.options.interrupt_animations {
769            GesturePhase::Cancel
770        } else {
771            self.camera.cancel_transitions_with_id(self.options.transition_id);
772            GesturePhase::End
773        };
774        self.camera.apply_camera_delta(&CameraDelta { phase, ..CameraDelta::default() });
775    }
776
777    /// Stops the step eases of the parts in `parts` ([`DELTA_PARTS`]).
778    fn stop_step_eases(&mut self, parts: [bool; DELTA_PARTS]) {
779        if let Some(gesture) = self.deltas.as_mut() {
780            for (ease, stop) in gesture.eases.iter_mut().zip(parts) {
781                if stop {
782                    *ease = None;
783                }
784            }
785        }
786    }
787
788    /// A press of `pointer`, at its position and at its `down_at` time.
789    fn down(&mut self, pointer: Pointer) -> bool {
790        let Pointer { id, kind, position, down_at: now, .. } = pointer;
791        if self.pointers.iter().any(|p| p.id == id) {
792            return false;
793        }
794        let touch = kind == PointerKind::Touch;
795        if !touch && !self.pointers.is_empty() {
796            return false;
797        }
798        if matches!(self.mode, Mode::Platform) {
799            // A press during a platform pinch takes over from it.
800            self.finish(now, Finish::Cancel);
801        }
802        self.pointers.push(pointer);
803        // A press takes over from deltas, and stops their easing.
804        self.deltas = None;
805        self.begin();
806        match (self.mode, self.pointers.len()) {
807            (Mode::Idle, 1) => {
808                self.mode = if touch && self.follows_tap(kind, position, now) {
809                    Mode::TapDrag { origin: position, moved: false, long_pressed: false }
810                } else {
811                    Mode::Pressed { long_pressed: false }
812                };
813                self.tracking.reset(now);
814            }
815            (Mode::Pressed { .. } | Mode::Pan | Mode::TapDrag { .. }, 2) if touch => {
816                let [a, b] = [self.pointers[0].position, self.pointers[1].position];
817                let vector = b - a;
818                self.mode = Mode::Pinch(Pinch {
819                    last: [a, b],
820                    start_distance: vector.length(),
821                    start_vector: vector,
822                    min_diameter: vector.length(),
823                    zooming: false,
824                    rotating: false,
825                    // Fingers above one another can't tilt.
826                    pitch: (!self.options.pitch.enabled || vector.y.abs() > vector.x.abs()).then_some(false),
827                    single_since: None,
828                    panning: false,
829                    tap: now - self.pointers[0].down_at < self.options.tap_interval_ms
830                        && matches!(self.mode, Mode::Pressed { .. }),
831                });
832                self.tracking.record(now, Step::default());
833            }
834            _ => self.mode = Mode::Ignored,
835        }
836        true
837    }
838
839    fn moved(&mut self, id: u32, position: V2, now: f64) -> bool {
840        let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
841            return false;
842        };
843        let last = self.pointers[index].position;
844        self.pointers[index].position = position;
845        match &mut self.mode {
846            Mode::Pressed { .. } => {
847                let pointer = self.pointers[index];
848                let down = pointer.down;
849                if position.distance(down) > self.options.click_tolerance {
850                    // The drag reads its modes as it starts.
851                    let modes = pointer.modes | self.modes;
852                    self.mode = if modes.rotate {
853                        Mode::Rotate
854                    } else if modes.box_zoom && self.options.zoom.enabled {
855                        Mode::BoxZoom { origin: down }
856                    } else {
857                        Mode::Pan
858                    };
859                    // The jump past the click tolerance counts toward the
860                    // release: it is motion over the time since the press.
861                    // Compose resets its tracker here, which protects its
862                    // least-squares fit; an average needs no protecting, and
863                    // dropping the jump loses the start of a short flick.
864                    self.drag_step(down, position, now);
865                }
866            }
867            Mode::Pan | Mode::Rotate => self.drag_step(last, position, now),
868            Mode::TapDrag { origin, moved, .. } => {
869                let (origin, dy) = (*origin, position.y - last.y);
870                *moved = *moved || position.distance(origin) > self.options.click_tolerance;
871                if *moved && self.options.zoom.enabled {
872                    let zoom = dy * self.options.tap_drag_zoom;
873                    let delta =
874                        CameraDelta { scale: Some(zoom.exp2()), anchor: Some(origin.into()), ..CameraDelta::default() };
875                    self.update(&delta);
876                    self.tracking.record(now, Step { zoom, around: Some(origin), ..Step::default() });
877                }
878            }
879            Mode::Pinch(_) if self.pointers.len() < 2 => {
880                // The other finger of a two-finger tap lifted, and this one
881                // moves on: a pan.
882                self.mode = Mode::Pan;
883                self.drag_step(last, position, now);
884            }
885            Mode::Pinch(pinch) => {
886                if index > 1 {
887                    return true;
888                }
889                let mut pinch = *pinch;
890                let points = [self.pointers[0].position, self.pointers[1].position];
891                self.pinch_step(&mut pinch, points, now);
892                self.mode = Mode::Pinch(pinch);
893            }
894            Mode::BoxZoom { .. } | Mode::Idle | Mode::Ignored | Mode::Platform => {}
895        }
896        true
897    }
898
899    /// One pan or mouse-rotate step from `from` to `to`.
900    fn drag_step(&mut self, from: V2, to: V2, now: f64) {
901        let delta = to - from;
902        match self.mode {
903            Mode::Rotate => {
904                let bearing = if self.options.bearing.enabled { delta.x * self.options.drag_rotate } else { 0.0 };
905                let pitch = if self.options.pitch.enabled { -delta.y * self.options.drag_pitch } else { 0.0 };
906                let step = CameraDelta { bearing: Some(bearing), pitch: Some(pitch), ..CameraDelta::default() };
907                self.update(&step);
908                self.tracking.record(now, Step { bearing, pitch, ..Step::default() });
909            }
910            Mode::BoxZoom { .. } => {}
911            _ if !self.options.pan.enabled => {}
912            _ => {
913                // The pointer is the point the drag holds, which the globe
914                // turns to keep under it.
915                let step =
916                    CameraDelta { offset: Some(delta.into()), anchor: Some(to.into()), ..CameraDelta::default() };
917                self.update(&step);
918                self.tracking.record(now, Step { pan: delta, ..Step::default() });
919            }
920        }
921    }
922
923    fn pinch_step(&mut self, pinch: &mut Pinch, points: [V2; 2], now: f64) {
924        let [a, b] = points;
925        let [la, lb] = pinch.last;
926        let (va, vb) = (a - la, b - lb);
927        let vector = b - a;
928        let tap_tolerance = self.options.tap_tolerance;
929        if pinch.tap
930            && (a.distance(self.pointers[0].down) > tap_tolerance || b.distance(self.pointers[1].down) > tap_tolerance)
931        {
932            pinch.tap = false;
933        }
934        // Two fingers moving up or down together tilt, and do nothing else
935        // (GL JS `TwoFingersTouchPitchHandler`).
936        if pinch.pitch.is_none() {
937            let (moved_a, moved_b) = (va.length() >= PITCH_DECIDE_PX, vb.length() >= PITCH_DECIDE_PX);
938            if moved_a && moved_b {
939                let vertical = |v: V2| v.y.abs() > v.x.abs();
940                pinch.pitch = Some(vertical(va) && vertical(vb) && (va.y > 0.0) == (vb.y > 0.0));
941            } else if moved_a || moved_b {
942                let since = *pinch.single_since.get_or_insert(now);
943                if now - since >= PITCH_DECIDE_MS {
944                    pinch.pitch = Some(false);
945                }
946            }
947            if pinch.pitch.is_none() {
948                return;
949            }
950        }
951        if pinch.pitch == Some(true) {
952            let pitch = f64::midpoint(va.y, vb.y) * -self.options.drag_pitch;
953            self.update(&CameraDelta { pitch: Some(pitch), ..CameraDelta::default() });
954            pinch.last = points;
955            pinch.tap = false;
956            self.tracking.record(now, Step { pitch, ..Step::default() });
957            return;
958        }
959        let (mid, last_mid) = ((a + b) / 2.0, (la + lb) / 2.0);
960        let distance = vector.length();
961        let last_distance = (lb - la).length();
962        pinch.min_diameter = pinch.min_diameter.min(distance);
963        if !pinch.zooming
964            && self.options.zoom.enabled
965            && (distance / pinch.start_distance).log2().abs() >= self.options.pinch_zoom_threshold
966        {
967            pinch.zooming = true;
968        }
969        if !pinch.rotating && self.options.bearing.enabled {
970            let threshold = self.options.rotate_threshold / (std::f64::consts::PI * pinch.min_diameter) * 360.0;
971            if angle(pinch.start_vector, vector).abs() >= threshold {
972                pinch.rotating = true;
973            }
974        }
975        if !pinch.panning
976            && self.options.pan.enabled
977            && (mid - (self.pointers[0].down + self.pointers[1].down) / 2.0).length() > self.options.click_tolerance
978        {
979            pinch.panning = true;
980        }
981        let pan = if pinch.panning { mid - last_mid } else { V2::ZERO };
982        let zoom = if pinch.zooming && last_distance > 0.0 { (distance / last_distance).log2() } else { 0.0 };
983        // Fingers turning clockwise turn the map clockwise.
984        let bearing = if pinch.rotating { -angle(lb - la, vector) } else { 0.0 };
985        pinch.last = points;
986        if pan == V2::ZERO && zoom == 0.0 && bearing == 0.0 {
987            return;
988        }
989        // The pan applies first, holding the fingers' middle, then the zoom
990        // and turn hold it in place.
991        let anchored = zoom != 0.0 || bearing != 0.0 || pan != V2::ZERO;
992        self.update(&CameraDelta {
993            offset: (pan != V2::ZERO).then_some(pan.into()),
994            scale: (zoom != 0.0).then_some(zoom.exp2()),
995            bearing: (bearing != 0.0).then_some(bearing),
996            anchor: anchored.then_some(mid.into()),
997            ..CameraDelta::default()
998        });
999        pinch.tap = false;
1000        self.tracking.record(now, Step { pan, zoom, bearing, around: Some(mid), ..Step::default() });
1001    }
1002
1003    fn up(&mut self, id: u32, position: Option<V2>, now: f64) -> bool {
1004        let Some(index) = self.pointers.iter().position(|p| p.id == id) else {
1005            return false;
1006        };
1007        let pointer = self.pointers.remove(index);
1008        let cancelled = position.is_none();
1009        // A cancelled pointer cancels its whole gesture, and the pointers
1010        // still down make no tap and no release until they all lift.
1011        if cancelled && !self.pointers.is_empty() {
1012            self.finish(now, Finish::Cancel);
1013            self.mode = Mode::Ignored;
1014            return true;
1015        }
1016        // A cancelled pointer finishes its gesture with `Cancel`, whatever
1017        // its release would have been.
1018        let unless_cancelled = |finish: Finish| if cancelled { Finish::Cancel } else { finish };
1019        match self.mode {
1020            Mode::Pinch(pinch) => {
1021                if !self.pointers.is_empty() {
1022                    // Lifting one finger continues as a one-finger pan;
1023                    // lifting the second ends a two-finger tap.
1024                    let tap = pinch.tap && now - pointer.down_at < self.options.tap_interval_ms;
1025                    self.mode = if tap {
1026                        Mode::Pinch(pinch)
1027                    } else {
1028                        self.tracking.stage(now);
1029                        Mode::Pan
1030                    };
1031                    return true;
1032                }
1033                self.finish(now, unless_cancelled(if pinch.tap { Finish::Settle } else { Finish::Glide }));
1034                if pinch.tap && !cancelled {
1035                    let mid = (pinch.last[0] + pinch.last[1]) / 2.0;
1036                    self.events.push(GestureEvent::TwoFingerTap { position: mid.into() });
1037                    self.tap_zoom(mid, self.options.two_finger_tap_zoom, now);
1038                }
1039            }
1040            Mode::Pan if !self.pointers.is_empty() => {}
1041            Mode::Pressed { long_pressed } => {
1042                if self.pointers.is_empty() {
1043                    self.finish(now, unless_cancelled(Finish::Settle));
1044                    // A long press that no frame timed reports as it lifts.
1045                    if !cancelled && !long_pressed && now - pointer.down_at >= self.options.long_press_ms {
1046                        let position = pointer.position.into();
1047                        self.events.push(GestureEvent::LongPress { id: pointer.id, position });
1048                        self.last_tap = None;
1049                    } else if !cancelled && !long_pressed {
1050                        self.tap(pointer, now);
1051                    }
1052                }
1053            }
1054            Mode::BoxZoom { origin } => {
1055                self.finish(now, unless_cancelled(Finish::Stop));
1056                if !cancelled {
1057                    self.zoom_to_box(origin, position.unwrap_or(pointer.position));
1058                }
1059            }
1060            Mode::TapDrag { origin, moved, long_pressed } => {
1061                if self.pointers.is_empty() {
1062                    self.last_tap = None;
1063                    self.finish(now, unless_cancelled(if moved { Finish::Glide } else { Finish::Settle }));
1064                    if !moved && !cancelled && !long_pressed {
1065                        let (id, position) = (pointer.id, origin.into());
1066                        // A long press that no frame timed reports as it lifts.
1067                        if now - pointer.down_at >= self.options.long_press_ms {
1068                            self.events.push(GestureEvent::LongPress { id, position });
1069                        } else {
1070                            self.events
1071                                .extend([GestureEvent::Tap { id, position }, GestureEvent::DoubleTap { id, position }]);
1072                            self.double_tap_zoom(pointer, origin, now);
1073                        }
1074                    }
1075                }
1076            }
1077            Mode::Pan | Mode::Rotate => {
1078                self.finish(now, unless_cancelled(Finish::Glide));
1079            }
1080            Mode::Ignored | Mode::Idle | Mode::Platform => {
1081                if self.pointers.is_empty() {
1082                    self.finish(now, unless_cancelled(Finish::Stop));
1083                }
1084            }
1085        }
1086        true
1087    }
1088
1089    /// A press released without moving before a long press: a tap, perhaps
1090    /// the second of a double tap.
1091    fn tap(&mut self, pointer: Pointer, now: f64) {
1092        let (id, position) = (pointer.id, pointer.position);
1093        self.events.push(GestureEvent::Tap { id, position: position.into() });
1094        if self.follows_tap(pointer.kind, position, now) {
1095            self.last_tap = None;
1096            self.events.push(GestureEvent::DoubleTap { id, position: position.into() });
1097            self.double_tap_zoom(pointer, position, now);
1098        } else {
1099            self.last_tap = Some((position, now, pointer.kind));
1100        }
1101    }
1102
1103    /// A double tap's zoom at `at`: in, or out with the zoom-out mode.
1104    fn double_tap_zoom(&mut self, pointer: Pointer, at: V2, now: f64) {
1105        let levels = self.options.double_tap_zoom;
1106        let out = (pointer.modes | self.modes).zoom_out;
1107        self.tap_zoom(at, if out { -levels } else { levels }, now);
1108    }
1109
1110    /// Zooms `levels` around `at` as a discrete delta does, unless the zoom
1111    /// is off or `levels` is 0.
1112    fn tap_zoom(&mut self, at: V2, levels: f64, now: f64) {
1113        if levels != 0.0 {
1114            self.delta(at, true, [0.0, 0.0, levels, 0.0, 0.0], now);
1115        }
1116    }
1117
1118    /// Ends the gesture with every pointer up: a release glides on with the
1119    /// speed its last moves had, and settles what it changed.
1120    fn finish(&mut self, now: f64, finish: Finish) {
1121        self.mode = Mode::Idle;
1122        let caught_glide = self
1123            .caught_glide
1124            .take()
1125            .and_then(|end| end.take())
1126            .filter(|end| self.options.carry_caught_glide && end.outcome == TransitionOutcome::Cancelled)
1127            .map(|end| end.velocity);
1128        match finish {
1129            Finish::Cancel => {
1130                self.deltas = None;
1131                self.cancel_phase();
1132            }
1133            Finish::Stop => self.end_phase(None),
1134            Finish::Settle | Finish::Glide => {
1135                let release = if finish == Finish::Glide { self.tracking.release(now) } else { Release::default() };
1136                let momentum = release.into_momentum(caught_glide, &self.options);
1137                self.end_phase(Some(&momentum));
1138            }
1139        }
1140    }
1141
1142    /// Whether a press of `kind` at `position` is the second of a double tap.
1143    fn follows_tap(&self, kind: PointerKind, position: V2, now: f64) -> bool {
1144        self.last_tap.is_some_and(|(at, time, k)| {
1145            k == kind && now - time < self.options.tap_interval_ms && at.distance(position) < self.options.tap_tolerance
1146        })
1147    }
1148
1149    /// Zooms so the box from `a` to `b` fills the view, centred on its
1150    /// middle (GL JS `BoxZoomHandler`); a box without area does nothing.
1151    fn zoom_to_box(&mut self, a: V2, b: V2) {
1152        let size = (b - a).abs();
1153        if size.x < 1.0 || size.y < 1.0 {
1154            return;
1155        }
1156        let Some(center) = self.camera.lat_lng_for_pixel(((a + b) / 2.0).into()) else {
1157            return;
1158        };
1159        let viewport = V2::from(self.camera.viewport());
1160        let zoom = (viewport.x / size.x).min(viewport.y / size.y).log2();
1161        // The box is what the user sees now: setting the zoom stops a
1162        // running notch ease.
1163        let target = clamp_zoom(&self.camera, zoom_of(&self.camera) + zoom);
1164        let update = CameraUpdate {
1165            mode: CameraUpdateMode::Ease,
1166            camera: CameraOptions { center: Some(center), zoom: Some(target), ..Default::default() },
1167            animation: self.animation(BOX_EASE, EASE),
1168            phase: GesturePhase::None,
1169        };
1170        self.step_to(&update);
1171    }
1172
1173    /// Camera movement from a delta at `position`, in `amounts` per
1174    /// [`DELTA_PARTS`], of the parts that are on; nothing moves when none is.
1175    /// A continuous delta moves at once; a discrete one eases, retargeting
1176    /// the ease of each part it moves.
1177    fn delta(&mut self, position: V2, discrete: bool, mut amounts: [f64; DELTA_PARTS], now: f64) -> bool {
1178        let options = &self.options;
1179        let on = [
1180            options.pan.enabled,
1181            options.pan.enabled,
1182            options.zoom.enabled,
1183            options.bearing.enabled,
1184            options.pitch.enabled,
1185        ];
1186        for (amount, on) in amounts.iter_mut().zip(on) {
1187            if !on || !amount.is_finite() {
1188                *amount = 0.0;
1189            }
1190        }
1191        if amounts.iter().all(|amount| *amount == 0.0) {
1192            return false;
1193        }
1194        let (duration, max_zoom) = (options.step_duration_ms, options.max_step_zoom);
1195        let mut gesture =
1196            self.deltas.unwrap_or(DeltaGesture { anchor: position, idle_until: now, eases: [None; DELTA_PARTS] });
1197        gesture.anchor = position;
1198        gesture.idle_until = now + options.delta_idle_ms;
1199        self.begin();
1200        if discrete {
1201            for (part, amount) in amounts.into_iter().enumerate() {
1202                if amount == 0.0 {
1203                    continue;
1204                }
1205                let ease = gesture.eases[part];
1206                // The zoom stops at its range, as GL JS's target does: levels
1207                // past a limit would hold the zoom there once the input
1208                // turns back, until it undid them.
1209                gesture.eases[part] = Some(if part == DELTA_ZOOM {
1210                    StepEase::retarget(ease, amount, now, duration, |levels| within_zoom_range(&self.camera, levels))
1211                } else {
1212                    StepEase::retarget(ease, amount, now, duration, |amount| amount)
1213                });
1214            }
1215        } else {
1216            amounts[DELTA_ZOOM] = amounts[DELTA_ZOOM].clamp(-max_zoom, max_zoom);
1217            self.move_by(amounts, position);
1218        }
1219        self.deltas = Some(gesture);
1220        true
1221    }
1222
1223    /// Moves each part by its amount per [`DELTA_PARTS`] at once, holding
1224    /// the ground under `at`.
1225    fn move_by(&mut self, amounts: [f64; DELTA_PARTS], at: V2) {
1226        let [x, y, zoom, bearing, pitch] = amounts;
1227        if amounts.iter().all(|amount| *amount == 0.0) {
1228            return;
1229        }
1230        let delta = CameraDelta {
1231            offset: (x != 0.0 || y != 0.0).then(|| ScreenCoordinate::new(x, y)),
1232            scale: (zoom != 0.0).then(|| zoom.exp2()),
1233            bearing: (bearing != 0.0).then_some(bearing),
1234            pitch: (pitch != 0.0).then_some(pitch),
1235            anchor: Some(at.into()),
1236            ..CameraDelta::default()
1237        };
1238        self.update(&delta);
1239    }
1240
1241    /// A pinch the platform recognized: it zooms and turns around its center
1242    /// as a touch pinch does, and glides on when it ends.
1243    fn platform_pinch(&mut self, center: V2, scale: f64, rotation: f64, phase: PinchPhase, now: f64) -> bool {
1244        let pinching = matches!(self.mode, Mode::Platform);
1245        match phase {
1246            PinchPhase::End | PinchPhase::Cancel => {
1247                if !pinching {
1248                    return false;
1249                }
1250                let finish = if phase == PinchPhase::End { Finish::Glide } else { Finish::Cancel };
1251                self.finish(now, finish);
1252                return true;
1253            }
1254            PinchPhase::Begin | PinchPhase::Update if !pinching => {
1255                if !matches!(self.mode, Mode::Idle) {
1256                    return false;
1257                }
1258                // A pinch takes over from deltas, and stops their easing.
1259                self.deltas = None;
1260                self.begin();
1261                self.tracking.reset(now);
1262                self.mode = Mode::Platform;
1263            }
1264            PinchPhase::Begin | PinchPhase::Update => {}
1265        }
1266        let zoom = if scale > 0.0 && scale.is_finite() && self.options.zoom.enabled { scale.log2() } else { 0.0 };
1267        // Fingers turning clockwise turn the map clockwise.
1268        let bearing = if rotation.is_finite() && self.options.bearing.enabled { -rotation } else { 0.0 };
1269        if zoom == 0.0 && bearing == 0.0 {
1270            return true;
1271        }
1272        self.update(&CameraDelta {
1273            scale: (zoom != 0.0).then_some(scale),
1274            bearing: (bearing != 0.0).then_some(bearing),
1275            anchor: Some(center.into()),
1276            ..CameraDelta::default()
1277        });
1278        self.tracking.record(now, Step { zoom, bearing, around: Some(center), ..Step::default() });
1279        true
1280    }
1281}
1282
1283fn zoom_of(camera: &impl GestureCamera) -> f64 {
1284    camera.camera().zoom.unwrap_or(0.0)
1285}
1286
1287fn clamp_zoom(camera: &impl GestureCamera, zoom: f64) -> f64 {
1288    let (min, max) = camera.zoom_range();
1289    zoom.max(min).min(max)
1290}
1291
1292/// `levels` of zoom from the camera's zoom, cut at its zoom range. A zoom
1293/// outside the range may still move toward it.
1294fn within_zoom_range(camera: &impl GestureCamera, levels: f64) -> f64 {
1295    let zoom = zoom_of(camera);
1296    let (min, max) = camera.zoom_range();
1297    levels.clamp((min - zoom).min(0.0), (max - zoom).max(0.0))
1298}
1299
1300/// The clockwise angle from `a` to `b` on screen, in degrees.
1301fn angle(a: V2, b: V2) -> f64 {
1302    (a.x * b.y - a.y * b.x).atan2(a.dot(b)).to_degrees()
1303}
1304
1305#[cfg(test)]
1306#[path = "recognizer_test.rs"]
1307mod recognizer_test;