mln-rs-util 0.0.13

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
// The C++ tile-ID constructors (`LatLng(CanonicalTileID)`,
// `LatLng(UnwrappedTileID)`, `LatLngBounds(CanonicalTileID)`) can't name
// the tile ID types here (mln_tile_id depends on mln_util), so they take the
// IDs' fields: `LatLng::from_canonical_tile(z, x, y)` etc.

use geometry::Point;
use mln_math::{clamp_f64, rad2deg, wrap};

use crate::constants;
use crate::error::Error;

pub type ScreenCoordinate = Point<f64>;
pub type ScreenLineString = Vec<Point<f64>>;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WrapMode {
    Unwrapped,
    Wrapped,
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LatLng {
    lat: f64,
    lon: f64,
}

impl Default for LatLng {
    fn default() -> Self {
        LatLng { lat: 0.0, lon: 0.0 }
    }
}

fn lat_(z: u8, y: i64) -> f64 {
    let n = std::f64::consts::PI - 2.0 * std::f64::consts::PI * y as f64 / 2.0f64.powf(f64::from(z));
    rad2deg((0.5 * (n.exp() - (-n).exp())).atan())
}

fn lon_(z: u8, x: i64) -> f64 {
    x as f64 / 2.0f64.powf(f64::from(z)) * constants::DEGREES_MAX - constants::LONGITUDE_MAX
}

impl LatLng {
    /// Fails with [`ErrorKind::InvalidArgument`](crate::ErrorKind) for a NaN
    /// coordinate, a latitude outside -90 to 90, or an infinite longitude.
    pub fn new(lat: f64, lon: f64) -> Result<Self, Error> {
        Self::with_mode(lat, lon, WrapMode::Unwrapped)
    }

    pub fn with_mode(lat: f64, lon: f64, mode: WrapMode) -> Result<Self, Error> {
        if lat.is_nan() {
            return Err(Error::invalid_argument("latitude must not be NaN"));
        }
        if lon.is_nan() {
            return Err(Error::invalid_argument("longitude must not be NaN"));
        }
        if lat.abs() > 90.0 {
            return Err(Error::invalid_argument("latitude must be between -90 and 90"));
        }
        if !lon.is_finite() {
            return Err(Error::invalid_argument("longitude must not be infinite"));
        }
        let mut result = LatLng { lat, lon };
        if mode == WrapMode::Wrapped {
            result.wrap();
        }
        Ok(result)
    }

    /// For construction from values that are valid by construction (the
    /// C++ `noexcept` paths).
    pub(crate) const fn new_unchecked(lat: f64, lon: f64) -> Self {
        LatLng { lat, lon }
    }

    /// The top left corner of the tile `z/x/y`.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn from_canonical_tile(z: u8, x: u32, y: u32) -> Self {
        LatLng::new_unchecked(lat_(z, i64::from(y)), lon_(z, i64::from(x)))
    }

    #[must_use]
    pub fn from_unwrapped_tile(z: u8, x: u32, y: u32, wrap: i16) -> Self {
        LatLng::new_unchecked(lat_(z, i64::from(y)), lon_(z, i64::from(x)) + f64::from(wrap) * constants::DEGREES_MAX)
    }

    #[must_use]
    pub fn latitude(&self) -> f64 {
        self.lat
    }

    #[must_use]
    pub fn longitude(&self) -> f64 {
        self.lon
    }

    #[must_use]
    pub fn wrapped(&self) -> LatLng {
        let mut r = *self;
        r.wrap();
        r
    }

    pub fn wrap(&mut self) {
        self.lon = wrap(self.lon, -constants::LONGITUDE_MAX, constants::LONGITUDE_MAX);
    }

    /// If the distance from start to end longitudes is between half and full
    /// world, unwrap the start longitude to ensure the shortest path is taken.
    pub fn unwrap_for_shortest_path(&mut self, end: &LatLng) {
        let delta = (end.lon - self.lon).abs();
        if delta <= constants::LONGITUDE_MAX || delta >= constants::DEGREES_MAX {
            return;
        }
        if self.lon > 0.0 && end.lon < 0.0 {
            self.lon -= constants::DEGREES_MAX;
        } else if self.lon < 0.0 && end.lon > 0.0 {
            self.lon += constants::DEGREES_MAX;
        }
    }
}

