From 56930aa54cd14d400eb8f324350451093534a110 Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Sat, 7 Nov 2026 15:10:49 +1100 Subject: [PATCH 1/2] feat: add GeoJSON.Polygon.triangles(maxEdgeDegrees:) Splits the triangulation until no edge is longer than a limit, splitting each edge at its middle from both sides, after flipping long slivers into rounder triangles. It's for renderers that project triangle corners and join them with straight lines. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + Sources/GeoJSONKitTurf/Turf+Triangulate.swift | 160 ++++++++++++++++++ .../RefinedTrianglesTests.swift | 125 ++++++++++++++ 3 files changed, 286 insertions(+) create mode 100644 Tests/GeoJSONKitTurfTests/RefinedTrianglesTests.swift diff --git a/README.md b/README.md index 8dd026a..449fca0 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,7 @@ Additionally, it adds the following features, which do not have a direct equival * `GeoJSON.Direction.wrap(min:max:)` * `GeoJSON.LineString.frechetDistance(to:)`: Determines the [Fréchet distance](https://en.wikipedia.org/wiki/Fréchet_distance) between two line strings, which is a measure of their similarity. * `GeoJSON.GeometryObject(splittingWhenCrossingAntiMeridian:)`: Breaks up a LineString or Polygon into two when crossing the anti-meridian. +* `GeoJSON.Polygon.triangles(maxEdgeDegrees:)`: Splits a polygon into triangles with no edge longer than a limit, for drawing a fill by projecting the triangles' corners. ## CLI diff --git a/Sources/GeoJSONKitTurf/Turf+Triangulate.swift b/Sources/GeoJSONKitTurf/Turf+Triangulate.swift index d40d30f..551afae 100644 --- a/Sources/GeoJSONKitTurf/Turf+Triangulate.swift +++ b/Sources/GeoJSONKitTurf/Turf+Triangulate.swift @@ -53,3 +53,163 @@ extension GeoJSON.Polygon { return triangles } } + +extension GeoJSON.Polygon { + /// Three corners, counter-clockwise when taking longitude and latitude as flat coordinates. + public struct Triangle: Hashable { + public let a: GeoJSON.Position + public let b: GeoJSON.Position + public let c: GeoJSON.Position + + public init(a: GeoJSON.Position, b: GeoJSON.Position, c: GeoJSON.Position) { + self.a = a + self.b = b + self.c = c + } + } + + /// Splits the polygon into triangles, as ``triangleIndices()`` does, then splits those + /// until no edge is longer than `maxEdgeDegrees`, taking longitude and latitude as flat + /// coordinates. + /// + /// This is for drawing a fill by projecting each triangle's corners and joining them with + /// straight lines, which only follows a curved projection where the triangles are small. + /// It also leaves each triangle that's near the edge of a map, or across its seam, small + /// enough to leave out or cut there. + /// + /// Each edge is split at its middle, from both sides, so a corner never ends up on the side + /// of a neighbour, which would leave a crack between them once they're projected. Long and + /// thin triangles from the triangulation are first turned into rounder ones, which take + /// fewer splits. + /// + /// Longitudes can run on past the antimeridian, which keeps a ring that crosses it in + /// one piece. Corners keep their altitude, and the corners that splitting adds have none. + /// + /// - Parameter maxEdgeDegrees: How long an edge can be, in degrees. `.infinity` leaves + /// the triangles as ``triangleIndices()`` has them. + /// - Returns: Triangles that together cover the polygon, but not its interiors. + public func triangles(maxEdgeDegrees: Double) -> [Triangle] { + let corners = ([exterior] + interiors).flatMap(\.positions) + let indices = triangleIndices() + var triangulated = stride(from: 0, to: indices.count - 2, by: 3).map { (indices[$0], indices[$0 + 1], indices[$0 + 2]) } + Self.flipToDelaunay(&triangulated, corners: corners, maxEdge: maxEdgeDegrees) + + var triangles: [Triangle] = [] + triangles.reserveCapacity(triangulated.count) + for (a, b, c) in triangulated { + Self.refine(corners[a], corners[b], corners[c], maxEdge: maxEdgeDegrees, into: &triangles) + } + return triangles + } + + private static func distance(_ a: GeoJSON.Position, _ b: GeoJSON.Position) -> Double { + let x = b.longitude - a.longitude, y = b.latitude - a.latitude + return (x * x + y * y).squareRoot() + } + + private static func midpoint(_ a: GeoJSON.Position, _ b: GeoJSON.Position) -> GeoJSON.Position { + GeoJSON.Position(latitude: (a.latitude + b.latitude) / 2, longitude: (a.longitude + b.longitude) / 2) + } + + /// Splits on the middle of the longest edge. Any edge that's too long is split at the same + /// place from both sides, so no triangle's corner ends up on the side of its neighbour. + private static func refine(_ a: GeoJSON.Position, _ b: GeoJSON.Position, _ c: GeoJSON.Position, maxEdge: Double, into triangles: inout [Triangle]) { + let ab = distance(a, b), bc = distance(b, c), ca = distance(c, a) + let longest = max(ab, bc, ca) + guard longest > maxEdge else { + triangles.append(Triangle(a: a, b: b, c: c)) + return + } + if longest == ab { + let middle = midpoint(a, b) + refine(a, middle, c, maxEdge: maxEdge, into: &triangles) + refine(middle, b, c, maxEdge: maxEdge, into: &triangles) + } else if longest == bc { + let middle = midpoint(b, c) + refine(a, b, middle, maxEdge: maxEdge, into: &triangles) + refine(a, middle, c, maxEdge: maxEdge, into: &triangles) + } else { + let middle = midpoint(c, a) + refine(a, b, middle, maxEdge: maxEdge, into: &triangles) + refine(middle, b, c, maxEdge: maxEdge, into: &triangles) + } + } + + private typealias Corners = (Int, Int, Int) + + /// Ears are long slivers, which all take a lot of splitting to get small, and flipping + /// the shared edge of a pair where the other diagonal is shorter gets rid of those. + private static func flipToDelaunay(_ triangles: inout [Corners], corners: [GeoJSON.Position], maxEdge: Double) { + // Only around those that get split, as the rest are small enough as they are, and + // most polygons have none of those. + func isLong(_ triangle: Corners) -> Bool { + let a = corners[triangle.0], b = corners[triangle.1], c = corners[triangle.2] + return max(distance(a, b), distance(b, c), distance(c, a)) > maxEdge + } + let long = triangles.filter(isLong) + guard !long.isEmpty else { return } + + struct Edge: Hashable { + let low: Int, high: Int + init(_ a: Int, _ b: Int) { (low, high) = a < b ? (a, b) : (b, a) } + } + var sides: [Edge: [Int]] = [:] + sides.reserveCapacity(triangles.count * 2) + func edges(_ triangle: Corners) -> [Edge] { + [Edge(triangle.0, triangle.1), Edge(triangle.1, triangle.2), Edge(triangle.2, triangle.0)] + } + for (index, triangle) in triangles.enumerated() { + for edge in edges(triangle) { sides[edge, default: []].append(index) } + } + + /// The triangle's corners, starting after the edge, so the first is the one opposite it. + func opposite(_ triangle: Corners, _ edge: Edge) -> Corners { + if triangle.0 != edge.low, triangle.0 != edge.high { return triangle } + if triangle.1 != edge.low, triangle.1 != edge.high { return (triangle.1, triangle.2, triangle.0) } + return (triangle.2, triangle.0, triangle.1) + } + + var pending = long.flatMap(edges) + // A fan needs about as many flips as the square of its size, and this is for one that crosses itself. + var budget = triangles.count * 200 + while let edge = pending.popLast(), budget > 0 { + guard let both = sides[edge], both.count == 2 else { continue } + budget -= 1 + // In counter-clockwise order: c is opposite, then a and b are the shared edge. + let first = opposite(triangles[both[0]], edge) + let second = opposite(triangles[both[1]], edge) + let c = first.0, a = first.1, b = first.2, d = second.0 + let pa = corners[a], pb = corners[b], pc = corners[c], pd = corners[d] + // The flip has to leave two triangles the right way around, for which the four + // corners have to be convex. + guard cross(pc, pa, pd) > 1e-9, cross(pd, pb, pc) > 1e-9 else { continue } + guard inCircle(pa, pb, pc, pd) > 1e-9 else { continue } + + let replacedFirst = (c, a, d), replacedSecond = (d, b, c) + for index in both { + for side in edges(triangles[index]) { sides[side]?.removeAll { $0 == index } } + } + triangles[both[0]] = replacedFirst + triangles[both[1]] = replacedSecond + for (index, triangle) in [(both[0], replacedFirst), (both[1], replacedSecond)] { + for side in edges(triangle) { + sides[side, default: []].append(index) + if side != Edge(c, d) { pending.append(side) } + } + } + } + } + + private static func cross(_ a: GeoJSON.Position, _ b: GeoJSON.Position, _ c: GeoJSON.Position) -> Double { + (b.longitude - a.longitude) * (c.latitude - a.latitude) - (b.latitude - a.latitude) * (c.longitude - a.longitude) + } + + /// Positive if `d` is inside the circle through the counter-clockwise `a`, `b` and `c`. + private static func inCircle(_ a: GeoJSON.Position, _ b: GeoJSON.Position, _ c: GeoJSON.Position, _ d: GeoJSON.Position) -> Double { + let adx = a.longitude - d.longitude, ady = a.latitude - d.latitude + let bdx = b.longitude - d.longitude, bdy = b.latitude - d.latitude + let cdx = c.longitude - d.longitude, cdy = c.latitude - d.latitude + let aSquared = adx * adx + ady * ady, bSquared = bdx * bdx + bdy * bdy, cSquared = cdx * cdx + cdy * cdy + return aSquared * (bdx * cdy - cdx * bdy) - bSquared * (adx * cdy - cdx * ady) + cSquared * (adx * bdy - bdx * ady) + } +} diff --git a/Tests/GeoJSONKitTurfTests/RefinedTrianglesTests.swift b/Tests/GeoJSONKitTurfTests/RefinedTrianglesTests.swift new file mode 100644 index 0000000..c35686d --- /dev/null +++ b/Tests/GeoJSONKitTurfTests/RefinedTrianglesTests.swift @@ -0,0 +1,125 @@ +// +// RefinedTrianglesTests.swift +// GeoJSONKitTurf +// + +#if canImport(Testing) && compiler(>=6) +import Foundation +import Testing + +import GeoJSONKit +import GeoJSONKitTurf + +struct RefinedTrianglesTests { + private static func polygon(_ rings: [[(x: Double, y: Double)]]) -> GeoJSON.Polygon { + GeoJSON.Polygon(rings.map { ring in ring.map { GeoJSON.Position(latitude: $0.y, longitude: $0.x) } }) + } + + private static func cross(_ a: GeoJSON.Position, _ b: GeoJSON.Position, _ c: GeoJSON.Position) -> Double { + (b.longitude - a.longitude) * (c.latitude - a.latitude) - (b.latitude - a.latitude) * (c.longitude - a.longitude) + } + + private static func distance(_ a: GeoJSON.Position, _ b: GeoJSON.Position) -> Double { + hypot(b.longitude - a.longitude, b.latitude - a.latitude) + } + + static let cases: [(String, [[(x: Double, y: Double)]], Double)] = [ + ("square", [[(10, 10), (40, 10), (40, 30), (10, 30), (10, 10)]], 600), + ("the other way around", [[(10, 10), (10, 30), (40, 30), (40, 10), (10, 10)]], 600), + ("concave", [[(0, 0), (40, 0), (40, 10), (10, 10), (10, 40), (0, 40), (0, 0)]], 700), + ("with a hole", [[(0, 0), (40, 0), (40, 40), (0, 40), (0, 0)], [(10, 10), (10, 20), (20, 20), (20, 10), (10, 10)]], 1500), + ("with two holes", [[(0, 0), (40, 0), (40, 40), (0, 40), (0, 0)], [(5, 5), (5, 15), (15, 15), (15, 5), (5, 5)], [(25, 25), (25, 35), (35, 35), (35, 25), (25, 25)]], 1400), + // Longitudes can run on past the antimeridian, which keeps a ring that crosses it in one piece. + ("past the antimeridian", [[(170, -10), (190, -10), (190, 10), (170, 10), (170, -10)]], 400), + // As Antarctica's ring is: along the coast, then along the south pole and back. + ("to the south pole and back", [stride(from: -180.0, through: 180.0, by: 20).map { ($0, -70) } + [(180, -90), (-180, -90), (-180, -70)]], 7200), + // Detailed coastlines go across themselves in tiny loops. + ("with sides that cross themselves", [[ + (0, 0), (19.9, 0), (20.1, -0.3), (19.9, -0.3), (20.1, 0), + (40, 0), (40, 19.9), (40.3, 20.1), (40.3, 19.9), (40, 20.1), + (40, 40), (20.1, 40), (19.9, 40.3), (20.1, 40.3), (19.9, 40), + (0, 40), (0, 20.1), (-0.3, 19.9), (-0.3, 20.1), (0, 19.9), (0, 0), + ]], 1600), + // And they're rounded, so that those loops can start and end on the very same corner. + ("with sides that go through their own corners", [[ + (0, 0), (20, 0), (20.1, -0.3), (19.9, -0.3), (20, 0), + (40, 0), (40, 20), (40.3, 20.1), (40.3, 19.9), (40, 20), + (40, 40), (20, 40), (19.9, 40.3), (20.1, 40.3), (20, 40), + (0, 40), (0, 20), (-0.3, 19.9), (-0.3, 20.1), (0, 20), (0, 0), + ]], 1600), + ("with a hole beyond it", [[(0, 0), (40, 0), (40, 40), (0, 40), (0, 0)], [(-3, 18), (-1, 18), (-1, 22), (-3, 22), (-3, 18)]], 1600), + ("a figure of eight", [[(-1, -1), (-10, -1), (-10, 1), (-1, 1), (1, -1), (21, -1), (21, 1), (1, 1), (-1, -1)]], 62), + ] + + @Test("Triangles add up to the polygon, turn the same way and stay small", arguments: cases) + func addUp(name: String, rings: [[(x: Double, y: Double)]], area: Double) { + let triangles = Self.polygon(rings).triangles(maxEdgeDegrees: 10) + var total = 0.0 + var longest = 0.0 + for triangle in triangles { + let twice = Self.cross(triangle.a, triangle.b, triangle.c) + #expect(twice >= 0) + total += twice / 2 + longest = max(longest, Self.distance(triangle.a, triangle.b), Self.distance(triangle.b, triangle.c), Self.distance(triangle.c, triangle.a)) + } + #expect(abs(total - area) < 0.001 * area) + #expect(longest <= 10) + } + + /// Each edge that's split is split from both sides, so no corner ends up on the side of a + /// neighbour, which would leave a crack where the two are drawn after projecting them. What + /// only one triangle has is then the polygon's outline, which adds up to its perimeter. + @Test func noCornerOnASide() { + let polygon = Self.polygon([ + [(0, 0), (40, 0), (40, 40), (0, 40), (0, 0)], + [(10, 10), (10, 20), (20, 20), (20, 10), (10, 10)], + ]) + struct Edge: Hashable { + let from: GeoJSON.Position, to: GeoJSON.Position + } + var edges: [Edge: Int] = [:] + for triangle in polygon.triangles(maxEdgeDegrees: 3) { + for (from, to) in [(triangle.a, triangle.b), (triangle.b, triangle.c), (triangle.c, triangle.a)] { + // Counter-clockwise, so a neighbour has the same edge the other way around. + if let count = edges[Edge(from: to, to: from)] { + edges[Edge(from: to, to: from)] = count == 1 ? nil : count - 1 + } else { + edges[Edge(from: from, to: to), default: 0] += 1 + } + } + } + let outline = edges.reduce(0.0) { $0 + Self.distance($1.key.from, $1.key.to) * Double($1.value) } + #expect(abs(outline - (160 + 40)) < 1e-9) + } + + @Test func unrefined() { + let polygon = Self.polygon([ + [(0, 0), (40, 0), (40, 40), (0, 40), (0, 0)], + [(10, 10), (10, 20), (20, 20), (20, 10), (10, 10)], + ]) + let positions = polygon.exterior.positions + polygon.interiors.flatMap(\.positions) + let indices = polygon.triangleIndices() + let expected = stride(from: 0, to: indices.count, by: 3).map { + GeoJSON.Polygon.Triangle(a: positions[indices[$0]], b: positions[indices[$0 + 1]], c: positions[indices[$0 + 2]]) + } + #expect(polygon.triangles(maxEdgeDegrees: .infinity) == expected) + } + + /// Ears along a strip with many corners are long slivers to its far side, which take a lot + /// of splitting to get small. Flipping them first leaves a zigzag across it instead. + @Test func fewTriangles() { + let bottom = (0...100).map { (x: Double($0), y: 0.0) } + let top = (0...100).reversed().map { (x: Double($0), y: 10.0) } + let triangles = Self.polygon([bottom + top + [bottom[0]]]).triangles(maxEdgeDegrees: 10) + // Each of the zigzag's 200 has a diagonal that's just too long, so takes a split. Without + // the flips it's more than ten times as many. + #expect(triangles.count == 400) + } + + @Test func tooFewCorners() { + #expect(Self.polygon([[(0, 0), (1, 1), (0, 0)]]).triangles(maxEdgeDegrees: 1).isEmpty) + #expect(Self.polygon([[]]).triangles(maxEdgeDegrees: 1).isEmpty) + } +} + +#endif From a437be0b93cc42a79b6fe3d2afbf0264c1ed8f51 Mon Sep 17 00:00:00 2001 From: Adrian Schoenig Date: Sat, 7 Nov 2026 15:26:46 +1100 Subject: [PATCH 2/2] feat: add GeoJSON.Polygon.unwrapped() Triangulating takes longitude and latitude as flat coordinates, so a ring that crosses the antimeridian, or goes around a pole as Antarctica's often does, needs its longitudes to run on, and the latter needs closing along the pole. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + Sources/GeoJSONKitTurf/Turf+Triangulate.swift | 85 +++++++++++++++++++ .../RefinedTrianglesTests.swift | 32 +++++++ 3 files changed, 118 insertions(+) diff --git a/README.md b/README.md index 449fca0..61b291e 100644 --- a/README.md +++ b/README.md @@ -77,6 +77,7 @@ Additionally, it adds the following features, which do not have a direct equival * `GeoJSON.LineString.frechetDistance(to:)`: Determines the [Fréchet distance](https://en.wikipedia.org/wiki/Fréchet_distance) between two line strings, which is a measure of their similarity. * `GeoJSON.GeometryObject(splittingWhenCrossingAntiMeridian:)`: Breaks up a LineString or Polygon into two when crossing the anti-meridian. * `GeoJSON.Polygon.triangles(maxEdgeDegrees:)`: Splits a polygon into triangles with no edge longer than a limit, for drawing a fill by projecting the triangles' corners. +* `GeoJSON.Polygon.unwrapped()`: Lets a polygon's rings run on past the anti-meridian instead of jumping across it, and closes a ring that goes around a pole along that pole, so it can be triangulated. ## CLI diff --git a/Sources/GeoJSONKitTurf/Turf+Triangulate.swift b/Sources/GeoJSONKitTurf/Turf+Triangulate.swift index 551afae..989c5b0 100644 --- a/Sources/GeoJSONKitTurf/Turf+Triangulate.swift +++ b/Sources/GeoJSONKitTurf/Turf+Triangulate.swift @@ -213,3 +213,88 @@ extension GeoJSON.Polygon { return aSquared * (bdx * cdy - cdx * bdy) - bSquared * (adx * cdy - cdx * ady) + cSquared * (adx * bdy - bdx * ady) } } + +extension GeoJSON.Polygon { + /// The polygon with rings that run on past the antimeridian instead of jumping across it, + /// which is what ``triangles(maxEdgeDegrees:)`` and ``triangleIndices()`` need, as they take + /// longitude and latitude as flat coordinates. + /// + /// Each position's longitude is then less than 180 degrees from the one before. A ring that + /// goes around a pole ends a turn away from where it started, so it's taken along that pole + /// to close it. Interiors are moved by whole turns to where the exterior is. An edge along + /// the antimeridian and back again, as a ring that's split there has, is left out, and so + /// is a position that's the same as the one before. + /// + /// - Returns: The polygon as it is where none of its rings cross the antimeridian. + public func unwrapped() -> GeoJSON.Polygon { + let exterior = Self.unwrap(exterior.positions) + guard exterior.count >= 4 else { return self } + let middle = Self.middleLongitude(of: exterior) + let interiors = interiors.map { interior -> GeoJSON.Polygon.LinearRing in + let hole = Self.unwrap(interior.positions) + guard !hole.isEmpty else { return interior } + // A ring on its own starts anywhere, and could be a turn away from the exterior. + let turns = ((middle - Self.middleLongitude(of: hole)) / 360).rounded() + return .init(positions: hole.map { GeoJSON.Position(latitude: $0.latitude, longitude: $0.longitude + turns * 360, altitude: $0.altitude) }) + } + return GeoJSON.Polygon(exterior: .init(positions: exterior), interiors: interiors) + } + + private static func middleLongitude(of positions: [GeoJSON.Position]) -> Double { + let longitudes = positions.map(\.longitude) + return (longitudes.min()! + longitudes.max()!) / 2 + } + + /// The ring's positions, closed, or none if it has fewer than three corners. + private static func unwrap(_ ring: [GeoJSON.Position]) -> [GeoJSON.Position] { + var positions = ring + if positions.count > 1, positions.first?.latitude == positions.last?.latitude, positions.first?.longitude == positions.last?.longitude { + positions.removeLast() + } + guard positions.count >= 3 else { return [] } + + var corners: [GeoJSON.Position] = [] + func add(_ corner: GeoJSON.Position) { + if let last = corners.last, last.latitude == corner.latitude, last.longitude == corner.longitude { return } + // An edge along the antimeridian and back again, as a ring that's split there has, + // once they're on top of each other. + if corners.count >= 2, corners[corners.count - 2].latitude == corner.latitude, corners[corners.count - 2].longitude == corner.longitude { + corners.removeLast() + } else { + corners.append(corner) + } + } + let start = positions[0].longitude + var longitude = start + for (index, position) in positions.enumerated() { + add(GeoJSON.Position(latitude: position.latitude, longitude: longitude, altitude: position.altitude)) + var delta = positions[(index + 1) % positions.count].longitude - position.longitude + if delta > 180 { delta -= 360 } + if delta < -180 { delta += 360 } + longitude += delta + } + let turn = longitude - start + if abs(turn) > 180 { + let south = positions.reduce(0) { $0 + $1.latitude } < 0 + // Straight to the pole from the corner that's closest to it, as from anywhere else + // that could run across the ring itself. + let closest = corners.indices.min { south ? corners[$0].latitude < corners[$1].latitude : corners[$0].latitude > corners[$1].latitude } ?? 0 + let from = corners[closest] + func shifted(_ corner: GeoJSON.Position, latitude: Double? = nil) -> GeoJSON.Position { + GeoJSON.Position(latitude: latitude ?? corner.latitude, longitude: corner.longitude + turn, altitude: latitude == nil ? corner.altitude : nil) + } + let rotated = Array(corners[closest...]) + corners[.. 1, let first = corners.first, let last = corners.last, first.latitude == last.latitude, first.longitude == last.longitude { + corners.removeLast() + } + guard corners.count >= 3 else { return [] } + return corners + [corners[0]] + } +} diff --git a/Tests/GeoJSONKitTurfTests/RefinedTrianglesTests.swift b/Tests/GeoJSONKitTurfTests/RefinedTrianglesTests.swift index c35686d..f0f047a 100644 --- a/Tests/GeoJSONKitTurfTests/RefinedTrianglesTests.swift +++ b/Tests/GeoJSONKitTurfTests/RefinedTrianglesTests.swift @@ -116,6 +116,38 @@ struct RefinedTrianglesTests { #expect(triangles.count == 400) } + static let wrappingCases: [(String, [[(x: Double, y: Double)]], Double)] = [ + ("across the antimeridian", [[(170, -10), (-170, -10), (-170, 10), (170, 10), (170, -10)]], 400), + ("a hole across the antimeridian", [[(160, -20), (-160, -20), (-160, 20), (160, 20), (160, -20)], [(170, -10), (170, 10), (-170, 10), (-170, -10), (170, -10)]], 1200), + ("a hole a turn away", [[(170, -10), (190, -10), (190, 10), (170, 10), (170, -10)], [(-185, -5), (-185, 5), (-175, 5), (-175, -5), (-185, -5)]], 300), + ("around the south pole", [stride(from: -180.0, through: 180.0, by: 20).map { ($0, -70) }], 7200), + ("around the north pole", [stride(from: 180.0, through: -180.0, by: -20).map { ($0, 70) }], 7200), + // It starts on a peninsula with a bay to its south, as Antarctica's ring does, which + // can't go straight to the pole. + ("around the south pole, from over a bay", [[(0, -60), (20, -70)] + stride(from: 60.0, to: 340, by: 30).map { ($0, -70) } + [(-20, -70), (-10, -85), (5, -80), (0, -60)]], 7037.5), + ("to the south pole and back", [stride(from: -180.0, through: 180.0, by: 20).map { ($0, -70) } + [(180, -90), (-180, -90), (-180, -70)]], 7200), + ("neither", [[(10, 10), (40, 10), (40, 30), (10, 30), (10, 10)]], 600), + ] + + @Test("Unwrapped rings add up to the polygon", arguments: wrappingCases) + func unwrapped(name: String, rings: [[(x: Double, y: Double)]], area: Double) { + let unwrapped = Self.polygon(rings).unwrapped() + for ring in [unwrapped.exterior] + unwrapped.interiors { + #expect(ring.positions.first == ring.positions.last) + for (from, to) in zip(ring.positions, ring.positions.dropFirst()) { + // Other than along a pole. + #expect(abs(to.longitude - from.longitude) <= 180 || (abs(from.latitude) == 90 && to.latitude == from.latitude)) + } + } + let total = unwrapped.triangles(maxEdgeDegrees: 10).reduce(0.0) { $0 + Self.cross($1.a, $1.b, $1.c) / 2 } + #expect(abs(total - area) < 0.001 * area) + } + + @Test func unwrappedKeepsWhatDoesNotWrap() { + let polygon = Self.polygon([[(10, 10), (40, 10), (40, 30), (10, 30), (10, 10)], [(15, 15), (15, 20), (20, 20), (20, 15), (15, 15)]]) + #expect(polygon.unwrapped().positionsArray == polygon.positionsArray) + } + @Test func tooFewCorners() { #expect(Self.polygon([[(0, 0), (1, 1), (0, 0)]]).triangles(maxEdgeDegrees: 1).isEmpty) #expect(Self.polygon([[]]).triangles(maxEdgeDegrees: 1).isEmpty)