1use crate::constants;
8use crate::error::Error;
9use crate::math::{clamp_f64, rad2deg, wrap};
10
11#[derive(Clone, Copy, Debug, PartialEq, Eq)]
12pub enum WrapMode {
13 Unwrapped,
14 Wrapped,
15}
16
17#[derive(Clone, Copy, Debug, PartialEq, mln_wire::Wire)]
18pub struct LatLng {
19 lat: f64,
20 lon: f64,
21}
22
23impl Default for LatLng {
24 fn default() -> Self {
25 LatLng { lat: 0.0, lon: 0.0 }
26 }
27}
28
29fn lat_(z: u8, y: i64) -> f64 {
30 let n = std::f64::consts::PI - 2.0 * std::f64::consts::PI * y as f64 / 2.0f64.powf(f64::from(z));
31 rad2deg((0.5 * (n.exp() - (-n).exp())).atan())
32}
33
34fn lon_(z: u8, x: i64) -> f64 {
35 x as f64 / 2.0f64.powf(f64::from(z)) * constants::DEGREES_MAX - constants::LONGITUDE_MAX
36}
37
38impl LatLng {
39 pub fn new(lat: f64, lon: f64) -> Result<Self, Error> {
42 Self::with_mode(lat, lon, WrapMode::Unwrapped)
43 }
44
45 pub fn with_mode(lat: f64, lon: f64, mode: WrapMode) -> Result<Self, Error> {
46 if lat.is_nan() {
47 return Err(Error::invalid_argument("latitude must not be NaN"));
48 }
49 if lon.is_nan() {
50 return Err(Error::invalid_argument("longitude must not be NaN"));
51 }
52 if lat.abs() > 90.0 {
53 return Err(Error::invalid_argument("latitude must be between -90 and 90"));
54 }
55 if !lon.is_finite() {
56 return Err(Error::invalid_argument("longitude must not be infinite"));
57 }
58 let mut result = LatLng { lat, lon };
59 if mode == WrapMode::Wrapped {
60 result.wrap();
61 }
62 Ok(result)
63 }
64
65 #[must_use]
69 pub fn saturating(lat: f64, lon: f64, mode: WrapMode) -> Self {
70 let lat = if lat.is_nan() { 0.0 } else { lat.clamp(-90.0, 90.0) };
71 let lon = if lon.is_nan() { 0.0 } else { lon.clamp(f64::MIN, f64::MAX) };
72 let mut result = LatLng { lat, lon };
73 if mode == WrapMode::Wrapped {
74 result.wrap();
75 }
76 result
77 }
78
79 pub(crate) const fn new_unchecked(lat: f64, lon: f64) -> Self {
81 LatLng { lat, lon }
82 }
83
84 #[cfg(test)]
86 #[must_use]
87 pub(crate) fn from_canonical_tile(z: u8, x: u32, y: u32) -> Self {
88 LatLng::new_unchecked(lat_(z, i64::from(y)), lon_(z, i64::from(x)))
89 }
90
91 #[must_use]
92 pub fn from_unwrapped_tile(z: u8, x: u32, y: u32, wrap: i16) -> Self {
93 LatLng::new_unchecked(lat_(z, i64::from(y)), lon_(z, i64::from(x)) + f64::from(wrap) * constants::DEGREES_MAX)
94 }
95
96 #[must_use]
97 pub fn latitude(&self) -> f64 {
98 self.lat
99 }
100
101 #[must_use]
102 pub fn longitude(&self) -> f64 {
103 self.lon
104 }
105
106 #[must_use]
107 pub fn wrapped(&self) -> LatLng {
108 let mut r = *self;
109 r.wrap();
110 r
111 }
112
113 pub fn wrap(&mut self) {
114 self.lon = wrap(self.lon, -constants::LONGITUDE_MAX, constants::LONGITUDE_MAX);
115 }
116
117 pub fn unwrap_for_shortest_path(&mut self, end: &LatLng) {
120 let delta = (end.lon - self.lon).abs();
121 if delta <= constants::LONGITUDE_MAX || delta >= constants::DEGREES_MAX {
122 return;
123 }
124 if self.lon > 0.0 && end.lon < 0.0 {
125 self.lon -= constants::DEGREES_MAX;
126 } else if self.lon < 0.0 && end.lon > 0.0 {
127 self.lon += constants::DEGREES_MAX;
128 }
129 }
130}
131
132#[derive(Clone, Copy, Debug)]
133pub struct LatLngBounds {
134 sw: LatLng,
135 ne: LatLng,
136 bounded: bool,
137}
138
139impl LatLngBounds {
140 const fn from_corners(sw: LatLng, ne: LatLng) -> Self {
141 LatLngBounds { sw, ne, bounded: true }
142 }
143
144 #[must_use]
146 pub fn world() -> Self {
147 LatLngBounds::from_corners(LatLng::new_unchecked(-90.0, -180.0), LatLng::new_unchecked(90.0, 180.0))
148 }
149
150 #[must_use]
152 pub fn singleton(a: LatLng) -> Self {
153 LatLngBounds::from_corners(a, a)
154 }
155
156 #[must_use]
159 pub fn hull(a: LatLng, b: LatLng) -> Self {
160 let mut bounds = LatLngBounds::from_corners(a, a);
161 bounds.extend(&b);
162 bounds
163 }
164
165 #[must_use]
168 pub fn empty() -> Self {
169 let mut bounds = Self::world();
170 std::mem::swap(&mut bounds.sw, &mut bounds.ne);
171 bounds
172 }
173
174 #[must_use]
180 pub fn infinite() -> Self {
181 LatLngBounds {
182 sw: LatLng::new_unchecked(-90.0, -180.0),
183 ne: LatLng::new_unchecked(90.0, 180.0),
184 bounded: false,
185 }
186 }
187
188 #[must_use]
190 pub fn from_canonical_tile(z: u8, x: u32, y: u32) -> Self {
191 LatLngBounds::from_corners(
192 LatLng::new_unchecked(lat_(z, i64::from(y) + 1), lon_(z, i64::from(x))),
193 LatLng::new_unchecked(lat_(z, i64::from(y)), lon_(z, i64::from(x) + 1)),
194 )
195 }
196
197 #[must_use]
198 pub fn valid(&self) -> bool {
199 (self.sw.latitude() <= self.ne.latitude()) && (self.sw.longitude() <= self.ne.longitude())
200 }
201
202 #[must_use]
203 pub fn south(&self) -> f64 {
204 self.sw.latitude()
205 }
206 #[must_use]
207 pub fn west(&self) -> f64 {
208 self.sw.longitude()
209 }
210 #[must_use]
211 pub fn north(&self) -> f64 {
212 self.ne.latitude()
213 }
214 #[must_use]
215 pub fn east(&self) -> f64 {
216 self.ne.longitude()
217 }
218
219 #[must_use]
220 pub fn southwest(&self) -> LatLng {
221 self.sw
222 }
223 #[must_use]
224 pub fn northeast(&self) -> LatLng {
225 self.ne
226 }
227 #[must_use]
228 pub fn southeast(&self) -> LatLng {
229 LatLng::new_unchecked(self.south(), self.east())
230 }
231 #[must_use]
232 pub fn northwest(&self) -> LatLng {
233 LatLng::new_unchecked(self.north(), self.west())
234 }
235
236 #[must_use]
237 pub fn center(&self) -> LatLng {
238 LatLng::new_unchecked(
241 f64::midpoint(self.sw.latitude(), self.ne.latitude()),
242 f64::midpoint(self.sw.longitude(), self.ne.longitude()),
243 )
244 }
245
246 #[must_use]
247 pub fn constrain(&self, p: &LatLng) -> LatLng {
248 if !self.bounded {
249 return *p;
250 }
251
252 let mut lat = p.latitude();
253 let mut lng = p.longitude();
254
255 if !self.contains_latitude(lat) {
256 lat = clamp_f64(lat, self.south(), self.north());
257 }
258
259 if !self.contains_longitude(lng, WrapMode::Unwrapped) {
260 lng = clamp_f64(lng, self.west(), self.east());
261 }
262
263 LatLng::new_unchecked(lat, lng)
264 }
265
266 pub fn extend(&mut self, point: &LatLng) {
267 self.sw = LatLng::new_unchecked(
268 f64::min(point.latitude(), self.sw.latitude()),
269 f64::min(point.longitude(), self.sw.longitude()),
270 );
271 self.ne = LatLng::new_unchecked(
272 f64::max(point.latitude(), self.ne.latitude()),
273 f64::max(point.longitude(), self.ne.longitude()),
274 );
275 }
276
277 #[must_use]
278 pub fn is_empty(&self) -> bool {
279 self.sw.latitude() > self.ne.latitude() || self.sw.longitude() > self.ne.longitude()
280 }
281
282 #[must_use]
283 pub fn crosses_antimeridian(&self) -> bool {
284 self.sw.wrapped().longitude() > self.ne.wrapped().longitude()
285 }
286
287 #[must_use]
288 pub fn contains(&self, point: &LatLng) -> bool {
289 self.contains_with_mode(point, WrapMode::Unwrapped)
290 }
291
292 #[must_use]
293 pub fn contains_with_mode(&self, point: &LatLng, wrap: WrapMode) -> bool {
294 self.contains_latitude(point.latitude()) && self.contains_longitude(point.longitude(), wrap)
295 }
296
297 #[cfg(test)]
298 #[must_use]
299 pub(crate) fn contains_bounds(&self, area: &LatLngBounds, wrap: WrapMode) -> bool {
300 let contains_area_latitude = area.north() <= self.north() && area.south() >= self.south();
301 if !contains_area_latitude {
302 return false;
303 }
304
305 let contains_unwrapped = area.east() <= self.east() && area.west() >= self.west();
306 if contains_unwrapped {
307 return true;
308 } else if wrap == WrapMode::Wrapped {
309 let wrapped = LatLngBounds::from_corners(self.sw.wrapped(), self.ne.wrapped());
310 let other = LatLngBounds::from_corners(area.sw.wrapped(), area.ne.wrapped());
311 if self.crosses_antimeridian() && !area.crosses_antimeridian() {
312 return (other.east() <= constants::LONGITUDE_MAX && other.west() >= wrapped.west())
313 || (other.east() <= wrapped.east() && other.west() >= -constants::LONGITUDE_MAX);
314 }
315 return other.east() <= wrapped.east() && other.west() >= wrapped.west();
316 }
317 false
318 }
319
320 #[cfg(test)]
321 #[must_use]
322 pub(crate) fn intersects(&self, area: LatLngBounds, wrap: WrapMode) -> bool {
323 let latitude_intersects = area.north() > self.south() && area.south() < self.north();
324 if !latitude_intersects {
325 return false;
326 }
327
328 let longitude_intersects = area.east() > self.west() && area.west() < self.east();
329 if longitude_intersects {
330 return true;
331 } else if wrap == WrapMode::Wrapped {
332 let wrapped = LatLngBounds::from_corners(self.sw.wrapped(), self.ne.wrapped());
333 let other = LatLngBounds::from_corners(area.sw.wrapped(), area.ne.wrapped());
334 if self.crosses_antimeridian() {
335 return area.crosses_antimeridian() || other.east() > wrapped.west() || other.west() < wrapped.east();
336 } else if other.crosses_antimeridian() {
337 return other.east() > wrapped.west() || other.west() < wrapped.east();
338 }
339 return other.east() > wrapped.west() && other.west() < wrapped.east();
340 }
341 false
342 }
343
344 fn contains_latitude(&self, latitude: f64) -> bool {
345 latitude >= self.south() && latitude <= self.north()
346 }
347
348 fn contains_longitude(&self, longitude: f64, wrap: WrapMode) -> bool {
349 if longitude >= self.west() && longitude <= self.east() {
350 return true;
351 }
352
353 if wrap == WrapMode::Wrapped {
354 let wrapped = LatLngBounds::from_corners(self.sw.wrapped(), self.ne.wrapped());
355 let longitude = crate::math::wrap(longitude, -constants::LONGITUDE_MAX, constants::LONGITUDE_MAX);
356 if self.crosses_antimeridian() {
357 return (longitude >= -constants::LONGITUDE_MAX && longitude <= wrapped.east())
358 || (longitude >= wrapped.west() && longitude <= constants::LONGITUDE_MAX);
359 }
360
361 return longitude >= wrapped.west() && longitude <= wrapped.east();
362 }
363
364 false
365 }
366}
367
368impl Default for LatLngBounds {
369 fn default() -> Self {
370 Self::infinite()
371 }
372}
373
374impl PartialEq for LatLngBounds {
375 fn eq(&self, b: &LatLngBounds) -> bool {
376 (!self.bounded && !b.bounded) || (self.bounded && b.bounded && self.sw == b.sw && self.ne == b.ne)
377 }
378}
379
380#[cfg(test)]
381mod tests {
382 use super::*;
383
384 #[test]
385 fn saturating_lat_lng() {
386 let lat_lng = LatLng::saturating(f64::NAN, f64::INFINITY, WrapMode::Unwrapped);
387 assert_eq!((0.0, f64::MAX), (lat_lng.latitude(), lat_lng.longitude()));
388 let lat_lng = LatLng::saturating(-100.0, f64::NAN, WrapMode::Unwrapped);
389 assert_eq!((-90.0, 0.0), (lat_lng.latitude(), lat_lng.longitude()));
390 assert_eq!(190.0 - 360.0, LatLng::saturating(0.0, 190.0, WrapMode::Wrapped).longitude());
391 }
392
393 #[test]
394 fn latlng_validation() {
395 assert!(LatLng::new(91.0, 0.0).is_err());
396 assert!(LatLng::new(f64::NAN, 0.0).is_err());
397 assert!(LatLng::new(0.0, f64::INFINITY).is_err());
398 assert!(LatLng::new(45.0, 190.0).is_ok());
399 }
400
401 #[test]
402 fn latlng_wrapping() {
403 let ll = LatLng::with_mode(0.0, 190.0, WrapMode::Wrapped).unwrap();
404 assert_eq!(ll.longitude(), -170.0);
405 }
406
407 #[test]
408 fn bounds_extend() {
409 let mut b = LatLngBounds::empty();
410 assert!(!b.valid());
411 b.extend(&LatLng::new(10.0, 20.0).unwrap());
412 b.extend(&LatLng::new(-10.0, -20.0).unwrap());
413 assert!(b.valid());
414 assert!(b.contains(&LatLng::new(0.0, 0.0).unwrap()));
415 assert!(!b.contains(&LatLng::new(11.0, 0.0).unwrap()));
416 }
417
418 #[test]
419 fn infinite_bounds_contains_like_world() {
420 let b = LatLngBounds::infinite();
422 assert!(!b.contains(&LatLng::new(0.0, 200.0).unwrap()));
423 assert_eq!(LatLngBounds::infinite(), LatLngBounds::default());
424 assert_ne!(LatLngBounds::infinite(), LatLngBounds::world());
425 }
426}