WebGPU From Zero · Episode 03

WGSL, the Shading Language

WGSL, the Shading Language is Episode 03 of WebGPU From Zero, a MasterAllArts free interactive lesson for artists learning creative 3D on the web.

Part of the MasterAllArts Creative 3D Roadmap .

Episode 03 · WebGPU From Zero

Every pixel you ever draw with WebGPU is decided by a program that runs on the GPU, in parallel, millions of times at once — once per pixel, every frame. That program is written in WGSL, the WebGPU Shading Language. It's the thing you'll type the most in this whole series, and right now it probably looks alien: @builtin, vec3f, f32, angle brackets everywhere. By the end of this page it won't. You'll be able to read it like English and bend the pattern below to your will.

So here's the promise: one fullscreen fragment shader, six stages, growing from a flat color into a hypnotic, mouse-reactive field of glowing shapes and color — and at every step the actual WGSL that produces it, explained line by line. Drag the sliders, flip the palette, move your mouse over it. This is a playground first and a grammar lesson second. Let's make WGSL stop looking like punctuation soup.

0 fps
move your mouse over the pattern
init…
Cosine palette, glow, and mouse reactivity — the shareable payoff.

Backend badge bottom-left: WebGPU if your browser supports it (Chrome / Edge 113+), or fallback (no WebGPU) with a Canvas2D twin so the page is alive everywhere. Everything below describes the real WebGPU path.

What you're looking at

A single triangle covers the whole canvas, and a fragment shader runs once for every pixel it covers. There is no geometry to speak of — no mesh, no vertices you care about. All the imagery comes from math evaluated per pixel: take the pixel's coordinate, do some arithmetic, return a color. That's the entire model, and it's the same model as GLSL shadertoys, just in a new, stricter language.

The six stages are six versions of that fragment function, from the most trivial (return one constant color) to the full thing (signed-distance shapes, a time-driven wave, and a cosine color palette with a glow that chases your mouse). Each stage maps 1:1 to a heading below. Step through them in the stage dropdown as you read.

Stage 1 — A color, returned from a function

The simplest possible fragment shader ignores everything and returns a single color. In WGSL a fragment shader is just a function marked @fragment whose return value is tagged @location(0) — meaning "this is the color for render target zero," i.e. the screen.

@fragment
fn fs() -> @location(0) vec4f {
  // r, g, b, a — all f32 in 0..1. The 1.0 suffix is mandatory (see pitfalls).
  return vec4f(0.85, 0.32, 0.18, 1.0);
}

Three things to notice right away. Functions use fn, not void main. The return type comes after a -> arrow, not before the name. And vec4f is WGSL's short alias for vec4<f32> — a 4-component vector of 32-bit floats. Those four numbers are red, green, blue, alpha. Change them, recompile, get a different flat color. That's a shader.

Stage 2 — UV coordinates and the builtins

To make anything interesting we need to know where we are. The vertex shader hands the fragment shader the pixel's screen position through a @builtin(position). Critically — and this is the #1 thing GLSL veterans get wrong — that builtin is in pixels, not 0→1. So we divide by the resolution (passed in via a uniform, covered next stage) to get normalized uv in 0→1, then use it as the red/green channels.

@fragment
fn fs(@builtin(position) frag: vec4f) -> @location(0) vec4f {
  // frag.xy is in PIXELS. Divide by resolution → 0..1 uv.
  let uv = frag.xy / u.res;        // .xy is a swizzle: pull two components out
  return vec4f(uv, 0.0, 1.0);     // vec4f(vec2, f32, f32) → packs uv into rg
}

Two new ideas. uv = frag.xy uses a swizzle: writing .xy after a vector pulls out a smaller vector of just those components. You can reorder and repeat too — v.yx, v.xxx, v.rgba (xyzw and rgba are interchangeable). And vec4f(uv, 0.0, 1.0) shows WGSL's handy constructor flattening: you can build a vec4 out of a vec2 plus two scalars, as long as the component count adds up to four.

Left edge is black, right edge is red (u→1), top is green-ier (v→1). It's the classic "am I alive" gradient. let declares an immutable binding — like const in JS. We'll meet its mutable sibling var in stage 5.

Stage 3 — A circle, and your first function

Now the headline concept of procedural graphics: the signed distance function (SDF). An SDF takes a point and returns how far it is from a shape — negative inside, zero on the edge, positive outside. The SDF of a circle is dead simple: distance from center, minus radius. We factor it into its own WGSL function so we can reuse it. This is the block to study — it's where the type rules bite.

// A WGSL function: typed params, an arrow, a typed return.
fn sdCircle(p: vec2f, r: f32) -> f32 {
  return length(p) - r;          // length() is built in
}

