Skip to content

Instantly share code, notes, and snippets.

@greggman
Last active February 23, 2024 00:05
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/dedef14ad06d72fda84ff8a83f6f44bc to your computer and use it in GitHub Desktop.
Save greggman/dedef14ad06d72fda84ff8a83f6f44bc to your computer and use it in GitHub Desktop.
Hello Triangle - WebGPU Utils
/*bug-in-github-api-content-can-not-be-empty*/
<script src="https://greggman.github.io./webgpu-utils/dist/1.x/webgpu-utils.js"></script>
async function main({adapter}) {
const device = await adapter?.requestDevice();
const { context, presentationFormat } = getContext(device, 640, 480);
const { buffers, bufferLayouts, numElements } = webgpuUtils.createBuffersAndAttributesFromArrays(device, { position: [
0, 0.5, 0,
-0.5, -0.5, 1,
0.5, -0.5, 1
] });
const module = device.createShaderModule({ code: `
struct MyVSInput { @location(0) position: vec4f, };
@vertex fn myVSMain(v: MyVSInput) -> @builtin(position) vec4f { return v.position; }
@fragment fn myFSMain() -> @location(0) vec4f { return vec4f(1, 0, 0, 1); }
`});
const pipeline = device.createRenderPipeline({ layout: 'auto',
vertex: { module, buffers: bufferLayouts },
fragment: { module, targets: [ {format: presentationFormat} ] },
});
const commandEncoder = device.createCommandEncoder();
const passEncoder = beginRenderPass(commandEncoder, [context.getCurrentTexture()]);
passEncoder.setPipeline(pipeline);
passEncoder.setVertexBuffer(0, buffers[0]);
passEncoder.draw(numElements);
passEncoder.end();
device.queue.submit([commandEncoder.finish()]);
}
// below there doesn't count given Toucan hides this as well
function beginRenderPass(encoder, attachemnts, loadOp = 'clear') {
return encoder.beginRenderPass({
colorAttachments: attachemnts.map(a => ({ view: a.createView(), loadOp, storeOp: 'store' })),
});
}
function getContext(device, width, height) {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
document.body.appendChild(canvas);
const context = canvas.getContext('webgpu');
const presentationFormat = navigator.gpu.getPreferredCanvasFormat();
context.configure({
device,
format: presentationFormat,
alphaMode: 'opaque', //'premultiplied',
});
return {context, presentationFormat};
}
async function setup() {
const adapter = await navigator.gpu?.requestAdapter();
main({ adapter });
}
setup();
{"name":"Hello Triangle - WebGPU Utils","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