SPB Git

Repository Public BSD-3-Clause

TriangulatorTests.swift 15.2 KB 308 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Packages/ORIXAtlas/Tests/ORIXAtlasTests/TriangulatorTests.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 ORIXTileStore92import Testing9394private typealias P = VectorTile.Point9596private func ring(_ pts: [(Int32, Int32)]) -> [P] { pts.map { P(x: $0.0, y: $0.1) } }9798/// Even-odd test of a point given in doubled coordinates against rings.99private func contains(_ rings: [[P]], x2: Int64, y2: Int64) -> Bool {100    var inside = false101    for r in rings {102        var j = r.count - 1103        for i in 0..<r.count {104            let a = r[i], b = r[j]105            let ay = 2 * Int64(a.y), by = 2 * Int64(b.y), ax = 2 * Int64(a.x), bx = 2 * Int64(b.x)106            if (ay > y2) != (by > y2), Double(x2) < Double(bx - ax) * Double(y2 - ay) / Double(by - ay) + Double(ax) { inside.toggle() }107            j = i108        }109    }110    return inside111}112113/// Area is preserved exactly and the centroid of every triangle is inside the polygon (and outside its holes).114private func expectExactCover(_ rings: [[P]], sourceLocation: SourceLocation = #_sourceLocation) {115    let r = Triangulator.triangulate(rings)116    let pts = rings.flatMap { $0 }117    #expect(r.diagnostics.isClean, sourceLocation: sourceLocation)118    #expect(r.indices.count % 3 == 0 && r.indices.allSatisfy { Int($0) < pts.count }, sourceLocation: sourceLocation)119    let want = abs(Triangulator.doubledSignedArea(rings[0])) - rings.dropFirst().reduce(0) { $0 + abs(Triangulator.doubledSignedArea($1)) }120    #expect(Triangulator.doubledArea(of: r.indices, points: pts) == want, sourceLocation: sourceLocation)121    var outside = 0122    for t in stride(from: 0, to: r.indices.count, by: 3) {123        let a = pts[Int(r.indices[t])], b = pts[Int(r.indices[t + 1])], c = pts[Int(r.indices[t + 2])]124        // Centroid in sixths to stay on integers: compare in doubled units after scaling by 3.125        let cx = Int64(a.x) + Int64(b.x) + Int64(c.x), cy = Int64(a.y) + Int64(b.y) + Int64(c.y)126        let scaled = rings.map { $0.map { P(x: $0.x * 3, y: $0.y * 3) } }127        if !contains(scaled, x2: 2 * cx, y2: 2 * cy) { outside += 1 }128    }129    #expect(outside == 0, sourceLocation: sourceLocation)130}131132@Suite struct TriangulatorTests {133    @Test func squareAndWindingAndClosingPoint() {134        let square = ring([(0, 0), (10, 0), (10, 10), (0, 10)])135        #expect(Triangulator.triangulate([square]).indices.count == 6)136        expectExactCover([square])137        expectExactCover([square.reversed()])138        let closed = square + [square[0]]139        let r = Triangulator.triangulate([closed])140        #expect(r.indices.count == 6 && !r.indices.contains(4))141    }142143    @Test func concaveShapes() {144        expectExactCover([ring([(0, 0), (20, 0), (20, 10), (10, 10), (10, 20), (0, 20)])])145        // A comb: many reflex vertices.146        var comb: [(Int32, Int32)] = [(0, 0)]147        for i in 0..<20 { let x = Int32(i * 10); comb += [(x, 50), (x + 5, 50), (x + 5, 10), (x + 10, 10)] }148        comb += [(200, 0)]149        expectExactCover([ring(comb)])150        // A spiral.151        expectExactCover([ring([(0, 0), (100, 0), (100, 100), (20, 100), (20, 40), (60, 40), (60, 60), (40, 60), (40, 80), (80, 80), (80, 20), (0, 20)])])152    }153154    @Test func holes() {155        let outer = ring([(0, 0), (100, 0), (100, 100), (0, 100)])156        let hole = ring([(40, 40), (60, 40), (60, 60), (40, 60)])157        let r = Triangulator.triangulate([outer, hole])158        #expect(r.indices.count == 8 * 3)159        expectExactCover([outer, hole])160        expectExactCover([outer.reversed(), hole.reversed()])161        // Several holes, including two aligned on the same row and one touching nothing but close to the edge.162        let holes = [ring([(10, 10), (20, 10), (20, 20), (10, 20)]), ring([(30, 10), (40, 10), (40, 20), (30, 20)]), ring([(70, 12), (90, 15), (80, 30)]),163                     ring([(10, 60), (30, 60), (30, 90), (10, 90)]), ring([(50, 50), (55, 45), (60, 50), (55, 55)]), ring([(98, 98), (99, 98), (99, 99), (98, 99)])]164        expectExactCover([outer] + holes)165        // A grid of holes: many bridges reaching the same vertices.166        var grid: [[P]] = [ring([(0, 0), (1000, 0), (1000, 1000), (0, 1000)])]167        for i in 0..<9 { for j in 0..<9 { let x = Int32(50 + i * 100), y = Int32(50 + j * 100); grid.append(ring([(x, y), (x + 50, y), (x + 50, y + 50), (x, y + 50)])) } }168        expectExactCover(grid)169    }170171    @Test func holeTouchingTheOuterRingAtAVertex() {172        let outer = ring([(0, 0), (100, 0), (100, 100), (0, 100)])173        let hole = ring([(0, 50), (30, 40), (30, 60)])174        let r = Triangulator.triangulate([outer, hole])175        let pts = outer + hole176        #expect(r.indices.allSatisfy { Int($0) < pts.count })177        #expect(Triangulator.doubledArea(of: r.indices, points: pts) == 2 * 10000 - 2 * 300)178    }179180    @Test func degenerateInputProducesNothingAndNeverTraps() {181        #expect(Triangulator.triangulate([]).indices.isEmpty)182        #expect(Triangulator.triangulate([[]]).indices.isEmpty)183        #expect(Triangulator.triangulate([ring([(1, 1)])]).indices.isEmpty)184        #expect(Triangulator.triangulate([ring([(1, 1), (5, 5)])]).indices.isEmpty)185        #expect(Triangulator.triangulate([ring([(0, 0), (5, 5), (10, 10), (20, 20)])]).indices.isEmpty)186        #expect(Triangulator.triangulate([ring([(3, 3), (3, 3), (3, 3), (3, 3)])]).indices.isEmpty)187        // Out and back along the same path: no area.188        #expect(Triangulator.triangulate([ring([(0, 0), (10, 0), (20, 5), (10, 0)])]).indices.isEmpty)189        // Repeated points and collinear points inside a valid ring are ignored.190        expectExactCover([ring([(0, 0), (0, 0), (5, 0), (10, 0), (10, 10), (10, 10), (0, 10)])])191        // Degenerate holes are skipped, the outer ring is still triangulated.192        let outer = ring([(0, 0), (10, 0), (10, 10), (0, 10)])193        #expect(Triangulator.triangulate([outer, ring([(2, 2), (4, 4)]), []]).indices.count == 6)194    }195196    @Test func extremeCoordinatesDoNotOverflow() {197        let m = Int32.max, n = Int32.min198        let r = Triangulator.triangulate([ring([(n, n), (m, n), (m, m), (n, m)]), ring([(-5, -5), (5, -5), (5, 5), (-5, 5)])])199        #expect(r.indices.count % 3 == 0 && r.indices.allSatisfy { $0 < 8 })200        #expect(!r.indices.isEmpty)201    }202203    @Test func selfTouchingAndSelfIntersectingRingsTerminate() {204        // Two triangles sharing one vertex, as a single ring (self-touching, still has a well-defined area).205        let pinch = ring([(0, 0), (10, 0), (5, 5), (10, 10), (0, 10), (5, 5)])206        let r = Triangulator.triangulate([pinch])207        #expect(r.indices.allSatisfy { $0 < 6 })208        #expect(Triangulator.doubledArea(of: r.indices, points: pinch) == 100)209        // A bow-tie (self-intersecting): invalid, any result is acceptable as long as it is bounded.210        let bow = ring([(0, 0), (10, 10), (10, 0), (0, 10)])211        let b = Triangulator.triangulate([bow])212        #expect(b.indices.count <= 3 * 4 && b.indices.allSatisfy { $0 < 4 })213        // A hole outside the outer ring, a hole crossing it, and a hole equal to the outer ring.214        let outer = ring([(0, 0), (10, 0), (10, 10), (0, 10)])215        for hole in [ring([(50, 50), (60, 50), (60, 60)]), ring([(5, 5), (20, 5), (20, 8), (5, 8)]), outer] {216            let x = Triangulator.triangulate([outer, hole])217            #expect(x.indices.count % 3 == 0 && x.indices.allSatisfy { Int($0) < 4 + hole.count })218        }219    }220221    @Test func randomSimplePolygonsAreCoveredExactly() {222        var g = SeededGenerator(seed: 2026)223        for _ in 0..<400 {224            // Star-shaped around the centre: increasing angles at least half a step apart (3.9 units at the smallest225            // radius, so rounding to integers cannot make edges cross), random radii.226            let n = Int.random(in: 3...160, using: &g)227            var pts: [(Int32, Int32)] = []228            for i in 0..<n {229                let angle = (Double(i) + Double.random(in: 0.25...0.75, using: &g)) / Double(n) * 2 * .pi230                let radius = Double.random(in: 200...2000, using: &g)231                pts.append((Int32((2048 + cos(angle) * radius).rounded()), Int32((2048 + sin(angle) * radius).rounded())))232            }233            var rings = [ring(pts)]234            // A hole well inside the smallest radius.235            if Bool.random(using: &g) { rings.append(ring([(2000, 2000), (2090, 2010), (2080, 2100), (2010, 2090)])) }236            expectExactCover(rings)237        }238    }239240    @Test func randomGarbageNeverTrapsAndStaysInRange() {241        var g = SeededGenerator(seed: 7)242        var triangles = 0243        for _ in 0..<1500 {244            let ringCount = Int.random(in: 1...4, using: &g)245            var rings: [[P]] = []246            for _ in 0..<ringCount {247                let n = Int.random(in: 0...60, using: &g)248                // A small lattice makes repeated points, collinear runs and crossings frequent.249                rings.append((0..<n).map { _ in P(x: Int32.random(in: 0...12, using: &g), y: Int32.random(in: 0...12, using: &g)) })250            }251            let total = rings.reduce(0) { $0 + $1.count }252            let r = Triangulator.triangulate(rings)253            #expect(r.indices.count % 3 == 0)254            #expect(r.indices.allSatisfy { Int($0) < total })255            // Ear clipping removes one vertex per triangle, bridges add two per hole.256            #expect(r.indices.count / 3 <= total + 2 * ringCount)257            triangles += r.indices.count / 3258        }259        #expect(triangles > 0)260    }261262    @Test func largeInvalidRingIsBounded() {263        // 20 000 random points: hostile input must finish in bounded time (the split search has a work budget).264        var g = SeededGenerator(seed: 99)265        let big = (0..<20_000).map { _ in P(x: Int32.random(in: 0...4096, using: &g), y: Int32.random(in: 0...4096, using: &g)) }266        let ms = milliseconds { let r = Triangulator.triangulate([big]); #expect(r.indices.allSatisfy { $0 < 20_000 }) }267        #expect(ms < 60_000)268    }269270    @Test(.enabled(if: TestData.hasMontreal)) func realMontrealPolygonsAreCoveredExactly() throws {271        let archive = try TestData.montreal()272        var total = 0, exact = 0, unclean = 0273        for id in TestData.benchmarkTiles() {274            guard let data = try archive.tile(id) else { continue }275            let tile = try VectorTile(data: data)276            for layer in tile.layers where ["buildings", "landuse", "water", "earth"].contains(layer.name) {277                for f in layer.features where f.type == .polygon {278                    for group in polygonGroups(f) {279                        let r = Triangulator.triangulate(group)280                        let pts = group.flatMap { $0 }281                        let want = abs(Triangulator.doubledSignedArea(group[0])) - group.dropFirst().reduce(0) { $0 + abs(Triangulator.doubledSignedArea($1)) }282                        total += 1283                        if Triangulator.doubledArea(of: r.indices, points: pts) == want { exact += 1 }284                        if !r.diagnostics.isClean { unclean += 1 }285                    }286                }287            }288        }289        print("Triangulator on real Montréal polygons: \(total) polygons, \(exact) exact, \(unclean) with diagnostics")290        #expect(total > 100_000)291        // Tile data is not guaranteed valid; what was measured on 2026-11-25 is 128 170 of 128 170.292        #expect(Double(exact) / Double(total) > 0.9999)293        #expect(unclean <= total / 10_000)294    }295}296297/// Splits a polygon feature into (exterior, holes…) groups the way the mesh builder does.298func polygonGroups(_ f: VectorTile.Feature) -> [[[VectorTile.Point]]] {299    var out: [[[VectorTile.Point]]] = []300    var sign: Int64 = 0301    for ring in f.parts {302        let area = Triangulator.doubledSignedArea(ring)303        if area == 0 { continue }304        if out.isEmpty || (area > 0) == (sign > 0) { out.append([ring]); sign = area } else { out[out.count - 1].append(ring) }305    }306    return out307}308
Files main
Menu

Theme