home/ atoms/ wgsl-vertex-shader-basics

A WGSL vertex shader is an @vertex function that takes @location inputs from the vertex buffer and returns a @builtin(position) vec4f

WGSL vertex shaders are functions decorated with @vertex. They must return at least a @builtin(position) vec4f — the clip-space position. Vertex buffer attributes are received as function arguments tagged with @location(n) matching the shaderLocation in the vertex buffer layout. The position is a vec4f(x, y, z, w) where w is typically 1. WGSL uses fn for functions, -> for return type, and vec2f/vec4f for typed vectors. Shaders are passed as strings to device.createShaderModule({ code }).

Examples

@vertex
fn vertexMain(@location(0) pos: vec2f) -> @builtin(position) vec4f {
  return vec4f(pos, 0, 1);
}

vec4f(pos, 0, 1) expands the 2D pos into the x,y components and sets z=0, w=1.

Assessment

Write a minimal WGSL vertex shader that reads a 2D position from @location(0) and returns it in clip space with z=0, w=1. Name three WGSL keywords that differ from JavaScript.

“vertex shader is defined as a function, and the GPU calls that function once for”
corpus · your-first-webgpu-app-google-codelab · chunk 6