Skip to main content

mln_engine/camera/
map_view.rs

1//! One view of a map: the camera, size and projection that a map snapshot or a
2//! rendered frame shows.
3
4use mln_style::error::Error;
5use mln_style::geo::{LatLng, WrapMode};
6use mln_style::size::Size;
7use mln_style::types::ProjectionDefinition;
8
9use crate::camera::camera::CameraOptions;
10use crate::camera::camera_limits::{CameraLimits, MAX_FIELD_OF_VIEW, MIN_FIELD_OF_VIEW};
11use crate::camera::constants;
12use crate::camera::mode::{ConstrainMode, ViewportMode};
13use crate::camera::projection_mode::{AxonometricMode, ProjectionMode};
14use crate::camera::transform_state::TransformState;
15use crate::camera::view::{ViewParams, map_offset, zoom_scale};
16use crate::geo::{EdgeInsets, NorthOrientation};
17
18/// A camera with every member set: the camera that a map has, where
19/// [`CameraOptions`] is a change to one.
20#[derive(Clone, Copy, Debug, Default, PartialEq)]
21pub struct Camera {
22    /// The coordinate at the center. It keeps the copy of the world that the
23    /// camera is in, so its longitude can be outside -180 to 180.
24    pub center: LatLng,
25    /// The altitude of the center, in meters above sea level.
26    pub center_altitude: f64,
27    /// Insets from the map's edges. The camera centers within the rest.
28    pub padding: EdgeInsets,
29    pub zoom: f64,
30    /// The rotation from north, in degrees.
31    pub bearing: f64,
32    /// The tilt toward the horizon, in degrees. 0 looks straight down.
33    pub pitch: f64,
34    /// The roll, in degrees.
35    pub roll: f64,
36    /// The vertical field of view, in degrees.
37    pub fov: f64,
38}
39
40impl From<Camera> for CameraOptions {
41    /// Options that set every member of the camera, and no anchor.
42    fn from(camera: Camera) -> Self {
43        CameraOptions {
44            center: Some(camera.center),
45            center_altitude: Some(camera.center_altitude),
46            padding: Some(camera.padding),
47            anchor: None,
48            zoom: Some(camera.zoom),
49            bearing: Some(camera.bearing),
50            pitch: Some(camera.pitch),
51            roll: Some(camera.roll),
52            fov: Some(camera.fov),
53        }
54    }
55}
56
57/// A size in logical pixels, and the physical pixels in each logical pixel.
58#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct LogicalExtent {
60    pub size: Size,
61    pub scale_factor: f64,
62}
63
64impl LogicalExtent {
65    #[must_use]
66    pub fn new(size: Size, scale_factor: f64) -> LogicalExtent {
67        LogicalExtent { size, scale_factor }
68    }
69}
70
71/// How a map orients and constrains its view.
72#[derive(Clone, Copy, Debug, PartialEq)]
73pub struct Viewport {
74    pub north_orientation: NorthOrientation,
75    pub constrain_mode: ConstrainMode,
76    pub viewport_mode: ViewportMode,
77    /// Insets that move the vanishing point off the center of the map.
78    pub frustum_offset: EdgeInsets,
79    /// Whether the center stands on the terrain, at its height under the
80    /// center, once that has loaded. The ground decides the altitude, so the
81    /// camera ignores the altitude it is given, such as the style's
82    /// `centerAltitude`: at rest the center stands on the ground, and a
83    /// command eases the altitude onto the ground where it leaves the center.
84    /// When this is off, every camera keeps the altitude it is given. Over
85    /// terrain, a command's eye stays above the ground either way. Without
86    /// terrain it changes nothing. On by default.
87    pub center_clamped_to_ground: bool,
88    /// Whether drags and zooms around a point on the globe turn the bearing,
89    /// so the planet keeps its orientation, and a drag can carry the camera
90    /// over a pole. Off by default: they keep the bearing, as MapLibre GL JS
91    /// does. It changes nothing while the map draws Mercator.
92    pub globe_free_bearing: bool,
93}
94
95impl Default for Viewport {
96    fn default() -> Self {
97        Viewport {
98            north_orientation: NorthOrientation::default(),
99            constrain_mode: ConstrainMode::default(),
100            viewport_mode: ViewportMode::default(),
101            frustum_offset: EdgeInsets::default(),
102            center_clamped_to_ground: true,
103            globe_free_bearing: false,
104        }
105    }
106}
107
108/// One view of a map: its camera, size, and projection.
109#[derive(Clone, Copy, Debug, PartialEq)]
110pub struct MapView {
111    pub camera: Camera,
112    pub extent: LogicalExtent,
113    /// Sets every member when it comes from a map. A member that a view leaves
114    /// unset takes the default of [`View`](crate::camera::View).
115    pub projection_mode: ProjectionMode,
116    pub viewport: Viewport,
117    /// The style's projection at the camera's zoom. A view from a map never
118    /// names `globe`, which [`to_state`](Self::to_state) resolves at the
119    /// camera's zoom.
120    pub projection: ProjectionDefinition,
121}
122
123impl MapView {
124    /// A transform state that shows exactly this view, to convert coordinates
125    /// for it.
126    ///
127    /// The state takes the camera as it is: it keeps the center's copy of the
128    /// world, and has no bounds and the widest zoom and pitch limits, so no
129    /// constraint of the map that the view came from moves the camera.
130    ///
131    /// `Err` for a view that no transform can show: a camera member that isn't
132    /// finite, a zoom, pitch or field of view outside the limits of every map,
133    /// a padding or frustum offset below zero, an empty size, a scale factor
134    /// that isn't positive, or a skew that isn't finite.
135    pub fn to_state(&self) -> Result<TransformState, Error> {
136        self.validate()?;
137        let camera = &self.camera;
138        let viewport = &self.viewport;
139        let projection = self.projection.at_zoom(camera.zoom);
140        let projection_transition = projection.transition_state();
141        let scale = zoom_scale(camera.zoom);
142        let (x, y) = map_offset(&camera.center, scale, projection_transition > 0.0);
143        let params = ViewParams {
144            size: self.extent.size,
145            frustum_offset: viewport.frustum_offset,
146            north_orientation: viewport.north_orientation,
147            viewport_mode: viewport.viewport_mode,
148            constrain_mode: viewport.constrain_mode,
149            center_clamped_to_ground: viewport.center_clamped_to_ground,
150            globe_free_bearing: viewport.globe_free_bearing,
151            projection_definition: projection,
152            projection_transition,
153            padding: camera.padding,
154            x,
155            y,
156            center_altitude: camera.center_altitude,
157            scale,
158            angle: -mln_style::math::deg2rad(camera.bearing),
159            pitch: mln_style::math::deg2rad(camera.pitch),
160            roll: mln_style::math::deg2rad(camera.roll),
161            fov: mln_style::math::deg2rad(camera.fov),
162            x_skew: self.projection_mode.x_skew.unwrap_or(0.0),
163            y_skew: self.projection_mode.y_skew.unwrap_or(1.0),
164            axonometric: self.projection_mode.axonometric.is_some_and(AxonometricMode::as_bool),
165            center_wrap: WrapMode::Unwrapped,
166            terrain_min_elevation: None,
167        };
168        Ok(TransformState::from_parts(params, CameraLimits::widest()))
169    }
170
171    /// The view that this describes, to draw it or convert coordinates for
172    /// it. `Err`: as [`to_state`](Self::to_state).
173    #[cfg(test)]
174    pub(crate) fn to_view(self) -> Result<crate::camera::view::View, Error> {
175        Ok(self.to_state()?.view().clone())
176    }
177
178    fn validate(&self) -> Result<(), Error> {
179        let camera = &self.camera;
180        let finite = [camera.center_altitude, camera.zoom, camera.bearing, camera.pitch, camera.roll, camera.fov];
181        if !finite.iter().all(|value| value.is_finite()) {
182            return Err(Error::invalid_argument("view camera members must be finite"));
183        }
184        let projection = &self.projection;
185        if !projection.transition.is_finite() {
186            return Err(Error::invalid_argument("view projection transition must be finite"));
187        }
188        let limits = TransformState::default();
189        // The globe lets the zoom fall below the minimum toward the poles.
190        let globe = projection.at_zoom(camera.zoom).transition_state() > 0.0;
191        let min_zoom = limits.min_zoom_at_latitude_with(camera.center.latitude(), globe);
192        if !(min_zoom..=constants::MAX_ZOOM).contains(&camera.zoom)
193            || !(mln_style::math::rad2deg(constants::PITCH_MIN)..=mln_style::math::rad2deg(constants::PITCH_MAX))
194                .contains(&camera.pitch)
195            || !(mln_style::math::rad2deg(MIN_FIELD_OF_VIEW)..=mln_style::math::rad2deg(MAX_FIELD_OF_VIEW))
196                .contains(&camera.fov)
197        {
198            return Err(Error::invalid_argument(
199                "view camera zoom, pitch and field of view must be within the limits of a map",
200            ));
201        }
202        if !valid_insets(&camera.padding) || !valid_insets(&self.viewport.frustum_offset) {
203            return Err(Error::invalid_argument("view padding and frustum offset must be finite and at least 0"));
204        }
205        let extent = &self.extent;
206        if extent.size.is_empty() || !extent.scale_factor.is_finite() || extent.scale_factor <= 0.0 {
207            return Err(Error::invalid_argument("view extent dimensions and scale factor must be positive"));
208        }
209        let mode = &self.projection_mode;
210        if !mode.x_skew.is_none_or(f64::is_finite) || !mode.y_skew.is_none_or(f64::is_finite) {
211            return Err(Error::invalid_argument("view projection skews must be finite"));
212        }
213        Ok(())
214    }
215}
216
217fn valid_insets(insets: &EdgeInsets) -> bool {
218    [insets.top, insets.left, insets.bottom, insets.right].iter().all(|value| value.is_finite() && *value >= 0.0)
219}