Architecture snapshot: November 2026. This article documents Play2Train's runtime determinism contract, job scheduler policies, floating-point hardware guards, and P2TR v6 binary replay pipeline (src/engine/runtime/Determinism.h/.cpp, src/engine/runtime/Scheduler.h/.cpp, src/engine/physics/config/FPMode.h/.cpp, FPGuard.h, and src/engine/physics/telemetry/Replay.h/.cpp — roughly 3,300 lines of core C++23, plus the pool, solver, and recorder files listed under Sources) inside Gattic's closed-source Play2Train SDK. Robot Universe exercises it through deterministic-replay test gates; PloppyPals is built on the same engine but does not use the replay pipeline.

If you drop the exact same stack of crates from the exact same height twice in a modern video game, you might expect them to bounce into the exact same pile. In most real-time engines, they do not. By the third bounce, one crate leans two millimeters farther left; by second five, the whole tower collapses differently. That invisibility makes rare physics bugs nearly impossible to reproduce, turns automated regression testing into noisy guesswork, and breaks deterministic replays.

Why do two identical runs drift apart? Almost never because of a single obvious mistake, and almost always because of three quiet sources of nondeterminism hiding underneath ordinary code:

  1. Scheduling races. Modern thread pools hand work to whichever CPU core finishes first. If Task B finishes ahead of Task A on Tuesday and behind it on Wednesday, shared queues, contact lists, and parallel sums execute in a different order.
  2. Floating-point rounding drift. Computers approximate decimal numbers in finite binary bits. Addition is not strictly associative ((a + b) + c can differ by one least-significant bit from a + (b + c)), and third-party libraries (audio mixers, graphics drivers) can leave a CPU thread's rounding mode or subnormal-number handling in an unexpected state.
  3. Unverified black-box steps. Even when an engine tries to be repeatable, a single end-of-run "mismatch" tells engineers nothing about where inside a 16-millisecond physics frame the first bit flipped.

Play2Train refuses to treat determinism as a handful of ad-hoc boolean flags sprinkled across subsystems. Instead, it models determinism as an explicit execution contract: a single DeterminismMode structure propagates automatically from the calling thread onto worker threads, upgrades the job scheduler into a sequence-ordered queue drained only at explicit pump points, replaces dynamic work stealing with fixed-grid stable-partition parallelism, locks the x86/SSE floating-point control register on both stepping and worker threads, and records a strict versioned binary replay (P2TR v6) carrying per-phase hashes at every stage of the physics step.

The execution contract: DeterminismMode and automatic propagation

In plain terms, think of DeterminismMode as a stamped factory work order attached to every simulation step. Rather than hoping each department remembers to follow the same rules, the ticket travels with the job wherever it goes — specifying whether determinism is active, whether strict enforcement is on, how many parallel lanes to split work across, how finely to slice ranges, and which random-number seed to start from.

In code (src/engine/runtime/Determinism.h), the entire contract fits into five fields:

cpp
struct DeterminismMode {
    bool     enabled     = false;
    bool     strict      = false;
    int      threads     = 1;
    int      chunkFactor = 1;
    uint64_t seed        = 0x9e3779b97f4a7c15ULL;
};

That default seed constant (0x9e3779b97f4a7c15ULL) is the 64-bit golden-ratio increment (2⁶⁴ / φ), which Play2Train also reuses in its hash mixers (Determinism::HashCombine and the per-phase replay hashes) and in its SplitMix64-based DeterministicRNG (src/engine/runtime/DeterministicRNG.h, including DeriveSeed(baseSeed, tag) for independent per-subsystem substreams).

Layered architecture diagram of Play2Train's determinism execution contract. At the top, DeterminismMode in runtime/Determinism.h defines five fields (enabled, strict, threads, chunkFactor, seed) stored as a global RCU atomic shared_ptr snapshot with thread-local ScopedMode overrides stamped onto worker tasks at submission time. In the middle layer, the contract drives two parallel subsystems: on the left, the Runtime Scheduler (Scheduler.h, FixedThreadPool, BlockingThreadPool) enforces DeterministicQueued single-job scheduling with explicit PumpDeterministic checkpoints and DeterministicParallel fixed-grid range splitting; on the right, Physics Hardware and Solver Guards (FPMode.cpp, FPGuard.h, ConstraintSolverDispatch.cpp) lock the SSE MXCSR control register (FTZ, DAZ, round-to-nearest-even) and apply canonical sorting and descending-cost island batching. At the bottom, the P2TR v6 binary replay pipeline (physics/telemetry/Replay.h/.cpp) validates a strict 32-byte version-6 header, writes sorted 72-byte EntityState snapshots, records a PhaseTag hash ladder per frame (seven live tags in nine stable slots), and defines typed POD solver records (JRTN, CCAG, PMAN) whose field-by-field serializers the recorder does not yet write.
One DeterminismMode contract propagates from thread-local scopes into worker pools, scheduler policies, SSE floating-point hardware flags, and the P2TR v6 replay stream.

