Skip to content

Recipes

GPUSimulation ​

Run a simulation on the GPU, with its state in float textures: particles, cellular automata, fluids and anything else where every item updates each frame.

A GPUSimulation keeps one texel per item, with up to four values in each state texture and up to four state textures. Each step() draws your shader over every texel: it reads the current state and writes the next, then the two swap. Because each item can read any texel, items can see their neighbours, which transform feedback can't do.

js
import { Renderer, GPUSimulation, Uniform, Vec2 } from 'wtc-gl'

// 16,384 particles simulated on the GPU. Each has a position and a velocity,
// kept in two float textures that the step shader writes in one pass. They
// drift through a flow field and scatter away from the pointer.
const step = /* glsl */ `#version 300 es
precision highp float;
uniform sampler2D b_position;
uniform sampler2D b_velocity;
uniform float u_time;
uniform float u_delta;
uniform vec2 u_pointer;
uniform float u_pointerStrength;
in vec2 v_uv;
layout(location = 0) out vec4 position;
layout(location = 1) out vec4 velocity;

vec2 field(vec2 p, float t) {
  return vec2(
    sin(p.y * 3.1 + t * 0.7) + sin(p.y * 1.7 - t * 0.4),
    cos(p.x * 2.9 - t * 0.5) + cos(p.x * 1.3 + t * 0.3)
  );
}

void main() {
  vec2 p = texture(b_position, v_uv).xy;
  vec2 v = texture(b_velocity, v_uv).xy;

  vec2 force = field(p * 1.5, u_time) * 0.8 - p * 0.6;
  vec2 away = p - u_pointer;
  force += u_pointerStrength * normalize(away + 1e-5) * 0.15 / (0.01 + dot(away, away));

  v = (v + force * u_delta) * exp(-1.6 * u_delta);
  position = vec4(p + v * u_delta, 0.0, 1.0);
  velocity = vec4(v, 0.0, 0.0);
}`

const vertex = /* glsl */ `#version 300 es
in vec3 position;
in vec2 reference;
uniform sampler2D b_position;
uniform sampler2D b_velocity;
uniform vec2 u_scale;
uniform float u_pointSize;
out float v_speed;
void main() {
  vec2 p = texture(b_position, reference).xy;
  v_speed = length(texture(b_velocity, reference).xy);
  gl_PointSize = u_pointSize;
  gl_Position = vec4(p * u_scale, 0.0, 1.0);
}`

const fragment = /* glsl */ `#version 300 es
precision highp float;
in float v_speed;
out vec4 colour;
void main() {
  vec3 slow = vec3(0.29, 0.62, 1.0);
  vec3 fast = vec3(0.95, 0.42, 0.26);
  vec3 c = mix(slow, fast, smoothstep(0.2, 1.2, v_speed));
  colour = vec4(c, 1.0) * 0.8;
}`

export default function (container) {
  const renderer = new Renderer({
    dpr: Math.min(devicePixelRatio, 2),
    alpha: true,
    premultipliedAlpha: true,
    clearColour: [0, 0, 0, 0]
  })
  const { gl } = renderer
  container.appendChild(gl.canvas)

  const pointer = new Uniform({
    name: 'pointer',
    value: [9, 9],
    kind: 'float_vec2'
  })
  const pointerStrength = new Uniform({
    name: 'pointerStrength',
    value: 0,
    kind: 'float'
  })
  const sim = new GPUSimulation(gl, {
    size: 128,
    state: ['position', 'velocity'],
    fragment: step,
    uniforms: { u_pointer: pointer, u_pointerStrength: pointerStrength },
    // Start spread over a disc, at rest
    initial: () => {
      const a = Math.random() * Math.PI * 2
      const r = Math.sqrt(Math.random()) * 0.8
      return { position: [Math.cos(a) * r, Math.sin(a) * r, 0, 1] }
    }
  })

  const scale = new Uniform({
    name: 'scale',
    value: [1, 1],
    kind: 'float_vec2'
  })
  const pointSize = new Uniform({ name: 'pointSize', value: 2, kind: 'float' })
  const points = sim.points({
    vertex,
    fragment,
    uniforms: { u_scale: scale, u_pointSize: pointSize },
    transparent: true,
    depthTest: false
  })

  // The pointer, in the simulation's space: y from -1 to 1, x by the aspect
  const onMove = (e) => {
    const rect = gl.canvas.getBoundingClientRect()
    const aspect = rect.width / rect.height
    pointer.value = [
      ((e.clientX - rect.left) / rect.width) * 2 * aspect - aspect,
      1 - ((e.clientY - rect.top) / rect.height) * 2
    ]
    pointerStrength.value = 1
  }
  const onLeave = () => (pointerStrength.value = 0)
  gl.canvas.addEventListener('pointermove', onMove)
  gl.canvas.addEventListener('pointerleave', onLeave)

  return {
    frame(time, delta) {
      // A few small steps a frame keep it stable at any frame rate
      const steps = 2
      for (let i = 0; i < steps; i++) sim.step(Math.min(delta, 1 / 30) / steps)
      renderer.render({ scene: points })
    },
    resize(width, height) {
      renderer.dimensions = new Vec2(width, height)
      scale.value = [height / width, 1]
      pointSize.value = 1.5 * renderer.dpr
    },
    dispose() {
      gl.canvas.removeEventListener('pointermove', onMove)
      gl.canvas.removeEventListener('pointerleave', onLeave)
      sim.remove()
      renderer.dispose()
      gl.canvas.remove()
    }
  }
}

