WebGPU 数据拷贝
前面几篇里,我们大多用 writeBuffer 往缓冲区写数据,用 writeTexture 往纹理写数据。其实往缓冲区或纹理里写数据,路子有好几种。
writeBuffer
writeBuffer 干的事,是把 JavaScript 里的 TypedArray 或 ArrayBuffer 数据拷进缓冲区。这是最直白的一种写法。
writeBuffer 的调用格式长这样:
device.queue.writeBuffer(
destBuffer, // 要写入的缓冲区
destOffset, // 目标缓冲区中开始写入的偏移量(字节)
srcData, // 类型化数组或 ArrayBuffer
srcOffset?, // srcData 中开始复制的偏移量,单位是 **元素个数**
size?, // 要从 srcData 复制的 **元素个数**
)
srcOffset 不传就默认 0,size 不传就默认取 srcData 的大小。
提一句:
srcOffset和size的单位是srcData的元素个数。换句话说:
device.queue.writeBuffer(someBuffer, someOffset, someFloat32Array, 6, 7);上面这段从第 6 个 float32 开始拷,拷 7 个 float32。 换成字节就是:从
someFloat32Array对应的 ArrayBuffer 视图偏移 24 字节处开始,拷 28 个字节。
writeTexture
writeTexture 是把 JavaScript 里的 TypedArray 或 ArrayBuffer 数据拷进纹理。
writeTexture 的函数签名是这样:
device.queue.writeTexture(
// 目标纹理的详细信息
{ texture, mipLevel: 0, origin: [0, 0, 0], aspect: "all" },
// 源数据
srcData,
// 源数据的布局信息
{ offset: 0, bytesPerRow, rowsPerImage },
// 大小:
[ width, height, depthOrArrayLayers ] 或 { width, height, depthOrArrayLayers }
)
有几点得注意:
texture得带GPUTextureUsage.COPY_DST用途标志。mipLevel、origin、aspect都有默认值,一般不用管。bytesPerRow:从当前块行走到下一个块行要多少字节。 只要拷的行数超过 1 个块行,这个参数基本就得给(实际用起来基本都超过 1 个块行)。rowsPerImage:从一张图的开头走到下一张图的开头要多少块行。 要拷的层数超过 1(也就是depthOrArrayLayers> 1),这个值就必须给。
整个复制过程,可以想成下面这段伪代码:
// 伪代码
const [x, y, z] = origin ?? [0, 0, 0];
const [blockWidth, blockHeight, bytesPerBlock] = getBlockInfoForTextureFormat(
texture.format,
);
const blocksAcross = width / blockWidth;
const blocksDown = height / blockHeight;
const bytesPerBlockRow = blocksAcross * bytesPerBlock;
for (layer = 0; layer < depthOrArrayLayers; layer) {
for (row = 0; row < blocksDown; ++row) {
const start = offset + (layer * rowsPerImage + row) * bytesPerRow;
copyRowToTexture(
texture, // 要复制到的纹理
x,
y + row,
z + layer, // 纹理中的目标位置
srcDataAsBytes + start,
bytesPerBlockRow,
);
}
}
块行(block row)
纹理是按块组织的。大多数“普通”纹理,块宽和块高都是 1。压缩纹理就不一样了。比如 bc1-rgba-unorm 格式,块宽 4、块高 4。那宽度设成 8、高度设成 12,实际只会拷 6 个块:第一行 2 个,第二行 2 个,第三行 2 个。
压缩纹理这边,大小和原点都得跟块大小对齐。
提一句:WebGPU 里凡是收大小(定义为
GPUExtent3D)的地方,给一个 1 到 3 个数字的数组也行,给一个 1 到 3 个属性的对象也行。height和depthOrArrayLayers默认都是 1,所以:
[2]表示大小 width = 2, height = 1, depthOrArrayLayers = 1[2, 3]表示大小 width = 2, height = 3, depthOrArrayLayers = 1[2, 3, 4]表示大小 width = 2, height = 3, depthOrArrayLayers = 4{ width: 2 }表示大小 width = 2, height = 1, depthOrArrayLayers = 1{ width: 2, height: 3 }表示大小 width = 2, height = 3, depthOrArrayLayers = 1{ width: 2, height: 3, depthOrArrayLayers: 4 }表示大小 width = 2, height = 3, depthOrArrayLayers = 4
同理,凡是出现原点(默认为
GPUOrigin3D)的地方,给 3 个数字的数组也行,给带x、y、z属性的对象也行。所有分量默认都是 0,所以:
[5]表示原点 x = 5, y = 0, z = 0[5, 6]表示原点 x = 5, y = 6, z = 0[5, 6, 7]表示原点 x = 5, y = 6, z = 7{ x: 5 }表示原点 x = 5, y = 0, z = 0{ x: 5, y: 6 }表示原点 x = 5, y = 6, z = 0{ x: 5, y: 6, z: 7 }表示原点 x = 5, y = 6, z = 7
aspect其实只在往深度-模板格式拷数据时才要紧。一次只能拷一个方面:要么只拷深度(depth-only),要么只拷模板(stencil-only)。
顺带说个冷知识:纹理对象自己就带
width、height、depthOrArrayLayer属性,也就是说它本身就是一个合法的GPUExtent3D。换句话说,下面这个纹理:const texture = device.createTexture({ format: "r8unorm", size: [2, 4], usage: GPUTextureUsage.COPY_DST | GPUTextureUsage.TEXTURE_ATTACHMENT, });下面这些写法都成立:
// 复制 2x4 像素的数据到纹理 const bytesPerRow = 2; device.queue.writeTexture({ texture }, data, { bytesPerRow }, [2, 4]); device.queue.writeTexture({ texture }, data, { bytesPerRow }, [ texture.width, texture.height, ]); device.queue.writeTexture( { texture }, data, { bytesPerRow }, { width: 2, height: 4 }, ); device.queue.writeTexture( { texture }, data, { bytesPerRow }, { width: texture.width, height: texture.height }, ); device.queue.writeTexture({ texture }, data, { bytesPerRow }, texture); // !!!最后一种之所以成立,就是因为纹理对象自带
width、height、depthOrArrayLayers。我们平时不用这种写法,不够直观,但它确实合法。
copyBufferToBuffer
copyBufferToBuffer,顾名思义,把一个缓冲区的数据拷到另一个缓冲区。
函数签名:
encoder.copyBufferToBuffer(
source, // 源缓冲区
sourceOffset, // 源缓冲区中的起始偏移量(字节)
dest, // 目标缓冲区
destOffset, // 目标缓冲区中的起始偏移量(字节)
size, // 要复制的字节数
);
source得带GPUBufferUsage.COPY_SRC用途标志。dest得带GPUBufferUsage.COPY_DST用途标志。size得是 4 的倍数。
copyBufferToTexture
copyBufferToTexture,顾名思义,把缓冲区数据拷到纹理。
函数签名:
encoder.copyBufferToTexture(
// 源缓冲区的详细信息
{ buffer, offset: 0, bytesPerRow, rowsPerImage },
// 目标纹理的详细信息
{ texture, mipLevel: 0, origin: [0, 0, 0], aspect: "all" },
// 大小:
[ width, height, depthOrArrayLayers ] 或 { width, height, depthOrArrayLayers }
)
参数跟 writeTexture 几乎一模一样。最大的区别就一条:bytesPerRow 必须是 256 的倍数!
texture得带GPUTextureUsage.COPY_DST用途标志。buffer得带GPUBufferUsage.COPY_SRC用途标志。
copyTextureToBuffer
copyTextureToBuffer,顾名思义,把纹理数据拷到缓冲区。
函数签名:
encoder.copyTextureToBuffer(
// 源纹理的详细信息
{ texture, mipLevel: 0, origin: [0, 0, 0], aspect: "all" },
// 目标缓冲区的详细信息
{ buffer, offset: 0, bytesPerRow, rowsPerImage },
// 大小:
[ width, height, depthOrArrayLayers ] 或 { width, height, depthOrArrayLayers }
)
参数跟 copyBufferToTexture 差不多,只是纹理(现在是源)和缓冲区(现在是目标)换了个位置。跟 copyBufferToTexture 一样,bytesPerRow 必须是 256 的倍数!
texture得带GPUTextureUsage.COPY_SRC用途标志。buffer得带GPUBufferUsage.COPY_DST用途标志。
copyTextureToTexture
copyTextureToTexture 把一个纹理的一部分拷到另一个纹理。
两个纹理的格式得一样,最多差个 '-srgb' 后缀。
函数签名:
encoder.copyTextureToTexture(
// 源纹理的详细信息
src: { texture, mipLevel: 0, origin: [0, 0, 0], aspect: "all" },
// 目标纹理的详细信息
dst: { texture, mipLevel: 0, origin: [0, 0, 0], aspect: "all" },
// 大小:
[ width, height, depthOrArrayLayers ] 或 { width, height, depthOrArrayLayers }
)
- src.
texture得带GPUTextureUsage.COPY_SRC用途标志。 - dst.
texture得带GPUTextureUsage.COPY_DST用途标志。 width得是块宽度的倍数。height得是块高度的倍数。- src.
origin[0]或.x得是块宽度的倍数。 - src.
origin[1]或.y得是块高度的倍数。 - dst.
origin[0]或.x得是块宽度的倍数。 - dst.
origin[1]或.y得是块高度的倍数。
着色器
着色器能读写存储缓冲区(storage buffer)、存储纹理(storage texture),还能间接渲染到纹理。这些都是往缓冲区和纹理写数据的路子。说白了,你可以写着色器来生成、复制、搬运数据。
映射缓冲区(Mapping Buffers)
缓冲区可以映射。映射的意思,就是让它能从 JavaScript 读或者写。
至少在 WebGPU 第一版里,可映射缓冲区的限制很死:它只能当中转站,用来往别的缓冲区/纹理拷数据,或者从别的缓冲区/纹理读数据。可映射缓冲区不能当别的缓冲区用(比如 uniform 缓冲区、顶点缓冲区、索引缓冲区、存储缓冲区)[1]。
可映射缓冲区有两种用途组合:
-
GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST这种缓冲区能用上面的复制命令从别的缓冲区或纹理拷数据进来,然后映射,在 JavaScript 里读这些值。
-
GPUBufferUsage.MAP_WRITE | GPUBufferUsage.COPY_SRC这种缓冲区能在 JavaScript 里映射、写数据,然后解映射,再用上面的复制命令把内容拷到别的缓冲区或纹理。
映射是异步的。得调 buffer.mapAsync(mode, offset = 0, size?),offset 和 size 的单位是字节。size 不指定就是整个缓冲区。mode 得是 GPUMapMode.READ 或 GPUMapMode.WRITE,而且得跟创建缓冲区时给的 MAP_ 用途标志对上。
mapAsync 返回一个 Promise。Promise resolve 之后,缓冲区就可以映射了。这时调 buffer.getMappedRange(offset = 0, size?) 就能拿到缓冲区的一部分或全部,offset 是映射区域在字节上的偏移。getMappedRange 返回 ArrayBuffer,所以一般还得拿它建个类型化数组才能用。
看个例子:
const buffer = device.createBuffer({
size: 1024,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST,
});
// 映射整个缓冲区
await buffer.mapAsync(GPUMapMode.READ);
// 将整个缓冲区作为 32 位浮点数组获取
const f32 = new Float32Array(buffer.getMappedRange())
...
buffer.unmap();
注意:缓冲区一旦映射,在调 unmap 之前 WebGPU 就用不了它。而调 unmap 的那一瞬间,缓冲区就从 JavaScript 里“消失”了。还是上面那个例子:
const f32 = new Float32Array(buffer.getMappedRange());
f32[0] = 123;
console.log(f32[0]); // 输出 123
buffer.unmap();
console.log(f32[0]); // 输出 undefined
映射缓冲区用来读数据的例子,第一篇文章里就见过:我们把一些数字翻倍放进存储缓冲区,再把结果拷到可映射缓冲区,映射之后读出来。
另一个例子是计算着色器基础:我们把各种 @builtin 计算着色器的值写进存储缓冲区,再拷到可映射缓冲区,映射读取。
mappedAtCreation
mappedAtCreation: true 是建缓冲区时能加的一个标志。加了它,缓冲区就不用带 GPUBufferUsage.COPY_DST 或 GPUBufferUsage.MAP_WRITE 用途标志。
这个标志很特殊,只在建缓冲区那一刻往里写数据时用得上。建的时候加上 mappedAtCreation: true,缓冲区一建出来就是已映射可写的状态。举个例子:
const buffer = device.createBuffer({
size: 16,
usage: GPUBufferUsage.UNIFORM,
mappedAtCreation: true,
});
const arrayBuffer = buffer.getMappedRange(0, buffer.size);
const f32 = new Float32Array(arrayBuffer);
f32.set([1, 2, 3, 4]);
buffer.unmap();
或者更省事一点:
const buffer = device.createBuffer({
size: 16,
usage: GPUBufferUsage.UNIFORM,
mappedAtCreation: true,
});
new Float32Array(buffer.getMappedRange(0, buffer.size)).set([1, 2, 3, 4]);
buffer.unmap();
注意,用 mappedAtCreation: true 建出来的缓冲区,不会自动带上别的用途标志。它只是方便你在建的时候写数据。建出来时是映射状态,你调过一次 unmap 之后,它就跟普通缓冲区一样,只能干你声明过的用途。换句话说,以后想往里拷数据,得有 GPUBufferUsage.COPY_DST;以后想再映射它,得有 GPUBufferUsage.MAP_READ 或 GPUBufferUsage.MAP_WRITE。
高效使用可映射缓冲区
前面说过,映射是异步的。也就是说,从调 mapAsync 请求映射,到映射完成、能调 getMappedRange,中间隔着一段说不准多长的时间。
常见的解法是常备一组已经映射好的缓冲区。它们本来就映射着,随时能用。用完调 unmap,等用到这个缓冲区的命令提交出去,就再请求映射一次。Promise resolve 后,把它扔回已映射缓冲池。什么时候要用却没有空闲的,就新建一个加进池子。
关键的三点
-
上传数据优先用
writeBuffer/writeTexture。
一次性的、不常更新的数据,直接用device.queue.writeBuffer或device.queue.writeTexture最省事,开销也低。它们不走命令编码器,很适合初始化数据。 -
copyBufferToTexture/copyTextureToBuffer的bytesPerRow必须是 256 的倍数。
这是 WebGPU 规范里的硬要求,不满足就报校验错误。上传纹理数据前,先把每行字节数对齐,免得运行时出错或者掉性能。 -
用
mappedAtCreation和映射缓冲区池,把初始化和读取都做顺。mappedAtCreation: true能在建缓冲区时同步写数据,省掉一次映射等待。- 频繁做异步映射(比如读 GPU 计算结果)时,维护一个已映射缓冲区池,就能把
mapAsync的等待抹掉,吞吐量也上来了。
术语对照
这篇只涉及 WebGPU 术语,没有 GLSL 相关内容(WebGPU 用的是 WGSL)。下面是关键术语的译法对照:
| 英文术语 | 建议中文译法 | 备注 |
|---|---|---|
| buffer | 缓冲区 | 与 WebGL 一致 |
| texture | 纹理 | 与 WebGL 一致 |
| mipLevel | mip 级别 / 多级渐远级别 | 保留 mip 原文更常见 |
| block row | 块行 | 压缩纹理中的概念 |
| bytesPerRow | 每行字节数 | 注意单位是字节 |
| rowsPerImage | 每图像行数 | 注意单位是块行数 |
| depthOrArrayLayers | 深度或数组层 | 与 GPUExtent3D 一致 |
| usage flags | 用途标志 | 如 GPUBufferUsage.COPY_SRC |
| storage buffer | 存储缓冲区 | 对应 GPUBufferUsage.STORAGE |
| uniform buffer | 统一缓冲区 | 对应 GPUBufferUsage.UNIFORM |
| vertex buffer | 顶点缓冲区 | 对应 GPUBufferUsage.VERTEX |
| index buffer | 索引缓冲区 | 对应 GPUBufferUsage.INDEX |
| mapping | 映射 | 异步过程 |
| mapAsync | mapAsync | 保留英文 API 名 |
| GPUMapMode | GPUMapMode | 保留英文 API 名 |
| mappedAtCreation | 创建时映射 | 标志名保留英文 |
| aspect | 纹理方面 | 深度/模板纹理中区分深度部分和模板部分 |
| compressed texture | 压缩纹理 | 如 BC1 格式 |
| block width/height | 块宽度/块高度 | 压缩纹理相关 |
这些译法都按 WebGPU 官方规范和社区习惯来,代码里的 API 名、枚举值一律保留英文,技术文章一般都这么写。
脚注
[1] 例外是设了 mappedAtCreation: true 的情况,见 mappedAtCreation。
