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 4c72d5eff7

4c72d5eff7784439a6b28123b2bbb83d45b635da

parent: 323a647574

Unsigned

cmc <hello@cleberg.net> · 2026-10-21 09:01 UTC

System 3D: shared meshes and materials, placeholder while RealityKit starts, scene detached on leaving 3D (!79)

Switching System from Map to 3D blocked the main thread for 1.5–2.0 s on the first switch and ~240 ms on later ones, with the 2D content frozen on screen until the 3D view appeared. `SolarSystem3DView.build` generated a night-shell mesh per body (~40), a sphere mesh per entity, and a translucent material per glow shell, night shell, tail cone, orbit and path. Leaving 3D kept the whole scene alive. App report (perf/app.md) finding 1.

## Changes

- One `generateSphere(radius: 1)` mesh for the Sun, its glow shells (now scaled 1.07–1.7 instead of generated at that radius), bodies, spacecraft, comet nuclei and the flare.
- `nightShell()` returns the mesh; it is built once with one material and shared by all bodies.
- Comet tail cones and their three materials are made once and shared by all comets. Spacecraft and nucleus materials are shared.
- Orbit materials are shared by colour and opacity (three in total); spacecraft paths share one material. Created only when the orbit/path entity is first created, as before.
- `SolarSystem3DView` shows `Color.black.overlay(ProgressView().tint(ink))` (as on the Sun tab) until a task sets `ready`, then creates the `RealityView`. The task sleeps 1 ms first so the placeholder is committed before RealityKit blocks the main thread.
- `SolarSceneEntities` detaches `root` in an `isolated deinit`. After leaving 3D, RealityView keeps its last `ARView` (referenced from `_RealityViewCameraModel`), and that view kept our scene: 151 `ModelEntity`, 23 `TextureAsset` still alive in a memory graph taken after switching back to Map. With the detach: 0 `ModelEntity`, 9 `TextureAsset`.

Rendering is unchanged: same meshes, materials, scales and draw order.

## Measurements

iPhone 18 Pro simulator (iOS 27), Release build, M2 Pro. A temporary probe (not committed) logged `CADisplayLink` frame intervals over 1.5× target, `phys_footprint` every 250 ms, the `RealityView` make closure duration around `build`, and when the placeholder appeared. A UI test opens System (Map), then switches to 3D and back to Map three times, 4–6 s apart, and on the first 3D visit flies to Saturn, the Sun and Jupiter for screenshots. 3 runs per side, interleaved; one run per side also recorded the screen with `simctl io recordVideo`. Load (`uptime`, 12 cores): main 3.94 → 3.69, 3.90 → 3.86, 3.25 → 3.37; branch 3.69 → 5.70, 3.88 → 3.25, 3.37 → 3.41.

| | main | branch |
|---|---:|---:|
| First switch in the process: longest main-thread frame | 1,504–2,044 ms | 1,361–1,396 ms |
| First switch: `RealityView` make closure (`build`) | 399–452 ms | 303–319 ms |
| Later switches: longest frame | 215–252 ms | 132–182 ms |
| Later switches: make closure (`build`) | 111–115 ms | 32–38 ms |
| Touch to first changed content (screen recording) | ~1.5 s (2D view frozen, only the segmented control animates) | next frame (17 ms), progress indicator animating during RealityKit start-up |
| Footprint before first 3D → after leaving 3D the third time | 44.5 → 101.0, 49.3 → 102.2, 48.9 → 101.4 MB | 45.0 → 87.5, 49.1 → 89.8, 48.2 → 90.3 MB |
| Footprint 3 s into the first 3D visit | 76–86 MB | 65–68 MB |

**Time Profiler**, one run per side (attached after launch; main thread, Running samples, within each 3D step):

| | main | branch |
|---|---:|---:|
| `build` incl., first switch | 384 ms | 308 ms |
| of which one RealityFoundation call at the start of `build` (first use in the process) | 278 ms | 270 ms |
| of which `nightShell()` | 31 ms | 1 ms |
| `build` incl., later switches | 107, 101 ms | 28, 30 ms |
| RealityKit outside `build`, first switch | 1,081 ms | 1,178 ms |

