Repository Public BSD-3-Clause
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Maps9// File : Packages/ORIXAtlas/Tests/ORIXAtlasTests/StyleAndMeshTests.swift10// Module : ORIXAtlasTests11// Repository : https://git.spboucher.ai/orix-maps12// Created : 2026-11-2513// Last Modified : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import ORIXAtlas90import ORIXGeoCore91import ORIXMapStyle92import ORIXTileStore93import Testing9495@Suite struct StyleTests {96 @Test func layerTableFitsOnePassAndKeepsDrawOrder() {97 #expect(AtlasLayer.allCases.count <= AtlasStyleTable.passSize)98 #expect(AtlasLayer.allCases.map(\.rawValue) == Array(0..<UInt16(AtlasLayer.allCases.count)))99 // Order of the style document: land, land use, water, tunnels, buildings, roads, boundaries, bridges.100 let order: [AtlasLayer] = [.earth, .landuseResidential, .water, .landusePedestrian, .tunnelHighway, .building, .roadPath, .roadMinor, .roadHighway, .roadRail, .boundaryCountry, .bridgePath, .bridgeRail]101 #expect(zip(order, order.dropFirst()).allSatisfy { $0.rawValue < $1.rawValue })102 #expect(AtlasLayer.road(.bridge, .highway) == .bridgeHighway && AtlasLayer.road(.tunnel, .path) == .tunnelPath)103 #expect(AtlasLayer.roadMajor.road?.kind == .major && AtlasLayer.roadMajor.road?.structure == .surface)104 #expect(AtlasLayer.water.road == nil && AtlasLayer.water.geometry == .fill && AtlasLayer.waterwayRiver.geometry == .line && AtlasLayer.bridgeRail.geometry == .line)105 }106107 @Test func exponentialInterpolationMatchesTheStyleSpecification() {108 let stops: [(zoom: Double, value: Double)] = [(13, 4.5), (16, 13)]109 #expect(AtlasStyle.interpolate(stops, at: 12) == 4.5 && AtlasStyle.interpolate(stops, at: 17) == 13)110 // t = (1.6^(z - 13) - 1) / (1.6^3 - 1)111 let expected = 4.5 + (13 - 4.5) * (pow(1.6, 1.5) - 1) / (pow(1.6, 3) - 1)112 #expect(abs(AtlasStyle.interpolate(stops, at: 14.5, base: 1.6) - expected) < 1e-12)113 #expect(abs(AtlasStyle.interpolate(stops, at: 14.5) - 8.75) < 1e-12)114 #expect(AtlasStyle.interpolate([], at: 3) == 0)115 }116117 @Test func roadWidthsFollowTheThemeAndTheZoom() {118 let day = BuiltInThemes.day119 #expect(AtlasStyle.roadWidth(.highway, theme: day, zoom: 13) == 4.5)120 #expect(AtlasStyle.roadWidth(.highway, theme: day, zoom: 2.9) == 0)121 #expect(AtlasStyle.roadWidth(.minor, theme: day, zoom: 10.9) == 0 && AtlasStyle.roadWidth(.minor, theme: day, zoom: 16) == 7)122 #expect(AtlasStyle.roadWidth(.path, theme: day, zoom: 14) == 0 && AtlasStyle.roadWidth(.path, theme: BuiltInThemes.terrain, zoom: 14) > 0)123 #expect(abs(AtlasStyle.roadWidth(.highway, theme: BuiltInThemes.highContrast, zoom: 13) - 4.5 * 1.25) < 1e-12)124 #expect(abs(AtlasStyle.roadWidth(.major, theme: BuiltInThemes.transit, zoom: 13) - 3.2 * 0.9 * 0.8) < 1e-12)125 // Widths never shrink while zooming in, and the casing is always wider than the road it surrounds.126 for kind in RoadClass.allCases {127 var last = 0.0128 for z in stride(from: 0.0, through: 20, by: 0.25) {129 let w = AtlasStyle.roadWidth(kind, theme: day, zoom: z)130 #expect(w >= last - 1e-12)131 last = w132 let c = AtlasStyle.casingWidth(kind, theme: day, zoom: z)133 if c > 0 { #expect(c >= w + 1 - 1e-9) }134 }135 }136 var flat = day137 flat.roadCasings = false138 #expect(AtlasStyle.casingWidth(.highway, theme: flat, zoom: 14) == 0)139 }140141 @Test func tableHidesWhatTheThemeAndTheZoomHide() {142 let low = AtlasStyle.table(theme: BuiltInThemes.day, zoom: 4)143 #expect(low[.earth].color == SIMD4<Float>(Float(0xF3) / 255, Float(0xF0) / 255, Float(0xE8) / 255, 1))144 #expect(low.background == BuiltInThemes.day[.water])145 #expect(low[.building].color.w == 0 && low[.roadMinor].color.w == 0 && low[.roadHighway].color.w == 1)146 #expect(abs(low[.landcoverForest].color.w - 0.9) < 1e-6)147 #expect(low.casing(.roadHighway).color.w == 0)148 let high = AtlasStyle.table(theme: BuiltInThemes.day, zoom: 15)149 #expect(high[.landcoverForest].color.w == 0 && high[.building].color.w > 0.9 && high[.buildingOutline].width == 1)150 #expect(high.casing(.roadHighway).width > high[.roadHighway].width && high.casing(.roadPath).color.w == 0)151 // Premultiplied alpha.152 let wood = high[.landuseWood].color153 #expect(abs(wood.w - 0.85) < 1e-6 && abs(wood.x - Float(0xBF) / 255 * 0.85) < 1e-6)154 // Tunnels are tinted and their casing is translucent.155 #expect(high[.tunnelHighway].color != high[.roadHighway].color && abs(high.casing(.tunnelHighway).color.w - 0.45) < 1e-6)156 let minimal = AtlasStyle.table(theme: BuiltInThemes.minimal, zoom: 15)157 #expect(minimal[.building].color.w == 0)158 var bare = BuiltInThemes.day159 bare.showLandUse = false160 let t = AtlasStyle.table(theme: bare, zoom: 15)161 #expect(t[.landusePark].color.w == 0 && t[.landusePedestrian].color.w == 0 && t[.water].color.w == 1)162 // Every theme resolves at every zoom with finite values.163 for theme in BuiltInThemes.all {164 for z in stride(from: 0.0, through: 20, by: 0.5) {165 let table = AtlasStyle.table(theme: theme, zoom: z)166 #expect(table.base.count == 64 && table.casing.count == 64)167 #expect((table.base + table.casing).allSatisfy { $0.color.w >= 0 && $0.color.w <= 1 && $0.width.isFinite && $0.width >= 0 && $0.color.x <= $0.color.w + 1e-6 })168 }169 }170 }171172 @Test func roadClassification() {173 func layer(_ pairs: [(String, String)]) -> AtlasLayer? {174 AtlasStyle.roadLayer(attributes: Dictionary(uniqueKeysWithValues: pairs.map { ($0.0, VectorTile.Value.string($0.1)) }))175 }176 #expect(layer([("kind", "highway"), ("kind_detail", "motorway")]) == .roadHighway)177 #expect(layer([("kind", "highway"), ("kind_detail", "motorway_link"), ("is_link", "true")]) == .roadLink)178 #expect(layer([("kind", "major_road"), ("is_bridge", "true")]) == .bridgeMajor)179 #expect(layer([("kind", "minor_road"), ("kind_detail", "service"), ("is_tunnel", "true")]) == .tunnelService)180 #expect(layer([("kind", "minor_road"), ("kind_detail", "residential")]) == .roadMinor)181 #expect(layer([("kind", "path"), ("kind_detail", "footway")]) == .roadPath)182 #expect(layer([("kind", "path"), ("kind_detail", "sidewalk")]) == nil)183 #expect(layer([("kind", "other"), ("kind_detail", "pier")]) == nil)184 #expect(layer([("kind", "rail"), ("kind_detail", "rail"), ("is_bridge", "true"), ("is_tunnel", "true")]) == .tunnelRail)185 #expect(layer([("kind", "ferry")]) == nil && layer([]) == nil)186 #expect(AtlasStyle.boundaryLayer(attributes: ["kind_detail": .number(2)]) == .boundaryCountry)187 #expect(AtlasStyle.boundaryLayer(attributes: ["kind_detail": .string("4")]) == .boundaryRegion)188 #expect(AtlasStyle.boundaryLayer(attributes: ["kind_detail": .string("6")]) == nil && AtlasStyle.boundaryLayer(attributes: [:]) == nil)189 }190191 @Test func roundGeometryOnlyWhereItCanShow() {192 #expect(AtlasStyle.lineGeometry(for: .roadMinor, tileZoom: 12, isDeepestZoom: false).join == .miter)193 #expect(AtlasStyle.lineGeometry(for: .roadMinor, tileZoom: 15, isDeepestZoom: true) == (.round, .round) as (LineJoin, LineCap))194 #expect(AtlasStyle.lineGeometry(for: .roadHighway, tileZoom: 12, isDeepestZoom: false) == (.round, .round) as (LineJoin, LineCap))195 #expect(AtlasStyle.lineGeometry(for: .bridgeHighway, tileZoom: 12, isDeepestZoom: false).cap == .butt)196 #expect(AtlasStyle.lineGeometry(for: .roadPath, tileZoom: 15, isDeepestZoom: true) == (.miter, .butt) as (LineJoin, LineCap))197 }198}199200@Suite struct TileMeshTests {201 static func syntheticTile() throws -> VectorTile {202 try MVT.tile([203 MVT.layer("earth", [MVT.Feature(type: .polygon, parts: [[(0, 0), (4096, 0), (4096, 4096), (0, 4096)]], attributes: [("kind", "earth")])]),204 MVT.layer("landuse", [205 MVT.Feature(type: .polygon, parts: [[(100, 100), (1100, 100), (1100, 1100), (100, 1100)], [(400, 400), (400, 800), (800, 800), (800, 400)]], attributes: [("kind", "park")]),206 MVT.Feature(type: .polygon, parts: [[(2000, 2000), (2100, 2000), (2100, 2100)]], attributes: [("kind", "not_a_kind")]),207 ]),208 MVT.layer("water", [209 MVT.Feature(type: .polygon, parts: [[(3000, 0), (4096, 0), (4096, 1000), (3000, 1000)]], attributes: [("kind", "water")]),210 MVT.Feature(type: .line, parts: [[(0, 3000), (500, 3100), (900, 3600)]], attributes: [("kind", "river")]),211 ]),212 MVT.layer("buildings", [MVT.Feature(type: .polygon, parts: [[(1500, 1500), (1700, 1500), (1700, 1700), (1500, 1700)]], attributes: [("kind", "building")])]),213 MVT.layer("roads", [214 MVT.Feature(type: .line, parts: [[(-64, 2048), (2048, 2048), (4160, 2048)]], attributes: [("kind", "highway")]),215 MVT.Feature(type: .line, parts: [[(2048, -64), (2048, 4160)]], attributes: [("kind", "minor_road"), ("is_bridge", "true")]),216 MVT.Feature(type: .line, parts: [[(10, 10), (300, 300)]], attributes: [("kind", "minor_road"), ("is_tunnel", "true")]),217 MVT.Feature(type: .line, parts: [[(5, 5)]], attributes: [("kind", "minor_road")]),218 MVT.Feature(type: .line, parts: [[(10, 10), (30, 30)]], attributes: [("kind", "aerialway")]),219 ]),220 MVT.layer("places", [MVT.Feature(type: .point, parts: [[(5, 5)]], attributes: [("kind", "locality"), ("name", "Somewhere")])]),221 ])222 }223224 @Test func vertexLayoutMatchesTheShader() {225 #expect(MemoryLayout<AtlasVertex>.stride == 12 && MemoryLayout<AtlasVertex>.size == 12)226 #expect(MemoryLayout<AtlasStyleEntry>.stride == 32)227 }228229 @Test func syntheticTileProducesOrderedSegments() throws {230 let tile = try Self.syntheticTile()231 let mesh = TileMeshBuilder.build(tile: tile, id: TileID(z: 14, x: 1, y: 2))232 #expect(mesh.indices.count % 3 == 0 && mesh.indices.allSatisfy { Int($0) < mesh.vertices.count })233 // earth 2 triangles, park with a hole 8, water 2, building 2.234 #expect(mesh.layerRanges[.earth]?.count == 6 && mesh.layerRanges[.landusePark]?.count == 24)235 #expect(mesh.layerRanges[.water]?.count == 6 && mesh.layerRanges[.building]?.count == 6)236 #expect(mesh.layerRanges[.buildingOutline] != nil && mesh.layerRanges[.waterwayRiver] != nil)237 #expect(mesh.layerRanges[.roadHighway] != nil && mesh.layerRanges[.bridgeMinor] != nil && mesh.layerRanges[.tunnelMinor] != nil)238 #expect(mesh.statistics.polygons == 4 && mesh.statistics.lines == 5)239 // The unknown land use kind, the aerialway and the place label are ignored; the one-point line is empty.240 #expect(mesh.statistics.ignoredFeatures == 3 && mesh.statistics.emptyGeometries == 1)241 #expect(mesh.statistics.triangulation.isClean && mesh.statistics.clampedVertices == 0)242 // Layers are stored in draw order.243 let ordered = mesh.layerRanges.sorted { $0.key.rawValue < $1.key.rawValue }.map(\.value)244 #expect(zip(ordered, ordered.dropFirst()).allSatisfy { $0.upperBound == $1.lowerBound })245 #expect(ordered.first?.lowerBound == 0 && ordered.last?.upperBound == mesh.indices.count)246 // fills → tunnel casing → tunnel + buildings → road casing → roads → bridge casing → bridges.247 #expect(mesh.segments.map(\.pass) == [.base, .casing, .base, .casing, .base, .casing, .base])248 let tunnel = try #require(mesh.layerRanges[.tunnelMinor]), outline = try #require(mesh.layerRanges[.buildingOutline])249 #expect(mesh.segments[1].indexStart == tunnel.lowerBound && mesh.segments[1].indexCount == tunnel.count)250 #expect(mesh.segments[2].indexStart == tunnel.lowerBound && mesh.segments[2].indexStart + mesh.segments[2].indexCount == outline.upperBound)251 #expect(mesh.segments.filter { $0.pass == .base }.map(\.indexCount).reduce(0, +) == mesh.indices.count)252 // Fill vertices carry no extrusion and their layer; line side vertices carry a unit extrusion.253 let earth = try #require(mesh.layerRanges[.earth])254 for i in mesh.indices[earth] { let v = mesh.vertices[Int(i)]; #expect(v.ex == 0 && v.ey == 0 && v.style == AtlasLayer.earth.rawValue) }255 let highway = try #require(mesh.layerRanges[.roadHighway])256 for i in mesh.indices[highway] {257 let v = mesh.vertices[Int(i)]258 #expect(v.style == AtlasLayer.roadHighway.rawValue)259 let length = (Float(v.ex) * Float(v.ex) + Float(v.ey) * Float(v.ey)).squareRoot() / AtlasVertex.extrusionScale260 #expect(length == 0 || abs(length - 1) < 0.01)261 }262 #expect(mesh.byteSize == mesh.vertices.count * 12 + mesh.indices.count * 4)263 // Deterministic.264 #expect(TileMeshBuilder.build(tile: tile, id: TileID(z: 14, x: 1, y: 2)) == mesh)265 // Without outlines there are fewer vertices and no outline layer.266 let plain = TileMeshBuilder.build(tile: tile, id: mesh.id, options: .init(buildingOutlines: false))267 #expect(plain.layerRanges[.buildingOutline] == nil && plain.vertices.count < mesh.vertices.count)268 }269270 @Test func otherExtentsAreNormalizedAndHugeCoordinatesClamped() throws {271 let tile = try MVT.tile([272 MVT.layer("earth", extent: 512, [MVT.Feature(type: .polygon, parts: [[(0, 0), (512, 0), (512, 512), (0, 512)]])]),273 MVT.layer("water", [MVT.Feature(type: .polygon, parts: [[(0, 0), (900_000, 0), (900_000, 900_000)]])]),274 ])275 let mesh = TileMeshBuilder.build(tile: tile, id: TileID(z: 3, x: 0, y: 0))276 let earth = try #require(mesh.layerRanges[.earth])277 #expect(mesh.indices[earth].map { mesh.vertices[Int($0)].x }.max() == 4096)278 #expect(mesh.statistics.clampedVertices > 0)279 #expect(mesh.vertices.map(\.x).max() == 32767)280 }281282 @Test func emptyTile() throws {283 let mesh = TileMeshBuilder.build(tile: try VectorTile(data: Data()), id: TileID(z: 0, x: 0, y: 0))284 #expect(mesh.isEmpty && mesh.segments.isEmpty && mesh.byteSize == 0)285 }286287 @Test func corruptedTilesNeverTrap() throws {288 // Flip bytes of a real tile: whatever still decodes must build without trapping, with indices in range.289 let archive = try TestData.world()290 let original = [UInt8](try #require(try archive.tile(TileID(z: 6, x: 18, y: 22))))291 var g = SeededGenerator(seed: 11)292 var decoded = 0, rejected = 0293 for _ in 0..<600 {294 var bytes = original295 for _ in 0..<Int.random(in: 1...8, using: &g) { bytes[Int.random(in: 0..<bytes.count, using: &g)] = UInt8.random(in: 0...255, using: &g) }296 if Bool.random(using: &g) { bytes.removeLast(Int.random(in: 0..<bytes.count, using: &g)) }297 guard let tile = try? VectorTile(data: Data(bytes)) else { rejected += 1; continue }298 decoded += 1299 let mesh = TileMeshBuilder.build(tile: tile, id: TileID(z: 6, x: 18, y: 22))300 #expect(mesh.indices.count % 3 == 0)301 #expect(mesh.indices.allSatisfy { Int($0) < mesh.vertices.count })302 #expect(mesh.segments.allSatisfy { $0.indexStart >= 0 && $0.indexStart + $0.indexCount <= mesh.indices.count })303 }304 #expect(decoded > 0 && rejected > 0)305 }306307 @Test func worldTileZero() throws {308 let archive = try TestData.world()309 let tile = try VectorTile(data: try #require(try archive.tile(TileID(z: 0, x: 0, y: 0))))310 let mesh = TileMeshBuilder.build(tile: tile, id: TileID(z: 0, x: 0, y: 0))311 #expect(mesh.triangleCount > 5_000)312 #expect(mesh.layerRanges[.earth] != nil && mesh.layerRanges[.water] != nil && mesh.layerRanges[.boundaryCountry] != nil)313 #expect(mesh.indices.allSatisfy { Int($0) < mesh.vertices.count })314 #expect(mesh.segments.map(\.pass) == [.base])315 }316317 @Test(.enabled(if: TestData.hasMontreal)) func montrealStreetTile() throws {318 let archive = try TestData.montreal()319 let id = WebMercator.tile(for: Coordinate(latitude: 45.5017, longitude: -73.5673), zoom: 15)320 let tile = try VectorTile(data: try #require(try archive.tile(id)))321 let mesh = TileMeshBuilder.build(tile: tile, id: id, options: .init(isDeepestZoom: true))322 #expect(mesh.layerRanges[.building] != nil && mesh.layerRanges[.roadMinor] != nil && mesh.layerRanges[.earth] != nil)323 #expect(mesh.segments.contains { $0.pass == .casing })324 #expect(mesh.indices.allSatisfy { Int($0) < mesh.vertices.count })325 #expect(mesh.statistics.triangulation.isClean)326 #expect(mesh.statistics.polygons > 500 && mesh.statistics.lines > 500)327 }328}329