<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Mohamad Homsi]]></title><description><![CDATA[Mohamad Homsi]]></description><link>https://mhomsi.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Sat, 28 Nov 2026 02:01:12 GMT</lastBuildDate><atom:link href="https://mhomsi.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How a Rust civ sim stays deterministic with WebAssembly SIMD and threads]]></title><description><![CDATA[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…]]></description><link>https://mhomsi.hashnode.dev/how-a-rust-civ-sim-stays-deterministic-with-webassembly-simd-and-threads</link><guid isPermaLink="true">https://mhomsi.hashnode.dev/how-a-rust-civ-sim-stays-deterministic-with-webassembly-simd-and-threads</guid><category><![CDATA[WebAssembly]]></category><category><![CDATA[GameDev]]></category><category><![CDATA[performance]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Mohamad Homsi]]></dc:creator><pubDate>Thu, 26 Nov 2026 07:12:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/6b069f79918e1696165babea/d91150ce-f2a8-44b3-b615-d826b9efce28.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I'm building <a href="https://thehumanbox.com">The Human Box</a>, 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: <a href="https://github.com/1homsi/thehumanbox">1homsi/thehumanbox</a>.</p>
<p>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.</p>
<p>The hosted browser world is deliberately small. <code>DEFAULT_MAX_POPULATION</code> is 350. The engine's hard cap, <code>MAX_POPULATION_LIMIT</code>, 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.</p>
<h2>One tick</h2>
<p><code>Simulation::tick</code> lives in <a href="https://github.com/1homsi/thehumanbox/blob/main/crates/sim-core/src/sim/simulation/tick.rs"><code>crates/sim-core/src/sim/simulation/tick.rs</code></a>. 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.</p>
<p>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 <code>DAY_LENGTH</code> 600 ticks. A season is 3,000.</p>
<p>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.</p>
<p>That turn is split on purpose. The comment in <code>tick.rs</code> 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.</p>
<p>Looking and choosing go through <code>sim/par.rs</code>. 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.</p>
<h2>Hot fields in columns</h2>
<p>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 <code>x</code> and <code>y</code> is wasteful.</p>
<p>So next to <code>Vec&lt;Organism&gt;</code> there is <code>OrganismColumns</code> in <a href="https://github.com/1homsi/thehumanbox/blob/main/crates/sim-core/src/organism/columns.rs"><code>crates/sim-core/src/organism/columns.rs</code></a>. Slot <code>i</code> is <code>organisms[i]</code>. The columns hold position, previous position, velocity, needs, a lineage id, age, a flag word, and an <code>alive</code> byte:</p>
<pre><code class="language-rust">pub struct OrganismColumns {
    ready: bool,
    pub x: Vec&lt;f32&gt;,
    pub y: Vec&lt;f32&gt;,
    // prev_*, vx, vy, energy, hydration, health ...
    /// `1` living, `0` dead. A byte, not `bool`, so a SIMD load is a lane.
    pub alive: Vec&lt;u8&gt;,
    pub lineage: Vec&lt;Sym&gt;,
    pub age: Vec&lt;u32&gt;,
    pub flags: Vec&lt;u32&gt;,
}
</code></pre>
<p>Columns are a cache, not the save image. <code>sync_from</code> copies the hot words off the structs and marks them ready. Anything that writes a hot field through the struct calls <code>invalidate</code>. After people choose and act, the columns are invalid until the next sync. Velocity smoothing at the end of the tick writes back through <code>smooth_velocity</code>.</p>
<p>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.</p>
<p>There is a small example, <code>crates/sim-core/examples/soa_columns.rs</code>, that walks a 4,000-person crowd the old way and the new way. When this landed in <a href="https://github.com/1homsi/thehumanbox/pull/1158">#1158</a>, 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.</p>
<h2>A spatial grid on those columns</h2>
<p>Neighbour scans do not compare every living pair. <code>SpatialIndex</code> in <a href="https://github.com/1homsi/thehumanbox/blob/main/crates/sim-core/src/sim/spatial.rs"><code>crates/sim-core/src/sim/spatial.rs</code></a> drops people into buckets. The organism pass uses a bucket size of 10 tiles. The occasional civilisation contact pass uses 8.</p>
<p>The build walks the <code>alive</code>, <code>x</code> and <code>y</code> columns four at a time and calls <code>simd::bucket4</code>. If the world would need more than 65,536 buckets (<code>MAX_DENSE_BUCKETS</code>), 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.</p>
<p>Queries reuse a caller-owned <code>Vec</code>. <code>query_into</code> 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.</p>
<h2>Four lanes, three backends, one answer</h2>
<p>The numeric kernels live in <a href="https://github.com/1homsi/thehumanbox/blob/main/crates/sim-core/src/simd/mod.rs"><code>crates/sim-core/src/simd/</code></a>. They cover movement integration, Manhattan and hypot distance, and the bucket coordinates above. Each kernel runs four lanes (<code>LANES = 4</code>).</p>
<p>Native builds use SSE2 or NEON. The wasm SIMD module (<code>feature = "wasm-simd"</code>) uses <code>simd128</code>. Everything else, including a wasm build without that feature, runs the same operations one lane at a time.</p>
<p>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 <code>hypot</code> follows <code>DetMath::det_hypot</code> (the f64 product inside <code>libm::hypotf</code>, then <code>sqrt</code>). The tests compare edges and random bit patterns against that scalar definition. If SIMD rounded differently, two browsers would diverge on the same seed.</p>
<p>The page never assumes the browser can run SIMD. <a href="https://github.com/1homsi/thehumanbox/blob/main/apps/web/src/simulation/wasmSimd.ts"><code>apps/web/src/simulation/wasmSimd.ts</code></a> keeps a one-instruction wasm module (<code>v128.const</code>) taken from the wasm-feature-detect probe. <code>WebAssembly.validate</code> 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 <code>Sim</code> API and tick the same world.</p>
<h2>Threads, but only when the page can share memory</h2>
<p>The first worker-thread change (<a href="https://github.com/1homsi/thehumanbox/pull/1159">#1159</a>) 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 <code>wasm-threads</code> build, which turns the <code>parallel</code> feature on through <code>wasm-bindgen-rayon</code> (<code>scripts/build-wasm-threads.sh</code>).</p>
<p><a href="https://github.com/1homsi/thehumanbox/blob/main/apps/web/src/simulation/wasmEngine.ts"><code>apps/web/src/simulation/wasmEngine.ts</code></a> decides which one to start. Threads are only requested when the page is cross-origin isolated and <code>SharedArrayBuffer</code> exists. Those come from the <code>Cross-Origin-Opener-Policy: same-origin</code> and <code>Cross-Origin-Embedder-Policy: require-corp</code> headers in <code>apps/web/public/_headers</code>. Mobile WebKit skips the threaded build. Elsewhere, the worker tries the threaded module first.</p>
<p>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 (<a href="https://github.com/1homsi/thehumanbox/issues/923">#923</a>). Now the threaded start gets a 3 second head start (<code>THREADS_HEAD_START_MS</code>). 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.</p>
<p>Thread count is <code>navigator.hardwareConcurrency</code> minus 2 cores reserved for the page and the renderer, capped at <code>MAX_SIM_THREADS</code> (6). WebKit desktop is capped at 4, and the start reserves a 640 MB heap before the pool comes up.</p>
<p>The rule that keeps this from changing the world when you change the core count is in <a href="https://github.com/1homsi/thehumanbox/blob/main/crates/sim-core/src/sim/par.rs"><code>crates/sim-core/src/sim/par.rs</code></a>:</p>
<pre><code class="language-rust">//! 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.
</code></pre>
<p><code>perceive_all</code> and <code>choose_all</code> are the obvious callers. Choosing does not draw from the world RNG on the workers. The tick draws one <code>tick_seed</code> on the main thread, and each person gets <code>choice_rng(tick_seed, index)</code>. Writes, including births, deaths and every later use of <code>self.rng</code>, stay in the original order.</p>
<p>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.</p>
<h2>What I am not claiming</h2>
<p>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.</p>
<p>CI still has a performance gate (<code>make perf-gate</code>): 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.</p>
<p>There is also a calm-town path (<code>town_lod.rs</code>) 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.</p>
<p>The renderer is a separate problem. The map runs on <a href="https://github.com/1homsi/xip">xipjs</a> in a WebGL2 stack, on the main thread, while the sim ticks in a Web Worker (<code>apps/web/src/simulation/wasmWorker.ts</code>). Paused worlds do not keep asking for frames.</p>
<p>If you want to read the code, start at <code>tick.rs</code>, then <code>organism/columns.rs</code>, <code>sim/spatial.rs</code>, <code>simd/mod.rs</code>, <code>sim/par.rs</code>, and <code>apps/web/src/simulation/wasmEngine.ts</code>.</p>
<p>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.</p>
<p>The code is at <a href="https://github.com/1homsi/thehumanbox">github.com/1homsi/thehumanbox</a>, and you can play it at <a href="https://thehumanbox.com">thehumanbox.com</a>.</p>
]]></content:encoded></item><item><title><![CDATA[How tribes invent their own languages in a Rust civilization sim]]></title><description><![CDATA[I'm building The Human Box, a civ sim that runs in the browser. Stone Age people wander around, find food, pair up, form tribes, fight, and eventually…]]></description><link>https://mhomsi.hashnode.dev/how-tribes-invent-their-own-languages-in-a-rust-civilization-sim</link><guid isPermaLink="true">https://mhomsi.hashnode.dev/how-tribes-invent-their-own-languages-in-a-rust-civilization-sim</guid><category><![CDATA[WebAssembly]]></category><category><![CDATA[GameDev]]></category><category><![CDATA[simulation]]></category><category><![CDATA[Rust]]></category><dc:creator><![CDATA[Mohamad Homsi]]></dc:creator><pubDate>Wed, 25 Nov 2026 08:45:19 GMT</pubDate><content:encoded><![CDATA[<p>I'm building <a href="https://thehumanbox.com">The Human Box</a>, a civ sim that runs in the browser. Stone Age people wander around, find food, pair up, form tribes, fight, and eventually build towns. The sim is all Rust compiled to wasm, and it's MIT on GitHub: <a href="https://github.com/1homsi/thehumanbox">1homsi/thehumanbox</a>.</p>
<p>The thing people ask about most is the languages. Tribes start with words nobody designed, and a few generations later the tribe next door has a different word for food, fire and home. I don't have a linguistics model. It's a handful of small rules in one file, <a href="https://github.com/1homsi/thehumanbox/blob/main/crates/sim-core/src/organism/vocabulary.rs"><code>crates/sim-core/src/organism/vocabulary.rs</code></a>, plus the few places in the sim that call them. Here's how it works.</p>
<h2>One slot per concept</h2>
<p>Every person carries a <code>Vocabulary</code>, which is one slot per concept from a fixed list called <code>CONCEPTS</code>. Right now the list has 417 entries. It starts with the basics and goes on to weather, feelings, kin terms, animals and landforms:</p>
<pre><code class="language-rust">pub const CONCEPTS: &amp;[&amp;str] = &amp;[
    "food",
    "water",
    "fire",
    "danger",
    "friend",
    "foe",
    "shelter",
    // ... 417 in total
];
</code></pre>
<p>Everyone has the same concepts. What's different is the word sitting in each slot. A word is one or two consonant-vowel syllables from a tiny sound set:</p>
<pre><code class="language-rust">const CONSONANTS: &amp;[u8] = b"bdfghjklmnprstvwz";
const VOWELS: &amp;[u8] = b"aeiou";

fn gen_syllable(rng: &amp;mut impl Rng) -&gt; String {
    let mut s = String::new();
    s.push(CONSONANTS[rng.random_range(0..CONSONANTS.len())] as char);
    s.push(VOWELS[rng.random_range(0..VOWELS.len())] as char);
    s
}

fn gen_word(rng: &amp;mut impl Rng) -&gt; String {
    let syllables = rng.random_range(1usize..=2);
    (0..syllables).map(|_| gen_syllable(rng)).collect()
}
</code></pre>
<p>So you get words like <code>ka</code>, <code>mibo</code> or <code>zute</code>. With 17 consonants and 5 vowels there are 85 one-syllable words and 7,225 two-syllable ones. Two founders landing on the same word for the same thing is rare, but it happens.</p>
<p>The first people in a world each get <code>Vocabulary::generate</code>, a random word for every concept. At that point they mostly can't understand each other, apart from the odd lucky match. Everything after that is just words getting copied, changed and forgotten.</p>
<h2>Kids copy their mother, with typos</h2>
<p>When a child is born, <code>growth.rs</code> calls <code>Vocabulary::inherit_from</code> on the mother's vocabulary. Each word has a 3% chance of picking up one sound change:</p>
<pre><code class="language-rust">for i in 0..child.slots.len() {
    if child.slots[i].is_empty() {
        continue;
    }
    if rng.random::&lt;f32&gt;() &lt; 0.03 {
        let bytes = child.text(i).as_bytes().to_vec();
        let pos = rng.random_range(0..bytes.len());
        let mut mutated = bytes;
        if pos % 2 == 0 {
            mutated[pos] = CONSONANTS[rng.random_range(0..CONSONANTS.len())];
        } else {
            mutated[pos] = VOWELS[rng.random_range(0..VOWELS.len())];
        }
        child.set(i, &amp;String::from_utf8_lossy(&amp;mutated));
    }
}
</code></pre>
<p>Words are always consonant-vowel pairs, so even positions are consonants and odd positions are vowels. A mutation swaps a consonant for a consonant or a vowel for a vowel. <code>mibo</code> can turn into <code>migo</code> or <code>mubo</code>, but never into something the sim's sound system can't produce. The words drift but keep their shape.</p>
<p>At 3% per word over a few hundred concepts, pretty much every kid is born talking a little differently from their mom. If that were the only rule, every family would end up with its own dialect. The next two rules are what hold a tribe together.</p>
<h2>Borrowing, one word at a time</h2>
<p>When two people interact in certain ways, the listener might borrow a word from the speaker. That's <code>absorb_from</code>:</p>
<pre><code class="language-rust">pub fn absorb_from(&amp;mut self, other: &amp;Vocabulary, rng: &amp;mut impl Rng) {
    let differing = (0..CONCEPTS.len())
        .filter(|&amp;i| self.differs_from(other, i))
        .count();
    if differing == 0 {
        return;
    }
    if rng.random::&lt;f32&gt;() &lt; 0.06 {
        let pick = rng.random_range(0..differing);
        let chosen = concept_order()
            .iter()
            .copied()
            .filter(|&amp;i| self.differs_from(other, i))
            .nth(pick);
        if let Some(i) = chosen {
            self.ensure_capacity();
            self.set(i, other.text(i));
        }
    }
}
</code></pre>
<p>6% of the time, the listener takes one of the words the two of them disagree on. That's slow on purpose. One conversation barely changes anyone, but if you hear the same neighbours every day you end up sounding like them.</p>
<p>The sim calls <code>absorb_from</code> in a few places:</p>
<ul>
<li><strong>Food calls and alarms</strong> (<code>social/signals.rs</code>). Someone calls out food and everyone within 12 tiles hears it and might borrow a word. Alarms carry 14 tiles.</li>
<li><strong>Gifts between tribes</strong> (<code>social/knowledge.rs</code>). If a gift leaves both sides on good enough terms, each borrows from the other.</li>
<li><strong>Teaching.</strong> The student borrows from the teacher.</li>
<li><strong>One of the calming social actions</strong> in the per-person act step. Everyone within 6 tiles borrows from the speaker.</li>
</ul>
<p>That's where loanwords come from. Tribes that trade and give gifts pick up each other's words, and tribes that only fight barely do.</p>
<h2>Inside a group, the majority wins</h2>
<p>Borrowing on its own is way too slow to keep a camp speaking one language. The bigger force is <code>converge_with</code>. It runs when people share what they know (food spots, water, danger) with the people around them:</p>
<pre><code class="language-rust">for (i, &amp;concept) in CONCEPTS.iter().enumerate() {
    if rng.random::&lt;f32&gt;() &gt;= adopt_rate {
        continue;
    }
    let mut counts: HashMap&lt;&amp;str, usize&gt; = HashMap::default();
    for snap in snapshots {
        if let Some(w) = snap.get(concept) {
            *counts.entry(w.as_str()).or_insert(0) += 1;
        }
    }
    let majority = counts
        .iter()
        .max_by(|a, b| a.1.cmp(b.1).then_with(|| b.0.cmp(a.0)))
        .map(|(&amp;w, _)| w);
    if let Some(majority) = majority {
        if self.text(i) != majority {
            self.set(i, majority);
            self.touch(i, tick);
        }
    }
}
</code></pre>
<p><code>social_knowledge_share</code> calls it with an <code>adopt_rate</code> of 0.40. So for each concept there's a 40% chance you look at what most of the group says and switch to that word if yours is different. "The group" is anyone within 4 tiles who's kin, a named friend, someone you trust, or from a tribe you like. Strangers and enemies don't count.</p>
<p>Inside a camp, words converge fast. Between camps that don't trust each other, they don't. Add the birth mutations on top and you get the result I was after: each tribe settles on its own word for food, and the words drift further apart the longer the tribes stay apart.</p>
<p>That tie-break in the snippet is there because of a bug. The first version used <code>max_by_key</code> on the <code>HashMap</code>, which breaks ties in iteration order. The hasher is randomly seeded, so the same world seed could pick a different winning word on a different run. Breaking ties on the word itself fixed it. The sim has to be deterministic for saves to work, and this was one of the places it quietly wasn't.</p>
<h2>Forgetting</h2>
<p>Words you don't use fade. Every vocabulary keeps a <code>last_used</code> tick per concept, and <code>decay</code> clears any word that hasn't been used in more than 5,000 ticks:</p>
<pre><code class="language-rust">let last = self.last_used[i];
if last == 0 {
    // Never explicitly used. Start the forgetting clock now
    self.last_used[i] = tick;
    continue;
}
if tick.saturating_sub(last) &gt; threshold_ticks {
    self.set(i, "");
}
</code></pre>
<p>Speaking, hearing a call, or picking up a word through convergence all reset the clock for that concept. The <code>last == 0</code> branch is another bug fix, and you can still see it in the comment. Originally "never used" got read as "last used at tick 0", so the moment a world passed tick 5,000, everyone forgot every word they'd never personally said.</p>
<p>A forgotten word matters later. Borrowing only swaps words when both people already have one, so a forgotten word comes back through convergence. You pick up whatever your group says. If that group includes friendly neighbours, you might not get your own tribe's old word back.</p>
<h2>Food calls are where it actually matters</h2>
<p>If understanding each other didn't matter, the languages would just be decoration. In <code>signal_food</code>, someone who knows where food is calls it out, and each listener compares the speaker's word for "food" with their own:</p>
<pre><code class="language-rust">let recognizes =
    signal_word.is_some() &amp;&amp; organisms[ni].vocabulary.known_word("food") == signal_word.as_deref();
// ...
let strength = if recognizes {
    base_strength
} else {
    base_strength * 0.3
};
</code></pre>
<p>If you share the word, the food location goes into your memory at full strength. If you don't, you get 30% of it. Kin also hear more strongly than strangers. Alarms work the same way, with separate strengths for kin vs. stranger and for recognised vs. not.</p>
<p><code>known_word</code> exists because of a third bug. The older <code>word_for</code> falls back to the English concept name when a slot is empty. So two people who'd both forgotten "food" ended up comparing <code>"food" == "food"</code> and counted as understanding each other. <code>known_word</code> returns <code>None</code> for a forgotten word, and <code>None</code> never matches.</p>
<p>So a tribe whose food word drifted away from its neighbours' is worse at using their calls, and the other way round. Nowhere in the code does it say "tribes should have separate languages". It falls out of births, borrowing, convergence and forgetting, and the food calls are what make it matter.</p>
<h2>Watching it in one family</h2>
<p>In the game, the person panel shows someone's words next to their parents' and grandparents' words for eight everyday concepts: food, water, fire, home, friend, sun, river and danger. That's in <code>organism/family_words.rs</code>. It's usually the easiest place to catch a mutation that stuck.</p>
<p>Drift takes generations, so a fresh world doesn't show much at first. On Nov 22 I merged an optional head-start world (<a href="https://github.com/1homsi/thehumanbox/pull/1156">#1156</a>). It starts tribes from one shared proto-language, and each tribe reshapes the words for the land it lives on: wetland tribes change "water" and "river", desert tribes change "fire" and "sun", and so on. It's off by default, except that people who arrive from a Reddit link with no save start in it (<a href="https://github.com/1homsi/thehumanbox/pull/1165">#1165</a>).</p>
<h2>Keeping ~400 words per person cheap</h2>
<p>Every living person carries one of these, and so do the dead people the sim still keeps around, so the memory layout matters. Each word sits inline in an 8-byte slot instead of being a <code>String</code> per concept:</p>
<pre><code class="language-rust">#[derive(Clone, Copy, Default)]
struct Word {
    len: u8,
    bytes: [u8; Word::INLINE], // INLINE = 7
}
</code></pre>
<p>Generated words are at most four letters, so they always fit. Anything longer, which only an old save can bring in, goes into a small side list. The doc comment on <code>Vocabulary</code> puts this at about 5 KB per vocabulary, down from 14 KB with a <code>String</code> per slot. The JSON format stayed the same: for human-readable serializers, custom <code>Serialize</code>/<code>Deserialize</code> impls still read and write the old <code>HashMap&lt;String, String&gt;</code> shape, and binary serializers get a packed word string instead. A test runs the compact type and the old one side by side to check they stay identical and draw the same random numbers.</p>
<h2>Recent perf work</h2>
<p>Language is a small slice of each tick. Most of the time goes to movement, sensing and spatial lookups. Three changes landed on main on Nov 22:</p>
<ul>
<li><strong>SIMD kernels</strong> (<a href="https://github.com/1homsi/thehumanbox/pull/1157">#1157</a>). Movement, distance checks and spatial-grid bucketing run four lanes at a time on SSE2, NEON and wasm <code>simd128</code>. The kernels match the scalar path bit for bit: no fused multiply-add, same rounding. The web build ships a SIMD wasm module and a scalar one, and the page only loads the SIMD one if <code>WebAssembly.validate</code> accepts it.</li>
<li><strong>Column layout for hot fields</strong> (<a href="https://github.com/1homsi/thehumanbox/pull/1158">#1158</a>). Position, velocity, needs, alive and lineage now also live in parallel columns next to the <code>Vec&lt;Organism&gt;</code>, rebuilt every tick. The spatial grid, crowd separation and sensing read from those columns. On the included 4,000-person benchmark that went from 423.7 µs to 396.7 µs per pass, about 1.07x. Not huge, but it's groundwork.</li>
<li><strong>Read-only passes on worker threads</strong> (<a href="https://github.com/1homsi/thehumanbox/pull/1159">#1159</a>). Sensing, route planning, border contacts and town assignment only read the world, so they run on worker threads now. Results get applied in index order, and every write, including draws from the world RNG, stays in the original order. In a 2,000-person test, a tick on 4 threads went from 21.75 ms to 19.98 ms. The web build stays single-threaded.</li>
</ul>
<p>All three follow the same rule as that vocabulary tie-break: a seed has to produce the same world. #1158 was checked against save fingerprints from main for several seeds and tick counts, and #1159 against a save that's byte-identical at 1, 4 and 6 threads. If a speedup changes what happens in the world, it can't go in as just a perf change. One later PR did: <a href="https://github.com/1homsi/thehumanbox/pull/1160">#1160</a> steps calm regions less often, which changes how a given seed plays out, so it was held for a separate decision instead of going in as a plain speedup.</p>
<h2>Try it</h2>
<p>You can play it at <a href="https://thehumanbox.com">thehumanbox.com</a>. Nothing to install, no account, and worlds save locally. Click a person to see their family's words. The code is at <a href="https://github.com/1homsi/thehumanbox">github.com/1homsi/thehumanbox</a>. The language system is <code>crates/sim-core/src/organism/vocabulary.rs</code>, and the calls that use it are in <code>crates/sim-core/src/sim/agents/social/</code>. Issues and PRs are welcome, and if you liked this, a star helps other people find it.</p>
<p><em>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.</em></p>
]]></content:encoded></item></channel></rss>