Skip to main content

mln_map/
transform.rs

1//! The map's camera: the commands, animations, gestures and momentum that
2//! move it within its limits.
3//!
4//! Each command is a transition whose frame function takes the state and
5//! returns the camera at the command's progress, which `apply_transitions`
6//! composes with the other commands' cameras. The transform calls no
7//! observer: it queues what happens as `TransformEvent`s, which its owner
8//! drains once the call returns, so no callback runs while the transform
9//! changes. Over terrain, the rules of `terrain` stand the camera on the
10//! ground and keep its eye above it.
11
12use std::f64::consts::PI;
13use std::rc::Rc;
14use std::sync::Arc;
15use std::time::Duration;
16
17use geometry::Point;
18use mln_map_types::{
19    AnimationOptions, CameraLimits, CameraOptions, CenterAndBearing, ConstrainMode, FreeCameraOptions,
20    NorthOrientation, ProjectionMode, TransformState, TransitionEnd, VerticalPerspectiveProjection, View, ViewportMode,
21};
22use mln_style::types::ProjectionDefinition;
23use mln_util::constants::M2PI;
24use mln_util::error::Error;
25use mln_util::geo::{EdgeInsets, LatLng, ScreenCoordinate, WrapMode};
26use mln_util::projection::Projection;
27use mln_util::size::Size;
28use mln_util::time::Instant;
29use parking_lot::Mutex;
30
31use crate::log_target;
32
33mod anchor;
34mod animation;
35mod gesture;
36mod momentum;
37mod terrain;
38mod transition;
39
40use gesture::GestureState;
41pub use terrain::TerrainGround;
42pub(crate) use terrain::lowest_ground;
43use transition::{FrameFn, JointEnd, Transition};
44
45use crate::map_event::{CameraChange, CameraChangeSource};
46
47/// A frame time older than this is stale, and counts as unset (see
48/// [`Transform::set_frame_time`]): longer than a frame at 10 fps, so any host
49/// that draws sets a fresh one first.
50pub const STALE_FRAME_TIME: Duration = Duration::from_millis(100);
51
52/// Converts the given angle (in radians) to be numerically close to the
53/// anchor angle, allowing it to be interpolated properly without sudden
54/// jumps.
55fn normalize_angle(mut angle: f64, anchor_angle: f64) -> f64 {
56    if angle.is_nan() || anchor_angle.is_nan() {
57        return 0.0;
58    }
59
60    angle = mln_math::wrap(angle, -PI, PI);
61    if angle == -PI {
62        angle = PI;
63    }
64    let diff = (angle - anchor_angle).abs();
65    if (angle - M2PI - anchor_angle).abs() < diff {
66        angle -= M2PI;
67    }
68    if (angle + M2PI - anchor_angle).abs() < diff {
69        angle += M2PI;
70    }
71
72    angle
73}
74
75/// A `LatLng` from coordinates the transform state keeps valid, saturating
76/// any that aren't (see [`LatLng::saturating`]).
77fn lat_lng(lat: f64, lon: f64) -> LatLng {
78    LatLng::saturating(lat, lon, WrapMode::Unwrapped)
79}
80
81/// An animation frame's insets, or `None` when one is NaN (infinite insets
82/// interpolate to NaN): the frame keeps the insets it has.
83fn frame_edge_insets(top: f64, left: f64, bottom: f64, right: f64) -> Option<EdgeInsets> {
84    if [top, left, bottom, right].iter().any(|value| value.is_nan()) {
85        log::error!(target: log_target::GENERAL, "an animation frame's insets are NaN");
86        return None;
87    }
88    Some(EdgeInsets::new(top, left, bottom, right))
89}
90
91/// An animation frame's `Projection::unproject`, or `None` (logged) for a
92/// point with no `LatLng`, such as NaN: the frame keeps the center and zoom,
93/// as [`frame_edge_insets`] does.
94fn frame_unproject(p: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Option<LatLng> {
95    Projection::unproject(p, scale, wrap_mode)
96        .map_err(|e| log::error!(target: log_target::GENERAL, "{}", e.message))
97        .ok()
98}
99
100/// Identifies a camera command that the transform started, in the
101/// [`TransformEvent::CommandEnded`] that reports its end. Each command the
102/// transform starts gets its own.
103#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
104pub struct CameraCommandId(u64);
105
106/// How a camera command ended.
107#[derive(Clone, Copy, Debug, PartialEq)]
108pub struct CommandEnd {
109    pub command: CameraCommandId,
110    /// The command's [`AnimationOptions::transition_id`].
111    pub transition_id: Option<u64>,
112    pub end: TransitionEnd,
113}
114
115/// What the transform reports, in order, for its owner to drain with
116/// [`Transform::drain_events`].
117#[derive(Clone, Copy, Debug, PartialEq)]
118pub enum TransformEvent {
119    CameraWillChange(CameraChange),
120    CameraIsChanging,
121    CameraDidChange(CameraChange),
122    /// A command ended: every command ends exactly once, unless the
123    /// transform is dropped with the command still running (see
124    /// [`Transform::close`]).
125    CommandEnded(CommandEnd),
126}
127
128pub(crate) type ProjectionForZoomFn = Rc<dyn Fn(f64) -> ProjectionDefinition>;
129
130// The camera fields that a command sets and owns, as bits.
131const CENTER: u16 = 1 << 0;
132const ZOOM: u16 = 1 << 1;
133const BEARING: u16 = 1 << 2;
134const PITCH: u16 = 1 << 3;
135const PADDING: u16 = 1 << 4;
136const ALTITUDE: u16 = 1 << 5;
137const ROLL: u16 = 1 << 6;
138const FOV: u16 = 1 << 7;
139
140/// The fields a command sets.
141fn camera_fields(camera: &CameraOptions) -> u16 {
142    let field = |set: bool, field: u16| if set { field } else { 0 };
143    field(camera.center.is_some(), CENTER)
144        | field(camera.zoom.is_some(), ZOOM)
145        | field(camera.bearing.is_some(), BEARING)
146        | field(camera.pitch.is_some(), PITCH)
147        | field(camera.padding.is_some(), PADDING)
148        | field(camera.center_altitude.is_some(), ALTITUDE)
149        | field(camera.roll.is_some(), ROLL)
150        | field(camera.fov.is_some(), FOV)
151}
152
153/// The time of the latest frame that a map's host drew, which the map's
154/// animations sample at and its camera commands start from (see
155/// [`Transform::set_frame_time`]). A clone shares the clock, so the thread
156/// that draws can set it while the map lives on another.
157#[derive(Clone, Debug, Default)]
158pub struct FrameClock(Arc<Mutex<Option<Instant>>>);
159
160impl FrameClock {
161    pub fn set(&self, time: Option<Instant>) {
162        *self.0.lock() = time;
163    }
164
165    #[must_use]
166    pub fn get(&self) -> Option<Instant> {
167        *self.0.lock()
168    }
169}
170
171pub struct Transform {
172    state: TransformState,
173
174    transitions: Vec<Transition>,
175    /// What the transform reports, for [`Self::drain_events`].
176    events: Vec<TransformEvent>,
177    /// The command being started, which the transitions it starts report
178    /// their end to (see [`Self::command`]), unless `silent`.
179    command: Option<CameraCommandId>,
180    /// Set while a command starts transitions whose ends another of its
181    /// transitions reports: a delta's changes before its momentum.
182    silent: bool,
183    next_command: u64,
184    /// The commands made of several transitions, whose end waits for the
185    /// last of them.
186    joint_ends: Vec<JointEnd>,
187    /// What the commands being started come from: a command unless a gesture
188    /// or a momentum starts them (see [`Self::with_source`]).
189    source: CameraChangeSource,
190    gesture: GestureState,
191    /// From a gesture's first change until it ends, its momentum included.
192    /// Over terrain, a gesture holds the altitude, and comes to rest on the
193    /// ground as it ends (see `terrain`).
194    gesture_in_progress: bool,
195    /// The fields that the running commands move (`CENTER`, `ZOOM`,
196    /// `BEARING`), as of the last frame.
197    moving: u16,
198    /// The host's current frame time (see [`Self::set_frame_time`]).
199    frame_time: FrameClock,
200    projection_for_zoom: Option<ProjectionForZoomFn>,
201    globe_drag_hold: Option<GlobeDragHold>,
202    /// The terrain the camera stands on ([`Self::set_terrain`]).
203    terrain: Option<TerrainGround>,
204    /// The time of the last frame that composed the commands' cameras,
205    /// from which the altitude over terrain heads on
206    /// ([`Self::ease_altitude`]).
207    last_frame: Option<Instant>,
208}
209
210/// The location a drag on the globe holds under the cursor, from the step
211/// that grabbed it. The next step carries the drag on if it starts where
212/// that one ended, at `cursor` with the camera and the view as that step
213/// left them; any other step grabs the location under where it starts.
214#[derive(Clone, Copy, Debug)]
215struct GlobeDragHold {
216    location: LatLng,
217    /// The height in meters of the sphere `location` is on.
218    height: f64,
219    cursor: ScreenCoordinate,
220    camera: CameraOptions,
221    size: Size,
222}
223
224impl Transform {
225    #[must_use]
226    pub fn new(constrain_mode: ConstrainMode, viewport_mode: ViewportMode) -> Self {
227        Self::from_state(TransformState::new(constrain_mode, viewport_mode))
228    }
229
230    pub(crate) fn from_state(state: TransformState) -> Self {
231        Transform {
232            state,
233            transitions: Vec::new(),
234            events: Vec::new(),
235            command: None,
236            silent: false,
237            next_command: 0,
238            joint_ends: Vec::new(),
239            source: CameraChangeSource::Command,
240            gesture: GestureState::default(),
241            gesture_in_progress: false,
242            moving: 0,
243            frame_time: FrameClock::default(),
244            projection_for_zoom: None,
245            globe_drag_hold: None,
246            terrain: None,
247            last_frame: None,
248        }
249    }
250
251    /// Drains what the transform reported since the last call, oldest
252    /// first. The transform keeps its buffer for what it reports next.
253    pub fn drain_events(&mut self) -> std::vec::Drain<'_, TransformEvent> {
254        self.events.drain(..)
255    }
256
257    /// Whether the transform reported something that
258    /// [`drain_events`](Self::drain_events) hasn't drained.
259    #[must_use]
260    pub fn has_events(&self) -> bool {
261        !self.events.is_empty()
262    }
263
264    fn emit(&mut self, event: TransformEvent) {
265        self.events.push(event);
266    }
267
268    // MARK: - Map View
269
270    pub fn resize(&mut self, size: Size) -> Result<(), Error> {
271        if size.is_empty() {
272            return Err(Error::invalid_argument("failed to resize: size is empty"));
273        }
274
275        if self.state.view().size() == size {
276            return Ok(());
277        }
278
279        self.emit(TransformEvent::CameraWillChange(CameraChange::default()));
280        self.state.set_size(size);
281        let (scale, center) = self.state.constrain_screen(self.state.view().scale());
282        if let Some(center) = center {
283            // Turns out that if you resize during a transition any changes
284            // made to the state will be ignored :( So if we have to constrain
285            // because of a resize and a transition is in progress - cancel
286            // the transition!
287            if self.in_transition() {
288                self.cancel_transitions();
289            }
290
291            // Setting x and y isn't enough to change the center: Cc and Bc
292            // must change too, which setLatLngZoom does.
293            let zoom = mln_map_types::scale_zoom(scale);
294            self.state.set_lat_lng_zoom(&center, zoom);
295            self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
296
297            return Ok(());
298        }
299        self.state.constrain_position(scale);
300
301        self.emit(TransformEvent::CameraDidChange(CameraChange::default()));
302        Ok(())
303    }
304
305    // MARK: - Camera
306
307    /// Returns the current camera options.
308    #[must_use]
309    pub fn camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
310        self.state.camera_options(padding)
311    }
312
313    /// Change any combination of center, zoom, bearing, and pitch, without a
314    /// transition. Omitted options keep their current animations.
315    pub fn jump_to(&mut self, camera: &CameraOptions) -> CameraCommandId {
316        self.command(|transform| transform.jump(camera))
317    }
318
319    fn jump(&mut self, camera: &CameraOptions) {
320        // On the globe the zoom decides how close to a pole the center can be.
321        // GL JS's jump bounds the center by the zoom it lands on, where its
322        // ease bounds it by the zoom it starts from unless given one, so the
323        // jump settles the zoom.
324        if self.state.view().is_globe()
325            && let Some(center) = camera.center
326            && camera.zoom.is_none()
327        {
328            let zoom = self.view().zoom()
329                + VerticalPerspectiveProjection::zoom_adjustment(
330                    self.view().center(WrapMode::Wrapped).latitude(),
331                    center.latitude(),
332                );
333            self.ease_to(&CameraOptions { zoom: Some(zoom), ..*camera }, &AnimationOptions::default());
334            return;
335        }
336        self.ease_to(camera, &AnimationOptions::default());
337    }
338
339    // MARK: - Position
340
341    /// Whether the globe is drawn on a sized screen, so screen points reach
342    /// it. Before the first resize, screen-point gestures are Mercator's.
343    fn globe_on_screen(&self) -> bool {
344        self.state.view().is_globe() && !self.state.view().size().is_empty()
345    }
346
347    /// Pans the map by the given amount.
348    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN
349    /// or infinite offset.
350    pub fn move_by(
351        &mut self,
352        offset: &ScreenCoordinate,
353        animation: &AnimationOptions,
354    ) -> Result<CameraCommandId, Error> {
355        self.move_by_with_anchor(offset, None, animation)
356    }
357
358    /// Moves the map by `offset`. A drag on the globe turns the planet so
359    /// that the location under `anchor` follows the cursor. The ground under
360    /// the cursor before the move follows it, on the plane at that ground's
361    /// height, or on the globe the sphere: sea level on the flat map, the
362    /// drawn ground over terrain ([`Self::set_terrain`]); without an anchor,
363    /// or with one that grabs no ground, the map moves on the plane or the
364    /// sphere at the center's altitude. On the globe, with the
365    /// bearing held, steps that follow one another, each starting at the
366    /// `anchor` of the one before with the camera as it left it, hold the
367    /// location the first of them grabbed, wherever
368    /// [`VerticalPerspectiveProjection::drag_center_holding`] has a center
369    /// that does. Fails as [`move_by`](Self::move_by) does.
370    pub fn move_by_with_anchor(
371        &mut self,
372        offset: &ScreenCoordinate,
373        anchor: Option<ScreenCoordinate>,
374        animation: &AnimationOptions,
375    ) -> Result<CameraCommandId, Error> {
376        let mut moved = Ok(());
377        let command = self.command(|transform| moved = transform.move_by_now(offset, anchor, animation));
378        moved.map(|()| command)
379    }
380
381    fn move_by_now(
382        &mut self,
383        offset: &ScreenCoordinate,
384        anchor: Option<ScreenCoordinate>,
385        animation: &AnimationOptions,
386    ) -> Result<(), Error> {
387        let flipped = |state: &TransformState, point: &ScreenCoordinate| {
388            ScreenCoordinate::new(point.x, f64::from(state.view().size().height) - point.y)
389        };
390        let size = self.state.view().size();
391        let view_center = self.state.view().padding().center_in(size);
392        let fling_duration = animation.duration.filter(|duration| *duration > Duration::ZERO);
393        let globe = self.globe_on_screen();
394        if globe && (offset.x.is_nan() || offset.y.is_nan()) {
395            return Err(Error::invalid_argument("offset must not be NaN"));
396        }
397        if globe && (!offset.x.is_finite() || !offset.y.is_finite()) {
398            return Err(Error::invalid_argument("offset must not be infinite"));
399        }
400        if globe
401            && let Some(duration) = fling_duration
402            && self.state.view().globe_free_bearing()
403        {
404            // A fling with the bearing free turns the planet on about the axis
405            // the drag turned it about, so it carries on over a pole instead
406            // of spinning round it.
407            let start = CenterAndBearing {
408                center: self.view().center(WrapMode::Unwrapped),
409                bearing: -mln_math::rad2deg(self.view().angle()),
410            };
411            let end = VerticalPerspectiveProjection::fling_camera(
412                self.state.view(),
413                &flipped(&self.state, &view_center),
414                &ScreenCoordinate::new(offset.x, -offset.y),
415            );
416            let start_zoom = self.view().zoom();
417            let frame: FrameFn = Box::new(move |state: &TransformState, t: f64| {
418                let camera = VerticalPerspectiveProjection::interpolate_camera(&start, &end, t);
419                let center = state.constrained_center(&camera.center, state.view().zoom());
420                CameraOptions {
421                    center: Some(center),
422                    zoom: Some(
423                        start_zoom
424                            + VerticalPerspectiveProjection::zoom_adjustment(
425                                start.center.latitude(),
426                                center.latitude(),
427                            ),
428                    ),
429                    bearing: Some(camera.bearing),
430                    ..Default::default()
431                }
432            });
433            // The fling sets the center, the zoom that keeps the planet's
434            // size and the bearing.
435            let fields = CameraOptions {
436                center: Some(end.center),
437                zoom: Some(start_zoom),
438                bearing: Some(end.bearing),
439                ..Default::default()
440            };
441            self.start_transition(&fields, animation, frame, None, duration, false);
442            return Ok(());
443        }
444
445        if globe && fling_duration.is_some() {
446            // An animated move, a fling, turns the globe as GL JS's inertia
447            // does: the location under the far end of a long one can be off
448            // the planet or over a pole. It stops short of half a turn, which
449            // the ease would take the other way round.
450            let mut center = self.state.constrained_center(
451                &VerticalPerspectiveProjection::pan_center(self.state.view(), offset),
452                self.view().zoom(),
453            );
454            let longitude = self.view().center(WrapMode::Unwrapped).longitude();
455            if (center.longitude() - longitude).abs() > 180.0 {
456                center = lat_lng(center.latitude(), longitude + 179.5f64.copysign(center.longitude() - longitude));
457            }
458            self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
459            return Ok(());
460        }
461
462        if globe {
463            // A drag turns the globe as GL JS's does: one rotation that brings
464            // the location under the cursor back under it with the bearing
465            // held, around the cursor when it is on the planet and around the
466            // center otherwise. With a free bearing the rotation turns the
467            // bearing too, so the location stays under the cursor.
468            //
469            // With the bearing held, that rotation loses the turn it would
470            // give the bearing, so step after step the location slips from
471            // under the cursor. Where a center holds it there exactly, the
472            // drag takes that center instead, for the location its first step
473            // grabbed. A step the exact center isn't for doesn't hold: the
474            // step after it grabs anew, so the drag goes from one way to the
475            // other without a jump.
476            //
477            // The location is on the sphere at the height of the ground the
478            // drag grabbed, or else at the center's altitude, as the planes
479            // of a drag on Mercator are.
480            let from = anchor.map(|anchor| ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y));
481            let held = self.globe_drag_hold.take().filter(|held| {
482                from.is_some_and(|from| (held.cursor.x - from.x).hypot(held.cursor.y - from.y) < 1e-3)
483                    && !self.state.view().globe_free_bearing()
484                    && held.size == size
485                    && held.camera == self.camera_options(None)
486            });
487            let height = match (held, anchor.zip(from)) {
488                (Some(held), _) => held.height,
489                (None, Some((anchor, from))) => self.anchor_height(&from, &anchor),
490                (None, None) => self.view().center_altitude(),
491            };
492            let on_globe = |state: &TransformState, point: &ScreenCoordinate| {
493                VerticalPerspectiveProjection::screen_coordinate_hits_globe(
494                    state.view(),
495                    &flipped(state, point),
496                    height,
497                )
498            };
499            let grab = match anchor {
500                Some(anchor) if on_globe(&self.state, &anchor) => anchor,
501                _ => view_center,
502            };
503            let pan_delta = ScreenCoordinate::new(offset.x, -offset.y);
504            let mut camera = CameraOptions::default();
505            let hold = match anchor.zip(from) {
506                Some((anchor, from)) if !self.state.view().globe_free_bearing() && on_globe(&self.state, &anchor) => {
507                    let location = match held {
508                        Some(held) => Some(held.location),
509                        None if on_globe(&self.state, &from) => self
510                            .state
511                            .view()
512                            .screen_coordinate_to_lat_lng_at(&flipped(&self.state, &from), height, WrapMode::Unwrapped)
513                            .ok(),
514                        None => None,
515                    };
516                    location.and_then(|location| {
517                        VerticalPerspectiveProjection::drag_center_holding(
518                            self.state.view(),
519                            &location,
520                            &flipped(&self.state, &anchor),
521                            height,
522                        )
523                        .map(|center| (location, anchor, center))
524                    })
525                }
526                _ => None,
527            };
528            let mut center = if let Some((_, _, center)) = hold {
529                center
530            } else if self.state.view().globe_free_bearing() {
531                let drag = VerticalPerspectiveProjection::drag_camera(
532                    self.state.view(),
533                    &flipped(&self.state, &grab),
534                    &pan_delta,
535                    height,
536                );
537                camera = CameraOptions { bearing: Some(drag.bearing), ..camera };
538                drag.center
539            } else {
540                VerticalPerspectiveProjection::drag_center(
541                    self.state.view(),
542                    &flipped(&self.state, &grab),
543                    &pan_delta,
544                    height,
545                )
546            };
547            center = self.state.constrained_center(&center, self.view().zoom());
548            let zoom = self.view().zoom()
549                + VerticalPerspectiveProjection::zoom_adjustment(
550                    self.view().center(WrapMode::Wrapped).latitude(),
551                    center.latitude(),
552                );
553            self.ease_to(&CameraOptions { center: Some(center), zoom: Some(zoom), ..camera }, animation);
554            self.globe_drag_hold = hold.map(|(location, cursor, _)| GlobeDragHold {
555                location,
556                height,
557                cursor,
558                camera: self.camera_options(None),
559                size,
560            });
561            return Ok(());
562        }
563
564        let mut center_offset = *offset;
565
566        // Reduce the offset so that it never goes past the horizon. If it
567        // goes past the horizon, the pan direction is opposite of the
568        // intended direction.
569        let pitch = self.state.view().pitch();
570        let offset_length = offset.x.hypot(offset.y);
571        if pitch > 0.0 && offset_length > 0.0 {
572            let camera_to_center =
573                0.5 * f64::from(self.state.view().size().height) / (self.state.view().fov() / 2.0).tan();
574            let pixels_to_horizon = (camera_to_center / pitch.tan()).abs();
575            // must be < 1 to keep the offset short of the horizon
576            let horizon_factor = 0.75;
577            let scale = pixels_to_horizon * horizon_factor / offset_length;
578            if scale < 1.0 {
579                center_offset = ScreenCoordinate::new(offset.x * scale, offset.y * scale);
580            }
581        }
582
583        let size = self.state.view().size();
584        let center = self.state.view().padding().center_in(size);
585        let point_on_screen = ScreenCoordinate::new(center.x - center_offset.x, center.y - center_offset.y);
586        // The ground the pointer grabbed follows it, on its plane; without an
587        // anchor, the map moves on the plane at the center's altitude. Use
588        // unwrapped LatLng to carry information about moveBy direction.
589        let anchored = anchor.and_then(|anchor| {
590            let grabbed = ScreenCoordinate::new(anchor.x - offset.x, anchor.y - offset.y);
591            Some((grabbed, anchor, self.anchor_plane(&grabbed, &anchor)?))
592        });
593        let (from, to, height) = anchored.unwrap_or((point_on_screen, center, self.view().center_altitude()));
594        let center = self.center_moving_on_plane(&from, &to, height)?;
595        self.ease_to(&CameraOptions { center: Some(center), ..Default::default() }, animation);
596        Ok(())
597    }
598
599    // MARK: - Limits
600
601    /// Sets the limits the camera moves within (see
602    /// [`TransformState::set_limits`]).
603    pub fn set_limits(&mut self, limits: CameraLimits) -> Result<(), Error> {
604        self.state.set_limits(limits)
605    }
606
607    pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
608        self.state.set_frustum_offset(frustum_offset);
609    }
610
611    // MARK: - Projection
612
613    pub fn set_projection_definition(&mut self, definition: &ProjectionDefinition) {
614        self.state.set_projection_definition(definition);
615    }
616
617    /// The projection the style gives at a zoom, which constrains an
618    /// animation's target as it constrains a jump.
619    pub(crate) fn set_projection_for_zoom(&mut self, projection_for_zoom: Option<ProjectionForZoomFn>) {
620        self.projection_for_zoom = projection_for_zoom;
621    }
622
623    pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
624        self.state.set_globe_free_bearing(free_bearing);
625    }
626
627    pub(crate) fn is_globe_free_bearing(&self) -> bool {
628        self.state.view().globe_free_bearing()
629    }
630
631    #[cfg(test)]
632    pub(crate) fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
633        self.state.view().is_location_occluded(lat_lng)
634    }
635
636    // MARK: - North Orientation
637
638    pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
639        self.state.set_north_orientation(orientation);
640        self.state.constrain_position(self.state.view().scale());
641    }
642
643    // MARK: - Constrain mode
644
645    pub fn set_constrain_mode(&mut self, mode: ConstrainMode) {
646        self.state.set_constrain_mode(mode);
647        self.state.constrain_position(self.state.view().scale());
648    }
649
650    // MARK: - Viewport mode
651
652    pub fn set_viewport_mode(&mut self, mode: ViewportMode) {
653        self.state.set_viewport_mode(mode);
654    }
655
656    /// Sets whether the center stands on the terrain. The map hands the
657    /// setting to [`set_terrain`](Self::set_terrain) on its next update.
658    pub fn set_center_clamped_to_ground(&mut self, clamped: bool) {
659        self.state.set_center_clamped_to_ground(clamped);
660    }
661
662    // MARK: - Projection mode
663
664    pub(crate) fn set_projection_mode(&mut self, options: &ProjectionMode) {
665        if let Some(x_skew) = options.x_skew {
666            self.state.set_x_skew(x_skew);
667        }
668        if let Some(y_skew) = options.y_skew {
669            self.state.set_y_skew(y_skew);
670        }
671        if let Some(axonometric) = options.axonometric {
672            self.state.set_axonometric(axonometric.as_bool());
673        }
674    }
675
676    // MARK: - Frame clock
677
678    /// Puts the camera's animations on the host's frame clock: commands start
679    /// at the latest frame's time rather than at `Instant::now()` when they are
680    /// made, and the map samples them at it. Each frame then shows its
681    /// animations exactly one frame further on, whenever the input or the
682    /// map's update ran, and an animation started between frames moves by
683    /// that frame's interval on the next one: no frame repeats the
684    /// camera, and none skips ahead. `None` goes back to `Instant::now()`.
685    ///
686    /// Orbis starts animations on the first frame after the call, which
687    /// keeps the camera still for that frame; a glide that continues a drag
688    /// would pause there.
689    pub fn set_frame_time(&mut self, time: Option<Instant>) {
690        self.frame_time.set(time);
691    }
692
693    /// The clock that [`set_frame_time`](Self::set_frame_time) sets.
694    pub(crate) fn frame_clock(&self) -> FrameClock {
695        self.frame_time.clone()
696    }
697
698    /// The host's frame time, unless it is stale: older than
699    /// [`STALE_FRAME_TIME`], as when the host stopped drawing frames or
700    /// forgot to set it this frame. A stale frame time would start a command
701    /// in the past, which the next frame would show already under way or
702    /// over.
703    pub(crate) fn frame_time(&self) -> Option<Instant> {
704        self.fresh_frame_time(Instant::now())
705    }
706
707    fn fresh_frame_time(&self, now: Instant) -> Option<Instant> {
708        self.frame_time.get().filter(|&time| now.saturating_duration_since(time) <= STALE_FRAME_TIME)
709    }
710
711    /// When commands start: the frame time, or now.
712    fn now(&self) -> Instant {
713        let now = Instant::now();
714        self.fresh_frame_time(now).unwrap_or(now)
715    }
716
717    /// Whether a gesture or a command moves the camera: the renderer draws
718    /// such frames for speed rather than crispness.
719    #[must_use]
720    pub fn is_camera_moving(&self) -> bool {
721        self.gesture_in_progress || self.moving & (CENTER | ZOOM | BEARING) != 0
722    }
723
724    // MARK: - Transform state
725
726    #[must_use]
727    pub fn state(&self) -> &TransformState {
728        &self.state
729    }
730
731    /// The view the camera shows now.
732    #[must_use]
733    pub fn view(&self) -> &View {
734        self.state.view()
735    }
736
737    #[cfg(test)]
738    pub(crate) fn is_rotating(&self) -> bool {
739        self.moving & BEARING != 0
740    }
741
742    #[cfg(test)]
743    pub(crate) fn is_scaling(&self) -> bool {
744        self.moving & ZOOM != 0
745    }
746
747    #[cfg(test)]
748    pub(crate) fn is_panning(&self) -> bool {
749        self.moving & CENTER != 0
750    }
751
752    // MARK: Conversion and projection
753
754    #[must_use]
755    pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
756        let mut point = self.state.view().lat_lng_to_screen_coordinate(lat_lng);
757        point.y = f64::from(self.state.view().size().height) - point.y;
758        point
759    }
760
761    /// The location under `point`, in screen coordinates (y down).
762    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN
763    /// or infinite point.
764    pub fn screen_coordinate_to_lat_lng(&self, point: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
765        let mut flipped_point = *point;
766        flipped_point.y = f64::from(self.state.view().size().height) - flipped_point.y;
767        self.state.view().screen_coordinate_to_lat_lng(&flipped_point, wrap_mode)
768    }
769
770    /// Where the line of sight through `point` (y down) meets the plane
771    /// `height` meters above sea level, on which the camera's moves solve
772    /// (see `anchor`). Fails as
773    /// [`View::screen_coordinate_to_lat_lng_at`].
774    pub(crate) fn screen_coordinate_to_lat_lng_at(
775        &self,
776        point: &ScreenCoordinate,
777        height: f64,
778        wrap_mode: WrapMode,
779    ) -> Result<LatLng, Error> {
780        self.view().screen_coordinate_to_lat_lng_at(&flip_y(self.view(), point), height, wrap_mode)
781    }
782
783    pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
784        self.cancel_transitions();
785        self.state.set_free_camera_options(options);
786    }
787}
788
789/// `point` measured from the other edge of `view`'s height: a screen point
790/// (y down) as a view point (y up), or back.
791pub(crate) fn flip_y(view: &View, point: &ScreenCoordinate) -> ScreenCoordinate {
792    ScreenCoordinate::new(point.x, f64::from(view.size().height) - point.y)
793}
794
795/// `seconds` truncated to whole nanoseconds; `None`
796/// when negative, NaN, or too long for a `Duration` made of nanoseconds. The
797/// bound is exclusive because `u64::MAX` rounds up as a double.
798fn nanos_from_secs(seconds: f64) -> Option<Duration> {
799    (seconds >= 0.0 && seconds * 1e9 < u64::MAX as f64).then(|| Duration::from_nanos((seconds * 1e9) as u64))
800}
801
802/// The most pitch that `insets` allow without showing the horizon above the
803/// padded area's center.
804fn max_pitch_for_padding(state: &TransformState, insets: &EdgeInsets) -> f64 {
805    // As `View::center_offset`.
806    let center_offset_y = 0.5 * (insets.top - insets.bottom);
807    if center_offset_y == 0.0 {
808        return state.limits().max_pitch;
809    }
810
811    let height = state.view().size().height;
812    debug_assert!(height != 0);
813    let field_of_view = state.view().fov();
814    // Half of fov is the field of view above perspective center.
815    let tangent_of_fov_above_center_angle =
816        (0.5 + center_offset_y / f64::from(height)) * 2.0 * (field_of_view / 2.0).tan();
817    let fov_above_center = tangent_of_fov_above_center_angle.atan();
818    f64::max(state.limits().min_pitch, state.limits().max_pitch + field_of_view / 2.0 - fov_above_center)
819}
820
821#[cfg(test)]
822#[path = "transform_test.rs"]
823mod transform_test;