Created
August 28, 2025 21:23
-
-
Save greggman/41fd862cb4e9cee690a76858279019fb to your computer and use it in GitHub Desktop.
WebGPU: Hello Triangle Compute Shader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*bug-in-github-api-content-can-not-be-empty*/ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<canvas></canvas> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const adapter = await navigator.gpu.requestAdapter(); | |
const device = await adapter.requestDevice(); | |
device.addEventListener('uncapturederror', e => console.log(e.error.message)); | |
const module = device.createShaderModule({ | |
code: ` | |
@group(0) @binding(0) var tex: texture_storage_2d<rgba8unorm, write>; | |
@compute @workgroup_size(1) fn cs(@builtin(global_invocation_id) pos: vec3u) { | |
let half = textureDimensions(tex).x / 2; | |
var color = vec4f(1, 0, 0, 1); | |
if (abs(i32(pos.x - half)) > i32(pos.y)) { | |
color = vec4f(0, 0, 1, 1); | |
} | |
textureStore(tex, pos.xy, color); | |
} | |
`, | |
}); | |
const pipeline = device.createComputePipeline({ layout: 'auto', compute: { module } }); | |
const canvas = document.querySelector('canvas'); | |
const context = canvas.getContext('webgpu'); | |
context.configure({ | |
device, | |
format: 'rgba8unorm', | |
usage: GPUTextureUsage.STORAGE_BINDING | GPUTextureUsage.TEXTURE_BINDING, | |
}); | |
const texture = context.getCurrentTexture(); | |
const bindGroup = device.createBindGroup({ | |
layout: pipeline.getBindGroupLayout(0), | |
entries: [ | |
{ binding: 0, resource: texture.createView() }, | |
], | |
}); | |
const encoder = device.createCommandEncoder(); | |
const pass = encoder.beginComputePass(); | |
pass.setPipeline(pipeline); | |
pass.setBindGroup(0, bindGroup); | |
pass.dispatchWorkgroups(texture.width, texture.height); | |
pass.end(); | |
device.queue.submit([encoder.finish()]); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"name":"WebGPU: Hello Triangle Compute Shader","settings":{},"filenames":["index.html","index.css","index.js"]} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment