Skip to content

三角形(頂点バッファを使って)

import shaderCode from "./shader.wgsl?raw"
const adapter = await navigator.gpu.requestAdapter()
if (!adapter) {
throw new Error("WebGPU cannot be initialized - Adapter not found")
}
const device = await adapter.requestDevice()
device.lost.then(() => {
throw new Error("WebGPU cannot be initialized - Device has been lost")
})
const canvas = document.querySelector("canvas")
const context = canvas!.getContext("webgpu")
if (!context) {
throw new Error("WebGPU cannot be initialized - Canvas does not support WebGPU")
}
const canvasFormat = navigator.gpu.getPreferredCanvasFormat()
context.configure({ device, format: canvasFormat })
const vertices = new Float32Array([0.0, 0.5, -0.5, -0.5, 0.5, -0.5])
const vertexBuffer = device.createBuffer({
size: vertices.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
})
device.queue.writeBuffer(vertexBuffer, 0, vertices)
const shaderModule = device.createShaderModule({ code: shaderCode })
const renderPipeline = device.createRenderPipeline({
layout: "auto",
vertex: {
module: shaderModule,
entryPoint: "vs_main",
buffers: [
{
arrayStride: vertices.BYTES_PER_ELEMENT * 2,
attributes: [
{
shaderLocation: 0,
offset: 0,
format: "float32x2"
}
]
}
]
},
fragment: {
module: shaderModule,
entryPoint: "fs_main",
targets: [
{
format: canvasFormat
}
]
}
})
const commandEncoder = device.createCommandEncoder()
const renderPass = commandEncoder.beginRenderPass({
colorAttachments: [
{
view: context.getCurrentTexture().createView(),
loadOp: "clear",
clearValue: { r: 0.749, g: 0.925, b: 1.0, a: 1 },
storeOp: "store"
}
]
})
renderPass.setPipeline(renderPipeline)
renderPass.setVertexBuffer(0, vertexBuffer)
renderPass.draw(3)
renderPass.end()
device.queue.submit([commandEncoder.finish()])