demo · v142
Triangle Picking
The use case the WebGPU CTS authors keep flagging: render a mesh to an "ID buffer" where each fragment writes its primitive_index as a colour, then read back the pixel under the cursor to know which triangle was clicked. Pure GPU picking, no CPU ray-tracing, no per-vertex ID attribute.
Requires Chrome 142+ with WebGPU and the optional
primitive-index adapter feature. On unsupported hardware the canvas stays black and the readouts say "no".
primitive-index feature
—
last clicked triangle
click a triangle
The pick works by sampling the ID-render target at the cursor's pixel. Encoding primitive_index into red/green channels gives 65,536 unique IDs.
shader snippet
// fragment shader writes the primitive index as RG colour
@fragment
fn fs(@builtin(primitive_index) idx: u32) -> @location(0) vec4<f32> {
let r = f32(idx & 0xff) / 255.0;
let g = f32((idx >> 8) & 0xff) / 255.0;
return vec4<f32>(r, g, 0.0, 1.0);
}
// later, on click: read one pixel back, decode r + g*256 = triangle index