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