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:
- 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.
- Floating-point rounding drift. Computers approximate decimal numbers in finite binary bits. Addition is not strictly associative (
(a + b) + ccan differ by one least-significant bit froma + (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. - 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:
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).
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 astd::atomic<std::shared_ptr<const DeterminismMode>>. Rare writes inSetGlobaltakeg_globalMtx, clampthreads ≥ 1andchunkFactor ≥ 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 asPhysicsSystem::Update— constructs an RAIIScopedModeguard that installs athread_localoverride (g_hasOverride,g_overrideMode) and restores the previous override (or clears back toGlobal()) on every exit path, including exceptions. - Automatic cross-thread inheritance. Whenever any task is submitted to
FixedThreadPoolorBlockingThreadPool, the submission path snapshotst.determinism = Engine::Determinism::Current()directly into the task record (RangeTaskor blocking task). When a worker thread picks that task up — even after recursive range splitting —ExecuteAndCompletewraps execution inEngine::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:
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.
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:
- End of main-thread frame update (
GameEngine.cpp). Immediately afterUpdateSystems(deltaTime)andPumpMainThread(), drainingg_detAnyandg_detMain. - Render-thread frame prep (
GameEngine.cpp). Right afterDrainDeferredResources()andPumpRenderThread(), beforeBeginFrame,BeginFrameMulti, andRenderAuthoringPreview, drainingg_detRenderserially on the render thread. - Wait & join assist (
Scheduler.cpp,FixedThreadPool.cpp,Scheduler_Groups.cpp). InsideDeterministicGroup::Wait(),FixedThreadPool::TaskGroup::Wait(),WaitIdle(), andWaitIdleBlocking()so waiting on queued work under strict determinism can never deadlock. - Clean shutdown (
GameEngine.cpp). LoopsPumpMainThread(kDrainAll),PumpRenderThread(kDrainAll), andPumpDeterministic(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 viascope.SetDeterministicHints(true, 8)) hash stably by sequence number:lane = seq % lanes. - Lanes
1 .. lanes - 1fan out as fixed batches ontoFixedThreadPool, Lane0runs inline on the caller (ensuring forward progress even if the pool is saturated), andg.Wait()joins all lanes beforePumpDeterministic()returns. Within every lane, jobs run in the order they were popped: priority first, then increasingseq.
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:
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.
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:
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:
ParallelForwithDeterministicParallel(StepPrecompute) enqueues exactlythreadstasks 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. ParallelReduceand island batches understrictare submitted as ordinary single jobs. The gatekeeper turns them into non-lane-safeDeterministicQueuedentries, which run one after another at the pump over the same fixed partition: slower than the pool, with identical results. Withstrictoff 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:
- Single-island fast path. Scenes with
≤ 1active island run inline with zero scheduling overhead. - Canonical cost ranking.
RankIslandsByCostscores every island bypairs.size() + joints.size()and sorts descending by cost, breaking ties strictly by ascendingislandIdx. - Greedy deterministic bin packing. When
deterministicReplayis enabled anddeterministicThreads > 1,PackIslandsIntoBatchesallocates exactlydeterministicThreadsbatches (neversched.ThreadCount(), so a 16-core workstation and an 8-core CI runner produce identical batches for the sameDeterminismMode) and assigns each ranked island to the lowest-cost batch so far. Each batch executes as one named job (ConstraintSolver::SolveIslands(det)). Withstrictoff the batches run concurrently on the worker pool, and because islands share no bodies, finish order cannot change a result. Withstricton, the jobs are submitted withPolicy::Default, which the gatekeeper rewrites to non-lane-safeDeterministicQueuedjobs, 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): Should0.5round 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 (
FTZbit 15,DAZbit 6): Numbers unimaginably close to zero (smaller than1.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:
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
}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()).
- Header (32 bytes, verified by
static_assert(kSerializedHeaderBytes == sizeof(Header))). Storesmagic('P2TR', 4 B),version(6, 4 B),seed(8 B),strict(1 B),reserved[7](7 B),deterministicThreads(int32_t, 4 B), anddeterministicChunkFactor(int32_t, 4 B). The current recorder fillsseedwith the scene's determinism hash at the start of recording andstrictwith the scene'sdeterministicReplayflag. - Sorted initial entity snapshot (
4 B + N × 72 B).CaptureInitialSnapshotcollects every active entity with aTransformorPhysicsBody, sorts them by ascendingEntityIDso container iteration order never leaks into the file, writesuint32_t entityCount, and writesN72-byteEntityStaterecords (id,hasTransform,hasBody,sleeping,motionType,position,rotationquaternion(w,x,y,z),scale,linearVelocity,angularVelocity— also pinned bystatic_assert). - Per-frame records (
16 B + 9 B × phaseCounteach). EachRecorder::RecordFramewritesfloat dt(4 B), the end-of-frameuint64_t hash(8 B),uint32_t phaseCount(4 B), andphaseCountpairs 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.
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-64little-endian).P2TR v6stores raw IEEE-754 little-endian floats, andFPModetargets SSE/SSE3MXCSR. 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::Readerrejects every version other thankVersion = 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, whendeterministicReplayandPhysicsSceneParams::deterministicFixedStepare both on, physics advances indeterministicFixedDtincrements (default1/60 s) from a double-precision accumulator clamped todeterministicMaxSubStepssteps (default8, butPhysicsSystem::Updatecaps it at4per 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 = trueby default (ENGINE_REQUIRE_SCOPE=0disables it): submitting work without an activeScopeaborts loudly rather than letting it escape frame lifetimes and corrupt replay teardown.ScopedAllowDetachedis reserved for narrow internal helpers,ParallelReduceamong 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, andsrc/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/kgfail-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.