编辑
2025-04-23
webgpu
0
请注意,本文编写于 76 天前,最后修改于 39 天前,其中某些信息可能已经过时。

目录

WebGPU 设置简图
WGSL 装饰器详解
WebGPU 核心概念
设备初始化
画布配置
渲染管线详解
管线创建
绑定组 (Bind Groups)
GPU纹理创建
渲染循环
坐标系图

WebGPU 新手简易入门教程 (一)

WebGPU 设置简图

webgpu-draw-diagram.svg

WGSL 装饰器详解

@builtin 装饰器 这些是GPU硬件自动提供的内置值:

js
@builtin(position) position: vec4f // 顶点在屏幕空间的位置 @builtin(vertex_index) vertexIndex: u32 // 当前顶点的索引号 @builtin(instance_index) instanceIndex: u32 // 实例索引

@location 装饰器 用于在着色器阶段之间传递自定义数据:

js
@location(0) texcoord: vec2f, // 纹理坐标 @location(1) color: vec3f, // 颜色 @location(2) normal: vec3f, // 法向量

WebGPU 核心概念

设备初始化

js
// 获取适配器和设备 const adapter = await navigator.gpu?.requestAdapter(); const device = await adapter?.requestDevice();

画布配置

js
const canvas = document.querySelector('canvas'); const context = canvas.getContext('webgpu'); context.configure({ device, format: presentationFormat, // 像素格式 });

渲染管线详解

管线创建

js
const pipeline = device.createRenderPipeline({ label: 'hardcoded textured quad pipeline', layout: 'auto', // 自动推断绑定组布局 vertex: { module, // 顶点着色器模块 }, fragment: { module, // 片段着色器模块 targets: [{ format: presentationFormat }], }, });

绑定组 (Bind Groups)

用于将资源绑定到着色器:

绑定组布局:

js
┌─────────────────────────────────────┐ │ @group(0) @binding(0) ourSampler │ ← 采样器 │ @group(0) @binding(1) ourTexture │ ← 纹理 └─────────────────────────────────────┘ | JavaScript中对应: ┌─────────────────────────────────────┐ │ binding: 0 → sampler │ │ binding: 1 → texture.createView() │ └─────────────────────────────────────┘

GPU纹理创建

js
const texture = device.createTexture({ size: [kTextureWidth, kTextureHeight], format: 'rgba8unorm', // 每个通道8位,归一化到[0,1] usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST, });

渲染循环

js
function render() { // 1. 获取当前帧缓冲 renderPassDescriptor.colorAttachments[0].view = context.getCurrentTexture().createView(); // 2. 创建命令编码器 const encoder = device.createCommandEncoder(); // 3. 开始渲染通道 const pass = encoder.beginRenderPass(renderPassDescriptor); // 4. 设置管线和资源 pass.setPipeline(pipeline); pass.setBindGroup(0, bindGroup); // 5. 绘制 pass.draw(6); // 绘制6个顶点(2个三角形) // 6. 结束并提交 pass.end(); device.queue.submit([encoder.finish()]); }

坐标系图

js
WebGPU 标准化设备坐标 (NDC) Y ↑ (-1,1) | (1,1) ----+----→ X (-1,-1) | (1,-1) | 纹理坐标 (01) Y ↑ (0,1) | (1,1) ----+----→ X (0,0) | (1,0) |
如果对你有用的话,可以打赏哦
打赏
ali pay
wechat pay

本文作者:幽灵

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 幽灵AI 许可协议。转载请注明出处!