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(crate) 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(crate) 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(crate) fn set_frustum_offset(&mut self, frustum_offset: &EdgeInsets) {
210        self.update(|p| p.frustum_offset = *frustum_offset);
211    }
212
213    pub(crate) fn set_north_orientation(&mut self, orientation: NorthOrientation) {
214        self.update(|p| p.north_orientation = orientation);
215    }
216
217    #[must_use]
218    pub(crate) fn constrain_mode(&self) -> ConstrainMode {
219        self.view.params().constrain_mode
220    }
221
222    pub(crate) fn set_constrain_mode(&mut self, mode: ConstrainMode) {
223        self.update(|p| p.constrain_mode = mode);
224    }
225
226    pub(crate) fn set_viewport_mode(&mut self, mode: ViewportMode) {
227        self.update(|p| p.viewport_mode = mode);
228    }
229
230    pub(crate) fn set_center_clamped_to_ground(&mut self, clamped: bool) {
231        self.update(|p| p.center_clamped_to_ground = clamped);
232    }
233
234    pub(crate) fn set_globe_free_bearing(&mut self, free_bearing: bool) {
235        self.update(|p| p.globe_free_bearing = free_bearing);
236    }
237
238    pub(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) fn set_fov(&mut self, fov: f64) {
354        if fov.is_finite() {
355            self.update(|p| p.fov = fov);
356        }
357    }
358
359    pub(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) 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(crate) fn constrain_camera_and_zoom_to_bounds(
473        &self,
474        requested_camera: &mut CameraOptions,
475        requested_zoom: &mut f64,
476    ) {
477        if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
478            return;
479        }
480
481        let view = &self.view;
482        let current_center = view.center(WrapMode::Unwrapped);
483        let center_lat_lng = requested_camera.center.unwrap_or(current_center);
484
485        let mut anchor_offset = Point::new(0.0, 0.0);
486        let requested_scale = zoom_scale(*requested_zoom);
487
488        // The transition will move the camera so that the anchor's location
489        // stays under it: the requested center is tested from where that
490        // leaves it.
491        if let Some(mut anchor) = requested_camera.anchor {
492            anchor.y = f64::from(view.size().height) - anchor.y;
493            // The location under the anchor at the requested scale.
494            let mut state = self.clone();
495            state.set_lat_lng_zoom(&current_center, scale_zoom(requested_scale));
496            // An anchor with no location is ignored, as the transition
497            // ignores it.
498            if let (Ok(anchor_lat_lng), Ok(screen_lat_lng)) = (
499                view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
500                state.view.screen_coordinate_to_lat_lng(&anchor, WrapMode::Unwrapped),
501            ) {
502                let lat_lng_coord = Projection::project(&anchor_lat_lng, requested_scale);
503                let anchor_coord = Projection::project(&screen_lat_lng, requested_scale);
504                anchor_offset = Point::new(lat_lng_coord.x - anchor_coord.x, lat_lng_coord.y - anchor_coord.y);
505            }
506        }
507
508        let current_bounds = self.limits.bounds;
509        let ne_bounds = Projection::project(&current_bounds.northeast(), requested_scale);
510        let sw_bounds = Projection::project(&current_bounds.southwest(), requested_scale);
511        let center = Projection::project(&center_lat_lng, requested_scale);
512        let current_center = Projection::project(&current_center, requested_scale);
513
514        let min_y = ne_bounds.y;
515        let max_y = sw_bounds.y;
516        let min_x = sw_bounds.x;
517        let max_x = ne_bounds.x;
518
519        let start_x = center.x;
520        let start_y = center.y;
521
522        let mut result_x = start_x;
523        let mut result_y = start_y;
524
525        let screen_width = view.size().width;
526        let screen_height = view.size().height;
527
528        let h2 = f64::from(screen_height) / 2.0;
529        if start_y - h2 + anchor_offset.y < min_y {
530            result_y = min_y + h2;
531        }
532        if start_y + anchor_offset.y + h2 > max_y {
533            result_y = max_y - h2;
534        }
535
536        let w2 = f64::from(screen_width) / 2.0;
537        if start_x + anchor_offset.x - w2 < min_x {
538            result_x = min_x + w2;
539        }
540        if start_x + anchor_offset.x + w2 > max_x {
541            result_x = max_x - w2;
542        }
543
544        let mut scale_y = 0.0;
545        if max_y - min_y < f64::from(screen_height) {
546            scale_y = f64::from(screen_height) / (max_y - min_y);
547            result_y = f64::midpoint(max_y, min_y);
548        }
549
550        let mut scale_x = 0.0;
551        if max_x - min_x < f64::from(screen_width) {
552            scale_x = f64::from(screen_width) / (max_x - min_x);
553            result_x = f64::midpoint(max_x, min_x);
554        }
555
556        let max_scale = if scale_x > scale_y { scale_x } else { scale_y };
557
558        // Max scale will be 1 when the screen is exactly the same size as the
559        // max bounds in either the X or Y direction. To avoid numerical
560        // instabilities we add small amount to the check to make sure we
561        // don't try to scale when we don't actually need it.
562        if max_scale > 1.000_001 {
563            *requested_zoom += scale_zoom(max_scale);
564
565            if scale_y > scale_x {
566                // If we scaled the y direction we want the resulting x
567                // position to be the same as the current x position.
568                result_x = current_center.x;
569            } else {
570                // If we scaled the x direction we want the resulting y
571                // position to be the same as the current y position.
572                result_y = current_center.y;
573            }
574
575            // Since we changed the scale, we might display something outside
576            // the bounds. When checking we need to take into consideration
577            // that we just changed the scale, since the resultX and minX were
578            // calculated with the requested scale, and not the scale we just
579            // calculated to make sure we stay inside the bounds.
580            if result_x * max_scale - w2 <= min_x * max_scale {
581                result_x = min_x * max_scale + w2;
582                result_x /= max_scale;
583            } else if result_x * max_scale + w2 >= max_x * max_scale {
584                result_x = max_x * max_scale - w2;
585                result_x /= max_scale;
586            }
587
588            if result_y * max_scale - h2 <= min_y * max_scale {
589                result_y = min_y * max_scale + h2;
590                result_y /= max_scale;
591            } else if result_y * max_scale + h2 >= max_y * max_scale {
592                result_y = max_y * max_scale - h2;
593                result_y /= max_scale;
594            }
595        }
596
597        if result_x != start_x || result_y != start_y {
598            // If we made changes just drop any anchor point
599            requested_camera.anchor = None;
600            // The clamped point is inside the bounds, so it has a LatLng.
601            requested_camera.center =
602                Projection::unproject(&Point::new(result_x, result_y), requested_scale, WrapMode::Unwrapped).ok();
603        }
604    }
605
606    /// The lowest zoom `ConstrainMode::Screen` allows: the one at which the
607    /// lat/lng bounds fill the screen, which
608    /// [`constrain_camera_and_zoom_to_bounds`](Self::constrain_camera_and_zoom_to_bounds)
609    /// raises lower zooms to. `None` in the other modes or without bounds.
610    #[must_use]
611    pub(crate) fn min_zoom_for_screen_bounds(&self) -> Option<f64> {
612        if self.constrain_mode() != ConstrainMode::Screen || self.limits.bounds == LatLngBounds::default() {
613            return None;
614        }
615        // The bounds' extent on screen grows with the scale alone, so they
616        // fill the screen at the same zoom wherever the center is.
617        let ne = Projection::project(&self.limits.bounds.northeast(), 1.0);
618        let sw = Projection::project(&self.limits.bounds.southwest(), 1.0);
619        let size = self.view.size();
620        let scale_x = f64::from(size.width) / (ne.x - sw.x);
621        let scale_y = f64::from(size.height) / (sw.y - ne.y);
622        Some(scale_zoom(f64::max(scale_x, scale_y)))
623    }
624
625    // MARK: - Moving the camera
626
627    /// Recenter the map so that the given coordinate is located at the given
628    /// point on screen.
629    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
630    /// NaN or infinite anchor.
631    #[cfg(test)]
632    pub(crate) fn move_lat_lng(&mut self, lat_lng: &LatLng, anchor: &ScreenCoordinate) -> Result<(), Error> {
633        self.move_lat_lng_at(lat_lng, anchor, 0.0)
634    }
635
636    /// Recenters the map so that `lat_lng`, `height` meters above sea level,
637    /// is at `anchor`, a point measured from the bottom edge (y up): the
638    /// center moves across the ground, with the zoom, the angles and the
639    /// center's altitude kept. At height 0 it is
640    /// [`move_lat_lng`](Self::move_lat_lng). The globe turns to hold
641    /// `lat_lng` on the sphere `height` meters above sea level, keeping the
642    /// planet's size on the screen. Fails as `move_lat_lng` does.
643    pub(crate) fn move_lat_lng_at(
644        &mut self,
645        lat_lng: &LatLng,
646        anchor: &ScreenCoordinate,
647        height: f64,
648    ) -> Result<(), Error> {
649        let view = &self.view;
650        if view.is_globe() {
651            if let Some(center) =
652                VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
653            {
654                let target = self.constrained_center(&center, view.zoom());
655                let zoom = view.zoom()
656                    + VerticalPerspectiveProjection::zoom_adjustment(
657                        view.center(WrapMode::Unwrapped).latitude(),
658                        target.latitude(),
659                    );
660                self.set_lat_lng_zoom(&target, zoom);
661            }
662            return Ok(());
663        }
664        let center = self.center_for_lat_lng_at(lat_lng, anchor, height)?;
665        // Wrapped, as easeTo and GL JS's setLocationAtPoint leave it, unless
666        // bounds keep it in their range.
667        let target = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
668        let zoom = self.view.zoom();
669        self.set_lat_lng_zoom(&target, zoom);
670        Ok(())
671    }
672
673    /// The center, unwrapped and before the limits constrain it, that puts
674    /// `lat_lng`, `height` meters above sea level, at `anchor` (y up) on a
675    /// Mercator view: the current center moved across the ground by as far
676    /// as `lat_lng` is from the location the line of sight through `anchor`
677    /// meets at that height (GL JS's `getCameraForLocationAtPoint`). On the
678    /// globe it is the center that holds `lat_lng` on the sphere at that
679    /// height, or fails where none does; before the globe has a size, its
680    /// points are Mercator's, as
681    /// [`crate::camera::View::screen_coordinate_to_lat_lng_at`] reads them. Fails as
682    /// [`move_lat_lng_at`](Self::move_lat_lng_at) does.
683    pub(crate) fn center_for_lat_lng_at(
684        &self,
685        lat_lng: &LatLng,
686        anchor: &ScreenCoordinate,
687        height: f64,
688    ) -> Result<LatLng, Error> {
689        let view = &self.view;
690        if view.is_globe() && !view.size().is_empty() {
691            return VerticalPerspectiveProjection::center_for_location_at_point(view, lat_lng, anchor, height)
692                .ok_or_else(|| Error::invalid_argument("no center holds the location at the point"));
693        }
694        let scale = view.scale();
695        let center_coord = Projection::project(&view.center(WrapMode::Unwrapped), scale);
696        let lat_lng_coord = Projection::project(lat_lng, scale);
697        let anchor_coord =
698            Projection::project(&view.screen_coordinate_to_lat_lng_at(anchor, height, WrapMode::Unwrapped)?, scale);
699        Projection::unproject(
700            &Point::new(
701                center_coord.x + lat_lng_coord.x - anchor_coord.x,
702                center_coord.y + lat_lng_coord.y - anchor_coord.y,
703            ),
704            scale,
705            WrapMode::Unwrapped,
706        )
707    }
708
709    pub fn set_lat_lng_zoom(&mut self, lat_lng: &LatLng, zoom: f64) {
710        if !zoom.is_finite() {
711            return;
712        }
713        let globe = self.view.is_globe();
714        let mut requested = *lat_lng;
715        // Globe centers arrive wrapped, and bounds across the antimeridian
716        // reach past 180 degrees: take the copy of the longitude nearest the
717        // bounds before constraining it.
718        if globe && self.limits.bounds != LatLngBounds::default() {
719            let turns =
720                ((self.limits.bounds.center().longitude() - lat_lng.longitude()) / constants::DEGREES_MAX).round();
721            requested = LatLng::saturating(
722                lat_lng.latitude(),
723                lat_lng.longitude() + turns * constants::DEGREES_MAX,
724                WrapMode::Unwrapped,
725            );
726        }
727        let mut constrained = self.limits.bounds.constrain(&requested);
728        // The globe's tile cover picks each tile's wrap from the center, so a
729        // center that jumped a whole world at the antimeridian would re-key
730        // every tile; keep it on the copy nearest the current one.
731        if globe && self.limits.bounds == LatLngBounds::default() {
732            let current = self.view.center(WrapMode::Unwrapped).longitude();
733            if current.is_finite() {
734                let turns = ((current - constrained.longitude()) / constants::DEGREES_MAX).round();
735                constrained = LatLng::saturating(
736                    constrained.latitude(),
737                    constrained.longitude() + turns * constants::DEGREES_MAX,
738                    WrapMode::Unwrapped,
739                );
740            }
741        }
742
743        let min_scale = if globe {
744            zoom_scale(self.min_zoom_at_latitude(constrained.latitude()))
745        } else {
746            self.constrained_min_scale()
747        };
748        let new_scale = mln_style::math::clamp_f64(zoom_scale(zoom), min_scale, self.max_scale());
749        let (x, y) = map_offset(&constrained, new_scale, globe);
750        // A far unwrapped longitude can overflow the point.
751        if !x.is_finite() || !y.is_finite() {
752            return;
753        }
754        let (scale, x, y) = self.constrain(new_scale, x, y);
755        self.update(|p| {
756            p.scale = scale;
757            p.x = x;
758            p.y = y;
759        });
760    }
761
762    /// Sets the center's altitude, in meters, which then holds through
763    /// changes of the zoom and the center.
764    pub(crate) fn set_center_altitude(&mut self, alt_m: f64) {
765        if !alt_m.is_finite() {
766            return;
767        }
768        self.update(|p| p.center_altitude = alt_m);
769    }
770
771    /// Sets the lowest ground near the center while terrain draws, in
772    /// meters, exaggerated, or `None` without terrain. With it, the view's
773    /// near and far planes fit raised and sunken ground; without it, they
774    /// fit the flat map. A height that isn't finite changes nothing.
775    pub(crate) fn set_terrain_min_elevation(&mut self, min_elevation: Option<f64>) {
776        if min_elevation.is_some_and(|min| !min.is_finite()) {
777            return;
778        }
779        self.update(|p| p.terrain_min_elevation = min_elevation);
780    }
781
782    /// Raises the eye by `lift` meters straight up, still looking at the
783    /// center at its altitude: keeps the center, its altitude, the bearing
784    /// and the roll, and solves the pitch and the zoom that put the eye there
785    /// (GL JS's `calculateCameraOptionsFromTo`, from the raised eye to the
786    /// center), within the limits. Heights convert to pixels at the center's
787    /// latitude. On the globe it solves in the plane of the center's
788    /// vertical, which the eye is near wherever it can come near the
789    /// ground. Returns whether the view changed; while the view shows
790    /// nothing, it doesn't.
791    pub(crate) fn raise_eye(&mut self, lift: f64) -> bool {
792        let view = &self.view;
793        if !lift.is_finite() || !view.is_valid() {
794            return false;
795        }
796        // The eye's offset from the center, in pixels at the zoom: across
797        // the ground, and up.
798        let distance = view.camera_to_center_distance();
799        let across = view.pitch().sin() * distance;
800        let up = view.pitch().cos() * distance + lift / Self::height_meters_per_pixel(view);
801        let raised = across.hypot(up);
802        if raised == 0.0 {
803            return false;
804        }
805        let pitch = mln_style::math::clamp_f64(across.atan2(up), self.limits.min_pitch, self.limits.max_pitch);
806        let zoom = view.zoom() + (distance / raised).log2();
807        let center = view.center(WrapMode::Unwrapped);
808        let before = *view.params();
809        self.set_pitch(pitch);
810        self.set_lat_lng_zoom(&center, zoom);
811        *self.view.params() != before
812    }
813
814    /// Moves the center along the view onto `hit`, the ground its line of
815    /// sight meets, with the eye, the pitch and the bearing kept: the center
816    /// stands as far along the view as `hit` is from the eye, at the height
817    /// the view reaches there, and the zoom follows from that distance (GL
818    /// JS's `moveCenterToElevation`, orbis's `recenter_on`). Distances across
819    /// the ground convert to meters at `hit`'s latitude, so where the
820    /// center's latitude was another, the center lands off `hit` by that
821    /// share of the distance between the latitudes' scales.
822    ///
823    /// On the globe the center moves along the line from the eye through
824    /// the center at its altitude, as far as `hit`, raised along its
825    /// vertical, is from the eye along it; it stands that far above the
826    /// sea-level sphere, and the zoom puts the eye that far from it (GL
827    /// JS's `calculateCameraOptionsFromTo`). The pitch and the bearing are
828    /// kept, which turns the eye about the new center by the angle between
829    /// the centers' verticals: under a meter where the camera is low enough
830    /// to meet terrain.
831    ///
832    /// Returns whether it moved the center there. It leaves the state as it
833    /// is while the view shows nothing, where `hit` isn't in front of the
834    /// eye, and where the limits would move the zoom or the center: the zoom
835    /// range, the bounds, and in [`ConstrainMode::Screen`] the bounds the
836    /// screen must stay within.
837    pub(crate) fn recenter_on(&mut self, hit: &GroundHit) -> bool {
838        let view = &self.view;
839        if !view.is_valid() {
840            return false;
841        }
842        let recentered =
843            if view.is_globe() { Self::recentered_on_sphere(view, hit) } else { self.recentered_on_plane(hit) };
844        let Some((center, altitude, zoom)) = recentered else { return false };
845
846        let mut moved = self.clone();
847        moved.set_center_altitude(altitude);
848        moved.set_lat_lng_zoom(&center, zoom);
849        // The limits clamp what they refuse, and the screen's bounds move it.
850        let landed = moved.view.center(WrapMode::Unwrapped);
851        let mut on_screen = CameraOptions { center: Some(landed), ..CameraOptions::default() };
852        let mut screen_zoom = moved.view.zoom();
853        moved.constrain_camera_and_zoom_to_bounds(&mut on_screen, &mut screen_zoom);
854        let refused = (moved.view.zoom() - zoom).abs() > 1e-9
855            || (landed.latitude() - center.latitude()).abs() > 1e-9
856            || (landed.longitude() - center.longitude()).abs() > 1e-9
857            || on_screen.center != Some(landed)
858            || screen_zoom != moved.view.zoom();
859        if refused {
860            return false;
861        }
862        *self = moved;
863        true
864    }
865
866    /// The center, its altitude and the zoom of [`Self::recenter_on`] on a
867    /// Mercator view, before the limits.
868    fn recentered_on_plane(&self, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
869        let view = &self.view;
870        let eye = view.eye_position();
871        let forward = view.camera_pose().forward();
872        // Meters per Web Mercator unit at zoom 0, across the ground at `hit`.
873        let latitude = hit.location(WrapMode::Unwrapped).latitude();
874        let meters = Projection::meters_per_pixel_at_latitude(latitude, 0.0) * TILE_SIZE_D;
875        let to_hit = DVec3::new((hit.world.x - eye.x) * meters, (hit.world.y - eye.y) * meters, hit.height - eye.z);
876        let distance = to_hit.dot(forward);
877        if !(distance.is_finite() && distance > 0.0) {
878            return None;
879        }
880        let world = Point::new(eye.x + forward.x * distance / meters, eye.y + forward.y * distance / meters);
881        let center = Projection::unproject(&world, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped).ok()?;
882        // Wrapped, as move_lat_lng leaves it, unless bounds keep it in their
883        // range.
884        let center = if self.limits.bounds == LatLngBounds::default() { center.wrapped() } else { center };
885        let zoom = scale_zoom(view.camera_to_center_distance() * meters / distance / TILE_SIZE_D);
886        Some((center, eye.z + forward.z * distance, zoom))
887    }
888
889    /// The center, its altitude and the zoom of [`Self::recenter_on`] on the
890    /// globe, before the limits, in unit-sphere space. The center keeps the
891    /// world copy nearest the current one, as the globe's moves do.
892    fn recentered_on_sphere(view: &View, hit: &GroundHit) -> Option<(LatLng, f64, f64)> {
893        let radius = |height: f64| 1.0 + height / VerticalPerspectiveProjection::GLOBE_RADIUS_METERS;
894        let eye = view.globe_camera_position();
895        let center = VerticalPerspectiveProjection::surface_vector(&view.center(WrapMode::Unwrapped))
896            * radius(view.center_altitude());
897        let forward = (center - eye).normalize();
898        let target =
899            VerticalPerspectiveProjection::surface_vector(&hit.location(WrapMode::Unwrapped)) * radius(hit.height);
900        let distance = (target - eye).dot(forward);
901        if !(distance.is_finite() && distance > 0.0) {
902            return None;
903        }
904        let point = eye + forward * distance;
905        let length = point.length();
906        let location = VerticalPerspectiveProjection::surface_vector_to_lat_lng(point / length)?;
907        let location = view.lat_lng_near_center(&location);
908        let radius_at_zoom_0 =
909            VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(1.0), location.latitude());
910        let zoom = scale_zoom(view.camera_to_center_distance() / distance / radius_at_zoom_0);
911        Some((location, (length - 1.0) * VerticalPerspectiveProjection::GLOBE_RADIUS_METERS, zoom))
912    }
913
914    /// Meters per pixel at the zoom of a height at the center: on Mercator
915    /// the view's, and on the globe those of its sphere, which it raises
916    /// heights on.
917    fn height_meters_per_pixel(view: &View) -> f64 {
918        if view.is_globe() {
919            let latitude = view.center(WrapMode::Unwrapped).latitude();
920            VerticalPerspectiveProjection::GLOBE_RADIUS_METERS
921                / VerticalPerspectiveProjection::globe_radius_pixels(Projection::world_size(view.scale()), latitude)
922        } else {
923            view.meters_per_pixel()
924        }
925    }
926}
927
928#[cfg(test)]
929#[path = "transform_state_test.rs"]
930mod transform_state_test;