I'm building The Human Box, a civilization sim that runs in the browser. People wander, find food, form tribes, fight, and eventually build towns. The engine is Rust, compiled to WebAssembly, and it's MIT on GitHub: 1homsi/thehumanbox.

I wrote earlier about how tribes invent their own words. This is about the other question I get: how the same engine ticks in a tab without the world changing when SIMD or threads turn on.

The hosted browser world is deliberately small. DEFAULT_MAX_POPULATION is 350. The engine's hard cap, MAX_POPULATION_LIMIT, is 5,000, which the desktop build can opt into. So this is not a 10,000-person demo. It is a tick that has to stay cheap at a few hundred people, and stay correct if someone later opens a much larger world.

One tick

Simulation::tick lives in crates/sim-core/src/sim/simulation/tick.rs. A tick is not "run every person." It is a fixed sequence: bookkeeping and strategy objectives, lineage aggregates, the civilisation pass, seasons and physics, droughts and weather, farms, animals, then the people.

Some of that work is on a cadence, not every tick. Physics steps every 5 ticks. The civilisation pass builds a spatial index with 8-tile buckets only every 500 ticks, for cross-lineage contact. Slow world evolution runs every 300 ticks. A day is DAY_LENGTH 600 ticks. A season is 3,000.

When it is time for the people, the code copies hot fields into columns, builds two spatial indexes with 10-tile buckets (people and animals), separates crowds, then takes each living person's turn.

That turn is split on purpose. The comment in tick.rs is the short version: everyone looks at once (reads of the world, on all cores), then each is written in order from what they saw. Then everyone chooses at once, from the world as choosing begins, and each acts on their choice, in order.

Looking and choosing go through sim/par.rs. Acting writes positions, needs, births and deaths on the struct, in index order. If a tribe splits mid-pass, only the people after the founder have their looks redone, because those are the only ones the split can change.

Hot fields in columns

A person is a large struct: memories, trust, names, inventory, a Q-table. The passes that walk everyone (rebuild the spatial grid, separate a crowd, scan neighbours, smooth velocity) only need a few words of that. Pulling the whole struct through cache for x and y is wasteful.

So next to Vec<Organism> there is OrganismColumns in crates/sim-core/src/organism/columns.rs. Slot i is organisms[i]. The columns hold position, previous position, velocity, needs, a lineage id, age, a flag word, and an alive byte:

