Skip to main content

mln_map/
transform.rs

1// The C++ transition lambdas capture `this`. Here a command's frame function
2// takes the state as an argument and returns the camera at its progress,
3// which `apply_transitions` composes with the other commands' cameras.
4//
5// C++ calls its observer and each command's finish callback from inside the
6// transform, and guards against callbacks that start or cancel commands
7// meanwhile. The port queues them as `TransformEvent`s, which the owner
8// drains once the call returns.
9
10use std::f64::consts::PI;
11use std::rc::Rc;
12use std::sync::Arc;
13use std::time::Duration;
14
15use geometry::Point;
16use mln_map_types::{
17    AnimationOptions, CameraDelta, CameraError, CameraMomentum, CameraOptions, CameraUpdate, CameraUpdateMode,
18    CameraVelocity, CenterAndBearing, ConstrainMode, FreeCameraOptions, GesturePhase, MomentumDecay,
19    MomentumDecayModel, MomentumEasing, MomentumSnap, NorthOrientation, ProjectionMode, TransformState, TransitionEnd,
20    TransitionOutcome, VerticalPerspectiveProjection, ViewportMode,
21};
22use mln_style_types::ProjectionDefinition;
23use mln_util::UnitBezier;
24use mln_util::constants::{DEFAULT_TRANSITION_EASE, M2PI, PITCH_MAX};
25use mln_util::error::Error;
26use mln_util::geo::{EdgeInsets, LatLng, LatLngBounds, ScreenCoordinate, WrapMode};
27use mln_util::interpolate::interpolate;
28use mln_util::logging::{Event, Log};
29use mln_util::projection::Projection;
30use mln_util::size::Size;
31use mln_util::time::Instant;
32use parking_lot::Mutex;
33
34use crate::map_event::{CameraChange, CameraChangeMode, CameraChangeSource};
35
36/// A frame time older than this is stale (see [`Transform::frame_time`]):
37/// longer than a frame at 10 fps, so any host that draws sets a fresh one
38/// first.
39pub(crate) const STALE_FRAME_TIME: Duration = Duration::from_millis(100);
40
41/// Converts the given angle (in radians) to be numerically close to the
42/// anchor angle, allowing it to be interpolated properly without sudden
43/// jumps.
44fn normalize_angle(mut angle: f64, anchor_angle: f64) -> f64 {
45    if angle.is_nan() || anchor_angle.is_nan() {
46        return 0.0;
47    }
48
49    angle = mln_math::wrap(angle, -PI, PI);
50    if angle == -PI {
51        angle = PI;
52    }
53    let diff = (angle - anchor_angle).abs();
54    if (angle - M2PI - anchor_angle).abs() < diff {
55        angle -= M2PI;
56    }
57    if (angle + M2PI - anchor_angle).abs() < diff {
58        angle += M2PI;
59    }
60
61    angle
62}
63
64fn lat_lng(lat: f64, lon: f64) -> LatLng {
65    // C++ constructs LatLng directly, which throws std::domain_error.
66    LatLng::new(lat, lon).unwrap_or_else(|e| panic!("{e}"))
67}
68
69/// An animation frame's `EdgeInsets(top, left, bottom, right)`. C++ throws
70/// `std::domain_error` for NaN (infinite insets interpolate to NaN) out of
71/// the frame, and nothing catches it; the port logs it, and the frame keeps
72/// the insets.
73fn frame_edge_insets(top: f64, left: f64, bottom: f64, right: f64) -> Option<EdgeInsets> {
74    EdgeInsets::new(top, left, bottom, right).map_err(|e| Log::error(Event::General, &e.message)).ok()
75}
76
77/// An animation frame's `Projection::unproject`, which constructs a `LatLng`
78/// and so can throw `std::domain_error` (NaN); handled as
79/// [`frame_edge_insets`]: the frame keeps the center and zoom.
80fn frame_unproject(p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Option<LatLng> {
81    Projection::unproject(p, scale, wrap_mode).map_err(|e| Log::error(Event::General, &e.message)).ok()
82}
83
84/// Formats `value` with six decimals, as `std::to_string(double)` does.
85fn std_to_string(value: f64) -> String {
86    format!("{value:.6}")
87}
88
89/// Identifies a camera command that the transform started, in the
90/// [`TransformEvent::CommandEnded`] that reports its end. Each command the
91/// transform starts gets its own.
92#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
93pub struct CameraCommandId(u64);
94
95/// How a camera command ended.
96#[derive(Clone, Copy, Debug, PartialEq)]
97pub struct CommandEnd {
98    pub command: CameraCommandId,
99    /// The command's [`AnimationOptions::transition_id`].
100    pub transition_id: Option<u64>,
101    pub end: TransitionEnd,
102}
103
104/// What the transform reports, in order, for its owner to drain with
105/// [`Transform::drain_events`].
106#[derive(Clone, Copy, Debug, PartialEq)]
107pub enum TransformEvent {
108    CameraWillChange(CameraChange),
109    CameraIsChanging,
110    CameraDidChange(CameraChange),
111    /// A command ended: every command ends exactly once, unless the
112    /// transform is dropped with the command still running (see
113    /// [`Transform::close`]).
114    CommandEnded(CommandEnd),
115}
116
117/// A command's camera at an eased progress: every field set, except a
118/// center or padding the frame could not compute (logged), which keeps the
119/// current one.
120type FrameFn = Box<dyn Fn(&TransformState, f64) -> CameraOptions>;
121pub(crate) type ProjectionForZoomFn = Rc<dyn Fn(f64) -> ProjectionDefinition>;
122
123// `Transform::CameraField`.
124const CENTER: u16 = 1 << 0;
125const ZOOM: u16 = 1 << 1;
126const BEARING: u16 = 1 << 2;
127const PITCH: u16 = 1 << 3;
128const PADDING: u16 = 1 << 4;
129const ALTITUDE: u16 = 1 << 5;
130const ROLL: u16 = 1 << 6;
131const FOV: u16 = 1 << 7;
132
133/// The fields a command sets.
134fn camera_fields(camera: &CameraOptions) -> u16 {
135    let field = |set: bool, field: u16| if set { field } else { 0 };
136    field(camera.center.is_some(), CENTER)
137        | field(camera.zoom.is_some(), ZOOM)
138        | field(camera.bearing.is_some(), BEARING)
139        | field(camera.pitch.is_some(), PITCH)
140        | field(camera.padding.is_some(), PADDING)
141        | field(camera.center_altitude.is_some(), ALTITUDE)
142        | field(camera.roll.is_some(), ROLL)
143        | field(camera.fov.is_some(), FOV)
144}
145
146/// One camera command.
147struct Transition {
148    /// Remaining property ownership; replacement removes fields from this
149    /// mask.
150    fields: u16,
151    /// Replacing any coupled field relinquishes all coupled fields together.
152    coupled_fields: u16,
153    /// Properties classified as moving at command start; intersected with
154    /// `fields` when reporting movement, so replaced properties no longer
155    /// contribute. A momentum adds the fields its settling moves.
156    moving_fields: u16,
157    start: Instant,
158    /// A momentum extends it for its settling.
159    duration: Duration,
160    animation: AnimationOptions,
161    frame: FrameFn,
162    anchor: Option<ScreenCoordinate>,
163    anchor_lat_lng: LatLng,
164    /// Set for a momentum, which moves the camera relative to where it
165    /// stands instead of through `frame`.
166    momentum: Option<MomentumState>,
167    /// Why the command ends, once something other than time ends it:
168    /// `Cancelled`, or `Replaced` when later commands took all its fields.
169    /// Set through [`Transition::ended_by`], where cancellation wins.
170    stopped: Option<TransitionOutcome>,
171    /// What started the command, which the change that ends it reports.
172    source: CameraChangeSource,
173    /// The command whose end this transition's end reports, if any.
174    command: Option<CameraCommandId>,
175    /// For a gesture's momentum, the gesture's serial: its end ends the
176    /// gesture, unless another one started since.
177    gesture: Option<u64>,
178}
179
180impl Transition {
181    /// A command without coupled fields, anchor, momentum, end to report or
182    /// gesture.
183    fn new(
184        fields: u16,
185        moving_fields: u16,
186        start: Instant,
187        duration: Duration,
188        animation: &AnimationOptions,
189        frame: FrameFn,
190        source: CameraChangeSource,
191    ) -> Transition {
192        Transition {
193            fields,
194            coupled_fields: 0,
195            moving_fields,
196            start,
197            duration,
198            animation: *animation,
199            frame,
200            anchor: None,
201            anchor_lat_lng: LatLng::default(),
202            momentum: None,
203            stopped: None,
204            source,
205            command: None,
206            gesture: None,
207        }
208    }
209
210    fn mode(&self) -> CameraChangeMode {
211        if self.duration == Duration::ZERO { CameraChangeMode::Immediate } else { CameraChangeMode::Animated }
212    }
213
214    /// Records why the command stops: `Cancelled` or `Replaced`. A
215    /// cancellation wins over a replacement, as the C API reports
216    /// it.
217    fn ended_by(&mut self, outcome: TransitionOutcome) {
218        if self.stopped != Some(TransitionOutcome::Cancelled) {
219            self.stopped = Some(outcome);
220        }
221    }
222
223    /// How the command ended, with a momentum's leftover speed: why it
224    /// stopped, else `Replaced` if later commands took every momentum part,
225    /// else `Completed`.
226    fn end(&self) -> TransitionEnd {
227        let (velocity, momentum_replaced) =
228            self.momentum.as_ref().map_or((CameraVelocity::default(), false), MomentumState::end);
229        let outcome = self.stopped.unwrap_or(if momentum_replaced {
230            TransitionOutcome::Replaced
231        } else {
232            TransitionOutcome::Completed
233        });
234        TransitionEnd { outcome, velocity, generation: 0 }
235    }
236
237    /// The elapsed share of the duration at `now`, in [0, 1]; 1 for an
238    /// immediate command, or without a clock.
239    fn progress(&self, now: Option<Instant>) -> f64 {
240        let duration = self.duration;
241        match now {
242            Some(now) if !duration.is_zero() => {
243                mln_math::clamp_f64(now.saturating_duration_since(self.start).div_duration_f64(duration), 0.0, 1.0)
244            }
245            _ => 1.0,
246        }
247    }
248
249    /// The time since the command started, at `now`; zero before it, and
250    /// `Duration::MAX` without a clock, which ends every command.
251    fn elapsed(&self, now: Option<Instant>) -> Duration {
252        now.map_or(Duration::MAX, |now| now.saturating_duration_since(self.start))
253    }
254
255    /// Whether the command's time has run out at `now`.
256    fn has_run_out(&self, now: Option<Instant>) -> bool {
257        now.is_none_or(|now| now >= self.start && self.elapsed(Some(now)) >= self.duration)
258    }
259}
260
261/// `seconds` truncated to whole nanoseconds, as `duration_cast` does; `None`
262/// when negative, NaN, or too long for a `Duration` made of nanoseconds. The
263/// bound is exclusive because `u64::MAX` rounds up as a double.
264fn nanos_from_secs(seconds: f64) -> Option<Duration> {
265    (seconds >= 0.0 && seconds * 1e9 < u64::MAX as f64).then(|| Duration::from_nanos((seconds * 1e9) as u64))
266}
267
268/// How far one part of a momentum moves, over how long, and along which
269/// curve.
270#[derive(Clone, Copy, Default)]
271struct Glide {
272    distance: f64,
273    duration: Duration,
274    /// For friction, the decay rate per second.
275    rate: f64,
276    /// For an eased glide, the curve it follows.
277    easing: Option<MomentumEasing>,
278}
279
280impl Glide {
281    /// Plans a release at `speed`, or returns nothing when it doesn't move.
282    fn plan(speed: f64, decay: &MomentumDecay) -> Option<Glide> {
283        if speed.is_nan() || speed <= 0.0 || speed < decay.min_speed {
284            return None;
285        }
286        let mut speed = f64::min(speed, decay.max_speed);
287        let mut glide = Glide::default();
288        let seconds;
289        match decay.model {
290            MomentumDecayModel::Friction => {
291                let half_life = decay.half_life.as_secs_f64();
292                if half_life.is_nan() || half_life <= 0.0 || decay.stop_speed.is_nan() || decay.stop_speed <= 0.0 {
293                    return None;
294                }
295                glide.rate = std::f64::consts::LN_2 / half_life;
296                speed = f64::min(speed, decay.stop_speed + glide.rate * decay.max_distance);
297                if speed <= decay.stop_speed {
298                    return None;
299                }
300                seconds = (speed / decay.stop_speed).ln() / glide.rate;
301                glide.distance = (speed - decay.stop_speed) / glide.rate;
302            }
303            MomentumDecayModel::Ease => {
304                glide.distance = f64::min(decay.distance, decay.max_distance);
305                seconds = decay.duration.as_secs_f64();
306                glide.easing = Some(decay.easing);
307            }
308        }
309        // A glide too long for the clock doesn't move.
310        if glide.distance.is_nan() || glide.distance <= 0.0 {
311            return None;
312        }
313        glide.duration = nanos_from_secs(seconds).filter(|duration| !duration.is_zero())?;
314        Some(glide)
315    }
316
317    /// The share of the distance covered after `elapsed`, from 0 to 1.
318    fn progress(&self, elapsed: Duration) -> f64 {
319        if elapsed >= self.duration {
320            return 1.0;
321        }
322        if elapsed.is_zero() {
323            return 0.0;
324        }
325        let t = elapsed.as_secs_f64();
326        let total = self.duration.as_secs_f64();
327        match self.easing {
328            None => (-self.rate * t).exp_m1() / (-self.rate * total).exp_m1(),
329            Some(easing) => bezier(&easing).solve(t / total, 1e-6),
330        }
331    }
332
333    /// The share of the distance covered per second after `elapsed`.
334    fn speed(&self, elapsed: Duration) -> f64 {
335        if elapsed >= self.duration {
336            return 0.0;
337        }
338        let t = elapsed.as_secs_f64();
339        let total = self.duration.as_secs_f64();
340        let Some(easing) = self.easing else {
341            return self.rate * (-self.rate * t).exp() / -(-self.rate * total).exp_m1();
342        };
343        // The slope dy/dx of the curve, from its derivatives in its own
344        // parameter, which starts just past 0 where both can be 0.
345        let ease = bezier(&easing);
346        let p = f64::max(ease.solve_curve_x(t / total, 1e-6), 1e-6);
347        let cy = 3.0 * easing.y1;
348        let by = 3.0 * (easing.y2 - easing.y1) - cy;
349        let ay = 1.0 - cy - by;
350        let dy = (3.0 * ay * p + 2.0 * by) * p + cy;
351        let dx = ease.sample_curve_derivative_x(p);
352        if dx > 0.0 { dy / dx / total } else { 0.0 }
353    }
354}
355
356fn bezier(easing: &MomentumEasing) -> UnitBezier {
357    UnitBezier::new(easing.x1, easing.y1, easing.x2, easing.y2)
358}
359
360/// One part of a running momentum.
361#[derive(Clone, Copy, Default)]
362struct MomentumPart {
363    /// The fields that this part needs to keep moving or to settle.
364    fields: u16,
365    glide: Glide,
366    /// The share of the distance already applied.
367    applied: f64,
368    moving: bool,
369    /// Where the part may settle once it stops moving.
370    snap: Option<MomentumSnap>,
371    snap_pending: bool,
372    /// The change that the settling makes, while it runs, when it started,
373    /// and its eased share applied.
374    snap_delta: Option<f64>,
375    snap_start: Duration,
376    snap_applied: f64,
377}
378
379impl MomentumPart {
380    fn active(&self) -> bool {
381        self.moving || self.snap_pending || self.snap_delta.is_some()
382    }
383}
384
385// The scalar parts of a momentum, in `MomentumState::scalars`.
386const MOMENTUM_ZOOM: usize = 0;
387const MOMENTUM_BEARING: usize = 1;
388const MOMENTUM_PITCH: usize = 2;
389
390/// A momentum under way.
391struct MomentumState {
392    options: CameraMomentum,
393    /// The pan's distance, with its direction.
394    pan_total: ScreenCoordinate,
395    pan: MomentumPart,
396    /// The zoom, bearing and pitch parts, and each one's signed distance.
397    scalars: [MomentumPart; 3],
398    scalar_totals: [f64; 3],
399    /// Whether another command took a field that a moving part needed.
400    replaced: bool,
401    /// When the last frame applied the momentum, from its start.
402    elapsed: Duration,
403}
404
405impl MomentumState {
406    fn anchor(&self, part: usize) -> Option<ScreenCoordinate> {
407        match part {
408            MOMENTUM_ZOOM => self.options.zoom_anchor,
409            MOMENTUM_BEARING => self.options.bearing_anchor,
410            _ => self.options.pitch_anchor,
411        }
412    }
413
414    /// Stops the parts that lost a field they need, and returns the fields
415    /// that the rest still need.
416    fn retain(&mut self, owned: u16) -> u16 {
417        let mut needed = 0;
418        let mut replaced = false;
419        for part in std::iter::once(&mut self.pan).chain(self.scalars.iter_mut()) {
420            if !part.active() {
421                continue;
422            }
423            if part.fields & owned != part.fields {
424                replaced |= part.moving || part.snap_delta.is_some();
425                part.moving = false;
426                part.snap_pending = false;
427                part.snap_delta = None;
428                continue;
429            }
430            needed |= part.fields;
431        }
432        self.replaced |= replaced;
433        needed
434    }
435
436    /// The speed of the parts still moving, as of the last frame, which left
437    /// the camera where it stands, and whether another command stopped a
438    /// part early by taking a field it needed.
439    fn end(&self) -> (CameraVelocity, bool) {
440        let mut velocity = CameraVelocity::default();
441        if self.pan.moving {
442            let share = self.pan.glide.speed(self.elapsed);
443            velocity.pan = ScreenCoordinate::new(self.pan_total.x * share, self.pan_total.y * share);
444        }
445        let speed = |i: usize| {
446            let part = &self.scalars[i];
447            if part.moving { self.scalar_totals[i] * part.glide.speed(self.elapsed) } else { 0.0 }
448        };
449        velocity.zoom = speed(MOMENTUM_ZOOM);
450        velocity.bearing = speed(MOMENTUM_BEARING);
451        velocity.pitch = speed(MOMENTUM_PITCH);
452        (velocity, self.replaced)
453    }
454}
455
456/// The change that `snap` makes to `value`, or zero when it stays. A
457/// circular value, the bearing, has its targets within one turn from the
458/// offset, and takes the shorter way around to the nearest.
459fn snap_delta(value: f64, snap: &MomentumSnap, circular: bool) -> f64 {
460    if snap.spacing.is_nan() || snap.spacing <= 0.0 {
461        return 0.0;
462    }
463    let delta = if circular {
464        let turn = value - snap.offset - 360.0 * ((value - snap.offset) / 360.0).floor();
465        let below = (turn / snap.spacing).floor() * snap.spacing;
466        let above = f64::min(below + snap.spacing, 360.0);
467        if turn - below <= above - turn { below - turn } else { above - turn }
468    } else {
469        // `f64::round` rounds halfway away from zero, as std::round does.
470        snap.offset + ((value - snap.offset) / snap.spacing).round() * snap.spacing - value
471    };
472    if delta.abs() <= snap.tolerance { delta } else { 0.0 }
473}
474
475/// The value that a part of a momentum moves, for its snap.
476fn momentum_value(state: &TransformState, part: usize) -> f64 {
477    match part {
478        MOMENTUM_ZOOM => state.get_zoom(),
479        MOMENTUM_BEARING => -mln_math::rad2deg(state.get_bearing()),
480        _ => mln_math::rad2deg(state.get_pitch()),
481    }
482}
483
484/// The time of the latest frame that a map's host drew, which the map's
485/// animations sample at and its camera commands start from (see
486/// [`Transform::set_frame_time`]). A clone shares the clock, so the thread
487/// that draws can set it while the map lives on another.
488#[derive(Clone, Debug, Default)]
489pub struct FrameClock(Arc<Mutex<Option<Instant>>>);
490
491impl FrameClock {
492    pub fn set(&self, time: Option<Instant>) {
493        *self.0.lock() = time;
494    }
495
496    #[must_use]
497    pub fn get(&self) -> Option<Instant> {
498        *self.0.lock()
499    }
500}
501
502pub struct Transform {
503    state: TransformState,
504
505    transitions: Vec<Transition>,
506    /// What the transform reports, for [`Self::drain_events`].
507    events: Vec<TransformEvent>,
508    /// The command being started, which the transitions it starts report
509    /// their end to (see [`Self::command`]), unless `silent`.
510    command: Option<CameraCommandId>,
511    /// Set while a command starts transitions whose ends another of its
512    /// transitions reports: a delta's changes before its momentum.
513    silent: bool,
514    next_command: u64,
515    /// The commands made of several transitions, whose end waits for the
516    /// last of them.
517    joint_ends: Vec<JointEnd>,
518    /// What the commands being started come from: a command unless a gesture
519    /// or a momentum starts them (see [`Self::with_source`]).
520    source: CameraChangeSource,
521    gesture: GestureState,
522    /// The host's current frame time (see [`Self::set_frame_time`]).
523    frame_time: FrameClock,
524    projection_for_zoom: Option<ProjectionForZoomFn>,
525    globe_free_bearing: bool,
526    globe_drag_hold: Option<GlobeDragHold>,
527}
528
529/// A command made of several transitions, which ends once with the
530/// outcome that covers them all: cancelled if any was, otherwise closed if
531/// any was, otherwise replaced if any was.
532struct JointEnd {
533    command: CameraCommandId,
534    remaining: u32,
535    outcome: TransitionOutcome,
536}
537
538/// The location a drag on the globe holds under the cursor, from the step
539/// that grabbed it. The next step carries the drag on if it starts where
540/// that one ended, at `cursor` with the camera and the view as that step
541/// left them; any other step grabs the location under where it starts.
542#[derive(Clone, Copy, Debug)]
543struct GlobeDragHold {
544    location: LatLng,
545    cursor: ScreenCoordinate,
546    camera: CameraOptions,
547    size: Size,
548}
549
550/// The gesture that camera deltas and updates with a phase make.
551#[derive(Clone, Copy, Debug, Default)]
552struct GestureState {
553    /// Between its first `Begin` or `Update` and its `End` or `Cancel`.
554    active: bool,
555    /// Counts gestures, so that an earlier gesture's momentum doesn't end a
556    /// later gesture.
557    serial: u64,
558    /// The fields the gesture changed (`ZOOM`, `BEARING`, `PITCH`), which
559    /// alone may settle.
560    changed: u16,
561}
562
563impl GestureState {
564    /// Records the fields a gesture's change moves.
565    fn change(&mut self, zoom: bool, bearing: bool, pitch: bool) {
566        self.changed |=
567            (if zoom { ZOOM } else { 0 }) | (if bearing { BEARING } else { 0 }) | (if pitch { PITCH } else { 0 });
568    }
569
570    /// Drops the snaps of the parts the gesture didn't change: only what it
571    /// changed settles.
572    fn mask_snaps(&self, momentum: &mut CameraMomentum) {
573        if self.changed & ZOOM == 0 {
574            momentum.zoom_snap = None;
575        }
576        if self.changed & BEARING == 0 {
577            momentum.bearing_snap = None;
578        }
579        if self.changed & PITCH == 0 {
580            momentum.pitch_snap = None;
581        }
582    }
583}
584
585impl Transform {
586    #[must_use]
587    pub fn new(constrain_mode: ConstrainMode, viewport_mode: ViewportMode) -> Self {
588        Self::from_state(TransformState::new(constrain_mode, viewport_mode))
589    }
590
591    pub(crate) fn from_state(state: TransformState) -> Self {
592        Transform {
593            state,
594            transitions: Vec::new(),
595            events: Vec::new(),
596            command: None,
597            silent: false,
598            next_command: 0,
599            joint_ends: Vec::new(),
600            source: CameraChangeSource::Command,
601            gesture: GestureState::default(),
602            frame_time: FrameClock::default(),
603            projection_for_zoom: None,
604            globe_free_bearing: false,
605            globe_drag_hold: None,
606        }
607    }
608
609    /// Drains what the transform reported since the last call, oldest
610    /// first. The transform keeps its buffer for what it reports next.
611    pub fn drain_events(&mut self) -> std::vec::Drain<'_, TransformEvent> {
612        self.events.drain(..)
613    }
614
615    /// Whether the transform reported something that
616    /// [`drain_events`](Self::drain_events) hasn't drained.
617    pub fn has_events(&self) -> bool {
618        !self.events.is_empty()
619    }
620
621    fn emit(&mut self, event: TransformEvent) {
622        self.events.push(event);
623    }
624
625    // MARK: - Map View
626
627    pub fn resize(&mut self, size: Size) -> Result<(), Error> {
628        if size.is_empty() {
629            return Err(Error::invalid_argument("failed to resize: size is empty"));
630        }
631
632        if self.state.get_size() == size {
633            return Ok(());
634        }
635
636        self.emit(TransformEvent::CameraWillChange(CameraChange::default()));
637        self.state.set_size(size);
638        let (scale, center) = self.state.constrain_screen(self.state.get_scale());
639        if let Some(center) = center {
640            // Turns out that if you resize during a transition any changes
641            // made to the state will be ignored :( So if we have to constrain
642            // because of a resize and a transition is in progress - cancel
643            // the transition!
644            if self.in_transition() {
645                self.cancel_transitions();
646            }
647
648            // Setting x and y isn't enough to change the center: Cc and Bc
649            // must change too, which setLatLngZoom does.
650            let zoom = self.state.scale_zoom(scale);
651            self.state.set_lat_lng_zoom(&center, zoom);
652            self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
653
654            return Ok(());
655        }
656        self.constrain_position(scale);
657
658        self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
659        Ok(())
660    }
661
662    // MARK: - Camera
663
664    /// Returns the current camera options.
665    pub fn get_camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
666        self.state.get_camera_options(padding)
667    }
668
669    /// Change any combination of center, zoom, bearing, and pitch, without a
670    /// transition. Omitted options keep their current animations.
671    pub fn jump_to(&mut self, camera: &CameraOptions) -> CameraCommandId {
672        self.command(|transform| transform.jump(camera))
673    }
674
675    fn jump(&mut self, camera: &CameraOptions) {
676        // On the globe the zoom decides how close to a pole the center can be.
677        // GL JS's jump bounds the center by the zoom it lands on, where its
678        // ease bounds it by the zoom it starts from unless given one, so the
679        // jump settles the zoom.
680        if self.state.is_globe_rendering()
681            && let Some(center) = camera.center
682            && camera.zoom.is_none()
683        {
684            let zoom = self.get_zoom()
685                + VerticalPerspectiveProjection::zoom_adjustment(
686                    self.get_lat_lng(WrapMode::Wrapped).latitude(),
687                    center.latitude(),
688                );
689            self.ease_to(&CameraOptions { zoom: Some(zoom), ..*camera }, &AnimationOptions::default());
690            return;
691        }
692        self.ease_to(camera, &AnimationOptions::default());
693    }
694
695    /// Change any combination of center, zoom, bearing, pitch and edgeInsets,
696    /// with a smooth animation between old and new values. Omitted options
697    /// keep their current animations and timing.
698    pub fn ease_to(&mut self, camera: &CameraOptions, animation: &AnimationOptions) -> CameraCommandId {
699        self.command(|transform| transform.ease(camera, animation))
700    }
701
702    fn ease(&mut self, input_camera: &CameraOptions, animation: &AnimationOptions) {
703        let mut camera = *input_camera;
704        let globe = self.state.is_globe_rendering();
705
706        let duration = animation.duration.unwrap_or(Duration::ZERO);
707        if !globe
708            && self.state.get_lat_lng_bounds() == LatLngBounds::default()
709            && !self.is_gesture_in_progress()
710            && duration != Duration::ZERO
711            && animation.easing.is_none()
712        {
713            // A plain timed ease flies without the zoom-out. The flight's
714            // ground speed rises and falls along its path even at a constant
715            // zoom, so an ease given an easing interpolates instead, and
716            // moves as that easing says, as GL JS's easeTo does.
717            self.fly_to(&camera, animation, true);
718            return;
719        }
720
721        let mut zoom = camera.zoom.unwrap_or(self.get_zoom());
722        if camera.zoom.is_none()
723            && let Some(center) = camera.center
724            && globe
725        {
726            zoom += VerticalPerspectiveProjection::zoom_adjustment(
727                self.get_lat_lng(WrapMode::Wrapped).latitude(),
728                center.latitude(),
729            );
730        }
731        self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
732
733        let padding = camera.padding.unwrap_or(self.state.get_edge_insets());
734        let mut start_lat_lng = self.get_lat_lng(WrapMode::Unwrapped);
735        let unwrapped_lat_lng = camera.center.unwrap_or(start_lat_lng);
736        // On the globe the ease heads for the center the zoom it was given
737        // allows, or else the zoom it starts from, as GL JS's does; its last
738        // frame is bounded by the zoom it ends on.
739        let lat_lng_end = self.state.constrained_center(
740            &if self.state.get_lat_lng_bounds() == LatLngBounds::default() {
741                unwrapped_lat_lng.wrapped()
742            } else {
743                unwrapped_lat_lng
744            },
745            if camera.zoom.is_some() { zoom } else { self.get_zoom() },
746        );
747
748        let mut bearing = match camera.bearing {
749            Some(b) => mln_math::deg2rad(-b),
750            None => self.get_bearing(),
751        };
752        let mut pitch = match camera.pitch {
753            Some(p) => mln_math::deg2rad(p),
754            None => self.get_pitch(),
755        };
756        let mut fov = match camera.fov {
757            Some(f) => mln_math::deg2rad(f),
758            None => self.get_field_of_view(),
759        };
760        let center_alt = camera.center_altitude.unwrap_or(self.state.get_center_altitude());
761        let roll = match camera.roll {
762            Some(r) => mln_math::deg2rad(r),
763            None => self.get_roll(),
764        };
765
766        if zoom.is_nan() || bearing.is_nan() || pitch.is_nan() || roll.is_nan() || fov.is_nan() {
767            self.end_unstarted(animation, TransitionOutcome::Cancelled);
768            return;
769        }
770
771        if self.state.get_lat_lng_bounds() == LatLngBounds::default() {
772            if self.is_gesture_in_progress() {
773                // If gesture in progress, we transfer the wrap rounds from the
774                // end longitude into start, so the "scroll effect" of rounding
775                // the world is the same while assuring the end longitude
776                // remains wrapped.
777                let wrap = unwrapped_lat_lng.longitude() - lat_lng_end.longitude();
778                start_lat_lng = lat_lng(start_lat_lng.latitude(), start_lat_lng.longitude() - wrap);
779            } else {
780                // Find the shortest path otherwise.
781                start_lat_lng.unwrap_for_shortest_path(&lat_lng_end);
782            }
783        }
784        let start_center_alt = self.state.get_center_altitude();
785
786        let start_point = Projection::project(&start_lat_lng, self.state.get_scale());
787        let end_point = Projection::project(&lat_lng_end, self.state.get_scale());
788
789        // Constrain camera options.
790        // The target is drawn in the projection the style gives at its zoom,
791        // which the animation may cross into.
792        let target_globe = match &self.projection_for_zoom {
793            Some(projection_for_zoom) => projection_for_zoom(zoom).transition_state() > 0.0,
794            None => globe,
795        };
796        zoom = mln_math::clamp_f64(
797            zoom,
798            self.state.get_min_zoom_at_latitude_with(lat_lng_end.latitude(), target_globe),
799            self.state.get_max_zoom(),
800        );
801        pitch = mln_math::clamp_f64(pitch, self.state.get_min_pitch(), self.state.get_max_pitch());
802        fov = mln_math::clamp_f64(fov, self.state.get_min_field_of_view(), self.state.get_max_field_of_view());
803
804        // Minimize rotation by taking the shorter path around the circle.
805        bearing = normalize_angle(bearing, self.state.get_bearing());
806
807        let start_zoom = self.state.get_zoom();
808        let start_bearing = normalize_angle(self.state.get_bearing(), bearing);
809        let start_pitch = self.state.get_pitch();
810        let start_roll = self.state.get_roll();
811        let start_fov = f64::from(self.state.get_field_of_view());
812        let start_edge_insets = self.state.get_edge_insets();
813
814        // On the globe the zoom is eased in equator terms so the planet holds
815        // its size as the latitude changes, and the center moves the way GL
816        // JS moves it: longitude paced at 1 / cos(latitude), sped up ahead of
817        // a zoom in.
818        let normalized_start_zoom = if globe {
819            start_zoom + VerticalPerspectiveProjection::zoom_adjustment(start_lat_lng.latitude(), 0.0)
820        } else {
821            start_zoom
822        };
823        let normalized_zoom = if globe {
824            zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0)
825        } else {
826            zoom
827        };
828        let final_scale = self.state.zoom_scale(normalized_zoom - normalized_start_zoom);
829        let base = if normalized_zoom > normalized_start_zoom {
830            f64::min(2.0, final_scale)
831        } else {
832            f64::max(0.5, final_scale)
833        };
834        let delta_latitude = if globe {
835            VerticalPerspectiveProjection::difference_of_angles_degrees(
836                start_lat_lng.latitude(),
837                lat_lng_end.latitude(),
838            )
839        } else {
840            0.0
841        };
842        let delta_longitude = if globe {
843            VerticalPerspectiveProjection::difference_of_angles_degrees(
844                start_lat_lng.longitude(),
845                lat_lng_end.longitude(),
846            )
847        } else {
848            0.0
849        };
850        let moves_around_anchor = camera.anchor.is_some() && camera.center.is_none();
851
852        let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
853            let (frame_lat_lng, frame_zoom) = if globe {
854                // An anchor moves the center a frame at a time (see
855                // apply_transitions), so it stays, and the zoom follows its
856                // latitude to keep the planet's size.
857                let mut frame_lat_lng =
858                    if moves_around_anchor { state.get_lat_lng(WrapMode::Unwrapped) } else { lat_lng_end };
859                let mut frame_zoom = zoom;
860                if moves_around_anchor {
861                    frame_zoom = interpolate(&normalized_start_zoom, &normalized_zoom, t)
862                        + VerticalPerspectiveProjection::zoom_adjustment(0.0, frame_lat_lng.latitude());
863                } else if t < 1.0 {
864                    let factor = t * base.powf(1.0 - t);
865                    frame_lat_lng = VerticalPerspectiveProjection::interpolate_lat_lng(
866                        &start_lat_lng,
867                        delta_latitude,
868                        delta_longitude,
869                        factor,
870                    )
871                    .wrapped();
872                    frame_zoom = if zoom == start_zoom {
873                        start_zoom
874                    } else {
875                        interpolate(&normalized_start_zoom, &normalized_zoom, t)
876                            + VerticalPerspectiveProjection::zoom_adjustment(0.0, frame_lat_lng.latitude())
877                    };
878                }
879                (Some(frame_lat_lng), frame_zoom)
880            } else {
881                let frame_point = interpolate(&start_point, &end_point, t);
882                (
883                    frame_unproject(&frame_point, state.zoom_scale(start_zoom), WrapMode::Unwrapped),
884                    interpolate(&start_zoom, &zoom, t),
885                )
886            };
887            CameraOptions {
888                center: frame_lat_lng,
889                zoom: Some(frame_zoom),
890                center_altitude: Some(interpolate(&start_center_alt, &center_alt, t)),
891                bearing: Some(-mln_math::rad2deg(mln_math::wrap(interpolate(&start_bearing, &bearing, t), -PI, PI))),
892                padding: interpolate_edge_insets(&start_edge_insets, &padding, t),
893                pitch: Some(mln_math::rad2deg(interpolate(&start_pitch, &pitch, t))),
894                roll: Some(mln_math::rad2deg(interpolate(&start_roll, &roll, t))),
895                fov: Some(mln_math::rad2deg(interpolate(&start_fov, &fov, t))),
896                ..Default::default()
897            }
898        });
899
900        // On the globe the zoom keeps the planet's size as the center's
901        // latitude changes, and a zoom moves the center when it bounds it
902        // closer to the equator, so an ease that moves the center sets both
903        // (an anchored one gets its center from the anchor).
904        let moves_center = input_camera.center.is_some() || lat_lng_end.wrapped() != start_lat_lng.wrapped();
905        let fields = if globe && moves_around_anchor {
906            CameraOptions { zoom: Some(zoom), ..*input_camera }
907        } else if globe && moves_center {
908            CameraOptions { center: Some(lat_lng_end), zoom: Some(zoom), ..*input_camera }
909        } else {
910            *input_camera
911        };
912        self.start_transition(&fields, animation, frame, duration, false);
913    }
914
915    /// This method implements an “optimal path” animation, as detailed in:
916    ///
917    /// Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and
918    /// panning.” INFOVIS ’03. pp. 15–22.
919    /// <https://www.win.tue.nl/~vanwijk/zoompan.pdf#page=5>.
920    ///
921    /// Where applicable, local variable documentation begins with the
922    /// associated variable or function in van Wijk (2003).
923    pub(crate) fn fly_to(
924        &mut self,
925        camera: &CameraOptions,
926        animation: &AnimationOptions,
927        linear_zoom_interpolation: bool,
928    ) -> CameraCommandId {
929        self.command(|transform| transform.fly(camera, animation, linear_zoom_interpolation))
930    }
931
932    fn fly(&mut self, input_camera: &CameraOptions, animation: &AnimationOptions, linear_zoom_interpolation: bool) {
933        let mut camera = *input_camera;
934        let globe = self.state.is_globe_rendering();
935
936        let mut zoom = camera.zoom.unwrap_or(self.get_zoom());
937        if camera.zoom.is_none()
938            && let Some(center) = camera.center
939            && globe
940        {
941            zoom += VerticalPerspectiveProjection::zoom_adjustment(
942                self.get_lat_lng(WrapMode::Wrapped).latitude(),
943                center.latitude(),
944            );
945        }
946        self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
947
948        let padding = camera.padding.unwrap_or(self.state.get_edge_insets());
949        // As in easeTo, the globe's flight heads for the center the zoom it
950        // was given, or else starts from, allows.
951        let lat_lng_end = self.state.constrained_center(
952            &camera.center.unwrap_or(self.get_lat_lng(WrapMode::Unwrapped)).wrapped(),
953            if camera.zoom.is_some() { zoom } else { self.get_zoom() },
954        );
955        let center_alt = camera.center_altitude.unwrap_or(self.state.get_center_altitude());
956        let mut bearing = match camera.bearing {
957            Some(b) => mln_math::deg2rad(-b),
958            None => self.get_bearing(),
959        };
960        let mut pitch = match camera.pitch {
961            Some(p) => mln_math::deg2rad(p),
962            None => self.get_pitch(),
963        };
964        let roll = match camera.roll {
965            Some(r) => mln_math::deg2rad(r),
966            None => self.get_roll(),
967        };
968        let mut fov = match camera.fov {
969            Some(f) => mln_math::deg2rad(f),
970            None => self.get_field_of_view(),
971        };
972
973        if zoom.is_nan()
974            || bearing.is_nan()
975            || pitch.is_nan()
976            || roll.is_nan()
977            || fov.is_nan()
978            || self.state.get_size().is_empty()
979        {
980            self.end_unstarted(animation, TransitionOutcome::Cancelled);
981            return;
982        }
983
984        // Determine endpoints.
985        let mut start_lat_lng = self.get_lat_lng(WrapMode::Unwrapped).wrapped();
986        start_lat_lng.unwrap_for_shortest_path(&lat_lng_end);
987        let start_center_alt = self.state.get_center_altitude();
988
989        let start_point = Projection::project(&start_lat_lng, self.state.get_scale());
990        let end_point = Projection::project(&lat_lng_end, self.state.get_scale());
991
992        // Constrain camera options.
993        // The target is drawn in the projection the style gives at its zoom,
994        // which the animation may cross into.
995        let target_globe = match &self.projection_for_zoom {
996            Some(projection_for_zoom) => projection_for_zoom(zoom).transition_state() > 0.0,
997            None => globe,
998        };
999        zoom = mln_math::clamp_f64(
1000            zoom,
1001            self.state.get_min_zoom_at_latitude_with(lat_lng_end.latitude(), target_globe),
1002            self.state.get_max_zoom(),
1003        );
1004        pitch = mln_math::clamp_f64(pitch, self.state.get_min_pitch(), self.state.get_max_pitch());
1005        fov = mln_math::clamp_f64(fov, self.state.get_min_field_of_view(), self.state.get_max_field_of_view());
1006
1007        // Minimize rotation by taking the shorter path around the circle.
1008        bearing = normalize_angle(bearing, self.state.get_bearing());
1009        let start_zoom = self.state.scale_zoom(self.state.get_scale());
1010        let start_bearing = normalize_angle(self.state.get_bearing(), bearing);
1011        let start_pitch = self.state.get_pitch();
1012        let start_roll = self.state.get_roll();
1013        let start_fov = f64::from(self.state.get_field_of_view());
1014
1015        // w₀: Initial visible span, measured in pixels at the initial scale.
1016        // Known henceforth as a <i>screenful</i>.
1017        let size = self.state.get_size();
1018        let w0 = f64::max(
1019            f64::from(size.width) - padding.left - padding.right,
1020            f64::from(size.height) - padding.top - padding.bottom,
1021        );
1022        // The globe counts zoom in equator terms and distance along the
1023        // surface, so the arc is the same at any latitude.
1024        let normalized_start_zoom = if globe {
1025            start_zoom + VerticalPerspectiveProjection::zoom_adjustment(start_lat_lng.latitude(), 0.0)
1026        } else {
1027            start_zoom
1028        };
1029        let normalized_zoom = if globe {
1030            zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0)
1031        } else {
1032            zoom
1033        };
1034        // w₁: Final visible span, measured in pixels with respect to the
1035        // initial scale.
1036        let w1 = w0 / self.state.zoom_scale(normalized_zoom - normalized_start_zoom);
1037        // Length of the flight path as projected onto the ground plane,
1038        // measured in pixels from the world image origin at the initial scale.
1039        let u1 = if globe {
1040            VerticalPerspectiveProjection::surface_distance_pixels(
1041                Projection::world_size(self.state.get_scale()),
1042                start_lat_lng.latitude(),
1043                &start_lat_lng,
1044                &lat_lng_end,
1045            )
1046        } else {
1047            (end_point.x - start_point.x).hypot(end_point.y - start_point.y)
1048        };
1049
1050        // ρ: The relative amount of zooming that takes place along the flight
1051        // path. A high value maximizes zooming for an exaggerated animation,
1052        // while a low value minimizes zooming for something closer to
1053        // easeTo().
1054        //
1055        // 1.42 is the average value selected by participants in the user
1056        // study in van Wijk (2003). A value of 6<sup>¼</sup> would be
1057        // equivalent to the root mean squared average velocity,
1058        // V<sub>RMS</sub>. A value of 1 produces a circular motion.
1059        let mut rho = 1.42;
1060        if globe {
1061            // GL JS: the arc may not dip below the map's or the flight's
1062            // minimum zoom, and that only ever lowers ρ.
1063            let floor_zoom =
1064                f64::max(animation.min_zoom.unwrap_or(self.state.get_min_zoom()), self.state.get_min_zoom());
1065            let normalized_floor_zoom = f64::min(
1066                f64::min(
1067                    floor_zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0),
1068                    normalized_start_zoom,
1069                ),
1070                normalized_zoom,
1071            );
1072            let min_zoom = mln_math::clamp_f64(
1073                normalized_floor_zoom + VerticalPerspectiveProjection::zoom_adjustment(0.0, lat_lng_end.latitude()),
1074                self.state.get_min_zoom_at_latitude(lat_lng_end.latitude()),
1075                self.state.get_max_zoom(),
1076            );
1077            let w_max = w0
1078                / self.state.zoom_scale(
1079                    min_zoom + VerticalPerspectiveProjection::zoom_adjustment(lat_lng_end.latitude(), 0.0)
1080                        - normalized_start_zoom,
1081                );
1082            if u1 != 0.0 {
1083                rho = f64::min(rho, (w_max / u1 * 2.0).sqrt());
1084            }
1085        } else if animation.min_zoom.is_some() || linear_zoom_interpolation {
1086            // util::min(a, b, c) = min(a, min(b, c)), fmin on doubles
1087            let mut min_zoom =
1088                mln_math::fmin(animation.min_zoom.unwrap_or(start_zoom), mln_math::fmin(start_zoom, zoom));
1089            min_zoom = mln_math::clamp_f64(
1090                min_zoom,
1091                self.state.get_min_zoom_at_latitude(lat_lng_end.latitude()),
1092                self.state.get_max_zoom(),
1093            );
1094            // w<sub>m</sub>: Maximum visible span, measured in pixels with
1095            // respect to the initial scale.
1096            let w_max = w0 / self.state.zoom_scale(min_zoom - start_zoom);
1097            rho = if u1 == 0.0 { 1.0 } else { (w_max / u1 * 2.0).sqrt() };
1098        }
1099        // ρ²
1100        let rho2 = rho * rho;
1101
1102        // rᵢ: Returns the zoom-out factor at one end of the animation.
1103        //
1104        // @param i 0 for the ascent or 1 for the descent.
1105        let r = |i: f64| -> f64 {
1106            // bᵢ
1107            let b = (w1 * w1 - w0 * w0 + if i == 0.0 { 1.0 } else { -1.0 } * rho2 * rho2 * u1 * u1)
1108                / (2.0 * if i == 0.0 { w0 } else { w1 } * rho2 * u1);
1109            ((b * b + 1.0).sqrt() - b).ln()
1110        };
1111
1112        // r₀: Zoom-out factor during ascent.
1113        let r0 = if u1 == 0.0 { f64::INFINITY } else { r(0.0) }; // Silence division by 0 on sanitize bot.
1114        let r1 = if u1 == 0.0 { f64::INFINITY } else { r(1.0) };
1115
1116        // When u₀ = u₁, the optimal path doesn’t require both ascent and
1117        // descent.
1118        let is_close = u1.abs() < 0.000_001 || !r0.is_finite() || !r1.is_finite();
1119
1120        // w(s): Returns the visible span on the ground, measured in pixels
1121        // with respect to the initial scale.
1122        //
1123        // Assumes an angular field of view of 2 arctan ½ ≈ 53°.
1124        let w = move |s: f64| -> f64 {
1125            if is_close {
1126                ((if w1 < w0 { -1.0 } else { 1.0 }) * rho * s).exp()
1127            } else {
1128                r0.cosh() / (r0 + rho * s).cosh()
1129            }
1130        };
1131        // u(s): Returns the distance along the flight path as projected onto
1132        // the ground plane, measured in pixels from the world image origin at
1133        // the initial scale.
1134        let u = move |s: f64| -> f64 {
1135            if is_close { 0.0 } else { w0 * (r0.cosh() * (r0 + rho * s).tanh() - r0.sinh()) / rho2 / u1 }
1136        };
1137        // S: Total length of the flight path, measured in ρ-screenfuls.
1138        let total_s = if is_close { (w1 / w0).ln().abs() / rho } else { (r1 - r0) / rho };
1139
1140        let duration = if let Some(duration) = animation.duration {
1141            duration
1142        } else {
1143            // V: Average velocity, measured in ρ-screenfuls per second.
1144            let mut velocity = 1.2;
1145            if let Some(v) = animation.velocity {
1146                velocity = v / rho;
1147            }
1148            // duration_cast<Duration>(duration<double>(S / velocity)). A
1149            // duration Duration can't hold jumps, as one past max_duration
1150            // does, rather than saturating to a flight that never ends.
1151            nanos_from_secs(total_s / velocity).unwrap_or_default()
1152        };
1153        let duration = match animation.max_duration {
1154            Some(max) if !linear_zoom_interpolation && duration > max => Duration::ZERO,
1155            _ => duration,
1156        };
1157        let start_scale = self.state.get_scale();
1158        let start_edge_insets = self.state.get_edge_insets();
1159        let delta_latitude = if globe {
1160            VerticalPerspectiveProjection::difference_of_angles_degrees(
1161                start_lat_lng.latitude(),
1162                lat_lng_end.latitude(),
1163            )
1164        } else {
1165            0.0
1166        };
1167        let delta_longitude = if globe {
1168            VerticalPerspectiveProjection::difference_of_angles_degrees(
1169                start_lat_lng.longitude(),
1170                lat_lng_end.longitude(),
1171            )
1172        } else {
1173            0.0
1174        };
1175
1176        let frame: FrameFn = Box::new(move |state: &TransformState, k: f64| {
1177            // s: The distance traveled along the flight path, measured in
1178            // ρ-screenfuls.
1179            let s = k * total_s;
1180            let us = if k == 1.0 { 1.0 } else { u(s) };
1181
1182            let (frame_lat_lng, frame_zoom) = if globe {
1183                let mut frame_lat_lng = lat_lng_end;
1184                let mut frame_zoom = zoom;
1185                if k < 1.0 {
1186                    frame_lat_lng = VerticalPerspectiveProjection::interpolate_lat_lng(
1187                        &start_lat_lng,
1188                        delta_latitude,
1189                        delta_longitude,
1190                        us,
1191                    )
1192                    .wrapped();
1193                    let frame_normalized_zoom = if linear_zoom_interpolation {
1194                        interpolate(&normalized_start_zoom, &normalized_zoom, k)
1195                    } else {
1196                        normalized_start_zoom + state.scale_zoom(1.0 / w(s))
1197                    };
1198                    frame_zoom = frame_normalized_zoom
1199                        + VerticalPerspectiveProjection::zoom_adjustment(0.0, frame_lat_lng.latitude());
1200                    if frame_zoom.is_nan() {
1201                        frame_zoom = zoom;
1202                    }
1203                }
1204                (Some(frame_lat_lng), frame_zoom)
1205            } else {
1206                // Calculate the current point and zoom level along the flight
1207                // path.
1208                let frame_point = interpolate(&start_point, &end_point, us);
1209                let mut frame_zoom = if linear_zoom_interpolation {
1210                    interpolate(&start_zoom, &zoom, k)
1211                } else {
1212                    start_zoom + state.scale_zoom(1.0 / w(s))
1213                };
1214
1215                // Zoom can be NaN if size is empty.
1216                if frame_zoom.is_nan() {
1217                    frame_zoom = zoom;
1218                }
1219
1220                // Convert to geographic coordinates and set the new viewpoint.
1221                (frame_unproject(&frame_point, start_scale, WrapMode::Unwrapped), frame_zoom)
1222            };
1223            CameraOptions {
1224                center: frame_lat_lng,
1225                zoom: Some(frame_zoom),
1226                center_altitude: Some(interpolate(&start_center_alt, &center_alt, us)),
1227                bearing: Some(-mln_math::rad2deg(mln_math::wrap(interpolate(&start_bearing, &bearing, k), -PI, PI))),
1228                padding: interpolate_edge_insets(&start_edge_insets, &padding, k),
1229                pitch: Some(mln_math::rad2deg(interpolate(&start_pitch, &pitch, k))),
1230                roll: Some(mln_math::rad2deg(interpolate(&start_roll, &roll, k))),
1231                fov: Some(mln_math::rad2deg(interpolate(&start_fov, &fov, k))),
1232                ..Default::default()
1233            }
1234        });
1235
1236        self.start_transition(input_camera, animation, frame, duration, !linear_zoom_interpolation);
1237    }
1238
1239    // MARK: - Position
1240
1241    /// Whether the globe is drawn on a sized screen, so screen points reach
1242    /// it. Before the first resize, screen-point gestures are Mercator's.
1243    fn globe_on_screen(&self) -> bool {
1244        self.state.is_globe_rendering() && !self.state.get_size().is_empty()
1245    }
1246
1247    /// Pans the map by the given amount.
1248    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN
1249    /// or infinite offset.
1250    pub fn move_by(
1251        &mut self,
1252        offset: &ScreenCoordinate,
1253        animation: &AnimationOptions,
1254    ) -> Result<CameraCommandId, Error> {
1255        self.move_by_with_anchor(offset, None, animation)
1256    }
1257
1258    /// Moves the map by `offset`. A drag on the globe turns the planet so
1259    /// that the location under `anchor` follows the cursor. With the bearing
1260    /// held, steps that follow one another, each starting at the `anchor` of
1261    /// the one before with the camera as it left it, hold the location the
1262    /// first of them grabbed, wherever
1263    /// [`VerticalPerspectiveProjection::drag_center_holding`] has a center
1264    /// that does. Fails as [`move_by`](Self::move_by) does.
1265    pub fn move_by_with_anchor(
1266        &mut self,
1267        offset: &ScreenCoordinate,
1268        anchor: Option<ScreenCoordinate>,
1269        animation: &AnimationOptions,
1270    ) -> Result<CameraCommandId, Error> {
1271        let mut moved = Ok(());
1272        let command = self.command(|transform| moved = transform.move_by_now(offset, anchor, animation));
1273        moved.map(|()| command)
1274    }
1275
1276    fn move_by_now(
1277        &mut self,
1278        offset: &ScreenCoordinate,
1279        anchor: Option<ScreenCoordinate>,
1280        animation: &AnimationOptions,
1281    ) -> Result<(), Error> {
1282        let flipped = |state: &TransformState, point: &ScreenCoordinate| {
1283            ScreenCoordinate::new(point.x, f64::from(state.get_size().height) - point.y)
1284        };
1285        let size = self.state.get_size();
1286        let view_center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
1287        let fling_duration = animation.duration.filter(|duration| *duration > Duration::ZERO);
1288        let globe = self.globe_on_screen();
1289        if globe && (offset.x.is_nan() || offset.y.is_nan()) {
1290            return Err(Error::invalid_argument("offset must not be NaN"));
1291        }
1292        if globe && (!offset.x.is_finite() || !offset.y.is_finite()) {
1293            return Err(Error::invalid_argument("offset must not be infinite"));
1294        }
1295        if globe
1296            && let Some(duration) = fling_duration
1297            && self.globe_free_bearing
1298        {
1299            // A fling with the bearing free turns the planet on about the axis
1300            // the drag turned it about, so it carries on over a pole instead
1301            // of spinning round it.
1302            let start = CenterAndBearing {
1303                center: self.get_lat_lng(WrapMode::Unwrapped),
1304                bearing: -mln_math::rad2deg(self.get_bearing()),
1305            };
1306            let end = VerticalPerspectiveProjection::fling_camera(
1307                &self.state,
1308                &flipped(&self.state, &view_center),
1309                &ScreenCoordinate::new(offset.x, -offset.y),
1310            );
1311            let start_zoom = self.get_zoom();
1312            let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
1313                let camera = VerticalPerspectiveProjection::interpolate_camera(&start, &end, t);
1314                let center = state.constrained_center(&camera.center, state.get_zoom());
1315                CameraOptions {
1316                    center: Some(center),
1317                    zoom: Some(
1318                        start_zoom
1319                            + VerticalPerspectiveProjection::zoom_adjustment(
1320                                start.center.latitude(),
1321                                center.latitude(),
1322                            ),
1323                    ),
1324                    bearing: Some(camera.bearing),
1325                    ..Default::default()
1326                }
1327            });
1328            // The fling sets the center, the zoom that keeps the planet's
1329            // size and the bearing.
1330            let fields = CameraOptions {
1331                center: Some(end.center),
1332                zoom: Some(start_zoom),
1333                bearing: Some(end.bearing),
1334                ..Default::default()
1335            };
1336            self.start_transition(&fields, animation, frame, duration, false);
1337            return Ok(());
1338        }
1339
1340        if globe && fling_duration.is_some() {
1341            // An animated move, a fling, turns the globe as GL JS's inertia
1342            // does: the location under the far end of a long one can be off
1343            // the planet or over a pole. It stops short of half a turn, which
1344            // the ease would take the other way round.
1345            let mut center = self
1346                .state
1347                .constrained_center(&VerticalPerspectiveProjection::pan_center(&self.state, offset), self.get_zoom());
1348            let longitude = self.get_lat_lng(WrapMode::Unwrapped).longitude();
1349            if (center.longitude() - longitude).abs() > 180.0 {
1350                center = lat_lng(center.latitude(), longitude + 179.5f64.copysign(center.longitude() - longitude));
1351            }
1352            self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
1353            return Ok(());
1354        }
1355
1356        if globe {
1357            // A drag turns the globe as GL JS's does: one rotation that brings
1358            // the location under the cursor back under it with the bearing
1359            // held, around the cursor when it is on the planet and around the
1360            // center otherwise. With a free bearing the rotation turns the
1361            // bearing too, so the location stays under the cursor.
1362            //
1363            // With the bearing held, that rotation loses the turn it would
1364            // give the bearing, so step after step the location slips from
1365            // under the cursor. Where a center holds it there exactly, the
1366            // drag takes that center instead, for the location its first step
1367            // grabbed. A step the exact center isn't for doesn't hold: the
1368            // step after it grabs anew, so the drag goes from one way to the
1369            // other without a jump.
1370            let on_globe = |state: &TransformState, point: &ScreenCoordinate| {
1371                VerticalPerspectiveProjection::screen_coordinate_hits_globe(state, &flipped(state, point))
1372            };
1373            let grab = match anchor {
1374                Some(anchor) if on_globe(&self.state, &anchor) => anchor,
1375                _ => view_center,
1376            };
1377            let pan_delta = ScreenCoordinate::new(offset.x, -offset.y);
1378            let mut camera = CameraOptions::default();
1379            let held = self.globe_drag_hold.take();
1380            let hold = match anchor {
1381                Some(anchor) if !self.globe_free_bearing && on_globe(&self.state, &anchor) => {
1382                    let from = ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y);
1383                    let location = match held {
1384                        Some(held)
1385                            if (held.cursor.x - from.x).hypot(held.cursor.y - from.y) < 1e-3
1386                                && held.size == size
1387                                && held.camera == self.get_camera_options(None) =>
1388                        {
1389                            Some(held.location)
1390                        }
1391                        _ if on_globe(&self.state, &from) => self
1392                            .state
1393                            .screen_coordinate_to_lat_lng(&flipped(&self.state, &from), WrapMode::Unwrapped)
1394                            .ok(),
1395                        _ => None,
1396                    };
1397                    location.and_then(|location| {
1398                        VerticalPerspectiveProjection::drag_center_holding(
1399                            &self.state,
1400                            &location,
1401                            &flipped(&self.state, &anchor),
1402                        )
1403                        .map(|center| (location, anchor, center))
1404                    })
1405                }
1406                _ => None,
1407            };
1408            let mut center = if let Some((_, _, center)) = hold {
1409                center
1410            } else if self.globe_free_bearing {
1411                let drag =
1412                    VerticalPerspectiveProjection::drag_camera(&self.state, &flipped(&self.state, &grab), &pan_delta);
1413                camera = CameraOptions { bearing: Some(drag.bearing), ..camera };
1414                drag.center
1415            } else {
1416                VerticalPerspectiveProjection::drag_center(&self.state, &flipped(&self.state, &grab), &pan_delta)
1417            };
1418            center = self.state.constrained_center(&center, self.get_zoom());
1419            let zoom = self.get_zoom()
1420                + VerticalPerspectiveProjection::zoom_adjustment(
1421                    self.get_lat_lng(WrapMode::Wrapped).latitude(),
1422                    center.latitude(),
1423                );
1424            self.ease_to(&CameraOptions { center: Some(center), zoom: Some(zoom), ..camera }, animation);
1425            self.globe_drag_hold = hold.map(|(location, cursor, _)| GlobeDragHold {
1426                location,
1427                cursor,
1428                camera: self.get_camera_options(None),
1429                size,
1430            });
1431            return Ok(());
1432        }
1433
1434        let mut center_offset = *offset;
1435
1436        // Reduce the offset so that it never goes past the horizon. If it
1437        // goes past the horizon, the pan direction is opposite of the
1438        // intended direction.
1439        let pitch = self.state.get_pitch();
1440        let offset_length = offset.x.hypot(offset.y);
1441        if pitch > 0.0 && offset_length > 0.0 {
1442            let camera_to_center =
1443                0.5 * f64::from(self.state.get_size().height) / (f64::from(self.state.get_field_of_view()) / 2.0).tan();
1444            let pixels_to_horizon = (camera_to_center / pitch.tan()).abs();
1445            // must be < 1 to keep the offset short of the horizon
1446            let horizon_factor = 0.75;
1447            let scale = pixels_to_horizon * horizon_factor / offset_length;
1448            if scale < 1.0 {
1449                center_offset = ScreenCoordinate::new(offset.x * scale, offset.y * scale);
1450            }
1451        }
1452
1453        let size = self.state.get_size();
1454        let center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
1455        let point_on_screen = ScreenCoordinate::new(center.x - center_offset.x, center.y - center_offset.y);
1456        // Use unwrapped LatLng to carry information about moveBy direction.
1457        let center = self.screen_coordinate_to_lat_lng(&point_on_screen, WrapMode::Unwrapped)?;
1458        self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
1459        Ok(())
1460    }
1461
1462    pub fn get_lat_lng(&self, wrap: WrapMode) -> LatLng {
1463        self.state.get_lat_lng(wrap)
1464    }
1465
1466    // MARK: - Zoom
1467
1468    pub(crate) fn get_zoom(&self) -> f64 {
1469        self.state.get_zoom()
1470    }
1471
1472    // MARK: - Bounds
1473
1474    pub fn set_lat_lng_bounds(&mut self, bounds: LatLngBounds) -> Result<(), Error> {
1475        if !bounds.valid() {
1476            return Err(Error::invalid_argument("failed to set bounds: bounds are invalid"));
1477        }
1478        self.state.set_lat_lng_bounds(bounds);
1479        Ok(())
1480    }
1481
1482    pub(crate) fn set_min_zoom(&mut self, min_zoom: f64) {
1483        if min_zoom.is_nan() {
1484            return;
1485        }
1486        self.state.set_min_zoom(min_zoom);
1487    }
1488
1489    pub(crate) fn set_max_zoom(&mut self, max_zoom: f64) {
1490        if max_zoom.is_nan() {
1491            return;
1492        }
1493        self.state.set_max_zoom(max_zoom);
1494    }
1495
1496    pub(crate) fn set_min_pitch(&mut self, min_pitch: f64) {
1497        if min_pitch.is_nan() {
1498            return;
1499        }
1500        if mln_math::deg2rad(min_pitch) < mln_util::constants::PITCH_MIN {
1501            Log::warning(
1502                Event::General,
1503                format!(
1504                    "Trying to set minimum pitch below the limit ({} degrees), the value will be clamped.",
1505                    std_to_string(mln_math::rad2deg(mln_util::constants::PITCH_MIN))
1506                ),
1507            );
1508        }
1509        self.state.set_min_pitch(mln_math::deg2rad(min_pitch));
1510    }
1511
1512    pub fn set_max_pitch(&mut self, max_pitch: f64) {
1513        if max_pitch.is_nan() {
1514            return;
1515        }
1516        if mln_math::deg2rad(max_pitch) > PITCH_MAX {
1517            Log::warning(
1518                Event::General,
1519                format!(
1520                    "Trying to set maximum pitch above the limit ({} degrees), the value will be clamped.",
1521                    std_to_string(mln_math::rad2deg(PITCH_MAX))
1522                ),
1523            );
1524        }
1525        self.state.set_max_pitch(mln_math::deg2rad(max_pitch));
1526    }
1527
1528    pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
1529        self.state.set_frustum_offset(frustum_offset);
1530    }
1531
1532    // MARK: - Bearing
1533
1534    pub(crate) fn get_bearing(&self) -> f64 {
1535        self.state.get_bearing()
1536    }
1537
1538    // MARK: - Pitch
1539
1540    pub fn get_pitch(&self) -> f64 {
1541        self.state.get_pitch()
1542    }
1543
1544    pub(crate) fn get_roll(&self) -> f64 {
1545        self.state.get_roll()
1546    }
1547
1548    /// Returns `state.getFieldOfView()` (a float) as double.
1549    pub(crate) fn get_field_of_view(&self) -> f64 {
1550        f64::from(self.state.get_field_of_view())
1551    }
1552
1553    // MARK: - Projection
1554
1555    pub fn set_projection_definition(&mut self, definition: &ProjectionDefinition) {
1556        self.state.set_projection_definition(definition);
1557    }
1558
1559    /// The projection the style gives at a zoom, which constrains an
1560    /// animation's target as it constrains a jump.
1561    pub(crate) fn set_projection_for_zoom(&mut self, projection_for_zoom: Option<ProjectionForZoomFn>) {
1562        self.projection_for_zoom = projection_for_zoom;
1563    }
1564
1565    pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
1566        self.globe_free_bearing = free_bearing;
1567    }
1568
1569    pub(crate) fn is_globe_free_bearing(&self) -> bool {
1570        self.globe_free_bearing
1571    }
1572
1573    #[cfg(test)]
1574    pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
1575        self.state.is_location_occluded(lat_lng)
1576    }
1577
1578    // MARK: - North Orientation
1579
1580    pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
1581        self.state.set_north_orientation(orientation);
1582        self.constrain_position(self.state.get_scale());
1583    }
1584
1585    /// Moves the state to the position nearest its own at `scale` that the
1586    /// constrain mode allows.
1587    fn constrain_position(&mut self, scale: f64) {
1588        let (scale, x, y) = self.state.constrain(scale, self.state.get_x(), self.state.get_y());
1589        self.state.set_x(x);
1590        self.state.set_y(y);
1591        self.state.set_scale(scale);
1592    }
1593
1594    // MARK: - Constrain mode
1595
1596    pub fn set_constrain_mode(&mut self, mode: ConstrainMode) {
1597        self.state.set_constrain_mode(mode);
1598        self.constrain_position(self.state.get_scale());
1599    }
1600
1601    // MARK: - Viewport mode
1602
1603    pub fn set_viewport_mode(&mut self, mode: ViewportMode) {
1604        self.state.set_viewport_mode(mode);
1605    }
1606
1607    // MARK: - Projection mode
1608
1609    pub(crate) fn set_projection_mode(&mut self, options: &ProjectionMode) {
1610        if let Some(x_skew) = options.x_skew {
1611            self.state.set_x_skew(x_skew);
1612        }
1613        if let Some(y_skew) = options.y_skew {
1614            self.state.set_y_skew(y_skew);
1615        }
1616        if let Some(axonometric) = options.axonometric {
1617            self.state.set_axonometric(axonometric);
1618        }
1619    }
1620
1621    #[cfg(test)]
1622    pub(crate) fn get_projection_mode(&self) -> ProjectionMode {
1623        ProjectionMode::default()
1624            .with_axonometric(self.state.get_axonometric())
1625            .with_x_skew(self.state.get_x_skew())
1626            .with_y_skew(self.state.get_y_skew())
1627    }
1628
1629    // MARK: - Transition
1630
1631    /// Starts one camera command. `camera` is the command as given: the
1632    /// fields it sets are the fields it takes over from the running
1633    /// commands. A flight couples center and zoom; an anchored command
1634    /// couples center with its fields. Replacing any field of a coupled
1635    /// group stops the whole group, and a command left with no fields
1636    /// finishes.
1637    fn start_transition(
1638        &mut self,
1639        camera: &CameraOptions,
1640        animation: &AnimationOptions,
1641        frame: FrameFn,
1642        duration: Duration,
1643        flight: bool,
1644    ) {
1645        let mut fields = camera_fields(camera);
1646        let mut coupled_fields = if flight { CENTER | ZOOM } else { 0 };
1647        fields |= coupled_fields;
1648
1649        // An anchor controls center together with the properties it
1650        // transforms. An explicit center takes precedence over an anchor.
1651        let mut anchor = if camera.center.is_some() { None } else { camera.anchor };
1652        let mut anchor_lat_lng = LatLng::default();
1653        if let Some(a) = anchor.as_mut() {
1654            a.y = f64::from(self.state.get_size().height) - a.y;
1655            // C++ throws std::domain_error out of the camera change for an
1656            // anchor that has no LatLng (NaN or infinite); the port logs it
1657            // and ignores the anchor.
1658            match self.state.screen_coordinate_to_lat_lng(a, WrapMode::Unwrapped) {
1659                Ok(lat_lng) => {
1660                    anchor_lat_lng = lat_lng;
1661                    fields |= CENTER;
1662                    coupled_fields = fields;
1663                }
1664                Err(e) => {
1665                    Log::error(Event::General, &e.message);
1666                    anchor = None;
1667                }
1668            }
1669        }
1670
1671        let target = frame(&self.state, 1.0);
1672        let panning = flight || anchor.is_some() || camera.center != Some(self.get_lat_lng(WrapMode::Unwrapped));
1673        let scaling = flight || target.zoom != Some(self.get_zoom());
1674        let rotating = target.bearing != Some(-mln_math::rad2deg(self.get_bearing()));
1675        let moving_fields = (if panning { CENTER } else { 0 })
1676            | (if scaling { ZOOM } else { 0 })
1677            | (if rotating { BEARING } else { 0 });
1678
1679        let start = self.now();
1680        let duration = if fields != 0 { duration } else { Duration::ZERO };
1681        let transition = Transition {
1682            coupled_fields,
1683            anchor,
1684            anchor_lat_lng,
1685            command: self.reporting(),
1686            ..Transition::new(fields, moving_fields, start, duration, animation, frame, self.source)
1687        };
1688        let mode = transition.mode();
1689
1690        let finished = self.release_fields(fields);
1691        self.transitions.push(transition);
1692        self.update_movement_flags();
1693        self.finish_transitions(finished);
1694
1695        self.emit(TransformEvent::CameraWillChange(CameraChange { mode, source: self.source }));
1696
1697        if duration == Duration::ZERO {
1698            let index = self.transitions.len() - 1;
1699            self.apply_transitions(Some(index), Some(start));
1700            let transition = self.transitions.remove(index);
1701            self.update_movement_flags();
1702            self.finish_transitions(vec![transition]);
1703        }
1704    }
1705
1706    /// Composes the current camera with the camera of each running command
1707    /// that isn't a momentum, or only of the one at `only`, at `now`, for
1708    /// the fields it still owns, then applies the result.
1709    fn apply_transitions(&mut self, only: Option<usize>, now: Option<Instant>) {
1710        // The center is unwrapped, or wrapped on the globe without bounds
1711        // (TransformState::get_camera_options).
1712        let current = self.state.get_camera_options(None);
1713        let mut camera = current;
1714
1715        let active = match only {
1716            Some(index) => &self.transitions[index..=index],
1717            None => &self.transitions[..],
1718        };
1719        for transition in active {
1720            if transition.momentum.is_some() {
1721                continue;
1722            }
1723            let t = transition.progress(now);
1724            let ease = transition.animation.easing.unwrap_or(DEFAULT_TRANSITION_EASE);
1725            let value = (transition.frame)(&self.state, if t == 1.0 { 1.0 } else { ease.solve(t, 0.001) });
1726            let fields = transition.fields;
1727            // A frame without a center or padding (see FrameFn) keeps the
1728            // current one.
1729            if fields & CENTER != 0 && value.center.is_some() {
1730                camera.center = value.center;
1731            }
1732            if fields & ZOOM != 0 {
1733                camera.zoom = value.zoom;
1734            }
1735            if fields & BEARING != 0 {
1736                camera.bearing = value.bearing;
1737            }
1738            if fields & PITCH != 0 {
1739                camera.pitch = value.pitch;
1740            }
1741            if fields & PADDING != 0 && value.padding.is_some() {
1742                camera.padding = value.padding;
1743            }
1744            if fields & ALTITUDE != 0 {
1745                camera.center_altitude = value.center_altitude;
1746            }
1747            if fields & ROLL != 0 {
1748                camera.roll = value.roll;
1749            }
1750            if fields & FOV != 0 {
1751                camera.fov = value.fov;
1752            }
1753        }
1754
1755        // An active anchor also applies to immediate changes of other
1756        // properties.
1757        let anchored = self.transitions.iter().rev().find_map(|transition| {
1758            let anchor = transition.anchor.filter(|_| transition.fields & CENTER != 0)?;
1759            Some((anchor, transition.anchor_lat_lng))
1760        });
1761
1762        // On the globe the anchor is re-read every frame and the zoom around
1763        // it is GL JS's blend of the exact solution and a damped heuristic;
1764        // the exact solution alone jumps near the horizon. A frame can't
1765        // return the C++ exception for an anchor with no LatLng; it is
1766        // logged, and the anchor's location at the start stands in.
1767        let globe_zoom_around = match anchored {
1768            Some((anchor, anchor_lat_lng)) if self.globe_on_screen() => {
1769                let location =
1770                    self.state.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped).unwrap_or_else(|e| {
1771                        Log::error(Event::General, &e.message);
1772                        anchor_lat_lng
1773                    });
1774                Some((location, self.state.get_zoom()))
1775            }
1776            _ => None,
1777        };
1778
1779        // Compose the camera before applying constraints. In particular,
1780        // padding and field of view determine the pitch limit, and center
1781        // and zoom jointly determine the geographic bounds and altitude
1782        // scale.
1783        //
1784        // C++ sets every angle from its degrees. The port leaves the angles
1785        // no command changed as they are, so that converting them to degrees
1786        // and back doesn't move them.
1787        let padding = camera.padding.unwrap_or_default();
1788        self.state.set_edge_insets(&padding);
1789        if let Some(fov) = camera.fov.filter(|_| camera.fov != current.fov) {
1790            self.state.set_field_of_view(mln_math::deg2rad(fov));
1791        }
1792        if let Some(bearing) = camera.bearing.filter(|_| camera.bearing != current.bearing) {
1793            self.state.set_bearing(mln_math::deg2rad(-bearing));
1794        }
1795        if let Some(roll) = camera.roll.filter(|_| camera.roll != current.roll) {
1796            self.state.set_roll(mln_math::deg2rad(roll));
1797        }
1798        let pitch = match camera.pitch.filter(|_| camera.pitch != current.pitch) {
1799            Some(pitch) => mln_math::deg2rad(pitch),
1800            None => self.state.get_pitch(),
1801        };
1802        self.state.set_pitch(f64::min(get_max_pitch_for_edge_insets(&self.state, &padding), pitch));
1803        let mut zoom = camera.zoom.unwrap_or_default();
1804        self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
1805        self.state.set_lat_lng_zoom(&camera.center.unwrap_or_default(), zoom);
1806        if let Some((anchor, anchor_lat_lng)) = anchored {
1807            match globe_zoom_around {
1808                Some((location, zoom_before)) if self.state.get_zoom() != zoom_before => {
1809                    let zoom_delta = self.state.get_zoom() - zoom_before;
1810                    VerticalPerspectiveProjection::zoom_around_point(
1811                        &mut self.state,
1812                        &anchor,
1813                        &location,
1814                        zoom_delta,
1815                        self.globe_free_bearing,
1816                    );
1817                }
1818                // The anchor had a LatLng at the start; a frame can't return
1819                // the C++ exception, so it is logged, as in frame_edge_insets.
1820                _ => {
1821                    if let Err(e) = self.state.move_lat_lng(&anchor_lat_lng, &anchor) {
1822                        Log::error(Event::General, &e.message);
1823                    }
1824                }
1825            }
1826        }
1827        self.state.set_center_altitude(camera.center_altitude.unwrap_or_default());
1828    }
1829
1830    /// Reports the fields the running commands move as the state's panning,
1831    /// scaling and rotating flags.
1832    fn update_movement_flags(&mut self) {
1833        let moving = self.transitions.iter().fold(0, |moving, t| moving | (t.fields & t.moving_fields));
1834        self.state.set_panning_in_progress(moving & CENTER != 0);
1835        self.state.set_scaling_in_progress(moving & ZOOM != 0);
1836        self.state.set_rotating_in_progress(moving & BEARING != 0);
1837    }
1838
1839    fn finish_transitions(&mut self, finished: Vec<Transition>) {
1840        for transition in finished {
1841            self.end_gesture_momentum(transition.gesture);
1842            self.report_end(transition.command, transition.animation.transition_id, transition.end());
1843            // This notification ends a command, not necessarily all camera
1844            // motion.
1845            let change = CameraChange { mode: transition.mode(), source: transition.source };
1846            self.emit(TransformEvent::CameraDidChange(change));
1847        }
1848    }
1849
1850    /// Whether any camera command is still animating.
1851    pub fn in_transition(&self) -> bool {
1852        !self.transitions.is_empty()
1853    }
1854
1855    /// Moves the camera to where its commands are at `now`, and ends the
1856    /// ones that have run out; `None`, for a map without a clock, ends them all.
1857    pub fn update_transitions(&mut self, now: Option<Instant>) {
1858        if self.transitions.is_empty() {
1859            return;
1860        }
1861
1862        if self.transitions.iter().any(|t| t.momentum.is_none()) {
1863            self.apply_transitions(None, now);
1864        }
1865        for index in 0..self.transitions.len() {
1866            self.advance_momentum(index, now);
1867        }
1868
1869        let finished: Vec<_> = self.transitions.extract_if(.., |t| t.has_run_out(now) || t.fields == 0).collect();
1870        self.update_movement_flags();
1871        if !self.transitions.is_empty() {
1872            self.emit(TransformEvent::CameraIsChanging);
1873        }
1874
1875        self.finish_transitions(finished);
1876    }
1877
1878    /// Takes `fields` from the running commands, and returns the ones left
1879    /// with no fields, which the caller finishes.
1880    fn release_fields(&mut self, fields: u16) -> Vec<Transition> {
1881        for active in &mut self.transitions {
1882            let mut replaced = fields;
1883            if active.coupled_fields & replaced != 0 {
1884                replaced |= active.coupled_fields;
1885            }
1886            active.fields &= !replaced;
1887            if let Some(momentum) = &mut active.momentum {
1888                active.fields = momentum.retain(active.fields);
1889            }
1890            if active.fields == 0 {
1891                active.ended_by(TransitionOutcome::Replaced);
1892            }
1893        }
1894        self.transitions.extract_if(.., |active| active.fields == 0).collect()
1895    }
1896
1897    // MARK: - Commands and their ends
1898
1899    /// Runs `start` as a camera command, and returns the command. The
1900    /// transitions that `start` starts report their end to it, as does a
1901    /// command that fails or has nothing to move. Within a command being
1902    /// started, `start` is part of that command.
1903    fn command(&mut self, start: impl FnOnce(&mut Self)) -> CameraCommandId {
1904        if let Some(command) = self.command {
1905            start(self);
1906            return command;
1907        }
1908        let command = CameraCommandId(self.next_command);
1909        self.next_command += 1;
1910        self.command = Some(command);
1911        start(self);
1912        self.command = None;
1913        command
1914    }
1915
1916    /// The command that the transitions being started report their end to.
1917    fn reporting(&self) -> Option<CameraCommandId> {
1918        self.command.filter(|_| !self.silent)
1919    }
1920
1921    /// Makes the command being started end once, when `count` of its ends
1922    /// have been reported.
1923    fn join_ends(&mut self, count: u32) {
1924        if let Some(command) = self.reporting().filter(|_| count > 1) {
1925            self.joint_ends.push(JointEnd { command, remaining: count, outcome: TransitionOutcome::Completed });
1926        }
1927    }
1928
1929    /// Reports an end of `command`, which ends it unless it waits for more
1930    /// (see [`Self::join_ends`]).
1931    fn report_end(&mut self, command: Option<CameraCommandId>, transition_id: Option<u64>, mut end: TransitionEnd) {
1932        let Some(command) = command else { return };
1933        if let Some(index) = self.joint_ends.iter().position(|joint| joint.command == command) {
1934            let joint = &mut self.joint_ends[index];
1935            joint.remaining -= 1;
1936            joint.outcome = match (joint.outcome, end.outcome) {
1937                (TransitionOutcome::Cancelled, _) | (_, TransitionOutcome::Cancelled) => TransitionOutcome::Cancelled,
1938                (TransitionOutcome::Closed, _) | (_, TransitionOutcome::Closed) => TransitionOutcome::Closed,
1939                (TransitionOutcome::Replaced, _) | (_, TransitionOutcome::Replaced) => TransitionOutcome::Replaced,
1940                _ => TransitionOutcome::Completed,
1941            };
1942            if joint.remaining > 0 {
1943                return;
1944            }
1945            end.outcome = joint.outcome;
1946            self.joint_ends.swap_remove(index);
1947        }
1948        self.emit(TransformEvent::CommandEnded(CommandEnd { command, transition_id, end }));
1949    }
1950
1951    /// Ends a command that started no transition: one that failed before it
1952    /// moved the camera, or a momentum with nothing to move.
1953    fn end_unstarted(&mut self, animation: &AnimationOptions, outcome: TransitionOutcome) {
1954        self.report_end(
1955            self.reporting(),
1956            animation.transition_id,
1957            TransitionEnd { outcome, ..TransitionEnd::default() },
1958        );
1959    }
1960
1961    // MARK: - Momentum
1962
1963    /// Continues a gesture with momentum. The momentum replaces the running
1964    /// animations of the fields that it moves, as a camera command does.
1965    #[cfg(test)]
1966    pub(crate) fn start_momentum(&mut self, options: &CameraMomentum, animation: &AnimationOptions) -> CameraCommandId {
1967        self.command(|transform| {
1968            transform.with_source(CameraChangeSource::Momentum, |transform| {
1969                transform.start_momentum_now(options, animation, None);
1970            });
1971        })
1972    }
1973
1974    /// Starts a momentum; `gesture` is the serial of the gesture it
1975    /// continues, which ends with it.
1976    fn start_momentum_now(&mut self, options: &CameraMomentum, animation: &AnimationOptions, gesture: Option<u64>) {
1977        let momentum_change = |mode: CameraChangeMode| CameraChange { mode, source: CameraChangeSource::Momentum };
1978        let mut momentum = MomentumState {
1979            options: *options,
1980            pan_total: ScreenCoordinate::new(0.0, 0.0),
1981            pan: MomentumPart::default(),
1982            scalars: [MomentumPart::default(); 3],
1983            scalar_totals: [0.0; 3],
1984            replaced: false,
1985            elapsed: Duration::ZERO,
1986        };
1987        let mut moving = 0;
1988        let mut settling = 0;
1989        let mut motion = Duration::ZERO;
1990        if let Some(velocity) = options.pan_velocity {
1991            let speed = velocity.x.hypot(velocity.y);
1992            if let Some(glide) = Glide::plan(speed, &options.pan_decay) {
1993                momentum.pan = MomentumPart { fields: CENTER, glide, moving: true, ..Default::default() };
1994                moving |= CENTER;
1995                motion = glide.duration;
1996                let scale = glide.distance / speed;
1997                momentum.pan_total = ScreenCoordinate::new(velocity.x * scale, velocity.y * scale);
1998            }
1999        }
2000        let scalars = [
2001            (options.zoom_velocity, &options.zoom_decay, options.zoom_anchor, options.zoom_snap, ZOOM),
2002            (options.bearing_velocity, &options.bearing_decay, options.bearing_anchor, options.bearing_snap, BEARING),
2003            (options.pitch_velocity, &options.pitch_decay, options.pitch_anchor, options.pitch_snap, PITCH),
2004        ];
2005        let mut instant = true;
2006        for (i, (velocity, decay, anchor, snap, field)) in scalars.into_iter().enumerate() {
2007            let part = &mut momentum.scalars[i];
2008            part.fields = field | if anchor.is_some() { CENTER } else { 0 };
2009            if let Some(velocity) = velocity
2010                && let Some(glide) = Glide::plan(velocity.abs(), decay)
2011            {
2012                part.glide = glide;
2013                part.moving = true;
2014                moving |= part.fields;
2015                motion = motion.max(glide.duration);
2016                momentum.scalar_totals[i] = glide.distance.copysign(velocity);
2017            }
2018            // Without motion, a part settles only if it is near a target now.
2019            part.snap = snap;
2020            part.snap_pending = snap.is_some_and(|snap| {
2021                part.moving || snap_delta(momentum_value(&self.state, i), &snap, i == MOMENTUM_BEARING) != 0.0
2022            });
2023            if part.snap_pending {
2024                settling |= part.fields;
2025                if snap.is_some_and(|snap| snap.duration != Duration::ZERO) {
2026                    instant = false;
2027                }
2028            }
2029        }
2030
2031        let start = self.now();
2032
2033        // A momentum that doesn't move ends at once, without a camera change,
2034        // and instant snaps without motion settle at once.
2035        if moving == 0 && (settling == 0 || instant) {
2036            if settling != 0 {
2037                let finished = self.release_fields(settling);
2038                self.update_movement_flags();
2039                self.finish_transitions(finished);
2040                self.emit(TransformEvent::CameraWillChange(momentum_change(CameraChangeMode::Immediate)));
2041                for i in 0..momentum.scalars.len() {
2042                    let part = &mut momentum.scalars[i];
2043                    let Some(snap) = part.snap.filter(|_| part.snap_pending) else { continue };
2044                    part.snap_pending = false;
2045                    let delta = snap_delta(momentum_value(&self.state, i), &snap, i == MOMENTUM_BEARING);
2046                    self.step_scalar(i, delta, momentum.anchor(i));
2047                }
2048            }
2049            self.end_gesture_momentum(gesture);
2050            self.end_unstarted(animation, TransitionOutcome::Completed);
2051            if settling != 0 {
2052                self.emit(TransformEvent::CameraDidChange(momentum_change(CameraChangeMode::Immediate)));
2053            }
2054            return;
2055        }
2056
2057        let fields = moving | settling;
2058        let transition = Transition {
2059            momentum: Some(momentum),
2060            gesture,
2061            command: self.reporting(),
2062            ..Transition::new(
2063                fields,
2064                moving,
2065                start,
2066                motion,
2067                animation,
2068                Box::new(|_, _| CameraOptions::default()),
2069                CameraChangeSource::Momentum,
2070            )
2071        };
2072        let finished = self.release_fields(fields);
2073        self.transitions.push(transition);
2074        self.update_movement_flags();
2075        self.finish_transitions(finished);
2076        self.emit(TransformEvent::CameraWillChange(momentum_change(CameraChangeMode::Animated)));
2077    }
2078
2079    /// Runs `start` with the commands it starts attributed to `source`.
2080    fn with_source<R>(&mut self, source: CameraChangeSource, start: impl FnOnce(&mut Self) -> R) -> R {
2081        let previous = std::mem::replace(&mut self.source, source);
2082        let result = start(self);
2083        self.source = previous;
2084        result
2085    }
2086
2087    /// Steps the zoom, bearing or pitch part of a momentum.
2088    fn step_scalar(&mut self, part: usize, amount: f64, anchor: Option<ScreenCoordinate>) -> bool {
2089        match part {
2090            MOMENTUM_ZOOM => self.step_zoom(amount, anchor),
2091            MOMENTUM_BEARING => {
2092                self.step_bearing(amount, anchor);
2093                true
2094            }
2095            _ => self.step_pitch(amount, anchor),
2096        }
2097    }
2098
2099    /// Moves the camera as the momentum at `index` says at `now`, if it is
2100    /// one.
2101    fn advance_momentum(&mut self, index: usize, now: Option<Instant>) {
2102        let transition = &mut self.transitions[index];
2103        let Some(mut momentum) = transition.momentum.take() else { return };
2104        let elapsed = transition.elapsed(now);
2105        let (mut duration, mut moving_fields) = (transition.duration, transition.moving_fields);
2106        momentum.elapsed = elapsed;
2107
2108        let advance = |part: &mut MomentumPart| -> f64 {
2109            if !part.moving {
2110                return 0.0;
2111            }
2112            let progress = part.glide.progress(elapsed);
2113            let fraction = progress - part.applied;
2114            part.applied = progress;
2115            if progress >= 1.0 {
2116                part.moving = false;
2117            }
2118            fraction
2119        };
2120        // A part that bounds or limits hold in place stops.
2121        let fraction = advance(&mut momentum.pan);
2122        if fraction != 0.0 {
2123            let total = momentum.pan_total;
2124            if !self.step_pan(ScreenCoordinate::new(total.x * fraction, total.y * fraction)) {
2125                momentum.pan.moving = false;
2126            }
2127        }
2128        for i in 0..momentum.scalars.len() {
2129            let anchor = momentum.anchor(i);
2130            let total = momentum.scalar_totals[i];
2131            let part = &mut momentum.scalars[i];
2132            let fraction = advance(part);
2133            if fraction != 0.0 && !self.step_scalar(i, total * fraction, anchor) {
2134                part.moving = false;
2135            }
2136            // The part settles once it stops moving, which can be before its
2137            // planned end when bounds, limits, or commands stopped it.
2138            if part.snap_pending && !part.moving {
2139                part.snap_pending = false;
2140                let snap = part.snap.unwrap_or_default();
2141                let delta = snap_delta(momentum_value(&self.state, i), &snap, i == MOMENTUM_BEARING);
2142                if delta != 0.0 {
2143                    part.snap_delta = Some(delta);
2144                    part.snap_start = elapsed;
2145                    duration = duration.max(elapsed.saturating_add(snap.duration));
2146                    moving_fields |= part.fields;
2147                }
2148            }
2149            if let Some(delta) = part.snap_delta {
2150                let duration = part.snap.unwrap_or_default().duration;
2151                // Without a clock, the snap ends with its command.
2152                let t = if duration.is_zero() || now.is_none() {
2153                    1.0
2154                } else {
2155                    mln_math::clamp_f64(elapsed.saturating_sub(part.snap_start).div_duration_f64(duration), 0.0, 1.0)
2156                };
2157                let eased = if t >= 1.0 { 1.0 } else { DEFAULT_TRANSITION_EASE.solve(t, 0.001) };
2158                let fraction = eased - part.snap_applied;
2159                part.snap_applied = eased;
2160                let moved = fraction == 0.0 || self.step_scalar(i, delta * fraction, anchor);
2161                if t >= 1.0 || !moved {
2162                    part.snap_delta = None;
2163                }
2164            }
2165        }
2166
2167        // Parts that ran to their end give up their fields.
2168        let transition = &mut self.transitions[index];
2169        transition.duration = duration;
2170        transition.moving_fields = moving_fields;
2171        transition.fields = momentum.retain(transition.fields);
2172        transition.momentum = Some(momentum);
2173    }
2174
2175    /// The anchor `anchor` (from the top left) as a state point, from the
2176    /// bottom left, with the `LatLng` under it; `None` without one. C++
2177    /// throws `std::domain_error` for an anchor that has no `LatLng`; the port
2178    /// logs it and ignores the anchor.
2179    fn momentum_anchor(&self, anchor: Option<ScreenCoordinate>) -> Option<(ScreenCoordinate, LatLng)> {
2180        let anchor = anchor?;
2181        let point = ScreenCoordinate::new(anchor.x, f64::from(self.state.get_size().height) - anchor.y);
2182        match self.state.screen_coordinate_to_lat_lng(&point, WrapMode::Unwrapped) {
2183            Ok(lat_lng) => Some((point, lat_lng)),
2184            Err(e) => {
2185                Log::error(Event::General, &e.message);
2186                None
2187            }
2188        }
2189    }
2190
2191    /// Moves the center so that `lat_lng` is at `point` again, keeping the
2192    /// altitude in meters, which moving the center keeps in pixels.
2193    fn hold_momentum_anchor(&mut self, anchor: Option<(ScreenCoordinate, LatLng)>) {
2194        let Some((point, lat_lng)) = anchor else { return };
2195        let altitude = self.state.get_center_altitude();
2196        if let Err(e) = self.state.move_lat_lng(&lat_lng, &point) {
2197            Log::error(Event::General, &e.message);
2198        }
2199        self.state.set_center_altitude(altitude);
2200    }
2201
2202    // Momentum steps, applied to the state as it stands. Each returns whether
2203    // it moved the camera, which bounds and limits can prevent.
2204
2205    fn step_pan(&mut self, offset: ScreenCoordinate) -> bool {
2206        // Each step moves the content no farther than a drag moves it in one
2207        // event, so the travel on screen stays even at high pitch. A frame
2208        // that would need more steps than a frame can afford takes longer
2209        // ones.
2210        const MAX_STEP: f64 = 16.0;
2211        const MAX_STEPS: f64 = 100.0;
2212        let distance = offset.x.hypot(offset.y);
2213        if distance.is_nan() || distance <= 0.0 {
2214            return true;
2215        }
2216        let before = self.get_lat_lng(WrapMode::Unwrapped);
2217        let altitude = self.state.get_center_altitude();
2218        let steps = f64::min((distance / MAX_STEP).ceil(), MAX_STEPS);
2219        let step = ScreenCoordinate::new(offset.x / steps, offset.y / steps);
2220        let bounded = self.state.get_lat_lng_bounds() != LatLngBounds::default();
2221        for _ in 0..steps as u32 {
2222            if self.globe_on_screen() {
2223                self.step_globe_pan(&step);
2224                continue;
2225            }
2226            let size = self.state.get_size();
2227            let center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
2228            let point = ScreenCoordinate::new(center.x - step.x, center.y - step.y);
2229            // C++ throws std::domain_error for a step that has no LatLng; the
2230            // port logs it and stops the step.
2231            let unwrapped = match self.screen_coordinate_to_lat_lng(&point, WrapMode::Unwrapped) {
2232                Ok(lat_lng) => lat_lng,
2233                Err(e) => {
2234                    Log::error(Event::General, &e.message);
2235                    break;
2236                }
2237            };
2238            let mut camera = CameraOptions {
2239                center: Some(if bounded { unwrapped } else { unwrapped.wrapped() }),
2240                ..Default::default()
2241            };
2242            let mut zoom = self.state.get_zoom();
2243            self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut zoom);
2244            self.state.set_lat_lng_zoom(&camera.center.unwrap_or(unwrapped), zoom);
2245        }
2246        self.state.set_center_altitude(altitude);
2247        self.get_lat_lng(WrapMode::Unwrapped) != before
2248    }
2249
2250    /// One pan step on the globe, as a drag around the view center
2251    /// ([`Self::move_by_with_anchor`] without an anchor) makes it: the
2252    /// planet turns, the bearing too when it is free, and the zoom keeps the
2253    /// planet's size as the latitude changes.
2254    fn step_globe_pan(&mut self, step: &ScreenCoordinate) {
2255        let size = self.state.get_size();
2256        let view_center = self.state.get_edge_insets().get_center(size.width as u16, size.height as u16);
2257        let grab = ScreenCoordinate::new(view_center.x, f64::from(size.height) - view_center.y);
2258        let pan_delta = ScreenCoordinate::new(step.x, -step.y);
2259        let (center, bearing) = if self.globe_free_bearing {
2260            let drag = VerticalPerspectiveProjection::drag_camera(&self.state, &grab, &pan_delta);
2261            (drag.center, Some(drag.bearing))
2262        } else {
2263            (VerticalPerspectiveProjection::drag_center(&self.state, &grab, &pan_delta), None)
2264        };
2265        let center = self.state.constrained_center(&center, self.get_zoom());
2266        let zoom = self.get_zoom()
2267            + VerticalPerspectiveProjection::zoom_adjustment(
2268                self.get_lat_lng(WrapMode::Wrapped).latitude(),
2269                center.latitude(),
2270            );
2271        if let Some(bearing) = bearing {
2272            self.state.set_bearing(mln_math::deg2rad(-bearing));
2273        }
2274        self.state.set_lat_lng_zoom(&center, zoom);
2275    }
2276
2277    fn step_zoom(&mut self, zoom: f64, anchor: Option<ScreenCoordinate>) -> bool {
2278        let before = self.state.get_zoom();
2279        let altitude = self.state.get_center_altitude();
2280        let anchor = self.momentum_anchor(anchor);
2281        let center = self.get_lat_lng(WrapMode::Unwrapped);
2282        let mut target = mln_math::clamp_f64(
2283            before + zoom,
2284            self.state.get_min_zoom_at_latitude(center.latitude()),
2285            self.state.get_max_zoom(),
2286        );
2287        let mut camera = CameraOptions { center: Some(center), ..Default::default() };
2288        self.state.constrain_camera_and_zoom_to_bounds(&mut camera, &mut target);
2289        self.state.set_lat_lng_zoom(&camera.center.unwrap_or(center), target);
2290        // The altitude in meters holds before the anchor correction, which
2291        // reads the projection, and through the correction's change of
2292        // center.
2293        self.state.set_center_altitude(altitude);
2294        match anchor {
2295            // On the globe the zoom around the anchor is the globe's, as in
2296            // apply_transitions.
2297            Some((point, lat_lng)) if self.globe_on_screen() && self.state.get_zoom() != before => {
2298                let zoom_delta = self.state.get_zoom() - before;
2299                VerticalPerspectiveProjection::zoom_around_point(
2300                    &mut self.state,
2301                    &point,
2302                    &lat_lng,
2303                    zoom_delta,
2304                    self.globe_free_bearing,
2305                );
2306            }
2307            _ => self.hold_momentum_anchor(anchor),
2308        }
2309        self.state.get_zoom() != before
2310    }
2311
2312    fn step_bearing(&mut self, bearing: f64, anchor: Option<ScreenCoordinate>) {
2313        let anchor = self.momentum_anchor(anchor);
2314        self.state.set_bearing(mln_math::wrap(self.state.get_bearing() - mln_math::deg2rad(bearing), -PI, PI));
2315        self.hold_momentum_anchor(anchor);
2316    }
2317
2318    fn step_pitch(&mut self, pitch: f64, anchor: Option<ScreenCoordinate>) -> bool {
2319        let anchor = self.momentum_anchor(anchor);
2320        let before = self.state.get_pitch();
2321        let max_pitch = get_max_pitch_for_edge_insets(&self.state, &self.state.get_edge_insets());
2322        self.state.set_pitch(mln_math::clamp_f64(
2323            before + mln_math::deg2rad(pitch),
2324            self.state.get_min_pitch(),
2325            max_pitch,
2326        ));
2327        if self.state.get_pitch() == before {
2328            return false;
2329        }
2330        self.hold_momentum_anchor(anchor);
2331        true
2332    }
2333
2334    /// Puts the camera's animations on the host's frame clock: commands start
2335    /// at the latest frame's time rather than at `Instant::now()` when they are
2336    /// made, and the map samples them at it. Each frame then shows its
2337    /// animations exactly one frame further on, whenever the input or the
2338    /// map's update ran, and an animation started between frames moves by
2339    /// that frame's interval on the next one: no frame repeats the
2340    /// camera, and none skips ahead. `None` goes back to `Instant::now()`.
2341    ///
2342    /// Orbis starts animations on the first frame after the call, which
2343    /// keeps the camera still for that frame; a glide that continues a drag
2344    /// would pause there.
2345    pub fn set_frame_time(&mut self, time: Option<Instant>) {
2346        self.frame_time.set(time);
2347    }
2348
2349    /// The clock that [`set_frame_time`](Self::set_frame_time) sets.
2350    pub(crate) fn frame_clock(&self) -> FrameClock {
2351        self.frame_time.clone()
2352    }
2353
2354    /// The host's frame time, unless it is stale: older than
2355    /// [`STALE_FRAME_TIME`], as when the host stopped drawing frames or
2356    /// forgot to set it this frame. A stale frame time would start a command
2357    /// in the past, which the next frame would show already under way or
2358    /// over.
2359    pub(crate) fn frame_time(&self) -> Option<Instant> {
2360        self.fresh_frame_time(Instant::now())
2361    }
2362
2363    fn fresh_frame_time(&self, now: Instant) -> Option<Instant> {
2364        self.frame_time.get().filter(|&time| now.saturating_duration_since(time) <= STALE_FRAME_TIME)
2365    }
2366
2367    /// When commands start: the frame time, or now.
2368    fn now(&self) -> Instant {
2369        let now = Instant::now();
2370        self.fresh_frame_time(now).unwrap_or(now)
2371    }
2372
2373    pub(crate) fn cancel_transitions(&mut self) {
2374        let mut finished = std::mem::take(&mut self.transitions);
2375        for transition in &mut finished {
2376            transition.ended_by(TransitionOutcome::Cancelled);
2377        }
2378        self.update_movement_flags();
2379        self.finish_transitions(finished);
2380    }
2381
2382    /// Cancels the commands whose [`AnimationOptions::transition_id`] equals
2383    /// `transition_id`, leaves the others running, and returns whether any
2384    /// command ended.
2385    pub fn cancel_transitions_with_id(&mut self, transition_id: u64) -> bool {
2386        let mut finished: Vec<_> = self
2387            .transitions
2388            .extract_if(.., |transition| transition.animation.transition_id == Some(transition_id))
2389            .collect();
2390        if finished.is_empty() {
2391            return false;
2392        }
2393        for transition in &mut finished {
2394            transition.ended_by(TransitionOutcome::Cancelled);
2395        }
2396        self.update_movement_flags();
2397        self.finish_transitions(finished);
2398        true
2399    }
2400
2401    /// Ends the running commands as closed, without a camera change. A map's
2402    /// owner calls it before it drops the map, so that it hears every
2403    /// command's end.
2404    pub fn close(&mut self) {
2405        for transition in std::mem::take(&mut self.transitions) {
2406            let end = TransitionEnd { outcome: TransitionOutcome::Closed, ..transition.end() };
2407            self.report_end(transition.command, transition.animation.transition_id, end);
2408        }
2409        self.update_movement_flags();
2410    }
2411
2412    // MARK: - Gesture
2413
2414    /// Moves the camera relative to where it is, as a gesture does
2415    /// (the C API's `mln_map_apply_camera_delta`). See
2416    /// [`CameraDelta`].
2417    pub fn apply_camera_delta(&mut self, delta: &CameraDelta) -> Result<CameraCommandId, CameraError> {
2418        delta.validate()?;
2419        Ok(self.command(|transform| transform.apply_camera_delta_now(delta)))
2420    }
2421
2422    fn apply_camera_delta_now(&mut self, delta: &CameraDelta) {
2423        let source = gesture_source(delta.phase);
2424        let pans = delta.offset.is_some();
2425        let eases = delta.scale.is_some() || delta.bearing.is_some() || delta.pitch.is_some();
2426        // With momentum, the command's end is the momentum's, and the delta's
2427        // own changes, which can't animate, apply before it starts.
2428        // Otherwise the pan and the ease end the command together.
2429        let parts = match delta.momentum {
2430            Some(_) => AnimationOptions::default(),
2431            None => delta.animation,
2432        };
2433        self.silent = delta.momentum.is_some();
2434        self.join_ends(u32::from(pans) + u32::from(eases));
2435        self.gesture_phase_before(delta.phase);
2436        if delta.phase != GesturePhase::None {
2437            self.gesture.change(
2438                delta.scale.is_some_and(|scale| scale != 1.0),
2439                delta.bearing.is_some_and(|bearing| bearing != 0.0),
2440                delta.pitch.is_some_and(|pitch| pitch != 0.0),
2441            );
2442        }
2443        self.with_source(source, |transform| {
2444            if let Some(offset) = delta.offset {
2445                // Validation keeps the offset finite, so it has a LatLng. The
2446                // anchor is the point the drag holds, which the globe keeps
2447                // under it.
2448                let _ = transform.move_by_with_anchor(&offset, delta.anchor, &parts);
2449            }
2450            if eases {
2451                let current = transform.get_camera_options(None);
2452                let target = CameraOptions {
2453                    zoom: delta.scale.map(|scale| current.zoom.unwrap_or(0.0) + scale.log2()),
2454                    bearing: delta.bearing.map(|bearing| current.bearing.unwrap_or(0.0) + bearing),
2455                    pitch: delta.pitch.map(|pitch| current.pitch.unwrap_or(0.0) + pitch),
2456                    anchor: delta.anchor,
2457                    ..CameraOptions::default()
2458                };
2459                transform.ease_to(&target, &parts);
2460            }
2461        });
2462        self.silent = false;
2463        match delta.momentum {
2464            Some(mut momentum) => {
2465                self.gesture.mask_snaps(&mut momentum);
2466                // The gesture ends as its momentum starts, rather than in
2467                // `gesture_phase_after`, so that a momentum with nothing to
2468                // move, which ends at once, ends it too.
2469                self.gesture.active = false;
2470                let serial = self.gesture.serial;
2471                self.with_source(CameraChangeSource::Momentum, |transform| {
2472                    transform.start_momentum_now(&momentum, &delta.animation, Some(serial));
2473                });
2474            }
2475            None if !pans && !eases => self.end_unstarted(&delta.animation, TransitionOutcome::Completed),
2476            None => {}
2477        }
2478        self.gesture_phase_after(delta.phase, delta.momentum.is_some());
2479    }
2480
2481    /// Moves the camera to absolute values, as a command or a gesture
2482    /// (the C API's `mln_map_update_camera`). See [`CameraUpdate`].
2483    pub fn update_camera(&mut self, update: &CameraUpdate) -> CameraCommandId {
2484        self.command(|transform| transform.update_camera_now(update))
2485    }
2486
2487    fn update_camera_now(&mut self, update: &CameraUpdate) {
2488        self.gesture_phase_before(update.phase);
2489        if update.phase != GesturePhase::None {
2490            // A gesture's update can repeat a field it doesn't change.
2491            let current = self.get_camera_options(None);
2492            let changes = |value: Option<f64>, now: Option<f64>| value.is_some() && value != now;
2493            self.gesture.change(
2494                changes(update.camera.zoom, current.zoom),
2495                changes(update.camera.bearing, current.bearing),
2496                changes(update.camera.pitch, current.pitch),
2497            );
2498        }
2499        self.with_source(gesture_source(update.phase), |transform| match update.mode {
2500            CameraUpdateMode::Jump => {
2501                transform.ease(&update.camera, &AnimationOptions { duration: None, ..update.animation });
2502            }
2503            CameraUpdateMode::Ease => transform.ease(&update.camera, &update.animation),
2504            CameraUpdateMode::Fly => transform.fly(&update.camera, &update.animation, false),
2505        });
2506        self.gesture_phase_after(update.phase, false);
2507    }
2508
2509    /// `Begin` cancels the running commands, and `Begin` and `Update` mark
2510    /// the gesture, before its change applies, so that the change follows
2511    /// the gesture rules (an ease doesn't fly, and wraps the longitude as a
2512    /// drag). The first phase after a gesture ended starts a new one, which
2513    /// an earlier gesture's momentum no longer ends.
2514    fn gesture_phase_before(&mut self, phase: GesturePhase) {
2515        if phase != GesturePhase::None && (phase == GesturePhase::Begin || !self.gesture.active) {
2516            self.gesture = GestureState { serial: self.gesture.serial.wrapping_add(1), ..GestureState::default() };
2517        }
2518        if phase == GesturePhase::Begin {
2519            self.cancel_transitions();
2520        }
2521        if matches!(phase, GesturePhase::Begin | GesturePhase::Update) {
2522            self.gesture.active = true;
2523            self.set_gesture_in_progress(true);
2524        }
2525    }
2526
2527    /// `Cancel` cancels the running commands after its change applies, and
2528    /// `End` and `Cancel` end the gesture: at once, or when its momentum
2529    /// ends.
2530    fn gesture_phase_after(&mut self, phase: GesturePhase, momentum: bool) {
2531        if phase == GesturePhase::Cancel {
2532            self.cancel_transitions();
2533        }
2534        if matches!(phase, GesturePhase::End | GesturePhase::Cancel) {
2535            self.gesture.active = false;
2536            if !momentum {
2537                self.set_gesture_in_progress(false);
2538            }
2539        }
2540    }
2541
2542    /// The end of a gesture's momentum ends the gesture, unless another
2543    /// gesture started since.
2544    fn end_gesture_momentum(&mut self, gesture: Option<u64>) {
2545        if gesture == Some(self.gesture.serial) && !self.gesture.active {
2546            self.set_gesture_in_progress(false);
2547        }
2548    }
2549
2550    pub(crate) fn set_gesture_in_progress(&mut self, in_progress: bool) {
2551        self.state.set_gesture_in_progress(in_progress);
2552    }
2553
2554    pub fn is_gesture_in_progress(&self) -> bool {
2555        self.state.is_gesture_in_progress()
2556    }
2557
2558    // MARK: - Transform state
2559
2560    pub fn get_state(&self) -> &TransformState {
2561        &self.state
2562    }
2563
2564    #[cfg(test)]
2565    pub(crate) fn is_rotating(&self) -> bool {
2566        self.state.is_rotating()
2567    }
2568
2569    #[cfg(test)]
2570    pub(crate) fn is_scaling(&self) -> bool {
2571        self.state.is_scaling()
2572    }
2573
2574    #[cfg(test)]
2575    pub(crate) fn is_panning(&self) -> bool {
2576        self.state.is_panning()
2577    }
2578
2579    // MARK: Conversion and projection
2580
2581    pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
2582        let mut point = self.state.lat_lng_to_screen_coordinate(lat_lng);
2583        point.y = f64::from(self.state.get_size().height) - point.y;
2584        point
2585    }
2586
2587    /// The location under `point`, in screen coordinates (y down).
2588    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN
2589    /// or infinite point.
2590    pub fn screen_coordinate_to_lat_lng(&self, point: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
2591        let mut flipped_point = *point;
2592        flipped_point.y = f64::from(self.state.get_size().height) - flipped_point.y;
2593        self.state.screen_coordinate_to_lat_lng(&flipped_point, wrap_mode)
2594    }
2595
2596    #[cfg(test)]
2597    pub(crate) fn get_free_camera_options(&self) -> FreeCameraOptions {
2598        self.state.get_free_camera_options()
2599    }
2600
2601    pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
2602        self.cancel_transitions();
2603        self.state.set_free_camera_options(options);
2604    }
2605}
2606
2607fn gesture_source(phase: GesturePhase) -> CameraChangeSource {
2608    if phase == GesturePhase::None { CameraChangeSource::Command } else { CameraChangeSource::Gesture }
2609}
2610
2611/// An animation frame's padding, `t` of the way from `start` to `end`; `None`
2612/// when it has none (see [`frame_edge_insets`]). C++ interpolates the insets
2613/// even when they don't change; the port keeps them, so that infinite insets
2614/// don't log on every frame.
2615fn interpolate_edge_insets(start: &EdgeInsets, end: &EdgeInsets, t: f64) -> Option<EdgeInsets> {
2616    if start == end {
2617        return Some(*end);
2618    }
2619    frame_edge_insets(
2620        interpolate(&start.top, &end.top, t),
2621        interpolate(&start.left, &end.left, t),
2622        interpolate(&start.bottom, &end.bottom, t),
2623        interpolate(&start.right, &end.right, t),
2624    )
2625}
2626
2627/// We don't want to show horizon: limit max pitch based on edge insets.
2628/// (`Transform::getMaxPitchForEdgeInsets`, called on the state inside the
2629/// frame function.)
2630fn get_max_pitch_for_edge_insets(state: &TransformState, insets: &EdgeInsets) -> f64 {
2631    // See TransformState::getCenterOffset.
2632    let center_offset_y = 0.5 * (insets.top - insets.bottom);
2633    if center_offset_y == 0.0 {
2634        return state.get_max_pitch();
2635    }
2636
2637    let height = state.get_size().height;
2638    debug_assert!(height != 0);
2639    let field_of_view = f64::from(state.get_field_of_view());
2640    // Half of fov is the field of view above perspective center.
2641    let tangent_of_fov_above_center_angle =
2642        (0.5 + center_offset_y / f64::from(height)) * 2.0 * (field_of_view / 2.0).tan();
2643    let fov_above_center = tangent_of_fov_above_center_angle.atan();
2644    f64::max(state.get_min_pitch(), state.get_max_pitch() + field_of_view / 2.0 - fov_above_center)
2645}
2646
2647#[cfg(test)]
2648#[path = "transform_test.rs"]
2649mod transform_test;