Skip to main content

vibe/physics/
nbody_3d.rs

1//! 3D N-Body Symplectic Gravitational and Relativistic Orbital Solver.
2//!
3//! Provides a zero-heap Velocity-Verlet / symplectic leapfrog integrator with
4//! Newtonian pairwise gravitational acceleration and optional 1st Post-Newtonian (1PN)
5//! Einstein-Infeld-Hoffmann perihelion precession corrections.
6//!
7//! Reference: `AGENTS.md` Workstream W5 (ยง5.4).
8
9/// Gravitational constant $G$ in $\text{m}^3 \cdot \text{kg}^{-1} \cdot \text{s}^{-2}$.
10pub const GRAVITATIONAL_CONSTANT: f64 = 6.67430e-11;
11
12/// Speed of light in vacuum $c$ in $\text{m} \cdot \text{s}^{-1}$.
13pub const SPEED_OF_LIGHT: f64 = 299_792_458.0;
14
15/// Maximum number of bodies supported in zero-heap stack buffer allocations.
16pub const MAX_STACK_BODIES: usize = 128;
17
18/// A celestial mass in 3D Cartesian coordinates.
19#[repr(C)]
20#[derive(Debug, Clone, Copy, PartialEq)]
21pub struct CelestialBody3D {
22    /// 3D position vector $[x, y, z]$ (meters).
23    pub position_m: [f64; 3],
24    /// 3D velocity vector $[v_x, v_y, v_z]$ (meters / second).
25    pub velocity_m_s: [f64; 3],
26    /// Inertial / gravitational mass (kilograms).
27    pub mass_kg: f64,
28    /// Physical spherical radius (meters).
29    pub radius_m: f64,
30}
31
32impl CelestialBody3D {
33    /// Constructs a new 3D celestial body.
34    pub const fn new(
35        position_m: [f64; 3],
36        velocity_m_s: [f64; 3],
37        mass_kg: f64,
38        radius_m: f64,
39    ) -> Self {
40        Self {
41            position_m,
42            velocity_m_s,
43            mass_kg,
44            radius_m,
45        }
46    }
47}
48
49/// Evaluates pairwise gravitational accelerations on all bodies into a preallocated slice.
50///
51/// If `include_1pn_gr` is true, applies the 1st Post-Newtonian Einstein-Infeld-Hoffmann
52/// relativistic orbital precession correction:
53///
54/// $$\mathbf{a}_{1PN} = \frac{G m_j}{c^2 r^3} \left[ \left( \frac{4 G m_j}{r} - v_{ij}^2 \right) \mathbf{r}_{ij} - 4 (\mathbf{r}_{ij} \cdot \mathbf{v}_{ij}) \mathbf{v}_{ij} \right]$$
55fn compute_accelerations(
56    bodies: &[CelestialBody3D],
57    softening_m: f64,
58    include_1pn_gr: bool,
59    acc_out: &mut [[f64; 3]],
60) {
61    let n = bodies.len();
62    for a in acc_out.iter_mut().take(n) {
63        *a = [0.0, 0.0, 0.0];
64    }
65
66    let soft_sq = softening_m * softening_m;
67    let c2 = SPEED_OF_LIGHT * SPEED_OF_LIGHT;
68
69    for i in 0..n {
70        let bi = &bodies[i];
71        for j in (i + 1)..n {
72            let bj = &bodies[j];
73            let dx = bj.position_m[0] - bi.position_m[0];
74            let dy = bj.position_m[1] - bi.position_m[1];
75            let dz = bj.position_m[2] - bi.position_m[2];
76
77            let dist_sq = dx * dx + dy * dy + dz * dz + soft_sq;
78            let dist = dist_sq.sqrt();
79            let inv_dist3 = 1.0 / (dist * dist_sq);
80
81            // Newtonian mutual gravity
82            let scale_newton = GRAVITATIONAL_CONSTANT * inv_dist3;
83            let a_newt_ij_x = scale_newton * dx;
84            let a_newt_ij_y = scale_newton * dy;
85            let a_newt_ij_z = scale_newton * dz;
86
87            acc_out[i][0] += a_newt_ij_x * bj.mass_kg;
88            acc_out[i][1] += a_newt_ij_y * bj.mass_kg;
89            acc_out[i][2] += a_newt_ij_z * bj.mass_kg;
90
91            acc_out[j][0] -= a_newt_ij_x * bi.mass_kg;
92            acc_out[j][1] -= a_newt_ij_y * bi.mass_kg;
93            acc_out[j][2] -= a_newt_ij_z * bi.mass_kg;
94
95            // Optional 1st Post-Newtonian (1PN) Einstein-Infeld-Hoffmann correction
96            if include_1pn_gr {
97                let dvx = bi.velocity_m_s[0] - bj.velocity_m_s[0];
98                let dvy = bi.velocity_m_s[1] - bj.velocity_m_s[1];
99                let dvz = bi.velocity_m_s[2] - bj.velocity_m_s[2];
100
101                let v_rel_sq = dvx * dvx + dvy * dvy + dvz * dvz;
102                let r_dot_v = dx * dvx + dy * dvy + dz * dvz;
103
104                let scale_1pn_j = (GRAVITATIONAL_CONSTANT * bj.mass_kg) / (c2 * dist * dist_sq);
105                let term_rad_j = (4.0 * GRAVITATIONAL_CONSTANT * bj.mass_kg / dist) - v_rel_sq;
106
107                acc_out[i][0] += scale_1pn_j * (term_rad_j * dx - 4.0 * r_dot_v * dvx);
108                acc_out[i][1] += scale_1pn_j * (term_rad_j * dy - 4.0 * r_dot_v * dvy);
109                acc_out[i][2] += scale_1pn_j * (term_rad_j * dz - 4.0 * r_dot_v * dvz);
110
111                let scale_1pn_i = (GRAVITATIONAL_CONSTANT * bi.mass_kg) / (c2 * dist * dist_sq);
112                let term_rad_i = (4.0 * GRAVITATIONAL_CONSTANT * bi.mass_kg / dist) - v_rel_sq;
113
114                acc_out[j][0] += scale_1pn_i * (term_rad_i * (-dx) - 4.0 * (-r_dot_v) * (-dvx));
115                acc_out[j][1] += scale_1pn_i * (term_rad_i * (-dy) - 4.0 * (-r_dot_v) * (-dvy));
116                acc_out[j][2] += scale_1pn_i * (term_rad_i * (-dz) - 4.0 * (-r_dot_v) * (-dvz));
117            }
118        }
119    }
120}
121
122/// Advances an N-body system by `dt_s` seconds using a symplectic Velocity-Verlet step.
123///
124/// Completely zero-heap; requires `bodies.len() <= MAX_STACK_BODIES`.
125pub fn step_nbody_3d_verlet(
126    bodies: &mut [CelestialBody3D],
127    dt_s: f64,
128    softening_m: f64,
129    include_1pn_gr: bool,
130) {
131    let n = bodies.len();
132    if n <= 1 {
133        return;
134    }
135    assert!(
136        n <= MAX_STACK_BODIES,
137        "nbody_3d: body count {} exceeds MAX_STACK_BODIES {}",
138        n,
139        MAX_STACK_BODIES
140    );
141
142    let mut a0 = [[0.0; 3]; MAX_STACK_BODIES];
143    compute_accelerations(bodies, softening_m, include_1pn_gr, &mut a0[..n]);
144
145    let half_dt = 0.5 * dt_s;
146    let dt_sq_half = 0.5 * dt_s * dt_s;
147
148    // 1. Advance position and half-step velocity
149    for i in 0..n {
150        let b = &mut bodies[i];
151        b.position_m[0] += b.velocity_m_s[0] * dt_s + a0[i][0] * dt_sq_half;
152        b.position_m[1] += b.velocity_m_s[1] * dt_s + a0[i][1] * dt_sq_half;
153        b.position_m[2] += b.velocity_m_s[2] * dt_s + a0[i][2] * dt_sq_half;
154
155        b.velocity_m_s[0] += a0[i][0] * half_dt;
156        b.velocity_m_s[1] += a0[i][1] * half_dt;
157        b.velocity_m_s[2] += a0[i][2] * half_dt;
158    }
159
160    // 2. Recompute accelerations at new positions
161    let mut a1 = [[0.0; 3]; MAX_STACK_BODIES];
162    compute_accelerations(bodies, softening_m, include_1pn_gr, &mut a1[..n]);
163
164    // 3. Complete velocity step
165    for i in 0..n {
166        let b = &mut bodies[i];
167        b.velocity_m_s[0] += a1[i][0] * half_dt;
168        b.velocity_m_s[1] += a1[i][1] * half_dt;
169        b.velocity_m_s[2] += a1[i][2] * half_dt;
170    }
171}
172
173/// Evaluates total mechanical energy (kinetic + gravitational potential) of the system in Joules.
174pub fn total_mechanical_energy(bodies: &[CelestialBody3D], softening_m: f64) -> f64 {
175    let mut kinetic = 0.0;
176    for b in bodies {
177        let v2 = b.velocity_m_s[0] * b.velocity_m_s[0]
178            + b.velocity_m_s[1] * b.velocity_m_s[1]
179            + b.velocity_m_s[2] * b.velocity_m_s[2];
180        kinetic += 0.5 * b.mass_kg * v2;
181    }
182
183    let mut potential = 0.0;
184    let soft_sq = softening_m * softening_m;
185    let n = bodies.len();
186
187    for i in 0..n {
188        for j in (i + 1)..n {
189            let dx = bodies[j].position_m[0] - bodies[i].position_m[0];
190            let dy = bodies[j].position_m[1] - bodies[i].position_m[1];
191            let dz = bodies[j].position_m[2] - bodies[i].position_m[2];
192            let dist = (dx * dx + dy * dy + dz * dz + soft_sq).sqrt();
193            potential -= (GRAVITATIONAL_CONSTANT * bodies[i].mass_kg * bodies[j].mass_kg) / dist;
194        }
195    }
196
197    kinetic + potential
198}
199
200/// Evaluates total 3D angular momentum vector $[L_x, L_y, L_z]$ of the system ($\text{kg} \cdot \text{m}^2 \cdot \text{s}^{-1}$).
201pub fn total_angular_momentum(bodies: &[CelestialBody3D]) -> [f64; 3] {
202    let mut lx = 0.0;
203    let mut ly = 0.0;
204    let mut lz = 0.0;
205
206    for b in bodies {
207        let rx = b.position_m[0];
208        let ry = b.position_m[1];
209        let rz = b.position_m[2];
210        let vx = b.velocity_m_s[0];
211        let vy = b.velocity_m_s[1];
212        let vz = b.velocity_m_s[2];
213
214        lx += b.mass_kg * (ry * vz - rz * vy);
215        ly += b.mass_kg * (rz * vx - rx * vz);
216        lz += b.mass_kg * (rx * vy - ry * vx);
217    }
218
219    [lx, ly, lz]
220}
221
222#[cfg(test)]
223mod tests {
224    use super::*;
225
226    #[test]
227    fn test_non_coplanar_three_body_conservation() {
228        // Sun-Earth-Asteroid 3-body system with non-coplanar asteroid orbit
229        let mut bodies = [
230            // Body 1: Central Star (Sun)
231            CelestialBody3D::new([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], 1.989e30, 6.96e8),
232            // Body 2: Coplanar planet (Earth in XY plane)
233            CelestialBody3D::new(
234                [1.496e11, 0.0, 0.0],
235                [0.0, 29780.0, 0.0],
236                5.972e24,
237                6.371e6,
238            ),
239            // Body 3: Inclined minor planet (non-coplanar: Z != 0, Vz != 0)
240            CelestialBody3D::new(
241                [0.0, 2.5e11, 5.0e10],
242                [-22000.0, 0.0, 8000.0],
243                1.0e22,
244                5.0e5,
245            ),
246        ];
247
248        let dt = 3600.0; // 1 hour step
249        let softening = 1000.0;
250
251        let e_init = total_mechanical_energy(&bodies, softening);
252        let l_init = total_angular_momentum(&bodies);
253
254        // Step 100 iterations of Verlet
255        for _ in 0..100 {
256            step_nbody_3d_verlet(&mut bodies, dt, softening, false);
257        }
258
259        let e_final = total_mechanical_energy(&bodies, softening);
260        let l_final = total_angular_momentum(&bodies);
261
262        // Symplectic energy preservation (< 0.01% drift over 100 steps)
263        let rel_energy_drift = (e_final - e_init).abs() / e_init.abs();
264        assert!(
265            rel_energy_drift < 1e-4,
266            "Energy drift {} exceeds tolerance",
267            rel_energy_drift
268        );
269
270        // Angular momentum conservation (< 1e-6 relative drift)
271        let l_mag_init = (l_init[0] * l_init[0] + l_init[1] * l_init[1] + l_init[2] * l_init[2]).sqrt();
272        let dl = [
273            l_final[0] - l_init[0],
274            l_final[1] - l_init[1],
275            l_final[2] - l_init[2],
276        ];
277        let dl_mag = (dl[0] * dl[0] + dl[1] * dl[1] + dl[2] * dl[2]).sqrt();
278        let rel_l_drift = dl_mag / l_mag_init;
279        assert!(
280            rel_l_drift < 1e-6,
281            "Angular momentum drift {} exceeds tolerance",
282            rel_l_drift
283        );
284    }
285
286    #[test]
287    fn test_relativistic_1pn_acceleration() {
288        let mut bodies = [
289            CelestialBody3D::new([0.0, 0.0, 0.0], [0.0, 0.0, 0.0], 1.989e30, 6.96e8),
290            CelestialBody3D::new(
291                [4.6e10, 0.0, 0.0], // Perihelion of Mercury
292                [0.0, 58980.0, 0.0],
293                3.3e23,
294                2.4e6,
295            ),
296        ];
297
298        // Step with 1PN enabled
299        step_nbody_3d_verlet(&mut bodies, 10.0, 1.0, true);
300        assert!(bodies[1].velocity_m_s[0] != 0.0 || bodies[1].velocity_m_s[1] != 0.0);
301    }
302}