mln-rs-engine 0.0.21

Part of mln-rs, a MapLibre map renderer written in Rust. 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
// Tile coordinates outside the `i32` range (or NaN) saturate (`as i32`), row
// arithmetic on `tile_y` wraps, and shifts by the zoom wrap their count
// (`wrapping_shl`), as in `tile::tile_id`.

use std::collections::VecDeque;
use std::convert::Infallible;
use std::iter::Peekable;

use geo_types::{Coord, Geometry, Polygon};
use geometry::Point;
use mln_style::collections::VecMap;
use mln_style::error::Error;
use mln_style::geo::LatLng;
use mln_style::geometry::{FeatureType, to_feature_type};
use mln_style::math::clamp_f64;

use crate::geo::projection::Projection;
use crate::tile::UnwrappedTileID;

pub(crate) type Bounds = Vec<Bound>;
pub(crate) type BoundsMap = VecMap<u32, Bounds>;

/// A chain of points from a local minimum to a local maximum. `winding`
/// indicates the direction of the original geometry.
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Bound {
    pub(crate) points: Vec<Point<f64>>,
    pub(crate) current_point: usize,
    pub(crate) winding: bool,
}

impl Bound {
    /// Compute the interpolated x coordinate at y for the current edge
    #[must_use]
    pub(crate) fn interpolate(&self, y: u32) -> f64 {
        let p0 = &self.points[self.current_point];
        let p1 = &self.points[self.current_point + 1];

        let dx = p1.x - p0.x;
        let dy = p1.y - p0.y;
        let mut x = p0.x;
        if dx == 0.0 {
            return x;
        } else if dy == 0.0 {
            return if f64::from(y) <= p0.y { p0.x } else { p1.x };
        }
        if f64::from(y) < p0.y {
            return x;
        }
        if f64::from(y) > p1.y {
            return p1.x;
        }
        x = (dx / dy) * (f64::from(y) - p0.y) + p0.x;
        x
    }
}

type PointList = Vec<Point<f64>>;

#[derive(Clone, Copy, Debug, PartialEq)]
struct TileSpan {
    xmin: i32,
    xmax: i32,
    winding: bool,
}

/// Reorder a ring of points such that it starts at a point with a local
/// minimum y-coordinate
fn start_list_on_local_minimum(points: &mut PointList) {
    // Iterators are indices; the caller guarantees `points.len() >= 2`.
    let end = points.len();
    let mut prev_pt = end - 2;
    let mut pt = 0;
    let mut next_pt = pt + 1;
    while pt != end {
        if (points[pt].y <= points[prev_pt].y) && (points[pt].y < points[next_pt].y) {
            break;
        }
        prev_pt = pt;
        pt += 1;
        next_pt += 1;
        if next_pt == end {
            next_pt = 1;
        }
    }
    if pt == end {
        return;
    }
    // Re-close linear rings with first_pt = last_pt
    if points.last() == points.first() {
        points.pop();
    }
    points.rotate_left(pt);
    points.push(points[0]);
}

/// Create a bound towards a local maximum point, starting from pt.
///  Traverse from current pt until the next pt changes y-direction, and copy
///  all points from start to end (inclusive) into a Bound.
fn create_bound_towards_maximum(points: &PointList, pt: &mut usize) -> Bound {
    if points.len() - *pt < 2 {
        return Bound::default();
    }

    let begin = *pt;
    let mut next_pt = begin + 1;
    while points[*pt].y <= points[next_pt].y {
        *pt += 1;
        next_pt += 1;
        if next_pt == points.len() {
            *pt += 1;
            break;
        }
    }

    let pt_distance = next_pt - begin;
    if pt_distance < 2 {
        return Bound::default();
    }

    let mut bnd = Bound::default();
    bnd.points.reserve(next_pt - begin);
    bnd.points.extend_from_slice(&points[begin..next_pt]);
    bnd.winding = true;
    bnd
}

/// Create a bound towards a local minimum point, starting from pt.
///  Traverse from current pt until the next pt changes y-direction, and copy
///  all points from start to end (inclusive) into a Bound.
fn create_bound_towards_minimum(points: &PointList, pt: &mut usize) -> Bound {
    if points.len() - *pt < 2 {
        return Bound::default();
    }

    let begin = *pt;
    let mut next_pt = begin + 1;
    while points[*pt].y > points[next_pt].y {
        *pt += 1;
        next_pt += 1;
        if next_pt == points.len() {
            *pt += 1;
            break;
        }
    }

    let pt_distance = next_pt - begin;
    if pt_distance < 2 {
        return Bound::default();
    }
    let mut bnd = Bound::default();
    bnd.points.reserve(next_pt - begin);
    // For bounds that start at a max, reverse copy so that all bounds start at a min
    bnd.points.extend(points[begin..next_pt].iter().rev().copied());
    bnd.winding = false;
    bnd
}

/// The tile row of a bound's first point at `y`, clamped to `0..=max_tile`.
/// A NaN `y` gives row 0.
fn start_row(y: f64, max_tile: f64) -> u32 {
    clamp_f64(y, 0.0, max_tile).floor() as u32
}

/// Given a set of points (ring or list) representing a shape, compute a set
/// of Bounds, where each Bound represents edges going from a local minima to
/// a local maxima point. The `BoundsMap` is an edge table indexed on the
/// starting Y-tile of each Bound.
fn build_bounds_map(points: &mut PointList, max_tile: u32, et: &mut BoundsMap, closed: bool) {
    if points.len() < 2 {
        return;
    }
    // While traversing closed rings, start the bounds at a local minimum.
    //  (For linestrings the starting point is always a local maxima/minima)
    if closed {
        start_list_on_local_minimum(points);
    }

    let mut points_iter = 0;
    while points_iter != points.len() {
        let to_max = create_bound_towards_maximum(points, &mut points_iter);
        let to_min = create_bound_towards_minimum(points, &mut points_iter);

        if to_max.points.len() >= 2 {
            // Projections may result in values beyond the bounds, clamp to max tile coordinates
            let y = start_row(to_max.points[0].y, f64::from(max_tile));
            et.entry(y).or_default().push(to_max);
        }
        if to_min.points.len() >= 2 {
            let y = start_row(to_min.points[0].y, f64::from(max_tile));
            et.entry(y).or_default().push(to_min);
        }
    }
    debug_assert_eq!(points_iter, points.len());
}

fn update_span(xp: &mut TileSpan, x: f64) {
    xp.xmin = std::cmp::min(xp.xmin, x.floor() as i32);
    xp.xmax = std::cmp::max(xp.xmax, x.ceil() as i32);
}

/// Use the active bounds, an accumulation of all bounds that enter the y tile
/// row, or start in that row.
/// Iterate all points of a bound until it exits the row (or ends) and compute
/// the set of X tiles it spans across. The winding direction of the bound is
/// also captured for each span to later fill tiles between bounds for
/// polygons
fn scan_row(y: u32, active_bounds: &mut Bounds) -> Vec<TileSpan> {
    let mut tile_range: Vec<TileSpan> = Vec::with_capacity(active_bounds.len());

    // The bottom of the row.
    let y1 = y.wrapping_add(1);
    for b in active_bounds.iter_mut() {
        let mut xp = TileSpan { xmin: i32::MAX, xmax: i32::MIN, winding: b.winding };
        let mut x;
        let num_edges = b.points.len() - 1;
        while b.current_point < num_edges {
            x = b.interpolate(y);
            update_span(&mut xp, x);

            // If this edge ends beyond the current row, find the x-intercept
            // where it exits the row
            let p1 = b.points[b.current_point + 1];
            if p1.y > f64::from(y1) {
                x = b.interpolate(y1);
                update_span(&mut xp, x);
                break;
            } else if b.current_point == num_edges - 1 {
                // For last edge, consider x-intercept at the end of the edge.
                x = p1.x;
                update_span(&mut xp, x);
            }
            b.current_point += 1;
        }
        tile_range.push(xp);
    }
    // Erase bounds in the active table whose current edge ends inside this row,
    // or there are no more edges
    active_bounds.retain(|bound| {
        !(bound.current_point == bound.points.len() - 1 && bound.points[bound.current_point].y <= f64::from(y1))
    });
    // Sort the X-extents of each crossing bound by x_min, x_max
    tile_range.sort_by_key(|span| (span.xmin, span.xmax));

    tile_range
}

/// The geometry visitor that builds the edge table, mapping each point through
/// `project`.
struct BuildBoundsMap<P> {
    zoom: i32,
    project: P,
}

impl<E, P: Fn(Point<f64>) -> Result<Point<f64>, E>> BuildBoundsMap<P> {
    /// The world's width in tiles.
    fn max_tile(&self) -> i32 {
        1i32.wrapping_shl(self.zoom as u32)
    }

    fn build_table(&self, points: &[Coord<f64>], et: &mut BoundsMap, closed: bool) -> Result<(), E> {
        let mut projected_points: PointList = Vec::with_capacity(points.len());
        for &p in points {
            projected_points.push((self.project)(Point::from(p))?);
        }
        build_bounds_map(&mut projected_points, self.max_tile() as u32, et, closed);
        Ok(())
    }

