Compare commits

...

1 Commits
v1.8.0 ... main

Author SHA1 Message Date
callebtc
04995f68e4
Port the Android globe geohash picker to iOS (#1807)
* Port the Android globe geohash picker to iOS

Adds the 3D globe picker from bitchat-android: a map button next to the
geohash field opens a full-screen orthographic globe (Natural Earth land,
borders and cities, geohash grid, crosshair) with drag/fling, pinch, tap
and double-tap, precision buttons and a fly-in to the current geohash.
Selecting teleports like typing a geohash.

Beyond a straight port:
- Fix ocean painted as land: the point-in-ring test counted the
  antimeridian seam as a crossing for Eurasia, flipping its fill over the
  Pacific and Atlantic. Android has the same bug.
- Motion detail only steps down within one gesture, so layers no longer
  flash on and off while dragging.
- The geohash grid and city dots draw at every detail level instead of
  vanishing while the globe moves.

Extracts GeohashCoverage so the sheet and picker share the cell-size
string, and adds the picker strings in all locales.

* Let the globe reach polar targets past the drag limit

A polar cell's center can lie past the ±89° drag limit (zzzz is at
89.91°). The animated intro clamped its latitude there and selected
zzzf, while the Reduce Motion path kept zzzz. Animations now always
reach their target; dragging keeps the limit on the far side and never
snaps a polar view back to it.
2026-10-25 02:55:00 +02:00
14 changed files with 4123 additions and 50 deletions

View File

@ -38,7 +38,10 @@ let package = Package(
"bitchat.entitlements",
"bitchat-macOS.entitlements",
"LaunchScreen.storyboard",
"ViewModels/Extensions/README.md"
"ViewModels/Extensions/README.md",
// Globe picker geometry, bundled by the Xcode app targets and read
// from Bundle.main; the SwiftPM build only runs tests.
"Resources/Globe"
],
resources: [
.process("Localizable.xcstrings")

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,67 @@
//
// GeohashCoverage.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Human-readable size of a geohash cell, shared by the location channels sheet and
/// the globe picker.
enum GeohashCoverage {
/// Approximate max cell dimension at the equator, e.g. "~4.9 km" or "~3.0 mi".
static func string(forPrecision len: Int, locale: Locale = .current) -> String {
// Values sourced from common geohash dimension tables.
let maxMeters: Double = {
switch len {
case 2: return 1_250_000
case 3: return 156_000
case 4: return 39_100
case 5: return 4_890
case 6: return 1_220
case 7: return 153
case 8: return 38.2
case 9: return 4.77
case 10: return 1.19
default:
if len <= 1 { return 5_000_000 }
// For >10, scale down conservatively by ~1/4 each char
let over = len - 10
return 1.19 * pow(0.25, Double(over))
}
}()
if usesMetric(locale) {
return "~\(formatDistance(maxMeters / 1000.0)) km"
} else {
return "~\(formatDistance(maxMeters / 1609.344)) mi"
}
}
/// Channel level a geohash of this length belongs to.
static func level(forLength length: Int) -> GeohashChannelLevel {
switch length {
case ...2: return .region
case 3...4: return .province
case 5: return .city
case 6: return .neighborhood
case 7: return .block
default: return .building
}
}
static func usesMetric(_ locale: Locale = .current) -> Bool {
if #available(iOS 16.0, macOS 13.0, *) {
return locale.measurementSystem == .metric
} else {
return locale.usesMetricSystem
}
}
private static func formatDistance(_ value: Double) -> String {
if value >= 100 { return String(format: "%.0f", value.rounded()) }
return String(format: "%.1f", value)
}
}

View File

@ -0,0 +1,250 @@
//
// GeohashPickerView.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import SwiftUI
/// Full-screen 3D globe for choosing a geohash channel to teleport to. The cell under
/// the crosshair is the selection; zooming changes precision, and the +/- buttons step
/// precision while framing the cell.
struct GeohashPickerView: View {
let onSelect: (String) -> Void
let onCancel: () -> Void
@StateObject private var state: GlobeState
@State private var world: GlobeWorldData?
@Environment(\.colorScheme) private var colorScheme
@ThemedPalette private var palette
private enum Strings {
static let instruction = String(localized: "geohash_picker.instruction", defaultValue: "drag to spin · pinch to zoom · tap to focus", comment: "Hint at the top of the globe geohash picker explaining its gestures")
static let noSelection = String(localized: "geohash_picker.no_selection", defaultValue: "select location", comment: "Shown in the globe geohash picker before a geohash is under the crosshair")
static let select = String(localized: "geohash_picker.select", defaultValue: "select", comment: "Button in the globe geohash picker that teleports to the geohash under the crosshair")
static let selectHint = String(localized: "geohash_picker.accessibility.select", defaultValue: "select geohash", comment: "Accessibility label for the globe picker's select button")
static let decreasePrecision = String(localized: "geohash_picker.accessibility.decrease_precision", defaultValue: "decrease precision", comment: "Accessibility label for the globe picker button that zooms out to a larger geohash cell")
static let increasePrecision = String(localized: "geohash_picker.accessibility.increase_precision", defaultValue: "increase precision", comment: "Accessibility label for the globe picker button that zooms in to a smaller geohash cell")
}
/// - Parameters:
/// - initialGeohash: cell to fly to; when empty, the coarsest of
/// `nearbyGeohashes` is used, else a wide view of the world.
init(
initialGeohash: String?,
nearbyGeohashes: [String] = [],
onSelect: @escaping (String) -> Void,
onCancel: @escaping () -> Void
) {
self.onSelect = onSelect
self.onCancel = onCancel
let target = Self.initialTarget(initialGeohash: initialGeohash, nearbyGeohashes: nearbyGeohashes)
_state = StateObject(wrappedValue: GlobeState(
targetLat: target.lat,
targetLon: target.lon,
initialPrecision: target.precision,
startZoomedOut: true
))
}
/// Where the intro flies to: the given geohash, else the coarsest nearby channel,
/// else a wide view at precision 2.
static func initialTarget(initialGeohash: String?, nearbyGeohashes: [String]) -> (lat: Double, lon: Double, precision: Int) {
let initial = (initialGeohash ?? "").trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
let focus = Geohash.isValidGeohash(initial)
? initial
: nearbyGeohashes.filter(Geohash.isValidGeohash).min { $0.count < $1.count }
guard let focus else { return (20, 0, 2) }
let center = Geohash.decodeCenter(focus)
return (center.lat, center.lon, min(max(focus.count, 1), GlobeMath.maxPrecision))
}
var body: some View {
ZStack {
palette.background
.ignoresSafeArea()
if let world {
GlobeView(state: state, colors: globeColors, world: world)
.ignoresSafeArea()
}
VStack(spacing: 0) {
topBar
Spacer(minLength: 0)
bottomControls
}
.padding(.horizontal, 16)
.padding(.top, 20)
.padding(.bottom, 20)
}
#if os(macOS)
.frame(minWidth: 560, minHeight: 640)
#endif
.task {
guard world == nil else { return }
world = await Task.detached(priority: .userInitiated) { GlobeWorldData.bundled }.value
}
}
// MARK: - Chrome
private var topBar: some View {
HStack(spacing: 10) {
Text(Strings.instruction)
.bitchatFont(size: 12)
.foregroundColor(palette.primary)
.multilineTextAlignment(.center)
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 14)
.padding(.vertical, 10)
.frame(maxWidth: .infinity)
.geohashPickerPanel()
SheetCloseButton(action: onCancel)
.foregroundColor(palette.primary)
.frame(width: 40, height: 40)
.geohashPickerPanel(cornerRadius: 20)
}
}
private var bottomControls: some View {
VStack(spacing: 10) {
VStack(spacing: 2) {
Text(verbatim: hasSelection ? "#\(state.selectedGeohash)" : Strings.noSelection)
.bitchatFont(size: 14, weight: .medium)
.foregroundColor(palette.primary)
if hasSelection {
Text(verbatim: "\(GeohashCoverage.level(forLength: state.precision).displayName) • \(GeohashCoverage.string(forPrecision: state.precision))")
.bitchatFont(size: 10)
.foregroundColor(palette.secondary)
}
}
.padding(.horizontal, 16)
.padding(.vertical, 8)
.geohashPickerPanel()
.accessibilityElement(children: .combine)
HStack(spacing: 10) {
precisionButton(systemImage: "minus", label: Strings.decreasePrecision) {
state.animatePrecision(state.precision - 1)
}
precisionButton(systemImage: "plus", label: Strings.increasePrecision) {
state.animatePrecision(state.precision + 1)
}
Button {
guard hasSelection else { return }
onSelect(state.selectedGeohash)
} label: {
HStack(spacing: 6) {
Image(systemName: "checkmark")
.font(.bitchatSystem(size: 14, weight: .semibold))
Text(verbatim: Strings.select)
.bitchatFont(size: 12)
}
.foregroundColor(palette.primary)
.pickerCapsule(fill: palette.accentBlue.opacity(0.12))
}
.buttonStyle(.plain)
.disabled(!hasSelection)
.opacity(hasSelection ? 1 : 0.38)
.accessibilityLabel(Strings.selectHint)
}
}
}
private func precisionButton(systemImage: String, label: String, action: @escaping () -> Void) -> some View {
Button(action: action) {
Image(systemName: systemImage)
.font(.bitchatSystem(size: 16, weight: .semibold))
.foregroundColor(palette.locationAccent)
.pickerCapsule(fill: palette.locationAccent.opacity(0.12))
}
.buttonStyle(.plain)
.accessibilityLabel(label)
}
private var hasSelection: Bool { !state.selectedGeohash.isEmpty }
// MARK: - Globe palette
/// Fixed land/ocean tones shared with the Android picker; the accent follows the
/// theme's location color.
private var globeColors: GlobeColors {
let accent = palette.locationAccent
if colorScheme == .dark {
let onSurface = Color(red: 0.961, green: 0.961, blue: 0.961)
let onSurfaceVariant = Color(red: 0.604, green: 0.651, blue: 0.604)
return GlobeColors(
accent: accent,
land: Color(red: 0.086, green: 0.141, blue: 0.106),
coastline: accent.opacity(0.45),
border: onSurfaceVariant.opacity(0.5),
oceanCenter: Color(red: 0.039, green: 0.078, blue: 0.063),
oceanEdge: Color(red: 0.008, green: 0.024, blue: 0.016),
atmosphere: accent,
graticule: onSurface.opacity(0.055),
grid: onSurfaceVariant.opacity(0.6),
label: onSurfaceVariant,
labelHalo: palette.background,
star: onSurface
)
} else {
let onSurface = Color(red: 0.075, green: 0.102, blue: 0.075)
let onSurfaceVariant = Color(red: 0.298, green: 0.341, blue: 0.298)
return GlobeColors(
accent: accent,
land: Color(red: 0.737, green: 0.824, blue: 0.753),
coastline: accent.opacity(0.5),
border: onSurfaceVariant.opacity(0.6),
oceanCenter: Color(red: 0.918, green: 0.949, blue: 0.925),
oceanEdge: Color(red: 0.831, green: 0.886, blue: 0.843),
atmosphere: accent,
graticule: onSurface.opacity(0.08),
grid: onSurfaceVariant.opacity(0.7),
label: onSurfaceVariant,
labelHalo: palette.background,
star: onSurfaceVariant
)
}
}
}
// MARK: - Styling
private struct GeohashPickerPanel: ViewModifier {
@Environment(\.appTheme) private var theme
@ThemedPalette private var palette
let cornerRadius: CGFloat
@ViewBuilder
func body(content: Content) -> some View {
if theme.usesGlassChrome {
content.themedOverlayPanel()
} else {
let shape = RoundedRectangle(cornerRadius: cornerRadius, style: .continuous)
content
.background(shape.fill(palette.background.opacity(0.85)))
.overlay(shape.stroke(palette.divider, lineWidth: 1))
.shadow(color: .black.opacity(0.25), radius: 6, x: 0, y: 2)
}
}
}
private extension View {
/// Floating translucent surface for the picker's hint, readout and close button.
func geohashPickerPanel(cornerRadius: CGFloat = 12) -> some View {
modifier(GeohashPickerPanel(cornerRadius: cornerRadius))
}
/// Pill button body sized like a standard 40pt-tall button.
func pickerCapsule(fill: Color) -> some View {
self
.padding(.horizontal, 24)
.frame(minHeight: 40)
.background(Capsule().fill(fill))
.contentShape(Capsule())
}
}

View File

