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