A GPU particle system is an array of structs in a storage buffer that a compute pass updates and a render pass draws. Mind WGSL's alignment (Arrays and Alignment): BookNest's Page (pos and vel as vec2f, then angle, spin, age, life) packs into 32 bytes, where a vec3f would force 16-byte alignment. Update in place when a particle depends only on itself, since invocation i then touches only element i. When particles read their neighbors, as in flocking or n-body gravity, ping-pong two buffers (read A, write B, swap bind groups) so no invocation sees a half-updated neighbor. No free list is needed if an expired particle respawns in its own slot.
<!doctype html>
<style>
body { margin: 0; background: #f7f4ee; font: 14px system-ui, sans-serif; }
.stage { position: relative; width: 100%; max-width: 600px; }
.stage canvas { display: block; width: 100%; }
.stage canvas + canvas { position: absolute; inset: 0; pointer-events: none; }
</style>
<div class="stage">
<canvas id="view" width="600" height="340"></canvas>
<canvas id="labels" width="600" height="340"></canvas>
</div>
<script>
const canvas = document.getElementById('view');
const ink = document.getElementById('labels').getContext('2d');
function showMessage(text) { // 2D fallback when WebGPU is missing
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#fbeaea'; ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#8a2b2b'; ctx.font = '18px system-ui, sans-serif'; ctx.textAlign = 'center';
ctx.fillText(text, canvas.width / 2, canvas.height / 2);
}
const COUNT = 3000;
const code = /* wgsl */ `
struct Particle { pos: vec2f, vel: vec2f, angle: f32, spin: f32, age: f32, life: f32 } // 32 bytes: no vec3f
@group(0) @binding(0) var<storage, read_write> particles: array<Particle>;
@group(0) @binding(1) var<uniform> sim: vec2f; // dt, time
fn rand(seed: u32) -> f32 {
var h = seed * 747796405u + 2891336453u;
h = ((h >> ((h >> 28u) + 4u)) ^ h) * 277803737u;
return f32((h >> 22u) ^ h) / 4294967296.0;
}
@compute @workgroup_size(64) fn update(@builtin(global_invocation_id) id: vec3u) {
if (id.x >= arrayLength(&particles)) { return; }
var p = particles[id.x]; // invocation i touches only element i: in place is safe
p.age += sim.x;
if (p.age >= p.life) { // expired: respawn in its own slot, no free list
let s = id.x * 7919 + u32(sim.y * 60) * 104729;
p = Particle(vec2f(rand(s) * 0.4 - 0.2, -0.45), vec2f(rand(s + 1) * 1.4 - 0.7, 1.2 + rand(s + 2) * 0.8),
rand(s + 3) * 6.28, rand(s + 4) * 8 - 4, 0, 1.5 + rand(s + 5) * 1.5);
}
p.vel += vec2f(0, -1.6) * sim.x; // gravity
p.vel *= 1 - 0.6 * sim.x; // drag
p.pos += p.vel * sim.x;
p.angle += p.spin * sim.x;
particles[id.x] = p;
}
@group(0) @binding(0) var<storage> drawn: array<Particle>;
struct Out { @builtin(position) pos: vec4f, @location(0) color: vec4f }
@vertex fn vs(@builtin(vertex_index) v: u32, @builtin(instance_index) i: u32) -> Out {
let p = drawn[i];
let q = (vec2f(f32(v & 1), f32(v >> 1)) - 0.5) * vec2f(0.012, 0.04); // a thin ribbon
let r = vec2f(q.x * cos(p.angle) - q.y * sin(p.angle), q.x * sin(p.angle) + q.y * cos(p.angle));
let tints = array(vec3f(0.85, 0.25, 0.20), vec3f(0.95, 0.70, 0.15), vec3f(0.10, 0.45, 0.75), vec3f(0.20, 0.60, 0.35));
let fade = select(0.0, 1 - p.age / p.life, p.life > 0);
return Out(vec4f(p.pos.x * 0.57 + r.x, p.pos.y + r.y, 0, 1), vec4f(tints[i % 4] * fade, fade));
}
@fragment fn fs(in: Out) -> @location(0) vec4f { return in.color; }`;
async function main() {
const adapter = await navigator.gpu?.requestAdapter();
if (!adapter) return showMessage('WebGPU is not available in this browser');
const device = await adapter.requestDevice();
const context = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat();
context.configure({ device, format });
const B = GPUBufferUsage;
const init = new Float32Array(COUNT * 8);
for (let i = 0; i < COUNT; i++) init[i * 8 + 6] = -3 * Math.random(); // staggered ages: a stream, not a burst
for (let i = 0; i < COUNT; i++) init[i * 8 + 7] = 0; // life 0: not born yet
const particles = device.createBuffer({ size: init.byteLength, usage: B.STORAGE | B.COPY_DST });
device.queue.writeBuffer(particles, 0, init);
const sim = device.createBuffer({ size: 8, usage: B.UNIFORM | B.COPY_DST });
const module = device.createShaderModule({ code });
const update = device.createComputePipeline({ layout: 'auto', compute: { module, entryPoint: 'update' } });
const blend = { srcFactor: 'one', dstFactor: 'one-minus-src-alpha' }; // premultiplied alpha
const render = device.createRenderPipeline({ layout: 'auto', primitive: { topology: 'triangle-strip' },
vertex: { module, entryPoint: 'vs' }, fragment: { module, entryPoint: 'fs', targets: [{ format, blend: { color: blend, alpha: blend } }] } });
const updateGroup = device.createBindGroup({ layout: update.getBindGroupLayout(0), entries: [
{ binding: 0, resource: { buffer: particles } }, { binding: 1, resource: { buffer: sim } }] });
const renderGroup = device.createBindGroup({ layout: render.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: particles } }] });
// The struct's byte layout, for reference
const fields = [['pos', 8, '#3d7fc4'], ['vel', 8, '#5aa36b'], ['angle', 4, '#d98a2b'], ['spin', 4, '#b25cc2'], ['age', 4, '#c9543b'], ['life', 4, '#888']];
let last = performance.now();
function frame(now) {
const dt = Math.min((now - last) / 1000, 1 / 30); last = now;
device.queue.writeBuffer(sim, 0, new Float32Array([dt, now / 1000]));
const encoder = device.createCommandEncoder();
const cp = encoder.beginComputePass();
cp.setPipeline(update); cp.setBindGroup(0, updateGroup); cp.dispatchWorkgroups(Math.ceil(COUNT / 64)); cp.end();
const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(),
clearValue: [0.97, 0.96, 0.93, 1], loadOp: 'clear', storeOp: 'store' }] });
pass.setPipeline(render); pass.setBindGroup(0, renderGroup); pass.draw(4, COUNT);
pass.end();
device.queue.submit([encoder.finish()]);
requestAnimationFrame(frame);
}
let x = 12;
ink.font = '11px ui-monospace, monospace';
for (const [name, bytes, color] of fields) {
ink.fillStyle = color; ink.fillRect(x, 10, bytes * 10 - 2, 18);
ink.fillStyle = '#fff'; ink.fillText(name, x + 3, 23);
x += bytes * 10;
}
ink.fillStyle = '#333'; ink.font = '11.5px system-ui, sans-serif';
ink.fillText(`struct Particle: 32 bytes x ${COUNT} in one storage buffer`, x + 10, 23);
ink.fillText('Updated in place (each invocation touches only its own element); expired ones respawn in their slot.', 12, 330);
requestAnimationFrame(frame);
}
main();
</script>