Creative Coding From Zero · Episode 16

Systems Finale

Systems Finale is Episode 16 of Creative Coding From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 16 · Creative Coding From Zero

Here is the whole season in one piece of glass. Thousands of tiny agents pour across a field, each one blind except for three little whiskers that taste the ground ahead. They steer toward wherever the taste is strongest, and as they walk they leave a faint trail behind them. The trail spreads a little, fades a little — and then the next agent smells that and follows it. Nobody is in charge. Nobody drew the map. But within a few seconds the blank field knots itself into glowing veins, hubs, and bridges: a living network that flocks, flows, and grows itself while you watch.

This is Physarum — the slime mold — reduced to its essence and run on a raw 2D canvas, no GPU, no libraries. It braids together everything Season 2 was about: the flocking instinct to move with your neighbors, the flow-field idea of agents reading a vector field, and the reaction-diffusion trick of a tiny chemical grid that diffuses and decays. Stitch those three together and you get something none of them is alone: an ecosystem that remembers where it has been, reinforces what works, and forgets the rest. Every seed grows a different organism. Let's build it in six stages, and then keep the one you love with a button.

0 fps
it evolves on its own — try the stage dropdown
canvas 2D · 7,000 agents
The full ecosystem — sense, deposit, diffuse, flock. A living network, unique per seed.

What you're looking at

Two things share the screen, and the trick is that they talk to each other in a loop. The first is a field: a small grid of numbers — think of it as an invisible layer of chemical (the biologists call it a pheromone) soaked into the ground. The second is a swarm of agents: each one is just a position and a heading, a dot that knows which way it's pointing. Every frame, the agents read the field in front of them and turn toward the strongest reading, then step forward and smear a little chemical into the field where they land. Then the field itself blurs and dims. That's the entire machine: sense → move → deposit → diffuse → decay, sixty times a second.

Like the reaction-diffusion episode, the field does not run at the canvas's pixel resolution — it runs on a modest grid (around 320×200 cells) stored in flat Float32Arrays, and that little image is upscaled to fill the frame. That separation — simulate small, draw big — is the whole reason thousands of agents and a diffusing field hold 60fps in plain JavaScript. The stage dropdown peels the system open one layer at a time: the bare field, then sensing, then depositing, then the diffuse-and-decay that makes networks actually emerge, then a pinch of flocking, then the full colored ecosystem you can keep.

Stage 1 — The field

Start with the substrate, alone. The field is one number per cell: how much trail- chemical is sitting there right now. We seed it with a faint, organic wash of fbm noise so it isn't dead flat — just enough low cloud that the agents, once they arrive, have something to nose toward instead of a perfectly uniform void. This stage runs the field's own life with no agents at all: it simply decays, dimming frame by frame, so you watch the seeded cloud breathe out and fade. It's frame zero of the world — the empty stage before the dancers walk on.

Why a grid and not, say, a list of trail segments? Because a grid gives us two superpowers almost for free: any agent can read or write any spot in O(1) by indexing y * W + x, and "spreading" the chemical is just blurring an image — a thing computers are extremely good at. The grid is the shared memory the whole colony writes notes into.

Stage 2 — Agents that sense and steer

Now release the agents, but let them only look, not yet leave marks. This is the heart of Physarum, and it's beautifully simple. Each agent has three sensors: one pointing straight ahead, and two angled off to the left and right. Each sensor reaches a short distance out in front of the agent and reads the field value at that spot. Then the agent compares the three readings and makes one decision:

  • If the center sensor smells the most, keep going straight.
  • If the left sensor wins, turn a little left.
  • If the right sensor wins, turn a little right.
  • If it's a tie or the area is blank, jitter randomly so the colony keeps exploring.

That's it. No pathfinding, no goals, no memory beyond the field itself. In this stage, with no trails being laid down, the agents just wander and gently herd toward the faint noise cloud — a shimmer of motion over the substrate. The sensor geometry (how far ahead, how wide the angle) is the single biggest lever on what patterns eventually grow; we'll come back to that in the pitfalls.

Stage 3 — Agents deposit trails

Flip on depositing. Now, after each agent steps forward, it adds a dab of chemical to the field cell it landed on. Suddenly the agents aren't just reading the world — they're writing it, and reading what they (and everyone else) wrote a moment ago. This is the feedback loop that turns a swarm into a system. The first agent to stumble across a promising direction lays a faint trace; the next agent senses that trace and follows, deepening it; soon a faint trace is a highway. Watch this stage with no diffusion yet and you'll see bright, jagged scribbles pile up — the raw deposits, sharp and noisy, like a thousand pens scratching the same page. It's alive, but it's a mess. The smoothing comes next.

Stage 4 — Diffuse and decay the field

This is the stage where networks are born, and it's two tiny operations on the grid. Diffuse: blur the field a touch each frame — every cell mixes with its neighbors — so a sharp scratch softens into a smooth ridge that nearby agents can sense from a little farther away. Decay: multiply the whole field by a number just under 1 (say 0.94) so old, unreinforced trails fade toward black. Together they perform a quiet, ruthless natural selection: a path that agents keep walking gets re-deposited faster than it decays, so it survives and brightens; a path nobody reuses fades to nothing. The jagged scribbles of Stage 3 resolve, before your eyes, into clean glowing veins with junctions and loops. This is the moment the piece stops looking like noise and starts looking like an organism.