Three implementation details in Determinism.cpp, FixedThreadPool.cpp, and BlockingThreadPool.cpp make this contract hard to drop by accident:

  • Mutex-free global reads via an RCU-style snapshot. Determinism::Global() loads a std::atomic<std::shared_ptr<const DeterminismMode>>. Rare writes in SetGlobal take g_globalMtx, clamp threads ≥ 1 and chunkFactor ≥ 1, and atomically swap in a new immutable snapshot, so readers never take that mutex and never see a half-written mode.
  • Scoped thread-local overrides (Determinism::ScopedMode). A subsystem entering a deterministic phase — such as PhysicsSystem::Update — constructs an RAII ScopedMode guard that installs a thread_local override (g_hasOverride, g_overrideMode) and restores the previous override (or clears back to Global()) on every exit path, including exceptions.
  • Automatic cross-thread inheritance. Whenever any task is submitted to FixedThreadPool or BlockingThreadPool, the submission path snapshots t.determinism = Engine::Determinism::Current() directly into the task record (RangeTask or blocking task). When a worker thread picks that task up — even after recursive range splitting — ExecuteAndComplete wraps execution in Engine::Determinism::ScopedMode detScope(task.determinism). Nested work submitted from inside a worker automatically inherits the exact contract of the thread that spawned it.

Determinism.h also provides the hash primitive. Determinism::HashCombine applies a fixed 64-bit golden-ratio mix followed by a MurmurHash3-style finalizer (>> 33, * 0xff51afd7ed558ccdULL, >> 33, * 0xc4ceb9fe1a85ec53ULL, >> 33); it is integer-only, so it produces the same value on every compiler and platform. A thread-local RecordPhase / DrainPhases sink for (tag, hash) pairs is available too, but the shipping replay ladder described below accumulates its phase hashes in the physics step's own per-frame vector, using a lighter mixer (MixGuardrailHash) that omits the finalizer.

DeterministicQueued scheduling and explicit pump points

To understand how Play2Train's scheduler (src/engine/runtime/Scheduler.h/.cpp) tames concurrency, compare two restaurant kitchens. In a normal work-stealing thread pool (Policy::Default), cooks grab whichever order slip is nearest whenever a burner frees up — great for throughput, terrible for repeatability because the order in which dishes finish depends on microsecond OS timing.

In Policy::DeterministicQueued, every submitted job gets a numbered sequence ticket (g_detSeq.fetch_add(1)), is filed by priority (High = 0, Normal = 1, Low = 2) and thread affinity (Any, MainThread, RenderThread), and waits quietly on the rail until the engine reaches an explicit pump point (Scheduler::PumpDeterministic()). Nothing executes at an arbitrary background moment.

Four scheduler policies and strict-mode auto-upgrade

Every job or range submitted through Scheduler resolves to one of four Scheduler::Policy modes:

Policy Target workload Execution behavior When used
Default General engine work Persistent work-stealing FixedThreadPool (or BlockingThreadPool for mayBlock / JobClass::IO) Normal non-deterministic gameplay and background tasks
DeterministicQueued Single jobs under strict determinism Stamped with monotonic g_detSeq, queued by (Affinity, JobClass, Priority), executed only at PumpDeterministic() Auto-enforced for all single jobs when det.enabled && det.strict
DeterministicInline Single jobs or ranges Executes immediately on the calling thread in submission order (respecting MainThread / RenderThread affinity) Explicit caller choice: ranges in any mode, single jobs only when strict is off (strict mode rewrites every single job to DeterministicQueued)
DeterministicParallel Range loops (ParallelFor, ParallelReduce) Fixed threads × chunkFactor chunk grid with stable striding; falls back to inline when threads ≤ 1 Auto-upgraded from Default for range work when det.enabled && det.strict

That automatic upgrade happens in one central gatekeeper (NormalizePolicyForDeterminism in Scheduler.cpp): when det.enabled && det.strict is active, every single-job submission is forced to DeterministicQueued (even an explicit DeterministicInline), and a range submission whose policy is Default is upgraded to DeterministicParallel. Physics range call sites such as StepPrecompute and BroadphaseSAP pass DeterministicParallel explicitly under replay instead of relying on the upgrade. Even Scheduler::Graph and Scheduler::FrameGraph (Scheduler_Graph.cpp) honor the contract: in strict deterministic mode, worker-class DAG tasks route into the graph's deterministic Wait() inline min-heap ordered by task handle rather than racing on the worker pool, and structured-concurrency Scope::Spawn (StructuredConcurrency.h) tracks strict jobs in a dedicated DeterministicGroup (m_detGroup) so Scope::Wait() never misses queued completions.

Explicit pump points and cost-unit budgets (never wall-clock time)

If you drained a queue for "up to 2 milliseconds of wall-clock time," determinism would shatter immediately: a background antivirus scan or thermal throttle would cause frame 100 to stop after 14 jobs on one run and 19 jobs on the next.

Play2Train eliminates clock jitter by converting frame budgets into deterministic abstract cost units:

text
units = max(1, budgetNs / quantumNs)      // default quantumNs = 50,000 ns (0.05 ms / unit)

Each job carries an integer weight (Options::deterministicCostUnits, default 1, or configured per structured-concurrency scope via Scope::SetDeterministicHints(laneSafe, costUnits)). When PumpDeterministic() runs, it drains a deterministic prefix strictly by priority (High → Normal → Low) and increasing submission sequence until used >= budgetUnits — never checking steady_clock during deterministic draining. If the very first job's cost exceeds the budget, it still runs so the queue can never starve.

Flow diagram and bar chart of Play2Train's DeterministicQueued scheduler and explicit pump points. At top left, Enqueue stamps each strict-mode single job with a monotonic sequence number g_detSeq, a costUnits weight of at least 1, and a laneSafe flag. In the center, Sequence-Ordered Queues partition entries across three affinity arrays (g_detAny, g_detMain, g_detRender), each with 6 JobClasses and 3 FIFO priority queues from High to Low. At top right, PumpDeterministic drains a deterministic prefix by cost units: main-affine and render-affine queues drain serially, while g_detAny fans out laneSafe jobs across lanes 1 to N-1 using lane = seq mod N and forces all non-laneSafe jobs plus lane 0 inline on the caller thread. A middle strip highlights the four explicit engine pump points: post-UpdateSystems, pre-render frame, Wait and WaitIdle assist, and Shutdown with kDrainAll. At the bottom, a horizontal bar chart compares the strict-mode default class budgets at a 50,000-nanosecond quantum: Physics 40 units (2.00 ms), Asset 30 units (1.50 ms), Engine 10 units (0.50 ms), Gameplay 10 units (0.50 ms), Render 10 units (0.50 ms), and IO 5 units (0.25 ms).
DeterministicQueued replaces wall-clock time budgets with deterministic cost units and drains work only at explicit, affinity-aware pump points.

When strict determinism is enabled and no explicit budgets have been set yet, PumpDeterministic() installs conservative per-class defaults once (all overridable via SetClassBudgetNs or ENGINE_DET_BUDGET_*_NS / ENGINE_DET_BUDGET_QUANTUM_NS environment variables):

JobClass Default budget (ns) Equivalent cost units (quantum = 50,000 ns) Environment override
Physics 2,000,000 ns (2.00 ms) 40 units ENGINE_DET_BUDGET_PHYSICS_NS
Asset 1,500,000 ns (1.50 ms) 30 units ENGINE_DET_BUDGET_ASSET_NS
Engine 500,000 ns (0.50 ms) 10 units ENGINE_DET_BUDGET_ENGINE_NS
Gameplay 500,000 ns (0.50 ms) 10 units ENGINE_DET_BUDGET_GAMEPLAY_NS
Render 500,000 ns (0.50 ms) 10 units ENGINE_DET_BUDGET_RENDER_NS
IO 250,000 ns (0.25 ms) 5 units ENGINE_DET_BUDGET_IO_NS

And when does PumpDeterministic() execute? At explicit, predictable points in the engine lifecycle:

  1. End of main-thread frame update (GameEngine.cpp). Immediately after UpdateSystems(deltaTime) and PumpMainThread(), draining g_detAny and g_detMain.
  2. Render-thread frame prep (GameEngine.cpp). Right after DrainDeferredResources() and PumpRenderThread(), before BeginFrame, BeginFrameMulti, and RenderAuthoringPreview, draining g_detRender serially on the render thread.
  3. Wait & join assist (Scheduler.cpp, FixedThreadPool.cpp, Scheduler_Groups.cpp). Inside DeterministicGroup::Wait(), FixedThreadPool::TaskGroup::Wait(), WaitIdle(), and WaitIdleBlocking() so waiting on queued work under strict determinism can never deadlock.
  4. Clean shutdown (GameEngine.cpp). Loops PumpMainThread(kDrainAll), PumpRenderThread(kDrainAll), and PumpDeterministic(kDrainAll) until the engine's root structured-concurrency scope has zero pending work.