@ -0,0 +1,285 @@
//
// GlobeGeometry.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import CoreGraphics
import Foundation
/// Polygon/polyline helpers that turn projected geometry into drawable screen paths:
/// splitting at the limb, closing fills along the horizon, and clipping to the viewport.
enum GlobeGeometry {
/// A projected point in disc units (radius 1, screen y down).
struct DiscPoint: Equatable {
let x: Double
let y: Double
let front: Bool
}
/// Core Graphics loses precision with path coordinates far outside the view, which
/// happens at high globe zoom. All geometry is clipped to an expanded viewport rect
/// in screen space before it becomes a path.
struct ClipRect {
let left: Double
let top: Double
let right: Double
let bottom: Double
init(size: CGSize) {
left = -Double(size.width)
top = -Double(size.height)
right = Double(size.width) * 2
bottom = Double(size.height) * 2
}
init(left: Double, top: Double, right: Double, bottom: Double) {
self.left = left
self.top = top
self.right = right
self.bottom = bottom
}
}
private static func limbPoint(behind: DiscPoint, front: DiscPoint) -> CGPoint {
var lo = 0.0
var hi = 1.0
for _ in 0..<14 {
let t = (lo + hi) / 2
let x = behind.x + (front.x - behind.x) * t
let y = behind.y + (front.y - behind.y) * t
if x * x + y * y < 1 { lo = t } else { hi = t }
}
let t = (lo + hi) / 2
return CGPoint(x: behind.x + (front.x - behind.x) * t, y: behind.y + (front.y - behind.y) * t)
}
/// Splits a projected polygon into front-facing runs (disc units). Runs that touch the
/// limb are padded with the horizon intersection point so they can be closed along the
/// horizon. Pass `closed = false` for open polylines (border lines).
static func frontRuns(_ pts: [DiscPoint], closed: Bool = true) -> [[CGPoint]] {
guard let first = pts.first, let last = pts.last else { return [] }
var runs: [[CGPoint]] = []
var run: [CGPoint] = []
var prev: DiscPoint? = closed ? last : nil
for cur in pts {
if cur.front {
if run.isEmpty, let p = prev, !p.front { run.append(limbPoint(behind: p, front: cur)) }
// Antimeridian wrap: consecutive front points can jump across the whole
// disc when a polygon crosses ±180° — break the run instead of drawing
// a chord through the view.
if let tail = run.last {
let dx = cur.x - Double(tail.x)
let dy = cur.y - Double(tail.y)
if dx * dx + dy * dy > 1.2 {
runs.append(run)
run = []
}
}
run.append(CGPoint(x: cur.x, y: cur.y))
} else if !run.isEmpty, let p = prev {
run.append(limbPoint(behind: p, front: cur))
runs.append(run)
run = []
}
prev = cur
}
if !run.isEmpty {
if closed, !runs.isEmpty, first.front, last.front {
runs[0] = run + runs[0]
} else {
// A fully front-facing ring has no limb transition to terminate its run.
// Close it explicitly; cell boundary sampling intentionally omits the
// duplicated final corner.
if closed, runs.isEmpty, first.front, last.front, let head = run.first {
run.append(head)
}
runs.append(run)
}
}
return runs
}
/// Builds a fill polygon (screen units) for a projected ring by clamping back-facing
/// points onto the limb and inserting horizon arc steps between consecutive limb
/// points, so the result approximates (polygon ∩ visible disc) without
/// self-intersecting chords.
static func fillPolygon(_ pts: [DiscPoint], cx: Double, cy: Double, r: Double) -> [CGPoint] {
var out: [CGPoint] = []
out.reserveCapacity(pts.count + 128)
var prevLimbAngle: Double?
var firstLimbAngle: Double?
func addArc(from: Double, to: Double) {
var d = to - from
while d > .pi { d -= 2 * .pi }
while d < -.pi { d += 2 * .pi }
let steps = min(max(Int(abs(d) / 0.04), 1), 64)
for s in 1..<steps {
let a = from + d * Double(s) / Double(steps)
out.append(CGPoint(x: cx + cos(a) * r, y: cy + sin(a) * r))
}
}
for p in pts {
if p.front {
out.append(CGPoint(x: cx + p.x * r, y: cy + p.y * r))
prevLimbAngle = nil
} else {
let len = (p.x * p.x + p.y * p.y).squareRoot()
let lx = len > 1e-6 ? p.x / len : 0
let ly = len > 1e-6 ? p.y / len : -1
let angle = atan2(ly, lx)
if let prev = prevLimbAngle { addArc(from: prev, to: angle) }
if firstLimbAngle == nil { firstLimbAngle = angle }
out.append(CGPoint(x: cx + lx * r, y: cy + ly * r))
prevLimbAngle = angle
}
}
// Wrap-around arc if the ring ends and starts on the limb.
if let lastAngle = prevLimbAngle, let firstAngle = firstLimbAngle, let head = pts.first, !head.front {
addArc(from: lastAngle, to: firstAngle)
}
return out
}
/// Sutherland–Hodgman clip of a polygon to the rect.
static func clipPolygon(_ pts: [CGPoint], to rect: ClipRect) -> [CGPoint] {
func clipEdge(
_ input: [CGPoint],
inside: (CGPoint) -> Bool,
intersect: (CGPoint, CGPoint) -> CGPoint
) -> [CGPoint] {
guard var s = input.last else { return input }
var result: [CGPoint] = []
result.reserveCapacity(input.count + 4)
for e in input {
let eIn = inside(e)
if eIn {
if !inside(s) { result.append(intersect(s, e)) }
result.append(e)
} else if inside(s) {
result.append(intersect(s, e))
}
s = e
}
return result
}
let left = CGFloat(rect.left), right = CGFloat(rect.right)
let top = CGFloat(rect.top), bottom = CGFloat(rect.bottom)
var out = pts
out = clipEdge(out, inside: { $0.x >= left }) { a, b in
CGPoint(x: left, y: a.y + (left - a.x) / (b.x - a.x) * (b.y - a.y))
}
out = clipEdge(out, inside: { $0.x <= right }) { a, b in
CGPoint(x: right, y: a.y + (right - a.x) / (b.x - a.x) * (b.y - a.y))
}
out = clipEdge(out, inside: { $0.y >= top }) { a, b in
CGPoint(x: a.x + (top - a.y) / (b.y - a.y) * (b.x - a.x), y: top)
}
out = clipEdge(out, inside: { $0.y <= bottom }) { a, b in
CGPoint(x: a.x + (bottom - a.y) / (b.y - a.y) * (b.x - a.x), y: bottom)
}
return out
}
/// Liang–Barsky clip of a segment to the rect; returns the clipped endpoints or nil.
static func clipSegment(_ a: CGPoint, _ b: CGPoint, to rect: ClipRect) -> (CGPoint, CGPoint)? {
let x0 = Double(a.x), y0 = Double(a.y)
let dx = Double(b.x) - x0
let dy = Double(b.y) - y0
var u1 = 0.0
var u2 = 1.0
func test(_ p: Double, _ q: Double) -> Bool {
if p == 0 { return q >= 0 }
let r = q / p
if p < 0 {
if r > u2 { return false }
if r > u1 { u1 = r }
} else {
if r < u1 { return false }
if r < u2 { u2 = r }
}
return true
}
guard test(-dx, x0 - rect.left),
test(dx, rect.right - x0),
test(-dy, y0 - rect.top),
test(dy, rect.bottom - y0) else { return nil }
return (
CGPoint(x: x0 + u1 * dx, y: y0 + u1 * dy),
CGPoint(x: x0 + u2 * dx, y: y0 + u2 * dy)
)
}
/// Orthographic projection can choose the wrong side of the horizon closure for very
/// large rings. A single center-point check is ambiguous for a large polygon and
/// caused an occasional whole-disc fill, so compare several visible points with the
/// original geographic ring and invert only when the opposite fill wins clearly.
static func projectedFillNeedsInversion(
polygon: [CGPoint],
ring: GlobeRing,
cx: Double,
cy: Double,
r: Double,
centerLat: Double,
centerLon: Double
) -> Bool {
let samples: [(Double, Double)] = [
(0, 0), (-0.5, 0), (0.5, 0), (0, -0.5), (0, 0.5),
(-0.35, -0.35), (0.35, -0.35), (-0.35, 0.35), (0.35, 0.35)
]
var normalErrors = 0
var invertedErrors = 0
for (nx, ny) in samples {
guard let location = GlobeMath.unproject(x: nx, y: ny, centerLat: centerLat, centerLon: centerLon) else { continue }
let geographicInside = ringContains(ring, lat: location.lat, lon: location.lon)
let projectedInside = polygonContains(polygon, x: cx + nx * r, y: cy + ny * r)
if projectedInside != geographicInside { normalErrors += 1 }
if !projectedInside != geographicInside { invertedErrors += 1 }
}
return invertedErrors < normalErrors
}
/// Even-odd point-in-polygon test in screen space.
static func polygonContains(_ polygon: [CGPoint], x: Double, y: Double) -> Bool {
guard polygon.count >= 3, var previous = polygon.last else { return false }
var inside = false
for current in polygon {
let cy = Double(current.y), py = Double(previous.y)
if (cy > y) != (py > y) {
let intersectionX = (Double(previous.x) - Double(current.x)) * (y - cy) / (py - cy) + Double(current.x)
if x < intersectionX { inside.toggle() }
}
previous = current
}
return inside
}
/// Point-in-ring test in geographic space: counts the ring edges that cross the
/// probe's meridian north of it. Each edge is followed the short way around, so a
/// ring that wraps the antimeridian (Eurasia at Chukotka) has no false crossing at
/// the ±180° seam. Comparing raw relative longitudes there misjudged whole oceans
/// as inside Eurasia, which flipped its fill over the Pacific and Atlantic.
static func ringContains(_ ring: GlobeRing, lat: Double, lon: Double) -> Bool {
guard ring.count >= 3 else { return false }
var inside = false
var previousIndex = ring.count - 1
for index in 0..<ring.count {
let startLat = ring.lats[previousIndex]
let endLat = ring.lats[index]
let start = GlobeMath.normalizeLon(ring.lons[previousIndex] - lon)
// Unbounded on purpose: the end only changes sign relative to the start
// when the edge crosses the probe meridian, never when it crosses ±180°.
let end = start + GlobeMath.normalizeLon(ring.lons[index] - ring.lons[previousIndex])
if (start > 0) != (end > 0) {
let t = start / (start - end)
if startLat + (endLat - startLat) * t > lat { inside.toggle() }
}
previousIndex = index
}
return inside
}
}

View File

@ -0,0 +1,149 @@
//
// GlobeMath.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// Orthographic globe projection and geohash zoom math for the 3D globe picker.
///
/// The globe is rendered as a disc of radius R centered on screen. Points are
/// projected with an orthographic projection around a view center lat/lon.
enum GlobeMath {
static let minZoom: Double = 1
static let maxZoom: Double = 120_000
static let maxPrecision = 12
struct Projection: Equatable {
/// Disc coordinates in units of globe radius, screen y down.
let x: Double
let y: Double
/// Cosine of the angular distance from the view center; negative on the far side.
let cosC: Double
}
/// Per-point sin/cos of latitude and longitude. Preparing these once removes
/// nearly all trigonometry from animated frames.
struct Terms: Sendable {
let sinLat: Double
let cosLat: Double
let sinLon: Double
let cosLon: Double
init(lat: Double, lon: Double) {
let latRadians = lat * .pi / 180
let lonRadians = lon * .pi / 180
sinLat = sin(latRadians)
cosLat = cos(latRadians)
sinLon = sin(lonRadians)
cosLon = cos(lonRadians)
}
}
/// Frame-local projector for prepared static geometry: center terms are calculated once.
struct PreparedProjector {
private let sinCenterLat: Double
private let cosCenterLat: Double
private let sinCenterLon: Double
private let cosCenterLon: Double
init(centerLat: Double, centerLon: Double) {
let latRadians = centerLat * .pi / 180
let lonRadians = centerLon * .pi / 180
sinCenterLat = sin(latRadians)
cosCenterLat = cos(latRadians)
sinCenterLon = sin(lonRadians)
cosCenterLon = cos(lonRadians)
}
func project(_ terms: Terms) -> Projection {
let sinDeltaLon = terms.sinLon * cosCenterLon - terms.cosLon * sinCenterLon
let cosDeltaLon = terms.cosLon * cosCenterLon + terms.sinLon * sinCenterLon
return Projection(
x: terms.cosLat * sinDeltaLon,
y: -(cosCenterLat * terms.sinLat - sinCenterLat * terms.cosLat * cosDeltaLon),
cosC: sinCenterLat * terms.sinLat + cosCenterLat * terms.cosLat * cosDeltaLon
)
}
}
/// Projects (lat, lon) onto the view disc of a globe centered at (centerLat, centerLon).
/// `cosC` is negative when the point is on the far side of the sphere.
static func projectRaw(lat: Double, lon: Double, centerLat: Double, centerLon: Double) -> Projection {
let phi = lat * .pi / 180
let phi0 = centerLat * .pi / 180
let dLambda = normalizeLon(lon - centerLon) * .pi / 180
let cosC = sin(phi0) * sin(phi) + cos(phi0) * cos(phi) * cos(dLambda)
let x = cos(phi) * sin(dLambda)
let y = -(cos(phi0) * sin(phi) - sin(phi0) * cos(phi) * cos(dLambda))
return Projection(x: x, y: y, cosC: cosC)
}
/// Like `projectRaw` but nil when the point is behind the limb.
static func project(lat: Double, lon: Double, centerLat: Double, centerLon: Double) -> Projection? {
let p = projectRaw(lat: lat, lon: lon, centerLat: centerLat, centerLon: centerLon)
return p.cosC >= 0 ? p : nil
}
/// Inverse projection: disc coordinates (units of radius, screen y down) back to lat/lon.
/// Returns nil if the point lies outside the disc.
static func unproject(x: Double, y: Double, centerLat: Double, centerLon: Double) -> (lat: Double, lon: Double)? {
let rho = (x * x + y * y).squareRoot()
if rho > 1 { return nil }
let c = asin(min(1, max(-1, rho)))
let phi0 = centerLat * .pi / 180
let sinC = sin(c)
let cosC = cos(c)
let lat: Double
let lonOffset: Double
if rho < 1e-9 {
lat = centerLat
lonOffset = 0
} else {
lat = asin(cosC * sin(phi0) + (-y) * sinC * cos(phi0) / rho) * 180 / .pi
lonOffset = atan2(x * sinC, rho * cos(phi0) * cosC - (-y) * sin(phi0) * sinC) * 180 / .pi
}
return (lat, normalizeLon(centerLon + lonOffset))
}
static func normalizeLon(_ lon: Double) -> Double {
var x = lon.truncatingRemainder(dividingBy: 360)
if x > 180 { x -= 360 }
if x < -180 { x += 360 }
return x
}
/// Longitude span of a geohash cell in degrees.
static func cellSpanLon(precision: Int) -> Double {
360 / pow(2, (5 * Double(precision) / 2).rounded(.up))
}
/// Latitude span of a geohash cell in degrees.
static func cellSpanLat(precision: Int) -> Double {
180 / pow(2, (5 * Double(precision) / 2).rounded(.down))
}
/// Picks the geohash precision whose cells render at a comfortable on-screen size
/// for the current zoom: the largest precision whose cell is at least ~22% of the
/// screen's smallest dimension.
static func autoPrecision(globeRadius: Double, screenMin: Double) -> Int {
let target = screenMin * 0.22
var best = 1
for p in 1...maxPrecision {
let span = cellSpanLat(precision: p) * .pi / 180 * globeRadius
if span >= target { best = p } else { break }
}
return min(max(best, 1), maxPrecision)
}
/// Zoom factor (globe radius multiplier over the fit-to-screen base radius) that frames
/// a cell of the given precision nicely: the cell spans ~1/3 of the screen.
static func zoomForPrecision(_ precision: Int, baseRadius: Double, screenMin: Double) -> Double {
let spanRadians = cellSpanLat(precision: precision) * .pi / 180
let targetRadius = (screenMin / 3) / spanRadians
return min(max(targetRadius / baseRadius, minZoom), maxZoom)
}
}

