Skip to content

donutTheJedi/Rocket-Launch-Simulation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

36 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

🚀 Orbital Rocket Simulation

🌐 Live Demo:
Current Live Demo: https://www.donutthejedi.com/

Hacker News

A realistic 2D physics simulation of orbital mechanics and rocket launches from Earth. Experience the challenge of launching a Falcon 9-like rocket into orbit with accurate physics, atmospheric modeling, and an intelligent closed-loop guidance system.

Rocket Simulation License

🌟 Part I think is coolest

Rocket Builder with live diagram — In the menu, "Build your own rocket" opens a panel where you can tweak stages, payload, and fairing. The Basic tab shows an interactive 2D diagram of your rocket: drag segment boundaries to change length and edges to change diameter. COG and CoP at pad are drawn in real time, and starting acceleration turns red if it's below 1 g (so you know the rocket would crash). Its so amazing to test extreme cases and just play around with your ideas, I havent tested it but it should work with model rockets

📋 Table of Contents

✨ Features

Physics & Simulation

  • Realistic Orbital Mechanics: Full 2-body problem with accurate vis-viva equations
  • US Standard Atmosphere 1976: Piecewise atmospheric model with geopotential altitude corrections
  • Variable Thrust: Sea-level to vacuum thrust and ISP variation
  • Atmospheric Drag: Velocity-relative drag calculations accounting for Earth's rotation
  • Mach-Dependent Drag Coefficient: Realistic transonic drag modeling with drag coefficient variation from subsonic through hypersonic regimes
  • Aerodynamic Forces: Angle of attack modeling with normal and axial forces, center of pressure calculations, and aerodynamic torque
  • Rotational Dynamics: Gimbal-based thrust vector control with realistic actuator dynamics and aerodynamic stability
  • Dynamic Center of Gravity: Real-time COG calculation based on fuel consumption and stage separation
  • Symplectic Euler Integration: Energy-conserving numerical integration for stable orbits
  • Adaptive Sub-stepping: Variable timestep for accuracy in different flight phases

Game Modes

  • Manual Control: Take full control of pitch with W/S keys while receiving guidance recommendations
  • Guided Launch: Set a target altitude and let the intelligent guidance system handle the launch
  • Orbital Mode: Spawn directly in orbit to practice orbital maneuvers and burns

Guidance System

  • Closed-Loop Guidance: Priority-based system that adapts to flight conditions
  • Max-Q Protection: Automatic structural limit protection during atmospheric flight
  • Orbit Shaping: Intelligent apoapsis/periapsis management for precise orbit insertion
  • Multiple Strategies: Direct ascent and traditional circularization approaches

User Interface

  • Real-Time Telemetry: Altitude, velocity, orbital parameters, Mach number, drag coefficient, COG, CoP, and more
  • Force Diagram: Visual representation of all forces acting on the rocket (gravity, thrust, drag, aerodynamic)
  • Rocket Diagram: 2D side view showing rocket orientation, COG, CP positions, and force vectors at their attachment points
  • Interactive Diagrams: Click to expand force and rocket diagrams for detailed viewing
  • Mission Events: Timeline of important mission milestones
  • Orbital Visualization: Real-time orbit prediction and visualization
  • Time Warp: Speed up simulation up to 1000x
  • Camera Controls: Follow rocket or center on Earth
  • Rocket Customization: Build your own rocket with Basic and Advanced parameter tabs; resizable diagram area (see Rocket Customization)

🚀 Getting Started

Prerequisites

  • A modern web browser (Chrome, Firefox, Edge, Safari)
  • No installation required - runs entirely in the browser!

Running the Simulation

  1. Clone or download this repository
  2. Open index.html in your web browser
  3. Click the MENU button to select a game mode
  4. Start your mission!

Quick Start Guide

  1. Select a Mode:

    • Manual Control: For hands-on experience
    • Guided Launch: For automated launches (set target altitude)
    • Orbital Mode: For practicing orbital mechanics
  2. Launch (Manual/Guided modes):

    • Click the LAUNCH button
    • Watch the telemetry and follow mission events
  3. Orbital Maneuvers (Orbital mode):

    • Use the burn controls to perform prograde, retrograde, normal, anti-normal, radial, and anti-radial burns
    • Hold buttons to burn, release to stop

