<!-- https://tinyactors.dev/anthill/ -->
# A million ants in your browser

Kind: pitch. For: [Agent-platform engineer](https://tinyactors.dev/audiences/agent-platform.xml), [Tech lead who approves dependencies](https://tinyactors.dev/audiences/tech-lead.xml).
Voice: [Pitch](https://tinyactors.dev/voices/pitch.xml).

> Two anthills in a browser tab, where every ant and queen is a tinyactors actor running on WebAssembly.

Two colonies share this field, and every ant and queen is an actor running in your browser.

<a id="watch"></a>

## Drop food and squash ants

Tap the field to use the tool you picked, and pinch to zoom in on a fight. Follow an ant to keep it in view beside its chart, lit in the state the ant is in.

Two anthills on a field. Workers carry food home to their queen, and workers of the two colonies fight where they meet.

<https://tinyactors.dev/anthill/#watch>

<a id="ant"></a>

## An ant is a statechart

An egg becomes a larva and then a worker, which forages until an event ends it. The world sends `die` when the ant grows old.

```scxml title="ant.scxml"
<?xml version="1.0" encoding="UTF-8"?>
<!-- An ant. An egg hatches into a larva, the larva grows into a worker, and
     the worker forages: out to look for food, home with what it found, a
     rest in the hill, out again. It decides only when something happens;
     the world (urn:world) picks each leg, says when it arrives, and says
     when it meets an enemy. Two fights kill it, old age kills it, and so
     does a reader's tap. -->
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="ant" initial="alive">
  <datamodel>
    <data id="colony" expr="0"/>
    <data id="stage" expr="'worker'"/>
    <data id="hp" expr="2"/>
  </datamodel>
  <state id="alive" initial="start">
    <transition event="kill" target="dead"/>
    <transition event="die" target="dead"/>
    <state id="start">
      <transition cond="stage === 'egg'" target="egg"/>
      <transition target="worker"/>
    </state>
    <state id="egg">
      <onentry><send event="hatch" delay="20s"/></onentry>
      <transition event="hatch" target="larva"/>
    </state>
    <state id="larva">
      <onentry><send event="grow" delay="30s"/></onentry>
      <transition event="grow" target="worker"/>
    </state>
    <state id="worker" initial="foraging">
      <transition event="fight" cond="hp &lt;= 1" target="dead"/>
      <transition event="fight"><assign location="hp" expr="hp - 1"/></transition>
      <state id="foraging">
        <onentry><send type="urn:world" event="forage"/></onentry>
        <transition event="found" target="carrying"/>
        <transition event="arrive" target="foraging"/>
      </state>
      <state id="carrying">
        <onentry><send type="urn:world" event="home"/></onentry>
        <transition event="arrive" target="resting"/>
      </state>
      <state id="resting">
        <onentry><send type="urn:world" event="rest"/></onentry>
        <transition event="arrive" target="foraging"/>
      </state>
    </state>
  </state>
  <final id="dead"/>
</scxml>
```

<a id="queen"></a>

## So is a queen

Once a second she lays an egg for every two pieces of food her workers brought home.

```scxml title="queen.scxml"
<?xml version="1.0" encoding="UTF-8"?>
<!-- A queen. Her colony's workers bring food home (harvest); once a second
     she lays an egg for every two pieces of food she holds, and the world
     hatches them as ants, while the colony has room. -->
<scxml xmlns="http://www.w3.org/2005/07/scxml" version="1.0"
       datamodel="ecmascript" name="queen" initial="laying">
  <datamodel>
    <data id="colony" expr="0"/>
    <data id="food" expr="0"/>
  </datamodel>
  <state id="laying">
    <onentry><send event="tick" delay="1s"/></onentry>
    <transition event="harvest">
      <assign location="food" expr="food + _event.data.food"/>
    </transition>
    <transition event="tick" cond="food &gt;= 2" target="laying">
      <send type="urn:world" event="lay">
        <param name="eggs" expr="Math.floor(food / 2)"/>
      </send>
      <assign location="food" expr="food % 2"/>
    </transition>
    <transition event="tick" target="laying"/>
  </state>
</scxml>
```

<a id="world"></a>

## Charts send messages to the world

The ant's chart sends `forage` to the world and waits for `arrive` or `found`. The world is a JavaScript object on this page that picks each destination.

```javascript title="world.mjs"
  const slot = free[--freeTop];
  if (session >= slotOf.length) {
    const grown = new Int32Array(Math.max(session + 1, slotOf.length * 2)).fill(-1);
    grown.set(slotOf);
    slotOf = grown;
  }
  slotOf[session] = slot;
  sessionOf[slot] = session;
  stage[slot] = BROOD; carrying[slot] = 0;
  phase[slot] = ((slot * .61803398875) % 1) * 2;
  t0[slot] = t1[slot] = 0;
  placeInHill(slot);
  counts.brood++; counts.born++;
  touch(slot);
}
```

This page runs each colony as a host in its own Web Worker, so the browser can use two CPU cores.

<a id="cost"></a>

## Messages decide how many ants keep up

An ant uses the CPU only while it handles a message. While it walks or rests, it waits in memory and your GPU draws it.

The rest slider sets how long ants stay in the hill between outings, so shorter rests mean more messages a second. The time per message stays level as you add ants, and the real-time chart shows whether your device keeps up.

<a id="node"></a>

## The same world runs in Node.js

With a simulated clock and a fixed seed, every run prints the same five minutes of both colonies.

```javascript title="main.mjs"
const chart = (name) => readFileSync(new URL(`./${name}.scxml`, import.meta.url), 'utf8');
const charts = { ant: chart('ant'), queen: chart('queen') };
const colonies = await Promise.all([0, 1].map((colony) => createColony(tinyactors, { charts, population: 1500, colony, seed: 7 })));
for (const colony of colonies) await colony.populate();

let messages = [null, null];
for (let minute = 1; minute <= 5; minute++) {
  for (let frame = 0; frame < 60_000 / FRAME; frame++) {
    messages = await Promise.all(colonies.map((colony, i) => colony.step(messages[1 - i])));
  }
  const stats = colonies.map((colony) => colony.stats());
  const shown = stats.map(({ colony: c }, i) => `hill ${i + 1}: ${c.workers} workers, ${c.brood} brood, ${c.stored} food home, ${c.born} born, ${c.deaths} died`);
  console.log(`minute ${minute}: ${shown.join('; ')}; ${stats[0].fights + stats[1].fights} fights`);
}
```

```text title="output"
minute 1: hill 1: 1500 workers, 0 brood, 1093 food home, 1500 born, 0 died; hill 2: 1499 workers, 1 brood, 1106 food home, 1501 born, 1 died; 29 fights
minute 2: hill 1: 1499 workers, 1 brood, 2322 food home, 1501 born, 1 died; hill 2: 1500 workers, 0 brood, 2345 food home, 1501 born, 1 died; 36 fights
minute 3: hill 1: 1490 workers, 10 brood, 3537 food home, 1511 born, 11 died; hill 2: 1493 workers, 7 brood, 3568 food home, 1509 born, 9 died; 58 fights
minute 4: hill 1: 1479 workers, 21 brood, 4748 food home, 1534 born, 34 died; hill 2: 1484 workers, 16 brood, 4753 food home, 1526 born, 26 died; 63 fights
minute 5: hill 1: 1456 workers, 44 brood, 5947 food home, 1584 born, 84 died; hill 2: 1465 workers, 35 brood, 5984 food home, 1568 born, 68 died; 65 fights
```
