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
// mapgrid.rs
//
// Copyright (c) 2019-2020  Minnesota Department of Transportation
//
//! BBox, TileId and MapGrid structs.
//!
use crate::error::Error;
use pointy::{Pt64, Transform64};
use std::fmt;

/// A bounding box is an axis-aligned rectangle.
///
/// It is defined by two corners: north_west and south_east.
///
/// # Example
/// ```
/// use mvt::BBox;
/// use pointy::Pt64;
///
/// let north_west = Pt64(-10.0, 0.0);
/// let south_east = Pt64(10.0, 8.0);
/// let bbox = BBox::new(north_west, south_east);
/// ```
#[derive(Clone, Copy, Debug)]
pub struct BBox {
    north_west: Pt64,
    south_east: Pt64,
}

/// A tile ID identifies a tile on a map grid at a specific zoom level.
///
/// It uses XYZ addressing, with X increasing from west to east and Y increasing
/// from north to south.  The X and Y values can range from 0 to
/// 2<sup>Z</sup>-1.
#[derive(Clone, Copy, Debug)]
pub struct TileId {
    x: u32, // not public to prevent invalid values being created
    y: u32,
    z: u32,
}

/// A map grid is used to address [tile]s on a map.
///
/// The grid should be in projected coördinates.  Use `default()` for
/// [Web Mercator].
///
/// [tile]: struct.Tile.html
/// [Web Mercator]: https://en.wikipedia.org/wiki/Web_Mercator_projection
#[derive(Clone, Debug)]
pub struct MapGrid {
    /// Spatial reference ID
    srid: i32,
    /// Bounding box
    bbox: BBox,
}

impl TileId {
    /// Get the X value.
    pub fn x(&self) -> u32 {
        self.x
    }

    /// Get the Y value.
    pub fn y(&self) -> u32 {
        self.y
    }

    /// Get the Z (zoom) value.
    pub fn z(&self) -> u32 {
        self.z
    }
}

impl fmt::Display for TileId {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}/{}/{}", self.z, self.x, self.y)
    }
}

impl BBox {
    /// Create a new bounding box.
    ///
    /// * `north_west` The north-west (top-left) corner of the bounds.
    /// * `south_east` The south-east (bottom-right) corner of the bounds.
    pub fn new(north_west: Pt64, south_east: Pt64) -> Self {
        BBox {
            north_west,
            south_east,
        }
    }

    /// Get the minimum X value.
    pub fn x_min(&self) -> f64 {
        self.north_west.x().min(self.south_east.x())
    }

    /// Get the maximum X value.
    pub fn x_max(&self) -> f64 {
        self.north_west.x().max(self.south_east.x())
    }

    /// Get the minimum Y value.
    pub fn y_min(&self) -> f64 {
        self.north_west.y().min(self.south_east.y())
    }

    /// Get the maximum Y value.
    pub fn y_max(&self) -> f64 {
        self.north_west.y().max(self.south_east.y())
    }

    /// Get the X span.
    fn x_span(&self) -> f64 {
        self.south_east.x() - self.north_west.x()
    }

    /// Get the Y span.
    fn y_span(&self) -> f64 {
        self.south_east.y() - self.north_west.y()
    }
}

/// Scales at each zoom level.
const SCALE: [f64; 32] = [
    // Someday, we can use const fn...
    1.0 / (1 << 0) as f64,
    1.0 / (1 << 1) as f64,
    1.0 / (1 << 2) as f64,
    1.0 / (1 << 3) as f64,
    1.0 / (1 << 4) as f64,
    1.0 / (1 << 5) as f64,
    1.0 / (1 << 6) as f64,
    1.0 / (1 << 7) as f64,
    1.0 / (1 << 8) as f64,
    1.0 / (1 << 9) as f64,
    1.0 / (1 << 10) as f64,
    1.0 / (1 << 11) as f64,
    1.0 / (1 << 12) as f64,
    1.0 / (1 << 13) as f64,
    1.0 / (1 << 14) as f64,
    1.0 / (1 << 15) as f64,
    1.0 / (1 << 16) as f64,
    1.0 / (1 << 17) as f64,
    1.0 / (1 << 18) as f64,
    1.0 / (1 << 19) as f64,
    1.0 / (1 << 20) as f64,
    1.0 / (1 << 21) as f64,
    1.0 / (1 << 22) as f64,
    1.0 / (1 << 23) as f64,
    1.0 / (1 << 24) as f64,
    1.0 / (1 << 25) as f64,
    1.0 / (1 << 26) as f64,
    1.0 / (1 << 27) as f64,
    1.0 / (1 << 28) as f64,
    1.0 / (1 << 29) as f64,
    1.0 / (1 << 30) as f64,
    1.0 / (1 << 31) as f64,
];

impl TileId {
    /// Create a new TildId.
    ///
    /// If invalid, returns [Error::InvalidTid](enum.Error.html).
    pub fn new(x: u32, y: u32, z: u32) -> Result<Self, Error> {
        TileId::check_valid(x, y, z)?;
        Ok(TileId { x, y, z })
    }

    /// Check whether a tile ID is valid.
    fn check_valid(x: u32, y: u32, z: u32) -> Result<(), Error> {
        if z > 31 {
            return Err(Error::InvalidTid());
        }
        let s = 1 << z;
        if x < s && y < s {
            Ok(())
        } else {
            Err(Error::InvalidTid())
        }
    }
}

