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

Commit d8ec3faf26

d8ec3faf26ccb74927d3c7591fe4aaa70eb637f5

parent: 9578b9e3ab

Unsigned

cmc <hello@cleberg.net> · 2026-10-22 04:18 UTC

Sky: camera view (!127)

- `CameraPose` and `Projection(camera:)` (SkyRenderer): world (x north, y west, z up) → device axes from Core Motion's rotation matrix rows; pinhole along −z; refraction (Sæmundsson, 10 °C, 1010 hPa) added to altitudes. `SkyView(camera:)` skips the background and Milky Way and draws the horizon as a dashed line.
- `ARSkyScreen` (app): `AVCaptureVideoPreviewLayer` (back wide camera, aspect fill); focal length in points = (long side / 2) / tan(videoFieldOfView / 2) × fill scale. `ARAttitude`: `.xArbitraryCorrectedZVertical` at 60 Hz; heading offset from one `.xTrueNorthZVertical` sample, then the compass is stopped; Align on the brightest planet, Moon or star ≤ mag 2 within 15° of centre (azimuth only; altitude from gravity).
- Sky tab Explore → Camera view (devices with a camera and true-north attitude). `NSCameraUsageDescription` added.
- Test: pinhole facing north (centre, up, east, behind) and refraction (0.48° at the horizon, 1′ at 45°). Package tests pass; iOS builds. Not run on a device: draw time (Debug label) and pointing still to measure.

Layout: unified · split