#[derive(Clone, Copy, Debug)]
pub struct LatLngBounds {
    sw: LatLng,
    ne: LatLng,
    bounded: bool,
}

impl LatLngBounds {
    const fn from_corners(sw: LatLng, ne: LatLng) -> Self {
        LatLngBounds { sw, ne, bounded: true }
    }

    /// Return a bounds covering the entire (unwrapped) world.
    #[must_use]
    pub fn world() -> Self {
        LatLngBounds::from_corners(LatLng::new_unchecked(-90.0, -180.0), LatLng::new_unchecked(90.0, 180.0))
    }

    /// Return the bounds consisting of the single point.
    #[must_use]
    pub fn singleton(a: LatLng) -> Self {
        LatLngBounds::from_corners(a, a)
    }

    /// Return the convex hull of two points; the smallest bounds that
    /// contains both.
    #[must_use]
    pub fn hull(a: LatLng, b: LatLng) -> Self {
        let mut bounds = LatLngBounds::from_corners(a, a);
        bounds.extend(&b);
        bounds
    }

    /// Return a bounds that may serve as the identity element for the
    /// extend operation.
    #[must_use]
    pub fn empty() -> Self {
        let mut bounds = Self::world();
        std::mem::swap(&mut bounds.sw, &mut bounds.ne);
        bounds
    }

    /// Construct an infinite bound, a bound for which the constrain method
    /// returns its input unmodified (the C++ default constructor).
    ///
    /// Note: this is different than `LatLngBounds::world()` since arbitrary
    /// unwrapped coordinates are also inside the bounds.
    #[must_use]
    pub fn infinite() -> Self {
        LatLngBounds {
            sw: LatLng::new_unchecked(-90.0, -180.0),
            ne: LatLng::new_unchecked(90.0, 180.0),
            bounded: false,
        }
    }

    /// The exact boundaries of the tile `z/x/y`.
    #[must_use]
    pub fn from_canonical_tile(z: u8, x: u32, y: u32) -> Self {
        LatLngBounds::from_corners(
            // `id.y + 1` is uint32_t arithmetic.
            LatLng::new_unchecked(lat_(z, i64::from(y.wrapping_add(1))), lon_(z, i64::from(x))),
            LatLng::new_unchecked(lat_(z, i64::from(y)), lon_(z, i64::from(x.wrapping_add(1)))),
        )
    }

    #[must_use]
    pub fn valid(&self) -> bool {
        (self.sw.latitude() <= self.ne.latitude()) && (self.sw.longitude() <= self.ne.longitude())
    }

    #[must_use]
    pub fn south(&self) -> f64 {
        self.sw.latitude()
    }
    #[must_use]
    pub fn west(&self) -> f64 {
        self.sw.longitude()
    }
    #[must_use]
    pub fn north(&self) -> f64 {
        self.ne.latitude()
    }
    #[must_use]
    pub fn east(&self) -> f64 {
        self.ne.longitude()
    }

    #[must_use]
    pub fn southwest(&self) -> LatLng {
        self.sw
    }
    #[must_use]
    pub fn northeast(&self) -> LatLng {
        self.ne
    }
    #[must_use]
    pub fn southeast(&self) -> LatLng {
        LatLng::new_unchecked(self.south(), self.east())
    }
    #[must_use]
    pub fn northwest(&self) -> LatLng {
        LatLng::new_unchecked(self.north(), self.west())
    }

    /// Panics if the longitude sum overflows to infinity (C++ constructs the
    /// `LatLng` in a `noexcept` function, so it terminates).
    #[must_use]
    pub fn center(&self) -> LatLng {
        LatLng::new(
            f64::midpoint(self.sw.latitude(), self.ne.latitude()),
            f64::midpoint(self.sw.longitude(), self.ne.longitude()),
        )
        .expect("LatLngBounds::center")
    }

    #[must_use]
    pub fn constrain(&self, p: &LatLng) -> LatLng {
        if !self.bounded {
            return *p;
        }

        let mut lat = p.latitude();
        let mut lng = p.longitude();

        if !self.contains_latitude(lat) {
            lat = clamp_f64(lat, self.south(), self.north());
        }

        if !self.contains_longitude(lng, WrapMode::Unwrapped) {
            lng = clamp_f64(lng, self.west(), self.east());
        }

        LatLng::new_unchecked(lat, lng)
    }

