Skip to main content

mln_engine/camera/
view.rs

1//! One view of a map: what its camera sees, with the matrices that draw it
2//! and convert between the screen and the map.
3
4use std::f64::consts::PI;
5
6use geometry::Point;
7use glam::dcamera::rh::proj::opengl::perspective;
8use glam::{DMat4, DVec2, DVec3, DVec4};
9use mln_style::constants::TILE_SIZE_D;
10use mln_style::error::Error;
11use mln_style::geo::{LatLng, WrapMode};
12use mln_style::size::Size;
13use mln_style::types::ProjectionDefinition;
14
15use crate::camera::camera::FreeCameraOptions;
16use crate::camera::camera_pose::CameraPose;
17use crate::camera::constants::DEFAULT_FOV;
18use crate::camera::map_view::{Camera, LogicalExtent, MapView, Viewport};
19use crate::camera::mode::{ConstrainMode, ViewportMode};
20use crate::camera::projection::{ProjectionData, mercator_tile_matrix};
21use crate::camera::projection_mode::{AxonometricMode, ProjectionMode};
22use crate::camera::tile_coordinate::TileCoordinate;
23use crate::camera::vertical_perspective_projection::VerticalPerspectiveProjection;
24pub use crate::geo::NorthOrientation;
25use crate::geo::constants::M2PI;
26use crate::geo::projection::Projection;
27use crate::geo::{EdgeInsets, ScreenCoordinate};
28use crate::tile::UnwrappedTileID;
29
30/// The largest pitch the Mercator horizon is computed for, in radians. Past
31/// it the distance to the horizon grows without bound, and with it the tiles
32/// the view needs.
33pub(crate) fn max_mercator_horizon_angle() -> f64 {
34    mln_style::math::deg2rad(89.25)
35}
36
37/// `x` rounded to the nearest integer when it is within a billionth of it,
38/// so that a zoom of 13.9999999 draws as 14.
39fn round_for_accuracy(x: f64) -> f64 {
40    let round_x = x.round();
41    let diff = (round_x - x).abs();
42    if diff < 1e-9 && diff > 0.0 { round_x } else { x }
43}
44
45/// The scale of `zoom`: 2 to its power.
46#[must_use]
47pub fn zoom_scale(zoom: f64) -> f64 {
48    round_for_accuracy(2.0f64.powf(zoom))
49}
50
51/// The zoom of `scale`: its base-2 logarithm.
52#[must_use]
53pub fn scale_zoom(scale: f64) -> f64 {
54    round_for_accuracy(scale.log2())
55}
56
57/// The map's offset from the world's center that puts `center` at the
58/// center of a view at `scale`, in pixels: the negated center. The globe's
59/// center can be on a pole, which Mercator's stops short of.
60pub(crate) fn map_offset(center: &LatLng, scale: f64, globe: bool) -> (f64, f64) {
61    let world_size = Projection::world_size(scale);
62    let latitude = mln_style::math::deg2rad(center.latitude());
63    let m = 1.0 - 1e-15;
64    let f = mln_style::math::clamp_f64(latitude.sin(), -m, m);
65    let x = -center.longitude() * (world_size / 360.0);
66    let cc = world_size / M2PI;
67    let y = if globe { cc * latitude.tan().asinh() } else { 0.5 * cc * ((1.0 + f) / (1.0 - f)).ln() };
68    (x, y)
69}
70
71/// The fractional part of `x`, with the sign of `x`.
72fn modf_fraction(x: f64) -> f64 {
73    if x.is_infinite() {
74        return 0.0f64.copysign(x);
75    }
76    (x - x.trunc()).copysign(x)
77}
78
79/// What a view shows, in the units its math works in.
80#[derive(Clone, Copy, Debug, PartialEq)]
81pub(crate) struct ViewParams {
82    pub(crate) size: Size,
83    pub(crate) frustum_offset: EdgeInsets,
84    pub(crate) north_orientation: NorthOrientation,
85    pub(crate) viewport_mode: ViewportMode,
86    /// The constrain mode of the map the view comes from, which
87    /// [`View::map_view`] reports.
88    pub(crate) constrain_mode: ConstrainMode,
89    /// Whether the center of the map the view comes from stands on its
90    /// terrain, which [`View::map_view`] reports.
91    pub(crate) center_clamped_to_ground: bool,
92    /// Whether drags and zooms on the globe of the map the view comes from
93    /// turn the bearing, which [`View::map_view`] reports.
94    pub(crate) globe_free_bearing: bool,
95    /// The style's projection, as it was last set.
96    pub(crate) projection_definition: ProjectionDefinition,
97    /// 0 is Mercator, 1 is the globe, in between is the transition.
98    pub(crate) projection_transition: f64,
99    pub(crate) padding: EdgeInsets,
100    /// The map's offset from the world's center, in pixels at `scale`: the
101    /// negated center.
102    pub(crate) x: f64,
103    pub(crate) y: f64,
104    /// The center's altitude, in meters. It holds through changes of the
105    /// zoom and the center; the matrices derive its pixels.
106    pub(crate) center_altitude: f64,
107    pub(crate) scale: f64,
108    /// The rotation of the map, in radians counterclockwise: the negated
109    /// bearing.
110    pub(crate) angle: f64,
111    pub(crate) pitch: f64,
112    pub(crate) roll: f64,
113    pub(crate) fov: f64,
114    pub(crate) x_skew: f64,
115    pub(crate) y_skew: f64,
116    pub(crate) axonometric: bool,
117    /// How [`View::camera`] reports the center.
118    pub(crate) center_wrap: WrapMode,
119    /// While terrain draws, the lowest ground near the center, in meters,
120    /// exaggerated; the near and far planes then fit raised ground.
121    pub(crate) terrain_min_elevation: Option<f64>,
122}
123
124impl ViewParams {
125    pub(crate) fn new(constrain_mode: ConstrainMode, viewport_mode: ViewportMode) -> Self {
126        ViewParams {
127            size: Size::default(),
128            frustum_offset: EdgeInsets::default(),
129            north_orientation: NorthOrientation::Upwards,
130            viewport_mode,
131            constrain_mode,
132            center_clamped_to_ground: true,
133            globe_free_bearing: false,
134            projection_definition: ProjectionDefinition::default(),
135            projection_transition: 0.0,
136            padding: EdgeInsets::default(),
137            x: 0.0,
138            y: 0.0,
139            center_altitude: 0.0,
140            scale: 1.0,
141            angle: 0.0,
142            pitch: 0.0,
143            roll: 0.0,
144            fov: DEFAULT_FOV,
145            x_skew: 0.0,
146            y_skew: 1.0,
147            axonometric: false,
148            center_wrap: WrapMode::Unwrapped,
149            terrain_min_elevation: None,
150        }
151    }
152}
153
154/// The matrices of a view, zero while its size is empty or its projection
155/// can't be inverted. The globe's are zero unless it renders the globe.
156#[derive(Clone, Copy, Debug)]
157struct Matrices {
158    projection: DMat4,
159    inv_projection: DMat4,
160    coord: DMat4,
161    /// The inverse of `coord` from the center of the map: it takes a screen
162    /// point to its offset from the center, which keeps the precision that
163    /// the whole world's coordinates would lose.
164    inverted_from_center: DMat4,
165    globe_view_projection: DMat4,
166    inv_globe_view_projection: DMat4,
167    globe_clipping_plane: DVec4,
168    globe_camera_position: DVec3,
169}
170
171impl Matrices {
172    const ZERO: Matrices = Matrices {
173        projection: DMat4::ZERO,
174        inv_projection: DMat4::ZERO,
175        coord: DMat4::ZERO,
176        inverted_from_center: DMat4::ZERO,
177        globe_view_projection: DMat4::ZERO,
178        inv_globe_view_projection: DMat4::ZERO,
179        globe_clipping_plane: DVec4::ZERO,
180        globe_camera_position: DVec3::ZERO,
181    };
182}
183
184/// One view of a map: its camera, size and projection, and the matrices it
185/// draws with. A view never changes: a map that moves its camera makes a new
186/// one.
187///
188/// Angles are in radians. A view with an empty size, or a camera whose
189/// projection can't be inverted, shows nothing.
190#[derive(Clone, Debug)]
191pub struct View {
192    params: ViewParams,
193    matrices: Matrices,
194}
195
196impl PartialEq for View {
197    /// Two views are equal if they show the same: the matrices follow.
198    fn eq(&self, other: &Self) -> bool {
199        self.params == other.params
200    }
201}
202
203impl Default for View {
204    fn default() -> Self {
205        View::new(ViewParams::new(ConstrainMode::HeightOnly, ViewportMode::Default))
206    }
207}
208
209impl View {
210    pub(crate) fn new(params: ViewParams) -> Self {
211        let mut view = View { params, matrices: Matrices::ZERO };
212        view.matrices = view.compute_matrices();
213        view
214    }
215
216    pub(crate) fn params(&self) -> &ViewParams {
217        &self.params
218    }
219
220    /// The matrices, from the view's parameters alone.
221    fn compute_matrices(&self) -> Matrices {
222        if self.params.size.is_empty() {
223            return Matrices::ZERO;
224        }
225        let projection = self.projection_matrix_with(self.near_z(), false);
226        let coord = self.coordinate_point_matrix(&projection);
227        let from_center = coord * DMat4::from_translation(self.center_coordinate());
228        let (Some(inv_projection), Some(inverted_from_center)) = (projection.try_inverse(), from_center.try_inverse())
229        else {
230            return Matrices::ZERO;
231        };
232        let mut matrices = Matrices { projection, inv_projection, coord, inverted_from_center, ..Matrices::ZERO };
233        if self.is_globe() {
234            let globe_radius = VerticalPerspectiveProjection::globe_radius_pixels(
235                Projection::world_size(self.params.scale),
236                self.center(WrapMode::Unwrapped).latitude(),
237            );
238            let globe_view_projection = VerticalPerspectiveProjection::globe_view_projection_matrix(self, globe_radius);
239            matrices.globe_view_projection = globe_view_projection;
240            matrices.inv_globe_view_projection = globe_view_projection.try_inverse().unwrap_or(DMat4::IDENTITY);
241            matrices.globe_clipping_plane = VerticalPerspectiveProjection::clipping_plane(self, globe_radius);
242            matrices.globe_camera_position = VerticalPerspectiveProjection::camera_position(self, globe_radius);
243        }
244        matrices
245    }
246
247    // MARK: - Dimensions
248
249    /// The size, in logical pixels.
250    #[must_use]
251    pub fn size(&self) -> Size {
252        self.params.size
253    }
254
255    /// Insets that move the vanishing point off the center of the view.
256    #[must_use]
257    pub fn frustum_offset(&self) -> EdgeInsets {
258        self.params.frustum_offset
259    }
260
261    /// Insets from the view's edges. The camera centers within the rest.
262    #[must_use]
263    pub fn padding(&self) -> EdgeInsets {
264        self.params.padding
265    }
266
267    #[must_use]
268    pub fn north_orientation(&self) -> NorthOrientation {
269        self.params.north_orientation
270    }
271
272    /// The rotation that the north orientation adds, in radians.
273    #[must_use]
274    pub fn north_orientation_angle(&self) -> f64 {
275        match self.params.north_orientation {
276            NorthOrientation::Upwards => 0.0,
277            NorthOrientation::Rightwards => PI / 2.0,
278            NorthOrientation::Downwards => PI,
279            NorthOrientation::Leftwards => -PI / 2.0,
280        }
281    }
282
283    #[must_use]
284    pub fn viewport_mode(&self) -> ViewportMode {
285        self.params.viewport_mode
286    }
287
288    /// Whether the map's center stands on its terrain
289    /// ([`Viewport::center_clamped_to_ground`]).
290    #[must_use]
291    pub fn center_clamped_to_ground(&self) -> bool {
292        self.params.center_clamped_to_ground
293    }
294
295    /// Whether drags and zooms on the globe turn the bearing
296    /// ([`Viewport::globe_free_bearing`]).
297    #[must_use]
298    pub fn globe_free_bearing(&self) -> bool {
299        self.params.globe_free_bearing
300    }
301
302    /// The center's offset from the middle of the view that the padding
303    /// makes, in pixels from the top left.
304    pub(crate) fn center_offset(&self) -> ScreenCoordinate {
305        let padding = &self.params.padding;
306        ScreenCoordinate::new(0.5 * (padding.left - padding.right), 0.5 * (padding.top - padding.bottom))
307    }
308
309    // MARK: - Camera
310
311    /// The center. `WrapMode::Unwrapped` keeps the copy of the world that
312    /// the camera is in.
313    #[must_use]
314    pub fn center(&self, wrap_mode: WrapMode) -> LatLng {
315        let world_size = Projection::world_size(self.params.scale);
316        LatLng::saturating(
317            mln_style::math::rad2deg(2.0 * (self.params.y / (world_size / M2PI)).exp().atan() - 0.5 * PI),
318            -self.params.x / (world_size / 360.0),
319            wrap_mode,
320        )
321    }
322
323    /// The world copy of `location` nearest the center, which bounds can keep
324    /// past the antimeridian.
325    #[must_use]
326    pub fn lat_lng_near_center(&self, location: &LatLng) -> LatLng {
327        let center = self.center(WrapMode::Unwrapped);
328        let wrapped_center = center.wrapped();
329        let mut nearest = location.wrapped();
330        nearest.unwrap_for_shortest_path(&wrapped_center);
331        LatLng::saturating(
332            nearest.latitude(),
333            nearest.longitude() + center.longitude() - wrapped_center.longitude(),
334            WrapMode::Unwrapped,
335        )
336    }
337
338    /// The center's altitude, in meters.
339    #[must_use]
340    pub fn center_altitude(&self) -> f64 {
341        self.params.center_altitude
342    }
343
344    /// Meters per pixel at the zoom, as at the center (GL JS's
345    /// `pixelsPerMeter`, inverted): the scale of every height the matrices
346    /// place, so that a point at the center's altitude draws at the center.
347    pub(crate) fn meters_per_pixel(&self) -> f64 {
348        Projection::meters_per_pixel_at_latitude(self.center(WrapMode::Unwrapped).latitude(), self.zoom())
349    }
350
351    /// The center's altitude in pixels at the zoom.
352    fn center_altitude_pixels(&self) -> f64 {
353        // A center at sea level, as on most maps, spares the conversion's
354        // transcendental functions on every new view.
355        if self.params.center_altitude == 0.0 {
356            return self.params.center_altitude;
357        }
358        self.params.center_altitude / self.meters_per_pixel()
359    }
360
361    #[must_use]
362    pub fn zoom(&self) -> f64 {
363        scale_zoom(self.params.scale)
364    }
365
366    /// The zoom, rounded down and clamped to the `u8` range.
367    #[must_use]
368    pub fn integer_zoom(&self) -> u8 {
369        f64::max(0.0, self.zoom()) as u8
370    }
371
372    /// The zoom's fractional part.
373    #[must_use]
374    pub fn zoom_fraction(&self) -> f64 {
375        self.zoom() - f64::from(self.integer_zoom())
376    }
377
378    /// 2 to the power of the zoom.
379    #[must_use]
380    pub fn scale(&self) -> f64 {
381        self.params.scale
382    }
383
384    /// The map's offset from the world's center along x, in pixels at the
385    /// scale: the negated center.
386    #[must_use]
387    pub fn x(&self) -> f64 {
388        self.params.x
389    }
390
391    /// The map's offset from the world's center along y.
392    #[must_use]
393    pub fn y(&self) -> f64 {
394        self.params.y
395    }
396
397    /// The map's rotation, counterclockwise: the negated bearing.
398    #[must_use]
399    pub fn angle(&self) -> f64 {
400        self.params.angle
401    }
402
403    /// The tilt toward the horizon. 0 looks straight down.
404    #[must_use]
405    pub fn pitch(&self) -> f64 {
406        self.params.pitch
407    }
408
409    #[must_use]
410    pub fn roll(&self) -> f64 {
411        self.params.roll
412    }
413
414    /// The vertical field of view.
415    #[must_use]
416    pub fn fov(&self) -> f64 {
417        self.params.fov
418    }
419
420    /// The field of view that the perspective projections use: [`fov`]
421    /// rounded to `f32`, the precision of the camera that drew the render
422    /// tests' expected images. At full precision, edges land a fraction of a
423    /// pixel away from theirs.
424    ///
425    /// [`fov`]: Self::fov
426    pub(crate) fn perspective_fov(&self) -> f64 {
427        f64::from(self.params.fov as f32)
428    }
429
430    /// The distance from the camera to the center, in pixels.
431    #[must_use]
432    pub fn camera_to_center_distance(&self) -> f64 {
433        0.5 * f64::from(self.params.size.height) / (self.params.fov / 2.0).tan()
434    }
435
436    /// GL JS's `getMercatorHorizon`: how far above the center of the view,
437    /// in pixels, the map ends and the sky starts. It is 0.85 of the way to
438    /// the flat map's geometric horizon, and never past 89.25 degrees from
439    /// straight down; at a pitch past that it is negative.
440    #[must_use]
441    pub fn mercator_horizon(&self) -> f64 {
442        let pitch = self.params.pitch;
443        self.camera_to_center_distance()
444            * f64::min((PI / 2.0 - pitch).tan() * 0.85, (max_mercator_horizon_angle() - pitch).tan())
445    }
446
447    #[must_use]
448    pub fn projection_mode(&self) -> ProjectionMode {
449        ProjectionMode {
450            axonometric: Some(AxonometricMode::from(self.params.axonometric)),
451            x_skew: Some(self.params.x_skew),
452            y_skew: Some(self.params.y_skew),
453        }
454    }
455
456    /// The camera, in degrees, as the map reports it.
457    #[must_use]
458    pub fn camera(&self) -> Camera {
459        Camera {
460            center: self.center(self.params.center_wrap),
461            center_altitude: self.center_altitude(),
462            padding: self.params.padding,
463            zoom: self.zoom(),
464            bearing: mln_style::math::rad2deg(-self.params.angle),
465            pitch: mln_style::math::rad2deg(self.params.pitch),
466            roll: mln_style::math::rad2deg(self.params.roll),
467            fov: mln_style::math::rad2deg(self.params.fov),
468        }
469    }
470
471    /// The view as its public description, at `scale_factor` physical pixels
472    /// in each logical pixel.
473    #[must_use]
474    pub fn map_view(&self, scale_factor: f64) -> MapView {
475        MapView {
476            camera: self.camera(),
477            extent: LogicalExtent { size: self.params.size, scale_factor },
478            projection_mode: self.projection_mode(),
479            viewport: Viewport {
480                north_orientation: self.params.north_orientation,
481                constrain_mode: self.params.constrain_mode,
482                viewport_mode: self.params.viewport_mode,
483                center_clamped_to_ground: self.params.center_clamped_to_ground,
484                globe_free_bearing: self.params.globe_free_bearing,
485                frustum_offset: self.params.frustum_offset,
486            },
487            projection: self.params.projection_definition,
488        }
489    }
490
491    /// Whether the view shows anything: it has a size and a scale.
492    #[must_use]
493    pub fn is_valid(&self) -> bool {
494        !self.params.size.is_empty() && self.params.scale.is_finite() && self.params.scale > 0.0
495    }
496
497    /// The camera's position and orientation, or the default pose while the
498    /// view isn't valid.
499    pub(crate) fn camera_pose(&self) -> CameraPose {
500        if !self.is_valid() {
501            return CameraPose::default();
502        }
503        let world_size = Projection::world_size(self.params.scale);
504        // x and y are the map's position, the camera's negated, from the
505        // middle of the world.
506        let center = DVec3::new(
507            0.5 * world_size - self.params.x,
508            0.5 * world_size - self.params.y,
509            self.center_altitude_pixels(),
510        );
511        // Orient the camera, then move it back from the center along its line
512        // of sight.
513        let mut camera = CameraPose::from_angles(DVec3::ZERO, self.params.roll, self.params.pitch, self.params.angle);
514        camera.position = (center - camera.forward() * self.camera_to_center_distance()) / world_size;
515        camera
516    }
517
518    /// The camera's position and orientation.
519    #[must_use]
520    pub fn free_camera_options(&self) -> FreeCameraOptions {
521        let camera = self.camera_pose();
522        FreeCameraOptions { position: Some(camera.position), orientation: Some(camera.orientation) }
523    }
524
525    /// Where the camera's eye is: its Web Mercator point at zoom 0 (from 0
526    /// to 1 across, y south) and its altitude in meters, of the meters the
527    /// view places heights in ([`center_altitude`](Self::center_altitude)).
528    /// On the globe it is the point under the eye, in the world copy nearest
529    /// the center, with y past 0 or 1 over a polar cap, and the eye's height
530    /// above the sea-level sphere.
531    #[must_use]
532    pub fn eye_position(&self) -> DVec3 {
533        if self.is_globe() && self.is_valid() {
534            let eye = self.matrices.globe_camera_position;
535            return VerticalPerspectiveProjection::sphere_point_to_world(self, eye).unwrap_or(eye);
536        }
537        let position = self.camera_pose().position;
538        let world_size = Projection::world_size(self.params.scale);
539        DVec3::new(position.x, position.y, position.z * world_size * self.meters_per_pixel())
540    }
541
542    /// A 3 by 3 grid over the projection matrix's near plane, its corners,
543    /// the middles of its edges and its center, in the units of
544    /// [`eye_position`](Self::eye_position): the renderer drops what is
545    /// nearer, so ground above a point shows as a hole into it. On the globe
546    /// it is the globe matrix's near plane. All are the eye while the view
547    /// shows nothing.
548    #[must_use]
549    pub fn near_plane_points(&self) -> [DVec3; 9] {
550        let eye = self.eye_position();
551        if self.matrices.projection == DMat4::ZERO {
552            return [eye; 9];
553        }
554        let clip = |index: usize| DVec3::new((index % 3) as f64 - 1.0, (index / 3) as f64 - 1.0, -1.0);
555        if self.is_globe() {
556            let inverse = self.matrices.inv_globe_view_projection;
557            return std::array::from_fn(|index| {
558                let point = inverse.project_point3(clip(index));
559                VerticalPerspectiveProjection::sphere_point_to_world(self, point).unwrap_or(eye)
560            });
561        }
562        let world_size = Projection::world_size(self.params.scale);
563        std::array::from_fn(|index| {
564            let point = self.matrices.inv_projection.project_point3(clip(index));
565            DVec3::new(point.x / world_size, point.y / world_size, point.z)
566        })
567    }
568
569    // MARK: - Projection
570
571    #[must_use]
572    pub fn projection_definition(&self) -> ProjectionDefinition {
573        self.params.projection_definition
574    }
575
576    /// 0 is Mercator, 1 is the globe, in between is the transition.
577    #[must_use]
578    pub fn projection_transition(&self) -> f64 {
579        self.params.projection_transition
580    }
581
582    /// Whether the view draws the globe, also while it hands over to or from
583    /// Mercator.
584    #[must_use]
585    pub fn is_globe(&self) -> bool {
586        self.params.projection_transition > 0.0
587    }
588
589    /// The globe while [`is_globe`](Self::is_globe), Mercator otherwise.
590    #[must_use]
591    pub fn projection(&self) -> crate::camera::Projection {
592        if self.is_globe() {
593            crate::camera::Projection::VerticalPerspective
594        } else {
595            crate::camera::Projection::Mercator
596        }
597    }
598
599    /// The same camera, size and center altitude on Mercator: the view at a
600    /// projection transition of 0. A view on Mercator is its own.
601    #[must_use]
602    pub fn mercator(&self) -> View {
603        if !self.is_globe() {
604            return self.clone();
605        }
606        View::new(ViewParams { projection_transition: 0.0, ..self.params })
607    }
608
609    /// The tile-to-world matrix of a tile at the view's scale.
610    #[must_use]
611    pub fn tile_matrix(&self, tile_id: &UnwrappedTileID) -> DMat4 {
612        mercator_tile_matrix(tile_id, self.params.scale)
613    }
614
615    /// The projection of a tile, through `proj_matrix`.
616    #[must_use]
617    pub fn projection_data_with(&self, tile_id: &UnwrappedTileID, proj_matrix: &DMat4) -> ProjectionData {
618        let mercator_matrix = *proj_matrix * self.tile_matrix(tile_id);
619        self.projection().projection_data(self, tile_id, &mercator_matrix)
620    }
621
622    /// The projection of a tile, through the projection matrix.
623    #[must_use]
624    pub fn projection_data(&self, tile_id: &UnwrappedTileID) -> ProjectionData {
625        self.projection_data_with(tile_id, &self.matrices.projection)
626    }
627
628    /// The projection of a tile whose Mercator tile-to-clip matrix is
629    /// `mercator_matrix`.
630    #[must_use]
631    pub fn projection_data_for_matrix(&self, tile_id: &UnwrappedTileID, mercator_matrix: &DMat4) -> ProjectionData {
632        self.projection().projection_data(self, tile_id, mercator_matrix)
633    }
634
635    /// The lowest ground near the center while terrain draws, in meters,
636    /// exaggerated; `None` without terrain
637    /// ([`TransformState::set_terrain_min_elevation`]).
638    ///
639    /// [`TransformState::set_terrain_min_elevation`]: crate::camera::TransformState::set_terrain_min_elevation
640    #[must_use]
641    pub fn terrain_min_elevation(&self) -> Option<f64> {
642        self.params.terrain_min_elevation
643    }
644
645    /// The distance from the camera to the near plane of the projection
646    /// matrix, in pixels: 1, or a fiftieth of the view's height while
647    /// terrain draws, as in GL JS, for the depth precision raised ground
648    /// needs. The globe's matrix takes it while terrain draws too.
649    #[must_use]
650    pub fn near_z(&self) -> f64 {
651        match self.params.terrain_min_elevation {
652            Some(_) => f64::from(self.params.size.height) / 50.0,
653            None => 1.0,
654        }
655    }
656
657    /// The distance from the camera to the far plane of the projection
658    /// matrix, in pixels at the zoom: past the farthest point of the ground
659    /// that the view shows, down to the terrain's lowest ground while it
660    /// draws.
661    #[must_use]
662    pub fn far_z(&self) -> f64 {
663        match self.params.terrain_min_elevation {
664            Some(min_elevation) => self.terrain_far_z(min_elevation),
665            None => self.flat_far_z(),
666        }
667    }
668
669    /// The far plane over a flat map, with the center at its altitude.
670    fn flat_far_z(&self) -> f64 {
671        let camera_to_center_distance = self.camera_to_center_distance();
672
673        let limited_pitch = mln_style::math::clamp_f64(self.params.pitch, 0.0, max_mercator_horizon_angle());
674        let camera_to_sea_level_distance =
675            camera_to_center_distance + self.center_altitude_pixels().abs() / limited_pitch.cos();
676
677        let tan_multiple = mln_style::math::clamp_f64(self.tan_fov_above_center() * limited_pitch.tan(), 0.0, 0.99);
678        let horizon_multiple =
679            mln_style::math::clamp_f64(self.fov_center_to_horizon().tan() * limited_pitch.tan(), 0.0, 0.99);
680
681        // The distance to the farthest fragment that is drawn, and a little
682        // more, for the precision of a fragment exactly there.
683        let furthest_distance = camera_to_sea_level_distance / (1.0 - tan_multiple.min(horizon_multiple));
684        furthest_distance * 1.01
685    }
686
687    /// GL JS's `cameraToSeaLevelDistance`, in pixels at the zoom: how far
688    /// the camera is from sea level along the view, past the center by its
689    /// altitude, at the pitch up to the horizon's limit, and at least half
690    /// the distance to the center.
691    #[must_use]
692    pub fn camera_to_sea_level_distance(&self) -> f64 {
693        let camera_to_center_distance = self.camera_to_center_distance();
694        let limited_pitch = self.params.pitch.min(max_mercator_horizon_angle());
695        f64::max(
696            camera_to_center_distance / 2.0,
697            camera_to_center_distance + self.center_altitude_pixels() / limited_pitch.cos(),
698        )
699    }
700
701    /// GL JS's far plane (`calculateNearFarZ`) over ground that reaches down
702    /// to `min_elevation` meters: it fits the lowest of that, the center and
703    /// 100 meters below the camera. The frustum offset shortens it as it
704    /// does the flat map's.
705    fn terrain_far_z(&self, min_elevation: f64) -> f64 {
706        let params = &self.params;
707        let camera_to_center_distance = self.camera_to_center_distance();
708        let pixels_per_meter = 1.0 / self.meters_per_pixel();
709
710        // Heights in pixels at the zoom.
711        let center_altitude = self.center_altitude_pixels();
712        let limited_pitch = params.pitch.min(max_mercator_horizon_angle());
713        let camera_to_sea_level_distance = self.camera_to_sea_level_distance();
714        let camera_altitude = params.pitch.cos() * camera_to_center_distance + center_altitude;
715        let lowest =
716            center_altitude.min(min_elevation * pixels_per_meter).min(camera_altitude - 100.0 * pixels_per_meter);
717        let lowest_plane = if lowest < 0.0 {
718            camera_to_sea_level_distance - lowest / limited_pitch.cos()
719        } else {
720            camera_to_sea_level_distance
721        };
722
723        // How far past the center, along the lowest plane, the ray at `angle`
724        // above the center of the view meets it: the law of sines in the
725        // triangle of the camera, the center and that point.
726        let ground_angle = PI / 2.0 + params.pitch;
727        let distance_past_center = |angle: f64| {
728            angle.sin() * lowest_plane / mln_style::math::clamp_f64(PI - ground_angle - angle, 0.01, PI - 0.01).sin()
729        };
730        let top_half_distance = distance_past_center(self.tan_fov_above_center().atan())
731            .min(distance_past_center(self.fov_center_to_horizon()));
732
733        (limited_pitch.sin() * top_half_distance + lowest_plane) * 1.01
734    }
735
736    /// The tangent of the angle from the center of the view, with the
737    /// padding, to its edge farthest up the map, in units where 1 is a pixel
738    /// at the center of the map: to the top edge of an upright view, and to
739    /// its farthest corner as the view turns.
740    fn tan_fov_above_center(&self) -> f64 {
741        let params = &self.params;
742        let half_width = 0.5 * f64::from(params.size.width);
743        let half_height = 0.5 * f64::from(params.size.height);
744        let offset = self.center_offset();
745        // The view's reach from its padded center to each edge, in pixels.
746        let (left, right) = (half_width + offset.x, half_width - offset.x);
747        let (top, bottom) = (half_height + offset.y - params.frustum_offset.top, half_height - offset.y);
748        let up = self.up_the_map();
749        let reach = (up.x * right).max(-up.x * left) + (up.y * top).max(-up.y * bottom);
750        reach / half_height * (params.fov / 2.0).tan()
751    }
752
753    /// The angle from the center of the view, with the padding, up the map
754    /// to the horizon, where the map ends and the sky starts (GL JS's
755    /// `calculateNearFarZ`): at high pitch it is below the top of the view.
756    /// The sky draws the horizon [`mercator_horizon`](Self::mercator_horizon)
757    /// pixels up the map from the center of the view without the padding,
758    /// so the padding's offset up the map moves it, but never past 89.25
759    /// degrees from straight down, nor below the center.
760    fn fov_center_to_horizon(&self) -> f64 {
761        let camera_to_center = self.camera_to_center_distance();
762        let horizon = self.mercator_horizon();
763        let min_horizon_angle = PI / 2.0 - max_mercator_horizon_angle();
764        if (horizon / camera_to_center).atan() <= min_horizon_angle {
765            return min_horizon_angle;
766        }
767        let offset = self.center_offset();
768        let offset_up = DVec2::new(-offset.x, offset.y).dot(self.up_the_map());
769        let farthest = camera_to_center * (max_mercator_horizon_angle() - self.params.pitch).tan();
770        (mln_style::math::clamp_f64(horizon + offset_up, 0.0, farthest) / camera_to_center).atan()
771    }
772
773    /// The unit direction up the map in the view, x right and y up, which
774    /// the roll, the viewport's flip and the north orientation turn: a roll
775    /// of 90 degrees turns the left edge up.
776    fn up_the_map(&self) -> DVec2 {
777        let (sin, cos) = self.params.roll.sin_cos();
778        let flip = if self.params.viewport_mode == ViewportMode::FlippedY { -1.0 } else { 1.0 };
779        DVec2::from_angle(-self.north_orientation_angle()).rotate(DVec2::new(-sin, flip * cos))
780    }
781
782    /// The projection matrix with its near plane at `near_z` pixels, aligned
783    /// to the pixel grid if `aligned`; zero while the size is empty.
784    #[must_use]
785    pub fn projection_matrix_with(&self, near_z: f64, aligned: bool) -> DMat4 {
786        let params = &self.params;
787        if params.size.is_empty() {
788            return DMat4::ZERO;
789        }
790
791        let offset = self.center_offset();
792        let width = f64::from(params.size.width);
793        let height = f64::from(params.size.height);
794
795        let camera = self.camera_pose();
796        let pixels_per_meter = 1.0 / self.meters_per_pixel();
797        let world_to_camera =
798            camera.world_to_camera(params.scale, pixels_per_meter, params.viewport_mode == ViewportMode::FlippedY);
799        let mut camera_to_clip = perspective(self.perspective_fov(), width / height, near_z, self.far_z());
800
801        // The vanishing point moves to the center of the padded view, from -1
802        // to 1 across it. An axonometric view has none.
803        if !params.axonometric {
804            camera_to_clip.z_axis.x = -offset.x * 2.0 / width;
805            camera_to_clip.z_axis.y = offset.y * 2.0 / height;
806        }
807
808        if params.north_orientation != NorthOrientation::Upwards {
809            camera_to_clip *= DMat4::from_rotation_z(-self.north_orientation_angle());
810        }
811
812        let mut proj_matrix = camera_to_clip * world_to_camera;
813
814        if params.axonometric {
815            // Without perspective, z skews x and y instead.
816            proj_matrix.z_axis.w = 0.0;
817            proj_matrix.z_axis.x = params.x_skew * pixels_per_meter;
818            proj_matrix.z_axis.y = params.y_skew * pixels_per_meter;
819        }
820
821        // The pixel-aligned matrix, for raster tiles: the center moves to a
822        // whole pixel, and by half a pixel more along a side of odd length,
823        // with the shift turned by the bearing and kept within half a pixel,
824        // so that rasters at right angles draw crisp.
825        if aligned {
826            let world_size = Projection::world_size(params.scale);
827            let dx = params.x - 0.5 * world_size;
828            let dy = params.y - 0.5 * world_size;
829
830            let x_shift = f64::from(params.size.width % 2) / 2.0;
831            let y_shift = f64::from(params.size.height % 2) / 2.0;
832            let angle_cos = params.angle.cos();
833            let angle_sin = params.angle.sin();
834            let dxa = -modf_fraction(dx) + angle_cos * x_shift + angle_sin * y_shift;
835            let dya = -modf_fraction(dy) + angle_cos * y_shift + angle_sin * x_shift;
836            proj_matrix *= DMat4::from_translation(DVec3::new(
837                if dxa > 0.5 { dxa - 1.0 } else { dxa },
838                if dya > 0.5 { dya - 1.0 } else { dya },
839                0.0,
840            ));
841        }
842        proj_matrix
843    }
844
845    /// The projection matrix: from world pixels at the scale, z in meters, to
846    /// clip space.
847    #[must_use]
848    pub fn projection_matrix(&self) -> DMat4 {
849        self.matrices.projection
850    }
851
852    #[must_use]
853    pub fn inverse_projection_matrix(&self) -> DMat4 {
854        self.matrices.inv_projection
855    }
856
857    /// The globe's view projection, from unit-sphere space to clip space,
858    /// while [`is_globe`](Self::is_globe).
859    #[must_use]
860    pub fn globe_view_projection_matrix(&self) -> DMat4 {
861        self.matrices.globe_view_projection
862    }
863
864    #[must_use]
865    pub fn inverse_globe_view_projection_matrix(&self) -> DMat4 {
866        self.matrices.inv_globe_view_projection
867    }
868
869    /// The plane, as `ax + by + cz + d`, that separates the globe's visible
870    /// hemisphere from its back.
871    #[must_use]
872    pub fn globe_clipping_plane(&self) -> DVec4 {
873        self.matrices.globe_clipping_plane
874    }
875
876    /// The camera in unit-sphere space.
877    #[must_use]
878    pub fn globe_camera_position(&self) -> DVec3 {
879        self.matrices.globe_camera_position
880    }
881
882    /// The center of the map in the units that `coord` takes: world pixels
883    /// over the tile size, at the scale.
884    fn center_coordinate(&self) -> DVec3 {
885        let world_size = Projection::world_size(self.params.scale);
886        DVec3::new(
887            (0.5 * world_size - self.params.x) / TILE_SIZE_D,
888            (0.5 * world_size - self.params.y) / TILE_SIZE_D,
889            0.0,
890        )
891    }
892
893    /// The matrix from world space in tiles to screen pixels, y up.
894    fn coordinate_point_matrix(&self, proj_matrix: &DMat4) -> DMat4 {
895        let size = self.params.size;
896        let pixel_matrix =
897            DMat4::from_scale(DVec3::new(f64::from(size.width) / 2.0, -f64::from(size.height) / 2.0, 1.0))
898                * DMat4::from_translation(DVec3::new(1.0, -1.0, 0.0));
899        pixel_matrix * *proj_matrix * DMat4::from_scale(DVec3::new(TILE_SIZE_D, TILE_SIZE_D, 1.0))
900    }
901
902    // MARK: - Conversions
903
904    /// The screen point of a location, measured from the bottom edge (y up).
905    #[must_use]
906    pub fn lat_lng_to_screen_coordinate(&self, lat_lng: &LatLng) -> ScreenCoordinate {
907        self.lat_lng_to_screen_coordinate_at(lat_lng, 0.0)
908    }
909
910    /// The screen point of a location `height` meters above sea level,
911    /// measured from the bottom edge (y up). The globe raises it along its
912    /// vertical.
913    #[must_use]
914    pub fn lat_lng_to_screen_coordinate_at(&self, lat_lng: &LatLng, height: f64) -> ScreenCoordinate {
915        self.clip_point_at(lat_lng, height).0
916    }
917
918    /// The screen point of a location and its clip-space position, whose w
919    /// is negative behind the camera. Both are zero while the size is empty.
920    #[must_use]
921    pub fn lat_lng_to_screen_coordinate_with_clip(&self, lat_lng: &LatLng) -> (ScreenCoordinate, DVec4) {
922        self.clip_point_at(lat_lng, 0.0)
923    }
924
925    /// [`lat_lng_to_screen_coordinate_with_clip`] of a location `height`
926    /// meters above sea level.
927    ///
928    /// [`lat_lng_to_screen_coordinate_with_clip`]: Self::lat_lng_to_screen_coordinate_with_clip
929    fn clip_point_at(&self, lat_lng: &LatLng, height: f64) -> (ScreenCoordinate, DVec4) {
930        if self.params.size.is_empty() {
931            return (ScreenCoordinate::new(0.0, 0.0), DVec4::ZERO);
932        }
933
934        if self.is_globe() {
935            return VerticalPerspectiveProjection::lat_lng_to_screen_coordinate(self, lat_lng, height);
936        }
937
938        let pt = Projection::project(lat_lng, self.params.scale);
939        let p = self.matrices.coord * DVec4::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D, height, 1.0);
940        (ScreenCoordinate::new(p.x / p.w, f64::from(self.params.size.height) - p.y / p.w), p)
941    }
942
943    /// Whether the globe hides a location from the camera; a Mercator view
944    /// hides nothing.
945    #[must_use]
946    pub fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
947        if self.params.size.is_empty() || !self.is_globe() {
948            return false;
949        }
950        let surface = VerticalPerspectiveProjection::surface_vector(lat_lng);
951        self.globe_clipping_plane().dot(surface.extend(1.0)) < 0.0
952    }
953
954    /// The tile coordinate under a screen point (y up) at `at_zoom`, as GL
955    /// JS's `pointCoordinate`.
956    #[must_use]
957    pub fn screen_coordinate_to_tile_coordinate(&self, point: &ScreenCoordinate, at_zoom: u8) -> TileCoordinate {
958        if self.params.size.is_empty() {
959            return TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 };
960        }
961
962        if self.is_globe() {
963            return match VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(
964                self,
965                point,
966                0.0,
967                WrapMode::Unwrapped,
968            ) {
969                Some(lat_lng) => TileCoordinate::from_lat_lng(f64::from(at_zoom), &lat_lng),
970                None => TileCoordinate { p: Point::new(0.0, 0.0), z: 0.0 },
971            };
972        }
973
974        self.mercator_screen_coordinate_to_tile_coordinate(point, at_zoom, 0.0)
975    }
976
977    /// The tile coordinate at `at_zoom` where the line of sight through
978    /// `point` (y up) meets the plane `height` meters above sea level; where
979    /// the line doesn't descend, the point at clip depth 0.
980    fn mercator_screen_coordinate_to_tile_coordinate(
981        &self,
982        point: &ScreenCoordinate,
983        at_zoom: u8,
984        height: f64,
985    ) -> TileCoordinate {
986        let flipped_y = f64::from(self.params.size.height) - point.y;
987
988        // The point's depth isn't known: unproject it at two depths, and take
989        // where the line between them meets the plane.
990        let inverted = self.matrices.inverted_from_center;
991        let offset0 = inverted.project_point3(DVec3::new(point.x, flipped_y, 0.0));
992        let offset1 = inverted.project_point3(DVec3::new(point.x, flipped_y, 1.0));
993
994        let z0 = offset0.z;
995        let z1 = offset1.z;
996        // `z0 - 0.0` is `z0`, so sea level is the flat map's plane to the bit.
997        let t = if z0 <= z1 { 0.0 } else { -(z0 - height) / (z1 - z0) };
998
999        let offset = offset0 + (offset1 - offset0) * t;
1000        let center = self.center_coordinate();
1001        let factor = f64::from(1i32.wrapping_shl(u32::from(at_zoom)));
1002        let scale = self.params.scale;
1003        TileCoordinate {
1004            p: Point::new((center.x + offset.x) / scale * factor, (center.y + offset.y) / scale * factor),
1005            z: f64::from(at_zoom),
1006        }
1007    }
1008
1009    /// The location under `point`, measured from the bottom edge (y up).
1010    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
1011    /// NaN or infinite point.
1012    pub fn screen_coordinate_to_lat_lng(&self, point: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
1013        self.screen_coordinate_to_lat_lng_at(point, 0.0, wrap_mode)
1014    }
1015
1016    /// The location where the line of sight through `point`, measured from
1017    /// the bottom edge (y up), meets the plane `height` meters above sea
1018    /// level; where the line doesn't descend, as at sea level, the point it
1019    /// passes a little way from the camera. The globe meets the sphere
1020    /// `height` meters above sea level, and a line that misses it the
1021    /// nearest point of that sphere's horizon. Fails as
1022    /// [`screen_coordinate_to_lat_lng`].
1023    ///
1024    /// [`screen_coordinate_to_lat_lng`]: Self::screen_coordinate_to_lat_lng
1025    pub fn screen_coordinate_to_lat_lng_at(
1026        &self,
1027        point: &ScreenCoordinate,
1028        height: f64,
1029        wrap_mode: WrapMode,
1030    ) -> Result<LatLng, Error> {
1031        // Without a size the point is Mercator's, as the tile coordinate is.
1032        if self.is_globe() && !self.params.size.is_empty() {
1033            if point.x.is_nan() || point.y.is_nan() {
1034                return Err(Error::invalid_argument("screen coordinate must not be NaN"));
1035            }
1036            if !point.x.is_finite() || !point.y.is_finite() {
1037                return Err(Error::invalid_argument("screen coordinate must not be infinite"));
1038            }
1039            return VerticalPerspectiveProjection::screen_coordinate_to_lat_lng(self, point, height, wrap_mode)
1040                .ok_or_else(|| Error::invalid_argument("the camera shows no location"));
1041        }
1042        let coord = if self.params.size.is_empty() {
1043            self.screen_coordinate_to_tile_coordinate(point, 0)
1044        } else {
1045            self.mercator_screen_coordinate_to_tile_coordinate(point, 0, height)
1046        };
1047        Projection::unproject(&coord.p, 1.0 / TILE_SIZE_D, wrap_mode)
1048    }
1049
1050    /// The line of sight through `point`, measured from the bottom edge (y
1051    /// up), from the near plane to the far plane: each end's Web Mercator
1052    /// point at zoom 0 (x in the world copy the view shows it in) and its
1053    /// height in meters. `None` on the globe, while the view shows nothing,
1054    /// and for a point that isn't finite.
1055    #[must_use]
1056    pub fn line_of_sight(&self, point: &ScreenCoordinate) -> Option<(DVec3, DVec3)> {
1057        if self.is_globe() || self.matrices.projection == DMat4::ZERO {
1058            return None;
1059        }
1060        let flipped_y = f64::from(self.params.size.height) - point.y;
1061        // The matrices are OpenGL's: clip depth runs from -1 at the near plane
1062        // to 1 at the far plane.
1063        let inverted = self.matrices.inverted_from_center;
1064        let center = self.center_coordinate();
1065        let scale = self.params.scale;
1066        let world = |depth: f64| {
1067            let offset = inverted.project_point3(DVec3::new(point.x, flipped_y, depth));
1068            DVec3::new((center.x + offset.x) / scale, (center.y + offset.y) / scale, offset.z)
1069        };
1070        let (near, far) = (world(-1.0), world(1.0));
1071        (near.is_finite() && far.is_finite()).then_some((near, far))
1072    }
1073
1074    /// How much farther the bottom-left corner of the view is from the
1075    /// camera than the center, by which queries pad what they look for; 0
1076    /// while the size is empty.
1077    #[must_use]
1078    pub fn max_pitch_scale_factor(&self) -> f64 {
1079        if self.params.size.is_empty() {
1080            return 0.0;
1081        }
1082        // The globe pads queries with the Mercator factor, as GL JS does, from
1083        // the corner's unclamped Mercator position.
1084        let corner = self.mercator_screen_coordinate_to_tile_coordinate(
1085            &ScreenCoordinate::new(0.0, f64::from(self.params.size.height)),
1086            0,
1087            0.0,
1088        );
1089        // A point on the screen has a LatLng unless the view holds NaN.
1090        let Ok(lat_lng) = Projection::unproject(&corner.p, 1.0 / TILE_SIZE_D, WrapMode::Unwrapped) else {
1091            return 0.0;
1092        };
1093
1094        let scale = self.params.scale;
1095        let pt = if self.is_globe() {
1096            Point::new(corner.p.x * scale, corner.p.y * scale)
1097        } else {
1098            let pt = Projection::project(&lat_lng, scale);
1099            Point::new(pt.x / TILE_SIZE_D, pt.y / TILE_SIZE_D)
1100        };
1101        let top_point = self.matrices.coord * DVec4::new(pt.x, pt.y, 0.0, 1.0);
1102        top_point.w / self.camera_to_center_distance()
1103    }
1104}