View File

@ -0,0 +1,552 @@
//
// GlobeState.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Combine
import Foundation
import QuartzCore
#if os(iOS)
import UIKit
#endif
/// How much of the globe a moving frame draws. Detail drops while the globe moves
/// on slow devices and is fully restored once interaction settles. The geohash grid
/// (selected cell and its neighbors) and the city dots are not part of this: both
/// are cheap next to the land geometry, and making them vanish while dragging and
/// pop back on release read as a rendering bug.
enum GlobeMotionDetail: Equatable, Comparable {
case full
case balanced
case fast
struct Frame: Equatable {
let graticuleStepDegrees: Double
let landPointStride: Int
let showBorders: Bool
let showCityLabels: Bool
}
var frame: Frame {
switch self {
case .full:
return Frame(graticuleStepDegrees: 4, landPointStride: 1, showBorders: true,
showCityLabels: true)
case .balanced:
return Frame(graticuleStepDegrees: 8, landPointStride: 2, showBorders: true,
showCityLabels: false)
case .fast:
return Frame(graticuleStepDegrees: 10, landPointStride: 2, showBorders: false,
showCityLabels: false)
}
}
/// Ordered from least to most detailed.
static func < (lhs: GlobeMotionDetail, rhs: GlobeMotionDetail) -> Bool {
lhs.rank < rhs.rank
}
private var rank: Int {
switch self {
case .fast: return 0
case .balanced: return 1
case .full: return 2
}
}
var moreDetailed: GlobeMotionDetail {
switch self {
case .fast: return .balanced
case .balanced, .full: return .full
}
}
/// The level measured frame cadence calls for. Hysteresis alone cannot stop
/// oscillation (shedding detail is what makes frames fast again), so `GlobeState`
/// only ever applies downgrades while the globe is moving.
func next(averageFrameMillis: Double) -> GlobeMotionDetail {
guard averageFrameMillis.isFinite else { return .fast }
switch self {
case .full:
if averageFrameMillis > 34 { return .fast }
if averageFrameMillis > 22 { return .balanced }
return .full
case .balanced:
if averageFrameMillis > 29 { return .fast }
if averageFrameMillis < 18.5 { return .full }
return .balanced
case .fast:
return averageFrameMillis < 22 ? .balanced : .fast
}
}
}
/// Picks the detail level for moving frames. A motion session spans everything from
/// touch-down through any fling or animation until the globe is at rest.
///
/// Within a session detail only ever steps down: shedding layers is what makes
/// frames fast again, so letting measured cadence step back up made neighbor cells,
/// labels and the grid flash on and off while dragging. Between sessions, a smooth
/// one lets the next start a level higher, until any session has had to shed detail.
struct GlobeMotionGovernor {
static let frameSampleCount = 8
static let smoothFrameMillis = 18.5
static let maxSampledFrameMillis = 50.0
private(set) var detail: GlobeMotionDetail = .full
private(set) var isSessionActive = false
private var startDetail: GlobeMotionDetail = .balanced
private var ceilingFound = false
private var sessionDegraded = false
private var windowMillis = 0.0
private var windowCount = 0
private var sessionMillis = 0.0
private var sessionCount = 0
mutating func beginSession() {
guard !isSessionActive else { return }
isSessionActive = true
sessionDegraded = false
windowMillis = 0
windowCount = 0
sessionMillis = 0
sessionCount = 0
detail = startDetail
}
mutating func recordFrame(millis: Double) {
guard isSessionActive else { return }
let frameMillis = min(max(millis, 1), Self.maxSampledFrameMillis)
windowMillis += frameMillis
windowCount += 1
sessionMillis += frameMillis
sessionCount += 1
guard windowCount >= Self.frameSampleCount else { return }
let wanted = detail.next(averageFrameMillis: windowMillis / Double(windowCount))
if wanted < detail {
detail = wanted
sessionDegraded = true
}
windowMillis = 0
windowCount = 0
}
/// Back to full detail at rest; remembers where the next session should start.
mutating func endSession() {
guard isSessionActive else { return }
isSessionActive = false
if sessionDegraded {
ceilingFound = true
startDetail = detail
} else if !ceilingFound,
sessionCount >= Self.frameSampleCount,
sessionMillis / Double(sessionCount) < Self.smoothFrameMillis {
startDetail = detail.moreDetailed
}
detail = .full
}
}
/// Hoisted state for the interactive 3D globe: view center, zoom, geohash precision
/// and the current selection. All mutation funnels through this class so rendering,
/// gestures and buttons stay in sync.
@MainActor
final class GlobeState: ObservableObject {
@Published private(set) var centerLat: Double
@Published private(set) var centerLon: Double
@Published private(set) var zoom: Double
@Published private(set) var precision: Int
@Published private(set) var selectedGeohash = ""
@Published private(set) var isInteracting = false
@Published private(set) var isAnimating = false
/// Detail level for moving frames; `.full` whenever the globe is at rest.
@Published private(set) var motionDetail: GlobeMotionDetail = .full
private(set) var baseRadius: Double = 0
private(set) var screenMin: Double = 0
/// Pending cinematic intro target; consumed once the viewport is known.
private var introTarget: (lat: Double, lon: Double, precision: Int)?
private var motion: Motion?
private var lastTick: CFTimeInterval?
private var governor = GlobeMotionGovernor()
private lazy var clock = GlobeFrameClock { [weak self] timestamp in
self?.tick(timestamp)
}
private enum Motion {
case tween(Tween)
case fling(vx: Double, vy: Double)
}
private struct Tween {
let startLat: Double
let startLon: Double
let endLat: Double
let dLon: Double
let startZoom: Double
let endZoom: Double
let targetPrecision: Int?
let duration: CFTimeInterval
var startTime: CFTimeInterval?
}
private enum Constants {
// Dragging stops close to the projection limit so polar geohash cells remain
// selectable; clamping tighter would make syncSelection() encode the wrong cell.
// Animations may go past it to reach a target (see clampedLat).
static let maxDragLat = 89.0
static let minFlingPerSecond = 35.0
static let maxFlingPerSecond = 1_200.0
static let maxFrameDelta = 1.0 / 30
static let maxFlingRadiusFractionPerFrame = 0.12
static let flingFrictionPerSecond = 4.2
}
/// - Parameter startZoomedOut: begin from a far, offset view and fly into the
/// target once the viewport is laid out.
init(targetLat: Double, targetLon: Double, initialPrecision: Int, startZoomedOut: Bool) {
let precision = min(max(initialPrecision, 1), GlobeMath.maxPrecision)
centerLat = startZoomedOut ? targetLat * 0.4 : targetLat
centerLon = startZoomedOut ? GlobeMath.normalizeLon(targetLon - 70) : targetLon
zoom = GlobeMath.minZoom
self.precision = precision
if startZoomedOut {
introTarget = (targetLat, targetLon, precision)
}
}
var globeRadius: Double { baseRadius * zoom }
var isInMotion: Bool { isInteracting || isAnimating }
/// Detail the next frame should draw.
var frameDetail: GlobeMotionDetail.Frame {
(isInMotion ? motionDetail : .full).frame
}
func setViewport(baseRadius: Double, screenMin: Double, animateIntro: Bool = true) {
guard baseRadius > 0, screenMin > 0 else { return }
let firstLayout = self.baseRadius <= 0
self.baseRadius = baseRadius
self.screenMin = screenMin
if firstLayout, let target = introTarget {
introTarget = nil
let targetZoom = GlobeMath.zoomForPrecision(target.precision, baseRadius: baseRadius, screenMin: screenMin)
if animateIntro {
// Cinematic intro: spin and zoom from the far view into the target location.
animateTo(lat: target.lat, lon: target.lon, zoom: targetZoom, precision: target.precision, duration: 1.4)
} else {
centerLat = target.lat
centerLon = target.lon
zoom = targetZoom
precision = target.precision
}
}
syncSelection()
}
// MARK: - Gestures
func beginInteraction() {
// Mark the touch first so catching a fling continues the same motion session.
isInteracting = true
motionStateChanged()
cancelAnimations()
}
/// Ends a touch; a release velocity (points/second) carries on as an inertial spin
/// within the same motion session.
func endInteraction(flingVelocityX vx: Double = 0, flingVelocityY vy: Double = 0) {
fling(vx: vx, vy: vy)
isInteracting = false
motionStateChanged()
}
/// Direct rotation from drag gestures. Deltas are in screen points.
func rotateBy(dx: Double, dy: Double) {
let r = globeRadius
guard r > 0 else { return }
let degPerPoint = 180 / (Double.pi * r)
centerLon = GlobeMath.normalizeLon(centerLon - dx * degPerPoint)
// A view already past the drag limit (a polar target) may move toward the
// equator but not further out, and never snaps back to the limit.
centerLat = clampedLat(centerLat + dy * degPerPoint, reaching: centerLat)
syncSelection()
}
/// Continuous zoom from pinch gestures; precision follows automatically.
func zoomBy(_ factor: Double) {
guard factor != 1, factor.isFinite, factor > 0 else { return }
zoom = min(max(zoom * factor, GlobeMath.minZoom), GlobeMath.maxZoom)
syncPrecisionFromZoom()
syncSelection()
}
/// Inertial spin after a fling. Velocities are in points/second.
func fling(vx: Double, vy: Double) {
var initialVx = min(max(vx, -Constants.maxFlingPerSecond), Constants.maxFlingPerSecond)
var initialVy = min(max(vy, -Constants.maxFlingPerSecond), Constants.maxFlingPerSecond)
if abs(initialVx) < Constants.minFlingPerSecond { initialVx = 0 }
if abs(initialVy) < Constants.minFlingPerSecond { initialVy = 0 }
guard initialVx != 0 || initialVy != 0 else { return }
start(.fling(vx: initialVx, vy: initialVy))
}
/// Single tap focuses the tapped point; double tap also zooms in.
func focus(lat: Double, lon: Double, zoomIn: Bool) {
if zoomIn {
animateTo(lat: lat, lon: lon, zoom: min(zoom * 1.9, GlobeMath.maxZoom), duration: 0.5)
} else {
animateTo(lat: lat, lon: lon, duration: 0.45)
}
}
// MARK: - Animations
/// Animate the view to a lat/lon, optionally to a zoom and precision.
func animateTo(lat: Double, lon: Double, zoom targetZoom: Double? = nil, precision targetPrecision: Int? = nil, duration: CFTimeInterval = 0.55) {
let endZoom = min(max(targetZoom ?? zoom, GlobeMath.minZoom), GlobeMath.maxZoom)
start(.tween(Tween(
startLat: centerLat,
startLon: centerLon,
endLat: lat,
dLon: GlobeMath.normalizeLon(lon - centerLon),
startZoom: zoom,
endZoom: endZoom,
targetPrecision: targetPrecision,
duration: duration
)))
}
/// Button-driven precision change: adjusts precision and animates zoom to frame it.
func animatePrecision(_ newPrecision: Int) {
let p = min(max(newPrecision, 1), GlobeMath.maxPrecision)
guard p != precision, baseRadius > 0 else { return }
let targetZoom = GlobeMath.zoomForPrecision(p, baseRadius: baseRadius, screenMin: screenMin)
animateTo(lat: centerLat, lon: centerLon, zoom: targetZoom, precision: p, duration: 0.45)
}
func cancelAnimations() {
motion = nil
if isAnimating {
isAnimating = false
motionStateChanged()
}
}
private func start(_ newMotion: Motion) {
motion = newMotion
if !isAnimating {
isAnimating = true
motionStateChanged()
}
clock.start()
}
private func finishMotion() {
motion = nil
isAnimating = false
motionStateChanged()
}
// MARK: - Frame loop
/// One display frame. Internal so tests can drive animations deterministically.
func tick(_ timestamp: CFTimeInterval) {
let previous = lastTick
lastTick = timestamp
let dt = previous.map { min(max(timestamp - $0, 0), Constants.maxFrameDelta) } ?? 0
switch motion {
case .tween(var tween):
let startTime = tween.startTime ?? timestamp
tween.startTime = startTime
let progress = min(max((timestamp - startTime) / tween.duration, 0), 1)
applyTween(tween, t: GlobeEasing.fastOutSlowIn(progress))
if progress >= 1 {
finishMotion()
} else {
motion = .tween(tween)
}
case .fling(var vx, var vy):
let maxStep = globeRadius * Constants.maxFlingRadiusFractionPerFrame
rotateBy(
dx: min(max(vx * dt, -maxStep), maxStep),
dy: min(max(vy * dt, -maxStep), maxStep)
)
let decay = exp(-Constants.flingFrictionPerSecond * dt)
vx *= decay
vy *= decay
if abs(vx) >= Constants.minFlingPerSecond || abs(vy) >= Constants.minFlingPerSecond {
motion = .fling(vx: vx, vy: vy)
} else {
finishMotion()
}
case nil:
break
}
if isInMotion, let previous {
governor.recordFrame(millis: (timestamp - previous) * 1000)
publishMotionDetail()
}
if motion == nil && !isInteracting {
clock.stop()
lastTick = nil
}
}
private func applyTween(_ tween: Tween, t: Double) {
// The target itself is always reachable: a polar cell's center can lie past
// the drag limit, and clamping it would end the animation on another cell.
centerLat = clampedLat(tween.startLat + (tween.endLat - tween.startLat) * t, reaching: tween.endLat)
centerLon = GlobeMath.normalizeLon(tween.startLon + tween.dLon * t)
// Exponential interpolation feels natural for zoom.
zoom = tween.startZoom * pow(tween.endZoom / tween.startZoom, t)
if let target = tween.targetPrecision {
precision = min(max(target, 1), GlobeMath.maxPrecision)
} else {
syncPrecisionFromZoom()
}
syncSelection()
}
/// Starts a motion session when the globe begins moving and ends it once both the
/// touch and any animation are done (see `GlobeMotionGovernor`).
private func motionStateChanged() {
if isInMotion {
guard !governor.isSessionActive else { return }
governor.beginSession()
lastTick = nil
clock.start()
} else {
governor.endSession()
}
publishMotionDetail()
}
private func publishMotionDetail() {
if motionDetail != governor.detail { motionDetail = governor.detail }
}
/// Clamps to the drag limit, widened (up to that pole) on `reach`'s side only.
private func clampedLat(_ lat: Double, reaching reach: Double) -> Double {
let lower = max(min(-Constants.maxDragLat, reach), -90)
let upper = min(max(Constants.maxDragLat, reach), 90)
return min(max(lat, lower), upper)
}
private func syncPrecisionFromZoom() {
guard baseRadius > 0 else { return }
let p = GlobeMath.autoPrecision(globeRadius: globeRadius, screenMin: screenMin)
if p != precision { precision = p }
}
private func syncSelection() {
guard baseRadius > 0 else { return }
let gh = Geohash.encode(latitude: centerLat, longitude: centerLon, precision: precision)
if gh != selectedGeohash { selectedGeohash = gh }
}
}
/// Material's FastOutSlowIn curve, cubic-bezier(0.4, 0.0, 0.2, 1.0), which the
/// Android globe animates with.
enum GlobeEasing {
static func fastOutSlowIn(_ t: Double) -> Double {
cubicBezier(t, x1: 0.4, y1: 0, x2: 0.2, y2: 1)
}
static func cubicBezier(_ t: Double, x1: Double, y1: Double, x2: Double, y2: Double) -> Double {
guard t > 0 else { return 0 }
guard t < 1 else { return 1 }
func sample(_ s: Double, _ a1: Double, _ a2: Double) -> Double {
let inv = 1 - s
return 3 * inv * inv * s * a1 + 3 * inv * s * s * a2 + s * s * s
}
// Solve x(s) = t by bisection; x is monotonic for these control points.
var lo = 0.0
var hi = 1.0
var s = t
for _ in 0..<24 {
let x = sample(s, x1, x2)
if abs(x - t) < 1e-6 { break }
if x < t { lo = s } else { hi = s }
s = (lo + hi) / 2
}
return sample(s, y1, y2)
}
}
/// Per-display-frame callback driving globe animations: CADisplayLink on iOS,
/// a common-mode timer on macOS.
@MainActor
final class GlobeFrameClock {
private let onFrame: (CFTimeInterval) -> Void
#if os(iOS)
private var displayLink: CADisplayLink?
private var proxy: Proxy?
private final class Proxy: NSObject {
weak var clock: GlobeFrameClock?
@objc func step(_ link: CADisplayLink) {
MainActor.assumeIsolated {
clock?.onFrame(link.timestamp)
}
}
}
#else
private var timer: Timer?
#endif
init(onFrame: @escaping (CFTimeInterval) -> Void) {
self.onFrame = onFrame
}
func start() {
#if os(iOS)
guard displayLink == nil else { return }
let proxy = Proxy()
proxy.clock = self
let link = CADisplayLink(target: proxy, selector: #selector(Proxy.step(_:)))
link.preferredFrameRateRange = CAFrameRateRange(minimum: 30, maximum: 120, preferred: 120)
link.add(to: .main, forMode: .common)
self.proxy = proxy
displayLink = link
#else
guard timer == nil else { return }
let timer = Timer(timeInterval: 1.0 / 60, repeats: true) { [weak self] _ in
MainActor.assumeIsolated {
self?.onFrame(CACurrentMediaTime())
}
}
RunLoop.main.add(timer, forMode: .common)
self.timer = timer
#endif
}
func stop() {
#if os(iOS)
displayLink?.invalidate()
displayLink = nil
proxy = nil
#else
timer?.invalidate()
timer = nil
#endif
}
deinit {
#if os(iOS)
displayLink?.invalidate()
#else
timer?.invalidate()
#endif
}
}

View File

@ -0,0 +1,831 @@
//
// GlobeView.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import SwiftUI
#if os(iOS)
import UIKit
#else
import AppKit
#endif
/// Color palette for the globe, derived from the app theme by the caller.
struct GlobeColors: Equatable {
let accent: Color
let land: Color
let coastline: Color
let border: Color
let oceanCenter: Color
let oceanEdge: Color
let atmosphere: Color
let graticule: Color
let grid: Color
let label: Color
let labelHalo: Color
let star: Color
}
/// Interactive orthographic globe: drag to spin (with inertia), pinch to zoom, tap to
/// focus, double tap to zoom in. The selected geohash is always the cell under the
/// crosshair at the screen center.
struct GlobeView: View {
@ObservedObject var state: GlobeState
let colors: GlobeColors
let world: GlobeWorldData
@Environment(\.displayScale) private var displayScale
@Environment(\.appTheme) private var theme
@Environment(\.accessibilityReduceMotion) private var reduceMotion
#if os(iOS)
@State private var selectionFeedback = UISelectionFeedbackGenerator()
#endif
var body: some View {
GeometryReader { proxy in
ZStack {
// Static background lives in its own layer and is not redrawn by globe movement.
GlobeStarfield(color: colors.star)
.equatable()
let renderer = GlobeRenderer(
centerLat: state.centerLat,
centerLon: state.centerLon,
radius: state.globeRadius,
zoom: state.zoom,
selectedGeohash: state.selectedGeohash,
detail: state.frameDetail,
colors: colors,
world: world,
pixel: 1 / max(displayScale, 1),
fontDesign: theme.bodyFontDesign
)
Canvas(rendersAsynchronously: false) { context, size in
renderer.draw(in: &context, size: size)
}
GlobeTouchLayer(state: state)
// Isolated so its pulse does not redraw the globe geometry.
GlobeCrosshair(color: colors.accent, isInMotion: state.isInMotion)
.allowsHitTesting(false)
}
.onAppear { updateViewport(proxy.size) }
.onChange(of: proxy.size) { updateViewport($0) }
}
.onChange(of: state.selectedGeohash) { [previous = state.selectedGeohash] _ in
guard !previous.isEmpty else { return }
#if os(iOS)
selectionFeedback.selectionChanged()
#endif
}
.accessibilityElement()
.accessibilityLabel(Text(verbatim: state.selectedGeohash.isEmpty ? "" : "#\(state.selectedGeohash)"))
.accessibilityAdjustableAction { direction in
switch direction {
case .increment: state.animatePrecision(state.precision + 1)
case .decrement: state.animatePrecision(state.precision - 1)
@unknown default: break
}
}
}
private func updateViewport(_ size: CGSize) {
let minDim = Double(min(size.width, size.height))
state.setViewport(baseRadius: minDim * 0.44, screenMin: minDim, animateIntro: !reduceMotion)
}
}
// MARK: - Background and crosshair
private struct GlobeStarfield: View, Equatable {
let color: Color
private struct Star {
let x: Double
let y: Double
let radius: Double
let alpha: Double
}
private static let stars: [Star] = {
var rng = SeededGenerator(seed: 42)
return (0..<160).map { _ in
Star(
x: rng.nextUnit(),
y: rng.nextUnit(),
radius: 0.6 + rng.nextUnit() * 1.5,
alpha: 0.15 + rng.nextUnit() * 0.55
)
}
}()
var body: some View {
Canvas { context, size in
for star in Self.stars {
let center = CGPoint(x: star.x * size.width, y: star.y * size.height)
let rect = CGRect(x: center.x - star.radius, y: center.y - star.radius, width: star.radius * 2, height: star.radius * 2)
context.fill(Path(ellipseIn: rect), with: .color(color.opacity(star.alpha)))
}
}
.allowsHitTesting(false)
}
/// Deterministic SplitMix64 so the sky is the same every time the picker opens.
private struct SeededGenerator {
var state: UInt64
init(seed: UInt64) { state = seed }
mutating func nextUnit() -> Double {
state &+= 0x9E37_79B9_7F4A_7C15
var z = state
z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9
z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB
z ^= z >> 31
return Double(z >> 11) / Double(1 << 53)
}
}
}
private struct GlobeCrosshair: View {
let color: Color
let isInMotion: Bool
var body: some View {
TimelineView(.animation(minimumInterval: nil, paused: isInMotion)) { timeline in
Canvas { context, size in
let alpha = isInMotion ? 0.9 : Self.pulse(at: timeline.date)
let shading = GraphicsContext.Shading.color(color.opacity(alpha))
let cx = size.width / 2
let cy = size.height / 2
let gap: CGFloat = 5
let len: CGFloat = 9
var path = Path()
path.move(to: CGPoint(x: cx - gap - len, y: cy))
path.addLine(to: CGPoint(x: cx - gap, y: cy))
path.move(to: CGPoint(x: cx + gap, y: cy))
path.addLine(to: CGPoint(x: cx + gap + len, y: cy))
path.move(to: CGPoint(x: cx, y: cy - gap - len))
path.addLine(to: CGPoint(x: cx, y: cy - gap))
path.move(to: CGPoint(x: cx, y: cy + gap))
path.addLine(to: CGPoint(x: cx, y: cy + gap + len))
context.stroke(path, with: shading, lineWidth: 1.6)
context.fill(Path(ellipseIn: CGRect(x: cx - 1.8, y: cy - 1.8, width: 3.6, height: 3.6)), with: shading)
}
}
}
/// 0.45 → 1 → 0.45 over 2.2s, eased like the Android picker's reversing tween.
private static func pulse(at date: Date) -> Double {
let period = 1.1
let phase = date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: period * 2) / period
let t = phase <= 1 ? phase : 2 - phase
return 0.45 + 0.55 * GlobeEasing.fastOutSlowIn(t)
}
}
// MARK: - Renderer
/// Draws one globe frame. Built fresh per frame from a snapshot of `GlobeState`.
private struct GlobeRenderer {
let centerLat: Double
let centerLon: Double
let radius: Double
let zoom: Double
let selectedGeohash: String
let detail: GlobeMotionDetail.Frame
let colors: GlobeColors
let world: GlobeWorldData
/// One device pixel in points; hairline widths are specified in pixels.
let pixel: Double
let fontDesign: Font.Design
private typealias DiscPoint = GlobeGeometry.DiscPoint
func draw(in context: inout GraphicsContext, size: CGSize) {
guard radius > 0, size.width > 0, size.height > 0 else { return }
let cx = Double(size.width) / 2
let cy = Double(size.height) / 2
let r = radius
let center = CGPoint(x: cx, y: cy)
let projector = GlobeMath.PreparedProjector(centerLat: centerLat, centerLon: centerLon)
let clip = GlobeGeometry.ClipRect(size: size)
let screenRect = CGRect(origin: .zero, size: size)
// Once the disc covers the screen, the sphere-wide gradients are constant across
// it (and their huge coordinates would only cost precision), so draw flat fills.
let coverRadius = (cx * cx + cy * cy).squareRoot() + 2
let discCoversScreen = r > coverRadius
let gradientsMatter = r < Double(min(size.width, size.height)) * 10
func disc(_ discRadius: Double) -> Path {
if discRadius > coverRadius { return Path(screenRect) }
return Path(ellipseIn: CGRect(x: cx - discRadius, y: cy - discRadius, width: discRadius * 2, height: discRadius * 2))
}
// Atmosphere glow
if !discCoversScreen {
context.fill(disc(r * 1.22), with: .radialGradient(
Gradient(stops: [
.init(color: colors.atmosphere.opacity(0.30), location: 0),
.init(color: colors.atmosphere.opacity(0.12), location: 0.75),
.init(color: colors.atmosphere.opacity(0), location: 1)
]),
center: center,
startRadius: 0,
endRadius: r * 1.22
))
}
// Ocean sphere
if gradientsMatter {
context.fill(disc(r), with: .radialGradient(
Gradient(stops: [
.init(color: colors.oceanCenter, location: 0),
.init(color: colors.oceanCenter, location: 0.7),
.init(color: colors.oceanEdge, location: 1)
]),
center: CGPoint(x: cx - r * 0.32, y: cy - r * 0.38),
startRadius: 0,
endRadius: r * 1.5
))
} else {
context.fill(Path(screenRect), with: .color(colors.oceanCenter))
}
drawGraticule(in: &context, cx: cx, cy: cy, r: r, clip: clip)
// Fill every landmass first. Coastlines are drawn in a separate final pass so a
// large continent fill can never cover an island outline drawn earlier.
var coastlines = Path()
for ring in world.land {
drawLand(ring, in: &context, projector: projector, cx: cx, cy: cy, r: r, clip: clip, coastlines: &coastlines)
}
context.stroke(coastlines, with: .color(colors.coastline), lineWidth: 1.4 * pixel)
// Country borders are restored when interaction settles.
if detail.showBorders {
var borders = Path()
for line in world.borders {
let pts = line.terms.map { terms -> (DiscPoint, Bool) in
let p = projector.project(terms)
return (DiscPoint(x: p.x, y: p.y, front: p.cosC > 0.005), p.cosC >= 0)
}
guard pts.contains(where: { $0.1 }) else { continue }
appendRuns(GlobeGeometry.frontRuns(pts.map(\.0), closed: false), to: &borders, cx: cx, cy: cy, r: r, clip: clip)
}
context.stroke(borders, with: .color(colors.border), lineWidth: 1.2 * pixel)
}
// Sphere shading: dark limb + night side for 3D depth
if gradientsMatter {
context.fill(disc(r + 1), with: .radialGradient(
Gradient(stops: [
.init(color: .black.opacity(0), location: 0),
.init(color: .black.opacity(0), location: 0.62),
.init(color: .black.opacity(0.34), location: 0.88),
.init(color: .black.opacity(0.72), location: 1)
]),
center: CGPoint(x: cx - r * 0.25, y: cy - r * 0.3),
startRadius: 0,
endRadius: r * 1.35
))
context.fill(disc(r + 1), with: .linearGradient(
Gradient(stops: [
.init(color: .black.opacity(0), location: 0),
.init(color: .black.opacity(0), location: 0.55),
.init(color: .black.opacity(0.42), location: 1)
]),
startPoint: CGPoint(x: cx - r * 0.7, y: cy - r * 0.7),
endPoint: CGPoint(x: cx + r * 0.75, y: cy + r * 0.8)
))
}
// Dots follow the zoom at every detail level; only their labels wait for rest.
drawCities(in: &context, projector: projector, cx: cx, cy: cy, r: r, size: size)
// The grid is drawn at every detail level, including while dragging.
if !selectedGeohash.isEmpty {
let cells = visibleCells
drawGeohashGrid(cells, in: &context, cx: cx, cy: cy, r: r, clip: clip)
drawGeohashLabels(cells, in: &context, cx: cx, cy: cy, r: r)
}
}
private var visibleCells: [String] {
var cells = [selectedGeohash]
for neighbor in Geohash.neighbors(of: selectedGeohash) where !cells.contains(neighbor) {
cells.append(neighbor)
}
return cells
}
private func screen(_ p: CGPoint, cx: Double, cy: Double, r: Double) -> CGPoint {
CGPoint(x: cx + Double(p.x) * r, y: cy + Double(p.y) * r)
}
private func appendRuns(_ runs: [[CGPoint]], to path: inout Path, cx: Double, cy: Double, r: Double, clip: GlobeGeometry.ClipRect) {
for run in runs where run.count >= 2 {
for k in 1..<run.count {
guard let segment = GlobeGeometry.clipSegment(
screen(run[k - 1], cx: cx, cy: cy, r: r),
screen(run[k], cx: cx, cy: cy, r: r),
to: clip
) else { continue }
path.move(to: segment.0)
path.addLine(to: segment.1)
}
}
}
private func drawGraticule(in context: inout GraphicsContext, cx: Double, cy: Double, r: Double, clip: GlobeGeometry.ClipRect) {
let step = detail.graticuleStepDegrees
var path = Path()
func trace(_ points: [(lat: Double, lon: Double)]) {
var prev: GlobeMath.Projection?
for point in points {
if let p = GlobeMath.project(lat: point.lat, lon: point.lon, centerLat: centerLat, centerLon: centerLon), p.cosC > 0.02 {
if let pp = prev, let segment = GlobeGeometry.clipSegment(
CGPoint(x: cx + pp.x * r, y: cy + pp.y * r),
CGPoint(x: cx + p.x * r, y: cy + p.y * r),
to: clip
) {
path.move(to: segment.0)
path.addLine(to: segment.1)
}
prev = p
} else {
prev = nil
}
}
}
// Latitude lines
for lat in stride(from: -75.0, through: 75.0, by: 15) {
trace(stride(from: -180.0, through: 180.0, by: step).map { (lat, $0) })
}
// Longitude lines
for lon in stride(from: -180.0, to: 180.0, by: 15) {
trace(stride(from: -90.0, through: 90.0, by: step).map { ($0, lon) })
}
context.stroke(path, with: .color(colors.graticule), lineWidth: pixel)
}
private func drawLand(
_ ring: GlobeRing,
in context: inout GraphicsContext,
projector: GlobeMath.PreparedProjector,
cx: Double, cy: Double, r: Double,
clip: GlobeGeometry.ClipRect,
coastlines: inout Path
) {
let pointStride = ring.count >= 64 ? detail.landPointStride : 1
let n = (ring.count - 1) / pointStride + 1
guard n >= 3 else { return }
var anyFront = false
var anyBack = false
var pts: [DiscPoint] = []
pts.reserveCapacity(n)
for i in 0..<n {
let p = projector.project(ring.terms[min(i * pointStride, ring.count - 1)])
if p.cosC >= 0 { anyFront = true } else { anyBack = true }
pts.append(DiscPoint(x: p.x, y: p.y, front: p.cosC > 0.005))
}
guard anyFront else { return }
appendRuns(GlobeGeometry.frontRuns(pts), to: &coastlines, cx: cx, cy: cy, r: r, clip: clip)
let polygon = GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
let invert = anyBack && GlobeGeometry.projectedFillNeedsInversion(
polygon: polygon, ring: ring, cx: cx, cy: cy, r: r, centerLat: centerLat, centerLon: centerLon
)
fill(pts, polygon: polygon, color: colors.land, in: &context, cx: cx, cy: cy, r: r, clip: clip, invert: invert)
}
private func fill(
_ pts: [DiscPoint],
polygon: [CGPoint]? = nil,
color: Color,
in context: inout GraphicsContext,
cx: Double, cy: Double, r: Double,
clip: GlobeGeometry.ClipRect,
invert: Bool = false
) {
guard pts.contains(where: \.front) else { return }
let poly = polygon ?? GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
guard poly.count >= 3 else { return }
let clipped = GlobeGeometry.clipPolygon(poly, to: clip)
guard clipped.count >= 3 else { return }
var path = Path()
if invert {
// Even-odd filling with the globe disc flips the one ring whose horizon
// closure the projection put on the wrong side.
let clipBounds = CGRect(x: clip.left, y: clip.top, width: clip.right - clip.left, height: clip.bottom - clip.top)
let discRect = CGRect(x: cx - r, y: cy - r, width: r * 2, height: r * 2)
if discRect.contains(clipBounds) {
path.addRect(clipBounds)
} else {
path.addEllipse(in: discRect)
}
}
path.addLines(clipped)
path.closeSubpath()
context.fill(path, with: .color(color), style: FillStyle(eoFill: invert))
}
private func drawCities(
in context: inout GraphicsContext,
projector: GlobeMath.PreparedProjector,
cx: Double, cy: Double, r: Double,
size: CGSize
) {
let maxRank: Int
if zoom < 2 {
maxRank = 1
} else if zoom < 8 {
maxRank = 3
} else if zoom < 40 {
maxRank = 4
} else {
maxRank = 10
}
let width = Double(size.width)
let height = Double(size.height)
for city in world.cities where city.rank <= maxRank {
let p = projector.project(city.terms)
guard p.cosC >= 0.03 else { continue }
let sx = cx + p.x * r
let sy = cy + p.y * r
guard sx >= -50, sx <= width + 50, sy >= -50, sy <= height + 50 else { continue }
let alpha = min(max(p.cosC, 0.25), 1)
let important = city.capital || city.megacity
let dotRadius = important ? 2.6 : 1.8
let dotColor = city.capital ? colors.accent.opacity(alpha) : colors.label.opacity(alpha * 0.85)
context.fill(
Path(ellipseIn: CGRect(x: sx - dotRadius, y: sy - dotRadius, width: dotRadius * 2, height: dotRadius * 2)),
with: .color(dotColor)
)
if detail.showCityLabels && (zoom >= 6 || (important && zoom >= 2.5)) {
drawLabel(
city.name,
at: CGPoint(x: sx + dotRadius + 3, y: sy),
anchor: .leading,
size: 10,
weight: .medium,
color: colors.label.opacity(200 / 255 * alpha),
halo: colors.labelHalo.opacity(140 / 255 * alpha),
in: &context
)
}
}
}
private func drawGeohashGrid(_ cells: [String], in context: inout GraphicsContext, cx: Double, cy: Double, r: Double, clip: GlobeGeometry.ClipRect) {
for cell in cells {
let isSelected = cell == selectedGeohash
let b = Geohash.decodeBounds(cell)
let spanLat = b.latMax - b.latMin
let spanLon = b.lonMax - b.lonMin
let steps = min(max(Int((spanLat / 1.5).rounded(.up)), 4), 48)
// Sample the cell boundary: N edge l->r, E edge t->b, S edge r->l, W edge b->t
var pts: [DiscPoint] = []
pts.reserveCapacity(steps * 4 + 4)
func add(_ lat: Double, _ rawLon: Double) {
// Keep the boundary continuous across the antimeridian relative to the view.
var lon = rawLon
while lon - centerLon > 180 { lon -= 360 }
while lon - centerLon < -180 { lon += 360 }
let p = GlobeMath.projectRaw(lat: lat, lon: lon, centerLat: centerLat, centerLon: centerLon)
pts.append(DiscPoint(x: p.x, y: p.y, front: p.cosC >= 0.005))
}
for s in 0...steps { add(b.latMax, b.lonMin + spanLon * Double(s) / Double(steps)) }
for s in 1...steps { add(b.latMax - spanLat * Double(s) / Double(steps), b.lonMax) }
for s in 1...steps { add(b.latMin, b.lonMax - spanLon * Double(s) / Double(steps)) }
for s in 1..<steps { add(b.latMin + spanLat * Double(s) / Double(steps), b.lonMin) }
guard pts.contains(where: \.front) else { continue }
var outline = Path()
appendRuns(GlobeGeometry.frontRuns(pts), to: &outline, cx: cx, cy: cy, r: r, clip: clip)
if isSelected {
fill(pts, color: colors.accent.opacity(0.20), in: &context, cx: cx, cy: cy, r: r, clip: clip)
context.stroke(outline, with: .color(colors.accent.opacity(0.35)), lineWidth: 7 * pixel)
context.stroke(outline, with: .color(colors.accent), lineWidth: 3.2 * pixel)
} else {
fill(pts, color: colors.grid.opacity(0.05), in: &context, cx: cx, cy: cy, r: r, clip: clip)
context.stroke(outline, with: .color(colors.grid), lineWidth: 1.6 * pixel)
}
}
}
private func drawGeohashLabels(_ cells: [String], in context: inout GraphicsContext, cx: Double, cy: Double, r: Double) {
for cell in cells {
let isSelected = cell == selectedGeohash
let c = Geohash.decodeCenter(cell)
guard let p = GlobeMath.project(lat: c.lat, lon: c.lon, centerLat: centerLat, centerLon: centerLon),
p.cosC >= 0.08 else { continue }
drawLabel(
cell,
at: CGPoint(x: cx + p.x * r, y: cy + p.y * r),
anchor: .center,
size: isSelected ? 12.5 : 10,
weight: isSelected ? .semibold : .medium,
color: isSelected ? colors.accent : colors.label.opacity(160 / 255 * min(max(p.cosC, 0.4), 1)),
halo: colors.labelHalo.opacity(isSelected ? 200 / 255 : 120 / 255),
in: &context
)
}
}
/// Text with a thin halo in the background color so labels stay legible over land,
/// grid lines and the limb shading.
private func drawLabel(
_ string: String,
at point: CGPoint,
anchor: UnitPoint,
size: CGFloat,
weight: Font.Weight,
color: Color,
halo: Color,
in context: inout GraphicsContext
) {
var resolved = context.resolve(
Text(verbatim: string).font(.system(size: size, weight: weight, design: fontDesign))
)
resolved.shading = .color(halo)
let w = size * 0.09
for (dx, dy) in [(-w, 0), (w, 0), (0, -w), (0, w), (-w, -w), (w, -w), (-w, w), (w, w)] {
context.draw(resolved, at: CGPoint(x: point.x + dx, y: point.y + dy), anchor: anchor)
}
resolved.shading = .color(color)
context.draw(resolved, at: point, anchor: anchor)
}
}
// MARK: - Touch handling
/// Gesture surface over the globe. A single raw-touch handler (rather than stacked
/// recognizers) mirrors the Android picker: centroid pan rotates, pinch zooms in the
/// same gesture, a quick tap focuses immediately and a second tap zooms in.
#if os(iOS)
private struct GlobeTouchLayer: UIViewRepresentable {
let state: GlobeState
func makeUIView(context: Context) -> GlobeTouchSurface {
let view = GlobeTouchSurface()
view.state = state
return view
}
func updateUIView(_ view: GlobeTouchSurface, context: Context) {
view.state = state
}
}
private final class GlobeTouchSurface: UIView {
weak var state: GlobeState?
private static let touchSlop: CGFloat = 8
private var touches: Set<UITouch> = []
private var downTime: TimeInterval = 0
private var downPosition: CGPoint = .zero
private var moved: CGVector = .zero
private var dragStarted = false
private var hadMultipleTouches = false
private var lastCentroid: CGPoint?
private var lastSpan: CGFloat?
private var samples: [(time: TimeInterval, position: CGPoint)] = []
private var lastTapTime: TimeInterval = 0
private var lastTapPosition: CGPoint = .zero
override init(frame: CGRect) {
super.init(frame: frame)
isMultipleTouchEnabled = true
backgroundColor = .clear
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func touchesBegan(_ began: Set<UITouch>, with event: UIEvent?) {
if touches.isEmpty, let first = began.first {
state?.beginInteraction()
downTime = first.timestamp
downPosition = first.location(in: self)
moved = .zero
dragStarted = false
hadMultipleTouches = false
samples = [(first.timestamp, downPosition)]
}
touches.formUnion(began)
if touches.count > 1 {
hadMultipleTouches = true
samples.removeAll()
}
resetBaseline()
}
override func touchesMoved(_ movedTouches: Set<UITouch>, with event: UIEvent?) {
guard let state, let previousCentroid = lastCentroid else { return }
let centroid = currentCentroid()
let pan = CGVector(dx: centroid.x - previousCentroid.x, dy: centroid.y - previousCentroid.y)
if pan != .zero {
moved.dx += pan.dx
moved.dy += pan.dy
if !dragStarted && hypot(moved.dx, moved.dy) >= Self.touchSlop {
dragStarted = true
}
if dragStarted { state.rotateBy(dx: Double(pan.dx), dy: Double(pan.dy)) }
}
if touches.count > 1, let previousSpan = lastSpan, previousSpan > 0 {
let span = currentSpan(around: centroid)
if span > 0 { state.zoomBy(Double(span / previousSpan)) }
lastSpan = span
}
lastCentroid = centroid
if !hadMultipleTouches, touches.count == 1, let touch = touches.first {
samples.append((touch.timestamp, touch.location(in: self)))
if samples.count > 20 { samples.removeFirst(samples.count - 20) }
}
}
override func touchesEnded(_ ended: Set<UITouch>, with event: UIEvent?) {
if !hadMultipleTouches, touches.count == 1, let touch = ended.first {
samples.append((touch.timestamp, touch.location(in: self)))
}
finish(ended, upTime: ended.first?.timestamp ?? downTime, cancelled: false)
}
override func touchesCancelled(_ cancelled: Set<UITouch>, with event: UIEvent?) {
finish(cancelled, upTime: cancelled.first?.timestamp ?? downTime, cancelled: true)
}
private func finish(_ lifted: Set<UITouch>, upTime: TimeInterval, cancelled: Bool) {
touches.subtract(lifted)
guard touches.isEmpty else {
resetBaseline()
return
}
lastCentroid = nil
lastSpan = nil
guard let state else { return }
guard !cancelled else {
state.endInteraction()
return
}
let isTap = !hadMultipleTouches
&& !dragStarted
&& upTime - downTime < 0.4
&& hypot(moved.dx, moved.dy) < Self.touchSlop
let r = state.globeRadius
let tapLocation = r > 0 ? GlobeMath.unproject(
x: Double((downPosition.x - bounds.midX) / r),
y: Double((downPosition.y - bounds.midY) / r),
centerLat: state.centerLat,
centerLon: state.centerLon
) : nil
if isTap, let location = tapLocation {
let isDouble = upTime - lastTapTime < 0.35
&& hypot(downPosition.x - lastTapPosition.x, downPosition.y - lastTapPosition.y) < Self.touchSlop * 4
lastTapTime = upTime
lastTapPosition = downPosition
state.focus(lat: location.lat, lon: location.lon, zoomIn: isDouble)
state.endInteraction()
} else if dragStarted && !hadMultipleTouches {
let velocity = releaseVelocity(at: upTime)
state.endInteraction(flingVelocityX: Double(velocity.dx), flingVelocityY: Double(velocity.dy))
} else {
state.endInteraction()
}
}
/// Average velocity over the last 100ms of movement; zero when the finger rested
/// before lifting.
private func releaseVelocity(at upTime: TimeInterval) -> CGVector {
guard let last = samples.last, upTime - last.time < 0.04 else { return .zero }
let window = samples.filter { last.time - $0.time <= 0.1 }
guard let first = window.first, last.time - first.time > 0.005 else { return .zero }
let dt = CGFloat(last.time - first.time)
return CGVector(dx: (last.position.x - first.position.x) / dt, dy: (last.position.y - first.position.y) / dt)
}
private func resetBaseline() {
let centroid = currentCentroid()
lastCentroid = centroid
lastSpan = touches.count > 1 ? currentSpan(around: centroid) : nil
}
private func currentCentroid() -> CGPoint {
guard !touches.isEmpty else { return .zero }
var x: CGFloat = 0
var y: CGFloat = 0
for touch in touches {
let p = touch.location(in: self)
x += p.x
y += p.y
}
return CGPoint(x: x / CGFloat(touches.count), y: y / CGFloat(touches.count))
}
private func currentSpan(around centroid: CGPoint) -> CGFloat {
guard !touches.isEmpty else { return 0 }
let total = touches.reduce(CGFloat(0)) { sum, touch in
let p = touch.location(in: self)
return sum + hypot(p.x - centroid.x, p.y - centroid.y)
}
return total / CGFloat(touches.count)
}
}
#else
private struct GlobeTouchLayer: NSViewRepresentable {
let state: GlobeState
func makeNSView(context: Context) -> GlobeTouchSurface {
let view = GlobeTouchSurface()
view.state = state
return view
}
func updateNSView(_ view: GlobeTouchSurface, context: Context) {
view.state = state
}
}
/// macOS: click-drag spins, trackpad pinch or scroll zooms, click focuses,
/// double click zooms in.
private final class GlobeTouchSurface: NSView {
weak var state: GlobeState?
private var lastDrag: CGPoint?
private var dragDistance: CGFloat = 0
private var samples: [(time: TimeInterval, position: CGPoint)] = []
override var isFlipped: Bool { true }
override var acceptsFirstResponder: Bool { true }
override func mouseDown(with event: NSEvent) {
state?.beginInteraction()
let p = convert(event.locationInWindow, from: nil)
lastDrag = p
dragDistance = 0
samples = [(event.timestamp, p)]
}
override func mouseDragged(with event: NSEvent) {
let p = convert(event.locationInWindow, from: nil)
if let last = lastDrag {
dragDistance += hypot(p.x - last.x, p.y - last.y)
state?.rotateBy(dx: Double(p.x - last.x), dy: Double(p.y - last.y))
}
lastDrag = p
samples.append((event.timestamp, p))
if samples.count > 20 { samples.removeFirst(samples.count - 20) }
}
override func mouseUp(with event: NSEvent) {
guard let state else { return }
lastDrag = nil
let p = convert(event.locationInWindow, from: nil)
let r = state.globeRadius
if dragDistance < 4 {
if r > 0, let location = GlobeMath.unproject(
x: Double((p.x - bounds.midX) / r),
y: Double((p.y - bounds.midY) / r),
centerLat: state.centerLat,
centerLon: state.centerLon
) {
state.focus(lat: location.lat, lon: location.lon, zoomIn: event.clickCount >= 2)
}
state.endInteraction()
} else if let last = samples.last, event.timestamp - last.time < 0.04,
let first = samples.first(where: { last.time - $0.time <= 0.1 }),
last.time - first.time > 0.005 {
let dt = CGFloat(last.time - first.time)
state.endInteraction(
flingVelocityX: Double((last.position.x - first.position.x) / dt),
flingVelocityY: Double((last.position.y - first.position.y) / dt)
)
} else {
state.endInteraction()
}
}
override func magnify(with event: NSEvent) {
state?.cancelAnimations()
state?.zoomBy(Double(1 + event.magnification))
}
override func scrollWheel(with event: NSEvent) {
state?.cancelAnimations()
state?.zoomBy(Double(exp(event.scrollingDeltaY * (event.hasPreciseScrollingDeltas ? 0.01 : 0.1))))
}
}
#endif

View File

@ -0,0 +1,139 @@
//
// GlobeWorldData.swift
// bitchat
//
// This is free and unencumbered software released into the public domain.
// For more information, see <https://unlicense.org>
//
import Foundation
/// A polygon ring or polyline on the globe, with projection terms prepared once.
struct GlobeRing: Sendable {
let lats: [Double]
let lons: [Double]
let terms: [GlobeMath.Terms]
var count: Int { lats.count }
init(lats: [Double], lons: [Double]) {
self.lats = lats
self.lons = lons
self.terms = zip(lats, lons).map { GlobeMath.Terms(lat: $0, lon: $1) }
}
}
struct GlobeCity: Sendable {
let name: String
let rank: Int
let capital: Bool
let megacity: Bool
/// The position, kept only as the projection terms the renderer reads.
let terms: GlobeMath.Terms
init(name: String, lat: Double, lon: Double, rank: Int, capital: Bool, megacity: Bool) {
self.name = name
self.rank = rank
self.capital = capital
self.megacity = megacity
self.terms = GlobeMath.Terms(lat: lat, lon: lon)
}
}
/// The bundled Natural Earth geometry (public domain) the globe draws: 110m land
/// polygons, admin-0 boundary lines and 50m populated places. The files are the
/// same ones the Android picker ships.
struct GlobeWorldData: Sendable {
let land: [GlobeRing]
let borders: [GlobeRing]
let cities: [GlobeCity]
/// Parsed on first access; callers load it off the main thread.
static let bundled = GlobeWorldData(bundle: .main)
init(land: [GlobeRing], borders: [GlobeRing], cities: [GlobeCity]) {
self.land = land
self.borders = borders
self.cities = cities
}
private init(bundle: Bundle) {
func data(_ name: String) -> Data? {
bundle.url(forResource: name, withExtension: "geojson").flatMap { try? Data(contentsOf: $0) }
}
self.init(
land: data("world_land").map(Self.parseLand) ?? [],
borders: data("world_borders").map(Self.parseBorders) ?? [],
cities: data("world_cities").map(Self.parseCities) ?? []
)
}
/// Polygon and MultiPolygon geometries; every ring (outer and holes) becomes one entry.
static func parseLand(_ data: Data) -> [GlobeRing] {
var rings: [GlobeRing] = []
for geometry in geometries(data) {
switch geometry["type"] as? String {
case "Polygon":
appendRings(geometry["coordinates"], minimumPoints: 3, to: &rings)
case "MultiPolygon":
for polygon in geometry["coordinates"] as? [Any] ?? [] {
appendRings(polygon, minimumPoints: 3, to: &rings)
}
default:
continue
}
}
return rings
}
/// LineString and MultiLineString geometries.
static func parseBorders(_ data: Data) -> [GlobeRing] {
var lines: [GlobeRing] = []
for geometry in geometries(data) {
switch geometry["type"] as? String {
case "LineString":
appendRings([geometry["coordinates"] as Any], minimumPoints: 2, to: &lines)
case "MultiLineString":
appendRings(geometry["coordinates"], minimumPoints: 2, to: &lines)
default:
continue
}
}
return lines
}
/// `{"cities": [{"n": name, "r": rank, "cap": 0|1, "mega": 0|1, "lat": .., "lon": ..}]}`
static func parseCities(_ data: Data) -> [GlobeCity] {
guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let entries = root["cities"] as? [[String: Any]] else { return [] }
return entries.compactMap { entry in
guard let name = entry["n"] as? String,
let lat = (entry["lat"] as? NSNumber)?.doubleValue,
let lon = (entry["lon"] as? NSNumber)?.doubleValue,
let rank = (entry["r"] as? NSNumber)?.intValue else { return nil }
return GlobeCity(
name: name,
lat: lat,
lon: lon,
rank: rank,
capital: (entry["cap"] as? NSNumber)?.intValue == 1,
megacity: (entry["mega"] as? NSNumber)?.intValue == 1
)
}
}
private static func geometries(_ data: Data) -> [[String: Any]] {
guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [] }
return root["geometries"] as? [[String: Any]] ?? []
}
/// GeoJSON positions are [lon, lat].
private static func appendRings(_ ringsJSON: Any?, minimumPoints: Int, to out: inout [GlobeRing]) {
for ring in ringsJSON as? [Any] ?? [] {
guard let points = ring as? [[NSNumber]], points.count >= minimumPoints else { continue }
let valid = points.filter { $0.count >= 2 }
guard valid.count >= minimumPoints else { continue }
out.append(GlobeRing(lats: valid.map { $0[1].doubleValue }, lons: valid.map { $0[0].doubleValue }))
}
}
}

