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 b7bb1e27ef

b7bb1e27efbdb58ca151c2c6c7fce2751fd1b6e8

parent: 2381013e89

Unsigned

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

Sky: Tycho-2 stars to V 9 and zoom to 3° (!123)

- `scripts/make-tycho.py`: input a VizieR TAP CSV (`VTmag < 9.6`, 221,275 rows); V = VT − 0.090 (BT − VT), B − V = 0.850 (BT − VT); keeps V 6–9; drops stars within 30″ of a BSC5 star with |ΔV| < 0.7 (BSC5 has no HIP column, so the HIP/HD step in PLAN was not possible). Output 121,088 stars, 1.7 MB.
- `Catalog.faintStars` (decoded on first use, `hr` 0); `SkyScene.faintStars(around:radius:)`; `SkyEngine.approximateJ2000(of:at:from:)` (no precession; for choosing the region).
- Sky tab: field floor 30° → 3°; below 40°, stars within the view's radius + 3° loaded off the main thread, keyed by scene and view to 2°. `StarBin` to magnitude 9; star radii × √(60/field) up to 2.5; faintest opacity 0.35.
- Tests: catalogue range, round trip for Vega within 1°, 100–600 stars within 5°. Rendered a 15° field around Lyra (3,265 stars). All package tests pass; iOS builds.

Layout: unified · split