**RealityKit's remaining share** (simulator; needs a device to judge): on the first switch, about 1.0 s of `ARView`/renderer start-up before the make closure runs, plus the ~270 ms first-use call inside `build`, out of a ~1.37 s hang; app code in `build` is ~40 ms. On later switches the hang is 132–182 ms, of which `build` is 32–38 ms. The placeholder stays on screen and animates during the hang, but touches are not handled until it ends.

**Memory after leaving 3D.** Our scene is freed (above), but the footprint stays ~40 MB above the pre-3D level. Memory graphs before 3D and after leaving it show the live heap at 28 → 57 MB; the growth is RealityKit allocations (material definitions, shader function constants, Metal library data, per-frame allocator) and the retained `ARView`. It does not grow with repeated switches. App code has no handle on these.

**Appearance.** Screenshots of the overview and of Saturn, the Sun and Jupiter after the fly-to compared with SSIM (status bar cropped): main vs branch falls in the same range as run-to-run on one side (overview 0.99963–0.999999, Sun 0.99979–0.99998, Saturn and Jupiter 0.990–0.998, where moons and the camera flight differ between runs). Glow, night side, Saturn's rings and tails look the same side by side.

## Tests

- `swift test` (Packages/MoonriseKit): 195 tests passed.
- `npm test` (server): 55 passed.
- `xcodebuild test` (Moonrise, iPhone 18 Pro simulator): passed. Accessibility audit 64 issues on both main and branch: Sky 4, Settings 2, System 7, Sun 3, News & launches 21, Library 14, Library page: Saturn 13. The audit visits System in Map mode, so the 3D view and its placeholder are not audited.
- MoonriseVision does not compile `SolarSystem3D.swift`; `xcodebuild build -scheme MoonriseVision -destination 'generic/platform=visionOS Simulator'` succeeded. No visionOS simulator runtime is installed, so it was not run.

## Not verified

- A device. The RealityKit start-up and first-use costs are simulator numbers.
- Whether `ARView` is also kept outside UI tests: the memory graphs were taken under XCUITest, where the accessibility element cache also references it.
- Switching tabs away from System and back keeps the 3D scene, as before; only leaving 3D releases it.

Layout: unified · split

