TExcelTAD
Home › Game Engine Architecture in C++ › Physics with Jolt

Physics with Jolt

Writing a robust rigid-body solver is a project of its own: broad phase, narrow phase, contact manifolds, constraint solving, sleeping, continuous collision. The Game Physics & Animation course teaches how those pieces work. An engine should almost always integrate a physics library rather than grow one. Jolt Physics (Jorrit Rouwe, MIT licence) is a strong default for 3D: it is multithreaded, deterministic when used carefully, has character controllers and vehicles, and ships in Horizon Forbidden West and in Godot 4.4+ as a built-in option.

The engine-side questions are the same for every physics library, so this lesson covers both: how to set Jolt up, and how to connect any physics world to your ECS.

The bridge between ECS and physics

The physics world owns its own copy of every body. The engine keeps a mapping between entities and body IDs, and every frame it does three things:

  1. Push: write gameplay changes into physics (teleports, impulses, kinematic targets).
  2. Step: advance the physics world in fixed steps (see The Game Loop and Fixed Timestep).
  3. Pull: copy the resulting positions and rotations of active bodies back into the entities' Transform components.

The runnable model uses a toy world (gravity, a floor, no rotation) in place of Jolt, but the bridge is the real shape:

cpp · try it yourself
#include <iomanip>
#include <iostream>
#include <map>
#include <string>
#include <vector>

// --- stands in for the physics library ----------------------------------
struct BodyID { int index; };
struct Body { double y, vy; bool dynamic, active; };
class PhysicsWorld {
    std::vector<Body> bodies;
public:
    BodyID add(double y, bool dynamic) { bodies.push_back({y, 0, dynamic, dynamic && y > 0.5}); return {int(bodies.size()) - 1}; }
    void addImpulse(BodyID id, double dv) { bodies[id.index].vy += dv; bodies[id.index].active = true; }
    void step(double dt) {
        for (Body& b : bodies) {
            if (!b.dynamic || !b.active) continue;
            b.vy += -9.81 * dt;
            b.y += b.vy * dt;
            if (b.y <= 0.5) { b.y = 0.5; b.vy = 0; b.active = false; }   // rests on the floor: goes to sleep
        }
    }
    double positionY(BodyID id) const { return bodies[id.index].y; }
    bool isActive(BodyID id) const { return bodies[id.index].active; }
};

// --- engine side -------------------------------------------------------
struct Transform { double y; };
struct RigidBody { BodyID body; };

int main() {
    std::cout << std::fixed << std::setprecision(3);
    std::map<std::string, Transform> transforms = {{"crate", {3.0}}, {"ball", {0.5}}, {"floor", {0.0}}};
    std::map<std::string, RigidBody> rigidBodies;

    PhysicsWorld world;
    for (auto& [name, t] : transforms) rigidBodies[name] = {world.add(t.y, name != "floor")};

    const double step = 1.0 / 60.0;
    double accumulator = 0;
    const double frameTimes[] = {1.0 / 30, 1.0 / 30, 1.0 / 30, 1.0 / 30, 1.0 / 30, 1.0 / 30};
    int steps = 0, copies = 0;

    for (int frame = 0; frame < 6; frame++) {
        if (frame == 2) world.addImpulse(rigidBodies["ball"].body, 4.0);        // 1) push gameplay input
        accumulator += frameTimes[frame];
        while (accumulator >= step - 1e-9) { world.step(step); accumulator -= step; steps++; }   // 2) step
        for (auto& [name, rb] : rigidBodies) {                                   // 3) pull active bodies
            if (!world.isActive(rb.body)) continue;
            transforms[name].y = world.positionY(rb.body);
            copies++;
        }
        std::cout << "frame " << frame << ": crate " << transforms["crate"].y << "  ball " << transforms["ball"].y << "\n";
    }
    std::cout << steps << " physics steps, " << copies << " transform copies\n";
}
frame 0: crate 2.992  ball 0.500
frame 1: crate 2.973  ball 0.500
frame 2: crate 2.943  ball 0.625
frame 3: crate 2.902  ball 0.739
frame 4: crate 2.850  ball 0.843
frame 5: crate 2.787  ball 0.935
12 physics steps, 10 transform copies

