JoltPhysics
A multi core friendly rigid body physics and collision detection library. Written in C++. Suitable for games and VR applications. Used by Horizon Forbidden West.
Top Related Projects
Quick Overview
Jolt Physics is a multi-core friendly, open-source physics engine written in C++. It is designed for game development and real-time simulation, offering high performance and a wide range of features for rigid body dynamics, collision detection, and constraint solving.
Pros
- High performance and multi-core support for efficient physics simulations
- Comprehensive feature set including various joint types, collision shapes, and vehicle simulation
- Cross-platform compatibility (Windows, Linux, macOS, and game consoles)
- Well-documented with extensive examples and test cases
Cons
- Relatively new compared to some established physics engines, which may result in fewer community resources
- Steeper learning curve for developers not familiar with advanced physics concepts
- Limited built-in support for soft body physics and fluid simulation
Code Examples
- Creating a basic physics world:
JPH::PhysicsSystem physics_system;
physics_system.Init(1024, 0, 1024, 1024);
physics_system.SetGravity(JPH::Vec3(0, -9.81f, 0));
- Adding a dynamic box to the world:
JPH::BoxShapeSettings box_settings(JPH::Vec3(1, 1, 1));
JPH::ShapeSettings::ShapeResult result = box_settings.Create();
JPH::BodyCreationSettings body_settings(result.Get(), JPH::Vec3(0, 10, 0), JPH::Quat::sIdentity(), JPH::EMotionType::Dynamic, Layers::MOVING);
JPH::Body *body = physics_system.GetBodyInterface().CreateBody(body_settings);
physics_system.GetBodyInterface().AddBody(body->GetID(), JPH::EActivation::Activate);
- Stepping the physics simulation:
const float delta_time = 1.0f / 60.0f;
physics_system.Update(delta_time, 1, 1, &temp_allocator, &job_system);
Getting Started
-
Clone the repository:
git clone https://github.com/jrouwe/JoltPhysics.git
-
Build the library using CMake:
cd JoltPhysics mkdir Build cd Build cmake .. cmake --build . --config Release
-
Include Jolt Physics in your project:
#include <Jolt/Jolt.h> #include <Jolt/Physics/PhysicsSystem.h>
-
Initialize the physics system and start using Jolt Physics in your application as shown in the code examples above.
Competitor Comparisons
Bullet Physics SDK: real-time collision detection and multi-physics simulation for VR, games, visual effects, robotics, machine learning etc.
Pros of Bullet3
- Widely adopted and battle-tested in various industries
- Extensive documentation and community support
- Supports a broader range of platforms and programming languages
Cons of Bullet3
- Older codebase with some legacy design decisions
- Can be more complex to set up and use for beginners
- Performance may be slower in certain scenarios
Code Comparison
JoltPhysics:
JPH::BodyInterface& body_interface = physics_system.GetBodyInterface();
JPH::Body* body = body_interface.CreateAndAddBody(body_creation_settings, JPH::EActivation::Activate);
Bullet3:
btRigidBody::btRigidBodyConstructionInfo rbInfo(mass, myMotionState, colShape, localInertia);
btRigidBody* body = new btRigidBody(rbInfo);
dynamicsWorld->addRigidBody(body);
JoltPhysics offers a more streamlined API for body creation and addition to the physics world, while Bullet3 requires separate steps for construction and world addition. JoltPhysics also uses a more modern C++ style with namespaces and references.
Both libraries provide robust physics simulation capabilities, but JoltPhysics focuses on modern C++ design and performance optimization, while Bullet3 offers broader platform support and a larger ecosystem of tools and resources.
NVIDIA PhysX SDK
Pros of PhysX
- Extensive industry adoption and long-term development history
- Robust GPU acceleration support for improved performance
- Comprehensive documentation and community support
Cons of PhysX
- Larger codebase and potentially higher complexity
- Closed-source nature limits customization and modification
- May have higher system requirements due to its feature-rich nature
Code Comparison
PhysX:
PxRigidDynamic* dynamicActor = physics.createRigidDynamic(PxTransform(PxVec3(0, 0, 0)));
PxRigidStatic* staticActor = physics.createRigidStatic(PxTransform(PxVec3(0, 0, 0)));
PxShape* shape = physics.createShape(PxSphereGeometry(1.0f), *material);
dynamicActor->attachShape(*shape);
Jolt Physics:
Body& body = *bodyInterface.CreateBody(BodyCreationSettings(new SphereShape(1.0f), Vec3(0, 0, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING));
bodyInterface.AddBody(body.GetID(), EActivation::Activate);
Both libraries offer similar functionality for creating and managing physics objects, but PhysX tends to have a more verbose syntax compared to Jolt Physics' more concise approach.
Box2D is a 2D physics engine for games
Pros of Box2D
- Lightweight and efficient, ideal for 2D physics simulations
- Well-established with extensive documentation and community support
- Easy to integrate into existing projects, especially for 2D games
Cons of Box2D
- Limited to 2D physics, lacking 3D capabilities
- May require additional work for complex 3D simulations or advanced features
- Less frequent updates compared to more actively maintained projects
Code Comparison
Box2D (C++):
b2Vec2 gravity(0.0f, -10.0f);
b2World world(gravity);
b2BodyDef bodyDef;
bodyDef.type = b2_dynamicBody;
b2Body* body = world.CreateBody(&bodyDef);
Jolt Physics (C++):
JPH::PhysicsSystem physics_system;
JPH::BodyInterface& body_interface = physics_system.GetBodyInterface();
JPH::Body* body = body_interface.CreateBody(JPH::BodyCreationSettings(
new JPH::BoxShape(JPH::Vec3(1, 1, 1)),
JPH::RVec3(0, 10, 0),
JPH::Quat::sIdentity(),
JPH::EMotionType::Dynamic,
0
));
Summary
Box2D is a popular choice for 2D physics simulations, offering simplicity and efficiency. However, Jolt Physics provides more comprehensive 3D capabilities and active development. The choice between them depends on project requirements and dimensionality needs.
2D physics engine for games
Pros of LiquidFun
- Specialized in fluid and soft body simulation, offering unique capabilities for game developers
- Backed by Google, potentially providing more resources and long-term support
- Includes particle-based fluid simulation, which is not a primary focus of Jolt Physics
Cons of LiquidFun
- Less active development, with the last update in 2015
- Limited to 2D physics, while Jolt Physics supports 3D simulations
- Smaller community and fewer recent contributions compared to Jolt Physics
Code Comparison
LiquidFun (C++):
b2World world(gravity);
b2ParticleSystemDef particleSystemDef;
b2ParticleSystem* particleSystem = world.CreateParticleSystem(&particleSystemDef);
Jolt Physics (C++):
JPH::PhysicsSystem physics_system;
physics_system.Init(max_bodies, num_body_mutexes, max_body_pairs, max_contact_constraints, broad_phase_layer_interface, object_vs_broad_phase_layer_filter, object_vs_object_layer_filter);
Both libraries use similar concepts for initializing the physics world, but LiquidFun focuses on particle systems for fluid simulation, while Jolt Physics provides a more general-purpose physics system setup.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Jolt Physics
A multi core friendly rigid body physics and collision detection library. Suitable for games and VR applications. Used by Horizon Forbidden West.
A YouTube video showing a ragdoll pile simulated with Jolt Physics. |
For more demos and videos go to the Samples section.
Design considerations
Why create yet another physics engine? Firstly, it has been a personal learning project. Secondly, I wanted to address some issues that I had with existing physics engines:
- Games do more than simulating physics. These things happen across multiple threads. We emphasize on concurrently accessing physics data outside of the main simulation update:
- Sections of the simulation can be loaded / unloaded in the background. We prepare a batch of physics bodies on a background thread without locking or affecting the simulation. We insert the batch into the simulation with a minimal impact on performance.
- Collision queries can run parallel to adding / removing or updating a body. If a change to a body happened on the same thread, the change will be immediately visible. If the change happened on another thread, the query will see a consistent before or after state. An alternative would be to have a read and write version of the world. This prevents changes from being visible immediately, so we avoid this.
- Collision queries can run parallel to the main physics simulation. We do a coarse check (broad phase query) before the simulation step and do fine checks (narrow phase query) in the background. This way, long running processes (like navigation mesh generation) can be spread out across multiple frames.
- Accidental wake up of bodies cause performance problems when loading / unloading content. Therefore, bodies will not automatically wake up when created. Neighboring bodies will not be woken up when bodies are removed. This can be triggered manually if desired.
- The simulation runs deterministically. You can replicate a simulation to a remote client by merely replicating the inputs to the simulation. Read the Deterministic Simulation section to understand the limits.
- We try to simulate behavior of rigid bodies in the real world but make approximations. Therefore, this library should mainly be used for games or VR simulations.
Features
- Simulation of rigid bodies of various shapes using continuous collision detection:
- Sphere
- Box
- Capsule
- Tapered-capsule
- Cylinder
- Tapered-cylinder
- Convex hull
- Plane
- Compound
- Mesh (triangle)
- Terrain (height field)
- Simulation of constraints between bodies:
- Fixed
- Point
- Distance (including springs)
- Hinge
- Slider (also called prismatic)
- Cone
- Rack and pinion
- Gear
- Pulley
- Smooth spline paths
- Swing-twist (for humanoid shoulders)
- 6 DOF
- Motors to drive the constraints.
- Collision detection:
- Casting rays.
- Testing shapes vs shapes.
- Casting a shape vs another shape.
- Broadphase only tests to quickly determine which objects may intersect.
- Sensors (trigger volumes).
- Animated ragdolls:
- Hard keying (kinematic only rigid bodies).
- Soft keying (setting velocities on dynamic rigid bodies).
- Driving constraint motors to an animated pose.
- Mapping a high detail (animation) skeleton onto a low detail (ragdoll) skeleton and vice versa.
- Game character simulation (capsule)
- Rigid body character. Moves during the physics simulation. Cheapest option and most accurate collision response between character and dynamic bodies.
- Virtual character. Does not have a rigid body in the simulation but simulates one using collision checks. Updated outside of the physics update for more control. Less accurate interaction with dynamic bodies.
- Vehicles
- Wheeled vehicles.
- Tracked vehicles.
- Motorcycles.
- Soft body simulation (e.g. a soft ball or piece of cloth).
- Edge constraints.
- Dihedral bend constraints.
- Tetrahedron volume constraints.
- Long range attachment constraints (also called tethers).
- Limiting the simulation to stay within a certain range of a skinned vertex.
- Internal pressure.
- Collision with simulated rigid bodies.
- Collision tests against soft bodies.
- Water buoyancy calculations.
- An optional double precision mode that allows large simulations.
Supported platforms
- Windows (Desktop or UWP) x86/x64/ARM32/ARM64
- Linux (tested on Ubuntu) x64/ARM64
- FreeBSD
- Android x86/x64/ARM32/ARM64
- Platform Blue (a popular game console) x64
- macOS x64/ARM64
- iOS x64/ARM64
- WebAssembly, see this separate project.
Required CPU features
- On x86/x64 the minimal requirements are SSE2. The library can be compiled using SSE4.1, SSE4.2, AVX, AVX2, or AVX512.
- On ARM64 the library uses NEON and FP16. On ARM32 it can be compiled without any special CPU instructions.
Documentation
To learn more about Jolt go to the latest Architecture and API documentation. Documentation for a specific release is also available.
To get started, look at the HelloWorld example. A HelloWorld example using CMake FetchContent is also available to show how you can integrate Jolt Physics in a CMake project.
Some algorithms used by Jolt are described in detail in my GDC 2022 talk: Architecting Jolt Physics for 'Horizon Forbidden West' (slides, slides with speaker notes, video).
Compiling
- Compiles with Visual Studio 2019+, Clang 10+ or GCC 9+.
- Uses C++ 17.
- Depends only on the standard template library.
- Doesn't use RTTI.
- Doesn't use exceptions.
If you want to run on Platform Blue you'll need to provide your own build environment and PlatformBlue.h due to NDA requirements. This file is available on the Platform Blue developer forum.
For build instructions go to the Build section. When upgrading from an older version of the library go to the Release Notes or API Changes sections.
Performance
If you're interested in how Jolt scales with multiple CPUs and compares to other physics engines, take a look at this document.
Folder structure
- Assets - This folder contains assets used by the TestFramework, Samples and JoltViewer.
- Build - Contains everything needed to build the library, see the Build section.
- Docs - Contains documentation for the library.
- HelloWorld - A simple application demonstrating how to use the Jolt Physics library.
- Jolt - All source code for the library is in this folder.
- JoltViewer - It is possible to record the output of the physics engine using the DebugRendererRecorder class (a .jor file), this folder contains the source code to an application that can visualize a recording. This is useful for e.g. visualizing the output of the PerformanceTest from different platforms. Currently available on Windows only.
- PerformanceTest - Contains a simple application that runs a performance test and collects timing information.
- Samples - This contains the sample application, see the Samples section. Currently available on Windows only.
- TestFramework - A rendering framework to visualize the results of the physics engine. Used by Samples and JoltViewer. Currently available on Windows only.
- UnitTests - A set of unit tests to validate the behavior of the physics engine.
- WebIncludes - A number of JavaScript resources used by the internal profiling framework of the physics engine.
Bindings for other languages
- C here and here
- C#
- JavaScript
- Zig
Integrations in other engines
See a list of projects that use Jolt Physics here.
License
The project is distributed under the MIT license.
Contributions
All contributions are welcome! If you intend to make larger changes, please discuss first in the GitHub Discussion section. For non-trivial changes, we require that you agree to a Contributor Agreement. When you create a PR, CLA assistant will prompt you to sign it.
Top Related Projects
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot