TExcelTAD
Home › Shaders & Graphics Programming › WebGPU and WGSL

WebGPU and WGSL

WebGPU is the successor to WebGL: a modern GPU API for the web, designed by the W3C's GPU for the Web group with input from the Vulkan, Direct3D 12 and Metal worlds. Its shader language is WGSL (WebGPU Shading Language). Browsers implement it on top of the native API of each platform (Chrome's Dawn and Firefox's wgpu translate to D3D12, Vulkan or Metal), and the same libraries run natively too, so WebGPU is also a portable desktop API for C++ (Dawn) and Rust (wgpu).

For learning, WebGPU sits in a sweet spot: it has the structure of Vulkan (pipelines, bind groups, command encoders, explicit render passes) without manual memory management or synchronization.

Note: WebGPU shipped in Chrome and Edge on desktop in 2023 and has since been rolling out to other browsers and platforms. Support still varies by browser, OS and GPU, so check current support (for example on caniuse.com) and keep a WebGL2 fallback for public games. Three.js has a WebGPURenderer that falls back to WebGL2 automatically.

WGSL in five minutes

WGSL looks more like Rust than C:

GLSL WGSL
vec2 vec3 vec4 (float) vec2f vec3f vec4f (shorthand for vec3<f32>)
ivec2, uvec2 vec2i, vec2u
float x = 1.0; var x: f32 = 1.0; or let x = 1.0; (immutable)
const float PI = 3.14159; const PI = 3.14159;
float f(float a) { … } fn f(a: f32) -> f32 { … }
mat4 m; m * v mat4x4f, m * v (column-major, like GLSL)
in/out variables function parameters and return values with @location(n)
gl_Position, gl_VertexID, gl_FragCoord @builtin(position), @builtin(vertex_index), @builtin(position) in a fragment input
uniform Block { … }; @group(0) @binding(0) var<uniform> u: Block;
mix, fract, clamp, smoothstep same names
mod(x, y) x % y (sign follows x, like C)
implicit int → float in some contexts never: write f32(i)

A complete WGSL module: a full-screen triangle (three vertices generated from the index, no vertex buffer) and the gradient shader from the first lesson:

wgsl
struct Uniforms {
    resolution: vec2f,   // offset 0, 8 bytes
    time: f32,           // offset 8, 4 bytes (struct size rounds up to 16)
};

@group(0) @binding(0) var<uniform> u: Uniforms;

@vertex
fn vs_main(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
    // One triangle that covers the screen: (-1,-1), (3,-1), (-1,3)
    var pos = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
    return vec4f(pos[i], 0.0, 1.0);
}

@fragment
fn fs_main(@builtin(position) frag: vec4f) -> @location(0) vec4f {
    // frag.xy is in pixels with the origin at the TOP-left (unlike gl_FragCoord)
    let uv = vec2f(frag.x / u.resolution.x, 1.0 - frag.y / u.resolution.y);
    let color = vec3f(uv.x, uv.y, 0.5 + 0.5 * sin(u.time));
    return vec4f(color, 1.0);
}