    fn build_polygon_table(&self, polygon: &Polygon<f64>, et: &mut BoundsMap) -> Result<(), E> {
        for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
            self.build_table(&ring.0, et, true)?;
        }
        Ok(())
    }

    /// Adds `p` as a bound of one zero-length edge.
    fn point(&self, p: Coord<f64>, et: &mut BoundsMap) -> Result<(), E> {
        let mut bnd = Bound::default();
        let point = (self.project)(Point::from(p))?;
        bnd.points.extend([point, point]);
        bnd.winding = false;
        let y = start_row(point.y, f64::from(self.max_tile()));
        et.entry(y).or_default().push(bnd);
        Ok(())
    }

    fn multi_point(&self, points: &geo_types::MultiPoint<f64>, et: &mut BoundsMap) -> Result<(), E> {
        for p in points {
            self.point(p.0, et)?;
        }
        Ok(())
    }

    fn apply(&self, geom: &Geometry<f64>) -> Result<BoundsMap, E> {
        let mut et = BoundsMap::new();
        match geom {
            Geometry::GeometryCollection(_) => {}
            Geometry::Point(p) => self.point(p.0, &mut et)?,
            Geometry::MultiPoint(points) => self.multi_point(points, &mut et)?,
            Geometry::Line(line) => self.build_table(&[line.start, line.end], &mut et, false)?,
            Geometry::LineString(line) => self.build_table(&line.0, &mut et, false)?,
            Geometry::MultiLineString(lines) => {
                for line in lines {
                    self.build_table(&line.0, &mut et, false)?;
                }
            }
            Geometry::Rect(rect) => self.build_polygon_table(&rect.to_polygon(), &mut et)?,
            Geometry::Triangle(triangle) => self.build_polygon_table(&triangle.to_polygon(), &mut et)?,
            Geometry::Polygon(polygon) => self.build_polygon_table(polygon, &mut et)?,
            Geometry::MultiPolygon(polygons) => {
                for polygon in polygons {
                    self.build_polygon_table(polygon, &mut et)?;
                }
            }
        }
        Ok(et)
    }
}

type TileSpans = VecDeque<(i32, i32)>;

/// Implements a modified scan-line algorithm to provide a streaming interface
/// for tile cover on arbitrary shapes. A `BoundsMap` is generated from the
/// input geometry where each tuple indicates the set of Bounds that start at a
/// y tile coordinate. Each bound represents a chain of edges from a local
/// y-minima to a local y-maxima. For each row, the `active_bounds` list
/// aggregates all bounds that enter into or begin in that row. This running
/// list of bounds is scanned, capturing the x-coordinates spanned by edges in
/// a bound until the bound exits the row (or ends). The result is a set of
/// (possibly overlapping) min,max pairs of x coordinates (spans). In the
/// simplest case a span represents the x-coordinates at which a single edge
/// intersects the top and bottom of a tile row. Interior tiles of a polygon
/// are captured by merging spans using the non-zero rule. The result of a scan
/// using `next_row` is a list of spans (`tile_x_spans`) of x-coordinates that
/// includes edges and interiors of polygons. `next()` returns a tileID for each
/// x-coordinate in `first..second` of each span in `tile_x_spans`.
pub(crate) struct ScanCover {
    zoom: i32,
    is_closed: bool,

    /// The bounds map's entries not yet moved into `active_bounds`, in key
    /// order.
    current_bounds: Peekable<mln_style::collections::IntoIter<u32, Bounds>>,
    /// List of bounds that begin at or before `tile_y`
    active_bounds: Bounds,

    tile_x_spans: TileSpans,
    tile_y: u32,
    tile_x: i32,
}

impl ScanCover {
    /// The cover at zoom `z` of `geom` in tile coordinates.
    pub(crate) fn new(z: i32, geom: &Geometry<f64>) -> ScanCover {
        let Ok(this) = Self::build(z, geom, Ok::<_, Infallible>);
        this
    }

    /// The cover at zoom `z` of `geom` in the world square, which spans 0 to
    /// 1 on both axes.
    #[cfg(feature = "sqlite")]
    pub(crate) fn new_in_world_square(z: i32, geom: &Geometry<f64>) -> ScanCover {
        let scale = 2f64.powi(z);
        let Ok(this) = Self::build(z, geom, |p: Point<f64>| Ok::<_, Infallible>(Point::new(p.x * scale, p.y * scale)));
        this
    }

    /// The cover at zoom `z` of `geom` in longitudes and latitudes, or an
    /// error for a point that isn't a valid `LatLng`.
    pub(crate) fn new_projected(z: i32, geom: &Geometry<f64>) -> Result<ScanCover, Error> {
        Self::build(z, geom, |p: Point<f64>| Ok(Projection::project_zoom(&LatLng::new(p.y, p.x)?, z)))
    }

