# Technical Reference - Orbital Mechanics Simulation
# Orbital Mechanics Simulation - Conceptual Reference
## Overview
N-body orbital mechanics simulator using analytical propagation for precise Keplerian trajectories. Supports elliptical, parabolic, and hyperbolic orbits with SOI (Sphere of Influence) transitions, impulsive burns, and 3D visualization using Raylib.
N-body orbital mechanics simulator using **analytical propagation** for precise Keplerian trajectories. Supports elliptical, parabolic, and hyperbolic orbits with dynamic Sphere of Influence (SOI) transitions, impulsive burns, and 3D visualization via Raylib.
## Architecture
C-style C++ implementation (structs/functions, no classes/templates) with modular design. The system is organized into these interconnected modules: Main (entry point), Simulation (core loop), Orbital Mechanics (Keplerian propagation), Physics (vector/matrix math), Maneuver (impulsive burns), Spacecraft (craft logic), Config Validator (validation), Test Utilities (testing helpers), Renderer (3D visualization), UI Renderer (2D panels), and Config Loader (TOML parsing). Main depends on simulation, renderer, and UI renderer. Simulation module coordinates physics calculations and depends on orbital mechanics, maneuver, spacecraft, and config loader modules. Renderer depends on config loader for configuration. See module sections below for detailed descriptions.
## Core Data Structures
Modular C-style C++ (structs/functions, no classes). Module dependencies:
### Vec3 (physics.h)
3D vector for position, velocity, and acceleration
```cpp
struct Vec3 {
double x, y, z;
};
```
### Mat3 (physics.h)
3x3 row-major matrix for coordinate transformations
```cpp
struct Mat3 {
double m00, m01, m02;
double m10, m11, m12;
double m20, m21, m22;
};
Main → Simulation → Orbital Mechanics → Physics
→ Maneuver
→ Config Loader
```
### OrbitalElements (orbital_mechanics.h)
Keplerian orbital elements using union for parabolic/hyperbolic distinction
Renderer and UI Renderer depend on Config Loader for display data. Test Utilities are standalone.
## Coordinate Frame System
**Local Frame**: Position/velocity relative to parent body. Primary system for orbital mechanics calculations. Maintains double-precision accuracy for small orbits (LEO, lunar).
**Global Frame**: Position/velocity from simulation origin (Sun at 0,0,0). Computed as `global = parent.global + local`. Used for SOI distance calculations and rendering.
**Conversion**: Simple vector addition/subtraction. All bodies and spacecraft store both local and global coordinates.
## Core Data Structures
### Vec3
3D vector (x, y, z). Operations: add, sub, cross, scale, magnitude, distance, normalize, dot.
### Mat3
3x3 row-major matrix. Used for orbital plane rotations (z-x-z Euler angles).
### OrbitalElements
Keplerian elements with union for parabolic/hyperbolic distinction:
**Hyperbolic (e > 1)**: Newton-Raphson on H - e·sinh(H) = M. Mean motion: n = √(μ/(-a)³) using negative semi-major axis. Initial guess: H = log(2M/e) when e·sinh(M) > M, else H = M.
## Orbital Element Reconstruction
### Local Frame
- Position/velocity relative to parent body
- Used for orbital mechanics calculations
- Primary coordinate system for propagation
Elements are dynamically maintained and reconstructed from Cartesian state when:
- **SOI transitions**: Parent changes, local coordinates update
- **Burns**: Velocity changes impulsively
- **Velocity drift**: |v_local - v_expected| > 1e-6 m/s before propagation
### Global Frame
- Position/velocity from simulation origin (Sun at 0,0,0)
- Computed each frame: `global = parent.global + local`
- Used for SOI distance calculations and rendering
Reconstruction uses `cartesian_to_orbital_elements()` which handles edge cases (near-circular e <1e-10,near-parabolic).
## Coordinate Transformations
Orbital plane orientation via z-x-z Euler rotation:
```
R_total = R_z(Ω) · R_x(i) · R_z(ω)
```
### Benefits
- Precision: Local coordinates use full double precision for small orbits (LEO, moon)
- Clarity: Separates orbit physics from system-wide positions
- Efficiency: SOI checks use global distances, propagation uses local
- Flexibility: Easy to add/remove bodies by updating parent_index
### Conversion Functions
- Local to global: `vec3_add(parent.global, local)`
- Global to local: `vec3_sub(global, parent.global)`
## Key Modules
### 1. Physics Module (physics.h/cpp)
Vector and matrix math utilities for orbital mechanics.
- All satisfy vis-viva equation: v² = μ(2/r - 1/a)
## Data Flow
### Initialization Sequence
The simulation initializes in this sequence: create_simulation() is called first, then load_system_config() parses the TOML file and loads bodies, spacecraft, and maneuvers. Next, run_all_config_validations() performs system-level validation. Then initialize_orbital_objects() converts orbital elements to local position/velocity for all bodies and spacecraft, computes global coordinates, and calculates SOI radii. Finally, the main simulation loop begins.
### Main Simulation Loop
The main simulation loop executes in this order: update_bodies_physics(), compute_global_coordinates(), execute_pending_maneuvers(), update_spacecraft_physics(), compute_spacecraft_globals(), then increments simulation time. Within update_bodies_physics(), for each body: check SOI via find_dominant_body, handle transitions by computing global coordinates from old parent, updating parent_index, computing new local coordinates, and reconstructing orbital elements. Then check velocity deviation with 1e-6 tolerance and reconstruct elements if needed. Propagate elements via propagate_orbital_elements() and update local position/velocity. compute_global_coordinates() updates all body global positions from parent.global + local. execute_pending_maneuvers() checks each unexecuted maneuver for time or true anomaly triggers. For true anomaly triggers: if crossing detected, sets scheduled_dt to time needed to reach target. When triggered, propagates spacecraft by scheduled_dt to exact position, executes burn, propagates remaining frame time, and marks spacecraft as handled to skip in update_spacecraft_physics(). update_spacecraft_physics() propagates spacecraft not already handled this frame. compute_spacecraft_globals() updates all spacecraft global positions.
### SOI Mechanics
SOI transitions are detected by calling find_dominant_body() before each physics update. If the parent changes, the body's global coordinates are computed in the old frame, the parent_index is updated, new local coordinates are computed, and orbital elements are reconstructed. Propagation then uses the new local frame.
## Location Hints
### Constants
- Gravitational constant: `G` in physics.h
- Parabolic tolerance: `PARABOLIC_TOLERANCE` in orbital_mechanics.h
- Kepler solver tolerance: `KEPLER_TOLERANCE` in orbital_mechanics.cpp
- SOI mass ratio: `MIN_MASS_RATIO` in config_validator.h
### Config Files
- Example: `configs/solar_system.toml`
- Format: TOML with [[bodies]], [[spacecraft]], [[maneuvers]] arrays
Use `WithinAbs(expected, tolerance)` for floating-point comparisons (NOT `Approx()`).
## Hybrid Documentation Strategy
This document provides high-level concepts and architecture. Per-module summary files (`src/*.summary.md`) contain detailed function documentation including signatures, parameters, formulas, and edge cases. Use both: this for the big picture, summaries for implementation details.
pi --model Qwen3.5-35B --provider llama.cpp --print "Summarize the module src/orbital_mechanics . Do not read in any other files, we will use this summary as input into another llm session. we need to preserve any interface structs,enums,function signatures, etc as the original source code, along with a concise summary of each. Only provide a detailed explaination for functions with complex algorithms. The Formatting should be summary first, then original source code underneath. Add any extra info as inline comments to the source"