App/Sources/ARSkyScreen.swift added +194
@@ -0,0 +1,194 @@
1import AVFoundation
2import CoreMotion
3import Library
4import SkyEngine
5import SkyRenderer
6import SwiftUI
7
8/// The sky drawn over the back camera's picture. Orientation comes from the gyroscope (Core Motion's arbitrary,
9/// gravity-corrected frame), not the compass: one compass reading sets the first heading, and Align turns the heading
10/// so a bright object near the centre sits at the centre. Positions include refraction.
11struct ARSkyScreen: View {
12 var scene: SkyScene
13 @State private var attitude = ARAttitude()
14 @State private var camera = CameraFeed()
15 @State private var drawTime: Duration?
16 @Environment(\.dismiss) private var dismiss
17
18 var body: some View {
19 GeometryReader { geo in
20 ZStack {
21 CameraPreview(session: camera.session).ignoresSafeArea()
22 if let pose = attitude.pose(focal: camera.focal(for: geo.size)) {
23 SkyView(scene: scene, centerAzimuth: attitude.center.azimuth, centerAltitude: attitude.center.altitude,
24 fieldOfView: camera.verticalField(for: geo.size), showMilkyWay: false, camera: pose) { d in
25 Task { @MainActor in drawTime = d }
26 }
27 .ignoresSafeArea()
28 .allowsHitTesting(false)
29 }
30 VStack {
31 HStack {
32 Text(attitude.status).font(.caption).padding(8).background(.black.opacity(0.5), in: RoundedRectangle(cornerRadius: 8))
33 Spacer()
34 Button("Done") { dismiss() }.buttonStyle(.borderedProminent)
35 }
36 Spacer()
37 if let target = attitude.alignmentTarget(in: scene) {
38 Button("Align on \(target.name)") { attitude.align(on: target) }
39 .buttonStyle(.borderedProminent)
40 }
41 #if DEBUG
42 if let drawTime { Text("draw \(drawTime.formatted(.units(allowed: [.milliseconds], width: .narrow)))").font(.caption2.monospacedDigit()) }
43 #endif
44 }
45 .padding()
46 Image(systemName: "plus").font(.title3.weight(.light)).foregroundStyle(.white.opacity(0.6)).allowsHitTesting(false)
47 }
48 }
49 .foregroundStyle(.white)
50 .onAppear { attitude.start(); camera.start() }
51 .onDisappear { attitude.stop(); camera.stop() }
52 }
53}
54
55/// Device attitude from the gyroscope, turned by a heading offset to true north.
56@MainActor
57@Observable
58final class ARAttitude {
59 /// The arbitrary frame's azimuth minus the true azimuth, degrees.
60 private(set) var offset: Double?
61 private(set) var aligned: String?
62 private var rows: (SIMD3<Double>, SIMD3<Double>, SIMD3<Double>)?
63 private let gyro = CMMotionManager(), compass = CMMotionManager()
64
65 func start() {
66 gyro.deviceMotionUpdateInterval = 1.0 / 60
67 gyro.startDeviceMotionUpdates(using: .xArbitraryCorrectedZVertical, to: .main) { [weak self] motion, _ in
68 guard let self, let m = motion?.attitude.rotationMatrix else { return }
69 MainActor.assumeIsolated {
70 self.rows = (SIMD3(m.m11, m.m12, m.m13), SIMD3(m.m21, m.m22, m.m23), SIMD3(m.m31, m.m32, m.m33))
71 }
72 }
73 // One heading from the compass to start from; the gyroscope carries on alone after that.
74 guard CMMotionManager.availableAttitudeReferenceFrames().contains(.xTrueNorthZVertical) else { offset = 0; return }
75 compass.startDeviceMotionUpdates(using: .xTrueNorthZVertical, to: .main) { [weak self] motion, _ in
76 guard let self, let m = motion?.attitude.rotationMatrix, let arb = self.rows else { return }
77 MainActor.assumeIsolated {
78 let trueAz = Pointing.direction(m31: m.m31, m32: m.m32, m33: m.m33).azimuth
79 let arbAz = Pointing.direction(m31: arb.2.x, m32: arb.2.y, m33: arb.2.z).azimuth
80 self.offset = remainder(arbAz - trueAz, 360)
81 self.compass.stopDeviceMotionUpdates()
82 }
83 }
84 }
85
86 func stop() {
87 gyro.stopDeviceMotionUpdates()
88 compass.stopDeviceMotionUpdates()
89 }
90
91 /// The device axes in a true-north frame: each row turned by the offset about the vertical.
92 func pose(focal: Double) -> CameraPose? {
93 guard let rows, let offset else { return nil }
94 let t = offset * .pi / 180, c = cos(t), s = sin(t)
95 func turn(_ r: SIMD3<Double>) -> SIMD3<Double> { SIMD3(r.x * c - r.y * s, r.x * s + r.y * c, r.z) }
96 return CameraPose(rows: (turn(rows.0), turn(rows.1), turn(rows.2)), focal: focal)
97 }
98
99 /// Where the camera points, true azimuth.
100 var center: Horizontal {
101 guard let rows else { return Horizontal(altitude: 0, azimuth: 0) }
102 let h = Pointing.direction(m31: rows.2.x, m32: rows.2.y, m33: rows.2.z)
103 let az = (h.azimuth - (offset ?? 0)).truncatingRemainder(dividingBy: 360)
104 return Horizontal(altitude: h.altitude, azimuth: az < 0 ? az + 360 : az)
105 }
106
107 var status: String {
108 guard offset != nil else { return "Finding a first heading" }
109 return aligned.map { "Aligned on \($0)" } ?? "Heading from the compass; align on a bright object"
110 }
111
112 /// The brightest planet, the Moon or a star of magnitude 2 or brighter within 15° of the centre.
113 func alignmentTarget(in scene: SkyScene) -> (name: String, position: Horizontal)? {
114 let c = center
115 func near(_ h: Horizontal) -> Bool { h.altitude > 0 && angle(h, c) < 15 }
116 let bodies = scene.bodies.filter { near($0.position) && $0.magnitude < 2 }.map { ($0.body.rawValue.capitalized, $0.position, $0.magnitude) }
117 let stars = scene.stars.filter { $0.star.magnitude <= 2 && near($0.position) }
118 .map { (starName($0.star.hr), $0.position, $0.star.magnitude) }
119 return (bodies + stars).min { $0.2 < $1.2 }.map { ($0.0, $0.1) }
120 }
121
122 /// Turns the heading so `target` is at the centre; altitude comes from gravity and is left alone.
123 func align(on target: (name: String, position: Horizontal)) {
124 guard let offset else { return }
125 self.offset = remainder(offset + center.azimuth - target.position.azimuth, 360)
126 aligned = target.name
127 }
128
129 private func angle(_ a: Horizontal, _ b: Horizontal) -> Double {
130 let r = Double.pi / 180
131 let c = sin(a.altitude * r) * sin(b.altitude * r) + cos(a.altitude * r) * cos(b.altitude * r) * cos((a.azimuth - b.azimuth) * r)
132 return acos(min(1, max(-1, c))) / r
133 }
134
135 private func starName(_ hr: Int) -> String {
136 Library.page(hr: hr)?.title ?? "HR \(hr)"
137 }
138}
139
140/// The back wide camera, previewed with aspect fill.
141@MainActor
142@Observable
143final class CameraFeed {
144 let session = AVCaptureSession()
145 /// Horizontal field of the active format (its long side) in degrees, and its size in pixels.
146 private(set) var field = 65.0
147 private(set) var dimensions = CGSize(width: 4, height: 3)
148
149 func start() {
150 guard let device = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back),
151 let input = try? AVCaptureDeviceInput(device: device), session.canAddInput(input) else { return }
152 session.addInput(input)
153 field = Double(device.activeFormat.videoFieldOfView)
154 let d = CMVideoFormatDescriptionGetDimensions(device.activeFormat.formatDescription)
155 dimensions = CGSize(width: Int(d.width), height: Int(d.height))
156 // AVCaptureSession is not Sendable; it is only started and stopped off the main thread, never shared otherwise.
157 nonisolated(unsafe) let session = session
158 Task.detached { session.startRunning() }
159 }
160
161 func stop() {
162 nonisolated(unsafe) let session = session
163 Task.detached { session.stopRunning() }
164 }
165
166 /// Focal length in screen points for a portrait view filled by the landscape sensor image.
167 func focal(for view: CGSize) -> Double {
168 let w = Double(max(dimensions.width, dimensions.height)), h = Double(min(dimensions.width, dimensions.height))
169 let scale = max(Double(view.width) / h, Double(view.height) / w)
170 return w / 2 / tan(field / 2 * .pi / 180) * scale
171 }
172
173 func verticalField(for view: CGSize) -> Double {
174 2 * atan(Double(view.height) / 2 / focal(for: view)) * 180 / .pi
175 }
176}
177
178struct CameraPreview: UIViewRepresentable {
179 var session: AVCaptureSession
180
181 func makeUIView(context: Context) -> PreviewView {
182 let v = PreviewView()
183 v.layer.session = session
184 v.layer.videoGravity = .resizeAspectFill
185 return v
186 }
187
188 func updateUIView(_ view: PreviewView, context: Context) {}
189
190 final class PreviewView: UIView {
191 override static var layerClass: AnyClass { AVCaptureVideoPreviewLayer.self }
192 override var layer: AVCaptureVideoPreviewLayer { super.layer as! AVCaptureVideoPreviewLayer }
193 }
194}
App/Sources/SkyScreen.swift +8
@@ -1,3 +1,4 @@
1import AVFoundation
12import Library
23import ObservingLog
34import SkyEngine
@@ -17,6 +18,7 @@ struct SkyScreen: View {
1718 @AppStorage(SettingsKey.horizonProfile) private var horizonProfile = ""
1819 @State private var faint: (key: FaintKey, stars: [PlacedStar])?
1920 @State private var eyepiece: EyepieceField?
21 @State private var showCamera = false
2022 @State private var showSettings = false
2123 @State private var showEvents = false
2224 @State private var showLog = false
@@ -109,6 +111,9 @@ struct SkyScreen: View {
109111 .sheet(isPresented: $showYear) {
110112 YearSheet(year: $model.historicalYear, south: model.observer.latitude < 0).preferredColorScheme(.dark)
111113 }
114 .fullScreenCover(isPresented: $showCamera) {
115 if let scene = model.scene { ARSkyScreen(scene: scene) }
116 }
112117 .sheet(isPresented: $showSettings, onDismiss: rescheduleNotifications) {
113118 SettingsScreen { model.applyLocationSettings() }
114119 .preferredColorScheme(.dark)
@@ -308,6 +313,9 @@ struct SkyScreen: View {
308313 }
309314 }
310315 Section("Explore") {
316 if pointer.available, AVCaptureDevice.default(for: .video) != nil {
317 Button { showCamera = true } label: { Label("Camera view", systemImage: "camera.viewfinder") }
318 }
311319 Menu {
312320 ForEach(EyepieceField.all(in: equipmentInventory.all())) { f in
313321 Button {
App/project.yml +1
@@ -76,6 +76,7 @@ targets:
7676 INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone: UIInterfaceOrientationPortrait
7777 INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad: UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight
7878 INFOPLIST_KEY_NSLocationWhenInUseUsageDescription: Moonrise uses your location to draw the sky above you.
79 INFOPLIST_KEY_NSCameraUsageDescription: Moonrise draws the sky over the camera's picture in Camera view. Nothing is recorded or sent.
7980 MoonriseWidgets:
8081 type: app-extension
8182 platform: iOS
PLAN.org +6 −1
@@ -555,7 +555,12 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled.
555555** v5.3: AR camera overlay
556556- First measure draw time and pointing on a device. Heading from the
557557 gyroscope with a one-object alignment, not the compass; a pinhole
558 projection matching the camera; refraction.
558 projection matching the camera; refraction. Done in code: Explore → Camera view;
559 =xArbitraryCorrectedZVertical= attitude, first heading from one compass
560 reading, Align on the brightest object within 15° of the centre; pinhole
561 projection from the camera format's field and the aspect-fill crop;
562 Sæmundsson refraction. Not yet measured on a device (draw time is shown in
563 Debug builds).
559564
560565** v5.4: System
561566- Juno, Europa Clipper, JUICE, Psyche, Parker Solar Probe, Lucy on the
Packages/MoonriseKit/Sources/SkyRenderer/SkyView.swift +56 −6
@@ -1,23 +1,64 @@
11import SkyEngine
22import SwiftUI
33
4/// Stereographic projection of the sky centred on a viewing direction.
4/// A phone camera's orientation and lens, for drawing the sky over its picture.
5public struct CameraPose: Sendable, Equatable {
6 /// Rows are the device's x (right), y (up) and z (out of the screen) axes in a frame with x north, y west, z up.
7 public var rows: (SIMD3<Double>, SIMD3<Double>, SIMD3<Double>)
8 /// Focal length in points on screen.
9 public var focal: Double
10
11 public init(rows: (SIMD3<Double>, SIMD3<Double>, SIMD3<Double>), focal: Double) {
12 self.rows = rows
13 self.focal = focal
14 }
15
16 public static func == (a: CameraPose, b: CameraPose) -> Bool {
17 a.rows.0 == b.rows.0 && a.rows.1 == b.rows.1 && a.rows.2 == b.rows.2 && a.focal == b.focal
18 }
19
20 /// Atmospheric refraction in degrees for an airless altitude (Bennett 1982, Sæmundsson's inverse form), 10 °C and 1010 hPa.
21 public static func refraction(_ altitude: Double) -> Double {
22 guard altitude > -2 else { return 0 }
23 return 1.02 / tan((altitude + 10.3 / (altitude + 5.11)) * .pi / 180) / 60
24 }
25}
26
27/// Stereographic projection of the sky centred on a viewing direction, or a pinhole projection through a camera.
528public struct Projection: Sendable {
629 public var centerAzimuth: Double
730 public var centerAltitude: Double
831 /// Horizontal field of view in degrees.
932 public var fieldOfView: Double
1033 public var size: CGSize
34 /// When set, points are placed as the camera sees them, with refraction.
35 public var camera: CameraPose?
1136
12 public init(centerAzimuth: Double, centerAltitude: Double, fieldOfView: Double, size: CGSize) {
37 public init(centerAzimuth: Double, centerAltitude: Double, fieldOfView: Double, size: CGSize, camera: CameraPose? = nil) {
1338 self.centerAzimuth = centerAzimuth
1439 self.centerAltitude = centerAltitude
1540 self.fieldOfView = fieldOfView
1641 self.size = size
42 self.camera = camera
1743 }
1844
1945 /// Screen point, or nil when the direction is behind the viewer.
2046 public func point(_ h: Horizontal) -> CGPoint? {
47 if let camera { return pinhole(h, camera) }
48 return stereographic(h)
49 }
50
51 /// The camera looks along the device's −z axis; x is right and y up on screen.
52 func pinhole(_ h: Horizontal, _ c: CameraPose) -> CGPoint? {
53 let r = Double.pi / 180
54 let alt = (h.altitude + CameraPose.refraction(h.altitude)) * r, az = h.azimuth * r
55 let w = SIMD3(cos(alt) * cos(az), -cos(alt) * sin(az), sin(alt))
56 let x = (c.rows.0 * w).sum(), y = (c.rows.1 * w).sum(), z = (c.rows.2 * w).sum()
57 guard z < -0.05 else { return nil }
58 return CGPoint(x: Double(size.width) / 2 + c.focal * x / -z, y: Double(size.height) / 2 - c.focal * y / -z)
59 }
60
61 func stereographic(_ h: Horizontal) -> CGPoint? {
2162 let r = Double.pi / 180
2263 let alt = h.altitude * r, alt0 = centerAltitude * r
2364 let dAz = (h.azimuth - centerAzimuth) * r
@@ -121,10 +162,12 @@ public struct SkyView: View {
121162 public var faintStars: [PlacedStar]
122163 /// An eyepiece's true field, degrees across, drawn as a circle at the centre.
123164 public var eyepieceField: Double?
165 /// Draw over a camera picture: no background or Milky Way, and the ground only as a line.
166 public var camera: CameraPose?
124167 /// Called after each draw with the time the draw took.
125168 public var onDraw: (@Sendable (Duration) -> Void)?
126169
127 public init(scene: SkyScene, centerAzimuth: Double = 180, centerAltitude: Double = 55, fieldOfView: Double = 110, style: SkyStyle = SkyStyle(), culture: SkyCulture? = nil, highlight: SkyHighlight? = nil, showDeepSky: Bool = true, showMilkyWay: Bool = true, horizon: HorizonProfile? = nil, faintStars: [PlacedStar] = [], eyepieceField: Double? = nil, onDraw: (@Sendable (Duration) -> Void)? = nil) {
170 public init(scene: SkyScene, centerAzimuth: Double = 180, centerAltitude: Double = 55, fieldOfView: Double = 110, style: SkyStyle = SkyStyle(), culture: SkyCulture? = nil, highlight: SkyHighlight? = nil, showDeepSky: Bool = true, showMilkyWay: Bool = true, horizon: HorizonProfile? = nil, faintStars: [PlacedStar] = [], eyepieceField: Double? = nil, camera: CameraPose? = nil, onDraw: (@Sendable (Duration) -> Void)? = nil) {
128171 self.scene = scene
129172 self.style = style
130173 self.culture = culture
@@ -134,6 +177,7 @@ public struct SkyView: View {
134177 self.horizon = horizon
135178 self.faintStars = faintStars
136179 self.eyepieceField = eyepieceField
180 self.camera = camera
137181 self.centerAzimuth = centerAzimuth
138182 self.centerAltitude = centerAltitude
139183 self.fieldOfView = fieldOfView
@@ -143,9 +187,9 @@ public struct SkyView: View {
143187 public var body: some View {
144188 Canvas { context, size in
145189 let start = ContinuousClock.now
146 let p = Projection(centerAzimuth: centerAzimuth, centerAltitude: centerAltitude, fieldOfView: fieldOfView, size: size)
147 context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(style.background))
148 if showMilkyWay { drawMilkyWay(&context, p) }
190 let p = Projection(centerAzimuth: centerAzimuth, centerAltitude: centerAltitude, fieldOfView: fieldOfView, size: size, camera: camera)
191 if camera == nil { context.fill(Path(CGRect(origin: .zero, size: size)), with: .color(style.background)) }
192 if showMilkyWay && camera == nil { drawMilkyWay(&context, p) }
149193 drawConstellations(&context, p)
150194 drawStars(&context, p)
151195 if showDeepSky { drawDeepSky(&context, p) }
@@ -398,6 +442,12 @@ public struct SkyView: View {
398442 az += 1
399443 }
400444 guard let first = edge.first, let last = edge.last else { return }
445 if camera != nil {
446 var line = Path()
447 line.addLines(edge)
448 context.stroke(line, with: .color(style.muted), style: StrokeStyle(lineWidth: 1, dash: [6, 4]))
449 return
450 }
401451 var ground = Path()
402452 ground.move(to: first)
403453 for pt in edge.dropFirst() { ground.addLine(to: pt) }
Packages/MoonriseKit/Tests/SkyRendererTests/SkyChartTests.swift +16
@@ -29,3 +29,19 @@ import SkyEngine
2929 #expect(near.count > 100 && near.count < 600)
3030 #expect(near.allSatisfy { $0.star.hr == 0 })
3131}
32
33@Test func pinholeProjectionFacingNorth() {
34 // Upright in portrait, facing north: x (right) is east, y (up) is up, z (towards the user) is south.
35 let pose = CameraPose(rows: (SIMD3(0, -1, 0), SIMD3(0, 0, 1), SIMD3(-1, 0, 0)), focal: 500)
36 let p = Projection(centerAzimuth: 0, centerAltitude: 0, fieldOfView: 60, size: CGSize(width: 400, height: 800), camera: pose)
37 let north = p.point(Horizontal(altitude: 0, azimuth: 0))!
38 #expect(abs(north.x - 200) < 1e-9)
39 #expect(abs(north.y - (400 - 500 * tan(CameraPose.refraction(0) * .pi / 180))) < 1e-6)
40 let up = p.point(Horizontal(altitude: 10, azimuth: 0))!
41 #expect(up.y < north.y && abs(up.x - 200) < 1e-9)
42 let east = p.point(Horizontal(altitude: 0, azimuth: 10))!
43 #expect(east.x > 200)
44 #expect(p.point(Horizontal(altitude: 0, azimuth: 180)) == nil)
45 #expect(abs(CameraPose.refraction(0) - 0.48) < 0.03)
46 #expect(abs(CameraPose.refraction(45) * 60 - 1.0) < 0.1)
47}