impl Default for MapGrid {
    fn default() -> Self {
        const HALF_SIZE_M: f64 = 20_037_508.342_789_248;
        const WEB_MERCATOR_SRID: i32 = 3857;
        let srid = WEB_MERCATOR_SRID;
        let north_west = Pt64(-HALF_SIZE_M, HALF_SIZE_M);
        let south_east = Pt64(HALF_SIZE_M, -HALF_SIZE_M);
        let bbox = BBox::new(north_west, south_east);
        MapGrid { srid, bbox }
    }
}

impl MapGrid {
    /// Create a new map grid.
    ///
    /// * `srid` Spatial reference ID.
    /// * `bbox` Bounding box.
    pub fn new(srid: i32, bbox: BBox) -> Self {
        MapGrid { srid, bbox }
    }

    /// Get the spatial reference ID.
    pub fn srid(&self) -> i32 {
        self.srid
    }

    /// Get the bounding box of the grid.
    pub fn bbox(&self) -> BBox {
        self.bbox
    }

    /// Get the bounding box of a tile ID.
    pub fn tile_bbox(&self, tid: TileId) -> BBox {
        let tz = SCALE[tid.z as usize];
        let sx = self.bbox.x_span() * tz;
        let sy = self.bbox.y_span() * tz;
        let tx = self.bbox.north_west.x();
        let ty = self.bbox.north_west.y();
        let t = Transform64::with_scale(sx, sy).translate(tx, ty);
        let tidx = f64::from(tid.x);
        let tidy = f64::from(tid.y);
        let north_west = t * Pt64(tidx, tidy);
        let south_east = t * Pt64(tidx + 1.0, tidy + 1.0);
        BBox::new(north_west, south_east)
    }

    /// Get the transform to coördinates in 0 to 1 range.
    pub fn tile_transform(&self, tid: TileId) -> Transform64 {
        let tx = self.bbox.north_west.x();
        let ty = self.bbox.north_west.y();
        let tz = f64::from(1 << tid.z);
        let sx = tz / self.bbox.x_span();
        let sy = tz / self.bbox.y_span();
        Transform64::with_translate(-tx, -ty)
            .scale(sx, sy)
            .translate(-f64::from(tid.x), -f64::from(tid.y))
    }
}

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

    #[test]
    fn test_tile_bbox() {
        let g = MapGrid::default();
        let tid = TileId::new(0, 0, 0).unwrap();
        let b = g.tile_bbox(tid);
        assert_eq!(
            b.north_west,
            Pt64(-20037508.3427892480, 20037508.3427892480)
        );
        assert_eq!(
            b.south_east,
            Pt64(20037508.3427892480, -20037508.3427892480)
        );

        let tid = TileId::new(0, 0, 1).unwrap();
        let b = g.tile_bbox(tid);
        assert_eq!(
            b.north_west,
            Pt64(-20037508.3427892480, 20037508.3427892480)
        );
        assert_eq!(b.south_east, Pt64(0.0, 0.0));

        let tid = TileId::new(1, 1, 1).unwrap();
        let b = g.tile_bbox(tid);
        assert_eq!(b.north_west, Pt64(0.0, 0.0));
        assert_eq!(
            b.south_east,
            Pt64(20037508.3427892480, -20037508.3427892480)
        );

        let tid = TileId::new(246, 368, 10).unwrap();
        let b = g.tile_bbox(tid);
        assert_eq!(b.north_west, Pt64(-10410111.756214727, 5635549.221409475));
        assert_eq!(b.south_east, Pt64(-10370975.997732716, 5596413.462927466));
    }
    #[test]
    fn test_tile_transform() {
        let g = MapGrid::default();
        let tid = TileId::new(0, 0, 0).unwrap();
        let t = g.tile_transform(tid);
        assert_eq!(
            Pt64(0.0, 0.0),
            t * Pt64(-20037508.3427892480, 20037508.3427892480)
        );
        assert_eq!(
            Pt64(1.0, 1.0),
            t * Pt64(20037508.3427892480, -20037508.3427892480)
        );

        let tid = TileId::new(0, 0, 1).unwrap();
        let t = g.tile_transform(tid);
        assert_eq!(
            Pt64(0.0, 0.0),
            t * Pt64(-20037508.3427892480, 20037508.3427892480)
        );
        assert_eq!(Pt64(1.0, 1.0), t * Pt64(0.0, 0.0));

        let tid = TileId::new(1, 1, 1).unwrap();
        let t = g.tile_transform(tid);
        assert_eq!(Pt64(0.0, 0.0), t * Pt64(0.0, 0.0));
        assert_eq!(
            Pt64(1.0, 1.0),
            t * Pt64(20037508.3427892480, -20037508.3427892480)
        );

        let tid = TileId::new(246, 368, 10).unwrap();
        let t = g.tile_transform(tid);
        assert_eq!(
            Pt64(0.0, 0.0),
            t * Pt64(-10410111.756214727, 5635549.221409475)
        );
        assert_eq!(
            Pt64(1.0, 0.9999999999999716),
            t * Pt64(-10370975.997732716, 5596413.462927466)
        );
    }
}