home/ atoms/ wgsl-fragment-shader-basics

A WGSL fragment shader is an @fragment function that returns a vec4f RGBA color tagged @location(0) for the first color attachment

A WGSL fragment shader is a function decorated with @fragment. It returns a vec4f RGBA color tagged with @location(0) to indicate it writes to the first color attachment. Components are (red, green, blue, alpha) in [0, 1]. Fragment shaders run once per rasterized pixel and may receive inter-stage variables from the vertex shader via @location(n) inputs. The simplest fragment shader returns a constant color; more complex ones use inter-stage data, textures, or geometry to vary color.

Examples

@fragment
fn fragmentMain() -> @location(0) vec4f {
  return vec4f(1, 0, 0, 1); // Solid red
}
// With inter-stage input:
@fragment
fn fragmentMain(@location(0) cell: vec2f) -> @location(0) vec4f {
  return vec4f(cell, 0, 1);
}

Assessment

Write a WGSL fragment shader that outputs solid green. Then modify it to accept a vec2f at @location(0) and use its components as the red and green channels.

“Fragment shaders are always called after vertex shaders. The GPU takes the outpu”
corpus · your-first-webgpu-app-google-codelab · chunk 7