🎮 Game Modes

Manual Control Mode

Take full control of your rocket's pitch angle while receiving real-time guidance recommendations.

  • Pitch Control: W/S keys or on-screen buttons
  • Control Modes:
    • Turn Rate Mode: Control target pitch angle, gimbal adjusts automatically
    • Gimbal Mode: Direct gimbal control for advanced users
  • Aerodynamic Forces: Optional aerodynamic forces simulation (available in gimbal mode)
    • Normal force and torque from angle of attack
    • Center of pressure visualization
    • Realistic stability effects
  • Guidance Recommendations: See what the guidance system suggests (displayed in cyan)
  • Learning Tool: Compare your decisions with optimal guidance
  • Rate Limited: Realistic 2°/s pitch rate limit

Guided Launch Mode

Set a target altitude and let the intelligent guidance system handle the entire launch sequence.

  • Configurable Target: Set any altitude from 150km to 2000km (default: 500km)
  • Automatic Guidance: Handles atmospheric ascent, orbit insertion, and circularization
  • Adaptive Strategy: Chooses direct ascent or traditional circularization based on target
  • Precision: Achieves orbit within ±5km tolerance

Orbital Mode

Spawn directly in orbit to practice orbital mechanics without going through launch.

  • Altitude Selection: Choose from presets (200km, 400km, 500km, 600km, 800km)
  • 10% Fuel: Realistic fuel constraint for practice
  • Orbital Burns: Full access to all burn directions
  • No Launch Events: Clean orbital environment

🎯 Controls

General Controls

Action Control
Open Menu MENU button
Launch LAUNCH button (Manual/Guided modes)
Pause/Resume PAUSE button
Reset Mission RESET button (restarts current mode)
Time Warp SPEED button (cycles: 1x, 2x, 5x, 10x, 25x, 50x, 100x, 500x, 1000x)
Zoom Out ZOOM OUT button or mouse wheel
Zoom In ZOOM IN button or mouse wheel
Auto Zoom AUTO ZOOM button (toggle)
Camera Mode FOLLOW ROCKET / CENTER EARTH button

Manual Control Mode Controls

Action Control
Pitch Up W key or ↑ PITCH UP button
Pitch Down S key or ↓ PITCH DOWN button
Throttle Up arrow key
Throttle Down arrow key
Open Settings Click ☰ Settings hamburger button (under Manual Control section)
Toggle Control Mode Turn Rate / Gimbal buttons (in Settings)
Toggle Aerodynamic Forces Off / On buttons (in Settings, Gimbal mode only)
Build your own rocket Build your own rocket button (under Manual Control, above Settings)
Resize diagram area Drag the vertical bar between parameters and diagram (Basic tab)

Orbital Mode

Action Control
Prograde Burn PROGRADE button (hold)
Retrograde Burn RETROGRADE button (hold)
Normal Burn NORMAL button (hold)
Anti-Normal Burn ANTI-NORMAL button (hold)
Radial Burn RADIAL button (hold)
Anti-Radial Burn ANTI-RADIAL button (hold)
Refuel REFUEL button (+5000 kg)

🔬 Technical Details

Physics Model

Atmospheric Model

  • US Standard Atmosphere 1976: Industry-standard atmospheric model
  • 7 Atmospheric Layers: Troposphere, tropopause, stratosphere (I & II), stratopause, mesosphere (I & II)
  • Geopotential Altitude: Correct conversion from geometric to geopotential altitude
  • Sutherland's Viscosity Law: Temperature-dependent dynamic viscosity

Orbital Mechanics

  • 2-Body Problem: Earth-centered gravitational model
  • Vis-Viva Equation: Accurate orbital velocity calculations
  • Kepler's Equation: Eccentric anomaly calculations for time predictions
  • Orbital Elements: Apoapsis, periapsis, semi-major axis, eccentricity

