Skip to main content

mln_map/transform/
gesture.rs

1//! Gestures: camera deltas and updates relative to where the camera is.
2
3use mln_map_types::{
4    AnimationOptions, CameraDelta, CameraError, CameraMomentum, CameraOptions, CameraUpdate, CameraUpdateMode,
5    GesturePhase, TransitionOutcome,
6};
7
8use super::{BEARING, CameraCommandId, PITCH, Transform, TransformEvent, ZOOM};
9use crate::map_event::{CameraChange, CameraChangeMode, CameraChangeSource};
10
11/// The gesture that camera deltas and updates with a phase make.
12#[derive(Clone, Copy, Debug, Default)]
13pub(super) struct GestureState {
14    /// Between its first `Begin` or `Update` and its `End` or `Cancel`.
15    pub(super) active: bool,
16    /// Counts gestures, so that an earlier gesture's momentum doesn't end a
17    /// later gesture.
18    serial: u64,
19    /// The fields the gesture changed (`ZOOM`, `BEARING`, `PITCH`), which
20    /// alone may settle.
21    changed: u16,
22    /// The altitude the gesture holds over terrain, once it took it
23    /// (see `terrain`).
24    pub(super) altitude: Option<f64>,
25}
26
27impl GestureState {
28    /// Records the fields a gesture's change moves.
29    fn change(&mut self, zoom: bool, bearing: bool, pitch: bool) {
30        self.changed |=
31            (if zoom { ZOOM } else { 0 }) | (if bearing { BEARING } else { 0 }) | (if pitch { PITCH } else { 0 });
32    }
33
34    /// Drops the snaps of the parts the gesture didn't change: only what it
35    /// changed settles.
36    fn mask_snaps(&self, momentum: &mut CameraMomentum) {
37        for (part, field) in
38            [(&mut momentum.zoom, ZOOM), (&mut momentum.bearing, BEARING), (&mut momentum.pitch, PITCH)]
39        {
40            if self.changed & field == 0 {
41                part.snap = None;
42            }
43        }
44    }
45}
46
47fn gesture_source(phase: GesturePhase) -> CameraChangeSource {
48    if phase == GesturePhase::None { CameraChangeSource::Command } else { CameraChangeSource::Gesture }
49}
50
51impl Transform {
52    /// Moves the camera relative to where it is, as a gesture does
53    /// (the C API's `mln_map_apply_camera_delta`). See
54    /// [`CameraDelta`].
55    pub fn apply_camera_delta(&mut self, delta: &CameraDelta) -> Result<CameraCommandId, CameraError> {
56        delta.validate()?;
57        Ok(self.command(|transform| transform.apply_camera_delta_now(delta)))
58    }
59
60    fn apply_camera_delta_now(&mut self, delta: &CameraDelta) {
61        let source = gesture_source(delta.phase);
62        let pans = delta.offset.is_some();
63        let eases = delta.scale.is_some() || delta.bearing.is_some() || delta.pitch.is_some();
64        // With momentum, the command's end is the momentum's, and the delta's
65        // own changes, which can't animate, apply before it starts.
66        // Otherwise the pan and the ease end the command together.
67        let parts = match delta.momentum {
68            Some(_) => AnimationOptions::default(),
69            None => delta.animation,
70        };
71        self.silent = delta.momentum.is_some();
72        self.join_ends(u32::from(pans) + u32::from(eases));
73        self.gesture_phase_before(delta.phase);
74        if delta.phase != GesturePhase::None {
75            self.gesture.change(
76                delta.scale.is_some_and(|scale| scale != 1.0),
77                delta.bearing.is_some_and(|bearing| bearing != 0.0),
78                delta.pitch.is_some_and(|pitch| pitch != 0.0),
79            );
80        }
81        self.with_source(source, |transform| {
82            if let Some(offset) = delta.offset {
83                // Validation keeps the offset finite, so it has a LatLng. The
84                // anchor is the point the drag holds, which the globe keeps
85                // under it.
86                let _ = transform.move_by_with_anchor(&offset, delta.anchor, &parts);
87            }
88            if eases {
89                let current = transform.camera_options(None);
90                let target = CameraOptions {
91                    zoom: delta.scale.map(|scale| current.zoom.unwrap_or(0.0) + scale.log2()),
92                    bearing: delta.bearing.map(|bearing| current.bearing.unwrap_or(0.0) + bearing),
93                    pitch: delta.pitch.map(|pitch| current.pitch.unwrap_or(0.0) + pitch),
94                    anchor: delta.anchor,
95                    ..CameraOptions::default()
96                };
97                transform.ease_to(&target, &parts);
98            }
99        });
100        self.silent = false;
101        match delta.momentum {
102            Some(mut momentum) => {
103                self.gesture.mask_snaps(&mut momentum);
104                // The gesture ends as its momentum starts, rather than in
105                // `gesture_phase_after`, so that a momentum with nothing to
106                // move, which ends at once, ends it too.
107                self.gesture.active = false;
108                let serial = self.gesture.serial;
109                self.with_source(CameraChangeSource::Momentum, |transform| {
110                    transform.start_momentum_now(&momentum, &delta.animation, Some(serial));
111                });
112            }
113            None if !pans && !eases => self.end_unstarted(&delta.animation, TransitionOutcome::Completed),
114            None => {}
115        }
116        self.gesture_phase_after(delta.phase, delta.momentum.is_some());
117    }
118
119    /// Moves the camera to absolute values, as a command or a gesture
120    /// (the C API's `mln_map_update_camera`). See [`CameraUpdate`].
121    pub fn update_camera(&mut self, update: &CameraUpdate) -> CameraCommandId {
122        self.command(|transform| transform.update_camera_now(update))
123    }
124
125    fn update_camera_now(&mut self, update: &CameraUpdate) {
126        self.gesture_phase_before(update.phase);
127        if update.phase != GesturePhase::None {
128            // A gesture's update can repeat a field it doesn't change.
129            let current = self.camera_options(None);
130            let changes = |value: Option<f64>, now: Option<f64>| value.is_some() && value != now;
131            self.gesture.change(
132                changes(update.camera.zoom, current.zoom),
133                changes(update.camera.bearing, current.bearing),
134                changes(update.camera.pitch, current.pitch),
135            );
136        }
137        self.with_source(gesture_source(update.phase), |transform| match update.mode {
138            CameraUpdateMode::Jump => {
139                transform.ease(&update.camera, &AnimationOptions { duration: None, ..update.animation });
140            }
141            CameraUpdateMode::Ease => transform.ease(&update.camera, &update.animation),
142            CameraUpdateMode::Fly => transform.fly(&update.camera, &update.animation, false),
143        });
144        self.gesture_phase_after(update.phase, false);
145    }
146
147    /// `Begin` cancels the running commands, and `Begin` and `Update` mark
148    /// the gesture, before its change applies, so that the change follows
149    /// the gesture rules (an ease doesn't fly, and wraps the longitude as a
150    /// drag). The first phase after a gesture ended starts a new one, which
151    /// an earlier gesture's momentum no longer ends.
152    fn gesture_phase_before(&mut self, phase: GesturePhase) {
153        if phase != GesturePhase::None && (phase == GesturePhase::Begin || !self.gesture.active) {
154            self.gesture = GestureState { serial: self.gesture.serial.wrapping_add(1), ..GestureState::default() };
155        }
156        if phase == GesturePhase::Begin {
157            self.cancel_transitions();
158        }
159        if matches!(phase, GesturePhase::Begin | GesturePhase::Update) {
160            self.gesture.active = true;
161            self.gesture_in_progress = true;
162        }
163    }
164
165    /// `Cancel` cancels the running commands after its change applies, and
166    /// `End` and `Cancel` end the gesture: at once, or when its momentum
167    /// ends. A gesture that ends at once comes to rest
168    /// ([`Self::come_to_rest`]), and reports the camera's change if that
169    /// moves it, though the picture stays.
170    fn gesture_phase_after(&mut self, phase: GesturePhase, momentum: bool) {
171        if phase == GesturePhase::Cancel {
172            self.cancel_transitions();
173        }
174        if matches!(phase, GesturePhase::End | GesturePhase::Cancel) {
175            self.gesture.active = false;
176            if !momentum {
177                self.gesture_in_progress = false;
178                if self.come_to_rest() {
179                    let change =
180                        CameraChange { mode: CameraChangeMode::Immediate, source: CameraChangeSource::Gesture };
181                    self.emit(TransformEvent::CameraWillChange(change));
182                    self.emit(TransformEvent::CameraDidChange(change));
183                }
184            }
185        }
186    }
187
188    /// The end of a gesture's momentum ends the gesture, unless another
189    /// gesture started since. The caller brings the camera to rest.
190    pub(super) fn end_gesture_momentum(&mut self, gesture: Option<u64>) {
191        if gesture == Some(self.gesture.serial) && !self.gesture.active {
192            self.gesture_in_progress = false;
193        }
194    }
195
196    #[cfg(test)]
197    pub(crate) fn set_gesture_in_progress(&mut self, in_progress: bool) {
198        self.gesture_in_progress = in_progress;
199    }
200
201    #[must_use]
202    pub fn is_gesture_in_progress(&self) -> bool {
203        self.gesture_in_progress
204    }
205}