this repository is a modular, extensible, and numerically robust 3d physics engine written in rust. it is designed for both classical and relativistic physics, with a focus on simulating geodesic motion in schwarzschild spacetime (black holes) and providing a flexible ecs (entity-component-system) foundation for future expansion.
this repository implements an extensible physics engine for simulating relativistic motion in curved spacetime, with a focus on schwarzschild (black hole) geodesics. the codebase is designed for both physical accuracy and numerical stability, using modern rust and an entity-component-system (ecs) architecture for flexibility and scalability. \
- relativistic geodesic integration:
- see
src/curvature.rs, especiallyintegrate_geodesic_sphericalandchristoffel_symbols_spherical. - integrates worldlines in schwarzschild spacetime using analytic christoffel symbols and a symplectic leapfrog method.
- see
- defensive numerics and robust integration:
- all coordinate singularities (e.g., r=0, θ=0/π) and floating-point nan/inf issues are handled with clamping and safe guards.
- four-acceleration is capped to prevent runaway velocities; proper time step (
d_tau) is adaptively reduced for large gamma (relativistic factor). - global gamma/energy clamping ensures all four-velocities remain physical; all normalization and construction routines are robust to NaN/Inf and unphysical states.
- see robust coordinate conversion, normalization, and integration in
src/curvature.rsandsrc/relativity.rs.
- ecs architecture:
- modular, scalable simulation of many particles/entities.
- scheduler and dispatcher for running systems in order, with event system support (see
src/ecs/scheduler/mod.rs). - see
src/ecs/mod.rsfor the ecs core, andsrc/main.rsfor usage. extensible gravity models: - Newtonian, Post-Newtonian, analytic General Relativity, and full Numerical Relativity infrastructure in
src/gravity.rs. - See
src/numerical_relativity.rsfor the grid-based metric evolution and BSSN formalism (foundation for full numerical relativity). - NumericalRelativityGravity now computes the metric, Christoffel symbols, and geodesic deviation using a 3D grid, with robust finite-difference derivatives and constraint damping.
- Debugging output for metric, Christoffel symbols, and force vectors is available for diagnosing grid curvature and force calculation.
- comprehensive four-vector algebra:
- lorentz boosts, minkowski and general metric inner products, four-force/acceleration, and normalization in
src/relativity.rs.
- lorentz boosts, minkowski and general metric inner products, four-force/acceleration, and normalization in
the schwarzschild metric describes spacetime around a non-rotating, uncharged black hole. the implementation is in metric::schwarzschild_spherical:
$$
ds^2 = -\left(1 - \frac{r_s}{r}\right)c^2 dt^2 + \left(1 - \frac{r_s}{r}\right)^{-1} dr^2 + r^2 d\theta^2 + r^2 \sin^2\theta d\phi^2
$$
where
the geodesic equation governs free-fall motion in curved spacetime. the code implements this in integrate_geodesic_spherical, using analytic christoffel symbols from christoffel_symbols_spherical:
$$
\frac{d^2 x^\mu}{d\tau^2} + \gamma^\mu_{\nu\lambda} \frac{dx^\nu}{d\tau} \frac{dx^\lambda}{d\tau} = 0
$$
where
for schwarzschild in spherical coordinates, the christoffel symbols are computed analytically in christoffel_symbols_spherical. this avoids the need for numerical derivatives and ensures physical correctness.
a leapfrog method is used for time evolution in integrate_geodesic_spherical, which is stable and preserves the norm of the four-velocity (timelike worldlines).
-
FourVector(seesrc/relativity.rs): represents spacetime events or four-momentum. Used throughout the codebase for all spacetime calculations. -
FourVelocity: Derivative of position with respect to proper time; always normalized to$-c^2$ in Minkowski metric. Construction and normalization routines are robust: all four-velocity and four-momentum creation is clamped to a global gamma/energy cap, and fallback logic ensures no unphysical (spacelike or NaN/Inf) states. - Operations: Lorentz boosts (
lorentz_boost_x,lorentz_boost_beta), inner products (minkowski_dot,metric_dot), normalization, conversion between 3-velocity and four-velocity, robust on-shell projection, and gamma clamping.
Example:
use relativity::{FourVector, FourVelocity};
let c = 299792458.0;
let v = FourVelocity::from_3velocity(0.1 * c, 0.0, 0.0, c);
let boosted = v.lorentz_boost_x(0.5); // boost in x-directionmetric(seesrc/curvature.rs): encapsulates the metric tensor for minkowski or schwarzschild spacetime. used for all inner products and normalization.christoffel_symbols_spherical: returns analytic christoffel symbols for schwarzschild in spherical coordinates. used directly in geodesic integration.
example:
use curvature::{metric, christoffel_symbols_spherical};
let rs = 2.0 * g * mass / (c * c);
let gamma = christoffel_symbols_spherical(r, theta, rs);
let metric = metric::schwarzschild_spherical(t, r, theta, phi, rs);integrate_geodesic_spherical(seesrc/curvature.rs): Integrates a particle's worldline using the geodesic equation in spherical coordinates. Handles all coordinate singularities and normalizes the four-velocity. Used as the canonical entry point for relativistic motion.FourVelocity::integrate_accel(seesrc/relativity.rs): Robustly integrates four-acceleration using RK4, with safety features:- Four-acceleration is capped to a maximum value to prevent runaway integration.
- The proper time step (
d_tau) is adaptively reduced for large gamma (relativistic factor). - Diagnostics are printed if capping or adaptive stepping is triggered.
- All outputs are clamped and normalized to ensure physical validity.
example:
use relativity::FourVelocity;
let (x_next, u_next) = v.integrate_geodesic(&x, &metric_fn, None, mass, d_tau, dx);
let v_next = v.integrate_accel(four_accel, d_tau, c);world(seesrc/ecs/mod.rs): manages entities and their components. provides methods for entity creation, deletion, and component management.physicssystem: integrates acceleration into velocity and velocity into position for all entities. seephysicssystemand its usage insrc/main.rs.
example:
use ecs::{world, physicssystem};
let mut world = world::new();
world.register_component::<position>();
let entity = world.create_entity();
world.add_component(entity, position(fourvector { t: 0.0, x: 1.0, y: 0.0, z: 0.0 }));
let mut physics_system = physicssystem;
physics_system.run(&mut world);src/gravity.rs: provides several gravity models via the GravityModel trait:
NewtonianGravity: Classic Newtonian gravity (for reference)PostNewtonianGravity: 1PN (weak field, slow motion) correctionGeneralRelativityGravity: Analytic Schwarzschild solution (static, spherically symmetric mass)NumericalRelativityGravity: Full grid-based metric evolution and force calculation (seesrc/numerical_relativity.rs) TheGravityKindenum allows runtime selection between these models.
Example:
use gravity::{GravityKind, GravityModel, NumericalRelativityGravity};
let grid = ...; // create or load a grid
let gravity = GravityKind::NumericalRelativity(NumericalRelativityGravity::new(grid));
let force = gravity.gravity_force(&pos, &vel, m, &src_pos, &src_vel, src_m, c);- See
src/numerical_relativity.rsfor the full infrastructure for evolving the metric on a 3D grid using the BSSN formalism. - The
GravityKind::NumericalRelativityvariant now computes the metric, Christoffel symbols, and geodesic deviation at each grid point, and applies these to force calculations for all entities. - The grid can be seeded with curvature (e.g., a Gaussian bump in the conformal factor), and the BSSN evolution is robustified with constraint damping and periodic boundary conditions.
- Debugging output is available: metric tensor, Christoffel symbol extrema, and force vectors are printed for each entity, allowing diagnosis of curvature and force propagation.
all coordinate conversions and denominators are clamped to avoid division by zero (see cartesian_to_spherical and all uses of .max() and .clamp() in src/curvature.rs).
four-velocity and four-momentum construction is globally clamped to a maximum gamma/energy; normalization is checked for nan/inf and handled gracefully (see normalize, clamp_gamma, and from_3velocity/from_four_momentum in src/relativity.rs).
force integration (integrate_accel) is robust to large forces and velocities, with capping and adaptive stepping.
collision response is robustified: post-collision four-momenta are projected on-shell and clamped, and all unphysical states are caught and corrected.
no christoffel symbol transformation between coordinate systems (avoids known bugs and ensures physical correctness).
see src/main.rs for a full simulation loop. minimal example:
use relativity::FourVector;
use curvature::integrate_geodesic_spherical;
let x = FourVector { t: 0.0, x: 10.0, y: 0.0, z: 0.0 };
let u = FourVector { t: 1.0, x: 0.0, y: 0.1, z: 0.0 };
let mass = 1.0;
let g = 6.67430e-11;
let c = 299792458.0;
let d_tau = 0.01;
let (x_next, u_next) = integrate_geodesic_spherical(&x, &u, mass, g, c, d_tau);- carroll, s. m. (2004). spacetime and geometry: an introduction to general relativity
- wald, r. m. (1984). general relativity
- poisson, e. (2004). a relativist's toolkit: the mathematics of black-hole mechanics
- wikipedia: schwarzschild metric
- wikipedia: geodesic (general relativity)
- clone and build:
git clone https://github.com/saltytine/relativity cd relativity cargo build - run the example simulation:
this will initialize the ecs, create entities, and run a relativistic simulation loop (see
cargo run
src/main.rs). - write your own simulation:
- use the ecs to create entities with
position,velocity,acceleration,mass, andforcecomponents. - use
integrate_geodesic_sphericalfor relativistic motion, or extend the ecs with your own systems. - swap or extend gravity models in
src/gravity.rsas needed.
- use the ecs to create entities with
- testing:
unit tests are provided for core math and ecs features.
cargo test
src/curvature.rs: metric, christoffel symbols, geodesic integrator, robust coordinate conversion.src/relativity.rs: four-vector algebra, four-velocity, four-force, normalization, lorentz boosts.src/gravity.rs: gravity models (newtonian, post-newtonian, analytic GR, and numerical relativity infrastructure), trait-based extensibility.src/numerical_relativity.rs: infrastructure for evolving the metric numerically on a grid (foundation for full numerical relativity).src/ecs/: ecs core (entities, components, systems, world management).src/main.rs: application entry point, ecs setup, simulation loop, and example usage.
- integrate a robust linear algebra library (
nalgebraorglam). - implement classical newtonian physics: collision detection, rigid body dynamics.
- extend to relativistic physics: time dilation, length contraction, relativistic momentum/energy, light speed constraints.
- physics integrators use 4d spacetime vectors; timestep based on proper time per object.
- modular ecs (entity-component-system) foundation using a custom implementation.
- renderer abstraction layer: swap between opengl (light systems) and vulkan/metal/dx12 (heavy systems).
- clean separation of engine modules: ecs, physics, rendering, input, and tooling.
- flexible, multi-pass rendering pipeline.
- physically based rendering (pbr), shadow mapping.
- shaders for relativistic visual effects: doppler shift, aberration.
- level of detail (lod) system for performance scaling.
- multi-threading with rust async/rayon for physics and rendering.
- configurable feature toggles for low/high-end hardware.
- simd optimization and caching for hot physics loops.
- clean api for entity management, physics parameters, and relativity settings.
- debugging tools: spacetime interval visualization, worldlines, frame transforms.
- unit tests for all modules.
- physics validation against known relativistic scenarios (twin paradox, light clocks, relativistic collisions).
- benchmarking and tuning for various hardware profiles.
- BSSN grid-based metric evolution (vacuum, 3+1D, robust numerics)
- Christoffel symbol computation from grid metric (finite differences)
- NumericalRelativityGravity: force calculation using grid Christoffel symbols
- Debug output for metric, Christoffel symbols, and force at each entity
- Grid seeding with curvature (Gaussian bump in conformal factor)
- Constraint damping and periodic boundary conditions
- project structure initialized
- ecs foundation (entity, component, system traits)
- ecs scheduler/dispatcher
- entity management (creation, deletion)
- component storage (sparse set, archetype, etc.)
- system registration and execution
- event system
- module separation (ecs, physics, rendering, input, tooling)
- renderer abstraction layer (opengl, vulkan, metal, dx12)
- engine configuration system
- integrate linear algebra library (
nalgebraorglam) - vector, matrix, quaternion math utilities
- classical physics engine core
- position and velocity components
- acceleration component and integration
- mass and force components (placeholders)
- physics system: acceleration → velocity → position
- rigid body dynamics
- collision detection (aabb, obb, sphere, mesh)
- collision resolution
- physics timestep/integration
- relativistic physics extension
- 4d spacetime vector math
- time dilation
- length contraction
- relativistic momentum & energy
- light speed constraints
- proper time-based physics integration
- advanced physics systems (planned)
- rendering pipeline abstraction
- multi-pass rendering support
- physically based rendering (pbr)
- shadow mapping
- relativistic visual shaders (doppler, aberration)
- level of detail (lod) system
- model/mesh loader
- texture/material system
- camera system
- lighting system
- multi-threading (async, rayon)
- feature toggles/config for hardware profiles
- simd optimization for physics
- caching/reuse of calculations
- dynamic lod switching
- render resolution scaling
- public api for entity/component management
- physics parameter configuration
- relativity settings api
- debugging tools
- force, metric, and Christoffel symbol debugging output (NumericalRelativity)
- spacetime interval visualization
- worldline visualization
- frame transform visualization
- logging and diagnostics for numerical relativity
- unit tests for ecs
- unit tests for math utilities
- unit tests for classical physics
- unit tests for relativistic physics
- rendering validation tests
- physics scenario validation (twin paradox, light clocks, relativistic collisions)
- benchmarking on low-end hardware
- benchmarking on high-end hardware
- performance tuning and profiling
this readme will be updated as the project progresses. each step will include detailed implementation, documentation, and unit tests.