This commit is contained in:
sagiferi
2026-10-24 13:20:55 +02:00
parent 93e06d148a
commit b33d1543fc
326 changed files with 20843 additions and 3 deletions
+201
View File
@@ -0,0 +1,201 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "adler2"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "crc32fast"
version = "1.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055"
dependencies = [
"cfg-if",
]
[[package]]
name = "fdeflate"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
dependencies = [
"simd-adler32",
]
[[package]]
name = "flate2"
version = "1.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
dependencies = [
"crc32fast",
"miniz_oxide 0.9.1",
"zlib-rs",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "miniz_oxide"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
dependencies = [
"adler2",
"simd-adler32",
]
[[package]]
name = "png"
version = "0.17.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
dependencies = [
"bitflags",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[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 = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "sfzenith-core"
version = "0.1.0"
dependencies = [
"crc32fast",
"png",
"serde",
"serde_json",
]
[[package]]
name = "simd-adler32"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "zlib-rs"
version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "sfzenith-core"
version = "0.1.0"
edition = "2021"
description = "Pure horizon-survey core: projection, FOV, horizon profile, NINA/Stellarium exporters. No I/O, no web-sys."
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json = "1"
png = "0.17"
crc32fast = "1"
+228
View File
@@ -0,0 +1,228 @@
//! Horizontal FOV estimate from two overlapping frames (NCC on a middle strip).
/// Average the middle 10% horizontal strip of an RGBA image into a 1D grayscale signal.
fn middle_strip_signal(rgba: &[u8], w: usize, h: usize) -> Vec<f64> {
let strip_start = h * 45 / 100;
let strip_end = (h * 55 / 100).max(strip_start + 1);
let strip_h = (strip_end - strip_start) as f64;
let mut row = vec![0.0f64; w];
for y in strip_start..strip_end {
for x in 0..w {
let idx = (y * w + x) * 4;
row[x] += 0.299 * rgba[idx] as f64
+ 0.587 * rgba[idx + 1] as f64
+ 0.114 * rgba[idx + 2] as f64;
}
}
for v in row.iter_mut() {
*v /= strip_h;
}
row
}
/// NCC: slide `b` over `a` to find the best positive offset where
/// a[offset..] correlates with b[..w-offset]. Returns (offset, ncc) or None.
fn best_shift(a: &[f64], b: &[f64]) -> Option<(usize, f64)> {
let w = a.len();
let min_overlap = w / 4;
let max_offset = w * 3 / 4;
let mut best_ncc = 0.3_f64; // minimum threshold
let mut best_offset = 0_usize;
for offset in 1..=max_offset {
let len = w - offset;
if len < min_overlap {
break;
}
let mean_a: f64 = a[offset..].iter().sum::<f64>() / len as f64;
let mean_b: f64 = b[..len].iter().sum::<f64>() / len as f64;
let mut num = 0.0_f64;
let mut den_a = 0.0_f64;
let mut den_b = 0.0_f64;
for i in 0..len {
let da = a[offset + i] - mean_a;
let db = b[i] - mean_b;
num += da * db;
den_a += da * da;
den_b += db * db;
}
let den = (den_a * den_b).sqrt();
if den > 1e-10 {
let ncc = num / den;
if ncc > best_ncc {
best_ncc = ncc;
best_offset = offset;
}
}
}
if best_offset == 0 {
None
} else {
Some((best_offset, best_ncc))
}
}
/// Calculate camera FOV from two overlapping frames and their heading difference.
/// Uses normalized cross-correlation on a horizontal strip from the middle of each image.
/// `heading_diff` may be given in either sign and across the 0/360 seam (e.g. 355°→5°);
/// frame order does not matter — both shift directions are searched.
/// Returns the estimated horizontal FOV in degrees (valid range 20–120), or -1.0 on failure.
pub fn calculate_fov(
rgba1: &[u8], w1: u32, h1: u32,
rgba2: &[u8], w2: u32, h2: u32,
heading_diff: f64,
) -> f64 {
if w1 != w2 || h1 != h2 || w1 == 0 || h1 == 0 {
return -1.0;
}
// Circular heading difference: 350°→10° is 20°, not −340°
let delta = {
let d = heading_diff.rem_euclid(360.0);
if d > 180.0 { 360.0 - d } else { d }
};
if delta < 1.0 {
return -1.0;
}
let w = w1 as usize;
let h = h1 as usize;
if rgba1.len() < w * h * 4 || rgba2.len() < w * h * 4 {
return -1.0;
}
let row1 = middle_strip_signal(rgba1, w, h);
let row2 = middle_strip_signal(rgba2, w, h);
// Rotation direction is unknown after circular normalization: try both orders
let fwd = best_shift(&row1, &row2);
let rev = best_shift(&row2, &row1);
let best = match (fwd, rev) {
(Some(f), Some(r)) => Some(if f.1 >= r.1 { f } else { r }),
(f, r) => f.or(r),
};
let Some((offset, _)) = best else {
return -1.0;
};
// Pure rotation by Δ shifts the image center by ≈ 2·f·tan(Δ/2) pixels,
// so focal length f = offset / (2·tan(Δ/2)) and FOV = 2·atan(w / 2f).
let focal_px = offset as f64 / (2.0 * (delta / 2.0).to_radians().tan());
let fov = 2.0 * ((w as f64) / (2.0 * focal_px)).atan().to_degrees();
if !(20.0..=120.0).contains(&fov) {
return -1.0;
}
fov
}
#[cfg(test)]
mod tests {
use super::calculate_fov;
const W: usize = 400;
const H: usize = 100;
/// Deterministic pseudo-random column brightness (LCG), same for every row.
fn column_value(x: i64) -> u8 {
let mut s = (x as u64).wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
s ^= s >> 33;
(s % 256) as u8
}
/// Build an RGBA image whose columns show the world pattern shifted by `shift` pixels
/// (positive shift = camera rotated right, scene moved left).
fn synthetic_frame(shift: i64) -> Vec<u8> {
let mut img = vec![0u8; W * H * 4];
for y in 0..H {
for x in 0..W {
let v = column_value(x as i64 + shift);
let idx = (y * W + x) * 4;
img[idx] = v;
img[idx + 1] = v;
img[idx + 2] = v;
img[idx + 3] = 255;
}
}
img
}
/// Pixel shift produced by rotating a camera of the given FOV by `delta` degrees.
fn shift_for(fov_deg: f64, delta_deg: f64) -> i64 {
let focal = W as f64 / (2.0 * (fov_deg / 2.0).to_radians().tan());
(2.0 * focal * (delta_deg / 2.0).to_radians().tan()).round() as i64
}
fn expected_fov_from_shift(shift: i64, delta_deg: f64) -> f64 {
let focal = shift as f64 / (2.0 * (delta_deg / 2.0).to_radians().tan());
2.0 * ((W as f64) / (2.0 * focal)).atan().to_degrees()
}
#[test]
fn recovers_known_fov() {
let delta = 10.0;
let shift = shift_for(60.0, delta);
let a = synthetic_frame(0);
let b = synthetic_frame(shift);
let fov = calculate_fov(&a, W as u32, H as u32, &b, W as u32, H as u32, delta);
let expected = expected_fov_from_shift(shift, delta);
assert!((fov - expected).abs() < 1.0, "fov={fov}, expected≈{expected}");
}
#[test]
fn handles_circular_heading_difference() {
// 355° → 5° is a 10° rotation, naive diff is −350°
let delta = 10.0;
let shift = shift_for(60.0, delta);
let a = synthetic_frame(0);
let b = synthetic_frame(shift);
let fov = calculate_fov(&a, W as u32, H as u32, &b, W as u32, H as u32, -350.0);
let expected = expected_fov_from_shift(shift, delta);
assert!((fov - expected).abs() < 1.0, "fov={fov}, expected≈{expected}");
}
#[test]
fn frame_order_does_not_matter() {
let delta = 10.0;
let shift = shift_for(60.0, delta);
let a = synthetic_frame(0);
let b = synthetic_frame(shift);
let fov = calculate_fov(&b, W as u32, H as u32, &a, W as u32, H as u32, delta);
let expected = expected_fov_from_shift(shift, delta);
assert!((fov - expected).abs() < 1.0, "fov={fov}, expected≈{expected}");
}
#[test]
fn rejects_mismatched_sizes_and_tiny_rotation() {
let a = synthetic_frame(0);
let b = synthetic_frame(10);
assert_eq!(calculate_fov(&a, W as u32, H as u32, &b, W as u32, (H - 1) as u32, 10.0), -1.0);
assert_eq!(calculate_fov(&a, W as u32, H as u32, &b, W as u32, H as u32, 0.5), -1.0);
assert_eq!(calculate_fov(&a, W as u32, H as u32, &b, W as u32, H as u32, 360.0), -1.0);
}
#[test]
fn rejects_textureless_frames() {
let flat = vec![128u8; W * H * 4];
assert_eq!(
calculate_fov(&flat, W as u32, H as u32, &flat, W as u32, H as u32, 10.0),
-1.0
);
}
#[test]
fn rejects_implausible_fov() {
// A 1-pixel shift for a 30° rotation implies an absurdly wide FOV
let a = synthetic_frame(0);
let b = synthetic_frame(1);
let fov = calculate_fov(&a, W as u32, H as u32, &b, W as u32, H as u32, 30.0);
assert_eq!(fov, -1.0, "fov={fov}");
}
}
+141
View File
@@ -0,0 +1,141 @@
//! N.I.N.A. custom horizon (`.hrz`) export and import. Format: docs/FORMATS.md.
use crate::profile::{HorizonProfile, ProfileError};
use std::fmt::Write as _;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HrzOptions {
/// Added to the detected edge (default +2°): keeps targets clear of tree
/// tips and absorbs compass error.
pub margin_deg: f64,
/// User north offset, applied before writing (see `HorizonProfile::rotated`).
pub north_offset_deg: f64,
}
impl Default for HrzOptions {
fn default() -> Self {
Self { margin_deg: 2.0, north_offset_deg: 0.0 }
}
}
/// Format an altitude with one decimal and a `.` separator, never "-0.0".
pub(crate) fn fmt_alt(v: f64) -> String {
let s = format!("{v:.1}");
if s == "-0.0" { "0.0".to_string() } else { s }
}
/// Write a `.hrz`: header `# Az Alt`, then 0..=360 in 1° steps (360 repeats 0
/// to close the loop), altitude = edge + margin clamped to [0, 90].
pub fn export_hrz(profile: &HorizonProfile, opts: HrzOptions) -> String {
let p = profile.rotated(opts.north_offset_deg);
let mut out = String::with_capacity(361 * 8);
out.push_str("# Az Alt\n");
for az in 0..=360i64 {
let alt = (p.at(az) + opts.margin_deg).clamp(0.0, 90.0);
let _ = writeln!(out, "{az} {}", fmt_alt(alt));
}
out
}
#[derive(Debug, Clone, PartialEq)]
pub enum HrzError {
/// Line number (1-based) and its content.
BadLine(usize, String),
/// Fewer than two azimuth/altitude pairs.
TooFewPoints,
Profile(ProfileError),
}
impl std::fmt::Display for HrzError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
HrzError::BadLine(n, l) => write!(f, "line {n}: cannot read \"{l}\""),
HrzError::TooFewPoints => write!(f, "a horizon file needs at least 2 points"),
HrzError::Profile(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for HrzError {}
fn parse_num(tok: &str) -> Option<f64> {
// Tolerate comma decimals from non-English Windows locales.
tok.replace(',', ".").parse::<f64>().ok().filter(|v| v.is_finite())
}
/// Read a `.hrz` (or Stellarium `azDeg_altDeg` horizon list) into a 1° profile.
/// `#` comments and blank lines are skipped; extra columns are ignored.
/// The values are taken as-is (an imported NINA file usually already includes
/// its author's safety margin).
pub fn parse_hrz(text: &str) -> Result<HorizonProfile, HrzError> {
let mut points = Vec::new();
for (i, raw) in text.lines().enumerate() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let mut toks = line.split_whitespace();
let pair = (toks.next().and_then(parse_num), toks.next().and_then(parse_num));
match pair {
(Some(az), Some(alt)) => points.push((az, alt)),
_ => return Err(HrzError::BadLine(i + 1, raw.to_string())),
}
}
if points.len() < 2 {
return Err(HrzError::TooFewPoints);
}
HorizonProfile::from_points(&points).map_err(HrzError::Profile)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn writes_361_lines_with_margin_and_clamp() {
let mut alt = vec![10.0; 360];
alt[0] = -3.0;
alt[1] = 89.5;
let p = HorizonProfile::from_altitudes(alt).unwrap();
let s = export_hrz(&p, HrzOptions::default());
let lines: Vec<&str> = s.lines().collect();
assert_eq!(lines.len(), 362);
assert_eq!(lines[0], "# Az Alt");
assert_eq!(lines[1], "0 0.0");
assert_eq!(lines[2], "1 90.0");
assert_eq!(lines[3], "2 12.0");
assert_eq!(lines[361], "360 0.0");
assert!(s.ends_with('\n'));
}
#[test]
fn north_offset_is_applied() {
let mut alt = vec![0.0; 360];
alt[10] = 20.0;
let p = HorizonProfile::from_altitudes(alt).unwrap();
let s = export_hrz(&p, HrzOptions { margin_deg: 0.0, north_offset_deg: 5.0 });
assert!(s.contains("\n15 20.0\n"));
}
#[test]
fn parses_comments_commas_and_sparse_points() {
let p = parse_hrz("# Az Alt\n\n0 10\n180\t30,5 extra\n").unwrap();
assert_eq!(p.at(0), 10.0);
assert_eq!(p.at(180), 30.5);
assert!((p.at(90) - 20.25).abs() < 1e-9);
}
#[test]
fn rejects_garbage() {
assert_eq!(parse_hrz("0 10\nfoo bar\n"), Err(HrzError::BadLine(2, "foo bar".into())));
assert_eq!(parse_hrz("# only\n0 10\n"), Err(HrzError::TooFewPoints));
}
#[test]
fn roundtrip_without_margin() {
let p = HorizonProfile::from_altitudes((0..360).map(|i| (i % 37) as f64 * 0.5).collect())
.unwrap();
let s = export_hrz(&p, HrzOptions { margin_deg: 0.0, north_offset_deg: 0.0 });
assert_eq!(parse_hrz(&s).unwrap(), p);
}
}
+21
View File
@@ -0,0 +1,21 @@
//! sfzenith core: pure, deterministic horizon-survey logic.
//!
//! No I/O, no clocks, no randomness, no web-sys. The same code is compiled to
//! wasm (via the `wasm/` adapter crate) and tested natively with `cargo test`.
//!
//! Conventions (see docs/FORMATS.md):
//! * Azimuth: degrees, 0 = true north, clockwise (90 = east).
//! * Altitude: degrees above the mathematical horizon.
//! * Profiles are stored in the *measured* frame; exporters apply the user's
//! north offset, so the offset can change without re-running detection.
pub mod fov;
pub mod hrz;
pub mod profile;
pub mod projection;
pub mod session;
pub mod skymask;
pub mod stellarium;
pub mod zip;
pub use profile::HorizonProfile;
+217
View File
@@ -0,0 +1,217 @@
//! Horizon profile: altitude of the sky edge for every whole degree of azimuth.
use std::fmt;
/// Number of samples in a profile: one per degree, azimuth 0..=359.
pub const STEPS: usize = 360;
#[derive(Debug, Clone, PartialEq)]
pub enum ProfileError {
/// No usable points were given.
Empty,
/// A value was NaN or infinite.
NotFinite,
/// A dense profile did not have exactly 360 values.
WrongLength(usize),
}
impl fmt::Display for ProfileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ProfileError::Empty => write!(f, "no horizon points"),
ProfileError::NotFinite => write!(f, "horizon contains a non-finite value"),
ProfileError::WrongLength(n) => write!(f, "expected {STEPS} altitudes, got {n}"),
}
}
}
impl std::error::Error for ProfileError {}
/// Altitude (deg) of the sky edge at azimuth 0°, 1°, … 359°.
#[derive(Debug, Clone, PartialEq)]
pub struct HorizonProfile {
alt: Vec<f64>,
}
impl HorizonProfile {
/// A flat profile at `alt_deg`.
pub fn flat(alt_deg: f64) -> Self {
Self { alt: vec![alt_deg; STEPS] }
}
/// Wrap an existing 1°-step profile (index = azimuth).
pub fn from_altitudes(alt: Vec<f64>) -> Result<Self, ProfileError> {
if alt.len() != STEPS {
return Err(ProfileError::WrongLength(alt.len()));
}
if alt.iter().any(|v| !v.is_finite()) {
return Err(ProfileError::NotFinite);
}
Ok(Self { alt })
}
/// Build a profile from sparse (azimuth, altitude) points by linear
/// interpolation around the circle (the 360°/0° seam is handled).
/// Points at the same azimuth (a vertical edge) resolve to the higher one,
/// so the result never cuts into an obstruction.
pub fn from_points(points: &[(f64, f64)]) -> Result<Self, ProfileError> {
if points.is_empty() {
return Err(ProfileError::Empty);
}
if points.iter().any(|(a, b)| !a.is_finite() || !b.is_finite()) {
return Err(ProfileError::NotFinite);
}
let mut pts: Vec<(f64, f64)> =
points.iter().map(|&(az, alt)| (az.rem_euclid(360.0), alt)).collect();
pts.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)));
let alt = (0..STEPS).map(|i| interp_circular(&pts, i as f64)).collect();
Ok(Self { alt })
}
/// Altitudes indexed by whole azimuth degree.
pub fn altitudes(&self) -> &[f64] {
&self.alt
}
/// Altitude at a whole azimuth degree (any integer, wrapped).
pub fn at(&self, az_deg: i64) -> f64 {
self.alt[az_deg.rem_euclid(STEPS as i64) as usize]
}
/// Linearly interpolated altitude at any azimuth.
pub fn sample(&self, az_deg: f64) -> f64 {
let a = az_deg.rem_euclid(360.0);
let i0 = a.floor();
let t = a - i0;
let v0 = self.at(i0 as i64);
let v1 = self.at(i0 as i64 + 1);
v0 + (v1 - v0) * t
}
/// Highest altitude in the profile.
pub fn max_alt(&self) -> f64 {
self.alt.iter().copied().fold(f64::NEG_INFINITY, f64::max)
}
/// Rotate the profile by a north offset: a feature measured at azimuth A
/// ends up at A + `offset_deg`.
pub fn rotated(&self, offset_deg: f64) -> Self {
if offset_deg == 0.0 {
return self.clone();
}
let alt = (0..STEPS).map(|i| self.sample(i as f64 - offset_deg)).collect();
Self { alt }
}
/// Circular median filter over ±`radius_deg` whole degrees
/// (0 = unchanged; 1 or 2 is the "light"/"strong" smoothing in the spec).
pub fn smoothed(&self, radius_deg: usize) -> Self {
if radius_deg == 0 {
return self.clone();
}
let r = radius_deg as i64;
let alt = (0..STEPS as i64)
.map(|i| {
let mut w: Vec<f64> = (-r..=r).map(|d| self.at(i + d)).collect();
w.sort_by(f64::total_cmp);
w[w.len() / 2]
})
.collect();
Self { alt }
}
}
/// Interpolate sorted, wrapped points at azimuth `az` in [0, 360).
fn interp_circular(pts: &[(f64, f64)], az: f64) -> f64 {
let n = pts.len();
if n == 1 {
return pts[0].1;
}
// Exact hits: take the highest point at this azimuth (vertical edges).
let exact = pts
.iter()
.filter(|p| (p.0 - az).abs() < 1e-9)
.map(|p| p.1)
.fold(f64::NEG_INFINITY, f64::max);
if exact.is_finite() {
return exact;
}
// Segment (prev, next) around `az`, wrapping across the seam.
let next_idx = pts.iter().position(|p| p.0 > az).unwrap_or(0);
let prev_idx = if next_idx == 0 { n - 1 } else { next_idx - 1 };
let (a0, v0) = pts[prev_idx];
let (a1, v1) = pts[next_idx];
let span = (a1 - a0).rem_euclid(360.0);
if span < 1e-9 {
return v0.max(v1);
}
let t = (az - a0).rem_euclid(360.0) / span;
v0 + (v1 - v0) * t
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interpolates_across_the_seam() {
let p = HorizonProfile::from_points(&[(350.0, 10.0), (10.0, 30.0)]).unwrap();
assert!((p.at(0) - 20.0).abs() < 1e-9);
assert!((p.at(355) - 15.0).abs() < 1e-9);
assert!((p.at(5) - 25.0).abs() < 1e-9);
// The long way round (10 → 350) is interpolated too.
assert!((p.at(180) - 20.0).abs() < 1e-9);
}
#[test]
fn single_point_is_flat() {
let p = HorizonProfile::from_points(&[(123.0, 7.5)]).unwrap();
assert!(p.altitudes().iter().all(|&v| v == 7.5));
}
#[test]
fn duplicate_azimuth_takes_the_higher_point() {
let p = HorizonProfile::from_points(&[(0.0, 0.0), (90.0, 5.0), (90.0, 40.0), (180.0, 0.0)])
.unwrap();
assert_eq!(p.at(90), 40.0);
}
#[test]
fn rejects_bad_input() {
assert_eq!(HorizonProfile::from_points(&[]), Err(ProfileError::Empty));
assert_eq!(
HorizonProfile::from_points(&[(0.0, f64::NAN)]),
Err(ProfileError::NotFinite)
);
assert_eq!(
HorizonProfile::from_altitudes(vec![0.0; 10]),
Err(ProfileError::WrongLength(10))
);
}
#[test]
fn rotation_moves_features_clockwise() {
let mut alt = vec![0.0; STEPS];
alt[100] = 30.0;
let p = HorizonProfile::from_altitudes(alt).unwrap();
let r = p.rotated(2.0);
assert_eq!(r.at(102), 30.0);
assert_eq!(r.at(100), 0.0);
let half = p.rotated(0.5);
assert!((half.at(100) - 15.0).abs() < 1e-9);
assert!((half.at(101) - 15.0).abs() < 1e-9);
// Wraps across north.
let w = p.rotated(-101.0);
assert_eq!(w.at(359), 30.0);
}
#[test]
fn median_removes_single_spikes() {
let mut alt = vec![10.0; STEPS];
alt[0] = 80.0;
let p = HorizonProfile::from_altitudes(alt).unwrap();
assert_eq!(p.smoothed(1).at(0), 10.0);
assert_eq!(p.smoothed(0).at(0), 80.0);
}
}
+423
View File
@@ -0,0 +1,423 @@
//! Gnomonic (pinhole camera) → equirectangular reprojection.
//!
//! Pure Rust, no web-sys: unit-tested natively with `cargo test`, compiled to
//! wasm for the browser. Conventions (W3C DeviceOrientation):
//! * Earth frame: X = east, Y = north, Z = up.
//! * Device frame: x = right of screen, y = top of screen, z = out of screen;
//! the rear camera looks along −z.
//! * v_earth = R · v_device with R = Rz(alpha)·Rx(beta)·Ry(gamma).
//! Composing R from the raw angles is exact even at beta≈90 (gimbal lock
//! only makes the *decomposition* ambiguous), which is why the full matrix
//! — not scalar heading/tilt — must drive the projection (roll included).
//! * Azimuth: 0° = north, clockwise (east = 90°). Elevation: 0° = horizon.
pub type Mat3 = [[f64; 3]; 3];
fn mat_mul(a: &Mat3, b: &Mat3) -> Mat3 {
let mut m = [[0.0; 3]; 3];
for (i, row) in m.iter_mut().enumerate() {
for (j, cell) in row.iter_mut().enumerate() {
*cell = (0..3).map(|k| a[i][k] * b[k][j]).sum();
}
}
m
}
fn mat_vec(m: &Mat3, v: [f64; 3]) -> [f64; 3] {
[
m[0][0] * v[0] + m[0][1] * v[1] + m[0][2] * v[2],
m[1][0] * v[0] + m[1][1] * v[1] + m[1][2] * v[2],
m[2][0] * v[0] + m[2][1] * v[1] + m[2][2] * v[2],
]
}
/// v · Rᵀ, i.e. transform an earth vector into the device frame.
fn mat_t_vec(m: &Mat3, v: [f64; 3]) -> [f64; 3] {
[
m[0][0] * v[0] + m[1][0] * v[1] + m[2][0] * v[2],
m[0][1] * v[0] + m[1][1] * v[1] + m[2][1] * v[2],
m[0][2] * v[0] + m[1][2] * v[1] + m[2][2] * v[2],
]
}
fn rz(deg: f64) -> Mat3 {
let (s, c) = deg.to_radians().sin_cos();
[[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
}
fn rx(deg: f64) -> Mat3 {
let (s, c) = deg.to_radians().sin_cos();
[[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
}
fn ry(deg: f64) -> Mat3 {
let (s, c) = deg.to_radians().sin_cos();
[[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
}
/// Device→earth rotation from W3C angles, with screen-orientation correction:
/// R_total = Rz(alpha)·Rx(beta)·Ry(gamma)·Rz(−screen_angle).
/// `screen_angle` is `screen.orientation.angle` (0 in portrait).
pub fn rotation_matrix(alpha_deg: f64, beta_deg: f64, gamma_deg: f64, screen_angle_deg: f64) -> Mat3 {
let r = mat_mul(&mat_mul(&rz(alpha_deg), &rx(beta_deg)), &ry(gamma_deg));
if screen_angle_deg == 0.0 {
r
} else {
mat_mul(&r, &rz(-screen_angle_deg))
}
}
/// Camera boresight azimuth (0°=N, clockwise, 0..360) and elevation in degrees.
pub fn camera_az_el(r: &Mat3) -> (f64, f64) {
let d = mat_vec(r, [0.0, 0.0, -1.0]); // camera looks along −z_device
let az = d[0].atan2(d[1]).to_degrees().rem_euclid(360.0); // atan2(east, north)
let el = d[2].asin().to_degrees();
(az, el)
}
/// iOS: derive an absolute-equivalent alpha from `webkitCompassHeading` so the
/// camera boresight azimuth equals the compass value while keeping measured
/// beta/gamma. Exact inversion of the boresight azimuth formula; falls back to
/// `360 − H` when the boresight is near-vertical (azimuth ill-defined there).
pub fn derive_ios_alpha(compass_heading_deg: f64, beta_deg: f64, gamma_deg: f64) -> f64 {
let (sb, _) = beta_deg.to_radians().sin_cos();
let (sg, cg) = gamma_deg.to_radians().sin_cos();
let num = -sg;
let den = sb * cg;
if num.abs() < 1e-9 && den.abs() < 1e-9 {
return (360.0 - compass_heading_deg).rem_euclid(360.0);
}
(num.atan2(den).to_degrees() - compass_heading_deg).rem_euclid(360.0)
}
pub struct PatchGeom {
pub x: i32,
pub y: i32,
pub w: u32,
pub h: u32,
}
/// Wrap an angle difference into (−180, 180].
fn wrap180(deg: f64) -> f64 {
let d = deg.rem_euclid(360.0);
if d > 180.0 { d - 360.0 } else { d }
}
/// Project the source pixel (u,v) as a ray in device space.
fn border_ray(u: f64, v: f64, cx: f64, cy: f64, f: f64) -> [f64; 3] {
[(u - cx) / f, -(v - cy) / f, -1.0]
}
fn normalize(v: [f64; 3]) -> [f64; 3] {
let n = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
[v[0] / n, v[1] / n, v[2] / n]
}
/// Does earth-direction `dir` land inside the source frame?
fn earth_dir_in_frame(r: &Mat3, dir: [f64; 3], cx: f64, cy: f64, f: f64, src_w: f64, src_h: f64) -> bool {
let d = mat_t_vec(r, dir);
if d[2] >= -1e-9 {
return false;
}
let u = cx + f * (d[0] / -d[2]);
let v = cy - f * (d[1] / -d[2]);
u >= 0.0 && u <= src_w - 1.0 && v >= 0.0 && v <= src_h - 1.0
}
/// Reproject a pinhole-camera RGBA frame into an equirectangular patch.
///
/// The strip maps azimuth 0..360 to x=0..strip_w and elevation
/// elev_max..elev_min to y=0..strip_h (equal deg/px on both axes assumed by
/// the caller, but not required). Returns the patch geometry (x normalized to
/// [0, strip_w); x+w may exceed strip_w — the caller composites the overflow
/// at x−strip_w) and its RGBA data (alpha 0 outside the source frame).
pub fn project_frame_core(
rgba: &[u8],
src_w: u32,
src_h: u32,
r: &Mat3,
h_fov_deg: f64,
strip_w: u32,
strip_h: u32,
elev_min_deg: f64,
elev_max_deg: f64,
) -> Option<(PatchGeom, Vec<u8>)> {
if src_w == 0 || src_h == 0 || strip_w == 0 || strip_h == 0 {
return None;
}
if !(1.0..=179.0).contains(&h_fov_deg) || elev_max_deg <= elev_min_deg {
return None;
}
if rgba.len() < (src_w * src_h * 4) as usize {
return None;
}
let sw = src_w as f64;
let sh = src_h as f64;
let f = (sw / 2.0) / (h_fov_deg.to_radians() / 2.0).tan();
let cx = (sw - 1.0) / 2.0;
let cy = (sh - 1.0) / 2.0;
let px_per_deg_x = strip_w as f64 / 360.0;
let elev_range = elev_max_deg - elev_min_deg;
let px_per_deg_y = strip_h as f64 / elev_range;
// --- Bounding box: project the source border into (az, el) ---
let (az_c, _) = camera_az_el(r);
let mut min_daz = f64::MAX;
let mut max_daz = f64::MIN;
let mut min_el = f64::MAX;
let mut max_el = f64::MIN;
const EDGE_SAMPLES: usize = 17;
let mut consider = |u: f64, v: f64| {
let d = normalize(mat_vec(r, border_ray(u, v, cx, cy, f)));
let az = d[0].atan2(d[1]).to_degrees().rem_euclid(360.0);
let el = d[2].asin().to_degrees();
let daz = wrap180(az - az_c);
if daz < min_daz { min_daz = daz; }
if daz > max_daz { max_daz = daz; }
if el < min_el { min_el = el; }
if el > max_el { max_el = el; }
};
for i in 0..EDGE_SAMPLES {
let t = i as f64 / (EDGE_SAMPLES - 1) as f64;
consider(t * (sw - 1.0), 0.0);
consider(t * (sw - 1.0), sh - 1.0);
consider(0.0, t * (sh - 1.0));
consider(sw - 1.0, t * (sh - 1.0));
}
// Zenith/nadir inside the frame → full azimuth span
let zenith_in = earth_dir_in_frame(r, [0.0, 0.0, 1.0], cx, cy, f, sw, sh);
let nadir_in = earth_dir_in_frame(r, [0.0, 0.0, -1.0], cx, cy, f, sw, sh);
if zenith_in {
max_el = 90.0;
}
if nadir_in {
min_el = -90.0;
}
// Clamp elevation to the strip's range
let el_lo = min_el.max(elev_min_deg);
let el_hi = max_el.min(elev_max_deg);
if el_lo >= el_hi {
return None;
}
const MARGIN_PX: f64 = 2.0;
let (px0, pw) = if zenith_in || nadir_in {
(0i32, strip_w)
} else {
let x_lo = (az_c + min_daz) * px_per_deg_x - MARGIN_PX;
let x_hi = (az_c + max_daz) * px_per_deg_x + MARGIN_PX;
let w = ((x_hi - x_lo).ceil() as u32).min(strip_w);
let x0 = (x_lo.floor() as i64).rem_euclid(strip_w as i64) as i32;
(x0, w)
};
let y0 = (((elev_max_deg - el_hi) * px_per_deg_y - MARGIN_PX).floor() as i64).max(0) as i32;
let y1 = (((elev_max_deg - el_lo) * px_per_deg_y + MARGIN_PX).ceil() as i64).min(strip_h as i64) as i32;
if y1 <= y0 {
return None;
}
let ph = (y1 - y0) as u32;
// --- Inverse-map every patch pixel ---
let mut out = vec![0u8; (pw * ph * 4) as usize];
// Precompute per-column azimuth trig and per-row elevation trig
let mut col_trig = Vec::with_capacity(pw as usize);
for i in 0..pw {
let az = ((px0 as f64 + i as f64 + 0.5) / px_per_deg_x).to_radians();
col_trig.push(az.sin_cos());
}
let mut row_trig = Vec::with_capacity(ph as usize);
for j in 0..ph {
let el = (elev_max_deg - (y0 as f64 + j as f64 + 0.5) / px_per_deg_y).to_radians();
row_trig.push(el.sin_cos());
}
for j in 0..ph as usize {
let (sel, cel) = row_trig[j];
for i in 0..pw as usize {
let (saz, caz) = col_trig[i];
let v_earth = [cel * saz, cel * caz, sel];
let d = mat_t_vec(r, v_earth);
if d[2] >= -1e-9 {
continue; // behind the camera → transparent
}
let u = cx + f * (d[0] / -d[2]);
let v = cy - f * (d[1] / -d[2]);
if u < 0.0 || u > sw - 1.0 || v < 0.0 || v > sh - 1.0 {
continue;
}
// Bilinear sample
let u0 = u.floor();
let v0 = v.floor();
let fu = u - u0;
let fv = v - v0;
let u0 = u0 as usize;
let v0 = v0 as usize;
let u1 = (u0 + 1).min(src_w as usize - 1);
let v1 = (v0 + 1).min(src_h as usize - 1);
let idx = |x: usize, y: usize| (y * src_w as usize + x) * 4;
let (i00, i10, i01, i11) = (idx(u0, v0), idx(u1, v0), idx(u0, v1), idx(u1, v1));
let o = (j * pw as usize + i) * 4;
for c in 0..3 {
let top = rgba[i00 + c] as f64 * (1.0 - fu) + rgba[i10 + c] as f64 * fu;
let bot = rgba[i01 + c] as f64 * (1.0 - fu) + rgba[i11 + c] as f64 * fu;
out[o + c] = (top * (1.0 - fv) + bot * fv).round() as u8;
}
out[o + 3] = 255;
}
}
Some((PatchGeom { x: px0, y: y0, w: pw, h: ph }, out))
}
#[cfg(test)]
mod tests {
use super::*;
const STRIP_W: u32 = 3072;
const STRIP_H: u32 = 1024;
const ELEV_MIN: f64 = -30.0;
const ELEV_MAX: f64 = 90.0;
const PX_PER_DEG: f64 = STRIP_W as f64 / 360.0; // 8.533…
fn solid_frame(w: u32, h: u32, rgb: [u8; 3]) -> Vec<u8> {
let mut v = vec![0u8; (w * h * 4) as usize];
for px in v.chunks_exact_mut(4) {
px[0] = rgb[0];
px[1] = rgb[1];
px[2] = rgb[2];
px[3] = 255;
}
v
}
fn assert_close(a: f64, b: f64, tol: f64, msg: &str) {
assert!((a - b).abs() < tol, "{msg}: {a} vs {b}");
}
#[test]
fn conventions_locked() {
// alpha=30, beta=90 (upright): heading should be 360-30=330
let (az, el) = camera_az_el(&rotation_matrix(30.0, 90.0, 0.0, 0.0));
assert_close(az, 330.0, 1e-9, "azimuth");
assert_close(el, 0.0, 1e-9, "elevation");
// beta=110: camera tilted 20° above horizon
let (_, el) = camera_az_el(&rotation_matrix(0.0, 110.0, 0.0, 0.0));
assert_close(el, 20.0, 1e-9, "tilt-up elevation");
}
#[test]
fn ios_alpha_roundtrip() {
// gamma=0, beta=90: exact naive form
assert_close(derive_ios_alpha(70.0, 90.0, 0.0), 290.0, 1e-9, "naive");
// rolled orientation: boresight azimuth must equal the compass value
let h = 123.0;
let alpha = derive_ios_alpha(h, 75.0, 20.0);
let (az, _) = camera_az_el(&rotation_matrix(alpha, 75.0, 20.0, 0.0));
assert_close(az, h, 1e-6, "roundtrip azimuth");
}
#[test]
fn center_pixel_lands_at_boresight() {
let (w, h) = (64u32, 48u32);
let rgba = solid_frame(w, h, [10, 200, 30]);
// alpha=270, beta=90 → azimuth 90, elevation 0
let r = rotation_matrix(270.0, 90.0, 0.0, 0.0);
let (geom, data) =
project_frame_core(&rgba, w, h, &r, 60.0, STRIP_W, STRIP_H, ELEV_MIN, ELEV_MAX).unwrap();
// strip position of (az 90, el 0)
let tx = (90.0 * PX_PER_DEG) as i32;
let ty = ((ELEV_MAX - 0.0) / (ELEV_MAX - ELEV_MIN) * STRIP_H as f64) as i32;
let lx = tx - geom.x;
let ly = ty - geom.y;
assert!(lx >= 0 && (lx as u32) < geom.w && ly >= 0 && (ly as u32) < geom.h, "center in patch");
let o = ((ly as u32 * geom.w + lx as u32) * 4) as usize;
assert_eq!(&data[o..o + 4], &[10, 200, 30, 255], "boresight pixel color");
}
#[test]
fn horizon_width_matches_fov() {
let (w, h) = (128u32, 96u32);
let rgba = solid_frame(w, h, [255, 0, 0]);
let fov = 50.0;
let r = rotation_matrix(180.0, 90.0, 0.0, 0.0); // az 180, el 0
let (geom, data) =
project_frame_core(&rgba, w, h, &r, fov, STRIP_W, STRIP_H, ELEV_MIN, ELEV_MAX).unwrap();
// measure opaque width along the horizon row
let horizon_y = ((ELEV_MAX / (ELEV_MAX - ELEV_MIN)) * STRIP_H as f64) as i32 - geom.y;
assert!(horizon_y >= 0 && (horizon_y as u32) < geom.h);
let mut opaque = 0;
for i in 0..geom.w {
if data[((horizon_y as u32 * geom.w + i) * 4 + 3) as usize] == 255 {
opaque += 1;
}
}
let expected = fov * PX_PER_DEG;
assert_close(opaque as f64, expected, 4.0, "horizon opaque width");
}
#[test]
fn roll_inverts_patch_aspect() {
let (w, h) = (120u32, 60u32); // wide frame
let rgba = solid_frame(w, h, [0, 0, 255]);
let fov = 40.0;
let upright = rotation_matrix(0.0, 90.0, 0.0, 0.0);
// (alpha=90, beta=0, gamma=-90): upright facing north, rolled 90°
let rolled = rotation_matrix(90.0, 0.0, -90.0, 0.0);
let (g1, _) =
project_frame_core(&rgba, w, h, &upright, fov, STRIP_W, STRIP_H, ELEV_MIN, ELEV_MAX).unwrap();
let (g2, _) =
project_frame_core(&rgba, w, h, &rolled, fov, STRIP_W, STRIP_H, ELEV_MIN, ELEV_MAX).unwrap();
assert!(g1.w > g1.h, "upright wide frame: patch wider than tall");
assert!(g2.h > g2.w, "rolled 90°: patch taller than wide");
let (az, el) = camera_az_el(&rolled);
assert_close(az, 0.0, 1e-6, "rolled boresight az");
assert_close(el, 0.0, 1e-6, "rolled boresight el");
}
#[test]
fn outside_frame_is_transparent() {
let (w, h) = (64u32, 48u32);
let rgba = solid_frame(w, h, [9, 9, 9]);
let r = rotation_matrix(0.0, 90.0, 0.0, 0.0);
let (geom, data) =
project_frame_core(&rgba, w, h, &r, 45.0, STRIP_W, STRIP_H, ELEV_MIN, ELEV_MAX).unwrap();
// corners of the (margin-padded) patch bbox lie outside the projected frame
assert_eq!(data[3], 0, "top-left corner transparent");
let last = ((geom.h - 1) * geom.w + (geom.w - 1)) as usize * 4 + 3;
assert_eq!(data[last], 0, "bottom-right corner transparent");
// interior (patch center) opaque
let mid = ((geom.h / 2) * geom.w + geom.w / 2) as usize * 4 + 3;
assert_eq!(data[mid], 255, "center opaque");
}
#[test]
fn wraparound_near_north() {
let (w, h) = (64u32, 48u32);
let rgba = solid_frame(w, h, [1, 2, 3]);
let r = rotation_matrix(5.0, 90.0, 0.0, 0.0); // azimuth 355
let (geom, _) =
project_frame_core(&rgba, w, h, &r, 40.0, STRIP_W, STRIP_H, ELEV_MIN, ELEV_MAX).unwrap();
assert!(geom.x >= 0 && (geom.x as u32) < STRIP_W, "x normalized");
assert!(geom.x as u32 + geom.w > STRIP_W, "patch crosses the 0/360 seam");
}
#[test]
fn zenith_frame_spans_full_width() {
let (w, h) = (64u32, 64u32);
let rgba = solid_frame(w, h, [7, 7, 7]);
// beta=180: camera points straight up
let r = rotation_matrix(0.0, 180.0, 0.0, 0.0);
let (geom, _) =
project_frame_core(&rgba, w, h, &r, 60.0, STRIP_W, STRIP_H, ELEV_MIN, ELEV_MAX).unwrap();
assert_eq!(geom.w, STRIP_W, "full azimuth span");
assert_eq!(geom.y, 0, "starts at the zenith edge");
}
}
+159
View File
@@ -0,0 +1,159 @@
//! Recorded session bundle (`session.json` + `sensors.jsonl` + frames/).
//! The phone records it; the desktop replays it through the same core.
//! Shape: docs/ARCHITECTURE.md and docs/examples/session/.
use serde::{Deserialize, Serialize};
pub const SESSION_VERSION: u32 = 1;
/// Rotation quaternion device→world, world = ENU (x East, y North, z Up).
pub type Quat = [f64; 4];
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Session {
pub version: u32,
pub created_at: String,
pub app: AppInfo,
pub device: Device,
pub site: Site,
pub north: North,
pub capture: CapturePlan,
#[serde(default)]
pub frames: Vec<FrameRecord>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sensor_stream: Option<SensorStream>,
/// Brush strokes; the format is not fixed yet, so it is kept verbatim.
#[serde(default)]
pub mask_edits: Vec<serde_json::Value>,
#[serde(default)]
pub result: Option<serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AppInfo {
pub name: String,
pub build: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Device {
pub platform: String,
pub model: String,
pub camera: Camera,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Camera {
pub width_px: u32,
pub height_px: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hfov_deg: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vfov_deg: Option<f64>,
/// Where the FOV came from: "assumed", "table", "calibrated", "manual", …
pub fov_source: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Site {
pub name: String,
pub lat_deg: f64,
pub lon_deg: f64,
pub elev_m: f64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub gps_accuracy_m: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct North {
/// "magnetic" or "true".
pub source: String,
pub declination_deg: f64,
pub user_offset_deg: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CapturePlan {
pub planned_frames: u32,
pub target_tilt_deg: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FrameRecord {
pub id: String,
pub file: String,
pub t: f64,
pub q: Quat,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub heading_accuracy_deg: Option<f64>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SensorStream {
pub file: String,
pub rate_hz: f64,
}
/// One line of `sensors.jsonl`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SensorSample {
pub t: f64,
pub q: Quat,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mag_heading_deg: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub heading_accuracy_deg: Option<f64>,
}
#[derive(Debug)]
pub enum SessionError {
Json(serde_json::Error),
/// Line number (1-based) in sensors.jsonl.
SensorLine(usize, serde_json::Error),
UnsupportedVersion(u32),
}
impl std::fmt::Display for SessionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SessionError::Json(e) => write!(f, "session.json: {e}"),
SessionError::SensorLine(n, e) => write!(f, "sensors.jsonl line {n}: {e}"),
SessionError::UnsupportedVersion(v) => write!(f, "unsupported session version {v}"),
}
}
}
impl std::error::Error for SessionError {}
impl Session {
pub fn from_json(text: &str) -> Result<Self, SessionError> {
let s: Session = serde_json::from_str(text).map_err(SessionError::Json)?;
if s.version != SESSION_VERSION {
return Err(SessionError::UnsupportedVersion(s.version));
}
Ok(s)
}
pub fn to_json(&self) -> String {
serde_json::to_string_pretty(self).expect("session is always serializable")
}
}
/// Parse `sensors.jsonl`; blank lines are skipped.
pub fn parse_sensors(text: &str) -> Result<Vec<SensorSample>, SessionError> {
text.lines()
.enumerate()
.filter(|(_, l)| !l.trim().is_empty())
.map(|(i, l)| serde_json::from_str(l).map_err(|e| SessionError::SensorLine(i + 1, e)))
.collect()
}
+485
View File
@@ -0,0 +1,485 @@
//! Sky / obstruction mask on the stitched equirectangular band, and the
//! horizon profile derived from it.
//!
//! First, classic version (docs/ARCHITECTURE.md "Sky mask"): sky is grown
//! from the top of the photographed area through smooth, bright, similar-
//! coloured pixels; thin vertical artefacts (frame seams, wires) are opened
//! away; obstruction blobs not connected to the ground (clouds, birds) become
//! sky. The edge is the **highest** obstruction pixel per column, so sky seen
//! through branches stays conservative. User brush edits override the result.
use crate::profile::HorizonProfile;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
pub const NO_DATA: u8 = 0;
pub const SKY: u8 = 1;
pub const GROUND: u8 = 2;
/// Geometry of an equirectangular band: column 0 = azimuth 0, full 360°
/// across the width; row 0 = `top_deg`, last row = `bottom_deg`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BandGeom {
pub width: u32,
pub height: u32,
pub top_deg: f64,
pub bottom_deg: f64,
}
impl BandGeom {
pub fn len(&self) -> usize {
self.width as usize * self.height as usize
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Altitude at the centre of row `y`.
pub fn alt_of_row(&self, y: usize) -> f64 {
self.top_deg - (y as f64 + 0.5) / self.height as f64 * (self.top_deg - self.bottom_deg)
}
/// Azimuth at the centre of column `x`.
pub fn az_of_col(&self, x: usize) -> f64 {
(x as f64 + 0.5) / self.width as f64 * 360.0
}
fn deg_per_px_y(&self) -> f64 {
(self.top_deg - self.bottom_deg) / self.height as f64
}
fn deg_per_px_x(&self) -> f64 {
360.0 / self.width as f64
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum EditMode {
Sky,
Ground,
}
/// One brush dab, in band coordinates (degrees). A stroke is a list of dabs.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MaskEdit {
pub mode: EditMode,
pub az_deg: f64,
pub alt_deg: f64,
pub radius_deg: f64,
}
// Tuning (8-bit channels). Sky is smooth: neighbour gradients of a clear or
// overcast sky stay well below these, foliage and edges far above.
const SEED_MAX_GRAD: f32 = 6.0;
const GROW_MAX_GRAD: f32 = 14.0;
const GROW_MAX_STEP: i32 = 30; // sum of |ΔR|+|ΔG|+|ΔB| between neighbours
const SEED_MIN_REL_BRIGHTNESS: f32 = 0.55; // × bright-sky reference
const GROW_MIN_REL_BRIGHTNESS: f32 = 0.40;
const OPEN_RADIUS_PX: usize = 2; // removes non-sky features ≤ 3 px wide
/// Classify every pixel of `rgba` (alpha < 128 = not photographed).
pub fn detect_sky(rgba: &[u8], g: BandGeom) -> Vec<u8> {
let (w, h) = (g.width as usize, g.height as usize);
let n = w * h;
if n == 0 || rgba.len() < n * 4 {
return vec![NO_DATA; n];
}
let covered: Vec<bool> = (0..n).map(|i| rgba[i * 4 + 3] >= 128).collect();
let gray: Vec<f32> = (0..n)
.map(|i| 0.299 * rgba[i * 4] as f32 + 0.587 * rgba[i * 4 + 1] as f32 + 0.114 * rgba[i * 4 + 2] as f32)
.collect();
let bright = |i: usize| rgba[i * 4].max(rgba[i * 4 + 1]).max(rgba[i * 4 + 2]) as f32;
let left = |i: usize| if i % w == 0 { i + w - 1 } else { i - 1 };
let right = |i: usize| if i % w == w - 1 { i + 1 - w } else { i + 1 };
// Central-difference gradient; uncovered neighbours contribute nothing.
let grad: Vec<f32> = (0..n)
.map(|i| {
if !covered[i] {
return f32::MAX;
}
let pair = |a: Option<usize>, b: Option<usize>| match (a, b) {
(Some(a), Some(b)) if covered[a] && covered[b] => (gray[a] - gray[b]).abs() / 2.0,
(Some(a), _) if covered[a] => (gray[a] - gray[i]).abs(),
(_, Some(b)) if covered[b] => (gray[b] - gray[i]).abs(),
_ => 0.0,
};
let y = i / w;
let up = (y > 0).then(|| i - w);
let down = (y + 1 < h).then(|| i + w);
pair(Some(left(i)), Some(right(i))) + pair(up, down)
})
.collect();
// Seeds: the top photographed pixel of each column, if it looks like sky.
let tops: Vec<Option<usize>> =
(0..w).map(|x| (0..h).map(|y| y * w + x).find(|&i| covered[i])).collect();
let mut top_bright: Vec<f32> = tops
.iter()
.flatten()
.filter(|&&i| grad[i] < SEED_MAX_GRAD)
.map(|&i| bright(i))
.collect();
let mut mask: Vec<u8> = covered.iter().map(|&c| if c { GROUND } else { NO_DATA }).collect();
if top_bright.is_empty() {
return mask;
}
top_bright.sort_by(f32::total_cmp);
let reference = top_bright[top_bright.len() * 3 / 4];
let mut queue = VecDeque::new();
for &i in tops.iter().flatten() {
if grad[i] < SEED_MAX_GRAD && bright(i) >= SEED_MIN_REL_BRIGHTNESS * reference {
mask[i] = SKY;
queue.push_back(i);
}
}
// Grow sky through smooth, similar, bright-enough neighbours.
let step = |a: usize, b: usize| {
(0..3).map(|c| (rgba[a * 4 + c] as i32 - rgba[b * 4 + c] as i32).abs()).sum::<i32>()
};
while let Some(i) = queue.pop_front() {
let y = i / w;
let mut nb = [Some(left(i)), Some(right(i)), None, None];
if y > 0 {
nb[2] = Some(i - w);
}
if y + 1 < h {
nb[3] = Some(i + w);
}
for j in nb.into_iter().flatten() {
if mask[j] == GROUND
&& grad[j] < GROW_MAX_GRAD
&& step(i, j) <= GROW_MAX_STEP
&& bright(j) >= GROW_MIN_REL_BRIGHTNESS * reference
{
mask[j] = SKY;
queue.push_back(j);
}
}
}
open_thin_columns(&mut mask, w, h);
drop_floating_ground(&mut mask, w, h);
mask
}
/// Non-sky pixels with sky within `OPEN_RADIUS_PX` on both the left and the
/// right of the same row are frame seams or wires: make them sky.
fn open_thin_columns(mask: &mut [u8], w: usize, h: usize) {
let r = OPEN_RADIUS_PX;
let orig = mask.to_vec();
for y in 0..h {
let row = &orig[y * w..(y + 1) * w];
for x in 0..w {
if row[x] != GROUND {
continue;
}
let sky_left = (1..=r).any(|d| row[(x + w - d) % w] == SKY);
let sky_right = (1..=r).any(|d| row[(x + d) % w] == SKY);
if sky_left && sky_right {
mask[y * w + x] = SKY;
}
}
}
}
/// Obstruction blobs that do not reach the bottom of the photographed area
/// (clouds, birds, lens flare) are sky. 8-connected flood from the bottom.
fn drop_floating_ground(mask: &mut [u8], w: usize, h: usize) {
let mut keep = vec![false; w * h];
let mut queue = VecDeque::new();
for x in 0..w {
if let Some(y) = (0..h).rev().find(|&y| mask[y * w + x] != NO_DATA) {
let i = y * w + x;
if mask[i] == GROUND {
keep[i] = true;
queue.push_back(i);
}
}
}
while let Some(i) = queue.pop_front() {
let (x, y) = ((i % w) as i64, (i / w) as i64);
for dy in -1..=1i64 {
for dx in -1..=1i64 {
let ny = y + dy;
if (dx == 0 && dy == 0) || ny < 0 || ny >= h as i64 {
continue;
}
let nx = (x + dx).rem_euclid(w as i64);
let j = (ny as usize) * w + nx as usize;
if !keep[j] && mask[j] == GROUND {
keep[j] = true;
queue.push_back(j);
}
}
}
}
for i in 0..w * h {
if mask[i] == GROUND && !keep[i] {
mask[i] = SKY;
}
}
}
/// Paint brush dabs onto the mask (they win over detection, also where no
/// photo exists). Distance is measured in degrees, azimuth wraps.
pub fn apply_edits(mask: &mut [u8], g: BandGeom, edits: &[MaskEdit]) {
let (w, h) = (g.width as usize, g.height as usize);
if mask.len() < w * h {
return;
}
let (dpx, dpy) = (g.deg_per_px_x(), g.deg_per_px_y());
for e in edits {
if !(e.radius_deg > 0.0 && e.az_deg.is_finite() && e.alt_deg.is_finite()) {
continue;
}
let value = match e.mode {
EditMode::Sky => SKY,
EditMode::Ground => GROUND,
};
let y0 = ((g.top_deg - (e.alt_deg + e.radius_deg)) / dpy).floor().max(0.0) as usize;
let y1 = (((g.top_deg - (e.alt_deg - e.radius_deg)) / dpy).ceil().max(0.0) as usize).min(h);
let cx = e.az_deg / dpx;
let rx = (e.radius_deg / dpx).ceil() as i64 + 1;
for y in y0..y1 {
let dalt = g.alt_of_row(y) - e.alt_deg;
for xi in (cx.floor() as i64 - rx)..=(cx.floor() as i64 + rx) {
let x = xi.rem_euclid(w as i64) as usize;
let mut daz = (g.az_of_col(x) - e.az_deg).rem_euclid(360.0);
if daz > 180.0 {
daz -= 360.0;
}
if daz * daz + dalt * dalt <= e.radius_deg * e.radius_deg {
mask[y * w + x] = value;
}
}
}
}
}
/// Altitude of the highest obstruction pixel per column (`None` = no data).
/// A photographed column with no obstruction at all reports the bottom of its
/// photo: the true edge is somewhere below, so this stays conservative.
pub fn column_edges(mask: &[u8], g: BandGeom) -> Vec<Option<f64>> {
let (w, h) = (g.width as usize, g.height as usize);
(0..w)
.map(|x| {
let mut lowest_data = None;
for y in 0..h {
match mask[y * w + x] {
GROUND => return Some(g.alt_of_row(y) + g.deg_per_px_y() / 2.0),
SKY => lowest_data = Some(y),
_ => {}
}
}
lowest_data.map(|y| g.alt_of_row(y))
})
.collect()
}
/// Which whole degrees of azimuth have photo data (index = azimuth).
pub fn coverage_degrees(mask: &[u8], g: BandGeom) -> Vec<bool> {
let mut cov = vec![false; 360];
for (x, e) in column_edges(mask, g).iter().enumerate() {
if e.is_some() {
cov[(g.az_of_col(x).floor() as usize) % 360] = true;
}
}
cov
}
/// Sky-edge profile: per whole degree the highest edge of the columns within
/// ±0.5°; degrees without photos are interpolated from their neighbours.
/// `None` when nothing is photographed.
pub fn edge_profile(mask: &[u8], g: BandGeom) -> Option<HorizonProfile> {
let mut best: Vec<Option<f64>> = vec![None; 360];
for (x, e) in column_edges(mask, g).into_iter().enumerate() {
if let Some(alt) = e {
let d = (g.az_of_col(x).round() as usize) % 360;
best[d] = Some(best[d].map_or(alt, |b: f64| b.max(alt)));
}
}
let pts: Vec<(f64, f64)> =
best.iter().enumerate().filter_map(|(d, v)| v.map(|a| (d as f64, a))).collect();
HorizonProfile::from_points(&pts).ok()
}
/// Whole degrees where obstruction reaches the top of the photographed area:
/// the frame was too low there and a higher shot is needed.
pub fn top_touch_degrees(mask: &[u8], g: BandGeom) -> Vec<bool> {
let (w, h) = (g.width as usize, g.height as usize);
let mut hits = vec![0u32; 360];
let mut cols = vec![0u32; 360];
for x in 0..w {
let d = (g.az_of_col(x).floor() as usize) % 360;
if let Some(y) = (0..h).find(|&y| mask[y * w + x] != NO_DATA) {
cols[d] += 1;
if mask[y * w + x] == GROUND {
hits[d] += 1;
}
}
}
(0..360).map(|d| cols[d] > 0 && hits[d] * 2 > cols[d]).collect()
}
#[cfg(test)]
mod tests {
use super::*;
const W: u32 = 720; // 2 px per degree
const H: u32 = 240; // +90 … −30, 2 px per degree
fn geom() -> BandGeom {
BandGeom { width: W, height: H, top_deg: 90.0, bottom_deg: -30.0 }
}
/// Smooth blue sky above `edge(az)`, textured dark ground below, photos
/// only between `lo` and `hi` altitude.
fn scene(edge: impl Fn(f64) -> f64, lo: f64, hi: f64) -> Vec<u8> {
let g = geom();
let mut v = vec![0u8; g.len() * 4];
for y in 0..H as usize {
let alt = g.alt_of_row(y);
for x in 0..W as usize {
let i = (y * W as usize + x) * 4;
if alt < lo || alt > hi {
continue;
}
if alt > edge(g.az_of_col(x)) {
let t = (alt / 90.0).clamp(0.0, 1.0);
v[i] = (150.0 - 60.0 * t) as u8;
v[i + 1] = (185.0 - 50.0 * t) as u8;
v[i + 2] = (225.0 - 20.0 * t) as u8;
} else {
let noise = ((x * 7919 + y * 104729) % 41) as u8;
v[i] = 20 + noise;
v[i + 1] = 40 + noise;
v[i + 2] = 15 + noise / 2;
}
v[i + 3] = 255;
}
}
v
}
fn tree(az: f64) -> f64 {
// 5° hills, a 25° tree around 120°.
let t = 25.0 * (-((az - 120.0) / 8.0).powi(2)).exp();
5.0 + 3.0 * (az.to_radians() * 3.0).sin() + t
}
#[test]
fn recovers_the_edge_within_a_degree() {
let g = geom();
let px = scene(tree, -22.0, 42.0);
let mask = detect_sky(&px, g);
let p = edge_profile(&mask, g).unwrap();
for az in (0..360).step_by(5) {
// Each degree keeps the highest edge within ±0.5° (conservative).
let want = (-5..=5).map(|k| tree(az as f64 + k as f64 * 0.1)).fold(f64::MIN, f64::max);
let got = p.at(az);
assert!((got - want).abs() <= 1.0, "az {az}: got {got:.2}, want {want:.2}");
assert!(got >= tree(az as f64) - 0.5, "az {az}: edge cut into the obstruction");
}
assert!(coverage_degrees(&mask, g).iter().all(|&c| c));
assert!(top_touch_degrees(&mask, g).iter().all(|&t| !t));
}
#[test]
fn exposure_seams_do_not_become_obstructions() {
let g = geom();
let mut px = scene(|_| 5.0, -22.0, 42.0);
// Every 15° a frame is 18 levels darker.
for y in 0..H as usize {
for x in 0..W as usize {
if (x / 30) % 2 == 1 {
let i = (y * W as usize + x) * 4;
for c in 0..3 {
px[i + c] = px[i + c].saturating_sub(18);
}
}
}
}
let p = edge_profile(&detect_sky(&px, g), g).unwrap();
assert!(p.max_alt() <= 6.0, "max edge {}", p.max_alt());
}
#[test]
fn floating_clouds_are_sky() {
let g = geom();
let mut px = scene(|_| 4.0, -22.0, 42.0);
// A textured grey cloud blob at 30° altitude, azimuth 200–210°.
for y in 0..H as usize {
let alt = g.alt_of_row(y);
for x in 0..W as usize {
let az = g.az_of_col(x);
if (28.0..32.0).contains(&alt) && (200.0..210.0).contains(&az) {
let i = (y * W as usize + x) * 4;
let n = ((x * 31 + y * 17) % 60) as u8;
px[i] = 120 + n;
px[i + 1] = 120 + n;
px[i + 2] = 125 + n;
}
}
}
let p = edge_profile(&detect_sky(&px, g), g).unwrap();
assert!(p.at(205) < 6.0, "cloud leaked into the edge: {}", p.at(205));
}
#[test]
fn tree_touching_the_top_is_reported() {
let g = geom();
let px = scene(|az| if (100.0..110.0).contains(&az) { 60.0 } else { 5.0 }, -22.0, 42.0);
let mask = detect_sky(&px, g);
let touch = top_touch_degrees(&mask, g);
assert!(touch[105]);
assert!(!touch[200]);
let p = edge_profile(&mask, g).unwrap();
assert!(p.at(105) >= 41.0);
}
#[test]
fn gaps_are_interpolated_and_reported() {
let g = geom();
let mut px = scene(|_| 10.0, -22.0, 42.0);
// Only 0–180° photographed.
for y in 0..H as usize {
for x in W as usize / 2..W as usize {
px[(y * W as usize + x) * 4 + 3] = 0;
}
}
let mask = detect_sky(&px, g);
let cov = coverage_degrees(&mask, g);
assert!(cov[90] && !cov[270]);
let p = edge_profile(&mask, g).unwrap();
assert!((p.at(270) - 10.0).abs() <= 1.0);
}
#[test]
fn brush_edits_override_detection() {
let g = geom();
let px = scene(|_| 5.0, -22.0, 42.0);
let mut mask = detect_sky(&px, g);
apply_edits(
&mut mask,
g,
&[MaskEdit { mode: EditMode::Ground, az_deg: 359.0, alt_deg: 20.0, radius_deg: 3.0 }],
);
let p = edge_profile(&mask, g).unwrap();
assert!(p.at(359) >= 22.0, "ground paint raises the edge: {}", p.at(359));
assert!(p.at(1) >= 21.0, "the dab wraps across north: {}", p.at(1));
apply_edits(
&mut mask,
g,
&[MaskEdit { mode: EditMode::Sky, az_deg: 359.0, alt_deg: 20.0, radius_deg: 4.0 }],
);
assert!(edge_profile(&mask, g).unwrap().at(359) < 6.0);
}
#[test]
fn nothing_photographed_gives_no_profile() {
let g = geom();
let px = vec![0u8; g.len() * 4];
assert!(edge_profile(&detect_sky(&px, g), g).is_none());
}
}
+496
View File
@@ -0,0 +1,496 @@
//! Stellarium landscape export: spherical (photo panorama) and polygonal
//! (outline only). Format and texture mapping: docs/FORMATS.md.
use crate::hrz::fmt_alt;
use crate::profile::HorizonProfile;
use serde::Deserialize;
use std::fmt::Write as _;
/// Observer location written to `[location]`.
#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Location {
pub lat_deg: f64,
pub lon_deg: f64,
/// Metres above sea level; omitted from the ini when unknown.
#[serde(default)]
pub elev_m: Option<f64>,
}
/// Text that goes into `landscape.ini`.
#[derive(Debug, Clone, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LandscapeMeta {
/// Site name, e.g. "Backyard pier".
pub name: String,
pub author: String,
/// Used in the description ("... made with <app>").
pub app_name: String,
#[serde(default)]
pub location: Option<Location>,
}
/// One file of an export: path inside the zip and its bytes.
pub type ExportFile = (String, Vec<u8>);
/// Degrees as Stellarium DMS, e.g. 47.4979 → `+47d29'52"`.
pub fn dms(deg: f64) -> String {
let sign = if deg < 0.0 { '-' } else { '+' };
let total = (deg.abs() * 3600.0).round() as i64;
format!("{sign}{}d{}'{}\"", total / 3600, (total / 60) % 60, total % 60)
}
/// Whole numbers without decimals, otherwise one decimal (ini angles).
fn fmt_deg(v: f64) -> String {
if v.fract() == 0.0 { format!("{}", v as i64) } else { fmt_alt(v) }
}
/// Keep ini values on one line.
fn ini_value(s: &str) -> String {
s.replace(['\r', '\n'], " ").trim().to_string()
}
/// Folder name inside the zip (Stellarium installs the landscape from it).
pub fn landscape_id(name: &str) -> String {
let mut id = String::new();
for c in name.to_lowercase().chars() {
let c = match c {
'á' | 'à' | 'â' | 'ä' => 'a',
'é' | 'è' | 'ê' | 'ë' => 'e',
'í' | 'ì' | 'î' | 'ï' => 'i',
'ó' | 'ò' | 'ô' | 'ö' | 'ő' => 'o',
'ú' | 'ù' | 'û' | 'ü' | 'ű' => 'u',
c => c,
};
if c.is_ascii_alphanumeric() {
id.push(c);
} else if !id.ends_with('_') && !id.is_empty() {
id.push('_');
}
}
let id = id.trim_end_matches('_').to_string();
if id.is_empty() { "horizon".to_string() } else { id }
}
fn push_location(out: &mut String, loc: &Option<Location>) {
if let Some(l) = loc {
out.push_str("\n[location]\nplanet = Earth\n");
let _ = writeln!(out, "latitude = {}", dms(l.lat_deg));
let _ = writeln!(out, "longitude = {}", dms(l.lon_deg));
if let Some(elev) = l.elev_m.filter(|e| e.is_finite()) {
let _ = writeln!(out, "altitude = {}", elev.round() as i64);
}
}
}
/// `horizon.txt` (azDeg_altDeg): the plain detected edge, no safety margin.
pub fn horizon_txt(profile: &HorizonProfile, site_name: &str) -> String {
let mut out = String::with_capacity(360 * 8 + 100);
let _ = writeln!(out, "# {} - sky edge, no safety margin", ini_value(site_name));
out.push_str("# azimuth (deg, N=0, E=90) altitude (deg)\n");
for az in 0..360i64 {
let _ = writeln!(out, "{az} {}", fmt_alt(profile.at(az).clamp(-90.0, 90.0)));
}
out
}
/// `landscape.ini` for the outline-only (polygonal) landscape.
pub fn polygonal_ini(meta: &LandscapeMeta) -> String {
let mut out = String::new();
out.push_str("[landscape]\n");
let _ = writeln!(out, "name = {} (outline)", ini_value(&meta.name));
let _ = writeln!(out, "author = {}", ini_value(&meta.author));
let _ = writeln!(out, "description = Horizon outline made with {}", ini_value(&meta.app_name));
out.push_str("type = polygonal\n");
out.push_str("polygonal_horizon_list = horizon.txt\n");
out.push_str("polygonal_horizon_list_mode = azDeg_altDeg\n");
out.push_str("polygonal_angle_rotatez = 0\n");
out.push_str("ground_color = .12,.12,.14\n");
push_location(&mut out, &meta.location);
out
}
/// `landscape.ini` for the photo panorama (spherical) landscape.
pub fn spherical_ini(meta: &LandscapeMeta, top_deg: f64, bottom_deg: f64) -> String {
let mut out = String::new();
out.push_str("[landscape]\n");
let _ = writeln!(out, "name = {}", ini_value(&meta.name));
let _ = writeln!(out, "author = {}", ini_value(&meta.author));
let _ = writeln!(
out,
"description = 360 degree horizon panorama made with {}",
ini_value(&meta.app_name)
);
out.push_str("type = spherical\n");
out.push_str("maptex = panorama.png\n");
let _ = writeln!(out, "maptex_top = {}", fmt_deg(top_deg));
let _ = writeln!(out, "maptex_bottom = {}", fmt_deg(bottom_deg));
out.push_str("angle_rotatez = 0\n");
out.push_str("bottom_cap_color = .05,.05,.05\n");
out.push_str("polygonal_horizon_list = horizon.txt\n");
out.push_str("polygonal_angle_rotatez = 0\n");
push_location(&mut out, &meta.location);
out
}
/// Outline-only landscape: `<id>_outline/landscape.ini` + `horizon.txt`.
pub fn export_polygonal(
profile: &HorizonProfile,
meta: &LandscapeMeta,
north_offset_deg: f64,
) -> Vec<ExportFile> {
let p = profile.rotated(north_offset_deg);
let dir = format!("{}_outline", landscape_id(&meta.name));
vec![
(format!("{dir}/landscape.ini"), polygonal_ini(meta).into_bytes()),
(format!("{dir}/horizon.txt"), horizon_txt(&p, &meta.name).into_bytes()),
]
}
// ---------------------------------------------------------------------------
// Spherical panorama
// ---------------------------------------------------------------------------
/// Source equirectangular band in the app's own layout: column 0 = measured
/// azimuth 0°, azimuth grows to the right over the full width (360°); row 0 =
/// `top_deg`, last row = `bottom_deg`, linear in altitude. RGBA, alpha 0 =
/// no photo. `sky_mask` (same size, `skymask::SKY` = sky) makes sky seen
/// below the edge (between branches) transparent too.
#[derive(Debug, Clone, Copy)]
pub struct PanoramaBand<'a> {
pub rgba: &'a [u8],
pub width: u32,
pub height: u32,
pub top_deg: f64,
pub bottom_deg: f64,
pub sky_mask: Option<&'a [u8]>,
}
#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct SphericalOptions {
pub width_px: u32,
pub height_px: u32,
/// Altitude of the output's top / bottom row (`maptex_top/bottom`).
pub top_deg: f64,
pub bottom_deg: f64,
pub north_offset_deg: f64,
}
impl Default for SphericalOptions {
fn default() -> Self {
Self { width_px: 8192, height_px: 2048, top_deg: 42.0, bottom_deg: -22.0, north_offset_deg: 0.0 }
}
}
impl SphericalOptions {
/// Default size with a band that fits this profile: top a few degrees
/// above the highest obstruction, bottom at the source's bottom (≥ −90).
pub fn fitted(profile: &HorizonProfile, src_bottom_deg: f64) -> Self {
let top = (profile.max_alt() + 5.0).ceil().clamp(10.0, 90.0);
let bottom = src_bottom_deg.floor().clamp(-90.0, top - 1.0);
Self { top_deg: top, bottom_deg: bottom, ..Self::default() }
}
}
/// Gray used below the edge where no photo covers the ground (≈ `.05`).
const GROUND_FILL: [u8; 4] = [13, 13, 13, 255];
/// Bilinear sample at fractional source position, skipping pixels without a
/// photo (alpha 0). `None` when no covered pixel contributes.
fn sample_rgb(src: &PanoramaBand, sx: f64, sy: f64) -> Option<[u8; 3]> {
let w = src.width as i64;
let h = src.height as i64;
let x0 = sx.floor();
let y0 = sy.floor();
let fx = sx - x0;
let fy = sy - y0;
let (x0, y0) = (x0 as i64, y0 as i64);
let mut acc = [0.0f64; 3];
let mut wsum = 0.0;
for (dx, dy, wt) in [
(0, 0, (1.0 - fx) * (1.0 - fy)),
(1, 0, fx * (1.0 - fy)),
(0, 1, (1.0 - fx) * fy),
(1, 1, fx * fy),
] {
let x = (x0 + dx).rem_euclid(w);
let y = (y0 + dy).clamp(0, h - 1);
let i = ((y * w + x) * 4) as usize;
if src.rgba[i + 3] == 0 || wt <= 0.0 {
continue;
}
for c in 0..3 {
acc[c] += src.rgba[i + c] as f64 * wt;
}
wsum += wt;
}
if wsum < 1e-6 {
return None;
}
Some([
(acc[0] / wsum).round() as u8,
(acc[1] / wsum).round() as u8,
(acc[2] / wsum).round() as u8,
])
}
/// Render Stellarium's texture: left edge = true azimuth 90° (East), growing
/// to the right; the north offset is baked in by shifting columns. Pixels
/// above the profile edge get alpha 0 (sky); below it the photo, or a dark
/// fill where no photo exists.
pub fn render_panorama(
src: &PanoramaBand,
profile: &HorizonProfile,
opts: &SphericalOptions,
) -> Result<Vec<u8>, String> {
validate(src, opts)?;
let (w, h) = (opts.width_px as usize, opts.height_px as usize);
let src_range = src.top_deg - src.bottom_deg;
// Per column: measured azimuth → source x and sky edge.
let cols: Vec<(f64, f64)> = (0..w)
.map(|x| {
let az_true = 90.0 + (x as f64 + 0.5) / w as f64 * 360.0;
let az = (az_true - opts.north_offset_deg).rem_euclid(360.0);
(az / 360.0 * src.width as f64 - 0.5, profile.sample(az))
})
.collect();
let mut out = vec![0u8; w * h * 4];
for y in 0..h {
let alt = opts.top_deg - (y as f64 + 0.5) / h as f64 * (opts.top_deg - opts.bottom_deg);
let sy = (src.top_deg - alt) / src_range * src.height as f64 - 0.5;
let in_src = sy >= -0.5 && sy <= src.height as f64 - 0.5;
let mask_row = match src.sky_mask {
Some(m) if in_src => {
let my = (sy.round().max(0.0) as usize).min(src.height as usize - 1);
Some(&m[my * src.width as usize..(my + 1) * src.width as usize])
}
_ => None,
};
let row = &mut out[y * w * 4..(y + 1) * w * 4];
for (x, &(sx, edge)) in cols.iter().enumerate() {
if alt > edge {
continue; // sky: stays transparent
}
if let Some(mr) = mask_row {
let mx = (sx.round() as i64).rem_euclid(src.width as i64) as usize;
if mr[mx] == crate::skymask::SKY {
continue;
}
}
let px = if in_src { sample_rgb(src, sx, sy) } else { None };
let rgba = match px {
Some([r, g, b]) => [r, g, b, 255],
None => GROUND_FILL,
};
row[x * 4..x * 4 + 4].copy_from_slice(&rgba);
}
}
Ok(out)
}
fn validate(src: &PanoramaBand, opts: &SphericalOptions) -> Result<(), String> {
if src.width == 0 || src.height == 0 {
return Err("panorama source is empty".into());
}
if src.rgba.len() < src.width as usize * src.height as usize * 4 {
return Err("panorama source buffer is smaller than width × height × 4".into());
}
if let Some(m) = src.sky_mask {
if m.len() < src.width as usize * src.height as usize {
return Err("sky mask is smaller than the panorama source".into());
}
}
if src.top_deg <= src.bottom_deg {
return Err("panorama source top must be above its bottom".into());
}
if opts.width_px == 0 || opts.height_px == 0 {
return Err("output size must be positive".into());
}
if !(opts.top_deg <= 90.0 && opts.bottom_deg >= -90.0 && opts.top_deg > opts.bottom_deg) {
return Err("output band must satisfy −90 ≤ bottom < top ≤ 90".into());
}
Ok(())
}
/// Encode RGBA8 pixels as PNG.
pub fn encode_png(rgba: &[u8], width: u32, height: u32) -> Result<Vec<u8>, String> {
let mut buf = Vec::new();
{
let mut enc = png::Encoder::new(&mut buf, width, height);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
let mut writer = enc.write_header().map_err(|e| e.to_string())?;
writer.write_image_data(rgba).map_err(|e| e.to_string())?;
}
Ok(buf)
}
/// Photo landscape: `<id>/landscape.ini`, `panorama.png`, `horizon.txt`.
pub fn export_spherical(
src: &PanoramaBand,
profile: &HorizonProfile,
meta: &LandscapeMeta,
opts: &SphericalOptions,
) -> Result<Vec<ExportFile>, String> {
let pixels = render_panorama(src, profile, opts)?;
let png = encode_png(&pixels, opts.width_px, opts.height_px)?;
let rotated = profile.rotated(opts.north_offset_deg);
let dir = landscape_id(&meta.name);
Ok(vec![
(format!("{dir}/landscape.ini"), spherical_ini(meta, opts.top_deg, opts.bottom_deg).into_bytes()),
(format!("{dir}/panorama.png"), png),
(format!("{dir}/horizon.txt"), horizon_txt(&rotated, &meta.name).into_bytes()),
])
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn dms_matches_stellarium_examples() {
assert_eq!(dms(47.4979), "+47d29'52\"");
assert_eq!(dms(19.0402), "+19d2'25\"");
assert_eq!(dms(-33.8568), "-33d51'24\"");
assert_eq!(dms(10.99999), "+11d0'0\"");
}
#[test]
fn ids_are_folder_safe() {
assert_eq!(landscape_id("Backyard pier"), "backyard_pier");
assert_eq!(landscape_id(" Kiskőrös / dűlő #2 "), "kiskoros_dulo_2");
assert_eq!(landscape_id("***"), "horizon");
}
#[test]
fn ini_without_location_has_no_location_section() {
let meta = LandscapeMeta {
name: "X".into(),
author: "A".into(),
app_name: "App".into(),
location: None,
};
let ini = polygonal_ini(&meta);
assert!(!ini.contains("[location]"));
assert!(ini.ends_with("ground_color = .12,.12,.14\n"));
assert!(spherical_ini(&meta, 37.5, -20.0).contains("maptex_top = 37.5\nmaptex_bottom = -20\n"));
}
#[test]
fn unknown_elevation_is_left_out() {
let meta = LandscapeMeta {
name: "X".into(),
author: "A".into(),
app_name: "App".into(),
location: Some(Location { lat_deg: 47.5, lon_deg: 19.0, elev_m: None }),
};
let ini = polygonal_ini(&meta);
assert!(ini.contains("latitude = +47d30'0\""));
assert!(!ini.contains("altitude"));
}
/// Source band where every column's red channel encodes its azimuth.
fn az_coded_band(w: u32, h: u32) -> Vec<u8> {
let mut v = vec![0u8; (w * h * 4) as usize];
for y in 0..h {
for x in 0..w {
let i = ((y * w + x) * 4) as usize;
v[i] = ((x as f64 + 0.5) / w as f64 * 360.0 / 2.0) as u8; // az/2
v[i + 1] = 100;
v[i + 3] = 255;
}
}
v
}
#[test]
fn east_is_the_left_edge_and_sky_is_transparent() {
let (sw, sh) = (720, 120);
let src_px = az_coded_band(sw, sh);
let src = PanoramaBand { rgba: &src_px, width: sw, height: sh, top_deg: 90.0, bottom_deg: -30.0, sky_mask: None };
let profile = HorizonProfile::flat(10.0);
let opts = SphericalOptions { width_px: 360, height_px: 64, top_deg: 42.0, bottom_deg: -22.0, north_offset_deg: 0.0 };
let out = render_panorama(&src, &profile, &opts).unwrap();
let px = |x: usize, y: usize| &out[(y * 360 + x) * 4..(y * 360 + x) * 4 + 4];
// Row 0 (42°) is above the 10° edge → transparent.
assert_eq!(px(0, 0)[3], 0);
// Bottom row is ground: photo, opaque.
let bottom = 63;
assert_eq!(px(0, bottom)[3], 255);
// Column 0 ≈ azimuth 90 (red = 45), 25 % ≈ 180 (S), 75 % ≈ 0/360 (N).
assert!((px(0, bottom)[0] as i32 - 45).abs() <= 1);
assert!((px(90, bottom)[0] as i32 - 90).abs() <= 1);
assert!((px(180, bottom)[0] as i32 - 135).abs() <= 1);
let n = px(271, bottom)[0] as i32; // just right of north
assert!(n <= 2, "north column red = {n}");
}
#[test]
fn north_offset_shifts_the_texture() {
let (sw, sh) = (720, 120);
let src_px = az_coded_band(sw, sh);
let src = PanoramaBand { rgba: &src_px, width: sw, height: sh, top_deg: 90.0, bottom_deg: -30.0, sky_mask: None };
let profile = HorizonProfile::flat(10.0);
let base = SphericalOptions { width_px: 360, height_px: 64, ..SphericalOptions::default() };
let shifted = SphericalOptions { north_offset_deg: 20.0, ..base };
let a = render_panorama(&src, &profile, &base).unwrap();
let b = render_panorama(&src, &profile, &shifted).unwrap();
let red = |v: &[u8], x: usize| v[(63 * 360 + x) * 4] as i32;
// Measured azimuth 110 (red 55) sits at column 20 before, column 40 after.
assert!((red(&a, 20) - 55).abs() <= 1);
assert!((red(&b, 40) - 55).abs() <= 1);
}
#[test]
fn sky_mask_holes_below_the_edge_are_transparent() {
let (sw, sh) = (360u32, 120u32);
let src_px = vec![90u8; (sw * sh * 4) as usize];
let mut mask = vec![crate::skymask::GROUND; (sw * sh) as usize];
// Sky hole at azimuth 180–190°, altitude 0–10° (rows 80–90 of +90…−30).
for y in 80..90 {
for x in 180..190 {
mask[y * sw as usize + x] = crate::skymask::SKY;
}
}
let src = PanoramaBand { rgba: &src_px, width: sw, height: sh, top_deg: 90.0, bottom_deg: -30.0, sky_mask: Some(&mask) };
let opts = SphericalOptions { width_px: 360, height_px: 120, top_deg: 90.0, bottom_deg: -30.0, north_offset_deg: 0.0 };
let out = render_panorama(&src, &HorizonProfile::flat(30.0), &opts).unwrap();
// Output column for azimuth 185 = (185 − 90) = 95; row for 5° = 85.
assert_eq!(out[(85 * 360 + 95) * 4 + 3], 0);
assert_eq!(out[(85 * 360 + 120) * 4 + 3], 255);
}
#[test]
fn ground_without_photo_is_filled_not_transparent() {
let (sw, sh) = (36, 12);
let src_px = vec![0u8; (sw * sh * 4) as usize]; // no photo anywhere
let src = PanoramaBand { rgba: &src_px, width: sw, height: sh, top_deg: 30.0, bottom_deg: -10.0, sky_mask: None };
let profile = HorizonProfile::flat(5.0);
let opts = SphericalOptions { width_px: 64, height_px: 32, top_deg: 40.0, bottom_deg: -40.0, north_offset_deg: 0.0 };
let out = render_panorama(&src, &profile, &opts).unwrap();
let last = &out[(31 * 64) * 4..(31 * 64) * 4 + 4];
assert_eq!(last, &GROUND_FILL);
}
#[test]
fn rejects_bad_bands() {
let px = vec![0u8; 16];
let src = PanoramaBand { rgba: &px, width: 2, height: 2, top_deg: 10.0, bottom_deg: 0.0, sky_mask: None };
let p = HorizonProfile::flat(0.0);
let bad = SphericalOptions { top_deg: 0.0, bottom_deg: 10.0, ..SphericalOptions::default() };
assert!(render_panorama(&src, &p, &bad).is_err());
let short = PanoramaBand { rgba: &px[..8], ..src };
assert!(render_panorama(&short, &p, &SphericalOptions::default()).is_err());
}
#[test]
fn png_has_signature_and_size() {
let png = encode_png(&[255, 0, 0, 255, 0, 0, 0, 0], 2, 1).unwrap();
assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
assert_eq!(u32::from_be_bytes([png[16], png[17], png[18], png[19]]), 2);
}
}
+96
View File
@@ -0,0 +1,96 @@
//! Minimal, deterministic zip writer (STORE, no compression).
//!
//! Exports are a few text files plus an already-deflated PNG, so compression
//! would gain nothing. Timestamps are fixed (1980-01-01) so output is
//! byte-stable for golden tests.
/// Build a zip archive from (path, contents) entries, in the given order.
/// Paths use `/` separators and are stored as UTF-8.
pub fn zip(files: &[(String, Vec<u8>)]) -> Vec<u8> {
const DOS_TIME: u16 = 0;
const DOS_DATE: u16 = (1 << 5) | 1; // 1980-01-01
const FLAG_UTF8: u16 = 1 << 11;
let mut out = Vec::new();
let mut central = Vec::new();
for (name, data) in files {
let offset = out.len() as u32;
let crc = crc32fast::hash(data);
let size = data.len() as u32;
let name_b = name.as_bytes();
// Local file header
out.extend_from_slice(&0x0403_4b50u32.to_le_bytes());
out.extend_from_slice(&20u16.to_le_bytes()); // version needed
out.extend_from_slice(&FLAG_UTF8.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes()); // method: store
out.extend_from_slice(&DOS_TIME.to_le_bytes());
out.extend_from_slice(&DOS_DATE.to_le_bytes());
out.extend_from_slice(&crc.to_le_bytes());
out.extend_from_slice(&size.to_le_bytes());
out.extend_from_slice(&size.to_le_bytes());
out.extend_from_slice(&(name_b.len() as u16).to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes()); // extra len
out.extend_from_slice(name_b);
out.extend_from_slice(data);
// Central directory entry
central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());
central.extend_from_slice(&20u16.to_le_bytes()); // version made by
central.extend_from_slice(&20u16.to_le_bytes()); // version needed
central.extend_from_slice(&FLAG_UTF8.to_le_bytes());
central.extend_from_slice(&0u16.to_le_bytes());
central.extend_from_slice(&DOS_TIME.to_le_bytes());
central.extend_from_slice(&DOS_DATE.to_le_bytes());
central.extend_from_slice(&crc.to_le_bytes());
central.extend_from_slice(&size.to_le_bytes());
central.extend_from_slice(&size.to_le_bytes());
central.extend_from_slice(&(name_b.len() as u16).to_le_bytes());
central.extend_from_slice(&0u16.to_le_bytes()); // extra
central.extend_from_slice(&0u16.to_le_bytes()); // comment
central.extend_from_slice(&0u16.to_le_bytes()); // disk start
central.extend_from_slice(&0u16.to_le_bytes()); // internal attrs
central.extend_from_slice(&0u32.to_le_bytes()); // external attrs
central.extend_from_slice(&offset.to_le_bytes());
central.extend_from_slice(name_b);
}
let cd_offset = out.len() as u32;
let cd_size = central.len() as u32;
let n = files.len() as u16;
out.extend_from_slice(&central);
// End of central directory
out.extend_from_slice(&0x0605_4b50u32.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&n.to_le_bytes());
out.extend_from_slice(&n.to_le_bytes());
out.extend_from_slice(&cd_size.to_le_bytes());
out.extend_from_slice(&cd_offset.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out
}
#[cfg(test)]
mod tests {
use super::zip;
#[test]
fn layout_is_valid_and_deterministic() {
let files = vec![
("a/landscape.ini".to_string(), b"[landscape]\n".to_vec()),
("a/horizon.txt".to_string(), b"0 1.0\n".to_vec()),
];
let z = zip(&files);
assert_eq!(z, zip(&files));
assert_eq!(&z[..4], &[0x50, 0x4b, 0x03, 0x04]);
let eocd = &z[z.len() - 22..];
assert_eq!(&eocd[..4], &[0x50, 0x4b, 0x05, 0x06]);
assert_eq!(u16::from_le_bytes([eocd[10], eocd[11]]), 2);
// Stored data is readable at the local header's payload offset.
let name_len = u16::from_le_bytes([z[26], z[27]]) as usize;
let start = 30 + name_len;
assert_eq!(&z[start..start + 12], b"[landscape]\n");
}
}
+101
View File
@@ -0,0 +1,101 @@
//! Golden tests against the designer's sample outputs in docs/examples/.
use sfzenith_core::hrz::{export_hrz, parse_hrz, HrzOptions};
use sfzenith_core::session::{parse_sensors, Session};
use sfzenith_core::stellarium::{
export_polygonal, export_spherical, horizon_txt, polygonal_ini, spherical_ini, LandscapeMeta,
Location, PanoramaBand, SphericalOptions,
};
use sfzenith_core::zip::zip;
use std::path::PathBuf;
fn example(rel: &str) -> String {
let p = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../docs/examples").join(rel);
std::fs::read_to_string(&p).unwrap_or_else(|e| panic!("{}: {e}", p.display()))
}
fn meta() -> LandscapeMeta {
LandscapeMeta {
name: "Backyard pier".into(),
author: "[AUTHOR]".into(),
app_name: "[APP NAME]".into(),
location: Some(Location { lat_deg: 47.4979, lon_deg: 19.0402, elev_m: Some(112.0) }),
}
}
#[test]
fn hrz_matches_example() {
// horizon.txt is the plain edge; the NINA file is the same edge + 2°.
let edge = parse_hrz(&example("stellarium-spherical/horizon.txt")).unwrap();
let hrz = export_hrz(&edge, HrzOptions::default());
assert_eq!(hrz, example("nina/backyard-pier.hrz"));
}
#[test]
fn horizon_txt_matches_example() {
let text = example("stellarium-spherical/horizon.txt");
let edge = parse_hrz(&text).unwrap();
assert_eq!(horizon_txt(&edge, "Backyard pier"), text);
assert_eq!(example("stellarium-polygonal/horizon.txt"), text);
}
#[test]
fn landscape_inis_match_examples() {
assert_eq!(spherical_ini(&meta(), 42.0, -22.0), example("stellarium-spherical/landscape.ini"));
assert_eq!(polygonal_ini(&meta()), example("stellarium-polygonal/landscape.ini"));
}
#[test]
fn polygonal_export_layout() {
let edge = parse_hrz(&example("stellarium-polygonal/horizon.txt")).unwrap();
let files = export_polygonal(&edge, &meta(), 0.0);
let names: Vec<&str> = files.iter().map(|f| f.0.as_str()).collect();
assert_eq!(names, ["backyard_pier_outline/landscape.ini", "backyard_pier_outline/horizon.txt"]);
assert_eq!(files[1].1, example("stellarium-polygonal/horizon.txt").into_bytes());
let z = zip(&files);
assert_eq!(z, zip(&export_polygonal(&edge, &meta(), 0.0)), "zip must be byte-stable");
}
#[test]
fn spherical_export_layout() {
let edge = parse_hrz(&example("stellarium-spherical/horizon.txt")).unwrap();
let (w, h) = (360u32, 120u32);
let px = vec![128u8; (w * h * 4) as usize];
let band = PanoramaBand { rgba: &px, width: w, height: h, top_deg: 90.0, bottom_deg: -30.0, sky_mask: None };
let opts = SphericalOptions { width_px: 512, height_px: 128, ..SphericalOptions::default() };
let files = export_spherical(&band, &edge, &meta(), &opts).unwrap();
let names: Vec<&str> = files.iter().map(|f| f.0.as_str()).collect();
assert_eq!(
names,
["backyard_pier/landscape.ini", "backyard_pier/panorama.png", "backyard_pier/horizon.txt"]
);
assert_eq!(files[0].1, example("stellarium-spherical/landscape.ini").into_bytes());
assert_eq!(&files[1].1[1..4], b"PNG");
}
#[test]
fn fitted_band_tracks_the_profile() {
let edge = parse_hrz(&example("stellarium-spherical/horizon.txt")).unwrap();
let o = SphericalOptions::fitted(&edge, -30.0);
assert_eq!((o.top_deg, o.bottom_deg), (31.0, -30.0)); // max edge 26.0 + 5
assert_eq!((o.width_px, o.height_px), (8192, 2048));
}
#[test]
fn session_example_roundtrips() {
let text = example("session/session.json");
let s = Session::from_json(&text).unwrap();
assert_eq!(s.site.name, "Backyard pier");
assert_eq!(s.frames.len(), 2);
assert_eq!(s.device.camera.fov_source, "assumed");
assert_eq!(Session::from_json(&s.to_json()).unwrap(), s);
// Every top-level key of the example survives a save.
let a: serde_json::Value = serde_json::from_str(&text).unwrap();
let b: serde_json::Value = serde_json::from_str(&s.to_json()).unwrap();
let keys = |v: &serde_json::Value| v.as_object().unwrap().keys().cloned().collect::<Vec<_>>();
assert_eq!(keys(&a), keys(&b));
let sensors = parse_sensors(&example("session/sensors.jsonl")).unwrap();
assert_eq!(sensors.len(), 2);
assert_eq!(sensors[1].mag_heading_deg, Some(354.5));
}