Safe deterministic lane parallelism inside PumpDeterministic

Even single queued jobs can exploit multiple cores safely when det.strict && det.threads > 1 on g_detAny. DeterministicQueue::DrainLanesBudgeted pops the exact same cost-budgeted prefix (priority → increasing seq) and assigns each entry to a lane:

  • Jobs with Options::deterministicParallelSafe == false (the safe default) are forced onto Lane 0 and run serially inline on the calling thread.
  • Jobs explicitly opted in (deterministicParallelSafe == true, such as independent narrowphase tasks configured via scope.SetDeterministicHints(true, 8)) hash stably by sequence number: lane = seq % lanes.
  • Lanes 1 .. lanes - 1 fan out as fixed batches onto FixedThreadPool, Lane 0 runs inline on the caller (ensuring forward progress even if the pool is saturated), and g.Wait() joins all lanes before PumpDeterministic() returns. Within every lane, jobs run in the order they were popped: priority first, then increasing seq.

Stable-partition parallelism: multi-core speed without floating-point drift

Most engineers assume you have to choose between fast (multi-threaded) and repeatable (single-threaded). Play2Train rejects that false choice with stable-partition parallelism (Policy::DeterministicParallel in Scheduler_Groups.cpp and Scheduler::ParallelReduce in Scheduler.h).

Imagine counting cash from 1,000 register drawers with 4 accountants. If you tell them "grab the next drawer whenever you're free and toss your running subtotal into a shared pile," the order in which pennies get rounded changes every day. Instead, Play2Train assigns fixed numbered bundles up front:

cpp
const int numChunks = std::max(1, threads * std::max(1, chunkFactor));
const int chunkSize = std::max(minGrain, (total + numChunks - 1) / numChunks);

for (int taskId = 0; taskId < threads; ++taskId) {
    // Stable striding: Task taskId always owns chunk = taskId, taskId + threads, ...
    for (int chunk = taskId; chunk < numChunks; chunk += threads) {
        const int b = begin + chunk * chunkSize;
        if (b >= end) break;
        const int e = std::min(end, b + chunkSize);
        partials[chunk] = rangeFn(b, e);
    }
}

Why does chunkFactor exist alongside threads? Because real physics workloads are uneven — some spatial cells are packed with ragdolls while others are empty sky. Setting chunkFactor > 1 (say, threads = 4, chunkFactor = 2 → 8 fixed chunks) interleaves work across tasks in a strided pattern (Task 0 gets chunks 0, 4; Task 1 gets 1, 5; Task 2 gets 2, 6; Task 3 gets 3, 7) for better load balance without ever making chunk boundaries depend on runtime timing.

Diagram illustrating Play2Train's stable-partition parallelism for threads = 4 and chunkFactor = 2. At top, a range from begin to end is divided into 8 fixed contiguous chunks C0 through C7 using chunkSize = max(minGrain, ceil(total / numChunks)). Four worker tasks take strided chunk assignments: Task 0 owns C0 and C4, Task 1 owns C1 and C5, Task 2 owns C2 and C6, and Task 3 owns C3 and C7, each writing into its own slot of the partials array regardless of which physical OS worker executes it. Arrows point down into a dark green ParallelReduce barrier bar showing the fixed-order combine fold from partials[0] through partials[7] after sched.Wait(group). Two bottom panels contrast why ordinary work stealing drifts — dynamic splitting changes chunk boundaries and floating-point addition is non-associative, (a + b) + c not equal to a + (b + c) — with physics island packing in ConstraintSolverDispatch, which ranks independent islands by descending pair-plus-joint cost (ties broken by ascending island index) and packs them greedily into deterministicThreads batches.
Fixed chunk boundaries plus index-ordered reduction decouple mathematical results from wall-clock thread completion order.

When combining results across chunks in Scheduler::ParallelReduce, every task writes exclusively to its own partials[chunk] slot, waits on sched.Wait(g), and then folds sequentially in exact chunk-index order 0 → 1 → … → numChunks - 1:

cpp
Acc out = init;
for (int chunk = 0; chunk < numChunks; ++chunk) {
    out = combineFn(out, partials[chunk]);
}
return out;