The game runs at 30 FPS and physics at 60 Hz, so each frame takes two steps (12 in total). The floor is static and never copied, and the ball rests asleep on the floor until the impulse in frame 2 wakes it, so the pull phase made 10 copies instead of 18. Copying only active bodies matters in real scenes, where most bodies are asleep most of the time. Jolt can tell you which bodies moved through BodyActivationListener or by iterating PhysicsSystem::GetActiveBodies.

Setting up Jolt

Jolt needs a few global registrations, an allocator for per-step scratch memory, a job system, and three small classes that describe collision layers. The structure below follows Jolt's HelloWorld sample.

cpp
#include <Jolt/Jolt.h>
#include <Jolt/RegisterTypes.h>
#include <Jolt/Core/Factory.h>
#include <Jolt/Core/TempAllocator.h>
#include <Jolt/Core/JobSystemThreadPool.h>
#include <Jolt/Physics/PhysicsSettings.h>
#include <Jolt/Physics/PhysicsSystem.h>
#include <Jolt/Physics/Collision/Shape/BoxShape.h>
#include <Jolt/Physics/Collision/Shape/SphereShape.h>
#include <Jolt/Physics/Body/BodyCreationSettings.h>
#include <thread>
using namespace JPH;

namespace Layers { constexpr ObjectLayer NON_MOVING = 0, MOVING = 1, NUM_LAYERS = 2; }
namespace BroadPhaseLayers { constexpr BroadPhaseLayer NON_MOVING(0), MOVING(1); constexpr uint NUM_LAYERS = 2; }

class BPLayerInterfaceImpl final : public BroadPhaseLayerInterface {
public:
    uint GetNumBroadPhaseLayers() const override { return BroadPhaseLayers::NUM_LAYERS; }
    BroadPhaseLayer GetBroadPhaseLayer(ObjectLayer layer) const override {
        return layer == Layers::NON_MOVING ? BroadPhaseLayers::NON_MOVING : BroadPhaseLayers::MOVING;
    }
#if defined(JPH_EXTERNAL_PROFILE) || defined(JPH_PROFILE_ENABLED)
    const char* GetBroadPhaseLayerName(BroadPhaseLayer layer) const override {
        return layer == BroadPhaseLayers::NON_MOVING ? "NON_MOVING" : "MOVING";
    }
#endif
};
class ObjectVsBroadPhaseLayerFilterImpl final : public ObjectVsBroadPhaseLayerFilter {
public:
    bool ShouldCollide(ObjectLayer layer1, BroadPhaseLayer layer2) const override {
        return layer1 == Layers::MOVING || layer2 == BroadPhaseLayers::MOVING;   // static vs static never collides
    }
};
class ObjectLayerPairFilterImpl final : public ObjectLayerPairFilter {
public:
    bool ShouldCollide(ObjectLayer a, ObjectLayer b) const override {
        return a == Layers::MOVING || b == Layers::MOVING;
    }
};

