Public
Edited
Apr 19, 2023
1 fork
2 stars
Insert cell
Insert cell
Insert cell
adapter = navigator.gpu?.requestAdapter()
Insert cell
device = adapter?.requestDevice()
Insert cell
Insert cell
canvas = DOM.canvas(width, 500)
Insert cell
context = canvas.getContext("webgpu")
Insert cell
presentationFormat = navigator.gpu?.getPreferredCanvasFormat()
Insert cell
{
// Configure the WebGPU Device
if (context)
context.configure({
device,
format: presentationFormat
});
}
Insert cell
Insert cell
module = device &&
device.createShaderModule({
label: "our hardcoded red triangle shaders",
code: `
@vertex fn vs(
@builtin(vertex_index) vertexIndex : u32
) -> @builtin(position) vec4f {
var pos = array<vec2f, 3>(
vec2f( 0.0, 0.5), // top center
vec2f(-0.5, -0.5), // bottom left
vec2f( 0.5, -0.5) // bottom right
);
return vec4f(pos[vertexIndex], 0.0, 1.0);
}
@fragment fn fs() -> @location(0) vec4f {
return vec4f(1.0, 0.0, 0.0, 1.0);
}
`
})
Insert cell
Insert cell
pipeline = device && device.createRenderPipeline({
label: "our hardcoded red triangle pipeline",
layout: "auto",
vertex: {
module,
entryPoint: "vs"
},
fragment: {
module,
entryPoint: "fs",
targets: [{ format: presentationFormat }]
}
})
Insert cell
renderPassDescriptor = ({
label: "our basic canvas renderPass",
colorAttachments: [
{
// view: <- to be filled out when we render
clearValue: [0.3, 0.3, 0.3, 1],
loadOp: "clear",
storeOp: "store"
}
]
})
Insert cell
Insert cell
{
if (context) {
// Get the current texture from the canvas context and
// set it as the texture to render to.
renderPassDescriptor.colorAttachments[0].view = context
.getCurrentTexture()
.createView();

// make a command encoder to start encoding commands
const encoder = device.createCommandEncoder({ label: "our encoder" });

// make a render pass encoder to encode render specific commands
const pass = encoder.beginRenderPass(renderPassDescriptor);
pass.setPipeline(pipeline);
pass.draw(3); // call our vertex shader 3 times
pass.end();

const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
}
}
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more