mln_style/crs/world.rs
1//! The world square a map draws in, which tile 0/0/0 covers and the quad tree
2//! of tiles subdivides, and how lng/lat maps to and from it: Web Mercator, or
3//! the coordinate reference system of a registered projection.
4
5use std::f64::consts::PI;
6use std::sync::Arc;
7
8use geometry::Point;
9use mln_wire::Wire;
10
11use super::mapping::{BoxSamples, CrsMapping, WorldBox};
12use super::{Crs, NO_ANSWER, TileMatrixSet, is_answer};
13use crate::constants::{DEGREES_MAX, EARTH_RADIUS_M, LATITUDE_MAX, TILE_SIZE_D};
14use crate::error::Error;
15use crate::geo::{LatLng, LatLngBounds, WrapMode};
16use crate::math::{clamp_f64, deg2rad, rad2deg};
17
18/// How a map's lng/lat maps to and from its world square, where tile 0/0/0
19/// spans 0 to 1 on both axes and y grows down: Web Mercator's, the default,
20/// or a registered projection's.
21///
22/// Each mapping converts positions in batches its own way, and has its own
23/// properties: whether its world wraps, the latitudes it keeps, its tile
24/// matrix set, and the scales of its ground and its heights. Everything else
25/// is the same for every mapping. Two mappings are equal when they are the
26/// same one: Mercator, or the same registered projection's.
27#[derive(Clone, Debug, Default, PartialEq, Eq)]
28pub struct WorldMapping(Plane);
29
30/// The plane that a [`WorldMapping`] maps lng/lat to.
31#[derive(Clone, Debug, Default)]
32enum Plane {
33 /// Web Mercator, whose world repeats east and west.
34 #[default]
35 Mercator,
36 /// A registered projection's coordinate reference system: a bounded
37 /// plane, with no world copies and no wrapping.
38 Crs(Arc<CrsMapping>),
39}
40
41impl PartialEq for Plane {
42 fn eq(&self, other: &Self) -> bool {
43 match (self, other) {
44 (Plane::Mercator, Plane::Mercator) => true,
45 (Plane::Crs(a), Plane::Crs(b)) => Arc::ptr_eq(a, b),
46 _ => false,
47 }
48 }
49}
50
51impl Eq for Plane {}
52
53/// Web Mercator's mapping, the default, for code that needs a reference to
54/// it.
55pub static MERCATOR: WorldMapping = WorldMapping(Plane::Mercator);
56
57impl WorldMapping {
58 /// A mapping of the registered projection `crs`, equal only to its
59 /// clones. A registry makes one for each of its projections, which every
60 /// map drawn in it shares.
61 #[must_use]
62 pub fn new(crs: Arc<Crs>) -> WorldMapping {
63 WorldMapping(Plane::Crs(Arc::new(CrsMapping::new(crs))))
64 }
65
66 /// `mercator`, or the registered projection's name.
67 #[must_use]
68 pub fn name(&self) -> &str {
69 match &self.0 {
70 Plane::Mercator => "mercator",
71 Plane::Crs(mapping) => &mapping.crs().name,
72 }
73 }
74
75 /// Whether the world repeats east and west, with world copies and
76 /// longitude wrapping.
77 #[must_use]
78 pub fn wraps(&self) -> bool {
79 matches!(self.0, Plane::Mercator)
80 }
81
82 /// The latitudes, south and north, that the world keeps: Mercator's
83 /// limit, past which it puts every location on the square's edge, or a
84 /// registered projection's range, from the center of its tile matrix
85 /// set toward each pole up to where the projection stretches distances
86 /// along the meridian ten times as much as at the center, found once,
87 /// when first asked for.
88 #[must_use]
89 pub fn latitude_range(&self) -> [f64; 2] {
90 match &self.0 {
91 Plane::Mercator => [-LATITUDE_MAX, LATITUDE_MAX],
92 Plane::Crs(mapping) => mapping.latitude_range(),
93 }
94 }
95
96 /// `lat_lng` in the world copy that longitudes from -180 to 180 cover,
97 /// where the world wraps; unchanged where it doesn't.
98 #[must_use]
99 pub fn wrap(&self, lat_lng: LatLng) -> LatLng {
100 if self.wraps() { lat_lng.wrapped() } else { lat_lng }
101 }
102
103 /// The tile grid whose tile 0/0/0 is the world square:
104 /// [`TileMatrixSet::WEB_MERCATOR`] on Mercator.
105 #[must_use]
106 pub fn tile_matrix_set(&self) -> TileMatrixSet {
107 match &self.0 {
108 Plane::Mercator => TileMatrixSet::WEB_MERCATOR,
109 Plane::Crs(mapping) => mapping.crs().tile_matrix_set,
110 }
111 }
112
113 /// Each lng/lat in degrees of `lng_lats` to its place in the world
114 /// square, into `world`, which is as long: NaN where the projection has
115 /// none. Mercator puts a latitude past its limit on the square's edge, as
116 /// [`project`](Self::project) does and
117 /// [`project_from_center`](Self::project_from_center) and
118 /// [`places_from_lng_lats`](Self::places_from_lng_lats) don't.
119 pub fn world_from_lng_lats(&self, lng_lats: &[[f64; 2]], world: &mut [[f64; 2]]) {
120 match &self.0 {
121 Plane::Mercator => mercator_places(lng_lats, world, mercator_latitude),
122 Plane::Crs(mapping) => mapping.world_from_lng_lats(lng_lats, world),
123 }
124 }
125
126 /// Each lng/lat in degrees of `lng_lats` to its place on the plane of the
127 /// world square, into `places`, which is as long, as
128 /// [`world_from_lng_lats`](Self::world_from_lng_lats) does, but on
129 /// Mercator past its latitude limit too, outside the square, where the
130 /// buffers of its edge tiles reach.
131 pub fn places_from_lng_lats(&self, lng_lats: &[[f64; 2]], places: &mut [[f64; 2]]) {
132 match &self.0 {
133 Plane::Mercator => mercator_places(lng_lats, places, |latitude| latitude),
134 Plane::Crs(mapping) => mapping.world_from_lng_lats(lng_lats, places),
135 }
136 }
137
138 /// Each place in the world square of `world` to lng/lat in degrees, into
139 /// `lng_lats`, which is as long, with the latitude within 90 degrees of
140 /// the equator. A registered projection's place that has no answer of its
141 /// own takes the nearest one inside the world square, or else the last
142 /// one with an answer on the line to the square's center, or else the
143 /// converter's own finite answer there, as GL JS's
144 /// [`CRSWorldCoordinateHelper.lngLatFromWorld`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/projection/crs.ts#L112-L120)
145 /// does; NaN where there is none of these.
146 pub fn lng_lats_from_world(&self, world: &[[f64; 2]], lng_lats: &mut [[f64; 2]]) {
147 match &self.0 {
148 Plane::Mercator => {
149 for (lng_lat, point) in lng_lats.iter_mut().zip(world) {
150 let answer = mercator_lng_lat(*point);
151 *lng_lat = if is_answer(&answer) { answer } else { NO_ANSWER };
152 }
153 }
154 Plane::Crs(mapping) => mapping.lng_lats_from_world(world, lng_lats),
155 }
156 }
157
158 /// The place of `lat_lng` in the world square, NaN where the projection
159 /// has none.
160 #[must_use]
161 pub fn world_from_lat_lng(&self, lat_lng: &LatLng) -> Point<f64> {
162 let mut world = [[0.0; 2]];
163 self.world_from_lng_lats(&[[lat_lng.longitude(), lat_lng.latitude()]], &mut world);
164 Point::new(world[0][0], world[0][1])
165 }
166
167 /// The location of a place in the world square, as
168 /// [`lng_lats_from_world`](Self::lng_lats_from_world) finds it. Fails
169 /// with [`ErrorKind::InvalidArgument`](crate::error::ErrorKind) where it
170 /// finds none.
171 pub fn lat_lng_from_world(&self, world: &Point<f64>) -> Result<LatLng, Error> {
172 let mut lng_lat = [[0.0; 2]];
173 self.lng_lats_from_world(&[[world.x, world.y]], &mut lng_lat);
174 if !is_answer(&lng_lat[0]) {
175 return Err(Error::invalid_argument(format!(
176 "the projection \"{}\" has no location at the world position {}, {}",
177 self.name(),
178 world.x,
179 world.y
180 )));
181 }
182 LatLng::with_mode(lng_lat[0][1], lng_lat[0][0], WrapMode::Unwrapped)
183 }
184
185 /// The point of `lat_lng` in a world `scale` times the tile size wide, a
186 /// latitude past Mercator's limit on the square's edge.
187 #[must_use]
188 pub fn project(&self, lat_lng: &LatLng, scale: f64) -> Point<f64> {
189 let world_size = scale * TILE_SIZE_D;
190 let world = self.world_from_lat_lng(lat_lng);
191 Point::new(world.x * world_size, world.y * world_size)
192 }
193
194 /// The location of a point in a world `scale` times the tile size wide,
195 /// in the world copy that `wrap_mode` asks for where the world wraps.
196 /// Fails as [`lat_lng_from_world`](Self::lat_lng_from_world) does.
197 pub fn unproject(&self, point: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Result<LatLng, Error> {
198 let world_size = scale * TILE_SIZE_D;
199 let lat_lng = self.lat_lng_from_world(&Point::new(point.x / world_size, point.y / world_size))?;
200 Ok(if wrap_mode == WrapMode::Wrapped { self.wrap(lat_lng) } else { lat_lng })
201 }
202
203 /// The place of `lat_lng` in a world `scale` times the tile size wide,
204 /// measured from the world square's center, with y down, where a
205 /// camera keeps its center: measured from the center, a location near it
206 /// keeps the precision that the offset of the square's corner would
207 /// round away. On Mercator it goes past the latitude limit too, as the
208 /// globe's center and an unconstrained one do, up to a finite distance
209 /// past the square's edge at the poles. NaN where the projection has no
210 /// place for it.
211 #[must_use]
212 pub fn project_from_center(&self, lat_lng: &LatLng, scale: f64) -> Point<f64> {
213 let world_size = scale * TILE_SIZE_D;
214 if let Plane::Mercator = self.0 {
215 return Point::new(
216 lat_lng.longitude() / DEGREES_MAX * world_size,
217 -mercator_north(lat_lng.latitude()) / (PI * 2.0) * world_size,
218 );
219 }
220 let place = self.world_from_lat_lng(lat_lng);
221 Point::new((place.x - 0.5) * world_size, (place.y - 0.5) * world_size)
222 }
223
224 /// The location of a place in a world `scale` times the tile size wide,
225 /// measured from the world square's center, as
226 /// [`project_from_center`](Self::project_from_center) measures it, in the
227 /// world copy that `wrap_mode` asks for where the world wraps. A place of
228 /// a registered projection without a location of its own takes the one
229 /// that [`lng_lats_from_world`](Self::lng_lats_from_world) falls back on,
230 /// and a coordinate that is NaN where there is none is
231 /// [`LatLng::saturating`]'s.
232 #[must_use]
233 pub fn unproject_from_center(&self, point: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> LatLng {
234 let world_size = scale * TILE_SIZE_D;
235 if let Plane::Mercator = self.0 {
236 let longitude = point.x / world_size * DEGREES_MAX;
237 let latitude = mercator_latitude_at(-point.y / world_size * (PI * 2.0));
238 return LatLng::saturating(latitude, longitude, wrap_mode);
239 }
240 let mut lng_lat = [[0.0; 2]];
241 self.lng_lats_from_world(&[[0.5 + point.x / world_size, 0.5 + point.y / world_size]], &mut lng_lat);
242 LatLng::saturating(lng_lat[0][1], lng_lat[0][0], WrapMode::Unwrapped)
243 }
244
245 /// Whether a place in the world square has a location of its own,
246 /// rather than the nearest one that
247 /// [`lng_lats_from_world`](Self::lng_lats_from_world) falls back on:
248 /// always on Mercator.
249 #[must_use]
250 pub fn has_lat_lng(&self, world: &Point<f64>) -> bool {
251 match &self.0 {
252 Plane::Mercator => true,
253 Plane::Crs(mapping) => mapping.has_lat_lng([world.x, world.y]),
254 }
255 }
256
257 /// How many meters of height a world unit stands for at `lat_lng`, the
258 /// scale that the map draws heights at there, such as terrain,
259 /// extrusions and the camera's altitude: on Mercator, the ground meters
260 /// a world unit spans at its latitude, so that heights match the ground;
261 /// in a registered projection, the extent of its tile matrix set, its
262 /// units taken as meters, anywhere.
263 #[must_use]
264 pub fn height_meters_per_world_unit(&self, lat_lng: &LatLng) -> f64 {
265 match &self.0 {
266 Plane::Mercator => mercator_meters_per_world_unit(lat_lng.latitude()),
267 Plane::Crs(mapping) => mapping.crs().tile_matrix_set.extent_at_zoom0,
268 }
269 }
270
271 /// How many meters on the ground a world unit spans at the lng/lat
272 /// `lng_lat`, in degrees, along `step`, a short step in the world square
273 /// from its place: on Mercator, the scale at its latitude, the same in
274 /// every direction; in a registered projection, whose scale can change
275 /// with the direction, the ground distance from `lng_lat` to the location
276 /// at the step's end, on the sphere of GL JS's
277 /// [`LngLat.distanceTo`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/lng_lat.ts#L133-L140),
278 /// over the step's length. NaN where the projection has no place for
279 /// `lng_lat`.
280 #[must_use]
281 pub fn ground_meters_per_world_unit(&self, lng_lat: [f64; 2], step: [f64; 2]) -> f64 {
282 let Plane::Crs(mapping) = &self.0 else {
283 return mercator_meters_per_world_unit(lng_lat[1]);
284 };
285 let mut place = [[0.0; 2]];
286 mapping.world_from_lng_lats(&[lng_lat], &mut place);
287 let mut end = [[0.0; 2]];
288 mapping.lng_lats_from_world(&[[place[0][0] + step[0], place[0][1] + step[1]]], &mut end);
289 ground_distance(lng_lat, end[0]) / step[0].hypot(step[1])
290 }
291
292 /// The places in the world square of a lng/lat box sampled on a grid,
293 /// 17 points on a side with its edges and corners, and how far its edges
294 /// stray from the lines between neighboring samples, which a shape that
295 /// holds the samples grows by to hold the box. Corners alone miss most of
296 /// a box whose edges curve, as a parallel does around a pole, and the
297 /// inside of the box matters where a projection runs off to infinity.
298 #[must_use]
299 pub fn lng_lat_box_samples(&self, bounds: &LatLngBounds) -> BoxSamples {
300 BoxSamples::new(bounds, |lng_lats, world| self.world_from_lng_lats(lng_lats, world))
301 }
302
303 /// The rectangle in the world square around a lng/lat box, as
304 /// [`BoxSamples::world_box`] finds it from the box's samples.
305 #[must_use]
306 pub fn lng_lat_box_to_world_box(&self, bounds: &LatLngBounds) -> WorldBox {
307 self.lng_lat_box_samples(bounds).world_box()
308 }
309}
310
311/// A mapping crosses as the name of its registered projection, or none for
312/// Mercator's, and the reading side takes the mapping that the
313/// [`StyleRegistry`](crate::StyleRegistry) in its context has by that name.
314impl Wire for WorldMapping {
315 fn write(&self, w: &mut mln_wire::Writer) {
316 match &self.0 {
317 Plane::Mercator => false.write(w),
318 Plane::Crs(mapping) => {
319 true.write(w);
320 mln_wire::write_str(w, &mapping.crs().name);
321 }
322 }
323 }
324
325 fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
326 if !bool::read(r)? {
327 return Some(WorldMapping::default());
328 }
329 let name = mln_wire::read_str(r)?;
330 let world = match r.context::<crate::StyleRegistry>() {
331 None => Err("a projection without a registry to resolve it against"),
332 Some(registry) => registry.projection(name).cloned().ok_or("unknown projection"),
333 };
334 match world {
335 Ok(world) => Some(world),
336 Err(message) => r.fail(message),
337 }
338 }
339}
340
341/// The earth's mean radius in meters, GL JS's
342/// [`earthRadius`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/lng_lat.ts#L8),
343/// on which its `LngLat.distanceTo` measures.
344const MEAN_EARTH_RADIUS_M: f64 = 6_371_008.8;
345
346/// The ground distance in meters between two lng/lats in degrees, on the
347/// sphere of GL JS's
348/// [`LngLat.distanceTo`](https://github.com/maplibre/maplibre-gl-js/blob/8a0091c64a25265a5c3883aeedcea96687c00d52/src/geo/lng_lat.ts#L133-L140):
349/// by the haversine formula, which keeps the centimeters across a few pixels
350/// at the highest zooms, where the spherical law of cosines of
351/// `distanceTo` rounds them to nothing.
352fn ground_distance([lng_a, lat_a]: [f64; 2], [lng_b, lat_b]: [f64; 2]) -> f64 {
353 let (lat_a, lat_b) = (lat_a.to_radians(), lat_b.to_radians());
354 let (half_latitude, half_longitude) = ((lat_b - lat_a) / 2.0, (lng_b - lng_a).to_radians() / 2.0);
355 let haversine = half_latitude.sin().powi(2) + lat_a.cos() * lat_b.cos() * half_longitude.sin().powi(2);
356 let chord = haversine.sqrt();
357 // Rounding can take it past 1; a NaN stays NaN.
358 2.0 * MEAN_EARTH_RADIUS_M * (if chord > 1.0 { 1.0 } else { chord }).asin()
359}
360
361/// `latitude` within Web Mercator's limit, past which Mercator puts every
362/// location on the world square's edge.
363fn mercator_latitude(latitude: f64) -> f64 {
364 clamp_f64(latitude, -LATITUDE_MAX, LATITUDE_MAX)
365}
366
367/// How many meters on the ground a world unit of Web Mercator spans at
368/// `latitude`, kept within Mercator's limit: the length of the parallel.
369fn mercator_meters_per_world_unit(latitude: f64) -> f64 {
370 deg2rad(mercator_latitude(latitude)).cos() * (PI * 2.0) * EARTH_RADIUS_M
371}
372
373/// How far north of the equator Web Mercator puts `latitude`, in degrees,
374/// in a world 2π wide: asinh(tan φ), which is ln(tan(π/4 + φ/2)) and stays
375/// finite at the poles.
376fn mercator_north(latitude: f64) -> f64 {
377 deg2rad(latitude).tan().asinh()
378}
379
380/// The latitude in degrees that Web Mercator puts `north` of the equator, in
381/// a world 2π wide: the inverse of [`mercator_north`].
382fn mercator_latitude_at(north: f64) -> f64 {
383 rad2deg(north.sinh().atan())
384}
385
386/// Web Mercator's places of `lng_lats`, in degrees, into `places`, each
387/// latitude through `latitude` first: NaN where a lng/lat isn't finite.
388fn mercator_places(lng_lats: &[[f64; 2]], places: &mut [[f64; 2]], latitude: impl Fn(f64) -> f64) {
389 for (place, &[lng, lat]) in places.iter_mut().zip(lng_lats) {
390 *place = if is_answer(&[lng, lat]) { mercator_point([lng, latitude(lat)]) } else { NO_ANSWER };
391 }
392}
393
394/// Web Mercator's place in the world square of a lng/lat in degrees.
395fn mercator_point([longitude, latitude]: [f64; 2]) -> [f64; 2] {
396 [0.5 + longitude / DEGREES_MAX, 0.5 - mercator_north(latitude) / (PI * 2.0)]
397}
398
399/// The lng/lat in degrees of a place in Web Mercator's world square, the
400/// inverse of [`mercator_point`], NaN or infinite where the place is.
401fn mercator_lng_lat([x, y]: [f64; 2]) -> [f64; 2] {
402 [(x - 0.5) * DEGREES_MAX, mercator_latitude_at((0.5 - y) * (PI * 2.0))]
403}