Rocket Physics

  • Variable Thrust: Pressure-adjusted thrust (sea-level to vacuum)
  • Variable ISP: Specific impulse varies with atmospheric pressure
  • Mass Flow Rate: Tsiolkovsky rocket equation
  • Drag Model: Velocity-relative drag with rotating atmosphere
  • Mach-Dependent Drag Coefficient: Realistic Cd(Mach) curves based on Saturn V wind tunnel data, modeling subsonic, transonic drag rise, supersonic, and hypersonic regimes
  • Dynamic Center of Gravity: Real-time COG calculation accounting for fuel consumption and stage separation
  • Gimbal Dynamics: Physical thrust vector control with rate limits and maximum deflection constraints
  • Rotational Dynamics: Angular velocity and orientation tracking with aerodynamic damping

Aerodynamic Forces (Optional - Gimbal Mode)

  • Angle of Attack Calculation: Computes AOA between rocket body axis and airspeed vector
  • Center of Pressure: Mach-dependent CP position calculation
    • Subsonic (M < 0.8): CP at 50% of rocket length
    • Transonic (M 0.8-1.2): CP shifts aft from 50% to 60%
    • Supersonic (M > 1.2): CP at 60% of rocket length
  • Normal Force Coefficient:
    • Subsonic: CN_alpha = 2 / sqrt(1 - Mach²) (Prandtl-Glauert correction)
    • Supersonic: CN_alpha = 4 / sqrt(Mach² - 1)
    • CN = CN_alpha × AOA
  • Aerodynamic Forces:
    • Normal force: Perpendicular to body axis, acts at CP
    • Axial force: Along body axis (drag component)
    • Aerodynamic torque: Normal force × moment arm (CP - COG)
  • Stability: Negative moment arm (CP < COG) provides natural stability

Rocket Configuration

You can customize your rocket before each mission via Build your own rocket (Manual Control section). The default is a Falcon 9-like configuration:

Stage 1:

  • Dry Mass: 22,200 kg
  • Propellant: 395,700 kg
  • Thrust (SL): 7,607 kN
  • Thrust (Vac): 8,227 kN
  • ISP (SL): 282 s
  • ISP (Vac): 311 s

Stage 2:

  • Dry Mass: 4,000 kg
  • Propellant: 92,670 kg
  • Thrust: 981 kN (vacuum)
  • ISP: 348 s

Payload: 15,000 kg

See Rocket Customization for the full parameter list and builder UI.

Numerical Integration

  • Symplectic Euler: Energy-conserving integrator for stable long-term orbits
  • Adaptive Sub-stepping:
    • 50ms steps during ascent
    • 10ms steps in orbit (for accuracy)
  • Maximum Timestep: 1.0s cap to prevent numerical instability

🧭 Guidance System

The guidance system uses a priority-based approach that adapts to flight conditions:

Atmospheric Phase (Below 70km)

  1. Height Priority: Get above 70km (out of significant atmosphere)
  2. Max-Q Protection: Don't exceed structural limits, follow prograde exactly
  3. Gravity Turn: Natural pitchover with turn rate limiting
  4. Minimum Vertical Velocity: Ensure enough vertical velocity at atmosphere exit

Vacuum Phase (Above 70km)

  1. Apoapsis Management: Raise apoapsis to target altitude
  2. Periapsis Safety: Ensure periapsis stays above 100km (safe altitude)
  3. Orbit Shaping: Adjust flight path angle based on target altitude
  4. Circularization: Precise burn at apoapsis for circular orbit

Guidance Cases

Case Condition Action
0 Pe < 0, Ap ≥ target 🚨 Emergency horizontal burn
1 Ap < target 📈 Raise apoapsis with FPA guidance
2a Pe < 100km, descending 🚨 Emergency prograde burn
2b Pe < 100km, ascending ⏳ Coast to Apo, then prograde
3 Ap > target ⏳ Coast to Pe, then retrograde
4a Pe < target, near Apo 🔄 Circularize prograde
4b Pe < target, far from Apo ⏳ Coast to apoapsis
5 Both within tolerance ✅ Orbit achieved

