WebGPU From Zero · Episode 07

A Million Particles

A Million Particles is Episode 07 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 07 · WebGPU From Zero

One million points of light, each one carrying its own position and velocity, each one swept along an invisible flow field that twists like smoke — and all of it updated and drawn sixty times a second without the data ever leaving the GPU. No CPU loop touches a particle. The numbers live in a storage buffer; a compute pass nudges them; a render pass reads the exact same bytes and paints them. The CPU's entire job, per frame, is to say "go."

This is the episode you screen-record and people refuse to believe. Drag the count slider to 1,000,000 and watch the fps counter sit at 60. Then push it to two million and feel where your particular GPU finally flinches. The thing that makes this possible isn't a clever trick — it's the whole point of WebGPU: a real compute stage that shares memory with rendering. Today we build it from an empty canvas.

0 fps
move your mouse over the cloud
WebGPU · 100k
A plain GPU integrator: each particle drifts on a gentle field. The skeleton everything else hangs on.

What you're looking at

Every frame, two GPU passes run back to back. First a compute pass walks all N particles in parallel, reads each one's position, samples a swirling curl-noise flow field at that spot, adds the result to the particle's velocity, applies a little damping, and integrates the position forward. Then a render pass binds the very same buffer as vertex data and draws each particle as a tiny glowing quad, blended additively so overlaps bloom into light. The position data is never copied to the CPU and back — that round-trip is exactly the thing that would kill a million-particle budget, and WebGPU lets us skip it entirely.

The number in the badge is real. The count slider re-allocates the storage buffer and re-seeds positions, so when it says 1,000,000 there are a million distinct (pos, vel) records being integrated. Hold 60 fps there and you've felt the difference between a fragment-shader toy and genuine general-purpose GPU compute.

The data: positions and velocities in a storage buffer

A particle is four floats: pos.xy and vel.xy. In WGSL a bare vec2<f32> aligns to 8 bytes, so a struct of two of them is a tidy 16 bytes with no hidden padding — but we treat 16 as the contract anyway, because 16 is the alignment WebGPU is happiest with and it leaves a clean lane open if you ever add a vec4 color later. One buffer, used three ways at once: the compute pass reads and writes it (STORAGE), the render pass reads it as geometry (VERTEX here we read it as STORAGE in the vertex stage), and we seed it once from the CPU (COPY_DST).

// One particle = pos.xy + vel.xy = 4 floats = 16 bytes.
const STRIDE = 4;                 // floats per particle
const BYTES  = STRIDE * 4;          // 16 bytes
const N      = 1_000_000;

const particles = device.createBuffer({
  size:  N * BYTES,                  // 1,000,000 × 16 = 16 MB
  usage: GPUBufferUsage.STORAGE      // compute reads+writes it
       | GPUBufferUsage.COPY_DST,    // we seed it once from the CPU
});

Mind the ceiling. A million particles is 16 MB. WebGPU guarantees a maxStorageBufferBindingSize of at least 128 MB (most desktop adapters report a lot more), so 16 MB is nowhere near the limit — even 2 million is only 32 MB. But the limit is real and it bites silently: bind a buffer larger than the adapter allows and pipeline creation throws a validation error, it doesn't just clamp. Read device.limits.maxStorageBufferBindingSize once at startup and cap your slider to it. The matching WGSL declaration is one line:

struct Particle { pos: vec2<f32>, vel: vec2<f32> };           // 16 bytes
@group(0) @binding(0) var<storage, read_write> parts: array<Particle>;
@group(0) @binding(1) var<uniform> u: Params;   // dt, count, flow, force, mouse…

Stage 1 — 100k baseline: the GPU integrator

Start with the skeleton. One hundred thousand particles, a trivial flow (just enough drift to prove the loop runs), and the integrator that every later stage builds on. The compute entry point is dispatched once per particle — we launch ceil(N / 64) workgroups of 64 threads, and the very first thing every invocation does is guard the tail, because dispatch always rounds up to whole workgroups and the spare threads at the end must not touch memory they don't own.