Making a simulation ​

js
import { GPUSimulation } from 'wtc-gl'

const sim = new GPUSimulation(gl, {
  size: 128, // 128 × 128 texels: 16,384 particles
  state: ['position', 'velocity'],
  fragment: step,
  initial: () => ({
    position: [Math.random() * 2 - 1, Math.random() * 2 - 1, 0, 1]
  })
})
  • size is the width and height of the state textures, in texels. A number is square. sim.count is the number of items.
  • state names the state textures, in the order the step shader writes them. One state, called state, is the default.
  • initial sets the starting values: a function of each item's index and texel (index, x, y) that returns a vec4 per state (a plain array when there's one state, or an object by name), or a Float32Array per state name. Anything left out starts at 0.

The step shader ​

The step shader is GLSL 3.00. It reads each state as a sampler2D called b_<name>, at v_uv, the texel being updated, and writes each state to its own output, in the order of state:

glsl
#version 300 es
precision highp float;
uniform sampler2D b_position;
uniform sampler2D b_velocity;
uniform float u_delta;
in vec2 v_uv;
layout(location = 0) out vec4 position;
layout(location = 1) out vec4 velocity;

void main() {
  vec4 p = texture(b_position, v_uv);
  vec4 v = texture(b_velocity, v_uv);
  v.y -= 9.8 * u_delta;
  position = p + v * u_delta;
  velocity = v;
}

Besides your own uniforms, it gets:

UniformTypeWhat it is
b_<name>sampler2DEach state, as it was before this step.
u_resolutionvec2The state's size in texels.
u_timefloatThe simulated time, in seconds.
u_deltafloatThis step's time, in seconds.

To read a neighbour, step by one texel: texture(b_state, v_uv + vec2(1.0, 0.0) / u_resolution). Set wrap: gl.REPEAT and reads past one edge come in from the other, for a world that wraps around.

Stepping ​

Call step once a frame, with the frame's time in seconds:

js
sim.step(delta)

Larger steps make simple integrations unstable. Several small steps a frame keep it steady at any frame rate, as the example does. u_time adds up the steps, so reset() starts it again from 0 along with the state.

Drawing the results ​

points() makes a mesh with one point per item. Its program gets the simulation's uniforms plus any of yours, and a reference attribute: the item's texel, to read its state in the vertex shader:

js
const particles = sim.points({
  vertex, // texture(b_position, reference).xy
  fragment,
  transparent: true
})
renderer.render({ scene: particles })

sim.uniforms is updated in place after every step, so any program you give those uniforms reads the latest state. Spread them into a full-screen pass to draw a field, as the webcam automaton demo does, or into an InstancedMesh's program to place a shape per item. sim.textures holds the latest state textures by name.

Precision ​

The state is 32-bit floats by default. type: gl.HALF_FLOAT halves the memory and is plenty for colours, flags and small values; positions that need precision over a large area want full floats. Rendering into float textures needs EXT_color_buffer_float, which the renderer turns on where it's available, as it is in every current desktop and mobile browser.

The state isn't filtered (filter: gl.NEAREST), so each read is exactly one item's values.

Resizing and cleaning up ​

resize(size) makes new state textures for a new number of items, and starts again from initial. remove() frees the state textures, the step pass, and the meshes points made.

From ParticleSimulation ​

GPUSimulation replaces the deprecated ParticleSimulation: it keeps its own state textures and step pass, so there's no Framebuffer to wire up by hand.

See also ​