Skip to content

Instantly share code, notes, and snippets.

@greggman
Created November 17, 2022 08:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greggman/17ae615b9cf4380e6520d5d4d92f3c0d to your computer and use it in GitHub Desktop.
Save greggman/17ae615b9cf4380e6520d5d4d92f3c0d to your computer and use it in GitHub Desktop.
WebGPU hello triangle via uniform array
/*bug-in-github-api-content-can-not-be-empty*/
<canvas></canvas>
async function run() {
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
const context = document.querySelector('canvas').getContext('webgpu');
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format: presentationFormat,
alphaMode: 'opaque',
});
const module = device.createShaderModule({
code: `
@group(0) @binding(0) var<uniform> myUniforms: array<vec3<f32>, 3>;
@vertex fn vs(
@builtin(vertex_index) VertexIndex : u32
) -> @builtin(position) vec4<f32> {
return vec4(myUniforms[VertexIndex], 1.0);
}
@fragment fn fs() -> @location(0) vec4<f32> {
return vec4(1.0, 0.0, 0.0, 1.0);
}
`,
});
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module,
entryPoint: 'vs',
},
fragment: {
module,
entryPoint: 'fs',
targets: [{ format: presentationFormat }],
},
});
const vsUniformBuffer = device.createBuffer({
size: 16 * 4 * 4,
usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(vsUniformBuffer, 0, new Float32Array([
0, -0.8, 0, 0,
-0.8, 0.8, 0, 0,
0.8, 0.8, 0, 0,
]));
const bindGroup = device.createBindGroup({
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: vsUniformBuffer } },
],
});
function frame() {
const encoder = device.createCommandEncoder();
const pass = encoder.beginRenderPass({
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
clearValue: [0.0, 0.0, 0.0, 0.0],
loadOp: 'clear',
storeOp: 'store',
},
],
});
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindGroup);
pass.draw(3);
pass.end();
device.queue.submit([encoder.finish()]);
}
requestAnimationFrame(frame);
}
run();
{"name":"WebGPU hello triangle via uniform array","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