Guidance System Flowchart

flowchart TD
    subgraph INIT["⚡ INITIALIZATION"]
        Start([Guidance Loop]) --> Gather[Gather State<br/>Position, Velocity, Altitude]
        Gather --> Predict[Predict Orbit<br/>Apoapsis, Periapsis, SMA]
    end

    subgraph ATMO["🌍 ATMOSPHERIC PHASE · Alt < 70km"]
        Predict --> AtmoCheck{Alt < 70km?}
        AtmoCheck -->|Yes| TimeCheck{T < 10s?}
        TimeCheck -->|Yes| Vertical["Vertical Ascent<br/>Pitch = 90°"]
        TimeCheck -->|No| KickCheck{T < 13s?}
        KickCheck -->|Yes| PitchKick["Pitch Kick<br/>Initiate gravity turn"]
        KickCheck -->|No| MaxQCheck{Q > 80% MaxQ?}
        MaxQCheck -->|Yes| MaxQ["Max-Q Protection<br/>Follow prograde"]
        MaxQCheck -->|No| AtmoGuidance["Atmospheric Guidance<br/>• Prograde following<br/>• Turn rate limiting<br/>• Min vVertical check"]
    end

    subgraph VACUUM["🌌 VACUUM PHASE · Alt ≥ 70km"]
        AtmoCheck -->|No| CalcFPA["Calculate Target FPA<br/>f(progress, target altitude)"]
        
        CalcFPA --> Case0{Pe < 0 AND<br/>Ap ≥ target?}
        Case0 -->|Yes| Emergency["🚨 CASE 0: EMERGENCY<br/>Burn horizontal, full throttle"]
        
        Case0 -->|No| Case1{Ap < target?}
        Case1 -->|Yes| RaiseApo["📈 CASE 1: RAISE APOAPSIS<br/>Burn with FPA guidance"]
        
        Case1 -->|No| Case2{Pe < 100km?}
        Case2 -->|Yes| DescendCheck{Descending?}
        DescendCheck -->|Yes| EmergencyPe["🚨 CASE 2a: EMERGENCY<br/>Burn prograde NOW"]
        DescendCheck -->|No| CoastToApo["⏳ CASE 2b: COAST TO APO<br/>Then burn prograde"]
        
        Case2 -->|No| Case3{Ap > target?}
        Case3 -->|Yes| CoastToPe["⏳ CASE 3: COAST TO PE<br/>Then retrograde burn"]
        
        Case3 -->|No| Case4{Pe < target?}
        Case4 -->|Yes| CircCheck{Near Apo?}
        CircCheck -->|Yes| Circ["🔄 CASE 4a: CIRCULARIZE<br/>Burn prograde at Apo"]
        CircCheck -->|No| CoastCirc["⏳ CASE 4b: COAST<br/>Wait for apoapsis"]
        
        Case4 -->|No| Achieved["✅ CASE 5: ORBIT ACHIEVED"]
    end

    subgraph OUTPUT["📤 OUTPUT"]
        Vertical & PitchKick & MaxQ & AtmoGuidance --> Constrain
        Emergency & RaiseApo & EmergencyPe --> Constrain
        CoastToApo & CoastToPe & Circ & CoastCirc & Achieved --> Constrain
        
        Constrain["Apply Constraints<br/>Pitch: -5° to 90°<br/>Rate: 2°/s max"] --> Return(["Return Command"])
    end
Loading

Key Parameters

  • Atmosphere limit: 70 km
  • Safe periapsis: 100 km (above atmosphere with margin)
  • Target orbit: Configurable (default: 500 km circular)
  • Pitch constraints: -5° to +90°
  • Max pitch rate: 2°/s
  • Max Q limit: 35 kPa (typical Falcon 9 structural limit)

🛠 Rocket Customization

Build and tune your own rocket before starting a mission. Open the menu, then click Build your own rocket (above Settings in the Manual Control section).

