Skip to main content

mln_engine/camera/
transform_state.rs

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