Journal 12 min read
Building a Deterministic Simulation in Rust and Headless Bevy ECS
How The Technical Area runs a deterministic simulation in Rust and headless Bevy ECS across 2D matches, event-driven calendars, and versioned game saves.
By The Technical Area
At 10 Hz on a 105 by 68 metre pitch, a 90-minute football match in The Technical Area runs for 54,000 ticks before stoppage time. One rounding difference in minute 14 shifts a pass by a fraction of a degree. By full time, that tiny drift can decide who touches a loose ball in the box and flip the scoreline.
For players, deterministic simulation settles a simple trust problem: a match watched live on screen plays out identically to one calculated in the background, and a career saved on Linux continues along the exact same league history on Windows. For us as developers, it lets any bug reproduce from a single integer seed and keeps 100-season balance benchmarks comparable from month to month.
Headless Bevy ECS without a window loop
Running headless Bevy ECS without a renderer or window loop lets 14 football domains plug into 10 declared schedules on single-threaded executors. Typed queries declare read and write access at compile time, and schedule validation rejects unordered access before kick-off. Persistent domain IDs also replace ECS entity handles across the simulation boundary.
Both simulation engines pull in only Bevy’s core ECS and application crates with default features disabled, pinned to Rust 1.99.0 and Bevy 0.20.1. During startup, a temporary application builder wires the schedules, runs initialisation, and moves the initialised ECS world out behind the simulation facade. Rendering, audio, and UI live in separate layers that read snapshots and query views from the outside, as shown on our technical page.
We adopted a Rust ECS to compose game domains cleanly. Tens of thousands of players and fixtures fit easily into plain structs and vectors, so memory throughput was never the bottleneck. Once we began layering transfers, contracts, training, club offices, and human manager decisions onto the same persistent world, plain arrays would have forced us to write and maintain a custom dependency scheduler. In headless Bevy ECS, the match simulator chains 8 sequential phases inside each tick, and the persistent world mounts 14 domain plugins across 10 calendar schedules.
Default Bevy schedules execute non-conflicting systems across worker threads, which turns a shared random generator into a thread-scheduling race. Every schedule in our Bevy Rust simulation therefore runs on a single-threaded executor with ambiguity detection set to fail hard. When two systems read or mutate conflicting components or random state without an explicit ordering edge, building the schedule fails in tests before any match runs.
Bevy’s built-in ECS entity handles are generational indices tied to spawn order, so they never cross the public facade or enter save files. Clubs, people, players, competitions, fixtures, seasons, and transfer deals carry sequential integer domain IDs starting at 1, indexed in ordered lookup maps. Before kick-off, the matchday layer translates world player IDs into fresh per-match slots inside an isolated match world, and systems that draw randomness or update shared state sort their queries by domain ID first.
Match timing in seconds and isolated random streams
Every physical rule in the 2D match engine is expressed in seconds, metres, and metres per second, while an integer counter tracks ticks internally. Integer counting eliminates cumulative floating-point clock drift across 54,000 ticks and lets background matches run at a lower tick frequency without altering half lengths.
A full match steps at 10 Hz (0.1 seconds per tick). Every step advances deterministic physics for ball flight, Magnus spin, ground friction, and player steering from that configured interval. Clock readings convert integer tick counts to match seconds only when stamping outgoing timeline events or live viewer snapshots. Doubling the frequency to 20 Hz changes outcomes for a given seed because players sample the pitch twice as often, yet halves still close at 45 minutes plus stoppage time.
Simulating every fixture in a multi-country football world at 10 Hz takes too long, because one full match uses roughly 0.8 to 0.95 seconds on a single CPU core. Background domestic fixtures therefore drop to 6 Hz and skip off-the-ball updates for players further than 20 metres from the ball on two out of every three ticks, unless they are in goal or actively pressing or marking. That reduces runtime by roughly 1.5x and keeps match statistics inside our real-football calibration bands. Stepping at 6 Hz does keep defenders within tackling reach about 30% longer, which raises foul counts by roughly 20%, so the referee applies a measured 0.85 yellow-card scale factor to match 10 Hz booking rates.
Live viewing drives the same tick schedule. A watched session accumulates elapsed frame seconds and steps whole integer ticks whenever enough time has built up. Deterministic simulation testing confirms that advancing in small irregular frame steps, reading pitch snapshots after every tick, and running headlessly from kick-off to full time produce identical match reports.
Randomness is scoped to match the lifetime of the data. Inside a single 90-minute match, every stochastic mechanic draws from one seeded ChaCha generator, starting with the first-half coin toss, so conflict detection catches unordered draws immediately. Across a 30-year career world, one shared generator would let an extra random roll in transfers shift youth intakes decades later. The world simulation avoids that by deriving 26 separate ChaCha streams keyed by stream slot, season, and entity or fixture ID, so clubs and fixtures never alter one another’s rolls.
Event-driven calendars and safe matchday parallelism
World state changes only when an ordered calendar queue reaches a dated event; nothing runs on idle days. Values that evolve continuously, such as player fitness recovery, are calculated from elapsed dates when read, so jumping 365 days at once runs the same arithmetic as stepping 1 day 365 times.
The queue stores scheduled events sorted by calendar date and then by a fixed event-kind precedence: matchdays, cup draws, season ends, youth intakes, seasonal rollovers, training weeks, finance events, club takeovers, plan reviews, and transfer rounds. When events share a date, that precedence locks in execution order, so a monthly club office plan review always completes before a transfer round begins, and a 1 July rollover ages squads before training or planning reads them. Advancing across a date range pops due events in order and pauses early only when a human manager owes a pending decision.
Avoiding daily world ticks saves thousands of redundant writes across tens of thousands of players and guarantees chunk independence. When a player finishes a match, his condition is stored alongside that date. Whenever selection or a squad screen checks his match condition later, the engine multiplies the elapsed days by his daily recovery rate, which scales from 0.06 per day at natural fitness 1 to 0.12 at 20 and caps at 100%. Splitting a season into one big leap, weekly jumps, or 365 single-day steps produces the exact same world digest, even across mid-season sackings, loans, and open transfer instalments.
Keeping ECS schedules single-threaded still leaves plenty of room for multi-core speed on matchdays. Before fixtures kick off, the main thread collects shared season facts once, then fans out pre-match tactical preparation and the fixtures themselves across scoped worker threads. Each worker reads only shared world data or simulates an isolated match world from a seeded ChaCha stream without touching persistent ECS state. Outputs are sorted back by job index and fixture ID before the main thread applies results serially, so 800 simulated days produce the identical world digest whether run on 1 CPU thread or 8.
Fixing 1-ULP floating-point drift across Windows and Linux
A simulation that repeats identically on one PC can still diverge between Windows and Linux because Rust delegates transcendental maths to each operating system’s libm. A 1-ULP rounding difference in one trigonometric or exponential function compounds across 54,000 match ticks into different passes, goals, and league tables.
Standard IEEE-754 arithmetic and square roots round identically across x86-64 processors. Transcendental functions such as sine, cosine, exponential, natural logarithm, tangent, and arbitrary floating-point powers do not, because Rust calls the host system’s libm by default. On certain inputs, Windows and Linux disagree in the final bit of a 32-bit float. Inside a coupled 54,000-tick match, that 1-ULP nudge bends a cross by a fraction of a degree, shifts who wins a header, and changes the result.
We ran straight into this during cross-platform testing. An exact match-report regression test recorded on Windows failed on Linux at the very commit that added it. Across our multi-match parity suite, Linux reduced-detail ratings for attacking midfielders averaged 6.2624 against a Windows full-match baseline of 6.1708, which put Linux up to three standard errors away from the Windows reference even though Linux full matches sat nearby at 6.2099.
Four controls keep floating point determinism tied strictly to the seed and configuration:
- Toolchain pinning locks the entire workspace to Rust 1.99.0 so compiler upgrades cannot silently alter instruction selection or fused multiply-add contraction between releases.
- Build-time feature flags hide all calibration overrides and attribute-ablation toggles from release builds. Shipped binaries fold every tuning parameter into compile-time constants with zero environment lookups, and developer tools exit immediately with status code 2 if an override variable is passed to a non-tuning binary.
- Unified save registration removes test-only override components from the persistent save registry, so test and release builds share one world layout.
- Portable pure-Rust maths is currently in progress on a dedicated branch to unify Windows and Linux match outcomes. That branch routes all transcendental functions and fixed-order integer powers through a pure-Rust libm crate. Per-crate Clippy lints forbid direct calls to host maths functions across the simulation crates, while hardware-rounded square-root vector helpers stay as they are.
The pure-Rust maths branch must pass a strict 5% speed limit on both Windows and Linux before merging. If replacing system libm slows full matches past 5%, we reject the change and maintain separate exact reference pins for Windows and Linux, while our statistical football profiles continue to hold on both platforms.
Why 100 simulated seasons slowed down nearly sixfold
Adding manager tactical selection pushed our 100-season release benchmark from 56.2 seconds to 332.6 seconds, a 5.92x slowdown against a 10% budget. Profiling proved the new tactics loop innocent: an older results helper was scanning every world entity and cloning 100 years of match records to read only four numbers.
Because manager tactics runs 19 candidate evaluations per side in every fixture, we timed that selection loop first. Per-system timing accumulators cleared the new tactics loop and pointed straight to contract-term checks running repeatedly across each season. An older helper walked every entity in the ECS world and cloned full match-result components across up to a century of history to extract only four fields: home club, away club, home goals, and away goals. When the tactics feature added team sheets, formations, and substitutions to stored match results, each clone grew roughly four times larger, and that turned an unindexed scan of historical records into the main cost of a season.
To bring multi-decade testing back below budget without changing simulation outcomes, we locked down four rules for every per-round or per-player hot path:
- Replace whole-world entity scans with typed queries filtered by active season and club before copying any data, reading only scalar fields and skipping vector-heavy history lists.
- Collect shared matchday facts such as played counts, losing streaks, upcoming fixture dates, and available squads once per round in a single index walk, then pass that context by reference.
- Precompute role-ability tables once per distinct role, pick top candidates directly without sorting entire squads, and remove temporary allocations from inner loops.
- Fan read-only pre-match tactical planning out across worker threads by whole round (thread spawning costs around 30 microseconds each on Windows, so small 20-item loops stay serial), then apply outcomes in fixed order.
| Benchmark stage (100 seasons, release) | Wall time | Relative to baseline | Primary driver |
|---|---|---|---|
| Baseline before manager tactics | 56.2 s | 1.00x | Pre-tactics world simulation |
| Initial tactics integration | 332.6 s | 5.92x | Full-world entity scan cloning expanded match histories |
| After hot-path fixes | 31.1 s | 0.58x | Typed scalar queries, single-pass round context, parallel planning |
After those fixes, 100 seasons completed in 31.1 seconds (0.58x of the original baseline, or 0.84x against a baseline patched with the same results fix). Every world snapshot and determinism check stayed bit-identical, because any optimisation that changes a match outcome is a gameplay rule change and must be reviewed as design.
Deterministic binary saves with postcard and zstd
Our game save system snapshots the world between calendar events using postcard Rust serialization inside a checksummed zstd frame, sorted strictly by domain ID. Ignoring raw ECS memory layout and storing collections in ordered maps guarantees that saving, loading, and continuing produces the exact same world and byte-identical save files.
Iterating an ECS world in archetype order depends on when components were inserted or moved during play. When our saver builds a snapshot, it traverses clubs, people, and fixtures in ascending domain-ID order and keeps every persistent map and set in ordered tree structures. Each entity writes one sparse record with optional component slots so unpopulated fields stay compact.
Every save opens with a small unencoded header carrying magic bytes, a 32-bit little-endian format version (currently version 3), and a length-prefixed UTF-8 game version string. Behind that header sits one level-3 zstd frame with content checksums enabled, and that frame wraps the typed postcard binary payload without runtime reflection. Reading the unencoded header before decompressing lets the loader refuse non-save files, unsupported format versions, corrupt streams, or broken world invariants cleanly without panicking. Until players keep saves across public releases, mismatched format versions are refused outright so we carry zero fragile migration code.
Lookup indices, club-office scoring functions, per-round scratch plans, failure flags, and test overrides never enter the save file and are rebuilt cleanly when a world loads. Integration tests switch on Bevy ECS debug reflection in test builds only and fail immediately if a developer adds a new persistent component or resource without placing it in either the save registry or the rebuilt list. A committed golden save snapshot tested across a full simulated year then guards against unversioned format changes.
Frequently asked questions
Running a deterministic Rust and Bevy ECS simulation across single matches and 100-season careers requires controlling system order, random isolation, floating-point maths, and save encoding together. Single-threaded schedules protect shared state while parallel workers handle independent fixtures, and explicit cross-OS controls catch compiler, environment, or platform drift early.
How do you keep headless Bevy ECS deterministic without losing simulation speed?
Run every ECS schedule on a single-threaded executor with ambiguity detection set to error on unordered resource or component conflicts, and sort query inputs by stable domain ID before drawing randomness or writing state. To recover multi-core throughput safely, fan out read-only pre-match planning and isolated match simulations across worker threads with seeded ChaCha streams, then sort outcomes back into fixed fixture order before applying changes serially.
Why can floating point determinism fail between Windows and Linux in Rust?
Hardware IEEE-754 rules make basic arithmetic and square roots identical across x86-64 machines, whereas Rust delegates transcendental functions such as sine, cosine, exponential, and logarithm to each operating system’s libm. A 1-ULP difference in the final bit of a float between Windows and Linux grows across 54,000 match ticks into different passes and scorelines. Replacing host calls with a pure-Rust libm fixes the split if it meets a strict 5% speed limit.
How does a Rust ECS game save system produce byte-identical saves?
Walk persistent entities in sorted domain-ID order for clubs, people, and fixtures so ECS archetype memory layout never enters the output, and store all persistent collections in ordered maps and sets. Encode the canonical payload with postcard inside a checksummed level-3 zstd frame behind an unencoded version header, rebuild transient lookup indices on load, and check test builds for any unregistered world component.
Follow development
The Technical Area is a 2D football management game in active development, built in Rust on headless Bevy ECS. The match engine, event-driven calendar, transfer market, and versioned save system pass multi-decade determinism and statistical verification suites, while current work completes cross-platform pure-Rust maths verification and builds the playable interface.
How the wider layers connect is outlined on the technical page.
If you want to follow a football management simulation built from first principles, join the development list.