The balance between deposit and decay is everything, and the living networks occupy a narrow band. Too much decay (or too little deposit) and the trails starve and the whole thing dims to a faint haze. Too little decay (or too much deposit) and every cell saturates into a solid glowing slab with no structure. The demo ships with defaults parked in the sweet spot; the two sliders let you walk to the edges and watch it die both ways.

Stage 5 — Flocking influence

The agents so far are loners — each follows the chemical and ignores its neighbors. Borrow one rule from Episode 09's boids: alignment, the urge to head the same way as the agents around you. We keep it cheap by reusing the field's grid as a spatial structure — but instead of a second grid, we lean on the trail itself: where many agents have recently passed, the field's local gradient already encodes a shared direction, and nudging each agent to follow that gradient (not just the brightest single sensor) makes neighbors fall into step. The visible result is that the veins stop being scratchy and start to stream — agents brush along established channels in coherent currents, like traffic finding lanes. The network gets sleeker, more directional, more like flowing water carving a delta.

Stage 6 — The full ecosystem

Everything at once, dressed for the frame. The field's value at each cell is mapped through a cosine palette — the same vivid, harmonious colormap from Episode 07 — so the faint background glows in one hue and the bright trunk-lines blaze in another, with the transition doing the work of light and shadow. Pick a palette from the dropdown (bioluminescent teal, volcanic magma, earthy spore, icy arctic), hit seed / regenerate to grow a completely different organism, and when one stops you in your tracks, save PNG. This is the frame-worthy stage and the whole point of the season — start here, let it evolve, then go back and understand exactly how it works.

How the code works

The piece is one tight loop over four small pieces. We keep the field in two flat typed arrays (read one, write the other, then swap — the same ping-pong as reaction-diffusion), and the agents in three parallel arrays for cache-friendly speed: ax, ay (position) and ah (heading angle).

// The field: one float per cell, on a MODEST grid (not canvas res).
const W = 320, H = 200, N = W * H;
let field  = new Float32Array(N);     // current chemical level
let fieldB = new Float32Array(N);     // scratch for the blur

// The agents: structure-of-arrays, not an array of objects.
const ax = new Float32Array(MAX);       // x position (grid space)
const ay = new Float32Array(MAX);       // y position
const ah = new Float32Array(MAX);       // heading, radians

First, the star of the show: sense and steer. We sample the field at three points ahead of the agent — left whisker, center, right whisker — and turn toward whichever is strongest. senseDist and senseAngle are the sensor geometry that shapes everything:

// Read the field at one sensor: a point `dist` ahead at heading `a`.
function senseAt(x, y, a, dist) {
  let sx = (x + Math.cos(a) * dist) | 0;
  let sy = (y + Math.sin(a) * dist) | 0;
  sx = ((sx % W) + W) % W;  sy = ((sy % H) + H) % H;   // wrap (torus)
  return field[sy * W + sx];
}

// Three whiskers: ahead-left, ahead, ahead-right. Turn toward the strongest.
const c = senseAt(x, y, h,              senseDist);   // center
const l = senseAt(x, y, h - senseAngle, senseDist);   // left
const r = senseAt(x, y, h + senseAngle, senseDist);   // right

if (c > l && c > r)        { /* center wins: go straight */ }
else if (l > r)            h -= turn;          // steer left
else if (r > l)            h += turn;          // steer right
else                      h += (rnd() - 0.5) * turn * 2;  // blank → wander

Second, deposit. After steering, the agent walks one step forward (wrapping at the edges so the world is a seamless torus) and adds chemical to the cell it lands on. In Stage 5 we mix a touch of the local field gradient into the heading first — that's the cheap "alignment" that makes agents stream along shared channels:

// Step forward along the (possibly steered) heading, then deposit.
x += Math.cos(h) * speed;
y += Math.sin(h) * speed;
x = ((x % W) + W) % W;   y = ((y % H) + H) % H;        // toroidal wrap

const idx = (y | 0) * W + (x | 0);
field[idx] += deposit;                                  // leave a trail
if (field[idx] > 255) field[idx] = 255;             // keep it bounded

ax[i] = x;  ay[i] = y;  ah[i] = h;                      // write back

Third, diffuse + decay the field. A 3×3 box blur spreads the chemical to neighbors, and a single multiply fades everything. We read from field into fieldB, then swap — never blur a grid in place, or later cells read half-updated neighbors and the texture corrupts:

// Blur (spread) + multiply (decay), reading field → fieldB, then swap.
for (let y = 0; y < H; y++) {
  for (let x = 0; x < W; x++) {
    const xm = (x - 1 + W) % W, xp = (x + 1) % W;
    const ym = (y - 1 + H) % H, yp = (y + 1) % H;
    // average of the 3×3 block = one cheap blur tap
    const sum =
      field[ym*W+xm] + field[ym*W+x] + field[ym*W+xp] +
      field[y *W+xm] + field[y *W+x] + field[y *W+xp] +
      field[yp*W+xm] + field[yp*W+x] + field[yp*W+xp];
    fieldB[y*W+x] = (sum / 9) * decay;            // blur, then fade
  }
}
[field, fieldB] = [fieldB, field];                       // ping-pong swap

