From daf362d545686d29a14d751e2c68c64b1b755953 Mon Sep 17 00:00:00 2001 From: Masashi Katsumata Date: Thu, 12 Nov 2026 16:49:28 -0800 Subject: [PATCH] Draw circle tiles on the GPU MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A circle tile went through CGContext once per circle, and each circle of a large set was read back from the geometry file as a new Shape (about 6 µs each). On US Antenna Horizons (723,800 circles) a zoomed-out tile took up to 2 s. MetalShapeRasterizer draws every circle of a tile as one instance (fill and outline by distance, 1 px antialiasing, source-over in the given order) and reads the pixels back for the Rust PNG encoder, like MetalMarkerRasterizer. The circles are read as plain values from the geometry file, and colours are converted once per palette entry. A tile with a circle bent by the projection (drawn as the 128-gon) stays on the CPU, as do tiles without Metal or with MAPCONDUCTOR_SHAPE_TILE_CPU=1. --- .../shapetile/MetalShapeRasterizer.swift | 214 ++++++++++++++++++ .../shapetile/ShapeTileRenderer.swift | 92 +++++++- .../shapetile/ShapeTileStorage.swift | 50 ++++ .../MetalShapeRasterizerTests.swift | 119 ++++++++++ 4 files changed, 473 insertions(+), 2 deletions(-) create mode 100644 Sources/MapConductorCore/shapetile/MetalShapeRasterizer.swift create mode 100644 Tests/MapConductorCoreTests/MetalShapeRasterizerTests.swift diff --git a/Sources/MapConductorCore/shapetile/MetalShapeRasterizer.swift b/Sources/MapConductorCore/shapetile/MetalShapeRasterizer.swift new file mode 100644 index 0000000..2954b67 --- /dev/null +++ b/Sources/MapConductorCore/shapetile/MetalShapeRasterizer.swift @@ -0,0 +1,214 @@ +import CoreGraphics +import Foundation +import Metal + +/// 円のタイルを GPU で描く。 +/// +/// ``MetalMarkerRasterizer`` と同じ骨格 -- オフスクリーンへ描いて読み戻し、 +/// PNG 化は core の Rust エンコーダに渡す。違うのは中身で、あちらはアトラスを +/// 貼るクアッド、こちらは円 1 つを 1 インスタンスにして、塗りと縁を距離で描く。 +/// +/// ## なぜ要るか +/// +/// CPU 側は円 1 つごとに `fillEllipse` と `strokeEllipse` を呼ぶ。US Antenna +/// Horizons(723,800 個)を引いたズームで見ると 1 タイルに 10 万個近く入り、 +/// 1 枚に 2 秒かかっていた。ピンチのたびにそれが何枚も並び、地図が止まって見えた。 +/// +/// ## CPU 経路と同じ絵にするために +/// +/// - 座標はタイルの画素(上が 0)。CPU 経路の点に `pixelRatio` を掛けたもの。 +/// - 塗り・縁とも、画素の中心から境界までの距離で 1 px 幅のアンチエイリアス。 +/// 縁は輪郭に中心を合わせた幅 `strokeWidth` の帯。 +/// - 1 つの円の中では塗りの上に縁を重ね、円どうしは渡した順に source-over で +/// 重ねる。1 回の描画命令の中でもブレンドはインスタンスの順に行われる。 +/// +/// Metal が使えないときは `nil` を返す。呼び出し側は CPU 経路へ落ちる。 +final class MetalShapeRasterizer { + + /// インスタンス 1 件。シェーダの `Instance` と同じ並び。 + struct Instance { + /// 円の中心(タイルの画素)。矩形のときは左上。 + var x: Float + var y: Float + /// 円の半径(画素)。矩形のときは幅。 + var radius: Float + /// 縁の幅(画素)。縁を描かないときは 0。矩形のときは高さ。 + var strokeWidth: Float + /// 乗算済みの RGBA。 + var fill: SIMD4 + var stroke: SIMD4 + /// 0: 円、1: 矩形(1 点の塗り)。 + var kind: UInt32 + var padding0: UInt32 = 0 + var padding1: UInt32 = 0 + var padding2: UInt32 = 0 + } + + private let device: MTLDevice + private let commandQueue: MTLCommandQueue + private let pipeline: MTLRenderPipelineState + private let queue = DispatchQueue(label: "com.mapconductor.shape.metal") + /// 描画先。画素の一辺ごとに 1 枚。 + private var targets: [Int: MTLTexture] = [:] + + private static let shaderSource = """ + #include + using namespace metal; + + struct Instance { + float x; + float y; + float radius; + float strokeWidth; + float4 fill; + float4 stroke; + uint kind; + uint pad0; + uint pad1; + uint pad2; + }; + + struct VertexOut { + float4 position [[position]]; + float2 pixel; + uint iid [[flat]]; + }; + + vertex VertexOut shape_vertex(uint vid [[vertex_id]], + uint iid [[instance_id]], + constant Instance *instances [[buffer(0)]], + constant float &extent [[buffer(1)]]) { + const float2 corners[6] = { float2(0,0), float2(1,0), float2(0,1), + float2(1,0), float2(1,1), float2(0,1) }; + float2 corner = corners[vid]; + Instance inst = instances[iid]; + float2 lo, hi; + if (inst.kind == 1) { + lo = float2(inst.x, inst.y); + hi = lo + float2(inst.radius, inst.strokeWidth); + } else { + // 縁の外側と、アンチエイリアスの 1 px ぶん広げる。 + float reach = inst.radius + inst.strokeWidth * 0.5 + 1.0; + lo = float2(inst.x, inst.y) - reach; + hi = float2(inst.x, inst.y) + reach; + } + float2 px = mix(lo, hi, corner); + float2 unit = px / extent; + VertexOut out; + out.position = float4(unit.x * 2.0 - 1.0, 1.0 - unit.y * 2.0, 0.0, 1.0); + out.pixel = px; + out.iid = iid; + return out; + } + + fragment float4 shape_fragment(VertexOut in [[stage_in]], + constant Instance *instances [[buffer(0)]]) { + Instance inst = instances[in.iid]; + if (inst.kind == 1) { + return inst.fill; + } + float d = length(in.pixel - float2(inst.x, inst.y)); + float fillCoverage = clamp(inst.radius - d + 0.5, 0.0, 1.0); + float halfWidth = inst.strokeWidth * 0.5; + float strokeCoverage = clamp(inst.radius + halfWidth - d + 0.5, 0.0, 1.0) + - clamp(inst.radius - halfWidth - d + 0.5, 0.0, 1.0); + float4 fill = inst.fill * fillCoverage; + float4 stroke = inst.stroke * strokeCoverage; + // 塗りの上に縁(乗算済みの source-over)。 + return stroke + fill * (1.0 - stroke.a); + } + """ + + /// 1 つを使い回す。パイプラインの作成は重く、描画は ``queue`` で順に流す。 + static let shared: MetalShapeRasterizer? = { + guard let device = MTLCreateSystemDefaultDevice(), + let commandQueue = device.makeCommandQueue() else { return nil } + return try? MetalShapeRasterizer(device: device, commandQueue: commandQueue) + }() + + private init(device: MTLDevice, commandQueue: MTLCommandQueue) throws { + self.device = device + self.commandQueue = commandQueue + let library = try device.makeLibrary(source: Self.shaderSource, options: nil) + let descriptor = MTLRenderPipelineDescriptor() + descriptor.vertexFunction = library.makeFunction(name: "shape_vertex") + descriptor.fragmentFunction = library.makeFunction(name: "shape_fragment") + let attachment = descriptor.colorAttachments[0]! + attachment.pixelFormat = .rgba8Unorm + attachment.isBlendingEnabled = true + attachment.rgbBlendOperation = .add + attachment.sourceRGBBlendFactor = .one + attachment.destinationRGBBlendFactor = .oneMinusSourceAlpha + attachment.alphaBlendOperation = .add + attachment.sourceAlphaBlendFactor = .one + attachment.destinationAlphaBlendFactor = .oneMinusSourceAlpha + pipeline = try device.makeRenderPipelineState(descriptor: descriptor) + } + + /// `CGColor` を乗算済みの RGBA(sRGB)にする。描かない色は nil。 + static func premultiplied(_ color: CGColor?) -> SIMD4? { + guard let color, color.alpha > 0, + let srgb = CGColorSpace(name: CGColorSpace.sRGB), + let converted = color.converted(to: srgb, intent: .defaultIntent, options: nil), + let c = converted.components, c.count >= 4 else { return nil } + let a = Float(min(max(c[3], 0), 1)) + func channel(_ v: CGFloat) -> Float { Float(min(max(v, 0), 1)) * a } + return SIMD4(channel(c[0]), channel(c[1]), channel(c[2]), a) + } + + /// 一辺 `pixels` のタイルに描いて PNG にする。描けなければ nil で、呼び出し側は CPU へ落ちる。 + func renderPng(instances: [Instance], pixels: Int) -> Data? { + guard !instances.isEmpty, pixels > 0 else { return nil } + return queue.sync { draw(instances: instances, pixels: pixels) } + } + + private func draw(instances: [Instance], pixels: Int) -> Data? { + let target: MTLTexture + if let existing = targets[pixels] { + target = existing + } else { + let descriptor = MTLTextureDescriptor.texture2DDescriptor( + pixelFormat: .rgba8Unorm, width: pixels, height: pixels, mipmapped: false) + descriptor.usage = [.renderTarget, .shaderRead] + guard let fresh = device.makeTexture(descriptor: descriptor) else { return nil } + targets[pixels] = fresh + target = fresh + } + guard let instanceBuffer = device.makeBuffer( + bytes: instances, + length: MemoryLayout.stride * instances.count, + options: .storageModeShared + ) else { return nil } + + let pass = MTLRenderPassDescriptor() + pass.colorAttachments[0].texture = target + pass.colorAttachments[0].loadAction = .clear + pass.colorAttachments[0].storeAction = .store + pass.colorAttachments[0].clearColor = MTLClearColorMake(0, 0, 0, 0) + guard let buffer = commandQueue.makeCommandBuffer(), + let encoder = buffer.makeRenderCommandEncoder(descriptor: pass) else { return nil } + + var extent = Float(pixels) + encoder.setRenderPipelineState(pipeline) + encoder.setVertexBuffer(instanceBuffer, offset: 0, index: 0) + encoder.setVertexBytes(&extent, length: MemoryLayout.size, index: 1) + encoder.setFragmentBuffer(instanceBuffer, offset: 0, index: 0) + encoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: 6, + instanceCount: instances.count) + encoder.endEncoding() + buffer.commit() + buffer.waitUntilCompleted() + guard buffer.error == nil else { return nil } + + let bytesPerRow = pixels * 4 + var readback = [UInt8](repeating: 0, count: bytesPerRow * pixels) + readback.withUnsafeMutableBytes { raw in + target.getBytes(raw.baseAddress!, bytesPerRow: bytesPerRow, + from: MTLRegionMake2D(0, 0, pixels, pixels), mipmapLevel: 0) + } + return readback.withUnsafeMutableBytes { raw -> Data? in + guard let base = raw.baseAddress else { return nil } + return TilePngEncoder.encode(rgba: base, width: pixels, height: pixels, premultiplied: true) + } + } +} diff --git a/Sources/MapConductorCore/shapetile/ShapeTileRenderer.swift b/Sources/MapConductorCore/shapetile/ShapeTileRenderer.swift index d3fe101..425ca8a 100644 --- a/Sources/MapConductorCore/shapetile/ShapeTileRenderer.swift +++ b/Sources/MapConductorCore/shapetile/ShapeTileRenderer.swift @@ -426,6 +426,16 @@ final class ShapeTileRenderer: TileProvider { ) if candidates.isEmpty { return nil } + let zoomCache = zoomCache(for: z, count: data.shapes.count) + let thinCircles = data.shapes[Int(candidates[0])]?.kind == .circle + if thinCircles, let gpu = gpuRasterizer(), + case let .drawn(png) = try drawCircles( + on: gpu, data, candidates: candidates, scale: scale, + originX: originX, originY: originY, ratio: ratio, isCancelled: isCancelled + ) { + return png + } + let pixels = tileSize * ratio let bytesPerRow = pixels * 4 guard let buffer = NSMutableData(length: bytesPerRow * pixels), @@ -442,8 +452,6 @@ final class ShapeTileRenderer: TileProvider { context.setLineJoin(.round) context.setLineCap(.round) - let zoomCache = zoomCache(for: z, count: data.shapes.count) - let thinCircles = data.shapes[Int(candidates[0])]?.kind == .circle var lastDot = [Int32](repeating: 0, count: thinCircles ? tileSize * tileSize : 0) if thinCircles { for (n, index) in candidates.enumerated() { if n & 255 == 255, isCancelled() { throw Cancelled() } @@ -527,6 +535,86 @@ final class ShapeTileRenderer: TileProvider { return png } + private enum GpuOutcome { + /// Drawn on the GPU: the PNG, or nil when nothing was drawn. + case drawn(Foundation.Data?) + /// The tile needs the CPU (a circle drawn as its 128-gon, or the GPU failed). + case fallback + } + + /// Circles only, on the GPU (``MetalShapeRasterizer``): the same choices as + /// the CPU loop in ``draw(_:z:x:y:ratio:isCancelled:)`` and ``CircleTilePainter`` + /// -- which circle a pixel keeps, Dot or Arc, outlined or not -- made into instances. + /// + /// Reads plain values (``ShapeTileStorage/circleValues(at:colors:)``): building a + /// ``Shape`` per circle from the geometry file took 6 µs, seconds for a tile of + /// a few hundred thousand, against milliseconds for drawing them all. + private func drawCircles( + on gpu: MetalShapeRasterizer, _ data: Data, candidates: [Int32], scale: Double, + originX: Double, originY: Double, ratio: Int, isCancelled: () -> Bool + ) throws -> GpuOutcome { + let colors = ShapeColorCache() + let tile = Double(tileSize) + /// -2: a circle of a pixel or more; -1: a dot outside this tile; else its pixel. + func slot(_ c: ShapeTileStorage.CircleValues) -> Int { + let radius = max(c.east - c.x, c.y - c.north, c.south - c.y) * scale + guard radius < 0.5 else { return -2 } + let x = floor(c.x * scale) - originX, y = floor(c.y * scale) - originY + guard x >= 0, x < tile, y >= 0, y < tile else { return -1 } + return Int(y) * tileSize + Int(x) + } + var lastDot = [Int32](repeating: 0, count: tileSize * tileSize) + for (n, index) in candidates.enumerated() { + if n & 4095 == 4095, isCancelled() { throw Cancelled() } + guard let c = data.shapes.circleValues(at: Int(index), colors: colors), + c.fill != nil || c.stroke != nil else { continue } + let at = slot(c) + if at >= 0 { lastDot[at] = index + 1 } + } + let r = Float(ratio) + var instances: [MetalShapeRasterizer.Instance] = [] + instances.reserveCapacity(min(candidates.count, tileSize * tileSize)) + for (n, index) in candidates.enumerated() { + if n & 4095 == 4095, isCancelled() { throw Cancelled() } + guard let c = data.shapes.circleValues(at: Int(index), colors: colors) else { continue } + let at = slot(c) + if at == -1 || (at >= 0 && lastDot[at] != index + 1) { continue } + let cx = c.x * scale, cy = c.y * scale + let rx = (c.east - c.x) * scale + let ryN = (c.y - c.north) * scale, ryS = (c.south - c.y) * scale + if max(rx, ryN, ryS) < 0.5 { + // Dot: one point, the fill colour or else the outline's. + guard let color = c.fill ?? c.stroke else { continue } + instances.append(.init( + x: Float(floor(cx) - originX) * r, y: Float(floor(cy) - originY) * r, radius: r, strokeWidth: r, + fill: color, stroke: .zero, kind: 1 + )) + continue + } + // Bent by the projection: the 128-gon, which only the CPU draws. + if max(abs(ryN - rx), abs(ryS - rx)) > CircleTilePainter.arcTolerancePx { return .fallback } + let outlined = 2 * max(rx, ryN, ryS) >= Self.minOutlinedPx + let stroke = outlined ? c.stroke : nil + if c.fill == nil && stroke == nil { continue } + instances.append(.init( + x: Float(cx - originX) * r, y: Float(cy - originY) * r, radius: Float(rx) * r, + strokeWidth: stroke == nil ? 0 : Float(c.strokeWidth) * r, + fill: c.fill ?? .zero, stroke: stroke ?? .zero, kind: 0 + )) + } + if instances.isEmpty { return .drawn(nil) } + if isCancelled() { throw Cancelled() } + guard let png = gpu.renderPng(instances: instances, pixels: tileSize * ratio) else { return .fallback } + return .drawn(png) + } + + /// The GPU rasterizer for circle tiles; nil without Metal, or with + /// `MAPCONDUCTOR_SHAPE_TILE_CPU=1` to compare against the CPU drawing. + private func gpuRasterizer() -> MetalShapeRasterizer? { + if ProcessInfo.processInfo.environment["MAPCONDUCTOR_SHAPE_TILE_CPU"] == "1" { return nil } + return MetalShapeRasterizer.shared + } + private static func add(_ ring: [Double], to path: CGMutablePath, originX: Double, originY: Double, close: Bool) { path.move(to: CGPoint(x: ring[0] - originX, y: ring[1] - originY)) var i = 2 diff --git a/Sources/MapConductorCore/shapetile/ShapeTileStorage.swift b/Sources/MapConductorCore/shapetile/ShapeTileStorage.swift index 42f412d..5169052 100644 --- a/Sources/MapConductorCore/shapetile/ShapeTileStorage.swift +++ b/Sources/MapConductorCore/shapetile/ShapeTileStorage.swift @@ -54,6 +54,47 @@ struct ShapeTileStorage { guard let file, overrides[index] == nil else { return false } return file.matches(state, at: index) } + + /// A circle as the GPU path reads it: plain values, no objects made. + struct CircleValues { + var x: Double, y: Double, north: Double, south: Double, east: Double + var strokeWidth: Double + /// Premultiplied colours; nil when not drawn. + var fill: SIMD4? + var stroke: SIMD4? + } + + /// The circle at `index` without building a ``Shape``: the file's record + /// as it is, or the overriding shape. Nil for an empty slot or another kind. + /// `colors` turns a colour into premultiplied RGBA once per colour. + func circleValues(at index: Int, colors: ShapeColorCache) -> CircleValues? { + if let file, overrides[index] == nil { + let r = file.record(at: index) + guard r.radius > 0 else { return nil } + return CircleValues( + x: r.x, y: r.y, north: r.north, south: r.south, east: r.east, strokeWidth: r.strokeWidth, + fill: file.premultipliedColor(r.fill), stroke: r.strokeWidth > 0 ? file.premultipliedColor(r.stroke) : nil + ) + } + guard let p = self[index], let c = p.circle else { return nil } + return CircleValues( + x: c.x, y: c.y, north: c.northY, south: c.southY, east: c.eastX, strokeWidth: p.strokeWidth, + fill: colors.premultiplied(p.fill), stroke: colors.premultiplied(p.stroke) + ) + } +} + +/// Premultiplied RGBA per `CGColor`, for one tile: a tile reuses a handful of colours. +final class ShapeColorCache { + private var cache: [CGColor: SIMD4?] = [:] + + func premultiplied(_ color: CGColor?) -> SIMD4? { + guard let color else { return nil } + if let hit = cache[color] { return hit } + let value = MetalShapeRasterizer.premultiplied(color) + cache[color] = value + return value + } } /// Fixed-width geometry streamed to an anonymous cache file and paged by the OS. @@ -74,6 +115,8 @@ final class CircleGeometryFile { let count: Int private let mapping: UnsafeMutableRawPointer private let colors: [CGColor] + /// The palette as premultiplied RGBA, made once: the GPU path reads a colour per circle. + private let premultipliedPalette: [SIMD4?] init(count: Int, shapeAt: (Int) -> ShapeTileRenderer.Shape?) throws { let directory = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) @@ -117,10 +160,17 @@ final class CircleGeometryFile { self.count = count self.mapping = mapped self.colors = palette + self.premultipliedPalette = palette.map { MetalShapeRasterizer.premultiplied($0) } } deinit { munmap(mapping, count * Self.stride) } + /// The colour at a record's index (0 is none) as premultiplied RGBA. + func premultipliedColor(_ index: UInt32) -> SIMD4? { + guard index > 0 else { return nil } + return premultipliedPalette[Int(index) - 1] + } + func record(at index: Int) -> Record { mapping.load(fromByteOffset: index * Self.stride, as: Record.self) } diff --git a/Tests/MapConductorCoreTests/MetalShapeRasterizerTests.swift b/Tests/MapConductorCoreTests/MetalShapeRasterizerTests.swift new file mode 100644 index 0000000..3107aac --- /dev/null +++ b/Tests/MapConductorCoreTests/MetalShapeRasterizerTests.swift @@ -0,0 +1,119 @@ +import CoreGraphics +import ImageIO +import UIKit +import XCTest + +@_spi(MapConductorDriver) @testable import MapConductorCore + +/// 円のタイルを GPU(`MetalShapeRasterizer`)と CPU(`CircleTilePainter` + CGContext)で描き、 +/// 同じ絵になることを確かめる。 +/// +/// 画素ごとの一致は求めない。アンチエイリアスの縁は描き方の違いで 1 段ずれる。 +/// 見るのは、塗りと縁の色が同じ場所に出ていること(縁の画素を除けばほぼ一致すること)と、 +/// 重ね順・小さな円の 1 点・縁なしの判定が CPU と同じであること。 +final class MetalShapeRasterizerTests: XCTestCase { + override func tearDown() { + unsetenv("MAPCONDUCTOR_SHAPE_TILE_CPU") + super.tearDown() + } + + private func decode(_ png: Data) throws -> [UInt8] { + let source = try XCTUnwrap(CGImageSourceCreateWithData(png as CFData, nil)) + let image = try XCTUnwrap(CGImageSourceCreateImageAtIndex(source, 0, nil)) + var bytes = [UInt8](repeating: 0, count: image.width * image.height * 4) + let context = try XCTUnwrap(CGContext( + data: &bytes, width: image.width, height: image.height, bitsPerComponent: 8, + bytesPerRow: image.width * 4, space: CGColorSpaceCreateDeviceRGB(), + bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue + )) + context.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height)) + return bytes + } + + /// 同じタイルを GPU と CPU で描いて、両方の画素を返す。 + private func renderBoth(_ shapes: [CircleTileShape], z: Int, x: Int, y: Int, ratio: Int = 1) throws -> (gpu: [UInt8], cpu: [UInt8]) { + try XCTSkipIf(MetalShapeRasterizer.shared == nil, "Metal が無い") + func render() throws -> [UInt8] { + let renderer = ShapeTileRenderer(pixelRatio: ratio) + renderer.setShapes(shapes.map { ShapeTileRenderer.Shape($0) }) + let png = try XCTUnwrap(renderer.renderTile(request: TileRequest(x: x, y: y, z: z))) + return try decode(png) + } + unsetenv("MAPCONDUCTOR_SHAPE_TILE_CPU") + let gpu = try render() + setenv("MAPCONDUCTOR_SHAPE_TILE_CPU", "1", 1) + let cpu = try render() + unsetenv("MAPCONDUCTOR_SHAPE_TILE_CPU") + return (gpu, cpu) + } + + /// 画素の何割が、どれかのチャンネルで `tolerance` を超えて違うか。 + private func mismatch(_ a: [UInt8], _ b: [UInt8], tolerance: Int) -> Double { + var bad = 0 + for i in stride(from: 0, to: a.count, by: 4) { + for c in 0..<4 where abs(Int(a[i + c]) - Int(b[i + c])) > tolerance { bad += 1; break } + } + return Double(bad) / Double(a.count / 4) + } + + private func worldPx(_ lat: Double, _ lng: Double, z: Int) -> (x: Double, y: Double) { + let scale = 256.0 * Double(1 << z) + let s = sin(lat * .pi / 180) + return ((lng + 180) / 360 * scale, (0.5 - log((1 + s) / (1 - s)) / (4 * .pi)) * scale) + } + + /// ボストン周辺に、色・透明度・大きさ・縁がまちまちの円を `count` 個。乱数は固定。 + private func scatter(count: Int, spanDegrees: Double, radiusMeters: ClosedRange) -> [CircleTileShape] { + var seed: UInt64 = 0x9E37_79B9_7F4A_7C15 + func next() -> Double { + seed = seed &* 6364136223846793005 &+ 1442695040888963407 + return Double(seed >> 11) / Double(1 << 53) + } + let palette: [UIColor] = [.red, .blue, .green, .orange, .purple] + return (0.. (x: Int, y: Int) { + let p = worldPx(42.36, -71.06, z: z) + return (Int(p.x / 256), Int(p.y / 256)) + } + + /// 街の円(数十〜数百 px)。塗り・縁・重なりがどれも見える大きさ。 + func testCityCirclesMatchTheCpuDrawing() throws { + let z = 15 + let t = tile(z: z) + let both = try renderBoth(scatter(count: 400, spanDegrees: 0.02, radiusMeters: 20...300), z: z, x: t.x, y: t.y) + // 縁のアンチエイリアス以外は一致する。 + XCTAssertLessThan(mismatch(both.gpu, both.cpu, tolerance: 48), 0.02) + XCTAssertLessThan(mismatch(both.gpu, both.cpu, tolerance: 8), 0.08) + } + + /// Retina のタイル(ratio 2)も同じ。 + func testRetinaTilesMatchTheCpuDrawing() throws { + let z = 15 + let t = tile(z: z) + let both = try renderBoth(scatter(count: 200, spanDegrees: 0.02, radiusMeters: 20...300), z: z, x: t.x, y: t.y, ratio: 2) + XCTAssertEqual(both.gpu.count, 512 * 512 * 4) + XCTAssertLessThan(mismatch(both.gpu, both.cpu, tolerance: 48), 0.02) + } + + /// 引いたズーム: 多くが 1 点か数 px。1 画素に重なった円は最後の 1 つだけ、が CPU と同じ。 + func testZoomedOutDotsMatchTheCpuDrawing() throws { + let z = 9 + let t = tile(z: z) + let both = try renderBoth(scatter(count: 20_000, spanDegrees: 1.5, radiusMeters: 50...800), z: z, x: t.x, y: t.y) + XCTAssertLessThan(mismatch(both.gpu, both.cpu, tolerance: 48), 0.03) + } +}