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 mln_wire::Wire;
9
10use super::mapping::{BoxSamples, CrsMapping, WorldBox};
11use super::{Crs, NO_ANSWER, TileMatrixSet, is_answer};
12use crate::constants::{DEGREES_MAX, EARTH_RADIUS_M, LATITUDE_MAX, TILE_SIZE_D};
13use crate::error::Error;
14use crate::geo::{LatLng, LatLngBounds, WrapMode};
15use crate::geometry::Point;
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; NaN where there is none of
144 /// these.
145 pub fn lng_lats_from_world(&self, world: &[[f64; 2]], lng_lats: &mut [[f64; 2]]) {
146 match &self.0 {
147 Plane::Mercator => {
148 for (lng_lat, point) in lng_lats.iter_mut().zip(world) {
149 let answer = mercator_lng_lat(*point);
150 *lng_lat = if is_answer(&answer) { answer } else { NO_ANSWER };
151 }
152 }
153 Plane::Crs(mapping) => mapping.lng_lats_from_world(world, lng_lats),
154 }
155 }
156
157 /// The place of `lat_lng` in the world square, NaN where the projection
158 /// has none.
159 #[must_use]
160 pub fn world_from_lat_lng(&self, lat_lng: &LatLng) -> Point<f64> {
161 let mut world = [[0.0; 2]];
162 self.world_from_lng_lats(&[[lat_lng.longitude(), lat_lng.latitude()]], &mut world);
163 Point::new(world[0][0], world[0][1])
164 }
165
166 /// The location of a place in the world square, as
167 /// [`lng_lats_from_world`](Self::lng_lats_from_world) finds it. Fails
168 /// with [`ErrorKind::InvalidArgument`](crate::error::ErrorKind) where it
169 /// finds none.
170 pub fn lat_lng_from_world(&self, world: &Point<f64>) -> Result<LatLng, Error> {
171 let mut lng_lat = [[0.0; 2]];
172 self.lng_lats_from_world(&[[world.x, world.y]], &mut lng_lat);
173 if !is_answer(&lng_lat[0]) {
174 return Err(Error::invalid_argument(format!(
175 "the projection \"{}\" has no location at the world position {}, {}",
176 self.name(),
177 world.x,
178 world.y
179 )));
180 }
181 LatLng::with_mode(lng_lat[0][1], lng_lat[0][0], WrapMode::Unwrapped)
182 }
183
184 /// The point of `lat_lng` in a world `scale` times the tile size wide, a
185 /// latitude past Mercator's limit on the square's edge.
186 #[must_use]
187 pub fn project(&self, lat_lng: &LatLng, scale: f64) -> Point<f64> {
188 let world_size = scale * TILE_SIZE_D;
189 let world = self.world_from_lat_lng(lat_lng);
190 Point::new(world.x * world_size, world.y * world_size)
191 }
192
193 /// The location of a point in a world `scale` times the tile size wide,
194 /// in the world copy that `wrap_mode` asks for where the world wraps.
195 /// Fails as [`lat_lng_from_world`](Self::lat_lng_from_world) does.
196 pub fn unproject(&self, point: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> Result<LatLng, Error> {
197 let world_size = scale * TILE_SIZE_D;
198 let lat_lng = self.lat_lng_from_world(&Point::new(point.x / world_size, point.y / world_size))?;
199 Ok(if wrap_mode == WrapMode::Wrapped { self.wrap(lat_lng) } else { lat_lng })
200 }
201
202 /// The place of `lat_lng` in a world `scale` times the tile size wide,
203 /// measured from the world square's center, with y down, where a
204 /// camera keeps its center: measured from the center, a location near it
205 /// keeps the precision that the offset of the square's corner would
206 /// round away. On Mercator it goes past the latitude limit too, as the
207 /// globe's center and an unconstrained one do, up to a finite distance
208 /// past the square's edge at the poles. NaN where the projection has no
209 /// place for it.
210 #[must_use]
211 pub fn project_from_center(&self, lat_lng: &LatLng, scale: f64) -> Point<f64> {
212 let world_size = scale * TILE_SIZE_D;
213 if self.0 == Plane::Mercator {
214 return Point::new(
215 lat_lng.longitude() / DEGREES_MAX * world_size,
216 -mercator_north(lat_lng.latitude()) / (PI * 2.0) * world_size,
217 );
218 }
219 let place = self.world_from_lat_lng(lat_lng);
220 Point::new((place.x - 0.5) * world_size, (place.y - 0.5) * world_size)
221 }
222
223 /// The location of a place in a world `scale` times the tile size wide,
224 /// measured from the world square's center, as
225 /// [`project_from_center`](Self::project_from_center) measures it, in the
226 /// world copy that `wrap_mode` asks for where the world wraps. A place of
227 /// a registered projection without a location of its own takes the one
228 /// that [`lng_lats_from_world`](Self::lng_lats_from_world) falls back on,
229 /// and a coordinate that is NaN where there is none is
230 /// [`LatLng::saturating`]'s.
231 #[must_use]
232 pub fn unproject_from_center(&self, point: &Point<f64>, scale: f64, wrap_mode: WrapMode) -> LatLng {
233 let world_size = scale * TILE_SIZE_D;
234 if self.0 == Plane::Mercator {
235 let longitude = point.x / world_size * DEGREES_MAX;
236 let latitude = mercator_latitude_at(-point.y / world_size * (PI * 2.0));
237 return LatLng::saturating(latitude, longitude, wrap_mode);
238 }
239 let mut lng_lat = [[0.0; 2]];
240 self.lng_lats_from_world(&[[0.5 + point.x / world_size, 0.5 + point.y / world_size]], &mut lng_lat);
241 LatLng::saturating(lng_lat[0][1], lng_lat[0][0], WrapMode::Unwrapped)
242 }
243
244 /// Whether a place in the world square has a location of its own,
245 /// rather than the nearest one that
246 /// [`lng_lats_from_world`](Self::lng_lats_from_world) falls back on:
247 /// always on Mercator.
248 #[must_use]
249 pub fn has_lat_lng(&self, world: &Point<f64>) -> bool {
250 match &self.0 {
251 Plane::Mercator => true,
252 Plane::Crs(mapping) => mapping.has_lat_lng([world.x, world.y]),
253 }
254 }
255
256 /// How many meters of height a world unit stands for at `lat_lng`, the
257 /// scale that the map draws heights at there, such as terrain,
258 /// extrusions and the camera's altitude: on Mercator, the ground meters
259 /// a world unit spans at its latitude, so that heights match the ground;
260 /// in a registered projection, the extent of its tile matrix set, its
261 /// units taken as meters, anywhere.
262 #[must_use]
263 pub fn height_meters_per_world_unit(&self, lat_lng: &LatLng) -> f64 {
264 match &self.0 {
265 Plane::Mercator => mercator_meters_per_world_unit(lat_lng.latitude()),
266 Plane::Crs(mapping) => mapping.crs().tile_matrix_set.extent_at_zoom0,
267 }
268 }
269
270 /// How many meters on the ground a world unit spans at the lng/lat
271 /// `lng_lat`, in degrees, along `step`, a short step in the world square
272 /// from its place: on Mercator, the scale at its latitude, the same in
273 /// every direction; in a registered projection, whose scale can change
274 /// with the direction, the ground distance from `lng_lat` to the location
275 /// at the step's end, on a sphere of the earth's mean radius, over the
276 /// step's length. NaN where the projection has no place for
277 /// `lng_lat`.
278 #[must_use]
279 pub fn ground_meters_per_world_unit(&self, lng_lat: [f64; 2], step: [f64; 2]) -> f64 {
280 let Plane::Crs(mapping) = &self.0 else {
281 return mercator_meters_per_world_unit(lng_lat[1]);
282 };
283 let mut place = [[0.0; 2]];
284 mapping.world_from_lng_lats(&[lng_lat], &mut place);
285 let mut end = [[0.0; 2]];
286 mapping.lng_lats_from_world(&[[place[0][0] + step[0], place[0][1] + step[1]]], &mut end);
287 ground_distance(lng_lat, end[0]) / step[0].hypot(step[1])
288 }
289
290 /// The places in the world square of a lng/lat box sampled on a grid,
291 /// 17 points on a side with its edges and corners, and how far its edges
292 /// stray from the lines between neighboring samples, which a shape that
293 /// holds the samples grows by to hold the box. Corners alone miss most of
294 /// a box whose edges curve, as a parallel does around a pole, and the
295 /// inside of the box matters where a projection runs off to infinity.
296 #[must_use]
297 pub fn lng_lat_box_samples(&self, bounds: &LatLngBounds) -> BoxSamples {
298 BoxSamples::new(bounds, |lng_lats, world| self.world_from_lng_lats(lng_lats, world))
299 }
300
301 /// The rectangle in the world square around a lng/lat box, as
302 /// [`BoxSamples::world_box`] finds it from the box's samples.
303 #[must_use]
304 pub fn lng_lat_box_to_world_box(&self, bounds: &LatLngBounds) -> WorldBox {
305 self.lng_lat_box_samples(bounds).world_box()
306 }
307}
308
309/// A mapping crosses as the name of its registered projection, or none for
310/// Mercator's, and the reading side takes the mapping that the
311/// [`StyleRegistry`](crate::StyleRegistry) in its context has by that name.
312impl Wire for WorldMapping {
313 fn write(&self, w: &mut mln_wire::Writer<'_>) {
314 match &self.0 {
315 Plane::Mercator => false.write(w),
316 Plane::Crs(mapping) => {
317 true.write(w);
318 mln_wire::write_str(w, &mapping.crs().name);
319 }
320 }
321 }
322
323 fn read(r: &mut mln_wire::Reader<'_>) -> Option<Self> {
324 if !bool::read(r)? {
325 return Some(WorldMapping::default());
326 }
327 let name = mln_wire::read_str(r)?;
328 let world = match r.context::<crate::StyleRegistry>() {
329 None => Err("a projection without a registry to resolve it against"),
330 Some(registry) => registry.projection(name).cloned().ok_or("unknown projection"),
331 };
332 match world {
333 Ok(world) => Some(world),
334 Err(message) => r.fail(message),
335 }
336 }
337}
338
339/// The earth's mean radius in meters, the IUGG's, on which ground distances
340/// measure.
341const MEAN_EARTH_RADIUS_M: f64 = 6_371_008.8;
342
343/// The ground distance in meters between two lng/lats in degrees, on a
344/// sphere of the earth's mean radius: by the haversine formula, which keeps
345/// the centimeters across a few pixels at the highest zooms, where the
346/// spherical law of cosines rounds them to nothing.
347fn ground_distance([lng_a, lat_a]: [f64; 2], [lng_b, lat_b]: [f64; 2]) -> f64 {
348 let (lat_a, lat_b) = (lat_a.to_radians(), lat_b.to_radians());
349 let (half_latitude, half_longitude) = ((lat_b - lat_a) / 2.0, (lng_b - lng_a).to_radians() / 2.0);
350 let haversine = half_latitude.sin().powi(2) + lat_a.cos() * lat_b.cos() * half_longitude.sin().powi(2);
351 let chord = haversine.sqrt();
352 // Rounding can take it past 1; a NaN stays NaN.
353 2.0 * MEAN_EARTH_RADIUS_M * (if chord > 1.0 { 1.0 } else { chord }).asin()
354}
355
356/// `latitude` within Web Mercator's limit, past which Mercator puts every
357/// location on the world square's edge.
358fn mercator_latitude(latitude: f64) -> f64 {
359 clamp_f64(latitude, -LATITUDE_MAX, LATITUDE_MAX)
360}
361
362/// How many meters on the ground a world unit of Web Mercator spans at
363/// `latitude`, kept within Mercator's limit: the length of the parallel.
364fn mercator_meters_per_world_unit(latitude: f64) -> f64 {
365 deg2rad(mercator_latitude(latitude)).cos() * (PI * 2.0) * EARTH_RADIUS_M
366}
367
368/// How far north of the equator Web Mercator puts `latitude`, in degrees,
369/// in a world 2π wide: asinh(tan φ), which is ln(tan(π/4 + φ/2)) and stays
370/// finite at the poles.
371fn mercator_north(latitude: f64) -> f64 {
372 deg2rad(latitude).tan().asinh()
373}
374
375/// The latitude in degrees that Web Mercator puts `north` of the equator, in
376/// a world 2π wide: the inverse of [`mercator_north`].
377fn mercator_latitude_at(north: f64) -> f64 {
378 rad2deg(north.sinh().atan())
379}
380
381/// Web Mercator's places of `lng_lats`, in degrees, into `places`, each
382/// latitude through `latitude` first: NaN where a lng/lat isn't finite.
383fn mercator_places(lng_lats: &[[f64; 2]], places: &mut [[f64; 2]], latitude: impl Fn(f64) -> f64) {
384 for (place, &[lng, lat]) in places.iter_mut().zip(lng_lats) {
385 *place = if is_answer(&[lng, lat]) { mercator_point([lng, latitude(lat)]) } else { NO_ANSWER };
386 }
387}
388
389/// Web Mercator's place in the world square of a lng/lat in degrees.
390fn mercator_point([longitude, latitude]: [f64; 2]) -> [f64; 2] {
391 [0.5 + longitude / DEGREES_MAX, 0.5 - mercator_north(latitude) / (PI * 2.0)]
392}
393
394/// The lng/lat in degrees of a place in Web Mercator's world square, the
395/// inverse of [`mercator_point`], NaN or infinite where the place is.
396fn mercator_lng_lat([x, y]: [f64; 2]) -> [f64; 2] {
397 [(x - 0.5) * DEGREES_MAX, mercator_latitude_at((0.5 - y) * (PI * 2.0))]
398}