WebGPU From Zero · Episode 04
Uniforms, Textures & Bind Groups
Uniforms, Textures & Bind Groups is Episode 04 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.
Part of the MasterAllArts Creative 3D Roadmap .
A GPU is a machine for turning data into pixels at terrifying speed — but it can't
touch a single byte you haven't explicitly handed it. Last episode our fragment shader
invented its colors from thin air. This one is about the plumbing: how you push a
bundle of uniforms across the bus, how you upload a texture and a
sampler, and how the bind group ties it all to specific
@group/@binding slots in your WGSL. No external assets — we generate the
texture procedurally in JavaScript (a checker dusted with noise) and sample it on a
fullscreen quad with live filtering and wrap modes.
This is also where most people first hit the #1 WebGPU footgun: a
uniform struct whose JavaScript layout doesn't match WGSL's alignment rules. A
vec3<f32> secretly eats 16 bytes, not 12, and if
your Float32Array packs it tight your shader reads garbage — or the API
throws a cryptic validation error before a single pixel appears. We make that the
centerpiece: stage 1 of the demo literally draws the bytes so the padding
stops being a mystery. By the end, "bind group" and "uniform alignment" will click.
What you're looking at
One fullscreen quad, drawn by the fullscreen-triangle trick from Episode 01 (two triangles is fine too; here a single oversized triangle covers the screen). Every pixel runs the same fragment shader, which reads from one uniform buffer and one texture through one sampler, all wired up by one bind group. The six stages are six states of that same machine:
- Stage 1 — Uniform layout. Before any texture, we visualize the
uniform buffer itself: a grid of 16-byte rows showing how each field
(
vec2,vec3,f32) lands, and where the padding goes. This is the alignment lesson, made visible. - Stage 2 — Upload texture. We build a checker+noise image on the
CPU and push it to the GPU with
writeTexture; the quad shows the raw upload at 1:1. - Stage 3 — Sample (nearest). The shader calls
textureSamplefor the first time. Crisp, blocky texels. - Stage 4 — Filter + wrap. Flip the filter select to
linearand the wrap torepeat; crank scale past 1 to send UVs outside [0,1] and watch clamp vs repeat fight. - Stage 5 — Animate UVs. A
timeuniform scrolls and zooms the texture coordinates — the texture is still static; only the lookup moves. - Stage 6 — Texture + uniforms. Everything composed: sampled color tinted by a uniform color and mix amount, breathing with time. The payoff shot.
The badge bottom-left reads WebGPU
on a capable browser (Chrome/Edge 113+) or fallback (no WebGPU) elsewhere,
where a Canvas2D twin draws the same procedural texture so the page is never black.
Stage 1 — A uniform buffer with multiple fields (and its alignment)
A uniform buffer is a small, read-only blob the shader sees every invocation —
perfect for per-frame constants (resolution, time, a tint color, a scale). The trap is
that WGSL lays out a struct by std140-ish alignment rules,
and your JavaScript Float32Array must match it byte for byte.
The rules that bite:
f32aligns to 4 bytes,vec2<f32>to 8,vec3<f32>andvec4<f32>both to 16.- A
vec3occupies 12 bytes of data but reserves 16 — the next field starts on the following 16-byte line. The 4 trailing bytes are dead padding. - The struct's total size is rounded up to a multiple of its largest alignment (here 16).
Here is the exact struct this demo uses, in WGSL and in the matching
Float32Array, side by side. Read the byte offsets in the comments — they
must agree or you get garbage:
// ---- WGSL: the uniform struct (16-byte aligned) ----
struct Uniforms {
resolution : vec2<f32>, // offset 0 (8 bytes)
scale : f32, // offset 8 (4 bytes)
time : f32, // offset 12 (4 bytes) — fills the 1st 16B slot
tint : vec3<f32>, // offset 16 (12 bytes, but ALIGNED to 16)
mixAmt : f32, // offset 28 (4 bytes) — rides in vec3's pad slot
stage : f32, // offset 32 (4 bytes)
filterMode : f32, // offset 36 (4 bytes)
wrapMode : f32, // offset 40 (4 bytes)
_pad : f32, // offset 44 (explicit tail pad → 48 total)
}; // sizeof = 48 (3 × 16-byte rows)
// ---- JS: the byte-identical Float32Array (12 floats = 48 bytes) ----
const u = new Float32Array(12); // 12 × 4 = 48 bytes
u[0] = canvas.width; u[1] = canvas.height; // resolution.xy → bytes 0..7
u[2] = scale; // scale → bytes 8..11
u[3] = time; // time → bytes 12..15
u[4] = tint.r; u[5] = tint.g; u[6] = tint.b; // tint.xyz → bytes 16..27
u[7] = mixAmt; // mixAmt → bytes 28..31 (vec3 pad!)
u[8] = stage; // stage → bytes 32..35
u[9] = filterMode; // filterMode → bytes 36..39
u[10] = wrapMode; // wrapMode → bytes 40..43
u[11] = 0; // _pad → bytes 44..47
device.queue.writeBuffer(ubo, 0, u); // one upload, whole struct
Notice the trick on line u[7]: mixAmt slots into the 4 bytes
that vec3 tint doesn't use. If instead you'd written tint as
three loose floats and then a vec3 after it, the offsets would shift and the
shader would read your scale where it expected a color. Stage 1
draws this layout — each 16-byte row as a band, each field a colored cell, the
pad cells hatched — so you can see the vec3 reserving a full line.
Rule of thumb: think in 16-byte rows. Group scalars to fill avec4's worth, putvec3s on their own line, and always pad the struct to a multiple of 16. When in doubt, lay everything out asvec4s — wasteful by a few bytes, immune to the footgun.
Stage 2 — Create and upload a procedural texture
No image files. We allocate a Uint8Array of RGBA pixels on the CPU, fill
it with a checkerboard modulated by cheap value-noise, then create a
GPUTexture and copy the bytes in with device.queue.writeTexture.
Two flags matter or nothing works: the texture's usage must include both
TEXTURE_BINDING (so a shader can sample it) and
COPY_DST (so we can write into it).
// Build an RGBA8 checker + noise image on the CPU (TEX×TEX texels)
const TEX = 256;
const pixels = new Uint8Array(TEX * TEX * 4);
for (let y = 0; y < TEX; y++) {
for (let x = 0; x < TEX; x++) {
const cx = (x >> 5) & 1, cy = (y >> 5) & 1; // 32px checker
const base = (cx ^ cy) ? 210 : 40;
const n = noise(x * 0.06, y * 0.06) * 60; // dust it with noise
const i = (y * TEX + x) * 4;
pixels[i+0] = clamp255(base + n);
pixels[i+1] = clamp255(base * 0.8 + n);
pixels[i+2] = clamp255(base * 0.55 + n * 1.5);
pixels[i+3] = 255;
}
}
const texture = device.createTexture({
size: [TEX, TEX, 1],
format: 'rgba8unorm',
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
});
device.queue.writeTexture(
{ texture }, // dest
pixels, // src bytes
{ bytesPerRow: TEX * 4, rowsPerImage: TEX }, // layout (see pitfall ↓)
{ width: TEX, height: TEX }, // copy size
);
const sampler = device.createSampler({
magFilter: 'nearest', minFilter: 'nearest',
addressModeU: 'clamp-to-edge', addressModeV: 'clamp-to-edge',
});
One subtlety hides in bytesPerRow: for arbitrary texture sizes WebGPU
requires it to be a multiple of 256. We sized our texture to 256 wide ×
4 bytes = 1024, which is already a multiple of 256, so we're safe. If your width isn't a
multiple of 64 texels (for RGBA8), you must round bytesPerRow up and copy
row-by-row with padding — see Pitfalls.
Stage 3 — Sample it on the quad (nearest filtering)
Now we wire the texture and sampler into a bind group. A bind group
is a bundle of GPU resources plugged into the numbered slots a pipeline expects. The
pipeline's bind-group layout declares the shape — "binding 0 is a uniform
buffer visible to the fragment stage, binding 1 is a float texture, binding 2 is a
filtering sampler" — and the bind group fills it with concrete objects. Both must agree
with the WGSL @group/@binding decorations exactly.
// The layout: 3 entries, fragment-visible. THIS is the contract.
const layout = device.createBindGroupLayout({
entries: [
{ binding: 0, visibility: GPUShaderStage.FRAGMENT,
buffer: { type: 'uniform' } }, // var<uniform>
{ binding: 1, visibility: GPUShaderStage.FRAGMENT,
texture: { sampleType: 'float' } }, // texture_2d<f32>
{ binding: 2, visibility: GPUShaderStage.FRAGMENT,
sampler: { type: 'filtering' } }, // sampler
],
});
// The bind group: the same 3 slots, now filled with real resources.
const bindGroup = device.createBindGroup({
layout,
entries: [
{ binding: 0, resource: { buffer: ubo } },
{ binding: 1, resource: texture.createView() },
{ binding: 2, resource: sampler },
],
});
// Pipeline uses an EXPLICIT layout built from our bind-group layout.
const pipeline = device.createRenderPipeline({
layout: device.createPipelineLayout({ bindGroupLayouts: [layout] }),
vertex: { module, entryPoint: 'vs' },
fragment: { module, entryPoint: 'fs', targets: [{ format }] },
primitive:{ topology: 'triangle-list' },
});
And the WGSL side — the three declarations whose @binding numbers must
line up with the layout above, plus the actual textureSample call. The
vertex shader emits a fullscreen triangle and hands the fragment shader a UV:
struct VSOut { @builtin(position) pos: vec4f, @location(0) uv: vec2f };
@vertex fn vs(@builtin(vertex_index) i: u32) -> VSOut {
// one oversized triangle covering the screen
var p = array<vec2f, 3>(vec2f(-1,-1), vec2f(3,-1), vec2f(-1,3));
var out: VSOut;
out.pos = vec4f(p[i], 0, 1);
out.uv = 0.5 * (p[i] + vec2f(1, 1)); // clip → [0,1] UV
out.uv.y = 1.0 - out.uv.y; // flip so +V is down
return out;
}
@group(0) @binding(0) var<uniform> U : Uniforms;
@group(0) @binding(1) var tex : texture_2d<f32>;
@group(0) @binding(2) var samp: sampler;
@fragment fn fs(in: VSOut) -> @location(0) vec4f {
let uv = in.uv * U.scale; // scale UVs (stage 4+)
let texel = textureSample(tex, samp, uv); // THE sample
return vec4f(texel.rgb, 1.0);
}
That's the whole texturing path. textureSample(tex, samp, uv) reads the
texture at uv using whatever filtering and wrap modes the sampler was
created with. With a nearest sampler you get crisp, blocky texels — each
output pixel snaps to the closest source texel.
Stage 4 — Linear filtering and wrap modes
The sampler is where filtering and wrapping live — not the shader. Two knobs:
- Filter (
magFilter/minFilter):nearestsnaps to the closest texel (crisp, pixelated when magnified);linearblends the four nearest texels (smooth, blurry when magnified). Flip the filter select and watch the checker edges go from hard stair-steps to soft ramps. - Wrap (
addressModeU/V): what happens when a UV leaves [0,1].clamp-to-edgesmears the border pixel outward;repeattiles the texture. Crank the scale slider past 1 so the UVs run off the edge, then toggle wrap: clamp gives one big stretched cell at the rim, repeat gives a grid of checkers.
Because a sampler is immutable, switching modes means creating new samplers and new bind groups. We build all four combinations (nearest/linear × clamp/repeat) once up front and just select the matching bind group per frame — cheap, no per-frame allocation:
// Pre-build 4 samplers + 4 bind groups; pick by current UI state.
function makeSampler(filter, wrap) {
const f = filter === 'linear' ? 'linear' : 'nearest';
const a = wrap === 'repeat' ? 'repeat' : 'clamp-to-edge';
return device.createSampler({
magFilter: f, minFilter: f, addressModeU: a, addressModeV: a,
});
}
const bindGroups = {};
for (const filter of ['nearest', 'linear'])
for (const wrap of ['clamp', 'repeat'])
bindGroups[filter + '-' + wrap] = device.createBindGroup({
layout,
entries: [
{ binding: 0, resource: { buffer: ubo } },
{ binding: 1, resource: texture.createView() },
{ binding: 2, resource: makeSampler(filter, wrap) },
],
});
Stage 5 — Animate the UVs with a uniform
The texture never changes — but the coordinates we feed
textureSample can. We push time into the uniform buffer each
frame and offset/zoom the UV in the shader. This is how scrolling skies, flowing water,
and parallax layers work: cheap UV math over a static texture.
@fragment fn fs(in: VSOut) -> @location(0) vec4f {
var uv = in.uv;
// stage 5+: scroll diagonally and gently zoom over time
let t = U.time;
uv += vec2f(t * 0.05, t * 0.03); // scroll
uv *= U.scale * (1.0 + 0.15 * sin(t * 0.6)); // breathing zoom
let texel = textureSample(tex, samp, uv);
return vec4f(texel.rgb, 1.0);
}
Set wrap to repeat here for a seamless infinite scroll; with
clamp you'll see the edge texel smear once the offset pushes past 1. Same
static 256×256 image, infinite motion.
Stage 6 — Texture + uniforms, composed
The finale brings the uniform color back in. We sample the (scrolling) texture, then
mix it toward a tint color by mixAmt, and let
time pulse the whole thing. Texture data and uniform constants flowing
through one bind group, combined in four lines:
@fragment fn fs(in: VSOut) -> @location(0) vec4f {
var uv = in.uv * U.scale + vec2f(U.time * 0.05, 0.0);
let texel = textureSample(tex, samp, uv).rgb;
let tinted = mix(texel, U.tint, U.mixAmt); // blend toward tint
let pulse = 0.85 + 0.15 * sin(U.time * 1.5); // breathe brightness
return vec4f(tinted * pulse, 1.0);
}
Drag the tint and tint hue sliders: tint hue drives the
color (the JS converts hue→RGB and writes it into the vec3 field),
tint drives mixAmt. Every slider you move is just a different
Float32Array uploaded to the same uniform buffer — no pipeline rebuild, no
re-record beyond the per-frame draw.
Common pitfalls
- Uniform struct alignment (the big one). A
vec3<f32>reserves 16 bytes, not 12. If your JS stride is wrong, every field after thevec3is misread — colors become scales, time becomes tint — usually with no error at all, just garbage on screen. Lay out in 16-byte rows, pad the struct to a multiple of 16, and prefer packing scalars into avec3's spare slot only when you've counted the bytes. When unsure, make everythingvec4. - Missing texture usage flags.
createTexture.usagemust includeTEXTURE_BINDING | COPY_DST— the first to sample it, the second towriteTextureinto it. Omit either and you get a validation error at bind-group or upload time. bytesPerRowmust be a multiple of 256.writeTexture(and texture-to-buffer copies) require row pitch aligned to 256 bytes. RGBA8 at 256px wide = 1024 bytes/row, fine. For odd widths, roundbytesPerRowup to the next 256 and stage a padded buffer — don't pass the tight width.- Sampler/texture not in the layout, or wrong visibility. Every
resource the shader touches needs an entry in the bind-group layout with
visibilitycovering the stage that uses it (hereFRAGMENT). Afilteringsampler also requires afloat-sampleable texture; pair'non-filtering'with'unfilterable-float'if you sample without filtering. - Binding numbers must match. WGSL
@binding(1), the layout entrybinding: 1, and the bind-group entrybinding: 1are one slot. A mismatch throws at pipeline or bind-group creation — read the validation message; it names the offending binding. - Forgetting to re-upload the buffer.
writeBuffercopies now; mutating yourFloat32Arrayafterward does nothing until you call it again. Re-upload every frame you change a uniform.
Exercises
- A second texture, blended. Generate a second procedural image (a
diagonal stripe pattern), add a
texture_2d<f32>at@binding(3)(and its layout entry), andmixthe two samples by a newblenduniform field. Mind the alignment when you add the field. - Time-based UV warp. In the fragment shader, displace the UV by a
sine of position and
time—uv += 0.02 * vec2f(sin(uv.y*20.0 + U.time), cos(uv.x*20.0 + U.time))— for a heat-haze wobble. Notice it costs nothing extra; it's just more math on the lookup coordinate. - Gradient-ramp texture. Swap the checker generator for a smooth horizontal gradient (or a 256×1 ramp) and sample it with a computed UV to use the texture as a color lookup table — the same trick games use for tone-mapping and palettes.
What's next
Episode 05 — Storage buffers + instancing: 100,000 sprites in one draw
call. We graduate from one fullscreen quad to a hundred thousand instances,
each pulling its own position and color from a big storage buffer (the
read/write cousin of the uniform buffer, with looser size limits), and draw them all
with a single draw(6, 100000). The bind-group muscle you built today is
exactly what feeds the instances their per-sprite data — and it's the on-ramp to the
compute episodes after it.