@compute @workgroup_size(64)
fn integrate(@builtin(global_invocation_id) gid: vec3<u32>) {
  let i = gid.x;
  if (i >= u.count) { return; }          // ← tail guard: spare threads bail

  var p = parts[i];

  let flow = curl(p.pos * u.flowScale + vec2(u.time * 0.05)) * u.force;
  p.vel = p.vel + flow * u.dt;
  p.vel = p.vel * u.damping;                // momentum bleed (Stage 3)
  p.pos = p.pos + p.vel * u.dt;

  wrap(&p.pos);                            // keep the cloud on screen
  parts[i] = p;                             // each thread writes only its own index
}

Because every invocation writes only parts[i] — its own slot — there are no data races and we don't need ping-pong double-buffering. (That changes the moment a particle needs to read its neighbors; that's Episode 08.) This in-place pattern is the cheapest possible compute shape, and it's why a million independent integrations fit in a couple of milliseconds.

Stage 2 — Curl-noise: a flow field that can't pile up

Drift is boring. We want smoke: particles that swirl, fold, and never just clump into a point or fly off to infinity. The trick is to make the velocity field divergence-free — no sources, no sinks — and the standard way to get that for free is curl noise. Take any smooth scalar noise field n(x, y), then build the velocity from its perpendicular gradient: (∂n/∂y, −∂n/∂x). By construction the divergence of that vector field is zero, so the flow circulates instead of converging. It looks exactly like the curl of fluid, because mathematically it is.

First we need cheap, smooth noise. A hash turns an integer lattice point into a pseudo-random value; we sample the four corners of the cell and smoothstep between them (value noise). Then we take the curl by finite differences — sample the noise twice, a hair apart, and rotate the gradient 90°.

// hash a 2D lattice point → [0,1)  (sin-free; stable across GPUs)
fn hash2(p: vec2<f32>) -> f32 {
  var q = fract(p * vec2(0.3183099, 0.3678794));
  q = q + dot(q, q.yx + 19.19);
  return fract(q.x * q.y * 95.4337);
}

// smooth value noise: bilerp the 4 cell corners with a smoothstep fade
fn vnoise(p: vec2<f32>) -> f32 {
  let i = floor(p);
  let f = fract(p);
  let u = f * f * (3.0 - 2.0 * f);            // smoothstep
  let a = hash2(i + vec2(0.0, 0.0));
  let b = hash2(i + vec2(1.0, 0.0));
  let c = hash2(i + vec2(0.0, 1.0));
  let d = hash2(i + vec2(1.0, 1.0));
  return mix(mix(a, b, u.x), mix(c, d, u.x), u.y);
}

// curl of the noise = perpendicular gradient → divergence-free flow
fn curl(p: vec2<f32>) -> vec2<f32> {
  let e = 0.01;
  let nx = vnoise(p + vec2(0.0, e)) - vnoise(p - vec2(0.0, e));
  let ny = vnoise(p + vec2(e, 0.0)) - vnoise(p - vec2(e, 0.0));
  return vec2(nx, -ny) / (2.0 * e);          // (∂n/∂y, −∂n/∂x)
}

Switch to Stage 2 and the difference is night and day: the cloud stops drifting and starts breathing. Bump the flow scale slider — small values give big lazy vortices, large values give fine turbulent filaments. That slider is just multiplying p.pos before it hits the noise, i.e. zooming the field in and out under the particles.

Stage 3 — Velocity + damping: tuning the momentum

So far each particle's velocity is whatever the field said this instant. Real smoke has inertia: a puff keeps coasting after the wind that pushed it has moved on. We already store vel, so we just stop overwriting it and start accumulating into it — the flow becomes an acceleration, not a teleport — then bleed a few percent of speed off every frame so nothing runs away:

p.vel = p.vel + curl(...) * u.force * u.dt;   // accelerate along the field
p.vel = p.vel * u.damping;                  // 0.96–0.99: keep some, lose some
p.pos = p.pos + p.vel * u.dt;

The force slider scales how hard the field pushes; damping is the counterweight. Too little damping and particles whip into chaos and smear to the edges; too much and they freeze into the field's streamlines like iron filings on a magnet. The sweet spot — around 0.97 — is where the cloud has visible momentum but still settles into coherent ribbons. This one multiply is the entire difference between "points on a vector field" and "something that moves like a fluid."

Stage 4 — Additive glow: there is no gl_PointSize

