WebGPUリファレンス
基本概念
GPUAdapter
物理的なGPUデバイスへのアクセスを提供するオブジェクト。
const adapter = await navigator.gpu.requestAdapter();
GPUDevice
GPUリソースの作成とコマンドの実行に使用される論理デバイス。
const device = await adapter.requestDevice();
GPUCommandEncoder
GPUコマンドをエンコードしてコマンドバッファを作成。
const encoder = device.createCommandEncoder();
const commandBuffer = encoder.finish();
device.queue.submit([commandBuffer]);
シェーダー(WGSL)
基本構造
// 頂点シェーダー
@vertex
fn vs_main(@location(0) position: vec3f) -> @builtin(position) vec4f {
return vec4f(position, 1.0);
}
// フラグメントシェーダー
@fragment
fn fs_main() -> @location(0) vec4f {
return vec4f(1.0, 0.0, 0.0, 1.0); // 赤色
}
データ型
f32
- 32ビット浮動小数点数i32
- 32ビット符号付き整数u32
- 32ビット符号なし整数bool
- 真偽値vec2f
,vec3f
,vec4f
- ベクトル型mat4x4f
- 4x4行列
パイプライン
レンダーパイプライン
const pipeline = device.createRenderPipeline({
layout: 'auto',
vertex: {
module: shaderModule,
entryPoint: 'vs_main',
buffers: [{
arrayStride: 12, // 3 * 4 bytes
attributes: [{
format: 'float32x3',
offset: 0,
shaderLocation: 0
}]
}]
},
fragment: {
module: shaderModule,
entryPoint: 'fs_main',
targets: [{
format: canvasFormat
}]
},
primitive: {
topology: 'triangle-list'
}
});
リソース管理
バッファ
// バッファの作成
const buffer = device.createBuffer({
size: vertices.byteLength,
usage: GPUBufferUsage.VERTEX | GPUBufferUsage.COPY_DST
});
// データの書き込み
device.queue.writeBuffer(buffer, 0, vertices);
テクスチャ
const texture = device.createTexture({
size: { width: 256, height: 256 },
format: 'rgba8unorm',
usage: GPUTextureUsage.TEXTURE_BINDING |
GPUTextureUsage.COPY_DST
});