Fourth, the compose loop + colormap: the small field grid → an ImageData → upscaled onto the canvas, exactly as in Episode 11. We walk the grid once, push each cell's value through the cosine palette, write four bytes, then a single drawImage stretches the tiny bitmap to fill the frame with smoothing on so the veins look like silk:

// One ImageData sized to the FIELD grid (W×H), upscaled once per frame.
function render() {
  const px = img.data;
  for (let i = 0; i < N; i++) {
    const t = Math.min(1, field[i] / 60);     // value → [0,1]
    const c = cosPalette(t, PA, PB, PC, PD);  // → [r,g,b] bytes
    const j = i * 4;
    px[j] = c[0]; px[j+1] = c[1]; px[j+2] = c[2]; px[j+3] = 255;
  }
  sctx.putImageData(img, 0, 0);              // fill the small offscreen
  ctx.imageSmoothingEnabled = true;
  ctx.drawImage(scratch, 0, 0, cw, ch);      // upscale to the big canvas
}

And that is the entire ecosystem. A field, three whiskers, a dab of chemical, a blur, a fade, a palette. Everything else is bookkeeping — and yet from those five lines of rule a whole living network organizes itself, every seed a different creature.

Common pitfalls

  • Simulating the field at canvas resolution. The number-one killer, same as reaction-diffusion. A 1600×1000 canvas is 1.6 million cells to blur every frame, on top of moving the agents — fps falls off a cliff. Keep the field on a modest grid (here ~320×200 ≈ 64k cells) in Float32Arrays, and upscale the rendered result with one drawImage. It looks just as good and runs a hundred times faster.
  • Sensor geometry off the sweet spot. The senseDist (how far ahead the whiskers reach) and senseAngle (how wide they splay) are what decide whether you get fine lace, chunky veins, or no structure at all. Sensors too short and agents can't "see" trails to follow — they wander and nothing coheres. Too long and everything smears into mush. Tune these two before you tune anything else; they matter more than agent count.
  • Deposit/decay out of balance. Living networks occupy a narrow band. Too much decay or too little deposit and the trails starve to a faint haze; too little decay or too much deposit and every cell saturates into a solid glowing slab with no veins. Ship good defaults (this demo does) and only nudge from there — it's easy to fall off either edge.
  • Blurring the field in place. If you write a blurred cell back into the same array you're sampling neighbors from, later cells in the loop read a mix of old and new values and the texture corrupts into drifting stripes. Read from field, write into fieldB, then swap — the ping-pong is mandatory.
  • Agent count vs fps. Each agent does three field reads (sensing) and one write (deposit) per frame; the field blur is a separate fixed cost. Doubling agents roughly doubles the agent cost but doesn't touch the blur, so there's a comfortable ceiling. The slider caps where 60fps holds on a typical laptop; push past it on purpose to feel the cost, and watch the fps counter.
  • Math.random() in the art path. Breaks reproducibility. All the per-agent jitter and the seeded noise cloud go through the shared mulberry32 stream, so a given seed grows the exact same organism every time — which is what makes seed / regenerate meaningful and the piece testable.

Exercises

  1. Two species. Give the colony two kinds of agent that deposit into two separate fields and sense only their own — but let each one's movement be slightly repelled by the other's trail. Render the two fields through two different cosine palettes (one into the warm channels, one into the cool) and watch territories, borders, and braided interference appear that a single species can never produce.
  2. Obstacles in the field. Add a boolean "wall" mask: cells the agents can't enter and that hold no chemical. Stamp some shapes (a circle, your initials, a maze) into the mask and let the network route around them. Slime mold famously solves mazes and reproduces transit maps this way — you'll watch it find the efficient paths on its own.
  3. Record a seamless loop. Let the system settle for a few hundred frames, then capture N frames with canvas.toDataURL (or grab the canvas with a screen recorder). Because the field is on a wrapping torus and the system reaches a slow steady state, a well-chosen window loops almost seamlessly — a hypnotic GIF of a network breathing. (Real export tooling is Season 3, Episode 23.)

What's next

That closes Season 2 — Simulation & Systems. Over eight episodes you went from a single particle to whole emergent worlds: flocking boids, cellular automata, reaction-diffusion, Verlet physics, tiling, wave-function collapse, differential growth — and now an ecosystem that fuses flow, flock, and growth into one self-organizing organism. You can take any "what if a thousand simple things followed one rule" idea and make it breathe on a blank canvas.

Season 3 — Tools & Frontiers is about reach and polish: picking up p5.js and seeing exactly what it wraps; making art for a pen plotter in crisp SVG; driving visuals from sound; carrying the toolkit into generative 3D with Three.js; and finally pushing the whole field and swarm onto the GPU as generative shaders, where a million agents run in real time. Everything you built by hand this season is about to get faster, sharper, and louder. Bring a seed you love — we'll be back.