Now make it beautiful, and meet WebGPU's sharpest gotcha for anyone coming from WebGL. In GLSL you'd set gl_PointSize in the vertex shader and the GPU would draw a sprite for you. WebGPU has no such builtin. The point-list topology exists, but a point is always exactly one pixel — there is no size knob. To get a particle bigger than one pixel you expand it into a quad yourself: draw 6 vertices per particle (two triangles), and in the vertex shader use the vertex index to push each corner out from the particle's center.

We don't even need a quad vertex buffer. draw(6, N) launches 6 vertices × N instances; vertex_index (0–5) picks the corner and instance_index picks which particle to read from the storage buffer:

// 6 vertices → 2 triangles → 1 quad, generated from the index alone
const CORNERS = array<vec2<f32>, 6>(
  vec2(-1.0, -1.0), vec2( 1.0, -1.0), vec2(-1.0,  1.0),
  vec2(-1.0,  1.0), vec2( 1.0, -1.0), vec2( 1.0,  1.0),
);

struct VsOut {
  @builtin(position) clip: vec4<f32>,
  @location(0) uv:    vec2<f32>,     // −1..1 across the quad, for the round falloff
  @location(1) speed: f32,        // |vel|, for color-by-speed
};

@vertex
fn vs(@builtin(vertex_index) vi: u32,
      @builtin(instance_index) ii: u32) -> VsOut {
  let p = parts[ii];                       // read THIS particle from storage
  let corner = CORNERS[vi];
  let center = p.pos * u.aspect;            // world → clip (square aspect fix)

  var out: VsOut;
  out.clip  = vec4(center + corner * u.pointSize, 0.0, 1.0);
  out.uv    = corner;
  out.speed = length(p.vel);
  return out;
}

The fragment shader carves the quad into a soft round dot with a Gaussian-ish falloff, tints it by speed (slow = cool blue, fast = hot magenta/white), and — critically — caps brightness so additive blending doesn't blow the whole screen to white:

@fragment
fn fs(in: VsOut) -> @location(0) vec4<f32> {
  let r = length(in.uv);
  if (r > 1.0) { discard; }                  // round, not square
  let falloff = exp(-r * r * 3.0);            // soft Gaussian-ish core

  let t = clamp(in.speed * 2.5, 0.0, 1.0);
  let cool = vec3(0.20, 0.55, 1.00);
  let hot  = vec3(1.00, 0.35, 0.85);
  let rgb  = mix(cool, hot, t);

  // additive: alpha is tiny on purpose so thousands can stack without clipping
  let a = falloff * 0.18;
  return vec4(rgb * a, a);                  // premultiplied
}

And the pipeline's blend state is what turns overlap into glow. Additive blending — src + dst — means every particle adds its light to whatever's already there, so dense regions accumulate into bright cores while sparse wisps stay dim. That's the whole smoke look in three lines of blend config:

const pipeline = device.createRenderPipeline({
  layout: bindLayout, /* …vertex+fragment… */
  fragment: { module, entryPoint: 'fs', targets: [{
    format,
    blend: {                                // ADDITIVE GLOW
      color: { srcFactor: 'one', dstFactor: 'one', operation: 'add' },
      alpha: { srcFactor: 'one', dstFactor: 'one', operation: 'add' },
    },
  }] },
  primitive: { topology: 'triangle-list' },
});

Toggle additive glow off and you get flat, alpha-blended dots — fine, but lifeless. Toggle it on and the cloud lights up from within. The reason the alpha in the fragment shader is only 0.18 and not 1.0 is the classic additive pitfall: if each particle adds full brightness, ten of them overlapping = pure white, and your gorgeous color turns into a featureless blob. Keep per-particle contribution small and let density do the work.

Stage 5 — One million, at sixty

This is the payoff. Drag count to 1,000,000. The buffer re-allocates, a million positions are seeded once, and from then on it's two GPU passes a frame. On a modern integrated GPU this holds 60 fps; on a discrete card you'll have headroom to spare, which is why the slider keeps going to 2,000,000. Watch the fps counter as you climb — the point where it finally dips below 60 is your hardware's honest particle budget, found live, no profiler required.

