use crcbl_core::WorldPos;
use glam::{DVec3, I64Vec3};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct FrameId(u32);
impl FrameId {
#[inline]
#[must_use]
pub fn index(self) -> usize {
self.0 as usize
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct State {
pub position: WorldPos,
pub velocity: DVec3,
}
impl State {
pub const AT_ORIGIN: Self = Self {
position: WorldPos::ORIGIN,
velocity: DVec3::ZERO,
};
#[inline]
#[must_use]
pub fn new(position: WorldPos, velocity: DVec3) -> Self {
Self { position, velocity }
}
}
#[derive(Debug)]
struct Frame {
parent: Option<FrameId>,
children: Vec<FrameId>,
depth: u32,
mu: f64,
soi_radius: f64,
origin: WorldPos,
velocity: DVec3,
}
#[derive(Debug)]
pub struct Frames {
frames: Vec<Frame>,
}
impl Frames {
#[must_use]
pub fn new(mu: f64) -> Self {
Self {
frames: vec![Frame {
parent: None,
children: Vec::new(),
depth: 0,
mu,
soi_radius: f64::INFINITY,
origin: WorldPos::ORIGIN,
velocity: DVec3::ZERO,
}],
}
}
#[inline]
#[must_use]
pub fn root(&self) -> FrameId {
FrameId(0)
}
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.frames.len()
}
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
false
}
pub fn add(
&mut self,
parent: FrameId,
mu: f64,
soi_radius: f64,
origin: WorldPos,
velocity: DVec3,
) -> FrameId {
assert!(
soi_radius > 0.0,
"a frame's sphere of influence must have a positive radius, got {soi_radius}"
);
let id = FrameId(u32::try_from(self.frames.len()).expect("frame count fits in u32"));
let depth = self.frames[parent.index()].depth + 1;
self.frames.push(Frame {
parent: Some(parent),
children: Vec::new(),
depth,
mu,
soi_radius,
origin: origin.normalize(),
velocity,
});
self.frames[parent.index()].children.push(id);
id
}
#[inline]
#[must_use]
pub fn parent(&self, id: FrameId) -> Option<FrameId> {
self.frames[id.index()].parent
}
#[inline]
#[must_use]
pub fn children(&self, id: FrameId) -> &[FrameId] {
&self.frames[id.index()].children
}
#[inline]
#[must_use]
pub fn mu(&self, id: FrameId) -> f64 {
self.frames[id.index()].mu
}
#[inline]
#[must_use]
pub fn soi_radius(&self, id: FrameId) -> f64 {
self.frames[id.index()].soi_radius
}
#[inline]
#[must_use]
pub fn state_in_parent(&self, id: FrameId) -> State {
let frame = &self.frames[id.index()];
State::new(frame.origin, frame.velocity)
}
pub fn set_state(&mut self, id: FrameId, state: State) {
assert!(
self.frames[id.index()].parent.is_some(),
"the root frame's origin is what every other frame is measured from and cannot move"
);
let frame = &mut self.frames[id.index()];
frame.origin = state.position.normalize();
frame.velocity = state.velocity;
}
#[must_use]
pub fn common_ancestor(&self, a: FrameId, b: FrameId) -> FrameId {
let (mut a, mut b) = (a, b);
while self.frames[a.index()].depth > self.frames[b.index()].depth {
a = self.frames[a.index()]
.parent
.expect("a deeper frame has a parent");
}
while self.frames[b.index()].depth > self.frames[a.index()].depth {
b = self.frames[b.index()]
.parent
.expect("a deeper frame has a parent");
}
while a != b {
a = self.frames[a.index()]
.parent
.expect("frames level and unequal are not the root");
b = self.frames[b.index()]
.parent
.expect("frames level and unequal are not the root");
}
a
}
#[must_use]
pub fn convert(&self, state: State, from: FrameId, to: FrameId) -> State {
let meeting = self.common_ancestor(from, to);
let mut state = state;
let mut up = from;
while up != meeting {
let frame = &self.frames[up.index()];
state.position = compose(frame.origin, state.position);
state.velocity += frame.velocity;
up = frame.parent.expect("the walk stops at the common ancestor");
}
let mut down = Vec::new();
let mut cursor = to;
while cursor != meeting {
down.push(cursor);
cursor = self.frames[cursor.index()]
.parent
.expect("the walk stops at the common ancestor");
}
for id in down.into_iter().rev() {
let frame = &self.frames[id.index()];
state.position = decompose(state.position, frame.origin);
state.velocity -= frame.velocity;
}
state
}
#[must_use]
pub fn transition(&self, state: State, frame: FrameId) -> Option<FrameId> {
let here = &self.frames[frame.index()];
for &child in &here.children {
let inside = &self.frames[child.index()];
if state.position.distance(inside.origin) < inside.soi_radius {
return Some(child);
}
}
if state.position.distance(WorldPos::ORIGIN) >= here.soi_radius {
return here.parent;
}
None
}
}
#[must_use]
#[expect(
clippy::disallowed_methods,
reason = "no constructed power exists yet; a sphere of influence is set up once \
per frame rather than stepped, and docs/backlog.md carries it"
)]
pub fn sphere_of_influence(semi_major_axis: f64, mu: f64, primary_mu: f64) -> f64 {
assert!(
semi_major_axis >= 0.0,
"a semi-major axis is not negative, got {semi_major_axis}"
);
assert!(
mu >= 0.0,
"a gravitational parameter is not negative, got {mu}"
);
assert!(
primary_mu > 0.0,
"the primary must have mass for a sphere of influence to be defined, got {primary_mu}"
);
semi_major_axis * (mu / primary_mu).powf(0.4)
}
fn compose(origin: WorldPos, offset: WorldPos) -> WorldPos {
WorldPos::new(
saturating_add(origin.sector, offset.sector),
origin.local + offset.local,
)
}
fn decompose(position: WorldPos, origin: WorldPos) -> WorldPos {
WorldPos::new(
saturating_sub(position.sector, origin.sector),
position.local - origin.local,
)
}
fn saturating_add(a: I64Vec3, b: I64Vec3) -> I64Vec3 {
I64Vec3::new(
a.x.saturating_add(b.x),
a.y.saturating_add(b.y),
a.z.saturating_add(b.z),
)
}
fn saturating_sub(a: I64Vec3, b: I64Vec3) -> I64Vec3 {
I64Vec3::new(
a.x.saturating_sub(b.x),
a.y.saturating_sub(b.y),
a.z.saturating_sub(b.z),
)
}
#[cfg(test)]
mod tests {
use super::*;
const SUN_MU: f64 = 1.327_124_400_18e20;
const EARTH_MU: f64 = 3.986_004_418e14;
const MOON_MU: f64 = 4.902_800_118e12;
const EARTH_ORBIT: f64 = 1.495_978_707e11;
const MOON_ORBIT: f64 = 3.844_00e8;
fn solar_system() -> (Frames, FrameId, FrameId, FrameId) {
let mut frames = Frames::new(SUN_MU);
let sun = frames.root();
let earth = frames.add(
sun,
EARTH_MU,
sphere_of_influence(EARTH_ORBIT, EARTH_MU, SUN_MU),
WorldPos::from_offset(DVec3::new(EARTH_ORBIT, 0.0, 0.0)),
DVec3::new(0.0, 29_780.0, 0.0),
);
let moon = frames.add(
earth,
MOON_MU,
sphere_of_influence(MOON_ORBIT, MOON_MU, EARTH_MU),
WorldPos::from_offset(DVec3::new(MOON_ORBIT, 0.0, 0.0)),
DVec3::new(0.0, 1_022.0, 0.0),
);
(frames, sun, earth, moon)
}
#[test]
fn the_spheres_of_influence_match_the_published_radii() {
let earth = sphere_of_influence(EARTH_ORBIT, EARTH_MU, SUN_MU);
let published = 9.24e8;
assert!(
(earth - published).abs() <= published * 0.01,
"Earth's SOI came out {earth} m, published {published} m"
);
let moon = sphere_of_influence(MOON_ORBIT, MOON_MU, EARTH_MU);
let published = 6.61e7;
assert!(
(moon - published).abs() <= published * 0.01,
"the Moon's SOI came out {moon} m, published {published} m"
);
let base = sphere_of_influence(1.0, 1.0, 1.0e6);
let quadrupled = sphere_of_influence(1.0, 4.0, 1.0e6);
let ratio = quadrupled / base;
#[expect(
clippy::disallowed_methods,
reason = "the platform's power is the oracle"
)]
let expected = 4.0f64.powf(0.4);
assert!(
(ratio - expected).abs() < 1e-12,
"four times the mass must give {expected} times the radius, got {ratio}"
);
}
#[test]
fn a_conversion_out_and_back_returns_the_state_exactly() {
let (frames, sun, _earth, moon) = solar_system();
let start = State::new(
WorldPos::from_offset(DVec3::new(1.0e7, -2.5e6, 3.25e6)),
DVec3::new(-900.0, 120.5, 7.25),
);
let out = frames.convert(start, moon, sun);
let back = frames.convert(out, sun, moon);
assert_eq!(
back.position, start.position,
"a round trip through the hierarchy must return the same position"
);
assert_eq!(back.velocity, start.velocity);
}
#[test]
fn a_crossing_far_from_the_origin_keeps_millimetres() {
const FAR: f64 = 1.0e15;
const MILLIMETRE: f64 = 1.0e-3;
let mut frames = Frames::new(SUN_MU);
let sun = frames.root();
let far = frames.add(
sun,
EARTH_MU,
1.0e9,
WorldPos::from_offset(DVec3::new(FAR, FAR, FAR)),
DVec3::ZERO,
);
let a = State::new(
WorldPos::from_offset(DVec3::new(1.0e8, 0.0, 0.0)),
DVec3::ZERO,
);
let b = State::new(a.position.translated(DVec3::X * MILLIMETRE), DVec3::ZERO);
let before = a.position.distance(b.position);
assert!(
(before - MILLIMETRE).abs() < MILLIMETRE * 1e-6,
"the two should start about a millimetre apart, got {before} m"
);
let converted_a = frames.convert(a, far, sun);
let converted_b = frames.convert(b, far, sun);
let after = converted_a.position.distance(converted_b.position);
const SEAM: f64 = 1.0e-9;
assert!(
(after - before).abs() < SEAM,
"a millimetre {FAR} m from the origin came back as {after} m, from {before} m"
);
let naive_a = FAR + 1.0e8;
let naive_b = FAR + 1.0e8 + MILLIMETRE;
assert_eq!(
naive_b - naive_a,
0.0,
"an `f64` metre coordinate at {FAR} m cannot hold a millimetre at all, \
which is what the sector split is for"
);
}
#[test]
fn a_state_converts_between_siblings_through_their_common_ancestor() {
let (mut frames, sun, earth, moon) = solar_system();
let mars = frames.add(
sun,
4.282_837e13,
1.0e9,
WorldPos::from_offset(DVec3::new(0.0, 2.279_39e11, 0.0)),
DVec3::ZERO,
);
assert_eq!(frames.common_ancestor(moon, mars), sun);
assert_eq!(frames.common_ancestor(moon, earth), earth);
assert_eq!(frames.common_ancestor(earth, earth), earth);
let seen = frames.convert(State::AT_ORIGIN, moon, mars);
let expected = DVec3::new(EARTH_ORBIT + MOON_ORBIT, -2.279_39e11, 0.0);
let error = (seen.position.delta(WorldPos::ORIGIN) - expected).length();
assert!(
error < 1.0e-6,
"the Moon seen from Mars should be at {expected:?}, came out {:?}",
seen.position.delta(WorldPos::ORIGIN)
);
assert_eq!(seen.velocity, DVec3::new(0.0, 29_780.0 + 1_022.0, 0.0));
}
#[test]
fn a_body_crossing_a_boundary_is_handed_to_the_frame_that_now_dominates() {
let (frames, sun, earth, moon) = solar_system();
let moon_soi = frames.soi_radius(moon);
let inside = State::new(
WorldPos::from_offset(DVec3::new(moon_soi * 0.5, 0.0, 0.0)),
DVec3::ZERO,
);
assert_eq!(
frames.transition(inside, moon),
None,
"a body well inside the Moon's sphere of influence stays in it"
);
let outside = State::new(
WorldPos::from_offset(DVec3::new(moon_soi * 1.5, 0.0, 0.0)),
DVec3::ZERO,
);
assert_eq!(
frames.transition(outside, moon),
Some(earth),
"past the Moon's sphere of influence, Earth dominates"
);
let near_moon = frames.convert(inside, moon, earth);
assert_eq!(
frames.transition(near_moon, earth),
Some(moon),
"a body inside the Moon's sphere of influence is handed to the Moon"
);
let between = State::new(
WorldPos::from_offset(DVec3::new(MOON_ORBIT * 0.5, 0.0, 0.0)),
DVec3::ZERO,
);
assert_eq!(frames.transition(between, earth), None);
let anywhere = State::new(WorldPos::from_offset(DVec3::splat(1.0e18)), DVec3::ZERO);
assert_eq!(frames.transition(anywhere, sun), None);
}
#[test]
fn a_transition_leaves_the_physical_state_untouched() {
let (frames, sun, earth, moon) = solar_system();
let moon_soi = frames.soi_radius(moon);
let leaving = State::new(
WorldPos::from_offset(DVec3::new(moon_soi, 0.0, 0.0)),
DVec3::new(310.0, -40.0, 5.0),
);
assert_eq!(frames.transition(leaving, moon), Some(earth));
let handed_over = frames.convert(leaving, moon, earth);
assert_eq!(
frames.convert(handed_over, earth, sun),
frames.convert(leaving, moon, sun),
"the same body seen from the root must not move when it changes frame"
);
let moon_origin = frames.state_in_parent(moon).position;
let still_there = handed_over.position.distance(moon_origin);
assert!(
(still_there - moon_soi).abs() < 1.0e-6,
"the body was {moon_soi} m from the Moon and is now {still_there} m from it"
);
assert_eq!(
handed_over.velocity - leaving.velocity,
frames.state_in_parent(moon).velocity
);
}
#[test]
fn moving_a_frame_moves_what_is_measured_through_it() {
let (mut frames, sun, _earth, moon) = solar_system();
let before = frames.convert(State::AT_ORIGIN, moon, sun);
let shifted = frames.state_in_parent(moon);
frames.set_state(
moon,
State::new(
shifted.position.translated(DVec3::new(0.0, 1.0e6, 0.0)),
shifted.velocity,
),
);
let after = frames.convert(State::AT_ORIGIN, moon, sun);
let moved = after.position.delta(before.position);
assert!(
(moved - DVec3::new(0.0, 1.0e6, 0.0)).length() < 1.0e-6,
"moving the Moon a megametre should move a body sitting on it the same, got {moved:?}"
);
}
}