Three.js From Zero · Article s16-01
Lorenz Attractor — 20,000 Particles Falling Into Chaos
20,000 particles fall onto the most famous strange attractor in mathematics — live, in 3D, with the chaos knobs exposed. Part of the MasterAllArts Creative 3D Roadmap.
Part of the MasterAllArts Creative 3D Roadmap .
Season 16 · Article 01 · Beautiful Math
Three differential equations from a 1963 weather paper, integrated live for twenty thousand particles at once. Every particle starts somewhere random — and every single one collapses onto the same glowing butterfly. This is the piece that opens Beautiful Math: a season where we take famous mathematical systems and render them the way they deserve.
Drag to orbit. Hit rescatter and watch the cloud of random points get pulled onto the attractor in about two seconds — that collapse is the whole reason this object is called an attractor. Then slowly drag rho down below ~24.7 and watch chaos die: every particle spirals into one of two fixed points and the butterfly dissolves. Drag it back up and chaos reignites.
Three equations, infinite surprise
Edward Lorenz was simulating convection rolls in the atmosphere when he found that his stripped-down model — just three coupled ordinary differential equations — never settled down and never repeated:
x' = σ(y − x)
y' = x(ρ − z) − y
z' = xy − βz
The classic parameters are σ = 10, ρ = 28, β = 8/3. There is no randomness anywhere in those three lines. The motion is fully determined by the starting point — and yet two starts that differ by a millionth diverge into completely different futures within seconds. That's deterministic chaos, and the butterfly shape it traces is bounded, infinitely detailed, and never self-intersecting.
In the 2D canvas version of this system (the one in my old math atlas), you integrate one trajectory and plot 20,000 points of its history. That's fine for a thumbnail. But the Lorenz system lives in 3D, and the honest way to show an attractor attracting is to give it thousands of victims at once.
Step 1 — Simulation state vs. GPU buffer
The mental model for every particle system in this season: you own two copies
of the world. Plain JavaScript arrays hold the simulation state — the real
mathematical coordinates. A BufferAttribute holds the render state —
whatever you want the GPU to draw this frame. Each frame you advance the math, then copy
math → buffer with any remapping you like.
const xs = new Float32Array(count);
const ys = new Float32Array(count);
const zs = new Float32Array(count);
const positions = new Float32Array(count * 3); // what the GPU sees
const colors = new Float32Array(count * 3);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('color', new THREE.BufferAttribute(colors, 3));
Why the split? Because Lorenz coordinates are a terrible camera target: the attractor floats around z ≈ 27, not the origin. When we copy into the buffer we re-axis it so the butterfly stands upright and centered:
positions[i * 3 + 0] = xs[i]; // Lorenz x → scene x
positions[i * 3 + 1] = zs[i] - 27; // Lorenz z → scene y, recentered
positions[i * 3 + 2] = ys[i]; // Lorenz y → scene z
Step 2 — Euler integration, the honest way
The derivative tells you where each particle wants to go; Euler integration just takes a small step in that direction. Per particle, per frame:
const dt = 0.003 * params.speed;
for (let s = 0; s < SUBSTEPS; s++) {
const dx = params.sigma * (y - x);
const dy = x * (params.rho - z) - y;
const dz = x * y - params.beta * z;
x += dx * dt;
y += dy * dt;
z += dz * dt;
}
Three substeps of dt = 0.003 per frame looks smooth and stays stable across the whole slider range. Euler is the least accurate integrator there is — and for art, that's fine. We're not forecasting weather; we're drawing its ghost. (If you ever need trajectories that stay faithful over long times, the upgrade path is Runge–Kutta 4 — same shape, four derivative evaluations per step.)
NaN and your screen is
black with no error. That's why the demo clamps speed and re-scatters any particle whose
coordinates blow past a sanity bound. If your particle system ever "just disappears," check
for NaN first.
Step 3 — Color is data
A white butterfly is already nice. But the system hands you a free second channel: the speed of each particle (the magnitude of that derivative vector you already computed). Particles whip around the outer wings and crawl through the center crossover — so map slow → deep blue, fast → hot orange, and the attractor paints its own anatomy:
const speed = Math.sqrt(dx * dx + dy * dy + dz * dz);
const t = Math.min(1, speed / 320);
const c = slowColor.clone().lerp(fastColor, t);
colors[i * 3 + 0] = c.r;
colors[i * 3 + 1] = c.g;
colors[i * 3 + 2] = c.b;
This is the single most reusable trick in data-driven art: never invent color when the system already produces a meaningful scalar. Velocity, curvature, age, density — pick one, normalize it, feed a lerp.
Step 4 — Making it glow
Same recipe as the galaxy generator, because it's the universal recipe for luminous particles:
const material = new THREE.PointsMaterial({
size: 0.45,
sizeAttenuation: true,
vertexColors: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
transparent: true,
opacity: 0.85,
});
Additive blending means overlapping particles add brightness instead of occluding each other — dense regions of the attractor automatically bloom toward white, which is exactly what your eye expects from a long-exposure photograph of light.
depthWrite: false is not optional. With depth writes
on, particles drawn early block particles behind them and additive blending silently breaks
into a patchy mess that looks "dirty" from some angles. Blend-don't-occlude always travels
as a pair: AdditiveBlending + depthWrite: false.
Step 5 — Tell the GPU what changed
Because we rewrite positions and colors every frame, two flags matter. Mark the attributes dirty after each update, and hint that this buffer is a frequent flyer:
geometry.getAttribute('position').needsUpdate = true;
geometry.getAttribute('color').needsUpdate = true;
// and at creation time:
positionAttr.setUsage(THREE.DynamicDrawUsage);
Forget needsUpdate and you'll see one beautiful frozen frame forever.
DynamicDrawUsage is just a driver hint, but it's free and it's the correct
label for a buffer you re-upload 60 times a second.
What the sliders teach
- rho is the temperature knob — the strength of the convection driving the system. Below ρ ≈ 24.74 the two wing centers become stable fixed points and every particle spirals in and dies there. Above it, neither point can hold anything, and trajectories are doomed to leap between the wings forever. You can feel the bifurcation by scrubbing the slider across 24–25.
- sigma couples x to y — drop it and the wings get lazier and rounder.
- beta is a damping term on z — push it up and the butterfly flattens.
- rescatter is the proof of the word "attractor": any cloud of starting points, same destiny.
The full demo source
Everything on this page is one importmap and one module script — view source, or copy the skeleton below into a blank HTML file and you have the whole piece. The complete listing (with sliders and the NaN guard) is what's running above.
<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';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
// scene / camera / renderer / controls — the standard opening move
// state arrays + buffer (Step 1)
// per frame: integrate (Step 2), recolor (Step 3), mark dirty (Step 5)
</script>
Where this season is going
I keep a private atlas of ~365 mathematical systems that make good art — fractals, attractors, flows, interference patterns, growth processes. Season 16 mines it. Each article takes one system, builds the most visually honest Three.js version of it I can manage, and extracts the reusable technique: this one gave you the simulation-state/GPU-buffer split, derivative-driven color, and the additive-glow pair. Next we leave chaos for order.
Next: S16-02 — Phyllotaxis in 3D. One angle (137.5°), ten thousand spheres, and the sunflower algorithm that instancing was invented for.