Skip to main content

mln_engine/camera/
transform_state.rs

1use std::f64::consts::PI;
2
3use constants::TILE_SIZE_D;
4use geometry::Point;
5use glam::{DQuat, DVec3};
6use mln_style::constants;
7use mln_style::error::Error;
8use mln_style::geo::{LatLng, LatLngBounds, WrapMode};
9use mln_style::size::Size;
10use mln_style::types::ProjectionDefinition;
11
12use crate::camera::camera::{CameraOptions, FreeCameraOptions};
13use crate::camera::camera_limits::CameraLimits;
14use crate::camera::camera_pose::CameraPose;
15use crate::camera::ground::GroundHit;
16use crate::camera::mode::ConstrainMode;
17use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
18use crate::camera::view::{
19    NorthOrientation, View, ViewParams, map_offset, max_mercator_horizon_angle, scale_zoom, zoom_scale,
20};
21use crate::geo::constants::M2PI;
22use crate::geo::projection::Projection;
23use crate::geo::{EdgeInsets, ScreenCoordinate};
24
25fn lat_lng_from_mercator(mercator_coordinate: Point<f64>, wrap_mode: WrapMode) -> Result<LatLng, Error> {
26    LatLng::with_mode(
27        mln_style::math::rad2deg(2.0 * (PI - mercator_coordinate.y * 2.0 * PI).exp().atan() - (PI / 2.0)),
28        mercator_coordinate.x * 360.0 - 180.0,
29        wrap_mode,
30    )
31}
32
33/// A map's camera with the limits that constrain it: the [`View`] it shows
34/// now, and the bounds, zoom, pitch and field of view it may move within.
35///
36/// Setters ignore numbers that aren't finite.
37#[derive(Clone, Debug, PartialEq)]
38pub struct TransformState {
39    view: View,
40    limits: CameraLimits,
41}
42
43impl Default for TransformState {
44    fn default() -> Self {
45        TransformState::new(ConstrainMode::HeightOnly)
46    }
47}
48
49impl TransformState {
50    #[must_use]
51    pub(crate) fn new(constrain_mode: ConstrainMode) -> Self {
52        TransformState { view: View::new(ViewParams::new(constrain_mode)), limits: CameraLimits::default() }
53    }
54
55    /// A state that shows `params` within `limits`, as they are.
56    pub(crate) fn from_parts(params: ViewParams, limits: CameraLimits) -> Self {
57        let mut state = TransformState { view: View::new(params), limits };
58        state.update(|_| ());
59        state
60    }
61
62    /// The view the camera shows now.
63    #[must_use]
64    pub fn view(&self) -> &View {
65        &self.view
66    }
67
68    /// Changes the view's parameters with `change`, and remakes the view if
69    /// they changed.
70    fn update(&mut self, change: impl FnOnce(&mut ViewParams)) {
71        let mut params = *self.view.params();
72        change(&mut params);
73        params.center_wrap = if params.projection_transition > 0.0 && self.limits.bounds == LatLngBounds::default() {
74            WrapMode::Wrapped
75        } else {
76            WrapMode::Unwrapped
77        };
78        if params != *self.view.params() {
79            self.view = View::new(params);
80        }
81    }
82
83    // MARK: - Projection
84
85    pub fn set_projection_definition(&mut self, definition: &ProjectionDefinition) {
86        let transition = definition.transition_state();
87        let previous = self.view.projection_transition();
88        self.update(|p| {
89            p.projection_definition = *definition;
90            p.projection_transition = transition;
91        });
92        // As GL JS's `migrateProjection` does: the globe allows lower zooms,
93        // latitudes past Mercator's and a center on another world copy, so
94        // Mercator's limits and its wrapped center apply again.
95        let leaves_globe = transition == 0.0 && previous > 0.0;
96        if leaves_globe && !self.view.size().is_empty() {
97            let wrap_mode =
98                if self.limits.bounds == LatLngBounds::default() { WrapMode::Wrapped } else { WrapMode::Unwrapped };
99            let center = self.view.center(wrap_mode);
100            let zoom = self.view.zoom();
101            self.set_lat_lng_zoom(&center, zoom);
102        }
103    }
104
105    // MARK: - Free camera
106
107    fn update_state_from_camera(&mut self, camera: &CameraPose) {
108        let position = camera.position;
109        let DVec3 { x: dx, y: dy, z: dz } = camera.forward();
110
111        let (new_roll, mut new_pitch, new_bearing) = camera.orientation_angles();
112        new_pitch = mln_style::math::clamp_f64(new_pitch, self.limits.min_pitch, self.limits.max_pitch);
113
114        // The zoom from the camera's altitude, and how far along its line of
115        // sight the ground is.
116        let center_distance = self.view.camera_to_center_distance();
117        let zoom;
118        let travel;
119        if dz < -1.0e-9 && position.z > 1.0e-9 && new_pitch <= max_mercator_horizon_angle() {
120            zoom = (center_distance / (position.z / new_pitch.cos() * TILE_SIZE_D)).log2();
121            travel = -position.z / dz;
122        } else {
123            zoom = 14.0;
124            let new_scale = mln_style::math::clamp_f64(2.0f64.powf(zoom), self.min_scale(), self.max_scale());
125            travel = center_distance / new_scale / TILE_SIZE_D;
126        }
127
128        let mercator_point = Point::new(position.x + dx * travel, position.y + dy * travel);
129        let Ok(center) = lat_lng_from_mercator(mercator_point, WrapMode::Unwrapped) else {
130            return;
131        };
132        let zoom = f64::min(zoom, self.limits.max_zoom);
133        self.set_lat_lng_zoom(&center, zoom);
134
135        let mercator_z = position.z + dz * travel;
136        let alt_m = mercator_z
137            * Projection::meters_per_pixel_at_latitude(self.view.center(WrapMode::Unwrapped).latitude(), 0.0)
138            * TILE_SIZE_D;
139        self.set_center_altitude(alt_m);
140        self.set_angle(new_bearing);
141        self.set_pitch(new_pitch);
142        self.set_roll(new_roll);
143    }
144
145    /// `position` with its altitude clamped to the zoom range, or `None` for
146    /// a position that isn't a number.
147    fn constrained_camera_position(&self, position: DVec3) -> Option<DVec3> {
148        if position.is_nan() {
149            return None;
150        }
151        let max_world_size = Projection::world_size(2.0f64.powf(self.limits.max_zoom));
152        let min_world_size = Projection::world_size(2.0f64.powf(self.min_zoom()));
153        let dist_to_center = self.view.camera_to_center_distance();
154        Some(DVec3::new(
155            position.x,
156            position.y,
157            mln_style::math::clamp_f64(position.z, dist_to_center / max_world_size, dist_to_center / min_world_size),
158        ))
159    }
160
161    /// `orientation` without the twist that a map's camera can't take, or
162    /// `None` for an orientation that isn't a rotation or that looks along
163    /// its up direction.
164    fn constrained_camera_orientation(orientation: DQuat) -> Option<DQuat> {
165        if orientation.is_nan() || orientation.length() == 0.0 {
166            return None;
167        }
168        let unit_quat = orientation.normalize();
169        CameraPose::orientation_from_frame(unit_quat * DVec3::NEG_Z, unit_quat * DVec3::NEG_Y)
170    }
171
172    pub(crate) fn set_free_camera_options(&mut self, options: &FreeCameraOptions) {
173        if !self.is_valid() {
174            return;
175        }
176
177        let mut camera = self.view.camera_pose();
178        let mut changed = false;
179        if let Some(orientation) = options.orientation
180            && orientation != camera.orientation
181            && let Some(orientation) = Self::constrained_camera_orientation(orientation)
182        {
183            camera.orientation = orientation;
184            changed = true;
185        }
186
187        if let Some(position) = options.position
188            && position != camera.position
189            && let Some(position) = self.constrained_camera_position(position)
190        {
191            camera.position = position;
192            changed = true;
193        }
194
195        if changed {
196            self.update_state_from_camera(&camera);
197        }
198    }
199
200    // MARK: - Dimensions
201
202    pub fn set_size(&mut self, size: Size) {
203        self.update(|p| p.size = size);
204    }
205
206    pub(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
207        self.update(|p| p.frustum_offset = *frustum_offset);
208    }
209
210    pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
211        self.update(|p| p.north_orientation = orientation);
212    }
213
214    #[must_use]
215    pub(crate) fn constrain_mode(&self) -> ConstrainMode {
216        self.view.params().constrain_mode
217    }
218
219    pub(crate) fn set_constrain_mode(&mut self, mode: ConstrainMode) {
220        self.update(|p| p.constrain_mode = mode);
221    }
222
223    pub(crate) fn set_center_clamped_to_ground(&mut self, clamped: bool) {
224        self.update(|p| p.center_clamped_to_ground = clamped);
225    }
226
227    pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
228        self.update(|p| p.globe_free_bearing = free_bearing);
229    }
230
231    pub(crate) fn set_padding(&mut self, padding: &EdgeInsets) {
232        self.update(|p| p.padding = *padding);
233    }
234
235    // MARK: - Camera options
236
237    /// The camera, with `padding` in place of its own if given.
238    #[must_use]
239    pub(crate) fn camera_options(&self, padding: Option<EdgeInsets>) -> CameraOptions {
240        let mut camera = self.view.camera();
241        if let Some(padding) = padding {
242            camera.padding = padding;
243        }
244        CameraOptions::from(camera)
245    }
246
247    // MARK: - Zoom
248
249    /// Lowest zoom allowed with the map centered at this latitude: the globe
250    /// lets the zoom fall below `min_zoom()` toward the poles by the
251    /// anchored-zoom adjustment, so the planet keeps its size on screen.
252    #[must_use]
253    pub(crate) fn min_zoom_at_latitude(&self, latitude: f64) -> f64 {
254        self.min_zoom_at_latitude_with(latitude, self.view.is_globe())
255    }
256
257    /// [`min_zoom_at_latitude`](Self::min_zoom_at_latitude) for a
258    /// camera on the globe or not, whatever the current projection.
259    #[must_use]
260    pub(crate) fn min_zoom_at_latitude_with(&self, latitude: f64, globe: bool) -> f64 {
261        if !globe {
262            return self.min_zoom();
263        }
264        // The globe's constraint never raises the scale, whichever projection
265        // the map is in now.
266        scale_zoom(self.min_scale()) + VerticalPerspectiveProjection::zoom_adjustment(0.0, latitude)
267    }
268
269    /// The center `constrain` would settle on for this one at this zoom: on
270    /// the globe the zoom decides how close to a pole the center can be.
271    #[must_use]
272    pub(crate) fn constrained_center(&self, lat_lng: &LatLng, zoom: f64) -> LatLng {
273        if self.constrain_mode() == ConstrainMode::None || !self.view.is_globe() {
274            return *lat_lng;
275        }
276        let max_latitude = VerticalPerspectiveProjection::max_latitude(
277            &self.view,
278            mln_style::math::clamp_f64(zoom, self.min_zoom_at_latitude(lat_lng.latitude()), self.limits.max_zoom),
279        );
280        LatLng::saturating(
281            mln_style::math::clamp_f64(lat_lng.latitude(), -max_latitude, max_latitude),
282            lat_lng.longitude(),
283            WrapMode::Unwrapped,
284        )
285    }
286
287    // MARK: - Limits
288
289    /// The limits the camera moves within.
290    #[must_use]
291    pub fn limits(&self) -> &CameraLimits {
292        &self.limits
293    }
294
295    /// Sets the limits the camera moves within, clamped to what any map
296    /// allows (see `CameraLimits::validated`), and moves the center into
297    /// new bounds. `Err`, changing nothing, for limits that leave the camera
298    /// nowhere to go.
299    pub fn set_limits(&mut self, limits: CameraLimits) -> Result<(), Error> {
300        let limits = limits.validated()?;
301        // The view can't zoom out past the zoom at which the world fills it.
302        let least_scale = self.constrain(zoom_scale(limits.min_zoom), self.view.x(), self.view.y()).0;
303        if zoom_scale(limits.max_zoom) < least_scale {
304            return Err(Error::invalid_argument("the maximum zoom must be at least the least zoom the view allows"));
305        }
306        let bounds_changed = limits.bounds != self.limits.bounds;
307        self.limits = limits;
308        if bounds_changed {
309            let lat_lng = self.view.center(WrapMode::Unwrapped);
310            let zoom = self.view.zoom();
311            self.set_lat_lng_zoom(&lat_lng, zoom);
312            self.update(|_| ());
313        }
314        Ok(())
315    }
316
317    fn min_scale(&self) -> f64 {
318        zoom_scale(self.limits.min_zoom)
319    }
320
321    fn max_scale(&self) -> f64 {
322        zoom_scale(self.limits.max_zoom)
323    }
324
325    /// The lowest zoom the constrain mode allows: the minimum zoom, raised
326    /// so that the view shows no area off the world.
327    #[must_use]
328    pub fn min_zoom(&self) -> f64 {
329        scale_zoom(self.constrained_min_scale())
330    }
331
332    fn constrained_min_scale(&self) -> f64 {
333        self.constrain(self.min_scale(), self.view.x(), self.view.y()).0
334    }
335
336    // MARK: - Rotation
337
338    /// Sets the map's rotation, in radians counterclockwise: the negated
339    /// bearing.
340    pub fn set_angle(&mut self, angle: f64) {
341        if angle.is_finite() {
342            self.update(|p| p.angle = angle);
343        }
344    }
345
346    pub(crate) fn set_fov(&mut self, fov: f64) {
347        if fov.is_finite() {
348            self.update(|p| p.fov = fov);
349        }
350    }
351
352    pub(crate) fn set_roll(&mut self, roll: f64) {
353        if roll.is_finite() {
354            self.update(|p| p.roll = roll);
355        }
356    }
357
358    pub fn set_pitch(&mut self, pitch: f64) {
359        if pitch.is_finite() {
360            self.update(|p| p.pitch = pitch);
361        }
362    }
363
364    pub(crate) fn set_x_skew(&mut self, skew: f64) {
365        if skew.is_finite() {
366            self.update(|p| p.x_skew = skew);
367        }
368    }
369
370    pub(crate) fn set_y_skew(&mut self, skew: f64) {
371        if skew.is_finite() {
372            self.update(|p| p.y_skew = skew);
373        }
374    }
375
376    pub(crate) fn set_axonometric(&mut self, axonometric: bool) {
377        self.update(|p| p.axonometric = axonometric);
378    }
379
380    // MARK: - Validity
381
382    /// Whether the view shows anything and its scale is within the zoom
383    /// range. Toward the poles the globe goes below the minimum scale;
384    /// `set_lat_lng_zoom` holds it to the floor there.
385    #[must_use]
386    pub(crate) fn is_valid(&self) -> bool {
387        let scale = self.view.scale();
388        self.view.is_valid()
389            && (if self.view.is_globe() { scale > 0.0 } else { scale >= self.min_scale() })
390            && scale <= self.max_scale()
391    }
392
393    // MARK: - Constraints
394
395    fn rotated_north(&self) -> bool {
396        matches!(self.view.north_orientation(), NorthOrientation::Leftwards | NorthOrientation::Rightwards)
397    }
398
399    /// In [`ConstrainMode::Screen`], the scale and center that keep the
400    /// lat/lng bounds on the screen at `scale`: the center only if it had to
401    /// move. Other modes return `scale` unchanged and no center.
402    #[must_use]
403    pub(crate) fn constrain_screen(&self, scale: f64) -> (f64, Option<LatLng>) {
404        if self.constrain_mode() != ConstrainMode::Screen {
405            return (scale, None);
406        }
407        let mut zoom = scale_zoom(scale);
408        let mut options = CameraOptions::default();
409        self.constrain_camera_and_zoom_to_bounds(&mut options, &mut zoom);
410        (zoom_scale(zoom), options.center)
411    }
412
413    /// The `(scale, x, y)` nearest the given ones that the constrain mode
414    /// allows.
415    #[must_use]
416    pub(crate) fn constrain(&self, mut scale: f64, mut x: f64, mut y: f64) -> (f64, f64, f64) {
417        let constrain_mode = self.constrain_mode();
418        if constrain_mode == ConstrainMode::None || constrain_mode == ConstrainMode::Screen {
419            return (scale, x, y);
420        }
421
422        // The globe has no off-world area: the center goes past the Mercator
423        // range toward a pole as far as the zoom allows.
424        if self.view.is_globe() {
425            let max_latitude = VerticalPerspectiveProjection::max_latitude(&self.view, scale_zoom(scale));
426            let max_y = Projection::world_size(scale) / M2PI * mln_style::math::deg2rad(max_latitude).tan().asinh();
427            y = mln_style::math::clamp_f64(y, -max_y, max_y);
428            return (scale, x, y);
429        }
430
431        let size = self.view.size();
432        let width = f64::from(size.width);
433        let height = f64::from(size.height);
434
435        // Constrain scale to avoid zooming out far enough to show off-world
436        // areas on the Y axis.
437        let ratio_y = (if self.rotated_north() { width } else { height }) / TILE_SIZE_D;
438        scale = mln_style::math::fmax(scale, ratio_y);
439
440        // Constrain min/max pan to avoid showing off-world areas on the Y axis.
441        let max_y = (scale * TILE_SIZE_D - (if self.rotated_north() { width } else { height })) / 2.0;
442        y = f64::max(-max_y, f64::min(y, max_y));
443
444        if constrain_mode == ConstrainMode::WidthAndHeight {
445            // Constrain min/max pan to avoid showing off-world areas on the X axis.
446            let max_x = (scale * TILE_SIZE_D - (if self.rotated_north() { height } else { width })) / 2.0;
447            x = f64::max(-max_x, f64::min(x, max_x));
448        }
449        (scale, x, y)
450    }
451
452    /// Moves the camera to the position nearest its own at `scale` that the
453    /// constrain mode allows.
454    pub(crate) fn constrain_position(&mut self, scale: f64) {
455        let (scale, x, y) = self.constrain(scale, self.view.x(), self.view.y());
456        if scale.is_finite() && x.is_finite() && y.is_finite() {
457            self.update(|p| {
458                p.scale = scale;
459                p.x = x;
460                p.y = y;
461            });
462        }
463    }
464
465    pub(crate) fn constrain_camera_and_zoom_to_bounds(
466        &self,
467        requested_camera: &mut CameraOptions,
468        requested_zoom: &mut f64,
469    ) {
470        if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
471            return;
472        }
473
474        let view = &self.view;
475        let current_center = view.center(WrapMode::Unwrapped);
476        let center_lat_lng = requested_camera.center.unwrap_or(current_center);
477
478        let mut anchor_offset = Point::new(0.0, 0.0);
479        let requested_scale = zoom_scale(*requested_zoom);
480
481        // The transition will move the camera so that the anchor's location
482        // stays under it: the requested center is tested from where that
483        // leaves it.
484        if let Some(mut anchor) = requested_camera.anchor {
485            anchor.y = f64::from(view.size().height) - anchor.y;
486            // The location under the anchor at the requested scale.
487            let mut state = self.clone();
488            state.set_lat_lng_zoom(&current_center, scale_zoom(requested_scale));
489            // An anchor with no location is ignored, as the transition
490            // ignores it.
491            if let (Ok(anchor_lat_lng), Ok(screen_lat_lng)) = (
492                view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
493                state.view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
494            ) {
495                let lat_lng_coord = Projection::project(&anchor_lat_lng, requested_scale);
496                let anchor_coord = Projection::project(&screen_lat_lng, requested_scale);
497                anchor_offset = Point::new(lat_lng_coord.x - anchor_coord.x, lat_lng_coord.y - anchor_coord.y);
498            }
499        }
500
501        let current_bounds = self.limits.bounds;
502        let ne_bounds = Projection::project(&current_bounds.northeast(), requested_scale);
503        let sw_bounds = Projection::project(&current_bounds.southwest(), requested_scale);
504        let center = Projection::project(&center_lat_lng, requested_scale);
505        let current_center = Projection::project(&current_center, requested_scale);
506
507        let min_y = ne_bounds.y;
508        let max_y = sw_bounds.y;
509        let min_x = sw_bounds.x;
510        let max_x = ne_bounds.x;
511
512        let start_x = center.x;
513        let start_y = center.y;
514
515        let mut result_x = start_x;
516        let mut result_y = start_y;
517
518        let screen_width = view.size().width;
519        let screen_height = view.size().height;
520
521        let h2 = f64::from(screen_height) / 2.0;
522        if start_y - h2 + anchor_offset.y < min_y {
523            result_y = min_y + h2;
524        }
525        if start_y + anchor_offset.y + h2 > max_y {
526            result_y = max_y - h2;
527        }
528
529        let w2 = f64::from(screen_width) / 2.0;
530        if start_x + anchor_offset.x - w2 < min_x {
531            result_x = min_x + w2;
532        }
533        if start_x + anchor_offset.x + w2 > max_x {
534            result_x = max_x - w2;
535        }
536
537        let mut scale_y = 0.0;
538        if max_y - min_y < f64::from(screen_height) {
539            scale_y = f64::from(screen_height) / (max_y - min_y);
540            result_y = f64::midpoint(max_y, min_y);
541        }
542
543        let mut scale_x = 0.0;
544        if max_x - min_x < f64::from(screen_width) {
545            scale_x = f64::from(screen_width) / (max_x - min_x);
546            result_x = f64::midpoint(max_x, min_x);
547        }
548
549        let max_scale = if scale_x > scale_y { scale_x } else { scale_y };
550
551        // Max scale will be 1 when the screen is exactly the same size as the
552        // max bounds in either the X or Y direction. To avoid numerical
553        // instabilities we add small amount to the check to make sure we
554        // don't try to scale when we don't actually need it.
555        if max_scale > 1.000_001 {
556            *requested_zoom += scale_zoom(max_scale);
557
558            if scale_y > scale_x {
559                // If we scaled the y direction we want the resulting x
560                // position to be the same as the current x position.
561                result_x = current_center.x;
562            } else {
563                // If we scaled the x direction we want the resulting y
564                // position to be the same as the current y position.
565                result_y = current_center.y;
566            }
567
568            // Since we changed the scale, we might display something outside
569            // the bounds. When checking we need to take into consideration
570            // that we just changed the scale, since the resultX and minX were
571            // calculated with the requested scale, and not the scale we just
572            // calculated to make sure we stay inside the bounds.
573            if result_x * max_scale - w2 <= min_x * max_scale {
574                result_x = min_x * max_scale + w2;
575                result_x /= max_scale;
576            } else if result_x * max_scale + w2 >= max_x * max_scale {
577                result_x = max_x * max_scale - w2;
578                result_x /= max_scale;
579            }
580
581            if result_y * max_scale - h2 <= min_y * max_scale {
582                result_y = min_y * max_scale + h2;
583                result_y /= max_scale;
584            } else if result_y * max_scale + h2 >= max_y * max_scale {
585                result_y = max_y * max_scale - h2;
586                result_y /= max_scale;
587            }
588        }
589
590        if result_x != start_x || result_y != start_y {
591            // If we made changes just drop any anchor point
592            requested_camera.anchor = None;
593            // The clamped point is inside the bounds, so it has a LatLng.
594            requested_camera.center =
595                Projection::unproject(&Point::new(result_x, result_y), requested_scale, WrapMode::Unwrapped).ok();
596        }
597    }
598
599    /// The lowest zoom `ConstrainMode::Screen` allows: the one at which the
600    /// lat/lng bounds fill the screen, which
601    /// [`constrain_camera_and_zoom_to_bounds`](Self::constrain_camera_and_zoom_to_bounds)
602    /// raises lower zooms to. `None` in the other modes or without bounds.
603    #[must_use]
604    pub(crate) fn min_zoom_for_screen_bounds(&self) -> Option<f64> {
605        if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
606            return None;
607        }
608        // The bounds' extent on screen grows with the scale alone, so they
609        // fill the screen at the same zoom wherever the center is.
610        let ne = Projection::project(&self.limits.bounds.northeast(), 1.0);
611        let sw = Projection::project(&self.limits.bounds.southwest(), 1.0);
612        let size = self.view.size();
613        let scale_x = f64::from(size.width) / (ne.x - sw.x);
614        let scale_y = f64::from(size.height) / (sw.y - ne.y);
615        Some(scale_zoom(f64::max(scale_x, scale_y)))
616    }
617
618    // MARK: - Moving the camera
619
620    /// Recenter the map so that the given coordinate is located at the given
621    /// point on screen.
622    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
623    /// NaN or infinite anchor.
624    #[cfg(test)]
625    pub(crate) fn move_lat_lng(&mut self, lat_lng: &LatLng, anchor: &ScreenCoordinate) -> Result<(), Error> {
626        self.move_lat_lng_at(lat_lng, anchor, 0.0)
627    }
628
629    /// Recenters the map so that `lat_lng`, `height` meters above sea level,
630    /// is at `anchor`, a point measured from the bottom edge (y up): the
631    /// center moves across the ground, with the zoom, the angles and the
632    /// center's altitude kept. At height 0 it is
633    /// [`move_lat_lng`](Self::move_lat_lng). The globe turns to hold
634    /// `lat_lng` on the sphere `height` meters above sea level, keeping the
635    /// planet's size on the screen. Fails as `move_lat_lng` does.
636    pub(crate) fn move_lat_lng_at(
637        &mut self,
638        lat_lng: &LatLng,
639        anchor: &ScreenCoordinate,
640        height: f64,
641    ) -> Result<(), Error> {
642        let view = &self.view;
643        if view.is_globe() {
644            if let Some(center) =
645                VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
646            {
647                let target = self.constrained_center(&center, view.zoom());
648                let zoom = view.zoom()
649                    + VerticalPerspectiveProjection::zoom_adjustment(
650                        view.center(WrapMode::Unwrapped).latitude(),
651                        target.latitude(),
652                    );
653                self.set_lat_lng_zoom(&target, zoom);
654            }
655            return Ok(());
656        }
657        let center = self.center_for_lat_lng_at(lat_lng, anchor, height)?;
658        // Wrapped, as easeTo and GL JS's setLocationAtPoint leave it, unless
659        // bounds keep it in their range.
660        let target = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
661        let zoom = self.view.zoom();
662        self.set_lat_lng_zoom(&target, zoom);
663        Ok(())
664    }
665
666    /// The center, unwrapped and before the limits constrain it, that puts
667    /// `lat_lng`, `height` meters above sea level, at `anchor` (y up) on a
668    /// Mercator view: the current center moved across the ground by as far
669    /// as `lat_lng` is from the location the line of sight through `anchor`
670    /// meets at that height (GL JS's `getCameraForLocationAtPoint`). On the
671    /// globe it is the center that holds `lat_lng` on the sphere at that
672    /// height, or fails where none does; before the globe has a size, its
673    /// points are Mercator's, as
674    /// [`crate::camera::View::screen_coordinate_to_lat_lng_at`] reads them. Fails as
675    /// [`move_lat_lng_at`](Self::move_lat_lng_at) does.
676    pub(crate) fn center_for_lat_lng_at(
677        &self,
678        lat_lng: &LatLng,
679        anchor: &ScreenCoordinate,
680        height: f64,
681    ) -> Result<LatLng, Error> {
682        let view = &self.view;
683        if view.is_globe() && !view.size().is_empty() {
684            return VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
685                .ok_or_else(|| Error::invalid_argument("no center holds the location at the point"));
686        }
687        let scale = view.scale();
688        let center_coord = Projection::project(&view.center(WrapMode::Unwrapped), scale);
689        let lat_lng_coord = Projection::project(lat_lng, scale);
690        let anchor_coord =
691            Projection::project(&view.screen_coordinate_to_lat_lng_at(anchor, height, WrapMode::Unwrapped)?, scale);
692        Projection::unproject(
693            &Point::new(
694                center_coord.x + lat_lng_coord.x - anchor_coord.x,
695                center_coord.y + lat_lng_coord.y - anchor_coord.y,
696            ),
697            scale,
698            WrapMode::Unwrapped,
699        )
700    }
701
702    pub fn set_lat_lng_zoom(&mut self, lat_lng: &LatLng, zoom: f64) {
703        if !zoom.is_finite() {
704            return;
705        }
706        let globe = self.view.is_globe();
707        let mut requested = *lat_lng;
708        // Globe centers arrive wrapped, and bounds across the antimeridian
709        // reach past 180 degrees: take the copy of the longitude nearest the
710        // bounds before constraining it.
711        if globe && self.limits.bounds != LatLngBounds::default() {
712            let turns =
713                ((self.limits.bounds.center().longitude() - lat_lng.longitude()) / constants::DEGREES_MAX).round();
714            requested = LatLng::saturating(
715                lat_lng.latitude(),
716                lat_lng.longitude() + turns * constants::DEGREES_MAX,
717                WrapMode::Unwrapped,
718            );
719        }
720        let mut constrained = self.limits.bounds.constrain(&requested);
721        // The globe's tile cover picks each tile's wrap from the center, so a
722        // center that jumped a whole world at the antimeridian would re-key
723        // every tile; keep it on the copy nearest the current one.
724        if globe && self.limits.bounds == LatLngBounds::default() {
725            let current = self.view.center(WrapMode::Unwrapped).longitude();
726            if current.is_finite() {
727                let turns = ((current - constrained.longitude()) / constants::DEGREES_MAX).round();
728                constrained = LatLng::saturating(
729                    constrained.latitude(),
730                    constrained.longitude() + turns * constants::DEGREES_MAX,
731                    WrapMode::Unwrapped,
732                );
733            }
734        }
735
736        let min_scale = if globe {
737            zoom_scale(self.min_zoom_at_latitude(constrained.latitude()))
738        } else {
739            self.constrained_min_scale()
740        };
741        let new_scale = mln_style::math::clamp_f64(zoom_scale(zoom), min_scale, self.max_scale());
742        let (x, y) = map_offset(&constrained, new_scale, globe);
743        // A far unwrapped longitude can overflow the point.
744        if !x.is_finite() || !y.is_finite() {
745            return;
746        }
747        let (scale, x, y) = self.constrain(new_scale, x, y);
748        self.update(|p| {
749            p.scale = scale;
750            p.x = x;
751            p.y = y;
752        });
753    }
754
755    /// Sets the center's altitude, in meters, which then holds through
756    /// changes of the zoom and the center.
757    pub(crate) fn set_center_altitude(&mut self, alt_m: f64) {
758        if !alt_m.is_finite() {
759            return;
760        }
761        self.update(|p| p.center_altitude = alt_m);
762    }
763
764    /// Sets the lowest ground near the center while terrain draws, in
765    /// meters, exaggerated, or `None` without terrain. With it, the view's
766    /// near and far planes fit raised and sunken ground; without it, they
767    /// fit the flat map. A height that isn't finite changes nothing.
768    pub(crate) fn set_terrain_min_elevation(&mut self, min_elevation: Option<f64>) {
769        if min_elevation.is_some_and(|min| !min.is_finite()) {
770            return;
771        }
772        self.update(|p| p.terrain_min_elevation = min_elevation);
773    }
774
775    /// Raises the eye by `lift` meters straight up, still looking at the
776    /// center at its altitude: keeps the center, its altitude, the bearing
777    /// and the roll, and solves the pitch and the zoom that put the eye there
778    /// (GL JS's `calculateCameraOptionsFromTo`, from the raised eye to the
779    /// center), within the limits. Heights convert to pixels at the center's
780    /// latitude. On the globe it solves in the plane of the center's
781    /// vertical, which the eye is near wherever it can come near the
782    /// ground. Returns whether the view changed; while the view shows
783    /// nothing, it doesn't.
784    pub(crate) fn raise_eye(&mut self, lift: f64) -> bool {
785        let view = &self.view;
786        if !lift.is_finite() || !view.is_valid() {
787            return false;
788        }
789        // The eye's offset from the center, in pixels at the zoom: across
790        // the ground, and up.
791        let distance = view.camera_to_center_distance();
792        let across = view.pitch().sin() * distance;
793        let up = view.pitch().cos() * distance + lift / Self::height_meters_per_pixel(view);
794        let raised = across.hypot(up);
795        if raised == 0.0 {
796            return false;
797        }
798        let pitch = mln_style::math::clamp_f64(across.atan2(up), self.limits.min_pitch, self.limits.max_pitch);
799        let zoom = view.zoom() + (distance / raised).log2();
800        let center = view.center(WrapMode::Unwrapped);
801        let before = *view.params();
802        self.set_pitch(pitch);
803        self.set_lat_lng_zoom(&center, zoom);
804        *self.view.params() != before
805    }
806
807    /// Moves the center along the view onto `hit`, the ground its line of
808    /// sight meets, with the eye, the pitch and the bearing kept: the center
809    /// stands as far along the view as `hit` is from the eye, at the height
810    /// the view reaches there, and the zoom follows from that distance (GL
811    /// JS's `moveCenterToElevation`, orbis's `recenter_on`). Distances across
812    /// the ground convert to meters at `hit`'s latitude, so where the
813    /// center's latitude was another, the center lands off `hit` by that
814    /// share of the distance between the latitudes' scales.
815    ///
816    /// On the globe the center moves along the line from the eye through
817    /// the center at its altitude, as far as `hit`, raised along its
818    /// vertical, is from the eye along it; it stands that far above the
819    /// sea-level sphere, and the zoom puts the eye that far from it (GL
820    /// JS's `calculateCameraOptionsFromTo`). The pitch and the bearing are
821    /// kept, which turns the eye about the new center by the angle between
822    /// the centers' verticals: under a meter where the camera is low enough
823    /// to meet terrain.
824    ///
825    /// Returns whether it moved the center there. It leaves the state as it
826    /// is while the view shows nothing, where `hit` isn't in front of the
827    /// eye, and where the limits would move the zoom or the center: the zoom
828    /// range, the bounds, and in [`ConstrainMode::Screen`] the bounds the
829    /// screen must stay within.
830    pub(crate) fn recenter_on(&mut self, hit: &GroundHit) -> bool {
831        let view = &self.view;
832        if !view.is_valid() {
833            return false;
834        }
835        let recentered =
836            if view.is_globe() { Self::recentered_on_sphere(view, hit) } else { self.recentered_on_plane(hit) };
837        let Some((center, altitude, zoom)) = recentered else { return false };
838
839        let mut moved = self.clone();
840        moved.set_center_altitude(altitude);
841        moved.set_lat_lng_zoom(&center, zoom);
842        // The limits clamp what they refuse, and the screen's bounds move it.
843        let landed = moved.view.center(WrapMode::Unwrapped);
844        let mut on_screen = CameraOptions { center: Some(landed), ..CameraOptions::default() };
845        let mut screen_zoom = moved.view.zoom();
846        moved.constrain_camera_and_zoom_to_bounds(&mut on_screen, &mut screen_zoom);
847        let refused = (moved.view.zoom() - zoom).abs() > 1e-9
848            || (landed.latitude() - center.latitude()).abs() > 1e-9
849            || (landed.longitude() - center.longitude()).abs() > 1e-9
850            || on_screen.center != Some(landed)
851            || screen_zoom != moved.view.zoom();
852        if refused {
853            return false;
854        }
855        *self = moved;
856        true
857    }
858
859    /// The center, its altitude and the zoom of [`Self::recenter_on`] on a
860    /// Mercator view, before the limits.
861    fn recentered_on_plane(&self, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
862        let view = &self.view;
863        let eye = view.eye_position();
864        let forward = view.camera_pose().forward();
865        // Meters per Web Mercator unit at zoom 0, across the ground at `hit`.
866        let latitude = hit.location(WrapMode::Unwrapped).latitude();
867        let meters = Projection::meters_per_pixel_at_latitude(latitude, 0.0) * TILE_SIZE_D;
868        let to_hit = DVec3::new((hit.world.x - eye.x) * meters, (hit.world.y - eye.y) * meters, hit.height - eye.z);
869        let distance = to_hit.dot(forward);
870        if !(distance.is_finite() && distance > 0.0) {
871            return None;
872        }
873        let world = Point::new(eye.x + forward.x * distance / meters, eye.y + forward.y * distance / meters);
874        let center = Projection::unproject(&world, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped).ok()?;
875        // Wrapped, as move_lat_lng leaves it, unless bounds keep it in their
876        // range.
877        let center = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
878        let zoom = scale_zoom(view.camera_to_center_distance() * meters / distance / TILE_SIZE_D);
879        Some((center, eye.z + forward.z * distance, zoom))
880    }
881
882    /// The center, its altitude and the zoom of [`Self::recenter_on`] on the
883    /// globe, before the limits, in unit-sphere space. The center keeps the
884    /// world copy nearest the current one, as the globe's moves do.
885    fn recentered_on_sphere(view: &View, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
886        let radius = |height: f64| 1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS;
887        let eye = view.globe_camera_position();
888        let center = VerticalPerspectiveProjection::surface_vector(&view.center(WrapMode::Unwrapped))
889            * radius(view.center_altitude());
890        let forward = (center - eye).normalize();
891        let target =
892            VerticalPerspectiveProjection::surface_vector(&hit.location(WrapMode::Unwrapped)) * radius(hit.height);
893        let distance = (target - eye).dot(forward);
894        if !(distance.is_finite() && distance > 0.0) {
895            return None;
896        }
897        let point = eye + forward * distance;
898        let length = point.length();
899        let location = VerticalPerspectiveProjection::surface_vector_to_lat_lng(point / length)?;
900        let location = view.lat_lng_near_center(&location);
901        let radius_at_zoom_0 =
902            VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(1.0), location.latitude());
903        let zoom = scale_zoom(view.camera_to_center_distance() / distance / radius_at_zoom_0);
904        Some((location, (length - 1.0) * VerticalPerspectiveProjection::GLOBE_RADIUS_METERS, zoom))
905    }
906
907    /// Meters per pixel at the zoom of a height at the center: on Mercator
908    /// the view's, and on the globe those of its sphere, which it raises
909    /// heights on.
910    fn height_meters_per_pixel(view: &View) -> f64 {
911        if view.is_globe() {
912            let latitude = view.center(WrapMode::Unwrapped).latitude();
913            VerticalPerspectiveProjection::GLOBE_RADIUS_METERS
914                / VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(view.scale()), latitude)
915        } else {
916            view.meters_per_pixel()
917        }
918    }
919}
920
921#[cfg(test)]
922#[path = "transform_state_test.rs"]
923mod transform_state_test;