三角形(各頂点に色を指定)
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-ignoreconst 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()])
struct VertexInput { @location(0) position: vec2f, @location(1) color: vec3f};
struct VertexOutput { @builtin(position) Position: vec4f, @location(0) color: vec3f};
@vertexfn vs_main(in: VertexInput) -> VertexOutput { var out: VertexOutput; out.Position = vec4f(in.position, 0.0, 1.0); out.color = in.color; return out;}
@fragmentfn fs_main(in: VertexOutput) -> @location(0) vec4f { return vec4f(in.color, 1.0);}