int main() {
    RegisterDefaultAllocator();
    Factory::sInstance = new Factory();
    RegisterTypes();

    TempAllocatorImpl tempAllocator(10 * 1024 * 1024);
    JobSystemThreadPool jobSystem(cMaxPhysicsJobs, cMaxPhysicsBarriers,
                                  int(std::thread::hardware_concurrency()) - 1);

    BPLayerInterfaceImpl bpLayers;                  // these three must outlive the PhysicsSystem
    ObjectVsBroadPhaseLayerFilterImpl objVsBp;
    ObjectLayerPairFilterImpl objVsObj;

    PhysicsSystem physics;
    physics.Init(/*maxBodies*/ 1024, /*numBodyMutexes*/ 0, /*maxBodyPairs*/ 1024,
                 /*maxContactConstraints*/ 1024, bpLayers, objVsBp, objVsObj);

    BodyInterface& bodies = physics.GetBodyInterface();
    BodyCreationSettings floorSettings(new BoxShape(Vec3(100.0f, 1.0f, 100.0f)), RVec3(0.0_r, -1.0_r, 0.0_r),
                                       Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING);
    BodyID floorId = bodies.CreateAndAddBody(floorSettings, EActivation::DontActivate);
    BodyCreationSettings ballSettings(new SphereShape(0.5f), RVec3(0.0_r, 2.0_r, 0.0_r),
                                      Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING);
    BodyID ballId = bodies.CreateAndAddBody(ballSettings, EActivation::Activate);
    physics.OptimizeBroadPhase();                   // after adding many bodies at once, e.g. on level load

    const float step = 1.0f / 60.0f;
    for (int i = 0; i < 120 && bodies.IsActive(ballId); i++) {
        physics.Update(step, /*collisionSteps*/ 1, &tempAllocator, &jobSystem);
        RVec3 p = bodies.GetCenterOfMassPosition(ballId);   // pull into your Transform component
    }

    bodies.RemoveBody(ballId);  bodies.DestroyBody(ballId);
    bodies.RemoveBody(floorId); bodies.DestroyBody(floorId);
    UnregisterTypes();
    delete Factory::sInstance;
    Factory::sInstance = nullptr;
}

Things that trip people up:

  • Build flags must match. Defines such as JPH_DOUBLE_PRECISION, JPH_DEBUG_RENDERER, JPH_PROFILE_ENABLED and JPH_OBJECT_STREAM change class layouts. Link through the CMake target (find_package(Jolt CONFIG REQUIRED), Jolt::Jolt with vcpkg's joltphysics port) so your code sees the same defines as the library.
  • RVec3 and _r are real-valued positions: float normally, double with JPH_DOUBLE_PRECISION for very large worlds.
  • Shapes are reference counted (RefConst<Shape>); the new BoxShape(…) passed to the settings is owned from then on, so don't delete it.
  • Locking. GetBodyInterface() takes body locks; inside contact callbacks use GetBodyInterfaceNoLock() or the body passed to you. Don't add or remove bodies during Update.
  • Contact callbacks (ContactListener::OnContactAdded) run on worker threads. Queue events and handle them on the main thread after the step, as in the event bus lesson.

Tip: Map game "collision layers" (player, enemy, projectile, debris, trigger) onto Jolt's ObjectLayer and keep only two or three broad-phase layers (static, moving, maybe debris). Too many broad-phase layers slows the broad phase down.

Other options

Library Notes
Box2D v3 2D, C API, multithreaded; the obvious 2D choice
PhysX 5 NVIDIA, open source (BSD-3); used by many engines; GPU features on NVIDIA hardware
Bullet older, widely known; robotics and research, less active for games
Rapier Rust, with JS bindings (used in the Game Physics course's browser examples)

Test yourself

In the ECS-physics bridge, why copy only active bodies back into transforms?

  1. Sleeping bodies have no position
  2. Sleeping bodies haven't moved, so copying them is wasted work, and most bodies sleep most of the time
  3. Jolt forbids reading sleeping bodies
  4. It makes the simulation deterministic

What are Jolt's ObjectLayer pair filter and broad-phase layer interface for?

  1. Rendering order
  2. Deciding which kinds of objects can collide, and grouping them into a few broad-phase trees
  3. Audio occlusion
  4. Saving bodies to disk

Why should contact callbacks queue events instead of running gameplay code directly?

  1. They are called before the step
  2. They run on physics worker threads during Update, where changing bodies or game state is unsafe
  3. They have no access to body IDs
  4. They are only called in debug builds