Transform feedback
TransformFeedback runs a vertex shader over a set of per-vertex values and writes the results back, so a simulation runs entirely on the GPU.
Each vertex is one thing being simulated: a particle, an agent in a flock, a point on a cloth. A vertex shader reads its last state from attributes, such as a position and a velocity, and writes the next state to its outputs. TransformFeedback captures those outputs into a second set of buffers, then swaps the two, so the next step reads what this one wrote. Nothing is copied back to JavaScript, so tens of thousands of particles cost little.
Simulating is separate from drawing. step() advances the simulation without drawing anything, and attribute(name) gives you its latest values to draw with any geometry and program you like.
import {
Renderer,
Mesh,
Program,
Geometry,
GeometryAttribute,
TransformFeedback,
Uniform,
Vec2
} from 'wtc-gl'
// 4,096 points simulated on the GPU. Each step, the simulation's vertex
// shader reads every point's position and velocity, works out the next ones,
// and writes them back; nothing comes back to JavaScript.
const COUNT = 4096
const simulateVertex = /* glsl */ `#version 300 es
in vec2 a_position;
in vec2 a_velocity;
in float a_seed;
uniform float u_time;
uniform float u_dt;
out vec2 v_position;
out vec2 v_velocity;
void main() {
vec2 p = a_position;
// Pulled towards the centre, pushed around it, and stirred
vec2 swirl = vec2(-p.y, p.x) / (length(p) + 0.05);
vec2 stir = vec2(sin(p.y * 6.0 + u_time), cos(p.x * 6.0 - u_time * 1.3));
vec2 force = -p * 1.5 + swirl * (0.3 + 0.3 * a_seed) + stir * 0.4;
v_velocity = (a_velocity + force * u_dt) * (1.0 - 0.8 * u_dt);
v_position = p + v_velocity * u_dt;
}`
// Nothing is drawn while simulating, but a program needs a fragment shader
const simulateFragment = /* glsl */ `#version 300 es
precision highp float;
out vec4 colour;
void main() { colour = vec4(0.0); }`
const drawVertex = /* glsl */ `#version 300 es
in vec2 position;
in vec2 velocity;
uniform float u_aspect;
uniform float u_pointSize;
out float v_speed;
void main() {
v_speed = length(velocity);
gl_PointSize = u_pointSize;
gl_Position = vec4(position.x / u_aspect, position.y, 0.0, 1.0);
}`
const drawFragment = /* glsl */ `#version 300 es
precision highp float;
in float v_speed;
out vec4 colour;
void main() {
if (length(gl_PointCoord - 0.5) > 0.5) discard;
vec3 slow = vec3(0.29, 0.62, 1.0);
vec3 fast = vec3(0.95, 0.42, 0.26);
colour = vec4(mix(slow, fast, smoothstep(0.2, 0.8, v_speed)), 1.0);
}`
export default function (container) {
const renderer = new Renderer({
dpr: Math.min(devicePixelRatio, 2),
alpha: true
})
const { gl } = renderer
container.appendChild(gl.canvas)
// Starting values: scattered points, still, each with a random seed
const positions = new Float32Array(COUNT * 2)
const velocities = new Float32Array(COUNT * 2)
const seeds = new Float32Array(COUNT)
for (let i = 0; i < COUNT; i++) {
positions[i * 2] = Math.random() * 2 - 1
positions[i * 2 + 1] = Math.random() * 2 - 1
seeds[i] = Math.random()
}
const u_time = new Uniform({ name: 'time', value: 0, kind: 'float' })
const u_dt = new Uniform({ name: 'dt', value: 0, kind: 'float' })
const simulation = new TransformFeedback(gl, {
program: new Program(gl, {
vertex: simulateVertex,
fragment: simulateFragment,
uniforms: { u_time, u_dt },
transformFeedbackVaryings: ['v_position', 'v_velocity']
}),
attributes: {
a_position: { size: 2, data: positions, varying: 'v_position' },
a_velocity: { size: 2, data: velocities, varying: 'v_velocity' }
},
staticAttributes: {
a_seed: new GeometryAttribute({ size: 1, data: seeds })
}
})
// The points read the simulation's latest results
const u_aspect = new Uniform({ name: 'aspect', value: 1, kind: 'float' })
const u_pointSize = new Uniform({
name: 'pointSize',
value: 3,
kind: 'float'
})
const points = new Mesh(gl, {
mode: gl.POINTS,
geometry: new Geometry(gl, {
position: simulation.attribute('a_position'),
velocity: simulation.attribute('a_velocity')
}),
program: new Program(gl, {
vertex: drawVertex,
fragment: drawFragment,
uniforms: { u_aspect, u_pointSize },
depthTest: false
})
})
return {
frame(time, delta) {
u_time.value = time
u_dt.value = Math.min(delta, 1 / 30)
simulation.step()
renderer.render({ scene: points })
},
resize(width, height) {
renderer.dimensions = new Vec2(width, height)
u_aspect.value = width / height
u_pointSize.value = 3 * renderer.dpr
},
dispose() {
simulation.remove()
simulation.program.remove()
points.geometry.remove()
points.program.remove()
renderer.dispose()
gl.canvas.remove()
}
}
}The simulation program
The simulation is an ordinary Program, with transformFeedbackVaryings naming the vertex shader outputs to capture:
import { Program } from 'wtc-gl'
const program = new Program(gl, {
vertex: simulateVertex,
fragment: simulateFragment,
uniforms: { u_time, u_dt },
transformFeedbackVaryings: ['v_position', 'v_velocity']
})#version 300 es
in vec2 a_position;
in vec2 a_velocity;
uniform float u_dt;
out vec2 v_position;
out vec2 v_velocity;
void main() {
v_velocity = a_velocity + vec2(0.0, -9.8) * u_dt;
v_position = a_position + v_velocity * u_dt;
}Nothing is drawn while it runs, but WebGL still needs a fragment shader to link the program. One that writes nothing useful will do:
#version 300 es
precision highp float;
out vec4 colour;
void main() { colour = vec4(0.0); }Each vertex only sees its own state, plus the uniforms and any textures the program reads. For simulations where each particle reads its neighbours, keep the state in textures instead (see particles in textures).
Attributes
attributes lists the values the simulation updates, keyed by their names in the vertex shader. Each has a size (1 to 4 floats per vertex), its starting values as a Float32Array, and the varying captured back into it:
import { TransformFeedback } from 'wtc-gl'
const COUNT = 10000
const positions = new Float32Array(COUNT * 2)
const velocities = new Float32Array(COUNT * 2)
// ...fill in the starting values
const simulation = new TransformFeedback(gl, {
program,
attributes: {
a_position: { size: 2, data: positions, varying: 'v_position' },
a_velocity: { size: 2, data: velocities, varying: 'v_velocity' }
}
})Every varying the program captures needs exactly one attribute, and every attribute's varying has to be captured; the constructor throws, naming what's missing, if they don't match.
The number of vertices, simulation.count, is the length of the first captured attribute's data divided by its size. Pass count to simulate fewer than the data holds. usage is the buffer usage hint, gl.DYNAMIC_COPY by default.
Static attributes
Values the simulation reads but never changes, such as a random seed or a rest position, go in staticAttributes as ordinary GeometryAttributes. They're uploaded once, and not captured:
import { GeometryAttribute } from 'wtc-gl'
const seeds = new Float32Array(COUNT).map(() => Math.random())
const simulation = new TransformFeedback(gl, {
program,
attributes: {
a_position: { size: 2, data: positions, varying: 'v_position' },
a_velocity: { size: 2, data: velocities, varying: 'v_velocity' }
},
staticAttributes: {
a_seed: new GeometryAttribute({ size: 1, data: seeds })
}
})Stepping
simulation.step() runs the program over every vertex once. Call it from your render loop, before drawing:
u_dt.value = delta
simulation.step()
renderer.render({ scene, camera })Because stepping doesn't draw, it can run more or less often than you draw. Several smaller steps a frame keep a fast simulation stable:
const substeps = 4
u_dt.value = delta / substeps
for (let i = 0; i < substeps; i++) simulation.step()Cap delta too, so a tab coming back from the background doesn't take one huge step.
Drawing the results
simulation.attribute(name) returns a GeometryAttribute that always holds the latest values: its buffer follows the results after every step. Add it to any geometry, under whatever name the drawing shader uses:
import { Geometry, Mesh, Program } from 'wtc-gl'
const points = new Mesh(gl, {
mode: gl.POINTS,
geometry: new Geometry(gl, {
position: simulation.attribute('a_position'),
velocity: simulation.attribute('a_velocity')
}),
program: new Program(gl, { vertex: pointsVertex, fragment: pointsFragment })
})Calling attribute again with the same name and options returns the same object, so the results can be drawn by several meshes with different programs: a glow and a sharp point, say.
The values only exist on the GPU, so a mesh drawn with a camera can't work out its bounds from them, and warns. Give it frustumCulled: false, or set geometry.bounds yourself if you know where the simulation stays.
One shape per vertex
To draw a shape, rather than a point, at every simulated vertex, ask for a per-instance attribute with instanced. The geometry's own attributes describe the shape, and it's drawn once for each simulated vertex:
import { Geometry, GeometryAttribute, Mesh } from 'wtc-gl'
const arrows = new Mesh(gl, {
geometry: new Geometry(gl, {
// A small triangle, pointing along +x
position: new GeometryAttribute({
size: 2,
data: new Float32Array([1, 0, -0.6, 0.5, -0.6, -0.5])
}),
a_position: simulation.attribute('a_position', { instanced: 1 }),
a_velocity: simulation.attribute('a_velocity', { instanced: 1 })
}),
program: arrowProgram
})The vertex shader places and turns the shape from a_position and a_velocity. instanced is the divisor: 1 advances to the next simulated vertex for every instance. This uses a plain Mesh; InstancedMesh is for instances whose matrices you set from JavaScript. The swarm demo draws its agents this way.
Interleaved buffers
By default each attribute gets its own buffer. Set transformFeedbackBufferMode: 'interleaved' on the program to capture every varying into one buffer instead, one vertex's values after another:
const program = new Program(gl, {
vertex: simulateVertex,
fragment: simulateFragment,
transformFeedbackVaryings: [
'v_position',
'v_velocity',
'v_colour',
'v_age',
'v_seed'
],
transformFeedbackBufferMode: 'interleaved'
})WebGL only promises four separately captured varyings, so a simulation with more needs interleaving. Nothing else changes: the attributes and attribute(name) work the same either way.
Starting again
simulation.reset() uploads each attribute's data again and starts from there. Change data first to start from somewhere new:
for (let i = 0; i < positions.length; i++) positions[i] = Math.random() * 2 - 1
simulation.reset()The same happens if the WebGL context is lost and restored: the simulation starts again from data.
Particles in textures
The GPUSimulation recipe takes the other approach: each particle's state is a texel in a float texture, updated by a fragment shader each step, and the points read that texture to place themselves. Simulating in a fragment shader is less direct, but each particle can read any other texel, which suits simulations where particles interact with their neighbours. See GPUSimulation.
Cleaning up
simulation.remove() deletes the buffers, including the static attributes', and the transform feedback objects. The program is left alone, as other things may use it; remove it yourself:
simulation.remove()
simulation.program.remove()See cleaning up.