App/Sources/SolarSystem3D.swift +68 −34
@@ -186,6 +186,10 @@ final class SolarSceneEntities {
186186 var debrisBuilt: (SolarScale, Float, String)?
187187 let flare = ModelEntity()
188188 let aurora = Entity()
189
190 /// RealityView's ARView can outlive the 3D view; detach the scene so its meshes, materials and
191 /// textures are freed when 3D is left.
192 isolated deinit { root.removeFromParent() }
189193}
190194
191195struct SolarSystem3DView: View {
@@ -205,6 +209,7 @@ struct SolarSystem3DView: View {
205209 @State private var flight: Task<Void, Never>?
206210 @State private var pulse = false
207211 @State private var viewSize = CGSize(width: 400, height: 600)
212 @State private var ready = false
208213 @AppStorage("solar.moons") private var showMoons = true
209214 @AppStorage("solar.dwarfs") private var showDwarfs = true
210215 @AppStorage("solar.craft") private var showCraft = true
@@ -224,16 +229,20 @@ struct SolarSystem3DView: View {
224229 var body: some View {
225230 GeometryReader { geo in
226231 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) }
232 if ready {
233 RealityView { content in
234 content.camera = .virtual
235 build(content)
236 } update: { _ in
237 place()
238 }
239 .gesture(dragGesture.simultaneously(with: pinchGesture))
240 .onTapGesture(coordinateSpace: .local) { tap($0, size: geo.size) }
235241
236 labels(size: geo.size).allowsHitTesting(false)
242 labels(size: geo.size).allowsHitTesting(false)
243 } else {
244 Color.black.overlay(ProgressView().tint(ink))
245 }
237246
238247 VStack(spacing: 8) {
239248 if let s = selected { card(s) }
@@ -256,6 +265,11 @@ struct SolarSystem3DView: View {
256265 .accessibilityElement(children: .contain)
257266 .accessibilityLabel("3D solar system. Drag to turn, pinch to zoom, tap a body to learn about it.")
258267 .onChange(of: scale) { resetView() }
268 .task {
269 // RealityKit's start-up blocks the main thread; let the placeholder reach the screen first.
270 try? await Task.sleep(for: .milliseconds(1))
271 ready = true
272 }
259273 .task { await loadWeather() }
260274 .task {
261275 while !Task.isCancelled {
@@ -369,8 +383,10 @@ struct SolarSystem3DView: View {
369383 e.camera.camera.fieldOfViewInDegrees = SolarCamera.fovDegrees
370384 e.root.addChild(e.camera)
371385
386 // One unit sphere for every round body; entities are scaled to size.
387 let sphere = MeshResource.generateSphere(radius: 1)
372388 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])
389 e.sun.model = ModelComponent(mesh: sphere, materials: [sunMaterial])
374390 e.root.addChild(e.sun)
375391 // Glow: nested translucent shells, fainter outward.
376392 for i in 1...10 {
@@ -378,7 +394,9 @@ struct SolarSystem3DView: View {
378394 let a = CGFloat(0.09 * pow(0.78, Double(i - 1)))
379395 var g = UnlitMaterial(color: UIColor(red: 1, green: 0.72, blue: 0.32, alpha: a))
380396 g.blending = .transparent(opacity: .init(floatLiteral: Float(a)))
381 e.sun.addChild(ModelEntity(mesh: .generateSphere(radius: r), materials: [g]))
397 let shell = ModelEntity(mesh: sphere, materials: [g])
398 shell.scale = .init(repeating: r)
399 e.sun.addChild(shell)
382400 }
383401
384402 // Planets, dwarf planets and moons: textured where there is a map, with a night side.
@@ -386,36 +404,45 @@ struct SolarSystem3DView: View {
386404 if let pluto = SolarPlanet.pluto { spheres.append(("pluto", pluto.color, pluto.tiltDeg)) }
387405 spheres += KeplerOrbit.dwarfPlanets.map { ($0.id, Library.page(id: $0.id)?.drawing?.color ?? "#999999", 0) }
388406 spheres += SolarMoon.all.map { ($0.id, $0.color, 0) }
407 let nightMesh = Self.nightShell()
408 var nightMaterial = UnlitMaterial(color: .black)
409 nightMaterial.blending = .transparent(opacity: .init(floatLiteral: 0.88))
410 nightMaterial.faceCulling = .none
389411 for s in spheres {
390412 let body = ModelEntity()
391413 // Plain colour first; the map, if there is one, is swapped in once it has loaded.
392414 let m = UnlitMaterial(color: UIColor(Color(hex: s.color) ?? .gray))
393 body.model = ModelComponent(mesh: .generateSphere(radius: 1), materials: [m])
415 body.model = ModelComponent(mesh: sphere, materials: [m])
394416 body.orientation = simd_quatf(angle: Float(s.tilt * .pi / 180), axis: [1, 0, 0])
395417 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))) }
396418 e.bodies[s.id] = body
397419 e.root.addChild(body)
398 let night = Self.nightShell()
420 let night = ModelEntity(mesh: nightMesh, materials: [nightMaterial])
399421 e.nights[s.id] = night
400422 e.root.addChild(night)
401423 }
402424
403425 // Spacecraft and comet nuclei: dots sized each frame to stay visible.
426 let craftMaterial = UnlitMaterial(color: Self.craftColor)
404427 for craft in Spacecraft.all {
405 let dot = ModelEntity(mesh: .generateSphere(radius: 1), materials: [UnlitMaterial(color: Self.craftColor)])
428 let dot = ModelEntity(mesh: sphere, materials: [craftMaterial])
406429 e.bodies["craft:\(craft.name)"] = dot
407430 e.root.addChild(dot)
408431 }
432 let nucleusMaterial = UnlitMaterial(color: UIColor(white: 0.92, alpha: 1))
433 // A soft tail: nested cones, wider and fainter outward.
434 let tailParts = ([(0.025, 0.3), (0.06, 0.14), (0.11, 0.06)] as [(Float, Float)]).map { radius, alpha in
435 var t = UnlitMaterial(color: UIColor(red: 0.7, green: 0.88, blue: 1, alpha: 1))
436 t.blending = .transparent(opacity: .init(floatLiteral: alpha))
437 return (mesh: MeshResource.generateCone(height: 1, radius: radius), material: t)
438 }
409439 for c in KeplerOrbit.comets {
410 let nucleus = ModelEntity(mesh: .generateSphere(radius: 1), materials: [UnlitMaterial(color: UIColor(white: 0.92, alpha: 1))])
440 let nucleus = ModelEntity(mesh: sphere, materials: [nucleusMaterial])
411441 e.bodies["comet:\(c.id)"] = nucleus
412442 e.root.addChild(nucleus)
413 // A soft tail: nested cones, wider and fainter outward.
414443 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]))
444 for part in tailParts {
445 tail.addChild(ModelEntity(mesh: part.mesh, materials: [part.material]))
419446 }
420447 e.tails[c.id] = tail
421448 e.root.addChild(tail)
@@ -429,7 +456,7 @@ struct SolarSystem3DView: View {
429456
430457 var flareMaterial = UnlitMaterial(color: UIColor(red: 1, green: 1, blue: 0.85, alpha: 0.9))
431458 flareMaterial.blending = .transparent(opacity: .init(floatLiteral: 0.9))
432 e.flare.model = ModelComponent(mesh: .generateSphere(radius: 1), materials: [flareMaterial])
459 e.flare.model = ModelComponent(mesh: sphere, materials: [flareMaterial])
433460 e.root.addChild(e.flare)
434461 for y: Float in [0.86, -0.86] {
435462 for (inner, outer, alpha) in [(0.36, 0.66, 0.22), (0.45, 0.56, 0.5)] as [(Float, Float, CGFloat)] {
@@ -535,13 +562,19 @@ struct SolarSystem3DView: View {
535562 if let (s, w) = e.orbitsBuilt, s == scale, w / width < 1.6, width / w < 1.6 { return }
536563 e.orbitsBuilt = (scale, width)
537564 let map = mapping
565 // Orbits of the same colour and opacity share a material, made when the first of them is created.
566 var materials: [String: UnlitMaterial] = [:]
538567 func set(_ id: String, _ points: [SIMD3<Float>], color: UIColor, opacity: Float) {
539568 let mesh = Self.ribbon(points, width: width, closed: true)
540569 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])
570 let key = "\(color) \(opacity)"
571 if materials[key] == nil {
572 var m = UnlitMaterial(color: color)
573 m.blending = .transparent(opacity: .init(floatLiteral: opacity))
574 m.faceCulling = .none
575 materials[key] = m
576 }
577 let orbit = ModelEntity(mesh: mesh, materials: [materials[key]!])
545578 e.orbits[id] = orbit
546579 e.root.addChild(orbit)
547580 }
@@ -567,6 +600,7 @@ struct SolarSystem3DView: View {
567600 e.pathsBuilt = (scale, width, bucket)
568601 let map = mapping
569602 let day = date.timeIntervalSince1970 / 86_400
603 var material: UnlitMaterial?
570604 for craft in Spacecraft.all {
571605 var pts = craft.points.filter { $0[0] <= day }.map { map.point(SIMD3($0[1], $0[2], $0[3])) }
572606 if let now = craft.position3(at: date) { pts.append(map.point(now)) }
@@ -574,10 +608,13 @@ struct SolarSystem3DView: View {
574608 if let existing = e.paths[craft.name] {
575609 existing.model?.mesh = mesh
576610 } 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])
611 if material == nil {
612 var m = UnlitMaterial(color: Self.craftColor)
613 m.blending = .transparent(opacity: .init(floatLiteral: 0.4))
614 m.faceCulling = .none
615 material = m
616 }
617 let path = ModelEntity(mesh: mesh, materials: [material!])
581618 e.paths[craft.name] = path
582619 e.root.addChild(path)
583620 }
@@ -666,7 +703,7 @@ struct SolarSystem3DView: View {
666703 }
667704
668705 /// 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 {
706 private static func nightShell() -> MeshResource {
670707 let rings = 24, segments = 64
671708 var positions: [SIMD3<Float>] = []
672709 var indices: [UInt32] = []
@@ -686,10 +723,7 @@ struct SolarSystem3DView: View {
686723 var d = MeshDescriptor(name: "night")
687724 d.positions = MeshBuffer(positions)
688725 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])
726 return (try? MeshResource.generate(from: [d])) ?? .generateBox(size: 0.001)
693727 }
694728
695729 // MARK: Labels, taps and the card