View File

@ -16,6 +16,9 @@ struct LocationChannelsSheet: View {
@State private var pendingShareGeohash: String?
@State private var showSharePrecisionWarning = false
@State private var activeSharePayload: ChannelSharePayload?
@State private var showGlobePicker = false
/// Geohash chosen on the globe; applied once the picker has dismissed.
@State private var pickedGeohash: String?
private enum Strings {
static let title: LocalizedStringKey = "location_channels.title"
@ -55,6 +58,7 @@ struct LocationChannelsSheet: View {
static let sharePrecisionTitle = String(localized: "channel.share.precision_warning.title", defaultValue: "share a precise location channel?", comment: "Title of the confirmation before sharing a neighborhood-or-finer geohash invite")
static let sharePrecisionMessage = String(localized: "channel.share.precision_warning.message", defaultValue: "this channel covers a small area. an invite sent over sms or imessage is visible to the carrier and both handsets — it discloses interest in that place, not only that someone uses bitchat.", comment: "Body of the confirmation before sharing a fine-precision geohash invite")
static let shareAnyway = String(localized: "channel.share.precision_warning.confirm", defaultValue: "share anyway", comment: "Confirms sharing a fine-precision location channel after the OpSec warning")
static let openMap = String(localized: "location_channels.accessibility.open_map", defaultValue: "open map", comment: "Accessibility label for the button that opens the globe geohash picker")
static func meshTitle(_ count: Int) -> String {
let label = String(localized: "location_channels.mesh_label", comment: "Label for the mesh channel row")
@ -220,6 +224,47 @@ struct LocationChannelsSheet: View {
.sheet(item: $activeSharePayload) { payload in
ShareActivityView(text: payload.text)
}
#if os(iOS)
.fullScreenCover(isPresented: $showGlobePicker, onDismiss: applyPickedGeohash) {
globePicker
}
#else
.sheet(isPresented: $showGlobePicker, onDismiss: applyPickedGeohash) {
globePicker
}
#endif
}
/// Opens on the typed geohash, else the current location channel; the picker
/// itself falls back to the coarsest nearby channel.
private var globePicker: some View {
let typed = customGeohash.trimmed.lowercased().replacingOccurrences(of: "#", with: "")
let initial: String
if !typed.isEmpty {
initial = typed
} else if case .location(let channel) = locationChannelsModel.selectedChannel {
initial = channel.geohash
} else {
initial = ""
}
return GeohashPickerView(
initialGeohash: initial,
nearbyGeohashes: locationChannelsModel.availableChannels.map(\.geohash),
onSelect: { geohash in
pickedGeohash = geohash
showGlobePicker = false
},
onCancel: { showGlobePicker = false }
)
}
private func applyPickedGeohash() {
guard let geohash = pickedGeohash else { return }
pickedGeohash = nil
guard validateGeohash(geohash) else { return }
customError = nil
locationChannelsModel.teleport(to: geohash)
isPresented = false
}
private func requestShare(forGeohash geohash: String) {
@ -384,6 +429,15 @@ struct LocationChannelsSheet: View {
.lowercased()
.replacingOccurrences(of: "#", with: "")
let isValid = validateGeohash(normalized)
Button(action: { showGlobePicker = true }) {
Image(systemName: "map")
.font(.bitchatSystem(size: 16))
.foregroundColor(palette.secondary)
.frame(width: 36, height: 36)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityLabel(Strings.openMap)
Button(action: {
let gh = normalized
guard isValid else { customError = Strings.invalidGeohash; return }
@ -627,59 +681,12 @@ extension LocationChannelsSheet {
// MARK: - Coverage helpers
extension LocationChannelsSheet {
private func coverageString(forPrecision len: Int) -> String {
// Approximate max cell dimension at equator for a given geohash length.
// Values sourced from common geohash dimension tables.
let maxMeters: Double = {
switch len {
case 2: return 1_250_000
case 3: return 156_000
case 4: return 39_100
case 5: return 4_890
case 6: return 1_220
case 7: return 153
case 8: return 38.2
case 9: return 4.77
case 10: return 1.19
default:
if len <= 1 { return 5_000_000 }
// For >10, scale down conservatively by ~1/4 each char
let over = len - 10
return 1.19 * pow(0.25, Double(over))
}
}()
let usesMetric: Bool = {
if #available(iOS 16.0, macOS 13.0, *) {
return Locale.current.measurementSystem == .metric
} else {
return Locale.current.usesMetricSystem
}
}()
if usesMetric {
let km = maxMeters / 1000.0
return "~\(formatDistance(km)) km"
} else {
let miles = maxMeters / 1609.344
return "~\(formatDistance(miles)) mi"
}
}
private func formatDistance(_ value: Double) -> String {
if value >= 100 { return String(format: "%.0f", value.rounded()) }
if value >= 10 { return String(format: "%.1f", value) }
return String(format: "%.1f", value)
GeohashCoverage.string(forPrecision: len)
}
private func bluetoothRangeString() -> String {
let usesMetric: Bool = {
if #available(iOS 16.0, macOS 13.0, *) {
return Locale.current.measurementSystem == .metric
} else {
return Locale.current.usesMetricSystem
}
}()
// Approximate Bluetooth LE range for typical mobile devices; environment dependent
return usesMetric ? "~10–50 m" : "~30–160 ft"
GeohashCoverage.usesMetric() ? "~10–50 m" : "~30–160 ft"
}
private func locationName(for level: GeohashChannelLevel) -> String? {

View File

@ -0,0 +1,485 @@
import CoreGraphics
import Foundation
import Testing
@testable import bitchat
struct GlobeMathTests {
@Test func preparedProjectorMatchesReferenceProjection() {
let centers: [(Double, Double)] = [(0, 0), (45.25, 12.5), (-72, 179.5)]
let points: [(Double, Double)] = [(0, 0), (51.5074, -0.1278), (-33.8688, 151.2093), (89, -179.9)]
for (centerLat, centerLon) in centers {
let projector = GlobeMath.PreparedProjector(centerLat: centerLat, centerLon: centerLon)
for (lat, lon) in points {
let actual = projector.project(GlobeMath.Terms(lat: lat, lon: lon))
let expected = GlobeMath.projectRaw(lat: lat, lon: lon, centerLat: centerLat, centerLon: centerLon)
#expect(abs(expected.x - actual.x) < 1e-9)
#expect(abs(expected.y - actual.y) < 1e-9)
#expect(abs(expected.cosC - actual.cosC) < 1e-9)
}
}
}
@Test func unprojectInvertsProjection() throws {
let p = GlobeMath.projectRaw(lat: 48.2, lon: 16.4, centerLat: 40, centerLon: 10)
let location = try #require(GlobeMath.unproject(x: p.x, y: p.y, centerLat: 40, centerLon: 10))
#expect(abs(location.lat - 48.2) < 1e-9)
#expect(abs(location.lon - 16.4) < 1e-9)
#expect(GlobeMath.unproject(x: 0.9, y: 0.9, centerLat: 0, centerLon: 0) == nil)
}
@Test func zoomForPrecisionStaysWithinInteractiveBounds() {
for precision in 1...GlobeMath.maxPrecision {
let zoom = GlobeMath.zoomForPrecision(precision, baseRadius: 400, screenMin: 900)
#expect(zoom >= GlobeMath.minZoom)
#expect(zoom <= GlobeMath.maxZoom)
}
}
/// The +/- buttons frame a precision; the pinch-driven precision must agree, or the
/// first pinch after a button tap would jump to another cell size.
@Test func autoPrecisionAgreesWithFramedPrecision() {
let base = 400.0, screen = 900.0
for precision in 2...GlobeMath.maxPrecision {
let zoom = GlobeMath.zoomForPrecision(precision, baseRadius: base, screenMin: screen)
guard zoom > GlobeMath.minZoom, zoom < GlobeMath.maxZoom else { continue }
#expect(GlobeMath.autoPrecision(globeRadius: base * zoom, screenMin: screen) == precision)
}
}
@Test func cellSpansMatchGeohashBounds() {
for precision in 1...8 {
let b = Geohash.decodeBounds(Geohash.encode(latitude: 10, longitude: 10, precision: precision))
#expect(abs((b.latMax - b.latMin) - GlobeMath.cellSpanLat(precision: precision)) < 1e-9)
#expect(abs((b.lonMax - b.lonMin) - GlobeMath.cellSpanLon(precision: precision)) < 1e-9)
}
}
}
struct GlobeGeometryTests {
private let square = [
GlobeGeometry.DiscPoint(x: -0.5, y: -0.5, front: true),
GlobeGeometry.DiscPoint(x: 0.5, y: -0.5, front: true),
GlobeGeometry.DiscPoint(x: 0.5, y: 0.5, front: true),
GlobeGeometry.DiscPoint(x: -0.5, y: 0.5, front: true)
]
@Test func closedFullyVisibleRingConnectsLastPointToFirst() throws {
let runs = GlobeGeometry.frontRuns(square, closed: true)
let run = try #require(runs.first)
#expect(runs.count == 1)
#expect(run.count == square.count + 1)
#expect(run.first == run.last)
}
@Test func openFullyVisibleLineDoesNotConnectLastPointToFirst() throws {
let runs = GlobeGeometry.frontRuns(square, closed: false)
let run = try #require(runs.first)
#expect(runs.count == 1)
#expect(run.count == square.count)
#expect(run.first != run.last)
}
@Test func ringCrossingTheLimbSplitsIntoFrontRuns() {
let pts = [
GlobeGeometry.DiscPoint(x: -0.5, y: 0, front: true),
GlobeGeometry.DiscPoint(x: 0, y: 0, front: true),
GlobeGeometry.DiscPoint(x: 0.5, y: 0, front: false),
GlobeGeometry.DiscPoint(x: 0.2, y: 0.2, front: true)
]
let runs = GlobeGeometry.frontRuns(pts, closed: false)
#expect(runs.count == 2)
#expect(runs.allSatisfy { $0.count >= 2 })
}
@Test func polygonContainsDistinguishesInsideAndOutsidePoints() {
let polygon = [CGPoint(x: -10, y: -10), CGPoint(x: 10, y: -10), CGPoint(x: 10, y: 10), CGPoint(x: -10, y: 10)]
#expect(GlobeGeometry.polygonContains(polygon, x: 0, y: 0))
#expect(!GlobeGeometry.polygonContains(polygon, x: 20, y: 0))
}
@Test func ringContainsDistinguishesInsideAndOutsideCoordinates() {
let ring = GlobeRing(lats: [-10, -10, 10, 10], lons: [-10, 10, 10, -10])
#expect(GlobeGeometry.ringContains(ring, lat: 0, lon: 0))
#expect(!GlobeGeometry.ringContains(ring, lat: 20, lon: 0))
}
@Test func ringContainsHandlesTheAntimeridian() {
let ring = GlobeRing(lats: [-10, -10, 10, 10], lons: [170, -170, -170, 170])
#expect(GlobeGeometry.ringContains(ring, lat: 0, lon: 180))
#expect(GlobeGeometry.ringContains(ring, lat: 0, lon: -175))
#expect(!GlobeGeometry.ringContains(ring, lat: 20, lon: 180))
#expect(!GlobeGeometry.ringContains(ring, lat: 0, lon: 0))
}
@Test func clipSegmentClampsToRect() throws {
let rect = GlobeGeometry.ClipRect(left: 0, top: 0, right: 10, bottom: 10)
let clipped = try #require(GlobeGeometry.clipSegment(CGPoint(x: -10, y: 5), CGPoint(x: 20, y: 5), to: rect))
#expect(clipped.0 == CGPoint(x: 0, y: 5))
#expect(clipped.1 == CGPoint(x: 10, y: 5))
#expect(GlobeGeometry.clipSegment(CGPoint(x: -10, y: -5), CGPoint(x: 20, y: -5), to: rect) == nil)
}
@Test func clipPolygonKeepsOnlyTheVisiblePart() {
let rect = GlobeGeometry.ClipRect(left: 0, top: 0, right: 10, bottom: 10)
let clipped = GlobeGeometry.clipPolygon(
[CGPoint(x: -5, y: -5), CGPoint(x: 15, y: -5), CGPoint(x: 15, y: 15), CGPoint(x: -5, y: 15)],
to: rect
)
#expect(clipped.count == 4)
#expect(clipped.allSatisfy { $0.x >= 0 && $0.x <= 10 && $0.y >= 0 && $0.y <= 10 })
}
@Test func smallVisibleRingIsNotInverted() {
let ring = GlobeRing(lats: [-10, -10, 10, 10], lons: [-10, 10, 10, -10])
let projector = GlobeMath.PreparedProjector(centerLat: 0, centerLon: 0)
let pts = ring.terms.map { terms -> GlobeGeometry.DiscPoint in
let p = projector.project(terms)
return GlobeGeometry.DiscPoint(x: p.x, y: p.y, front: p.cosC > 0.005)
}
let polygon = GlobeGeometry.fillPolygon(pts, cx: 100, cy: 100, r: 100)
#expect(!GlobeGeometry.projectedFillNeedsInversion(
polygon: polygon, ring: ring, cx: 100, cy: 100, r: 100, centerLat: 0, centerLon: 0
))
}
}
struct GlobeMotionDetailTests {
@Test func fullDetailPreservesAllGlobeFeatures() {
let detail = GlobeMotionDetail.full.frame
#expect(detail.landPointStride == 1)
#expect(detail.showBorders)
#expect(detail.showCityLabels)
}
@Test func balancedDetailPreservesOrientationAndSelection() {
let detail = GlobeMotionDetail.balanced.frame
#expect(detail.landPointStride == 2)
#expect(detail.showBorders)
#expect(!detail.showCityLabels)
}
@Test func fastDetailUsesMinimumMovingFrameWork() {
let detail = GlobeMotionDetail.fast.frame
#expect(detail.landPointStride == 2)
#expect(!detail.showBorders)
#expect(!detail.showCityLabels)
}
@Test func adaptiveDetailDegradesOnSlowFramesAndRecoversWithHysteresis() {
#expect(GlobeMotionDetail.full.next(averageFrameMillis: 24) == .balanced)
#expect(GlobeMotionDetail.balanced.next(averageFrameMillis: 32) == .fast)
#expect(GlobeMotionDetail.fast.next(averageFrameMillis: 17) == .balanced)
#expect(GlobeMotionDetail.balanced.next(averageFrameMillis: 17) == .full)
#expect(GlobeMotionDetail.balanced.next(averageFrameMillis: 20) == .balanced)
#expect(GlobeMotionDetail.full.next(averageFrameMillis: .nan) == .fast)
}
private func record(_ governor: inout GlobeMotionGovernor, frames: Int, millis: Double) -> [GlobeMotionDetail] {
(0..<frames).map { _ in
governor.recordFrame(millis: millis)
return governor.detail
}
}
/// Regression: dropping detail makes frames fast, and stepping back up mid-drag
/// made the grid, neighbor cells and labels flash on and off.
@Test func detailNeverStepsBackUpDuringOneMotion() {
var governor = GlobeMotionGovernor()
#expect(governor.detail == .full)
governor.beginSession()
#expect(governor.detail == .balanced)
var seen = record(&governor, frames: 8, millis: 33)
seen += record(&governor, frames: 64, millis: 8)
seen += record(&governor, frames: 8, millis: 33)
seen += record(&governor, frames: 64, millis: 8)
#expect(seen.contains(.fast))
// Monotonic: once a level is dropped it never returns within the session.
#expect(zip(seen, seen.dropFirst()).allSatisfy { $1 <= $0 })
governor.endSession()
#expect(governor.detail == .full)
}
@Test func smoothSessionsStartTheNextOneHigherUntilOneDegrades() {
var governor = GlobeMotionGovernor()
governor.beginSession()
_ = record(&governor, frames: 16, millis: 8)
governor.endSession()
governor.beginSession()
#expect(governor.detail == .full)
_ = record(&governor, frames: 8, millis: 26)
#expect(governor.detail == .balanced)
governor.endSession()
// Having failed once, later smooth sessions stop retrying the upgrade, so
// detail doesn't alternate from one gesture to the next.
for _ in 0..<3 {
governor.beginSession()
#expect(governor.detail == .balanced)
_ = record(&governor, frames: 16, millis: 8)
governor.endSession()
}
}
@Test func easingRunsFromZeroToOneMonotonically() {
#expect(GlobeEasing.fastOutSlowIn(0) == 0)
#expect(GlobeEasing.fastOutSlowIn(1) == 1)
var previous = 0.0
for step in 1...20 {
let value = GlobeEasing.fastOutSlowIn(Double(step) / 20)
#expect(value >= previous)
previous = value
}
#expect(GlobeEasing.fastOutSlowIn(0.5) > 0.7)
}
}
@MainActor
struct GlobeStateTests {
@Test func selectionFollowsTheViewCenterOnceLaidOut() {
let state = GlobeState(targetLat: 48.2, targetLon: 16.4, initialPrecision: 4, startZoomedOut: false)
#expect(state.selectedGeohash.isEmpty)
state.setViewport(baseRadius: 170, screenMin: 390)
#expect(state.selectedGeohash == Geohash.encode(latitude: 48.2, longitude: 16.4, precision: 4))
}
@Test func introWithoutAnimationJumpsStraightToTheTarget() {
let state = GlobeState(targetLat: 37.77, targetLon: -122.42, initialPrecision: 5, startZoomedOut: true)
state.setViewport(baseRadius: 170, screenMin: 390, animateIntro: false)
#expect(state.precision == 5)
#expect(state.selectedGeohash == Geohash.encode(latitude: 37.77, longitude: -122.42, precision: 5))
#expect(!state.isAnimating)
}
@Test func pinchingInRaisesPrecisionAndRotationClampsNearThePoles() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 1, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
let before = state.precision
state.zoomBy(64)
#expect(state.precision > before)
state.rotateBy(dx: 0, dy: 1_000_000)
#expect(state.centerLat <= 89)
#expect(state.selectedGeohash.count == state.precision)
}
@Test func zoomStaysWithinBounds() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 2, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
state.zoomBy(0.0001)
#expect(state.zoom == GlobeMath.minZoom)
state.zoomBy(1e12)
#expect(state.zoom == GlobeMath.maxZoom)
// Pinching tops out around block-sized cells; finer precision is button-only.
#expect(state.precision == GlobeMath.autoPrecision(globeRadius: state.globeRadius, screenMin: 390))
#expect(state.precision >= 7)
}
@Test func interactionCancelsAnimationsAndRestoresFullDetail() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 2, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
state.animatePrecision(4)
#expect(state.isAnimating)
#expect(state.motionDetail == .balanced)
state.beginInteraction()
#expect(!state.isAnimating)
#expect(state.isInteracting)
state.endInteraction()
#expect(!state.isInMotion)
#expect(state.motionDetail == .full)
#expect(state.frameDetail == GlobeMotionDetail.full.frame)
}
@Test func releasingIntoAFlingKeepsTheSameMotionSession() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 2, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
state.beginInteraction()
#expect(state.motionDetail == .balanced)
state.endInteraction(flingVelocityX: 800, flingVelocityY: 0)
#expect(!state.isInteracting)
#expect(state.isAnimating)
#expect(state.motionDetail == .balanced)
state.beginInteraction()
#expect(!state.isAnimating)
#expect(state.motionDetail == .balanced)
state.endInteraction()
#expect(state.motionDetail == .full)
}
/// Review regression (PR #1807): `zzzz`'s center is 89.91°, past the ±89° drag
/// limit. The animated intro used to clamp there and select `zzzf`, while the
/// Reduce Motion path kept `zzzz`.
@Test func polarIntroLandsOnTheRequestedCellWithAndWithoutAnimation() {
let target = GeohashPickerView.initialTarget(initialGeohash: "zzzz", nearbyGeohashes: [])
#expect(target.lat > 89)
let animated = GlobeState(targetLat: target.lat, targetLon: target.lon, initialPrecision: target.precision, startZoomedOut: true)
animated.setViewport(baseRadius: 170, screenMin: 390, animateIntro: true)
#expect(animated.isAnimating)
animated.tick(100)
animated.tick(110)
#expect(!animated.isAnimating)
#expect(animated.selectedGeohash == "zzzz")
let still = GlobeState(targetLat: target.lat, targetLon: target.lon, initialPrecision: target.precision, startZoomedOut: true)
still.setViewport(baseRadius: 170, screenMin: 390, animateIntro: false)
#expect(still.selectedGeohash == "zzzz")
#expect(still.centerLat == animated.centerLat)
}
@Test func draggingFromAPolarTargetNeverSnapsBackToTheDragLimit() {
let center = Geohash.decodeCenter("zzzz")
let state = GlobeState(targetLat: center.lat, targetLon: center.lon, initialPrecision: 4, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
let start = state.centerLat
state.rotateBy(dx: 0, dy: 50)
#expect(state.centerLat == start)
state.rotateBy(dx: 0, dy: -0.01)
#expect(state.centerLat < start)
#expect(state.centerLat > 89)
state.rotateBy(dx: 0, dy: -1_000_000)
#expect(state.centerLat == -89)
}
@Test func slowFlingsAreIgnored() {
let state = GlobeState(targetLat: 0, targetLon: 0, initialPrecision: 2, startZoomedOut: false)
state.setViewport(baseRadius: 170, screenMin: 390)
state.fling(vx: 10, vy: -10)
#expect(!state.isAnimating)
state.fling(vx: 800, vy: 0)
#expect(state.isAnimating)
state.cancelAnimations()
}
}
struct GlobeWorldDataTests {
private static let landURL = URL(fileURLWithPath: #filePath)
.deletingLastPathComponent()
.deletingLastPathComponent()
.appendingPathComponent("bitchat/Resources/Globe/world_land.geojson")
/// Regression: Eurasia wraps the antimeridian at Chukotka, and the old relative-
/// longitude test counted the ±180° seam as a crossing, so open ocean read as
/// inside Eurasia and its fill was flipped over the Pacific and Atlantic.
@Test func bundledLandClassifiesOceansAndContinents() throws {
let land = GlobeWorldData.parseLand(try Data(contentsOf: Self.landURL))
#expect(land.count > 100)
func isLand(_ lat: Double, _ lon: Double) -> Bool {
land.contains { GlobeGeometry.ringContains($0, lat: lat, lon: lon) }
}
for (lat, lon) in [(0.0, -150.0), (32.3, -64.8), (40.0, -50.0), (-30.0, 80.0), (10.0, -30.0), (60.0, -85.0)] {
#expect(!isLand(lat, lon), "ocean at \(lat),\(lon) read as land")
}
for (lat, lon) in [(55.75, 37.62), (64.7, 177.5), (39.9, 116.4), (39.0, -98.0), (-15.8, -47.9), (0.0, 20.0)] {
#expect(isLand(lat, lon), "land at \(lat),\(lon) read as ocean")
}
}
/// No visible ocean pixel may be painted by a land fill, from any vantage point.
@Test func landFillsLeaveVisibleOceanUncovered() throws {
let land = GlobeWorldData.parseLand(try Data(contentsOf: Self.landURL))
let size = CGSize(width: 402, height: 874)
let cx = 201.0, cy = 437.0
let clip = GlobeGeometry.ClipRect(size: size)
let oceans: [(Double, Double)] = [(32.3, -64.8), (40, -50), (30, -20), (0, -150), (-30, 80)]
for centerLat in stride(from: -60.0, through: 60, by: 30) {
for centerLon in stride(from: -180.0, to: 180, by: 30) {
for zoom in [1.0, 3, 8] {
let r = 0.44 * 402 * zoom
let projector = GlobeMath.PreparedProjector(centerLat: centerLat, centerLon: centerLon)
for ocean in oceans {
guard let p = GlobeMath.project(lat: ocean.0, lon: ocean.1, centerLat: centerLat, centerLon: centerLon),
(p.x * p.x + p.y * p.y).squareRoot() < 0.98 else { continue }
let point = CGPoint(x: cx + p.x * r, y: cy + p.y * r)
guard CGRect(origin: .zero, size: size).contains(point) else { continue }
for ring in land {
let projected = ring.terms.map { projector.project($0) }
guard projected.contains(where: { $0.cosC >= 0 }) else { continue }
let pts = projected.map { GlobeGeometry.DiscPoint(x: $0.x, y: $0.y, front: $0.cosC > 0.005) }
let polygon = GlobeGeometry.fillPolygon(pts, cx: cx, cy: cy, r: r)
let invert = projected.contains(where: { $0.cosC < 0 }) && GlobeGeometry.projectedFillNeedsInversion(
polygon: polygon, ring: ring, cx: cx, cy: cy, r: r, centerLat: centerLat, centerLon: centerLon
)
let clipped = GlobeGeometry.clipPolygon(polygon, to: clip)
guard clipped.count >= 3 else { continue }
let path = CGMutablePath()
if invert { path.addEllipse(in: CGRect(x: cx - r, y: cy - r, width: 2 * r, height: 2 * r)) }
path.addLines(between: clipped)
path.closeSubpath()
#expect(
!path.contains(point, using: invert ? .evenOdd : .winding),
"ocean \(ocean) painted as land viewing \(centerLat),\(centerLon) at zoom \(zoom)"
)
}
}
}
}
}
}
@Test func parsesPolygonsMultiPolygonsAndLines() {
let land = Data("""
{"type":"GeometryCollection","geometries":[
{"type":"Polygon","coordinates":[[[0,0],[10,0],[10,10],[0,0]]]},
{"type":"MultiPolygon","coordinates":[[[[20,20],[30,20],[30,30],[20,20]]],[[[1,1],[2,2]]]]}
]}
""".utf8)
let rings = GlobeWorldData.parseLand(land)
#expect(rings.count == 2)
// GeoJSON positions are [lon, lat].
#expect(rings[0].lons == [0, 10, 10, 0])
#expect(rings[0].lats == [0, 0, 10, 0])
#expect(rings[0].terms.count == rings[0].count)
let borders = Data("""
{"type":"GeometryCollection","geometries":[
{"type":"LineString","coordinates":[[0,0],[1,1]]},
{"type":"MultiLineString","coordinates":[[[2,2],[3,3],[4,4]],[[5,5]]]}
]}
""".utf8)
let lines = GlobeWorldData.parseBorders(borders)
#expect(lines.map(\.count) == [2, 3])
}
@Test func parsesCities() {
let cities = GlobeWorldData.parseCities(Data("""
{"cities":[{"n":"Vienna","r":1,"cap":1,"mega":0,"pop":1,"lon":16.37,"lat":48.2},{"n":"broken"}]}
""".utf8))
#expect(cities.count == 1)
#expect(cities[0].name == "Vienna")
#expect(cities[0].capital)
#expect(!cities[0].megacity)
#expect(abs(cities[0].terms.sinLat - sin(48.2 * .pi / 180)) < 1e-12)
#expect(abs(cities[0].terms.sinLon - sin(16.37 * .pi / 180)) < 1e-12)
}
}
@MainActor
struct GeohashPickerTargetTests {
@Test func prefersTheGivenGeohash() {
let target = GeohashPickerView.initialTarget(initialGeohash: "u2edk", nearbyGeohashes: ["u2"])
let center = Geohash.decodeCenter("u2edk")
#expect(target.lat == center.lat)
#expect(target.lon == center.lon)
#expect(target.precision == 5)
}
@Test func fallsBackToTheCoarsestNearbyChannel() {
let target = GeohashPickerView.initialTarget(initialGeohash: "", nearbyGeohashes: ["u2edk", "u2e", "u2edk7q"])
#expect(target.precision == 3)
#expect(target.lat == Geohash.decodeCenter("u2e").lat)
}
@Test func defaultsToAWideWorldView() {
let target = GeohashPickerView.initialTarget(initialGeohash: nil, nearbyGeohashes: [])
#expect(target.lat == 20)
#expect(target.lon == 0)
#expect(target.precision == 2)
}
@Test func coverageMatchesTheChannelLevels() {
#expect(GeohashCoverage.level(forLength: 1) == .region)
#expect(GeohashCoverage.level(forLength: 4) == .province)
#expect(GeohashCoverage.level(forLength: 5) == .city)
#expect(GeohashCoverage.level(forLength: 12) == .building)
#expect(GeohashCoverage.string(forPrecision: 5, locale: Locale(identifier: "de_DE")) == "~4.9 km")
#expect(GeohashCoverage.string(forPrecision: 2, locale: Locale(identifier: "en_US")) == "~777 mi")
}
}