Browse Source

Restructure documentation: extract and consolidate

- Rename implementation_plan.md → technical_reference.md
- Extract rendering system to docs/rendering.md
- Extract future work to docs/future_work.md
- Consolidate coordinate frame sections (top-level + Local Coordinate Frames)
- Add spacecraft and maneuver config loader documentation
- Remove AccelerationContext struct (no longer used)
- Remove Implementation Status section
- Update references in README.md, AGENTS.md, opencode.json
main
cinnaboot 6 months ago
parent
commit
b045d09c94
  1. 4
      AGENTS.md
  2. 2
      README.md
  3. 258
      docs/future_work.md
  4. 308
      docs/rendering.md
  5. 264
      docs/technical_reference.md
  6. 2
      opencode.json

4
AGENTS.md

@ -7,7 +7,8 @@
## Architecture
- C-style C++ (structs/functions, NO classes/templates)
- Raylib (git submodule) for 3D - chose over SFML (no 3D support)
- See docs/implementation_plan.md for data structures reference
- See docs/technical_reference.md for data structures reference
- See docs/rendering.md for rendering system reference
## Coding Rules
- Use .cpp extensions (for future C++ features if needed)
@ -35,6 +36,7 @@
- Format: YYYY-MM-DD-descriptive-name.md
- Keep concise: changes made, commits, results (net line count)
- See existing summaries for reference format
- Always ask the user if we want to update the technical_reference after generating a summary
## Common Commands
- Build: make

2
README.md

@ -42,7 +42,7 @@ make clean-all # Clean everything including raylib
## Documentation
- **[Technical Reference](docs/implementation_plan.md)** - Data structures and module overview
- **[Technical Reference](docs/technical_reference.md)** - Data structures and module overview
## Testing

258
docs/future_work.md