Basic Tab

  • Stage 1 & 2: Dry mass, propellant mass, thrust (SL/vac), diameter, length, drag coefficient
  • Payload: Mass, length, diameter
  • Fairing: Mass, length, diameter
  • Diagram area: A resizable panel (drag the vertical bar to change its width). The rectangle inside scales to fit while keeping aspect ratio. This is a placeholder: a customizable rocket diagram is planned here so you can see and interact with your rocket shape (e.g. drag to resize stages, fuel tanks) to make tuning more intuitive. The feature is not done yet.

Advanced Tab

  • Stages: Isp (SL/vac), tank length ratio, engine length, engine mass fraction, gimbal (max angle, rate, pivot point)
  • Global: Fairing jettison altitude, propellant density

Behavior

  • Reset to default: Restores the Falcon 9-like configuration
  • Done: Closes the builder; your design applies to the next mission start (Manual, Guided, or Orbital)
  • All parameters are persisted for the session; the simulation reads from the current config when you launch or spawn

Planned: Customizable Rocket Diagram (not yet implemented)

The diagram area in the Basic tab currently shows a simple rectangle that resizes with the panel. The goal is to replace it with an interactive rocket diagram that reflects your parameters (stage lengths, diameters, payload, fairing) and allows intuitive editing—e.g. dragging to adjust stage height or tank size—so building a rocket feels more visual and intuitive. This is not yet implemented.

📁 Project Structure

Rocket/
├── index.html          # Main HTML file
├── README.md          # This file
├── css/
│   └── styles.css     # UI styling
└── js/
    ├── main.js        # Main game loop and menu logic
    ├── state.js       # Game state management
    ├── physics.js     # Atmospheric and physics calculations
    ├── guidance.js    # Closed-loop guidance system
    ├── orbital.js     # Orbital mechanics calculations
    ├── events.js      # Mission event tracking
    ├── input.js       # User input handling
    ├── renderer.js    # Canvas rendering
    ├── telemetry.js   # Telemetry display updates
    ├── rocketConfig.js # Current rocket config (get/set, builder)
    └── constants.js   # Physical constants and default configuration

Key Files

  • main.js: Game loop, update function, menu system
  • guidance.js: Complete closed-loop guidance implementation (880 lines)
  • physics.js: US Standard Atmosphere 1976 model, drag, thrust calculations
  • orbital.js: Orbit prediction, vis-viva, Kepler's equation
  • state.js: State management, orbital spawn function

🎓 Educational Value

This simulation is excellent for:

  • Learning Orbital Mechanics: Understand how orbits work in practice
  • Rocket Science: See how thrust, gravity, and drag interact
  • Guidance Systems: Learn how closed-loop guidance works
  • Atmospheric Physics: Explore how atmosphere affects flight
  • Mission Planning: Practice orbital maneuvers and burns

🎯 Roadmap

Guidance System

Powered Explicit Guidance (PEG)

Replace the current priority-based guidance with the iterative PEG algorithm used by Space Shuttle and Falcon 9. PEG computes optimal steering commands by solving for the thrust direction that achieves target orbital conditions while minimizing propellant usage.

  • Implement PEG state estimator (current position, velocity, mass)
  • Add iterative guidance loop with convergence criteria
  • Compute time-to-go and required velocity-to-be-gained (Vgo)
  • Generate pitch/yaw steering commands from PEG output
  • Handle guidance mode transitions (atmospheric → PEG handoff)
  • Add PEG telemetry display (Vgo, time-to-cutoff, steering angles)

Physics Fidelity

Mach-Dependent Drag Coefficient ✅

Implement realistic transonic drag modeling. Real rockets experience significant drag coefficient variation, particularly the transonic drag rise around Mach 0.8–1.2.

  • Research Cd(Mach) curves for slender bodies (NASA technical reports)
  • Implement piecewise or polynomial Cd interpolation
  • Add subsonic regime (M < 0.8): ~0.25–0.30
  • Add transonic drag rise (M 0.8–1.2): peak ~0.45–0.50
  • Add supersonic regime (M > 1.2): gradual decrease ~0.35
  • Add hypersonic regime (M > 5): stabilized ~0.20
  • Display current Cd and Mach number in telemetry