Uniform buffers follow strict alignment rules: a vec2f aligns to 8 bytes, a vec3f and vec4f to 16, and the struct size rounds up to its largest alignment. Putting a vec3f after a lone f32 silently inserts padding, the classic "my uniforms are garbage" bug (it exists in GLSL's std140 layout too). Ordering members from large to small avoids most of it.

The JavaScript side

The host code mirrors the Vulkan objects you met in the last two lessons:

WebGPU Vulkan equivalent
GPUAdapter (navigator.gpu.requestAdapter()) physical device
GPUDevice (adapter.requestDevice()) logical device
device.queue queue
canvas context configure() swapchain
GPURenderPipeline graphics pipeline
GPUBindGroup / GPUBindGroupLayout descriptor set / descriptor set layout
GPUCommandEncoder + beginRenderPass() command buffer + vkCmdBeginRendering
js
const adapter = await navigator.gpu?.requestAdapter();
if (!adapter) throw new Error('WebGPU is not available');
const device = await adapter.requestDevice();

const canvas = document.querySelector('canvas');
const context = canvas.getContext('webgpu');
const format = navigator.gpu.getPreferredCanvasFormat();     // 'bgra8unorm' or 'rgba8unorm'
context.configure({ device, format });

const module = device.createShaderModule({ code: wgslSource });
const pipeline = device.createRenderPipeline({
  layout: 'auto',                                             // derive bind group layouts from the shader
  vertex: { module, entryPoint: 'vs_main' },
  fragment: { module, entryPoint: 'fs_main', targets: [{ format }] },
  primitive: { topology: 'triangle-list' },
});

const uniformBuffer = device.createBuffer({ size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
const bindGroup = device.createBindGroup({
  layout: pipeline.getBindGroupLayout(0),
  entries: [{ binding: 0, resource: { buffer: uniformBuffer } }],
});

function frame(ms) {
  device.queue.writeBuffer(uniformBuffer, 0, new Float32Array([canvas.width, canvas.height, ms / 1000, 0]));
  const encoder = device.createCommandEncoder();
  const pass = encoder.beginRenderPass({
    colorAttachments: [{
      view: context.getCurrentTexture().createView(),        // this frame's swapchain image
      clearValue: { r: 0, g: 0, b: 0, a: 1 }, loadOp: 'clear', storeOp: 'store',
    }],
  });
  pass.setPipeline(pipeline);
  pass.setBindGroup(0, bindGroup);
  pass.draw(3);                                               // the full-screen triangle
  pass.end();
  device.queue.submit([encoder.finish()]);
  requestAnimationFrame(frame);
}
requestAnimationFrame(frame);

Note what is missing compared with Vulkan: no fences, no semaphores, no image layouts, no memory types. The implementation tracks resource usage and inserts the barriers. You still get the explicit structure (pipelines built up front, bind groups, command encoding), which is where performance comes from.

Try it

The same program, live. If your browser or GPU has no WebGPU, it prints a message instead of drawing.

html · try it yourself
<style>html, body { margin: 0; height: 100%; background: #111; color: #ddd; font: 14px system-ui; } canvas { display: block; width: 100%; height: 100%; }</style>
<canvas></canvas>
<script type="module">
const wgsl = `
struct Uniforms { resolution: vec2f, time: f32 };
@group(0) @binding(0) var<uniform> u: Uniforms;

@vertex fn vs_main(@builtin(vertex_index) i: u32) -> @builtin(position) vec4f {
  var pos = array<vec2f, 3>(vec2f(-1.0, -1.0), vec2f(3.0, -1.0), vec2f(-1.0, 3.0));
  return vec4f(pos[i], 0.0, 1.0);
}

@fragment fn fs_main(@builtin(position) frag: vec4f) -> @location(0) vec4f {
  let uv = vec2f(frag.x / u.resolution.x, 1.0 - frag.y / u.resolution.y);
  let p = (uv - 0.5) * vec2f(u.resolution.x / u.resolution.y, 1.0);
  let ring = 1.0 - smoothstep(0.0, 0.02, abs(length(p) - 0.3 - 0.05 * sin(u.time * 2.0)));
  let color = vec3f(uv.x, uv.y, 0.5 + 0.5 * sin(u.time)) * 0.6 + vec3f(ring);
  return vec4f(color, 1.0);
}`;

const canvas = document.querySelector('canvas');
const adapter = navigator.gpu ? await navigator.gpu.requestAdapter() : null;
if (!adapter) {
  document.body.textContent = 'WebGPU is not available in this browser or on this GPU. The WebGL2 playgrounds in this course still work.';
  console.log('WebGPU not available');
} else {
  const device = await adapter.requestDevice();
  canvas.width = Math.floor(innerWidth * devicePixelRatio);
  canvas.height = Math.floor(innerHeight * devicePixelRatio);
  const context = canvas.getContext('webgpu');
  const format = navigator.gpu.getPreferredCanvasFormat();
  context.configure({ device, format });

  const module = device.createShaderModule({ code: wgsl });
  const info = await module.getCompilationInfo();
  for (const m of info.messages) console.log(`WGSL ${m.type} line ${m.lineNum}: ${m.message}`);

  const pipeline = device.createRenderPipeline({
    layout: 'auto',
    vertex: { module, entryPoint: 'vs_main' },
    fragment: { module, entryPoint: 'fs_main', targets: [{ format }] },
    primitive: { topology: 'triangle-list' },
  });
  const ubo = device.createBuffer({ size: 16, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST });
  const bindGroup = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [{ binding: 0, resource: { buffer: ubo } }] });

  function frame(ms) {
    device.queue.writeBuffer(ubo, 0, new Float32Array([canvas.width, canvas.height, ms / 1000, 0]));
    const encoder = device.createCommandEncoder();
    const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(), clearValue: { r: 0, g: 0, b: 0, a: 1 }, loadOp: 'clear', storeOp: 'store' }] });
    pass.setPipeline(pipeline);
    pass.setBindGroup(0, bindGroup);
    pass.draw(3);
    pass.end();
    device.queue.submit([encoder.finish()]);
    requestAnimationFrame(frame);
  }
  requestAnimationFrame(frame);
  console.log(`WebGPU running, canvas format ${format}`);
}
</script>

getCompilationInfo() returns WGSL errors and warnings with line numbers: break the shader (delete a ;) and run it to see them. Errors in pipeline or bind group creation are reported as validation errors in the browser's developer console.

Compute shaders

WebGPU also has compute shaders, which WebGL never had: general-purpose GPU programs that read and write storage buffers, used for particles, culling, physics and image processing.

wgsl
@group(0) @binding(0) var<storage, read_write> positions: array<vec2f>;
@group(0) @binding(1) var<storage, read> velocities: array<vec2f>;

@compute @workgroup_size(64)
fn integrate(@builtin(global_invocation_id) id: vec3u) {
    let i = id.x;
    if (i >= arrayLength(&positions)) { return; }      // the last workgroup may run past the end
    positions[i] += velocities[i] * (1.0 / 60.0);
}

Dispatch it with pass.dispatchWorkgroups(Math.ceil(count / 64)) inside encoder.beginComputePass().

Porting GLSL to WGSL

Tools translate between the languages: naga (part of wgpu) and Tint (part of Dawn) convert SPIR-V or GLSL to WGSL and back, and Slang can emit WGSL. They are listed in the Toolkit. For short shaders, porting by hand with the table above takes minutes.

Test yourself

Which WebGPU object plays the role of a Vulkan descriptor set?

  1. GPUBuffer
  2. GPUBindGroup
  3. GPURenderPipeline
  4. GPUQueue

Where is the origin of @builtin(position) in a WGSL fragment shader?

  1. Bottom-left, like gl_FragCoord
  2. Top-left
  3. Center of the screen
  4. It is in NDC, not pixels

What does WebGPU do for you that Vulkan does not?

  1. Compiles pipelines lazily at draw time
  2. Tracks resource usage and handles synchronization and memory types
  3. Removes the need for shaders
  4. Lets you skip render passes