Three.js From Zero · Article s17-05

The Ising Model — A Phase Transition Under Your Thumb

160,000 spins flipping by Metropolis coin-toss on the GPU: checkerboard decomposition for race-free parallel randomness, a temperature slider through the critical point, and a probe-pass magnetization readout. Part of the MasterAllArts Creative 3D Roadmap.

Part of the MasterAllArts Creative 3D Roadmap .

← Three.js From Zero S17-05 · Order & Chaos

Season 17 · Article 05 · Order & Chaos

One hundred sixty thousand tiny magnets, each seeing only its four neighbors, each flipping by coin-toss. Below a critical temperature they spontaneously agree and the screen freezes into continents of consensus; above it they bicker forever in static. Exactly in between — at T = 2.269… — the system can't decide, and fluctuates at every size at once. The demo opens at that temperature. You're looking at the most studied object in statistical physics, boiling.

— fps · T=2.27 · |m|=—

The experiment that makes physicists out of artists: drag temperature from 4.0 (pure noise) slowly down past 2.27 and watch domains crystallize and coarsen — islands eating smaller islands, in real time. Then park it exactly at 2.27 and stare: patches flicker at every scale from single pixels to half the screen. That's criticality — the same all-scales structure as a coastline. Drag on the canvas to paint a patch of up-spins and watch the temperature decide whether your graffiti survives. field is a thumb on the scale: even ±0.1 picks a winner below T꜀.

The simplest possible model of agreement

Each cell holds a spin, +1 or −1. The only physics: a spin is happier (lower energy) agreeing with its four neighbors, and temperature jiggles everything. Energy of flipping spin s:

ΔE = 2 · s · (Σ neighbors + h)        // h = external field

That's the entire model — proposed in 1920, solved exactly by Onsager in 1944 (one of the legendary calculations of physics), and the reason we understand phase transitions at all. The critical temperature falls out exactly: T꜀ = 2/ln(1+√2) ≈ 2.269. The same math now models opinion spread, neuron ensembles, and image denoising — anything where local agreement fights global noise.

Step 1 — Metropolis: physics by coin toss

The update rule (Metropolis, 1953 — same Metropolis as the Manhattan Project) is two lines:

if (dE <= 0.0)                 flip();          // lowers energy → always
else if (rand < exp(-dE / T))  flip();          // raises energy → sometimes

The second line is the genius: uphill moves are allowed, with a probability that dies exponentially in the cost. That single concession makes the simulation sample the true thermal distribution instead of greedily freezing into the first local minimum. (You've used this idea before even if you didn't know it — it's the heart of simulated annealing.) Randomness on the GPU is the hash trick from Physarum: hash the cell's UV with a time salt, get a fresh pseudo-coin every pass.

Step 2 — The checkerboard: this article's keeper

Here's the trap. A fragment shader updates every cell simultaneously — but Metropolis needs each flip to see its neighbors' current values. If two adjacent spins both decide to flip in the same pass (each reacting to the other's old value), they can chase each other forever — the lattice falls into a blinking anti-pattern that looks like a broken monitor and samples no physics at all.

The exact fix is two colors: tint the lattice like a chessboard. A black cell's four neighbors are all white, and vice versa — so updating only the black cells in one pass is perfectly race-free, then only the white cells in the next:

// in the shader: am I this pass's color?
vec2 cell = floor(vUv / uTexel);
float myColor = mod(cell.x + cell.y, 2.0);
if (myColor != uParity) {           // not my turn:
  gl_FragColor = vec4(sEncoded, 0.0, 0.0, 1.0);   // copy myself through
  return-equivalent;
}
/* …Metropolis update… */

// in JS: two passes per sweep
for (const parity of [0, 1]) {
  simMaterial.uniforms.uParity.value = parity;
  /* render → swap */
}

Checkerboard decomposition is the standard answer whenever a stochastic or sequential algorithm has to run on parallel hardware with nearest-neighbor coupling — Ising, Gauss–Seidel solvers, graph coloring, lattice QCD on supercomputers. Two passes instead of one, and the parallelism becomes honest.

Pitfall: spins are discrete — filtering must be too. The sim textures use NearestFilter and plain 8-bit channels. Linear filtering would hand the shader blurred half-spins at cell borders, quietly corrupting ΔE; float textures would waste bandwidth on values that are only ever 0 or 1. Match the storage to the math: binary state, byte texture, nearest sampling. (Compare: the wave tank needed HalfFloat; the agent positions needed full Float. Three articles, three precisions, all deliberate.)

Step 3 — The probe pass: measuring without stalling

The magnetization readout |m| in the stats bar — the average spin, the order parameter of the transition — requires reading GPU data back to JavaScript, which is the most expensive thing you can ask a GPU pipeline to do. So the demo cheats responsibly: every 20 frames it renders the spin field into a tiny 48×30 target and reads that back — 5,760 bytes instead of 650KB, a statistically perfect sample for a one-decimal readout.

renderer.setRenderTarget(probeTarget);          // 48×30, byte
renderer.render(copyQuad, camera);
renderer.readRenderTargetPixels(probeTarget, 0, 0, 48, 30, probeBuffer);
// average probeBuffer → m ∈ [−1, +1]

Readback economics in one rule: never read back at full resolution, never read back every frame, and never read back mid-frame. A probe pass respects all three.

What to watch (the physics tour)

  • Quench: reheat at T = 4, then yank temperature to 1.8. Domain walls slowly straighten and shrink — coarsening, the same physics as soap froth and metal annealing. |m| crawls toward ±1.
  • Criticality: at 2.27, fluctuations at all scales, |m| hovering indecisively near 0 with huge swings. This boundary-of-order is where the season's title lives.
  • Symmetry breaking: below T꜀ with field = 0, the system picks orange or blue arbitrarily — run reheat + quench twice and you'll likely get different winners. Identical laws, different history.
  • The field: ±0.1 below T꜀ flips the whole world to one color — and your painted graffiti melts or freezes depending on whether it agrees with the field.

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 byte+nearest render targets, spins as 0/1       (the pitfall)
// per sweep: parity-0 pass → swap → parity-1 pass → swap   (Step 2)
// Metropolis rule with hash randomness                 (Step 1)
// probe pass every 20 frames → |m| readout             (Step 3)
</script>