krz/moonrise

Night-sky companion for iPhone, Apple Watch and Vision Pro: what's up tonight, the Moon, planets, launches and missions, and a Library of the solar system. SwiftUI app with a Cloudflare Workers backend. astronomy cloudflare-workers ios night-sky space swiftui visionos watchos

App/Sources/SolarSystem3D.swift

b327e0d6e7ab67511c5bade3f3c3a93834f6e9ca
moonrise/App/Sources/SolarSystem3D.swift history · blame · raw

941 lines · 44564 bytes

  1import Feeds
  2import Library
  3import RealityKit
  4import SkyEngine
  5import SkyRenderer
  6import SwiftUI
  7import UIKit
  8
  9/// How distances and sizes are drawn in the 3D solar system.
 10enum SolarScale: String, CaseIterable, Identifiable {
 11    /// Distances raised to the power 0.4 and sizes enlarged, so everything fits and can be seen.
 12    case compressed
 13    /// Distances and sizes both true (1 AU = 1 scene metre); planets need markers to be found.
 14    case trueScale
 15    var id: String { rawValue }
 16    var name: String { self == .compressed ? "Compressed" : "True scale" }
 17}
 18
 19/// One of the Sun's planets, with what the scene needs to draw it.
 20struct SolarPlanet: Identifiable, Sendable {
 21    var id: String
 22    var body: Body?
 23    var radiusKm: Double
 24    var color: String
 25    var tiltDeg: Double
 26    var periodDays: Double
 27
 28    static let all: [SolarPlanet] = [
 29        ("mercury", Body.mercury, 88.0), ("venus", .venus, 224.7), ("earth", nil, 365.25), ("mars", .mars, 687.0),
 30        ("jupiter", .jupiter, 4332.6), ("saturn", .saturn, 10_759.2), ("uranus", .uranus, 30_688.5), ("neptune", .neptune, 60_182.0),
 31    ].compactMap { id, body, period in
 32        guard let d = Library.page(id: id)?.drawing else { return nil }
 33        return SolarPlanet(id: id, body: body, radiusKm: d.radiusKm ?? 6371, color: d.color ?? "#cccccc", tiltDeg: d.axialTiltDeg ?? 0, periodDays: period)
 34    }
 35
 36    /// Pluto, which Astronomy Engine covers, drawn with the dwarf planets.
 37    static let pluto: SolarPlanet? = Library.page(id: "pluto")?.drawing.map {
 38        SolarPlanet(id: "pluto", body: .pluto, radiusKm: $0.radiusKm ?? 1188, color: $0.color ?? "#cdb79e", tiltDeg: $0.axialTiltDeg ?? 0, periodDays: 90_560)
 39    }
 40
 41    /// Heliocentric position on J2000 ecliptic axes, AU.
 42    func position(at date: Date) -> SIMD3<Double> {
 43        if let body { return (try? SkyEngine.heliocentricEcliptic(body, at: date)) ?? .zero }
 44        return (try? SkyEngine.heliocentricEarth(at: date)) ?? .zero
 45    }
 46}
 47
 48/// A moon from its Library page: exact positions for Earth's Moon and Jupiter's four big moons,
 49/// a circular orbit in the planet's equator plane (at an arbitrary starting point) for the rest.
 50struct SolarMoon: Identifiable, Sendable {
 51    var id: String
 52    var parent: String
 53    var distanceKm: Double
 54    var periodDays: Double
 55    var radiusKm: Double
 56    var color: String
 57
 58    static let galilean = ["io", "europa", "ganymede", "callisto"]
 59
 60    static let all: [SolarMoon] = Library.pages(in: .moons).compactMap { p in
 61        guard let dist = p.facts.first(where: { $0.label.hasPrefix("Mean distance from") }),
 62              let period = p.facts.first(where: { $0.label.hasPrefix("Orbital period") }),
 63              let km = number(dist.value), let days = number(period.value) else { return nil }
 64        let parent = dist.label.replacingOccurrences(of: "Mean distance from ", with: "").lowercased()
 65        let retrograde = p.facts.contains { $0.value == "Retrograde" }
 66        return SolarMoon(id: p.id, parent: parent, distanceKm: km, periodDays: retrograde ? -days : days,
 67                         radiusKm: p.drawing?.radiusKm ?? 100, color: p.drawing?.color ?? "#999999")
 68    }
 69
 70    /// 1070400 from "1,070,400 km"; 0.319 from "0.319 days (7 h 39 m)".
 71    static func number(_ s: String) -> Double? {
 72        s.split(separator: " ").first.flatMap { Double($0.replacingOccurrences(of: ",", with: "")) }
 73    }
 74
 75    var isExact: Bool { id == "moon" || Self.galilean.contains(id) }
 76}
 77
 78/// Maps ecliptic AU to scene metres (y up) and gives drawn radii for each scale.
 79struct SolarMapping {
 80    var scale: SolarScale
 81
 82    static let auKm = 1.495978707e8
 83    static let sunRadiusKm = 695_700.0
 84
 85    func point(_ v: SIMD3<Double>) -> SIMD3<Float> {
 86        let r = (v * v).sum().squareRoot()
 87        guard r > 0 else { return .zero }
 88        let d = scale == .compressed ? 1.6 * pow(r, 0.4) : r
 89        let u = v / r * d
 90        return SIMD3(Float(u.x), Float(u.z), Float(-u.y))
 91    }
 92
 93    /// Ecliptic axes to scene axes without changing length.
 94    static func axes(_ v: SIMD3<Double>) -> SIMD3<Float> { SIMD3(Float(v.x), Float(v.z), Float(-v.y)) }
 95
 96    func radius(km: Double) -> Float {
 97        scale == .compressed ? Float(0.09 * pow(km / 6371, 0.45)) : Float(km / Self.auKm)
 98    }
 99
100    /// How far from its planet a moon is drawn: log-squeezed in compressed scale, true otherwise.
101    func moonDistance(km: Double, planetRadiusKm: Double) -> Float {
102        scale == .compressed
103            ? radius(km: planetRadiusKm) * Float(1.2 + 1.6 * log10(max(km / planetRadiusKm, 1.5)))
104            : Float(km / Self.auKm)
105    }
106
107    var sunRadius: Float { scale == .compressed ? 0.35 : Float(Self.sunRadiusKm / Self.auKm) }
108}
109
110/// Orbit camera around a target point.
111struct SolarCamera: Equatable {
112    var target: SIMD3<Float> = .zero
113    var yaw: Float = 0.4
114    var pitch: Float = 0.55
115    var distance: Float = 14
116    static let fovDegrees: Float = 50
117
118    var position: SIMD3<Float> {
119        target + distance * SIMD3(cos(pitch) * sin(yaw), sin(pitch), cos(pitch) * cos(yaw))
120    }
121
122    /// Screen position of a scene point, or nil if it is behind the camera.
123    func project(_ p: SIMD3<Float>, in size: CGSize) -> CGPoint? {
124        let pos = position
125        let f = simd_normalize(target - pos)
126        let r = simd_normalize(simd_cross(f, SIMD3(0, 1, 0)))
127        let u = simd_cross(r, f)
128        let v = p - pos
129        let z = simd_dot(v, f)
130        guard z > 0 else { return nil }
131        let k = Float(size.height / 2) / tan(Self.fovDegrees * .pi / 360)
132        return CGPoint(x: size.width / 2 + CGFloat(simd_dot(v, r) / z * k), y: size.height / 2 - CGFloat(simd_dot(v, u) / z * k))
133    }
134
135    func distance(to p: SIMD3<Float>) -> Float { simd_length(p - position) }
136}
137
138/// The live space weather the scene shows: a flare on the Sun and an aurora ring on Earth.
139struct SolarWeather: Equatable {
140    var kp: Double?
141    /// Strongest X-ray flux in the last three hours and when it peaked.
142    var flare: (flux: Double, time: Date)?
143    /// From `SunFeeds.summary`, the same text as the Sun tab.
144    var summary: String?
145
146    static func == (a: SolarWeather, b: SolarWeather) -> Bool { a.kp == b.kp && a.flare?.flux == b.flare?.flux && a.summary == b.summary }
147
148    var showsFlare: Bool { (flare?.flux ?? 0) >= 1e-5 }
149    var showsAurora: Bool { (kp ?? 0) >= 4 }
150}
151
152/// Which optional layers are drawn.
153struct SolarLayers: Equatable {
154    var moons = true
155    var dwarfs = true
156    var craft = true
157    var comets = true
158}
159
160/// Anything the scene draws and can label or fly to.
161struct SolarMarker {
162    enum Kind { case sun, planet, moon, dwarf, craft, comet }
163    var id: String
164    var name: String
165    var kind: Kind
166    var scene: SIMD3<Float>
167    /// Drawn radius in scene units (for dots, the dot's size at the current zoom).
168    var radius: Float
169    var visible: Bool
170}
171
172/// Entities created once and moved on each update.
173@MainActor
174final class SolarSceneEntities {
175    let root = Entity()
176    let camera = PerspectiveCamera()
177    let sun = ModelEntity()
178    var bodies: [String: ModelEntity] = [:]
179    var nights: [String: ModelEntity] = [:]
180    var tails: [String: ModelEntity] = [:]
181    var orbits: [String: ModelEntity] = [:]
182    var orbitsBuilt: (SolarScale, Float)?
183    var paths: [String: ModelEntity] = [:]
184    var pathsBuilt: (SolarScale, Float, Int)?
185    let debris = ModelEntity()
186    var debrisBuilt: (SolarScale, Float, String)?
187    let flare = ModelEntity()
188    let aurora = Entity()
189}
190
191struct SolarSystem3DView: View {
192    var date: Date
193    var live: Bool
194    @Binding var scale: SolarScale
195    var ink: Color
196    var accent: Color
197    var onOpen: (LibraryPage) -> Void
198
199    @State private var entities = SolarSceneEntities()
200    @State private var cam = SolarCamera()
201    @State private var dragStart: SolarCamera?
202    @State private var pinchStart: Float?
203    @State private var selected: String?
204    @State private var weather = SolarWeather()
205    @State private var flight: Task<Void, Never>?
206    @State private var pulse = false
207    @State private var viewSize = CGSize(width: 400, height: 600)
208    @AppStorage("solar.moons") private var showMoons = true
209    @AppStorage("solar.dwarfs") private var showDwarfs = true
210    @AppStorage("solar.craft") private var showCraft = true
211    @AppStorage("solar.comets") private var showComets = true
212
213    private var mapping: SolarMapping { SolarMapping(scale: scale) }
214    private var layers: SolarLayers { SolarLayers(moons: showMoons, dwarfs: showDwarfs, craft: showCraft, comets: showComets) }
215
216    private static let mainComets: Set<String> = ["halley", "encke", "67p"]
217    private static let craftColor = UIColor(red: 0.88, green: 0.24, blue: 0.19, alpha: 1)
218
219    /// Meteor showers within a week of their peak, with a parent orbit to draw.
220    private var activeShowers: [MeteorShower] {
221        MeteorShower.major.filter { $0.parent != nil && abs($0.daysToPeak(from: date)) <= 7 }
222    }
223
224    var body: some View {
225        GeometryReader { geo in
226            ZStack {
227                RealityView { content in
228                    content.camera = .virtual
229                    build(content)
230                } update: { _ in
231                    place()
232                }
233                .gesture(dragGesture.simultaneously(with: pinchGesture))
234                .onTapGesture(coordinateSpace: .local) { tap($0, size: geo.size) }
235
236                labels(size: geo.size).allowsHitTesting(false)
237
238                VStack(spacing: 8) {
239                    if let s = selected { card(s) }
240                    Spacer()
241                    HStack(alignment: .bottom) {
242                        Text(summary)
243                            .font(.caption2).dimmed(0.8)
244                            .padding(.horizontal, 10).padding(.vertical, 6)
245                            .background(Color.black.opacity(0.7), in: RoundedRectangle(cornerRadius: 10))
246                        Spacer(minLength: 8)
247                        layerMenu
248                    }
249                }
250                .padding(12)
251            }
252            .clipped()
253            .onAppear { viewSize = geo.size; cam.distance = fitDistance() }
254            .onChange(of: geo.size) { viewSize = geo.size }
255        }
256        .accessibilityElement(children: .contain)
257        .accessibilityLabel("3D solar system. Drag to turn, pinch to zoom, tap a body to learn about it.")
258        .onChange(of: scale) { resetView() }
259        .task { await loadWeather() }
260        .task {
261            while !Task.isCancelled {
262                try? await Task.sleep(for: .milliseconds(700))
263                pulse.toggle()
264            }
265        }
266    }
267
268    private var summary: String {
269        var lines: [String] = []
270        if let s = activeShowers.first, let parent = KeplerOrbit.comets.first(where: { $0.id == s.parent }) {
271            let d = s.daysToPeak(from: date)
272            let when = abs(d) < 1 ? "peak today" : d > 0 ? "peak in \(Int(d.rounded())) days" : "peaked \(Int((-d).rounded())) days ago"
273            lines.append("\(s.name) \(when): Earth is crossing debris from \(parent.name).")
274        }
275        lines.append(live ? weather.summary ?? "Loading space weather" : "Live space weather is shown only for today.")
276        return lines.joined(separator: "\n")
277    }
278
279    private var layerMenu: some View {
280        Menu {
281            Toggle("Moons", isOn: $showMoons)
282            Toggle("Dwarf planets", isOn: $showDwarfs)
283            Toggle("Spacecraft", isOn: $showCraft)
284            Toggle("Comets and meteor showers", isOn: $showComets)
285        } label: {
286            Image(systemName: "square.3.layers.3d").font(.body).frame(width: 44, height: 44)
287                .background(Color.black.opacity(0.7), in: Circle())
288        }
289        .accessibilityLabel("Layers")
290    }
291
292    // MARK: Markers
293
294    /// Every body's scene position and drawn size for the current date, scale, layers and camera.
295    private func markers() -> [SolarMarker] {
296        let map = mapping
297        var out: [SolarMarker] = [SolarMarker(id: "sun", name: "Sun", kind: .sun, scene: .zero, radius: map.sunRadius, visible: true)]
298        var parents: [String: (scene: SIMD3<Float>, radiusKm: Double, tiltDeg: Double)] = [:]
299        func dot(_ p: SIMD3<Float>) -> Float { cam.distance(to: p) * 0.006 }
300
301        for p in SolarPlanet.all {
302            let s = map.point(p.position(at: date))
303            parents[p.id] = (s, p.radiusKm, p.tiltDeg)
304            out.append(SolarMarker(id: p.id, name: Library.page(id: p.id)?.title ?? p.id, kind: .planet, scene: s, radius: map.radius(km: p.radiusKm), visible: true))
305        }
306        if let pluto = SolarPlanet.pluto {
307            let s = map.point(pluto.position(at: date))
308            parents["pluto"] = (s, pluto.radiusKm, pluto.tiltDeg)
309            out.append(SolarMarker(id: "pluto", name: "Pluto", kind: .dwarf, scene: s, radius: map.radius(km: pluto.radiusKm), visible: layers.dwarfs))
310        }
311        for k in KeplerOrbit.dwarfPlanets {
312            let r = Library.page(id: k.id)?.drawing?.radiusKm ?? 500
313            out.append(SolarMarker(id: k.id, name: k.name, kind: .dwarf, scene: map.point(k.position(at: date)), radius: map.radius(km: r), visible: layers.dwarfs))
314        }
315
316        // Moons appear when the camera is near their planet (or the planet or moon is selected).
317        let galilean = SkyEngine.galileanMoons(at: date)
318        let jd = date.timeIntervalSince1970 / 86_400 + 2_440_587.5
319        var reach: [String: Float] = [:]
320        var moonMarkers: [SolarMarker] = []
321        for m in SolarMoon.all {
322            guard let parent = parents[m.parent] else { continue }
323            let dist = map.moonDistance(km: m.distanceKm, planetRadiusKm: parent.radiusKm)
324            reach[m.parent] = max(reach[m.parent] ?? 0, dist)
325            var dir: SIMD3<Float>
326            if m.id == "moon" {
327                dir = simd_normalize(SolarMapping.axes(SkyEngine.geocentricMoonEcliptic(at: date)))
328            } else if let i = SolarMoon.galilean.firstIndex(of: m.id) {
329                dir = simd_normalize(SolarMapping.axes(galilean[i]))
330            } else {
331                let phase = Double(m.id.unicodeScalars.reduce(0) { $0 + Int($1.value) } % 97) / 97
332                let a = 2 * Double.pi * ((jd - 2_451_545) / m.periodDays + phase)
333                let flat = SIMD3(Float(cos(a)), 0, Float(sin(a)))
334                dir = simd_quatf(angle: Float(parent.tiltDeg * .pi / 180), axis: [1, 0, 0]).act(flat)
335            }
336            moonMarkers.append(SolarMarker(id: m.id, name: Library.page(id: m.id)?.title ?? m.id, kind: .moon,
337                                           scene: parent.scene + dir * dist, radius: map.radius(km: m.radiusKm), visible: false))
338        }
339        for i in moonMarkers.indices {
340            let m = SolarMoon.all.first { $0.id == moonMarkers[i].id }!
341            guard let parent = parents[m.parent], let r = reach[m.parent] else { continue }
342            let near = cam.distance(to: parent.scene) < r * 16
343            let chosen = selected == m.id || selected == m.parent
344            let parentShown = m.parent != "pluto" || layers.dwarfs
345            moonMarkers[i].visible = layers.moons && parentShown && (near || chosen)
346        }
347        out += moonMarkers
348
349        for craft in Spacecraft.all {
350            guard let p = craft.position3(at: date) else { continue }
351            let s = map.point(p)
352            out.append(SolarMarker(id: "craft:\(craft.name)", name: craft.name, kind: .craft, scene: s, radius: dot(s), visible: layers.craft))
353        }
354
355        let showerParents = Set(activeShowers.compactMap(\.parent))
356        for c in KeplerOrbit.comets {
357            let s = map.point(c.position(at: date))
358            let shown = layers.comets && (Self.mainComets.contains(c.id) || showerParents.contains(c.id))
359            out.append(SolarMarker(id: "comet:\(c.id)", name: c.name, kind: .comet, scene: s, radius: dot(s), visible: shown))
360        }
361        return out
362    }
363
364    // MARK: Scene
365
366    private func build(_ content: RealityViewCameraContent) {
367        let e = entities
368        content.add(e.root)
369        e.camera.camera.fieldOfViewInDegrees = SolarCamera.fovDegrees
370        e.root.addChild(e.camera)
371
372        let sunMaterial = UnlitMaterial(color: UIColor(red: 1, green: 0.86, blue: 0.5, alpha: 1))
373        e.sun.model = ModelComponent(mesh: .generateSphere(radius: 1), materials: [sunMaterial])
374        e.root.addChild(e.sun)
375        // Glow: nested translucent shells, fainter outward.
376        for i in 1...10 {
377            let r = 1 + Float(i) * 0.07
378            let a = CGFloat(0.09 * pow(0.78, Double(i - 1)))
379            var g = UnlitMaterial(color: UIColor(red: 1, green: 0.72, blue: 0.32, alpha: a))
380            g.blending = .transparent(opacity: .init(floatLiteral: Float(a)))
381            e.sun.addChild(ModelEntity(mesh: .generateSphere(radius: r), materials: [g]))
382        }
383
384        // Planets, dwarf planets and moons: textured where there is a map, with a night side.
385        var spheres: [(id: String, color: String, tilt: Double)] = SolarPlanet.all.map { ($0.id, $0.color, $0.tiltDeg) }
386        if let pluto = SolarPlanet.pluto { spheres.append(("pluto", pluto.color, pluto.tiltDeg)) }
387        spheres += KeplerOrbit.dwarfPlanets.map { ($0.id, Library.page(id: $0.id)?.drawing?.color ?? "#999999", 0) }
388        spheres += SolarMoon.all.map { ($0.id, $0.color, 0) }
389        for s in spheres {
390            let body = ModelEntity()
391            // Plain colour first; the map, if there is one, is swapped in once it has loaded.
392            let m = UnlitMaterial(color: UIColor(Color(hex: s.color) ?? .gray))
393            body.model = ModelComponent(mesh: .generateSphere(radius: 1), materials: [m])
394            body.orientation = simd_quatf(angle: Float(s.tilt * .pi / 180), axis: [1, 0, 0])
395            if s.id == "saturn" { body.addChild(Self.annulus(inner: 1.24, outer: 2.27, color: UIColor(red: 0.85, green: 0.78, blue: 0.62, alpha: 0.7))) }
396            e.bodies[s.id] = body
397            e.root.addChild(body)
398            let night = Self.nightShell()
399            e.nights[s.id] = night
400            e.root.addChild(night)
401        }
402
403        // Spacecraft and comet nuclei: dots sized each frame to stay visible.
404        for craft in Spacecraft.all {
405            let dot = ModelEntity(mesh: .generateSphere(radius: 1), materials: [UnlitMaterial(color: Self.craftColor)])
406            e.bodies["craft:\(craft.name)"] = dot
407            e.root.addChild(dot)
408        }
409        for c in KeplerOrbit.comets {
410            let nucleus = ModelEntity(mesh: .generateSphere(radius: 1), materials: [UnlitMaterial(color: UIColor(white: 0.92, alpha: 1))])
411            e.bodies["comet:\(c.id)"] = nucleus
412            e.root.addChild(nucleus)
413            // A soft tail: nested cones, wider and fainter outward.
414            let tail = ModelEntity()
415            for (radius, alpha) in [(0.025, 0.3), (0.06, 0.14), (0.11, 0.06)] as [(Float, Float)] {
416                var t = UnlitMaterial(color: UIColor(red: 0.7, green: 0.88, blue: 1, alpha: 1))
417                t.blending = .transparent(opacity: .init(floatLiteral: alpha))
418                tail.addChild(ModelEntity(mesh: .generateCone(height: 1, radius: radius), materials: [t]))
419            }
420            e.tails[c.id] = tail
421            e.root.addChild(tail)
422        }
423
424        var debrisMaterial = UnlitMaterial(color: UIColor(red: 1, green: 0.88, blue: 0.65, alpha: 0.55))
425        debrisMaterial.blending = .transparent(opacity: .init(floatLiteral: 0.55))
426        debrisMaterial.faceCulling = .none
427        e.debris.model = ModelComponent(mesh: .generateBox(size: 0.0001), materials: [debrisMaterial])
428        e.root.addChild(e.debris)
429
430        var flareMaterial = UnlitMaterial(color: UIColor(red: 1, green: 1, blue: 0.85, alpha: 0.9))
431        flareMaterial.blending = .transparent(opacity: .init(floatLiteral: 0.9))
432        e.flare.model = ModelComponent(mesh: .generateSphere(radius: 1), materials: [flareMaterial])
433        e.root.addChild(e.flare)
434        for y: Float in [0.86, -0.86] {
435            for (inner, outer, alpha) in [(0.36, 0.66, 0.22), (0.45, 0.56, 0.5)] as [(Float, Float, CGFloat)] {
436                let ring = Self.annulus(inner: inner, outer: outer, color: UIColor(red: 0.35, green: 1, blue: 0.55, alpha: alpha))
437                ring.position.y = y * 1.02
438                e.aurora.addChild(ring)
439            }
440        }
441        e.bodies["earth"]?.addChild(e.aurora)
442        place()
443        loadTextures()
444    }
445
446    /// Loads surface maps off the main thread (about 0.6 s for all of them) and applies each as it arrives.
447    private func loadTextures() {
448        let e = entities
449        var jobs: [(entity: ModelEntity, url: URL, tint: UIColor)] = e.bodies.compactMap { id, entity in
450            GlobeView.mapURL(id).map { (entity, $0, .white) }
451        }
452        if let sun = Bundle.main.url(forResource: "sun", withExtension: "jpg", subdirectory: "Globes") { jobs.append((e.sun, sun, .white)) }
453        for job in jobs {
454            Task {
455                guard let texture = try? await TextureResource(contentsOf: job.url) else { return }
456                var m = UnlitMaterial()
457                m.color = .init(tint: job.tint, texture: .init(texture))
458                job.entity.model?.materials = [m]
459            }
460        }
461    }
462
463    /// Moves everything for the current date, scale, layers and camera.
464    private func place() {
465        let e = entities
466        let map = mapping
467        e.sun.scale = .init(repeating: map.sunRadius)
468        for m in markers() where m.kind != .sun {
469            guard let body = e.bodies[m.id] else { continue }
470            body.isEnabled = m.visible
471            body.position = m.scene
472            body.scale = .init(repeating: m.radius)
473            if let night = e.nights[m.id] {
474                night.isEnabled = m.visible
475                night.position = m.scene
476                night.scale = .init(repeating: m.radius * 1.004)
477                night.orientation = simd_quatf(from: SIMD3(0, 1, 0), to: simd_normalize(-m.scene))
478            }
479            if m.kind == .comet, let tail = e.tails[String(m.id.dropFirst(6))] {
480                place(tail: tail, at: m, map: map)
481            }
482        }
483        rebuildOrbitsIfNeeded()
484        rebuildPathsIfNeeded()
485        rebuildDebrisIfNeeded()
486        // Planet orbits are a guide at system scale; close to a planet they only cut across it.
487        let farEnough = cam.distance > map.radius(km: 70_000) * 25
488        for (id, o) in e.orbits {
489            o.isEnabled = farEnough && orbitShown(id)
490        }
491        for p in e.paths.values { p.isEnabled = farEnough && layers.craft }
492
493        if live, weather.showsFlare, let earth = e.bodies["earth"] {
494            e.flare.isEnabled = true
495            e.flare.position = simd_normalize(earth.position) * map.sunRadius * 1.02
496            e.flare.scale = .init(repeating: map.sunRadius * (pulse ? 0.22 : 0.16))
497        } else {
498            e.flare.isEnabled = false
499        }
500        e.aurora.isEnabled = live && weather.showsAurora
501
502        e.camera.look(at: cam.target, from: cam.position, relativeTo: nil)
503        e.camera.camera.near = max(cam.distance * 0.001, 1e-9)
504        e.camera.camera.far = cam.distance * 100 + 400
505    }
506
507    /// A comet's tail points away from the Sun and grows as the comet nears it; none beyond 4 AU.
508    private func place(tail: ModelEntity, at m: SolarMarker, map: SolarMapping) {
509        guard let c = KeplerOrbit.comets.first(where: { "comet:\($0.id)" == m.id }) else { return }
510        let au = (c.position(at: date) * c.position(at: date)).sum().squareRoot()
511        guard m.visible, au < 4 else { tail.isEnabled = false; return }
512        tail.isEnabled = true
513        let away = simd_normalize(m.scene)
514        let length = (map.scale == .compressed ? 0.9 : 0.4) * Float(min(1 / au, 2.5))
515        // The cone's apex is at +y: point it at the Sun so the tail widens away from it.
516        tail.orientation = simd_quatf(from: SIMD3(0, 1, 0), to: -away)
517        tail.scale = .init(repeating: length)
518        tail.position = m.scene + away * length / 2
519    }
520
521    private func orbitShown(_ id: String) -> Bool {
522        if id.hasPrefix("comet:") {
523            let c = String(id.dropFirst(6))
524            return layers.comets && (Self.mainComets.contains(c) || activeShowers.contains { $0.parent == c })
525        }
526        if id.hasPrefix("dwarf:") { return layers.dwarfs }
527        return true
528    }
529
530    /// Orbit ribbons for planets, dwarf planets and comets; rebuilt when the scale changes or the zoom
531    /// changes enough that their width would look wrong.
532    private func rebuildOrbitsIfNeeded() {
533        let e = entities
534        let width = cam.distance * 0.0022
535        if let (s, w) = e.orbitsBuilt, s == scale, w / width < 1.6, width / w < 1.6 { return }
536        e.orbitsBuilt = (scale, width)
537        let map = mapping
538        func set(_ id: String, _ points: [SIMD3<Float>], color: UIColor, opacity: Float) {
539            let mesh = Self.ribbon(points, width: width, closed: true)
540            if let existing = e.orbits[id] { existing.model?.mesh = mesh; return }
541            var m = UnlitMaterial(color: color)
542            m.blending = .transparent(opacity: .init(floatLiteral: opacity))
543            m.faceCulling = .none
544            let orbit = ModelEntity(mesh: mesh, materials: [m])
545            e.orbits[id] = orbit
546            e.root.addChild(orbit)
547        }
548        for p in SolarPlanet.all + [SolarPlanet.pluto].compactMap({ $0 }) {
549            let pts = (0..<240).map { i in map.point(p.position(at: date.addingTimeInterval(Double(i) / 240 * p.periodDays * 86_400))) }
550            set(p.id == "pluto" ? "dwarf:pluto" : p.id, pts, color: .white, opacity: p.id == "pluto" ? 0.12 : 0.22)
551        }
552        for k in KeplerOrbit.dwarfPlanets {
553            set("dwarf:\(k.id)", k.orbitPath().map(map.point), color: .white, opacity: 0.12)
554        }
555        for c in KeplerOrbit.comets {
556            set("comet:\(c.id)", c.orbitPath(steps: 400).map(map.point), color: UIColor(red: 0.6, green: 0.8, blue: 1, alpha: 1), opacity: 0.22)
557        }
558    }
559
560    /// Spacecraft paths from launch to the slider's date, rebuilt every 10 days of date change.
561    private func rebuildPathsIfNeeded() {
562        let e = entities
563        let width = cam.distance * 0.0022
564        let bucket = Int(date.timeIntervalSince1970 / 864_000)
565        let built = e.pathsBuilt
566        if let built, built.0 == scale, built.1 / width < 1.6, width / built.1 < 1.6, built.2 == bucket { return }
567        e.pathsBuilt = (scale, width, bucket)
568        let map = mapping
569        let day = date.timeIntervalSince1970 / 86_400
570        for craft in Spacecraft.all {
571            var pts = craft.points.filter { $0[0] <= day }.map { map.point(SIMD3($0[1], $0[2], $0[3])) }
572            if let now = craft.position3(at: date) { pts.append(map.point(now)) }
573            let mesh: MeshResource = pts.count > 1 ? Self.ribbon(pts, width: width, closed: false) : .generateBox(size: 0.0001)
574            if let existing = e.paths[craft.name] {
575                existing.model?.mesh = mesh
576            } else {
577                var m = UnlitMaterial(color: Self.craftColor)
578                m.blending = .transparent(opacity: .init(floatLiteral: 0.4))
579                m.faceCulling = .none
580                let path = ModelEntity(mesh: mesh, materials: [m])
581                e.paths[craft.name] = path
582                e.root.addChild(path)
583            }
584        }
585    }
586
587    /// Debris along an active meteor shower's parent orbit: small specks, densest where it crosses Earth's orbit.
588    private func rebuildDebrisIfNeeded() {
589        let e = entities
590        let showers = layers.comets ? activeShowers.compactMap(\.parent).sorted().joined(separator: ",") : ""
591        let size = cam.distance * 0.0016
592        if let (s, w, key) = e.debrisBuilt, s == scale, key == showers, w / size < 1.6, size / w < 1.6 { return }
593        e.debrisBuilt = (scale, size, showers)
594        guard !showers.isEmpty else { e.debris.isEnabled = false; return }
595        e.debris.isEnabled = true
596        let map = mapping
597        var rng = SeededRandom(seed: 42)
598        var positions: [SIMD3<Float>] = []
599        var indices: [UInt32] = []
600        for id in showers.split(separator: ",") {
601            guard let c = KeplerOrbit.comets.first(where: { $0.id == id }) else { continue }
602            for p in c.orbitPath(steps: 360) {
603                let r = (p * p).sum().squareRoot()
604                // More specks near 1 AU, where Earth meets the stream.
605                let copies = abs(r - 1) < 0.15 ? 4 : 1
606                for _ in 0..<copies {
607                    let jitter = SIMD3(rng.next() - 0.5, rng.next() - 0.5, rng.next() - 0.5) * 0.08 * max(r, 0.3)
608                    let c = map.point(p + jitter)
609                    let base = UInt32(positions.count)
610                    positions += [c + SIMD3(size, 0, 0), c + SIMD3(-size / 2, size, 0), c + SIMD3(-size / 2, -size / 2, size)]
611                    indices += [base, base + 1, base + 2]
612                }
613            }
614        }
615        var d = MeshDescriptor(name: "debris")
616        d.positions = MeshBuffer(positions)
617        d.primitives = .triangles(indices)
618        if let mesh = try? MeshResource.generate(from: [d]) { e.debris.model?.mesh = mesh }
619    }
620
621    // MARK: Meshes
622
623    /// A flat ribbon through `points`, lying in the plane of the orbit.
624    private static func ribbon(_ points: [SIMD3<Float>], width: Float, closed: Bool) -> MeshResource {
625        var positions: [SIMD3<Float>] = []
626        var indices: [UInt32] = []
627        let n = points.count
628        for i in 0..<n {
629            let next = closed ? points[(i + 1) % n] : points[min(i + 1, n - 1)]
630            let prev = closed ? points[(i + n - 1) % n] : points[max(i - 1, 0)]
631            var t = next - prev
632            if simd_length(t) < 1e-12 { t = SIMD3(1, 0, 0) }
633            var side = simd_cross(simd_normalize(t), SIMD3(0, 1, 0))
634            if simd_length(side) < 1e-6 { side = SIMD3(1, 0, 0) }
635            side = simd_normalize(side) * width / 2
636            positions += [points[i] - side, points[i] + side]
637            if closed || i < n - 1 {
638                let a = UInt32(2 * i), b = UInt32(2 * ((i + 1) % n))
639                indices += [a, a + 1, b, b, a + 1, b + 1]
640            }
641        }
642        var d = MeshDescriptor(name: "orbit")
643        d.positions = MeshBuffer(positions)
644        d.primitives = .triangles(indices)
645        return (try? MeshResource.generate(from: [d])) ?? .generateBox(size: 0.0001)
646    }
647
648    /// A flat ring in the local x-z plane, radii in units of the parent's radius.
649    private static func annulus(inner: Float, outer: Float, color: UIColor) -> ModelEntity {
650        let n = 96
651        var positions: [SIMD3<Float>] = []
652        var indices: [UInt32] = []
653        for i in 0..<n {
654            let a = Float(i) / Float(n) * 2 * .pi
655            positions += [SIMD3(cos(a) * inner, 0, sin(a) * inner), SIMD3(cos(a) * outer, 0, sin(a) * outer)]
656            let p = UInt32(2 * i), q = UInt32(2 * ((i + 1) % n))
657            indices += [p, p + 1, q, q, p + 1, q + 1]
658        }
659        var d = MeshDescriptor(name: "ring")
660        d.positions = MeshBuffer(positions)
661        d.primitives = .triangles(indices)
662        var m = UnlitMaterial(color: color)
663        m.blending = .transparent(opacity: .init(floatLiteral: Float(color.cgColor.alpha)))
664        m.faceCulling = .none
665        return ModelEntity(mesh: (try? MeshResource.generate(from: [d])) ?? .generateBox(size: 0.001), materials: [m])
666    }
667
668    /// The half of a unit sphere below y = 0, drawn dark and mostly opaque over a body's night side.
669    private static func nightShell() -> ModelEntity {
670        let rings = 24, segments = 64
671        var positions: [SIMD3<Float>] = []
672        var indices: [UInt32] = []
673        for i in 0...rings {
674            let lat = -Float.pi / 2 * Float(i) / Float(rings)
675            for j in 0...segments {
676                let lon = Float(j) / Float(segments) * 2 * .pi
677                positions.append(SIMD3(cos(lat) * cos(lon), sin(lat), cos(lat) * sin(lon)))
678            }
679        }
680        for i in 0..<rings {
681            for j in 0..<segments {
682                let a = UInt32(i * (segments + 1) + j), b = a + UInt32(segments + 1)
683                indices += [a, b, a + 1, a + 1, b, b + 1]
684            }
685        }
686        var d = MeshDescriptor(name: "night")
687        d.positions = MeshBuffer(positions)
688        d.primitives = .triangles(indices)
689        var m = UnlitMaterial(color: .black)
690        m.blending = .transparent(opacity: .init(floatLiteral: 0.88))
691        m.faceCulling = .none
692        return ModelEntity(mesh: (try? MeshResource.generate(from: [d])) ?? .generateBox(size: 0.001), materials: [m])
693    }
694
695    // MARK: Labels, taps and the card
696
697    private func screenPoints(size: CGSize) -> [(marker: SolarMarker, point: CGPoint, radius: CGFloat)] {
698        markers().filter(\.visible).compactMap { m in
699            cam.project(m.scene, in: size).map { (m, $0, pixelRadius(m.radius, at: m.scene, size: size)) }
700        }
701    }
702
703    private func pixelRadius(_ r: Float, at p: SIMD3<Float>, size: CGSize) -> CGFloat {
704        let k = Float(size.height / 2) / tan(SolarCamera.fovDegrees * .pi / 360)
705        return CGFloat(r / max(cam.distance(to: p), 1e-9) * k)
706    }
707
708    /// Points to label, most important first, skipping a label that would sit on one already placed.
709    private func labelled(size: CGSize) -> [(marker: SolarMarker, point: CGPoint, radius: CGFloat, showName: Bool)] {
710        let planetOrder = ["jupiter", "saturn", "uranus", "neptune", "earth", "venus", "mars", "mercury"]
711        func rank(_ m: SolarMarker) -> Int {
712            switch m.kind {
713            case .sun: 0
714            case .planet: 1 + (planetOrder.firstIndex(of: m.id) ?? 9)
715            case .craft: 20
716            case .dwarf: 30
717            case .comet: 40
718            case .moon: 50
719            }
720        }
721        var placed: [CGPoint] = []
722        let points = screenPoints(size: size)
723        // Anything whose centre falls on the disc of a nearer body is hidden behind it.
724        let discs = points.filter { $0.radius > 4 }.map { ($0.point, $0.radius, cam.distance(to: $0.marker.scene)) }
725        return points
726            .filter { item in
727                let d = cam.distance(to: item.marker.scene)
728                return !discs.contains { $0.2 < d && hypot($0.0.x - item.point.x, $0.0.y - item.point.y) < $0.1 }
729            }
730            .sorted { rank($0.marker) < rank($1.marker) }
731            .map { item in
732                let at = CGPoint(x: item.point.x, y: item.point.y - max(item.radius, 5) - 9)
733                let clear = item.marker.id == selected || placed.allSatisfy { abs($0.x - at.x) > 48 || abs($0.y - at.y) > 14 }
734                if clear { placed.append(at) }
735                return (item.marker, item.point, item.radius, clear)
736            }
737    }
738
739    private func labels(size: CGSize) -> some View {
740        ZStack {
741            ForEach(labelled(size: size), id: \.marker.id) { item in
742                let m = item.marker
743                let isSelected = m.id == selected
744                let color: Color = isSelected ? accent : m.kind == .craft ? accent.opacity(0.9) : m.kind == .comet ? Color(red: 0.7, green: 0.85, blue: 1) : ink.opacity(m.kind == .moon ? 0.7 : 0.85)
745                ZStack {
746                    if item.radius < 3, m.kind != .craft, m.kind != .comet {
747                        Circle().stroke(isSelected ? accent : ink.opacity(0.6), lineWidth: 1.2).frame(width: 10, height: 10)
748                    }
749                    if item.showName {
750                        Text(m.name).font(.caption2.weight(isSelected ? .semibold : .regular))
751                            .foregroundStyle(color)
752                            .shadow(color: .black, radius: 2)
753                            .fixedSize()
754                            .offset(y: -max(item.radius, 5) - 9)
755                    }
756                }
757                .position(item.point)
758            }
759        }
760    }
761
762    private func tap(_ location: CGPoint, size: CGSize) {
763        let hit = screenPoints(size: size)
764            .map { ($0.marker.id, hypot($0.point.x - location.x, $0.point.y - location.y) - max($0.radius, 0)) }
765            .filter { $0.1 < 28 }
766            .min { $0.1 < $1.1 }
767        guard let id = hit?.0 else { selected = nil; return }
768        selected = id
769        fly(to: id)
770    }
771
772    /// The selected body's Library page, title, one-line description and position note.
773    private func details(_ id: String) -> (page: LibraryPage?, title: String, subtitle: String, note: String?) {
774        func fromSun(_ v: SIMD3<Double>) -> String {
775            let au = (v * v).sum().squareRoot()
776            return String(format: "%.2f AU from the Sun · sunlight takes %@", au, lightTime(au))
777        }
778        if id.hasPrefix("craft:") {
779            let name = String(id.dropFirst(6))
780            let page = Library.page(spacecraft: name)
781            let pos = Spacecraft.all.first { $0.name == name }?.position3(at: date)
782            return (page, name, page?.subtitle ?? "Spacecraft", pos.map(fromSun))
783        }
784        if id.hasPrefix("comet:"), let c = KeplerOrbit.comets.first(where: { "comet:\($0.id)" == id }) {
785            let years = c.periodDays / 365.25
786            let last = Date(timeIntervalSince1970: (c.perihelionJD - 2_440_587.5) * 86_400)
787            var sub = String(format: "Goes round the Sun every %.0f years.", years)
788            if years < 10 {
789                sub += " Next closest to the Sun \(c.nextPerihelion(after: .now).formatted(.dateTime.month(.wide).year()))."
790            } else {
791                sub += " Last closest to the Sun in \(last.formatted(.dateTime.year()))."
792            }
793            if let shower = MeteorShower.major.first(where: { $0.parent == c.id }) {
794                sub += " Its debris makes the \(shower.name)."
795            }
796            return (c.page.flatMap { Library.page(id: $0) }, c.name, sub, fromSun(c.position(at: date)))
797        }
798        let page = Library.page(id: id)
799        let title = page?.title ?? id
800        let subtitle = page?.subtitle ?? ""
801        if let m = SolarMoon.all.first(where: { $0.id == id }) {
802            let parentName = Library.page(id: m.parent)?.title ?? m.parent
803            let note = "\(Int(m.distanceKm).formatted()) km from \(parentName)" + (m.isExact ? "" : " · position illustrative")
804            return (page, title, subtitle, note)
805        }
806        if let p = SolarPlanet.all.first(where: { $0.id == id }) ?? (id == "pluto" ? SolarPlanet.pluto : nil) {
807            return (page, title, subtitle, fromSun(p.position(at: date)))
808        }
809        if let k = KeplerOrbit.dwarfPlanets.first(where: { $0.id == id }) {
810            return (page, title, subtitle, fromSun(k.position(at: date)))
811        }
812        return (page, title, subtitle, nil)
813    }
814
815    private func card(_ id: String) -> some View {
816        let d = details(id)
817        return VStack(alignment: .leading, spacing: 6) {
818            HStack {
819                Text(d.title).font(.headline)
820                Spacer()
821                Button { selected = nil; resetView() } label: {
822                    Image(systemName: "xmark").font(.footnote.weight(.semibold)).frame(width: 44, height: 44).contentShape(Rectangle())
823                }
824                .buttonStyle(.plain)
825                .padding(-12)
826                .accessibilityLabel("Close")
827            }
828            if !d.subtitle.isEmpty { Text(d.subtitle).font(.footnote).dimmed(0.75).fixedSize(horizontal: false, vertical: true) }
829            if let note = d.note { Text(note).font(.footnote.monospacedDigit()).dimmed(0.85) }
830            if let page = d.page {
831                Button("Read more") { onOpen(page) }.font(.subheadline.weight(.medium)).foregroundStyle(accent)
832            }
833        }
834        .padding(14)
835        .background(Color(white: 0.06), in: RoundedRectangle(cornerRadius: 14))
836        .contentShape(RoundedRectangle(cornerRadius: 14))
837        .overlay(RoundedRectangle(cornerRadius: 14).stroke(ink.opacity(0.15), lineWidth: 0.5))
838    }
839
840    private func lightTime(_ au: Double) -> String {
841        let s = au * 499.004784
842        let h = Int(s / 3600), m = Int(s.truncatingRemainder(dividingBy: 3600) / 60)
843        return h > 0 ? "\(h) h \(m) min" : "\(m) min"
844    }
845
846    // MARK: Camera
847
848    private var dragGesture: some Gesture {
849        DragGesture(minimumDistance: 4)
850            .onChanged { g in
851                flight?.cancel()
852                if dragStart == nil { dragStart = cam }
853                cam.yaw = dragStart!.yaw - Float(g.translation.width) * 0.008
854                cam.pitch = min(max(dragStart!.pitch + Float(g.translation.height) * 0.008, -1.45), 1.45)
855            }
856            .onEnded { _ in dragStart = nil }
857    }
858
859    private var pinchGesture: some Gesture {
860        MagnifyGesture()
861            .onChanged { g in
862                flight?.cancel()
863                if pinchStart == nil { pinchStart = cam.distance }
864                let limits: ClosedRange<Float> = scale == .compressed ? 0.02...80 : 1e-6...400
865                cam.distance = min(max(pinchStart! / Float(g.magnification), limits.lowerBound), limits.upperBound)
866            }
867            .onEnded { _ in pinchStart = nil }
868    }
869
870    private func resetView() {
871        animateCamera(to: SolarCamera(target: .zero, yaw: cam.yaw, pitch: 0.55, distance: fitDistance()))
872    }
873
874    /// Camera distance at which Neptune's orbit fits the narrower side of the view.
875    private func fitDistance() -> Float {
876        let neptune = Float(mapping.scale == .compressed ? 1.6 * pow(30.1, 0.4) : 30.1)
877        let tanV = tan(SolarCamera.fovDegrees * .pi / 360)
878        let tanH = tanV * Float(viewSize.width / max(viewSize.height, 1))
879        return neptune * 1.22 / min(tanV, tanH)
880    }
881
882    /// Centres on a body and zooms to a few times its drawn radius (or a fixed distance for dots).
883    private func fly(to id: String) {
884        guard let m = markers().first(where: { $0.id == id }) else { return }
885        let distance: Float
886        switch m.kind {
887        case .craft, .comet: distance = scale == .compressed ? 1.2 : 0.6
888        default: distance = m.radius * (m.id == "saturn" ? 2.3 : 1) * 7
889        }
890        animateCamera(to: SolarCamera(target: m.scene, yaw: cam.yaw, pitch: max(cam.pitch, 0.25), distance: distance))
891    }
892
893    /// Moves the camera over about a second, interpolating distance on a log scale.
894    private func animateCamera(to end: SolarCamera) {
895        flight?.cancel()
896        let start = cam
897        flight = Task {
898            let frames = 50
899            for f in 1...frames {
900                try? await Task.sleep(for: .milliseconds(18))
901                if Task.isCancelled { return }
902                let x = Float(f) / Float(frames)
903                let t = x < 0.5 ? 4 * x * x * x : 1 - pow(-2 * x + 2, 3) / 2
904                cam.target = start.target + (end.target - start.target) * t
905                cam.pitch = start.pitch + (end.pitch - start.pitch) * t
906                cam.distance = exp(Foundation.log(start.distance) + (Foundation.log(end.distance) - Foundation.log(start.distance)) * t)
907            }
908        }
909    }
910
911    // MARK: Weather
912
913    private func loadWeather() async {
914        while !Task.isCancelled {
915            async let kp = try? SpaceWeather.fetch()
916            async let sun = SunFeeds.load(force: false)
917            let (k, s) = await (kp, sun)
918            var w = SolarWeather(kp: k?.kpNow)
919            if let s {
920                let recent = s.snapshot.xray.filter { $0.time > .now.addingTimeInterval(-3 * 3600) }
921                if let peak = recent.max(by: { $0.flux < $1.flux }) { w.flare = (peak.flux, peak.time) }
922                w.summary = SunFeeds.summary(s.snapshot).map { s.complete ? $0 : "\($0) (\(SunFeeds.source(s.snapshot)))" }
923            }
924            #if DEBUG
925            if UserDefaults.standard.bool(forKey: "debugSolarEvents") { w.kp = 6.3; w.flare = (2.4e-5, .now) }
926            #endif
927            weather = w
928            try? await Task.sleep(for: .seconds(600))
929        }
930    }
931}
932
933/// A small deterministic generator, so debris looks the same each time it is rebuilt.
934private struct SeededRandom {
935    var state: UInt64
936    init(seed: UInt64) { state = seed }
937    mutating func next() -> Double {
938        state = state &* 6_364_136_223_846_793_005 &+ 1_442_695_040_888_963_407
939        return Double(state >> 11) / Double(1 << 53)
940    }
941}