@ -0,0 +1,258 @@
# Future Work - Project Roadmap
## Overview
This document outlines planned enhancements and future development areas for the Orbital Mechanics Simulation project.
## Immediate Priorities
### More Accurate Integration Methods
**Current:** RK4 (Runge-Kutta 4th order) integration
**Proposed:** Newton-Raphson propagation for higher precision
**Benefits:**
- Improved accuracy for long-term orbit predictions
- Better handling of near-parabolic trajectories
- Reduced numerical drift in N-body systems
**Implementation Considerations:**
- May require adaptive timestep sizing
- More complex than RK4
- Trade-off between accuracy and performance
### Reference Frame Switching
**Current:** Fixed global/local coordinate frames per body type
**Proposed:** Dynamic reference frame selection based on orbital regime
**Use Cases:**
- Spacecraft transitioning between planetary SOIs
- Interplanetary trajectories needing optimal precision
- Multi-body perturbation modeling
**Benefits:**
- Optimal numerical precision for all orbit types
- Automatic frame selection based on physics state
- Better simulation stability during SOI transitions
## Mid-Term Enhancements
### SOI Transition Frame Transformations (Phase 3)
**Status:** Partially implemented (SOI detection complete)
**Missing:** Proper coordinate transformations during SOI crossings
**Requirements:**
- Convert position/velocity between frames during transition
- Preserve orbital elements across frame boundaries
- Handle momentum and energy conservation
- Implement smooth interpolation to avoid discontinuities
**Implementation:**
- Define transformation matrices for frame changes
- Implement hysteresis to prevent oscillation
- Add validation tests for energy/momentum conservation
- Consider relative velocity of parent bodies
### Io and Titan Orbital Stability Tuning
**Issue:** Outer solar system moons exhibit orbital drift
**Approaches:**
- Reduced timestep for moon systems
- Specialized local frame handling
- Higher precision for distant parent-body interactions
- Moon-specific integration parameters
**Validation:**
- Long-term stability tests (> 100 orbits)
- Energy conservation metrics
- Orbital period accuracy verification
## Visualization Enhancements
### 3D Orbital Visualization with Inclination
**Current:** 2D orbits (XY plane simulation)
**Proposed:** Full 3D orbits with inclination support
**Features:**
- Orbit plane inclination angles
- Orbital node visualization (ascending/descending)
- 3D orbit path rendering
- Interactive inclination adjustment in UI
**Implementation:**
- Add inclination parameter to CelestialBody
- 3D position/velocity vectors
- Update orbit rendering for 3D basis
- UI controls for inclination editing
### Visual Highlighting of Selected Body
**Current:** Camera follows selected body, no visual emphasis
**Proposed:** Clear visual distinction for selected objects
**Options:**
- Different rendering style (solid vs wireframe)
- Selection indicator ring or brackets
- Highlighting color overlay
- Orbit path brightness boost
**UI Integration:**
- Sync with existing selection system
- Maintain readability of other objects
- Adjustable highlight intensity
### Enhanced UI Features
**Search Functionality:**
- Text search for bodies/spacecraft by name
- Filter by mass, parent, orbital parameters
- Keyboard shortcuts for quick access
**Multiple Selection:**
- Select multiple bodies for comparison
- Batch operations for group editing
- Comparative information display
**Orbital Metrics Panel:**
- Real-time orbital element display
- Period prediction
- Delta-v to parent calculations
- Time to periapsis/apoapsis
- Inclination and node information
**Configured Maneuvers UI:**
- Interactive maneuver planning
- Delta-v budget tracking
- Burn time predictions
- Visual maneuver timeline
## Advanced Physics Features
### N-Body Perturbations
**Current:** 2-body approximation (only parent influence)
**Proposed:** Full N-body gravitational interactions
**Benefits:**
- More realistic moon orbits
- Trojan point detection
- Perturbation-based trajectory corrections
- Multi-body SOI modeling
**Performance Considerations:**
- O(N²) complexity for all-body interactions
- May need spatial partitioning for large N
- Selective N-body for nearby bodies only
### Atmospheric Drag
**Use Case:** Spacecraft reentry and low orbit decay
**Implementation:**
- Atmosphere model for planets
- Drag force calculations
- Altitude-dependent density
- Reentry trajectory prediction
### Tidal Forces
**Application:**
- Orbital decay for close satellites
- Tidal locking evolution
- Roche limit calculations
- Tidal acceleration for moons
## Testing and Validation
### Expanded Test Suite
- Reference frame transition tests
- N-body interaction validation
- Long-term stability benchmarks (> 1000 orbits)
- Regression testing for numerical drift
- Performance profiling tests
### Orbital Mechanics Benchmarks
- Known orbital periods (Earth, Mars, Jupiter)
- Escape trajectory validation
- Hyperbolic asymptotic velocity checks
- SOI crossing accuracy
- Energy conservation across SOI boundaries
## Data and Configuration
### Expanded Solar System Data
- Dwarf planets (Pluto, Ceres, Eris)
- Asteroid belt objects
- Kuiper belt objects
- Cometary orbital data
- Real-world spacecraft trajectories
### Configurable Scenarios
- Earth-Moon system detailed modeling
- Exoplanet systems
- Binary star systems
- Asteroid flyby simulations
- Gravity assist maneuvers
## Performance Optimizations
### Adaptive Timestepping
- Smaller timesteps during SOI transitions
- Larger timesteps for stable orbits
- Error-based step size adjustment
- Performance-accuracy trade-off controls
### Multi-threading
- Parallel physics updates for independent bodies
- Multi-threaded orbit path rendering
- Parallel test execution
### GPU Acceleration
- GPU-based physics integration
- CUDA/OpenCL orbit calculations
- Raylib GPU rendering improvements
## Documentation and Examples
### Tutorial Scenarios
- Step-by-step orbital mechanics lessons
- Common maneuver examples (Hohmann transfer, gravity assist)
- Troubleshooting guide for orbital instability
### API Documentation
- Function reference with examples
- Configuration file reference
- Test writing guide
- Extension development guide
## Infrastructure
### Build System Enhancements
- CMake alternative to Makefile
- Package manager integration
- Dependency version pinning
- Cross-platform build testing
### Continuous Integration
- Automated testing on push
- Code coverage tracking
- Performance regression detection
- Multi-platform CI (Linux, macOS, Windows)
### Debugging Tools
- Orbit state visualization
- Frame transformation inspector
- Energy/momentum logging
- Interactive parameter adjustment
## Research Directions
### Relativistic Corrections
- Perihelion precession of Mercury
- General relativistic orbit adjustments
- Light-time corrections
### Non-gravitational Forces
- Solar radiation pressure
- Magnetic field interactions
- Thrust modeling for powered flight
### Orbital Determination
- Ephemeris matching
- Observation data fitting
- Orbit determination algorithms
- Uncertainty quantification