    pub fn extend(&mut self, point: &LatLng) {
        self.sw = LatLng::new_unchecked(
            f64::min(point.latitude(), self.sw.latitude()),
            f64::min(point.longitude(), self.sw.longitude()),
        );
        self.ne = LatLng::new_unchecked(
            f64::max(point.latitude(), self.ne.latitude()),
            f64::max(point.longitude(), self.ne.longitude()),
        );
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.sw.latitude() > self.ne.latitude() || self.sw.longitude() > self.ne.longitude()
    }

    #[must_use]
    pub fn crosses_antimeridian(&self) -> bool {
        self.sw.wrapped().longitude() > self.ne.wrapped().longitude()
    }

    #[must_use]
    pub fn contains(&self, point: &LatLng) -> bool {
        self.contains_with_mode(point, WrapMode::Unwrapped)
    }

    #[must_use]
    pub fn contains_with_mode(&self, point: &LatLng, wrap: WrapMode) -> bool {
        self.contains_latitude(point.latitude()) && self.contains_longitude(point.longitude(), wrap)
    }

    #[cfg(test)]
    #[must_use]
    pub(crate) fn contains_bounds(&self, area: &LatLngBounds, wrap: WrapMode) -> bool {
        let contains_area_latitude = area.north() <= self.north() && area.south() >= self.south();
        if !contains_area_latitude {
            return false;
        }

        let contains_unwrapped = area.east() <= self.east() && area.west() >= self.west();
        if contains_unwrapped {
            return true;
        } else if wrap == WrapMode::Wrapped {
            let wrapped = LatLngBounds::from_corners(self.sw.wrapped(), self.ne.wrapped());
            let other = LatLngBounds::from_corners(area.sw.wrapped(), area.ne.wrapped());
            if self.crosses_antimeridian() && !area.crosses_antimeridian() {
                return (other.east() <= constants::LONGITUDE_MAX && other.west() >= wrapped.west())
                    || (other.east() <= wrapped.east() && other.west() >= -constants::LONGITUDE_MAX);
            }
            return other.east() <= wrapped.east() && other.west() >= wrapped.west();
        }
        false
    }

    #[cfg(test)]
    #[must_use]
    pub(crate) fn intersects(&self, area: LatLngBounds, wrap: WrapMode) -> bool {
        let latitude_intersects = area.north() > self.south() && area.south() < self.north();
        if !latitude_intersects {
            return false;
        }

        let longitude_intersects = area.east() > self.west() && area.west() < self.east();
        if longitude_intersects {
            return true;
        } else if wrap == WrapMode::Wrapped {
            let wrapped = LatLngBounds::from_corners(self.sw.wrapped(), self.ne.wrapped());
            let other = LatLngBounds::from_corners(area.sw.wrapped(), area.ne.wrapped());
            if self.crosses_antimeridian() {
                return area.crosses_antimeridian() || other.east() > wrapped.west() || other.west() < wrapped.east();
            } else if other.crosses_antimeridian() {
                return other.east() > wrapped.west() || other.west() < wrapped.east();
            }
            return other.east() > wrapped.west() && other.west() < wrapped.east();
        }
        false
    }

    fn contains_latitude(&self, latitude: f64) -> bool {
        latitude >= self.south() && latitude <= self.north()
    }

    fn contains_longitude(&self, longitude: f64, wrap: WrapMode) -> bool {
        if longitude >= self.west() && longitude <= self.east() {
            return true;
        }

        if wrap == WrapMode::Wrapped {
            let wrapped = LatLngBounds::from_corners(self.sw.wrapped(), self.ne.wrapped());
            // LatLng(0.0, longitude).wrapped(): longitude is finite here
            // (it compared above), except for NaN/inf inputs, which the C++
            // constructor rejects by throwing in a noexcept function.
            let longitude =
                LatLng::new(0.0, longitude).expect("LatLngBounds::contains_longitude").wrapped().longitude();
            if self.crosses_antimeridian() {
                return (longitude >= -constants::LONGITUDE_MAX && longitude <= wrapped.east())
                    || (longitude >= wrapped.west() && longitude <= constants::LONGITUDE_MAX);
            }

            return longitude >= wrapped.west() && longitude <= wrapped.east();
        }

        false
    }
}

impl Default for LatLngBounds {
    fn default() -> Self {
        Self::infinite()
    }
}

