Skip to main content

mln_map/
map_projection.rs

1// gtests-core: added for test/map/map.test.cpp (LatLngForPixelUnwrapped,
2// PixelForLatLngAfterZoomAroundAPointAcrossTheAntimeridian).
3
4use std::sync::Arc;
5
6use mln_map_types::{Camera, CameraOptions, Elevation, MapView, TransformState, View};
7use mln_util::error::Error;
8use mln_util::geo::{LatLng, ScreenCoordinate, WrapMode};
9
10use crate::map::Map;
11use crate::transform::{TerrainGround, Transform, flip_y, lowest_ground};
12
13/// Converts coordinates for one camera and size, without a map: on the
14/// ground a renderer drew of a terrain ([`with_ground`](Self::with_ground)),
15/// or else on the flat map. It holds only a transform state and the ground,
16/// so it can move to another thread.
17pub struct MapProjection {
18    state: TransformState,
19    ground: Option<Arc<dyn Elevation>>,
20}
21
22const _: () = {
23    const fn sendable<T: Send>() {}
24    sendable::<MapProjection>();
25};
26
27impl MapProjection {
28    /// A projection for the map's camera, on the ground it draws
29    /// ([`Map::ground`]), as the map converts.
30    #[must_use]
31    pub fn new(map: &Map) -> Self {
32        Self::from_state(map.transform_state().clone()).with_ground(map.ground())
33    }
34
35    pub(crate) fn from_state(state: TransformState) -> Self {
36        MapProjection { state, ground: None }
37    }
38
39    /// A projection for one view of a map, from a [`MapSnapshot`] or a
40    /// rendered frame, on the flat map. `Err`: as [`MapView::to_state`].
41    ///
42    /// [`MapSnapshot`]: crate::MapSnapshot
43    pub fn from_view(view: &MapView) -> Result<Self, Error> {
44        Ok(Self::from_state(view.to_state()?))
45    }
46
47    /// The projection on `ground`, the ground a renderer drew of a terrain
48    /// ([`Map::ground`]), or on the flat map for `None`. The view's near and
49    /// far planes fit that ground as the map's do, which the line of sight
50    /// to the ground lies between.
51    #[must_use]
52    pub fn with_ground(mut self, ground: Option<Arc<dyn Elevation>>) -> Self {
53        self.ground = ground;
54        self.fit_planes();
55        self
56    }
57
58    /// Fits the view's near and far planes to the ground under the center,
59    /// or to the flat map without ground.
60    fn fit_planes(&mut self) {
61        let lowest = self.ground.as_deref().map(|ground| lowest_ground(self.state.view(), ground));
62        if lowest != self.state.view().terrain_min_elevation() {
63            self.state.set_terrain_min_elevation(lowest);
64        }
65    }
66
67    /// The screen point of `lat_lng`, in the copy of the world nearest the
68    /// camera's center: standing on the projection's ground, or at sea
69    /// level on the flat map ([`Map::pixel_for_lat_lng`]).
70    #[must_use]
71    pub fn pixel_for_lat_lng(&self, lat_lng: &LatLng) -> ScreenCoordinate {
72        pixel_for_lat_lng(self.state.view(), self.ground.as_deref(), lat_lng)
73    }
74
75    /// The height the projection's ground was drawn at, at `lat_lng`, in
76    /// meters with the terrain's exaggeration
77    /// ([`View::drawn_height_at`](mln_map_types::View::drawn_height_at)).
78    /// `None` on the flat map, and where no ground was drawn.
79    #[must_use]
80    pub fn elevation(&self, lat_lng: &LatLng) -> Option<f64> {
81        self.state.view().drawn_height_at(lat_lng, &**self.ground.as_ref()?)
82    }
83
84    /// Whether the globe hides `lat_lng` from the camera; a Mercator view
85    /// hides nothing.
86    #[must_use]
87    pub fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
88        self.state.view().is_location_occluded(lat_lng)
89    }
90
91    /// The location under `pixel`: on the projection's ground, or on the
92    /// flat map ([`Map::lat_lng_for_pixel`]). Fails with
93    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN or
94    /// infinite pixel.
95    pub fn lat_lng_for_pixel(&self, pixel: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
96        lat_lng_for_pixel(self.state.view(), self.ground.as_deref(), pixel, wrap_mode)
97    }
98
99    /// Moves the camera as a map's [`jump_to`](Map::jump_to) would, without
100    /// its constraints. On the projection's ground, as on the map's, a move
101    /// around an anchor holds the ground under it, and the eye stays above
102    /// the ground; the center keeps the altitude it is given. The ground
103    /// stays: where the camera now sees ground it doesn't hold, it converts
104    /// as where the line of sight meets none.
105    pub fn set_camera(&mut self, camera: &CameraOptions) {
106        let mut transform = self.transform();
107        let terrain = self.ground.clone().map(|ground| TerrainGround { elevation: Some(ground), clamped: false });
108        transform.set_terrain(terrain);
109        transform.jump_to(camera);
110        self.state = transform.state().clone();
111        self.fit_planes();
112    }
113
114    /// The camera, with its center in the copy of the world that it is in.
115    #[must_use]
116    pub fn camera(&self) -> Camera {
117        self.state.view().camera()
118    }
119
120    /// A transform over a copy of the state, to move its camera as a map
121    /// would.
122    fn transform(&self) -> Transform {
123        Transform::from_state(self.state.clone())
124    }
125}
126
127/// The screen point (y down) of `lat_lng` in `view`, in the copy of the world
128/// nearest its center: standing on `ground`, the ground a renderer drew of a
129/// terrain ([`View::lat_lng_to_screen_coordinate_on`]), or at sea level
130/// without one.
131pub(crate) fn pixel_for_lat_lng(view: &View, ground: Option<&dyn Elevation>, lat_lng: &LatLng) -> ScreenCoordinate {
132    let lat_lng = view.lat_lng_near_center(lat_lng);
133    let point = match ground {
134        Some(ground) => view.lat_lng_to_screen_coordinate_on(&lat_lng, ground),
135        None => view.lat_lng_to_screen_coordinate(&lat_lng),
136    };
137    flip_y(view, &point)
138}
139
140/// The location under `pixel` (y down) in `view`: on `ground`
141/// ([`View::screen_coordinate_to_lat_lng_on`]), or at sea level without one.
142/// Fails as [`View::screen_coordinate_to_lat_lng`].
143pub(crate) fn lat_lng_for_pixel(
144    view: &View,
145    ground: Option<&dyn Elevation>,
146    pixel: &ScreenCoordinate,
147    wrap_mode: WrapMode,
148) -> Result<LatLng, Error> {
149    let point = flip_y(view, pixel);
150    match ground {
151        Some(ground) => view.screen_coordinate_to_lat_lng_on(&point, ground, wrap_mode),
152        None => view.screen_coordinate_to_lat_lng(&point, wrap_mode),
153    }
154}