Skip to main content

mln_engine/camera/
map_projection.rs

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