impl PartialEq for LatLngBounds {
    fn eq(&self, b: &LatLngBounds) -> bool {
        (!self.bounded && !b.bounded) || (self.bounded && b.bounded && self.sw == b.sw && self.ne == b.ne)
    }
}

/// Determines the orientation of the map.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum NorthOrientation {
    #[default]
    Upwards,
    Rightwards,
    Downwards,
    Leftwards,
}

/// The distance on each side between a rectangle and a rectangle within.
///
/// The fields are public (seed API); `new` validates like the C++
/// constructor.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct EdgeInsets {
    /// Number of pixels inset from the top edge.
    pub top: f64,
    /// Number of pixels inset from the left edge.
    pub left: f64,
    /// Number of pixels inset from the bottom edge.
    pub bottom: f64,
    /// Number of pixels inset from the right edge.
    pub right: f64,
}

impl EdgeInsets {
    /// Fails with [`ErrorKind::InvalidArgument`](crate::ErrorKind) for a NaN
    /// inset.
    pub fn new(top: f64, left: f64, bottom: f64, right: f64) -> Result<Self, Error> {
        if top.is_nan() {
            return Err(Error::invalid_argument("top must not be NaN"));
        }
        if left.is_nan() {
            return Err(Error::invalid_argument("left must not be NaN"));
        }
        if bottom.is_nan() {
            return Err(Error::invalid_argument("bottom must not be NaN"));
        }
        if right.is_nan() {
            return Err(Error::invalid_argument("right must not be NaN"));
        }
        Ok(EdgeInsets { top, left, bottom, right })
    }

    #[must_use]
    pub fn top(&self) -> f64 {
        self.top
    }
    #[must_use]
    pub fn left(&self) -> f64 {
        self.left
    }
    #[must_use]
    pub fn bottom(&self) -> f64 {
        self.bottom
    }
    #[must_use]
    pub fn right(&self) -> f64 {
        self.right
    }

    #[must_use]
    pub fn get_center(&self, width: u16, height: u16) -> ScreenCoordinate {
        Point::new(
            (f64::from(width) - self.left() - self.right()) / 2.0 + self.left(),
            (f64::from(height) - self.top() - self.bottom()) / 2.0 + self.top(),
        )
    }
}

impl std::ops::AddAssign for EdgeInsets {
    fn add_assign(&mut self, o: EdgeInsets) {
        self.top += o.top;
        self.left += o.left;
        self.bottom += o.bottom;
        self.right += o.right;
    }
}

impl std::ops::Add for EdgeInsets {
    type Output = EdgeInsets;
    // C++ goes through the throwing constructor (NaN from inf + -inf).
    fn add(self, o: EdgeInsets) -> EdgeInsets {
        EdgeInsets::new(self.top + o.top, self.left + o.left, self.bottom + o.bottom, self.right + o.right)
            .expect("EdgeInsets::operator+")
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct LatLngAltitude {
    pub location: LatLng,
    pub altitude: f64,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn latlng_validation() {
        assert!(LatLng::new(91.0, 0.0).is_err());
        assert!(LatLng::new(f64::NAN, 0.0).is_err());
        assert!(LatLng::new(0.0, f64::INFINITY).is_err());
        assert!(LatLng::new(45.0, 190.0).is_ok());
    }

    #[test]
    fn latlng_wrapping() {
        let ll = LatLng::with_mode(0.0, 190.0, WrapMode::Wrapped).unwrap();
        assert_eq!(ll.longitude(), -170.0);
    }

    #[test]
    fn bounds_extend() {
        let mut b = LatLngBounds::empty();
        assert!(!b.valid());
        b.extend(&LatLng::new(10.0, 20.0).unwrap());
        b.extend(&LatLng::new(-10.0, -20.0).unwrap());
        assert!(b.valid());
        assert!(b.contains(&LatLng::new(0.0, 0.0).unwrap()));
        assert!(!b.contains(&LatLng::new(11.0, 0.0).unwrap()));
    }

    #[test]
    fn infinite_bounds_contains_like_world() {
        // C++ contains() does not look at `bounded`.
        let b = LatLngBounds::infinite();
        assert!(!b.contains(&LatLng::new(0.0, 200.0).unwrap()));
        assert_eq!(LatLngBounds::infinite(), LatLngBounds::default());
        assert_ne!(LatLngBounds::infinite(), LatLngBounds::world());
    }
}