use fixed::types::extra::{U11, U16};
use fixed::{FixedI16, FixedU16};
use nalgebra::{Vector2, Vector3};
use serde::{Deserialize, Serialize};
use std::f64::consts::PI;
const TWO_PI: f64 = PI + PI;
pub type StarAx = FixedI16<U11>;
pub type QuadAx = FixedU16<U16>;
#[derive(
rkyv_08::Archive,
rkyv_08::Serialize,
rkyv_08::Deserialize,
Serialize,
Deserialize,
PartialEq,
Debug,
Clone,
Copy,
)]
#[rkyv(crate=rkyv_08)]
pub struct CoordCelestial {
pub ra: f64, pub dec: f64, }
pub type CoordCartesian = Vector2<f64>;
pub type CoordUnitSphere = Vector3<f64>;
pub type CoordUnitSphereFP = [StarAx; 3];
impl From<CoordUnitSphere> for CoordCelestial {
fn from(spherical: CoordUnitSphere) -> Self {
let ra: f64 = spherical.y.atan2(spherical.x);
let ra: f64 = if ra < 0f64 { ra + TWO_PI } else { ra };
let dec: f64 = spherical.z.asin();
CoordCelestial { ra, dec }
}
}
impl From<&CoordUnitSphere> for CoordCelestial {
fn from(spherical: &CoordUnitSphere) -> Self {
let ra: f64 = spherical.y.atan2(spherical.x);
let ra: f64 = if ra < 0f64 { ra + TWO_PI } else { ra };
let dec: f64 = spherical.z.asin();
CoordCelestial { ra, dec }
}
}
impl Into<CoordUnitSphere> for CoordCelestial {
fn into(self) -> CoordUnitSphere {
CoordUnitSphere::new(
self.dec.cos() * self.ra.cos(),
self.dec.cos() * self.ra.sin(),
self.dec.sin(),
)
}
}
pub fn coord_unit_sphere_from_radec(ra: f64, dec: f64) -> CoordUnitSphere {
(CoordCelestial { ra, dec }).into()
}
pub fn get_midpoint(a: &CoordUnitSphere, b: &CoordUnitSphere) -> CoordUnitSphere {
(a + b).normalize()
}
pub fn tan_project(s: &CoordUnitSphere, r: &CoordUnitSphere) -> Option<CoordCartesian> {
let s_dot_r = s.dot(&r);
if s_dot_r < 0f64 {
return None;
}
Some(if (r.z - 1f64).abs() < f64::EPSILON {
CoordCartesian::new(s.x / s.z, s.y / s.z)
} else if (r.z + 1f64).abs() < f64::EPSILON {
CoordCartesian::new(-s.x / s.z, s.y / s.z)
} else {
let eta = Vector3::new(-r.y, r.x, 0f64);
let eta_scale_inv = eta.x * eta.x + (1f64 / (eta.y * eta.y)).sqrt();
let eta = eta * eta_scale_inv;
let xi = r.cross(&eta);
let inv_s_dot_r = 1f64 / s_dot_r;
CoordCartesian::new(s.dot(&eta) * inv_s_dot_r, s.dot(&xi) * inv_s_dot_r)
})
}