Even if Task 3 finishes before Task 0 on one run and after Task 0 on the next, the sequence of floating-point operations inside combineFn is 100% invariant.

Which paths run concurrently

The fixed partition is what makes results repeatable; whether chunks actually execute at the same time depends on the path and on strict:

  • ParallelFor with DeterministicParallel (StepPrecompute) enqueues exactly threads tasks straight onto the worker pool, so chunks run concurrently.
  • Single jobs that opt in as lane-safe (SetDeterministicHints(true, …), used by narrowphase and the broadphase bucket tasks) fan out across lanes at the pump, also concurrently.
  • ParallelReduce and island batches under strict are submitted as ordinary single jobs. The gatekeeper turns them into non-lane-safe DeterministicQueued entries, which run one after another at the pump over the same fixed partition: slower than the pool, with identical results. With strict off they run on the worker pool.

Deterministic physics island packing (ConstraintSolverDispatch.cpp)

The physics constraint solver applies the same principle at the island level. Because connected bodies, contacts, and joints are partitioned into disjoint solver islands (no two islands share a body), Play2Train's DispatchIslands solves multi-island scenes with a batching plan that does not depend on the machine:

  1. Single-island fast path. Scenes with ≤ 1 active island run inline with zero scheduling overhead.
  2. Canonical cost ranking. RankIslandsByCost scores every island by pairs.size() + joints.size() and sorts descending by cost, breaking ties strictly by ascending islandIdx.
  3. Greedy deterministic bin packing. When deterministicReplay is enabled and deterministicThreads > 1, PackIslandsIntoBatches allocates exactly deterministicThreads batches (never sched.ThreadCount(), so a 16-core workstation and an 8-core CI runner produce identical batches for the same DeterminismMode) and assigns each ranked island to the lowest-cost batch so far. Each batch executes as one named job (ConstraintSolver::SolveIslands(det)). With strict off the batches run concurrently on the worker pool, and because islands share no bodies, finish order cannot change a result. With strict on, the jobs are submitted with Policy::Default, which the gatekeeper rewrites to non-lane-safe DeterministicQueued jobs, so they run serially at the pump in submission order.

Locking the CPU's math rules: FPMode and FPGuard

For non-technical readers, here is one of computing's weirdest traps: a CPU does not have just one way to do decimal arithmetic. Every CPU thread carries a tiny hidden hardware settings register — on x86-64 processors, the 32-bit MXCSR register — that controls two critical behaviors:

  • Rounding mode (RC, bits 14:13): Should 0.5 round to nearest-even, down toward −∞, up toward +∞, or toward zero? If a third-party audio or graphics driver flips rounding mode on a thread and forgets to restore it, every subsequent physics calculation on that thread subtly tilts.
  • Subnormal (denormal) numbers (FTZ bit 15, DAZ bit 6): Numbers unimaginably close to zero (smaller than 1.18 × 10⁻³⁸ in 32-bit float) can trigger slow hardware microcode assists or behave differently depending on whether a CPU flushes them to zero.

Play2Train locks these hardware bits directly in src/engine/physics/config/FPMode.cpp and wraps them in a move-only RAII guard (FPGuard::ScopedDeterminism in src/engine/physics/config/FPGuard.h); the excerpt below is abridged:

cpp
constexpr unsigned int kFlushToZeroMask       = 1u << 15; // FTZ
constexpr unsigned int kRoundingModeMask      = 3u << 13; // RC bits 14:13 (00 = RN-even)
constexpr unsigned int kDenormalsZeroMask     = 1u << 6;  // DAZ (SSE3+)
constexpr unsigned int kDeterministicModeMask = kFlushToZeroMask | kDenormalsZeroMask;