    fn build<E>(
        z: i32,
        geom: &Geometry<f64>,
        project: impl Fn(Point<f64>) -> Result<Point<f64>, E>,
    ) -> Result<ScanCover, E> {
        let is_closed = to_feature_type(Some(geom)) == FeatureType::Polygon;

        let bounds_map = BuildBoundsMap { zoom: z, project }.apply(geom)?;
        let empty = bounds_map.is_empty();
        let mut this = ScanCover {
            zoom: z,
            is_closed,
            current_bounds: bounds_map.into_iter().peekable(),
            active_bounds: Bounds::new(),
            tile_x_spans: TileSpans::new(),
            tile_y: 0,
            tile_x: 0,
        };
        if empty {
            return Ok(this);
        }

        // Initialize the active edge table, and current row span
        this.tile_y = 0;
        this.next_row();
        if let Some(&(first, _)) = this.tile_x_spans.front() {
            this.tile_x = first;
        }
        Ok(this)
    }

    /// Aggregate all Bounds that start in or enter into the next `tile_y` row.
    /// Multi-geoms may have discontinuity in the `BoundsMap`, so skip forward to
    /// the next `tile_y` row when the current/next row has no more bounds in it.
    /// Use `scan_row` to generate the x spans. Merge spans to avoid
    /// duplicate tiles in `ScanCover::next()`. For closed geometry, use the
    /// non-zero rule to expand (fill) tiles between pairs of spans.
    fn next_row(&mut self) {
        // Update `active_bounds` for the next row
        if let Some(&(first, _)) = self.current_bounds.peek()
            && self.active_bounds.is_empty()
            && first > self.tile_y
        {
            // For multi-geoms: use the next row with an edge table starting point
            self.tile_y = first;
        }
        let tile_y = self.tile_y;
        if let Some((_, bounds)) = self.current_bounds.next_if(|&(first, _)| first == tile_y) {
            self.active_bounds.extend(bounds);
        }
        // Scan the active bounds and update `tile_x_spans` with x_min, x_max pairs
        let xps = scan_row(self.tile_y, &mut self.active_bounds);
        if xps.is_empty() {
            return;
        }

        let mut x_min = xps[0].xmin;
        let mut x_max = xps[0].xmax;
        let mut nz_rule: i32 = if xps[0].winding { 1 } else { -1 };
        for xp in &xps[1..] {
            if (!self.is_closed || nz_rule == 0) && xp.xmin > x_max && xp.xmax >= x_max {
                self.tile_x_spans.push_back((x_min, x_max));
                x_min = xp.xmin;
            }
            nz_rule += if xp.winding { 1 } else { -1 };
            x_max = std::cmp::max(x_max, xp.xmax);
        }
        self.tile_x_spans.push_back((x_min, x_max));
    }

    #[must_use]
    pub(crate) fn has_next(&self) -> bool {
        match self.tile_x_spans.front() {
            Some(&(_, second)) => self.tile_x < second && self.tile_y < 1u32.wrapping_shl(self.zoom as u32),
            None => false,
        }
    }
}

impl Iterator for ScanCover {
    type Item = UnwrappedTileID;

    fn next(&mut self) -> Option<UnwrappedTileID> {
        if !self.has_next() {
            return None;
        }

        let x = self.tile_x;
        let y = self.tile_y;
        self.tile_x += 1;
        if self.tile_x_spans.front().is_some_and(|&(_, end)| self.tile_x >= end) {
            self.tile_x_spans.pop_front();
            if self.tile_x_spans.is_empty() {
                self.tile_y = self.tile_y.wrapping_add(1);
                self.next_row();
            }
            if let Some(&(first, _)) = self.tile_x_spans.front() {
                self.tile_x = first;
            }
        }
        // `zoom` came from a `u8`.
        Some(UnwrappedTileID::new(self.zoom as u8, i64::from(x), i64::from(y)))
    }
}

#[cfg(test)]
mod tests {
    use geo_types::{Geometry, LineString, MultiLineString};

    use super::ScanCover;

    /// The `(x, y)` tiles at zoom 4 that cover `geom`, with `x` unwrapped.
    fn cover(geom: &Geometry<f64>) -> Vec<(i64, u32)> {
        ScanCover::new(4, geom)
            .map(|id| (i64::from(id.canonical.x) + i64::from(id.wrap) * 16, id.canonical.y))
            .collect()
    }

    #[test]
    fn a_span_inside_another_keeps_the_outer_end() {
        let lines = Geometry::MultiLineString(MultiLineString(vec![
            LineString::from(vec![(0.5, 0.5), (9.5, 0.5)]),
            LineString::from(vec![(2.5, 0.5), (3.5, 0.5)]),
        ]));
        assert_eq!(cover(&lines), (0..10).map(|x| (x, 0)).collect::<Vec<_>>());
    }

    #[test]
    fn a_span_west_of_the_world_ends_at_its_last_tile() {
        let line = Geometry::LineString(LineString::from(vec![(-5.5, 0.5), (-3.5, 0.5)]));
        assert_eq!(cover(&line), vec![(-6, 0), (-5, 0), (-4, 0)]);
    }
}