App/Sources/SkyScreen.swift +34 −3
@@ -15,6 +15,7 @@ struct SkyScreen: View {
1515 @AppStorage(SettingsKey.showDeepSky) private var showDeepSky = true
1616 @AppStorage(SettingsKey.showMilkyWay) private var showMilkyWay = true
1717 @AppStorage(SettingsKey.horizonProfile) private var horizonProfile = ""
18 @State private var faint: (key: FaintKey, stars: [PlacedStar])?
1819 @State private var showSettings = false
1920 @State private var showEvents = false
2021 @State private var showLog = false
@@ -48,10 +49,11 @@ struct SkyScreen: View {
4849 style.background.ignoresSafeArea()
4950 if let scene = model.scene {
5051 let view = current(width: geo.size.width)
51 SkyView(scene: scene, centerAzimuth: view.azimuth, centerAltitude: view.altitude, fieldOfView: view.fieldOfView, style: style, culture: Catalog.skyCultures.first { $0.id == skyCulture }, highlight: (tour.map { $0.steps[tourStep].target } ?? shown).flatMap(highlight), showDeepSky: showDeepSky, showMilkyWay: showMilkyWay, horizon: HorizonProfile(stored: horizonProfile)) { [stats] d in
52 SkyView(scene: scene, centerAzimuth: view.azimuth, centerAltitude: view.altitude, fieldOfView: view.fieldOfView, style: style, culture: Catalog.skyCultures.first { $0.id == skyCulture }, highlight: (tour.map { $0.steps[tourStep].target } ?? shown).flatMap(highlight), showDeepSky: showDeepSky, showMilkyWay: showMilkyWay, horizon: HorizonProfile(stored: horizonProfile), faintStars: faintStars(scene, view)) { [stats] d in
5253 stats.record(d)
5354 }
5455 .ignoresSafeArea()
56 .task(id: FaintKey(scene: scene, view: view)) { await loadFaint(scene, view) }
5557 .gesture(panGesture(width: geo.size.width).simultaneously(with: zoomGesture))
5658 .onTapGesture(coordinateSpace: .local) { location in
5759 let p = Projection(centerAzimuth: view.azimuth, centerAltitude: view.altitude, fieldOfView: view.fieldOfView, size: geo.size)
@@ -207,9 +209,38 @@ struct SkyScreen: View {
207209 Task { details = await model.details(of: body) }
208210 }
209211
212 static let minimumField = 3.0
213 /// Narrower than this, Tycho-2 stars to V 9 are added around the view.
214 static let faintField = 40.0
215
216 /// Which faint stars are loaded: the scene's time and place, and the view centre to 2° and field to 5°.
217 struct FaintKey: Hashable {
218 var date: Date, latitude: Double, longitude: Double, azimuth: Int, altitude: Int, field: Int
219 init(scene: SkyScene, view: (azimuth: Double, altitude: Double, fieldOfView: Double)) {
220 date = scene.date; latitude = scene.observer.latitude; longitude = scene.observer.longitude
221 azimuth = Int(view.azimuth / 2); altitude = Int(view.altitude / 2)
222 field = view.fieldOfView < Self.faintField ? Int(view.fieldOfView / 5) : -1
223 }
224 static var faintField: Double { SkyScreen.faintField }
225 }
226
227 private func faintStars(_ scene: SkyScene, _ view: (azimuth: Double, altitude: Double, fieldOfView: Double)) -> [PlacedStar] {
228 guard view.fieldOfView < Self.faintField, let faint, faint.key.date == scene.date else { return [] }
229 return faint.stars
230 }
231
232 /// Tycho-2 stars within the view's diagonal of its centre, off the main thread.
233 private func loadFaint(_ scene: SkyScene, _ view: (azimuth: Double, altitude: Double, fieldOfView: Double)) async {
234 let key = FaintKey(scene: scene, view: view)
235 guard key.field >= 0 else { faint = nil; return }
236 let center = Horizontal(altitude: view.altitude, azimuth: view.azimuth), radius = view.fieldOfView * 0.9 + 3
237 let stars = await Task.detached { scene.faintStars(around: center, radius: radius) }.value
238 if !Task.isCancelled { faint = (key, stars) }
239 }
240
210241 /// The view direction with any in-progress gestures applied.
211242 private func current(width: CGFloat) -> (azimuth: Double, altitude: Double, fieldOfView: Double) {
212 let fov = min(max(fieldOfView / Double(zoom), 30), 140)
243 let fov = min(max(fieldOfView / Double(zoom), Self.minimumField), 140)
213244 if pointer.active { return (pointer.direction.azimuth, pointer.direction.altitude, fov) }
214245 let degreesPerPoint = fov / Double(max(width, 1))
215246 let az = (azimuth - Double(drag.width) * degreesPerPoint).truncatingRemainder(dividingBy: 360)
@@ -239,7 +270,7 @@ struct SkyScreen: View {
239270 private var zoomGesture: some Gesture {
240271 MagnifyGesture()
241272 .updating($zoom) { value, state, _ in state = value.magnification }
242 .onEnded { value in fieldOfView = min(max(fieldOfView / Double(value.magnification), 30), 140) }
273 .onEnded { value in fieldOfView = min(max(fieldOfView / Double(value.magnification), Self.minimumField), 140) }
243274 }
244275
245276 private var header: some View {
PLAN.org +3
@@ -540,6 +540,9 @@ Worker; DSN Now freshness; NASA/ESA image licences; 26 LoC plates bundled.
540540 1.6 MB binary), NGC objects, a deeper zoom and eyepiece field-of-view
541541 circles from the equipment inventory. Merge: drop Tycho-2 stars matched to
542542 BSC5 by HIP/HD, then by position (10″, ΔV 0.5); BSC5 keeps HR numbers.
543 Done for the stars: 121,088 Tycho-2 stars V 6–9 (1.7 MB), BSC5 matches
544 dropped by position alone (30″, ΔV 0.7; BSC5 has no HIP numbers); placed
545 around the view below 40° field; zoom to 3°.
543546- Horizon profile. Done: 36 altitudes (10° steps) set by dragging in Settings
544547 → Horizon; the sky chart draws them as ground.
545548
Packages/MoonriseKit/Package.swift +1 −1
@@ -23,7 +23,7 @@ let package = Package(
2323 .target(
2424 name: "SkyRenderer",
2525 dependencies: ["SkyEngine"],
26 resources: [.copy("Resources/bsc5.json"), .copy("Resources/constellations.json"), .copy("Resources/coastline.json"), .copy("Resources/spacecraft.json"), .copy("Resources/skycultures.json"), .copy("Resources/messier.json"), .copy("Resources/milkyway.bin")]
26 resources: [.copy("Resources/bsc5.json"), .copy("Resources/constellations.json"), .copy("Resources/coastline.json"), .copy("Resources/spacecraft.json"), .copy("Resources/skycultures.json"), .copy("Resources/messier.json"), .copy("Resources/milkyway.bin"), .copy("Resources/tycho2.bin")]
2727 ),
2828 .target(name: "Feeds", dependencies: ["SkyEngine"]),
2929 .target(name: "ObservingLog", dependencies: ["Library", "SkyRenderer"]),
Packages/MoonriseKit/Sources/SkyEngine/SkyEngine.swift +19
@@ -216,3 +216,22 @@ public enum SkyEngine {
216216 return a.angle
217217 }
218218}
219
220extension SkyEngine {
221 /// The J2000 right ascension and declination (degrees) of a horizontal direction, roughly: precession,
222 /// nutation and refraction are ignored, so it is off by up to a degree or so. For choosing which part of a
223 /// catalogue to place, not for placing it.
224 public static func approximateJ2000(of h: Horizontal, at date: Date, from observer: Observer) -> (ra: Double, dec: Double) {
225 lock.lock()
226 var t = time(date)
227 let gast = Astronomy_SiderealTime(&t)
228 lock.unlock()
229 let r = Double.pi / 180
230 let phi = observer.latitude * r, alt = h.altitude * r, az = h.azimuth * r
231 let dec = asin(sin(phi) * sin(alt) + cos(phi) * cos(alt) * cos(az))
232 let ha = atan2(-sin(az) * cos(alt), cos(phi) * sin(alt) - sin(phi) * cos(alt) * cos(az))
233 let lst = gast * 15 + observer.longitude
234 let ra = (lst - ha / r).truncatingRemainder(dividingBy: 360)
235 return (ra < 0 ? ra + 360 : ra, dec / r)
236 }
237}
Packages/MoonriseKit/Sources/SkyRenderer/Resources/tycho2.bin added

Binary file not shown.

Packages/MoonriseKit/Sources/SkyRenderer/SkyScene.swift +31
@@ -83,6 +83,24 @@ public enum Catalog {
8383 return rows.map { Star(hr: Int($0[0]), ra: $0[1], dec: $0[2], magnitude: $0[3], colorIndex: $0[4], pmRA: $0[5], pmDec: $0[6]) }
8484 }()
8585
86 /// Tycho-2 stars from V 6 to 9 not in the Bright Star Catalogue (ESA; Høg et al. 2000), sorted by V, built by
87 /// scripts/make-tycho.py; `hr` is 0. About 121,000 stars, decoded on first use.
88 public static let faintStars: [Star] = {
89 let url = Bundle.module.url(forResource: "tycho2", withExtension: "bin")!
90 let data = try! Data(contentsOf: url)
91 return stride(from: 0, to: data.count - 13, by: 14).map { o in
92 data.withUnsafeBytes { b in
93 let ra = Double(b.loadUnaligned(fromByteOffset: o, as: UInt32.self).littleEndian) / 4_294_967_296 * 360
94 let dec = Double(b.loadUnaligned(fromByteOffset: o + 4, as: Int32.self).littleEndian) / 2_147_483_647 * 90
95 let v = Double(b[o + 8]) / 20 - 2
96 let bv = Double(Int8(bitPattern: b[o + 9])) / 50
97 let pmRA = Double(b.loadUnaligned(fromByteOffset: o + 10, as: Int16.self).littleEndian) / 1000
98 let pmDec = Double(b.loadUnaligned(fromByteOffset: o + 12, as: Int16.self).littleEndian) / 1000
99 return Star(hr: 0, ra: ra, dec: dec, magnitude: v, colorIndex: bv, pmRA: pmRA, pmDec: pmDec)
100 }
101 }
102 }()
103
86104 /// Stars by HR number.
87105 public static let starsByHR: [Int: Star] = Dictionary(uniqueKeysWithValues: stars.map { ($0.hr, $0) })
88106
@@ -145,6 +163,19 @@ public struct SkyScene: Sendable {
145163
146164 static let milkyWayFloor: UInt8 = 48
147165
166 /// Tycho-2 stars within `radius` degrees of a direction, placed for this scene. The region is chosen with an
167 /// approximate inverse transform, so `radius` should allow a degree or two.
168 public func faintStars(around center: Horizontal, radius: Double) -> [PlacedStar] {
169 let c = SkyEngine.approximateJ2000(of: center, at: date, from: observer)
170 let r = Double.pi / 180
171 let cosLimit = cos(radius * r), sinDec = sin(c.dec * r), cosDec = cos(c.dec * r)
172 let near = Catalog.faintStars.filter { s in
173 sin(s.dec * r) * sinDec + cos(s.dec * r) * cosDec * cos((s.ra - c.ra) * r) >= cosLimit
174 }
175 let placed = SkyEngine.horizontal(j2000: near.map { $0.position(at: date) }, at: date, from: observer)
176 return zip(near, placed).map { PlacedStar(star: $0, position: $1) }
177 }
178
148179 public init(date: Date, observer: Observer, magnitudeLimit: Double = 6.5) throws {
149180 self.date = date
150181 self.observer = observer
Packages/MoonriseKit/Sources/SkyRenderer/SkyView.swift +13 −8
@@ -79,14 +79,14 @@ public struct SkyStyle: Sendable {
7979/// Stars are filled one path per bin: half a magnitude by four tints from B−V.
8080struct StarBin {
8181 static let tints = 4
82 /// Magnitudes −2 to 6.5.
83 static let count = 18 * tints
82 /// Magnitudes −2 to 9.
83 static let count = 23 * tints
8484 var index: Int
8585
8686 init(index: Int) { self.index = index }
8787
8888 init(magnitude: Double, colorIndex: Double) {
89 let m = min(max(Int(((magnitude + 2) * 2).rounded()), 0), 17)
89 let m = min(max(Int(((magnitude + 2) * 2).rounded()), 0), 22)
9090 let t = min(max(Int(((colorIndex + 0.3) / 2 * Double(Self.tints - 1)).rounded()), 0), Self.tints - 1)
9191 index = m * Self.tints + t
9292 }
@@ -117,10 +117,12 @@ public struct SkyView: View {
117117 public var showMilkyWay: Bool
118118 /// Trees and buildings drawn as ground above the horizon.
119119 public var horizon: HorizonProfile?
120 /// Tycho-2 stars around the view, when zoomed in.
121 public var faintStars: [PlacedStar]
120122 /// Called after each draw with the time the draw took.
121123 public var onDraw: (@Sendable (Duration) -> Void)?
122124
123 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, onDraw: (@Sendable (Duration) -> Void)? = nil) {
125 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] = [], onDraw: (@Sendable (Duration) -> Void)? = nil) {
124126 self.scene = scene
125127 self.style = style
126128 self.culture = culture
@@ -128,6 +130,7 @@ public struct SkyView: View {
128130 self.showDeepSky = showDeepSky
129131 self.showMilkyWay = showMilkyWay
130132 self.horizon = horizon
133 self.faintStars = faintStars
131134 self.centerAzimuth = centerAzimuth
132135 self.centerAltitude = centerAltitude
133136 self.fieldOfView = fieldOfView
@@ -244,18 +247,20 @@ public struct SkyView: View {
244247 }
245248 }
246249
247 /// Each star at its own radius; colour and opacity per `StarBin`, faintest bins first.
250 /// Each star at its own radius, larger when zoomed in (up to 2.5 times); colour and opacity per `StarBin`,
251 /// faintest bins first.
248252 func drawStars(_ context: inout GraphicsContext, _ p: Projection) {
249253 var bins = [Path](repeating: Path(), count: StarBin.count)
250 for s in scene.stars where s.position.altitude > 0 {
254 let boost = min(2.5, max(1, (60 / fieldOfView).squareRoot()))
255 for s in scene.stars + faintStars where s.position.altitude > 0 {
251256 guard let pt = p.point(s.position) else { continue }
252 let r = max(0.3, 2.6 - 0.42 * s.star.magnitude)
257 let r = max(0.3, 2.6 - 0.42 * s.star.magnitude) * boost
253258 bins[StarBin(magnitude: s.star.magnitude, colorIndex: s.star.colorIndex).index]
254259 .addEllipse(in: CGRect(x: pt.x - r, y: pt.y - r, width: 2 * r, height: 2 * r))
255260 }
256261 for i in bins.indices.reversed() where !bins[i].isEmpty {
257262 let bin = StarBin(index: i)
258 let opacity = min(1, max(0.25, 1.15 - 0.13 * bin.magnitude))
263 let opacity = min(1, max(0.35, 1.15 - 0.13 * bin.magnitude))
259264 context.fill(bins[i], with: .color(style.starColor(tint: bin.tint).opacity(opacity)))
260265 }
261266 }
Packages/MoonriseKit/Tests/SkyRendererTests/HorizonProfileTests.swift deleted −16
@@ -1,16 +0,0 @@
1import Foundation
2import Testing
3@testable import SkyRenderer
4
5@Test func horizonProfileInterpolatesAndStores() throws {
6 var h = HorizonProfile()
7 #expect(h.isFlat)
8 h.altitudes[9] = 20 // 90°, east
9 #expect(h.altitude(at: 90) == 20)
10 #expect(h.altitude(at: 95) == 10)
11 #expect(h.altitude(at: 85) == 10)
12 #expect(h.altitude(at: 450) == 20)
13 #expect(h.altitude(at: -270) == 20)
14 #expect(HorizonProfile(stored: h.stored) == h)
15 #expect(HorizonProfile(stored: "1,2") == nil)
16}
Packages/MoonriseKit/Tests/SkyRendererTests/SkyChartTests.swift added +31
@@ -0,0 +1,31 @@
1import Foundation
2import Testing
3import SkyEngine
4@testable import SkyRenderer
5
6@Test func horizonProfileInterpolatesAndStores() throws {
7 var h = HorizonProfile()
8 #expect(h.isFlat)
9 h.altitudes[9] = 20 // 90°, east
10 #expect(h.altitude(at: 90) == 20)
11 #expect(h.altitude(at: 95) == 10)
12 #expect(h.altitude(at: 85) == 10)
13 #expect(h.altitude(at: 450) == 20)
14 #expect(h.altitude(at: -270) == 20)
15 #expect(HorizonProfile(stored: h.stored) == h)
16 #expect(HorizonProfile(stored: "1,2") == nil)
17}
18
19@Test func faintStarsAroundAViewDirection() throws {
20 #expect(Catalog.faintStars.count > 100_000)
21 #expect(Catalog.faintStars.allSatisfy { $0.magnitude >= 5.95 && $0.magnitude <= 9.05 })
22 let date = try Date("2026-08-15T23:00:00Z", strategy: .iso8601), here = Observer(latitude: 51.48, longitude: 0)
23 let scene = try SkyScene(date: date, observer: here)
24 // Vega (HR 7001): its horizontal position turned back to J2000 lands within a degree.
25 let vega = try #require(scene.starsByHR[7001])
26 let back = SkyEngine.approximateJ2000(of: vega, at: date, from: here)
27 #expect(abs(back.ra - 279.23) < 1 && abs(back.dec - 38.78) < 1)
28 let near = scene.faintStars(around: vega, radius: 5)
29 #expect(near.count > 100 && near.count < 600)
30 #expect(near.allSatisfy { $0.star.hr == 0 })
31}
THIRD_PARTY.org +1
@@ -13,6 +13,7 @@
1313| Orbital elements for Ceres, Haumea, Makemake, Eris and seven comets (=Packages/MoonriseKit/Sources/SkyEngine/Kepler.swift=) | JPL Small-Body Database, fetched 2026-10-19 | NASA/JPL, no published restrictions | https://ssd.jpl.nasa.gov/tools/sbdb_lookup.html |
1414| ConstellationLines v1.4, Copyright (c) 2005-2026 Marc van der Sluys | =Packages/MoonriseKit/Sources/SkyRenderer/Resources/constellations.json= | CC BY 4.0 | https://github.com/MarcvdSluys/ConstellationLines, doi:10.5281/zenodo.10397192 |
1515| Gaia's sky in colour, ESA/Gaia/DPAC: Milky Way brightness on a 2° grid (=scripts/make-milkyway.swift=) | =Packages/MoonriseKit/Sources/SkyRenderer/Resources/milkyway.bin= | CC BY-SA 3.0 IGO; the derived grid is under the same licence | https://www.esa.int/ESA_Multimedia/Images/2018/04/Gaia_s_sky_in_colour2 |
16| Tycho-2 Catalogue (ESA; Høg et al. 2000, A&A 355, L27), VizieR I/259: stars from V 6 to 9 not in BSC5 (=scripts/make-tycho.py=) | =Packages/MoonriseKit/Sources/SkyRenderer/Resources/tycho2.bin= | ESA archive data, CC BY-NC 3.0 IGO; credit ESA | https://cdsarc.cds.unistra.fr/viz-bin/cat/I/259 |
1617| Natural Earth 1:110m coastline v5.1.2 | =Packages/MoonriseKit/Sources/SkyRenderer/Resources/coastline.json= | Public domain | https://www.naturalearthdata.com |
1718| Launch Library 2 (The Space Devs) | fetched at runtime by =server/= | Free API; credit shown in the app | https://thespacedevs.com/llapi |
1819| JPL Horizons spacecraft vectors (Voyager 1, 2, Pioneer 10, 11, New Horizons) | =Packages/MoonriseKit/Sources/SkyRenderer/Resources/spacecraft.json= | NASA/JPL, no published restrictions | https://ssd.jpl.nasa.gov/horizons/ |
scripts/make-tycho.py added +63
@@ -0,0 +1,63 @@
1#!/usr/bin/env python3
2"""Builds SkyRenderer/Resources/tycho2.bin: Tycho-2 stars from V 6 to 9 that are not in the Bright Star Catalogue.
3
4Input is a VizieR TAP CSV of I/259/tyc2 (ESA; Høg et al. 2000), queried with
5 SELECT RAmdeg, DEmdeg, pmRA, pmDE, BTmag, VTmag, HIP FROM "I/259/tyc2" WHERE VTmag < 9.6
6V = VT − 0.090 (BT − VT) and B − V = 0.850 (BT − VT) (ESA 1997, Hipparcos and Tycho Catalogues, vol. 1, 1.3).
7Stars without a mean position are left out, as are those brighter than V 6 (the Bright Star Catalogue is
8complete there) and any within 30″ of a BSC5 star whose V is within 0.7.
9
10Record, 14 bytes, little-endian, sorted by V: RA as UInt32 (360° = 2^32), Dec as Int32 (90° = 2^31 − 1),
11V as UInt8 ((V + 2) × 20), B − V as Int8 (× 50), pmRA (× cos dec) and pmDec as Int16 in mas/yr. J2000.
12
13 scripts/make-tycho.py tyc2.csv
14"""
15import csv
16import json
17import math
18import struct
19import sys
20from pathlib import Path
21
22RES = Path(__file__).resolve().parent.parent / "Packages/MoonriseKit/Sources/SkyRenderer/Resources"
23
24bright = json.load(open(RES / "bsc5.json"))
25cells = {}
26for hr, ra, dec, v, *_ in bright:
27 cells.setdefault((int(dec), int(ra)), []).append((ra, dec, v))
28
29
30def in_bsc(ra, dec, v):
31 for d in (-1, 0, 1):
32 for r in (-1, 0, 1):
33 for bra, bdec, bv in cells.get((int(dec) + d, (int(ra) + r) % 360), []):
34 dra = (ra - bra + 180) % 360 - 180
35 sep = math.hypot(dra * math.cos(math.radians(dec)), dec - bdec) * 3600
36 if sep < 30 and abs(v - bv) < 0.7:
37 return True
38 return False
39
40
41rows = []
42for r in csv.DictReader(open(sys.argv[1])):
43 if not r["RAmdeg"] or not r["VTmag"]:
44 continue
45 vt, ra, dec = float(r["VTmag"]), float(r["RAmdeg"]), float(r["DEmdeg"])
46 bt = float(r["BTmag"]) if r["BTmag"] else None
47 v = vt - 0.090 * (bt - vt) if bt is not None else vt
48 bv = 0.850 * (bt - vt) if bt is not None else 0.6
49 if v < 6 or v > 9 or in_bsc(ra, dec, v):
50 continue
51 pmra = float(r["pmRA"]) if r["pmRA"] else 0
52 pmde = float(r["pmDE"]) if r["pmDE"] else 0
53 rows.append((v, ra, dec, bv, pmra, pmde))
54
55rows.sort()
56clamp = lambda x, lo, hi: max(lo, min(hi, x))
57with open(RES / "tycho2.bin", "wb") as f:
58 for v, ra, dec, bv, pmra, pmde in rows:
59 f.write(struct.pack("<IiBbhh",
60 int(ra / 360 * 2**32) % 2**32, int(dec / 90 * (2**31 - 1)),
61 clamp(round((v + 2) * 20), 0, 255), clamp(round(bv * 50), -128, 127),
62 clamp(round(pmra), -32768, 32767), clamp(round(pmde), -32768, 32767)))
63print(len(rows), "stars,", len(rows) * 14, "bytes")