Modern Apps git

← Modern-Apps.git

astronomy: native rust coordinate transforms and sky projection

Commit
e20c0c72f04b3640d7dd20e7fde406fe6303c020
Author
Vayun Mathur <[email protected]>
When
2026-07-29 03:16 UTC (4 months ago)
Parents
4ce4e75

Diff

astronomy/build.gradle.kts
diff --git a/astronomy/build.gradle.kts b/astronomy/build.gradle.ktsindex 67c160e330..2e8f0c760f 100644--- a/astronomy/build.gradle.kts+++ b/astronomy/build.gradle.kts@@ -13,6 +13,17 @@ android {     } } +androidComponents {+    onVariants { variant ->+        variant.sources.jniLibs?.addStaticSourceDirectory(+            layout.buildDirectory.dir("rustJniLibs").get().asFile.absolutePath+        )+    }+}++// Native celestial transforms + sky projection (Rust). See astronomy/src/main/rust/.+rustNativeLib("astronomy_engine", "astronomy")+ metadataScreenshots {     // SkyMapPage gates behind location via PermissionsChecker — grant so first-run     // system prompt doesn't hijack the screenshots. Camera is optional AR overlay.
astronomy/src/main/java/com/vayunmathur/astronomy/domain/AstronomyNative.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/AstronomyNative.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/AstronomyNative.ktnew file mode 100644index 0000000000..2e8056fccc--- /dev/null+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/AstronomyNative.kt@@ -0,0 +1,36 @@+package com.vayunmathur.astronomy.domain++/**+ * JNI bridge to the native `astronomy_engine` Rust library: the per-tick /+ * per-frame hot paths (batch RaDec -> AltAz, batch stereographic projection).+ *+ * The fully-qualified name of this object MUST stay+ * `com.vayunmathur.astronomy.domain.AstronomyNative` so the JNI symbol mangling+ * (`Java_com_vayunmathur_astronomy_domain_AstronomyNative_*`) matches.+ */+object AstronomyNative {+    init {+        System.loadLibrary("astronomy_engine")+    }++    /**+     * Batch RaDec -> AltAz. [radec] is interleaved `[ra0,dec0,ra1,dec1,...]` in+     * radians; returns interleaved `[az0,alt0,az1,alt1,...]` in radians.+     */+    external fun batchRaDecToAltAz(radec: DoubleArray, lstRad: Double, latRad: Double): DoubleArray++    /**+     * Batch stereographic projection. [altaz] is interleaved `[az0,alt0,...]`;+     * returns interleaved `[x0,y0,x1,y1,...]` in screen pixels, with `Float.NaN`+     * for both components of any culled point.+     */+    external fun batchProject(+        altaz: DoubleArray,+        centerAzRad: Double,+        centerAltRad: Double,+        fovDeg: Double,+        screenW: Double,+        screenH: Double,+        rotationRad: Double,+    ): FloatArray+}
astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.ktindex 0b702fba7f..005b47a184 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/engine/CoordinateTransforms.kt@@ -1,5 +1,6 @@ package com.vayunmathur.astronomy.domain.engine +import com.vayunmathur.astronomy.domain.AstronomyNative import kotlin.math.*  data class RaDec(val raRad: Double, val decRad: Double) {@@ -57,21 +58,17 @@ object CoordinateTransforms {         return acos(sd.coerceIn(-1.0, 1.0))     } +    // Native batch transform: marshal to an interleaved [ra,dec,...] DoubleArray,+    // transform in Rust, rebuild the List<AltAz>.     fun batchRaDecToAltAz(radecs: List<RaDec>, lstRad: Double, latRad: Double): List<AltAz> {-        val sinLat = sin(latRad); val cosLat = cos(latRad)-        return radecs.map { rd ->-            val ha = (lstRad - rd.raRad).normalizePi()-            val sinDec = sin(rd.decRad); val cosDec = cos(rd.decRad)-            val sinAlt = sinDec * sinLat + cosDec * cosLat * cos(ha)-            val alt = asin(sinAlt.coerceIn(-1.0, 1.0))-            val cosAlt = cos(alt)-            val az = if (abs(cosAlt) < 1e-10) 0.0 else {-                val cosAz = (sinDec - sinAlt * sinLat) / (cosAlt * cosLat)-                val sinAz = -cosDec * sin(ha) / cosAlt-                atan2(sinAz, cosAz).normalize2Pi()-            }-            AltAz(az, alt)+        if (radecs.isEmpty()) return emptyList()+        val input = DoubleArray(radecs.size * 2)+        for (i in radecs.indices) {+            input[2 * i] = radecs[i].raRad+            input[2 * i + 1] = radecs[i].decRad         }+        val out = AstronomyNative.batchRaDecToAltAz(input, lstRad, latRad)+        return List(radecs.size) { i -> AltAz(out[2 * i], out[2 * i + 1]) }     }      fun atmosphericRefractionDeg(trueAltDeg: Double): Double {
astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.ktindex 4dd472eba1..f674551418 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/domain/projection/StereographicProjection.kt@@ -1,9 +1,38 @@ package com.vayunmathur.astronomy.domain.projection  import androidx.compose.ui.geometry.Offset+import com.vayunmathur.astronomy.domain.AstronomyNative import com.vayunmathur.astronomy.domain.engine.AltAz import kotlin.math.* +/**+ * Batch-project a list of [AltAz] under [viewState] via the native+ * `astronomy_engine` projection, returning one nullable screen point per input+ * (`Float.NaN` from native == culled == null), positionally aligned with the+ * input. Intended for the largest list (stars) on the render hot path.+ */+fun projectAll(viewState: ViewState, altAzList: List<AltAz>): List<Offset?> {+    if (altAzList.isEmpty()) return emptyList()+    val input = DoubleArray(altAzList.size * 2)+    for (i in altAzList.indices) {+        input[2 * i] = altAzList[i].azRad+        input[2 * i + 1] = altAzList[i].altRad+    }+    val out = AstronomyNative.batchProject(+        input,+        viewState.centerAzRad,+        viewState.centerAltRad,+        viewState.fovDegDouble,+        viewState.screenW.toDouble(),+        viewState.screenH.toDouble(),+        viewState.rotationRad,+    )+    return List(altAzList.size) { i ->+        val x = out[2 * i]; val y = out[2 * i + 1]+        if (x.isNaN() || y.isNaN()) null else Offset(x, y)+    }+}+ class StereographicProjection(private val viewState: ViewState) : SkyProjection {     private val sinCenterAlt = sin(viewState.centerAltRad)     private val cosCenterAlt = cos(viewState.centerAltRad)
astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.ktindex 72f4129708..67e2223dcf 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/AstronomyViewModel.kt@@ -128,13 +128,12 @@ class AstronomyViewModel(app: Application) : AndroidViewModel(app) {         val jd = TimeEngine.instantToJulianDate(time)         val lst = TimeEngine.lstRad(jd, obs.lonRad)         val magLim = _magLimit.value.toDouble()-        val stars = catalog.stars.asSequence()-            .filter { it.mag <= magLim }-            .map { s ->-                val rd = RaDec(s.ra, s.dec)-                val aa = CoordinateTransforms.raDecToAltAz(rd, lst, obs.latRad)-                VisibleStar(s, aa, rd)-            }.toList()+        val visibleStars = catalog.stars.filter { it.mag <= magLim }+        val starRaDecs = visibleStars.map { RaDec(it.ra, it.dec) }+        val starAltAz = CoordinateTransforms.batchRaDecToAltAz(starRaDecs, lst, obs.latRad)+        val stars = visibleStars.mapIndexed { i, s ->+            VisibleStar(s, starAltAz[i], starRaDecs[i])+        }          val constLines = catalog.constellations.map { c ->             ConstellationLine(c.abbr, c.name, c.lines)
astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyCanvas.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyCanvas.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyCanvas.ktindex 5205333e86..dc0b5cabc2 100644--- a/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyCanvas.kt+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/ui/pages/SkyCanvas.kt@@ -22,6 +22,7 @@ import androidx.compose.ui.unit.sp import com.vayunmathur.astronomy.domain.engine.AltAz import com.vayunmathur.astronomy.domain.projection.StereographicProjection import com.vayunmathur.astronomy.domain.projection.ViewState+import com.vayunmathur.astronomy.domain.projection.projectAll import com.vayunmathur.astronomy.ui.TrajectoryPoint import com.vayunmathur.astronomy.ui.VisibleArt import com.vayunmathur.astronomy.ui.VisibleSky@@ -76,7 +77,12 @@ fun SkyCanvas(     val currentOnTap by rememberUpdatedState(onTap)      val projectedStars = remember(visibleSky.stars, projection) {-        visibleSky.stars.mapNotNull { vs -> projection.project(vs.altAz)?.let { Triple(vs, it, vs.star.mag) } }+        // Stars are the largest list; batch-project them (native fast path when+        // available) and zip results back positionally, dropping culled points.+        val projected = projectAll(viewState, visibleSky.stars.map { it.altAz })+        visibleSky.stars.mapIndexedNotNull { i, vs ->+            projected[i]?.let { Triple(vs, it, vs.star.mag) }+        }     }     val projectedPlanets = remember(visibleSky.planets, projection) {         visibleSky.planets.mapNotNull { vp -> projection.project(vp.altAz)?.let { vp to it } }
astronomy/src/main/rust/.gitignore
diff --git a/astronomy/src/main/rust/.gitignore b/astronomy/src/main/rust/.gitignorenew file mode 100644index 0000000000..ea8c4bf7f3--- /dev/null+++ b/astronomy/src/main/rust/.gitignore@@ -0,0 +1 @@+/target
astronomy/src/main/rust/Cargo.lock
diff --git a/astronomy/src/main/rust/Cargo.lock b/astronomy/src/main/rust/Cargo.locknew file mode 100644index 0000000000..990e5f49e3--- /dev/null+++ b/astronomy/src/main/rust/Cargo.lock@@ -0,0 +1,258 @@+# This file is automatically @generated by Cargo.+# It is not intended for manual editing.+version = 4++[[package]]+name = "astronomy_engine"+version = "0.1.0"+dependencies = [+ "jni",+]++[[package]]+name = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"++[[package]]+name = "cesu8"+version = "1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"++[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"++[[package]]+name = "combine"+version = "4.6.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "jni"+version = "0.21.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"+dependencies = [+ "cesu8",+ "cfg-if",+ "combine",+ "jni-sys 0.3.1",+ "log",+ "thiserror",+ "walkdir",+ "windows-sys 0.45.0",+]++[[package]]+name = "jni-sys"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"+dependencies = [+ "jni-sys 0.4.1",+]++[[package]]+name = "jni-sys"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"+dependencies = [+ "jni-sys-macros",+]++[[package]]+name = "jni-sys-macros"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"+dependencies = [+ "quote",+ "syn",+]++[[package]]+name = "log"+version = "0.4.33"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "proc-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quote"+version = "1.0.47"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"+dependencies = [+ "proc-macro2",+]++[[package]]+name = "same-file"+version = "1.0.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"+dependencies = [+ "winapi-util",+]++[[package]]+name = "syn"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "thiserror"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"+dependencies = [+ "thiserror-impl",+]++[[package]]+name = "thiserror-impl"+version = "1.0.69"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "unicode-ident"+version = "1.0.24"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "winapi-util"+version = "0.1.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"+dependencies = [+ "windows-sys 0.61.2",+]++[[package]]+name = "windows-link"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows_aarch64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"++[[package]]+name = "windows_aarch64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[package]]+name = "windows_i686_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"++[[package]]+name = "windows_i686_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[package]]+name = "windows_x86_64_gnu"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"++[[package]]+name = "windows_x86_64_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
astronomy/src/main/rust/Cargo.toml
diff --git a/astronomy/src/main/rust/Cargo.toml b/astronomy/src/main/rust/Cargo.tomlnew file mode 100644index 0000000000..2a55f6dde2--- /dev/null+++ b/astronomy/src/main/rust/Cargo.toml@@ -0,0 +1,19 @@+[package]+name = "astronomy_engine"+version = "0.1.0"+edition = "2021"+description = "Native celestial coordinate transforms + stereographic sky projection for the astronomy app, via JNI"+license = "GPL-2.0-only"++[lib]+name = "astronomy_engine"+crate-type = ["cdylib", "rlib"]++[dependencies]+jni = "0.21"++[profile.release]+opt-level = 3+lto = true+codegen-units = 1+strip = true
astronomy/src/main/rust/rust-toolchain.toml
diff --git a/astronomy/src/main/rust/rust-toolchain.toml b/astronomy/src/main/rust/rust-toolchain.tomlnew file mode 100644index 0000000000..fa6ac3abd8--- /dev/null+++ b/astronomy/src/main/rust/rust-toolchain.toml@@ -0,0 +1,3 @@+[toolchain]+channel = "1.97.0"+targets = ["aarch64-linux-android"]
astronomy/src/main/rust/src/coords.rs
diff --git a/astronomy/src/main/rust/src/coords.rs b/astronomy/src/main/rust/src/coords.rsnew file mode 100644index 0000000000..518827bc30--- /dev/null+++ b/astronomy/src/main/rust/src/coords.rs@@ -0,0 +1,57 @@+//! Celestial coordinate transforms. Pure math ported 1:1 from+//! `CoordinateTransforms.kt` (`batchRaDecToAltAz`) and the `normalizePi` /+//! `normalize2Pi` helpers from `TimeEngine.kt`. Kept dependency-free so it runs+//! under host `cargo test`.++use std::f64::consts::PI;++/// Kotlin `Double.normalizePi()`: wrap to (-PI, PI].+#[inline]+fn normalize_pi(x: f64) -> f64 {+    let mut v = (x + PI) % (2.0 * PI);+    if v < 0.0 {+        v += 2.0 * PI;+    }+    v - PI+}++/// Kotlin `Double.normalize2Pi()`: wrap to [0, 2PI).+#[inline]+fn normalize_2pi(x: f64) -> f64 {+    let mut v = x % (2.0 * PI);+    if v < 0.0 {+        v += 2.0 * PI;+    }+    v+}++/// Batch RaDec -> AltAz. `radec` is interleaved `[ra0, dec0, ra1, dec1, ...]`+/// in radians; returns interleaved `[az0, alt0, az1, alt1, ...]` in radians.+/// Mirrors `CoordinateTransforms.batchRaDecToAltAz` exactly, including hoisting+/// sin/cos of the latitude out of the loop and the `abs(cosAlt) < 1e-10` guard.+pub fn batch_radec_to_altaz(radec: &[f64], lst_rad: f64, lat_rad: f64) -> Vec<f64> {+    let sin_lat = lat_rad.sin();+    let cos_lat = lat_rad.cos();+    let n = radec.len() / 2;+    let mut out = Vec::with_capacity(n * 2);+    for i in 0..n {+        let ra = radec[2 * i];+        let dec = radec[2 * i + 1];+        let ha = normalize_pi(lst_rad - ra);+        let sin_dec = dec.sin();+        let cos_dec = dec.cos();+        let sin_alt = sin_dec * sin_lat + cos_dec * cos_lat * ha.cos();+        let alt = sin_alt.clamp(-1.0, 1.0).asin();+        let cos_alt = alt.cos();+        let az = if cos_alt.abs() < 1e-10 {+            0.0+        } else {+            let cos_az = (sin_dec - sin_alt * sin_lat) / (cos_alt * cos_lat);+            let sin_az = -cos_dec * ha.sin() / cos_alt;+            normalize_2pi(sin_az.atan2(cos_az))+        };+        out.push(az);+        out.push(alt);+    }+    out+}
astronomy/src/main/rust/src/lib.rs
diff --git a/astronomy/src/main/rust/src/lib.rs b/astronomy/src/main/rust/src/lib.rsnew file mode 100644index 0000000000..bfb1193730--- /dev/null+++ b/astronomy/src/main/rust/src/lib.rs@@ -0,0 +1,210 @@+//! Astronomy native library: batch celestial coordinate transforms (RaDec ->+//! AltAz) and batch stereographic sky projection, exposed to Kotlin via JNI.+//! Ports the two per-tick / per-frame hot paths from Kotlin; the math lives in+//! dependency-free modules so it is testable on the host.++mod coords;+mod projection;++pub use coords::batch_radec_to_altaz;+pub use projection::{batch_project, Projector};++#[cfg(test)]+mod tests {+    use super::*;+    use std::f64::consts::PI;++    // Scalar reference implementation of raDecToAltAz, matching the Kotlin+    // scalar `CoordinateTransforms.raDecToAltAz`.+    fn scalar_radec_to_altaz(ra: f64, dec: f64, lst: f64, lat: f64) -> (f64, f64) {+        let normalize_pi = |x: f64| {+            let mut v = (x + PI) % (2.0 * PI);+            if v < 0.0 {+                v += 2.0 * PI;+            }+            v - PI+        };+        let normalize_2pi = |x: f64| {+            let mut v = x % (2.0 * PI);+            if v < 0.0 {+                v += 2.0 * PI;+            }+            v+        };+        let ha = normalize_pi(lst - ra);+        let sin_alt = dec.sin() * lat.sin() + dec.cos() * lat.cos() * ha.cos();+        let alt = sin_alt.clamp(-1.0, 1.0).asin();+        let cos_alt = alt.cos();+        let az = if cos_alt.abs() < 1e-10 {+            0.0+        } else {+            let cos_az = (dec.sin() - sin_alt * lat.sin()) / (cos_alt * lat.cos());+            let sin_az = -dec.cos() * ha.sin() / cos_alt;+            normalize_2pi(sin_az.atan2(cos_az))+        };+        (az, alt)+    }++    #[test]+    fn batch_altaz_matches_scalar() {+        // A few (ra, dec) pairs, one lst/lat.+        let lst = 1.234;+        let lat = 0.71; // ~40.7 deg N+        let cases = [+            (0.0, 0.0),+            (1.0, 0.5),+            (3.5, -0.3),+            (5.9, 1.2),+            (2.0, -1.0),+        ];+        let radec: Vec<f64> = cases.iter().flat_map(|&(ra, dec)| [ra, dec]).collect();+        let out = batch_radec_to_altaz(&radec, lst, lat);+        assert_eq!(out.len(), cases.len() * 2);+        for (i, &(ra, dec)) in cases.iter().enumerate() {+            let (az, alt) = scalar_radec_to_altaz(ra, dec, lst, lat);+            assert!((out[2 * i] - az).abs() < 1e-12, "az mismatch at {i}");+            assert!((out[2 * i + 1] - alt).abs() < 1e-12, "alt mismatch at {i}");+        }+    }++    #[test]+    fn batch_altaz_hand_checked_zenith() {+        // A star on the meridian (ha=0) at the same dec as latitude sits at the+        // zenith: alt = 90 deg (PI/2), az irrelevant.+        let lat = 0.5;+        let lst = 1.0;+        let ra = lst; // ha = 0+        let dec = lat;+        let out = batch_radec_to_altaz(&[ra, dec], lst, lat);+        assert!((out[1] - PI / 2.0).abs() < 1e-9, "expected zenith, got alt={}", out[1]);+    }++    #[test]+    fn project_center_maps_to_screen_center() {+        let w = 1080.0;+        let h = 1920.0;+        let center_az = 1.3;+        let center_alt = 0.4;+        // A point exactly at the view center should map to the screen center.+        let out = batch_project(&[center_az, center_alt], center_az, center_alt, 60.0, w, h, 0.0);+        assert!((out[0] as f64 - w / 2.0).abs() < 1e-3, "x not centered: {}", out[0]);+        assert!((out[1] as f64 - h / 2.0).abs() < 1e-3, "y not centered: {}", out[1]);+    }++    #[test]+    fn project_outside_fov_returns_nan() {+        let w = 1080.0;+        let h = 1920.0;+        let center_az = 0.0;+        let center_alt = 0.0;+        // Antipodal-ish point (opposite azimuth, high negative alt) is well+        // outside the cull disk of a narrow FOV -> NaN.+        let out = batch_project(&[PI, -PI / 2.0], center_az, center_alt, 30.0, w, h, 0.0);+        assert!(out[0].is_nan() && out[1].is_nan(), "expected NaN, got ({}, {})", out[0], out[1]);+    }++    #[test]+    fn project_interleaving_and_length() {+        let w = 800.0;+        let h = 600.0;+        // First point in-view (center), second point culled.+        let altaz = [0.5, 0.2, PI, -PI / 2.0];+        let out = batch_project(&altaz, 0.5, 0.2, 45.0, w, h, 0.0);+        assert_eq!(out.len(), 4);+        assert!(!out[0].is_nan() && !out[1].is_nan());+        assert!(out[2].is_nan() && out[3].is_nan());+    }+}++#[cfg(not(test))]+mod jni_bindings {+    use super::*;+    use jni::objects::{JClass, JDoubleArray};+    use jni::sys::{jdouble, jdoubleArray, jfloatArray};+    use jni::JNIEnv;++    /// `batchRaDecToAltAz(radec, lstRad, latRad)`. `radec` interleaved+    /// `[ra0,dec0,...]` radians; returns interleaved `[az0,alt0,...]` radians,+    /// or null on error.+    #[no_mangle]+    pub extern "system" fn Java_com_vayunmathur_astronomy_domain_AstronomyNative_batchRaDecToAltAz<+        'l,+    >(+        env: JNIEnv<'l>,+        _class: JClass<'l>,+        radec: JDoubleArray<'l>,+        lst_rad: jdouble,+        lat_rad: jdouble,+    ) -> jdoubleArray {+        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            let len = env.get_array_length(&radec).unwrap_or(0) as usize;+            let mut buf = vec![0f64; len];+            if env.get_double_array_region(&radec, 0, &mut buf).is_err() {+                return None;+            }+            Some(batch_radec_to_altaz(&buf, lst_rad, lat_rad))+        }))+        .unwrap_or(None);++        let result = match result {+            Some(r) => r,+            None => return std::ptr::null_mut(),+        };+        let out = match env.new_double_array(result.len() as i32) {+            Ok(a) => a,+            Err(_) => return std::ptr::null_mut(),+        };+        if env.set_double_array_region(&out, 0, &result).is_err() {+            return std::ptr::null_mut();+        }+        out.into_raw()+    }++    /// `batchProject(altaz, centerAzRad, centerAltRad, fovDeg, screenW, screenH,+    /// rotationRad)`. `altaz` interleaved `[az0,alt0,...]`; returns interleaved+    /// `[x0,y0,...]` pixels (NaN,NaN for culled points), or null on error.+    #[no_mangle]+    #[allow(clippy::too_many_arguments)]+    pub extern "system" fn Java_com_vayunmathur_astronomy_domain_AstronomyNative_batchProject<'l>(+        env: JNIEnv<'l>,+        _class: JClass<'l>,+        altaz: JDoubleArray<'l>,+        center_az_rad: jdouble,+        center_alt_rad: jdouble,+        fov_deg: jdouble,+        screen_w: jdouble,+        screen_h: jdouble,+        rotation_rad: jdouble,+    ) -> jfloatArray {+        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+            let len = env.get_array_length(&altaz).unwrap_or(0) as usize;+            let mut buf = vec![0f64; len];+            if env.get_double_array_region(&altaz, 0, &mut buf).is_err() {+                return None;+            }+            Some(batch_project(+                &buf,+                center_az_rad,+                center_alt_rad,+                fov_deg,+                screen_w,+                screen_h,+                rotation_rad,+            ))+        }))+        .unwrap_or(None);++        let result = match result {+            Some(r) => r,+            None => return std::ptr::null_mut(),+        };+        let out = match env.new_float_array(result.len() as i32) {+            Ok(a) => a,+            Err(_) => return std::ptr::null_mut(),+        };+        if env.set_float_array_region(&out, 0, &result).is_err() {+            return std::ptr::null_mut();+        }+        out.into_raw()+    }+}
astronomy/src/main/rust/src/projection.rs
diff --git a/astronomy/src/main/rust/src/projection.rs b/astronomy/src/main/rust/src/projection.rsnew file mode 100644index 0000000000..32d5456af6--- /dev/null+++ b/astronomy/src/main/rust/src/projection.rs@@ -0,0 +1,154 @@+//! Stereographic sky projection. Pure math ported 1:1 from+//! `StereographicProjection.kt` (constructor precomputes, `projectCore`,+//! `angularDist`, and the FOV cull in `project`). No Compose / dependency-free+//! so it runs under host `cargo test`.++use std::f64::consts::PI;++#[inline]+fn to_radians(deg: f64) -> f64 {+    deg * PI / 180.0+}++/// Precomputed projector, mirroring the fields the Kotlin+/// `StereographicProjection` constructor derives from a `ViewState`.+pub struct Projector {+    sin_center_alt: f64,+    cos_center_alt: f64,+    center_az: f64,+    scale: f64,+    half_fov: f64,+    screen_w: f64,+    screen_h: f64,+    rotation_rad: f64,+}++impl Projector {+    pub fn new(+        center_az_rad: f64,+        center_alt_rad: f64,+        fov_deg: f64,+        screen_w: f64,+        screen_h: f64,+        rotation_rad: f64,+    ) -> Projector {+        let sin_center_alt = center_alt_rad.sin();+        let cos_center_alt = center_alt_rad.cos();+        // ViewState.fovRad = toRadians(fovDeg), then clamped 1..150 deg.+        let fov_rad = to_radians(fov_deg).clamp(to_radians(1.0), to_radians(150.0));+        let scale = {+            let rho_edge = 2.0 * (fov_rad / 2.0 / 2.0).tan();+            if rho_edge < 1e-9 {+                1.0+            } else {+                (screen_w * 0.5) / rho_edge+            }+        };+        let half_fov = {+            let w = screen_w;+            let h = screen_h;+            let corner_rho = 0.5 * (w * w + h * h).sqrt();+            let theta_corner = 2.0 * ((corner_rho / scale) / 2.0).atan();+            (theta_corner + to_radians(2.0)).clamp(to_radians(1.0), to_radians(179.0))+        };+        Projector {+            sin_center_alt,+            cos_center_alt,+            center_az: center_az_rad,+            scale,+            half_fov,+            screen_w,+            screen_h,+            rotation_rad,+        }+    }++    /// Mirrors `StereographicProjection.angularDist` including the `+3*PI` wrap.+    fn angular_dist(&self, az_rad: f64, alt_rad: f64) -> f64 {+        let sin_alt = alt_rad.sin();+        let cos_alt = alt_rad.cos();+        let d_az = {+            let it = az_rad - self.center_az;+            ((it + 3.0 * PI) % (2.0 * PI)) - PI+        };+        let cos_theta = self.sin_center_alt * sin_alt + self.cos_center_alt * cos_alt * d_az.cos();+        cos_theta.clamp(-1.0, 1.0).acos()+    }++    /// Mirrors `StereographicProjection.projectCore` (note the `+PI` wrap here,+    /// distinct from `angularDist`'s `+3*PI`).+    fn project_core(&self, az_rad: f64, alt_rad: f64, theta: f64) -> (f32, f32) {+        if theta < 1e-9 {+            return ((self.screen_w / 2.0) as f32, (self.screen_h / 2.0) as f32);+        }+        let rho = 2.0 * (theta / 2.0).tan() * self.scale;+        let sin_alt = alt_rad.sin();+        let cos_alt = alt_rad.cos();+        let d_az = {+            let it = az_rad - self.center_az;+            ((it + PI) % (2.0 * PI)) - PI+        };+        let sin_daz = d_az.sin();+        let cos_daz = d_az.cos();+        let phi = (sin_daz * cos_alt)+            .atan2(self.cos_center_alt * sin_alt - self.sin_center_alt * cos_alt * cos_daz);+        let x = rho * phi.sin();+        let y = rho * phi.cos();+        let cos_r = self.rotation_rad.cos();+        let sin_r = self.rotation_rad.sin();+        let xr = x * cos_r - y * sin_r;+        let yr = x * sin_r + y * cos_r;+        (+            (self.screen_w / 2.0 + xr) as f32,+            (self.screen_h / 2.0 + yr) as f32,+        )+    }++    /// Mirrors `StereographicProjection.project`: returns `None` when culled.+    pub fn project(&self, az_rad: f64, alt_rad: f64) -> Option<(f32, f32)> {+        let theta = self.angular_dist(az_rad, alt_rad);+        if theta > self.half_fov {+            return None;+        }+        Some(self.project_core(az_rad, alt_rad, theta))+    }+}++/// Batch stereographic projection. `altaz` is interleaved `[az0, alt0, ...]`;+/// returns interleaved `[x0, y0, x1, y1, ...]` in screen pixels, with both+/// components set to `f32::NAN` for any point `project` culls.+pub fn batch_project(+    altaz: &[f64],+    center_az_rad: f64,+    center_alt_rad: f64,+    fov_deg: f64,+    screen_w: f64,+    screen_h: f64,+    rotation_rad: f64,+) -> Vec<f32> {+    let p = Projector::new(+        center_az_rad,+        center_alt_rad,+        fov_deg,+        screen_w,+        screen_h,+        rotation_rad,+    );+    let n = altaz.len() / 2;+    let mut out = Vec::with_capacity(n * 2);+    for i in 0..n {+        let az = altaz[2 * i];+        let alt = altaz[2 * i + 1];+        match p.project(az, alt) {+            Some((x, y)) => {+                out.push(x);+                out.push(y);+            }+            None => {+                out.push(f32::NAN);+                out.push(f32::NAN);+            }+        }+    }+    out+}