void SetDeterministicFP(bool strict) {
#if defined(__SSE__) || defined(_M_IX86) || defined(_M_X64)
    unsigned int mxcsr = _mm_getcsr();
    if (strict) {
        mxcsr |= kDeterministicModeMask;  // Enable FTZ + DAZ
        mxcsr &= ~kRoundingModeMask;      // Force Round-to-Nearest-Even (00)
    } else {
        mxcsr &= ~kDeterministicModeMask; // Restore standard IEEE denormal handling
    }
    _mm_setcsr(mxcsr);
#else
    static_cast<void>(strict);
#endif
}
Hardware bitfield diagram of the lower 16 bits of the x86 SSE MXCSR control register controlled by FPMode::SetDeterministicFP(true). Bit 15 (FTZ, Flush-To-Zero) is highlighted dark green and set to 1; bits 14 and 13 (RC, Rounding Control) are highlighted bright lime and cleared to 00 for IEEE-754 round-to-nearest-even; bits 12 through 7 (exception masks PM through IM) and bits 5 through 0 (sticky exception flags PE through IE) remain preserved; bit 6 (DAZ, Denormals-Are-Zero on SSE3+) is highlighted dark green and set to 1. Three explanatory cards summarize each flag below the register. At the bottom, a dark panel illustrates why per-thread re-arming is mandatory because MXCSR is per-thread hardware state: PhysicsSystem::Update installs FPGuard::ScopedDeterminism on the stepping thread, while worker-thread entry points inside StepPrecompute, StepNarrowphase, and ConstraintSolverDispatch explicitly call FPMode::SetDeterministicFP(true) before executing bounds, GJK/EPA, or SI/NGS solver math.
Because MXCSR is per-thread CPU state, Play2Train guards both the stepping thread via RAII and the parallel precompute, narrowphase, and island-solver workers.

Notice the subtle concurrency trap highlighted in the diagram above: MXCSR is per-thread hardware state. Setting FPGuard::ScopedDeterminism inside PhysicsSystem::Update protects the calling thread, not the background worker threads inside FixedThreadPool! That is why Play2Train explicitly re-arms FPMode::SetDeterministicFP(true) at the start of each of these parallel physics workers:

  • StepPrecompute.cpp (before parallel collider bounds/geometry precomputation; when replay and strict mode are both on)
  • StepNarrowphase.cpp (before parallel GJK/EPA/manifold contact generation; when replay is on)
  • ConstraintSolverDispatch.cpp (before parallel island SI/NGS constraint solving; when strict mode is on)

On non-x86 architectures where SSE intrinsics are absent, SetDeterministicFP compiles cleanly as an explicit no-op rather than breaking portability, while the header notes clearly that bit-identical P2TR v6 binary replays assume x86-64 little-endian hardware.

P2TR v6: a versioned binary replay format with per-phase hashes

Suppose everything above is wired up — and one day, after a code change, an automated replay test fails on Frame 418. Without granular telemetry, you only know that at the end of Frame 418, Crate #17 ended up at y = 1.0021 instead of y = 1.0019. Was it broadphase? Continuous collision detection? Narrowphase contact matching? The constraint solver? Warm-starting?

Play2Train solves this with P2TR v6 (src/engine/physics/telemetry/Replay.h/.cpp and src/engine/runtime/PhysicsReplayRecorder.cpp): a compact, strictly versioned binary flight recorder that captures not only the initial world and each frame's final state hash, but a ladder of per-phase guardrail hashes inside every single physics step.

Exact wire layout and strict validation

Every P2TR v6 file is raw little-endian IEEE-754 floats and fixed-width integers, opened by Replay::Reader with strict exact-version validation (header.magic == 0x50325452u 'P2TR', header.version == 6u; every other version is rejected with an explicit diagnostic string in LastError()).

  1. Header (32 bytes, verified by static_assert(kSerializedHeaderBytes == sizeof(Header))). Stores magic ('P2TR', 4 B), version (6, 4 B), seed (8 B), strict (1 B), reserved[7] (7 B), deterministicThreads (int32_t, 4 B), and deterministicChunkFactor (int32_t, 4 B). The current recorder fills seed with the scene's determinism hash at the start of recording and strict with the scene's deterministicReplay flag.
  2. Sorted initial entity snapshot (4 B + N × 72 B). CaptureInitialSnapshot collects every active entity with a Transform or PhysicsBody, sorts them by ascending EntityID so container iteration order never leaks into the file, writes uint32_t entityCount, and writes N 72-byte EntityState records (id, hasTransform, hasBody, sleeping, motionType, position, rotation quaternion (w,x,y,z), scale, linearVelocity, angularVelocity — also pinned by static_assert).
  3. Per-frame records (16 B + 9 B × phaseCount each). Each Recorder::RecordFrame writes float dt (4 B), the end-of-frame uint64_t hash (8 B), uint32_t phaseCount (4 B), and phaseCount pairs of (uint8_t phaseTag, uint64_t phaseHash).

Before allocating memory for any snapshot or frame, Replay::Reader checks both hard caps (kMaxEntityCount = 1u << 20 = 1,048,576 entities; kMaxPhaseCount = 64) and overflow-safe remaining-file-byte checks (count <= remaining / bytesPerRecord), so a truncated or corrupted replay file fails cleanly without wild allocations or undefined reads.

