Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / map / src / main / rust / tests / real_archive / fixture.rs
fixture.rs315 lines · 11.6 KiBRaw
| 1 | //! Synthetic `.mamaps` archives for the real-archive tests. |
| 2 | //! |
| 3 | //! The planet tests in `real_archive.rs` run against these archives by |
| 4 | //! default (temp dir, built in-test through the same `StreamWriter` the |
| 5 | //! generator uses); setting `MAMAPS_REAL_ARCHIVE` switches them back to |
| 6 | //! the real planet file. Nothing here reads fixtures from disk. |
| 7 | |
| 8 | use std::path::{Path, PathBuf}; |
| 9 | |
| 10 | use tilecodec::mamaps::archive::{ |
| 11 | self as sidecar, ArchiveEntry, GRAPH_MAGIC, GRAPH_VERSION_MIN, TRANSIT_MAGIC, |
| 12 | }; |
| 13 | use tilecodec::mamaps::body::{ |
| 14 | BuildingAttrs, Carriageway, Feature, Heightmap, LaneTurns, Layer as BodyLayer, |
| 15 | MarkingConvention, Part, GEOM_LINE, GEOM_POINT, GEOM_POLYGON, NAME_NONE, WINDING_OUTER, |
| 16 | }; |
| 17 | use tilecodec::mamaps::dict; |
| 18 | use tilecodec::mamaps::header::Header; |
| 19 | use tilecodec::mamaps::write::{Options, StreamWriter}; |
| 20 | use tilecodec::pmtiles::tile_id; |
| 21 | |
| 22 | /// Build id stamped on every synthetic archive (and its sidecar footer). |
| 23 | pub const BUILD_ID: u64 = 0x5eed_5eed_5eed_5eed; |
| 24 | |
| 25 | const ENV: &str = "MAMAPS_REAL_ARCHIVE"; |
| 26 | |
| 27 | /// The planet archive `MAMAPS_REAL_ARCHIVE` names, if any. |
| 28 | pub fn planet_path() -> Option<PathBuf> { |
| 29 | match std::env::var(ENV) { |
| 30 | Ok(p) if !p.trim().is_empty() && Path::new(&p).is_file() => Some(PathBuf::from(p)), |
| 31 | _ => None, |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | /// The archive under test: the planet file when `MAMAPS_REAL_ARCHIVE` |
| 36 | /// names one (`planet == true`), else the synthetic archive `build` |
| 37 | /// writes to a temp file. |
| 38 | pub fn acquire(tag: &str, build: impl FnOnce(&Path)) -> (PathBuf, bool) { |
| 39 | match planet_path() { |
| 40 | Some(path) => (path, true), |
| 41 | None => { |
| 42 | let path = temp_path(tag); |
| 43 | build(&path); |
| 44 | (path, false) |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | /// Slippy-map tile containing (lat, lon) at zoom `z`. |
| 50 | pub fn tile_of(lat: f64, lon: f64, z: u8) -> (u32, u32) { |
| 51 | let n = (1u64 << z) as f64; |
| 52 | let x = ((lon + 180.0) / 360.0 * n).floor(); |
| 53 | let lat_r = lat.to_radians(); |
| 54 | let y = |
| 55 | ((1.0 - (lat_r.tan() + 1.0 / lat_r.cos()).ln() / std::f64::consts::PI) / 2.0 * n).floor(); |
| 56 | let max = n as u32 - 1; |
| 57 | ((x as u32).min(max), (y as u32).min(max)) |
| 58 | } |
| 59 | |
| 60 | /// A temp `.mamaps` path unique to this test process and `tag`. |
| 61 | pub fn temp_path(tag: &str) -> PathBuf { |
| 62 | let path = |
| 63 | std::env::temp_dir().join(format!("synthetic-archive-{tag}-{}.mamaps", std::process::id())); |
| 64 | let _ = std::fs::remove_file(&path); |
| 65 | path |
| 66 | } |
| 67 | |
| 68 | fn kind(name: &str) -> u16 { |
| 69 | map_renderer::style::kind_id(name).unwrap_or_else(|| panic!("schema kind {name}")) |
| 70 | } |
| 71 | |
| 72 | fn feat(kind: u16, geom_type: u8, name_idx: u16) -> Feature { |
| 73 | Feature { |
| 74 | kind, |
| 75 | kind_detail: dict::NONE, |
| 76 | geom_type, |
| 77 | flags: 0, |
| 78 | name_idx, |
| 79 | parts_offset: 0, |
| 80 | part_count: 1, |
| 81 | transit_color: 0, |
| 82 | transit_ordinal: 0, |
| 83 | transit_lanes: 0, |
| 84 | transit_taper: 0, |
| 85 | lane_count: 0, |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | fn push(layer: &mut BodyLayer, mut f: Feature, pts: &[(i16, i16)]) { |
| 90 | f.parts_offset = layer.parts.len() as u32; |
| 91 | layer.parts.push(Part { |
| 92 | coord_start: layer.coords.len() as u32, |
| 93 | point_count: pts.len() as u32, |
| 94 | winding: WINDING_OUTER, |
| 95 | }); |
| 96 | layer.coords.extend_from_slice(pts); |
| 97 | layer.features.push(f); |
| 98 | } |
| 99 | |
| 100 | /// A tile body carrying every basemap layer the style draws (all but |
| 101 | /// `traffic`, which the planet writer no longer emits either), plus the |
| 102 | /// optional side tables the reader decodes: turn lanes, carriageways, |
| 103 | /// building attrs, region links and a DEM heightmap peaking at `peak` |
| 104 | /// metres. |
| 105 | pub fn rich_body(peak: i32) -> tilecodec::mamaps::body::Body { |
| 106 | let mut body = tilecodec::mamaps::body::Body::new(4096); |
| 107 | body.names = vec!["Grid Street".to_string(), "Synthetic City".to_string(), "Cafe".to_string()]; |
| 108 | |
| 109 | let mut landtype = BodyLayer::new(dict::LAYER_LANDTYPE); |
| 110 | push( |
| 111 | &mut landtype, |
| 112 | feat(dict::NONE, GEOM_POLYGON, NAME_NONE), |
| 113 | &[(0, 0), (4096, 0), (4096, 4096), (0, 4096)], |
| 114 | ); |
| 115 | push( |
| 116 | &mut landtype, |
| 117 | feat(kind("lake"), GEOM_POLYGON, NAME_NONE), |
| 118 | &[(500, 3000), (1100, 3000), (1100, 3400), (500, 3400)], |
| 119 | ); |
| 120 | body.layers.push(landtype); |
| 121 | |
| 122 | let mut roads = BodyLayer::new(dict::LAYER_ROADS); |
| 123 | let mut road = feat(kind("major_road"), GEOM_LINE, 1); |
| 124 | road.lane_count = 2; |
| 125 | push(&mut roads, road, &[(100, 100), (1500, 900), (2600, 1800), (3900, 2700)]); |
| 126 | body.layers.push(roads); |
| 127 | |
| 128 | let mut boundaries = BodyLayer::new(dict::LAYER_BOUNDARIES); |
| 129 | push( |
| 130 | &mut boundaries, |
| 131 | feat(kind("region_area"), GEOM_POLYGON, NAME_NONE), |
| 132 | &[(200, 200), (3800, 200), (3800, 3800), (200, 3800)], |
| 133 | ); |
| 134 | body.layers.push(boundaries); |
| 135 | |
| 136 | let mut buildings = BodyLayer::new(dict::LAYER_BUILDINGS); |
| 137 | push( |
| 138 | &mut buildings, |
| 139 | feat(kind("building"), GEOM_POLYGON, NAME_NONE), |
| 140 | &[(0, 0), (1000, 0), (1000, 1000), (0, 1000), (0, 0)], |
| 141 | ); |
| 142 | body.layers.push(buildings); |
| 143 | |
| 144 | let mut places = BodyLayer::new(dict::LAYER_PLACES); |
| 145 | push(&mut places, feat(kind("locality"), GEOM_POINT, 2), &[(2048, 2048)]); |
| 146 | body.layers.push(places); |
| 147 | |
| 148 | let mut poi = BodyLayer::new(dict::LAYER_POI); |
| 149 | push(&mut poi, feat(kind("cafe"), GEOM_POINT, 3), &[(1024, 1024)]); |
| 150 | body.layers.push(poi); |
| 151 | |
| 152 | let mut transit = BodyLayer::new(dict::LAYER_TRANSIT); |
| 153 | let mut line = feat(kind("rail"), GEOM_LINE, NAME_NONE); |
| 154 | line.transit_color = 0x00E3_1B23; |
| 155 | line.transit_lanes = 1; |
| 156 | line.transit_taper = 255; |
| 157 | push(&mut transit, line, &[(0, 4000), (4096, 200)]); |
| 158 | body.layers.push(transit); |
| 159 | |
| 160 | let mut junction = BodyLayer::new(dict::LAYER_JUNCTION); |
| 161 | push( |
| 162 | &mut junction, |
| 163 | feat(dict::NONE, GEOM_LINE, NAME_NONE), |
| 164 | &[(0, 100), (500, 100), (1000, 300)], |
| 165 | ); |
| 166 | body.layers.push(junction); |
| 167 | |
| 168 | let mut safety = BodyLayer::new(dict::LAYER_SAFETY); |
| 169 | push(&mut safety, feat(kind("speed_camera"), GEOM_POINT, NAME_NONE), &[(3000, 3000)]); |
| 170 | body.layers.push(safety); |
| 171 | |
| 172 | body.ids = vec![(dict::LAYER_BOUNDARIES, vec![4242])]; |
| 173 | body.turn_lanes = |
| 174 | vec![(dict::LAYER_ROADS, vec![LaneTurns { forward: vec![0b0110], backward: Vec::new() }])]; |
| 175 | body.buildings = vec![( |
| 176 | dict::LAYER_BUILDINGS, |
| 177 | vec![BuildingAttrs { |
| 178 | height: 120, |
| 179 | min_height: 0, |
| 180 | roof_height: 0, |
| 181 | roof_shape: 0, |
| 182 | roof_direction: 0, |
| 183 | roof_orientation: 0, |
| 184 | building_colour: 0, |
| 185 | roof_colour: 0, |
| 186 | }], |
| 187 | )]; |
| 188 | body.carriageways = |
| 189 | vec![(dict::LAYER_ROADS, vec![Carriageway { forward: 1, backward: 1, solid_dividers: 0 }])]; |
| 190 | body.convention = Some(MarkingConvention { left_hand: false, yellow_centre: false }); |
| 191 | body.region_links = vec![(dict::LAYER_PLACES, vec![4242])]; |
| 192 | body.heightmap = Some(heightmap(4, 0, peak)); |
| 193 | body |
| 194 | } |
| 195 | |
| 196 | /// A `dim` x `dim` heightmap rising by row from `lo` to `hi` metres. |
| 197 | pub fn heightmap(dim: u16, lo: i32, hi: i32) -> Heightmap { |
| 198 | let mut samples = Vec::with_capacity(dim as usize * dim as usize); |
| 199 | for row in 0..dim { |
| 200 | let metres = |
| 201 | if dim > 1 { lo + (hi - lo) * i32::from(row) / i32::from(dim - 1) } else { lo }; |
| 202 | for _ in 0..dim { |
| 203 | samples.push((metres + 32768) as u16); |
| 204 | } |
| 205 | } |
| 206 | Heightmap { dim, samples } |
| 207 | } |
| 208 | |
| 209 | /// A rich body whose heightmap spans `lo..hi` metres (DEM tests). |
| 210 | pub fn dem_body(lo: i32, hi: i32) -> tilecodec::mamaps::body::Body { |
| 211 | let mut body = rich_body(hi); |
| 212 | body.heightmap = Some(heightmap(8, lo, hi)); |
| 213 | body |
| 214 | } |
| 215 | |
| 216 | /// Write `tiles` (any order; the writer needs ascending tile ids) as a |
| 217 | /// tiles-only archive at `path` and return the path. |
| 218 | pub fn write_archive( |
| 219 | path: &Path, |
| 220 | tiles: &[(u8, u32, u32, tilecodec::mamaps::body::Body)], |
| 221 | ) -> PathBuf { |
| 222 | let mut rows: Vec<(u64, &tilecodec::mamaps::body::Body)> = |
| 223 | tiles.iter().map(|(z, x, y, b)| (tile_id(*z, u64::from(*x), u64::from(*y)), b)).collect(); |
| 224 | rows.sort_by_key(|(id, _)| *id); |
| 225 | // Distinct cities share the z0 tile; the writer wants each id once. |
| 226 | rows.dedup_by_key(|(id, _)| *id); |
| 227 | let mut writer = StreamWriter::new(Options { |
| 228 | build_id: BUILD_ID, |
| 229 | rings_validated: true, |
| 230 | ..Options::default() |
| 231 | }) |
| 232 | .expect("writer options"); |
| 233 | for (id, body) in rows { |
| 234 | writer.append(id, body).expect("append tile"); |
| 235 | } |
| 236 | writer.finish_to_path(path).expect("finish archive"); |
| 237 | path.to_path_buf() |
| 238 | } |
| 239 | |
| 240 | fn graph_meta(node_count: u64, edge_count: u64) -> Vec<u8> { |
| 241 | let mut out = Vec::new(); |
| 242 | out.extend_from_slice(&GRAPH_MAGIC.to_le_bytes()); |
| 243 | out.extend_from_slice(&GRAPH_VERSION_MIN.to_le_bytes()); |
| 244 | out.extend_from_slice(&node_count.to_le_bytes()); |
| 245 | out.extend_from_slice(&edge_count.to_le_bytes()); |
| 246 | out.extend_from_slice(&0u64.to_le_bytes()); |
| 247 | out.extend_from_slice(&0u64.to_le_bytes()); |
| 248 | out |
| 249 | } |
| 250 | |
| 251 | fn poi_header(magic: &[u8; 4], count: u32, len: usize) -> Vec<u8> { |
| 252 | let mut out = vec![0u8; len]; |
| 253 | out[0..4].copy_from_slice(magic); |
| 254 | out[8..12].copy_from_slice(&count.to_le_bytes()); |
| 255 | out |
| 256 | } |
| 257 | |
| 258 | /// The smallest payload set `ArchiveView` accepts for every kind the app |
| 259 | /// reads: a one-node graph, one POI record, and a header-only transit |
| 260 | /// pack. Counts are the validators' own arithmetic (see the tilecodec |
| 261 | /// archive tests, whose fixtures these mirror). |
| 262 | fn sidecar_payloads() -> Vec<(u8, Vec<u8>, u64)> { |
| 263 | let mut transit = vec![0u8; 80 + 20 * 16]; |
| 264 | transit[0..4].copy_from_slice(&TRANSIT_MAGIC.to_le_bytes()); |
| 265 | transit[4..8].copy_from_slice(&7u32.to_le_bytes()); |
| 266 | transit[8..12].copy_from_slice(&20u32.to_le_bytes()); |
| 267 | vec![ |
| 268 | (sidecar::ARCHIVE_KIND_GRAPH_META, graph_meta(1, 0), 0), |
| 269 | (sidecar::ARCHIVE_KIND_GRAPH_NODES, vec![0u8; 24], 1), |
| 270 | (sidecar::ARCHIVE_KIND_GRAPH_EDGES, vec![0u8; 16], 0), |
| 271 | (sidecar::ARCHIVE_KIND_GRAPH_INTERMEDIATE, vec![0u8; 26], 0), |
| 272 | (sidecar::ARCHIVE_KIND_GRAPH_NAMES, b"\0Grid Street\0".to_vec(), 0), |
| 273 | (sidecar::ARCHIVE_KIND_GRAPH_LANES, vec![0u8; 12], 0), |
| 274 | (sidecar::ARCHIVE_KIND_GRAPH_ELEVATION, vec![0u8; 2], 0), |
| 275 | (sidecar::ARCHIVE_KIND_POI_INDEX, vec![0u8; 14], 0), |
| 276 | (sidecar::ARCHIVE_KIND_POI_NAMES, b"\0Cafe\0".to_vec(), 0), |
| 277 | (sidecar::ARCHIVE_KIND_POI_ATTRS, poi_header(b"MAPA", 1, 12), 0), |
| 278 | (sidecar::ARCHIVE_KIND_POI_SPATIAL, poi_header(b"PSP1", 1, 32), 0), |
| 279 | (sidecar::ARCHIVE_KIND_POI_WORDS, poi_header(b"PNI1", 1, 16), 0), |
| 280 | (sidecar::ARCHIVE_KIND_TRANSIT, transit, 0), |
| 281 | (sidecar::ARCHIVE_KIND_GRAPH_OVERLAY, b"MOVL".to_vec(), 0), |
| 282 | (sidecar::ARCHIVE_KIND_POI_REGION, poi_header(b"PRG1", 1, 20), 0), |
| 283 | ] |
| 284 | } |
| 285 | |
| 286 | /// Append the sidecar payloads to the tiles-only archive at `path` |
| 287 | /// (header `file_len` patched to cover the whole file). |
| 288 | pub fn append_sidecar(path: &Path) { |
| 289 | let mut out = std::fs::read(path).expect("read tiles archive"); |
| 290 | let mut header = Header::parse(&out).expect("tile header parses"); |
| 291 | assert_eq!(header.build_id, BUILD_ID); |
| 292 | while out.len() as u64 % sidecar::ARCHIVE_ALIGN != 0 { |
| 293 | out.push(0); |
| 294 | } |
| 295 | let mut entries = Vec::new(); |
| 296 | for (kind, bytes, extra) in sidecar_payloads() { |
| 297 | while out.len() as u64 % sidecar::ARCHIVE_ALIGN != 0 { |
| 298 | out.push(0); |
| 299 | } |
| 300 | let offset = out.len() as u64; |
| 301 | out.extend_from_slice(&bytes); |
| 302 | entries.push(ArchiveEntry { kind, flags: 0, offset, len: bytes.len() as u64, extra }); |
| 303 | } |
| 304 | while out.len() as u64 % sidecar::ARCHIVE_ALIGN != 0 { |
| 305 | out.push(0); |
| 306 | } |
| 307 | let dir_offset = out.len() as u64; |
| 308 | let (dir, footer) = sidecar::serialize_dir(&entries, BUILD_ID, dir_offset); |
| 309 | out.extend_from_slice(&dir); |
| 310 | out.extend_from_slice(&footer.serialize()); |
| 311 | header.file_len = out.len() as u64; |
| 312 | let head = header.serialize(); |
| 313 | out[..head.len()].copy_from_slice(&head); |
| 314 | std::fs::write(path, &out).expect("write full archive"); |
| 315 | } |