Skip to main content

mln_map/
map_projection.rs

1// gtests-core: added for test/map/map.test.cpp (LatLngForPixelUnwrapped,
2// PixelForLatLngAfterZoomAroundAPointAcrossTheAntimeridian).
3
4use mln_map_types::{Camera, CameraOptions, MapView, TransformState};
5use mln_util::error::Error;
6use mln_util::geo::{LatLng, ScreenCoordinate, WrapMode};
7
8use crate::map::Map;
9use crate::transform::Transform;
10
11/// Converts coordinates for one camera and size, without a map. It holds only
12/// a transform state, so it can move to another thread.
13pub struct MapProjection {
14    state: TransformState,
15}
16
17const _: () = {
18    const fn sendable<T: Send>() {}
19    sendable::<MapProjection>();
20};
21
22impl MapProjection {
23    pub fn new(map: &Map) -> Self {
24        Self::from_state(map.get_transform_state())
25    }
26
27    pub(crate) fn from_state(state: TransformState) -> Self {
28        MapProjection { state }
29    }
30
31    /// A projection for one view of a map, from a [`MapSnapshot`] or a
32    /// rendered frame. `Err`: as [`MapView::to_state`].
33    ///
34    /// [`MapSnapshot`]: crate::MapSnapshot
35    pub fn from_view(view: &MapView) -> Result<Self, Error> {
36        Ok(Self::from_state(view.to_state()?))
37    }
38
39    /// The screen point of `lat_lng`, in the copy of the world nearest the
40    /// camera's center.
41    pub fn pixel_for_lat_lng(&self, lat_lng: &LatLng) -> ScreenCoordinate {
42        let mut point = self.state.lat_lng_to_screen_coordinate(&self.state.lat_lng_near_center(lat_lng));
43        point.y = f64::from(self.state.get_size().height) - point.y;
44        point
45    }
46
47    /// Whether the globe hides `lat_lng` from the camera; a Mercator view
48    /// hides nothing.
49    pub fn is_location_occluded(&self, lat_lng: &LatLng) -> bool {
50        self.state.is_location_occluded(lat_lng)
51    }
52
53    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a NaN or infinite
54    /// pixel.
55    pub fn lat_lng_for_pixel(&self, pixel: &ScreenCoordinate, wrap_mode: WrapMode) -> Result<LatLng, Error> {
56        let mut flipped = *pixel;
57        flipped.y = f64::from(self.state.get_size().height) - flipped.y;
58        self.state.screen_coordinate_to_lat_lng(&flipped, wrap_mode)
59    }
60
61    pub fn set_camera(&mut self, camera: &CameraOptions) {
62        let mut transform = self.transform();
63        transform.jump_to(camera);
64        self.state = transform.get_state().clone();
65    }
66
67    /// The camera, with its center in the copy of the world that it is in.
68    pub fn camera(&self) -> Camera {
69        self.state.camera()
70    }
71
72    /// A transform over a copy of the state, to move its camera as a map
73    /// would.
74    fn transform(&self) -> Transform {
75        Transform::from_state(self.state.clone())
76    }
77}