Wire-format byte map of Play2Train's P2TR v6 binary replay stream and its per-phase hash bisection workflow. The top panel maps the exact little-endian layout: a 32-byte Header (4-byte P2TR magic, 4-byte version 6, 8-byte seed, 1-byte strict flag, 7 reserved bytes, 4-byte threads, 4-byte chunkFactor); an initial snapshot with a 4-byte entityCount capped at 2^20 followed by N 72-byte EntityState records sorted by EntityID; repeating FrameRecords containing 4-byte dt, 8-byte frameHash, 4-byte phaseCount capped at 64, and K 9-byte (PhaseTag, uint64 hash) pairs; and, set apart from the stream, three standalone typed solver records with field-by-field serializers that the recorder does not yet write: JRTN (78 bytes), CCAG (20 bytes), and PMAN (349 bytes). The bottom dark panel illustrates Run A versus Run B phase-hash bisection on Frame N: tags 0 (PreFrameStart), 1 (BuildMovers), 2 (CCDPrepass), 4 (BuildColliders), and 5 (Broadphase) all match, while tag 6 (NarrowphasePairs) is highlighted bright lime as the first divergence, isolating the bug before downstream PersistentManifold (8) and end-of-frame hashes drift.
Exact byte-level structure of P2TR v6 and how per-phase hashes turn a mysterious simulation drift into an immediate single-stage diagnosis.

The PhaseTag guardrail ladder: seven live hashes in nine stable slots

Inside src/engine/physics/world/Update.cpp and StepSolveFinalize.cpp, Play2Train hashes canonical sorted views of the physics pipeline at each major milestone, mixing raw IEEE-754 float bit patterns (PhysicsUtils::FloatBits) with the golden-ratio mixer (0x9e3779b97f4a7c15ULL):

Tag ID PhaseTag enum What is hashed (canonical order) Role in bisection
0 PreFrameStart Sorted active EntityID list Confirms identical entity set entering the step
1 BuildMovers Sorted movers by EntityID: startPos + vel float bits Catches velocity-integration or input divergence
2 CCDPrepass Canonicalized (min, max) sorted CCD candidate pairs Catches continuous-collision prepass drift
3 SeedFrameCaches Reserved stable enum slot Stream-format stability
4 BuildColliders Sorted colliders by EntityID: colliderId, OBB center float bits, shape enum Catches bounds, transform, or hull mismatch
5 Broadphase Canonicalized (min, max) sorted broadphase pairs pairsN Catches spatial broadphase or AABB drift
6 NarrowphasePairs Per-pair cacheKey and every contact point's c.id, in narrowphase output order Catches GJK/EPA/narrowphase contact differences
7 SolveFinalize Reserved optional slot, never emitted (the end-of-frame hash is stored in FrameRecord::hash) That end-of-frame digest hashes sorted positions, linear/angular velocities, sleep flags (0xABCDEF vs 0x123456), and contact pairs
8 PersistentManifold Sorted persistentManifoldCache keys + HashManifoldState (points sorted by contactId, floats quantized at 1e-6) Catches post-solve persistent manifold warm-start drift (recorded only when persistent manifolds and deterministic replay are both active)

When Run A and Run B disagree on Frame N, comparing their phaseChecks arrays takes microseconds: if tags 0, 1, 2, 4, 5 match and tag 6 (NarrowphasePairs) diverges, you immediately know broadphase and colliders were bit-identical and the bug lives inside narrowphase — cutting hours of blind debugging down to one file.

Field-by-field typed solver payloads (never memcpying padded structs)

In addition to the core stream, Replay.h defines a composable ByteWriter / ByteReader pair and three 32-bit tagged POD payload records (RecordTag) for capturing and testing deep solver state. They are standalone serializers: the current Recorder does not write them into a replay file (the format leaves room for them), and the engine's unit tests round-trip them directly. The caller writes the record tag, while the Write/Read helpers handle only the payload, so the widths below exclude the 4-byte tag:

RecordTag (ASCII / hex) Struct Exact serialized width Contents & design note
'JRTN' (0x4A52544E) JointRuntimeStateRecord 78 bytes jointId, body indices, frozen ReplayJointKind (0..4), enabled/broken/sleeping bools, sleepStreak, lastResidual, lambdaPosition[3], warmStartImpulse[3], assignedIsland, and flat-union per-kind lambdas
'CCAG' (0x43434147) ContactCacheEntryRecord 20 bytes id (uint64_t), normal impulse nImp, and tangent impulses tImp1, tImp2
'PMAN' (0x504D414E) PersistentManifoldRecord 349 bytes pairKey (8 B), count (1 B), lastFrame (4 B), plus all 4 fixed Point slots (4 × 84 B: contactId, lastSeen, lpA[3], lpB[3], n[3], t1[3], t2[3], depth, lambdaN, lambdaT1, lambdaT2)

