TExcelTAD
Home › Game Physics & Animation › Determinism

Determinism

A simulation is deterministic when the same starting state and the same inputs always produce the same result, bit for bit. A fixed timestep is the first requirement, but not the only one. Determinism decides whether you can:

  • record only the player's inputs and replay a match later;
  • run a lockstep multiplayer game (RTS, fighting games), where every machine simulates the world and only inputs travel over the network;
  • reproduce a bug report: "the crate fell through the floor on frame 4182";
  • run automated tests that compare a simulation to a saved result.

There are levels: the same binary on the same machine (easy), the same binary on different machines with the same CPU family (harder), and different compilers, CPUs and platforms (hard, and only some engines promise it).

Floating-point math is not associative

In real numbers (a + b) + c == a + (b + c). In floating point, each + rounds, so the order of operations changes the last bits. A physics engine that sums forces, or solves contacts, in a different order gets a slightly different answer, and in a chaotic system (a stack of boxes, a break shot in pool) tiny differences grow until objects end up in visibly different places.

cpp · try it yourself
#include <iostream>
#include <iomanip>

int main() {
    std::cout << std::setprecision(17);
    double a = 0.1, b = 0.2, c = 0.3;
    std::cout << "(a + b) + c = " << (a + b) + c << "\n";
    std::cout << "a + (b + c) = " << a + (b + c) << "\n";

    // Summing the same forces in a different order:
    double forces[] = {1e8, 3.14159, -1e8, 2.71828};
    double forward = 0, backward = 0;
    for (int i = 0; i < 4; i++) forward += forces[i];
    for (int i = 3; i >= 0; i--) backward += forces[i];
    std::cout << "forward sum  = " << forward << "\n";
    std::cout << "backward sum = " << backward << "\n";
}
(a + b) + c = 0.60000000000000009
a + (b + c) = 0.59999999999999998
forward sum  = 5.8598699991989136
backward sum = 5.8598700016736984

Neither answer is wrong; they are just different. Determinism doesn't need exact math, it needs the same math every time.

Order matters in the solver too

Physics solvers handle contacts one at a time (sequential impulses, see Stacking, Iterations and Sleeping). The order of contacts changes the result even with perfect arithmetic. Here three balls touch in a row, and a single pass resolves the two contacts in different orders:

cpp · try it yourself
#include <iostream>
#include <iomanip>

struct Ball { double v; };

// One elastic contact between equal masses: swap the approaching velocities.
void resolve(Ball& left, Ball& right) {
    if (left.v > right.v) { double t = left.v; left.v = right.v; right.v = t; }
}

int main() {
    std::cout << std::fixed << std::setprecision(3);
    for (int order = 0; order < 2; order++) {
        Ball a{3}, b{0}, c{-1};          // a hits b while c moves into b from the right
        if (order == 0) { resolve(a, b); resolve(b, c); }
        else            { resolve(b, c); resolve(a, b); }
        std::cout << (order == 0 ? "A-B then B-C: " : "B-C then A-B: ")
                  << a.v << " " << b.v << " " << c.v << "\n";
    }
}
A-B then B-C: 0.000 -1.000 3.000
B-C then A-B: -1.000 3.000 0.000

Same balls, same contacts, different outcome. (After one pass neither result is finished: in both, two balls are still approaching, and further solver iterations would keep working on them. The point is that the intermediate state, and therefore the final one, depends on the order.) Engines therefore make the contact order depend only on the simulation state: pairs are sorted by stable body IDs or by the order in which they were created, never by memory addresses (which change between runs) or by iterating an unordered hash set.

Common sources of non-determinism

Source Fix
Variable dt, or physics in a per-frame update fixed step (Fixed Timestep and Interpolation)
Iterating std::unordered_map/unordered_set, or sorting by pointer sort pairs and islands by stable IDs
Multithreading where the result depends on which thread finishes first split work deterministically; merge results in a fixed order
Compiler flags such as -ffast-math, or fused multiply-add on one platform but not another disable fast-math for simulation code; control FMA contraction (for example -ffp-contract=off)
sin, cos, atan2, sqrt from different math libraries sqrt is exactly rounded by IEEE 754; for trig use your own implementation where cross-platform results matter
Uninitialized memory, reading a stale value initialize everything; run sanitizers
Game code that reads wall-clock time or an unseeded generator seeded generators, simulation time only

Fixed-point math: determinism by construction

Some lockstep games avoid floats in the simulation entirely and use fixed-point numbers: integers with an implied scale (here 16.16, so 65536 means 1.0). Integer arithmetic is exact and identical on every CPU, so the result is too. The cost is range, precision and convenience.

cpp · try it yourself
#include <iostream>
#include <iomanip>
#include <cstdint>

using fixed = int64_t;                              // 16.16 stored in 64 bits to keep products safe
const fixed ONE = 1 << 16;
fixed fromDouble(double d) { return static_cast<fixed>(d * ONE); }
double toDouble(fixed f) { return static_cast<double>(f) / ONE; }
fixed mul(fixed a, fixed b) { return (a * b) >> 16; }

int main() {
    std::cout << std::fixed << std::setprecision(5);
    const fixed dt = ONE / 60, g = fromDouble(-9.81);
    fixed y = fromDouble(10), v = fromDouble(4);
    for (int i = 0; i < 60; i++) {                  // one second of semi-implicit Euler
        v += mul(g, dt);
        y += mul(v, dt);
    }
    std::cout << "fixed-point: y = " << toDouble(y) << " (raw " << y << ")\n";

    double yd = 10, vd = 4;
    for (int i = 0; i < 60; i++) { vd += -9.81 / 60; yd += vd / 60; }
    std::cout << "double:      y = " << yd << "\n";
}
fixed-point: y = 9.01398 (raw 590740)
double:      y = 9.01325

The raw integer is the whole state: send it, hash it, compare it, and every platform agrees. The fixed-point value is a little off from the double result because dt = 1/60 and each product are truncated, but it is off in the same way everywhere.

What engines promise

  • Box2D v3 is designed to be deterministic across thread counts and 64-bit platforms. It bases the simulation order on the creation order of bodies, shapes and joints, and builds with floating-point contraction disabled.
  • Jolt is deterministic when the same binary runs the same API calls in the same order; a CROSS_PLATFORM_DETERMINISTIC CMake option (a few percent slower) extends that across compilers and platforms. Some things, such as the order of contact callbacks from worker threads, are still not ordered, so sort what your game logic reads.
  • Rapier has an "enhanced determinism" feature for cross-platform bit-exact results.
  • PhysX in Unity and Chaos in Unreal are generally repeatable on the same machine and build, but not designed for cross-platform lockstep. Networked games built on them send states (snapshots) rather than relying on every client computing the same thing. The Multiplayer Game Networking course covers both approaches.

Check each engine's current documentation before you design a lockstep game around it: the guarantees come with conditions (same build, same thread count, no certain features).

Test yourself

Why can summing the same forces in a different order give a different result?

  1. Because of a compiler bug
  2. Floating-point addition rounds after each operation, so it is not associative
  3. Because forces are vectors
  4. It can't; addition is commutative

A physics engine stores contact pairs in a hash set keyed by body pointers. Why does that hurt determinism?

  1. Hash sets are slow
  2. Memory addresses change between runs, so the iteration order and hence the solver order change
  3. Pointers can't be hashed
  4. It only matters with multithreading

Which kind of multiplayer game depends most on a deterministic simulation?

  1. A turn-based game sending full board states
  2. A lockstep game that sends only player inputs
  3. A game that sends snapshots of every object
  4. A single-player game