pub struct OrganismColumns { ready: bool, pub x: Vec<f32>, pub y: Vec<f32>, // prev_*, vx, vy, energy, hydration, health ... /// `1` living, `0` dead. A byte, not `bool`, so a SIMD load is a lane. pub alive: Vec<u8>, pub lineage: Vec<Sym>, pub age: Vec<u32>, pub flags: Vec<u32>, } 

Columns are a cache, not the save image. sync_from copies the hot words off the structs and marks them ready. Anything that writes a hot field through the struct calls invalidate. After people choose and act, the columns are invalid until the next sync. Velocity smoothing at the end of the tick writes back through smooth_velocity.

Pairing still uses the live structs. It runs after that person's own step, and the people before them have already aged, moved, partnered or died. A snapshot taken at the start of the turn would answer a different question.

There is a small example, crates/sim-core/examples/soa_columns.rs, that walks a 4,000-person crowd the old way and the new way. When this landed in #1158, that pass went from 423.7 µs to 396.7 µs, about 1.07x. Not a headline speedup. It is what the SIMD kernels and the spatial rebuild actually read.

A spatial grid on those columns

Neighbour scans do not compare every living pair. SpatialIndex in crates/sim-core/src/sim/spatial.rs drops people into buckets. The organism pass uses a bucket size of 10 tiles. The occasional civilisation contact pass uses 8.

The build walks the alive, x and y columns four at a time and calls simd::bucket4. If the world would need more than 65,536 buckets (MAX_DENSE_BUCKETS), the index switches from a dense grid to a sparse map. A comment in the file notes that a 600 by 300 tile map in 10-tile buckets is only 1,800 buckets, so almost every real world stays dense.

Queries reuse a caller-owned Vec. query_into clears it and fills it, instead of allocating a fresh one per person per look. Perception of nearby animals, for example, queries radius 8 into a scratch buffer, then measures distances four lanes at a time.

Four lanes, three backends, one answer

The numeric kernels live in crates/sim-core/src/simd/. They cover movement integration, Manhattan and hypot distance, and the bucket coordinates above. Each kernel runs four lanes (LANES = 4).

Native builds use SSE2 or NEON. The wasm SIMD module (feature = "wasm-simd") uses simd128. Everything else, including a wasm build without that feature, runs the same operations one lane at a time.

The important part is not the width. It is that every kernel has to match the scalar path bit for bit: no fused multiply-add, no reassociation, and hypot follows DetMath::det_hypot (the f64 product inside libm::hypotf, then sqrt). The tests compare edges and random bit patterns against that scalar definition. If SIMD rounded differently, two browsers would diverge on the same seed.

The page never assumes the browser can run SIMD. apps/web/src/simulation/wasmSimd.ts keeps a one-instruction wasm module (v128.const) taken from the wasm-feature-detect probe. WebAssembly.validate accepts it only when the engine can run SIMD. If it does, the worker loads the SIMD build. If it does not, it loads the scalar build. Both export the same Sim API and tick the same world.

Threads, but only when the page can share memory

The first worker-thread change (#1159) ran read-only passes on Rayon and left the web build single-threaded. That is still the fallback. The web client can now also load a third module, the wasm-threads build, which turns the parallel feature on through wasm-bindgen-rayon (scripts/build-wasm-threads.sh).

apps/web/src/simulation/wasmEngine.ts decides which one to start. Threads are only requested when the page is cross-origin isolated and SharedArrayBuffer exists. Those come from the Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp headers in apps/web/public/_headers. Mobile WebKit skips the threaded build. Elsewhere, the worker tries the threaded module first.

The threaded module is about 5 MB, so a hung compile used to hold the splash screen for the full 30 second module timeout plus the 10 second pool timeout, 40 seconds, before the single-thread engine even began (#923). Now the threaded start gets a 3 second head start (THREADS_HEAD_START_MS). If it is still going, the single-thread engine starts beside it, and whichever is ready first runs the world. A fast threaded start never downloads the second module.

Thread count is navigator.hardwareConcurrency minus 2 cores reserved for the page and the renderer, capped at MAX_SIM_THREADS (6). WebKit desktop is capped at 4, and the start reserves a 640 MB heap before the pool comes up.

The rule that keeps this from changing the world when you change the core count is in crates/sim-core/src/sim/par.rs:

//! The rule that keeps worlds reproducible: work handed to these helpers reads the world and returns a //! value; it never writes to the world or draws from the world's random numbers. Results come back in index //! order, so a run gives the same world whatever the number of cores, and the same world with the //! `parallel` feature off (the web build), where the same work runs on one thread. 

perceive_all and choose_all are the obvious callers. Choosing does not draw from the world RNG on the workers. The tick draws one tick_seed on the main thread, and each person gets choice_rng(tick_seed, index). Writes, including births, deaths and every later use of self.rng, stay in the original order.

When #1159 landed, a 2,000-person test went from 21.75 ms to 19.98 ms a tick on 4 threads. Same story as the column bench: a modest win, measured, and only accepted because a save stayed byte-identical at 1, 4 and 6 threads.

What I am not claiming

I am not claiming the browser runs 5,000 people at 60 frames a second. The default hosted cap is 350. The 4,000 and 2,000 figures above are benchmark crowds, not the world you get when you open the site.

CI still has a performance gate (make perf-gate): three seeds at 8,000 ticks, plus one 25,000-tick run, checking max, p99 and mean time per tick, memory, and a checksum of the printed history. The gate is there because a slower tick on a bigger world is not the same as a slower tick.

There is also a calm-town path (town_lod.rs) that can step a quiet region every 8, 16, 32 or 64 ticks instead of every tick. That does change how a given seed plays out, so it is a behaviour change, not a transparent speedup. I am leaving that for another write-up.

The renderer is a separate problem. The map runs on xipjs in a WebGL2 stack, on the main thread, while the sim ticks in a Web Worker (apps/web/src/simulation/wasmWorker.ts). Paused worlds do not keep asking for frames.

If you want to read the code, start at tick.rs, then organism/columns.rs, sim/spatial.rs, simd/mod.rs, sim/par.rs, and apps/web/src/simulation/wasmEngine.ts.

I use AI-assisted coding tools on this project. They helped with parts of the code, and an AI assistant helped draft this write-up.

The code is at github.com/1homsi/thehumanbox, and you can play it at thehumanbox.com.