A mangrove coast from code, taken apart
How a small artificial-life toy works, piece by piece, and where the real science is
The mangrove toy shows a muddy coast with a tide, mangroves, a few animals and mud that comes and goes. This article takes it apart: what each piece does, the code that does it, the idea behind it, and what to read to go further.
Built with AI coding tools: I set the direction, tested and decided; the tools wrote the code and the first draft of this article. The reference list was checked against Crossref, and what I say about each source against its abstract or an open copy. I am not an expert in this field. I am learning it, and this article is my map so far.
A toy, not a model
Every rule in the toy was made up to look and feel right. No rule was fitted to a measurement, no number in it means anything outside the toy, and the place does not exist. That is the difference to a model. The last part is about what it would take to cross it.
The toy is still useful to me as a way in. Each of its pieces is a small, complete example of an idea from agent-based modelling or artificial life, and each one fits on a screen.
The shape of the program
The toy is one HTML file of about 120 KB with no library and no data files. A short Python script puts it together from ten JavaScript modules, a page template and a style sheet, about 2,500 lines in all. Drawing is WebGL2 written by hand; sound is the Web Audio API.
The loop that runs every frame is short. It moves the clock, lets the mud (when years run or a storm blows) and the animals take one step, passes what happened to the sound, and draws (from main.js):
if (playing) {
simT += dt; growT += dt; tod = (tod + dt / DAY_S) % 1;
const E = env();
coastStep(dt, E.storm);
if (falling.length) falling = falling.filter((f) => simT - f.t0 < 4.4 || (deleteVAO(gl, f.m), false));
life.update(dt, E);
for (const ev of life.drain()) sound.event(ev);
sound.update(dt, E);
cam.update(dt, playing);
dirty = true;
}
if (dirty) draw();E is the state of the world that everything else reads: the water level, how much night it is, the time, and how strong the storm is. Most parts read only this record and the height of the ground. The exceptions: the animals see each other, they send events to the sound, and the trees tell the mud rule and the fireflies where they stand.
One name, one world
Every world has a name such as salt-heron-42. The name is hashed to a number, and the number starts a small random number generator (from util.js):
function hashString(s) {
let h = 2166136261 >>> 0;
for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); }
return h >>> 0;
}
function mulberry32(a) {
return function () {
a = (a + 0x6D2B79F5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}The hash is the FNV-1a scheme. mulberry32 is a small generator written by Tommy Ettinger in 2017, here in the JavaScript form by “bryc”. All three are in the public domain. The coast, the trees, where the animals start and where seedlings come up all draw their random numbers from generators started this way. The same name therefore gives the same coast. The sound, the lightning and the way a tree falls use the browser’s own random numbers and differ each time.
A habit worth taking from this: if a run cannot be repeated, a surprising result cannot be examined.
The coast
The ground is a function that gives a height for every place. It has four parts: a slope from land to sea, a shoreline that bends, bumps in the mud, and tidal creeks (from world.js):
function base(x, z) {
const bend = noise.fbm(x * 0.02 + off[0], off[1], 2) * 9; // the shore bends
const zz = z - bend;
let h = -zz * 0.075 + 0.2; // land at -z, sea at +z
h += noise.fbm(x * 0.07 + off[2], z * 0.07, 3) * 0.35; // bumps in the mud
// Tidal creeks: noise stretched along the slope, channels where it crosses zero.
const wx = x + noise.fbm(x * 0.035, z * 0.035 + off[3], 2) * 10;
const c = noise.fbm(wx * 0.05 + off[1], z * 0.015 + off[0], 3);
const ch = Math.exp(-(c * c) / 0.0018);
const inland = 1 - smooth(1.4, 2.6, h);
h -= ch * inland * (0.6 + 0.9 * smooth(-15, 30, zz));
return h;
}noise.fbm is two-dimensional gradient noise of the kind Perlin introduced (Perlin 1985; the smoothing curve in the code is the one from Perlin 2002), summed over a few scales. The creeks are the one trick here. A noise field that is stretched along the slope crosses zero along long, winding lines. The code digs a channel wherever the field is close to zero, so the lines become creeks.
The water level is a sine wave, and a storm lifts it for a while (from main.js):
const TIDE = { mid: 0.05, amp: 0.8, period: 40 };
// …
const tideAt = (t) => TIDE.mid + TIDE.amp * Math.sin(t * 2 * Math.PI / TIDE.period);
// …
const waterNow = () => tideAt(simT) + SURGE * stormAmt();The tide takes 40 seconds and a day and night take 90. Neither stands for a real tide or day. Figure 3 shows a cut through one coast with the levels that matter in the rules.
Growing a tree
Each mangrove is grown by a recipe: a trunk that leans a little, prop roots that arch from the trunk down into the mud, and a crown in which every branch splits into a few shorter, thinner ones until leaf clumps end it (Figure 4).
The crown is one recursive function (from trees.js, shortened):
function branch(p, dir, len, rad, depth) {
const nC = depth === 0 ? 3 + Math.floor(rnd() * 2) : 2 + (rnd() < 0.45 ? 1 : 0);
const [u, w] = perpBasis(dir);
const phi0 = rnd() * Math.PI * 2;
for (let c = 0; c < nC; c++) {
const phi = phi0 + c / nC * Math.PI * 2 + (rnd() - 0.5) * 0.6;
const th = (depth === 0 ? 0.7 : 0.45) + rnd() * 0.35;
let d = V.add(V.mul(dir, Math.cos(th)), V.mul(V.add(V.mul(u, Math.cos(phi)), V.mul(w, Math.sin(phi))), Math.sin(th)));
d[1] += 0.12;
d = V.norm(d);
const L = len * (0.62 + rnd() * 0.22);
const end = V.add(p, V.mul(d, L));
// … the branch itself is drawn here as a tube …
if (depth + 1 < maxD) {
pts.push(end[0], end[1], end[2], G(gb), 0);
branch(end, d, L, rad * 0.62, depth + 1);
} else {
const s = (0.5 + rnd() * 0.35) * (0.6 + H * 0.12);
clump(out, end, s, rnd, G(0.82 + rnd() * 0.08), G(0.97), 2 + rnd() * 0.98);
if (!seedling) crowns.push(end);
}
}
}Each call picks how many children there are, spreads them around the parent’s direction, tilts them outward and a little upward, and makes each one shorter and thinner than its parent. When the depth runs out, a leaf clump ends the branch.
Describing the form of a tree by a few branching parameters goes back at least to Honda (1971). Growing plants by rewriting rules, the L-systems named after Lindenmayer, is the subject of The Algorithmic Beauty of Plants (Prusinkiewicz and Lindenmayer 1990; the first paper is Lindenmayer 1968). The toy is much simpler than either: it has no grammar, only this function.
Letting it grow in front of you
Every vertex of a tree carries two extra things: the point it grows out of, and the window of time in which it grows. The vertex shader slides it from one to the other (from shaders.js):
float f = aGrow.y > aGrow.x ? clamp((uGrow - aGrow.x) / (aGrow.y - aGrow.x), 0.0, 1.0) : 1.0;
f = f * f * (3.0 - 2.0 * f);
vec3 p = mix(aAnchor, aPos, f);The trunk has early windows, the roots follow, then the branches level by level, and the leaves come last. The forest a world starts with is sent to the graphics card once. While it grows, no vertex is sent again: the growth is driven by one changing number, uGrow (and the time moves the leaves in the wind).
Three looks from one geometry
There is only one geometry. The shader for ground, trees and animals computes three pictures of every pixel, ink on paper, flat low-poly shapes in fog, and glowing lines, and blends them. Two small tricks do most of the work (from shaders.js):
vec3 n = normalize(cross(dFdx(vPos), dFdy(vPos)));The mesh carries no normals. The shader asks how the position changes from one pixel to the next, across and down, and the cross product of the two is the direction the triangle faces. This gives flat facets for free.
float e = min(min(vBary.x, vBary.y), vBary.z);
float wire = lineAt(e, 1.1 * uDpr) * (1.0 - ground) * (1.0 - smoothstep(25.0, 60.0, dist));In leaf clumps and the animals’ bodies, each corner of a triangle carries one of the values (1,0,0), (0,1,0), (0,0,1). Inside the triangle they blend, and the smallest of the three says how close a pixel is to an edge. Trunks, roots and branches, and the animals’ thin parts such as legs, are tubes made of four-sided faces; their corners carry a variant of these values, so the diagonal of each face stays hidden. lineAt turns the distance into a line of even width on the screen:
float lineAt(float v, float widthPx) {
float d = abs(v) / max(fwidth(v), 1e-5);
return 1.0 - smoothstep(widthPx * 0.5 - 0.5, widthPx * 0.5 + 0.5, d);
}The same function draws the line where the water meets the ground (ink by day, amber at night). A sibling, gridLine, draws the height contours on the mud. At the end the three pictures are mixed:
vec3 w = styleWeights(h);
vec3 col = w.x * inkCol + w.y * poly + w.z * grid;styleWeights returns the mix for this pixel. By default it follows the time of day. In the other mode it follows the height above the water, so everything above the tide line is ink and everything below is glowing lines:
vec3 styleWeights(float y) {
if (uMode < 0.5) return uW;
{
float d = y - uWater;
float ink = smoothstep(0.02, 0.12, d);
float grid = smoothstep(0.02, 0.12, -d);
return vec3(ink, 1.0 - ink - grid, grid);
}
}Water, sky, rain and the points of light have their own small shaders that follow the same mix.
The fish: a school without a leader
The fish come first because their rules are the easiest to state. Each fish looks at the others within a short distance and does three things (Figure 6). These are the three rules known from Reynolds’ boids (Reynolds 1987).
In the code the three rules are three sums over the neighbours (from life.js):
for (let j = 0; j < n; j++) {
if (i === j) continue;
const g = fish[j], dx = g.x - f.x, dz = g.z - f.z, d2 = dx * dx + dz * dz;
if (d2 < 6.25) {
cnt++; ax += g.vx; az += g.vz; cx += g.x; cz += g.z;
if (d2 < 0.5) { sx -= dx / (d2 + 0.05); sz -= dz / (d2 + 0.05); }
}
}
let fx = sx * 0.6, fz = sz * 0.6;
if (cnt) { fx += (ax / cnt - f.vx) * 0.8 + (cx / cnt - f.x) * 0.4; fz += (az / cnt - f.vz) * 0.8 + (cz / cnt - f.z) * 0.4; }s pushes a fish away from any neighbour that is too close, a is the average velocity of the neighbours, and c is their middle. The toy adds a few more forces: turn where the water gets shallow, flee the heron, stay inside the world, a little random wobble, and a lowest and highest speed.
No fish knows about the school. The fish start in three loose groups, but nothing in the code keeps a group together or lines it up. That is what you see when all of them follow the rules, and it is the point of the example: a pattern at the level of the group that no line of code describes.
Every fish looks at every other fish, so the work grows with the square of their number. With at most 70 fish that is fine.
Crabs, a heron, mudskippers: small state machines
The other animals each have a state and a rule for changing it. The heron has three states:
A crab is in its hole or out of it. One line decides whether it wants to be out (from life.js):
const want = storm < 0.2 && W < c.bh - 0.06 && Math.hypot(c.x - heron.x, c.z - heron.z) > 4;No storm, the water below its hole, and the heron far away. Because the tide moves, the part of the shore with crabs on it grows downward as the water falls and shrinks again as it returns, without any code that says so.
A mudskipper picks, among a few random spots nearby, the one closest to the water’s edge and hops there. Each of the animals has one rule that you can read in the toy by tapping it.
This is what “agent-based” means in this article: many individuals, each with a state and a local rule, and no script for the whole. For how the approach is used in earnest, two entry points are Bonabeau (2002) on agent-based modelling of human systems and DeAngelis and Grimm (2014) on individual-based models in ecology.
The fireflies: falling into step
Each firefly is an oscillator: a phase that runs round and round, and a flash when it passes the top. Each one has its own pace, about three flashes in four seconds with a small spread. At night each one is also pulled a little toward the moment when the others flash on average. A population of oscillators coupled like this is known as the Kuramoto model (Kuramoto 1975; Strogatz 2000). The equations below are the model in its common textbook form; they were not checked against the full text of these two works.
For firefly \(k\) with phase \(\theta_k\) and pace \(\omega_k\), the model is
\[ \frac{d\theta_k}{dt} = \omega_k + \frac{K}{N}\sum_{j=1}^{N}\sin(\theta_j - \theta_k). \]
Written like this, every firefly needs to look at every other one. But the sum can be replaced by two numbers for the whole swarm. Define \(r\) and \(\psi\) by
\[ r\,e^{i\psi} = \frac{1}{N}\sum_{j=1}^{N} e^{i\theta_j}, \]
where \(i\) is the imaginary unit. So \(r\) says how much the swarm is in step (0 not at all, 1 fully) and \(\psi\) is the phase of the average. Then the same equation reads
\[ \frac{d\theta_k}{dt} = \omega_k + K\,r\,\sin(\psi - \theta_k). \]
That is what the code does, one small step of time per frame: one pass to get \(r\) and \(\psi\), one pass to move every phase (from life.js):
let sx = 0, sy = 0;
for (const f of flies) { sx += Math.cos(f.ph); sy += Math.sin(f.ph); }
const n = flies.length || 1, order = Math.hypot(sx, sy) / n, psi = Math.atan2(sy, sx);
const K = 0.9 * smooth(0.2, 0.8, night);
let flashes = 0;
for (const f of flies) {
const before = Math.floor(f.ph / 6.2832);
f.ph += (f.w + K * order * Math.sin(psi - f.ph)) * dt;
if (Math.floor(f.ph / 6.2832) > before) flashes++;
// … where it hovers and how bright it is …
}The pull grows with \(r\). When the swarm is out of step, nobody is pulled much. Once a few happen to agree, they pull harder, more join, and the pull grows again. Below a certain strength of coupling this never gets going. Figure 8 shows it with the toy’s own update rule: 110 fireflies with the toy’s spread of paces, started out of step, for three values of \(K\), each held constant for 60 seconds. The figure shows one random start. Over 200 different random starts, \(r\) averaged over the last ten seconds lies between 0.03 and 0.15 without coupling, between 0.07 and 0.28 with \(K = 0.2\) (nine runs in ten, in both cases), and between 0.98 and 0.99 with \(K = 0.9\), the toy’s value at full night. This is the rule on its own, not a recording of a toy night: in the toy the pull fades in at dusk, and a night is over in well under a minute. The onset of synchronization in this model is the subject of Strogatz (2000).
At nightfall the toy sets all phases at random again, so every night starts out of step. In the sound, two bells mark each common beat, louder the more the fireflies flash in step.
Buck and Buck (1968) studied how real fireflies flash in synchrony, and Mirollo and Strogatz (1990) analysed the synchronization of pulse-coupled oscillators. The toy’s version is not a model of any firefly.
The mud: a coast that changes
This is the nearest thing to a landscape model in the toy, and the most made up. Over the height function lies a grid of changes. With every toy year each cell in the reach of the waves loses a little mud if no tree is near and gains a little if trees are near (Figure 9).
The whole rule is one loop over the grid (from coast.js):
for (let k = 0; k < N; k++) {
const h = h0[k] + delta[k];
if (h < -1.6 || h > 1.0 || dyke[k] > 0.2) continue;
const q = Math.min(1, scour[k]), s = Math.min(1, shelter[k]) * (1 - q);
const reach = smooth(-1.5, -0.7, h) * (1 - smooth(0.2, 0.7, h)); // where the waves work
let d = -0.022 * dy * (1 - s) * (1 + 2 * q) * reach; // bare mud goes
d += 0.035 * dy * s * smooth(-0.9, -0.3, h) * (1 - smooth(0.45, 0.8, h)); // held mud builds up
if (storm) d -= storm * (1 - 0.7 * s) * (1 + 2 * q) * reach;
delta[k] = clamp(delta[k] + d, -2.5, 0.6);
}shelter is a field that the trees paint around themselves, and scour is a field around a wall of earth. A storm takes mud everywhere in the waves’ reach, less among trees. Around a wall the mud goes faster, and trees there hold none of it. When years pass, changes on ground below about the high-tide line also even out with their neighbours, so a hole in the bed fills and the ground around it sinks. A tree whose ground has dropped too far falls over.
There is a feedback loop in this. Trees hold mud, mud in the right band lets seedlings come up, and seedlings become trees. Take the trees away at one place and the loop runs the other way. The rules say that trees hold mud. They do not say where the edge of the forest will be in thirty years; whether it moves seaward or gives way comes out of the loop.
Cells in a row, each updated step by step by a fixed rule from the values of its neighbours, are called a cellular automaton (Wolfram 1983). The same works on a grid; Conway’s Game of Life (Gardner 1970) is one. The toy’s grid is only a loose relative: its cells hold amounts, not on and off, and trees and walls act on them from outside.
Sound that follows the world
Every sound is computed. Nothing is recorded.
The sound reads the same record of the world as everything else. The water, for example, gets louder and brighter with the tide, with each wave that washes in, and with a storm (from sound.js):
const wash = Math.pow(0.5 + 0.5 * Math.sin(env.t * 0.75), 2); // a wave washes in every few seconds
water.gain.setTargetAtTime(0.08 + 0.08 * tide + 0.08 * wash + 0.3 * env.storm, t, 0.3);
waterF.frequency.setTargetAtTime(380 + 300 * tide + 250 * wash + 700 * env.storm, t, 0.3);A slow chord changes every twelve seconds and gets darker at night. A bell melody walks up and down one five-note scale. The animals send events (a heron’s strike, the fireflies’ common beat) and the sound answers them.
A link that plays the coast again
Because the coast comes from the name, a link can carry it. What the visitor did to the coast is added as a short list, and opening the link does it all again.
?seed=salt-heron-42&c=m.8Dgneh.8Gl3km.8S
The part after c= reads: the coast is in toy year 22 (m in base 36). In year 8 a wall (D) was built at the place gneh, sand was taken (G) at l3km, and there was a storm (S). A place is four characters, two for each direction, in steps of a sixteenth of a toy unit (from main.js):
const enc = (v) => Math.round((clamp(v, -40, 40) + 40) * 16).toString(36).padStart(2, '0');
const dec = (s) => parseInt(s, 36) / 16 - 40;Two things make the replay come out the same. Every action is first rounded to this grid, live as well as on replay. And the dice for new seedlings come from the world’s name and the year, not from the clock:
const rnd = mulberry32((hashString(seedName) ^ Math.imul(Y, 0x9e3779b1)) >>> 0);The replay runs in whole years and takes each storm at once, so the result can differ a little from what was played live. On another device the coast is similar but not identical, because the number of trees and the fineness of the grid follow the device.
Staying fast on a phone
Three things keep the frame rate up.
Instancing. One crab is a small mesh. All crabs are drawn in a single call, with one short record per crab for where it is, which way it faces and how big it is. The same goes for fish and mudskippers.
Detail by device. The toy picks one of three levels when it starts:
| low | medium | high | |
|---|---|---|---|
| ground grid (cells per side) | 96 | 128 | 176 |
| full-grown trees at the start | 20 | 30 | 46 |
| crabs | 30 | 50 | 80 |
| fish | 30 | 48 | 70 |
| fireflies | 60 | 110 | 180 |
| plankton points | 250 | 450 | 800 |
Resolution that gives way. If the frame rate drops under 30, the picture is drawn with fewer pixels and scaled up (from main.js):
if (fps < 30 && pr > 0.6 && now - lastAdapt > 2500) { pr = Math.max(0.6, pr * 0.85); lastAdapt = now; }The toy also stops when the tab is hidden, and shows a still picture with a play button for visitors who have asked their device for less motion.
From toy to model
What would have to change before any of this could say something about a real coast?
Write the model down so others can rebuild it. There is a standard protocol for describing individual-based and agent-based models (Grimm et al. 2006), known as the ODD protocol and updated twice since (Grimm et al. 2020).
Tie the rules to observations. Grimm et al. (2005) describe a general strategy for this, which they call pattern-oriented modelling.
Use what is known about the system. Models of mangrove forests exist. Berger and Hildenbrandt (2000) model the spacing, ageing and neighbourhood competition of mangrove trees; Berger et al. (2008) review the advances and limits of individual-based models of mangrove forests. For the mud, Woodroffe et al. (2016) review mangrove sedimentation and sea-level rise, Fagherazzi et al. (2012) review numerical models of salt marsh evolution, Mazda et al. (1997) study mangroves as protection from waves on a coast in Vietnam, and Winterwerp et al. (2013) define what the rehabilitation of an eroding mangrove-mud coast requires. For the Mekong Delta, Anthony et al. (2015) link rapid erosion to human activities. The toy’s rules were not derived from any of these papers. They are where I would start reading before writing a rule that claims anything.
Use a framework instead of hand-written loops once the question is serious: NetLogo (Wilensky 1999), Mesa in Python (Kazil, Masad, and Crooks 2020), Agents.jl in Julia (Datseris, Vahdati, and DuBois 2024).
What the toy leaves out
No sediment budget: mud appears and vanishes. No wave physics, no currents, no salinity. One kind of tree, with no competition for light or space beyond a minimum distance. Animals do not eat, breed or die. All rates and thresholds were set without data, to look right. The toy year has no relation to a real year.
A reading guide
Agents and individuals. The boids paper (Reynolds 1987); a model of segregation (Schelling 1971) and artificial societies grown from the bottom up (Epstein and Axtell 1996); methods and overviews (Bonabeau 2002; DeAngelis and Grimm 2014); describing and grounding a model (Grimm et al. 2005, 2006, 2020).
Synchrony. The model (Kuramoto 1975), the onset of synchronization in it (Strogatz 2000), real fireflies (Buck and Buck 1968) and pulse-coupled oscillators (Mirollo and Strogatz 1990).
Growing forms from rules. Trees and plants (Honda 1971; Lindenmayer 1968; Prusinkiewicz and Lindenmayer 1990), noise (Perlin 1985, 2002), and the chemical basis of form (Turing 1952).
Artificial life. The Game of Life (Gardner 1970), evolved virtual creatures (Sims 1994), Lenia (Chan 2019), and two overviews (Langton 1995; Bedau 2003).
Mangroves and muddy coasts, the real ones. (Berger and Hildenbrandt 2000; Berger et al. 2008; Mazda et al. 1997; Fagherazzi et al. 2012; Winterwerp et al. 2013; Anthony et al. 2015; Woodroffe et al. 2016).
Frameworks. (Wilensky 1999; Kazil, Masad, and Crooks 2020; Datseris, Vahdati, and DuBois 2024).
What comes next
More small worlds of this kind are planned, each with an article like this one that takes it apart.


