Skip to main content

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