Skip to content

Uniform Buffers

The triangle’s color and offset come from a 32-byte uniform buffer. The vec4f color occupies the first 16 bytes, the vec2f offset starts at byte 16, and the uniform layout rules round the struct to 32 bytes. The full explanation is in Uniform buffers.

Moving triangle

const uniformData = new Float32Array(8);
const uniformBuffer = device.createBuffer({
size: uniformData.byteLength,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [{ binding: 0, resource: { buffer: uniformBuffer } }],
});
function frame(time) {
uniformData[0] = 0.45 + 0.55 * Math.sin(time * 1.3);
uniformData[1] = 0.35 + 0.45 * Math.sin(time * 1.7 + 2);
uniformData[2] = 0.4 + 0.5 * Math.sin(time * 1.1 + 4);
uniformData[3] = 1;
uniformData[4] = Math.sin(time) * 0.35;
uniformData[5] = Math.cos(time * 0.8) * 0.25;
device.queue.writeBuffer(uniformBuffer, 0, uniformData);
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindGroup);
pass.draw(3);
}
struct Uniforms {
color: vec4f,
offset: vec2f,
}
@group(0) @binding(0) var<uniform> uniforms: Uniforms;