Why is a million cheap when the same loop in JavaScript would melt? Three reasons, all of them WebGPU's reason for existing: (1) the integration is embarrassingly parallel — a million independent threads, no coordination; (2) the data never crosses the bus — compute writes the buffer, the vertex stage reads the same buffer, the CPU is never in the loop; and (3) we seed positions exactly once, not per frame. Re-randomizing a million particles every frame (or, worse, mapAsync-ing them back to the CPU) would erase the win instantly.

One million particles × 16 bytes = 16 MB, integrated and drawn 60 times a second = ~960 MB/s of pure GPU memory traffic that your CPU never sees. That's the number to put on screen and let people stare at.

Stage 6 — Interactive force: the cloud answers your mouse

The final stage hands the whole cloud a leash. We pass the mouse position into the params uniform as another point in the field, and in the integrator we add a force pointing toward (attract) or away from (repel) it, scaled by inverse distance so the pull is strong up close and gentle far away:

// in the compute integrator, after the curl-noise force:
let toMouse = u.mouse - p.pos;
let d2 = dot(toMouse, toMouse) + 0.02;       // +eps: never divide by zero
let pull = toMouse / d2 * u.mouseForce;     // mouseForce = ±strength
p.vel = p.vel + pull * u.dt;

That + 0.02 on the squared distance is the only thing standing between a smooth attractor and a particle that hits the cursor, divides by zero, and rockets off to NaN — taking a streak of white garbage with it. Flip the mouse control between attract and repel and sweep the cursor through the cloud: in attract mode you gather a million points into a swirling knot; in repel mode you carve a clean hole that the curl-noise immediately tries to heal. Same buffer, same two passes — you're just feeding the compute shader one more vector.

Common pitfalls

  • Reaching for gl_PointSize. It does not exist in WebGPU. Either expand each particle to a quad in the vertex shader (what we do — 6 vertices per instance) or use point-list topology and accept exactly one pixel per particle. There is no middle option and no resizing of points.
  • Additive blow-out to white. With src + dst blending, brightness accumulates. If each particle emits full alpha, dense regions clip to pure white and you lose all color and structure. Keep per-particle alpha small (we use 0.18) and let overlap build the highlights.
  • Re-initializing positions every frame. Seed once — on the CPU at buffer creation, or with a one-shot init compute pass — then only ever integrate. Re-seeding per frame resets the simulation to noise and throws away all the motion you just computed.
  • mapAsync in the hot path. Reading the buffer back to the CPU is an async round-trip that stalls the pipeline. Never do it per frame. The compute output feeds the vertex stage on the GPU; the CPU never sees a particle.
  • The storage-buffer ceiling. maxStorageBufferBindingSize is guaranteed only to 128 MB. Binding a larger buffer throws at pipeline creation — it does not silently shrink. Check device.limits and clamp your count.
  • Forgetting the tail guard. dispatchWorkgroups rounds up to whole workgroups, so the last group has threads with i >= count. Without if (i >= u.count) { return; } they read or write past the array and corrupt memory (or trip a validation error).
  • Non-deterministic init. Seed the RNG (we use a fixed integer LCG) so the cloud is identical every load — essential for debugging and for screen-recording the exact same gorgeous frame twice.

Exercises

  1. Your own field. Replace the curl() call with a vector field of your design — a plain rotation vec2(-p.y, p.x) for a perfect vortex, or two added rotations at different centers. Notice which fields conserve the cloud and which let it escape (hint: divergence).
  2. Color by direction. Instead of coloring by speed, color by heading: compute atan2(vel.y, vel.x) in the vertex shader, pass it as hue, and convert HSV→RGB in the fragment shader. Now the flow's structure is painted directly onto the smoke.
  3. A second attractor. Add a second mouse-independent attractor at a fixed point (or one that orbits on u.time) and sum both pulls in the integrator. Two attractors of opposite sign make a dipole the cloud streams between.

What's next

Episode 08 — Boids on the GPU, the season finale. Every particle so far has been a hermit: it reads its own position and the field, nothing else. Boids flock because each one reads its neighbors — separation, alignment, cohesion — and the instant a thread needs to read data other threads are also writing, our cozy in-place buffer breaks. We'll fix it with ping-pong double-buffering (read A, write B, swap) and a spatial grid so a million birds don't each check a million others. Same GPU-resident pipeline; one more dimension of life.