Engine Gimbal Dynamics ✅

Model realistic thrust vector control (TVC) with physical gimbal constraints instead of instantaneous thrust direction changes.

  • Add gimbal angle state (current deflection from centerline)
  • Implement gimbal rate limits (~20°/s for Stage 1, ~15°/s for Stage 2)
  • Add maximum gimbal deflection constraint (~5° for both stages)
  • Model gimbal response lag (rate-limited actuator dynamics)
  • Update guidance to account for gimbal authority limits
  • Visualize gimbal angle on rocket rendering
  • Add gimbal telemetry (commanded vs actual deflection)
  • PD controller for gimbal command generation

Aerodynamic Forces ✅

Implement realistic aerodynamic forces when rocket has angle of attack.

  • Calculate angle of attack (AOA) between body axis and airspeed vector
  • Calculate center of pressure (CP) with Mach-dependent position
  • Implement normal force coefficient (CN) with Prandtl-Glauert corrections
  • Calculate normal and axial aerodynamic forces
  • Apply aerodynamic torque based on CP-COG moment arm
  • Add aerodynamic forces toggle (available in gimbal control mode)
  • Visualize forces in force and rocket diagrams
  • Display CoP position in telemetry

User Experience

Interactive Diagrams ✅

Real-time visualization of forces and rocket state.

  • Force diagram showing all force vectors (gravity, thrust, drag, aerodynamic)
  • Rocket diagram with COG/CP markers and force vectors at attachment points
  • Click-to-expand functionality for detailed viewing
  • Diagrams rotate with rocket orientation
  • Automatic stage separation visualization

Rocket Customization (Builder) ✅ (partial)

Build your own rocket with Basic and Advanced parameter tabs; diagram area is a placeholder.

  • Current rocket config module (get/set, reset to default)
  • "Build your own rocket" button and modal (Basic / Advanced tabs)
  • Basic tab: thrust, mass, diameter, length, propellant, drag coeff (+ payload, fairing)
  • Advanced tab: Isp, tank ratio, engine length, gimbal, fairing jettison alt, propellant density
  • Customizable rocket diagram (not yet done): Replace placeholder rectangle with an interactive diagram that reflects your parameters (stage lengths, diameters, payload, fairing) and allows intuitive editing—e.g. drag to resize stage height or tank size—so building a rocket is more visual and intuitive

Telemetry Graphs & Post-Flight Review

Add real-time plotting during flight and comprehensive post-flight analysis.

Real-Time Graphs

  • Altitude vs time
  • Velocity vs time (surface velocity + orbital velocity)
  • Acceleration vs time (with Max-Q marker)
  • Dynamic pressure vs time
  • Flight path angle vs time
  • Apoapsis/Periapsis evolution

Post-Flight Review

  • Mission summary statistics (max altitude, max velocity, max Q, flight time)
  • Delta-V breakdown by phase (gravity losses, drag losses, steering losses)
  • Guidance performance analysis (actual vs commanded pitch)
  • Propellant usage timeline
  • Export flight data to CSV/JSON
  • Replay flight with adjustable playback speed

⚠️ Current Issues

  • Engine shuts off in manual control
  • When clicking in and out of UI it can bug
  • Poor phone formating

🐛 Known Limitations

  • 2D Only: Simplified to 2D plane (no inclination changes)
  • No Wind/Weather: Atmospheric conditions are standard only
  • Instant Stage Separation: Real separations have dynamics
  • No Structural Failure: Max-Q protection exists but no failure modeling

🤝 Contributing

Contributions are welcome! Areas for improvement:

  • 3D orbital mechanics
  • Additional rocket configurations
  • Mission scenarios
  • UI/UX improvements

📝 License

This project is open source. Feel free to use, modify, and distribute.

🙏 Acknowledgments

  • US Standard Atmosphere 1976: NOAA, NASA, and USAF
  • Falcon 9 Specifications: Based on publicly available SpaceX data
  • Orbital Mechanics: Based on classical two-body problem solutions

Enjoy your journey to orbit! 🚀