308
docs/rendering.md

@ -0,0 +1,308 @@
# Rendering System - Technical Reference
## Overview
3D visualization system using raylib for interactive orbital mechanics simulation. Supports logarithmic distance scaling, orbit path rendering, spacecraft tracking, and maneuver planning visualization.
## Core Data Structure
### RenderState (renderer.h)
```cpp
struct RenderState {
Camera3D camera;
double distance_scale; // Scale factor for distances
double size_scale; // Scale factor for body sizes
int selected_body_index; // -1 = no selection
int selected_craft_index; // -1 = no selection
int previous_selected_body; // Previous selected body index
int body_list_scroll; // Scroll position for body list
int body_list_active; // Active item index in body list
bool camera_follow_body; // Whether camera follows selected body
Vector3 camera_offset; // Offset from target when following body
bool was_following_body; // Previous frame follow state
};
```
## Coordinate Transformation
### Simulation to Render Coordinates
The simulation uses an XY plane while rendering uses XZ plane (Y is up in raylib).
**Transformation:**
- Simulation (X, Y, Z) → Render (X, -Z, Y)
- 90-degree rotation around X-axis
**Implementation:**
```cpp
Vector3 sim_to_render(Vec3 pos, double scale) {
return (Vector3){
(float)(pos.x * scale),
(float)(-pos.z * scale),
(float)(pos.y * scale)
};
}
```
### Scaling Factors
**Distance Scale:** `1e-9` (1 render unit = 1 billion meters)
- Optimized for solar system scale
- Used for position transformations
**Size Scale:** `1e-9` (same as distance scale)
- Applied to body radii
- Minimum visible radius: 0.5 units (ensures tiny bodies are visible)
**Radius Scaling:**
```cpp
float scale_radius(double radius, double scale) {
float scaled = (float)(radius * scale);
float min_radius = 0.5f;
return (scaled > min_radius) ? scaled : min_radius;
}
```
## Camera System
### Camera Setup
- Position: (0, 50, 100) initially
- Target: Origin (0, 0, 0)
- Up vector: (0, 1, 0)
- FOV: 45 degrees
- Projection: Perspective
### Camera Controls
**Arrow Keys:**
- Left/Right: Orbit around target (horizontal rotation)
- Up/Down: Zoom in/out (preserve viewing angle)
**Camera Follow Mode:**
- Tracks selected body or spacecraft
- Preserves relative offset when following
- Updates target position each frame to follow moving objects
- Maintains camera distance when switching between bodies
**Camera Rotation Logic:**
- Uses camera's up vector for horizontal orbit
- Rotates forward vector around up axis
- Preserves camera distance from target
**Follow State Transitions:**
1. **Enable follow**: Store current offset from target
2. **Body switch**: Recalculate offset to maintain distance
3. **Frame update**: Move camera to maintain offset from moving target
## Object Rendering
### Celestial Bodies
**Rendering:**
- Wireframe spheres (`DrawSphereWires`)
- Color from body's RGB values
- Position scaled and transformed to render coordinates
- Radius scaled with minimum visible size
**Order:** All bodies rendered after orbit paths
### Spacecraft
**Rendering:**
- Fixed-size wireframe spheres (5.0 units)
- Cyan color (0, 255, 255)
- Position scaled and transformed
**Purpose:** Visual marker for spacecraft tracking at solar system distances
### Maneuver Markers
**Rendering:**
- Cubes (`DrawCube`) colored by burn direction
- Size based on delta-v magnitude (2-10 units, clamped)
- Only shown for unexecuted maneuvers
- Positioned at spacecraft location
**Color Coding:**
- PROGRADE: Green (0, 255, 0)
- RETROGRADE: Red (255, 0, 0)
- NORMAL: Yellow (255, 255, 0)
- ANTINORMAL: Orange (255, 165, 0)
- RADIAL_IN: Magenta (255, 0, 255)
- RADIAL_OUT: Cyan (0, 255, 255)
- CUSTOM: White (255, 255, 255)
**Render Order:** Top layer, after spacecraft
## Orbit Rendering
### Orbital Basis Calculation
**Components:**
- `periapsis_dir`: Normalized eccentricity vector (points toward periapsis)
- `normal`: Normalized angular momentum vector (orbit plane normal)
- `q_vec`: Cross product of normal and periapsis_dir (completes basis)
**Purpose:** Defines orbital plane for transforming orbital elements to Cartesian coordinates
### Elliptical Orbits (e < 0.98)
**Parameters:**
- Semi-major axis: `a = -μ / (2 * specific_energy)`
- Semi-minor axis: `b = a * sqrt(1 - e²)`
- Focus offset: `c = a * e`
**Rendering:**
- 100 segments
- Full orbit (0 to 2π)
- Drawn as series of line segments in orbital basis
### Parabolic Orbits (0.98 ≤ e ≤ 1.02)
**Parameters:**
- Semi-latus rectum: `p = h² / μ`
**Rendering:**
- 80 segments
- True anomaly range: -π*0.95 to π*0.95 (avoid singularity at ±π)
- Escape trajectory path
### Hyperbolic Orbits (e > 1.02)
**Parameters:**
- Semi-major axis: `a = μ / (2 * (-specific_energy))` (negative for hyperbola)
- Semi-latus rectum: `p = a * (1 - e²)`
- Max true anomaly: `acos(-1/e) * 0.95`
**Rendering:**
- 60 segments
- Shows asymptotic behavior approaching true anomaly limit
- Fast escape trajectory visualization
**Orbit Color:** Half-intensity body color (128 alpha)
### Render Order
1. Reference grid
2. Orbit paths (for all bodies with parents)
3. Bodies
4. Spacecraft
5. Maneuver markers
## UI System (raygui)
### Info Panel (Bottom-Left)
**Content:**
- Simulation time (in days)
- Body count
- FPS
- Controls reference
- Config file name
**Dimensions:** 300×300 pixels
### Objects List (Top-Left)
**Content:**
- All celestial bodies (no prefix)
- All spacecraft (🚀 prefix)
- Scrollable list view
**Interaction:**
- Clicking enables camera follow
- Updates selected_body_index or selected_craft_index
- Triggers camera offset calculation
**Dimensions:** 200×400 pixels
### Info Panel (Top-Right)
**Content (Body Selected):**
- Name, mass, radius
- Position (global for root, local for children)
- Velocity magnitude
- Eccentricity, semi-major axis
- Parent body name
- SOI radius
**Content (Spacecraft Selected):**
- Name, mass
- Local position and velocity
- Parent body name
- Pending/Executed maneuver counts
**Empty:** Displays placeholder panel when nothing selected
**Dimensions:** 250×300 pixels
### Maneuver List (Below Info Panel)
**Content (Spacecraft Selected Only):**
- List of maneuvers for selected spacecraft
- Status prefix: [PENDING] or [DONE]
- Maneuver names
**Details:**
- Next pending maneuver: name and delta-v
- Last executed maneuver: name, delta-v, execution time
- "No maneuvers defined" if none exist
**Dimensions:** 300×400 pixels
**Position:** Y=320 (below info panel)
## Rendering Pipeline
### Main Loop Sequence
1. **BeginDrawing**: Clear background to black
2. **BeginMode3D**: Enter 3D rendering
3. **Draw Reference Grid**: Subtle gray grid lines
4. **Render Orbit Paths**: Calculate and draw all orbits
5. **Render Bodies**: Draw all celestial bodies
6. **Render Spacecraft**: Draw all spacecraft
7. **Render Maneuver Markers**: Draw pending maneuver indicators
8. **EndMode3D**: Exit 3D rendering
9. **Render UI Panels**: Draw all raygui panels
10. **EndDrawing**: Complete frame
### Performance Considerations
- 60 FPS target
- Wireframe rendering for faster performance
- Minimum visible size prevents tiny bodies
- Fixed spacecraft marker size for visibility at distance
- Clipped orbit segments to avoid infinite paths
## Module Functions
### Initialization
- `init_renderer(width, height, title)` - Setup raylib window
- `close_renderer()` - Cleanup raylib
- `setup_camera(render_state)` - Initialize camera parameters
### Camera
- `update_camera(render_state, sim)` - Handle input and camera follow
### Rendering
- `render_body(body, render_state)` - Draw single celestial body
- `render_spacecraft(craft, render_state)` - Draw spacecraft marker
- `render_maneuver_marker(craft, maneuver, render_state)` - Draw burn indicator
- `render_simulation(sim, render_state)` - Full scene rendering
### UI
- `render_info(sim)` - Bottom-left info panel
- `render_body_list_ui(sim, render_state)` - Objects selection panel
- `render_body_info_ui(sim, render_state)` - Top-right info panel
- `render_maneuver_list_ui(sim, render_state)` - Maneuver list panel
### Scaling
- `scale_position(pos, scale)` - Transform simulation to render position
- `scale_radius(radius, scale)` - Apply size scaling with minimum
## Technical Notes
### Raylib Integration
- Header-only raygui for UI
- raymath for vector operations
- Perspective 3D camera
- Wireframe sphere rendering
### Color Handling
- Body colors: float RGB (0.0-1.0) → byte RGB (0-255)
- Orbit colors: 50% intensity, 50% alpha
- Spacecraft: Fixed cyan
- Maneuvers: Direction-based colors with alpha
### Reference Grid
- Subtle gray lines (20, 20, 20) for minor axes
- Brighter axes (40, 40, 40) for X and Z zero lines
- Extends from -500 to 500 in both directions
- Helps orient user in 3D space
### Memory Management
- UI panels allocate temporary buffers for lists
- List text freed after rendering
- No persistent UI state allocation

