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::crs::WorldMapping;
5use mln_style::error::Error;
6use mln_style::geo::{LatLng, WrapMode};
7use mln_style::size::Size;
8use mln_style::types::ProjectionDefinition;
9
10use crate::camera::camera::CameraOptions;
11use crate::camera::camera_limits::{CameraLimits, MAX_FIELD_OF_VIEW, MIN_FIELD_OF_VIEW};
12use crate::camera::constants;
13use crate::camera::mode::ConstrainMode;
14use crate::camera::projection_mode::{AxonometricMode, ProjectionMode};
15use crate::camera::transform_state::TransformState;
16use crate::camera::view::{ViewParams, center_offset, zoom_scale};
17use crate::geo::{EdgeInsets, NorthOrientation};
18
19/// A camera with every member set: the camera that a map has, where
20/// [`CameraOptions`] is a change to one.
21#[derive(Clone, Copy, Debug, Default, PartialEq)]
22pub struct Camera {
23    /// The coordinate at the center. It keeps the copy of the world that the
24    /// camera is in, so its longitude can be outside -180 to 180.
25    pub center: LatLng,
26    /// The altitude of the center, in meters above sea level.
27    pub center_altitude: f64,
28    /// Insets from the map's edges. The camera centers within the rest.
29    pub padding: EdgeInsets,
30    pub zoom: f64,
31    /// The rotation from north, in degrees.
32    pub bearing: f64,
33    /// The tilt toward the horizon, in degrees. 0 looks straight down.
34    pub pitch: f64,
35    /// The roll, in degrees.
36    pub roll: f64,
37    /// The vertical field of view, in degrees.
38    pub fov: f64,
39}
40
41impl From<Camera> for CameraOptions {
42    /// Options that set every member of the camera, and no anchor.
43    fn from(camera: Camera) -> Self {
44        CameraOptions {
45            center: Some(camera.center),
46            center_altitude: Some(camera.center_altitude),
47            padding: Some(camera.padding),
48            anchor: None,
49            zoom: Some(camera.zoom),
50            bearing: Some(camera.bearing),
51            pitch: Some(camera.pitch),
52            roll: Some(camera.roll),
53            fov: Some(camera.fov),
54        }
55    }
56}
57
58/// A size in logical pixels, and the physical pixels in each logical pixel.
59#[derive(Clone, Copy, Debug, PartialEq)]
60pub struct LogicalExtent {
61    pub size: Size,
62    pub scale_factor: f64,
63}
64
65impl LogicalExtent {
66    #[must_use]
67    pub fn new(size: Size, scale_factor: f64) -> LogicalExtent {
68        LogicalExtent { size, scale_factor }
69    }
70
71    /// The size in physical pixels of a target with this extent: each
72    /// dimension times the scale factor, rounded to the nearest pixel, so a
73    /// dimension under half a pixel has none. `None` for an empty size, a
74    /// scale factor that isn't finite and positive, or a dimension too large
75    /// for `u32`.
76    ///
77    /// A host that fits its surface or view to the map's target sizes it by
78    /// this, so that the two agree to the pixel. Rounding keeps a product a
79    /// hair short of a whole number, as with a scale factor rounded to `f32`
80    /// (5/3 as 1.6666666), at that number.
81    #[must_use]
82    pub fn physical_size(&self) -> Option<Size> {
83        if self.size.is_empty() || !self.scale_factor.is_finite() || self.scale_factor <= 0.0 {
84            return None;
85        }
86        let physical = |logical: u32| {
87            let pixels = (f64::from(logical) * self.scale_factor).round();
88            (pixels <= f64::from(u32::MAX)).then_some(pixels as u32)
89        };
90        Some(Size::new(physical(self.size.width)?, physical(self.size.height)?))
91    }
92}
93
94/// How a map orients and constrains its view.
95#[derive(Clone, Copy, Debug, PartialEq)]
96pub struct Viewport {
97    pub north_orientation: NorthOrientation,
98    pub constrain_mode: ConstrainMode,
99    /// Insets that move the vanishing point off the center of the map.
100    pub frustum_offset: EdgeInsets,
101    /// Whether the center stands on the terrain, at its height under the
102    /// center, once that has loaded. The ground decides the altitude, so the
103    /// camera ignores the altitude it is given, such as the style's
104    /// `centerAltitude`: at rest the center stands on the ground, and a
105    /// command eases the altitude onto the ground where it leaves the center.
106    /// When this is off, every camera keeps the altitude it is given. Over
107    /// terrain, a command's eye stays above the ground either way. Without
108    /// terrain it changes nothing. On by default.
109    pub center_clamped_to_ground: bool,
110    /// Whether drags and zooms around a point on the globe turn the bearing,
111    /// so the planet keeps its orientation, and a drag can carry the camera
112    /// over a pole. Off by default: they keep the bearing, as they do on
113    /// Mercator. It changes nothing while the map draws Mercator.
114    pub globe_free_bearing: bool,
115}
116
117impl Default for Viewport {
118    fn default() -> Self {
119        Viewport {
120            north_orientation: NorthOrientation::default(),
121            constrain_mode: ConstrainMode::default(),
122            frustum_offset: EdgeInsets::default(),
123            center_clamped_to_ground: true,
124            globe_free_bearing: false,
125        }
126    }
127}
128
129/// What a view draws the map in: a built-in projection, or a registered one.
130#[derive(Clone, Debug, PartialEq)]
131pub enum ViewProjection {
132    /// Mercator, the globe, or the transition between them: the style's
133    /// projection at the camera's zoom. A view from a map never names
134    /// `globe`, which [`MapView::to_state`] resolves at the camera's zoom.
135    BuiltIn(ProjectionDefinition),
136    /// A registered projection, which draws flat, with how it maps lng/lat to
137    /// its world square ([`View::world`](crate::camera::View::world)).
138    Registered(WorldMapping),
139}
140
141impl ViewProjection {
142    /// How lng/lat maps to the world square that the view draws in:
143    /// Mercator's for a built-in projection.
144    #[must_use]
145    pub fn world(&self) -> &WorldMapping {
146        match self {
147            ViewProjection::BuiltIn(_) => &mln_style::crs::MERCATOR,
148            ViewProjection::Registered(world) => world,
149        }
150    }
151
152    /// 0 on a flat map, 1 on the globe, and in between during the
153    /// transition between them.
154    #[must_use]
155    pub(crate) fn transition(&self) -> f64 {
156        match self {
157            ViewProjection::BuiltIn(definition) => definition.transition_state(),
158            ViewProjection::Registered(_) => 0.0,
159        }
160    }
161}
162
163impl From<ProjectionDefinition> for ViewProjection {
164    fn from(definition: ProjectionDefinition) -> Self {
165        ViewProjection::BuiltIn(definition)
166    }
167}
168
169/// One view of a map: its camera, size, and projection.
170#[derive(Clone, Debug, PartialEq)]
171pub struct MapView {
172    pub camera: Camera,
173    pub extent: LogicalExtent,
174    /// Sets every member when it comes from a map. A member that a view leaves
175    /// unset takes the default of [`View`](crate::camera::View).
176    pub projection_mode: ProjectionMode,
177    pub viewport: Viewport,
178    /// What the view draws the map in.
179    pub projection: ViewProjection,
180}
181
182impl MapView {
183    /// A transform state that shows exactly this view, to convert coordinates
184    /// for it.
185    ///
186    /// The state takes the camera as it is: it keeps the center's copy of the
187    /// world, and has no bounds and the widest zoom and pitch limits, so no
188    /// constraint of the map that the view came from moves the camera.
189    ///
190    /// `Err` for a view that no transform can show: a camera member that isn't
191    /// finite, a center that the projection has no place for, a zoom, pitch or
192    /// field of view outside the limits of every map, a padding or frustum
193    /// offset below zero, an empty size, a scale factor that isn't positive,
194    /// or a skew that isn't finite.
195    pub fn to_state(&self) -> Result<TransformState, Error> {
196        self.validate()?;
197        let camera = &self.camera;
198        let viewport = &self.viewport;
199        let projection = match &self.projection {
200            ViewProjection::BuiltIn(definition) => ViewProjection::BuiltIn(definition.at_zoom(camera.zoom)),
201            registered @ ViewProjection::Registered(_) => registered.clone(),
202        };
203        let world = projection.world();
204        let scale = zoom_scale(camera.zoom);
205        let Some((x, y)) = center_offset(world, &camera.center, scale) else {
206            return Err(Error::invalid_argument(format!(
207                "the projection \"{}\" has no place for the view's center",
208                world.name()
209            )));
210        };
211        let params = ViewParams {
212            size: self.extent.size,
213            frustum_offset: viewport.frustum_offset,
214            north_orientation: viewport.north_orientation,
215            constrain_mode: viewport.constrain_mode,
216            center_clamped_to_ground: viewport.center_clamped_to_ground,
217            globe_free_bearing: viewport.globe_free_bearing,
218            projection,
219            padding: camera.padding,
220            x,
221            y,
222            center_altitude: camera.center_altitude,
223            scale,
224            angle: -mln_style::math::deg2rad(camera.bearing),
225            pitch: mln_style::math::deg2rad(camera.pitch),
226            roll: mln_style::math::deg2rad(camera.roll),
227            fov: mln_style::math::deg2rad(camera.fov),
228            x_skew: self.projection_mode.x_skew.unwrap_or(0.0),
229            y_skew: self.projection_mode.y_skew.unwrap_or(1.0),
230            axonometric: self.projection_mode.axonometric.is_some_and(AxonometricMode::as_bool),
231            center_wrap: WrapMode::Unwrapped,
232            terrain_min_elevation: None,
233        };
234        Ok(TransformState::from_parts(params, CameraLimits::widest()))
235    }
236
237    /// The view that this describes, to draw it or convert coordinates for
238    /// it. `Err`: as [`to_state`](Self::to_state).
239    #[cfg(test)]
240    pub(crate) fn to_view(&self) -> Result<crate::camera::view::View, Error> {
241        Ok(self.to_state()?.view().clone())
242    }
243
244    fn validate(&self) -> Result<(), Error> {
245        let camera = &self.camera;
246        let finite = [camera.center_altitude, camera.zoom, camera.bearing, camera.pitch, camera.roll, camera.fov];
247        if !finite.iter().all(|value| value.is_finite()) {
248            return Err(Error::invalid_argument("view camera members must be finite"));
249        }
250        let globe = match &self.projection {
251            ViewProjection::BuiltIn(definition) => {
252                if !definition.transition.is_finite() {
253                    return Err(Error::invalid_argument("view projection transition must be finite"));
254                }
255                definition.at_zoom(camera.zoom).transition_state() > 0.0
256            }
257            ViewProjection::Registered(_) => false,
258        };
259        let limits = TransformState::default();
260        // The globe lets the zoom fall below the minimum toward the poles.
261        let min_zoom = limits.min_zoom_at_latitude_with(camera.center.latitude(), globe);
262        if !(min_zoom..=constants::MAX_ZOOM).contains(&camera.zoom)
263            || !(mln_style::math::rad2deg(constants::PITCH_MIN)..=mln_style::math::rad2deg(constants::PITCH_MAX))
264                .contains(&camera.pitch)
265            || !(mln_style::math::rad2deg(MIN_FIELD_OF_VIEW)..=mln_style::math::rad2deg(MAX_FIELD_OF_VIEW))
266                .contains(&camera.fov)
267        {
268            return Err(Error::invalid_argument(
269                "view camera zoom, pitch and field of view must be within the limits of a map",
270            ));
271        }
272        if !valid_insets(&camera.padding) || !valid_insets(&self.viewport.frustum_offset) {
273            return Err(Error::invalid_argument("view padding and frustum offset must be finite and at least 0"));
274        }
275        let extent = &self.extent;
276        if extent.size.is_empty() || !extent.scale_factor.is_finite() || extent.scale_factor <= 0.0 {
277            return Err(Error::invalid_argument("view extent dimensions and scale factor must be positive"));
278        }
279        let mode = &self.projection_mode;
280        if !mode.x_skew.is_none_or(f64::is_finite) || !mode.y_skew.is_none_or(f64::is_finite) {
281            return Err(Error::invalid_argument("view projection skews must be finite"));
282        }
283        Ok(())
284    }
285}
286
287fn valid_insets(insets: &EdgeInsets) -> bool {
288    [insets.top, insets.left, insets.bottom, insets.right].iter().all(|value| value.is_finite() && *value >= 0.0)
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294
295    #[test]
296    fn physical_size_rounds_to_the_nearest_pixel() {
297        let physical =
298            |width, height, scale_factor| LogicalExtent::new(Size::new(width, height), scale_factor).physical_size();
299        // Browsers report 5/3 rounded to f32, at which 870 and 615 come a hair
300        // short of whole pixels.
301        let five_thirds = f64::from(5.0_f32 / 3.0);
302        assert_eq!(physical(870, 615, five_thirds), Some(Size::new(1450, 1025)));
303        assert_eq!(physical(871, 616, five_thirds), Some(Size::new(1452, 1027)));
304        assert_eq!(physical(410, 731, 2.625), Some(Size::new(1076, 1919)));
305        assert_eq!(physical(1, 3, 0.25), Some(Size::new(0, 1)));
306        assert_eq!(physical(u32::MAX, 1, 1.0), Some(Size::new(u32::MAX, 1)));
307        assert_eq!(physical(0x8000_0000, 1, 2.0), None);
308        assert_eq!(physical(0, 1, 1.0), None);
309        assert_eq!(physical(1, 1, f64::NAN), None);
310        assert_eq!(physical(1, 1, 0.0), None);
311    }
312}