Three.js From Zero · Article s16-06
Reaction–Diffusion — Growing Leopard Spots on the GPU
Gray-Scott on ping-pong render targets: the season's first shader piece — paint chemical V with your mouse and watch coral, mitosis, and leopard spots grow at 512×320, twelve steps a frame. Part of the MasterAllArts Creative 3D Roadmap.
Part of the MasterAllArts Creative 3D Roadmap .
Season 16 · Article 06 · Beautiful Math
In 1952, Alan Turing proposed that two chemicals — one feeding, one killing, both spreading — could paint every coat pattern in the animal kingdom. He never saw it run. You're about to: 163,840 simulation cells updated a dozen times per frame, entirely on your GPU. This is the season's first shader article, and reaction–diffusion is the best possible reason to learn render targets.
Draw on it. Click and drag anywhere on the canvas — you're injecting chemical V, and the system grows your strokes into coral. Then switch presets: mitosis makes every spot split in two like dividing cells; worms writhes; waves never settles. The feed/kill sliders move you through the famous Gray–Scott parameter map — most of it is dead (all U or all V), and every pattern you've ever seen lives on a one-percent-wide coastline between the two extinctions.
The chemistry, minus the lab
The Gray–Scott model tracks two concentrations per cell. U is food. V is the organism: it consumes U to make more of itself (one U + two V → three V). U is pumped in everywhere at the feed rate; V is removed everywhere at the kill rate. Both diffuse — U twice as fast as V. Per cell, per tick:
u' = u + (Du·∇²u − u·v² + feed·(1−u))
v' = v + (Dv·∇²v + u·v² − (feed+kill)·v)
The u·v² term is the engine: V grows where V already is (autocatalysis), but
starves where it has eaten the U — so spots stop growing at exactly the size where diffusion
can resupply their border. Pattern is what stalemate looks like.
My old atlas version runs this on the CPU — a 160×100 grid in a quadruple-nested JavaScript loop, and that's roughly the ceiling before the main thread chokes. But look at the math: every cell update reads only its neighbors and writes only itself. No cell waits for any other. That's not a loop — that's a fragment shader.
Step 0 — The mental shift
Everything in this article is three re-labelings:
- A texture is a 2D array of floats. Forget "image" — channels R and G will store u and v. Nobody ever sees this texture.
- A fragment shader is the body of a per-cell loop that the GPU runs for every cell simultaneously. You write the inside of the loop; the GPU is the loop.
- A render target is how you make the GPU write the loop's output into a texture instead of the screen.
const simTarget = () => new THREE.WebGLRenderTarget(512, 320, {
type: THREE.HalfFloatType, // concentrations need fractions, not bytes
format: THREE.RGBAFormat,
});
let read = simTarget(), write = simTarget();
Step 1 — A quad that ignores the camera
To run a shader once per cell, draw one rectangle that covers the screen exactly, with a vertex shader that refuses to do any 3D:
const vertexShader = /* glsl */`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = vec4(position.xy, 0.0, 1.0); // no camera, no matrices
}`;
const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), simMaterial);
A plane spanning −1..1 in clip space is the screen. This one idiom — fullscreen quad plus camera-less vertex shader — is the foundation of every post-processing effect, every GPGPU sim, every "shader art" piece on the internet. Learn it once here.
Step 2 — Ping-pong: why two targets
A GPU cannot read from and write to the same texture in one pass (every cell runs at once — half your neighbor reads would see new values, half old, differently every frame). So: two targets, swap roles every step.
function step() {
simMaterial.uniforms.uTex.value = read.texture;
renderer.setRenderTarget(write);
renderer.render(simScene, camera);
[read, write] = [write, read]; // the entire trick
}
// run 8–24 of these per displayed frame — they're nearly free
setRenderTarget(null). After the sim
steps, you must point the renderer back at the screen before the display pass — otherwise
your final render quietly disappears into the last render target and the canvas stays
black. If a GPGPU demo shows nothing and logs nothing, this is the first thing to check.
Step 3 — The simulation shader
The whole CPU loop becomes twelve lines of GLSL. The Laplacian — "how different am I from my surroundings" — is a 3×3 stencil: center −1, edges 0.2, corners 0.05:
vec2 c = texture2D(uTex, vUv).rg; // .r = u, .g = v
vec2 lap = -c;
lap += 0.20 * texture2D(uTex, vUv + vec2( uTexel.x, 0)).rg;
lap += 0.20 * texture2D(uTex, vUv + vec2(-uTexel.x, 0)).rg;
lap += 0.20 * texture2D(uTex, vUv + vec2(0, uTexel.y)).rg;
lap += 0.20 * texture2D(uTex, vUv + vec2(0, -uTexel.y)).rg;
lap += 0.05 * (texture2D(uTex, vUv + uTexel).rg + /* …3 more corners */);
float uvv = c.r * c.g * c.g;
float u2 = c.r + (1.0 * lap.r - uvv + uFeed * (1.0 - c.r));
float v2 = c.g + (0.5 * lap.g + uvv - (uFeed + uKill) * c.g);
gl_FragColor = vec4(clamp(u2, 0.0, 1.0), clamp(v2, 0.0, 1.0), 0.0, 1.0);
uTexel is 1/resolution — one cell's width in UV coordinates. The
diffusion rates (1.0 and 0.5) are baked in; feed and kill arrive as uniforms, which is what
makes the sliders free: changing a uniform costs nothing, the shader never recompiles.
Step 4 — The display pass is a colormap
The sim texture stores chemistry, not color. A second, dumber shader reads V and maps it through a gradient — dark void → ultraviolet → ember → white-hot rim:
float v = texture2D(uTex, vUv).g;
vec3 col = uBg;
col = mix(col, uMid, smoothstep(0.05, 0.22, v));
col = mix(col, uHot, smoothstep(0.22, 0.38, v));
col = mix(col, vec3(1.0), smoothstep(0.38, 0.55, v));
gl_FragColor = vec4(col, 1.0);
Separating simulation from presentation is the same discipline as the season's "color is data" pattern, enforced by architecture: you can swap the palette, or render the field as 3D terrain, without touching the chemistry.
Step 5 — Painting with a uniform
The brush is four floats: uBrush = (x, y, radius, on). The sim shader checks
each cell's distance to the brush and injects V inside it. Pointer events update the uniform;
the GPU does the painting. No readbacks, no CPU pixel pushing — input flows down to
the GPU and never comes back.
if (uBrush.w > 0.5 &&
length((vUv - uBrush.xy) * vec2(uAspect, 1.0)) < uBrush.z) {
v2 = max(v2, 0.9);
}
The feed/kill map
- coral (f 0.0545, k 0.0620) — labyrinthine growth that fills the canvas like brain coral.
- mitosis (f 0.0367, k 0.0649) — spots grow, pinch, and divide. The most biological thing a GPU will ever do for you.
- spots (f 0.0300, k 0.0620) — stable leopard rosettes.
- worms (f 0.0780, k 0.0610) — stripes that crawl but never join.
- waves (f 0.0140, k 0.0450) — perpetual motion; patterns that erase and rewrite themselves forever.
These five points are a few thousandths apart. That fragility is the lesson Turing was after: you don't need a different mechanism for every pattern in nature — one mechanism, barely tuned, covers leopards, zebrafish, seashells, and fingertips.
The skeleton
<script type="importmap">
{ "imports": {
"three": "https://unpkg.com/three@0.170.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.170.0/examples/jsm/" } }
</script>
<script type="module">
import * as THREE from 'three';
// two HalfFloat render targets (Step 0)
// fullscreen quad + camera-less vertex shader (Step 1)
// per frame: N× { sim pass → swap } (Steps 2–3)
// setRenderTarget(null) → display pass (Step 4)
</script>
Next: S16-07 — The Mandelbrot Set. The most famous object in mathematics, as a smooth-colored, infinitely zoomable fragment shader — and why the zoom eventually hits a floating-point wall.