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 })
// prettier-ignore
const vertices = new Float32Array([
// A
0.0, 0.5, // coordinate
1.0, 0.0, 0.0, // color
// B
-0.5, -0.5, // coordinate
0.0, 1.0, 0.0, // color
// C
0.5, -0.5, // coordinate
0.0, 0.0, 1.0 // color
])
const vertexBuffer = device.createBuffer({
size: vertices.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST,
mappedAtCreation: true
})
new Float32Array(vertexBuffer.getMappedRange()).set(vertices)
vertexBuffer.unmap()
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 + 3),
attributes: [
{
shaderLocation: 0,
offset: 0,
format: "float32x2"
},
{
shaderLocation: 1,
offset: 4 * 2,
format: "float32x3"
}
]
}
]
},
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.718, g: 0.694, b: 0.949, a: 1 },
storeOp: "store"
}
]
})
renderPass.setPipeline(renderPipeline)
renderPass.setVertexBuffer(0, vertexBuffer)
renderPass.draw(3)
renderPass.end()
device.queue.submit([commandEncoder.finish()])