WebGPU 绑定组布局(Bind Group Layouts)
原作者: webgpufundamentals Contributors
为什么需要绑定组布局?
绑定组布局(Bind Group Layouts)是 WebGPU 用来快速把绑定组(Bind Groups)跟计算管线(Compute Pipelines)、渲染管线(Render Pipelines)对上号的机制。思路很简单:费时的详细校验,挪到创建绑定组那会儿就做完;真正绘制或者调度计算的时候,只查一点点东西。
工作原理
一条管线(GPUComputePipeline 或者 GPURenderPipeline)会用一个 GPUPipelineLayout,里面定义了 0 个或多个 GPUBindGroupLayout。每个 GPUBindGroupLayout 对应一个组索引(group index)。绑定组也是拿某个具体的 GPUBindGroupLayout 建出来的。
调用 draw 或 dispatchWorkgroups 时,WebGPU 只做一件事:看看当前管线的 GPUPipelineLayout 里,每个组索引对应的 GPUBindGroupLayout,跟 setBindGroup 绑上去的那个绑定组是不是对得上。这一步很轻,因为细活儿在建绑定组的时候就干完了。
要是建管线时写 layout: 'auto',WebGPU 会自动生成 GPUPipelineLayout,把 GPUBindGroupLayout 填好。但有两种情况你得自己建布局:
- 需要跟默认
'auto'不一样的布局 —— 比如用rgba32float纹理。 - 想让多个管线共用一个绑定组 —— 自动生成的布局没法跨管线复用。
使用不同于 layout: 'auto' 的布局:rgba32float 纹理
默认情况下,texture_2d<f32> 绑定会被推断成可过滤(filterable)纹理。但 rgba32float(以及所有 xxx32float 格式)默认不可过滤,除非设备开了对应的可选特性。所以直接 layout: 'auto' 会报校验错误。
问题代码(修改前)
const textureData = new Uint8Array([ // 原为 Uint8Array
b, _, _, _, _,
...
].flat());
const texture = device.createTexture({
size: [kTextureWidth, kTextureHeight],
format: 'rgba8unorm', // 原格式
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
});
改成 rgba32float 之后:
const _ = [1, 0, 0, 1]; // red
const y = [1, 1, 0, 1]; // yellow
const b = [0, 0, 1, 1]; // blue
const textureData = new Float32Array(
[
b,
_,
_,
_,
_,
_,
y,
y,
y,
_,
_,
y,
_,
_,
_,
_,
y,
y,
_,
_,
_,
y,
_,
_,
_,
_,
y,
_,
_,
_,
_,
_,
_,
_,
_,
].flat(),
);
const texture = device.createTexture({
size: [kTextureWidth, kTextureHeight],
format: "rgba32float",
usage: GPUTextureUsage.TEXTURE_BINDING | GPUTextureUsage.COPY_DST,
});
device.queue.writeTexture(
{ texture },
textureData,
{ bytesPerRow: kTextureWidth * 4 * 4 }, // 注意每个浮点占4字节
{ width: kTextureWidth, height: kTextureHeight },
);
跑起来浏览器会报类似这样的错:
None of the supported sample types (UnfilterableFloat) of [Texture “yellow F on red”] match the expected sample types (Float).
While validating entries[1] as a Sampled Texture. Expected entry layout:{sampleType: TextureSampleType::Float, ...}
意思很清楚:自动布局默认要 sampleType: "float"(可过滤),而 rgba32float 只支持 "unfilterable-float"。
解决方案:手动创建布局
先建 GPUBindGroupLayout,采样器类型改成 'non-filtering',纹理采样类型改成 'unfilterable-float':
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.FRAGMENT,
sampler: {
type: "non-filtering", // 改为非过滤
},
},
{
binding: 1,
visibility: GPUShaderStage.FRAGMENT,
texture: {
sampleType: "unfilterable-float", // 改为不可过滤浮点
viewDimension: "2d",
multisampled: false,
},
},
],
});
再建 GPUPipelineLayout,塞进管线里:
const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout],
});
const pipeline = device.createRenderPipeline({
label: "hardcoded textured quad pipeline",
layout: pipelineLayout, // 替换原来的 layout: 'auto'
vertex: { module },
fragment: {
module,
targets: [{ format: presentationFormat }],
},
});
这下 rgba32float 纹理就能正常用了。
注意:采样器的
magFilter、minFilter或mipmapFilter要是设成'linear',照样报错——非过滤采样器不让做线性过滤。
使用不同布局:动态偏移(Dynamic Offsets)
默认情况下,绑定组里的 uniform/storage buffer 在创建时就把整个缓冲区或者指定的 offset+length 定死了,之后改不了。想在 setBindGroup 的时候动态换 offset,就得在布局里写 hasDynamicOffset: true。
修改计算着色器
@group(0) @binding(0) `var<storage, read_write>` a: `array<f32>`;
@group(0) @binding(1) `var<storage, read_write>` b: `array<f32>`;
@group(0) @binding(2) `var<storage, read_write>` dst: `array<f32>`;
@compute @workgroup_size(1) fn computeSomething(
@builtin(global_invocation_id) id: vec3u
) {
let i = id.x;
dst[i] = a[i] + b[i];
}
创建带动态偏移的布局
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: "storage", hasDynamicOffset: true },
},
{
binding: 1,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: "storage", hasDynamicOffset: true },
},
{
binding: 2,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: "storage", hasDynamicOffset: true },
},
],
});
建管线时用这个布局:
const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout],
});
const pipeline = device.createComputePipeline({
label: "add elements compute pipeline",
layout: pipelineLayout,
compute: { module },
});
准备缓冲区
偏移量必须是 256 的倍数(看设备限制,见 minStorageBufferOffsetAlignment)。这里建个 768 字节的缓冲区,能支持 0、256、512 三个偏移:
const input = new Float32Array(64 * 3);
input.set([1, 3, 5]);
input.set([11, 12, 13], 64);
const workBuffer = device.createBuffer({
label: "work buffer",
size: input.byteLength,
usage:
GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC | GPUBufferUsage.COPY_DST,
});
device.queue.writeBuffer(workBuffer, 0, input);
创建绑定组并指定偏移
绑定组里每个动态缓冲区都要写 size(不写就是整个缓冲区),setBindGroup 时再传一个偏移数组:
const bindGroup = device.createBindGroup({
label: "bindGroup for work buffer",
layout: pipeline.getBindGroupLayout(0),
entries: [
{ binding: 0, resource: { buffer: workBuffer, size: 256 } },
{ binding: 1, resource: { buffer: workBuffer, size: 256 } },
{ binding: 2, resource: { buffer: workBuffer, size: 256 } },
],
});
// 编码命令
pass.setPipeline(pipeline);
pass.setBindGroup(0, bindGroup, [0, 256, 512]); // 三个动态偏移
pass.dispatchWorkgroups(3);
pass.end();
性能提示:动态偏移比非动态偏移稍慢一点,因为偏移范围检查被推到了
setBindGroup调用的时候。调用次数不多的话感觉不出来;但一帧上千次,可能就值得建几个固定偏移的绑定组了。
在多个管线间共享绑定组
手动建绑定组布局还有个重要理由:复用绑定组。比如渲染阴影时,你可能希望全局、材质、局部这几层绑定组,阴影管线和主渲染管线能一起用,而不是每条管线各建一套。
下面拿两个计算管线共用一个绑定组举例。
两个不同的计算着色器
const moduleTimes2 = device.createShaderModule({
code: /* wgsl */ `
@group(0) @binding(0) `var<storage, read_write>` data: `array<f32>`;
@compute @workgroup_size(1) fn computeSomething(
@builtin(global_invocation_id) id: vec3u
) {
let i = id.x;
data[i] = data[i] * 2.0;
}
`,
});
const modulePlus3 = device.createShaderModule({
code: /* wgsl */ `
@group(0) @binding(0) `var<storage, read_write>` data: `array<f32>`;
@compute @workgroup_size(1) fn computeSomething(
@builtin(global_invocation_id) id: vec3u
) {
let i = id.x;
data[i] = data[i] + 3.0;
}
`,
});
共享同一个布局
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: { type: "storage", minBindingSize: 0 },
},
],
});
const pipelineLayout = device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout],
});
const pipelineTimes2 = device.createComputePipeline({
label: "doubling compute pipeline",
layout: pipelineLayout,
compute: { module: moduleTimes2 },
});
const pipelinePlus3 = device.createComputePipeline({
label: "plus 3 compute pipeline",
layout: pipelineLayout,
compute: { module: modulePlus3 },
});
使用同一个绑定组
const bindGroup = device.createBindGroup({
label: "bindGroup for work buffer",
layout: bindGroupLayout, // 注意直接使用共享布局
entries: [{ binding: 0, resource: workBuffer }],
});
const encoder = device.createCommandEncoder();
const pass = encoder.beginComputePass();
pass.setPipeline(pipelineTimes2);
pass.setBindGroup(0, bindGroup);
pass.dispatchWorkgroups(input.length);
pass.setPipeline(pipelinePlus3); // 切换管线,绑定组不变
pass.dispatchWorkgroups(input.length);
pass.end();
一个绑定组,两套计算,就这么跑完了。
绑定组布局注意事项
每个条目必须声明 binding 索引
{ binding: 0, ... }
每个条目必须声明可见的着色器阶段
visibility: GPUShaderStage.FRAGMENT | GPUShaderStage.VERTEX;
// 或
visibility: GPUShaderStage.COMPUTE |
GPUShaderStage.FRAGMENT |
GPUShaderStage.VERTEX;
默认值
texture绑定的默认值:{ sampleType: 'float', viewDimension: '2d', multisampled: false }sampler绑定的默认值:{ type: "filtering"; }
所以常见写法可以简写成:
const bindGroupLayout = device.createBindGroupLayout({
entries: [
{ binding: 0, visibility: GPUShaderStage.FRAGMENT, sampler: {} },
{ binding: 1, visibility: GPUShaderStage.FRAGMENT, texture: {} },
],
});
尽可能声明 minBindingSize
绑的是 uniform buffer(或者大小已知的 storage buffer)时,最好设上 minBindingSize,比如:
buffer: {
type: 'uniform',
minBindingSize: 32, // 对应 uniform struct 的大小
}
这样 WebGPU 会在 createBindGroup 时检查缓冲区够不够大,而不是每次 draw/dispatch 都查一遍,性能更好。storage buffer 要是声明成数组、允许大小不一,那就不设。
关键的三点
-
显式声明绑定组布局,对齐纹理采样能力
用rgba32float这类不可过滤纹理时,必须手动建GPUBindGroupLayout,采样器设成'non-filtering'、纹理设成'unfilterable-float'。这样就不会被自动布局的默认假设坑到,运行时错误少了,管线也能在目标设备上正常建出来。 -
用
minBindingSize提前验证缓冲区大小
在缓冲绑定里写上minBindingSize,WebGPU 就在建绑定组时把大小查完,不用每次绘制/调度重复检查。draw call 的 CPU 开销能降不少,绘制调用多的时候特别明显。 -
复用绑定组布局和绑定组,少建资源、少切换
手动建GPUBindGroupLayout和GPUPipelineLayout,让多个管线共用一个绑定组。这样不用给每条管线重复建类似的绑定组,代码短了,内存也省。设计绑定组结构时把全局、材质、局部数据分层,渲染循环会更清楚,性能也更好。
术语对照
这篇讲的是 WebGPU,着色语言是 WGSL(WebGPU Shading Language),不是 WebGL/GLSL。不过要是你从 WebGL 过来,下面这几组术语值得对一下:
| 英文术语 | 中文推荐 | 备注 |
|---|---|---|
| Bind Group Layout | 绑定组布局 | WebGPU 独有概念,类似 WebGL 中的 uniform block / texture unit 组织方式,但更显式 |
| GPUBindGroupLayout | GPU 绑定组布局对象 | API 接口名保留英文 |
| GPUPipelineLayout | GPU 管线布局对象 | 同上 |
| GPUShaderStage | GPU 着色器阶段 | 对应 VERTEX / FRAGMENT / COMPUTE |
| Storage Buffer | 存储缓冲区 | 类似于 GLSL 中 SSBO(Shader Storage Buffer Object) |
| Uniform Buffer | 统一缓冲区 | 对应 WebGL 的 UBO |
| Sampler | 采样器 | 对应 GLSL 的 sampler2D 等,但 WebGPU 中采样器是独立资源 |
| Filterable / Unfilterable | 可过滤 / 不可过滤 | 指纹理是否支持线性过滤 |
texture_2d<f32> | 2D 浮点纹理 | WGSL 类型,不同于 GLSL 的 sampler2D |
rgba32float | RGBA 32 位浮点纹理格式 | 对应 GLSL 中 GL_RGBA32F |
| Dynamic Offsets | 动态偏移 | WebGPU 特有,在 setBindGroup 时调整缓冲区偏移 |
minBindingSize | 最小绑定大小 | 提前校验缓冲区大小 |
重要提醒:WebGPU 用的是 WGSL,GLSL 代码不能直接搬到 WebGPU。迁移时得把 uniform、in/out、sampler2D 这些语法改写成 WGSL 的 @group/@binding、var<uniform>、texture_2d 之类。
这篇是照着 webgpufundamentals.org 的同名教程编译的,省掉了一些导航和交互内容,核心概念和代码示例都留着。想看完整示例和交互演示,去原始链接。
