use std::collections::HashMap;
use avian2d::math::TAU;
use avian2d::prelude::LinearVelocity;
use bevy::log::debug;
use bevy::math::ops::atan2;
use bevy::prelude::{Component, Plugin, Transform};
use bevy::time::Time;
use serde::{Deserialize, Serialize};
use crate::config::planet::{Planet, PlanetSpring, PlanetSpringJoint};
use crate::prelude::{App, Query, Res, Update, Without};
pub struct OrbitPlugin;
impl Plugin for OrbitPlugin {
fn build(&self, app: &mut App) {
app.add_systems(Update, update_orbits);
}
}
fn update_orbits(
mut planets: Query<(&Planet, &Transform, &mut LinearVelocity), Without<PlanetSpring>>,
planets_2: Query<(&Planet, &Transform), Without<PlanetSpring>>,
mut planet_springs: Query<(&PlanetSpring, &mut Transform), Without<Planet>>,
time: Res<Time>
) {
let parent_velocities = planets.iter().map(|u| (u.0.name.clone(), u.2.clone())).collect::<HashMap<String, LinearVelocity>>();
for (planet, _, mut vel) in planets.iter_mut() {
let Some(orbit_data) = &planet.orbit else { continue; };
// find parent
let Some(parent) = planets_2.iter().find(|u| u.0.name == orbit_data.orbiting) else { continue; };
let a = (planet.default_transform[0] - parent.0.default_transform[0]) / (1.0 - orbit_data.eccentricity);
let e = orbit_data.eccentricity;
let t = orbit_data.period;
let time = time.elapsed_secs();
// calculate position of the planet
let m = (TAU / t) * time;
let e_k = iterative_kepler(m, e);
let nu = 2.0 * atan2(
(1.0 + e).sqrt() * (e_k / 2.0).sin(),
(1.0 - e).sqrt() * (e_k / 2.0).cos(),
);
let r = a * (1.0 - e * e_k.cos());
let x = r * nu.cos();
let y = r * nu.sin();
// find the spring
let Some(mut planet_spring) = planet_springs.iter_mut().find(|u| u.0.name == planet.name) else { continue; };
planet_spring.1.translation.x = x + parent.1.translation.x;
planet_spring.1.translation.y = y + parent.1.translation.y;
let Some(parent_velocity) = parent_velocities.get(&orbit_data.orbiting) else { continue; };
let de_dt = (TAU / t) / (1.0 - e * e_k.cos());
let b_factor = (1.0 - e * e).sqrt();
let vx = -a * e_k.sin() * de_dt;
let vy = a * b_factor * e_k.cos() * de_dt;
vel.x = vx + parent_velocity.x;
vel.y = vy + parent_velocity.y;
}
}
fn iterative_kepler(m: f32, e: f32) -> f32 {
let mut output = m;
for _ in 0..100 {
let d = (m - output + e * output.sin()) / (1.0 - e * output.cos());
output += d;
if d.abs() < 1e-10 {
break;
}
}
output
}