You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
9.1 KiB
9.1 KiB
Orbital Mechanics Simulation - Implementation Plan
Project Overview
A 3D orbital mechanics simulation using 2-body gravitational model with sphere of influence (SOI) transitions. Real-time visualization of the solar system (Sun, planets, moons) using raylib with C-style C++.
Technical Constraints
- C-style C++ only: structs and functions, no classes or templates
- Small, focused functions
- Simple rotations (Euler angles / axis-angle) - quaternions deferred for later
- Euler integration for physics
- raylib for 3D visualization
Project Structure
claudes_game/
├── src/
│ ├── main.cpp
│ ├── physics.cpp
│ ├── physics.h
│ ├── bodies.cpp
│ ├── bodies.h
│ ├── renderer.cpp
│ ├── renderer.h
│ ├── config_loader.cpp
│ └── config_loader.h
├── configs/
│ ├── solar_system.txt
│ └── example_binary_star.txt
├── Makefile
└── README.md
Core Data Structures
Vec3 (physics.h)
struct Vec3 {
double x, y, z;
};
CelestialBody (bodies.h)
struct CelestialBody {
char name[64];
double mass; // kg
double radius; // meters
Vec3 position; // meters from solar system origin
Vec3 velocity; // m/s
double soi_radius; // sphere of influence radius (meters)
int parent_index; // index of gravitational parent (-1 for Sun)
float color[3]; // RGB for rendering
};
SimulationState (bodies.h)
struct SimulationState {
CelestialBody* bodies;
int body_count;
double time; // simulation time (seconds)
double dt; // time step (seconds)
};
Key Components
1. Physics Module (physics.c/h)
Functions:
Vec3 vec3_add(Vec3 a, Vec3 b)- vector additionVec3 vec3_sub(Vec3 a, Vec3 b)- vector subtractionVec3 vec3_scale(Vec3 v, double s)- scalar multiplicationdouble vec3_magnitude(Vec3 v)- vector lengthdouble vec3_distance(Vec3 a, Vec3 b)- distance between pointsVec3 vec3_normalize(Vec3 v)- unit vectorVec3 calculate_gravity_force(CelestialBody* body, CelestialBody* parent)- 2-body forceVec3 calculate_acceleration(Vec3 force, double mass)- F = mavoid euler_step(CelestialBody* body, Vec3 acceleration, double dt)- Euler integration
2. Bodies Module (bodies.c/h)
Functions:
SimulationState* create_simulation(int max_bodies)- allocate simulationvoid destroy_simulation(SimulationState* sim)- cleanupvoid add_body(SimulationState* sim, const char* name, double mass, double radius, Vec3 pos, Vec3 vel, float r, float g, float b)- add celestial bodyint find_dominant_body(SimulationState* sim, int body_index)- determine which body has gravitational dominancevoid update_soi(CelestialBody* body, CelestialBody* parent)- calculate sphere of influence radiusvoid update_simulation(SimulationState* sim)- single time step update
SOI Calculation:
Using Hill sphere approximation: r_soi = a * (m/M)^(2/5)
where a = semi-major axis, m = body mass, M = parent mass
3. Config Loader Module (config_loader.cpp/h)
Functions:
bool load_system_config(SimulationState* sim, const char* filepath)- load bodies from config filebool parse_body_line(const char* line, CelestialBody* body)- parse single body definitionvoid calculate_initial_velocities(SimulationState* sim)- compute circular orbit velocities from positions
Config File Format (simple text):
# Comment lines start with #
# Format: name mass(kg) radius(m) x(m) y(m) z(m) parent_index r g b
Sun 1.989e30 6.96e8 0 0 0 -1 1.0 1.0 0.0
Earth 5.972e24 6.371e6 1.496e11 0 0 0 0.0 0.5 1.0
Moon 7.342e22 1.737e6 1.4996e11 0 0 1 0.7 0.7 0.7
# Velocity is calculated automatically for circular orbits
Example configs to provide:
configs/solar_system.txt- Our solar system with Sun, 8 planets, major moonsconfigs/example_binary_star.txt- Binary star system with planets
4. Renderer Module (renderer.c/h)
Functions:
void init_renderer(int width, int height, const char* title)- initialize raylib windowvoid setup_camera(Camera3D* camera)- configure 3D cameravoid render_body(CelestialBody* body, double scale)- draw sphere for bodyvoid render_simulation(SimulationState* sim, Camera3D* camera)- render all bodiesvoid draw_orbit_trail(Vec3* positions, int count, Color color)- draw orbit path (future enhancement)void close_renderer()- cleanup raylib
Rendering approach:
- Use logarithmic scaling for distances (solar system is huge)
- Use exponential scaling for body sizes (make small bodies visible)
- Simple camera controls (rotate around Sun, zoom in/out)
- Display FPS and simulation time
5. Main Loop (main.cpp)
1. Parse command line arguments (config file path, default to configs/solar_system.txt)
2. Initialize raylib window and camera
3. Create simulation and load system from config file
4. Main loop:
a. Handle input (camera controls, pause/resume, speed adjustment)
b. Update physics (multiple sub-steps per frame for stability)
c. Check for SOI transitions
d. Render scene
e. Update camera
5. Cleanup and exit
Implementation Steps
Phase 1: Foundation
- Create project structure and Makefile
- Implement Vec3 and basic vector math functions (physics.c/h)
- Define CelestialBody and SimulationState structs (bodies.h)
- Create basic simulation functions (create, destroy, add_body)
Phase 2: Physics Core
- Implement 2-body gravity calculation
- Implement Euler integration step
- Implement SOI detection and parent switching logic
- Create update_simulation() function
Phase 3: Config Loading System
- Implement config file parser (parse_body_line, skip comments/empty lines)
- Implement load_system_config() to read and populate simulation
- Create configs/solar_system.txt with our solar system data
- Implement calculate_initial_velocities() for circular orbits
- Calculate SOI radii for all bodies after loading
Phase 4: Visualization
- Initialize raylib window and 3D camera
- Implement render_body() with scaling
- Implement render_simulation() to draw all bodies
- Add basic camera controls (orbital rotation, zoom)
Phase 5: Integration and Refinement
- Integrate rendering with physics loop in main.cpp
- Add command line argument parsing for config file selection
- Add time scaling controls (speed up/slow down simulation)
- Add pause/resume functionality
- Display simulation info (time, FPS, body count, current config)
- Create example_binary_star.txt config for testing
- Test and tune time step for stability
Technical Notes
Config File System Benefits
- Flexibility: Easily create any star system without recompiling
- Testing: Quickly test different scenarios (binary stars, close encounters, etc.)
- Sharing: Users can share interesting system configurations
- Debugging: Simplified test cases with just 2-3 bodies
- Education: Learn about different orbital configurations by experimenting
Scaling for Visualization
- Distance scale: Use logarithmic or power-law scaling (e.g.,
display_pos = sign(pos) * pow(abs(pos), 0.3)) - Size scale: Make minimum visible radius (e.g., max(actual_radius * scale, min_visible_radius))
- Keep Sun at origin for simplicity
Time Step Considerations
- Solar system scale requires small time steps (try dt = 60 seconds initially)
- May need multiple physics updates per render frame
- Allow user to adjust simulation speed multiplier
SOI Transition Logic
For each body (except Sun):
1. Calculate distance to current parent
2. Calculate distance to all other potential parents
3. Check if body is within SOI of a different parent
4. If yes, switch parent_index and recalculate relative state
Initial Conditions
- Use Keplerian orbital elements or simplified circular orbits
- Ensure velocity is perpendicular to position vector for circular orbits
- Circular orbit velocity: v = sqrt(G * M / r)
Files to Create
src/physics.h- Vector math and physics declarationssrc/physics.cpp- Vector math and physics implementationssrc/bodies.h- Body and simulation data structuressrc/bodies.cpp- Body management and simulation updatesrc/config_loader.h- Config file parsing declarationssrc/config_loader.cpp- Config file loading implementationsrc/renderer.h- Rendering declarationssrc/renderer.cpp- raylib rendering implementationsrc/main.cpp- Main loop and program entryconfigs/solar_system.txt- Our solar system configurationconfigs/example_binary_star.txt- Example binary star systemMakefile- Build configurationREADME.md- Project documentation and config format docs
Future Enhancements (Not in Initial Implementation)
- Quaternion-based rotations
- Orbit trail rendering
- N-body simulation mode
- Patched conic approximation
- More accurate integration (RK4, Verlet)
- Save/load simulation state
- Interactive body selection and info display
- Reference frame switching