Why does Play2Train copy runtime structs like JointSolverState or PersistentManifold into stand-alone POD records and serialize them field by field instead of calling memcpy? Because C++ structs with mixed-size fields (bool, uint16_t, float, uint64_t) contain compiler-inserted padding bytes whose contents are uninitialized garbage — memcpying them leaks non-deterministic stack/heap bytes straight into golden replay files and breaks binary compatibility across compilers. Writing every field explicitly through ByteWriter (and unconditionally writing all 4 slots of PersistentManifoldRecord for a constant 349-byte stride) guarantees clean, zero-padding, deterministic bytes every time. The 32-byte header and 72-byte EntityState take a simpler route, since the recorder writes those structs directly. That is safe only because the static_asserts above prove they contain no padding.

Explicit design boundaries and honest trade-offs

Play2Train's headers are intentionally candid about what this contract guarantees — and where its boundaries lie:

  • Same-architecture bit reproducibility (x86-64 little-endian). P2TR v6 stores raw IEEE-754 little-endian floats, and FPMode targets SSE/SSE3 MXCSR. Cross-ISA determinism (for example, x86-64 vs ARM64 with differing FMA contraction or transcendental libraries) is not claimed by this contract alone.
  • No legacy replay format baggage. Replay::Reader rejects every version other than kVersion = 6. Rather than carrying fragile v1–v5 compatibility decoders that obscure stream invariants, older recordings are regenerated when the wire contract advances.
  • Fixed-step clamping prevents spiral-of-death nondeterminism. In PhysicsSystem.cpp, when deterministicReplay and PhysicsSceneParams::deterministicFixedStep are both on, physics advances in deterministicFixedDt increments (default 1/60 s) from a double-precision accumulator clamped to deterministicMaxSubSteps steps (default 8, but PhysicsSystem::Update caps it at 4 per call), so frame-rate spikes never produce unbounded variable-dt drift.
  • Opt-in lane parallelism, safe by default. Single queued jobs default to deterministicParallelSafe = false (forcing serial execution on Lane 0) so a developer cannot accidentally introduce a shared-state race under strict determinism; parallel lanes require an explicit opt-in after verifying disjoint writes. Under strict mode, anything that is not lane-safe runs serially at the pump.
  • Structured concurrency stays enforced. Play2Train keeps g_requireScope = true by default (ENGINE_REQUIRE_SCOPE=0 disables it): submitting work without an active Scope aborts loudly rather than letting it escape frame lifetimes and corrupt replay teardown. ScopedAllowDetached is reserved for narrow internal helpers, ParallelReduce among them.

Sources and further reading

  • Play2Train SDK (closed-source) — Gattic's internal C++23 engine containing src/engine/runtime/Determinism.h/.cpp, src/engine/runtime/DeterministicRNG.h, src/engine/runtime/Scheduler.h/.cpp, src/engine/runtime/Scheduler_Groups.cpp, src/engine/runtime/Scheduler_Graph.cpp, src/engine/runtime/StructuredConcurrency.h, src/engine/runtime/FixedThreadPool.cpp, src/engine/runtime/BlockingThreadPool.cpp, src/engine/runtime/GameEngine.cpp, src/engine/runtime/PhysicsSystem.cpp, src/engine/runtime/PhysicsReplayRecorder.cpp, src/engine/physics/config/FPMode.h/.cpp, src/engine/physics/config/FPGuard.h, src/engine/physics/solver/ConstraintSolverDispatch.cpp, src/engine/physics/world/Update.cpp, src/engine/physics/world/StepSolveFinalize.cpp, and src/engine/physics/telemetry/Replay.h/.cpp.
  • Active Ragdolls with Staged Recovery in Play2Train — companion architecture deep dive covering Play2Train's 68k-line soft D6 joint solver, implicit spring-damper drives, five-stage recovery state machine, and 1e6 J/kg fail-safe.
  • AI-Drivable Animation Authoring in Play2Train — companion architecture deep dive covering Play2Train's embedded Unix-socket posing server, two-bone IK, timeline HUD, and procedural quadruped generator.
  • Robot Universe (closed-source, in development) — open-world cyberpunk action adventure set in Haven City, consuming Play2Train::Engine; its test gates exercise deterministic physics replays, and it has a headless MCP runtime.
  • PloppyPals (closed-source, in development) — companion creature-care game built on Play2Train::Engine; it does not use the replay pipeline.