@fragment
fn fs(@builtin(position) frag: vec4f) -> @location(0) vec4f {
  // center the coords and fix aspect so the circle stays round
  let uv = (frag.xy * 2.0 - u.res) / u.res.y;
  let d  = sdCircle(uv, 0.5);
  // smoothstep gives an antialiased edge instead of a hard step()
  let m  = 1.0 - smoothstep(0.0, 0.01, d);
  return vec4f(vec3f(m), 1.0);  // vec3f(m) = (m, m, m): grayscale
}

Look at the function signature: each parameter is name: type, the return type follows the arrow, and there are no surprises — WGSL won't quietly convert an int you pass into a float it wanted. length(), smoothstep(), and step() are built-in just like in GLSL. And notice the splat constructor vec3f(m): handing a single scalar to a vector constructor fills all components with it, so that's (m, m, m) — a clean grayscale. (Try the freq slider here — it warps the radius so the disc breathes.)

Stage 4 — Animation, and the Uniforms struct

To animate we need time, resolution, and the mouse inside the shader. The GPU can't read JS variables; you hand data across the boundary through a uniform buffer. On the WGSL side it's a struct bound with @group and @binding. This is the block that connects the two worlds — read it next to the JS that fills it.

// === WGSL side: the contract ===
struct Uniforms {
  res:   vec2f,   // canvas size in pixels  (offset 0)
  mouse: vec2f,   // mouse in pixels        (offset 8)
  time:  f32,     // seconds                (offset 16)
  freq:  f32,     // from the slider        (offset 20)
  count: f32,     // shape count            (offset 24)
  pal:   f32,     // palette index          (offset 28)
  mouseOn: f32,   // 0 or 1                 (offset 32)
};
@group(0) @binding(0) var<uniform> u: Uniforms;
// === JS side: write the SAME byte layout ===
const ubo = device.createBuffer({
  size: 48,  // round UP to a multiple of 16 — see pitfalls
  usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
const data = new Float32Array([
  canvas.width, canvas.height,  // res   → u.res
  mouseX, mouseY,               // mouse → u.mouse
  timeSeconds, freq, count, pal, mouseOn,  // the f32 tail
  0, 0, 0,                      // pad to 48 bytes (12 floats)
]);
device.queue.writeBuffer(ubo, 0, data);

The order and types of the struct fields and the floats in the array must match exactly — the GPU just reinterprets bytes. With u.time in hand, the shader can move: feed time into a sin() and the field ripples. The whole stage is one line of animated arithmetic:

// inside fs(), with centered uv:
let wave = sin(uv.x * u.freq + u.time) * 0.5 + 0.5;
let band = sin(uv.y * u.freq - u.time * 1.3) * 0.5 + 0.5;
return vec4f(vec3f(wave, band, wave * band), 1.0);

Notice 0.5 and 1.3 are written with decimal points on purpose. In WGSL 1.3 is an f32 but 2 is an integer, and you cannot multiply an f32 by an integer without an explicit cast. Drag freq and watch the wavelength change in real time — you're editing u.freq from JS, the shader re-reads it every frame.

Stage 5 — A little SDF scene: min(), and a loop

One shape is lonely. To combine several SDFs you take the min() of their distances — the union of shapes is "the distance to the nearest one." We orbit a handful of circles and union them in a for loop. This stage introduces the mutable var (a loop accumulator must be reassignable) and the strict i32 → f32 cast you need when a loop counter meets float math.

var d = 1e9;                          // var: mutable. let would be illegal here.
let n = i32(u.count);                 // cast f32 uniform → i32 for the loop bound
for (var i = 0; i < n; i = i + 1) {
  // i is i32; f32(i) is REQUIRED — no implicit int→float cast in WGSL
  let a = f32(i) / f32(n) * 6.2831853 + u.time;
  let c = vec2f(cos(a), sin(a)) * 0.55;  // orbit center
  d = min(d, sdCircle(uv - c, 0.18));   // union
}

The cast points are the whole lesson. i is an i32 because integer literals are integers; the moment you want i in float arithmetic you must write f32(i). GLSL would silently promote it; WGSL refuses, and that refusal is a feature — it means a shader either compiles correctly or tells you exactly which line is wrong. The count slider drives n; crank it and more orbiting blobs melt together via min().

Stage 6 — Cosine palette, glow, and the mouse

The shareable payoff. We color the scene with Inigo Quilez's cosine palette — four vec3 coefficients fed through a cosine give an infinite smooth gradient with one knob. We add a soft glow that falls off with distance from the shapes, and we let the mouse nudge the field around. Here's the palette function and the heart of the final fragment:

// Cosine gradient: a, b control center+amplitude; c, d control freq+phase.
fn palette(t: f32, a: vec3f, b: vec3f, c: vec3f, d: vec3f) -> vec3f {
  // 6.28318 = 2π. cos() works component-wise on a vec3.
  return a + b * cos(6.28318 * (c * t + d));
}
// …after the loop builds `d` (nearest-shape distance):
let fill  = 1.0 - smoothstep(0.0, 0.02, d);    // solid body, AA edge
let glow  = 0.02 / max(abs(d), 0.001);     // 1/d halo — guard the divide!
let tone  = palette(d * 2.0 + u.time * 0.2, A, B, C, D);
let col   = tone * (fill + glow * 0.6);     // swizzle-free vec3 math
return vec4f(col, 1.0);

That's the entire visible language surface: typed functions, vec3 arithmetic that operates component-wise, a built-in cos() that maps over a vector, swizzles, smoothstep for soft edges, and a carefully guarded 1/d glow (an unguarded divide-by-zero would punch a hole in the image). The palette dropdown swaps the A/B/C/D coefficient sets; with the mouse toggle on, your cursor warps the field and brightens the nearest blobs. This is the frame you'd screenshot.

WGSL vs GLSL — the cheat sheet

If you already know GLSL, almost everything transfers — the differences are mostly spelling and strictness. Keep this table next to you for a week and the friction disappears:

ConceptGLSLWGSL
Functionfloat f(vec2 p){…}fn f(p: vec2f) -> f32 {…}
Float vectorvec3vec3f / vec3<f32>
Const / mutableconst / (plain)let / var
Entry pointvoid main()@fragment fn fs() -> @location(0) vec4f
Pixel positiongl_FragCoord@builtin(position) (also pixels)
Output colorgl_FragColor =return a @location(0) value
Uniformsloose uniform floatsa struct + @group/@binding
Int → floatimplicitexplicit f32(i)
Splat ctorvec3(x)vec3f(x) (same idea, strict)

The single biggest mental shift: WGSL has no implicit numeric conversions. GLSL will happily let 1 stand in for 1.0; WGSL treats them as different types and makes you say which you mean. It feels pedantic for a day and then saves you from a category of bug that used to be invisible.

Common pitfalls

  • 1.0 vs 1 — and no implicit casts. A number with a decimal point is f32; one without is an integer. You can't mix them: uv * 2 is a type error, write uv * 2.0. To use an integer in float math, wrap it: f32(i). This is the error you'll hit most in your first hour.
  • Uniform buffers want 16-byte alignment. A uniform struct's total size must round up to a multiple of 16 bytes, and vec3f aligns to 16 too (it eats the same space as a vec4f). Our struct is 36 bytes of data, so we size the buffer to 48 and pad the JS array with zeros. Wrong stride = garbage values or a validation error at draw time.
  • @builtin(position) is in pixels. Unlike a 0→1 texture coordinate, the fragment position is the actual pixel (e.g. 1280, 720). Always divide by u.res before using it as a UV, or your whole pattern collapses into the bottom-left pixel.
  • Vector constructors are strict about counts. vec3f(x) means (x,x,x); vec3f(x,y,z) means three distinct components; vec3f(uv, z) flattens a vec2 plus a scalar. But vec3f(x, y) (only two args, no splat) is an error — the components must add up to exactly three.
  • var vs let. let is an immutable binding (you can't reassign it); var is mutable. A loop counter or an accumulator you update must be var. Reach for let by default and only upgrade to var when you actually reassign.
  • Guard your divides. The 1/d glow blows up to infinity at d = 0. Clamp the denominator (max(abs(d), 0.001)) or you'll get NaNs that render as black holes or flicker.

Exercises

  1. Add a box SDF and union it in. Write fn sdBox(p: vec2f, b: vec2f) -> f32 { let q = abs(p) - b; return length(max(q, vec2f(0.0))) + min(max(q.x, q.y), 0.0); }, then inside the loop do d = min(d, sdBox(uv - c, vec2f(0.16))) on alternate i. Watch min() fuse squares and circles into one blobby creature.
  2. Expose a warp uniform. Add a warp: f32 field to the struct (remember to bump the buffer size and pad to 16), wire a slider to it, and distort the UV before the scene: let uv2 = uv + u.warp * vec2f(sin(uv.y*3.0 + u.time), cos(uv.x*3.0));. A tiny value makes the whole field swim.
  3. Make the palette mouse-driven. In stage 6, replace the time term in the palette call's t with a value derived from the mouse: let t = d * 2.0 + (u.mouse.x / u.res.x) * 3.0;. Now dragging horizontally scrubs the entire color scheme — a one-line shareable knob.

What's next

Episode 04 — getting data IN: uniforms, textures, samplers, and the bind-group model. We've been sneaking a single uniform buffer across the JS↔GPU boundary; next we do it properly. You'll learn the full bind-group layout system, how to upload an image as a texture, what a sampler actually does, and how to feed several resources into one shader at once. It's the plumbing that turns a toy pattern into a real renderer.