264
docs/implementation_plan.md → docs/technical_reference.md

@ -7,8 +7,41 @@
- C-style C++ only: structs and functions, no classes or templates
- RK4 (Runge-Kutta 4th order) integration for physics
- Simple rotations (quaternions deferred)
- raylib for 3D visualization
- Single root body systems only (parent_index = -1 for exactly one body)
## Coordinate Frame Strategy
The simulation uses a hybrid coordinate frame system optimized for numerical precision in nested orbital systems.
**Global Frame:**
- Origin at root body (index 0, parent_index = -1)
- All positions/velocities are in meters relative to this origin
- Used for SOI calculations, rendering, and interplanetary trajectories
**Local Frame:**
- Position/velocity relative to gravitational parent
- Used for most bodies in stable nested orbits (moons around planets)
- RK4 integration operates in local frame to preserve floating-point precision
**Coordinate Frame Selection:**
- Bodies using local frame: Children with stable orbital relationships (e.g., moons orbiting planets)
- Bodies using global frame: Direct children of root body (planets) and bodies on interplanetary trajectories
- Dual coordinate storage maintained for seamless frame transitions during SOI crossings
**Benefits:**
- Eliminates large offsets in floating-point calculations (moon at 3.8×10⁸ m instead of 1.5×10¹¹ m)
- Isolates moon orbits from planetary perturbations
- Maintains full floating-point precision for small orbital changes
- Improved Earth-Moon orbital stability (20% drift → stable)
**Key Functions:**
- `initialize_local_coordinates()` - initializes local frame positions/velocities from global coordinates
- `compute_global_coordinates()` - computes global positions/velocities from local frames
- `compute_spacecraft_globals()` - calculates global coordinates for all spacecraft
**Implementation Details:**
- Dual coordinate storage: both local and global coordinates maintained
- Parent bodies treated as origin in child's reference frame during integration
- RK4 integration operates on local coordinates
- Global coordinates computed after each physics step for rendering and SOI checks
## Core Data Structures
@ -43,18 +76,18 @@ struct SimulationState {
CelestialBody* bodies;
int body_count;
int max_bodies;
Spacecraft* spacecraft;
int craft_count;
int max_craft;
Maneuver* maneuvers;
int maneuver_count;
int max_maneuvers;
double time; // simulation time (seconds)
double dt; // time step (seconds)
};
```
### RenderState (renderer.h)
```cpp
struct RenderState {
Camera3D camera;
double distance_scale; // Scale factor for distances
double size_scale; // Scale factor for body sizes
bool show_info; // Display simulation info
char config_name[256];
};
```
@ -71,12 +104,45 @@ struct OrbitalElements {
};
```
### AccelerationContext (physics.h)
### Spacecraft (spacecraft.h)
```cpp
struct AccelerationContext {
SimulationState* sim;
CelestialBody* current_body;
int body_index;
struct Spacecraft {
char name[64];
double mass;
Vec3 local_position;
Vec3 local_velocity;
Vec3 position;
Vec3 velocity;
int parent_index;
};
```
### Maneuver (maneuver.h)
```cpp
enum BurnDirection {
BURN_PROGRADE,
BURN_RETROGRADE,
BURN_NORMAL,
BURN_ANTINORMAL,
BURN_RADIAL_IN,
BURN_RADIAL_OUT,
BURN_CUSTOM
};
enum TriggerType {
TRIGGER_TIME,
TRIGGER_TRUE_ANOMALY
};
struct Maneuver {
char name[64];
int craft_index;
BurnDirection direction;
double delta_v;
TriggerType trigger_type;
double trigger_value;
bool executed;
double executed_time;
};
```
@ -131,21 +197,53 @@ Simulation state management and updates. SOI detection using Hill sphere: `r_soi
- Child bodies updated in parent's local frame
- Global coordinates computed for all children
**Additional functions:**
- `create_simulation()` / `destroy_simulation()` - memory management for simulation state
- `add_body_to_simulation()` / `add_spacecraft()` - dynamic addition of bodies and spacecraft
- `update_bodies_physics()` / `update_spacecraft_physics()` - separated physics updates
- `execute_pending_maneuvers()` - processes scheduled burn maneuvers
- `compute_spacecraft_globals()` - calculates global coordinates for all spacecraft
- `initialize_bodies()` - combined initialization for velocities, SOI radii, and local coordinates
### Maneuver (maneuver.cpp/h)
Burn execution system for spacecraft orbital maneuvers. Supports multiple burn directions and trigger types.
**Enums:**
- `BurnDirection`: PROGRADE, RETROGRADE, NORMAL, ANTINORMAL, RADIAL_IN, RADIAL_OUT, CUSTOM
- `TriggerType`: TIME, TRUE_ANOMALY
**Key functions:**
- Direction calculation: `calculate_prograde_dir()`, `calculate_retrograde_dir()`, `calculate_normal_dir()`, `calculate_antinormal_dir()`, `calculate_radial_in_dir()`, `calculate_radial_out_dir()`, `get_burn_direction_vector()`
- Burn application: `apply_impulsive_burn()`, `apply_custom_burn()`
- Execution: `check_maneuver_trigger()`, `execute_maneuver()`
- Utility: `calculate_orbital_velocity()`
**Implementation:**
- All burn direction vectors calculated in local frame relative to current orbital state
- Impulsive burns apply instantaneous velocity changes
- Trigger types allow time-based or orbital-position-based burn execution
- Maneuvers track execution state and timestamp
### Config Loader (config_loader.cpp/h)
TOML-based config parser using tomlc17 library. Auto-calculates circular orbit velocities and SOI radii.
**Key functions:**
- `load_system_config()` - main entry point, loads bodies/spacecraft/maneuvers from config file
- `parse_toml_body()` - parses individual body entries
- `calculate_initial_velocities()` - sets circular orbit velocities using vis-viva equation
- `calculate_soi_radii()` - computes sphere of influence for all bodies
- `parse_toml_spacecraft()` - parses spacecraft entries
- `parse_toml_maneuver()` - parses maneuver entries
- `load_spacecraft_from_toml()` - loads spacecraft array from config
- `load_maneuvers_from_toml()` - loads maneuvers array from config
- `initialize_bodies()` - combined initialization: velocities, SOI radii, and local coordinates
**Config format details:**
- TOML array of tables: `[[bodies]]`
- TOML arrays: `[[bodies]]`, `[[spacecraft]]`, `[[maneuvers]]`
- Comments start with `#`
- `parent_index = -1` indicates root body (star)
- Supports nested orbits (planets with moons)
- All numeric values accept integers or floats
**Config format (TOML):**
**Config format (TOML) - Bodies:**
```toml
[[bodies]]
name = "Sun"
@ -168,14 +266,49 @@ eccentricity = 0.0
semi_major_axis = 1.496e11
```
### Renderer (renderer.cpp/h)
Raylib 3D visualization with logarithmic distance scaling and size scaling for visibility.
**Config format (TOML) - Spacecraft:**
```toml
[[spacecraft]]
name = "LEO_Satellite"
mass = 1000.0
position = { x = 0.0, y = 6.771e6, z = 0.0 }
velocity = { x = 7660.0, y = 0.0, z = 0.0 }
parent_index = 1
```
- `position` and `velocity` are in local frame relative to parent
- `velocity` is optional (defaults to zero if omitted)
**Orbit rendering:**
- Elliptical orbits: e < 0.98
- Parabolic orbits: 0.98 ≤ e ≤ 1.02 (uses escape trajectory formula)
- Hyperbolic orbits: e > 1.02 (shows asymptotic behavior)
- `render_parabolic_orbit()` renders escape paths with true anomaly range: -π*0.95 to π*0.95
**Config format (TOML) - Maneuvers:**
```toml
[[maneuvers]]
name = "orbit_raise"
spacecraft_name = "LEO_Satellite"
trigger_type = "time"
trigger_value = 3600.0
direction = "prograde"
delta_v = 500.0
```
- `trigger_type`: "time" (seconds) or "true_anomaly" (radians)
- `direction`: "prograde", "retrograde", "normal", "antinormal", "radial_in", "radial_out"
- `delta_v`: velocity change magnitude in m/s
**Validation rules:**
- Body count must not exceed `max_bodies`
- Spacecraft count must not exceed `max_craft`
- Maneuver count must not exceed `max_maneuvers`
- Body `parent_index` must be < body index or -1 (root)
- Parent-child distance must exceed combined radii
- Spacecraft `parent_index` must reference valid body
- Maneuver `spacecraft_name` must reference existing spacecraft
- Maneuver names must be unique within config
### Renderer (renderer.cpp/h)
Raylib 3D visualization system. See **[docs/rendering.md](rendering.md)** for complete documentation including:
- Camera controls and follow system
- Object rendering (bodies, spacecraft, maneuvers)
- Orbit path rendering (elliptical, parabolic, hyperbolic)
- UI panels (info, body list, maneuver list)
- Coordinate transformation and scaling
### Test Utilities (test_utilities.cpp/h)
Test helper functions for orbital mechanics validation.
@ -189,25 +322,6 @@ Test helper functions for orbital mechanics validation.
- `update_orbit_tracker()` - tracks orbital progress and detects completion
- `compare_double()` / `compare_vec3()` - floating-point comparison with tolerance
### Local Coordinate Frames (simulation.cpp/h)
Hierarchical coordinate system for improved numerical precision in nested orbits.
**Key functions:**
- `initialize_local_coordinates()` - initializes local frame positions/velocities from global coordinates
- `compute_global_coordinates()` - computes global positions/velocities from local frames
**Benefits:**
- Eliminates large offsets in floating-point calculations (moon at 3.8×10⁸ m instead of 1.5×10¹¹ m)
- Isolates moon orbits from planetary perturbations
- Maintains full floating-point precision for small orbital changes
- Improved Earth-Moon orbital stability (20% drift → stable)
**Implementation Details:**
- Dual coordinate storage: both local and global coordinates maintained
- Parent bodies treated as origin in child's reference frame during integration
- RK4 integration operates on local coordinates
- Global coordinates computed after each physics step for rendering and SOI checks
### Main Program (main.cpp)
GUI-only application with interactive 3D visualization.
- Initializes simulation with MAX_BODIES=100, TIME_STEP=60 seconds
@ -243,6 +357,7 @@ GUI-only application with interactive 3D visualization.
### Test Infrastructure
- **Framework**: Catch2 for unit testing
- use `./orbit_test -s '[CONFIG_NAME]'` to show extra [INFO] messages on passing tests if needed
- **Test Configs**: `tests/configs/` contains test scenarios
- `solar_system.toml` - Full solar system with moons
- `earth_circular.toml`, `mars_circular.toml` - Simple orbital tests
@ -282,9 +397,15 @@ GUI-only application with interactive 3D visualization.
## Data Flow
### Initialization Sequence
1. Configuration file → `load_system_config()` → populates `SimulationState`
2. `calculate_initial_velocities()` → sets circular orbit velocities for all bodies
3. `calculate_soi_radii()` → computes sphere of influence for each body
1. Configuration file → `load_system_config()` → populates `SimulationState`:
- Loads bodies array from `[[bodies]]`
- Loads spacecraft array from `[[spacecraft]]`
- Loads maneuvers array from `[[maneuvers]]`
2. `initialize_bodies()` → combined initialization:
- Calculates circular orbit velocities for all bodies (using vis-viva equation)
- Computes sphere of influence radius for each body (Hill sphere)
- Sets local coordinates (position/velocity) for all bodies
- Initializes spacecraft global coordinates
### Main Simulation Loop
1. `update_simulation()` → for each body:
@ -301,34 +422,6 @@ GUI-only application with interactive 3D visualization.
- Uses 0.5x distance hysteresis to prevent oscillation between parents
- `find_dominant_body()` checks all bodies and selects most dominant influence
## Implementation Status
### ✅ Completed
- Phase 1-4: Core physics, simulation, config loading, and rendering
- Raylib integration with 3D camera
- Distance and size scaling for visualization
- TOML config file system with solar system configs (includes Sun + 8 planets + 6 moons)
- RK4 (Runge-Kutta 4th order) integration for improved accuracy
- Time scaling controls (speed up/slow down simulation)
- Pause/resume functionality
- Orbital elements calculation
- **Hierarchical coordinate frames (local + global storage)**
- **Parent-first update order for stability**
- **Parabolic orbit support (e=1.0)**
- **Hyperbolic orbit support (e>1.0)**
- **Physics module refactoring (parameter-based signatures)**
- **Comprehensive test suite (8 test files, 39+ assertions)**
- **Build system with automated testing**
- **UI body selection and information display (raygui integration)**
- **Camera follow feature for selected bodies**
- **Camera follow improvements: distance preservation and proper orbital rotation**
### 🔨 Remaining/Future Work
- More accurate integration methods (Newton-Raphson propagation)
- Reference frame switching
- SOI transition frame transformations (Phase 3 of hierarchical frames)
- Io and Titan orbital stability tuning
## Technical Notes
### Code Style and Architecture
@ -338,12 +431,6 @@ GUI-only application with interactive 3D visualization.
- Layer separation: Physics, Simulation, Configuration, Rendering layers
- Physics module is independent of simulation structures (parameter-based signatures)
### Scaling for Visualization
- Distance: logarithmic/power-law scaling for solar system scale
- Size: minimum visible radius to prevent tiny bodies from disappearing
- Origin at Sun for simplicity
- Both distance_scale and size_scale are configurable in RenderState
### Physics Considerations
- Timestep: 60 seconds for solar system scale
- Circular orbit velocity: `v = sqrt(G * M / r)`
@ -353,12 +440,3 @@ GUI-only application with interactive 3D visualization.
- SOI transitions use 0.5x distance hysteresis to prevent oscillation
- Parabolic orbits use escape velocity: `v² = 2GM/r`
- Hyperbolic orbits have positive total energy and asymptotic velocity
## Future Enhancements
- More accurate integration methods (Newton-Raphson propagation)
- Reference frame switching
- 3D orbital visualization with inclination
- SOI transition frame transformations (Phase 3 of hierarchical frames)
- Camera focus on selected body
- Visual highlighting of selected body in 3D view
- Enhanced UI features (search, multiple selection, orbital metrics)

2
opencode.json

@ -2,6 +2,6 @@
"$schema": "https://opencode.ai/config.json",
"instructions": [
"AGENTS.md",
"docs/implementation_plan.md"
"docs/technical_reference.md"
]
}

Loading…
Cancel
Save