WebGPU

W3C 候选推荐草案,

关于本文档的更多信息
此版本:
https://www.w3.org/TR/2025/CRD-webgpu-20250711/
最新发布版本:
https://www.w3.org/TR/webgpu/
编辑草案:
https://gpuweb.github.io/gpuweb/
先前版本:
历史:
https://www.w3.org/standards/history/webgpu/
反馈:
public-gpu@w3.org 邮件主题请写为 “[webgpu] …消息主题…” (存档)
GitHub
编辑者:
(Google)
(Google)
(Mozilla)
前任编辑者:
(Apple Inc.)
(Mozilla)
(Apple Inc.)
参与:
提交问题 (开放问题)
测试套件:
WebGPU CTS

摘要

WebGPU 提供了一个 API,可用于在图形处理单元(GPU)上执行渲染与计算等操作。

本文件状态

本节描述了本文档在发布时的状态。当前 W3C 出版物和本技术报告的最新修订可在 W3C 标准与草案索引 查询。

欢迎对本规范提出反馈和意见。建议优先通过 GitHub Issues 参与讨论。你也可以向 GPU for the Web 工作组邮件列表 public-gpu@w3.org存档)发送评论。本草案突出了工作组仍需讨论的一些待决问题,目前尚未就其结果作出决定,包括其有效性。

本文档由 GPU for the Web 工作组推荐流程 作为候选推荐草案发布。为确保有充分的广泛评审机会,本文件将至少保持候选推荐状态至

工作组期望在至少两个已部署的浏览器中基于现代 GPU 系统 API 演示每项特性的实现。测试套件将用于编写实现报告。

作为候选推荐发布并不代表 W3C 及其成员的认可。候选推荐草案整合了工作组打算在后续推荐快照中包含的前一候选推荐的更改。

本文档可随时维护和更新,其中部分内容尚在完善中。

本文档由遵循 W3C 专利政策 的工作组编写。W3C 维护了与本组交付物相关的 专利公开列表,该页面也包括专利披露说明。个人如获知包含 必要权利要求 的专利,应依 W3C 专利政策第6节 披露相关信息。

本文档受 2023年11月3日 W3C 流程文档 管辖。

1. 引言

本节为非规范性内容。

图形处理单元(GPU)在个人计算领域中已成为实现丰富渲染和计算应用的关键。WebGPU 是一个为 Web 暴露 GPU 硬件能力的 API。该 API 从零开始设计,能够高效映射到(2014年之后的)原生 GPU API。WebGPU 与 WebGL 无关,也不直接针对 OpenGL ES。

WebGPU 将物理 GPU 硬件视为 GPUAdapter。它通过 GPUDevice 提供与适配器的连接,设备负责管理资源,并通过设备的 GPUQueue 执行命令。GPUDevice 可能拥有自己的高速存储器以供处理单元访问。GPUBufferGPUTexture 是由 GPU 内存支持的物理资源GPUCommandBufferGPURenderBundle 是用户录制命令的容器。GPUShaderModule 包含 着色器代码。其他资源如 GPUSamplerGPUBindGroup 用于配置 GPU 如何使用物理资源

GPU 通过 GPUCommandBuffer 编码的命令,通过 管线 执行,该管线是固定功能与可编程阶段的混合体。可编程阶段运行着色器,即专为 GPU 硬件设计的特殊程序。管线的大部分状态由 GPURenderPipelineGPUComputePipeline 对象定义。未包含在这些 管线对象中的状态,则在命令编码阶段通过如 beginRenderPass()setBlendConstant() 之类命令设置。

2. 恶意使用考量

本节为非规范性内容。 介绍了在 Web 上暴露此 API 所带来的风险。

2.1. 安全考量

WebGPU 的安全要求与 Web 一贯的要求相同,也是不可协商的。总体原则是:在所有命令到达 GPU 之前进行严格校验,确保页面只能操作自身数据。

2.1.1. 基于 CPU 的未定义行为

WebGPU 实现会将用户发起的工作量转换为目标平台特定的 API 命令。原生 API 规定了命令的有效用法(例如见 vkCreateDescriptorSetLayout),并且通常不保证不遵守有效用法规则时的任何结果。这被称为“未定义行为”,攻击者可以利用它访问非授权内存,或迫使驱动执行任意代码。

为禁止不安全用法,WebGPU 针对任意输入都定义了允许的行为范围。实现必须校验所有用户输入,只允许有效工作负载到达驱动。本规范规定了所有错误条件及其处理语义。例如,在 copyBufferToBuffer() 的 "source" 和 "destination" 同时指定同一缓冲区,且区间相交时,GPUCommandEncoder 会生成错误,且不会执行其它操作。

更多错误处理信息参见 § 22 错误与调试

2.1.2. 基于 GPU 的未定义行为

WebGPU 着色器 由 GPU 内部的计算单元执行。在原生 API 中,某些着色器指令可能在 GPU 上导致未定义行为。为应对这一点,WebGPU 严格定义了着色器指令集及其行为。当为 createShaderModule() 提供着色器时,WebGPU 实现必须在进行任何平台特定着色器转换或变换之前进行校验。

2.1.3. 未初始化数据

一般来说,分配新内存可能暴露系统上其它应用残留的数据。为避免此问题,WebGPU 在概念上会将所有资源初始化为零,尽管若实现检测到开发者已手动初始化内容时可跳过此步骤。这包括着色器内变量和共享工作组内存。

清除工作组内存的具体机制依平台而异。若原生 API 未提供清除机制,WebGPU 实现会先在所有调用中清空,再同步,然后继续执行开发者代码。

注:
资源在队列操作中被使用时,其初始化状态只有在操作入队时才能确定(而不是在命令缓冲区编码时)。因此,一些实现会在入队时执行非优化的延迟清除(如清除纹理,而不是将 GPULoadOp "load" 改为 "clear")。

因此,无论实现是否有性能损耗,所有实现应当在开发者控制台发出警告。

2.1.4. 着色器中的越界访问

着色器可以直接访问物理资源(如 "uniform" GPUBufferBinding),也可以通过纹理单元(为纹理坐标转换而设的固定功能硬件块)间接访问。WebGPU API 的校验只能保证所有着色器输入已提供且类型正确。如果未通过纹理单元访问,WebGPU API 无法保证数据访问不会越界。

为防止着色器访问非本应用 GPU 内存,WebGPU 实现可在驱动中启用“健壮缓冲区访问”模式,确保访问不会超出缓冲区界限。

或者,实现可在着色器代码中插入手动越界检查。此时,越界检查仅适用于数组索引,对结构体字段访问则无需手动检查,因为主机侧 minBindingSize 校验已覆盖。

若着色器尝试读取物理资源边界外的数据,实现可以:

  1. 返回资源边界内其他位置的值

  2. 返回值向量 "(0, 0, 0, X)",其中 X 可为任意值

  3. 部分丢弃绘制或调度调用

若着色器尝试写入物理资源边界外,实现可以:

  1. 写入资源边界内其他位置

  2. 丢弃写入操作

  3. 部分丢弃绘制或调度调用

2.1.5. 无效数据

从 CPU 向 GPU 上传 浮点数数据或在 GPU 上生成浮点数时,可能会出现不对应于有效数值的二进制表示(如无穷大或 NaN)。此时 GPU 行为取决于硬件对 IEEE-754 标准的实现精度。WebGPU 保证引入无效浮点数只会影响算术运算结果,不会有其他副作用。

2.1.6. 驱动漏洞

GPU 驱动程序和其他软件一样可能存在漏洞。攻击者可能利用驱动的错误行为访问非授权数据。为降低风险,WebGPU 工作组将与 GPU 厂商协作,将 WebGPU 一致性测试套件(CTS)集成到驱动测试流程中,类似 WebGL 的做法。WebGPU 实现应对已发现的部分漏洞有兼容性处理,并对无法绕过的已知漏洞驱动禁用 WebGPU。

2.1.7. 时序攻击

2.1.7.1. 内容时间线时序

WebGPU 不会向 JavaScript 暴露在 内容时间线上由 agentagent cluster 中共享的新状态。内容时间线状态如 [[mapping]] 仅在显式 内容时间线任务(如普通 JavaScript)中变化。

2.1.7.2. 设备/队列时间线时序

可写存储缓冲区和其他跨调用通信机制可能用于在队列时间线上构造高精度定时器。

可选的 "timestamp-query" 特性也为 GPU 操作提供高精度计时。为缓解安全和隐私风险,定时查询的值被对齐到较低精度:参见 current queue timestamp。特别注意:

2.1.8. Row hammer 攻击

Row hammer 是一类利用 DRAM 单元状态泄漏的攻击,可被用于 GPU。WebGPU 没有专门的防护措施,依赖于平台级解决方案,例如缩短内存刷新间隔。

2.1.9. 拒绝服务

WebGPU 应用可访问 GPU 内存和计算单元。WebGPU 实现可以限制应用可用的 GPU 内存,以保证其他应用的响应性。对于 GPU 处理时间,WebGPU 实现可以设置“看门狗”定时器,确保应用不会导致 GPU 无响应超过数秒。这些措施类似于 WebGL 所采用的策略。

2.1.10. 工作负载识别

WebGPU 提供对全局受限资源的访问,这些资源由同一台机器上不同程序(和网页)共享。应用可通过间接探测全局资源受限程度,进而推测其他网页正在进行的工作负载。这些问题与 Javascript 中的系统内存和 CPU 执行吞吐量类似。WebGPU 没有对此提供额外的缓解措施。

2.1.11. 内存资源

WebGPU 允许从机器全局内存堆(如 VRAM)进行可失败的分配。这使得应用可以通过尝试分配并观察分配失败情况,探测系统剩余可用内存(针对特定堆类型)。

GPU 内部一般有一个或多个(通常只有两个)所有运行应用共享的内存堆。当某个堆耗尽时,WebGPU 创建资源会失败。这是可观察到的,可能使恶意应用推测出其他应用使用了哪些堆,以及它们分配了多少。

2.1.12. 计算资源

如果一个站点与另一个站点同时使用 WebGPU,它可能会观察到处理某些工作的耗时增加。例如,持续向队列提交计算工作并跟踪完成时间,可能会发现其他任务也开始使用 GPU。

GPU 有多个可独立测试的部分,如算术单元、纹理采样单元、原子单元等。恶意应用可以检测某些单元的负载,并试图分析压力模式来猜测其他应用的工作负载。这与 Javascript 的 CPU 执行现实类似。

2.1.13. 能力滥用

恶意站点可能滥用 WebGPU 所暴露的能力,运行对用户或其体验无益、仅对站点有利的计算。例如隐蔽挖矿、密码破解或彩虹表计算。

无法针对这类 API 使用方式加以防范,因为浏览器无法区分有效负载和滥用负载。这是 Web 上所有通用计算能力(如 JavaScript、WebAssembly 或 WebGL)面临的普遍问题。WebGPU 只是让某些负载的实现更容易,或比 WebGL 更高效。

为缓解此类滥用,浏览器可对后台标签页的操作进行限速,可警告标签页资源占用过高,并可限制哪些上下文允许使用 WebGPU。

用户代理可基于启发式方法向用户发出高功耗警告,尤其在检测到潜在恶意使用时。如果实现此类警告,应将 WebGPU 使用纳入与 JavaScript、WebAssembly、WebGL 等相同的启发式中。

2.2. 隐私考量

There is a tracking vector here. WebGPU 的隐私考量与 WebGL 类似。GPU API 十分复杂,必须出于必要暴露设备能力的各个方面,以便开发者能够有效利用这些能力。一般的缓解方法是对潜在可识别信息进行归一化或分桶,并在可能的情况下强制行为一致。

用户代理不得暴露超过 32 种可区分配置或分桶。

2.2.1. 机器特有功能与限制

WebGPU 可以揭示底层 GPU 架构和设备结构的许多细节,包括可用的物理适配器、GPU 和 CPU 资源的多项限制(如最大纹理尺寸),以及可用的任何可选硬件专属能力。

用户代理没有义务暴露真实硬件限制,可以完全控制机器细节的暴露程度。减少指纹识别的一种策略是将所有目标平台归为少数几个分桶。总体来说,暴露硬件限制的隐私影响与 WebGL 相同。

默认限制值也被故意设置得足够高,以便大多数应用无需请求更高限制即可运行。所有 API 的使用都按请求限制进行校验,因此不会因意外而向用户暴露实际硬件能力。

2.2.2. 机器特有产物

和 WebGL 一样,可以观察到一些机器特有的光栅化/精度差异和性能差异。这涉及光栅化覆盖及模式、着色器阶段间 varyings 的插值精度、计算单元调度,以及更多执行相关特性。

通常,同一厂商的大多数或全部设备的光栅化和精度指纹是相同的。性能差异难以完全规避,但信号强度较低(如 JS 执行性能)。

对隐私要求高的应用和用户代理应采用软件实现以消除这类产物。

2.2.3. 机器特有性能

通过测量 GPU 上特定操作的性能也是区分用户的一个因素。即便计时精度较低,重复执行某一操作也能体现用户机器在特定负载下的快慢。这是常见的识别向量(WebGL 和 Javascript 皆有),但信号较低且难以完全规避。

WebGPU 计算管线让开发者可绕过固定功能硬件直接访问 GPU,这带来了独特设备指纹识别的额外风险。用户代理可通过将逻辑 GPU 调用与实际计算单元解耦来降低此风险。

2.2.4. 用户代理状态

本规范未为源定义任何额外用户代理状态。但预期用户代理会对 GPUShaderModuleGPURenderPipelineGPUComputePipeline 等高开销编译结果进行缓存。这些缓存有助于提升 WebGPU 应用首次访问后的加载速度。

对规范而言,这些缓存与极快编译无异,但应用可以轻易测量 createComputePipelineAsync() 的耗时。这可能导致跨源信息泄露(如“用户是否访问过包含特定着色器的站点”),因此用户代理应遵循 存储分区最佳实践。

系统的 GPU 驱动也可能有自己的着色器和管线编译缓存。用户代理可在可能的情况下禁用该缓存,或为着色器添加分区数据,使驱动将其视为不同对象。

2.2.5. 驱动漏洞

安全考量中提到的问题外,驱动漏洞还可能导致行为差异,成为区分用户的手段。此处可采用安全考量中提及的缓解措施,如与 GPU 厂商协作,在用户代理中实现已知问题的兼容处理。

2.2.6. 适配器标识符

WebGL 实践表明,开发者有合理需求识别其代码运行的 GPU,以便创建和维护健壮的 GPU 内容。例如识别有已知驱动漏洞的适配器,以便规避或避免在某些硬件上使用表现不佳的特性。

但暴露适配器标识符自然会增加指纹识别信息量,因此有必要限制适配器识别的精度。

可以采取多项缓解措施以平衡内容健壮性与隐私保护。首先,用户代理可通过主动识别和规避已知驱动问题,减少开发者负担,就像浏览器开始用 GPU 以来所做的一样。

默认暴露适配器标识符时应尽量宽泛,只要有用即可。例如,可仅标识适配器厂商及架构而非具体型号。有时也可报告实际适配器的合理代理的标识符。

在需要完整详细适配器信息(如提交 bug 报告)时,可请用户同意向页面披露更多硬件信息。

最后,若用户代理认为合适(如增强隐私模式下),可完全不报告适配器标识符。

3. 基础

3.1. 约定

3.1.1. 语法速记

本规范中使用了如下语法速记:

.(点)语法,常见于编程语言。

短语“Foo.Bar”表示“值(或接口)FooBar 成员”。如果 Foo有序映射(ordered map)BarFoo 中未存在,则返回 undefined

短语“Foo.Bar提供”表示“Bar 成员存在映射Foo 中”。

?.(可选链)语法,借鉴自 JavaScript。

短语“Foo?.Bar”表示:“如果 FoonullundefinedBarFoo 中未存在,则为 undefined;否则为 Foo.Bar”。

例如,若 buffer 是一个 GPUBuffer,则 buffer?.\[[device]].\[[adapter]] 表示:“如果 buffernullundefined,则为 undefined;否则为 buffer\[[device]] 内部槽的 \[[adapter]] 内部槽。”

??(空值合并)语法,借鉴自 JavaScript。

短语“x ?? y”表示:“如果 x 不为 null 或 undefined,则为 x,否则为 y。”

槽支持属性(slot-backed attribute)

由同名内部槽支持的 WebIDL 属性。其可变性视规范而定。

3.1.2. WebGPU 对象

WebGPU 对象WebGPU 接口内部对象组成。

WebGPU 接口定义了WebGPU 对象的公共接口和状态。它可在其创建的内容时间线上使用,此时它是 JavaScript 暴露的 WebIDL 接口。

任何包含 GPUObjectBase 的接口都是 WebGPU 接口

内部对象跟踪WebGPU 对象设备时间线上的状态。所有对内部对象可变状态的读写都发生在单一有序的设备时间线步骤中。

WebGPU 对象上可定义以下特殊属性类型:

不可变属性(immutable property)

在对象初始化时设定的只读槽,可从任意时间线访问。

注:由于该槽不可变,实现可在多个时间线中保有副本,按需分配。不可变属性这样定义是为避免在规范中描述多个副本。

若命名为 [[带括号]],则是内部槽。
若命名为 不带括号,则是 WebGPU 接口readonly 槽支持属性

内容时间线属性(content timeline property)

仅可从对象创建的内容时间线访问的属性。

若命名为 [[带括号]],则是内部槽。
若命名为 不带括号,则是 WebGPU 接口槽支持属性

设备时间线属性(device timeline property)

跟踪内部对象状态,仅可从对象创建的设备时间线访问。设备时间线属性可为可变的。

设备时间线属性命名为 [[带括号]],为内部槽。

队列时间线属性(queue timeline property)

跟踪内部对象状态,仅可从对象创建的队列时间线访问。队列时间线属性可为可变的。

队列时间线属性命名为 [[带括号]],为内部槽。

interface mixin GPUObjectBase {
    attribute USVString label;
};
创建一个新的 WebGPU 对象GPUObjectBase parent,接口 TGPUObjectDescriptorBase descriptor)(其中 T 继承自 GPUObjectBase),请在内容时间线上执行以下步骤:
  1. deviceparent.[[device]]

  2. objectT 的新实例。

  3. 设置 object.[[device]]device

  4. 设置 object.labeldescriptor.label

  5. 返回 object

GPUObjectBase 具有如下不可变属性

[[device]],类型为device,只读

拥有该内部对象设备

对此对象内容的操作断言其运行在设备时间线上,并且设备是有效的。

GPUObjectBase 具有如下内容时间线属性

label类型为 USVString

开发者提供的标签,由实现自定义使用。可由浏览器、操作系统或其他工具用于帮助开发者识别底层内部对象。示例包括在 GPUError 消息、控制台警告、浏览器开发者工具和平台调试工具中显示标签。

注:
实现应当利用标签提升错误消息的可读性,用于标识 WebGPU 对象。

但这不必是标识对象的唯一方式:实现还应结合其他可用信息,尤其是在没有标签时。例如:

注:
labelGPUObjectBase 的属性。两个 GPUObjectBase “包装器”对象即使引用同一底层对象,其 label 状态也是完全独立的(如由 getBindGroupLayout() 返回时)。除非通过 JavaScript 设置,否则 label 属性不会变更。

这意味着一个底层对象可关联多个标签。本规范未定义标签如何传递到 设备时间线。标签的使用完全由实现自定义:错误消息可显示最近设置的标签、所有已知标签,或完全不显示标签。

属性类型为 USVString,因为某些用户代理可能将其传递给底层原生 API 的调试工具。

GPUObjectBase 具有如下设备时间线属性

[[valid]],类型为boolean,初始值为 true

若为 true,表示该内部对象可用。

注:
理想情况下,WebGPU 接口不应阻止其父对象(如拥有它的 [[device]])被垃圾回收。然而,这无法保证,因为某些实现可能需要强引用父对象。

因此,开发者应假定 WebGPU 接口在所有子对象被回收前可能不会被垃圾回收。这可能导致部分资源比预期保留更长时间。

如果需要可预测地释放分配的资源,应优先调用 destroy 方法(如 GPUDevice.destroy()GPUBuffer.destroy()),而不是依赖垃圾回收。

3.1.3. 对象描述符

对象描述符用于保存创建对象所需的信息,通常通过 GPUDevicecreate* 方法之一进行对象创建。

dictionary GPUObjectDescriptorBase {
    USVString label = "";
};

GPUObjectDescriptorBase 具有如下成员:

label类型为 USVString,默认值为 ""

GPUObjectBase.label 的初始值。

3.2. 异步性

3.2.1. 无效的内部对象与传染性无效

WebGPU 中的对象创建操作不会返回 Promise,但其本质上是异步的。返回的对象引用的是在设备时间线上被操作的内部对象。多数在设备时间线上发生的错误不会通过异常或拒绝抛出,而是通过关联设备上生成的 GPUError 进行传递。

内部对象可以是有效无效无效对象不会在之后变为有效,但部分有效对象可以被使无效(invalidated)

如果对象无法被创建,则其从创建开始即为无效。例如,对象描述符未能描述出有效对象,或者没有足够内存分配资源时会发生此情况。如果从另一个无效对象创建对象(例如对无效的 GPUTexture 调用 createView()),也会如此。这类情况称为传染性无效

大多数类型的内部对象在创建后不会变为无效,但仍可能变得不可用,例如其所属设备丢失destroyed,或对象处于特殊内部状态(如缓冲区状态“destroyed”)。

部分类型的内部对象在创建后可以变为无效;具体包括设备适配器GPUCommandBuffer,以及命令/通道/捆绑编码器。

给定 GPUObjectBase object,若 object.[[valid]]true,则为有效
给定 GPUObjectBase object,若 object.[[valid]]false,则为无效
给定 GPUObjectBase object,若满足以下设备时间线步骤的所有要求,则其可与 targetObject 一同使用(valid to use with)
使无效(invalidate) GPUObjectBase object,请在设备时间线上执行以下步骤:
  1. object.[[valid]] 设为 false

3.2.2. Promise 顺序

WebGPU 中有若干操作会返回 promise。

WebGPU 不保证这些 promise 的 settle(resolve 或 reject)顺序,除非有如下例外:

应用不得依赖于其它 promise 的 settle 顺序。

3.3. 坐标系统

渲染操作使用如下坐标系统:

注:WebGPU 的坐标系统与 DirectX 图形管线中的坐标系统一致。

3.4. 编程模型

3.4.1. 时间线

WebGPU 的行为以“时间线”为单位进行描述。每个操作(以算法定义)都发生在某个时间线上。时间线明确了操作的顺序,以及哪些状态可被哪些操作访问。

注: 这种“时间线”模型反映了浏览器引擎多进程模型(如“内容进程”和“GPU 进程”)的约束,也体现了许多实现中 GPU 作为独立执行单元的现实。实现 WebGPU 并不要求时间线并行执行,因此不要求多进程,甚至不要求多线程。(但如 获取上下文图像内容副本 这类需同步阻塞其它时间线完成的情况,仍需支持并发。)

内容时间线

与 Web 脚本的执行相关。包括本规范描述的所有方法调用。

要从 GPUDevice device 的操作向内容时间线派发步骤,可通过 为 GPUDevice 排队全局任务

设备时间线

与用户代理发起的 GPU 设备操作相关。包括适配器、设备、GPU 资源与状态对象的创建,这些操作从用户代理控制 GPU 的部分看通常是同步的,但可在独立的操作系统进程中运行。

队列时间线

与 GPU 计算单元上操作的执行相关。包括实际在 GPU 上运行的绘制、拷贝和计算任务。

时间线无关

可以与上述任意时间线关联。

如仅操作不可变属性或调用步骤传入的参数,则可派发到任意时间线。

以下展示了与各时间线关联的步骤和值的样式。该样式为非规范性内容,规范文本始终明确描述了其关联。
不可变值示例术语定义

可用于任意时间线。

内容时间线示例术语定义

仅可用于内容时间线

设备时间线示例术语定义

仅可用于设备时间线

队列时间线示例术语定义

仅可用于队列时间线

时间线无关的步骤如下所示。

不可变值示例术语的用法。

内容时间线上执行的步骤如下所示。

不可变值示例术语的用法。 内容时间线示例术语的用法。

设备时间线上执行的步骤如下所示。

不可变值示例术语的用法。 设备时间线示例术语的用法。

队列时间线上执行的步骤如下所示。

不可变值示例术语的用法。 队列时间线示例术语的用法。

本规范中,当返回值依赖于非内容时间线上发生的工作时,采用异步操作。API 以 promise 或事件的形式表现异步操作。

GPUComputePassEncoder.dispatchWorkgroups() 示例:
  1. 用户在 内容时间线 上通过 GPUComputePassEncoder 的方法编码 dispatchWorkgroups 命令。

  2. 用户调用 GPUQueue.submit(),将 GPUCommandBuffer 提交给用户代理,用户代理在 设备时间线 上调用操作系统驱动进行底层提交。

  3. GPU 调度器在 队列时间线 上将提交分派到实际计算单元执行。

GPUDevice.createBuffer() 示例:
  1. 用户填写 GPUBufferDescriptor,并用其创建 GPUBuffer,在 内容时间线 上发生。

  2. 用户代理在 设备时间线 上创建底层缓冲区。

GPUBuffer.mapAsync() 示例:
  1. 用户在 内容时间线 上请求映射 GPUBuffer,并获得一个 promise。

  2. 用户代理检查该缓冲区是否正被 GPU 使用,并设置提醒在使用结束后再次检查。

  3. 在 GPU 于 队列时间线 上使用完缓冲区后,用户代理将其映射到内存并 resolve 该 promise。

3.4.2. 内存模型

本节为非规范性内容。

一旦应用初始化过程中获取到 GPUDevice,我们可以将 WebGPU 平台描述为包含以下各层:

  1. 实现本规范的用户代理。

  2. 为该设备提供底层原生 API 驱动的操作系统。

  3. 实际的 CPU 和 GPU 硬件。

WebGPU 平台的每一层可能有不同类型的内存,用户代理在实现规范时需要加以考虑:

大多数物理资源分配在适合 GPU 计算或渲染的内存类型中。当用户需要向 GPU 提供新数据时,数据可能首先需要跨越进程边界,抵达与 GPU 驱动通信的用户代理部分。随后可能需要使数据对驱动可见,有时这需要拷贝到驱动分配的中转(staging)内存。最后,数据还可能需要传输到独立 GPU 内存中,并在内部转换为最适合 GPU 运算的布局。

所有这些转换都由用户代理的 WebGPU 实现负责完成。

注:上述示例描述了最坏情况,实际实现中可能无需跨越进程边界,或者能直接向用户暴露由驱动管理的内存(例如通过 ArrayBuffer),从而避免数据拷贝。

3.4.3. 资源用法

物理资源可以被GPU 命令内部用法使用:

输入(input)

为 draw 或 dispatch 调用提供输入数据的缓冲区。会保留内容。由缓冲区 INDEXVERTEXINDIRECT 允许。

常量(constant)

从着色器视角为常量的资源绑定。会保留内容。由缓冲区 UNIFORM 或纹理 TEXTURE_BINDING 允许。

存储(storage)

读/写存储资源绑定。由缓冲区 STORAGE 或纹理 STORAGE_BINDING 允许。

存储只读(storage-read)

只读存储资源绑定。会保留内容。由缓冲区 STORAGE 或纹理 STORAGE_BINDING 允许。

附件(attachment)

在渲染通道中作为读/写输出附件或仅写解决目标的纹理。由纹理 RENDER_ATTACHMENT 允许。

附件只读(attachment-read)

在渲染通道中作为只读附件的纹理。会保留内容。由纹理 RENDER_ATTACHMENT 允许。

子资源(subresource)指整个缓冲区或纹理子资源

某些内部用法彼此兼容。子资源(subresource)可以处于多个用法组合的状态。若列表 U 满足下列任一规则,则称其为兼容用法列表(compatible usage list)

强制要求用法仅可组合为兼容用法列表,使得 API 能够限制内存操作中的数据竞争出现时机。该属性使基于 WebGPU 的应用更容易无修改地在不同平台上运行。

示例:
在同一 GPURenderPassEncoder 中,将同一缓冲区既作为存储,又作为输入绑定,会导致该缓冲区的用法列表为非兼容用法列表
示例:
这些规则允许只读深度模板:单个深度/模板纹理可在渲染通道中同时以两种只读用法使用:
示例:
存储用法例外允许两种原本不被允许的情况:
示例:
附件用法例外允许一个纹理子资源多次作为附件使用。这对于允许 3D 纹理的不相交切片作为不同附件绑定到同一渲染通道很有必要。

但同一切片不得作为两个不同附件重复绑定;这由 beginRenderPass() 检查。

3.4.4. 同步机制

用法范围(usage scope)是一个从有序映射,其键为子资源,值为 列表<内部用法>。每个用法范围覆盖一组可能并发执行的操作,因此在该范围内对子资源的使用只能是兼容用法列表

若对于 scope 中每个 [subresource, usageList],usageList 均为兼容用法列表,则 用法范围 scope 通过用法范围校验
要向 使用作用域(usage scope) usageScope 添加(add)一个 子资源(subresource) subresource,并指定 usage(内部用法或一组内部用法usage
  1. 如果 usageScope[subresource] 不存在,则将其设为 []

  2. 追加 usageusageScope[subresource]。

要将 使用作用域(usage scope) A 合并(merge)使用作用域(usage scope) B
  1. 对于 A 中的每一项 [subresource, usage]:

    1. 添加(Add) subresourceB,并指定 usage usage

用法范围在编码期间被构建和校验:

用法范围如下:

注:拷贝命令为独立操作,不使用用法范围进行校验,其自身实现了防止自竞争的校验。

示例:
以下资源用法被计入用法范围

3.5. 核心内部对象

3.5.1. 适配器(Adapters)

适配器(adapter)标识系统上的 WebGPU 实现:既包括底层平台上的计算/渲染功能实例,也包括浏览器在该功能之上实现 WebGPU 的实例。

适配器通过 GPUAdapter 暴露。

适配器并不唯一代表底层实现:多次调用 requestAdapter() 每次都会返回不同的适配器对象。

每个 适配器对象只能用于创建一个 设备(device):一旦成功调用 requestDevice(),该适配器的 [[state]] 变为 "consumed"。此外,适配器对象可能在任何时刻过期(expire)

注: 这样保证应用在创建设备时能使用最新的系统状态来选择适配器。也让多种场景(如首次初始化、因适配器移除重初始化、因 GPUDevice.destroy() 测试重初始化等)行为保持一致,提高健壮性。

若适配器以显著性能换取更广兼容性、更可预测行为或更好的隐私,则可视为回退适配器(fallback adapter)。不是每个系统都必须提供回退适配器。

适配器具有如下不可变属性

[[features]],类型为 有序集合<GPUFeatureName>,只读

可用于在此适配器上创建设备的特性

[[limits]],类型为支持的限制,只读

可用于在此适配器上创建设备的最佳限制。每个限制值必须与支持的限制中该项的默认值相同或更好(better)。

[[fallback]],类型为 boolean,只读

true 时,表示该适配器是回退适配器

[[xrCompatible]],类型为 boolean

true 时,表示该适配器请求了与 WebXR 会话 兼容。

适配器具有如下设备时间线属性

[[state]],初始值为 "valid"
"valid"

适配器可用于创建设备。

"consumed"

适配器已被用于创建设备,不能再次使用。

"expired"

适配器因其他原因已过期。

使 GPUAdapter 过期,请在设备时间线上执行:
  1. adapter.[[adapter]].[[state]] 设为 "expired"

3.5.2. 设备(Devices)

设备(device)适配器的逻辑实例,通过它可以创建内部对象

设备通过 GPUDevice 暴露。

一个设备独占其上创建的所有内部对象:当该设备变为无效丢失销毁时),它本身和所有直接(如 createTexture())或间接(如 createView())创建的对象都会隐式变为不可用

设备具有如下不可变属性

[[adapter]],类型为 适配器,只读

创建该设备的适配器

[[features]],类型为 有序集合<GPUFeatureName>,只读

可在该设备上使用的特性,在创建时确定。即使底层适配器支持更多特性,也不能使用额外特性。

[[limits]],类型为支持的限制,只读

可在该设备上使用的限制,在创建时确定。即使底层适配器支持更高限制,也不能使用更高值(better)。

设备具有如下内容时间线属性

[[content device]],类型为 GPUDevice,只读

该设备关联的内容时间线 GPUDevice 接口实例。

要从适配器 adapterGPUDeviceDescriptor descriptor 创建新设备,请执行以下设备时间线步骤:
  1. featuresdescriptor.requiredFeatures 中值的有序集合

  2. 如果 features 包含 "texture-formats-tier2"

    1. 追加 "texture-formats-tier1"features

  3. 如果 features 包含 "texture-formats-tier1"

    1. 追加 "rg11b10ufloat-renderable"features

  4. 追加 "core-features-and-limits"features

  5. limits 为所有值均为默认值的支持的限制对象。

  6. 对于 descriptor.requiredLimits 中每个 (key, value):

    1. 如果 value 不为 undefinedvalue 优于 limits[key]:

      1. limits[key] = value

  7. device 为新设备对象。

  8. device.[[adapter]] = adapter

  9. device.[[features]] = features

  10. device.[[limits]] = limits

  11. 返回 device

每当用户代理需要撤销设备访问权限时,会在该设备的设备时间线上调用 丢失设备(device, "unknown"),该操作可能优先于当前队列中的其他操作。

如果某操作失败且副作用可能导致设备上的对象状态可见变化或内部实现/驱动状态损坏,应当丢失该设备以防止这些变化被观察到。

注: 非应用主动发起的设备丢失(通过 destroy())时,用户代理应无条件向开发者发出警告,即使 lost promise 已被处理。此类场景应极其罕见,并且该信号对开发者至关重要,因为大多数 WebGPU API 会尽量表现为“一切正常”以避免中断运行时流程:不会抛出校验错误,大多数 promise 正常 resolve 等。

丢失设备(device, reason),请执行以下设备时间线步骤:
  1. 使 device 无效

  2. device.[[content device]]内容时间线上执行:

    1. 用新的 GPUDeviceLostInfo resolve device.lost,其中 reason 设为 reasonmessage 设为实现自定义值。

      注: message 不应泄露不必要的用户/系统信息,且绝不应用于应用程序解析。

  3. 完成所有等待 device 变为丢失的未完成步骤。

注:丢失的设备不会再生成错误。参见 § 22 错误与调试

监听时间线事件 event设备 device,并由 timeline 上的 steps 处理:

则在 timeline 上执行 steps

3.6. 可选功能

WebGPU 适配器设备具备功能,这些功能描述了WebGPU在不同实现之间的差异, 通常是由于硬件或系统软件的限制。 一项功能可以是特性限制

用户代理不得透露超过32个可区分的配置或分组。

适配器的功能必须符合§ 4.2.1 适配器功能保证

仅支持的功能可以在requestDevice()中请求; 请求不支持的功能会导致失败。

设备的功能在"一个新的设备"中确定, 通过从适配器的默认值(无特性和默认的支持的限制)开始, 并根据在requestDevice()中请求的功能添加功能。 这些功能无论适配器的功能如何均会被强制执行。

这里是追踪向量。 有关隐私方面的考虑,请参阅§ 2.2.1 机器特定的功能和限制

3.6.1. 特性

特性是一组可选的 WebGPU 功能,并非所有实现都支持这些功能,通常是由于硬件或系统软件的限制所致。

所有特性都是可选的,但适配器会对其可用性做出一定保证 (参见§ 4.2.1 适配器功能保证)。

设备仅支持在创建时确定的那组特性(参见§ 3.6 可选功能)。 API 调用将根据这些特性(而非适配器的特性)进行校验:

只有当 GPUObjectBaseobject[[device]].[[features]] 包含 feature 时,GPUFeatureName feature 才被认为是 启用的

每个特性所启用的功能描述可参见特性索引

注意: 启用特性未必是理想选择,可能会影响性能。 因此,为了提升不同设备和实现间的可移植性,应用程序通常只应请求实际需要的特性。

3.6.2. 限制

每个限制都是对设备上 WebGPU 使用的数值限制。

注意: 设置“更好”的限制未必是理想选择,因为这样可能会对性能产生影响。 因此,为了提升不同设备和实现之间的可移植性,应用程序通常只有在确实需要时才请求比默认值更好的限制。

每个限制都有一个默认值。

适配器始终保证支持默认值或更好的 (参见§ 4.2.1 适配器功能保证)。

设备仅支持在创建时确定的那组限制(参见§ 3.6 可选功能)。 API 调用根据这些限制进行校验(而非适配器的限制), 不允许“更好”或更差。

对于任何给定的限制,一些值是更好的更好的限制值始终放宽校验,从而使更多程序变得有效。 对于每个限制类别,“更好”的定义如下。

不同的限制具有不同的限制类别

最大值

限制在传递给 API 的某些值上强制设置一个最大值。

更高的值是更好的

仅能设置为 ≥ 默认值 的值。 较低的值会被限制为默认值

对齐

限制在传递给 API 的某些值上强制设置一个最小对齐;即该值必须是限制的倍数。

较低的值是更好的

仅能设置为 ≤ 默认值 的2的幂次。 非2的幂次值是无效的。 更高的2的幂次值会被限制为默认值

支持的限制 对象具有 WebGPU 定义的每个限制的值:

限制名称 类型 限制类别 默认值
maxTextureDimension1D GPUSize32 最大值 8192
创建dimension "1d"纹理时, size.width 的最大允许值。
maxTextureDimension2D GPUSize32 最大值 8192
创建dimension "2d"纹理时, size.widthsize.height 的最大允许值。
maxTextureDimension3D GPUSize32 最大值 2048
创建dimension "3d"纹理时, size.widthsize.heightsize.depthOrArrayLayers 的最大允许值。
maxTextureArrayLayers GPUSize32 最大值 256
创建dimension "2d"纹理时, size.depthOrArrayLayers 的最大允许值。
maxBindGroups GPUSize32 最大值 4
创建GPUPipelineLayout时, bindGroupLayouts 中允许的GPUBindGroupLayouts的最大数量。
maxBindGroupsPlusVertexBuffers GPUSize32 最大值 24
同时使用的绑定组和顶点缓冲区槽位的最大数量,包括所有低于最大索引的空槽位。 在createRenderPipeline()绘制调用中验证。
maxBindingsPerBindGroup GPUSize32 最大值 1000
创建GPUBindGroupLayout时可用的绑定索引数量。

注意: 此限制具有规范性,但属于人为设定。 按默认绑定槽位限制,一个绑定组实际上无法使用1000个绑定, 但这允许GPUBindGroupLayoutEntry.binding 的值达到999。这一限制允许实现把绑定空间当作数组而不是稀疏映射结构,便于内存管理。

maxDynamicUniformBuffersPerPipelineLayout GPUSize32 最大值 8
在一个GPUPipelineLayout中, 所有为动态偏移的uniform buffer的GPUBindGroupLayoutEntry条目的最大数量。 详见绑定槽位限制说明
maxDynamicStorageBuffersPerPipelineLayout GPUSize32 最大值 4
在一个GPUPipelineLayout中, 所有为动态偏移的storage buffer的GPUBindGroupLayoutEntry条目的最大数量。 详见绑定槽位限制说明
maxSampledTexturesPerShaderStage GPUSize32 最大值 16
对于每个GPUShaderStage stage,在一个GPUPipelineLayout中, 所有采样纹理的GPUBindGroupLayoutEntry条目的最大数量。 详见绑定槽位限制说明
maxSamplersPerShaderStage GPUSize32 最大值 16
对于每个GPUShaderStage stage,在一个GPUPipelineLayout中, 所有采样器的GPUBindGroupLayoutEntry条目的最大数量。 详见绑定槽位限制说明
maxStorageBuffersPerShaderStage GPUSize32 最大值 8
对于每个GPUShaderStage stage,在一个GPUPipelineLayout中, 所有存储缓冲区的GPUBindGroupLayoutEntry条目的最大数量。 详见绑定槽位限制说明
maxStorageTexturesPerShaderStage GPUSize32 最大值 4
对于每个可能的GPUShaderStage stage, 在一个GPUPipelineLayout中, 所有存储纹理类型GPUBindGroupLayoutEntry的最大数量。 详见绑定槽位限制说明
maxUniformBuffersPerShaderStage GPUSize32 最大值 12
对于每个可能的GPUShaderStage stage, 在一个GPUPipelineLayout中, 所有uniform buffer类型GPUBindGroupLayoutEntry的最大数量。 详见绑定槽位限制说明
maxUniformBufferBindingSize GPUSize64 最大值 65536 字节
绑定类型为 GPUBindGroupLayoutEntry ,且entry.buffer?.type"uniform" 时, GPUBufferBinding.size 的最大值。
maxStorageBufferBindingSize GPUSize64 最大值 134217728 字节(128 MiB)
绑定类型为 GPUBindGroupLayoutEntry ,且entry.buffer?.type"storage""read-only-storage" 时, GPUBufferBinding.size 的最大值。
minUniformBufferOffsetAlignment GPUSize32 对齐 256 字节
绑定类型为 GPUBindGroupLayoutEntry ,且entry.buffer?.type"uniform" 时, GPUBufferBinding.offset 以及 setBindGroup() 传入的动态偏移量所需的对齐要求。
minStorageBufferOffsetAlignment GPUSize32 对齐 256 字节
绑定类型为 GPUBindGroupLayoutEntry ,且entry.buffer?.type"storage""read-only-storage" 时, GPUBufferBinding.offset 以及 setBindGroup() 传入的动态偏移量所需的对齐要求。
maxVertexBuffers GPUSize32 最大值 8
创建GPURenderPipeline时,允许的buffers的最大数量。
maxBufferSize GPUSize64 最大值 268435456 字节(256 MiB)
创建GPUBuffer时,size的最大数值。
maxVertexAttributes GPUSize32 最大值 16
创建GPURenderPipeline时,所有attributesbuffers中的总和的最大数量。
maxVertexBufferArrayStride GPUSize32 最大值 2048 字节
创建GPURenderPipeline时,arrayStride的最大允许值。
maxInterStageShaderVariables GPUSize32 最大值 16
阶段间通信(如顶点输出、片元输入)可用的输入或输出变量的最大数量。
maxColorAttachments GPUSize32 最大值 8
GPURenderPipelineDescriptor.fragment.targetsGPURenderPassDescriptor.colorAttachmentsGPURenderPassLayout.colorFormats 中允许的最大颜色附件数量。
maxColorAttachmentBytesPerSample GPUSize32 最大值 32
渲染管线输出数据中,跨所有颜色附件存储一个采样(像素或子像素)所需的最大字节数。
maxComputeWorkgroupStorageSize GPUSize32 最大值 16384 字节
一个计算阶段GPUShaderModule入口点可用的workgroup存储的最大字节数。
maxComputeInvocationsPerWorkgroup GPUSize32 最大值 256
一个计算阶段GPUShaderModule入口点的workgroup_size各维度乘积的最大值。
maxComputeWorkgroupSizeX GPUSize32 最大值 256
一个计算阶段GPUShaderModule入口点的workgroup_size X 维度的最大值。
maxComputeWorkgroupSizeY GPUSize32 最大值 256
一个计算阶段GPUShaderModule入口点的workgroup_size Y 维度的最大值。
maxComputeWorkgroupSizeZ GPUSize32 最大值 64
一个计算阶段GPUShaderModule入口点的workgroup_size Z 维度的最大值。
maxComputeWorkgroupsPerDimension GPUSize32 最大值 65535
dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ)的参数的最大值。
3.6.2.1. GPUSupportedLimits

GPUSupportedLimits 用于暴露适配器或设备的支持的限制。 参见 GPUAdapter.limitsGPUDevice.limits

[Exposed=(Window, Worker), SecureContext]
interface GPUSupportedLimits {
    readonly attribute unsigned long maxTextureDimension1D;
    readonly attribute unsigned long maxTextureDimension2D;
    readonly attribute unsigned long maxTextureDimension3D;
    readonly attribute unsigned long maxTextureArrayLayers;
    readonly attribute unsigned long maxBindGroups;
    readonly attribute unsigned long maxBindGroupsPlusVertexBuffers;
    readonly attribute unsigned long maxBindingsPerBindGroup;
    readonly attribute unsigned long maxDynamicUniformBuffersPerPipelineLayout;
    readonly attribute unsigned long maxDynamicStorageBuffersPerPipelineLayout;
    readonly attribute unsigned long maxSampledTexturesPerShaderStage;
    readonly attribute unsigned long maxSamplersPerShaderStage;
    readonly attribute unsigned long maxStorageBuffersPerShaderStage;
    readonly attribute unsigned long maxStorageTexturesPerShaderStage;
    readonly attribute unsigned long maxUniformBuffersPerShaderStage;
    readonly attribute unsigned long long maxUniformBufferBindingSize;
    readonly attribute unsigned long long maxStorageBufferBindingSize;
    readonly attribute unsigned long minUniformBufferOffsetAlignment;
    readonly attribute unsigned long minStorageBufferOffsetAlignment;
    readonly attribute unsigned long maxVertexBuffers;
    readonly attribute unsigned long long maxBufferSize;
    readonly attribute unsigned long maxVertexAttributes;
    readonly attribute unsigned long maxVertexBufferArrayStride;
    readonly attribute unsigned long maxInterStageShaderVariables;
    readonly attribute unsigned long maxColorAttachments;
    readonly attribute unsigned long maxColorAttachmentBytesPerSample;
    readonly attribute unsigned long maxComputeWorkgroupStorageSize;
    readonly attribute unsigned long maxComputeInvocationsPerWorkgroup;
    readonly attribute unsigned long maxComputeWorkgroupSizeX;
    readonly attribute unsigned long maxComputeWorkgroupSizeY;
    readonly attribute unsigned long maxComputeWorkgroupSizeZ;
    readonly attribute unsigned long maxComputeWorkgroupsPerDimension;
};
3.6.2.2. GPUSupportedFeatures

GPUSupportedFeatures 是一个 类似集合(setlike) 接口。它的 集合条目 是适配器或设备支持的 GPUFeatureName 值。 它只能包含 GPUFeatureName 枚举中的字符串。

[Exposed=(Window, Worker), SecureContext]
interface GPUSupportedFeatures {
    readonly setlike<DOMString>;
};
注意:
GPUSupportedFeatures集合条目 类型为 DOMString, 这样可以让用户代理优雅地处理后续规范修订中新增但用户代理尚未识别的有效 GPUFeatureName。 如果 集合条目 的类型是 GPUFeatureName,如下代码将抛出 TypeError, 而不是返回 false
检查对未知特性的支持:
if (adapter.features.has('unknown-feature')) {
    // 使用 unknown-feature
} else {
    console.warn('unknown-feature is not supported by this adapter.');
}
3.6.2.3. WGSLLanguageFeatures

WGSLLanguageFeaturesnavigator.gpu.wgslLanguageFeatures类似集合(setlike) 接口。 它的 集合条目 是该实现支持的 WGSL 语言扩展 的字符串名称(不论适配器或设备)。

[Exposed=(Window, Worker), SecureContext]
interface WGSLLanguageFeatures {
    readonly setlike<DOMString>;
};
3.6.2.4. GPUAdapterInfo

GPUAdapterInfo 用于暴露关于适配器的各种标识信息。

GPUAdapterInfo 的成员不保证有任何特定值;如果没有提供值,该属性将返回空字符串 ""。是否揭示这些值由用户代理自行决定,并且某些设备上可能所有值都为空。因此,应用必须能够处理任何可能的 GPUAdapterInfo 值,包括这些值缺失的情况。

适配器的 GPUAdapterInfo 可通过 GPUAdapter.infoGPUDevice.adapterInfo 获取。 这些信息是不可变的:对于某个适配器,每次访问同一个 GPUAdapterInfo 属性都会返回相同的值。

注意: 虽然 GPUAdapterInfo 属性一旦访问就不可变, 但实现可以在首次访问前延后决定每个属性的内容。

注意: 即便其他 GPUAdapter 实例代表同一物理适配器, 它们在 GPUAdapterInfo 中揭示的值也可能不同。 但除非有特殊事件提升了页面可访问的标识信息(本规范未定义此类事件),否则它们应当揭示相同的值。

There is a tracking vector here. 关于隐私考虑,请参见 § 2.2.6 适配器标识符

[Exposed=(Window, Worker), SecureContext]
interface GPUAdapterInfo {
    readonly attribute DOMString vendor;
    readonly attribute DOMString architecture;
    readonly attribute DOMString device;
    readonly attribute DOMString description;
    readonly attribute unsigned long subgroupMinSize;
    readonly attribute unsigned long subgroupMaxSize;
    readonly attribute boolean isFallbackAdapter;
};

GPUAdapterInfo 拥有如下属性:

vendor类型为 DOMString,只读

适配器的厂商名称(如有)。否则为空字符串。

architecture类型为 DOMString,只读

适配器所属 GPU 家族或类别的名称(如有)。否则为空字符串。

device类型为 DOMString,只读

适配器的厂商自定义标识符(如有)。否则为空字符串。

注意: 这是代表适配器类型的值。例如,可能是 PCI 设备ID。它不会像序列号一样唯一标识某块硬件。

description类型为 DOMString,只读

驱动报告的关于适配器的人类可读字符串描述(如有)。否则为空字符串。

注意: description 没有采用任何格式化,不建议尝试解析此值。根据 GPUAdapterInfo 改变行为的应用(如为已知驱动问题应用修正),应尽量依赖其他字段。

subgroupMinSize类型为 unsigned long,只读

如果支持 "subgroups" 特性,则为适配器支持的最小 子组大小

subgroupMaxSize类型为 unsigned long,只读

如果支持 "subgroups" 特性,则为适配器支持的最大 子组大小

isFallbackAdapter类型为 boolean,只读

适配器是否为回退适配器

要为指定的 adapter adapter 创建一个 新的适配器信息(new adapter info),请执行如下 内容时序 步骤:
  1. adapterInfo 为新的 GPUAdapterInfo

  2. 如果已知厂商,则将 adapterInfo.vendor 设为 adapter 的厂商名,并格式化为规范化标识符字符串。为保护隐私,用户代理也可以将 adapterInfo.vendor 设为空字符串,或一个合理近似的厂商名(同样为规范化标识符字符串)。

  3. 如果已知架构,则将 adapterInfo.architecture 设为代表 adapter 所属 GPU 家族或类别的规范化标识符字符串。为保护隐私,用户代理也可以设为空字符串,或合理近似的架构名(同样为规范化标识符字符串)。

  4. 如果已知设备,则将 adapterInfo.device 设为 adapter 的厂商自定义标识符,并格式化为规范化标识符字符串。为保护隐私,用户代理也可以设为空字符串,或合理近似的标识符(同样为规范化标识符字符串)。

  5. 如果已知描述,则将 adapterInfo.description 设为驱动报告的 adapter 描述。为保护隐私,用户代理也可以设为空字符串,或合理近似的描述。

  6. 如果支持 "subgroups" 特性,则将 subgroupMinSize 设为支持的最小子组大小;否则设为 4。

    注意: 为保护隐私,用户代理可以选择不支持某些特性,或为属性提供不会区分不同设备但依然可用的值(如对所有设备使用默认值 4)。

  7. 如果支持 "subgroups" 特性,则将 subgroupMaxSize 设为支持的最大子组大小;否则设为 128。

    注意: 为保护隐私,用户代理可以选择不支持某些特性,或为属性提供不会区分不同设备但依然可用的值(如对所有设备使用默认值 128)。

  8. adapterInfo.isFallbackAdapter 设为 adapter.[[fallback]]

  9. 返回 adapterInfo

规范化标识符字符串(normalized identifier string)指符合如下模式的字符串:

[a-z0-9]+(-[a-z0-9]+)*

a-z 0-9 -
合法规范化标识符字符串的示例包括:
  • gpu

  • 3d

  • 0x3b2f

  • next-gen

  • series-x20-ultra

3.7. 扩展文档

“扩展文档”是描述新功能的附加文档,这些功能是非规范性的,不属于 WebGPU/WGSL 规范的一部分。 它们描述了在这些规范基础上构建的功能,通常包含一个或多个新的 API 特性标志和/或 WGSL enable 指令,或与其他草案 Web 规范的交互。

WebGPU 实现不得暴露扩展功能;这样做属于规范违规。 新功能只有在被集成到 WebGPU 规范(本文档)和/或 WGSL 规范后,才成为 WebGPU 标准的一部分。

3.8. 源限制(Origin Restrictions)

WebGPU 允许访问存储在图片、视频和画布中的图像数据。 出于安全原因,对跨域媒体的使用施加了限制,因为着色器可以被用来间接推测已上传到 GPU 的纹理内容。

WebGPU 不允许上传 不是 origin-clean 的图片源。

这也意味着,使用 WebGPU 渲染的 canvas 的 origin-clean 标志永远不会被置为 false

关于为图片和视频元素发起 CORS 请求的更多信息,请参考:

3.9. 任务源(Task Sources)

3.9.1. WebGPU 任务源

WebGPU 定义了一个新的 任务源,称为 WebGPU 任务源。 它用于 uncapturederror 事件和 GPUDevice.lost

若要为 GPUDevice device 排队一个全局任务(queue a global task),并在 内容时序 上执行一系列步骤 steps
  1. WebGPU 任务源 上,为用于创建 device 的全局对象,按 steps 排队一个全局任务

3.9.2. 自动过期任务源

WebGPU 定义了一个新的 任务源,称为 自动过期任务源。 它用于自动、定时地销毁某些对象:

要用 GPUDevice device 和一系列步骤 steps内容时序排队一个自动过期任务
  1. 自动过期任务源 上,为用于创建 device 的全局对象,按 steps 排队一个全局任务

来自 自动过期任务源 的任务应当以高优先级处理;尤其是排入队列后,应当在用户自定义(JavaScript)任务之前执行。

注意:
这种行为更可预测,也能通过及早发现关于隐式生命周期的错误假设,帮助开发者编写更具移植性的应用程序。开发者仍然强烈建议在多个实现中进行测试。

实现说明: 以高优先级处理过期“任务”也可以通过在事件循环处理模型的某个固定点插入额外步骤来实现,而不一定非要运行实际的任务。

3.10. 色彩空间与编码

WebGPU 不提供色彩管理。WebGPU 内的所有值(如纹理元素)都是原始数值,不是经过色彩管理的色值。

WebGPU 确实与色彩管理的输出(通过 GPUCanvasConfiguration)和输入(通过 copyExternalImageToTexture()importExternalTexture())对接。因此,必须在 WebGPU 数值和外部色值之间进行色彩转换。每个接口点都会本地定义一种编码(色彩空间、传递函数和 alpha 预乘),用于解释 WebGPU 的数值。

WebGPU 允许 PredefinedColorSpace 枚举中的所有色彩空间。注意,每个色彩空间都定义了扩展范围(详见 CSS 相关定义),可以表示其空间外的颜色值(包括色度和明度)。

超出色域的预乘 RGBA 值指 R/G/B 其中任意一个通道的值大于 alpha 通道的值。例如,预乘 sRGB RGBA 值 [1.0, 0, 0, 0.5] 表示原始(未预乘)颜色 [2, 0, 0] 且 alpha 为 50%,在 CSS 中可写作 rgb(srgb 2 0 0 / 50%)。和所有 sRGB 色域外的颜色一样,这在扩展色彩空间中是有定义的点(alpha 为 0 时除外,此时没有颜色)。但若此类值输出到可见画布,结果未定义(见 GPUCanvasAlphaMode "premultiplied")。

3.10.1. 色彩空间转换

颜色在空间间转换时,需根据上述定义将其在一个空间中的表示转换为另一个空间中的表示。

如果源值少于4个 RGBA 通道,则缺失的绿/蓝/alpha 通道分别设为0, 0, 1,然后再做色彩空间/编码和 alpha 预乘转换。转换后,如果目标需要的通道数少于4,则忽略多余通道。

注意: 灰度图像通常在其色彩空间下表现为 RGB 值 (V, V, V) 或 RGBA 值 (V, V, V, A)

颜色在转换时不会被有损截断:若源色值本就在目标色彩空间的色域外,转换后会产生超出[0, 1]范围的值。例如,sRGB 目标下,如果源为 rgba16float,色彩空间更广(如 Display-P3),或为预乘且包含超出色域的预乘值,都可能出现上述情况。

同样,如果源值有高位深(如 16 位/分量 PNG)或扩展范围(如 float16 存储的 canvas),这些颜色会在转换过程中保留,且中间计算的精度不少于源。

3.10.2. 色彩空间转换省略

若源与目标的色彩空间/编码一致,则无需转换。通常,若某一步是恒等函数(无操作),实现应当出于性能考虑省略该步骤。

为获得最佳性能,应用应当设置色彩空间和编码选项,以最小化整个流程中所需的转换次数。 对于各种 GPUCopyExternalImageSourceInfo 图像源:

注意: 在依赖这些特性前,请检查浏览器的实现支持。

3.11. JavaScript 到 WGSL 的数值转换

WebGPU API 的多个部分(可覆盖管线 constants 和渲染通道清除值)会接收来自 WebIDL(doublefloat)的数值,并将其转换为 WGSL 值(booli32u32f32f16)。

将类型为 doublefloat 的 IDL 值 idlValue 转换为 WGSL 类型(to WGSL type) T,可能抛出 TypeError,请执行以下 设备时序 步骤:

注意:TypeError 只会在 设备时序 内产生,并不会抛到 JavaScript。

  1. 断言 idlValue 是有限值,因为它不是 unrestricted doubleunrestricted float

  2. vidlValue 转换为 ECMAScript 值 后得到的 ECMAScript Number。

  3. 如果 Tbool

    返回与 !v 转换为 IDL 类型 boolean 后结果对应的 WGSL bool 值。

    注意: 本算法是在从 ECMAScript 值到 IDL doublefloat 值的转换之后调用的。如果原始 ECMAScript 值为非数值、非布尔值(如 []{}),那么 WGSL bool 结果可能与直接转换为 IDL boolean 的结果不同。

    如果 Ti32

    返回 WGSL i32 值,该值对应于 ?v 转换为类型为 [EnforceRange] longIDL 值 的结果。

    如果 Tu32

    返回 WGSL u32 值,该值对应于 ?v 转换为类型为 [EnforceRange] unsigned longIDL 值 的结果。

    如果 Tf32

    返回 WGSL f32 值,该值对应于 ?v 转换为类型为 floatIDL 值 的结果。

    如果 Tf16
    1. wgslF32 为 WGSL f32 值,该值对应于 ?v 转换为类型为 floatIDL 值 的结果。

    2. 返回 f16(wgslF32),即 !WGSL 浮点数转换 所定义,将 WGSL f32 值转换为 f16 的结果。

    注意:只要值在 f32 的范围内,即使超出 f16 的范围,也不会抛出错误。

若要将 GPUColor color 转换为纹理格式的 texel 值(to a texel value of texture format) format,可能抛出 TypeError,请执行以下 设备时序 步骤:

注意:TypeError 只会在 设备时序 内产生,并不会抛到 JavaScript。

  1. format 的各分量类型(断言全部相同)为:

    浮点类型或归一化类型

    Tf32

    有符号整型

    Ti32

    无符号整型

    Tu32

  2. wgslColor 为 WGSL vec4<T>,其 4 个分量为 color 的 RGBA 通道,每个都 转换为 WGSL 类型 T

  3. § 23.2.7 输出合并 的同样规则将 wgslColor 转换为 format,并返回结果。

    注意: 对于非整型类型,实际取值为实现定义。对于归一化类型,值会被限制在该类型允许的范围内。

注意: 换言之,写入的值就如同由 WGSL 着色器以 f32i32u32 类型的 vec4 输出。

4. 初始化

WindowWorkerGlobalScope 上下文中,GPU 对象通过 NavigatorWorkerNavigator 接口暴露,访问方式为 navigator.gpu

interface mixin NavigatorGPU {
    [SameObject, SecureContext] readonly attribute GPU gpu;
};
Navigator includes NavigatorGPU;
WorkerNavigator includes NavigatorGPU;

NavigatorGPU 具有以下属性:

gpu类型为 GPU,只读

一个全局单例,提供诸如 requestAdapter() 的顶级入口点。

4.2. GPU

GPU 是 WebGPU 的入口点。

[Exposed=(Window, Worker), SecureContext]
interface GPU {
    Promise<GPUAdapter?> requestAdapter(optional GPURequestAdapterOptions options = {});
    GPUTextureFormat getPreferredCanvasFormat();
    [SameObject] readonly attribute WGSLLanguageFeatures wgslLanguageFeatures;
};

GPU 具有以下方法:

requestAdapter(options)

从用户代理请求一个 adapter。用户代理选择是否返回适配器,并根据提供的选项进行选择。

调用对象: GPU this.

参数:

参数表:GPU.requestAdapter(options) 方法。
参数 类型 可空 可选 描述
options GPURequestAdapterOptions 用于选择适配器的条件。

返回: Promise<GPUAdapter?>

内容时序步骤:

  1. contentTimeline 为当前 内容时序

  2. promise一个新的 promise

  3. this设备时序上执行 初始化步骤

  4. 返回 promise

设备时序 初始化步骤
  1. 以下步骤的所有要求必须满足。

    1. options.featureLevel必须为一个特性级别字符串

    如果满足要求用户代理选择返回一个适配器:

    1. 设置 adapter 为根据 § 4.2.2 适配器选择 中的规则和 options 的条件选择的 adapter,并遵循 § 4.2.1 适配器能力保证。根据定义初始化适配器的属性:

      1. 根据适配器的支持能力设置 adapter.[[limits]]adapter.[[features]]adapter.[[features]] 必须包含 "core-features-and-limits"

      2. 如果 adapter 满足回退适配器的条件,则将 adapter.[[fallback]] 设置为 true。否则,设置为 false

      3. adapter.[[xrCompatible]] 设置为 options.xrCompatible

    否则:

    1. adapternull

  2. contentTimeline 上执行后续步骤。

内容时序步骤:
  1. 如果 adapter 不为 null

    1. 解析(Resolve) promise,返回一个封装了 adapter 的新 GPUAdapter

  2. 否则,解析(Resolve) promise,返回 null

getPreferredCanvasFormat()

返回在本系统上显示 8 位深度、标准动态范围内容的最佳 GPUTextureFormat。只能返回 "rgba8unorm""bgra8unorm"

返回值可作为 format 传递给 configure() 方法,以确保相关 GPUCanvasContext 能高效显示其内容。

注意: 未显示到屏幕上的 canvas 使用此格式可能无益,也可能有益。

调用对象: GPU this。

返回: GPUTextureFormat

内容时序 步骤:

  1. 根据本系统 WebGPU canvas 显示的最佳格式,返回 "rgba8unorm""bgra8unorm"

GPU 有以下属性:

wgslLanguageFeatures 类型为 WGSLLanguageFeatures,只读

支持的 WGSL 语言扩展的名称。 支持的语言扩展会自动启用。

适配器 可能 随时被 过期。 当系统状态发生任何可能影响任何 requestAdapter() 调用结果的变化时,用户代理 应当 使所有 先前返回的 适配器 过期。例如:

注意: 用户代理可能会选择经常 过期 适配器,即使系统状态没有发生变化(例如在适配器创建后几秒或几分钟)。 这有助于混淆真实的系统状态变化,并让开发者更加意识到,在调用 requestAdapter() 之前,总是需要重新请求适配器再调用 requestDevice()。 如果应用遇到这种情况,标准的设备丢失恢复处理应当能够使其恢复。

无提示地请求一个 GPUAdapter
const gpuAdapter = await navigator.gpu.requestAdapter();

4.2.1. 适配器能力保证

任何由 GPUAdapter 通过 requestAdapter() 返回的对象都必须提供以下保证:

4.2.2. 适配器选择

GPURequestAdapterOptions 为用户代理提供指示,表明哪些配置适合应用程序。

dictionary GPURequestAdapterOptions {
    DOMString featureLevel = "core";
    GPUPowerPreference powerPreference;
    boolean forceFallbackAdapter = false;
    boolean xrCompatible = false;
};
enum GPUPowerPreference {
    "low-power",
    "high-performance",
};

GPURequestAdapterOptions 拥有如下成员:

featureLevel 类型为 DOMString,默认值为 "core"

适配器请求的“功能级别”。

允许的 功能级别字符串值为:

"core"

无影响。

"compatibility"

无影响。

注意: 该值为将来引入额外验证限制时保留。 目前应用不应使用此值。

powerPreference 类型为 GPUPowerPreference

可选,为用户代理提供一个提示,指示应从系统可用适配器中选择哪种类别的 适配器

该提示的值可能影响选择哪个适配器,但不得影响是否返回适配器。

注意: 该提示的主要用途是在多GPU系统上影响所用的GPU。 例如,某些笔记本电脑有低功耗集成GPU和高性能独立GPU。该提示也可能影响所选GPU的电源配置,以匹配请求的电源偏好。

注意: 根据具体硬件配置(如电池状态、外接显示器或可卸载GPU),即使设置了相同的电源偏好,用户代理可能依然选择不同的 适配器。 通常,在相同硬件配置和状态下,且 powerPreference 一致,用户代理通常会选择同一个适配器。

必须为以下值之一:

undefined(或未设置)

不给用户代理提供任何提示。

"low-power"

表示请求优先考虑节能而非性能。

注意: 如果内容渲染需求较低(如每秒只渲染一帧,仅绘制相对简单的几何体和着色器,或只用小型HTML canvas元素),一般应使用该选项。 如果内容允许,鼓励开发者使用此值,因为这可能大幅提升便携设备的电池寿命。

"high-performance"

表示请求优先考虑性能而非能耗。

注意: 选择此值时,开发者应注意,对于在所选适配器上创建的 设备,用户代理更可能强制设备丢失,以便切换到低功耗适配器节能。 只有在确有必要时,开发者才应指定此值,因为它可能会大幅降低便携设备的电池寿命。

forceFallbackAdapter 类型为 boolean,默认值为 false

若设为 true,表示只能返回 回退适配器。如果用户代理不支持 回退适配器,则 requestAdapter() 会返回 null

注意: 即使 forceFallbackAdapter 设为 falserequestAdapter() 仍可能返回 回退适配器(当没有其他合适的 适配器可用,或用户代理选择返回回退适配器时)。 希望避免应用在 回退适配器上运行的开发者应在请求 GPUDevice 前检查 info.isFallbackAdapter 属性。

xrCompatible 类型为 boolean,默认值为 false

若设为 true,表示必须返回用于 WebXR会话渲染的最佳 适配器。如果用户代理或系统不支持 WebXR会话,则适配器选择可忽略此值。

注意: 如果在请求适配器时 xrCompatible 未设为 true,则从该适配器创建的 GPUDevice 无法用于 WebXR会话 渲染。

请求 "high-performance" GPUAdapter
const gpuAdapter = await navigator.gpu.requestAdapter({
    powerPreference: 'high-performance'
});

4.3. GPUAdapter

GPUAdapter 封装了一个 适配器, 并描述其能力(特性限制)。

要获取一个 GPUAdapter, 请使用 requestAdapter()

[Exposed=(Window, Worker), SecureContext]
interface GPUAdapter {
    [SameObject] readonly attribute GPUSupportedFeatures features;
    [SameObject] readonly attribute GPUSupportedLimits limits;
    [SameObject] readonly attribute GPUAdapterInfo info;

    Promise<GPUDevice> requestDevice(optional GPUDeviceDescriptor descriptor = {});
};

GPUAdapter 拥有以下不可变属性

features 类型为 GPUSupportedFeatures,只读

this.[[adapter]].[[features]] 中的值集合。

limits 类型为 GPUSupportedLimits,只读

this.[[adapter]].[[limits]] 中的限制。

info 类型为 GPUAdapterInfo,只读

关于该 GPUAdapter 所对应物理适配器的信息。

对于同一个 GPUAdapter, 暴露的 GPUAdapterInfo 值在时间上是恒定的。

每次返回的都是同一个对象。首次创建该对象的方法如下:

调用对象: GPUAdapter this.

返回: GPUAdapterInfo

内容时间线 步骤:

  1. this.[[adapter]] 返回一个新的适配器信息

[[adapter]],类型为 adapter,只读

GPUAdapter 所引用的 适配器

GPUAdapter 拥有以下方法:

requestDevice(descriptor)

从该 适配器 请求一个 设备

这是一次性操作:如果成功返回了设备,则适配器变为 "consumed"

调用对象: GPUAdapter this.

参数:

方法 GPUAdapter.requestDevice(descriptor) 的参数。
参数 类型 可为 null 可选 描述
descriptor GPUDeviceDescriptor 请求的 GPUDevice 的描述信息。

返回: Promise<GPUDevice>

内容时间线 步骤:

  1. contentTimeline 为当前 内容时间线

  2. promise新的 promise

  3. adapterthis.[[adapter]]

  4. this设备时间线 执行 初始化步骤

  5. 返回 promise

设备时间线 初始化步骤
  1. 如果下列任何要求未满足:

    则在 contentTimeline 上执行下列步骤并返回:

    内容时间线 步骤:
    1. 拒绝 promise,并给出 TypeError

    注意: 这与浏览器完全不识别某特性的情况下抛出的错误相同(在其 GPUFeatureName 定义里)。 这使得浏览器不支持某特性和某适配器不支持某特性时的行为一致。

  2. 以下步骤中的所有要求 必须 被满足。

    1. adapter.[[state]] 不得为 "consumed"

    2. 对于 descriptor.requiredLimits 中每个 keyvalue 对(且 value 不为 undefined):

      1. key 必须支持的限制的成员名。

      2. value 不得adapter.[[limits]][key] 更高。

      3. key类别对齐value 必须 是小于 232 的 2 的幂。

      注意: 即使 valueundefined,当 key 未被识别时,用户代理应考虑给出开发者可见的警告。

    若有未满足项,则在 contentTimeline 上执行下列步骤并返回:

    内容时间线 步骤:
    1. 拒绝 promise,并给出 OperationError

  3. 如果 adapter.[[state]]"expired" 或用户代理无法完成该请求:

    1. device 为新的 设备

    2. 丢失该设备(device, "unknown")。

    3. 断言 adapter.[[state]]"expired"

      注意: 当发生这种情况时,用户代理应考虑在大多数或所有情况下向开发者发出警告。应用应从 requestAdapter() 开始重新初始化逻辑。

    否则:

    1. device 为带有 descriptor 描述能力的新设备

    2. 使 adapter 过期

  4. contentTimeline 上执行后续步骤。

内容时间线 步骤:
  1. gpuDevice 为新的 GPUDevice 实例。

  2. 设置 gpuDevice.[[device]]device

  3. 设置 device.[[content device]]gpuDevice

  4. 设置 gpuDevice.labeldescriptor.label

  5. 解决 promise,返回 gpuDevice

    注意: 如果由于适配器无法完成请求而设备已丢失,则 device.lostpromise 解决前已经解决。

请求带有默认特性和限制的 GPUDevice
const gpuAdapter = await navigator.gpu.requestAdapter();
const gpuDevice = await gpuAdapter.requestDevice();

4.3.1. GPUDeviceDescriptor

GPUDeviceDescriptor 描述一个设备请求。

dictionary GPUDeviceDescriptor
     : GPUObjectDescriptorBase {
sequence<GPUFeatureName> requiredFeatures = [];
record<DOMString, (GPUSize64 or undefined)> requiredLimits = {};
GPUQueueDescriptor defaultQueue = {};
};

GPUDeviceDescriptor 拥有以下成员:

requiredFeatures 类型为 sequence<GPUFeatureName>,默认值为 []

指定设备请求所需的特性。 如果适配器无法提供这些特性,请求会失败。

API调用的校验只允许恰好指定的特性,不多也不少。

requiredLimits 类型为 record<DOMString, (GPUSize64 or undefined)>,默认值为 {}

指定设备请求所需的限制。 如果适配器无法提供这些限制,请求会失败。

每个非 undefined 值的 key 必须是支持的限制的成员名。

在最终设备上的 API 调用会根据该设备的实际限制(不是适配器的限制;见 § 3.6.2 限制)进行校验。

defaultQueue 类型为 GPUQueueDescriptor,默认值为 {}

默认 GPUQueue 的描述符。

当支持 "texture-compression-astc" 特性时,请求 GPUDevice
const gpuAdapter = await navigator.gpu.requestAdapter();

const requiredFeatures = [];
if (gpuAdapter.features.has('texture-compression-astc')) {
    requiredFeatures.push('texture-compression-astc')
}

const gpuDevice = await gpuAdapter.requestDevice({
    requiredFeatures
});
请求 GPUDevice 并指定更高的 maxColorAttachmentBytesPerSample 限制:
const gpuAdapter = await navigator.gpu.requestAdapter();

if (gpuAdapter.limits.maxColorAttachmentBytesPerSample < 64) {
    // 当所需限制不被支持时,采取措施,要么降级代码路径,要么提示用户其设备不满足最低要求。
}

// 请求更高的每样本最大颜色附件字节数限制。
const gpuDevice = await gpuAdapter.requestDevice({
    requiredLimits: { maxColorAttachmentBytesPerSample: 64 },
});
4.3.1.1. GPUFeatureName

每个 GPUFeatureName 都标识一组功能,如果可用,可使 WebGPU 支持本来无效的额外用法。

enum GPUFeatureName {
    "core-features-and-limits",
    "depth-clip-control",
    "depth32float-stencil8",
    "texture-compression-bc",
    "texture-compression-bc-sliced-3d",
    "texture-compression-etc2",
    "texture-compression-astc",
    "texture-compression-astc-sliced-3d",
    "timestamp-query",
    "indirect-first-instance",
    "shader-f16",
    "rg11b10ufloat-renderable",
    "bgra8unorm-storage",
    "float32-filterable",
    "float32-blendable",
    "clip-distances",
    "dual-source-blending",
    "subgroups",
    "texture-formats-tier1",
    "texture-formats-tier2",
};

4.4. GPUDevice

GPUDevice 封装了一个设备并暴露该设备的功能。

GPUDevice 是创建WebGPU 接口的顶层接口。

要获取一个 GPUDevice,请使用 requestDevice()

[Exposed=(Window, Worker), SecureContext]
interface GPUDevice : EventTarget {
    [SameObject] readonly attribute GPUSupportedFeatures features;
    [SameObject] readonly attribute GPUSupportedLimits limits;
    [SameObject] readonly attribute GPUAdapterInfo adapterInfo;

    [SameObject] readonly attribute GPUQueue queue;

    undefined destroy();

    GPUBuffer createBuffer(GPUBufferDescriptor descriptor);
    GPUTexture createTexture(GPUTextureDescriptor descriptor);
    GPUSampler createSampler(optional GPUSamplerDescriptor descriptor = {});
    GPUExternalTexture importExternalTexture(GPUExternalTextureDescriptor descriptor);

    GPUBindGroupLayout createBindGroupLayout(GPUBindGroupLayoutDescriptor descriptor);
    GPUPipelineLayout createPipelineLayout(GPUPipelineLayoutDescriptor descriptor);
    GPUBindGroup createBindGroup(GPUBindGroupDescriptor descriptor);

    GPUShaderModule createShaderModule(GPUShaderModuleDescriptor descriptor);
    GPUComputePipeline createComputePipeline(GPUComputePipelineDescriptor descriptor);
    GPURenderPipeline createRenderPipeline(GPURenderPipelineDescriptor descriptor);
    Promise<GPUComputePipeline> createComputePipelineAsync(GPUComputePipelineDescriptor descriptor);
    Promise<GPURenderPipeline> createRenderPipelineAsync(GPURenderPipelineDescriptor descriptor);

    GPUCommandEncoder createCommandEncoder(optional GPUCommandEncoderDescriptor descriptor = {});
    GPURenderBundleEncoder createRenderBundleEncoder(GPURenderBundleEncoderDescriptor descriptor);

    GPUQuerySet createQuerySet(GPUQuerySetDescriptor descriptor);
};
GPUDevice includes GPUObjectBase;

GPUDevice 拥有以下 不可变属性

features 类型为 GPUSupportedFeatures,只读

包含设备支持的 GPUFeatureName 的集合([[device]].[[features]])。

limits 类型为 GPUSupportedLimits,只读

该设备支持的限制([[device]].[[limits]])。

queue 类型为 GPUQueue,只读

此设备的主 GPUQueue

adapterInfo 类型为 GPUAdapterInfo,只读

创建此 设备的物理适配器的信息,该 GPUDevice 所指向的适配器。

对于同一个 GPUDevice,暴露的 GPUAdapterInfo 值在时间上是恒定的。

每次返回的都是同一个对象。首次创建该对象的方法如下:

调用对象: GPUDevice this

返回: GPUAdapterInfo

内容时间线 步骤:

  1. this.[[device]].[[adapter]] 返回一个新的适配器信息

[[device]]GPUDevice 所引用的 设备

GPUDevice 拥有以下方法:

destroy()

销毁该 设备,阻止进一步的操作。所有未完成的异步操作将失败。

注意: 多次销毁同一个设备是合法的。

调用对象: GPUDevice this

内容时间线 步骤:

  1. 对该设备的所有 GPUBuffer 调用 unmap()

  2. this设备时间线 上执行后续步骤。

  1. 丢失该设备(this.[[device]], "destroyed")。

注意: 由于无法在该设备上排队新的操作,实现可以立即中止所有未完成的异步操作并释放资源,包括刚刚解除映射的内存。

GPUDevice允许的缓冲区用法 包括:
GPUDevice允许的纹理用法 包括:

4.5. 示例

一个更健壮的请求 GPUAdapterGPUDevice 并进行错误处理的示例:
let gpuDevice = null;

async function initializeWebGPU() {
    // 检查用户代理是否支持 WebGPU。
    if (!('gpu' in navigator)) {
        console.error("用户代理不支持 WebGPU。");
        return false;
    }

    // 请求适配器。
    const gpuAdapter = await navigator.gpu.requestAdapter();

    // 如果找不到合适的适配器,requestAdapter 可能会 resolve 为 null。
    if (!gpuAdapter) {
        console.error('未找到 WebGPU 适配器。');
        return false;
    }

    // 请求设备。
    // 注意:如果给可选字典传递了无效参数,promise 会 reject。为避免 promise 被拒绝,
    // 总是应在调用 requestDevice() 前检查特性和限制是否被适配器支持。
    gpuDevice = await gpuAdapter.requestDevice();

    // requestDevice 永远不会返回 null,但如果出于某种原因无法满足有效的设备请求,
    // 它可能会返回一个已经丢失的设备。
    // 此外,设备在创建后可能随时丢失(如:浏览器资源管理、驱动更新),
    // 因此应始终优雅地处理设备丢失。
    gpuDevice.lost.then((info) => {
        console.error(`WebGPU 设备已丢失: ${info.message}`);

        gpuDevice = null;

        // 多数设备丢失的原因是临时性的,因此应用应在丢失后尝试获取新设备,
        // 除非丢失原因是应用主动销毁了设备。注意,所有用旧设备创建的 WebGPU 资源(缓冲区、纹理等)
        // 都需要用新设备重新创建。
        if (info.reason != 'destroyed') {
            initializeWebGPU();
        }
    });

    onWebGPUInitialized();

    return true;
}

function onWebGPUInitialized() {
    // 在这里创建 WebGPU 资源……
}

initializeWebGPU();

5. 缓冲区

5.1. GPUBuffer

GPUBuffer 表示一块可用于 GPU 操作的内存块。 数据以线性布局存储,这意味着分配的每个字节都可以通过其相对于 GPUBuffer 起始位置的偏移来寻址, 但具体操作可能有对齐限制。某些 GPUBuffers 可以被映射,使这块内存可以通过一个称为映射的 ArrayBuffer 访问。

GPUBuffer 通过 createBuffer() 创建。 缓冲区可以 mappedAtCreation

[Exposed=(Window, Worker), SecureContext]
interface GPUBuffer {
    readonly attribute GPUSize64Out size;
    readonly attribute GPUFlagsConstant usage;

    readonly attribute GPUBufferMapState mapState;

    Promise<undefined> mapAsync(GPUMapModeFlags mode, optional GPUSize64 offset = 0, optional GPUSize64 size);
    ArrayBuffer getMappedRange(optional GPUSize64 offset = 0, optional GPUSize64 size);
    undefined unmap();

    undefined destroy();
};
GPUBuffer includes GPUObjectBase;

enum GPUBufferMapState {
    "unmapped",
    "pending",
    "mapped",
};

GPUBuffer 拥有以下 不可变属性

size 类型为 GPUSize64Out,只读

GPUBuffer 分配的字节长度。

usage 类型为 GPUFlagsConstant,只读

GPUBuffer 的允许用法。

GPUBuffer 拥有以下 内容时间线属性

mapState 类型为 GPUBufferMapState,只读

缓冲区的当前 GPUBufferMapState

"unmapped"

缓冲区未被 this.getMappedRange() 映射使用。

"pending"

缓冲区已请求映射,但尚未完成。映射可能成功,也可能在 mapAsync() 校验时失败。

"mapped"

缓冲区已映射,可以通过 this.getMappedRange() 使用。

getter 步骤如下:

内容时间线 步骤:
  1. 如果 this.[[mapping]] 不为 null,返回 "mapped"

  2. 如果 this.[[pending_map]] 不为 null,返回 "pending"

  3. 返回 "unmapped"

[[pending_map]],类型为 Promise<void> 或 null,初始为 null

当前挂起的 mapAsync() 调用返回的 Promise

永远不会有多个挂起的映射,因为如果已有请求在进行中,mapAsync() 会立即拒绝。

[[mapping]],类型为 活动缓冲区映射null,初始为 null

仅当缓冲区当前被 getMappedRange() 映射使用时才设置。否则为 null(即使有 [[pending_map]])。

活动缓冲区映射 是具有以下字段的结构:

data,类型为 数据块

GPUBuffer 的映射数据。应用通过 ArrayBuffer 视图访问,由 getMappedRange() 返回并存储在 views 中。

mode,类型为 GPUMapModeFlags

映射的 GPUMapModeFlags,由相应 mapAsync()createBuffer() 调用指定。

range,类型为元组 [unsigned long long, unsigned long long]

GPUBuffer 被映射的范围。

views,类型为 list<ArrayBuffer>

通过 getMappedRange() 返回给应用的 ArrayBuffer。这些视图会在 unmap() 被调用时被追踪并分离。

要用 mode mode 和 range range 初始化活动缓冲区映射,执行以下 内容时间线 步骤:
  1. sizerange[1] - range[0]。

  2. data? CreateByteDataBlock(size)。

    注意:
    这可能抛出 RangeError。 为了保证一致和可预测性:
    • 对于 new ArrayBuffer() 在某一时刻能成功的任意 size,此分配 也应 同时成功。

    • 对于 new ArrayBuffer() 确定性 抛出 RangeError 的任意 size,此分配 也应 抛出。

  3. 返回具有如下内容的 活动缓冲区映射

缓冲区的映射与解除映射。
缓冲区映射失败。

GPUBuffer 拥有以下 设备时间线属性

[[internal state]]

缓冲区的当前内部状态:

"available"

缓冲区可用于队列操作(除非已失效)。

"unavailable"

缓冲区因已映射而不可用于队列操作。

"destroyed"

缓冲区因被 destroy() 而无法用于任何操作。

5.1.1. GPUBufferDescriptor

dictionary GPUBufferDescriptor
     : GPUObjectDescriptorBase {
required GPUSize64 size;
required GPUBufferUsageFlags usage;
boolean mappedAtCreation = false;
};

GPUBufferDescriptor 拥有以下成员:

size 类型为 GPUSize64

缓冲区的字节大小。

usage 类型为 GPUBufferUsageFlags

缓冲区允许的用法。

mappedAtCreation 类型为 boolean,默认值为 false

如果为 true,则缓冲区会以已映射状态创建,允许立即调用 getMappedRange()。 即使 usage 不包含 MAP_READMAP_WRITE,也可以设置 mappedAtCreationtrue。 这可用于设置缓冲区的初始数据。

即使最终缓冲区创建失败,也保证看起来映射范围可读写直到其被解除映射。

5.1.2. 缓冲区用法

typedef [EnforceRange] unsigned long GPUBufferUsageFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUBufferUsage {
    const GPUFlagsConstant MAP_READ      = 0x0001;
    const GPUFlagsConstant MAP_WRITE     = 0x0002;
    const GPUFlagsConstant COPY_SRC      = 0x0004;
    const GPUFlagsConstant COPY_DST      = 0x0008;
    const GPUFlagsConstant INDEX         = 0x0010;
    const GPUFlagsConstant VERTEX        = 0x0020;
    const GPUFlagsConstant UNIFORM       = 0x0040;
    const GPUFlagsConstant STORAGE       = 0x0080;
    const GPUFlagsConstant INDIRECT      = 0x0100;
    const GPUFlagsConstant QUERY_RESOLVE = 0x0200;
};

GPUBufferUsage 标志决定了 GPUBuffer 创建后可以如何使用:

MAP_READ

缓冲区可被映射用于读取。(例如:调用 mapAsync() 并传入 GPUMapMode.READ

只能与 COPY_DST 组合使用。

MAP_WRITE

缓冲区可被映射用于写入。(例如:调用 mapAsync() 并传入 GPUMapMode.WRITE

只能与 COPY_SRC 组合使用。

COPY_SRC

缓冲区可作为拷贝操作的源。(例如:作为 copyBufferToBuffer()copyBufferToTexture() 调用的 source 参数)

COPY_DST

缓冲区可作为拷贝或写入操作的目标。(例如:作为 copyBufferToBuffer()copyTextureToBuffer() 调用的 destination 参数,或作为 writeBuffer() 的目标。)

INDEX

缓冲区可作为索引缓冲区使用。(例如:传递给 setIndexBuffer()。)

VERTEX

缓冲区可作为顶点缓冲区使用。(例如:传递给 setVertexBuffer()。)

UNIFORM

缓冲区可用作 uniform 缓冲区。(例如:用于 GPUBufferBindingLayout 的绑定组条目,且 buffer.type"uniform"。)

STORAGE

缓冲区可用作 storage 缓冲区。(例如:用于 GPUBufferBindingLayout 的绑定组条目,且 buffer.type"storage""read-only-storage"。)

INDIRECT

缓冲区可用于存储间接命令参数。(例如:作为 indirectBuffer 参数传递给 drawIndirect()dispatchWorkgroupsIndirect() 调用。)

QUERY_RESOLVE

缓冲区可用于捕获查询结果。(例如:作为 destination 参数传递给 resolveQuerySet()。)

5.1.3. 缓冲区创建

createBuffer(descriptor)

创建一个 GPUBuffer

调用对象: GPUDevice this

参数:

GPUDevice.createBuffer(descriptor) 方法的参数。
参数 类型 可为 null 可选 描述
descriptor GPUBufferDescriptor 要创建的 GPUBuffer 描述信息。

返回: GPUBuffer

内容时间线 步骤:

  1. b! 创建新的 WebGPU 对象(this, GPUBuffer, descriptor)。

  2. 设置 b.sizedescriptor.size

  3. 设置 b.usagedescriptor.usage

  4. 如果 descriptor.mappedAtCreationtrue

    1. 如果 descriptor.size 不是 4 的倍数,抛出 RangeError

    2. 设置 b.[[mapping]]? 初始化活动缓冲区映射,mode 为 WRITE,range 为 [0, descriptor.size]

  5. this设备时间线 上执行 初始化步骤

  6. 返回 b

设备时间线 初始化步骤
  1. 如有以下任一要求未被满足, 生成校验错误使 b 失效并返回。

注意: 如果缓冲区创建失败,且 descriptor.mappedAtCreationfalse, 任何对 mapAsync() 的调用都会被拒绝,因此为支持映射而分配的任何资源都可以被回收。

  1. 如果 descriptor.mappedAtCreationtrue

    1. 设置 b.[[internal state]] 为 "unavailable"。

    否则:

    1. 设置 b.[[internal state]] 为 "available"。

  2. b 创建设备分配,并将每个字节置零。

    如果分配失败且无副作用,生成内存不足错误使 b 失效并返回。

创建一个 128 字节、可写入的 uniform 缓冲区:
const buffer = gpuDevice.createBuffer({
    size: 128,
    usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST
});

5.1.4. 缓冲区销毁

应用如果不再需要某个 GPUBuffer,可以在垃圾回收前调用 destroy() 主动放弃访问它。 销毁缓冲区还会解除映射,释放为映射分配的内存。

注意: 这样允许用户代理在所有先前提交的与该 GPUBuffer 相关的操作完成后及时回收其 GPU 内存。

GPUBuffer 拥有以下方法:

destroy()

销毁该 GPUBuffer

注意: 多次销毁同一个缓冲区是合法的。

调用对象: GPUBuffer this

返回值: undefined

内容时间线 步骤:

  1. 调用 this.unmap()

  2. this.[[device]]设备时间线 上执行后续步骤。

设备时间线 步骤:
  1. 设置 this.[[internal state]] 为 "destroyed"。

注意: 由于无法继续用该缓冲区排队新操作,实现可以立即释放资源分配,包括刚刚解除映射的内存。

5.2. 缓冲区映射

应用可以请求映射 GPUBuffer,从而通过代表该 GPUBuffer 分配部分的 ArrayBuffer 访问其内容。 映射 GPUBuffer 的请求是通过 mapAsync() 异步进行的,以便用户代理能确保 GPU 在应用访问内容前已完成对该 GPUBuffer 的使用。 被映射的 GPUBuffer 不能被 GPU 使用,必须通过 unmap() 解除映射后才能再次用于 队列时间线的工作提交。

一旦 GPUBuffer 被映射,应用可通过 getMappedRange() 同步访问其内容范围。 返回的 ArrayBuffer 只能被 unmap()(直接或通过 GPUBuffer.destroy()GPUDevice.destroy())分离,不能被转移。 任何其它操作试图这样做都会抛出 TypeError

typedef [EnforceRange] unsigned long GPUMapModeFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUMapMode {
    const GPUFlagsConstant READ  = 0x0001;
    const GPUFlagsConstant WRITE = 0x0002;
};

GPUMapMode 标志决定了调用 mapAsync()GPUBuffer 被如何映射:

READ

只对创建时带有 MAP_READ 用法的缓冲区有效。

映射后,调用 getMappedRange() 将返回包含缓冲区当前值的 ArrayBuffer。对返回的 ArrayBuffer 的更改在 unmap() 后会被丢弃。

WRITE

只对创建时带有 MAP_WRITE 用法的缓冲区有效。

映射后,调用 getMappedRange() 将返回包含缓冲区当前值的 ArrayBuffer。对返回的 ArrayBuffer 的更改会在 unmap() 后写入缓冲区。

注意: 由于 MAP_WRITE 用法只能与 COPY_SRC 组合,写映射永远不会返回 GPU 产生的数据,返回的 ArrayBuffer 只包含初始化为零的数据或网页之前映射写入的数据。

GPUBuffer 拥有以下方法:

mapAsync(mode, offset, size)

映射 GPUBuffer 的指定范围,并在缓冲区内容可以通过 getMappedRange() 访问时 resolve 返回的 Promise

返回的 Promise 表示缓冲区已被映射,不保证其它 内容时间线可见操作完成,特别是不保证其它 Promise(如 onSubmittedWorkDone() 或其它 mapAsync())已 resolve。

PromiseonSubmittedWorkDone() 返回则保证在该队列上之前的所有 mapAsync() 已完成。

调用对象: GPUBuffer this

参数:

GPUBuffer.mapAsync(mode, offset, size) 方法的参数。
参数 类型 可为 null 可选 描述
mode GPUMapModeFlags 缓冲区应以读或写方式映射。
offset GPUSize64 要映射的范围起始字节偏移。
size GPUSize64 要映射的范围字节大小。

返回值: Promise<undefined>

内容时间线步骤:

  1. contentTimeline 为当前 内容时间线

  2. this.mapState 不为 "unmapped"

    1. this.[[device]]设备时间线 上执行 early-reject steps

    2. 返回 被拒绝的 promise,错误为 OperationError

  3. p 为新的 Promise

  4. 设置 this.[[pending_map]] = p

  5. this.[[device]]设备时间线 上执行 validation steps

  6. 返回 p

设备时间线 early-reject steps
  1. 生成校验错误

  2. 返回。

设备时间线 validation steps
  1. 如果 sizeundefined

    1. rangeSize = max(0, this.size - offset)。

    否则:

    1. rangeSize = size

  2. 如果下述任一条件不满足:

    1. 设置 deviceLosttrue

    2. contentTimeline 上执行 map failure steps

    3. 返回。

  3. 如果下述任一条件不满足:

    否则:

    1. 设置 deviceLostfalse

    2. contentTimeline 上执行 map failure steps

    3. 生成校验错误

    4. 返回。

  4. this.[[internal state]] 设为 "unavailable"。

    注意: 缓冲区被映射后,在解除映射前其内容不会改变。

  5. 当下述任一事件发生(以先发生者为准),或已发生时:

    然后在 this.[[device]]设备时间线 上执行后续步骤。

设备时间线 步骤:
  1. this.[[device]]失效,则 deviceLost 设为 true,否则为 false

    注意: 设备可能在前后步骤之间丢失。

  2. 如果 deviceLost

    1. contentTimeline 上执行 map failure steps

    否则:

    1. internalStateAtCompletion = this.[[internal state]]

      注意: 只有当此时缓冲区因 unmap() 变为 "available" 时,[[pending_map]]p,后续 mapping 步骤不会成功。

    2. dataForMappedRegionthisoffset 开始,长度为 rangeSize 字节的内容。

    3. contentTimeline 上执行 map success steps

内容时间线 map success steps
  1. this.[[pending_map]]p

    注意: 映射已被 unmap() 取消。

    1. 断言 p 已被拒绝。

    2. 返回。

  2. 断言 p 仍为 pending。

  3. 断言 internalStateAtCompletion 为 "unavailable"。

  4. mapping = 初始化活动缓冲区映射,mode 为 mode,range 为 [offset, offset + rangeSize]

    若分配失败:

    1. this.[[pending_map]] = null,并 拒绝 p,错误为 RangeError

    2. 返回。

  5. mapping.data 设为 dataForMappedRegion

  6. this.[[mapping]] = mapping

  7. this.[[pending_map]] = null,并 resolve p

内容时间线 map failure steps
  1. 如果 this.[[pending_map]]p

    注意: 映射已被 unmap() 取消。

    1. 断言 p 已被拒绝。

    2. 返回。

  2. 断言 p 仍为 pending。

  3. this.[[pending_map]] = null

  4. 如果 deviceLost

    1. 拒绝 p 并抛出 AbortError

      注意: 这和用 unmap() 取消 map 时抛出的错误类型一致。

    否则:

    1. 拒绝 p 并抛出 OperationError

getMappedRange(offset, size)

返回包含指定范围 GPUBuffer 内容的 ArrayBuffer

调用对象: GPUBuffer this

参数:

GPUBuffer.getMappedRange(offset, size) 方法的参数。
参数 类型 可为 null 可选 描述
offset GPUSize64 要返回内容的起始字节偏移。
size GPUSize64 要返回的 ArrayBuffer 字节长度。

返回值: ArrayBuffer

内容时间线 步骤:

  1. 如果 size 未指定:

    1. rangeSize = max(0, this.size - offset)。

    否则,rangeSize = size

  2. 如以下任一条件不满足,则抛出 OperationError 并返回:

    注意:GPUBuffer,即使其为 mappedAtCreation无效,只要 内容时间线 未知其无效,依然可以获取映射范围。

  3. data = this.[[mapping]].data

  4. view = 创建 ArrayBuffer,大小为 rangeSize,指针可变地引用 data 从 (offset - [[mapping]].range[0]) 开始的内容。

    注意: 这里不会抛出 RangeError,因为 data 已在 mapAsync()createBuffer() 时分配。

  5. 设置 view.[[ArrayBufferDetachKey]] 为 "WebGPUBufferMapping"。

    注意: 这样如果尝试用除 unmap() 外的方法分离该 ArrayBuffer,会抛出 TypeError

  6. 追加 viewthis.[[mapping]].views

  7. 返回 view

注意:getMappedRange() 调用未先检查映射状态(如等待 mapAsync() resolve、查询 mapState"mapped" 或等待 onSubmittedWorkDone()),用户代理应考虑发出开发警告。

unmap()

解除 GPUBuffer 的映射范围,使其内容重新可被 GPU 使用。

调用对象: GPUBuffer this

返回值: undefined

内容时间线 步骤:

  1. 如果 this.[[pending_map]] 不为 null

    1. 拒绝 this.[[pending_map]],错误为 AbortError

    2. this.[[pending_map]] = null

  2. 如果 this.[[mapping]]null

    1. 返回。

  3. 对于 this.[[mapping]].views 中的每个 ArrayBuffer ab

    1. 执行 DetachArrayBuffer(ab, "WebGPUBufferMapping")。

  4. bufferUpdate = null

  5. 如果 this.[[mapping]].mode 包含 WRITE

    1. bufferUpdate = { data: this.[[mapping]].data, offset: this.[[mapping]].range[0] }。

    注意: 如果缓冲区不是以 WRITE 模式映射,解除映射时应用对映射范围 ArrayBuffer 的本地修改会被丢弃,不会影响后续映射内容。

  6. this.[[mapping]] = null

  7. this.[[device]]设备时间线 上执行后续步骤。

设备时间线 步骤:
  1. 如下条件任一不满足则返回:

  2. 断言 this.[[internal state]] 为 "unavailable"。

  3. 如果 bufferUpdate 不为 null

    1. this.[[device]].queue队列时间线 上执行:

      队列时间线 步骤:
      1. bufferUpdate.data 更新 thisbufferUpdate.offset 开始的内容。

  4. this.[[internal state]] 设为 "available"。

6. 纹理与纹理视图

6.1. GPUTexture

纹理(texture)1d2d3d 的数据数组组成,每个元素可包含多个值用于表示如颜色等信息。纹理的读写方式取决于创建时使用的 GPUTextureUsage。 例如,纹理可被采样、读写于渲染与计算管线着色器,也可由渲染通道输出写入。纹理在 GPU 内部通常以多维访问优化的布局存储,而非线性存储。

一个 纹理 由一个或多个 纹理子资源(texture subresource) 组成,每个子资源由 mipmap 级别 唯一标识, 对于 2d 纹理,还包括 数组层aspect(分量)

纹理子资源 是一种 子资源:每个子资源可在单一 用法范围 内有不同 内部用途

每个 mipmap 级别 的子资源 在每个空间维度上的尺寸大约是上一级资源的一半 (见 mipmap 级别特定逻辑纹理范围)。 0 级子资源的尺寸等于纹理本身的尺寸,更小的级别通常用于存储同一图像的低分辨率版本。 GPUSampler 与 WGSL 提供了选择与插值 细节级别 的能力,可显式或自动进行。

"2d" 纹理可以是 数组层(array layer) 的集合。 每一层的子资源尺寸都相同。非 2d 纹理的所有子资源的数组层索引都为 0。

每个子资源有一个 aspect(分量)。 彩色纹理只有一个分量:color深度或模板格式 的纹理可能有多个分量: depth 分量, stencil 分量,或两者皆有, 可被特殊用法所使用,如 depthStencilAttachment"depth" 绑定。

"3d" 纹理可以有多个 切片(slice),每个切片是该纹理在特定 z 值下的二维图像。 切片不是独立的子资源。

[Exposed=(Window, Worker), SecureContext]
interface GPUTexture {
    GPUTextureView createView(optional GPUTextureViewDescriptor descriptor = {});

    undefined destroy();

    readonly attribute GPUIntegerCoordinateOut width;
    readonly attribute GPUIntegerCoordinateOut height;
    readonly attribute GPUIntegerCoordinateOut depthOrArrayLayers;
    readonly attribute GPUIntegerCoordinateOut mipLevelCount;
    readonly attribute GPUSize32Out sampleCount;
    readonly attribute GPUTextureDimension dimension;
    readonly attribute GPUTextureFormat format;
    readonly attribute GPUFlagsConstant usage;
};
GPUTexture includes GPUObjectBase;

GPUTexture 拥有如下不可变属性

width类型为 GPUIntegerCoordinateOut,只读

GPUTexture 的宽度。

height类型为 GPUIntegerCoordinateOut,只读

GPUTexture 的高度。

depthOrArrayLayers类型为 GPUIntegerCoordinateOut,只读

GPUTexture 的深度或层数。

mipLevelCount类型为 GPUIntegerCoordinateOut,只读

GPUTexture 的 mip 级别数量。

sampleCount类型为 GPUSize32Out,只读

GPUTexture 的采样数。

dimension类型为 GPUTextureDimension,只读

每个子资源的 texel 集的维度。

format类型为 GPUTextureFormat,只读

GPUTexture 的格式。

usage类型为 GPUFlagsConstant,只读

GPUTexture 允许的用途。

[[viewFormats]],类型为 sequence<GPUTextureFormat>

为此 GPUTexture 创建视图时可用作 GPUTextureViewDescriptor.formatGPUTextureFormat 集合。

GPUTexture 拥有如下设备时间线属性

[[destroyed]],类型为 boolean, 初始值为 false

如果纹理被销毁,它将无法再被用于任何操作,其底层内存可以被释放。

compute render extent(baseSize, mipLevel)

参数:

返回: GPUExtent3DDict

设备时间线步骤:

  1. extent 为新的 GPUExtent3DDict 对象。

  2. 设置 extent.width 为 max(1, baseSize.widthmipLevel)。

  3. 设置 extent.height 为 max(1, baseSize.heightmipLevel)。

  4. 设置 extent.depthOrArrayLayers 为 1。

  5. 返回 extent

逻辑 mip 级别特定纹理范围(logical miplevel-specific texture extent) 指的是某个 纹理 在特定 mipLevel 下的 texel 尺寸。 其计算过程如下:

逻辑 mip 级别特定纹理范围 (descriptor, mipLevel)

参数:

返回: GPUExtent3DDict

  1. extent 为新的 GPUExtent3DDict 对象。

  2. 如果 descriptor.dimension 为:

    "1d"
    "2d"
    "3d"
  3. 返回 extent

物理 mip 级别特定纹理范围(physical miplevel-specific texture extent) 指的是某个 纹理 在特定 mipLevel 下的 texel 尺寸,并包含为形成完整texel block而可能补齐的额外填充。其计算过程如下:

物理 mip 级别特定纹理范围 (descriptor, mipLevel)

参数:

返回: GPUExtent3DDict

  1. extent 为新的 GPUExtent3DDict 对象。

  2. logicalExtent = 逻辑 mip 级别特定纹理范围(descriptor, mipLevel)。

  3. 如果 descriptor.dimension 为:

    "1d"
    "2d"
    "3d"
  4. 返回 extent

6.1.1. GPUTextureDescriptor

dictionary GPUTextureDescriptor
         : GPUObjectDescriptorBase {
    required GPUExtent3D size;
    GPUIntegerCoordinate mipLevelCount = 1;
    GPUSize32 sampleCount = 1;
    GPUTextureDimension dimension = "2d";
    required GPUTextureFormat format;
    required GPUTextureUsageFlags usage;
    sequence<GPUTextureFormat> viewFormats = [];
};

GPUTextureDescriptor 拥有如下成员:

size类型为 GPUExtent3D

纹理的宽度、高度和深度或层数。

mipLevelCount类型为 GPUIntegerCoordinate,默认值为1

该纹理包含的 mip 级别数量。

sampleCount类型为 GPUSize32,默认值为1

纹理的采样数。当 sampleCount > 1 时,表示为多重采样纹理。

dimension类型为 GPUTextureDimension,默认值为"2d"

指定纹理是一维、二维数组层,还是三维纹理。

format类型为 GPUTextureFormat

纹理的格式。

usage类型为 GPUTextureUsageFlags

纹理允许的用途。

viewFormats类型为 sequence<GPUTextureFormat>,默认值为[]

指定在该纹理上调用 createView() 时,允许作为 format 的格式(除了纹理实际的 format 外)。

注意:
添加格式到该列表可能会带来显著的性能影响,因此应避免不必要地添加格式。

实际的性能影响高度依赖于目标系统;开发者需在多种系统上测试应用以了解具体影响。例如,在某些系统上,formatviewFormats 包含 "rgba8unorm-srgb" 时, 性能可能不如仅包含 "rgba8unorm" 的纹理。其他格式和格式组合在不同系统上也有类似注意事项。

该列表的格式必须与纹理格式 兼容

两个 GPUTextureFormatformatviewFormat,当且仅当满足以下条件时,纹理视图格式兼容(texture view format compatible)
  • format 等于 viewFormat,或

  • formatviewFormat 唯一区别在于是否为 srgb 格式(后缀为 -srgb)。

enum GPUTextureDimension {
    "1d",
    "2d",
    "3d",
};
"1d"

指定仅有宽度的一维纹理。"1d" 纹理不能有 mipmap,不能多重采样,不能使用压缩或深度/模板格式,也不能作为渲染目标。

"2d"

指定具有宽度和高度,并可具有层的二维纹理。

"3d"

指定具有宽度、高度和深度的三维纹理。"3d" 纹理不能多重采样,且其格式必须支持 3d 纹理(所有纯色格式和部分打包/压缩格式)。

6.1.2. 纹理用法

typedef [EnforceRange] unsigned long GPUTextureUsageFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUTextureUsage {
    const GPUFlagsConstant COPY_SRC          = 0x01;
    const GPUFlagsConstant COPY_DST          = 0x02;
    const GPUFlagsConstant TEXTURE_BINDING   = 0x04;
    const GPUFlagsConstant STORAGE_BINDING   = 0x08;
    const GPUFlagsConstant RENDER_ATTACHMENT = 0x10;
};

GPUTextureUsage 标志决定 GPUTexture 创建后可如何使用:

COPY_SRC

该纹理可作为拷贝操作的源。(例如:作为 source 参数传递给 copyTextureToTexture()copyTextureToBuffer() 调用。)

COPY_DST

该纹理可作为拷贝或写入操作的目标。(例如:作为 destination 参数传递给 copyTextureToTexture()copyBufferToTexture() 调用,或作为 writeTexture() 的目标。)

TEXTURE_BINDING

该纹理可在着色器中作为采样纹理绑定(例如:作为 GPUTextureBindingLayout 的绑定组项)。

STORAGE_BINDING

该纹理可在着色器中作为存储纹理绑定(例如:作为 GPUStorageTextureBindingLayout 的绑定组项)。

RENDER_ATTACHMENT

该纹理可作为渲染通道中的颜色或深度/模板附件使用。(例如:作为 GPURenderPassColorAttachment.viewGPURenderPassDepthStencilAttachment.view。)

最大 mipLevel 数量(dimension, size)

参数:

  1. 计算最大维度值 m

  2. 返回 floor(log2(m)) + 1。

6.1.3. 纹理创建

createTexture(descriptor)

创建一个 GPUTexture

调用对象: GPUDevice this.

参数:

参数列表: GPUDevice.createTexture(descriptor)
参数 类型 可为 null 可选 描述
descriptor GPUTextureDescriptor 描述要创建的 GPUTexture

返回值: GPUTexture

内容时间线步骤:

  1. ? 校验 GPUExtent3D 形状(descriptor.size)。

  2. ? 校验纹理格式所需特性 (descriptor.format, this.[[device]])。

  3. ? 校验纹理格式所需特性 (对 descriptor.viewFormats 的每一项, this.[[device]])。

  4. t = ! 创建新的 WebGPU 对象(this, GPUTexture, descriptor)。

  5. t.width = descriptor.size.width

  6. t.height = descriptor.size.height

  7. t.depthOrArrayLayers = descriptor.size.depthOrArrayLayers

  8. t.mipLevelCount = descriptor.mipLevelCount

  9. t.sampleCount = descriptor.sampleCount

  10. t.dimension = descriptor.dimension

  11. t.format = descriptor.format

  12. t.usage = descriptor.usage

  13. this设备时间线上执行初始化步骤

  14. 返回 t

设备时间线 初始化步骤
  1. 如以下任一条件不满足,产生校验错误置为无效并返回。

  2. t.[[viewFormats]] = descriptor.viewFormats

  3. t 创建设备分配,使每个块具有与全零比特表示的块等价的 texel 表示。

    如分配失败且无副作用,产生内存不足错误置为无效并返回。

validating GPUTextureDescriptor(this, descriptor):

参数:

设备时间线步骤:

  1. limits = this.[[limits]]

  2. 仅当所有如下要求都满足时返回 true,否则返回 false

创建一个 16x16、RGBA 格式、二维、单数组层、单 mip 级别的纹理:
const texture = gpuDevice.createTexture({
    size: { width: 16, height: 16 },
    format: 'rgba8unorm',
    usage: GPUTextureUsage.TEXTURE_BINDING,
});

6.1.4. 纹理销毁

当应用不再需要某个 GPUTexture 时,可以通过调用 destroy() 主动失去对此对象的访问权,而无需等待垃圾回收。

注意: 这样允许用户代理在该 GPUTexture 相关的所有已提交操作完成后,回收其占用的 GPU 内存。

GPUTexture 拥有如下方法:

destroy()

销毁该 GPUTexture

调用对象: GPUTexture this

返回值: undefined

内容时间线步骤:

  1. 设备时间线上执行如下步骤。

设备时间线步骤:
  1. this.[[destroyed]] 设为 true。

6.2. GPUTextureView

GPUTextureView 是对某个 纹理子资源 子集的视图,由特定 GPUTexture 定义。

[Exposed=(Window, Worker), SecureContext]
interface GPUTextureView {
};
GPUTextureView includes GPUObjectBase;

GPUTextureView 拥有如下不可变属性

[[texture]],只读

该视图所属的 GPUTexture

[[descriptor]],只读

描述此纹理视图的 GPUTextureViewDescriptor

所有 GPUTextureViewDescriptor 的可选字段都有定义。

[[renderExtent]],只读

对于可渲染视图,这是渲染时实际使用的 GPUExtent3DDict

注意:该范围取决于 baseMipLevel

纹理视图 view子资源(subresources)集合, 设 [[descriptor]]desc, 是 view.[[texture]] 的子资源子集,其中每个子资源 s 满足:

只有当两个 GPUTextureView 的子资源集合有交集时,它们才 视图别名(texture-view-aliasing)

6.2.1. 纹理视图创建

dictionary GPUTextureViewDescriptor
         : GPUObjectDescriptorBase {
    GPUTextureFormat format;
    GPUTextureViewDimension dimension;
    GPUTextureUsageFlags usage = 0;
    GPUTextureAspect aspect = "all";
    GPUIntegerCoordinate baseMipLevel = 0;
    GPUIntegerCoordinate mipLevelCount;
    GPUIntegerCoordinate baseArrayLayer = 0;
    GPUIntegerCoordinate arrayLayerCount;
};

GPUTextureViewDescriptor 拥有如下成员:

format类型为 GPUTextureFormat

纹理视图的格式。必须是纹理的 format 或创建时指定的 viewFormats 之一。

dimension类型为 GPUTextureViewDimension

视图的维度。

usage类型为 GPUTextureUsageFlags,默认值为0

纹理视图允许的 usage。必须是纹理 usage 标志的子集。若为 0,则默认为纹理的全部 usage 标志。

注意:如果视图的 format 不支持纹理的全部 usage,则默认值会失败,此时必须显式指定视图的 usage

aspect类型为 GPUTextureAspect,默认值为"all"

视图可访问的纹理 aspect

baseMipLevel类型为 GPUIntegerCoordinate,默认值为0

该视图可访问的第一个(最详细) mipmap 级别。

mipLevelCount类型为 GPUIntegerCoordinate

baseMipLevel 开始,该视图可访问的 mipmap 级别数量。

baseArrayLayer类型为 GPUIntegerCoordinate,默认值为0

该视图可访问的第一个数组层索引。

arrayLayerCount类型为 GPUIntegerCoordinate

baseArrayLayer 开始,该视图可访问的数组层数量。

enum GPUTextureViewDimension {
"1d",
"2d",
"2d-array",
"cube",
"cube-array",
"3d",
};
"1d"

该视图作为一维图像。

对应的 WGSL 类型:

  • texture_1d

  • texture_storage_1d

"2d"

该视图作为单一的二维图像。

对应的 WGSL 类型:

  • texture_2d

  • texture_storage_2d

  • texture_multisampled_2d

  • texture_depth_2d

  • texture_depth_multisampled_2d

"2d-array"

该视图作为二维图像数组。

对应的 WGSL 类型:

  • texture_2d_array

  • texture_storage_2d_array

  • texture_depth_2d_array

"cube"

该视图作为立方体贴图。

该视图有 6 个数组层,分别对应立方体的 6 个面,顺序为 [+X, -X, +Y, -Y, +Z, -Z],朝向如下:

立方体贴图各面。+U/+V 轴表示各面纹理坐标,也即每个面的 texel copy 内存布局。

注意:从内部看,这是一个左手坐标系,+X 右,+Y 上,+Z 前。

采样时会在立方体各面间无缝进行。

对应的 WGSL 类型:

  • texture_cube

  • texture_depth_cube

"cube-array"

该视图作为 n 个立方体贴图的打包数组,每个立方体 6 个数组层,总共 6n 层。

对应的 WGSL 类型:

  • texture_cube_array

  • texture_depth_cube_array

"3d"

该视图作为三维图像。

对应的 WGSL 类型:

  • texture_3d

  • texture_storage_3d

每个 GPUTextureAspect 值对应一组 aspectaspect 集合如下定义:

enum GPUTextureAspect {
    "all",
    "stencil-only",
    "depth-only",
};
"all"

纹理格式的所有可用 aspect 都可被该视图访问。对于颜色格式,可访问 color aspect。对于深度-模板复合格式,可访问 depth 和 stencil 两个 aspect。只有单一 aspect 的深度或模板格式,仅可访问该 aspect。

aspect 集合为 [color, depth, stencil]。

"stencil-only"

仅可访问深度或模板格式的 stencil aspect。

aspect 集合为 [stencil]。

"depth-only"

仅可访问深度或模板格式的 depth aspect。

aspect 集合为 [depth]。

createView(descriptor)

创建一个 GPUTextureView

注意:
默认情况下,createView() 会创建一个可以表示整个纹理的视图。例如,在一个具有多个图层的 "2d" 纹理上调用 createView() 且未指定 dimension 时,将会创建一个 "2d-array" GPUTextureView, 即使指定了 arrayLayerCount 为 1。

对于那些在开发时无法确定图层数的来源创建的纹理,建议在调用 createView() 时显式提供 dimension ,以确保着色器兼容性。

调用对象: GPUTexture this

参数:

参数列表: GPUTexture.createView(descriptor)
参数 类型 可为 null 可选 描述
descriptor GPUTextureViewDescriptor 要创建的 GPUTextureView 的描述。

返回值: view,类型为 GPUTextureView

内容时间线步骤:

  1. ? 校验纹理格式所需特性(descriptor.format, this.[[device]])。

  2. view = ! 创建新的 WebGPU 对象(this, GPUTextureView, descriptor)。

  3. this设备时间线上执行初始化步骤

  4. 返回 view

设备时间线 初始化步骤
  1. descriptor 设为对 thisdescriptor 执行 解析 GPUTextureViewDescriptor 默认值 的结果。

  2. 如下条件有任一不满足,产生校验错误置为无效并返回 view

  3. view 为新的 GPUTextureView对象。

  4. view.[[texture]] = this

  5. view.[[descriptor]] = descriptor

  6. descriptor.usage 包含 RENDER_ATTACHMENT

    1. renderExtent = 计算渲染范围([this.width, this.height, this.depthOrArrayLayers], descriptor.baseMipLevel)。

    2. view.[[renderExtent]] = renderExtent

当为 GPUTextureView textureGPUTextureViewDescriptor descriptor 执行 解析 GPUTextureViewDescriptor 默认值 时,执行如下设备时间线步骤:
  1. resolveddescriptor 的副本。

  2. 如果 resolved.format提供

    1. format = 解析 GPUTextureAspect(format, descriptor.aspect)。

    2. 如果 formatnull

      否则:

      • 设置 resolved.format = format

  3. 如果 resolved.mipLevelCount提供: 设置 resolved.mipLevelCount = texture.mipLevelCountresolved.baseMipLevel

  4. 如果 resolved.dimension提供,且 texture.dimension 为:

    "1d"

    设置 resolved.dimension = "1d"

    "2d"

    array layer count 为 1:

    否则:

    "3d"

    设置 resolved.dimension = "3d"

  5. 如果 resolved.arrayLayerCount提供,且 resolved.dimension 为:

    "1d""2d"、或"3d"

    设置 resolved.arrayLayerCount = 1

    "cube"

    设置 resolved.arrayLayerCount = 6

    "2d-array""cube-array"

    设置 resolved.arrayLayerCount = array layer counttexture) − resolved.baseArrayLayer

  6. 如果 resolved.usage0,设置 resolved.usage = texture.usage

  7. 返回 resolved

要确定 GPUTexture texturearray layer count,执行如下步骤:
  1. texture.dimension 为:

    "1d""3d"

    返回 1

    "2d"

    返回 texture.depthOrArrayLayers

6.3. 纹理格式

格式名称指定了分量顺序、每个分量的位数和分量的数据类型。

如果格式带有 -srgb 后缀,则在着色器中读取和写入颜色值时会应用 sRGB 的 gamma 到线性及其反向转换。压缩纹理格式由 特性 提供。命名应遵循此约定,以纹理名称为前缀,例如 etc2-rgba8unorm

texel block(像素块)是像素格式 GPUTextureFormat 下纹理的单一可寻址元素,在区块压缩格式下为单一压缩块。

texel block width(像素块宽度)texel block height(像素块高度)指定了一个像素块的尺寸。

texel block copy footprint指的是某个GPUTextureFormat中某aspect像素块拷贝时所占字节数(如适用)。

注意: 像素块内存开销是指存储一个GPUTextureFormat 像素块所需的字节数。不是所有格式都完全定义此值。该值仅作参考,非规范性内容。

enum GPUTextureFormat {
    // 8-bit formats
    "r8unorm",
    "r8snorm",
    "r8uint",
    "r8sint",

    // 16-bit formats
    "r16unorm",
    "r16snorm",
    "r16uint",
    "r16sint",
    "r16float",
    "rg8unorm",
    "rg8snorm",
    "rg8uint",
    "rg8sint",

    // 32-bit formats
    "r32uint",
    "r32sint",
    "r32float",
    "rg16unorm",
    "rg16snorm",
    "rg16uint",
    "rg16sint",
    "rg16float",
    "rgba8unorm",
    "rgba8unorm-srgb",
    "rgba8snorm",
    "rgba8uint",
    "rgba8sint",
    "bgra8unorm",
    "bgra8unorm-srgb",
    // Packed 32-bit formats
    "rgb9e5ufloat",
    "rgb10a2uint",
    "rgb10a2unorm",
    "rg11b10ufloat",

    // 64-bit formats
    "rg32uint",
    "rg32sint",
    "rg32float",
    "rgba16unorm",
    "rgba16snorm",
    "rgba16uint",
    "rgba16sint",
    "rgba16float",

    // 128-bit formats
    "rgba32uint",
    "rgba32sint",
    "rgba32float",

    // Depth/stencil formats
    "stencil8",
    "depth16unorm",
    "depth24plus",
    "depth24plus-stencil8",
    "depth32float",

    // "depth32float-stencil8" feature
    "depth32float-stencil8",

    // BC compressed formats usable if "texture-compression-bc" is both
    // supported by the device/user agent and enabled in requestDevice.
    "bc1-rgba-unorm",
    "bc1-rgba-unorm-srgb",
    "bc2-rgba-unorm",
    "bc2-rgba-unorm-srgb",
    "bc3-rgba-unorm",
    "bc3-rgba-unorm-srgb",
    "bc4-r-unorm",
    "bc4-r-snorm",
    "bc5-rg-unorm",
    "bc5-rg-snorm",
    "bc6h-rgb-ufloat",
    "bc6h-rgb-float",
    "bc7-rgba-unorm",
    "bc7-rgba-unorm-srgb",

    // ETC2 compressed formats usable if "texture-compression-etc2" is both
    // supported by the device/user agent and enabled in requestDevice.
    "etc2-rgb8unorm",
    "etc2-rgb8unorm-srgb",
    "etc2-rgb8a1unorm",
    "etc2-rgb8a1unorm-srgb",
    "etc2-rgba8unorm",
    "etc2-rgba8unorm-srgb",
    "eac-r11unorm",
    "eac-r11snorm",
    "eac-rg11unorm",
    "eac-rg11snorm",

    // ASTC compressed formats usable if "texture-compression-astc" is both
    // supported by the device/user agent and enabled in requestDevice.
    "astc-4x4-unorm",
    "astc-4x4-unorm-srgb",
    "astc-5x4-unorm",
    "astc-5x4-unorm-srgb",
    "astc-5x5-unorm",
    "astc-5x5-unorm-srgb",
    "astc-6x5-unorm",
    "astc-6x5-unorm-srgb",
    "astc-6x6-unorm",
    "astc-6x6-unorm-srgb",
    "astc-8x5-unorm",
    "astc-8x5-unorm-srgb",
    "astc-8x6-unorm",
    "astc-8x6-unorm-srgb",
    "astc-8x8-unorm",
    "astc-8x8-unorm-srgb",
    "astc-10x5-unorm",
    "astc-10x5-unorm-srgb",
    "astc-10x6-unorm",
    "astc-10x6-unorm-srgb",
    "astc-10x8-unorm",
    "astc-10x8-unorm-srgb",
    "astc-10x10-unorm",
    "astc-10x10-unorm-srgb",
    "astc-12x10-unorm",
    "astc-12x10-unorm-srgb",
    "astc-12x12-unorm",
    "astc-12x12-unorm-srgb",
};

"depth24plus""depth24plus-stencil8" 格式的 depth 分量可以实现为 24 位深度值,也可以实现为 "depth32float" 值。

stencil8 格式可以实现为真正的 "stencil8",也可以实现为 "depth24stencil8"(此时 depth aspect 是隐藏且不可访问的)。

注意:
尽管 depth32float 通道的精度在可表示区间 (0.0 到 1.0) 内严格高于 24 位深度通道,但可表示的值集合并非完全包含关系。

格式为 可渲染(renderable)格式,若其为 颜色可渲染格式,或为深度或模板格式。 若某格式在 § 26.1.1 普通颜色格式 中标记了 RENDER_ATTACHMENT 能力,则为颜色可渲染格式。其它格式不是颜色可渲染格式。所有深度或模板格式均为可渲染格式。

可渲染格式若可与渲染管线混合(blending)使用,则也是 可混合(blendable)格式。详见 § 26.1 纹理格式能力

格式为 可过滤(filterable)格式,若其支持 GPUTextureSampleType"float"(不只是 "unfilterable-float"),即该格式可用于 "filtering" 类型 GPUSampler。详见 § 26.1 纹理格式能力

解析 GPUTextureAspect(format, aspect)

参数:

返回值: GPUTextureFormatnull

  1. aspect 为:

    "all"

    返回 format

    "depth-only"
    "stencil-only"

    format 为 depth-stencil-format: 返回 aspect-specific format,详见 § 26.1.2 深度/模板格式;如该 format 不含此 aspect,返回 null

  2. 返回 null

某些纹理格式的使用需要在 GPUDevice 上启用特性。由于新格式可添加到规范中,所以实现可能不知道这些枚举值。为保证一致性,尝试在未启用相关特性的设备上使用需要特性的格式时会抛出异常,这与实现本身不识别该格式时行为一致。

§ 26.1 纹理格式能力,了解哪些 GPUTextureFormat 需要特性支持。

校验纹理格式所需特性(GPUTextureFormat format, 逻辑device device)
  1. format 需要特性且 device.[[features]]包含该特性:

    1. 抛出 TypeError

6.4. GPUExternalTexture

GPUExternalTexture 是一个可采样的二维纹理,用于封装外部视频帧。它是不可变快照;其内容不会随时间变化,无论是来自 WebGPU 内部(仅可采样)还是外部(如视频帧推进)。

GPUExternalTexture 可通过 externalTexture 绑定组布局成员作为绑定项绑定到绑定组。注意该成员会占用多个绑定槽,详见相关定义。

注意:
GPUExternalTexture 可以在不复制导入源的情况下实现,但这取决于实现定义因素。底层表示的所有权可能是独占的,也可能与其他所有者(如视频解码器)共享,但这对应用透明。

外部纹理的底层表示不可见(除精确采样行为外),但通常包括:

实现内部使用的配置在不同时间、系统、用户代理、媒体源、甚至同一个视频资源的帧之间可能不一致。为适应各种可能的实现,每个外部纹理绑定都会保守地占用:

[Exposed=(Window, Worker), SecureContext]
interface GPUExternalTexture {
};
GPUExternalTexture includes GPUObjectBase;

GPUExternalTexture 拥有如下不可变属性

[[descriptor]],类型为GPUExternalTextureDescriptor,只读

创建该纹理时所用的 descriptor。

GPUExternalTexture 拥有如下不可变属性

[[expired]],类型为 boolean,初始值为 false

表示对象是否已过期(不可再用)。

注意:[[destroyed]] 不同,该值可从 true 恢复到 false

6.4.1. 导入外部纹理

外部纹理可通过 importExternalTexture() 从外部视频对象创建。

HTMLVideoElement 创建的外部纹理会在导入后自动过期(即销毁),而不像其他资源那样需要手动或等垃圾回收。外部纹理过期时,其 [[expired]] 属性变为 true

VideoFrame 创建的外部纹理会在且仅在源 VideoFrame关闭时过期(无论是通过 close() 还是其他方式)。

注意:decode() 所述,开发者在输出 VideoFrame 上调用 close(),以避免解码器阻塞。如果导入的 VideoFrame 被丢弃但未关闭,导入的 GPUExternalTexture 会保持其存活,直到它也被丢弃。只有两者都被丢弃后,VideoFrame 才能被垃圾回收。由于垃圾回收不可预测,这仍然可能导致解码器阻塞。

一旦 GPUExternalTexture 过期,必须再次调用 importExternalTexture()。不过,用户代理可能会取消过期,返回同一个 GPUExternalTexture,而不是新建一个。通常只有应用调度与视频帧率同步(如用 requestVideoFrameCallback())时才会避免返回同一个对象。如返回同一对象,二者相等,且引用旧对象的 GPUBindGroupGPURenderBundle 等依然有效。

dictionary GPUExternalTextureDescriptor
 : GPUObjectDescriptorBase {
required (HTMLVideoElement or VideoFrame) source;
PredefinedColorSpace colorSpace = "srgb";
};

GPUExternalTextureDescriptor 字典含如下成员:

source类型为 (HTMLVideoElement or VideoFrame)

要导入为外部纹理的视频源。源尺寸详见外部源尺寸表。

colorSpace类型为 PredefinedColorSpace,默认 "srgb"

读取时,source 的图像内容会被转换到的色彩空间。

importExternalTexture(descriptor)

创建一个包裹所提供图像源的 GPUExternalTexture

调用对象: GPUDevice this

参数:

GPUDevice.importExternalTexture(descriptor) 方法参数
参数 类型 可为 null 可选 描述
descriptor GPUExternalTextureDescriptor 提供外部图像源对象及相关创建选项。

返回: GPUExternalTexture

内容时间线步骤:

  1. source = descriptor.source

  2. source 的当前图像内容与最近一次用同一 descriptor(忽略 label)调用 importExternalTexture() 相同,且用户代理选择复用:

    1. previousResult 为上次返回的 GPUExternalTexture

    2. previousResult.[[expired]]false,恢复底层资源所有权。

    3. result = previousResult

    注意:这样应用可检测重复导入,避免重新创建依赖对象(如 GPUBindGroup)。实现仍需支持同一帧被多个 GPUExternalTexture 包裹,因为导入元数据如 colorSpace 可变。

    否则:

    1. source 不为 origin-clean,抛出 SecurityError 并返回。

    2. usability = ? 检查图像参数可用性(source)。

    3. usabilitygood

      1. 生成校验错误

      2. 返回无效 GPUExternalTexture

    4. data 为将 source 当前图像内容转换为 descriptor.colorSpace(未预乘 alpha)所得。

      可能导致超出 [0,1] 范围的值。如需裁剪,可采样后再做。

      注意:虽描述为拷贝,也可实现为指向只读底层数据和元数据的引用。

    5. result 为包裹 data 的新 GPUExternalTexture

  3. sourceHTMLVideoElement排队自动过期任务,内容包括:

    1. result.[[expired]]true,释放底层资源所有权。

    注意:应在采样同一任务中导入 HTMLVideoElement,建议结合 requestVideoFrameCallbackrequestAnimationFrame() 使用,否则纹理可能在应用用完前被销毁。

  4. sourceVideoFrame,则当 source 关闭时,执行:

    1. result.[[expired]]true

  5. result.label = descriptor.label

  6. 返回 result

使用 video 元素外部纹理以页面动画帧率渲染:
const videoElement = document.createElement('video');
// ... 设置 videoElement,等待其就绪 ...

function frame() {
    requestAnimationFrame(frame);

    // 每帧都重新导入视频,因为导入的纹理很可能已过期。
    // 浏览器可能缓存并复用旧帧,如复用会返回同一个 GPUExternalTexture。
    // 这时旧的 bind group 依然有效。
    const externalTexture = gpuDevice.importExternalTexture({
        source: videoElement
    });

    // ... 使用 externalTexture 渲染 ...
}
requestAnimationFrame(frame);
若有 requestVideoFrameCallback,则以视频帧率渲染 video 元素外部纹理:
const videoElement = document.createElement('video');
// ... 设置 videoElement ...

function frame() {
    videoElement.requestVideoFrameCallback(frame);

    // 帧已推进,需重新导入
    const externalTexture = gpuDevice.importExternalTexture({
        source: videoElement
    });

    // ... 使用 externalTexture 渲染 ...
}
videoElement.requestVideoFrameCallback(frame);

6.5. 采样外部纹理绑定

externalTexture 绑定点允许绑定 GPUExternalTexture 对象(来自视频等动态图像源)。同时也支持 GPUTextureGPUTextureView

注意:GPUTextureGPUTextureView 被绑定到 externalTexture 绑定点时,其行为等同于单一 RGBA plane、无裁剪、无旋转、无颜色转换的 GPUExternalTexture

外部纹理在 WGSL 中以 texture_external 表示,可通过 textureLoadtextureSampleBaseClampToEdge 读取。

textureSampleBaseClampToEdge 所用的 sampler 用于采样底层纹理。

绑定资源类型GPUExternalTexture 时,采样结果在 colorSpace 设置的色彩空间中。对于具体外部纹理,采样器(及其过滤操作)是在底层值转换到指定色彩空间之前还是之后应用,是实现相关的。

注意: 若内部表示为 RGBA 平面,则采样行为与常规 2D 纹理一致。若有多个底层平面(如 Y+UV),采样器会分别对每个底层纹理采样,再进行 YUV 到指定色彩空间的转换。

7. 采样器(Samplers)

7.1. GPUSampler

GPUSampler 用于编码可在着色器中解释纹理资源数据的变换与过滤信息。

GPUSampler 通过 createSampler() 创建。

[Exposed=(Window, Worker), SecureContext]
interface GPUSampler {
};
GPUSampler includes GPUObjectBase;

GPUSampler 拥有如下不可变属性

[[descriptor]],类型为 GPUSamplerDescriptor,只读

创建 GPUSampler 时使用的 GPUSamplerDescriptor

[[isComparison]],类型为 boolean,只读

GPUSampler 是否为比较采样器。

[[isFiltering]],类型为 boolean,只读

GPUSampler 是否对纹理的多个采样结果加权(即支持过滤)。

7.1.1. GPUSamplerDescriptor

GPUSamplerDescriptor 指定了创建 GPUSampler 时应使用的选项。

dictionary GPUSamplerDescriptor
         : GPUObjectDescriptorBase {
    GPUAddressMode addressModeU = "clamp-to-edge";
    GPUAddressMode addressModeV = "clamp-to-edge";
    GPUAddressMode addressModeW = "clamp-to-edge";
    GPUFilterMode magFilter = "nearest";
    GPUFilterMode minFilter = "nearest";
    GPUMipmapFilterMode mipmapFilter = "nearest";
    float lodMinClamp = 0;
    float lodMaxClamp = 32;
    GPUCompareFunction compare;
    [Clamp] unsigned short maxAnisotropy = 1;
};
addressModeU, 类型为 GPUAddressMode,默认值为 "clamp-to-edge"
addressModeV, 类型为 GPUAddressMode,默认值为 "clamp-to-edge"
addressModeW, 类型为 GPUAddressMode,默认值为 "clamp-to-edge"

分别指定纹理在宽度、高度和深度坐标方向上的 地址模式

magFilter, 类型为 GPUFilterMode,默认值为 "nearest"

指定当采样区域小于等于一个纹素时的采样行为。

minFilter, 类型为 GPUFilterMode,默认值为 "nearest"

指定当采样区域大于一个纹素时的采样行为。

mipmapFilter, 类型为 GPUMipmapFilterMode,默认值为 "nearest"

指定在 mipmap 层级之间采样时的行为。

lodMinClamp, 类型为 float,默认值为 0
lodMaxClamp, 类型为 float,默认值为 32

分别指定采样纹理时内部使用的最小和最大细节层级(LOD)

compare, 类型为 GPUCompareFunction

如果提供,则采样器将被设为比较采样器,并使用指定的 GPUCompareFunction

注意:比较采样器可以使用过滤,但采样结果依赖于实现,可能不同于普通过滤规则。

maxAnisotropy, 类型为 unsigned short,默认值为 1

指定采样器使用的最大各向异性值上限。当 maxAnisotropy 大于 1 且实现支持时,启用各向异性过滤。

各向异性过滤可提高在斜视角下采样纹理的图像质量。更高的 maxAnisotropy 值表示过滤时支持的最大各向异性比。

注意:
大多数实现支持 maxAnisotropy 取值范围为 1 到 16(含)。实际使用值将被限制在平台支持的最大值。

具体的过滤行为依赖于实现。

细节层级(Level of detail,LOD) 描述了采样纹理时选用的 mip 层级。可以通过 textureSampleLevel 等着色器方法显式指定,也可以由纹理坐标导数隐式决定。

注意:参考 Scale Factor Operation, LOD Operation and Image Level SelectionVulkan 1.3 规范)了解隐式 LOD 如何计算。

GPUAddressMode 描述了采样纹理时纹素超出纹理边界时的采样器行为。

enum GPUAddressMode {
    "clamp-to-edge",
    "repeat",
    "mirror-repeat",
};
"clamp-to-edge"

纹理坐标被限制在 0.0 到 1.0 区间内。

"repeat"

纹理坐标将在纹理另一侧环绕。

"mirror-repeat"

纹理坐标将在纹理另一侧环绕,但当坐标的整数部分为奇数时,纹理会翻转。

GPUFilterModeGPUMipmapFilterMode 描述采样区域不正好覆盖一个纹素时采样器的行为。

注意:参考 Texel FilteringVulkan 1.3 规范)了解采样器如何确定在不同过滤模式下采样哪些纹素。

enum GPUFilterMode {
    "nearest",
    "linear",
};

enum GPUMipmapFilterMode {
    "nearest",
    "linear",
};
"nearest"

返回最接近纹理坐标的纹素值。

"linear"

每个维度选择两个纹素,并返回它们值的线性插值。

GPUCompareFunction 指定比较采样器的行为。如果在着色器中使用比较采样器,depth_ref 会与获取到的纹素值进行比较,生成比较结果(通过则为 1.0f,未通过为 0.0f)。

比较后,如果启用纹理过滤,则会进行过滤步骤,使多个比较结果混合,结果在 [0, 1] 区间。过滤应当如常处理,但可能以更低精度或不做混合。

enum GPUCompareFunction {
    "never",
    "less",
    "equal",
    "less-equal",
    "greater",
    "not-equal",
    "greater-equal",
    "always",
};
"never"

比较测试始终不通过。

"less"

当提供值小于采样值时,比较测试通过。

"equal"

当提供值等于采样值时,比较测试通过。

"less-equal"

当提供值小于等于采样值时,比较测试通过。

"greater"

当提供值大于采样值时,比较测试通过。

"not-equal"

当提供值不等于采样值时,比较测试通过。

"greater-equal"

当提供值大于等于采样值时,比较测试通过。

"always"

比较测试始终通过。

7.1.2. 采样器创建

createSampler(descriptor)

创建一个 GPUSampler

调用对象: GPUDevice this。

参数:

参数表:GPUDevice.createSampler(descriptor) 方法。
参数名 类型 可为 null 可选 描述
descriptor GPUSamplerDescriptor 要创建的 GPUSampler 的描述信息。

返回: GPUSampler

内容时间线步骤:

  1. s = ! 创建新的 WebGPU 对象(this, GPUSampler, descriptor)。

  2. 设备时间线 上对 this 执行 初始化步骤

  3. 返回 s

设备时间线 初始化步骤
  1. 如果下列任一条件不满足,则生成校验错误使 s 无效 并返回。

  2. 设置 s.[[descriptor]]descriptor

  3. 如果 s.[[descriptor]]compare 属性为 null 或未定义,则设置 s.[[isComparison]]false。否则设置为 true

  4. 如果 minFiltermagFiltermipmapFilter 都不是 "linear",则设置 s.[[isFiltering]]false;否则设为 true

创建一个支持三线性过滤并重复纹理坐标的 GPUSampler
const sampler = gpuDevice.createSampler({
    addressModeU: 'repeat',
    addressModeV: 'repeat',
    magFilter: 'linear',
    minFilter: 'linear',
    mipmapFilter: 'linear',
});

8. 资源绑定

8.1. GPUBindGroupLayout

GPUBindGroupLayout 定义了绑定在 GPUBindGroup 中的一组资源与着色器阶段可访问性的接口关系。

[Exposed=(Window, Worker), SecureContext]
interface GPUBindGroupLayout {
};
GPUBindGroupLayout includes GPUObjectBase;

GPUBindGroupLayout 具有以下不可变属性

[[descriptor]],类型为 GPUBindGroupLayoutDescriptor, 只读

8.1.1. 绑定组布局创建

GPUBindGroupLayout 通过 GPUDevice.createBindGroupLayout() 创建。

dictionary GPUBindGroupLayoutDescriptor
         : GPUObjectDescriptorBase {
    required sequence<GPUBindGroupLayoutEntry> entries;
};

GPUBindGroupLayoutDescriptor 字典包含以下成员:

entries类型为 sequence<GPUBindGroupLayoutEntry>

用于描述绑定组内着色器资源绑定的条目列表。

GPUBindGroupLayoutEntry 描述了要包含在 GPUBindGroupLayout 中的单个着色器资源绑定。

dictionary GPUBindGroupLayoutEntry {
    required GPUIndex32 binding;
    required GPUShaderStageFlags visibility;

    GPUBufferBindingLayout buffer;
    GPUSamplerBindingLayout sampler;
    GPUTextureBindingLayout texture;
    GPUStorageTextureBindingLayout storageTexture;
    GPUExternalTextureBindingLayout externalTexture;
};

GPUBindGroupLayoutEntry 字典包含以下成员:

binding类型为 GPUIndex32

绑定组布局内资源绑定的唯一标识符,对应于 GPUBindGroupEntry.binding 以及 GPUShaderModule 中的 @binding 属性。

visibility类型为 GPUShaderStageFlags

GPUShaderStage 各成员组成的位集合。每个被设置的位表示该资源在对应着色器阶段可访问。

buffer类型为 GPUBufferBindingLayout
sampler类型为 GPUSamplerBindingLayout
texture类型为 GPUTextureBindingLayout
storageTexture类型为 GPUStorageTextureBindingLayout
externalTexture类型为 GPUExternalTextureBindingLayout

这些成员中必须且只能设置一个,表示绑定类型。该成员的内容指定该类型的选项。

createBindGroup() 中对应的资源必须为该绑定类型的binding resource type

typedef [EnforceRange] unsigned long GPUShaderStageFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUShaderStage {
    const GPUFlagsConstant VERTEX   = 0x1;
    const GPUFlagsConstant FRAGMENT = 0x2;
    const GPUFlagsConstant COMPUTE  = 0x4;
};

GPUShaderStage 包含以下标志,指示此 GPUBindGroupEntry 对应的 GPUBindGroupLayoutEntry 可见于哪些着色器阶段:

VERTEX

绑定组条目在顶点着色器中可访问。

FRAGMENT

绑定组条目在片元着色器中可访问。

COMPUTE

绑定组条目在计算着色器中可访问。

GPUBindGroupLayoutEntrybinding member 由其定义的成员决定: buffersamplertexturestorageTexture, 或 externalTexture。 每个 GPUBindGroupLayoutEntry 只能定义一个成员。 每个成员有其对应的 GPUBindingResource 类型,每个绑定类型对应一个内部用法,见下表:

绑定成员 资源类型 绑定类型
绑定用法
buffer GPUBufferBinding
(或 GPUBuffer 作为简写)
"uniform" constant
"storage" storage
"read-only-storage" storage-read
sampler GPUSampler "filtering" constant
"non-filtering"
"comparison"
texture GPUTextureView
(或 GPUTexture 作为简写)
"float" constant
"unfilterable-float"
"depth"
"sint"
"uint"
storageTexture GPUTextureView
(或 GPUTexture 作为简写)
"write-only" storage
"read-write"
"read-only" storage-read
externalTexture GPUExternalTexture
GPUTextureView
(或 GPUTexture 作为简写)
constant
列表 GPUBindGroupLayoutEntryentries 超出绑定槽限制(exceeds the binding slot limits),指当用于某一限制的槽数超过 支持的限制 limits 中的支持值时。 每个 entry 可能会占用多个限制的多个槽。

设备时间线步骤:

  1. 对于 entries 中的每个 entry,如果:

    entry.buffer?.type"uniform"entry.buffer?.hasDynamicOffsettrue

    视为使用了 1 个 maxDynamicUniformBuffersPerPipelineLayout 槽。

    entry.buffer?.type"storage"entry.buffer?.hasDynamicOffsettrue

    视为使用了 1 个 maxDynamicStorageBuffersPerPipelineLayout 槽。

  2. 对于每个着色器阶段 stage,即 « VERTEX, FRAGMENT, COMPUTE »:

    1. 对于每个 entriesentry,若其 entry.visibility 包含 stage,则:

      entry.buffer?.type"uniform"

      视为使用了 1 个 maxUniformBuffersPerShaderStage 槽。

      entry.buffer?.type"storage""read-only-storage"

      视为使用了 1 个 maxStorageBuffersPerShaderStage 槽。

      entry.sampler 存在(provided

      视为使用了 1 个 maxSamplersPerShaderStage 槽。

      entry.texture 存在

      视为使用了 1 个 maxSampledTexturesPerShaderStage 槽。

      entry.storageTexture 存在

      视为使用了 1 个 maxStorageTexturesPerShaderStage 槽。

      entry.externalTexture 存在

      视为使用 4 个 maxSampledTexturesPerShaderStage 槽, 1 个 maxSamplersPerShaderStage 槽,以及 1 个 maxUniformBuffersPerShaderStage 槽。

      注意:详见 GPUExternalTexture 相关说明。

enum GPUBufferBindingType {
    "uniform",
    "storage",
    "read-only-storage",
};

dictionary GPUBufferBindingLayout {
    GPUBufferBindingType type = "uniform";
    boolean hasDynamicOffset = false;
    GPUSize64 minBindingSize = 0;
};

GPUBufferBindingLayout 字典包含以下成员:

type类型为 GPUBufferBindingType,默认值为 "uniform"

指示绑定到该绑定点的缓冲区所需的类型。

hasDynamicOffset类型为 boolean,默认值为 false

指示该绑定是否需要动态偏移。

minBindingSize类型为 GPUSize64,默认值为 0

指示与该绑定点使用的缓冲区绑定的最小 size

createBindGroup() 中总会对绑定进行该尺寸的校验。

若该值不为 0,则管线创建时还会额外校验 该值是否大于等于变量的最小缓冲区绑定大小

若该值 0,则管线创建时忽略,转而由 draw/dispatch 指令 校验绑定组中每个绑定是否满足变量的最小缓冲区绑定大小

注意: 理论上,类似的运行时校验也可用于其它用于早期校验的绑定相关字段,如 sampleTypeformat,但目前仅在管线创建时校验。 不过这样的运行时校验可能开销大或不必要复杂,因此仅对 minBindingSize 启用,因为它对易用性影响最大。

enum GPUSamplerBindingType {
    "filtering",
    "non-filtering",
    "comparison",
};

dictionary GPUSamplerBindingLayout {
    GPUSamplerBindingType type = "filtering";
};

GPUSamplerBindingLayout 字典包含以下成员:

type类型为 GPUSamplerBindingType,默认值为 "filtering"

指示绑定到此绑定点所需采样器的类型。

enum GPUTextureSampleType {
    "float",
    "unfilterable-float",
    "depth",
    "sint",
    "uint",
};

dictionary GPUTextureBindingLayout {
    GPUTextureSampleType sampleType = "float";
    GPUTextureViewDimension viewDimension = "2d";
    boolean multisampled = false;
};

GPUTextureBindingLayout 字典包含以下成员:

sampleType类型为 GPUTextureSampleType,默认值为 "float"

指示绑定到该绑定点的纹理视图所需的类型。

viewDimension类型为 GPUTextureViewDimension,默认值为 "2d"

指示绑定到该绑定点的纹理视图所需的 dimension

multisampled类型为 boolean,默认值为 false

指示绑定到该绑定点的纹理视图是否必须为多重采样。

enum GPUStorageTextureAccess {
    "write-only",
    "read-only",
    "read-write",
};

dictionary GPUStorageTextureBindingLayout {
    GPUStorageTextureAccess access = "write-only";
    required GPUTextureFormat format;
    GPUTextureViewDimension viewDimension = "2d";
};

GPUStorageTextureBindingLayout 字典包含以下成员:

access类型为 GPUStorageTextureAccess,默认值为 "write-only"

此绑定的访问模式,指示可读性和可写性。

format类型为 GPUTextureFormat

绑定到此绑定点的纹理视图所需的 format

viewDimension类型为 GPUTextureViewDimension,默认值为 "2d"

绑定到此绑定点的纹理视图所需的 dimension

dictionary GPUExternalTextureBindingLayout {
};

GPUBindGroupLayout 对象拥有以下设备时间线属性

[[entryMap]],类型为 有序映射<GPUSize32, GPUBindGroupLayoutEntry>, 只读

指向该 GPUBindGroupLayout 所描述的 GPUBindGroupLayoutEntry 的绑定索引映射表。

[[dynamicOffsetCount]],类型为 GPUSize32, 只读

GPUBindGroupLayout 中具有动态偏移的缓冲区绑定数量。

[[exclusivePipeline]],类型为 GPUPipelineBase? ,只读

如果是作为默认管线布局一部分创建的,则为创建该 GPUBindGroupLayout 的管线。若不为 null,则用该 GPUBindGroupLayout 创建的 GPUBindGroup 只能与指定的 GPUPipelineBase 一起使用。

createBindGroupLayout(descriptor)

创建一个 GPUBindGroupLayout

调用对象: GPUDevice this

参数:

GPUDevice.createBindGroupLayout(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPUBindGroupLayoutDescriptor 要创建的 GPUBindGroupLayout 的描述信息。

返回: GPUBindGroupLayout

内容时间线步骤:

  1. 对于 descriptor.entries 中的每个 GPUBindGroupLayoutEntry entry

    1. 如果 entry.storageTexture提供

      1. ? 校验纹理格式所需特性,针对 entry.storageTexture.formatthis.[[device]]

  2. layout = ! 创建 WebGPU 对象(this, GPUBindGroupLayout, descriptor)。

  3. this设备时间线上执行 初始化步骤

  4. 返回 layout

设备时间线 初始化步骤
  1. 若下列任意条件不满足,则生成校验错误使 layout 无效并返回。

  2. 设置 layout.[[descriptor]]descriptor

  3. 设置 layout.[[dynamicOffsetCount]]descriptorbuffer 被提供,且 buffer.hasDynamicOffsettrue 的条目数量。

  4. 设置 layout.[[exclusivePipeline]]null

  5. 对于 descriptor.entries 中的每个 GPUBindGroupLayoutEntry entry

    1. entry.binding 作为 key,将 entry 插入 layout.[[entryMap]]

8.1.2. 兼容性

两个 GPUBindGroupLayout 对象 ab 被认为是 组等价(group-equivalent) 当且仅当满足以下所有条件:

如果绑定组布局是组等价的,则它们可以在所有场合下互换使用。

8.2. GPUBindGroup

GPUBindGroup 定义了一组要共同绑定的资源,以及这些资源在着色器阶段的使用方式。

[Exposed=(Window, Worker), SecureContext]
interface GPUBindGroup {
};
GPUBindGroup includes GPUObjectBase;

GPUBindGroup 具有以下设备时间线属性

[[layout]],类型为 GPUBindGroupLayout, 只读

与该 GPUBindGroup 相关联的 GPUBindGroupLayout

[[entries]],类型为 sequence<GPUBindGroupEntry>, 只读

GPUBindGroup 所描述的所有 GPUBindGroupEntry 集合。

[[usedResources]],类型为 usage scope,只读

该绑定组使用的缓冲区和纹理子资源集合, 并关联有内部用法标志列表。

GPUBindGroup bindGroup已绑定缓冲区范围(bound buffer ranges), 给定 list<GPUBufferDynamicOffset> dynamicOffsets,按如下方式计算:
  1. result 为新的 集合<(GPUBindGroupLayoutEntry, GPUBufferBinding)>。

  2. dynamicOffsetIndex 为 0。

  3. bindGroup.[[entries]] 中每个 GPUBindGroupEntry bindGroupEntry(按 bindGroupEntry.binding 排序):

    1. bindGroupLayoutEntry = bindGroup.[[layout]].[[entryMap]][bindGroupEntry.binding]。

    2. bindGroupLayoutEntry.buffer被提供则 continue

    3. bound = get as buffer binding(bindGroupEntry.resource)。

    4. bindGroupLayoutEntry.buffer.hasDynamicOffset

      1. bound.offset 增加 dynamicOffsets[dynamicOffsetIndex]。

      2. dynamicOffsetIndex 增加 1。

    5. (bindGroupLayoutEntry, bound) 添加到 result

  4. 返回 result

8.2.1. 绑定组创建

GPUBindGroup 通过 GPUDevice.createBindGroup() 创建。

dictionary GPUBindGroupDescriptor
         : GPUObjectDescriptorBase {
    required GPUBindGroupLayout layout;
    required sequence<GPUBindGroupEntry> entries;
};

GPUBindGroupDescriptor 字典包含以下成员:

layout类型为 GPUBindGroupLayout

该绑定组条目所遵循的 GPUBindGroupLayout

entries类型为 sequence<GPUBindGroupEntry>

描述要为 layout 所描述的每个绑定暴露给着色器的资源条目的列表。

typedef (GPUSampler or
         GPUTexture or
         GPUTextureView or
         GPUBuffer or
         GPUBufferBinding or
         GPUExternalTexture) GPUBindingResource;

dictionary GPUBindGroupEntry {
    required GPUIndex32 binding;
    required GPUBindingResource resource;
};

GPUBindGroupEntry 描述要绑定到 GPUBindGroup 的单个资源,包含以下成员:

binding类型为 GPUIndex32

该绑定组内资源绑定的唯一标识符,对应于 GPUBindGroupLayoutEntry.binding 以及 GPUShaderModule 中的 @binding 属性。

resource类型为 GPUBindingResource

要绑定的资源,可以是 GPUSamplerGPUTextureGPUTextureViewGPUBufferGPUBufferBinding, 或 GPUExternalTexture

GPUBindGroupEntry 具有以下设备时间线属性

[[prevalidatedSize]],类型为 boolean

该绑定条目在创建时其缓冲区大小是否已被校验。

dictionary GPUBufferBinding {
    required GPUBuffer buffer;
    GPUSize64 offset = 0;
    GPUSize64 size;
};

GPUBufferBinding 描述了要作为资源绑定的缓冲区及可选范围,包含以下成员:

buffer类型为 GPUBuffer

要绑定的 GPUBuffer

offset类型为 GPUSize64,默认值为 0

以字节为单位,buffer 起始到绑定暴露给着色器的范围起点的偏移量。

size类型为 GPUSize64

缓冲区绑定的大小(字节)。 若未提供,则指定从 offset 起至 buffer 末尾的区间。

createBindGroup(descriptor)

创建一个 GPUBindGroup

调用对象: GPUDevice this

参数:

GPUDevice.createBindGroup(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPUBindGroupDescriptor 要创建的 GPUBindGroup 的描述信息。

返回: GPUBindGroup

内容时间线步骤:

  1. bindGroup = ! 创建新的 WebGPU 对象(this, GPUBindGroup, descriptor)。

  2. this设备时间线上执行 初始化步骤

  3. 返回 bindGroup

设备时间线 初始化步骤
  1. limits = this.[[device]].[[limits]]

  2. 若下列任一条件不满足,则生成校验错误使 bindGroup 无效并返回。

    • descriptor.layout 必须可与 this 配合使用。

    • descriptor.entries 的数量与 descriptor.layout 的条目数量完全相等。

    对于 descriptor.entries 中的每个 GPUBindGroupEntry bindingDescriptor

  3. bindGroup.[[layout]] = descriptor.layout

  4. bindGroup.[[entries]] = descriptor.entries

  5. bindGroup.[[usedResources]] = {}。

  6. descriptor.entries 中的每个 GPUBindGroupEntry bindingDescriptor

    1. internalUsagelayoutBinding绑定用法

    2. resource 所见的每个子资源,都以 internalUsage 形式添加到 [[usedResources]]

    3. layoutBindingbinding memberbufferlayoutBinding.buffer.minBindingSize0,则 bindingDescriptor.[[prevalidatedSize]] 设为 false,否则设为 true

作为纹理视图获取(get as texture view)(resource)

参数:

返回: GPUTextureView

  1. 断言 resource 必须为 GPUTextureGPUTextureView

  2. 如果 resource 为:

    GPUTexture
    1. 返回 resource.createView()

    GPUTextureView
    1. 返回 resource

作为缓冲区绑定获取(get as buffer binding)(resource)

参数:

返回: GPUBufferBinding

  1. 断言 resource 必须为 GPUBufferGPUBufferBinding

  2. 如果 resource 为:

    GPUBuffer
    1. bufferBinding 为新的 GPUBufferBinding

    2. 设置 bufferBinding.bufferresource

    3. 返回 bufferBinding

    GPUBufferBinding
    1. 返回 resource

有效缓冲区绑定大小(effective buffer binding size)(binding)

参数:

返回: GPUSize64

  1. 如果 binding.size提供

    1. 返回 max(0, binding.buffer.size - binding.offset);

  2. 返回 binding.size

两个 GPUBufferBinding 对象 ab 被认为是 缓冲区绑定别名(buffer-binding-aliasing),当且仅当满足以下全部条件:

注意:进行该计算时,任何动态偏移已应用到范围上。

8.3. GPUPipelineLayout

GPUPipelineLayout 定义了在命令编码期间通过 setBindGroup() 设置的所有 GPUBindGroup 对象的资源,与通过 GPURenderCommandsMixin.setPipelineGPUComputePassEncoder.setPipeline 设置的管线着色器之间的映射关系。

资源的完整绑定地址可以定义为以下三元组:

  1. 资源可见的着色器阶段掩码

  2. 绑定组索引(bind group index)

  3. 绑定号(binding number)

该地址的各分量也可视为管线的绑定空间。一个 GPUBindGroup (与相应的 GPUBindGroupLayout 一起) 覆盖了某个固定绑定组索引的空间。其包含的绑定需要是该绑定组索引上着色器所用资源的超集。

[Exposed=(Window, Worker), SecureContext]
interface GPUPipelineLayout {
};
GPUPipelineLayout includes GPUObjectBase;

GPUPipelineLayout 具有以下设备时间线属性

[[bindGroupLayouts]],类型为 list<GPUBindGroupLayout>, 只读

在创建时通过 GPUPipelineLayoutDescriptor.bindGroupLayouts 提供的 GPUBindGroupLayout 对象列表。

注意:为多个 GPURenderPipelineGPUComputePipeline 管线复用同一个 GPUPipelineLayout 可确保在切换这些管线时,用户代理无需在内部重新绑定资源。

GPUComputePipeline 对象 X 是用 GPUPipelineLayout.bindGroupLayouts A、B、C 创建的。GPUComputePipeline 对象 Y 是用 GPUPipelineLayout.bindGroupLayouts A、D、C 创建的。假设命令编码顺序有两次 dispatch:
  1. setBindGroup(0, ...)

  2. setBindGroup(1, ...)

  3. setBindGroup(2, ...)

  4. setPipeline(X)

  5. dispatchWorkgroups()

  6. setBindGroup(1, ...)

  7. setPipeline(Y)

  8. dispatchWorkgroups()

在该场景中,即使 GPUPipelineLayout.bindGroupLayouts 索引 2 处的 GPUBindGroupLayout 或槽 2 处的 GPUBindGroup 都未变化,用户代理仍需为第二次 dispatch 重新绑定组槽 2。

注意: GPUPipelineLayout 的建议用法是将最常用且最少变动的绑定组放在布局“底部”,即绑定组槽号较低的位置(如 0 或 1)。绑定组在绘制调用间变动越频繁,其索引应越高。该通用建议有助于用户代理最小化绘制调用间的状态切换,从而降低 CPU 开销。

8.3.1. 管线布局创建

GPUPipelineLayout 通过 GPUDevice.createPipelineLayout() 创建。

dictionary GPUPipelineLayoutDescriptor
         : GPUObjectDescriptorBase {
    required sequence<GPUBindGroupLayout?> bindGroupLayouts;
};

GPUPipelineLayoutDescriptor 字典定义了管线所用的所有 GPUBindGroupLayout,包含以下成员:

bindGroupLayouts类型为 sequence<GPUBindGroupLayout?>

管线将使用的可选 GPUBindGroupLayout 列表。每个元素对应 GPUShaderModule 中的 @group 属性,第 N 个元素对应 @group(N)

createPipelineLayout(descriptor)

创建一个 GPUPipelineLayout

调用对象: GPUDevice this

参数:

GPUDevice.createPipelineLayout(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPUPipelineLayoutDescriptor 要创建的 GPUPipelineLayout 的描述信息。

返回: GPUPipelineLayout

内容时间线步骤:

  1. pl = ! 创建新的 WebGPU 对象(this, GPUPipelineLayout, descriptor)。

  2. this设备时间线上执行 初始化步骤

  3. 返回 pl

设备时间线 初始化步骤
  1. limits = this.[[device]].[[limits]]

  2. bindGroupLayouts 为一个包含 nullGPUBindGroupLayout 列表, 大小等于 limits.maxBindGroups

  3. descriptor.bindGroupLayouts 中每个索引 ibindGroupLayout

    1. 如果 bindGroupLayoutnullbindGroupLayout.[[descriptor]].entries 非空:

      1. 设置 bindGroupLayouts[i] 为 bindGroupLayout

  4. allEntries 为所有非 null bglbgl.[[descriptor]].entries 拼接后的结果。

  5. 若下列任一条件不满足,则生成校验错误使 pl 无效并返回。

  6. 设置 pl.[[bindGroupLayouts]]bindGroupLayouts

注意: 若两个 GPUPipelineLayout 的内部 [[bindGroupLayouts]] 序列中包含的每个 GPUBindGroupLayout 对象两两 组等价,则它们对任意用途都是等价的。

8.4. 示例

创建一个 GPUBindGroupLayout ,描述具有 uniform buffer、纹理和采样器的绑定。 然后使用该 GPUBindGroupLayout 创建 GPUBindGroupGPUPipelineLayout
const bindGroupLayout = gpuDevice.createBindGroupLayout({
    entries: [{
        binding: 0,
        visibility: GPUShaderStage.VERTEX | GPUShaderStage.FRAGMENT,
        buffer: {}
    }, {
        binding: 1,
        visibility: GPUShaderStage.FRAGMENT,
        texture: {}
    }, {
        binding: 2,
        visibility: GPUShaderStage.FRAGMENT,
        sampler: {}
    }]
});

const bindGroup = gpuDevice.createBindGroup({
    layout: bindGroupLayout,
    entries: [{
        binding: 0,
        resource: { buffer: buffer },
    }, {
        binding: 1,
        resource: texture
    }, {
        binding: 2,
        resource: sampler
    }]
});

const pipelineLayout = gpuDevice.createPipelineLayout({
    bindGroupLayouts: [bindGroupLayout]
});

9. 着色器模块

9.1. GPUShaderModule

[Exposed=(Window, Worker), SecureContext]
interface GPUShaderModule {
    Promise<GPUCompilationInfo> getCompilationInfo();
};
GPUShaderModule includes GPUObjectBase;

GPUShaderModule 是对内部着色器模块对象的引用。

9.1.1. 着色器模块创建

dictionary GPUShaderModuleDescriptor
         : GPUObjectDescriptorBase {
    required USVString code;
    sequence<GPUShaderModuleCompilationHint> compilationHints = [];
};
code类型为 USVString

该着色器模块的 WGSL 源代码。

compilationHints类型为 sequence<GPUShaderModuleCompilationHint>,默认值为 []

GPUShaderModuleCompilationHint 的列表。

应用程序提供的任何 hint 应当 包含有关将来会从该入口创建管线的某个 entry point 的信息。

实现 应当 使用 GPUShaderModuleCompilationHint 中的任何信息,尽可能在 createShaderModule() 内完成编译。

除了类型检查外,这些 hint 不会以任何方式被校验。

注意:
compilationHints 中提供信息不会产生除性能以外的可观察效果。为从未创建的管线提供 hint 可能对性能有害。

由于单个着色器模块可以包含多个入口点,并且可以从一个着色器模块创建多个管线,因此实现只在 createShaderModule() 时尽可能多地编译会更高效,而不是在多次 createComputePipeline()createRenderPipeline() 时多次编译。

hint 只应用于其明确命名的入口点。与 GPUProgrammableStage.entryPoint 不同,即使模块中只有一个入口点,这里也没有默认值。

注意: hint 不会以可观察方式被校验,但用户代理 可以 向开发者(比如在浏览器开发者工具)展示可识别错误(如未知入口点名或不兼容的管线布局)。

createShaderModule(descriptor)

创建一个 GPUShaderModule

调用对象: GPUDevice this。

参数:

GPUDevice.createShaderModule(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPUShaderModuleDescriptor 要创建的 GPUShaderModule 的描述信息。

返回: GPUShaderModule

内容时间线步骤:

  1. sm = ! 创建新的 WebGPU 对象(this, GPUShaderModule, descriptor)。

  2. this设备时间线上执行 初始化步骤

  3. 返回 sm

设备时间线 初始化步骤
  1. error 为使用 WGSL 源 descriptor.code 创建着色器模块时产生的任何错误,若无错误则为 null

  2. 若下列任一要求不满足,则生成校验错误使 sm 无效并返回。

    注意: 未分类错误不会在着色器模块创建时出现。实现如果在着色器模块创建阶段检测到此类错误,必须表现为着色器模块有效,并将错误推迟到管线创建阶段再暴露。

注意:
用户代理不应在此处校验错误的 message 文本中包含详细的编译器错误消息或着色器代码文本:这些详情可通过 getCompilationInfo() 访问。用户代理为开发者提供易读、格式化的错误详情(比如在浏览器开发者工具中以可展开警告展示完整着色器源码)。

由于生产环境中着色器编译错误应该很罕见,用户代理可以选择无论错误处理方式如何(GPU 错误作用域uncapturederror 事件处理器),都向开发者展示这些错误,例如以可展开警告形式。 如果不这样做,应当提供并记录其他方式让开发者访问这些可读错误详情,比如添加一个复选框总是显示错误,或在控制台记录 GPUCompilationInfo 对象时显示可读详情。

从 WGSL 代码创建 GPUShaderModule
// 一个简单的 vertex 和 fragment 着色器对,将用红色填充视口。
const shaderSource = `
    var<private> pos : array<vec2<f32>, 3> = array<vec2<f32>, 3>(
        vec2(-1.0, -1.0), vec2(-1.0, 3.0), vec2(3.0, -1.0));

    @vertex
    fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> @builtin(position) vec4<f32> {
        return vec4(pos[vertexIndex], 1.0, 1.0);
    }

    @fragment
    fn fragmentMain() -> @location(0) vec4<f32> {
        return vec4(1.0, 0.0, 0.0, 1.0);
    }
`;

const shaderModule = gpuDevice.createShaderModule({
    code: shaderSource,
});
9.1.1.1. 着色器模块编译提示

着色器模块编译提示是可选的附加信息,用于指明某个 GPUShaderModule 的入口点将来如何被使用。对于某些实现,这些信息可以帮助更早完成着色器模块编译,从而提升性能。

dictionary GPUShaderModuleCompilationHint {
    required USVString entryPoint;
    (GPUPipelineLayout or GPUAutoLayoutMode) layout;
};
layout类型为 (GPUPipelineLayout or GPUAutoLayoutMode)

一个 GPUPipelineLayout ,表示 GPUShaderModule 在后续 createComputePipeline()createRenderPipeline() 调用中可能会与之配合使用。 如果设置为 "auto",则会为该 hint 关联的入口点使用默认管线布局

注意:
如果可能,作者应该在 createShaderModule()createComputePipeline() / createRenderPipeline() 之间提供一致的信息。

如果应用在调用 createShaderModule() 时无法提供 hint 信息,通常不应因此推迟调用 createShaderModule(),而应在 compilationHints 序列或单个 GPUShaderModuleCompilationHint 成员中省略未知信息。省略该信息可能导致编译被延迟到 createComputePipeline() / createRenderPipeline()

如果作者无法确保传给 createShaderModule() 的 hint 信息会与后续 createComputePipeline() / createRenderPipeline() 使用的信息一致,则应避免向 createShaderModule() 提供该信息,因为不匹配的 hint 可能导致不必要的编译发生。

9.1.2. 着色器模块编译信息

enum GPUCompilationMessageType {
    "error",
    "warning",
    "info",
};

[Exposed=(Window, Worker), Serializable, SecureContext]
interface GPUCompilationMessage {
    readonly attribute DOMString message;
    readonly attribute GPUCompilationMessageType type;
    readonly attribute unsigned long long lineNum;
    readonly attribute unsigned long long linePos;
    readonly attribute unsigned long long offset;
    readonly attribute unsigned long long length;
};

[Exposed=(Window, Worker), Serializable, SecureContext]
interface GPUCompilationInfo {
    readonly attribute FrozenArray<GPUCompilationMessage> messages;
};

GPUCompilationMessageGPUShaderModule 编译器生成的信息、警告或错误消息。这些消息面向开发者、可读性强,用于帮助诊断着色器 code 中的问题。每条消息可能对应着色器代码中的某个具体位置、某段子串,或根本不对应代码中的任何具体位置。

GPUCompilationMessage 具有以下属性:

message类型为 DOMString,只读

该编译消息的人类可读、可本地化文本

注意: message 应遵循字符串语言和方向元信息最佳实践,包括未来可能出现的相关标准。

编者注: 截至目前,还没有兼容并与传统 API 保持一致的语言/方向推荐方案,未来如有应正式采纳。

type类型为 GPUCompilationMessageType,只读

消息的严重级别。

如果 type"error", 则该消息对应 shader-creation error

lineNum类型为 unsigned long long,只读

消息对应的着色器 code 的行号。值为 1 起始,1 表示第一行。行由换行符分隔。

如果 message 对应某个子串,则此处为子串起始行。若消息不对应代码中任何具体点,则为 0

linePos类型为 unsigned long long,只读

从第 lineNum 行起始到消息对应点或子串起始的 UTF-16 单元偏移量。值为 1 起始,linePos1 表示该行第一个单元。

如对应子串,则指向子串第一个 UTF-16 单元。若消息不对应代码中任何具体点,则为 0

offset类型为 unsigned long long,只读

从着色器 code 起始到消息对应点或子串起始的 UTF-16 单元偏移量。必须与 lineNumlinePos 指向同一位置。若消息不对应代码中任何具体点,则为 0

length类型为 unsigned long long,只读

消息对应子串的 UTF-16 单元数量。若消息不对应子串则为 0

注意: GPUCompilationMessage.lineNumGPUCompilationMessage.linePos 都是从 1 起始,便于与大多数文本编辑器的行列号一致。

注意: GPUCompilationMessage.offsetGPUCompilationMessage.length 可直接传给 substr(),取出消息对应的着色器 code 子串。

getCompilationInfo()

返回 GPUShaderModule 编译期间的所有消息。

消息的位置、顺序和内容均为实现自定义,不保证以 lineNum 排序。

调用对象: GPUShaderModule this

返回: Promise<GPUCompilationInfo>

内容时间线步骤:

  1. contentTimeline 为当前 内容时间线

  2. promise新 Promise

  3. this设备时间线上执行 同步步骤

  4. 返回 promise

设备时间线 同步步骤
  1. eventthis着色器模块创建完成(无论成功与否)时发生。

  2. 监听时间线事件 eventthis.[[device]], 后续步骤在 contentTimeline 上执行。

内容时间线步骤:
  1. info 为新的 GPUCompilationInfo

  2. messagesthis着色器模块创建期间产生的所有错误、警告或信息消息(如设备丢失则为 [])。

  3. 对于 messages 中每条 message

    1. m 为新的 GPUCompilationMessage

    2. 设置 m.messagemessage 的文本。

    3. 如果 messageshader-creation error

      设置 m.type"error"

      如果是 warning:

      设置 m.type"warning"

      否则:

      设置 m.type"info"

    4. 如果 message 对应着色器 code 的具体子串或位置:
      1. 设置 m.lineNum 为消息指向的第一行(从 1 起)。

      2. 设置 m.linePos 为该行对应 UTF-16 单元的编号(从 1 起),若消息针对整行则为 1

      3. 设置 m.offset 为从代码开头到子串或位置的 UTF-16 单元数。

      4. 设置 m.length 为子串的 UTF-16 长度,若针对位置则为 0。

      否则:
      1. 设置 m.lineNum0

      2. 设置 m.linePos0

      3. 设置 m.offset0

      4. 设置 m.length0

    5. m 加入 info.messages

  4. resolve promiseinfo

10. 管线

管线(pipeline),无论是 GPUComputePipeline 还是 GPURenderPipeline, 都代表由 GPU 硬件、驱动和用户代理共同完成的完整功能流程:处理绑定和顶点缓冲区等输入数据,并产生输出(比如输出渲染目标的颜色)。

结构上,管线由一系列可编程阶段(着色器)和固定功能状态(如混合模式)组成。

注意: 在内部,具体实现平台可能会把部分固定功能状态转换成着色器代码,并与用户提供的着色器链接。这种链接是管线对象必须整体创建的原因之一。

这种组合状态作为单个对象创建(GPUComputePipelineGPURenderPipeline), 并可通过单条指令切换(分别为 GPUComputePassEncoder.setPipeline()GPURenderCommandsMixin.setPipeline())。

创建管线有两种方式:

同步(即时)管线创建

createComputePipeline()createRenderPipeline() 返回可立即在 pass encoder 中使用的管线对象。

失败时,管线对象无效,调用会产生 校验错误内部错误

注意: 返回的是句柄对象,但实际管线创建并非同步。如果管线创建耗时较长,可能在从创建到首次 setPipeline() 使用、 finish()、或 submit() 之间的某一处导致 设备时间线 阻塞,具体点未规定。

异步管线创建

createComputePipelineAsync()createRenderPipelineAsync() 返回 Promise,管线创建完成时解析为管线对象。

失败时,Promise 拒绝并返回 GPUPipelineError

GPUPipelineError 描述管线创建失败。

[Exposed=(Window, Worker), SecureContext, Serializable]
interface GPUPipelineError : DOMException {
    constructor(optional DOMString message = "", GPUPipelineErrorInit options);
    readonly attribute GPUPipelineErrorReason reason;
};

dictionary GPUPipelineErrorInit {
    required GPUPipelineErrorReason reason;
};

enum GPUPipelineErrorReason {
    "validation",
    "internal",
};

GPUPipelineError 构造函数:

constructor()
参数:
GPUPipelineError.constructor() 方法参数。
参数 类型 可为 null 可选 描述
message DOMString 基础 DOMException 的错误消息。
options GPUPipelineErrorInit 特定于 GPUPipelineError 的选项。

内容时间线步骤:

  1. 设置 this.name"GPUPipelineError"

  2. 设置 this.messagemessage

  3. 设置 this.reasonoptions.reason

GPUPipelineError 具有以下属性:

reason类型为 GPUPipelineErrorReason,只读

只读slot-backed 属性,暴露管线创建中遇到的错误类型,为 GPUPipelineErrorReason

GPUPipelineError 对象是可序列化对象

序列化步骤,给定 valueserialized,为:
  1. DOMException序列化步骤处理 valueserialized

反序列化步骤,给定 valueserialized,为:
  1. DOMException反序列化步骤处理 valueserialized

10.1. 基础管线

enum GPUAutoLayoutMode {
    "auto",
};

dictionary GPUPipelineDescriptorBase
         : GPUObjectDescriptorBase {
    required (GPUPipelineLayout or GPUAutoLayoutMode) layout;
};
layout类型为 (GPUPipelineLayout or GPUAutoLayoutMode)

本管线的 GPUPipelineLayout, 或 "auto" 以自动生成管线布局。

注意: 若使用 "auto", 则此管线无法与其它管线共享 GPUBindGroup

interface mixin GPUPipelineBase {
    [NewObject] GPUBindGroupLayout getBindGroupLayout(unsigned long index);
};

GPUPipelineBase 具有以下设备时间线属性

[[layout]],类型为 GPUPipelineLayout

定义可与 this 配合使用的资源布局。

GPUPipelineBase 具有以下方法:

getBindGroupLayout(index)

获取与 GPUPipelineBaseindex 处的 GPUBindGroupLayout 兼容的 GPUBindGroupLayout

调用对象: GPUPipelineBase this

参数:

GPUPipelineBase.getBindGroupLayout(index) 方法参数。
参数 类型 可为 null 可选 描述
index unsigned long 管线布局 [[bindGroupLayouts]] 序列的索引。

返回: GPUBindGroupLayout

内容时间线步骤:

  1. layout 为新的 GPUBindGroupLayout 对象。

  2. this设备时间线上执行 初始化步骤

  3. 返回 layout

设备时间线 初始化步骤
  1. limits = this.[[device]].[[limits]]

  2. 若下列任一条件不满足,则生成校验错误使 layout 无效并返回。

  3. 初始化 layout 使其为 this.[[layout]].[[bindGroupLayouts]][index] 的副本。

    注意: GPUBindGroupLayout 永远是按值使用,不按引用,因此等价于返回同一个内部对象并创建新WebGPU 接口。每次都返回新 GPUBindGroupLayout WebGPU 接口,以避免 内容时间线设备时间线之间的往返。

10.1.1. 默认管线布局

如果 GPUPipelineBase 对象在创建时 layout 设置为 "auto",则会自动创建并使用一个默认布局。

注意: 默认布局为简易管线提供便利,大多数场景推荐显式布局。由默认布局创建的绑定组无法与其他管线共享,且默认布局结构在着色器变更时可能发生变化,导致绑定组创建异常。

GPUPipelineBase pipeline 创建默认管线布局设备时间线步骤如下:

  1. groupCount = 0。

  2. groupDescsdevice.[[limits]].maxBindGroups 个新的 GPUBindGroupLayoutDescriptor 对象序列。

  3. 对每个 groupDesc in groupDescs

    1. 设置 groupDesc.entries 为一个空的 序列

  4. 对创建 pipeline 时描述中的每个 GPUProgrammableStage stageDesc

    1. shaderStagestageDescpipeline 中对应的 GPUShaderStageFlags

    2. entryPoint = get the entry point(shaderStage, stageDesc)。断言 entryPointnull

    3. entryPoint 静态使用的每个资源 resource

      1. groupresource 的 "group" 标注。

      2. bindingresource 的 "binding" 标注。

      3. entry 为新的 GPUBindGroupLayoutEntry

      4. 设置 entry.bindingbinding

      5. 设置 entry.visibilityshaderStage

      6. resource 为采样器绑定:

        1. samplerLayout 为新的 GPUSamplerBindingLayout

        2. 设置 entry.samplersamplerLayout

      7. resource 为比较采样器绑定:

        1. samplerLayout 为新的 GPUSamplerBindingLayout

        2. 设置 samplerLayout.type"comparison"

        3. 设置 entry.samplersamplerLayout

      8. resource 为缓冲区绑定:

        1. bufferLayout 为新的 GPUBufferBindingLayout

        2. 设置 bufferLayout.minBindingSizeresource最小缓冲绑定大小

        3. 如果 resource 为只读存储缓冲区:

          1. 设置 bufferLayout.type"read-only-storage"

        4. 如果 resource 为存储缓冲区:

          1. 设置 bufferLayout.type"storage"

        5. 设置 entry.bufferbufferLayout

      9. resource 为采样纹理绑定:

        1. textureLayout 为新的 GPUTextureBindingLayout

        2. 如果 resource 为深度纹理绑定:

          否则,根据 resource 采样类型:

          f32 且存在对 resource静态使用,且在带采样器的纹理内建函数调用中

          设置 textureLayout.sampleType"float"

          f32 否则

          设置 textureLayout.sampleType"unfilterable-float"

          i32

          设置 textureLayout.sampleType"sint"

          u32

          设置 textureLayout.sampleType"uint"

        3. 设置 textureLayout.viewDimensionresource 的维度。

        4. resource 为多采样纹理:

          1. 设置 textureLayout.multisampledtrue

        5. 设置 entry.texturetextureLayout

      10. resource 为存储纹理绑定:

        1. storageTextureLayout 为新的 GPUStorageTextureBindingLayout

        2. 设置 storageTextureLayout.formatresource 的格式。

        3. 设置 storageTextureLayout.viewDimensionresource 的维度。

        4. 若访问模式为:

          read

          设置 textureLayout.access"read-only"

          write

          设置 textureLayout.access"write-only"

          read_write

          设置 textureLayout.access"read-write"

        5. 设置 entry.storageTexturestorageTextureLayout

      11. 设置 groupCount = max(groupCount, group + 1)。

      12. groupDescs[group] 已存在 binding 等于 binding 的条目 previousEntry

        1. entryvisibility 不同于 previousEntry

          1. entry.visibility 的比特位并入 previousEntry.visibility

        2. resource 为缓冲区绑定且 entrybuffer.minBindingSize 大于 previousEntry

          1. 设置 previousEntry.buffer.minBindingSizeentry.buffer.minBindingSize

        3. resource 为采样纹理绑定且 entrytexture.sampleTypepreviousEntry 不同,且二者均为 "float""unfilterable-float"

          1. 设置 previousEntry.texture.sampleType"float"

        4. entrypreviousEntry 其他属性不同:

          1. 返回 null(导致管线创建失败)。

        5. resource 为存储纹理绑定,entry.storageTexture.access"read-write"previousEntry.storageTexture.access"write-only",且格式兼容,见 § 26.1.1 普通色彩格式表:

          1. 设置 previousEntry.storageTexture.access"read-write"

      13. 否则

        1. entry 添加到 groupDescs[group]。

  5. groupLayouts 为新 列表

  6. i 从 0 到 groupCount - 1:

    1. groupDesc = groupDescs[i]。

    2. bindGroupLayout = device.createBindGroupLayout()(groupDesc)。

    3. 设置 bindGroupLayout.[[exclusivePipeline]]pipeline

    4. bindGroupLayout 添加到 groupLayouts

  7. desc 为新的 GPUPipelineLayoutDescriptor

  8. 设置 desc.bindGroupLayoutsgroupLayouts

  9. 返回 device.createPipelineLayout()(desc)。

10.1.2. GPUProgrammableStage

GPUProgrammableStage 描述了用户提供的 GPUShaderModule 中控制 管线某个可编程阶段的入口点。 入口点名称遵循 WGSL 标识符对比的规则。

dictionary GPUProgrammableStage {
    required GPUShaderModule module;
    USVString entryPoint;
    record<USVString, GPUPipelineConstantValue> constants = {};
};

typedef double GPUPipelineConstantValue; // 可表示 WGSL 的 bool、f32、i32、u32、以及启用时的 f16。

GPUProgrammableStage 具有以下成员:

module类型为 GPUShaderModule

包含本可编程阶段将要执行代码的 GPUShaderModule

entryPoint类型为 USVString

本阶段执行时将使用的 module 中的函数名。

注意: 虽然 entryPoint 不是必填项,消费 GPUProgrammableStage 的方法必须使用“获取入口点”算法确定实际入口点。

constants类型为 record<USVString, GPUPipelineConstantValue>,默认值为 {}

指定着色器模块 module可被管线重写(pipeline-overridable) 常量的值。

每个此类 可重写常量都唯一由一个 可重写常量标识符字符串标识, 代表其声明指定的 管线常量 ID,否则为常量名称。

每个键值对的 key 必须等于对应常量的 标识符字符串,其对比规则见WGSL 标识符对比。管线执行时,该常量将取指定值。

值类型为 GPUPipelineConstantValue,即 double。会转换为常量的 WGSL 类型(bool/i32/u32/f32/f16)。转换失败会生成校验错误。

WGSL 中定义的管线可重写常量:
@id(0)      override has_point_light: bool = true;  // 算法控制。
@id(1200)   override specular_param: f32 = 2.3;     // 数值控制。
@id(1300)   override gain: f32;                     // 必须重写。
            override width: f32 = 0.0;              // 通过 API 使用名字 "width" 指定
                                                    //   
            override depth: f32;                    // 通过 API 使用名字 "depth" 指定,必须重写。
            override height = 2 * depth;            // 默认值依赖另一个可重写常量。

对应的 JavaScript 代码,仅传递必须重写(无默认值)的常量:

{
    // ...
    constants: {
        1300: 2.0,  // "gain"
        depth: -1,  // "depth"
    }
}

对应的 JavaScript 代码,重写所有常量:

{
    // ...
    constants: {
        0: false,   // "has_point_light"
        1200: 3.0,  // "specular_param"
        1300: 2.0,  // "gain"
        width: 20,  // "width"
        depth: -1,  // "depth"
        height: 15, // "height"
    }
}
获取入口点(get the entry point)(GPUShaderStage stage, GPUProgrammableStage descriptor),请执行如下设备时间线步骤:
  1. 如果 descriptor.entryPoint 已提供

    1. 如果 descriptor.module 包含名称与 descriptor.entryPoint 相等且着色器阶段等于 stage 的入口点,则返回该入口点。

      否则,返回 null

    否则:

    1. 如果 descriptor.module 中着色器阶段等于 stage 的入口点恰好有一个,则返回该入口点。

      否则,返回 null

验证 GPUProgrammableStage(validating GPUProgrammableStage)(stage, descriptor, layout, device)

参数:

以下所有步骤中的要求都必须满足。若有任一不满足,则返回 false;全部满足则返回 true

  1. descriptor.module 必须 可与 device 配合使用。

  2. entryPoint = 获取入口点(stage, descriptor)。

  3. entryPoint 必须不为 null

  4. entryPoint 静态使用的每个 binding

  5. entryPoint 所在着色器阶段所有函数中的每个纹理内建函数调用,若同时使用了 sampled texturedepth texture 类型的 textureBinding 以及类型为 sampler(排除 sampler_comparison)的 samplerBinding

    1. texturetextureBinding 对应的 GPUBindGroupLayoutEntry

    2. samplersamplerBinding 对应的 GPUBindGroupLayoutEntry

    3. sampler.type"filtering", 则 texture.sampleType 必须"float"

    注意: "comparison" 采样器只能用于 "depth" 纹理,因为只有该类型能绑定到 WGSL texture_depth_* 绑定点。

  6. descriptor.constants 的每个 keyvalue

    1. key 必须等于着色器模块 descriptor.module 中某个 可重写常量(pipeline-overridable)标识符字符串(判断规则见 WGSL 标识符对比)。管线可重写常量无需被 entryPoint 静态使用。令该常量类型为 T

    2. 将 IDL 值 value 转换为 WGSL 类型 T不得抛出 TypeError

  7. entryPoint 静态使用的每个管线可重写常量 key

  8. 根据 [WGSL] 规范,不得产生 管线创建 程序错误

验证着色器绑定(validating shader binding)(variable, layout)

参数:

bindGroup 为绑定组索引,bindIndex 为绑定索引,均来自着色器绑定声明 variable

当且仅当下列所有条件满足时,返回 true

最小缓冲绑定大小(minimum buffer binding size)用于缓冲绑定变量 var,计算方式如下:
  1. Tvar存储类型(store type)

  2. T运行时尺寸数组,或包含运行时尺寸数组,则将该 array<E> 替换为 array<E, 1>

    注意: 这样确保至少有一个元素内存,允许数组索引被限制在实际长度范围内,从而保证内存访问安全。

  3. 返回 SizeOf(T)。

注意: 强制此下限可确保通过缓冲变量的读写只会访问缓冲区界限内的内存。

资源绑定、可重写管线常量、着色器阶段输入或输出, 若出现在相应入口点的着色器阶段接口中,则认为被该入口点静态使用(statically used)

10.2. GPUComputePipeline

GPUComputePipeline 是一种管线,控制计算着色器阶段, 并可用于 GPUComputePassEncoder

计算输入和输出均通过绑定传递,受指定的 GPUPipelineLayout 控制。 输出对应类型为 "storage"buffer 绑定, 以及类型为 "write-only""read-write"storageTexture 绑定。

计算管线的阶段:

  1. 计算着色器(Compute shader)

[Exposed=(Window, Worker), SecureContext]
interface GPUComputePipeline {
};
GPUComputePipeline includes GPUObjectBase;
GPUComputePipeline includes GPUPipelineBase;

10.2.1. 计算管线的创建

GPUComputePipelineDescriptor 描述了一个计算管线。更多细节参见§ 23.1 计算

dictionary GPUComputePipelineDescriptor
         : GPUPipelineDescriptorBase {
    required GPUProgrammableStage compute;
};

GPUComputePipelineDescriptor 具有以下成员:

compute类型为 GPUProgrammableStage

描述该管线的计算着色器入口点。

createComputePipeline(descriptor)

使用同步管线创建方式创建一个 GPUComputePipeline

调用对象: GPUDevice this.

参数:

GPUDevice.createComputePipeline(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPUComputePipelineDescriptor 要创建的 GPUComputePipeline 的描述信息。

返回: GPUComputePipeline

内容时间线步骤:

  1. pipeline = ! 创建新 WebGPU 对象(create a new WebGPU object)(this, GPUComputePipeline, descriptor)。

  2. this设备时间线上执行 初始化步骤

  3. 返回 pipeline

设备时间线 初始化步骤
  1. descriptor.layout"auto", 则令 layout默认管线布局; 否则,layout = descriptor.layout

  2. 以下所有步骤要求都必须满足。若有不满足,则生成校验错误使 pipeline 无效并返回。

    1. layout 必须可与 this 配合使用。

    2. 验证 GPUProgrammableStage(COMPUTE, descriptor.compute, layout, this) 必须成功。

    3. entryPoint = 获取入口点(COMPUTE, descriptor.compute)。

      断言 entryPoint 不为 null

    4. workgroupStorageUsedroundUp(16, SizeOf(T)) 的和, 其中 TentryPoint 静态使用的所有地址空间为 "workgroup" 的变量类型。

      workgroupStorageUsed 必须device.limits.maxComputeWorkgroupStorageSize

    5. entryPoint 必须每个工作组内使用的线程数 ≤ device.limits.maxComputeInvocationsPerWorkgroup

    6. entryPointworkgroup_size 属性的每个分量 必须 ≤ [device.limits.maxComputeWorkgroupSizeX, device.limits.maxComputeWorkgroupSizeY, device.limits.maxComputeWorkgroupSizeZ]。

  3. 如实现管线创建过程中产生了任何管线创建未分类错误生成内部错误使 pipeline 无效并返回。

    注意: 即便实现已在着色器模块创建时检测到未分类错误,也会在此处抛出。

  4. 设置 pipeline.[[layout]] = layout

createComputePipelineAsync(descriptor)

使用异步管线创建方式创建 GPUComputePipeline。 返回的 Promise 会在管线准备好可用时 resolve。

若管线创建失败,返回的 Promise 将 reject,并返回 GPUPipelineError。 (此时不会向 device 派发 GPUError。)

注意: 建议尽可能使用本方法,可避免阻塞队列时间线的管线编译工作。

调用对象: GPUDevice this.

参数:

GPUDevice.createComputePipelineAsync(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPUComputePipelineDescriptor 要创建的 GPUComputePipeline 的描述信息。

返回: Promise<GPUComputePipeline>

内容时间线步骤:

  1. contentTimeline 为当前内容时间线

  2. promise新 Promise

  3. this设备时间线上执行 初始化步骤

  4. 返回 promise

设备时间线 初始化步骤
  1. pipeline 为新建的 GPUComputePipeline, 类似于调用 this.createComputePipeline() 时传入 descriptor,但将产生的错误捕获为 error,而不是派发到 device。

  2. eventpipeline管线创建(无论成功与否)完成时发生。

  3. 监听时间线事件 eventthis.[[device]], 后续步骤于 设备时间线执行。

设备时间线步骤:
  1. pipeline 有效this 已丢失

    1. contentTimeline 上执行下列步骤:

      内容时间线步骤:
      1. resolve promisepipeline

    2. 返回。

    注意: 设备丢失不会产生错误。参见 § 22 错误与调试

  2. pipeline 无效error内部错误,在 contentTimeline 上执行下列步骤并返回:

    内容时间线步骤:
    1. reject promise,返回 GPUPipelineErrorreason"internal"

  3. pipeline 无效error校验错误,在 contentTimeline 上执行下列步骤并返回:

    内容时间线步骤:
    1. reject promise,返回 GPUPipelineErrorreason"validation"

创建一个简单的 GPUComputePipeline
const computePipeline = gpuDevice.createComputePipeline({
    layout: pipelineLayout,
    compute: {
        module: computeShaderModule,
        entryPoint: 'computeMain',
    }
});

10.3. GPURenderPipeline

GPURenderPipeline 是一种管线,控制顶点和片元着色器阶段,并可用于 GPURenderPassEncoder 以及 GPURenderBundleEncoder

渲染管线的输入包括:

渲染管线的输出包括:

渲染管线包含以下渲染阶段(render stages)

  1. 顶点抓取,由 GPUVertexState.buffers 控制

  2. 顶点着色器,由 GPUVertexState 控制

  3. 图元组装,由 GPUPrimitiveState 控制

  4. 光栅化,由 GPUPrimitiveStateGPUDepthStencilState、 以及 GPUMultisampleState 控制

  5. 片元着色器,由 GPUFragmentState 控制

  6. 模板测试和操作,由 GPUDepthStencilState 控制

  7. 深度测试与写入,由 GPUDepthStencilState 控制

  8. 输出合并,由 GPUFragmentState.targets 控制

[Exposed=(Window, Worker), SecureContext]
interface GPURenderPipeline {
};
GPURenderPipeline includes GPUObjectBase;
GPURenderPipeline includes GPUPipelineBase;

GPURenderPipeline 具有以下设备时间线属性

[[descriptor]],类型为 GPURenderPipelineDescriptor, 只读

描述此管线的 GPURenderPipelineDescriptor

所有可选字段均已定义。

[[writesDepth]],类型为 boolean, 只读

如果管线会写入深度/模板附件的深度分量,则为 true。

[[writesStencil]],类型为 boolean, 只读

如果管线会写入深度/模板附件的模板分量,则为 true。

10.3.1. 渲染管线的创建

GPURenderPipelineDescriptor 通过配置各渲染阶段描述一个渲染管线。详见 § 23.2 渲染

dictionary GPURenderPipelineDescriptor
         : GPUPipelineDescriptorBase {
    required GPUVertexState vertex;
    GPUPrimitiveState primitive = {};
    GPUDepthStencilState depthStencil;
    GPUMultisampleState multisample = {};
    GPUFragmentState fragment;
};

GPURenderPipelineDescriptor 具有以下成员:

vertex类型为 GPUVertexState

描述管线的顶点着色器入口点和其输入缓冲区布局。

primitive类型为 GPUPrimitiveState,默认值为 {}

描述管线的图元相关属性。

depthStencil类型为 GPUDepthStencilState

描述可选的深度-模板属性,包括测试、操作和偏移。

multisample类型为 GPUMultisampleState,默认值为 {}

描述管线的多重采样属性。

fragment类型为 GPUFragmentState

描述管线的片元着色器入口点及其输出颜色。如未提供,则启用§ 23.2.8 无颜色输出模式。

createRenderPipeline(descriptor)

使用同步管线创建方式创建 GPURenderPipeline

调用对象: GPUDevice this.

参数:

GPUDevice.createRenderPipeline(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPURenderPipelineDescriptor 要创建的 GPURenderPipeline 描述信息。

返回: GPURenderPipeline

内容时间线步骤:

  1. descriptor.fragment 已提供

    1. 遍历 descriptor.fragment.targets 的所有非 null colorState

      1. ? 校验纹理格式所需特性colorState.formatthis.[[device]]

  2. descriptor.depthStencil 已提供

    1. ? 校验纹理格式所需特性descriptor.depthStencil.formatthis.[[device]]

  3. pipeline = ! 创建新 WebGPU 对象(this, GPURenderPipeline, descriptor)。

  4. this设备时间线上执行 初始化步骤

  5. 返回 pipeline

设备时间线 初始化步骤
  1. descriptor.layout"auto", 则令 layout默认管线布局, 否则 layout = descriptor.layout

  2. 以下步骤要求全部必须满足。如有不满足,则生成校验错误使 pipeline 无效并返回。

    1. layout 必须可与 this 配合使用。

    2. 验证 GPURenderPipelineDescriptor(descriptor, layout, this) 必须成功。

    3. vertexBufferCountdescriptor.vertex.buffers 中最后一个非 null 项的索引加 1,如无则为 0。

    4. layout.[[bindGroupLayouts]].size + vertexBufferCount 必须 ≤ this.[[device]].[[limits]].maxBindGroupsPlusVertexBuffers

  3. 如实现管线创建过程中产生任何管线创建未分类错误生成内部错误使 pipeline 无效并返回。

    注意: 即使着色器模块创建时检测到未分类错误,错误也会在此处抛出。

  4. 设置 pipeline.[[descriptor]] = descriptor

  5. 设置 pipeline.[[writesDepth]] = false。

  6. 设置 pipeline.[[writesStencil]] = false。

  7. depthStencil = descriptor.depthStencil

  8. depthStencil 非 null:

    1. depthStencil.depthWriteEnabled 已提供

      1. 设置 pipeline.[[writesDepth]] = depthStencil.depthWriteEnabled

    2. depthStencil.stencilWriteMask 非 0:

      1. stencilFront = depthStencil.stencilFront

      2. stencilBack = depthStencil.stencilBack

      3. cullMode = descriptor.primitive.cullMode

      4. cullMode 不为 "front",且 stencilFront.passOpstencilFront.depthFailOpstencilFront.failOp 任意一项非 "keep"

        1. 设置 pipeline.[[writesStencil]] = true。

      5. cullMode 不为 "back",且 stencilBack.passOpstencilBack.depthFailOpstencilBack.failOp 任意一项非 "keep"

        1. 设置 pipeline.[[writesStencil]] = true。

  9. 设置 pipeline.[[layout]] = layout

createRenderPipelineAsync(descriptor)

使用异步管线创建方式创建 GPURenderPipeline。 返回的 Promise 会在管线准备好可用时 resolve。

若管线创建失败,返回的 Promise 将 reject,并返回 GPUPipelineError。 (不会向 device 派发 GPUError。)

注意: 建议尽量使用本方法,可避免阻塞队列时间线的管线编译工作。

调用对象: GPUDevice this.

参数:

GPUDevice.createRenderPipelineAsync(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPURenderPipelineDescriptor 要创建的 GPURenderPipeline 描述信息。

返回: Promise<GPURenderPipeline>

内容时间线步骤:

  1. contentTimeline 为当前内容时间线

  2. promise = 新 Promise

  3. this设备时间线上执行 初始化步骤

  4. 返回 promise

设备时间线 初始化步骤
  1. pipeline 为新建的 GPURenderPipeline, 类似于调用 this.createRenderPipeline() 时传入 descriptor,但将产生的错误捕获为 error,而不是派发到 device。

  2. eventpipeline管线创建(无论成功与否)完成时发生。

  3. 监听时间线事件 eventthis.[[device]], 后续步骤于 设备时间线执行。

设备时间线步骤:
  1. pipeline 有效this 已丢失

    1. contentTimeline 上执行下列步骤:

      内容时间线步骤:
      1. resolve promisepipeline

    2. 返回。

    注意: 设备丢失不会产生错误。参见 § 22 错误与调试

  2. pipeline 无效error内部错误,在 contentTimeline 上执行下列步骤并返回:

    内容时间线步骤:
    1. reject promise,返回 GPUPipelineErrorreason"internal"

  3. pipeline 无效error校验错误,在 contentTimeline 上执行下列步骤并返回:

    内容时间线步骤:
    1. reject promise,返回 GPUPipelineErrorreason"validation"

验证 GPURenderPipelineDescriptor(validating GPURenderPipelineDescriptor)(descriptor, layout, device)

参数:

设备时间线步骤:

  1. 若下列所有条件均满足则返回 true

验证阶段间接口(validating inter-stage interfaces)(device, descriptor)

参数:

返回值: boolean

设备时间线步骤:

  1. maxVertexShaderOutputVariables = device.limits.maxInterStageShaderVariables

  2. maxVertexShaderOutputLocation = device.limits.maxInterStageShaderVariables - 1。

  3. descriptor.primitive.topology"point-list"

    1. maxVertexShaderOutputVariables 减 1。

  4. clip_distancesdescriptor.vertex 的输出中声明:

    1. clipDistancesSizeclip_distances 的数组大小。

    2. maxVertexShaderOutputVariables 减 ceil(clipDistancesSize / 4)。

    3. maxVertexShaderOutputLocation 减 ceil(clipDistancesSize / 4)。

  5. 如下要求有任意一项不满足则返回 false

    • 用户自定义顶点输出数量不超过 maxVertexShaderOutputVariables

    • 每个用户自定义顶点输出的locationmaxVertexShaderOutputLocation

  6. descriptor.fragment 已提供

    1. maxFragmentShaderInputVariables = device.limits.maxInterStageShaderVariables

    2. front_facingsample_indexsample_mask 内建变量descriptor.fragment 的输入:

      1. maxFragmentShaderInputVariables 减 1。

    3. 如有下列任一项不满足则返回 false

      • descriptor.fragment 的每个用户自定义输入,均有 descriptor.vertex 中用户自定义输出在 location、类型和插值方式上对应。

        注意: 顶点-only 管线可有用户自定义顶点输出,其值会被丢弃。

      • 用户自定义片元输入数量不超过 maxFragmentShaderInputVariables

    4. 断言每个用户自定义片元输入的location均小于 device.limits.maxInterStageShaderVariables。(由上规则推得)

  7. 返回 true

创建一个简单的 GPURenderPipeline
const renderPipeline = gpuDevice.createRenderPipeline({
    layout: pipelineLayout,
    vertex: {
        module: shaderModule,
        entryPoint: 'vertexMain'
    },
    fragment: {
        module: shaderModule,
        entryPoint: 'fragmentMain',
        targets: [{
            format: 'bgra8unorm',
        }],
    }
});

10.3.2. 图元状态(Primitive State)

dictionary GPUPrimitiveState {
    GPUPrimitiveTopology topology = "triangle-list";
    GPUIndexFormat stripIndexFormat;
    GPUFrontFace frontFace = "ccw";
    GPUCullMode cullMode = "none";

    // 需要 "depth-clip-control" 特性。
    boolean unclippedDepth = false;
};

GPUPrimitiveState 拥有以下成员,描述 GPURenderPipeline 如何根据顶点输入构造和光栅化图元:

topology类型为 GPUPrimitiveTopology,默认值为 "triangle-list"

由顶点输入生成的图元类型。

stripIndexFormat 类型为 GPUIndexFormat

用于带 strip 拓扑 ("line-strip""triangle-strip") 的管线, 决定索引缓冲区格式和图元重启值 ("uint16"/0xFFFF"uint32"/0xFFFFFFFF)。 非 strip 拓扑管线不允许设置此项。

注意: 某些实现需要提前知道图元重启值,以编译管线状态对象。

若 strip 拓扑管线用于带索引的绘制调用 (drawIndexed()drawIndexedIndirect()), 则必须设置该值,并且要与 draw 调用所用索引缓冲区格式(setIndexBuffer() 设置)一致。

详见 § 23.2.3 图元组装

frontFace类型为 GPUFrontFace,默认值为 "ccw"

定义哪些多边形被视为正面(front-facing)

cullMode类型为 GPUCullMode,默认值为 "none"

定义哪些多边形朝向会被裁剪(cull),如有的话。

unclippedDepth 类型为 boolean,默认值为 false

如为 true,表示深度裁剪(depth clipping)被禁用。

需要启用 "depth-clip-control" 特性。

验证 GPUPrimitiveState(validating GPUPrimitiveState)(descriptor, device) 参数:

设备时间线步骤:

  1. 如果下列所有条件都满足则返回 true

enum GPUPrimitiveTopology {
    "point-list",
    "line-list",
    "line-strip",
    "triangle-list",
    "triangle-strip",
};

GPUPrimitiveTopology 定义了 GPURenderPipeline 的绘制调用会使用的图元类型。详见 § 23.2.5 光栅化

"point-list"

每个顶点定义一个点图元。

"line-list"

每两个连续顶点组成一个线段图元。

"line-strip"

第一个顶点后,每个顶点与前一个顶点组成一个线段图元。

"triangle-list"

每三个连续顶点组成一个三角形图元。

"triangle-strip"

前两个顶点后,每个顶点与前两个顶点组成一个三角形图元。

enum GPUFrontFace {
    "ccw",
    "cw",
};

GPUFrontFace 定义 GPURenderPipeline 视为正面(front-facing)的多边形。详见 § 23.2.5.4 多边形光栅化

"ccw"

顶点在帧缓区坐标中按逆时针顺序排列的多边形被视为正面

"cw"

顶点在帧缓区坐标中按顺时针顺序排列的多边形被视为正面

enum GPUCullMode {
    "none",
    "front",
    "back",
};

GPUPrimitiveTopology 定义了哪些多边形会被 GPURenderPipeline 的绘制调用裁剪。详见 § 23.2.5.4 多边形光栅化

"none"

不丢弃任何多边形。

"front"

正面多边形将被丢弃。

"back"

背面多边形将被丢弃。

注意: GPUFrontFaceGPUCullMode 对于 "point-list""line-list""line-strip" 拓扑无效。

10.3.3. 多重采样状态(Multisample State)

dictionary GPUMultisampleState {
    GPUSize32 count = 1;
    GPUSampleMask mask = 0xFFFFFFFF;
    boolean alphaToCoverageEnabled = false;
};

GPUMultisampleState 拥有以下成员,描述 GPURenderPipeline 如何与渲染通道的多重采样附件进行交互。

count类型为 GPUSize32,默认值为 1

每像素的采样数。该 GPURenderPipeline 仅与 colorAttachmentsdepthStencilAttachmentsampleCount 匹配的附件纹理兼容。

mask类型为 GPUSampleMask,默认值 0xFFFFFFFF

决定哪些采样点会被写入的掩码。

alphaToCoverageEnabled类型为 boolean,默认值 false

true 时,表示片元的 alpha 通道用于生成采样覆盖掩码。

验证 GPUMultisampleState(validating GPUMultisampleState)(descriptor) 参数:

设备时间线步骤:

  1. 若下列所有条件均满足则返回 true

10.3.4. 片元状态(Fragment State)

dictionary GPUFragmentState
         : GPUProgrammableStage {
    required sequence<GPUColorTargetState?> targets;
};
targets类型为 sequence<GPUColorTargetState?>

一个 GPUColorTargetState 列表,定义本管线写入的颜色目标的格式和行为。

验证 GPUFragmentState(validating GPUFragmentState)(device, descriptor, layout)

参数:

设备时间线步骤:

  1. 若下列所有要求都满足则返回 true

验证 GPUFragmentState 的 color attachment bytes per sample(Validating GPUFragmentState’s color attachment bytes per sample)(device, targets)

参数:

设备时间线步骤:

  1. formats 为一个空的 list<GPUTextureFormat?>

  2. 遍历 targets 中的每个 target

    1. targetundefined,则跳过。

    2. 追加 target.formatformats

  3. 计算 color attachment bytes per sample(formats) 必须 ≤ device.[[limits]].maxColorAttachmentBytesPerSample

注意: 片元着色器可输出的值可能多于管线实际使用的颜色输出,未被使用的值会被忽略。

GPUBlendComponent component 是一个 有效 GPUBlendComponent(valid GPUBlendComponent),在逻辑 device device 上,需满足以下要求:

10.3.5. 颜色目标状态(Color Target State)

dictionary GPUColorTargetState {
    required GPUTextureFormat format;

    GPUBlendState blend;
    GPUColorWriteFlags writeMask = 0xF;  // GPUColorWrite.ALL
};
format类型为 GPUTextureFormat

该颜色目标的 GPUTextureFormat。管线只与 在对应颜色附件中使用该格式的 GPURenderPassEncoderGPUTextureView 兼容。

blend类型为 GPUBlendState

该颜色目标的混合行为。如未定义,则禁用该颜色目标的混合。

writeMask类型为 GPUColorWriteFlags,默认值 0xF

控制绘制到该颜色目标时写入哪些通道的位掩码。

dictionary GPUBlendState {
    required GPUBlendComponent color;
    required GPUBlendComponent alpha;
};
color类型为 GPUBlendComponent

定义对应渲染目标颜色通道的混合行为。

alpha类型为 GPUBlendComponent

定义对应渲染目标 alpha 通道的混合行为。

typedef [EnforceRange] unsigned long GPUColorWriteFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUColorWrite {
    const GPUFlagsConstant RED   = 0x1;
    const GPUFlagsConstant GREEN = 0x2;
    const GPUFlagsConstant BLUE  = 0x4;
    const GPUFlagsConstant ALPHA = 0x8;
    const GPUFlagsConstant ALL   = 0xF;
};
10.3.5.1. 混合状态(Blend State)
dictionary GPUBlendComponent {
    GPUBlendOperation operation = "add";
    GPUBlendFactor srcFactor = "one";
    GPUBlendFactor dstFactor = "zero";
};

GPUBlendComponent 拥有以下成员,描述片元的颜色或 alpha 分量是如何混合的:

operation类型为 GPUBlendOperation,默认值为 "add"

定义用于计算写入目标附件分量值的 GPUBlendOperation

srcFactor类型为 GPUBlendFactor,默认值为 "one"

定义对来自片元着色器的值执行的 GPUBlendFactor 操作。

dstFactor类型为 GPUBlendFactor,默认值为 "zero"

定义对来自目标附件的值执行的 GPUBlendFactor 操作。

下表说明了用于描述片元位置的颜色分量的符号:

RGBAsrc 片元着色器输出到颜色附件的颜色。 如果着色器没有返回 alpha 通道,则不能使用 src-alpha 混合因子。
RGBAsrc1 片元着色器输出到带有 "@blend_src" 属性1 的颜色附件的颜色。 如果着色器没有返回 alpha 通道,则不能使用 src1-alpha 混合因子。
RGBAdst 当前颜色附件中的颜色。 缺失的绿色/蓝色/alpha 通道分别默认 0, 0, 1
RGBAconst 当前 [[blendConstant]]
RGBAsrcFactor srcFactor 定义的源混合因子分量。
RGBAdstFactor dstFactor 定义的目标混合因子分量。
enum GPUBlendFactor {
    "zero",
    "one",
    "src",
    "one-minus-src",
    "src-alpha",
    "one-minus-src-alpha",
    "dst",
    "one-minus-dst",
    "dst-alpha",
    "one-minus-dst-alpha",
    "src-alpha-saturated",
    "constant",
    "one-minus-constant",
    "src1",
    "one-minus-src1",
    "src1-alpha",
    "one-minus-src1-alpha",
};

GPUBlendFactor 定义了源或目标混合因子的计算方式:

GPUBlendFactor 混合因子 RGBA 分量 特性
"zero" (0, 0, 0, 0)
"one" (1, 1, 1, 1)
"src" (Rsrc, Gsrc, Bsrc, Asrc)
"one-minus-src" (1 - Rsrc, 1 - Gsrc, 1 - Bsrc, 1 - Asrc)
"src-alpha" (Asrc, Asrc, Asrc, Asrc)
"one-minus-src-alpha" (1 - Asrc, 1 - Asrc, 1 - Asrc, 1 - Asrc)
"dst" (Rdst, Gdst, Bdst, Adst)
"one-minus-dst" (1 - Rdst, 1 - Gdst, 1 - Bdst, 1 - Adst)
"dst-alpha" (Adst, Adst, Adst, Adst)
"one-minus-dst-alpha" (1 - Adst, 1 - Adst, 1 - Adst, 1 - Adst)
"src-alpha-saturated" (min(Asrc, 1 - Adst), min(Asrc, 1 - Adst), min(Asrc, 1 - Adst), 1)
"constant" (Rconst, Gconst, Bconst, Aconst)
"one-minus-constant" (1 - Rconst, 1 - Gconst, 1 - Bconst, 1 - Aconst)
"src1" (Rsrc1, Gsrc1, Bsrc1, Asrc1) dual-source-blending
"one-minus-src1" (1 - Rsrc1, 1 - Gsrc1, 1 - Bsrc1, 1 - Asrc1)
"src1-alpha" (Asrc1, Asrc1, Asrc1, Asrc1)
"one-minus-src1-alpha" (1 - Asrc1, 1 - Asrc1, 1 - Asrc1, 1 - Asrc1)
enum GPUBlendOperation {
    "add",
    "subtract",
    "reverse-subtract",
    "min",
    "max",
};

GPUBlendOperation 定义了用于组合源和目标混合因子的算法:

GPUBlendOperation RGBA 分量
"add" RGBAsrc × RGBAsrcFactor + RGBAdst × RGBAdstFactor
"subtract" RGBAsrc × RGBAsrcFactor - RGBAdst × RGBAdstFactor
"reverse-subtract" RGBAdst × RGBAdstFactor - RGBAsrc × RGBAsrcFactor
"min" min(RGBAsrc, RGBAdst)
"max" max(RGBAsrc, RGBAdst)

10.3.6. 深度/模板状态(Depth/Stencil State)

dictionary GPUDepthStencilState {
    required GPUTextureFormat format;

    boolean depthWriteEnabled;
    GPUCompareFunction depthCompare;

    GPUStencilFaceState stencilFront = {};
    GPUStencilFaceState stencilBack = {};

    GPUStencilValue stencilReadMask = 0xFFFFFFFF;
    GPUStencilValue stencilWriteMask = 0xFFFFFFFF;

    GPUDepthBias depthBias = 0;
    float depthBiasSlopeScale = 0;
    float depthBiasClamp = 0;
};

GPUDepthStencilState 拥有以下成员,描述 GPURenderPipeline 如何影响渲染通道的 depthStencilAttachment

format类型为 GPUTextureFormat

GPURenderPipeline 可兼容的 depthStencilAttachmentformat

depthWriteEnabled类型为 boolean

指示该 GPURenderPipeline 是否可以修改 depthStencilAttachment 的深度值。

depthCompare类型为 GPUCompareFunction

用于将片元深度与 depthStencilAttachment 深度值进行比较的操作。

stencilFront类型为 GPUStencilFaceState,默认值为 {}

定义前面图元的模板比较和操作方式。

stencilBack类型为 GPUStencilFaceState,默认值为 {}

定义背面图元的模板比较和操作方式。

stencilReadMask类型为 GPUStencilValue,默认值 0xFFFFFFFF

控制执行模板测试时读取 depthStencilAttachment 模板值哪些位的位掩码。

stencilWriteMask类型为 GPUStencilValue,默认值 0xFFFFFFFF

控制执行模板操作时写入 depthStencilAttachment 模板值哪些位的位掩码。

depthBias类型为 GPUDepthBias,默认值 0

加到每个三角形片元的恒定深度偏移。详见 带偏移的片元深度(biased fragment depth)

depthBiasSlopeScale类型为 float,默认值 0

随三角形片元斜率变化的深度偏移。详见 带偏移的片元深度(biased fragment depth)

depthBiasClamp类型为 float,默认值 0

三角形片元的最大深度偏移。详见 带偏移的片元深度(biased fragment depth)

注意: depthBiasdepthBiasSlopeScaledepthBiasClamp"point-list""line-list""line-strip" 图元无效,且必须为 0。

带偏移的片元深度(biased fragment depth) 指的是对使用 GPUDepthStencilState state 绘制时写入 depthStencilAttachment attachment 的片元,计算方式如下(队列时间线步骤):
  1. format = attachment.view.format

  2. rformat 转为 32 位 float 后大于 0 的最小正可表示值。

  3. maxDepthSlope 为片元深度值的水平和垂直斜率中的最大值。

  4. formatunorm 格式:

    1. bias(float)state.depthBias * r + state.depthBiasSlopeScale * maxDepthSlope

  5. 否则,如 formatfloat 格式:

    1. bias(float)state.depthBias * 2^(exp(primitive 最大深度) - r) + state.depthBiasSlopeScale * maxDepthSlope

  6. state.depthBiasClamp > 0

    1. bias 设为 min(state.depthBiasClamp, bias)

  7. 否则如 state.depthBiasClamp < 0

    1. bias 设为 max(state.depthBiasClamp, bias)

  8. state.depthBias0state.depthBiasSlopeScale0

    1. 将片元深度值设为 片元深度值 + bias

验证 GPUDepthStencilState(validating GPUDepthStencilState)(descriptor, topology)

参数:

设备时间线步骤:

  1. 当且仅当下列所有条件都满足时返回 true

dictionary GPUStencilFaceState {
    GPUCompareFunction compare = "always";
    GPUStencilOperation failOp = "keep";
    GPUStencilOperation depthFailOp = "keep";
    GPUStencilOperation passOp = "keep";
};

GPUStencilFaceState 拥有以下成员,描述模板比较和操作的方式:

compare类型为 GPUCompareFunction,默认值为 "always"

在用 [[stencilReference]] 的值与片元 depthStencilAttachment 的模板值进行测试时使用的 GPUCompareFunction

failOp类型为 GPUStencilOperation,默认值为 "keep"

如片元模板比较测试(由 compare 描述)失败,则执行的 GPUStencilOperation 操作。

depthFailOp类型为 GPUStencilOperation,默认值为 "keep"

如片元深度比较(由 depthCompare 描述)失败,则执行的 GPUStencilOperation 操作。

passOp类型为 GPUStencilOperation,默认值为 "keep"

如片元模板比较测试(由 compare 描述)通过,则执行的 GPUStencilOperation 操作。

enum GPUStencilOperation {
    "keep",
    "zero",
    "replace",
    "invert",
    "increment-clamp",
    "decrement-clamp",
    "increment-wrap",
    "decrement-wrap",
};

GPUStencilOperation 定义了以下操作:

"keep"

保持当前模板值。

"zero"

将模板值设为 0

"replace"

将模板值设为 [[stencilReference]]

"invert"

对当前模板值取按位非。

"increment-clamp"

将当前模板值加一,并钳制到 depthStencilAttachment 模板分量的最大可表示值。

"decrement-clamp"

将当前模板值减一,并钳制到 0

"increment-wrap"

将当前模板值加一,如超过 depthStencilAttachment 模板分量最大可表示值,则回绕为 0。

"decrement-wrap"

将当前模板值减一,如小于 0,则回绕为 depthStencilAttachment 模板分量最大可表示值。

10.3.7. 顶点状态(Vertex State)

enum GPUIndexFormat {
    "uint16",
    "uint32",
};

索引格式(index format)决定了缓冲区中索引值的数据类型,并且在用于 strip 图元拓扑("line-strip""triangle-strip")时,也指定了图元重启值(primitive restart value)。图元重启值(primitive restart value) 表示哪个索引值意味着应当新建一个图元,而不是继续用先前的索引顶点构建三角带。

GPUPrimitiveState 指定 strip 图元拓扑时,若用于带索引绘制,必须指定 stripIndexFormat, 以便在管线创建时就明确将使用的图元重启值。 指定 list 图元拓扑的 GPUPrimitiveState 在索引渲染时会使用 setIndexBuffer() 传递的索引格式。

索引格式(Index format) 字节数(Byte size) 图元重启值(Primitive restart value)
"uint16" 2 0xFFFF
"uint32" 4 0xFFFFFFFF
10.3.7.1. 顶点格式(Vertex Formats)

GPUVertexFormat 指定顶点属性的数据格式,决定如何从顶点缓冲区读取数据并传递到着色器。格式名表明了分量的顺序、每个分量的比特数,以及该分量的顶点数据类型

每种顶点数据类型(vertex data type) 都可以映射到任意同基类型的WGSL 标量类型,无论每个分量有多少位:

顶点格式前缀(Vertex format prefix) 顶点数据类型(Vertex data type) 兼容 WGSL 类型(Compatible WGSL types)
uint unsigned int(无符号整数) u32
sint signed int(有符号整数) i32
unorm unsigned normalized(无符号归一化) f16, f32
snorm signed normalized(有符号归一化)
float floating point(浮点数)

多分量格式的“x”后面的数字表示分量数量。顶点格式和着色器类型的分量数不一致是允许的,多余分量会被丢弃,不足分量则用默认值补齐。

一个顶点属性,格式为 "unorm8x2" ,字节值为 [0x7F, 0xFF] ,可在着色器中通过如下类型访问:
着色器类型(Shader type) 着色器值(Shader value)
f16 0.5h
f32 0.5f
vec2<f16> vec2(0.5h, 1.0h)
vec2<f32> vec2(0.5f, 1.0f)
vec3<f16> vec2(0.5h, 1.0h, 0.0h)
vec3<f32> vec2(0.5f, 1.0f, 0.0f)
vec4<f16> vec2(0.5h, 1.0h, 0.0h, 1.0h)
vec4<f32> vec2(0.5f, 1.0f, 0.0f, 1.0f)

关于顶点格式如何在着色器中暴露,详见 § 23.2.2 顶点处理

enum GPUVertexFormat {
    "uint8",
    "uint8x2",
    "uint8x4",
    "sint8",
    "sint8x2",
    "sint8x4",
    "unorm8",
    "unorm8x2",
    "unorm8x4",
    "snorm8",
    "snorm8x2",
    "snorm8x4",
    "uint16",
    "uint16x2",
    "uint16x4",
    "sint16",
    "sint16x2",
    "sint16x4",
    "unorm16",
    "unorm16x2",
    "unorm16x4",
    "snorm16",
    "snorm16x2",
    "snorm16x4",
    "float16",
    "float16x2",
    "float16x4",
    "float32",
    "float32x2",
    "float32x3",
    "float32x4",
    "uint32",
    "uint32x2",
    "uint32x3",
    "uint32x4",
    "sint32",
    "sint32x2",
    "sint32x3",
    "sint32x4",
    "unorm10-10-10-2",
    "unorm8x4-bgra",
};
顶点格式(Vertex format) 数据类型(Data type) 分量数(Components) 字节数(byteSize) 示例 WGSL 类型(Example WGSL type)
"uint8" 无符号整数(unsigned int) 1 1 u32
"uint8x2" 无符号整数 2 2 vec2<u32>
"uint8x4" 无符号整数 4 4 vec4<u32>
"sint8" 有符号整数(signed int) 1 1 i32
"sint8x2" 有符号整数 2 2 vec2<i32>
"sint8x4" 有符号整数 4 4 vec4<i32>
"unorm8" 无符号归一化(unsigned normalized) 1 1 f32
"unorm8x2" 无符号归一化 2 2 vec2<f32>
"unorm8x4" 无符号归一化 4 4 vec4<f32>
"snorm8" 有符号归一化(signed normalized) 1 1 f32
"snorm8x2" 有符号归一化 2 2 vec2<f32>
"snorm8x4" 有符号归一化 4 4 vec4<f32>
"uint16" 无符号整数 1 2 u32
"uint16x2" 无符号整数 2 4 vec2<u32>
"uint16x4" 无符号整数 4 8 vec4<u32>
"sint16" 有符号整数 1 2 i32
"sint16x2" 有符号整数 2 4 vec2<i32>
"sint16x4" 有符号整数 4 8 vec4<i32>
"unorm16" 无符号归一化 1 2 f32
"unorm16x2" 无符号归一化 2 4 vec2<f32>
"unorm16x4" 无符号归一化 4 8 vec4<f32>
"snorm16" 有符号归一化 1 2 f32
"snorm16x2" 有符号归一化 2 4 vec2<f32>
"snorm16x4" 有符号归一化 4 8 vec4<f32>
"float16" 浮点数(float) 1 2 f32
"float16x2" 浮点数 2 4 vec2<f16>
"float16x4" 浮点数 4 8 vec4<f16>
"float32" 浮点数 1 4 f32
"float32x2" 浮点数 2 8 vec2<f32>
"float32x3" 浮点数 3 12 vec3<f32>
"float32x4" 浮点数 4 16 vec4<f32>
"uint32" 无符号整数 1 4 u32
"uint32x2" 无符号整数 2 8 vec2<u32>
"uint32x3" 无符号整数 3 12 vec3<u32>
"uint32x4" 无符号整数 4 16 vec4<u32>
"sint32" 有符号整数 1 4 i32
"sint32x2" 有符号整数 2 8 vec2<i32>
"sint32x3" 有符号整数 3 12 vec3<i32>
"sint32x4" 有符号整数 4 16 vec4<i32>
"unorm10-10-10-2" 无符号归一化 4 4 vec4<f32>
"unorm8x4-bgra" 无符号归一化 4 4 vec4<f32>
enum GPUVertexStepMode {
    "vertex",
    "instance",
};

步进模式(step mode)配置了如何根据当前的顶点索引或实例索引计算顶点缓冲区数据的地址:

"vertex"

每个顶点地址按 arrayStride 递增, 在不同实例之间重置。

"instance"

每个实例地址按 arrayStride 递增。

dictionary GPUVertexState
     : GPUProgrammableStage {
sequence<GPUVertexBufferLayout?> buffers = [];
};
buffers类型为 sequence<GPUVertexBufferLayout?>,默认值为 []

一个 GPUVertexBufferLayout 列表,定义了本管线所用顶点缓冲区中顶点属性数据的布局。

顶点缓冲区(vertex buffer)在概念上是对缓冲区内存的视图,把它看作“结构体数组”。arrayStride 是该数组中每个元素(结构)之间的字节跨度。每个顶点缓冲区的元素就像一个结构体,其内存布局由 attributes 定义,attributes 描述了结构体成员。

每个 GPUVertexAttribute 描述了该成员的 format 以及在结构体中的 offset 字节偏移量。

每个 attribute 在顶点着色器中表现为一个独立输入,绑定一个数值类型的 location,由 shaderLocation 指定。每个 location 在 GPUVertexState 内必须唯一。

dictionary GPUVertexBufferLayout {
    required GPUSize64 arrayStride;
    GPUVertexStepMode stepMode = "vertex";
    required sequence<GPUVertexAttribute> attributes;
};
arrayStride类型为 GPUSize64

该数组元素之间的字节跨度。

stepMode类型为 GPUVertexStepMode,默认值为 "vertex"

该数组每个元素是按顶点还是按实例计(per-vertex 或 per-instance)。

attributes类型为 sequence<GPUVertexAttribute>

定义每个元素内各顶点属性(结构体成员)的数组。

dictionary GPUVertexAttribute {
    required GPUVertexFormat format;
    required GPUSize64 offset;
    required GPUIndex32 shaderLocation;
};
format类型为 GPUVertexFormat

该属性的 GPUVertexFormat

offset类型为 GPUSize64

从该结构体起始到该属性数据的字节偏移量。

shaderLocation类型为 GPUIndex32

该属性关联的数值 location,需与 "@location" 属性vertex.module 中对应。

验证 GPUVertexBufferLayout(validating GPUVertexBufferLayout)(device, descriptor)

参数:

设备时间线步骤:

  1. 当且仅当下列所有条件都满足时,返回 true

验证 GPUVertexState(validating GPUVertexState)(device, descriptor, layout)

参数:

设备时间线步骤:

  1. entryPoint = 获取入口点(VERTEX, descriptor)。

  2. 断言(Assert) entryPoint 不为 null

  3. 以下所有要求 必须满足:

    1. 验证 GPUProgrammableStage(VERTEX, descriptor, layout, device) 必须成功。

    2. descriptor.buffers.size 必须device.[[device]].[[limits]].maxVertexBuffers

    3. 列表 descriptor.buffers 中的每个 vertexBuffer 描述符 必须通过 验证 GPUVertexBufferLayout(device, vertexBuffer)。

    4. 所有 vertexBuffer.attributes.size 之和, 必须 ≤ device.[[device]].[[limits]].maxVertexAttributes

    5. 对于 entryPoint 静态使用的每个顶点属性声明(位置 location,类型 T), 必须存在且仅存在一组 (i, j) 使得 descriptor.buffers[i]? .attributes[j] .shaderLocation == location

      attrib 为该 GPUVertexAttribute

    6. T 必须attrib.format顶点数据类型(vertex data type)兼容:

      "unorm"、"snorm" 或 "float"

      T 必须是 f32vecN<f32>

      "uint"

      T 必须是 u32vecN<u32>

      "sint"

      T 必须是 i32vecN<i32>

11. 复制(Copies)

11.1. 缓冲区复制(Buffer Copies)

缓冲区复制操作基于原始字节执行。

WebGPU 提供了“缓冲式” GPUCommandEncoder 命令:

以及“即时” GPUQueue 操作:

11.2. 纹素复制(Texel Copies)

纹素复制(Texel copy)操作针对的是纹理/图像数据,而不是字节。

WebGPU 提供“缓冲式” GPUCommandEncoder 命令:

以及“即时” GPUQueue 操作:

在纹素复制过程中,纹素会以等价纹素表示(equivalent texel representation)被复制。 纹素复制仅保证源中的有效、正常数字值在目标中具有相同的数值,但可能不会保留以下值的位表示:

注意: 复制操作可能通过 WGSL 着色器实现,所以可能会观察到任何文档中描述的 WGSL 浮点行为

下列定义被这些方法所用:

11.2.1. GPUTexelCopyBufferLayout

"GPUTexelCopyBufferLayout" 描述了在“缓冲区”字节(GPUBufferAllowSharedBufferSource) 中的纹素在“纹素复制”操作中的“布局”。

dictionary GPUTexelCopyBufferLayout {
    GPUSize64 offset = 0;
    GPUSize32 bytesPerRow;
    GPUSize32 rowsPerImage;
};

纹素图像(texel image)由一行或多行纹素块组成,这里称为纹素块行(texel block row)。每个texel imagetexel block row数量相同,且所有纹素块的GPUTextureFormat一致。

GPUTexelCopyBufferLayout 描述了线性内存中多个texel image的布局。当在textureGPUBuffer之间复制数据,或通过GPUQueue写入texture时会用到。

在字节数组与纹理之间的复制操作总是以整个 纹素块为单位。无法只更新一个纹素块的一部分。

纹素块在每个texel block row中在内存中紧密排列,每个相邻的纹素块之间无填充,包括对深度或模板纹理特定 aspect 的复制:模板值以字节数组紧密排列,深度值以相应类型("depth16unorm" 或 "depth32float")数组紧密排列。

offset类型为 GPUSize64,默认值为 0

从纹素数据源(如 GPUTexelCopyBufferInfo.buffer) 起始到纹素数据起始位置的字节偏移量。

bytesPerRow类型为 GPUSize32

每个 纹素块行 起始到下一个 纹素块行 起始的字节跨度。

若存在多个 纹素块行(即复制高度或深度大于一个块)时为必填项。

rowsPerImage类型为 GPUSize32

每个 纹素图像 包含的 纹素块行数量。 rowsPerImage × bytesPerRow 即为每个 纹素图像 起始到下一个 纹素图像 起始的字节跨度。

若存在多个 纹素图像(即复制深度大于 1)时为必填项。

11.2.2. GPUTexelCopyBufferInfo

"GPUTexelCopyBufferInfo" 描述了作为“缓冲区”源或目标的 GPUBufferGPUTexelCopyBufferLayout 的“参数信息”,用于“纹素复制”操作。 它与 copySize 一起描述了 GPUBuffer 中某一区域纹素的内存布局。

dictionary GPUTexelCopyBufferInfo
         : GPUTexelCopyBufferLayout {
    required GPUBuffer buffer;
};
buffer类型为 GPUBuffer

根据所调用的方法,该缓冲区要么包含要被复制的纹素数据,要么用于存储被复制的纹素数据。

验证 GPUTexelCopyBufferInfo(validating GPUTexelCopyBufferInfo)

参数:

返回: boolean

设备时间线步骤:

  1. 当且仅当下列所有条件都满足时返回 true

11.2.3. GPUTexelCopyTextureInfo

"GPUTexelCopyTextureInfo" 描述了作为“纹理”源或目标的 GPUTexture 等对象在“纹素复制”操作中的“参数信息”。 它和 copySize 一起描述了纹理的一个子区域(跨越同一 mip-map 层级的一个或多个连续纹理子资源)。

dictionary GPUTexelCopyTextureInfo {
    required GPUTexture texture;
    GPUIntegerCoordinate mipLevel = 0;
    GPUOrigin3D origin = {};
    GPUTextureAspect aspect = "all";
};
texture类型为 GPUTexture

要复制到或从其复制的纹理。

mipLevel类型为 GPUIntegerCoordinate,默认值为 0

要复制到或从其复制的 texture 的 mip-map 层级。

origin类型为 GPUOrigin3D,默认值为 {}

定义复制的起点——要复制到或从其复制的纹理子区域的最小角落。与 copySize 一起,定义完整的复制子区域。

aspect类型为 GPUTextureAspect,默认值为 "all"

定义要复制到/从其复制的 texture 的哪些 aspect。

纹理复制子区域(texture copy sub-region),对于 GPUTexelCopyTextureInfo copyTexture 的深度切片或数组层 index,按如下步骤确定:
  1. texture = copyTexture.texture

  2. 如果 texture.dimension 为:

    1d
    1. 断言 index0

    2. depthSliceOrLayertexture

    2d

    depthSliceOrLayertexture 的 array layer index

    3d

    depthSliceOrLayertexture 的 depth slice index

  3. textureMipdepthSliceOrLayer 的 mip 级别 copyTexture.mipLevel

  4. 返回 textureMipcopyTexture.aspect aspect。

纹素块字节偏移量(texel block byte offset),对于由 GPUTexelCopyBufferLayout bufferLayout 描述的数据,纹素块 xyGPUTexture texture 的深度切片或数组层 z,按如下步骤确定:
  1. blockBytestexture.format纹素块复制脚印

  2. imageOffset = (z × bufferLayout.rowsPerImage × bufferLayout.bytesPerRow) + bufferLayout.offset

  3. rowOffset = (y × bufferLayout.bytesPerRow) + imageOffset

  4. blockOffset = (x × blockBytes) + rowOffset

  5. 返回 blockOffset

验证 GPUTexelCopyTextureInfo(validating GPUTexelCopyTextureInfo)(texelCopyTextureInfo, copySize)

参数:

返回: boolean

设备时间线步骤:

  1. blockWidthtexelCopyTextureInfo.texture.format纹素块宽度

  2. blockHeighttexelCopyTextureInfo.texture.format纹素块高度

  3. 当且仅当下列所有条件满足时返回 true

验证纹理缓冲区复制(validating texture buffer copy)(texelCopyTextureInfo, bufferLayout, dataLength, copySize, textureUsage, aligned)

参数:

返回: boolean

设备时间线步骤:

  1. texture = texelCopyTextureInfo.texture

  2. aspectSpecificFormat = texture.format

  3. offsetAlignment = texture.format纹素块复制脚印

  4. 当且仅当下列所有条件满足时返回 true

    1. 验证 GPUTexelCopyTextureInfo(texelCopyTextureInfo, copySize) 返回 true

    2. texture.sampleCount 为 1。

    3. texture.usage 包含 textureUsage

    4. 如果 texture.format深度或模板格式

      1. texelCopyTextureInfo.aspect 必须指定 texture.format 的单一 aspect。

      2. 如果 textureUsage 是:

        COPY_SRC

        该 aspect 必须根据 § 26.1.2 深度模板格式 是有效的纹素复制源。

        COPY_DST

        该 aspect 必须根据 § 26.1.2 深度模板格式 是有效的纹素复制目标。

      3. 根据 § 26.1.2 深度模板格式,将 aspectSpecificFormat 设为aspect-specific format

      4. offsetAlignment 设为 4。

    5. 如果 alignedtrue

      1. bufferLayout.offset 必须是 offsetAlignment 的倍数。

    6. 验证线性纹理数据(bufferLayout, dataLength, aspectSpecificFormat, copySize) 成功。

11.2.4. GPUCopyExternalImageDestInfo

WebGPU 纹理保存的是原始数值数据,并没有附带描述颜色的语义元数据。 然而,copyExternalImageToTexture() 复制自带有颜色描述信息的源。

"GPUCopyExternalImageDestInfo" 描述了 "copyExternalImageToTexture()" 操作中 "目标(dest)" 的 "参数信息(info)"。 它是一个 GPUTexelCopyTextureInfo,但额外带有色彩空间/编码和 alpha 预乘元数据,以便在复制过程中保留语义色彩数据。 这些元数据仅影响复制操作的语义,不影响目标纹理对象本身的状态或语义。

dictionary GPUCopyExternalImageDestInfo
         : GPUTexelCopyTextureInfo {
    PredefinedColorSpace colorSpace = "srgb";
    boolean premultipliedAlpha = false;
};
colorSpace类型为 PredefinedColorSpace,默认值为 "srgb"

描述写入目标纹理时使用的色彩空间和编码。

可能导致超出 [0, 1] 范围的值被写入目标纹理(如果其格式可以表示这些值)。 否则,结果会被裁剪到目标纹理格式的允许范围内。

注意: 如果 colorSpace 与源图像一致,则可能无需进行转换。详见 § 3.10.2 色彩空间转换省略

premultipliedAlpha类型为 boolean,默认值为 false

描述写入目标纹理时,RGB 通道是否应由 alpha 通道进行预乘。

如果此选项为 true,且 source 也为预乘,则即使 RGB 分量超过其对应的 alpha 分量,也必须保留源 RGB 值。

注意: 如果 premultipliedAlpha 与源图像一致,则可能无需进行转换。详见 § 3.10.2 色彩空间转换省略

11.2.5. GPUCopyExternalImageSourceInfo

"GPUCopyExternalImageSourceInfo" 描述了 "copyExternalImageToTexture()" 操作中 "源(source)" 的 "参数信息(info)"。

typedef (ImageBitmap or
         ImageData or
         HTMLImageElement or
         HTMLVideoElement or
         VideoFrame or
         HTMLCanvasElement or
         OffscreenCanvas) GPUCopyExternalImageSource;

dictionary GPUCopyExternalImageSourceInfo {
    required GPUCopyExternalImageSource source;
    GPUOrigin2D origin = {};
    boolean flipY = false;
};

GPUCopyExternalImageSourceInfo 有如下成员:

source类型为 GPUCopyExternalImageSource

纹素复制的源。 复制源数据会在调用 copyExternalImageToTexture() 时被捕获。源尺寸由外部源尺寸表给出。

origin类型为 GPUOrigin2D,默认值为 {}

定义复制起点——要复制的源子区域的最小(左上)角。与 copySize 一起定义完整的复制区域。

flipY类型为 boolean,默认值为 false

描述源图像是否需要垂直翻转。

如果该选项为 true,则复制时会进行垂直翻转:源区域的最后一行被复制到目标区域的第一行,依此类推。 origin 仍然以源图像的左上角为原点,向下递增。

当外部源被用来创建或复制到纹理时,外部源尺寸(external source dimensions) 由源类型决定,见下表:

外部源类型(External Source type) 尺寸(Dimensions)
ImageBitmap ImageBitmap.width, ImageBitmap.height
HTMLImageElement HTMLImageElement.naturalWidth, HTMLImageElement.naturalHeight
HTMLVideoElement 帧固有宽度(intrinsic width of the frame), 帧固有高度(intrinsic height of the frame)
VideoFrame VideoFrame.displayWidth, VideoFrame.displayHeight
ImageData ImageData.width, ImageData.height
HTMLCanvasElementOffscreenCanvas (使用 CanvasRenderingContext2DGPUCanvasContextHTMLCanvasElement.width, HTMLCanvasElement.height
HTMLCanvasElementOffscreenCanvas (使用 WebGLRenderingContextBaseWebGLRenderingContextBase.drawingBufferWidth, WebGLRenderingContextBase.drawingBufferHeight
HTMLCanvasElementOffscreenCanvas (使用 ImageBitmapRenderingContextImageBitmapRenderingContext 的内部输出 bitmap ImageBitmap.width, ImageBitmap.height

11.2.6. 子程序(Subroutines)

GPUTexelCopyTextureInfo 物理子资源尺寸(physical subresource size)

参数:

返回: GPUExtent3D

GPUTexelCopyTextureInfo 物理子资源尺寸的计算如下:

widthheightdepthOrArrayLayers 分别为 texelCopyTextureInfo.texture 子资源(subresource)mipmap 级别 texelCopyTextureInfo.mipLevel物理 mip 层特定纹理范围的宽度、高度和深度。

验证线性纹理数据(validating linear texture data)(layout, byteSize, format, copyExtent)

参数:

GPUTexelCopyBufferLayout layout

线性纹理数据的布局。

GPUSize64 byteSize

线性数据的总字节数。

GPUTextureFormat format

纹理的格式。

GPUExtent3D copyExtent

要复制的纹理范围。

设备时间线步骤:

  1. 令:

  2. 若未满足下述输入校验要求则失败:

  3. 令:

    注意: 这些默认值没有实际影响,因为总是被乘以 0。

  4. requiredBytesInCopy = 0。

  5. copyExtent.depthOrArrayLayers > 0:

    1. requiredBytesInCopy 增加 bytesPerRow × rowsPerImage × (copyExtent.depthOrArrayLayers − 1)。

    2. 如果 heightInBlocks > 0:

      1. requiredBytesInCopy 增加 bytesPerRow × (heightInBlocks − 1) + bytesInLastRow

  6. 若未满足下述条件则失败:

    • 布局应在线性数据范围内: layout.offset + requiredBytesInCopybyteSize

验证纹理复制范围(validating texture copy range)

参数:

GPUTexelCopyTextureInfo texelCopyTextureInfo

要复制到的纹理子资源及复制起点。

GPUExtent3D copySize

纹理的尺寸。

设备时间线步骤:

  1. blockWidth = texelCopyTextureInfo.texture.format纹素块宽度

  2. blockHeight = texelCopyTextureInfo.texture.format纹素块高度

  3. subresourceSize = GPUTexelCopyTextureInfo 物理子资源尺寸

  4. 返回下述所有条件是否满足:

    注意: 纹理复制范围针对 物理(向上取整)尺寸进行校验(对于压缩格式),允许复制操作访问未完全位于纹理内的纹理块。

两个 GPUTextureFormat format1format2 当且仅当以下条件满足时为可复制兼容(copy-compatible)
纹理复制的子资源集合(set of subresources for texture copy)(texelCopyTextureInfo, copySize) 是 texture = texelCopyTextureInfo.texture 的子资源子集,满足如下条件的每个子资源 s

12. 命令缓冲区(Command Buffers)

命令缓冲区是预先记录的GPU 命令队列时间轴步骤块)的列表,可以提交到 GPUQueue 执行。 每个 GPU 命令 表示要在 队列时间轴 上执行的任务,如设置状态、绘制、资源拷贝等。

一个 GPUCommandBuffer 只能提交一次,提交后即被失效。 若需要跨多次提交复用渲染命令,请使用 GPURenderBundle

12.1. GPUCommandBuffer

[Exposed=(Window, Worker), SecureContext]
interface GPUCommandBuffer {
};
GPUCommandBuffer includes GPUObjectBase;

GPUCommandBuffer 具有以下设备时间轴属性

[[command_list]] ,类型为 list<GPU 命令>,只读

一个 列表,包含此命令缓冲区提交时将在队列时间轴上执行的 GPU 命令

[[renderState]] ,类型为 RenderState,初始值为 null

任何渲染通道命令正在执行时所使用的当前状态。

12.1.1. 命令缓冲区创建(Command Buffer Creation)

dictionary GPUCommandBufferDescriptor
 : GPUObjectDescriptorBase {
};

13. 命令编码(Command Encoding)

13.1. GPUCommandsMixin

GPUCommandsMixin 定义了所有编码命令接口的通用状态。它没有方法。

interface mixin GPUCommandsMixin {
};

GPUCommandsMixin 具有以下设备时间轴属性

[[state]] ,类型为 encoder state,初始值为 "open"

编码器的当前状态。

[[commands]] ,类型为 list<GPU 命令>,初始值为 []

一个 列表,包含当包含这些命令的 GPUCommandBuffer 被提交时将在队列时间轴上执行的 GPU 命令

编码器状态(encoder state) 可能为以下之一:

"open"

编码器可用于编码新命令。

"locked"

编码器无法使用,因为它被子编码器锁定:它是一个 GPUCommandEncoder,且有一个 GPURenderPassEncoderGPUComputePassEncoder 处于活动状态。 当通道结束时,编码器重新变为“open”状态。

在此状态下发出的任何命令都会使编码器失效

"ended"

编码器已结束,无法再编码新命令。

在此状态下发出的任何命令都会产生验证错误

验证编码器状态(Validate the encoder state),针对 GPUCommandsMixin encoder,执行以下设备时间轴步骤:
  1. 如果 encoder.[[state]] 为:

    "open"

    返回 true

    "locked"

    使 encoder 失效 并返回 false

    "ended"

    产生验证错误,并返回 false

入队命令(Enqueue a command)GPUCommandsMixin encoder,该命令将执行 GPU 命令 command 的步骤,执行以下设备时间轴步骤:
  1. 追加 commandencoder[[commands]]

  2. command 作为 GPUCommandBuffer 的一部分执行时:

    1. 执行 command 的步骤。

13.2. GPUCommandEncoder

[Exposed=(Window, Worker), SecureContext]
interface GPUCommandEncoder {
    GPURenderPassEncoder beginRenderPass(GPURenderPassDescriptor descriptor);
    GPUComputePassEncoder beginComputePass(optional GPUComputePassDescriptor descriptor = {});

    undefined copyBufferToBuffer(
        GPUBuffer source,
        GPUBuffer destination,
        optional GPUSize64 size);
    undefined copyBufferToBuffer(
        GPUBuffer source,
        GPUSize64 sourceOffset,
        GPUBuffer destination,
        GPUSize64 destinationOffset,
        optional GPUSize64 size);

    undefined copyBufferToTexture(
        GPUTexelCopyBufferInfo source,
        GPUTexelCopyTextureInfo destination,
        GPUExtent3D copySize);

    undefined copyTextureToBuffer(
        GPUTexelCopyTextureInfo source,
        GPUTexelCopyBufferInfo destination,
        GPUExtent3D copySize);

    undefined copyTextureToTexture(
        GPUTexelCopyTextureInfo source,
        GPUTexelCopyTextureInfo destination,
        GPUExtent3D copySize);

    undefined clearBuffer(
        GPUBuffer buffer,
        optional GPUSize64 offset = 0,
        optional GPUSize64 size);

    undefined resolveQuerySet(
        GPUQuerySet querySet,
        GPUSize32 firstQuery,
        GPUSize32 queryCount,
        GPUBuffer destination,
        GPUSize64 destinationOffset);

    GPUCommandBuffer finish(optional GPUCommandBufferDescriptor descriptor = {});
};
GPUCommandEncoder includes GPUObjectBase;
GPUCommandEncoder includes GPUCommandsMixin;
GPUCommandEncoder includes GPUDebugCommandsMixin;

13.2.1. 命令编码器创建(Command Encoder Creation)

dictionary GPUCommandEncoderDescriptor
 : GPUObjectDescriptorBase {
};
createCommandEncoder(descriptor)

创建一个 GPUCommandEncoder

调用者: GPUDevice this.

参数:

GPUDevice.createCommandEncoder(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPUCommandEncoderDescriptor 要创建的 GPUCommandEncoder 的描述信息。

返回: GPUCommandEncoder

内容时间轴(Content timeline)步骤:

  1. e! 创建一个新的 WebGPU 对象(this, GPUCommandEncoder, descriptor)。

  2. this设备时间轴上执行 初始化步骤

  3. 返回 e

设备时间轴 初始化步骤
  1. 如未满足以下任一条件,生成验证错误使 e 失效 并返回。

创建一个 GPUCommandEncoder, 编码清空缓冲区的命令,完成编码器生成 GPUCommandBuffer, 并提交到 GPUQueue
const commandEncoder = gpuDevice.createCommandEncoder();
commandEncoder.clearBuffer(buffer);
const commandBuffer = commandEncoder.finish();
gpuDevice.queue.submit([commandBuffer]);

13.3. 通道编码(Pass Encoding)

beginRenderPass(descriptor)

开始编码由 descriptor 描述的渲染通道。

调用者: GPUCommandEncoder this

参数:

GPUCommandEncoder.beginRenderPass(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPURenderPassDescriptor 要创建的 GPURenderPassEncoder 的描述信息。

返回: GPURenderPassEncoder

内容时间轴(Content timeline)步骤:

  1. descriptor.colorAttachments 中每一个非 nullcolorAttachment

    1. 如果 colorAttachment.clearValue提供

      1. ? 校验 GPUColor 形状 (colorAttachment.clearValue)。

  2. pass 为一个新的 GPURenderPassEncoder 对象。

  3. this设备时间轴上执行 初始化步骤

  4. 返回 pass

设备时间轴 初始化步骤
  1. 验证编码器状态(Validate the encoder state)this。 如果返回 false,使 pass 失效并返回。

  2. 设置 this.[[state]] 为 "locked"。

  3. attachmentRegions 为 [纹理子资源depthSlice?] 对的列表,初始为空。每个对描述要渲染到的纹理区域,对于 "3d" 纹理仅包含一个 depth slice。

  4. descriptor.colorAttachments 中每一个非 nullcolorAttachment

    1. 将 [colorAttachment.view, colorAttachment.depthSlice ?? null] 添加到 attachmentRegions

    2. 如果 colorAttachment.resolveTarget 不为 null

      1. 将 [colorAttachment.resolveTarget, undefined] 添加到 attachmentRegions

  5. 如未满足以下任一要求,使 pass 失效并返回。

    • descriptor 必须符合设备 this.[[device]]有效用法(Valid Usage) 规则。

    • attachmentRegions 中的纹理区域集合必须两两不相交,即任何两个区域都不能重叠。

  6. attachmentRegions 中的每个纹理子资源attachment 用法添加到 pass.[[usage scope]]

  7. depthStencilAttachmentdescriptor.depthStencilAttachment

  8. 如果 depthStencilAttachment 不为 null

    1. depthStencilViewdepthStencilAttachment.view

    2. depthStencilViewdepth 子资源(如有)以 attachment-read 用法(若 depthStencilAttachment.depthReadOnly 为 true),否则以 attachment 用法,添加到 pass.[[usage scope]]

    3. depthStencilViewstencil 子资源(如有)以 attachment-read 用法(若 depthStencilAttachment.stencilReadOnly 为 true),否则以 attachment 用法,添加到 pass.[[usage scope]]

    4. 设置 pass.[[depthReadOnly]]depthStencilAttachment.depthReadOnly

    5. 设置 pass.[[stencilReadOnly]]depthStencilAttachment.stencilReadOnly

  9. 设置 pass.[[layout]]derive render targets layout from pass(descriptor)。

  10. 如果 descriptor.timestampWrites提供

    1. timestampWritesdescriptor.timestampWrites

    2. 如果 timestampWrites.beginningOfPassWriteIndex提供,则追加一个包含以下步骤的GPU 命令this.[[commands]]

      1. 在通道命令开始执行前,将当前队列时间戳写入 timestampWrites.beginningOfPassWriteIndex 索引的 timestampWrites.querySet

    3. 如果 timestampWrites.endOfPassWriteIndex提供,则设置 pass.[[endTimestampWrite]] 为一个包含如下步骤的GPU 命令

      1. 在通道命令执行完后,将当前队列时间戳写入 timestampWrites.endOfPassWriteIndex 索引的 timestampWrites.querySet

  11. 设置 pass.[[drawCount]] 为 0。

  12. 设置 pass.[[maxDrawCount]]descriptor.maxDrawCount

  13. 设置 pass.[[maxDrawCount]]descriptor.maxDrawCount

  14. 入队命令(Enqueue a command)this,执行时在队列时间轴上执行后续步骤。

队列时间轴 步骤:
  1. 令当前正在执行的 [[renderState]]GPUCommandBuffer 成为一个新的 RenderState

  2. 设置 [[renderState]].[[colorAttachments]]descriptor.colorAttachments

  3. 设置 [[renderState]].[[depthStencilAttachment]]descriptor.depthStencilAttachment

  4. descriptor.colorAttachments 中每一个非 nullcolorAttachment

    1. colorViewcolorAttachment.view

    2. 如果 colorView.[[descriptor]].dimension 为:

      "3d"

      colorSubregioncolorAttachment.depthSlicecolorView

      否则

      colorSubregioncolorView

    3. 如果 colorAttachment.loadOp 为:

      "load"

      确保 colorSubregion 的内容被加载到与 colorSubregion 关联的帧缓冲区内存中。

      "clear"

      将与 colorSubregion 关联的帧缓冲区内存的每个texel设置为 colorAttachment.clearValue

  5. 如果 depthStencilAttachment 不为 null

    1. 如果 depthStencilAttachment.depthLoadOp 为:

      提供

      断言 depthStencilAttachment.depthReadOnlytrue,并确保 depthStencilViewdepth 子资源内容被加载到与 depthStencilView 关联的帧缓冲区内存

      "load"

      确保 depthStencilViewdepth 子资源内容被加载到与 depthStencilView 关联的帧缓冲区内存

      "clear"

      将与 depthStencilViewdepth 子资源关联的帧缓冲区内存的每个texel设置为 depthStencilAttachment.depthClearValue

    2. 如果 depthStencilAttachment.stencilLoadOp 为:

      提供

      断言 depthStencilAttachment.stencilReadOnlytrue,并确保 depthStencilViewstencil 子资源内容被加载到与 depthStencilView 关联的帧缓冲区内存

      "load"

      确保 depthStencilViewstencil 子资源内容被加载到与 depthStencilView 关联的帧缓冲区内存

      "clear"

      将与 depthStencilViewstencil 子资源关联的帧缓冲区内存的每个texel设置为 depthStencilAttachment.stencilClearValue

注意: 只读深度-模板(Read-only depth-stencil)附件会被隐式视为采用 "load" 操作。需要只读附件未提供 load op 的验证在 GPURenderPassDepthStencilAttachment 有效用法中进行。

beginComputePass(descriptor)

开始编码由 descriptor 描述的计算通道(compute pass)。

调用者: GPUCommandEncoder this

参数:

GPUCommandEncoder.beginComputePass(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPUComputePassDescriptor

返回: GPUComputePassEncoder

内容时间轴步骤:

  1. pass 为一个新的 GPUComputePassEncoder 对象。

  2. this设备时间轴上执行 初始化步骤

  3. 返回 pass

设备时间轴 初始化步骤
  1. 验证编码器状态(Validate the encoder state)this。 如果返回 false,使 pass 失效并返回。

  2. 设置 this.[[state]] 为 "locked"。

  3. 如未满足以下任一要求,使 pass 失效并返回。

  4. 如果 descriptor.timestampWrites提供

    1. timestampWritesdescriptor.timestampWrites

    2. 如果 timestampWrites.beginningOfPassWriteIndex提供,则追加一个包含以下步骤的GPU 命令this.[[commands]]

      1. 在通道命令开始执行前,将当前队列时间戳写入 timestampWrites.beginningOfPassWriteIndex 索引的 timestampWrites.querySet

    3. 如果 timestampWrites.endOfPassWriteIndex提供,则设置 pass.[[endTimestampWrite]] 为一个包含如下步骤的GPU 命令

      1. 在通道命令执行完后,将当前队列时间戳写入 timestampWrites.endOfPassWriteIndex 索引的 timestampWrites.querySet

13.4. 缓冲区拷贝命令(Buffer Copy Commands)

copyBufferToBuffer() 有两个重载:

copyBufferToBuffer(source, destination, size)

简写,相当于 copyBufferToBuffer(source, 0, destination, 0, size)

copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)

GPUCommandEncoder 编码一个命令, 将数据从一个 GPUBuffer 的子区域复制到另一个 GPUBuffer 的子区域。

调用者: GPUCommandEncoder this

参数:

GPUCommandEncoder.copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size) 方法参数。
参数 类型 可为 null 可选 描述
source GPUBuffer 要拷贝的 GPUBuffer
sourceOffset GPUSize64 源 buffer 的起始偏移(字节)。
destination GPUBuffer 目标 GPUBuffer
destinationOffset GPUSize64 目标 buffer 的写入起始偏移(字节)。
size GPUSize64 要拷贝的字节数。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. 如果 sizeundefined,则设为 source.sizesourceOffset

  3. 如未满足以下任一条件,使 this 失效并返回。

    • source 可与 this 有效共用

    • destination 可与 this 有效共用

    • source.usage 包含 COPY_SRC

    • destination.usage 包含 COPY_DST

    • size 是 4 的倍数。

    • sourceOffset 是 4 的倍数。

    • destinationOffset 是 4 的倍数。

    • source.size ≥ (sourceOffset + size)。

    • destination.size ≥ (destinationOffset + size)。

    • sourcedestination 不是同一个 GPUBuffer

  4. 入队命令(Enqueue a command)this,执行时在队列时间轴上执行后续步骤。

队列时间轴步骤:
  1. sourcesourceOffset 起的 size 字节复制到 destinationdestinationOffset 起始位置。

clearBuffer(buffer, offset, size)

GPUCommandEncoder 编码一个命令,将 GPUBuffer 的子区域填充为零。

调用者: GPUCommandEncoder this

参数:

GPUCommandEncoder.clearBuffer(buffer, offset, size) 方法参数。
参数 类型 可为 null 可选 描述
buffer GPUBuffer 要清零的 GPUBuffer
offset GPUSize64 清零子区域的起始偏移(字节)。
size GPUSize64 要清零的子区域字节数。默认为 buffer 大小减去 offset

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. 如果 size 未指定,则设 size = max(0, buffer.size - offset)

  3. 如未满足以下任一条件,使 this 失效并返回。

    • buffer 可与 this 有效共用

    • buffer.usage 包含 COPY_DST

    • size 是 4 的倍数。

    • offset 是 4 的倍数。

    • buffer.size ≥ (offset + size)。

  4. 入队命令(Enqueue a command)this,执行时在队列时间轴上执行后续步骤。

队列时间轴步骤:
  1. bufferoffset 起的 size 字节设置为 0

13.5. 像素块拷贝命令(Texel Copy Commands)

copyBufferToTexture(source, destination, copySize)

GPUCommandEncoder 编码一个命令, 将数据从 GPUBuffer 的子区域复制到一个或多个连续的纹理子资源的子区域。

调用者: GPUCommandEncoder this

参数:

GPUCommandEncoder.copyBufferToTexture(source, destination, copySize) 方法参数。
参数 类型 可为 null 可选 描述
source GPUTexelCopyBufferInfo 结合 copySize,定义源 buffer 区域。
destination GPUTexelCopyTextureInfo 结合 copySize,定义目标纹理子资源 区域。
copySize GPUExtent3D

返回: undefined

内容时间轴步骤:

  1. ? 校验 GPUOrigin3D 形状(destination.origin)。

  2. ? 校验 GPUExtent3D 形状(copySize)。

  3. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. alignedtrue

  3. dataLengthsource.buffer.size

  4. 如未满足以下任一条件,使 this 失效并返回。

  5. 入队命令(Enqueue a command)this,执行时在队列时间轴上执行后续步骤。

队列时间轴步骤:
  1. blockWidthdestination.texturetexel block width

  2. blockHeightdestination.texturetexel block height

  3. dstOrigindestination.origin

  4. dstBlockOriginX = (dstOrigin.x ÷ blockWidth)。

  5. dstBlockOriginY = (dstOrigin.y ÷ blockHeight)。

  6. blockColumns = (copySize.width ÷ blockWidth)。

  7. blockRows = (copySize.height ÷ blockHeight)。

  8. 断言 dstBlockOriginXdstBlockOriginYblockColumnsblockRows 均为整数。

  9. 对于 z 属于区间 [0, copySize.depthOrArrayLayers − 1]:

    1. dstSubregion纹理拷贝子区域z + dstOrigin.z)的 destination

    2. 对于 y 属于区间 [0, blockRows − 1]:

      1. 对于 x 属于区间 [0, blockColumns − 1]:

        1. blockOffsettexel block 字节偏移,对应于 destination.texture 的 (x, y, z)。

        2. dstSubregion 的 (dstBlockOriginX + x, dstBlockOriginY + y) 像素块 设置为与 source.buffer 偏移 blockOffset 处的 像素块 等价像素表达

copyTextureToBuffer(source, destination, copySize)

GPUCommandEncoder 编码一个命令, 将数据从一个或多个连续纹理子资源的子区域复制到 GPUBuffer 的子区域中。

调用者: GPUCommandEncoder this

参数:

GPUCommandEncoder.copyTextureToBuffer(source, destination, copySize) 方法参数。
参数 类型 可为 null 可选 描述
source GPUTexelCopyTextureInfo 结合 copySize,定义源纹理子资源区域。
destination GPUTexelCopyBufferInfo 结合 copySize,定义目标 buffer 区域。
copySize GPUExtent3D

返回: undefined

内容时间轴步骤:

  1. ? 校验 GPUOrigin3D 形状(source.origin)。

  2. ? 校验 GPUExtent3D 形状(copySize)。

  3. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. alignedtrue

  3. dataLengthdestination.buffer.size

  4. 如未满足以下任一条件,使 this 失效并返回。

  5. 入队命令(Enqueue a command)this,执行时在队列时间轴上执行后续步骤。

队列时间轴步骤:
  1. blockWidthsource.texturetexel block width

  2. blockHeightsource.texturetexel block height

  3. srcOriginsource.origin

  4. srcBlockOriginX = (srcOrigin.x ÷ blockWidth)。

  5. srcBlockOriginY = (srcOrigin.y ÷ blockHeight)。

  6. blockColumns = (copySize.width ÷ blockWidth)。

  7. blockRows = (copySize.height ÷ blockHeight)。

  8. 断言 srcBlockOriginXsrcBlockOriginYblockColumnsblockRows 均为整数。

  9. 对于 z 属于区间 [0, copySize.depthOrArrayLayers − 1]:

    1. srcSubregion纹理拷贝子区域z + srcOrigin.z)的 source

    2. 对于 y 属于区间 [0, blockRows − 1]:

      1. 对于 x 属于区间 [0, blockColumns − 1]:

        1. blockOffsettexel block 字节偏移,对应于 source.texture 的 (x, y, z)。

        2. destination.bufferblockOffset 处设置为 srcSubregion 的 (srcBlockOriginX + x, srcBlockOriginY + y) 像素块等价像素表达

copyTextureToTexture(source, destination, copySize)

GPUCommandEncoder 编码一个命令, 将数据从一个或多个连续纹理子资源的子区域复制到另一个或多个连续纹理子资源的子区域。

调用者: GPUCommandEncoder this

参数:

GPUCommandEncoder.copyTextureToTexture(source, destination, copySize) 方法参数。
参数 类型 可为 null 可选 描述
source GPUTexelCopyTextureInfo 结合 copySize,定义源纹理子资源区域。
destination GPUTexelCopyTextureInfo 结合 copySize,定义目标纹理子资源区域。
copySize GPUExtent3D

返回: undefined

内容时间轴步骤:

  1. ? 校验 GPUOrigin3D 形状(source.origin)。

  2. ? 校验 GPUOrigin3D 形状(destination.origin)。

  3. ? 校验 GPUExtent3D 形状(copySize)。

  4. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. 如未满足以下任一条件,使 this 失效并返回。

  3. 入队命令(Enqueue a command)this,执行时在队列时间轴上执行后续步骤。

队列时间轴步骤:
  1. blockWidthsource.texture像素块宽度

  2. blockHeightsource.texture像素块高度

  3. srcOriginsource.origin

  4. srcBlockOriginX = (srcOrigin.x ÷ blockWidth)。

  5. srcBlockOriginY = (srcOrigin.y ÷ blockHeight)。

  6. dstOrigindestination.origin

  7. dstBlockOriginX = (dstOrigin.x ÷ blockWidth)。

  8. dstBlockOriginY = (dstOrigin.y ÷ blockHeight)。

  9. blockColumns = (copySize.width ÷ blockWidth)。

  10. blockRows = (copySize.height ÷ blockHeight)。

  11. 断言 srcBlockOriginXsrcBlockOriginYdstBlockOriginXdstBlockOriginYblockColumnsblockRows 均为整数。

  12. 对于 z 属于区间 [0, copySize.depthOrArrayLayers − 1]:

    1. srcSubregion纹理拷贝子区域z + srcOrigin.z)的 source

    2. dstSubregion纹理拷贝子区域z + dstOrigin.z)的 destination

    3. 对于 y 属于区间 [0, blockRows − 1]:

      1. 对于 x 属于区间 [0, blockColumns − 1]:

        1. dstSubregion 的 (dstBlockOriginX + x, dstBlockOriginY + y) 像素块 设置为与 srcSubregion 的 (srcBlockOriginX + x, srcBlockOriginY + y) 像素块 等价像素表达

13.6. 查询(Queries)

resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset)

GPUQuerySet 的查询结果解析(resolve)到指定范围的 GPUBuffer 中。

调用者: GPUCommandEncoder this。

参数:

GPUCommandEncoder.resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset) 方法参数。
参数 类型 可为 null 可选 描述
querySet GPUQuerySet
firstQuery GPUSize32
queryCount GPUSize32
destination GPUBuffer
destinationOffset GPUSize64

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. 如未满足以下任一条件,使 this 失效并返回。

    • querySet 可与 this 有效共用

    • destination 可与 this 有效共用

    • destination.usage 包含 QUERY_RESOLVE

    • firstQuery < querySet 的查询数量。

    • (firstQuery + queryCount) ≤ querySet 的查询数量。

    • destinationOffset 是 256 的倍数。

    • destinationOffset + 8 × queryCountdestination.size

  3. 入队命令(Enqueue a command)this,执行时在队列时间轴上执行后续步骤。

队列时间轴步骤:
  1. queryIndex = firstQuery

  2. offset = destinationOffset

  3. queryIndex < firstQuery + queryCount 时:

    1. destinationoffset 起的 8 字节设置为 querySetqueryIndex 位置的值。

    2. queryIndex = queryIndex + 1。

    3. offset = offset + 8。

13.7. 终结(Finalization)

通过调用 finish(),可以创建包含由 GPUCommandEncoder 录制的命令的 GPUCommandBuffer。 一旦 finish() 被调用,该命令编码器将无法再被使用。

finish(descriptor)

完成命令序列的录制,并返回对应的 GPUCommandBuffer

调用者: GPUCommandEncoder this

参数:

GPUCommandEncoder.finish(descriptor) 方法参数。
参数 类型 可为 null 可选 描述
descriptor GPUCommandBufferDescriptor

返回: GPUCommandBuffer

内容时间轴步骤:

  1. commandBuffer 为一个新的 GPUCommandBuffer

  2. this.[[device]]设备时间轴上执行 finish steps

  3. 返回 commandBuffer

设备时间轴 finish steps
  1. validationSucceeded = true,如果以下所有要求都满足,否则为 false

  2. 设置 this.[[state]] 为 "ended"。

  3. 如果 validationSucceeded == false,则:

    1. 生成校验错误(Generate a validation error)

    2. 返回一个 失效GPUCommandBuffer

  4. 设置 commandBuffer.[[command_list]]this.[[commands]]

14. 可编程通道(Programmable Passes)

interface mixin GPUBindingCommandsMixin {
    undefined setBindGroup(GPUIndex32 index, GPUBindGroup? bindGroup,
        optional sequence<GPUBufferDynamicOffset> dynamicOffsets = []);

    undefined setBindGroup(GPUIndex32 index, GPUBindGroup? bindGroup,
        [AllowShared] Uint32Array dynamicOffsetsData,
        GPUSize64 dynamicOffsetsDataStart,
        GPUSize32 dynamicOffsetsDataLength);
};

GPUBindingCommandsMixin 假设同一对象上存在 GPUObjectBaseGPUCommandsMixin 成员。 它只能被同时包含了这些 mixin 的接口所包含。

GPUBindingCommandsMixin 具有如下设备时间轴属性

[[bind_groups]] , 类型为 有序映射 <GPUIndex32, GPUBindGroup>,初始为空

每个索引当前的 GPUBindGroup

[[dynamic_offsets]] , 类型为 有序映射 <GPUIndex32, 列表 <GPUBufferDynamicOffset>>,初始为空

每个 [[bind_groups]] 条目的当前动态偏移。

14.1. 绑定组(Bind Groups)

setBindGroup() 有两个重载:

setBindGroup(index, bindGroup, dynamicOffsets)

设置给定索引处的当前 GPUBindGroup

调用者: GPUBindingCommandsMixin this。

参数:

index , 类型 GPUIndex32,不可为 null,必填

要设置绑定组的索引。

bindGroup , 类型 GPUBindGroup,可为 null,必填

后续渲染或计算命令要用的绑定组。

dynamicOffsets , 类型 sequence<GPUBufferDynamicOffset>,不可为 null,默认 []

对于 bindGroup 中各 buffer.hasDynamicOffset 为 true 的条目,按 GPUBindGroupLayoutEntry.binding 顺序给出 buffer 偏移(字节)。详见 说明

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. dynamicOffsetCount = 0,若 bindGroupnull,否则为 bindGroup.[[layout]].[[dynamicOffsetCount]]

  3. 如未满足以下任一要求,使 this 失效并返回。

  4. 如果 bindGroupnull

    1. 移除 this.[[bind_groups]][index]。

    2. 移除 this.[[dynamic_offsets]][index]。

    否则:

    1. 如未满足以下任一要求,使 this 失效并返回。

    2. 设置 this.[[bind_groups]][index] 为 bindGroup

    3. 设置 this.[[dynamic_offsets]][index] 为 dynamicOffsets 的拷贝。

    4. 如果 thisGPURenderCommandsMixin

      1. this.[[bind_groups]] 中每个 bindGroup合并 bindGroup.[[usedResources]]this.[[usage scope]]

setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength)

设置给定索引处的当前 GPUBindGroup,动态偏移通过 Uint32Array 的子集指定。

调用者: GPUBindingCommandsMixin this

参数:

GPUBindingCommandsMixin.setBindGroup(index, bindGroup, dynamicOffsetsData, dynamicOffsetsDataStart, dynamicOffsetsDataLength) 方法参数。
参数 类型 可为 null 可选 描述
index GPUIndex32 要设置绑定组的索引。
bindGroup GPUBindGroup? 后续渲染或计算命令要用的绑定组。
dynamicOffsetsData Uint32Array 对于 bindGroup 中各 buffer.hasDynamicOffset 为 true 的条目,按 GPUBindGroupLayoutEntry.binding 顺序给出 buffer 偏移(字节)。详见 说明
dynamicOffsetsDataStart GPUSize64 dynamicOffsetsData 中 buffer 偏移数据起始的元素偏移。
dynamicOffsetsDataLength GPUSize32 要从 dynamicOffsetsData 读取的 buffer 偏移数量。

返回: undefined

内容时间轴步骤:

  1. 如未满足以下任一要求,抛出 RangeError 并返回。

    • dynamicOffsetsDataStart 必须 ≥ 0。

    • dynamicOffsetsDataStart + dynamicOffsetsDataLength 必须 ≤ dynamicOffsetsData.length

  2. dynamicOffsets列表,内容为 dynamicOffsetsData 拷贝的 dynamicOffsetsDataStartdynamicOffsetsDataLength 个元素。

  3. 调用 this.setBindGroup(index, bindGroup, dynamicOffsets)。

注意:
动态偏移(dynamic offset)按照 GPUBindGroupLayoutEntry.binding 顺序应用。

这意味着,如果 dynamic bindingsGPUBindGroupLayoutEntry 的列表,列表中每个成员的 buffer?.hasDynamicOffset 被设置为 true,并按 GPUBindGroupLayoutEntry.binding 排序,则 dynamic offset[i](传给 setBindGroup() 的)对应 dynamic bindings[i]

对于以下方式创建的 GPUBindGroupLayout
// 注意:数组内绑定顺序可以乱序,最终会按 binding index 排序。
let layout = gpuDevice.createBindGroupLayout({
    entries: [{
        binding: 1,
        buffer: {},
    }, {
        binding: 2,
        buffer: { dynamicOffset: true },
    }, {
        binding: 0,
        buffer: { dynamicOffset: true },
    }]
});

再通过如下方式创建的 GPUBindGroup 使用:

// 和上面一样,这里的数组顺序无关紧要。
// 甚至不需要和 layout 里的顺序一致。
let bindGroup = gpuDevice.createBindGroup({
    layout: layout,
    entries: [{
        binding: 1,
        resource: { buffer: bufferA, offset: 256 },
    }, {
        binding: 2,
        resource: { buffer: bufferB, offset: 512 },
    }, {
        binding: 0,
        resource: { buffer: bufferC },
    }]
});

并使用如下方式绑定:

pass.setBindGroup(0, bindGroup, [1024, 2048]);

则实际生效的 buffer 偏移如下:

Binding Buffer Offset
0 bufferC 1024(动态)
1 bufferA 256(静态)
2 bufferB 2560(静态 + 动态)
要在给定 GPUBindGroup bindGroup 上遍历每个动态绑定偏移(Iterate over each dynamic binding offset), 并对每个动态偏移执行指定 steps,按如下设备时间轴步骤:
  1. dynamicOffsetIndex = 0

  2. layout = bindGroup.[[layout]]

  3. bindGroup.[[entries]] 中每个 GPUBindGroupEntry entry, 按 entry.binding 升序遍历:

    1. bindingDescriptor = layout.[[entryMap]][entry.binding]。

    2. 如果 bindingDescriptor.buffer?.hasDynamicOffsettrue

      1. bufferBinding = get as buffer binding(entry.resource)。

      2. bufferLayout = bindingDescriptor.buffer

      3. bufferBindingbufferLayoutdynamicOffsetIndex 调用 steps

      4. dynamicOffsetIndex = dynamicOffsetIndex + 1

Validate encoder bind groups(encoder, pipeline)

参数:

GPUBindingCommandsMixin encoder

要校验绑定组的编码器。

GPUPipelineBase pipeline

要校验 encoder 绑定组兼容性的管线。

Device timeline steps:

  1. 如未满足以下任一条件,返回 false

否则返回 true

Encoder bind groups alias a writable resource(encoder, pipeline) 如果任何可写 buffer 绑定范围与同一 buffer 的其他绑定范围有重叠,或者任何可写纹理绑定在纹理子资源上与任何其他纹理绑定重叠(可以是同一个或不同的 GPUTextureView 对象)。

Note: 此算法限制了 usage scope storage exception 的使用。

参数:

GPUBindingCommandsMixin encoder

要校验绑定组的编码器。

GPUPipelineBase pipeline

要校验 encoder 绑定组兼容性的管线。

Device timeline steps:

  1. 对于 stage 属于 [VERTEX, FRAGMENT, COMPUTE]:

    1. bufferBindings 为 (GPUBufferBinding, boolean) 对的列表,后者表示资源是否作为可写使用。

    2. textureViews 为 (GPUTextureView, boolean) 对的列表,后者表示资源是否作为可写使用。

    3. 对于 pipeline.[[layout]].[[bindGroupLayouts]] 中每一对 (GPUIndex32 bindGroupIndex, GPUBindGroupLayout bindGroupLayout):

      1. bindGroup = encoder.[[bind_groups]][bindGroupIndex]。

      2. bindGroupLayoutEntries = bindGroupLayout.[[descriptor]].entries

      3. bufferRangesbindGroup已绑定 buffer 范围,使用动态偏移 encoder.[[dynamic_offsets]][bindGroupIndex]。

      4. 对于 bufferRanges 中每一对 (GPUBindGroupLayoutEntry bindGroupLayoutEntry, GPUBufferBinding resource),其中 bindGroupLayoutEntry.visibility 包含 stage

        1. resourceWritable = (bindGroupLayoutEntry.buffer.type == "storage")。

        2. 对于 bufferBindings 中每一对 (GPUBufferBinding pastResource, boolean pastResourceWritable):

          1. 如果 (resourceWritablepastResourceWritable) 为 true,且 pastResourceresource buffer-binding-aliasing,返回 true

        3. 追加 (resource, resourceWritable) 到 bufferBindings

      5. 对于 bindGroupLayoutEntries 中每个 GPUBindGroupLayoutEntry bindGroupLayoutEntrybindGroup 中对应的 GPUTextureView resource,其中 bindGroupLayoutEntry.visibility 包含 stage

        1. 如果 bindGroupLayoutEntry.storageTexture 未提供,continue

        2. resourceWritablebindGroupLayoutEntry.storageTexture.access 是否为可写访问模式。

        3. 对于 textureViews 中每一对 (GPUTextureView pastResource, boolean pastResourceWritable):

          1. 如果 (resourceWritablepastResourceWritable) 为 true,且 pastResourceresource texture-view-aliasing,返回 true

        4. 追加 (resource, resourceWritable) 到 textureViews

  2. 返回 false

Note: 强烈建议实现做此算法的优化。

15. 调试标记(Debug Markers)

GPUDebugCommandsMixin 提供用于给一组命令应用调试标签或在命令序列中插入单个标签的方法。

调试组可以嵌套,从而形成有层次的标记命令,且必须成对平衡。

对象标签 类似,这些标签没有强制行为,但可能会显示在错误消息、浏览器开发者工具中,也可能传递给底层原生 API。

interface mixin GPUDebugCommandsMixin {
    undefined pushDebugGroup(USVString groupLabel);
    undefined popDebugGroup();
    undefined insertDebugMarker(USVString markerLabel);
};

GPUDebugCommandsMixin 假设同一对象上存在 GPUObjectBaseGPUCommandsMixin 成员。它只能被同时包含了这些 mixin 的接口所包含。

GPUDebugCommandsMixin 具有如下设备时间轴属性

[[debug_group_stack]],类型为 stack<USVString>

当前活跃调试组标签的栈。

GPUDebugCommandsMixin 具有如下方法:

pushDebugGroup(groupLabel)

开始一个包含后续命令的调试组。

Called on: GPUDebugCommandsMixin this

参数:

GPUDebugCommandsMixin.pushDebugGroup(groupLabel) 方法参数。
参数 类型 可为 null 可选 描述
groupLabel USVString 命令组的标签。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

Device timeline steps:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. Push groupLabelthis.[[debug_group_stack]] 栈顶。

popDebugGroup()

结束最近一次 pushDebugGroup() 启动的调试组。

Called on: GPUDebugCommandsMixin this

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

Device timeline steps:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. 如未满足以下要求,使 this 失效并返回。

  3. Popthis.[[debug_group_stack]] 弹出一项。

insertDebugMarker(markerLabel)

在命令流中插入一个带标签的标记点。

Called on: GPUDebugCommandsMixin this。

参数:

GPUDebugCommandsMixin.insertDebugMarker(markerLabel) 方法参数。
参数 类型 可为 null 可选 描述
markerLabel USVString 要插入的标签。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

Device timeline steps:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

16. 计算通道(Compute Passes)

16.1. GPUComputePassEncoder

[Exposed=(Window, Worker), SecureContext]
interface GPUComputePassEncoder {
    undefined setPipeline(GPUComputePipeline pipeline);
    undefined dispatchWorkgroups(GPUSize32 workgroupCountX, optional GPUSize32 workgroupCountY = 1, optional GPUSize32 workgroupCountZ = 1);
    undefined dispatchWorkgroupsIndirect(GPUBuffer indirectBuffer, GPUSize64 indirectOffset);

    undefined end();
};
GPUComputePassEncoder includes GPUObjectBase;
GPUComputePassEncoder includes GPUCommandsMixin;
GPUComputePassEncoder includes GPUDebugCommandsMixin;
GPUComputePassEncoder includes GPUBindingCommandsMixin;

GPUComputePassEncoder 具有如下设备时间轴属性

[[command_encoder]],类型为 GPUCommandEncoder,只读

创建此计算通道编码器的 GPUCommandEncoder

[[endTimestampWrite]],类型为 GPU command?,只读,默认 null

用于在通道结束时写入时间戳的 GPU command(如有)。

[[pipeline]],类型为 GPUComputePipeline,初始为 null

当前的 GPUComputePipeline

16.1.1. 计算通道编码器的创建(Compute Pass Encoder Creation)

dictionary GPUComputePassTimestampWrites {
    required GPUQuerySet querySet;
    GPUSize32 beginningOfPassWriteIndex;
    GPUSize32 endOfPassWriteIndex;
};
querySet类型 GPUQuerySet

要写入查询结果的 GPUQuerySet,类型为 "timestamp"

beginningOfPassWriteIndex类型 GPUSize32

如指定,表示计算通道开始时写入时间戳的 querySet 中的查询索引。

endOfPassWriteIndex类型 GPUSize32

如指定,表示计算通道结束时写入时间戳的 querySet 中的查询索引。

注意: 时间戳查询值以纳秒为单位写入,但数值的含义是实现定义的,且可能不是单调递增。详情见§ 20.4 时间戳查询

dictionary GPUComputePassDescriptor
         : GPUObjectDescriptorBase {
    GPUComputePassTimestampWrites timestampWrites;
};
timestampWrites类型 GPUComputePassTimestampWrites

定义此通道需要写入哪些时间戳以及写入位置。

16.1.2. 调度(Dispatch)

setPipeline(pipeline)

设置当前的 GPUComputePipeline

调用者: GPUComputePassEncoder this。

参数:

GPUComputePassEncoder.setPipeline(pipeline) 方法参数。
参数 类型 可为 null 可选 描述
pipeline GPUComputePipeline 后续调度命令使用的计算管线。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

Device timeline steps:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. 如未满足以下条件,使 this 失效并返回。

    • pipeline 必须 可与 this 有效共用。

  3. 设置 this.[[pipeline]]pipeline

dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ)

使用当前 GPUComputePipeline 派发工作。详见§ 23.1 计算

调用者: GPUComputePassEncoder this。

参数:

GPUComputePassEncoder.dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ) 方法参数。
参数 类型 可为 null 可选 描述
workgroupCountX GPUSize32 待派发 workgroup 网格的 X 维度。
workgroupCountY GPUSize32 待派发 workgroup 网格的 Y 维度。
workgroupCountZ GPUSize32 待派发 workgroup 网格的 Z 维度。
注意:
xyz 传递给 dispatchWorkgroups()dispatchWorkgroupsIndirect() 的值,是每个维度需要派发的 workgroup 数量,不是每个维度的着色器调用(shader invocation)数量。这与现代原生 GPU API 的行为一致,但与 OpenCL 不同。

例如,如果一个 GPUShaderModule 的入口点定义了 @workgroup_size(4, 4),并用 computePass.dispatchWorkgroups(8, 8); 派发,则总共会调用 4*4*8*8=1024 次:即 4x4 的 workgroup 在 X、Y 两轴各派发 8 次。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

Device timeline steps:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. usageScope 为一个空的usage scope

  3. this.[[bind_groups]] 中每个 bindGroup合并 bindGroup.[[usedResources]]this.[[usage scope]]

  4. 如未满足以下条件,使 this 失效并返回。

  5. bindingStatethis 的当前状态快照。

  6. Enqueue a commandthis,该命令将在队列时间轴上执行后续步骤。

Queue timeline steps:
  1. 以 [workgroupCountX, workgroupCountY, workgroupCountZ] 维度、bindingState.[[pipeline]] 以及 bindingState.[[bind_groups]] 执行 workgroup 网格。

dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset)

使用当前 GPUComputePipeline,从 GPUBuffer 读取参数派发工作。详见§ 23.1 计算

缓冲区中编码的 indirect dispatch parameters 必须是3 个 32 位无符号整数(共 12 字节)的紧凑块,顺序与 dispatchWorkgroups() 参数一致。例如:

let dispatchIndirectParameters = new Uint32Array(3);
dispatchIndirectParameters[0] = workgroupCountX;
dispatchIndirectParameters[1] = workgroupCountY;
dispatchIndirectParameters[2] = workgroupCountZ;
调用者: GPUComputePassEncoder this。

参数:

GPUComputePassEncoder.dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset) 方法参数。
参数 类型 可为 null 可选 描述
indirectBuffer GPUBuffer 包含间接调度参数的缓冲区。
indirectOffset GPUSize64 缓冲区 indirectBuffer 内调度数据起始的字节偏移。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

Device timeline steps:
  1. 验证编码器状态(Validate the encoder state)this。如返回 false,直接返回。

  2. usageScope 为一个空的usage scope

  3. this.[[bind_groups]] 中每个 bindGroup合并 bindGroup.[[usedResources]]this.[[usage scope]]

  4. Add indirectBufferusageScope,用法为input

  5. 如未满足以下条件,使 this 失效并返回。

  6. bindingStatethis 的当前状态快照。

  7. Enqueue a commandthis,该命令将在队列时间轴上执行后续步骤。

Queue timeline steps:
  1. workgroupCountX 为从 indirectBufferindirectOffset 字节处读取的无符号 32 位整数。

  2. workgroupCountY 为从 indirectBufferindirectOffset+4 字节处读取的无符号 32 位整数。

  3. workgroupCountZ 为从 indirectBufferindirectOffset+8 字节处读取的无符号 32 位整数。

  4. 如果 workgroupCountXworkgroupCountYworkgroupCountZ 大于 this.device.limits.maxComputeWorkgroupsPerDimension,则返回。

  5. 以 [workgroupCountX, workgroupCountY, workgroupCountZ] 维度、bindingState.[[pipeline]] 以及 bindingState.[[bind_groups]] 执行 workgroup 网格。

16.1.3. 结束(Finalization)

计算通道编码器可以通过调用 end() 结束,表示用户已完成本通道的命令录制。一旦调用 end(),该计算通道编码器不可再使用。

end()

完成本计算通道命令序列的录制。

调用者: GPUComputePassEncoder this

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

Device timeline steps:
  1. parentEncoder = this.[[command_encoder]]

  2. 如未满足以下任一要求,生成校验错误并返回。

  3. 设置 this.[[state]] 为 "ended"。

  4. 设置 parentEncoder.[[state]] 为 "open"。

  5. 如未满足以下任一要求,使 parentEncoder 失效并返回。

  6. 扩展 parentEncoder.[[commands]],追加 this.[[commands]]

  7. 如果 this.[[endTimestampWrite]] 不为 null

    1. 扩展 parentEncoder.[[commands]],追加 this.[[endTimestampWrite]]

17. 渲染通道(Render Passes)

17.1. GPURenderPassEncoder

[Exposed=(Window, Worker), SecureContext]
interface GPURenderPassEncoder {
    undefined setViewport(float x, float y,
        float width, float height,
        float minDepth, float maxDepth);

    undefined setScissorRect(GPUIntegerCoordinate x, GPUIntegerCoordinate y,
                        GPUIntegerCoordinate width, GPUIntegerCoordinate height);

    undefined setBlendConstant(GPUColor color);
    undefined setStencilReference(GPUStencilValue reference);

    undefined beginOcclusionQuery(GPUSize32 queryIndex);
    undefined endOcclusionQuery();

    undefined executeBundles(sequence<GPURenderBundle> bundles);
    undefined end();
};
GPURenderPassEncoder includes GPUObjectBase;
GPURenderPassEncoder includes GPUCommandsMixin;
GPURenderPassEncoder includes GPUDebugCommandsMixin;
GPURenderPassEncoder includes GPUBindingCommandsMixin;
GPURenderPassEncoder includes GPURenderCommandsMixin;

GPURenderPassEncoder 具有如下设备时间轴属性

[[command_encoder]],类型为 GPUCommandEncoder,只读

创建此渲染通道编码器的 GPUCommandEncoder

[[attachment_size]],只读

设置为以下范围:

  • width, height = 通道渲染附件的尺寸

[[occlusion_query_set]],类型为 GPUQuerySet,只读

用于存储本通道遮挡查询结果的 GPUQuerySet,在通道创建时由 GPURenderPassDescriptor.occlusionQuerySet 初始化。

[[endTimestampWrite]],类型为 GPU command?,只读,默认 null

用于在通道结束时写入时间戳的 GPU command(如有)。

[[maxDrawCount]],类型为 GPUSize64,只读

本通道允许的最大绘制次数。

[[occlusion_query_active]],类型为 boolean

本通道的 [[occlusion_query_set]] 是否正被写入。

在作为 GPUCommandBuffer 一部分执行编码的渲染通道命令时,会使用内部 RenderState 对象来跟踪渲染所需的当前状态。

RenderState 具有如下队列时间轴属性

[[occlusionQueryIndex]],类型为 GPUSize32

[[occlusion_query_set]] 中存储遮挡查询结果的索引。

[[viewport]]

当前视口矩形和深度范围。初始值如下:

  • x, y = 0.0, 0.0

  • width, height = 通道渲染目标的尺寸

  • minDepth, maxDepth = 0.0, 1.0

[[scissorRect]]

当前剪裁矩形,初始值如下:

  • x, y = 0, 0

  • width, height = 通道渲染目标的尺寸

[[blendConstant]],类型为 GPUColor

当前混合常量,初始为 [0, 0, 0, 0]

[[stencilReference]],类型为 GPUStencilValue

当前模板参考值,初始为 0

[[colorAttachments]],类型为 sequence<GPURenderPassColorAttachment?>

本渲染通道的颜色附件及其状态。

[[depthStencilAttachment]],类型为 GPURenderPassDepthStencilAttachment?

本渲染通道的深度/模板附件及其状态。

渲染通道还具有 帧缓冲内存(framebuffer memory),用于存储由绘制命令写入、混合和深度/模板测试读取的每个附件的texel数据。

注意: 根据 GPU 硬件,帧缓冲内存 可能是附件纹理分配的内存,也可能是一个独立区域,纹理数据需被拷贝至/从该区域(如 tile-based 架构)。

17.1.1. 渲染通道编码器的创建(Render Pass Encoder Creation)

dictionary GPURenderPassTimestampWrites {
    required GPUQuerySet querySet;
    GPUSize32 beginningOfPassWriteIndex;
    GPUSize32 endOfPassWriteIndex;
};
querySet类型 GPUQuerySet

要写入查询结果的 GPUQuerySet,类型为 "timestamp"

beginningOfPassWriteIndex类型 GPUSize32

如指定,表示渲染通道开始时写入时间戳的 querySet 中的查询索引。

endOfPassWriteIndex类型 GPUSize32

如指定,表示渲染通道结束时写入时间戳的 querySet 中的查询索引。

注意: 时间戳查询值以纳秒为单位写入,但数值的含义是实现定义的,且可能不是单调递增。详情见§ 20.4 时间戳查询

dictionary GPURenderPassDescriptor
         : GPUObjectDescriptorBase {
    required sequence<GPURenderPassColorAttachment?> colorAttachments;
    GPURenderPassDepthStencilAttachment depthStencilAttachment;
    GPUQuerySet occlusionQuerySet;
    GPURenderPassTimestampWrites timestampWrites;
    GPUSize64 maxDrawCount = 50000000;
};
colorAttachments类型 sequence<GPURenderPassColorAttachment?>

该序列中的 GPURenderPassColorAttachment 集合定义了此渲染通道执行时输出到哪些颜色附件。

用法兼容性限制,任一颜色附件不得与其他附件或渲染通道中使用的任何资源混用(alias)。

depthStencilAttachment类型 GPURenderPassDepthStencilAttachment

GPURenderPassDepthStencilAttachment 值,定义此渲染通道执行时输出和测试的深度/模板附件。

用法兼容性限制,可写深度/模板附件不得与其他附件或渲染通道中使用的任何资源混用(alias)。

occlusionQuerySet类型 GPUQuerySet

GPUQuerySet,定义本通道遮挡查询结果的存储位置。

timestampWrites类型 GPURenderPassTimestampWrites

定义此通道将写入哪些时间戳及其位置。

maxDrawCount类型 GPUSize64,默认 50000000

本渲染通道允许的最大绘制(draw)调用次数。某些实现会利用此值分配渲染通道前需要的资源。除非确定会有更多绘制调用,保持默认值即可。

有效用法(Valid Usage)

对于给定 GPUDevice deviceGPURenderPassDescriptor this,需要满足如下校验规则:

  1. this.colorAttachments.size 必须 ≤ device.[[limits]].maxColorAttachments

  2. this.colorAttachments 中每个非 nullcolorAttachment

    1. colorAttachment.view 必须 可与 device 有效共用。

    2. 如果 colorAttachment.resolveTarget提供

      1. colorAttachment.resolveTarget 必须 可与 device 有效共用。

    3. colorAttachment 必须满足 GPURenderPassColorAttachment 有效用法 规则。

  3. this.depthStencilAttachment提供

    1. this.depthStencilAttachment.view 必须 可与 device 有效共用。

    2. this.depthStencilAttachment 必须满足 GPURenderPassDepthStencilAttachment 有效用法 规则。

  4. 必须至少存在一个附件,满足下列之一:

  5. 校验 GPURenderPassDescriptor 的 color attachment 每采样字节数(device, this.colorAttachments) 成功。

  6. this.colorAttachments 所有非 nullview,以及如有的 this.depthStencilAttachment.view,其 sampleCount 必须相等。

  7. this.colorAttachments 所有非 nullview 及如有的 this.depthStencilAttachment.view,其 [[renderExtent]] 必须一致。

  8. this.occlusionQuerySet提供

    1. this.occlusionQuerySet 必须 可与 device 有效共用。

    2. this.occlusionQuerySet.type 必须为 occlusion

  9. this.timestampWrites提供

校验 GPURenderPassDescriptor 的 color attachment 每采样字节数(device, colorAttachments)

参数:

设备时间轴步骤:

  1. formats 为一个空的列表<GPUTextureFormat?>。

  2. colorAttachments 中每个 colorAttachment

    1. colorAttachmentundefined,continue。

    2. 追加 colorAttachment.view.[[descriptor]].formatformats

  3. 计算 color attachment 每采样字节数(formats) 必须 ≤ device.[[limits]].maxColorAttachmentBytesPerSample

17.1.1.1. 颜色附件(Color Attachments)
dictionary GPURenderPassColorAttachment {
    required (GPUTexture or GPUTextureView) view;
    GPUIntegerCoordinate depthSlice;
    (GPUTexture or GPUTextureView) resolveTarget;

    GPUColor clearValue;
    required GPULoadOp loadOp;
    required GPUStoreOp storeOp;
};
view类型 (GPUTexture or GPUTextureView)

描述此颜色附件要输出到的纹理子资源(subresource)子资源get as texture view(view) 决定。

depthSlice类型 GPUIntegerCoordinate

指示 "3d" view 的深度切片索引,将作为此颜色附件的输出。

resolveTarget类型 (GPUTexture or GPUTextureView)

描述当 view 为多重采样时,用于接收解析后输出的纹理子资源子资源get as texture view(resolveTarget) 决定。

clearValue类型 GPUColor

表示在执行渲染通道前,将 view 清除到的值。若未提供,则默认为 {r: 0, g: 0, b: 0, a: 0}。若 loadOp 不为 "clear",则忽略此项。

clearValue 的各分量均为 double 值,会转换为与渲染附件匹配的纹理格式的 texel 值。转换失败会产生校验错误。

loadOp类型 GPULoadOp

表示在执行渲染通道前,对 view 执行的加载操作。

注意: 推荐优先使用清除操作;详见 "clear"

storeOp类型 GPUStoreOp

在执行渲染通道后,对 view 执行的存储操作。

GPURenderPassColorAttachment 有效用法

给定 GPURenderPassColorAttachment this

  1. renderViewDescriptor = this.view.[[descriptor]]

  2. renderTexture = this.view.[[texture]]

  3. 必须满足以下所有要求:

    1. renderViewDescriptor.format 必须是颜色可渲染格式

    2. this.view 必须是可渲染纹理视图(renderable texture view)

    3. 如果 renderViewDescriptor.dimension"3d"

      1. this.depthSlice 必须提供,且 depthOrArrayLayers 小于 当前 miplevel 逻辑纹理范围renderTexturemipmap level renderViewDescriptor.baseMipLevel)的深度或数组层数。

      否则:

      1. this.depthSlice 不得被提供

    4. this.loadOp"clear"

      1. 将 IDL 值 this.clearValue 转换为纹理格式的 texel 值 renderViewDescriptor.format 时不得抛出 TypeError

        注意: 若超出格式范围但仍在 WGSL 基元类型(f32i32u32)范围内,不会报错。

    5. this.resolveTarget 被提供

      1. resolveViewDescriptor = this.resolveTarget.[[descriptor]]

      2. resolveTexture = this.resolveTarget.[[texture]]

      3. renderTexture.sampleCount 必须大于 1。

      4. resolveTexture.sampleCount 必须为 1。

      5. this.resolveTarget 必须是非 3D 的可渲染纹理视图

      6. this.resolveTarget.[[renderExtent]]this.view.[[renderExtent]] 必须相等。

      7. resolveViewDescriptor.format 必须等于 renderViewDescriptor.format

      8. resolveTexture.format 必须等于 renderTexture.format

      9. resolveViewDescriptor.format 必须支持§ 26.1.1 普通颜色格式中的解析。

一个 GPUTextureView view可渲染纹理视图(renderable texture view),若满足以下设备时间轴步骤的所有要求:
  1. descriptor = view.[[descriptor]]

  2. descriptor.usage 必须包含 RENDER_ATTACHMENT

  3. descriptor.dimension 必须为 "2d""2d-array""3d"

  4. descriptor.mipLevelCount 必须为 1。

  5. descriptor.arrayLayerCount 必须为 1。

  6. descriptor.aspect 必须包含 view.[[texture]] 的全部aspect

计算 color attachment 每采样字节数(formats)

参数:

返回: GPUSize32

  1. total = 0。

  2. formats 中每个非 null 的 format

    1. 断言 format颜色可渲染格式

    2. renderTargetPixelByteCostformatrender target pixel byte cost

    3. renderTargetComponentAlignmentformatrender target component alignment

    4. total 向上取整到不小于 totalrenderTargetComponentAlignment 的最小倍数。

    5. renderTargetPixelByteCost 加到 total 上。

  3. 返回 total

17.1.1.2. 深度/模板附件(Depth/Stencil Attachments)
dictionary GPURenderPassDepthStencilAttachment {
    required (GPUTexture or GPUTextureView) view;

    float depthClearValue;
    GPULoadOp depthLoadOp;
    GPUStoreOp depthStoreOp;
    boolean depthReadOnly = false;

    GPUStencilValue stencilClearValue = 0;
    GPULoadOp stencilLoadOp;
    GPUStoreOp stencilStoreOp;
    boolean stencilReadOnly = false;
};
view类型 (GPUTexture or GPUTextureView)

描述此深度/模板附件将要输出和读取的纹理子资源子资源get as texture view(view) 决定。

depthClearValue类型 float

表示在执行渲染通道前,将 view 的深度分量清除到的值。若 depthLoadOp 不为 "clear",则忽略此项。必须在 0.0 到 1.0 之间(含)。

depthLoadOp类型 GPULoadOp

表示在执行渲染通道前,对 view 深度分量执行的加载操作。

注意: 推荐优先使用清除操作;详见 "clear"

depthStoreOp类型 GPUStoreOp

在执行渲染通道后,对 view 深度分量执行的存储操作。

depthReadOnly类型 boolean,默认 false

表示 view 的深度分量只读。

stencilClearValue类型 GPUStencilValue,默认 0

表示在执行渲染通道前,将 view 的模板分量清除到的值。若 stencilLoadOp 不为 "clear",则忽略此项。

该值会被转换为 view 模板 aspect 类型,即取与一个texel 模板位数相同的低位。

stencilLoadOp类型 GPULoadOp

表示在执行渲染通道前,对 view 模板分量执行的加载操作。

注意: 推荐优先使用清除操作;详见 "clear"

stencilStoreOp类型 GPUStoreOp

在执行渲染通道后,对 view 模板分量执行的存储操作。

stencilReadOnly类型 boolean,默认 false

表示 view 的模板分量只读。

GPURenderPassDepthStencilAttachment 有效用法

给定 GPURenderPassDepthStencilAttachment this,需要满足以下校验规则:

17.1.1.3. 加载与存储操作(Load & Store Operations)
enum GPULoadOp {
    "load",
    "clear",
};
"load"

将该附件的现有值加载到渲染通道中。

"clear"

将该附件的清除值加载到渲染通道中。

注意: 在某些 GPU 硬件(主要是移动端)上,"clear" 的开销明显更低,因为它避免了从主内存加载数据到 tile 本地内存。 在其他 GPU 上,两者差别不大。因此,推荐在初始值无关紧要(如渲染目标会被天空盒等覆盖清除)的情况下,优先使用 "clear" 而不是 "load"

enum GPUStoreOp {
    "store",
    "discard",
};
"store"

将渲染通道该附件的结果值存储下来。

"discard"

丢弃渲染通道该附件的结果值。

注意: 被丢弃的附件表现为被清零,但实现并不要求在通道结束时执行清零。未显式清零的实现必须在附件内容首次被读取(如采样、拷贝、后续渲染通道用 "load" 附加、显示或回读 canvas 等)前延迟清零。

17.1.1.4. 渲染通道布局(Render Pass Layout)

GPURenderPassLayout 声明了 GPURenderBundle 的渲染目标布局。 它也被用于内部描述 GPURenderPassEncoder 布局GPURenderPipeline 布局。 它决定了渲染通道、渲染包和渲染管线之间的兼容性。

dictionary GPURenderPassLayout
     : GPUObjectDescriptorBase {
    required sequence<GPUTextureFormat?> colorFormats;
    GPUTextureFormat depthStencilFormat;
    GPUSize32 sampleCount = 1;
};
colorFormats类型 sequence<GPUTextureFormat?>

本通道或渲染包的颜色附件的 GPUTextureFormat 列表。

depthStencilFormat类型 GPUTextureFormat

本通道或渲染包的深度/模板附件的 GPUTextureFormat

sampleCount类型 GPUSize32,默认 1

本通道或渲染包的每像素采样数。

两个 GPURenderPassLayout 被认为相等(equal),当且仅当:
从通道推导渲染目标布局(derive render targets layout from pass)

参数:

返回: GPURenderPassLayout

设备时间轴步骤:

  1. layout 为新的 GPURenderPassLayout 对象。

  2. descriptor.colorAttachments 中每个 colorAttachment

    1. 如果 colorAttachment 不为 null

      1. 设置 layout.sampleCountcolorAttachment.view.[[texture]].sampleCount

      2. colorAttachment.view.[[descriptor]].format 追加到 layout.colorFormats

    2. 否则:

      1. layout.colorFormats 追加 null

  3. depthStencilAttachment = descriptor.depthStencilAttachment

  4. 如果 depthStencilAttachment 不为 null

    1. view = depthStencilAttachment.view

    2. 设置 layout.sampleCountview.[[texture]].sampleCount

    3. 设置 layout.depthStencilFormatview.[[descriptor]].format

  5. 返回 layout

从管线推导渲染目标布局(derive render targets layout from pipeline)

参数:

返回: GPURenderPassLayout

设备时间轴步骤:

  1. layout 为新的 GPURenderPassLayout 对象。

  2. 设置 layout.sampleCountdescriptor.multisample.count

  3. 如果 descriptor.depthStencil提供

    1. 设置 layout.depthStencilFormatdescriptor.depthStencil.format

  4. 如果 descriptor.fragment提供

    1. descriptor.fragment.targets 中每个 colorTarget

      1. colorTarget 不为 null,则将 colorTarget.format 追加到 layout.colorFormats,否则追加 null

  5. 返回 layout

17.1.2. 结束(Finalization)

渲染通道编码器可以通过调用 end() 结束,表示用户已完成本通道的命令录制。一旦调用 end(),该渲染通道编码器不可再使用。

end()

完成本渲染通道命令序列的录制。

调用者: GPURenderPassEncoder this

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. parentEncoder = this.[[command_encoder]]

  2. 如未满足以下任一要求,生成校验错误并返回:

  3. 设置 this.[[state]] 为 "ended"。

  4. 设置 parentEncoder.[[state]] 为 "open"。

  5. 如未满足以下任一要求,使 parentEncoder 失效并返回:

  6. 扩展 parentEncoder.[[commands]],追加 this.[[commands]]

  7. 如果 this.[[endTimestampWrite]] 不为 null

    1. 扩展 parentEncoder.[[commands]],追加 this.[[endTimestampWrite]]

  8. 将渲染命令入队this,该命令将在队列时间轴上以 renderState 执行后续步骤。

队列时间轴步骤:
  1. renderState.[[colorAttachments]] 中每个非 nullcolorAttachment

    1. colorView = colorAttachment.view

    2. colorView.[[descriptor]].dimension 为:

      "3d"

      colorSubregion = colorAttachment.depthSlice

      否则

      colorSubregion = colorView

    3. colorAttachment.resolveTarget 不为 null

      1. colorSubregion 的每个texel 的多重采样解析为单采样,并拷贝到 colorAttachment.resolveTarget

    4. colorAttachment.loadOp 为:

      "store"

      确保与 colorSubregion 关联的帧缓冲内存内容存储到了 colorSubregion

      "discard"

      colorSubregion 的每个texel 置零。

  2. depthStencilAttachment = renderState.[[depthStencilAttachment]]

  3. depthStencilAttachment 不为 null

    1. depthStencilAttachment.depthLoadOp 为:

      提供

      断言 depthStencilAttachment.depthReadOnlytrue,并保持 depthStencilView深度 子资源 不变。

      "store"

      确保与 深度 子资源 相关的帧缓冲内存存储于 depthStencilView

      "discard"

      深度 子资源 的每个texel 置零。

    2. depthStencilAttachment.stencilLoadOp 为:

      提供

      断言 depthStencilAttachment.stencilReadOnlytrue,并保持 depthStencilView模板 子资源 不变。

      "store"

      确保与 模板 子资源 相关的帧缓冲内存存储于 depthStencilView

      "discard"

      模板 子资源 的每个texel 置零。

  4. renderState = null

注意: 被丢弃的附件表现为被清零,但实现并不要求在通道结束时执行清零。详情见 "discard" 的说明。

注意: 只读深度/模板附件可以被视为隐式使用 "store" 操作,但由于其内容在渲染通道内并未变化,实际实现无需更新附件。只读附件不允许指定 storeOp 的校验在 GPURenderPassDepthStencilAttachment 有效用法中完成。

17.2. GPURenderCommandsMixin

GPURenderCommandsMixin 定义了 GPURenderPassEncoderGPURenderBundleEncoder 共有的渲染命令。

interface mixin GPURenderCommandsMixin {
    undefined setPipeline(GPURenderPipeline pipeline);

    undefined setIndexBuffer(GPUBuffer buffer, GPUIndexFormat indexFormat, optional GPUSize64 offset = 0, optional GPUSize64 size);
    undefined setVertexBuffer(GPUIndex32 slot, GPUBuffer? buffer, optional GPUSize64 offset = 0, optional GPUSize64 size);

    undefined draw(GPUSize32 vertexCount, optional GPUSize32 instanceCount = 1,
        optional GPUSize32 firstVertex = 0, optional GPUSize32 firstInstance = 0);
    undefined drawIndexed(GPUSize32 indexCount, optional GPUSize32 instanceCount = 1,
        optional GPUSize32 firstIndex = 0,
        optional GPUSignedOffset32 baseVertex = 0,
        optional GPUSize32 firstInstance = 0);

    undefined drawIndirect(GPUBuffer indirectBuffer, GPUSize64 indirectOffset);
    undefined drawIndexedIndirect(GPUBuffer indirectBuffer, GPUSize64 indirectOffset);
};

GPURenderCommandsMixin 假定对象上同时存在 GPUObjectBaseGPUCommandsMixinGPUBindingCommandsMixin 成员。它只能被同样包含这些 mixin 的接口包含。

GPURenderCommandsMixin 具有如下设备时间轴属性

[[layout]],类型 GPURenderPassLayout,只读

渲染通道的布局。

[[depthReadOnly]],类型 boolean,只读

如为 true,表示深度分量未被修改。

[[stencilReadOnly]],类型 boolean,只读

如为 true,表示模板分量未被修改。

[[usage scope]],类型 usage scope,初始为空

本渲染通道或渲染包的用法范围(usage scope)

[[pipeline]],类型 GPURenderPipeline,初始为 null

当前的 GPURenderPipeline

[[index_buffer]],类型 GPUBuffer,初始为 null

当前用于读取索引数据的缓冲区。

[[index_format]],类型 GPUIndexFormat

[[index_buffer]] 中索引数据的格式。

[[index_buffer_offset]],类型 GPUSize64

当前设置的 [[index_buffer]] 区段在字节上的偏移量。

[[index_buffer_size]],类型 GPUSize64

当前设置的 [[index_buffer]] 区段的字节大小,初始为 0

[[vertex_buffers]],类型 有序映射<slot, GPUBuffer>,初始为空

每个 slot 当前用于读取顶点数据的 GPUBuffer

[[vertex_buffer_sizes]],类型 有序映射<slot, GPUSize64>,初始为空

每个 slot 当前设置的 GPUBuffer 区段的字节大小。

[[drawCount]],类型 GPUSize64

本编码器录制的绘制命令数。

要在 GPURenderCommandsMixin encoder入队一个渲染命令(Enqueue a render command),以 GPU Command commandRenderState renderState
  1. 追加 commandencoder.[[commands]]

  2. command 作为 GPUCommandBuffer commandBuffer 的一部分被执行时:

    1. commandBuffer.[[renderState]] 作为 renderState,执行 command 的步骤。

17.2.1. 绘制(Drawing)

setPipeline(pipeline)

设置当前的 GPURenderPipeline

调用者: GPURenderCommandsMixin this。

参数:

参数说明:GPURenderCommandsMixin.setPipeline(pipeline)
参数 类型 可为 null 可选 描述
pipeline GPURenderPipeline 后续绘制命令用到的渲染管线。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. pipelineTargetsLayout = 从管线推导渲染目标布局(pipeline.[[descriptor]])。

  3. 如未满足以下任一条件,使 this 失效并返回:

  4. 设置 this.[[pipeline]]pipeline

setIndexBuffer(buffer, indexFormat, offset, size)

设置当前索引缓冲区。

调用者: GPURenderCommandsMixin this。

参数:

参数说明:GPURenderCommandsMixin.setIndexBuffer(buffer, indexFormat, offset, size)
参数 类型 可为 null 可选 描述
buffer GPUBuffer 后续绘制命令要用到的索引数据缓冲区。
indexFormat GPUIndexFormat buffer 中索引数据的格式。
offset GPUSize64 索引数据在 buffer 中的字节偏移,默认 0
size GPUSize64 索引数据在 buffer 中的字节大小,默认 buffer 大小减去 offset。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. 如未指定 size,则设 size = max(0, buffer.size - offset)。

  3. 如未满足以下任一条件,使 this 失效并返回:

  4. 添加 buffer[[usage scope]],用法为 input

  5. 设置 this.[[index_buffer]]buffer

  6. 设置 this.[[index_format]]indexFormat

  7. 设置 this.[[index_buffer_offset]]offset

  8. 设置 this.[[index_buffer_size]]size

setVertexBuffer(slot, buffer, offset, size)

为指定的 slot 设置当前顶点缓冲区。

调用者: GPURenderCommandsMixin this。

参数:

参数说明:GPURenderCommandsMixin.setVertexBuffer(slot, buffer, offset, size)
参数 类型 可为 null 可选 描述
slot GPUIndex32 要设置顶点缓冲区的 slot。
buffer GPUBuffer? 后续绘制命令用到的顶点数据缓冲区。
offset GPUSize64 顶点数据在 buffer 中的字节偏移,默认为 0
size GPUSize64 顶点数据在 buffer 中的字节大小,默认为缓冲区大小减去 offset。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. buffernull,则 bufferSize = 0,否则 bufferSize = buffer.size

  3. 如未提供 size,则设 size = max(0, bufferSize - offset)。

  4. 如未满足以下任一条件,使 this 失效并返回:

  5. buffernull

    1. 移除 this.[[vertex_buffers]][slot]。

    2. 移除 this.[[vertex_buffer_sizes]][slot]。

    否则:

    1. 如未满足以下任一条件,使 this 失效并返回:

    2. 添加 buffer[[usage scope]],用法为 input

    3. 设置 this.[[vertex_buffers]][slot] 为 buffer

    4. 设置 this.[[vertex_buffer_sizes]][slot] 为 size

draw(vertexCount, instanceCount, firstVertex, firstInstance)

绘制图元。 详细规范见 § 23.2 渲染

调用于: GPURenderCommandsMixin this.

参数:

方法 GPURenderCommandsMixin.draw(vertexCount, instanceCount, firstVertex, firstInstance) 的参数。
参数 类型 可为 null 可选 描述
vertexCount GPUSize32 要绘制的顶点数。
instanceCount GPUSize32 要绘制的实例数。
firstVertex GPUSize32 从顶点缓冲区的哪个偏移(单位:顶点)开始绘制。
firstInstance GPUSize32 要绘制的第一个实例。

返回值: undefined

内容时间线 步骤:

  1. 设备时间线 上对 this.[[device]] 执行后续步骤。

设备时间线 步骤:
  1. 验证 this编码器状态。如果返回 false,则返回。

  2. 以下步骤中的所有要求 必须 满足。 如有未满足,失效 this 并返回。

    1. this 绘制必须有效

    2. buffersthis.[[pipeline]].[[descriptor]].vertex.buffers

    3. 对于每一个 GPUIndex32 slot,从 0buffers.size(不包含):

      1. 如果 buffers[slot] 为 null继续

      2. bufferSizethis.[[vertex_buffer_sizes]][slot]。

      3. stridebuffers[slot].arrayStride

      4. attributesbuffers[slot].attributes

      5. lastStrideattributes 中每个 attribute 的 (offset + byteSize(attribute.format)) 的最大值,若 attributes 为空,则为 0。

      6. 根据 buffers[slot].stepMode 计算 strideCount

        "vertex"

        firstVertex + vertexCount

        "instance"

        firstInstance + instanceCount

      7. 如果 strideCount0

        1. (strideCount1) × stride + lastStride 必须bufferSize

  3. this.[[drawCount]] 增加 1。

  4. bindingStatethis 当前状态的快照。

  5. this入队一个渲染命令 ,当执行时在 队列时间线 上用 renderState 进行后续步骤。

队列时间线 步骤:
  1. 绘制 instanceCount 个实例,从 firstInstance 开始, 每个实例由 vertexCount 个顶点组成,从 firstVertex 开始, 使用 bindingStaterenderState 中的状态。

drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance)

绘制带索引的图元。 详细规范见 § 23.2 渲染

调用于: GPURenderCommandsMixin this.

参数:

方法 GPURenderCommandsMixin.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance) 的参数。
参数 类型 可为 null 可选 描述
indexCount GPUSize32 要绘制的索引数。
instanceCount GPUSize32 要绘制的实例数。
firstIndex GPUSize32 从索引缓冲区的哪个偏移(单位:索引)开始绘制。
baseVertex GPUSignedOffset32 在索引访问顶点缓冲区前,每个索引值要加上的偏移量。
firstInstance GPUSize32 要绘制的第一个实例。

返回值: undefined

内容时间线 步骤:

  1. 设备时间线 上对 this.[[device]] 执行后续步骤。

设备时间线 步骤:
  1. 验证 this编码器状态。如果返回 false,则返回。

  2. 如有下列任一条件不满足,失效 this 并返回。

  3. this.[[drawCount]] 增加 1。

  4. bindingStatethis 当前状态的快照。

  5. this入队一个渲染命令 ,当执行时在 队列时间线 上用 renderState 进行后续步骤。

队列时间线 步骤:
  1. 绘制 instanceCount 个实例,从 firstInstance 开始, 每个实例由 indexCount 个带索引的顶点组成,从索引 firstIndex(对应顶点 baseVertex)开始, 使用 bindingStaterenderState 中的状态。

注意: WebGPU 应用不应使用超出任意绑定顶点缓冲区(GPUVertexStepMode "vertex")范围的索引数据。 不同 WebGPU 实现对这种行为的处理方式不同,因此允许多种行为:要么整个绘制调用被丢弃,要么对越界属性的访问由 WGSL 的 无效内存引用 描述。

drawIndirect(indirectBuffer, indirectOffset)

使用从 GPUBuffer 读取的参数绘制图元。 详细规范见 § 23.2 渲染

缓冲区中编码的 间接绘制参数 必须是一个紧凑排列的四个 32 位无符号整数值(总共 16 字节),顺序与 draw() 方法参数一致。 例如:

let drawIndirectParameters = new Uint32Array(4);
drawIndirectParameters[0] = vertexCount;
drawIndirectParameters[1] = instanceCount;
drawIndirectParameters[2] = firstVertex;
drawIndirectParameters[3] = firstInstance;

对应 firstInstance 的值必须为 0,除非启用了 "indirect-first-instance" 特性。如果未启用 "indirect-first-instance" 特性firstInstance 不为 0,则 drawIndirect() 调用会被视为无操作。

调用于: GPURenderCommandsMixin this.

参数:

方法 GPURenderCommandsMixin.drawIndirect(indirectBuffer, indirectOffset) 的参数。
参数 类型 可为 null 可选 描述
indirectBuffer GPUBuffer 包含间接绘制参数的缓冲区。
indirectOffset GPUSize64 indirectBuffer 中绘制数据起始的字节偏移。

返回值: undefined

内容时间线 步骤:

  1. 设备时间线 上对 this.[[device]] 执行后续步骤。

设备时间线 步骤:
  1. 验证 this编码器状态。如果返回 false,则返回。

  2. 如有下列任一条件不满足,失效 this 并返回。

  3. indirectBufferinput 用法加入 [[usage scope]]

  4. this.[[drawCount]] 增加 1。

  5. bindingStatethis 当前状态的快照。

  6. this入队一个渲染命令 ,当执行时在 队列时间线 上用 renderState 进行后续步骤。

队列时间线 步骤:
  1. vertexCount 为从 indirectBufferindirectOffset 字节位置读取的无符号 32 位整数。

  2. instanceCount 为从 indirectBuffer 的 (indirectOffset + 4) 字节读取的无符号 32 位整数。

  3. firstVertex 为从 indirectBuffer 的 (indirectOffset + 8) 字节读取的无符号 32 位整数。

  4. firstInstance 为从 indirectBuffer 的 (indirectOffset + 12) 字节读取的无符号 32 位整数。

  5. 绘制 instanceCount 个实例,从 firstInstance 开始, 每个实例由 vertexCount 个顶点组成,从 firstVertex 开始, 使用 bindingStaterenderState 中的状态。

drawIndexedIndirect(indirectBuffer, indirectOffset)

使用从 GPUBuffer 读取的参数绘制带索引的图元。 详细规范见 § 23.2 渲染

缓冲区中编码的 间接 drawIndexed 参数 必须是一个紧凑排列的五个 32 位值(共 20 字节),顺序与 drawIndexed() 方法参数一致。 其中 baseVertex 为有符号 32 位整数,其他均为无符号 32 位整数。例如:

let drawIndexedIndirectParameters = new Uint32Array(5);
let drawIndexedIndirectParametersSigned = new Int32Array(drawIndexedIndirectParameters.buffer);
drawIndexedIndirectParameters[0] = indexCount;
drawIndexedIndirectParameters[1] = instanceCount;
drawIndexedIndirectParameters[2] = firstIndex;
// baseVertex 是有符号值。
drawIndexedIndirectParametersSigned[3] = baseVertex;
drawIndexedIndirectParameters[4] = firstInstance;

对应 firstInstance 的值必须为 0,除非启用了 "indirect-first-instance" 特性。如果未启用 "indirect-first-instance" 特性firstInstance 不为 0,则 drawIndexedIndirect() 调用会被视为无操作。

调用于: GPURenderCommandsMixin this.

参数:

方法 GPURenderCommandsMixin.drawIndexedIndirect(indirectBuffer, indirectOffset) 的参数。
参数 类型 可为 null 可选 描述
indirectBuffer GPUBuffer 包含间接 drawIndexed 参数的缓冲区。
indirectOffset GPUSize64 indirectBuffer 中绘制数据起始的字节偏移。

返回值: undefined

内容时间线 步骤:

  1. 设备时间线 上对 this.[[device]] 执行后续步骤。

设备时间线 步骤:
  1. 验证 this编码器状态。如果返回 false,则返回。

  2. 如有下列任一条件不满足,失效 this 并返回。

  3. indirectBufferinput 用法加入 [[usage scope]]

  4. this.[[drawCount]] 增加 1。

  5. bindingStatethis 当前状态的快照。

  6. this入队一个渲染命令 ,当执行时在 队列时间线 上用 renderState 进行后续步骤。

队列时间线 步骤:
  1. indexCount 为从 indirectBufferindirectOffset 字节位置读取的无符号 32 位整数。

  2. instanceCount 为从 indirectBuffer 的 (indirectOffset + 4) 字节读取的无符号 32 位整数。

  3. firstIndex 为从 indirectBuffer 的 (indirectOffset + 8) 字节读取的无符号 32 位整数。

  4. baseVertex 为从 indirectBuffer 的 (indirectOffset + 12) 字节读取的有符号 32 位整数。

  5. firstInstance 为从 indirectBuffer 的 (indirectOffset + 16) 字节读取的无符号 32 位整数。

  6. 绘制 instanceCount 个实例,从 firstInstance 开始, 每个实例由 indexCount 个带索引的顶点组成,从索引 firstIndex(对应顶点 baseVertex)开始, 使用 bindingStaterenderState 中的状态。

要判断是否可以用 GPURenderCommandsMixin encoder 进行有效绘制(valid to draw),请执行以下设备时间轴步骤:
  1. 如未满足以下任一条件,则返回 false

  2. 否则返回 true

要判断是否可以用 GPURenderCommandsMixin encoder 进行有效索引绘制(valid to draw indexed),请执行以下设备时间轴步骤:
  1. 如未满足以下任一条件,则返回 false

  2. 否则返回 true

17.2.2. 光栅化状态(Rasterization state)

GPURenderPassEncoder 拥有多种方法影响本编码器用于绘制命令的附件的光栅化过程。

setViewport(x, y, width, height, minDepth, maxDepth)

设置光栅化阶段用于线性映射从归一化设备坐标视口坐标的视口。

调用者: GPURenderPassEncoder this

参数:

参数说明:GPURenderPassEncoder.setViewport(x, y, width, height, minDepth, maxDepth)
参数 类型 可为 null 可选 描述
x float 视口的最小 X 像素值。
y float 视口的最小 Y 像素值。
width float 视口宽度(像素)。
height float 视口高度(像素)。
minDepth float 视口的最小深度值。
maxDepth float 视口的最大深度值。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. maxViewportRange = this.limits.maxTextureDimension2D × 2

  3. 如未满足以下任一条件,使 this 失效并返回:

    • x ≥ -maxViewportRange

    • y ≥ -maxViewportRange

    • 0widththis.limits.maxTextureDimension2D

    • 0heightthis.limits.maxTextureDimension2D

    • x + widthmaxViewportRange1

    • y + heightmaxViewportRange1

    • 0.0minDepth1.0

    • 0.0maxDepth1.0

    • minDepthmaxDepth

  4. 将渲染命令入队this,该命令将在队列时间轴上以 renderState 执行后续步骤。

队列时间轴步骤:
  1. xywidthheight 四者以不低于整数精度统一取整。

  2. 设置 renderState.[[viewport]] 为范围 xywidthheightminDepthmaxDepth

setScissorRect(x, y, width, height)

设置光栅化阶段使用的裁剪矩形。经过视口坐标变换后,所有落在裁剪矩形外的片元将被丢弃。

调用者: GPURenderPassEncoder this

参数:

参数说明:GPURenderPassEncoder.setScissorRect(x, y, width, height)
参数 类型 可为 null 可选 描述
x GPUIntegerCoordinate 裁剪矩形的最小 X 像素值。
y GPUIntegerCoordinate 裁剪矩形的最小 Y 像素值。
width GPUIntegerCoordinate 裁剪矩形的宽度(像素)。
height GPUIntegerCoordinate 裁剪矩形的高度(像素)。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. 如未满足以下任一条件,使 this 失效并返回:

  3. 将渲染命令入队this,该命令将在队列时间轴上以 renderState 执行后续步骤。

队列时间轴步骤:
  1. 设置 renderState.[[scissorRect]] 为范围 xywidthheight

setBlendConstant(color)

设置用于 "constant""one-minus-constant" GPUBlendFactor 的常数混合颜色和 alpha 值。

调用者: GPURenderPassEncoder this。

参数:

参数说明:GPURenderPassEncoder.setBlendConstant(color)
参数 类型 可为 null 可选 描述
color GPUColor 用于混合的颜色。

返回: undefined

内容时间轴步骤:

  1. ? 校验 GPUColor 结构(color)。

  2. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. 将渲染命令入队this,该命令将在队列时间轴上以 renderState 执行后续步骤。

队列时间轴步骤:
  1. 设置 renderState.[[blendConstant]]color

setStencilReference(reference)

设置模板测试中 "replace" GPUStencilOperation 时使用的 [[stencilReference]] 值。

调用者: GPURenderPassEncoder this。

参数:

参数说明:GPURenderPassEncoder.setStencilReference(reference)
参数 类型 可为 null 可选 描述
reference GPUStencilValue 新的模板参考值。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. 将渲染命令入队this,该命令将在队列时间轴上以 renderState 执行后续步骤。

队列时间轴步骤:
  1. 设置 renderState.[[stencilReference]]reference

17.2.3. 查询(Queries)

beginOcclusionQuery(queryIndex)
调用者: GPURenderPassEncoder this

参数:

参数说明:GPURenderPassEncoder.beginOcclusionQuery(queryIndex)
参数 类型 可为 null 可选 描述
queryIndex GPUSize32 在查询集内的查询索引。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. 如未满足以下任一条件,使 this 失效并返回:

  3. 设置 this.[[occlusion_query_active]]true

  4. 将渲染命令入队this,该命令将在队列时间轴上以 renderState 执行后续步骤。

队列时间轴步骤:
  1. 设置 renderState.[[occlusionQueryIndex]]queryIndex

endOcclusionQuery()
调用者: GPURenderPassEncoder this。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. 如未满足以下任一条件,使 this 失效并返回:

  3. 设置 this.[[occlusion_query_active]]false

  4. 将渲染命令入队this,该命令将在队列时间轴上以 renderState 执行后续步骤。

队列时间轴步骤:
  1. 如自对应 beginOcclusionQuery() 执行以来有任意片元样本通过所有每片元测试,则 passingFragments 非零,否则为零。

    注意: 如果没有发生任何 draw 调用,passingFragments 为零。

  2. passingFragments 写入 this.[[occlusion_query_set]]renderState.[[occlusionQueryIndex]] 处。

17.2.4. 渲染包(Bundles)

executeBundles(bundles)

在本渲染通道中执行此前录制到给定 GPURenderBundle 列表中的命令。

当执行 GPURenderBundle 时,不会继承渲染通道的管线、绑定组、顶点和索引缓冲区。每次 GPURenderBundle 执行完毕后,渲染通道的管线、绑定组和顶点/索引缓冲区状态都会被清除(重置为初始空值)。

注意: 状态是被清除,而不是恢复到之前的状态。即便执行 0 个 GPURenderBundles,也会发生清除。

调用者: GPURenderPassEncoder this。

参数:

参数说明:GPURenderPassEncoder.executeBundles(bundles)
参数 类型 可为 null 可选 描述
bundles sequence<GPURenderBundle> 要执行的渲染包列表。

返回: undefined

内容时间轴步骤:

  1. this.[[device]]设备时间轴上执行后续步骤。

设备时间轴步骤:
  1. 校验编码器状态。如返回 false,则返回。

  2. 如未满足以下任一条件,使 this 失效并返回:

  3. 对于 bundles 中每一个 bundle

    1. this.[[drawCount]] 增加 bundle.[[drawCount]]

    2. 合并 bundle.[[usage scope]]this.[[usage scope]]

    3. 将渲染命令入队this,该命令将在队列时间轴renderState 执行如下步骤:

      队列时间轴步骤:
      1. renderState 执行 bundle.[[command_list]] 中的每个命令。

        注意: 执行渲染包时,renderState 不能被改变。绑定状态在包编码时已捕获,执行包时不再使用。

  4. 重置渲染通道绑定状态(Reset the render pass binding state)

重置渲染通道绑定状态(Reset the render pass binding state),对 GPURenderPassEncoder encoder 执行以下设备时间轴步骤:
  1. 清空 encoder.[[bind_groups]]

  2. 设置 encoder.[[pipeline]]null

  3. 设置 encoder.[[index_buffer]]null

  4. 清空 encoder.[[vertex_buffers]]

18. 渲染包(Bundles)

渲染包(bundle)是一种部分的、受限的通道,可以被编码一次、随后多次作为后续通道编码器的一部分执行,而不像典型的命令缓冲区那样使用后即失效。对于反复发出且内容不变的命令,这可以减少编码和提交的开销。

18.1. GPURenderBundle

[Exposed=(Window, Worker), SecureContext]
interface GPURenderBundle {
};
GPURenderBundle includes GPUObjectBase;
[[command_list]], 类型为 list<GPU command>

一个 列表,包含在执行 GPURenderBundle 时需提交给 GPURenderPassEncoderGPU 命令

[[usage scope]], 类型为 usage scope,初始为空

该渲染包的 usage scope,用于后续合并到 GPURenderPassEncoder[[usage scope]],见 executeBundles()

[[layout]], 类型为 GPURenderPassLayout

渲染包的布局。

[[depthReadOnly]], 类型为 boolean

若为 true,表示执行该渲染包时不会修改深度分量。

[[stencilReadOnly]], 类型为 boolean

若为 true,表示执行该渲染包时不会修改模板分量。

[[drawCount]], 类型为 GPUSize64

GPURenderBundle 内的绘制命令数。

18.1.1. 渲染包创建(Render Bundle Creation)

dictionary GPURenderBundleDescriptor
         : GPUObjectDescriptorBase {
};
[Exposed=(Window, Worker), SecureContext]
interface GPURenderBundleEncoder {
    GPURenderBundle finish(optional GPURenderBundleDescriptor descriptor = {});
};
GPURenderBundleEncoder includes GPUObjectBase;
GPURenderBundleEncoder includes GPUCommandsMixin;
GPURenderBundleEncoder includes GPUDebugCommandsMixin;
GPURenderBundleEncoder includes GPUBindingCommandsMixin;
GPURenderBundleEncoder includes GPURenderCommandsMixin;
createRenderBundleEncoder(descriptor)

创建一个 GPURenderBundleEncoder

调用者: GPUDevice this

参数:

参数说明:GPUDevice.createRenderBundleEncoder(descriptor)
参数 类型 可为 null 可选 描述
descriptor GPURenderBundleEncoderDescriptor 要创建的 GPURenderBundleEncoder 的描述信息。

返回: GPURenderBundleEncoder

内容时间轴步骤:

  1. ? 校验纹理格式所需特性,对 descriptor.colorFormats 的每个非 null 元素,使用 this.[[device]]

  2. descriptor.depthStencilFormat 被提供

    1. ? 校验纹理格式所需特性,对 descriptor.depthStencilFormat,使用 this.[[device]]

  3. e = ! 创建新的 WebGPU 对象(this, GPURenderBundleEncoder, descriptor)。

  4. this设备时间轴上执行 初始化步骤

  5. 返回 e

设备时间轴 初始化步骤
  1. 如未满足以下任一条件:生成校验错误使 e 失效并返回。

  2. 设置 e.[[layout]]descriptor(包含的 GPURenderPassLayout 接口)的副本。

  3. 设置 e.[[depthReadOnly]]descriptor.depthReadOnly

  4. 设置 e.[[stencilReadOnly]]descriptor.stencilReadOnly

  5. 设置 e.[[state]] 为 "open"。

  6. 设置 e.[[drawCount]] 为 0。

18.1.2. 编码(Encoding)

dictionary GPURenderBundleEncoderDescriptor
         : GPURenderPassLayout {
    boolean depthReadOnly = false;
    boolean stencilReadOnly = false;
};
depthReadOnly, 类型为 boolean,默认值为 false

true 时,表示渲染包不会修改其被执行所在任意渲染通道的 GPURenderPassDepthStencilAttachment 的深度分量。

参见 只读深度-模板

stencilReadOnly, 类型为 boolean,默认值为 false

true 时,表示渲染包不会修改其被执行所在任意渲染通道的 GPURenderPassDepthStencilAttachment 的模板分量。

参见 只读深度-模板

18.1.3. 渲染包终结(Finalization)

finish(descriptor)

完成渲染包命令序列的录制。

调用者: GPURenderBundleEncoder this。

参数:

参数说明:GPURenderBundleEncoder.finish(descriptor)
参数 类型 可为 null 可选 描述
descriptor GPURenderBundleDescriptor

返回: GPURenderBundle

内容时间轴步骤:

  1. 创建新 GPURenderBundle,记为 renderBundle

  2. this.[[device]]设备时间轴上执行 finish steps

  3. 返回 renderBundle

设备时间轴 finish steps
  1. 若满足以下全部要求,则 validationSucceededtrue,否则为 false

  2. 设置 this.[[state]] 为 "ended"。

  3. validationSucceededfalse

    1. 生成校验错误

    2. 返回 失效GPURenderBundle

  4. 设置 renderBundle.[[command_list]]this.[[commands]]

  5. 设置 renderBundle.[[usage scope]]this.[[usage scope]]

  6. 设置 renderBundle.[[drawCount]]this.[[drawCount]]

19. 队列

19.1. GPUQueueDescriptor

GPUQueueDescriptor 描述了一个队列请求。

dictionary GPUQueueDescriptor
         : GPUObjectDescriptorBase {
};

19.2. GPUQueue

[Exposed=(Window, Worker), SecureContext]
interface GPUQueue {
    undefined submit(sequence<GPUCommandBuffer> commandBuffers);

    Promise<undefined> onSubmittedWorkDone();

    undefined writeBuffer(
        GPUBuffer buffer,
        GPUSize64 bufferOffset,
        AllowSharedBufferSource data,
        optional GPUSize64 dataOffset = 0,
        optional GPUSize64 size);

    undefined writeTexture(
        GPUTexelCopyTextureInfo destination,
        AllowSharedBufferSource data,
        GPUTexelCopyBufferLayout dataLayout,
        GPUExtent3D size);

    undefined copyExternalImageToTexture(
        GPUCopyExternalImageSourceInfo source,
        GPUCopyExternalImageDestInfo destination,
        GPUExtent3D copySize);
};
GPUQueue includes GPUObjectBase;

GPUQueue 拥有以下方法:

writeBuffer(buffer, bufferOffset, data, dataOffset, size)

对指定的数据发起写操作,将其写入到 GPUBuffer 中。

调用对象: GPUQueue this.

参数说明:

方法 GPUQueue.writeBuffer(buffer, bufferOffset, data, dataOffset, size) 的参数。
参数 类型 可为 null 可选 说明
buffer GPUBuffer 要写入的缓冲区。
bufferOffset GPUSize64 buffer 中开始写入的字节偏移。
data AllowSharedBufferSource 要写入 buffer 的数据。
dataOffset GPUSize64 data 中开始写入的偏移量。如果 dataTypedArray,则以元素为单位,否则以字节为单位。
size GPUSize64 要从 data 写入到 buffer 的内容大小。如果 dataTypedArray,则以元素为单位,否则以字节为单位。

返回值: undefined

内容时间线 步骤:

  1. 如果 dataArrayBufferDataView, 则元素类型为“byte”。 否则,data 是 TypedArray,元素类型为 TypedArray 的类型。

  2. dataSizedata 的大小(以元素计)。

  3. 如果 size 缺失, 则 contentsSize = dataSizedataOffset; 否则,contentsSize = size

  4. 如果下列任一条件不满足, 抛出 OperationError 并返回。

    • contentsSize ≥ 0。

    • dataOffset + contentsSizedataSize

    • contentsSize(以字节计)是 4 字节的倍数。

  5. dataContents数据源 data 所持有字节的副本

  6. contentsdataContentsdataOffset 元素开始的 contentsSize 个元素。

  7. 设备时间线 上执行后续步骤。

设备时间线 步骤:
  1. 如果下列任一条件不满足, 生成校验错误 并返回。

  2. 队列时间线 上执行后续步骤。

队列时间线 步骤:
  1. contentsbufferOffset 起写入 buffer

writeTexture(destination, data, dataLayout, size)

对指定的数据发起写操作,将其写入到 GPUTexture 中。

调用对象: GPUQueue this.

参数说明:

方法 GPUQueue.writeTexture(destination, data, dataLayout, size) 的参数。
参数 类型 可为 null 可选 说明
destination GPUTexelCopyTextureInfo 要写入的纹理子资源及其起始位置。
data AllowSharedBufferSource 要写入 destination 的数据。
dataLayout GPUTexelCopyBufferLayout data 中内容的布局。
size GPUExtent3D 要从 data 写入到 destination 的内容范围。

返回值: undefined

内容时间线 步骤:

  1. ? 校验 GPUOrigin3D 形状(destination.origin)。

  2. ? 校验 GPUExtent3D 形状(size)。

  3. dataBytes数据源 data 所持有字节的副本

    注意:本步骤描述为将所有 data 复制到设备时间线, 但实际上 data 可能远大于实际所需。实现时应当优化,仅复制必要的字节。

  4. 设备时间线 上执行后续步骤。

设备时间线 步骤:
  1. aligned = false

  2. dataLength = dataBytes.长度

  3. 如果下列任一条件不满足, 生成校验错误 并返回。

    注意:GPUCommandEncoder.copyBufferToTexture() 不同,本方法对 dataLayout.bytesPerRowdataLayout.offset 没有对齐要求。

  4. 队列时间线 上执行后续步骤。

队列时间线 步骤:
  1. blockWidthdestination.texture像素块宽度

  2. blockHeightdestination.texture像素块高度

  3. dstOrigindestination.origin

  4. dstBlockOriginX = (dstOrigin.x ÷ blockWidth)。

  5. dstBlockOriginY = (dstOrigin.y ÷ blockHeight)。

  6. blockColumns = (copySize.width ÷ blockWidth)。

  7. blockRows = (copySize.height ÷ blockHeight)。

  8. 断言 dstBlockOriginXdstBlockOriginYblockColumnsblockRows 都为整数。

  9. 对每个 z 属于区间 [0, copySize.depthOrArrayLayers − 1]:

    1. dstSubregion纹理拷贝子区域 (z + dstOrigin.z) of destination

    2. 对每个 y 属于区间 [0, blockRows − 1]:

      1. 对每个 x 属于区间 [0, blockColumns − 1]:

        1. blockOffset像素块字节偏移量(由 dataLayout 对于 (x, y, z) 以及 destination.texture 决定)。

        2. 像素块 (dstBlockOriginX + xdstBlockOriginY + y) 处的 dstSubregion 设置为 等价像素表示, 其数据由 dataBytesblockOffset 处描述。

copyExternalImageToTexture(source, destination, copySize)

对平台图片/canvas 的内容执行拷贝操作,将其复制到目标纹理中。

该操作会按照 GPUCopyExternalImageDestInfo 的参数,将数据执行颜色编码,转换为目标编码。

拷贝到 -srgb 纹理中时,其结果纹理的字节内容与对应的非 -srgb 格式拷贝相同,但解码值会不同。 因此,拷贝完成后,采样目标纹理的结果会因格式是否为 -srgb 而不同,其他条件不变。

注意:
当从 "webgl"/"webgl2" 上下文的 canvas 拷贝时, WebGL 绘制缓冲区 在帧显示周期的某些时间点(如图像被送到合成器显示后)可能不存在。 为避免此问题,可以:
  • 在与 WebGL 渲染操作相同的 task 内调用 copyExternalImageToTexture(), 以确保拷贝发生在 WebGL canvas 显示前。

  • 如果无法做到,可在 WebGLContextAttributes 中设置 preserveDrawingBuffer 选项为 true,这样帧内容在显示后缓冲区中仍保留一份副本。 注意,这样会有额外的性能开销。

调用对象: GPUQueue this.

参数说明:

方法 GPUQueue.copyExternalImageToTexture(source, destination, copySize) 的参数。
参数 类型 可为 null 可选 说明
source GPUCopyExternalImageSourceInfo 要拷贝的源图像及其起始位置。
destination GPUCopyExternalImageDestInfo 要写入的纹理子资源及其起始位置及编码元数据。
copySize GPUExtent3D 要从 source 写入到 destination 的内容范围。

返回值: undefined

内容时间线 步骤:

  1. ? 校验 GPUOrigin2D 形状(source.origin)。

  2. ? 校验 GPUOrigin3D 形状(destination.origin)。

  3. ? 校验 GPUExtent3D 形状(copySize)。

  4. sourceImagesource.source

  5. 如果 sourceImage 不是同源, 抛出 SecurityError 并返回。

  6. 如果下列任一条件不满足,抛出 OperationError 并返回。

    • source.origin.x + copySize.width 必须 ≤ sourceImage 的宽度。

    • source.origin.y + copySize.height 必须 ≤ sourceImage 的高度。

    • copySize.depthOrArrayLayers 必须 ≤ 1。

  7. usability? 检查图像参数可用性(source)。

  8. 设备时间线 上执行后续步骤。

设备时间线 步骤:
  1. texturedestination.texture

  2. 如果下列任一条件不满足,生成校验错误 并返回。

  3. 如果 copySize.depthOrArrayLayers > 0,则在 队列时间线 上执行后续步骤。

队列时间线 步骤:
  1. 断言 destination.texture像素块宽度为 1, 像素块高度为 1,且 copySize.depthOrArrayLayers 为 1。

  2. srcOriginsource.origin

  3. dstOrigindestination.origin

  4. dstSubregion纹理拷贝子区域(dstOrigin.z) of destination

  5. 对于 y ∈ [0, copySize.height − 1]:

    1. srcY 等于 y,如果 source.flipYfalse,否则为 (copySize.height − 1 − y)。

    2. 对于 x ∈ [0, copySize.width − 1]:

      1. dstSubregion像素块 (dstOrigin.x + x, dstOrigin.y + y) 设置为 source.source 中 (srcOrigin.x + x, srcOrigin.y + srcY) 像素的 等价像素表示, 并根据 destination.colorSpacedestination.premultipliedAlpha 应用所需的颜色编码后得到。

submit(commandBuffers)

安排 GPU 在此队列上执行命令缓冲区。

已提交的命令缓冲区不可再次使用。

调用对象: GPUQueue this.

参数说明:

方法 GPUQueue.submit(commandBuffers) 的参数。
参数 类型 可为 null 可选 说明
commandBuffers sequence<GPUCommandBuffer>

返回值: undefined

内容时间线 步骤:

  1. 设备时间线 上执行后续步骤:

设备时间线 步骤:
  1. 如果下列任一条件不满足,生成校验错误使每个 GPUCommandBuffercommandBuffers 中失效并返回。

  2. commandBuffers 中每个 commandBuffer

    1. 使 commandBuffer 失效。

  3. 队列时间线 上执行后续步骤:

队列时间线 步骤:
  1. commandBuffers 中每个 commandBuffer

    1. 执行 commandBuffer.[[command_list]] 中的每条命令。

onSubmittedWorkDone()

返回一个 Promise ,当队列处理完目前为止提交的所有工作后,该 Promise 会被 resolve。

Promise resolve 意味着在此之前调用过的 mapAsync() 并且最后只在该队列上独占使用过的 GPUBuffer 的操作也已完成。

调用对象: GPUQueue this.

返回值: Promise<undefined>

内容时间线 步骤:

  1. contentTimeline 为当前 内容时间线

  2. promise一个新的 promise

  3. 设备时间线 上执行 synchronization steps

  4. 返回 promise

设备时间线 synchronization steps
  1. 所有当前排队的操作完成时,发生 event

  2. 监听时间线事件 eventthis.[[device]], 后续步骤由 contentTimeline 处理。

内容时间线 步骤:
  1. resolve promise

20. 查询(Queries)

20.1. GPUQuerySet

[Exposed=(Window, Worker), SecureContext]
interface GPUQuerySet {
    undefined destroy();

    readonly attribute GPUQueryType type;
    readonly attribute GPUSize32Out count;
};
GPUQuerySet includes GPUObjectBase;

GPUQuerySet 拥有以下不可变属性

type, 类型为 GPUQueryType,只读

GPUQuerySet 管理的查询的类型。

count, 类型为 GPUSize32Out,只读

GPUQuerySet 管理的查询数量。

GPUQuerySet 拥有以下设备时间线属性

[[destroyed]], 类型为 boolean, 初始值为 false

如果查询集被销毁,则不能再用于任何操作,其底层内存可被释放。

20.1.1. 查询集创建(QuerySet Creation)

GPUQuerySetDescriptor 指定用于创建 GPUQuerySet 时的选项。

dictionary GPUQuerySetDescriptor
         : GPUObjectDescriptorBase {
    required GPUQueryType type;
    required GPUSize32 count;
};
type, 类型为 GPUQueryType

GPUQuerySet 管理的查询类型。

count, 类型为 GPUSize32

GPUQuerySet 管理的查询数量。

createQuerySet(descriptor)

创建一个 GPUQuerySet

调用对象: GPUDevice this.

参数说明:

方法 GPUDevice.createQuerySet(descriptor) 的参数。
参数 类型 可为 null 可选 说明
descriptor GPUQuerySetDescriptor 要创建的 GPUQuerySet 的描述信息。

返回值: GPUQuerySet

内容时间线 步骤:

  1. 如果 descriptor.type"timestamp", 但 "timestamp-query" 没有 this 启用:

    1. 抛出 TypeError

  2. q! 创建新的 WebGPU 对象(this, GPUQuerySet, descriptor).

  3. 设置 q.typedescriptor.type

  4. 设置 q.countdescriptor.count

  5. 设备时间线 上执行 初始化步骤

  6. 返回 q

设备时间线 初始化步骤
  1. 如果以下任一条件不满足,生成校验错误使 q 失效并返回。

    • this 不得为丢失状态。

    • descriptor.count 必须 ≤ 4096。

  2. q 创建一个设备分配,查询集内的每个条目初始化为 0。

    如果分配失败且无副作用, 生成内存不足错误使 q 失效并返回。

创建一个包含 32 个遮挡查询结果的 GPUQuerySet
const querySet = gpuDevice.createQuerySet({
    type: 'occlusion',
    count: 32
});

20.1.2. 查询集销毁(Query Set Destruction)

应用在不再需要 GPUQuerySet 时,可以通过调用 destroy() 主动失去对其的访问权,无需等到垃圾回收。

GPUQuerySet 拥有以下方法:

destroy()

销毁该 GPUQuerySet

调用对象: GPUQuerySet this.

返回值: undefined

内容时间线 步骤:

  1. 设备时间线 上执行后续步骤。

设备时间线 步骤:
  1. this.[[destroyed]] 设为 true

20.2. 查询类型(QueryType)

enum GPUQueryType {
    "occlusion",
    "timestamp",
};

20.3. 遮挡查询(Occlusion Query)

遮挡查询仅可在渲染通道(render pass)中使用,用于统计一组绘制命令中所有片元通过所有片元测试(包括剪裁、采样掩码、透明度覆盖、模板和深度测试)后,实际输出合并阶段的片元采样数量。查询结果为非零时,表示至少有一个采样通过测试并到达渲染管线的输出合并阶段;为 0 时,表示没有采样通过测试。

在开始一个渲染通道时,必须设置 GPURenderPassDescriptor.occlusionQuerySet ,以便在该通道内使用遮挡查询。遮挡查询需成对调用 beginOcclusionQuery()endOcclusionQuery() ,且不可嵌套,并通过 GPUBufferGPUCommandEncoder.resolveQuerySet() 解析为64 位无符号整数

20.4. 时间戳查询(Timestamp Query)

时间戳查询允许应用通过以下方式将时间戳写入 GPUQuerySet

然后通过 GPUCommandEncoder.resolveQuerySet() 将时间戳值(以纳秒为单位,64 位无符号整数)解析到 GPUBuffer

时间戳值是实现定义的,并不保证单调递增。物理设备可能偶尔重置时间戳计数器,这会导致时间戳出现非预期的数值(如本应递增却出现负间隔)。这种情况应较为罕见,可以安全忽略。应用不应因意外的时间戳值而导致程序失败。

There is a tracking vector here. 时间戳查询由高精度计时器实现(参见 § 2.1.7.2 设备/队列时间线计时)。 为降低安全性和隐私风险,其精度必须被降低:

获取当前队列时间戳时,执行如下队列时间线步骤:

注意:由于跨域隔离通常不适用于 设备时间线队列时间线crossOriginIsolatedCapability 永远不会设为 true

校验 timestampWrites(device, timestampWrites)

参数:

设备时间线 步骤:

  1. 若满足以下要求则返回 true,否则返回 false

    • "timestamp-query" 必须 device 启用。

    • timestampWrites.querySet 必须 可与 device 一起使用。

    • timestampWrites.querySet.type 必须为 "timestamp"

    • timestampWrites 的写入索引成员 (beginningOfPassWriteIndexendOfPassWriteIndex)中:

      • 至少要有一个被指定

      • 若指定了多个:

        • 不得有重复值。

        • 每个索引都必须小于 timestampWrites.querySet.count

21. 画布渲染(Canvas Rendering)

21.1. HTMLCanvasElement.getContext()

GPUCanvasContext 对象是通过 getContext() 方法(传入字符串字面量 'webgpu' 作为 contextType 参数)在 HTMLCanvasElement 实例上创建的。

从一个离屏 HTMLCanvasElement 获取 GPUCanvasContext
const canvas = document.createElement('canvas');
const context = canvas.getContext('webgpu');

与 WebGL 或 2D 上下文创建不同,HTMLCanvasElement.getContext()OffscreenCanvas.getContext() 的第二个参数(上下文创建属性字典 options)会被忽略。 请改用 GPUCanvasContext.configure(), 该方法允许在不替换画布的情况下改变画布配置。

在画布上创建 'webgpu' 上下文HTMLCanvasElementOffscreenCanvas canvas),请执行以下 内容时间线步骤:
  1. context 为一个新的 GPUCanvasContext

  2. 设置 context.canvascanvas

  3. 替换 context 的绘制缓冲区。

  4. 返回 context

注意: 当调用 getContext() 获取 WebGPU 画布上下文时,如果传入了被忽略的 options 参数,用户代理应考虑向开发者发出可见警告。

21.2. GPUCanvasContext

[Exposed=(Window, Worker), SecureContext]
interface GPUCanvasContext {
    readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas;

    undefined configure(GPUCanvasConfiguration configuration);
    undefined unconfigure();

    GPUCanvasConfiguration? getConfiguration();
    GPUTexture getCurrentTexture();
};

GPUCanvasContext 拥有以下内容时间线属性

canvas, 类型为 (HTMLCanvasElement 或 OffscreenCanvas),只读

此上下文创建自的画布对象。

[[configuration]],类型为 GPUCanvasConfiguration? ,初始值为 null

此上下文当前配置所用的参数。

如果上下文尚未配置或已经调用 unconfigure() ,则为 null

[[textureDescriptor]],类型为 GPUTextureDescriptor? ,初始值为 null

当前配置的纹理描述符,由 [[configuration]] 和画布生成。

若上下文尚未配置或已 unconfigure() ,则为 null

[[drawingBuffer]],一个图片对象,初始为 与画布同尺寸的透明黑色图像

绘制缓冲区是画布的工作副本图像数据。 通过 [[currentTexture]] (由 getCurrentTexture() 返回)可获得可写视图。

绘制缓冲区用于获取上下文图像内容副本 (如画布显示或读取时)。即使 [[configuration]].alphaMode"opaque",绘制缓冲区仍可能为透明。 alphaMode 仅影响“获取上下文图像内容副本”算法的结果。

绘制缓冲区的生命周期超出 [[currentTexture]] ,即使画布已显示,之前渲染的内容也仍然保留。只有在替换绘制缓冲区时才会清除。

每当读取绘制缓冲区时,必须确保所有之前提交的写入操作(例如队列提交)都已通过 [[currentTexture]] 完成。

[[currentTexture]],类型为 GPUTexture? ,初始为 null

当前帧要绘制的 GPUTexture。 它提供了底层 [[drawingBuffer]] 的可写视图。 getCurrentTexture() 若该槽为 null 则填充后返回。

在可见画布的稳定状态下,通过 currentTexture 对绘制缓冲区的更改在更新 WebGPU 画布渲染时被显示。 此时或之前,纹理会被销毁, [[currentTexture]] 被置为 null,下次调用 getCurrentTexture() 时会重新创建。

销毁 currentTexture 不影响绘制缓冲区内容,只是提前终止了对该缓冲区的写访问。 在同一帧内,getCurrentTexture() 依然返回相同的已销毁纹理。

过期当前纹理会把 currentTexture 置为 null。 它由 configure()、 画布尺寸变更、显示、transferToImageBitmap() 等调用。

[[lastPresentedImage]],类型为 (readonly image)?,初始为 null

最近一次在“更新 WebGPU 画布渲染”中展示的图片。 如果设备丢失或被销毁,该图片 可以 作为“获取上下文图像内容副本”的回退,以防画布变空白。

注意: 只有实现了回退机制的实现才需要有该属性,这不是强制的。

GPUCanvasContext 拥有以下方法:

configure(configuration)

为该画布上下文配置参数。 这会把绘制缓冲区清为透明黑(见 替换绘制缓冲区)。

调用对象: GPUCanvasContext this.

参数说明:

方法 GPUCanvasContext.configure(configuration) 的参数。
参数 类型 可为 null 可选 说明
configuration GPUCanvasConfiguration 上下文的期望配置。

返回值: undefined

内容时间线步骤:

  1. device = configuration.device

  2. ? 校验纹理格式所需特性 (configuration.formatdevice.[[device]])。

  3. ? 校验纹理格式所需特性(对 configuration.viewFormats 的每一个元素, device.[[device]])。

  4. 如果支持的上下文格式包含 configuration.format ,则抛出 TypeError

  5. descriptor = 为画布和配置生成 GPUTextureDescriptor(this.canvas, configuration)。

  6. 设置 this.[[configuration]]configuration

    注意:
    本规范要求通过 toneMapping 选项支持 HDR。 如果用户代理仅支持 toneMapping: "standard", 那么 toneMapping 属性不应存在于 GPUCanvasConfiguration, 因此不会出现在 getConfiguration() 返回值,也不会被 configure() 访问。 这允许网站检测功能支持。
  7. 设置 this.[[textureDescriptor]]descriptor

  8. 替换绘制缓冲区

  9. 设备时间线 上执行后续步骤。

设备时间线步骤:
  1. 若下列任一条件不满足,生成校验错误并返回。

    注意: 该早期校验在下次 configure() 调用前有效,size 校验例外,画布尺寸变更时需重新校验。

unconfigure()

移除上下文配置,并销毁所有在配置期间创建的纹理。

调用对象: GPUCanvasContext this.

返回值: undefined

内容时间线步骤:

  1. this.[[configuration]] 置为 null

  2. this.[[textureDescriptor]] 置为 null

  3. 替换绘制缓冲区

getConfiguration()

返回上下文配置。

调用对象: GPUCanvasContext this.

返回值: GPUCanvasConfigurationnull

内容时间线步骤:

  1. configurationthis.[[configuration]] 的副本。

  2. 返回 configuration

注意:
getConfiguration() 显示 toneMapping 已实现且 dynamic-range 媒体查询指示支持 HDR 时,WebGPU 画布使用完整 HDR 范围渲染内容,而不是将值钳制在 HDR 显示的 SDR 范围内。
getCurrentTexture()

获取即将由 GPUCanvasContext 合成到文档的 GPUTexture

注意:
应用在绘制到画布纹理的同一个任务中调用 getCurrentTexture() 。否则,该纹理可能会在应用渲染完成前被下面这些步骤销毁。

过期任务(定义见下)是可选实现的。即使实现了,任务源优先级不是规范定义的,可能最快在下一个任务发生,也可能等到所有任务源为空才发生(见 automatic expiry task source)。 只有在可见画布被显示时(更新 WebGPU 画布渲染)及其他 "过期当前纹理" 调用方才保证过期。

调用对象: GPUCanvasContext this.

返回值: GPUTexture

内容时间线步骤:

  1. 如果 this.[[configuration]]null, 抛出 InvalidStateError 并返回。

  2. 断言 this.[[textureDescriptor]] 不为 null

  3. devicethis.[[configuration]].device

  4. 如果 this.[[currentTexture]]null

    1. 替换绘制缓冲区

    2. 设置 this.[[currentTexture]] 为调用 device.createTexture() 并传入 this.[[textureDescriptor]] 的结果,但 GPUTexture 底层存储指向 this.[[drawingBuffer]]

      注意: 如果纹理无法创建(如校验失败或内存不足),则会抛出错误并返回无效化GPUTexture。 这里的部分校验与 configure() 中的校验重复,实现不得跳过这些校验。

  5. 可选排队自动过期任务,参数为 device device 和下列步骤:

    1. 过期当前纹理

      注意: 如果在 更新 WebGPU 画布渲染 时已发生则无影响。

  6. 返回 this.[[currentTexture]]

注意: 每次调用 getCurrentTexture() 都会返回同一个 GPUTexture 对象,直到执行“过期当前纹理”,即使该纹理被销毁、校验失败或分配失败也如此。

获取上下文图像内容的副本

参数:

返回: 图像内容

内容时间线 步骤:

  1. snapshot 为一个与 context.canvas 尺寸相同的透明黑图片。

  2. configurationcontext.[[configuration]]

  3. 如果 configurationnull

    1. 返回 snapshot

    注意: 当上下文尚未配置或已被 unconfigure() 时,configuration 会是 null。这与画布没有上下文时的行为一致。

  4. 确保所有已提交的工作项(如队列提交)都已通过 context.[[currentTexture]] 完成对图像的写入。

  5. 如果 configuration.device 被认为有效

    1. snapshot 设为 context.[[drawingBuffer]] 的副本。

    否则,如果 context.[[lastPresentedImage]] 不为 null

    1. 可选,将 snapshot 设为 context.[[lastPresentedImage]] 的副本。

      注意: 这是可选的,因为 [[lastPresentedImage]] 可能已不存在,取决于设备丢失的原因。即使实现仍可访问该图像,也可以选择跳过此步骤。

  6. alphaModeconfiguration.alphaMode

  7. 如果 alphaMode"opaque":
    1. snapshot 的 alpha 通道清为 1.0。

    2. snapshot 标记为 opaque。

    注意: 如果 [[currentTexture]] (若有)已被销毁(如在“过期当前纹理”时),alpha 通道是不可观察的,实现可以就地清除 alpha。

    否则:

    snapshotalphaMode 标记。

  8. snapshotconfigurationcolorSpacetoneMapping 标记。

  9. 返回 snapshot

替换绘制缓冲区,对 GPUCanvasContext context 执行如下 内容时间线 步骤:
  1. 过期当前纹理

  2. configurationcontext.[[configuration]]

  3. context.[[drawingBuffer]] 设为与 context.canvas 尺寸相同的透明黑图片。

    • 如果 configuration 为 null,绘制缓冲区用颜色空间 "srgb" 标记。在此情况下,缓冲区会保持空白直到配置上下文。

    • 否则,绘制缓冲区拥有指定的 configuration.format ,并用指定的 configuration.colorSpaceconfiguration.toneMapping 标记。

    注意: configuration.alphaMode 在“获取上下文图像内容副本”前会被忽略。

    注意:
    新替换的绘制缓冲区图像表现为被清为透明黑,但如同 "discard" 一样,实现可以按需惰性清除,只有在必要时才清除。

    注意: 如果绘制缓冲区已清空且配置正确,则通常这不会有实际效果。

过期当前纹理,对 GPUCanvasContext context 执行如下 内容时间线 步骤:
  1. 如果 context.[[currentTexture]] 不为 null

    1. 调用 context.[[currentTexture]].destroy() (不销毁 context.[[drawingBuffer]]), 以终止对图像的写入访问。

    2. context.[[currentTexture]] 设为 null

21.3. HTML 规范挂钩

下列算法“挂钩”到 HTML 规范中的相关算法,并必须在指定时机运行。

当从带有 GPUCanvasContext contextHTMLCanvasElementOffscreenCanvas 读取 “bitmap” 时,执行如下 内容时间线 步骤:
  1. 返回 该 context 的图像内容副本

注意:
这一过程会在多个场景下触发,包括:

如果 alphaMode"opaque",则会清除 alpha 通道。若实现能以忽略 alpha 通道的方式读取或显示图像,则可跳过此步骤。

如果应用仅为互操作(非展示)目的使用画布,不需要时应避免 "opaque"

更新 WebGPU 画布渲染 (带有 占位画布元素HTMLCanvasElementOffscreenCanvas) 并带有 GPUCanvasContext context 时,在取得画布图像内容之前,于 事件循环处理模型 的以下子步骤:

注意: Service worker 和 Shared worker 没有“更新渲染”步骤,因为它们不能渲染用户可见画布。 requestAnimationFrame()ServiceWorkerGlobalScopeSharedWorkerGlobalScope 不可用, OffscreenCanvastransferControlToOffscreen() 创建后不能发送到这些 worker

执行以下 内容时间线 步骤:

  1. 过期当前纹理

    注意: 如果之前已在 getCurrentTexture() 排队的任务中执行,则本步骤无实际效果。

  2. context.[[lastPresentedImage]] 设为 context.[[drawingBuffer]]

    注意: 这里只是引用,不是副本;当前纹理过期后,绘制缓冲区内容不可再原地更改。

注意: 这不会发生在独立创建的 OffscreenCanvas (例如 new OffscreenCanvas())上。

transferToImageBitmap from WebGPU

当在带有 GPUCanvasContext context 的画布上调用 transferToImageBitmap() 后,从画布的 bitmap 创建 ImageBitmap ,执行如下 内容时间线 步骤:

  1. 替换绘制缓冲区

注意: 这使得 transferToImageBitmap() 等价于“移动”图像内容(可能包括清除 alpha),而无需复制。

21.4. GPUCanvasConfiguration

支持的上下文格式是以下 集合中的 GPUTextureFormat: «"bgra8unorm""rgba8unorm""rgba16float"»。 当这些格式被指定为 GPUCanvasConfiguration.format 时,无论 GPUCanvasConfiguration.device 如何,都必须被支持。

注意: 画布配置不能使用 srgb 格式,如 "bgra8unorm-srgb"。 应该使用非 srgb 的等价格式(如 "bgra8unorm"), 在 viewFormats 中指定 srgb 格式, 并通过 createView() 创建一个 srgb 格式的视图。

enum GPUCanvasAlphaMode {
    "opaque",
    "premultiplied",
};

enum GPUCanvasToneMappingMode {
    "standard",
    "extended",
};

dictionary GPUCanvasToneMapping {
  GPUCanvasToneMappingMode mode = "standard";
};

dictionary GPUCanvasConfiguration {
    required GPUDevice device;
    required GPUTextureFormat format;
    GPUTextureUsageFlags usage = 0x10;  // GPUTextureUsage.RENDER_ATTACHMENT
    sequence<GPUTextureFormat> viewFormats = [];
    PredefinedColorSpace colorSpace = "srgb";
    GPUCanvasToneMapping toneMapping = {};
    GPUCanvasAlphaMode alphaMode = "opaque";
};

GPUCanvasConfiguration 拥有以下成员:

device类型为 GPUDevice

通过 getCurrentTexture() 返回的纹理将与该 GPUDevice 兼容。

format类型为 GPUTextureFormat

通过 getCurrentTexture() 返回的纹理的格式。必须为支持的上下文格式之一。

usage类型为 GPUTextureUsageFlags,默认值为0x10

通过 getCurrentTexture() 返回的纹理的用途。RENDER_ATTACHMENT 为默认用途,但如果显式设置 usage,则不会自动包含。若需将 getCurrentTexture() 返回的纹理作为渲染通道的颜色目标,请确保包含 RENDER_ATTACHMENT

viewFormats类型为 sequence<GPUTextureFormat>,默认值为[]

通过 getCurrentTexture() 返回的纹理所创建视图允许使用的格式。

colorSpace类型为 PredefinedColorSpace,默认值为"srgb"

写入到通过 getCurrentTexture() 返回纹理的值将以该色彩空间显示。

toneMapping类型为 GPUCanvasToneMapping,默认值为 {}

色调映射决定通过 getCurrentTexture() 返回纹理的内容如何显示。

注意: 如果实现不支持 HDR WebGPU 画布,则也不应暴露该成员,以便特性检测。参见 getConfiguration()

alphaMode类型为 GPUCanvasAlphaMode,默认值为"opaque"

决定 alpha 值在通过 getCurrentTexture() 返回纹理被读取、显示或用作图像源时的效果。

配置一个 GPUCanvasContext 以和指定的 GPUDevice 配合使用,并采用此上下文的首选格式:
const canvas = document.createElement('canvas');
const context = canvas.getContext('webgpu');

context.configure({
    device: gpuDevice,
    format: navigator.gpu.getPreferredCanvasFormat(),
});
为画布和配置生成 GPUTextureDescriptor( (HTMLCanvasElementOffscreenCanvas) canvas, GPUCanvasConfiguration configuration) 是一个 GPUTextureDescriptor ,具有以下成员:

其它成员均使用默认值。

canvas.width 指 HTMLCanvasElement.widthOffscreenCanvas.widthcanvas.height 指 HTMLCanvasElement.heightOffscreenCanvas.height

21.4.1. 画布色彩空间

在展示时,画布中的颜色值会被转换到屏幕的色彩空间。

toneMapping 决定了在屏幕色彩空间内对超出 [0, 1] 区间的值的处理方式。

21.4.2. 画布上下文尺寸

除画布的分辨率(由 canvas 的 widthheight 设置)外,所有画布配置都通过 configure() 进行设置。

注意: 与 WebGL 和 2D 画布类似,调整 WebGPU 画布大小会丢失当前绘制缓冲区的内容。在 WebGPU 中,这是通过替换绘制缓冲区实现的。

当带有 GPUCanvasContext contextHTMLCanvasElementOffscreenCanvas canvas 设置了 widthheight 属性时, 更新画布大小,执行以下内容时间线步骤:
  1. 替换绘制缓冲区

  2. configurationcontext.[[configuration]]

  3. 如果 configuration 不为 null

    1. context.[[textureDescriptor]] 设为 为画布和配置生成 GPUTextureDescriptor(canvas, configuration)。

注意: 这可能会生成一个超出设备 GPUTextureDescriptor maxTextureDimension2D 限制的纹理描述符,此时在 getCurrentTexture() 内部校验会失败。

注意: 只要设置了 canvaswidthheight 属性,无论值有无变化,该算法都会运行。

21.5. GPUCanvasToneMappingMode

该枚举指定颜色值如何显示到屏幕。

"standard"

在屏幕标准动态范围内的颜色值保持不变,所有其它颜色值被投影到屏幕的标准动态范围内。

注意: 这种投影通常通过将颜色空间内的颜色值钳制到 [0, 1] 区间来实现。

例如,假设将值 (1.035, -0.175, -0.140) 写入一个 'srgb' 画布。

如果将其呈现到 sRGB 屏幕,则会先转换为 sRGB(因为画布本身就是 sRGB,所以实际无变化),再投影到显示空间。使用分量逐一钳制,结果为 sRGB 值 (1.0, 0.0, 0.0)

如果将其呈现到 Display P3 屏幕,则会转换为 Display P3 色彩空间的值 (0.948, 0.106, 0.01),无需钳制。

"extended"

在屏幕扩展动态范围内的颜色值保持不变,所有其它颜色值被投影到屏幕的扩展动态范围内。

注意: 这种投影通常通过将颜色空间内的颜色值钳制到屏幕可显示的值区间来实现,该区间可能包括大于 1 的值。

例如,假设将值 (2.5, -0.15, -0.15) 写入一个 'srgb' 画布。

如果将其呈现到支持 [0, 4] 区间的 sRGB 屏幕,则会先转换为 sRGB(画布本身就是 sRGB,实际无变化),再投影到显示空间。使用分量逐一钳制,结果为 sRGB 值 (2.5, 0.0, 0.0)

如果将其呈现到支持 [0, 2] 区间的 Display P3 屏幕,则会转换为 Display P3 色彩空间的值 (2.3, 0.545, 0.386),再投影到显示空间。使用分量逐一钳制,结果为 Display P3 值 (2.0, 0.545, 0.386)

21.6. GPUCanvasAlphaMode

该枚举选择画布内容在读取、显示到屏幕或用作图像源 时(如在 drawImage、toDataURL 等)如何解释。

下文中,src 表示画布纹理中的一个值,dst 表示画布被合成到的目标图像(如 HTML 页面渲染或 2D 画布)。

"opaque"

以不透明方式读取 RGB,忽略 alpha 值。如果内容本身不是不透明的,则在“获取上下文图像内容副本”时将 alpha 通道清为 1.0。

"premultiplied"

以预乘方式读取 RGBA:颜色值已乘以其 alpha。100% 红色,50% alpha 时为 [0.5, 0, 0, 0.5]

如果画布纹理在内容读取时包含超色域预乘 RGBA 值,行为取决于画布的用途:

作为图像源

值会保留,详情见色彩空间转换

显示到屏幕

合成结果未定义。

注意: 即使色彩空间转换本可在合成前产生在色域内的值,合成的中间格式未指定,因此结果未定义。

22. 错误与调试

在 WebGPU 的正常操作过程中,通过 分发错误(dispatch error) 抛出错误。

在设备 丢失 后,尽可能不再抛出错误。 从此时起,实现不再需要执行校验或错误跟踪:

22.1. 致命错误

enum GPUDeviceLostReason {
    "unknown",
    "destroyed",
};

[Exposed=(Window, Worker), SecureContext]
interface GPUDeviceLostInfo {
    readonly attribute GPUDeviceLostReason reason;
    readonly attribute DOMString message;
};

partial interface GPUDevice {
    readonly attribute Promise<GPUDeviceLostInfo> lost;
};

GPUDevice 拥有以下额外属性:

lost类型为 Promise<GPUDeviceLostInfo>,只读

一个槽支持属性,其值为设备创建时即产生、在设备生命周期内保持挂起,设备丢失时被解析的 promise。

初始化时,该属性被设置为一个新的 promise

22.2. GPUError

[Exposed=(Window, Worker), SecureContext]
interface GPUError {
    readonly attribute DOMString message;
};

GPUError 是所有 popErrorScope()uncapturederror 事件抛出的错误的基类。

只有那些在各自算法中明确说明可能抛出错误条件及其子类型的操作,才会生成错误。

丢失的设备不会生成任何错误。参见 § 22 错误与调试

注意: GPUError 在本规范未来版本中可能会增加新的子类型。应用应处理此种可能性,优先仅使用错误的 message,如需特殊处理可用 instanceof。如果需要序列化错误(如用于 JSON 或调试报告),可用 error.constructor.name

GPUError 拥有以下不可变属性

message类型为 DOMString,只读

一条人类可读、可本地化文本消息,提供关于发生错误的信息。

注意: 此消息通常用于应用开发者调试及收集调试报告信息,不应直接呈现给终端用户。

注意: 用户代理不应在此消息中包含机器可解析的信息,如 "out-of-memory" 时的系统内存剩余情况,或其他内存耗尽相关细节。

注意: message 应遵循语言和方向信息最佳实践,包括未来标准关于字符串语言和方向元数据的规范。

编辑注: 截至本文撰写时,还没有既兼容又与旧 API 保持一致的语言/方向推荐方案,未来出现时应正式采用。

[Exposed=(Window, Worker), SecureContext]
interface GPUValidationError
        : GPUError {
    constructor(DOMString message);
};

GPUValidationErrorGPUError 的子类型,表示某操作未满足所有校验要求。校验错误总是应用错误的表现,假定使用相同 [[features]][[limits]] ,应在所有设备上以同样方式失败。

要为 GPUDevice device 生成校验错误,请执行以下步骤:

设备时间线 步骤:

  1. error 为带有合适错误信息的新 GPUValidationError

  2. 分发错误 errordevice

[Exposed=(Window, Worker), SecureContext]
interface GPUOutOfMemoryError
        : GPUError {
    constructor(DOMString message);
};

GPUOutOfMemoryErrorGPUError 的子类型,表示没有足够的空闲内存完成请求的操作。若用更低内存需求(如更小的纹理尺寸)重试,或先释放其他资源占用的内存,操作可能会成功。

要为 GPUDevice device 生成内存不足错误,请执行以下步骤:

设备时间线 步骤:

  1. error 为带有合适错误信息的新 GPUOutOfMemoryError

  2. 分发错误 errordevice

[Exposed=(Window, Worker), SecureContext]
interface GPUInternalError
        : GPUError {
    constructor(DOMString message);
};

GPUInternalErrorGPUError 的子类型,表示即使满足所有校验要求,操作仍因系统或实现特定原因失败。例如,操作可能超出了实现能力,而这些无法被支持的限制准确描述。同一操作在其他设备或不同情形下可能成功。

要为 GPUDevice device 生成内部错误,请执行以下步骤:

设备时间线 步骤:

  1. error 为带有合适错误信息的新 GPUInternalError

  2. 分发错误 errordevice

22.3. 错误作用域(Error Scopes)

GPU 错误作用域 会捕获在该 GPU 错误作用域 当前时生成的 GPUError。 错误作用域用于隔离一组 WebGPU 调用过程中发生的错误,通常用于调试或使操作更加容错。

GPU 错误作用域拥有以下设备时间线属性

[[errors]],类型为 list<GPUError>,初始值为 []

GPU 错误作用域 当前时观察到的所有 GPUError(如果有)。

[[filter]],类型为 GPUErrorFilter

决定此 GPU 错误作用域 观测哪些类型的 GPUError

enum GPUErrorFilter {
    "validation",
    "out-of-memory",
    "internal",
};

partial interface GPUDevice {
    undefined pushErrorScope(GPUErrorFilter filter);
    Promise<GPUError?> popErrorScope();
};

GPUErrorFilter 定义了调用 pushErrorScope() 时要捕获的错误类型:

"validation"

表示该错误作用域将捕获 GPUValidationError

"out-of-memory"

表示该错误作用域将捕获 GPUOutOfMemoryError

"internal"

表示该错误作用域将捕获 GPUInternalError

GPUDevice 拥有以下设备时间线属性

[[errorScopeStack]],类型为 stack<GPU 错误作用域>

已被推送到 GPUDevice 上的 错误作用域栈

当前错误作用域,用于 GPUError errorGPUDevice device,通过对 device设备时间线执行以下步骤确定:

设备时间线步骤:

  1. 如果 error 是以下类型的实例:

    GPUValidationError

    type 为 "validation"。

    GPUOutOfMemoryError

    type 为 "out-of-memory"。

    GPUInternalError

    type 为 "internal"。

  2. scopedevice.[[errorScopeStack]] 的最后一个

  3. scope 不为 undefined 时:

    1. 如果 scope.[[filter]] 等于 type,则返回 scope

    2. scope 设为 device.[[errorScopeStack]] 的前一

  4. 返回 undefined

分发错误 GPUError errorGPUDevice device,请执行以下设备时间线步骤:
设备时间线步骤:

注意: 丢失的设备不会生成错误。 如果在device丢失时调用本算法,应用将无法观察到该错误。 参见§ 22 错误与调试

  1. scopeerrordevice当前错误作用域

  2. 如果 scope 不为 undefined

    1. 追加 errorscope.[[errors]]

    2. 返回。

  3. 否则,执行以下内容时间线步骤:

内容时间线步骤:
  1. 如用户代理选择,为 GPUDevice device 排队全局任务,步骤如下:

    1. device 上触发一个名为 "uncapturederror" 的 GPUUncapturedErrorEvent, 其 errorerror

注意: 派发事件后,用户代理应当将未捕获的错误暴露给开发者,例如在浏览器开发者控制台中作为警告,除非事件的 defaultPrevented 为 true。换句话说,调用 preventDefault() 可以阻止控制台警告。

注意: 用户代理可选择限制 GPUUncapturedErrorEvent 的数量,以防过多错误处理或日志影响性能。

pushErrorScope(filter)

将一个新的GPU 错误作用域压入 this[[errorScopeStack]]

调用对象: GPUDevice this

参数:

参数列表:GPUDevice.pushErrorScope(filter)
参数 类型 可为 null 可选 说明
filter GPUErrorFilter 该错误作用域关注的错误类型。

返回: undefined

内容时间线步骤:

  1. this设备时间线上执行以下步骤。

设备时间线步骤:
  1. scope 为新的GPU 错误作用域

  2. scope.[[filter]] 设为 filter

  3. 压入 scopethis.[[errorScopeStack]]

popErrorScope()

this[[errorScopeStack]] 弹出一个GPU 错误作用域, 并返回该作用域期间捕获的任意 GPUError,无则为 null

Promise 解析顺序不保证。

调用对象: GPUDevice this

返回: Promise<GPUError?>

内容时间线步骤:

  1. contentTimeline 为当前内容时间线

  2. promise新 promise

  3. this设备时间线上执行 check steps

  4. 返回 promise

设备时间线 check steps
  1. 如果 this 已丢失

    1. contentTimeline 上执行:

      内容时间线步骤:
      1. 决议 promise,其值为 null

    2. 返回。

    注意: 丢失的设备不会生成错误。参见§ 22 错误与调试

  2. 若下列要求之一未满足:

    则在 contentTimeline 上执行:

    内容时间线步骤:
    1. 拒绝 promise 并抛出 OperationError

  3. scope 为从 this.[[errorScopeStack]]弹出

  4. errorscope.[[errors]] 中任意一个元素,无则为 null

    对于列表中的任意两项 E1 和 E2,若 E2 由 E1 导致,则不应选择 E2。

    注意: 例如,若 E1 来源于 t = createTexture(), E2 来源于 t.createView()t invalid, 应优先选择 E1,使开发者更易理解问题所在。两者都是 GPUValidationError,差别仅在于 message 字段。

  5. 当前或未来某个未指定时间点,在 contentTimeline 上执行:

    注意: 允许 popErrorScope() 的解析顺序和选取错误无关,允许实现异步校验(比如 shader 编译可在后台线程异步完成),只要依赖状态的观察在合适时机完成即可。

内容时间线步骤:
  1. 决议 promise,其值为 error

使用错误作用域捕获一次可能失败的 GPUDevice 操作中的校验错误:
gpuDevice.pushErrorScope('validation');

let sampler = gpuDevice.createSampler({
    maxAnisotropy: 0, // 非法,maxAnisotropy 至少为 1。
});

gpuDevice.popErrorScope().then((error) => {
    if (error) {
        // 创建采样器出错,丢弃。
        sampler = null;
        console.error(`创建采样器时发生错误: ${error.message}`);
    }
});
注意:
错误作用域可以包含任意多的命令。其覆盖范围通常与应用希望针对错误发生时采取的措施相关。

例如,只包含单个资源(如纹理或缓冲区)创建的错误作用域可用于检测如内存不足的情况,此时应用可尝试释放部分资源再重试分配。

错误作用域无法标识具体哪条命令失败。因此,若整个模型加载过程所有命令都包裹在同一作用域内,就无法判断是否由于内存约束导致失败,通常释放资源并不能解决问题,更合适的做法是降级到其他模型或警告用户无法加载该模型。如果需要响应内存约束,可以将分配内存的操作包裹在更小的嵌套错误作用域中。

22.4. 遥测(Telemetry)

当生成了未被任何GPU 错误作用域捕获的 GPUError 时,用户代理可以GPUDevice 上,使用 GPUUncapturedErrorEvent触发事件,事件名为 uncapturederror

注意: uncapturederror 事件用于遥测和报告意外错误。它们未必针对所有未捕获错误都会派发(如错误数量可能有限制),不应用于处理应用正常运行时已知的错误场景。此类情况请优先使用 pushErrorScope()popErrorScope()

[Exposed=(Window, Worker), SecureContext]
interface GPUUncapturedErrorEvent : Event {
    constructor(
        DOMString type,
        GPUUncapturedErrorEventInit gpuUncapturedErrorEventInitDict
    );
    [SameObject] readonly attribute GPUError error;
};

dictionary GPUUncapturedErrorEventInit : EventInit {
    required GPUError error;
};

GPUUncapturedErrorEvent 拥有以下属性:

error类型为 GPUError,只读

一个槽支持属性,表示未捕获的错误对象。其类型与 popErrorScope() 返回的错误相同。

partial interface GPUDevice {
    attribute EventHandler onuncapturederror;
};

GPUDevice 拥有以下内容时间线属性

onuncapturederror类型为 EventHandler

用于 uncapturederror 事件类型的事件处理 IDL 属性

监听 GPUDevice 的未捕获错误:
gpuDevice.addEventListener('uncapturederror', (event) => {
    // 重新输出错误,因为添加事件监听器可能会屏蔽控制台日志。
    console.error('捕获到未被捕获的 WebGPU 错误:', event.error);

    myEngineDebugReport.uncapturedErrors.push({
        type: event.error.constructor.name,
        message: event.error.message,
    });
});

23. 详细操作

本节描述了各类 GPU 操作的详细过程。

23.1. 计算(Computing)

计算操作直接访问 GPU 的可编程硬件。计算着色器没有着色器阶段输入或输出;其结果通过向被绑定为 GPUBufferBindingLayout 并设置 GPUBufferBindingType"storage" 的存储绑定,或以 GPUStorageTextureBindingLayout 方式,写入数据产生副作用。 这些操作通过 GPUComputePassEncoder 编码,包括:

主要的计算算法如下:

compute(descriptor, drawCall, state)

参数:

  1. computeInvocations列表

  2. computeStagedescriptor.compute

  3. workgroupSizecomputeStage.entryPoint 应用 computeStage.constantscomputeStage.module 后计算得到的工作组大小。

  4. workgroupX 遍历 [0, dispatchCall.workgroupCountX] 区间:

    1. workgroupY 遍历 [0, dispatchCall.workgroupCountY] 区间:

      1. workgroupZ 遍历 [0, dispatchCall.workgroupCountZ] 区间:

        1. localX 遍历 [0, workgroupSize.x] 区间:

          1. localY 遍历 [0, workgroupSize.y] 区间:

            1. localZ 遍历 [0, workgroupSize.z] 区间:

              1. invocation{ computeStage, workgroupX, workgroupY, workgroupZ, localX, localY, localZ }

              2. 追加 invocationcomputeInvocations

  5. computeInvocations 中每个 invocation,以设备选择的任意顺序(可并行):

    1. 设置着色器内建变量(builtins)

      • 如果需要,设置 num_workgroups 内建变量为 (
        dispatchCall.workgroupCountX,
        dispatchCall.workgroupCountY,
        dispatchCall.workgroupCountZ
        )

      • 如果需要,设置 workgroup_id 内建变量为 (
        invocation.workgroupX,
        invocation.workgroupY,
        invocation.workgroupZ
        )

      • 如果需要,设置 local_invocation_id 内建变量为 (
        invocation.localX,
        invocation.localY,
        invocation.localZ
        )

      • 如果需要,设置 global_invocation_id 内建变量为 (
        invocation.workgroupX * workgroupSize.x + invocation.localX,
        invocation.workgroupY * workgroupSize.y + invocation.localY,
        invocation.workgroupZ * workgroupSize.z + invocation.localZ
        )

      • 如果需要,设置 local_invocation_index 内建变量为 invocation.localX + (invocation.localY * workgroupSize.x) + (invocation.localZ * workgroupSize.x * workgroupSize.y)

    2. 调用 invocation.computeStage 描述的计算着色器入口点。

注意: 着色器调用没有顺序保证,通常会根据设备能力并行执行。开发者不应假设任一调用或工作组会在其他调用开始前完成。有些设备看似顺序一致,但这一行为不可依赖,因为不同设备表现不一。需要跨调用同步的着色器必须使用 同步内建函数进行协调。

如果着色器执行未在合理时间内结束(由用户代理决定),设备可能会丢失

23.2. 渲染(Rendering)

渲染由一组在 GPURenderPassEncoder 中执行的 GPU 操作完成, 这些操作会修改被渲染通道附件(render pass attachments)查看的纹理数据。 这些操作包括:

注意: 渲染是 GPU 的传统用途,并且由硬件中的多个固定功能块支持。

主要渲染算法如下:

render(pipeline, drawCall, state)

参数:

  1. descriptorpipeline.[[descriptor]]

  2. 索引解析(Resolve indices)。参见 § 23.2.1 索引解析

    vertexListresolve indices(drawCall, state) 的结果。

  3. 顶点处理(Process vertices)。参见 § 23.2.2 顶点处理

    执行 process vertices(vertexList, drawCall, descriptor.vertex, state)。

  4. 图元组装(Assemble primitives)。参见 § 23.2.3 图元组装

    执行 assemble primitives(vertexList, drawCall, descriptor.primitive)。

  5. 图元裁剪(Clip primitives)。参见 § 23.2.4 图元裁剪

    primitiveList 为此阶段的输出。

  6. 光栅化(Rasterize)。参见 § 23.2.5 光栅化

    rasterizationListrasterize(primitiveList, state) 的结果。

  7. 片元处理(Process fragments)。参见 § 23.2.6 片元处理

    收集 fragments 列表,其由遍历 rasterizationList 中每个 rasterPoint,执行 process fragment(rasterPoint, descriptor, state) 产生。

  8. 写像素(Write pixels)。参见 § 23.2.7 输出合并

    对于 fragments 中每个非 null 的 fragment

23.2.1. 索引解析(Index Resolution)

在渲染的首个阶段,管线会为每个实例构建要处理的顶点列表。

索引解析(resolve indices)(drawCall, state)

参数:

返回: 整型索引列表。

  1. vertexIndexList 为一个空索引列表。

  2. 如果 drawCall 是索引绘制调用:

    1. drawCall.indexCount 个整数初始化 vertexIndexList

    2. 对于 i 从 0 到 drawCall.indexCount(不含)循环:

      1. relativeVertexIndex = fetch index(i + drawCall.firstIndex, state.[[index_buffer]]).

      2. 如果 relativeVertexIndex 为特殊值 "out of bounds", 则返回空列表。

        注意: 实现可选择在此情况下显示警告,特别是在容易检测的场景(如非 indirect 索引绘制)。

      3. drawCall.baseVertex + relativeVertexIndex 追加到 vertexIndexList

  3. 否则:

    1. drawCall.vertexCount 个整数初始化 vertexIndexList

    2. 将每个 vertexIndexListi 设为 drawCall.firstVertex + i

  4. 返回 vertexIndexList

注意: 对于间接绘制调用,indexCountvertexCount 等属性从 indirect 缓冲区读取,而不是从绘制命令本身。

索引获取(fetch index)(i, buffer, offset, format)

参数:

返回: 无符号整数或 "out of bounds"

  1. indexSizestate.[[index_format]] 决定:

    "uint16"

    2

    "uint32"

    4

  2. 如果 state.[[index_buffer_offset]] + |i + 1| × indexSize > state.[[index_buffer_size]], 返回特殊值 "out of bounds"

  3. state.[[index_buffer]] 中,从偏移 state.[[index_buffer_offset]] + i × indexSize 处,大小为 indexSize 字节的数据,按无符号整数解释并返回。

23.2.2. 顶点处理(Vertex Processing)

顶点处理阶段是渲染管线的可编程阶段, 用于处理顶点属性数据,并为§ 23.2.4 图元裁剪生成裁剪空间位置,以及为 § 23.2.6 片元处理生成其他数据。

顶点处理(process vertices)(vertexIndexList, drawCall, desc, state)

参数:

每个 vertexIndexList 中的顶点 vertexIndex,在每个 rawInstanceIndex 实例下,均独立处理。 rawInstanceIndex 的范围为 0 到 drawCall.instanceCount - 1。 此处理可并行发生,诸如对 GPUBufferBindingType "storage" 绑定的写入等副作用可无序发生。

  1. instanceIndex = rawInstanceIndex + drawCall.firstInstance。

  2. desc.buffers 列表中每个非 nullvertexBufferLayout

    1. i 为该 buffer layout 在列表中的索引。

    2. vertexBuffervertexBufferOffsetvertexBufferBindingSize 分别为 state.[[vertex_buffers]] 在槽 i 处的 buffer、offset 和 size。

    3. vertexElementIndex 根据 vertexBufferLayout.stepMode 决定:

      "vertex"

      vertexIndex

      "instance"

      instanceIndex

    4. drawCallOutOfBoundsfalse

    5. vertexBufferLayout.attributes 中每个 attributeDesc

      1. attributeOffset = vertexBufferOffset + vertexElementIndex * vertexBufferLayout.arrayStride + attributeDesc.offset

      2. 如果 attributeOffset + byteSize(attributeDesc.format) > vertexBufferOffset + vertexBufferBindingSize

        1. drawCallOutOfBounds 设为 true

        2. 实现可选(implementation-defined清空 vertexIndexList 并返回,取消本次绘制调用。

          注意: 这允许实现提前检测索引缓冲区的越界值,而不是等到 无效内存引用 行为时才发现。

    6. vertexBufferLayout.attributes 中每个 attributeDesc

      1. 如果 drawCallOutOfBoundstrue

        1. 根据 WGSL 的无效内存引用行为从 vertexBuffer 加载属性 data

          注意: 无效内存引用 允许多种实现,包括即使 drawCallOutOfBounds 为 true 但单个属性在范围内时依然返回“正确”值。

        否则:

        1. attributeOffset = vertexBufferOffset + vertexElementIndex * vertexBufferLayout.arrayStride + attributeDesc.offset

        2. vertexBufferattributeOffset 处加载格式为 attributeDesc.format 的属性 data。 组件按 x, y, z, w 顺序从内存加载。

      2. 根据通道格式规则,将 data 转换为着色器可见格式。

        类型为 "snorm8x2",字节值为 [0x70, 0xD0] 的属性 在 WGSL 中将被转换为 vec2<f32>(0.88, -0.38)
      3. data 调整为着色器类型:

        • 若二者均为标量,或均为同维度向量,无需调整。

        • data 为向量而着色器为标量,仅取首个分量。

        • 若均为向量且 data 维度更高,则截断多余分量。

          类型为 "float32x3",值为 vec3<f32>(1.0, 2.0, 3.0) 的属性, 若着色器期望 2 分量向量,则以 vec2<f32>(1.0, 2.0) 传递。
        • 若着色器为高维向量或 data 为标量,缺失分量用 vec4<*>(0, 0, 0, 1) 填充。

          类型为 "sint32",值为 5 的属性,若着色器期望 4 分量向量,则传递 vec4<i32>(5, 0, 0, 1)
      4. data 绑定到顶点着色器输入位置 attributeDesc.shaderLocation

  3. state.[[bind_groups]] 中每个 GPUBindGroup group(索引为 index):

    1. 对该 bind group 中每个 GPUBindingResource 资源:

      1. entry 为该资源对应的 GPUBindGroupLayoutEntry

      2. entry.visibility 包含 VERTEX

  4. 设置着色器内建变量

    • 如有,设置 vertex_index 内建变量为 vertexIndex

    • 如有,设置 instance_index 内建变量为 instanceIndex

  5. 调用 desc 描述的顶点着色器入口点。

    注意: 目标平台可能缓存顶点着色器调用结果, 同一 vertexIndex 多次出现不保证会多次调用,也不保证只调用一次。

    如果设备在合理时间内着色器执行未结束(由用户代理判定),则设备可能会丢失

23.2.3. 图元组装(Primitive Assembly)

图元的组装由 GPU 的固定功能阶段完成。

组装图元(assemble primitives)(vertexIndexList, drawCall, desc)

参数:

对于每个实例,图元根据 vertexIndexList,从着色器处理过的顶点组装而成。

  1. 首先,如果图元拓扑是 strip(即 desc.stripIndexFormat 不为 undefined), 且 drawCall 是索引绘制,则以 desc.stripIndexFormat 的最大值为分隔符,将 vertexIndexList 拆分为若干子列表。

    示例:vertexIndexList 值为 [1, 2, 65535, 4, 5, 6],类型为 "uint16", 拆分后的子列表为 [1, 2][4, 5, 6]

  2. 对于每个子列表 vl,根据 desc.topology 类型生成图元:

    "line-list"

    线段图元由 (vl.0, vl.1),(vl.2, vl.3),(vl.4, vl.5) 等依次组成。 每个后续图元消耗 2 个顶点。

    "line-strip"

    线段图元由 (vl.0, vl.1),(vl.1, vl.2),(vl.2, vl.3) 等组成。 每个后续图元消耗 1 个顶点。

    "triangle-list"

    三角形图元由 (vl.0, vl.1, vl.2), (vl.3, vl.4, vl.5),(vl.6, vl.7, vl.8) 等组成。 每个后续图元消耗 3 个顶点。

    "triangle-strip"

    三角形图元由 (vl.0, vl.1, vl.2), (vl.2, vl.1, vl.3),(vl.2, vl.3, vl.4), (vl.4, vl.3, vl.5) 等组成。 每个后续图元消耗 1 个顶点。

    不完整的图元会被丢弃。

23.2.4. 图元裁剪(Primitive Clipping)

顶点着色器必须生成一个内建的 position(类型为 vec4<f32>), 它表示顶点在裁剪空间坐标中的裁剪位置

图元会被裁剪到裁剪体积内,对于任何属于图元内的裁剪位置 p,该体积由以下不等式定义:

"clip-distances" 特性启用时,该裁剪体积可通过用户定义的半空间进一步收紧,可在顶点阶段输出声明 clip_distances。该数组中的每个值会在图元内线性插值,插值结果小于 0 的部分会被裁剪。

descriptor.primitive.unclippedDepthtrue,则不进行深度裁剪裁剪体积在 z 轴无限制。

若图元所有边都完全处于裁剪体积内,则此阶段图元保持不变。 若图元边与裁剪体积边界相交,则交点会以新边连通,且新边位于裁剪体积边界上。 对于三角形图元(descriptor.primitive.topology"triangle-list""triangle-strip"), 此重连可能在多边形内部引入新顶点。

若图元与裁剪体积边界相交,裁剪后的多边形必须包含该边界上的点。

若顶点着色器输出其它浮点值(标量或向量)并声明为 "perspective" 插值,则这些值也会被裁剪。 处于裁剪体积内的顶点的输出值不受裁剪影响。若图元被裁剪,则新生成顶点的输出值也需按裁剪规则处理。

对于被裁剪的顶点边 ab 生成的新顶点 c,定义 t 为边上比例: c.p = t × a.p + (1 - t) × b.p, 其中 x.p 是顶点 x裁剪位置

对每个有片元输入的顶点输出值 "v",a.v 和 b.v 分别为 ab 顶点的输出。 剪裁后新顶点 c.v 的值根据插值限定符产生:

flat

flat 插值不受影响,参照激发顶点(provoking vertex), 由着色器声明的插值采样模式(interpolation sampling)决定。输出对整个图元相同,等于激发顶点的输出。

linear

插值比例会基于裁剪位置的透视坐标调整,使结果在屏幕空间内线性。

perspective

在裁剪空间内线性插值,得到透视校正值。

图元裁剪的结果是一组新的图元,均包含在裁剪体积内。

23.2.5. 光栅化(Rasterization)

光栅化是硬件处理阶段,将生成的图元映射到 帧缓冲区(framebuffer) 的二维渲染区域——即当前 GPURenderPassEncoder 的渲染附件集合。 该渲染区域被划分为均匀的像素网格。

帧缓冲区的坐标从渲染目标的左上角开始。 每个单位正好对应一个像素。详见 § 3.3 坐标系统

光栅化决定哪些像素会被图元影响。若开启多重采样,每个像素会进一步被分割为 descriptor.multisample.count 个样本。 标准采样模式如下, 每个样本的位置都以像素左上角为原点的帧缓冲坐标系给出,像素范围为 (0,0) 到 (1,1):

multisample.count 样本位置
1 样本0: (0.5, 0.5)
4 样本0: (0.375, 0.125)
样本1: (0.875, 0.375)
样本2: (0.125, 0.625)
样本3: (0.625, 0.875)

实现必须在光栅化时,为指定的 标准采样模式使用对应 multisample.count

定义 FragmentDestination,其包含:

position

帧缓冲坐标表示的二维像素位置

sampleIndex

§ 23.2.10 每样本着色 激活则为整数,否则为 null

我们还用到归一化设备坐标(NDC)。其范围为 X/Y:-1 到 1,Z:0 到 1。

光栅化产生一组 RasterizationPoint,每项包含:

destination

参见 FragmentDestination

coverageMask

多重采样覆盖掩码,见 § 23.2.11 样本掩码

frontFacing

为 true 表示该点在图元正面

perspectiveDivisor

指跨图元插值的 1.0 ÷ W

depth

视口坐标中的深度,即 [[viewport]]minDepthmaxDepth 之间。

primitiveVertices

组成该图元的顶点输出列表

barycentricCoordinates

§ 23.2.5.3 重心坐标

光栅化(rasterize)(primitiveList, state)

参数:

返回: RasterizationPoint 列表。

primitiveList 中每个图元独立处理,但图元顺序会影响后续深度/模板操作和像素写入。

  1. 首先,将裁剪后的顶点变换为归一化设备坐标(NDC)。 假设输出位置为 p,则 NDC 坐标与透视除数为:

    ndc(p) = vector(p.x ÷ p.w, p.y ÷ p.w, p.z ÷ p.w)

    divisor(p) = 1.0 ÷ p.w

  2. vp = state.[[viewport]]。 将 NDC 位置 n 映射到视口坐标

    • 根据渲染目标偏移和尺寸计算帧缓冲区坐标:

      framebufferCoords(n) = vector(vp.x + 0.5 × (n.x + 1) × vp.width, vp.y + 0.5 × (−n.y + 1) × vp.height)

    • 深度按线性映射 [0, 1] 到视口深度范围:

      depth(n) = vp.minDepth + n.z × ( vp.maxDepth - vp.minDepth )

  3. rasterizationPoints 为点集,每个点的属性(divisor(p)framebufferCoords(n)depth(n) 等)按其在图元上的位置插值,与 § 23.2.4 图元裁剪同理。若为用户自定义属性(非内建输出),则使用 WGSL 插值类型,由 @interpolate 属性指定。

  4. 根据 primitive.topology,采用相应的光栅化算法:

    "point-list"

    未被 § 23.2.4 图元裁剪过滤的点进入 § 23.2.5.1 点光栅化

    "line-list""line-strip"

    § 23.2.4 图元裁剪裁剪的线条进入 § 23.2.5.2 线光栅化

    "triangle-list""triangle-strip"

    § 23.2.4 图元裁剪生成的多边形进入 § 23.2.5.4 多边形光栅化

  5. 移除所有 rasterizationPointsrp,使其 destination.position 不在 state.[[scissorRect]] 范围内。

  6. 返回 rasterizationPoints

23.2.5.1. 点光栅化(Point Rasterization)

在包含该点帧缓冲区坐标的像素内,选择一个FragmentDestination

覆盖掩码(coverage mask)取决于多重采样模式:

样本频率(sample-frequency)

coverageMask = 1 ≪ sampleIndex

像素频率多重采样(pixel-frequency multi-sampling)

coverageMask = 1 ≪ descriptor.multisample.count − 1

无多重采样(no multi-sampling)

coverageMask = 1

23.2.5.2. 线光栅化(Line Rasterization)

线光栅化的具体算法没有规定,不同实现可能不同。例如,可以用 § 23.2.5.4 多边形光栅化 在直线段周围绘制一个 1 像素宽的矩形, 或用 Bresenham 线算法选取FragmentDestination

注意: 详情见 Basic Line Segment RasterizationBresenham Line Segment Rasterization,参见 Vulkan 1.3 规范。

23.2.5.3. 重心坐标(Barycentric coordinates)

重心坐标是一组 n 个数 bi,定义在包含点 p 的凸多边形(顶点为 vi,位于帧缓冲区空间)。 每个 bi 取值范围为 0 到 1,表示点距离顶点 vi 的接近度。 它们的和恒为 1:

∑ (bi) = 1

这些坐标唯一确定多边形内(或边界上)任意点 p

p = ∑ (bi × pi)

对于三角形(3 顶点多边形),点 p 的重心坐标可如下计算:

Apolygon = A(v1, v2, v3) b1 = A(p, b2, b3) ÷ Apolygon b2 = A(b1, p, b3) ÷ Apolygon b3 = A(b1, b2, p) ÷ Apolygon

其中 A(点集) 表示由这些顶点组成的多边形的面积。

对于超过 3 顶点的多边形,具体算法依实现而定。一种可行实现是将多边形三角剖分,然后根据点所在三角形计算重心坐标。

23.2.5.4. 多边形光栅化(Polygon Rasterization)

当多边形朝向投影方向时,称为正面(front-facing); 否则为背面(back-facing)

多边形光栅化(rasterize polygon)()

参数:

返回: RasterizationPoint 列表。

  1. rasterizationPoints 为一个空列表。

  2. v(i) 为裁剪后多边形第 i 个顶点(从1开始,共 n 个顶点)的帧缓冲区坐标。

    注意: 此处用“多边形”而非“三角形”,因为 § 23.2.4 图元裁剪 可能引入额外顶点, 但应用无法察觉。

  3. 判断多边形是否为正面,依据其在帧缓冲区坐标中的 area 符号:

    area = 0.5 × ((v1.x × vn.y − vn.x × v1.y) + ∑ (vi+1.x × vi.y − vi.x × vi+1.y))

    area 的正负含义取决于 primitive.frontFace

    "ccw"

    area > 0 视为 正面,否则为 背面

    "cw"

    area < 0 视为 正面,否则为 背面

  4. 根据 primitive.cullMode 剔除图元:

    "none"

    所有图元都通过测试。

    "front"

    正面图元被丢弃,不进入后续渲染管线。

    "back"

    背面图元被丢弃。

  5. 帧缓冲区空间内,确定多边形内的片元(fragments)集合——即将进行每片元操作的位置。 此过程称为“点采样”(point sampling)。 具体逻辑依 descriptor.multisample

    关闭多重采样(disabled)

    片元与像素中心关联。即所有帧缓冲区坐标 C 满足 fract(C) = vector2(0.5, 0.5) 且位于多边形内均包含。 若像素中心位于边界,是否包含未定义。

    注意: 这与光栅化器的精度有关。

    开启多重采样(enabled)

    每个像素包含 descriptor.multisample.count 个实现自定义的位置。 这些位置有顺序,且全帧缓冲区所有像素一致,每个样本对应多重采样帧缓冲区的一个片元。

    光栅化器会生成每像素命中的位置掩码,即“sample-mask”,并作为内建变量提供给片元着色器。

  6. 对每个生成的 FragmentDestination 类型片元:

    1. rp 为新的 RasterizationPoint 对象

    2. 计算 b,即该片元的§ 23.2.5.3 重心坐标,并赋值给 rp.barycentricCoordinates

    3. divi 的深度值。

    4. rp.depth 设为 ∑ (bi × di)

    5. rp 加入 rasterizationPoints

  7. 返回 rasterizationPoints

23.2.6. 片元处理(Fragment Processing)

片元处理阶段是渲染管线的可编程阶段, 用于计算将要写入渲染目标的片元数据(通常为颜色)。

该阶段为每个RasterizationPoint生成一个片元(Fragment)

片元处理(process fragment)(rp, descriptor, state)

参数:

返回: Fragmentnull

  1. fragmentDesc = descriptor.fragment

  2. depthStencilDesc = descriptor.depthStencil

  3. fragment 为新的 Fragment 对象。

  4. fragment.destination = rp.destination

  5. fragment.frontFacing = rp.frontFacing

  6. fragment.coverageMask = rp.coverageMask

  7. fragment.depth = rp.depth

  8. 如果着色器未输出 frag_depth 内建变量

    1. fragment.depthPassed = compare fragment(fragment.destination, fragment.depth, "depth", state.[[depthStencilAttachment]], depthStencilDesc?.depthCompare)。

  9. stencilState = depthStencilDesc?.stencilFront (若 rp.frontFacing 为 true),否则为 depthStencilDesc?.stencilBack

  10. fragment.stencilPassed = compare fragment(fragment.destination, state.[[stencilReference]], "stencil", state.[[depthStencilAttachment]], stencilState?.compare)。

  11. 如果 fragmentDesc 不为 null

    1. fragment.depthPassedfalse,且着色器入口未输出 frag_depth 内建变量,也未写入任何storage 绑定,则以下步骤可被跳过。

    2. 设置着色器输入内建变量。对每个入口点的非复合参数,若有 内建变量注解,按下表赋值:

      position

      vec4<f32>(rp.destination.position, rp.depth, rp.perspectiveDivisor)

      front_facing

      rp.frontFacing

      sample_index

      rp.destination.sampleIndex

      sample_mask

      rp.coverageMask

    3. 对片元阶段的每个用户指定着色器输入

      1. value 为插值后的片元输入,基于 rp.barycentricCoordinatesrp.primitiveVertices 以及输入上的插值限定符。

      2. 将对应片元着色器location输入设为 value

    4. 调用 fragmentDesc 描述的片元着色器入口点。

      如果设备在合理时间内着色器未完成(由用户代理判定),则设备可能会丢失。

    5. 若片元执行了 discard,则返回 null

    6. fragment.colors 为着色器输出的 片元阶段输出值。

    7. 取着色器输出的内建变量

      1. 如输出 frag_depth 内建变量value

        1. vp = state.[[viewport]]

        2. fragment.depth = clamp(value, vp.minDepth, vp.maxDepth)。

        3. fragment.depthPassed = compare fragment(fragment.destination, fragment.depth, "depth", state.[[depthStencilAttachment]], depthStencilDesc?.depthCompare)。

    8. 如输出 sample_mask 内建变量value

      1. fragment.coverageMask = fragment.coverageMaskvalue

    否则,处于§ 23.2.8 无色输出(No Color Output)模式,fragment.colors 为空。

  12. 返回 fragment

片元比较(compare fragment)(destination, value, aspect, attachment, compareFunc)

参数:

返回: 若比较通过则为 true,否则为 false

片元的处理会并行进行,所有副作用(如对 GPUBufferBindingType "storage" 绑定的写入)可无序发生。

23.2.7. 输出合并(Output Merging)

输出合并是渲染管线的固定功能阶段,用于将片元颜色、深度和模板数据写入渲染通道附件。

处理深度模板(process depth stencil)(fragment, pipeline, state)

参数:

  1. depthStencilDesc = pipeline.[[descriptor]].depthStencil

  2. pipeline.[[writesDepth]]truefragment.depthPassedtrue

    1. state.[[depthStencilAttachment]]fragment.destination 处的深度 aspect 设为 fragment.depth

  3. pipeline.[[writesStencil]] 为 true:

    1. stencilState = depthStencilDesc.stencilFront (若 fragment.frontFacingtrue),否则为 depthStencilDesc.stencilBack

    2. fragment.stencilPassedfalse

      • stencilOp = stencilState.failOp

      否则若 fragment.depthPassedfalse

      否则:

      • stencilOp = stencilState.passOp

    3. state.[[depthStencilAttachment]]fragment.destination 处的模板 aspect 按 stencilOp 描述的操作更新值。

本阶段的深度输入(如有)会被限制在当前 [[viewport]] 的深度范围内(无论片元着色器是否写入 frag_depth 内建变量)。

处理颜色附件(process color attachments)(fragment, pipeline, state)

参数:

  1. fragment.depthPassedfalsefragment.stencilPassedfalse,则返回。

  2. targets = pipeline.[[descriptor]].fragment.targets

  3. state.[[colorAttachments]] 中每个 attachment

    1. colorfragment.colors 中与 attachment 对应的值。

    2. targetDesc 为与 attachment 对应的 targets 条目。

    3. targetDesc.blend 被提供

      1. colorBlend = targetDesc.blend.color

      2. alphaBlend = targetDesc.blend.alpha

      3. color 的 RGB 分量设为由 colorBlend.operationcolorBlend.srcFactorcolorBlend.dstFactor 计算得到的值。

      4. color 的 alpha 分量设为由 alphaBlend.operationalphaBlend.srcFactoralphaBlend.dstFactor 计算得到的值。

    4. color 赋值给 attachmentfragment.destination 处的值。

23.2.8. 无色输出(No Color Output)

在无色输出模式下,管线不会产生任何颜色附件输出。

管线仍会执行光栅化,并根据顶点位置输出生成深度值。深度测试和模板操作依然可用。

23.2.9. Alpha 到覆盖(Alpha to Coverage)

在 alpha-to-coverage 模式下,会根据片元着色器输出 @location(0) 处的 alpha 分量, 生成一个额外的 MSAA 样本的 alpha-to-coverage 掩码

生成该掩码的算法依平台而异,不同像素可有不同实现。保证:

23.2.10. 每样本着色(Per-Sample Shading)

在渲染到多重采样渲染附件时,片元着色器可以按每像素或每样本运行。 如果 sample_index 内建变量sample 插值采样被用且影响着色器输出,片元着色器必须每样本运行一次。 否则可以只对每像素运行一次,并将结果广播到最终样本掩码内的各样本。

使用每样本着色时,样本 N 的颜色输出由 sample_index == N 时的片元着色器执行结果产生。

23.2.11. 样本掩码(Sample Masking)

像素的最终样本掩码(final sample mask)计算为: 光栅化掩码(rasterization mask) & mask & 着色器输出掩码(shader-output mask)

只考虑掩码的低 count 位。

最终样本掩码N 位为 0,则该样本的所有颜色输出都会被丢弃, 深度测试和模板操作也不会对深度模板附件上相应样本执行。

光栅化掩码(rasterization mask)由光栅化阶段产生, 取决于多边形形状。图形覆盖到的样本在掩码中相应位为 1。

着色器输出掩码(shader-output mask)为片元着色器输出 "sample_mask" 内建变量 的值。 若片元着色器未输出该内建变量,且 alphaToCoverageEnabled 启用,则 着色器输出掩码alpha-to-coverage 掩码; 否则默认为 0xFFFFFFFF。

24. 类型定义(Type Definitions)

typedef [EnforceRange] unsigned long GPUBufferDynamicOffset;
typedef [EnforceRange] unsigned long GPUStencilValue;
typedef [EnforceRange] unsigned long GPUSampleMask;
typedef [EnforceRange] long GPUDepthBias;

typedef [EnforceRange] unsigned long long GPUSize64;
typedef [EnforceRange] unsigned long GPUIntegerCoordinate;
typedef [EnforceRange] unsigned long GPUIndex32;
typedef [EnforceRange] unsigned long GPUSize32;
typedef [EnforceRange] long GPUSignedOffset32;

typedef unsigned long long GPUSize64Out;
typedef unsigned long GPUIntegerCoordinateOut;
typedef unsigned long GPUSize32Out;

typedef unsigned long GPUFlagsConstant;

24.1. 颜色与向量(Colors & Vectors)

dictionary GPUColorDict {
    required double r;
    required double g;
    required double b;
    required double a;
};
typedef (sequence<double> or GPUColorDict) GPUColor;

注意: double 能精确表示 32 位有符号/无符号整数和单精度浮点数。

r, 类型为 double

红色通道值。

g, 类型为 double

绿色通道值。

b, 类型为 double

蓝色通道值。

a, 类型为 double

alpha 通道值。

对于给定的 GPUColorcolor,根据其类型,语法如下:
校验 GPUColor 形状(validate GPUColor shape)(color)

参数:

返回: undefined

内容时间线步骤:

  1. 如果 color 是序列且 color.size ≠ 4,则抛出 TypeError

dictionary GPUOrigin2DDict {
    GPUIntegerCoordinate x = 0;
    GPUIntegerCoordinate y = 0;
};
typedef (sequence<GPUIntegerCoordinate> or GPUOrigin2DDict) GPUOrigin2D;
对于给定的 GPUOrigin2Dorigin,根据其类型,语法如下:
校验 GPUOrigin2D 形状(validate GPUOrigin2D shape)(origin)

参数:

返回: undefined

内容时间线步骤:

  1. 如果 origin 是序列且 origin.size > 2,则抛出 TypeError

dictionary GPUOrigin3DDict {
    GPUIntegerCoordinate x = 0;
    GPUIntegerCoordinate y = 0;
    GPUIntegerCoordinate z = 0;
};
typedef (sequence<GPUIntegerCoordinate> or GPUOrigin3DDict) GPUOrigin3D;
对于给定的 GPUOrigin3Dorigin,根据其类型,语法如下:
校验 GPUOrigin3D 形状(validate GPUOrigin3D shape)(origin)

参数:

返回: undefined

内容时间线步骤:

  1. 如果 origin 是序列且 origin.size > 3,则抛出 TypeError

dictionary GPUExtent3DDict {
required GPUIntegerCoordinate width;
GPUIntegerCoordinate height = 1;
GPUIntegerCoordinate depthOrArrayLayers = 1;
};
typedef (sequence<GPUIntegerCoordinate> or GPUExtent3DDict) GPUExtent3D;
width, 类型为 GPUIntegerCoordinate

范围的宽度。

height, 类型为 GPUIntegerCoordinate,默认值为 1

范围的高度。

depthOrArrayLayers, 类型为 GPUIntegerCoordinate,默认值为 1

范围的深度或包含的数组层数。 如果与 GPUTexture 配合 GPUTextureDimension"3d" 时定义纹理深度。 若与 GPUTexture 配合 GPUTextureDimension"2d" 时定义数组层数。

对于给定的 GPUExtent3Dextent,根据其类型,语法如下:
校验 GPUExtent3D 形状(validate GPUExtent3D shape)(extent)

参数:

返回: undefined

内容时间线步骤:

  1. 如果:

25. 特性索引(Feature Index)

25.1. "core-features-and-limits"

允许使用所有 Core WebGPU 特性和限制。

注意:目前该特性在所有适配器上可用,即使未请求也会自动在所有设备上启用。

25.2. "depth-clip-control"

允许禁用深度裁剪(depth clipping)

该特性增加了如下可选 API 接口

25.3. "depth32float-stencil8"

允许显式创建格式为 "depth32float-stencil8" 的纹理(texture)。

该特性增加了如下可选 API 接口

25.4. "texture-compression-bc"

允许显式创建 BC 压缩格式(包括 “S3TC”、"RGTC" 和 "BPTC")的纹理。仅支持 2D 纹理。

注意: 支持 "texture-compression-bc" 的适配器并不总是支持 "texture-compression-bc-sliced-3d"。 若要使用 "texture-compression-bc-sliced-3d", 必须显式启用 "texture-compression-bc", 因为本特性不会自动启用 BC 格式。

该特性增加了如下可选 API 接口

25.5. "texture-compression-bc-sliced-3d"

允许为 BC 压缩格式的纹理使用 3d 维度。

注意: 支持 "texture-compression-bc" 的适配器并不总是支持 "texture-compression-bc-sliced-3d"。 若要使用 "texture-compression-bc-sliced-3d", 必须显式启用 "texture-compression-bc", 因为本特性不会自动启用 BC 格式。

该特性未增加任何可选 API 接口

25.6. "texture-compression-etc2"

允许显式创建 ETC2 压缩格式的纹理。仅支持 2D 纹理。

该特性增加了如下可选 API 接口

25.7. "texture-compression-astc"

允许显式创建 ASTC 压缩格式的纹理。仅支持 2D 纹理。

该特性增加了如下可选 API 接口

25.8. "texture-compression-astc-sliced-3d"

允许为 ASTC 压缩格式的纹理使用 3d 维度。

注意: 支持 "texture-compression-astc" 的适配器并不总是支持 "texture-compression-astc-sliced-3d"。 若要使用 "texture-compression-astc-sliced-3d", 必须显式启用 "texture-compression-astc", 因为本特性不会自动启用 ASTC 格式。

该特性未增加任何可选 API 接口

25.9. "timestamp-query"

为 GPU 命令缓冲区提供查询时间戳的能力。参见 § 20.4 时间戳查询(Timestamp Query)

该特性增加了如下可选 API 接口

25.10. "indirect-first-instance"

允许在间接绘制参数间接 drawIndexed 参数中使用非零的 firstInstance 值。

该特性未增加任何可选 API 接口

25.11. "shader-f16"

允许在 WGSL 中使用半精度浮点类型 f16

该特性增加了如下可选 API 接口

25.12. "rg11b10ufloat-renderable"

允许格式为 "rg11b10ufloat" 的纹理使用 RENDER_ATTACHMENT,并允许该格式的纹理进行混合、多重采样和解析。

该特性未增加任何可选 API 接口

在设备创建时启用 "texture-formats-tier1" 也会启用 "rg11b10ufloat-renderable"

25.13. "bgra8unorm-storage"

允许格式为 "bgra8unorm" 的纹理使用 STORAGE_BINDING 用法。

该特性未增加任何可选 API 接口

25.14. "float32-filterable"

使格式为 "r32float""rg32float""rgba32float" 的纹理可滤波(filterable)

25.15. "float32-blendable"

使格式为 "r32float""rg32float""rgba32float" 的纹理可混合(blendable)

25.16. "clip-distances"

允许在 WGSL 中使用 clip_distances

该特性增加了如下可选 API 接口

25.17. "dual-source-blending"

允许在 WGSL 中使用 blend_src,并可同时将两个像素着色器输出 (@blend_src(0)@blend_src(1)) 作为对单个颜色附件 location 0 的混合操作输入。

该特性增加了如下可选 API 接口

25.18. "subgroups"

允许 WGSL 中使用 subgroup 和 quad 操作。

该特性未增加可选 API 接口,但只要适配器支持该特性,GPUAdapterInfo 的如下成员会暴露真实值:

25.19. "texture-formats-tier1"

支持如下新的 GPUTextureFormat 可用于 RENDER_ATTACHMENT可混合(blendable)multisamplingSTORAGE_BINDING 能力,并支持 "read-only""write-only" GPUStorageTextureAccess

允许如下 RENDER_ATTACHMENT可混合(blendable)multisamplingresolve 能力用于如下 GPUTextureFormat

允许如下 "read-only""write-only" GPUStorageTextureAccess 用于如下 GPUTextureFormat

在设备创建时启用 "texture-formats-tier2" 也会启用 "texture-formats-tier1"

在设备创建时启用 "texture-formats-tier1" 也会启用 "rg11b10ufloat-renderable"

25.20. "texture-formats-tier2"

允许如下 "read-write" GPUStorageTextureAccess 用于如下 GPUTextureFormat

在设备创建时启用 "texture-formats-tier2" 也会启用 "texture-formats-tier1"

26. 附录(Appendices)

26.1. 纹理格式能力(Texture Format Capabilities)

26.1.1. 普通颜色格式(Plain color formats)

所有支持的普通颜色格式支持用法: COPY_SRCCOPY_DSTTEXTURE_BINDING, 以及维度 "3d"

RENDER_ATTACHMENTSTORAGE_BINDING 列分别指明对 GPUTextureUsage.RENDER_ATTACHMENTGPUTextureUsage.STORAGE_BINDING 用法的支持情况。

渲染目标像素字节成本(render target pixel byte cost)渲染目标组件对齐(render target component alignment) 用于校验 maxColorAttachmentBytesPerSample 限制。

注意: 这些格式的texel 块内存成本(texel block memory cost) 与其texel 块拷贝占用空间(texel block copy footprint)相同。

格式(Format) 所需特性(Feature) GPUTextureSampleType RENDER_ATTACHMENT 可混合(blendable) 多重采样(multisampling) 可解析(resolve) STORAGE_BINDING Texel 块拷贝占用空间(footprint)(字节) 渲染目标像素字节成本(字节)
"write-only" "read-only" "read-write"
每分量8位(1字节渲染目标组件对齐
r8unorm "float",
"unfilterable-float"
If "texture-formats-tier1" is enabled If "texture-formats-tier2" is enabled 1
r8snorm "float",
"unfilterable-float"
若启用 "texture-formats-tier1" 1
r8uint "uint" 若启用 "texture-formats-tier1" 若启用 "texture-formats-tier2" 1
r8sint "sint" 若启用 "texture-formats-tier1" 若启用 "texture-formats-tier2" 1
rg8unorm "float",
"unfilterable-float"
若启用 "texture-formats-tier1" 2
rg8snorm "float",
"unfilterable-float"
若启用 "texture-formats-tier1" 2
rg8uint "uint" 若启用 "texture-formats-tier1" 2
rg8sint "sint" 若启用 "texture-formats-tier1" 2
rgba8unorm "float",
"unfilterable-float"
若启用 "texture-formats-tier2" 4 8
rgba8unorm-srgb "float",
"unfilterable-float"
4 8
rgba8snorm "float",
"unfilterable-float"
若启用 "texture-formats-tier1" 4
rgba8uint "uint" 若启用 "texture-formats-tier2" 4
rgba8sint "sint" 若启用 "texture-formats-tier2" 4
bgra8unorm "float",
"unfilterable-float"
若启用 "bgra8unorm-storage" 4 8
bgra8unorm-srgb "float",
"unfilterable-float"
4 8
每分量16位(2字节渲染目标组件对齐
r16unorm "texture-formats-tier1" "unfilterable-float" 2
r16snorm "texture-formats-tier1" "unfilterable-float" 2
r16uint "uint" 若启用 "texture-formats-tier1" 若启用 "texture-formats-tier2" 2
r16sint "sint" 若启用 "texture-formats-tier1" 若启用 "texture-formats-tier2" 2
r16float "float",
"unfilterable-float"
若启用 "texture-formats-tier1" 若启用 "texture-formats-tier2" 2
rg16unorm "texture-formats-tier1" "unfilterable-float" 4
rg16snorm "texture-formats-tier1" "unfilterable-float" 4
rg16uint "uint" 若启用 "texture-formats-tier1" 4
rg16sint "sint" 若启用 "texture-formats-tier1" 4
rg16float "float",
"unfilterable-float"
若启用 "texture-formats-tier1" 4
rgba16unorm "texture-formats-tier1" "unfilterable-float" 8
rgba16snorm "texture-formats-tier1" "unfilterable-float" 8
rgba16uint "uint" 若启用 "texture-formats-tier2" 8
rgba16sint "sint" 若启用 "texture-formats-tier2" 8
rgba16float "float",
"unfilterable-float"
若启用 "texture-formats-tier2" 8
每分量32位(4字节渲染目标组件对齐
r32uint "uint" 4
r32sint "sint" 4
r32float "unfilterable-float" 若启用 "float32-blendable" 4
rg32uint "uint" 8
rg32sint "sint" 8
rg32float "unfilterable-float" 若启用 "float32-blendable" 8
rgba32uint "uint" 若启用 "texture-formats-tier2" 16
rgba32sint "sint" 若启用 "texture-formats-tier2" 16
rgba32float "unfilterable-float" 若启用 "float32-blendable" 若启用 "texture-formats-tier2" 16
混合分量宽度,每 texel 32 位(4字节渲染目标组件对齐
rgb10a2uint "uint" 若启用 "texture-formats-tier1" 4 8
rgb10a2unorm "float",
"unfilterable-float"
若启用 "texture-formats-tier1" 4 8
rg11b10ufloat "float",
"unfilterable-float"
若启用 "rg11b10ufloat-renderable" 若启用 "texture-formats-tier1" 4 8

26.1.2. 深度-模板格式(Depth-stencil formats)

深度或模板格式(depth-or-stencil format) 指的是任何带有深度和/或模板方面的格式。 组合深度-模板格式(combined depth-stencil format) 是指同时具有深度和模板方面的深度或模板格式

所有深度或模板格式都支持 COPY_SRCCOPY_DSTTEXTURE_BINDING, 以及 RENDER_ATTACHMENT 用法。这些格式都支持多重采样(multisampling)。 但某些拷贝操作对源和目标格式有限制,并且这些格式都不支持 "3d" 纹理维度。

深度纹理不能与 "filtering" 采样器一起使用,但即使使用滤波,始终可以与 "comparison" 采样器一起使用。

格式(Format)
注意:
texel块内存成本(Bytes)
方面(Aspect) GPUTextureSampleType 有效texel拷贝有效texel拷贝目标 texel块拷贝占用空间(Bytes) aspect-specific format
stencil8 1 − 4 stencil "uint" 1 stencil8
depth16unorm 2 depth "depth", "unfilterable-float" 2 depth16unorm
depth24plus 4 depth "depth", "unfilterable-float" depth24plus
depth24plus-stencil8 4 − 8 depth "depth", "unfilterable-float" depth24plus
stencil "uint" 1 stencil8
depth32float 4 depth "depth", "unfilterable-float" 4 depth32float
depth32float-stencil8 5 − 8 depth "depth", "unfilterable-float" 4 depth32float
stencil "uint" 1 stencil8

24位深度(24-bit depth) 指的是范围为0.0到1.0的24位无符号归一化深度格式,如果暴露出来,其拼写为 "depth24unorm"。

26.1.2.1. 读取和采样深度/模板纹理(Reading and Sampling Depth/Stencil Textures)

可以将一个深度方面(depth-aspect)的 GPUTextureView 绑定到 texture_depth_* 绑定类型,或绑定到其他非深度的2d/cube纹理类型。

模板方面(stencil-aspect)的 GPUTextureView 必须绑定到普通纹理绑定类型。sampleTypeGPUBindGroupLayout 中必须为 "uint"

读取或采样纹理的深度或模板方面时,表现为纹理包含值 (V, X, X, X),其中 V 为实际深度或模板值,X 为实现定义的未指定值。

对于深度方面绑定,这些未指定值在 texture_depth_* 类型的绑定下是不可见的。

如果一个深度纹理以 texture_2d<f32> 类型绑定到 tex

注意: 除非增加类似深度采样器那样更受限的模板采样器类型,否则实现上很难高效“屏蔽”深度/模板读取的驱动差异。 由于这在 WebGL 中不是移植性痛点,因此预计在 WebGPU 中也不会有问题。 实际上,根据硬件不同,可能会得到 (V, V, V, V)(V, 0, 0, 1)V 为深度或模板值)。

26.1.2.2. 拷贝深度/模板纹理(Copying Depth/Stencil Textures)

depth32float 格式("depth32float""depth32float-stencil8")的深度方面有受限的范围。 因此,只允许从同格式的其他纹理进行拷贝到此类纹理。

depth24plus 格式("depth24plus""depth24plus-stencil8")的深度方面有不透明的表示(实现为 24位深度"depth32float")。 因此,这些格式不允许深度方面texel 拷贝操作。

注意:
这些不允许的拷贝其实可以通过如下方式模拟:

26.1.3. 打包格式(Packed formats)

所有打包纹理格式(packed texture formats)都支持 COPY_SRCCOPY_DST、 以及 TEXTURE_BINDING 用法。 这些格式全部是可过滤(filterable)的。 但这些格式都不是可渲染(renderable)的,也不支持多重采样(multisampling)。

压缩格式(compressed format) 指的是任何块大小大于 1×1 的格式。

注意: 这些格式的texel 块内存成本 与其texel 块拷贝占用空间相同。

格式(Format) texel 块拷贝占用空间(字节) GPUTextureSampleType texel 块宽度/高度 "3d" 特性(Feature)
rgb9e5ufloat 4 "float",
"unfilterable-float"
1 × 1
bc1-rgba-unorm 8 "float",
"unfilterable-float"
4 × 4 若启用 "texture-compression-bc-sliced-3d" texture-compression-bc
bc1-rgba-unorm-srgb
bc2-rgba-unorm 16
bc2-rgba-unorm-srgb
bc3-rgba-unorm 16
bc3-rgba-unorm-srgb
bc4-r-unorm 8
bc4-r-snorm
bc5-rg-unorm 16
bc5-rg-snorm
bc6h-rgb-ufloat 16
bc6h-rgb-float
bc7-rgba-unorm 16
bc7-rgba-unorm-srgb
etc2-rgb8unorm 8 "float",
"unfilterable-float"
4 × 4 texture-compression-etc2
etc2-rgb8unorm-srgb
etc2-rgb8a1unorm 8
etc2-rgb8a1unorm-srgb
etc2-rgba8unorm 16
etc2-rgba8unorm-srgb
eac-r11unorm 8
eac-r11snorm
eac-rg11unorm 16
eac-rg11snorm
astc-4x4-unorm 16 "float",
"unfilterable-float"
4 × 4 If "texture-compression-astc-sliced-3d" is enabled texture-compression-astc
astc-4x4-unorm-srgb
astc-5x4-unorm 16 5 × 4
astc-5x4-unorm-srgb
astc-5x5-unorm 16 5 × 5
astc-5x5-unorm-srgb
astc-6x5-unorm 16 6 × 5
astc-6x5-unorm-srgb
astc-6x6-unorm 16 6 × 6
astc-6x6-unorm-srgb
astc-8x5-unorm 16 8 × 5
astc-8x5-unorm-srgb
astc-8x6-unorm 16 8 × 6
astc-8x6-unorm-srgb
astc-8x8-unorm 16 8 × 8
astc-8x8-unorm-srgb
astc-10x5-unorm 16 10 × 5
astc-10x5-unorm-srgb
astc-10x6-unorm 16 10 × 6
astc-10x6-unorm-srgb
astc-10x8-unorm 16 10 × 8
astc-10x8-unorm-srgb
astc-10x10-unorm 16 10 × 10
astc-10x10-unorm-srgb
astc-12x10-unorm 16 12 × 10
astc-12x10-unorm-srgb
astc-12x12-unorm 16 12 × 12
astc-12x12-unorm-srgb

一致性(Conformance)

文档约定(Document conventions)

一致性要求通过描述性断言和 RFC 2119 术语的组合来表达。 本规范规范性部分中的关键字 “MUST”、“MUST NOT”、“REQUIRED”、“SHALL”、“SHALL NOT”、“SHOULD”、“SHOULD NOT”、“RECOMMENDED”、“MAY” 和 “OPTIONAL” 应按照 RFC 2119 中的描述进行解释。 但是,为了易读性,本规范中这些词并非全部以大写字母出现。

除非明确标记为非规范性内容、示例和注释,否则本规范的所有文本均为规范性内容。 [RFC2119]

本规范中的示例以“例如”开头,或通过 class="example" 与规范性文本区分开来,如下所示:

这是一个信息性示例。

信息性注释以“注意”一词开头,并通过 class="note" 与规范性文本区分开来,如下所示:

注意,这是一个信息性注释。

一致性算法(Conformant Algorithms)

以祈使句形式表述在算法中的要求(如“去除所有前导空格字符”或“返回 false 并终止这些步骤”),应根据引入算法时使用的关键字(“必须”、“应该”、“可以”等)来解释其含义。

以算法或具体步骤表述的一致性要求可以以任何方式实现,只要最终结果等效即可。 特别地,本规范中定义的算法旨在易于理解,而非高性能。鼓励实现者进行优化。

索引(Index)

本规范定义的术语(Terms defined by this specification)

通过引用定义的术语

参考文献

规范性引用

[DOM]
Anne van Kesteren. DOM 标准. Living Standard. URL: https://dom.spec.whatwg.org/
[ECMASCRIPT]
ECMAScript 语言规范. URL: https://tc39.es/ecma262/multipage/
[HR-TIME-3]
Yoav Weiss. 高分辨率时间. 2024年11月7日. WD. URL: https://www.w3.org/TR/hr-time-3/
[HTML]
Anne van Kesteren; 等. HTML 标准. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[I18N-GLOSSARY]
Richard Ishida; Addison Phillips. 国际化术语表. 2024年10月17日. NOTE. URL: https://www.w3.org/TR/i18n-glossary/
[INFRA]
Anne van Kesteren; Domenic Denicola. Infra 标准. Living Standard. URL: https://infra.spec.whatwg.org/
[RFC2119]
S. Bradner. RFC 中用于指示需求级别的关键词. 1997年3月. Best Current Practice. URL: https://datatracker.ietf.org/doc/html/rfc2119
[WEBCODECS]
Paul Adenot; Eugene Zemtsov. WebCodecs. 2025年5月14日. WD. URL: https://www.w3.org/TR/webcodecs/
[WEBGL-1]
Dean Jackson; Jeff Gilbert. WebGL 规范,版本 1.0. 2017年8月9日. URL: https://www.khronos.org/registry/webgl/specs/latest/1.0/
[WEBIDL]
Edgar Chen; Timothy Gu. Web IDL 标准. Living Standard. URL: https://webidl.spec.whatwg.org/
[WEBXR]
Brandon Jones; Manish Goregaokar; Rik Cabanier. WebXR Device API. 2025年4月17日. CRD. URL: https://www.w3.org/TR/webxr/
[WGSL]
Alan Baker; Mehmet Oguz Derin; David Neto. WebGPU 着色语言. 2025年7月3日. CRD. URL: https://www.w3.org/TR/WGSL/

参考性引用

[MEDIAQUERIES-5]
Dean Jackson; 等. Media Queries Level 5. 2021年12月18日. WD. URL: https://www.w3.org/TR/mediaqueries-5/
[SERVICE-WORKERS]
Yoshisato Yanagisawa; Monica CHINTALA. Service Workers. 2025年3月6日. CRD. URL: https://www.w3.org/TR/service-workers/
[VULKAN]
The Khronos Vulkan Working Group. Vulkan 1.3. URL: https://registry.khronos.org/vulkan/specs/1.3/html/vkspec.html

IDL 索引

interface mixin GPUObjectBase {
    attribute USVString label;
};

dictionary GPUObjectDescriptorBase {
    USVString label = "";
};

[Exposed=(Window, Worker), SecureContext]
interface GPUSupportedLimits {
    readonly attribute unsigned long maxTextureDimension1D;
    readonly attribute unsigned long maxTextureDimension2D;
    readonly attribute unsigned long maxTextureDimension3D;
    readonly attribute unsigned long maxTextureArrayLayers;
    readonly attribute unsigned long maxBindGroups;
    readonly attribute unsigned long maxBindGroupsPlusVertexBuffers;
    readonly attribute unsigned long maxBindingsPerBindGroup;
    readonly attribute unsigned long maxDynamicUniformBuffersPerPipelineLayout;
    readonly attribute unsigned long maxDynamicStorageBuffersPerPipelineLayout;
    readonly attribute unsigned long maxSampledTexturesPerShaderStage;
    readonly attribute unsigned long maxSamplersPerShaderStage;
    readonly attribute unsigned long maxStorageBuffersPerShaderStage;
    readonly attribute unsigned long maxStorageTexturesPerShaderStage;
    readonly attribute unsigned long maxUniformBuffersPerShaderStage;
    readonly attribute unsigned long long maxUniformBufferBindingSize;
    readonly attribute unsigned long long maxStorageBufferBindingSize;
    readonly attribute unsigned long minUniformBufferOffsetAlignment;
    readonly attribute unsigned long minStorageBufferOffsetAlignment;
    readonly attribute unsigned long maxVertexBuffers;
    readonly attribute unsigned long long maxBufferSize;
    readonly attribute unsigned long maxVertexAttributes;
    readonly attribute unsigned long maxVertexBufferArrayStride;
    readonly attribute unsigned long maxInterStageShaderVariables;
    readonly attribute unsigned long maxColorAttachments;
    readonly attribute unsigned long maxColorAttachmentBytesPerSample;
    readonly attribute unsigned long maxComputeWorkgroupStorageSize;
    readonly attribute unsigned long maxComputeInvocationsPerWorkgroup;
    readonly attribute unsigned long maxComputeWorkgroupSizeX;
    readonly attribute unsigned long maxComputeWorkgroupSizeY;
    readonly attribute unsigned long maxComputeWorkgroupSizeZ;
    readonly attribute unsigned long maxComputeWorkgroupsPerDimension;
};

[Exposed=(Window, Worker), SecureContext]
interface GPUSupportedFeatures {
    readonly setlike<DOMString>;
};

[Exposed=(Window, Worker), SecureContext]
interface WGSLLanguageFeatures {
    readonly setlike<DOMString>;
};

[Exposed=(Window, Worker), SecureContext]
interface GPUAdapterInfo {
    readonly attribute DOMString vendor;
    readonly attribute DOMString architecture;
    readonly attribute DOMString device;
    readonly attribute DOMString description;
    readonly attribute unsigned long subgroupMinSize;
    readonly attribute unsigned long subgroupMaxSize;
    readonly attribute boolean isFallbackAdapter;
};

interface mixin NavigatorGPU {
    [SameObject, SecureContext] readonly attribute GPU gpu;
};
Navigator includes NavigatorGPU;
WorkerNavigator includes NavigatorGPU;

[Exposed=(Window, Worker), SecureContext]
interface GPU {
    Promise<GPUAdapter?> requestAdapter(optional GPURequestAdapterOptions options = {});
    GPUTextureFormat getPreferredCanvasFormat();
    [SameObject] readonly attribute WGSLLanguageFeatures wgslLanguageFeatures;
};

dictionary GPURequestAdapterOptions {
    DOMString featureLevel = "core";
    GPUPowerPreference powerPreference;
    boolean forceFallbackAdapter = false;
    boolean xrCompatible = false;
};

enum GPUPowerPreference {
    "low-power",
    "high-performance",
};

[Exposed=(Window, Worker), SecureContext]
interface GPUAdapter {
    [SameObject] readonly attribute GPUSupportedFeatures features;
    [SameObject] readonly attribute GPUSupportedLimits limits;
    [SameObject] readonly attribute GPUAdapterInfo info;

    Promise<GPUDevice> requestDevice(optional GPUDeviceDescriptor descriptor = {});
};

dictionary GPUDeviceDescriptor
         : GPUObjectDescriptorBase {
    sequence<GPUFeatureName> requiredFeatures = [];
    record<DOMString, (GPUSize64 or undefined)> requiredLimits = {};
    GPUQueueDescriptor defaultQueue = {};
};

enum GPUFeatureName {
    "core-features-and-limits",
    "depth-clip-control",
    "depth32float-stencil8",
    "texture-compression-bc",
    "texture-compression-bc-sliced-3d",
    "texture-compression-etc2",
    "texture-compression-astc",
    "texture-compression-astc-sliced-3d",
    "timestamp-query",
    "indirect-first-instance",
    "shader-f16",
    "rg11b10ufloat-renderable",
    "bgra8unorm-storage",
    "float32-filterable",
    "float32-blendable",
    "clip-distances",
    "dual-source-blending",
    "subgroups",
    "texture-formats-tier1",
    "texture-formats-tier2",
};

[Exposed=(Window, Worker), SecureContext]
interface GPUDevice : EventTarget {
    [SameObject] readonly attribute GPUSupportedFeatures features;
    [SameObject] readonly attribute GPUSupportedLimits limits;
    [SameObject] readonly attribute GPUAdapterInfo adapterInfo;

    [SameObject] readonly attribute GPUQueue queue;

    undefined destroy();

    GPUBuffer createBuffer(GPUBufferDescriptor descriptor);
    GPUTexture createTexture(GPUTextureDescriptor descriptor);
    GPUSampler createSampler(optional GPUSamplerDescriptor descriptor = {});
    GPUExternalTexture importExternalTexture(GPUExternalTextureDescriptor descriptor);

    GPUBindGroupLayout createBindGroupLayout(GPUBindGroupLayoutDescriptor descriptor);
    GPUPipelineLayout createPipelineLayout(GPUPipelineLayoutDescriptor descriptor);
    GPUBindGroup createBindGroup(GPUBindGroupDescriptor descriptor);

    GPUShaderModule createShaderModule(GPUShaderModuleDescriptor descriptor);
    GPUComputePipeline createComputePipeline(GPUComputePipelineDescriptor descriptor);
    GPURenderPipeline createRenderPipeline(GPURenderPipelineDescriptor descriptor);
    Promise<GPUComputePipeline> createComputePipelineAsync(GPUComputePipelineDescriptor descriptor);
    Promise<GPURenderPipeline> createRenderPipelineAsync(GPURenderPipelineDescriptor descriptor);

    GPUCommandEncoder createCommandEncoder(optional GPUCommandEncoderDescriptor descriptor = {});
    GPURenderBundleEncoder createRenderBundleEncoder(GPURenderBundleEncoderDescriptor descriptor);

    GPUQuerySet createQuerySet(GPUQuerySetDescriptor descriptor);
};
GPUDevice includes GPUObjectBase;

[Exposed=(Window, Worker), SecureContext]
interface GPUBuffer {
    readonly attribute GPUSize64Out size;
    readonly attribute GPUFlagsConstant usage;

    readonly attribute GPUBufferMapState mapState;

    Promise<undefined> mapAsync(GPUMapModeFlags mode, optional GPUSize64 offset = 0, optional GPUSize64 size);
    ArrayBuffer getMappedRange(optional GPUSize64 offset = 0, optional GPUSize64 size);
    undefined unmap();

    undefined destroy();
};
GPUBuffer includes GPUObjectBase;

enum GPUBufferMapState {
    "unmapped",
    "pending",
    "mapped",
};

dictionary GPUBufferDescriptor
         : GPUObjectDescriptorBase {
    required GPUSize64 size;
    required GPUBufferUsageFlags usage;
    boolean mappedAtCreation = false;
};

typedef [EnforceRange] unsigned long GPUBufferUsageFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUBufferUsage {
    const GPUFlagsConstant MAP_READ      = 0x0001;
    const GPUFlagsConstant MAP_WRITE     = 0x0002;
    const GPUFlagsConstant COPY_SRC      = 0x0004;
    const GPUFlagsConstant COPY_DST      = 0x0008;
    const GPUFlagsConstant INDEX         = 0x0010;
    const GPUFlagsConstant VERTEX        = 0x0020;
    const GPUFlagsConstant UNIFORM       = 0x0040;
    const GPUFlagsConstant STORAGE       = 0x0080;
    const GPUFlagsConstant INDIRECT      = 0x0100;
    const GPUFlagsConstant QUERY_RESOLVE = 0x0200;
};

typedef [EnforceRange] unsigned long GPUMapModeFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUMapMode {
    const GPUFlagsConstant READ  = 0x0001;
    const GPUFlagsConstant WRITE = 0x0002;
};

[Exposed=(Window, Worker), SecureContext]
interface GPUTexture {
    GPUTextureView createView(optional GPUTextureViewDescriptor descriptor = {});

    undefined destroy();

    readonly attribute GPUIntegerCoordinateOut width;
    readonly attribute GPUIntegerCoordinateOut height;
    readonly attribute GPUIntegerCoordinateOut depthOrArrayLayers;
    readonly attribute GPUIntegerCoordinateOut mipLevelCount;
    readonly attribute GPUSize32Out sampleCount;
    readonly attribute GPUTextureDimension dimension;
    readonly attribute GPUTextureFormat format;
    readonly attribute GPUFlagsConstant usage;
};
GPUTexture includes GPUObjectBase;

dictionary GPUTextureDescriptor
         : GPUObjectDescriptorBase {
    required GPUExtent3D size;
    GPUIntegerCoordinate mipLevelCount = 1;
    GPUSize32 sampleCount = 1;
    GPUTextureDimension dimension = "2d";
    required GPUTextureFormat format;
    required GPUTextureUsageFlags usage;
    sequence<GPUTextureFormat> viewFormats = [];
};

enum GPUTextureDimension {
    "1d",
    "2d",
    "3d",
};

typedef [EnforceRange] unsigned long GPUTextureUsageFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUTextureUsage {
    const GPUFlagsConstant COPY_SRC          = 0x01;
    const GPUFlagsConstant COPY_DST          = 0x02;
    const GPUFlagsConstant TEXTURE_BINDING   = 0x04;
    const GPUFlagsConstant STORAGE_BINDING   = 0x08;
    const GPUFlagsConstant RENDER_ATTACHMENT = 0x10;
};

[Exposed=(Window, Worker), SecureContext]
interface GPUTextureView {
};
GPUTextureView includes GPUObjectBase;

dictionary GPUTextureViewDescriptor
         : GPUObjectDescriptorBase {
    GPUTextureFormat format;
    GPUTextureViewDimension dimension;
    GPUTextureUsageFlags usage = 0;
    GPUTextureAspect aspect = "all";
    GPUIntegerCoordinate baseMipLevel = 0;
    GPUIntegerCoordinate mipLevelCount;
    GPUIntegerCoordinate baseArrayLayer = 0;
    GPUIntegerCoordinate arrayLayerCount;
};

enum GPUTextureViewDimension {
    "1d",
    "2d",
    "2d-array",
    "cube",
    "cube-array",
    "3d",
};

enum GPUTextureAspect {
    "all",
    "stencil-only",
    "depth-only",
};

enum GPUTextureFormat {
    // 8-bit formats
    "r8unorm",
    "r8snorm",
    "r8uint",
    "r8sint",

    // 16-bit formats
    "r16unorm",
    "r16snorm",
    "r16uint",
    "r16sint",
    "r16float",
    "rg8unorm",
    "rg8snorm",
    "rg8uint",
    "rg8sint",

    // 32-bit formats
    "r32uint",
    "r32sint",
    "r32float",
    "rg16unorm",
    "rg16snorm",
    "rg16uint",
    "rg16sint",
    "rg16float",
    "rgba8unorm",
    "rgba8unorm-srgb",
    "rgba8snorm",
    "rgba8uint",
    "rgba8sint",
    "bgra8unorm",
    "bgra8unorm-srgb",
    // Packed 32-bit formats
    "rgb9e5ufloat",
    "rgb10a2uint",
    "rgb10a2unorm",
    "rg11b10ufloat",

    // 64-bit formats
    "rg32uint",
    "rg32sint",
    "rg32float",
    "rgba16unorm",
    "rgba16snorm",
    "rgba16uint",
    "rgba16sint",
    "rgba16float",

    // 128-bit formats
    "rgba32uint",
    "rgba32sint",
    "rgba32float",

    // Depth/stencil formats
    "stencil8",
    "depth16unorm",
    "depth24plus",
    "depth24plus-stencil8",
    "depth32float",

    // "depth32float-stencil8" feature
    "depth32float-stencil8",

    // BC compressed formats usable if "texture-compression-bc" is both
    // supported by the device/user agent and enabled in requestDevice.
    "bc1-rgba-unorm",
    "bc1-rgba-unorm-srgb",
    "bc2-rgba-unorm",
    "bc2-rgba-unorm-srgb",
    "bc3-rgba-unorm",
    "bc3-rgba-unorm-srgb",
    "bc4-r-unorm",
    "bc4-r-snorm",
    "bc5-rg-unorm",
    "bc5-rg-snorm",
    "bc6h-rgb-ufloat",
    "bc6h-rgb-float",
    "bc7-rgba-unorm",
    "bc7-rgba-unorm-srgb",

    // ETC2 compressed formats usable if "texture-compression-etc2" is both
    // supported by the device/user agent and enabled in requestDevice.
    "etc2-rgb8unorm",
    "etc2-rgb8unorm-srgb",
    "etc2-rgb8a1unorm",
    "etc2-rgb8a1unorm-srgb",
    "etc2-rgba8unorm",
    "etc2-rgba8unorm-srgb",
    "eac-r11unorm",
    "eac-r11snorm",
    "eac-rg11unorm",
    "eac-rg11snorm",

    // ASTC compressed formats usable if "texture-compression-astc" is both
    // supported by the device/user agent and enabled in requestDevice.
    "astc-4x4-unorm",
    "astc-4x4-unorm-srgb",
    "astc-5x4-unorm",
    "astc-5x4-unorm-srgb",
    "astc-5x5-unorm",
    "astc-5x5-unorm-srgb",
    "astc-6x5-unorm",
    "astc-6x5-unorm-srgb",
    "astc-6x6-unorm",
    "astc-6x6-unorm-srgb",
    "astc-8x5-unorm",
    "astc-8x5-unorm-srgb",
    "astc-8x6-unorm",
    "astc-8x6-unorm-srgb",
    "astc-8x8-unorm",
    "astc-8x8-unorm-srgb",
    "astc-10x5-unorm",
    "astc-10x5-unorm-srgb",
    "astc-10x6-unorm",
    "astc-10x6-unorm-srgb",
    "astc-10x8-unorm",
    "astc-10x8-unorm-srgb",
    "astc-10x10-unorm",
    "astc-10x10-unorm-srgb",
    "astc-12x10-unorm",
    "astc-12x10-unorm-srgb",
    "astc-12x12-unorm",
    "astc-12x12-unorm-srgb",
};

[Exposed=(Window, Worker), SecureContext]
interface GPUExternalTexture {
};
GPUExternalTexture includes GPUObjectBase;

dictionary GPUExternalTextureDescriptor
         : GPUObjectDescriptorBase {
    required (HTMLVideoElement or VideoFrame) source;
    PredefinedColorSpace colorSpace = "srgb";
};

[Exposed=(Window, Worker), SecureContext]
interface GPUSampler {
};
GPUSampler includes GPUObjectBase;

dictionary GPUSamplerDescriptor
         : GPUObjectDescriptorBase {
    GPUAddressMode addressModeU = "clamp-to-edge";
    GPUAddressMode addressModeV = "clamp-to-edge";
    GPUAddressMode addressModeW = "clamp-to-edge";
    GPUFilterMode magFilter = "nearest";
    GPUFilterMode minFilter = "nearest";
    GPUMipmapFilterMode mipmapFilter = "nearest";
    float lodMinClamp = 0;
    float lodMaxClamp = 32;
    GPUCompareFunction compare;
    [Clamp] unsigned short maxAnisotropy = 1;
};

enum GPUAddressMode {
    "clamp-to-edge",
    "repeat",
    "mirror-repeat",
};

enum GPUFilterMode {
    "nearest",
    "linear",
};

enum GPUMipmapFilterMode {
    "nearest",
    "linear",
};

enum GPUCompareFunction {
    "never",
    "less",
    "equal",
    "less-equal",
    "greater",
    "not-equal",
    "greater-equal",
    "always",
};

[Exposed=(Window, Worker), SecureContext]
interface GPUBindGroupLayout {
};
GPUBindGroupLayout includes GPUObjectBase;

dictionary GPUBindGroupLayoutDescriptor
         : GPUObjectDescriptorBase {
    required sequence<GPUBindGroupLayoutEntry> entries;
};

dictionary GPUBindGroupLayoutEntry {
    required GPUIndex32 binding;
    required GPUShaderStageFlags visibility;

    GPUBufferBindingLayout buffer;
    GPUSamplerBindingLayout sampler;
    GPUTextureBindingLayout texture;
    GPUStorageTextureBindingLayout storageTexture;
    GPUExternalTextureBindingLayout externalTexture;
};

typedef [EnforceRange] unsigned long GPUShaderStageFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUShaderStage {
    const GPUFlagsConstant VERTEX   = 0x1;
    const GPUFlagsConstant FRAGMENT = 0x2;
    const GPUFlagsConstant COMPUTE  = 0x4;
};

enum GPUBufferBindingType {
    "uniform",
    "storage",
    "read-only-storage",
};

dictionary GPUBufferBindingLayout {
    GPUBufferBindingType type = "uniform";
    boolean hasDynamicOffset = false;
    GPUSize64 minBindingSize = 0;
};

enum GPUSamplerBindingType {
    "filtering",
    "non-filtering",
    "comparison",
};

dictionary GPUSamplerBindingLayout {
    GPUSamplerBindingType type = "filtering";
};

enum GPUTextureSampleType {
    "float",
    "unfilterable-float",
    "depth",
    "sint",
    "uint",
};

dictionary GPUTextureBindingLayout {
    GPUTextureSampleType sampleType = "float";
    GPUTextureViewDimension viewDimension = "2d";
    boolean multisampled = false;
};

enum GPUStorageTextureAccess {
    "write-only",
    "read-only",
    "read-write",
};

dictionary GPUStorageTextureBindingLayout {
    GPUStorageTextureAccess access = "write-only";
    required GPUTextureFormat format;
    GPUTextureViewDimension viewDimension = "2d";
};

dictionary GPUExternalTextureBindingLayout {
};

[Exposed=(Window, Worker), SecureContext]
interface GPUBindGroup {
};
GPUBindGroup includes GPUObjectBase;

dictionary GPUBindGroupDescriptor
         : GPUObjectDescriptorBase {
    required GPUBindGroupLayout layout;
    required sequence<GPUBindGroupEntry> entries;
};

typedef (GPUSampler or
         GPUTexture or
         GPUTextureView or
         GPUBuffer or
         GPUBufferBinding or
         GPUExternalTexture) GPUBindingResource;

dictionary GPUBindGroupEntry {
    required GPUIndex32 binding;
    required GPUBindingResource resource;
};

dictionary GPUBufferBinding {
    required GPUBuffer buffer;
    GPUSize64 offset = 0;
    GPUSize64 size;
};

[Exposed=(Window, Worker), SecureContext]
interface GPUPipelineLayout {
};
GPUPipelineLayout includes GPUObjectBase;

dictionary GPUPipelineLayoutDescriptor
         : GPUObjectDescriptorBase {
    required sequence<GPUBindGroupLayout?> bindGroupLayouts;
};

[Exposed=(Window, Worker), SecureContext]
interface GPUShaderModule {
    Promise<GPUCompilationInfo> getCompilationInfo();
};
GPUShaderModule includes GPUObjectBase;

dictionary GPUShaderModuleDescriptor
         : GPUObjectDescriptorBase {
    required USVString code;
    sequence<GPUShaderModuleCompilationHint> compilationHints = [];
};

dictionary GPUShaderModuleCompilationHint {
    required USVString entryPoint;
    (GPUPipelineLayout or GPUAutoLayoutMode) layout;
};

enum GPUCompilationMessageType {
    "error",
    "warning",
    "info",
};

[Exposed=(Window, Worker), Serializable, SecureContext]
interface GPUCompilationMessage {
    readonly attribute DOMString message;
    readonly attribute GPUCompilationMessageType type;
    readonly attribute unsigned long long lineNum;
    readonly attribute unsigned long long linePos;
    readonly attribute unsigned long long offset;
    readonly attribute unsigned long long length;
};

[Exposed=(Window, Worker), Serializable, SecureContext]
interface GPUCompilationInfo {
    readonly attribute FrozenArray<GPUCompilationMessage> messages;
};

[Exposed=(Window, Worker), SecureContext, Serializable]
interface GPUPipelineError : DOMException {
    constructor(optional DOMString message = "", GPUPipelineErrorInit options);
    readonly attribute GPUPipelineErrorReason reason;
};

dictionary GPUPipelineErrorInit {
    required GPUPipelineErrorReason reason;
};

enum GPUPipelineErrorReason {
    "validation",
    "internal",
};

enum GPUAutoLayoutMode {
    "auto",
};

dictionary GPUPipelineDescriptorBase
         : GPUObjectDescriptorBase {
    required (GPUPipelineLayout or GPUAutoLayoutMode) layout;
};

interface mixin GPUPipelineBase {
    [NewObject] GPUBindGroupLayout getBindGroupLayout(unsigned long index);
};

dictionary GPUProgrammableStage {
    required GPUShaderModule module;
    USVString entryPoint;
    record<USVString, GPUPipelineConstantValue> constants = {};
};

typedef double GPUPipelineConstantValue; // May represent WGSL's bool, f32, i32, u32, and f16 if enabled.

[Exposed=(Window, Worker), SecureContext]
interface GPUComputePipeline {
};
GPUComputePipeline includes GPUObjectBase;
GPUComputePipeline includes GPUPipelineBase;

dictionary GPUComputePipelineDescriptor
         : GPUPipelineDescriptorBase {
    required GPUProgrammableStage compute;
};

[Exposed=(Window, Worker), SecureContext]
interface GPURenderPipeline {
};
GPURenderPipeline includes GPUObjectBase;
GPURenderPipeline includes GPUPipelineBase;

dictionary GPURenderPipelineDescriptor
         : GPUPipelineDescriptorBase {
    required GPUVertexState vertex;
    GPUPrimitiveState primitive = {};
    GPUDepthStencilState depthStencil;
    GPUMultisampleState multisample = {};
    GPUFragmentState fragment;
};

dictionary GPUPrimitiveState {
    GPUPrimitiveTopology topology = "triangle-list";
    GPUIndexFormat stripIndexFormat;
    GPUFrontFace frontFace = "ccw";
    GPUCullMode cullMode = "none";

    // Requires "depth-clip-control" feature.
    boolean unclippedDepth = false;
};

enum GPUPrimitiveTopology {
    "point-list",
    "line-list",
    "line-strip",
    "triangle-list",
    "triangle-strip",
};

enum GPUFrontFace {
    "ccw",
    "cw",
};

enum GPUCullMode {
    "none",
    "front",
    "back",
};

dictionary GPUMultisampleState {
    GPUSize32 count = 1;
    GPUSampleMask mask = 0xFFFFFFFF;
    boolean alphaToCoverageEnabled = false;
};

dictionary GPUFragmentState
         : GPUProgrammableStage {
    required sequence<GPUColorTargetState?> targets;
};

dictionary GPUColorTargetState {
    required GPUTextureFormat format;

    GPUBlendState blend;
    GPUColorWriteFlags writeMask = 0xF;  // GPUColorWrite.ALL
};

dictionary GPUBlendState {
    required GPUBlendComponent color;
    required GPUBlendComponent alpha;
};

typedef [EnforceRange] unsigned long GPUColorWriteFlags;
[Exposed=(Window, Worker), SecureContext]
namespace GPUColorWrite {
    const GPUFlagsConstant RED   = 0x1;
    const GPUFlagsConstant GREEN = 0x2;
    const GPUFlagsConstant BLUE  = 0x4;
    const GPUFlagsConstant ALPHA = 0x8;
    const GPUFlagsConstant ALL   = 0xF;
};

dictionary GPUBlendComponent {
    GPUBlendOperation operation = "add";
    GPUBlendFactor srcFactor = "one";
    GPUBlendFactor dstFactor = "zero";
};

enum GPUBlendFactor {
    "zero",
    "one",
    "src",
    "one-minus-src",
    "src-alpha",
    "one-minus-src-alpha",
    "dst",
    "one-minus-dst",
    "dst-alpha",
    "one-minus-dst-alpha",
    "src-alpha-saturated",
    "constant",
    "one-minus-constant",
    "src1",
    "one-minus-src1",
    "src1-alpha",
    "one-minus-src1-alpha",
};

enum GPUBlendOperation {
    "add",
    "subtract",
    "reverse-subtract",
    "min",
    "max",
};

dictionary GPUDepthStencilState {
    required GPUTextureFormat format;

    boolean depthWriteEnabled;
    GPUCompareFunction depthCompare;

    GPUStencilFaceState stencilFront = {};
    GPUStencilFaceState stencilBack = {};

    GPUStencilValue stencilReadMask = 0xFFFFFFFF;
    GPUStencilValue stencilWriteMask = 0xFFFFFFFF;

    GPUDepthBias depthBias = 0;
    float depthBiasSlopeScale = 0;
    float depthBiasClamp = 0;
};

dictionary GPUStencilFaceState {
    GPUCompareFunction compare = "always";
    GPUStencilOperation failOp = "keep";
    GPUStencilOperation depthFailOp = "keep";
    GPUStencilOperation passOp = "keep";
};

enum GPUStencilOperation {
    "keep",
    "zero",
    "replace",
    "invert",
    "increment-clamp",
    "decrement-clamp",
    "increment-wrap",
    "decrement-wrap",
};

enum GPUIndexFormat {
    "uint16",
    "uint32",
};

enum GPUVertexFormat {
    "uint8",
    "uint8x2",
    "uint8x4",
    "sint8",
    "sint8x2",
    "sint8x4",
    "unorm8",
    "unorm8x2",
    "unorm8x4",
    "snorm8",
    "snorm8x2",
    "snorm8x4",
    "uint16",
    "uint16x2",
    "uint16x4",
    "sint16",
    "sint16x2",
    "sint16x4",
    "unorm16",
    "unorm16x2",
    "unorm16x4",
    "snorm16",
    "snorm16x2",
    "snorm16x4",
    "float16",
    "float16x2",
    "float16x4",
    "float32",
    "float32x2",
    "float32x3",
    "float32x4",
    "uint32",
    "uint32x2",
    "uint32x3",
    "uint32x4",
    "sint32",
    "sint32x2",
    "sint32x3",
    "sint32x4",
    "unorm10-10-10-2",
    "unorm8x4-bgra",
};

enum GPUVertexStepMode {
    "vertex",
    "instance",
};

dictionary GPUVertexState
         : GPUProgrammableStage {
    sequence<GPUVertexBufferLayout?> buffers = [];
};

dictionary GPUVertexBufferLayout {
    required GPUSize64 arrayStride;
    GPUVertexStepMode stepMode = "vertex";
    required sequence<GPUVertexAttribute> attributes;
};

dictionary GPUVertexAttribute {
    required GPUVertexFormat format;
    required GPUSize64 offset;

    required GPUIndex32 shaderLocation;
};

dictionary GPUTexelCopyBufferLayout {
    GPUSize64 offset = 0;
    GPUSize32 bytesPerRow;
    GPUSize32 rowsPerImage;
};

dictionary GPUTexelCopyBufferInfo
         : GPUTexelCopyBufferLayout {
    required GPUBuffer buffer;
};

dictionary GPUTexelCopyTextureInfo {
    required GPUTexture texture;
    GPUIntegerCoordinate mipLevel = 0;
    GPUOrigin3D origin = {};
    GPUTextureAspect aspect = "all";
};

dictionary GPUCopyExternalImageDestInfo
         : GPUTexelCopyTextureInfo {
    PredefinedColorSpace colorSpace = "srgb";
    boolean premultipliedAlpha = false;
};

typedef (ImageBitmap or
         ImageData or
         HTMLImageElement or
         HTMLVideoElement or
         VideoFrame or
         HTMLCanvasElement or
         OffscreenCanvas) GPUCopyExternalImageSource;

dictionary GPUCopyExternalImageSourceInfo {
    required GPUCopyExternalImageSource source;
    GPUOrigin2D origin = {};
    boolean flipY = false;
};

[Exposed=(Window, Worker), SecureContext]
interface GPUCommandBuffer {
};
GPUCommandBuffer includes GPUObjectBase;

dictionary GPUCommandBufferDescriptor
         : GPUObjectDescriptorBase {
};

interface mixin GPUCommandsMixin {
};

[Exposed=(Window, Worker), SecureContext]
interface GPUCommandEncoder {
    GPURenderPassEncoder beginRenderPass(GPURenderPassDescriptor descriptor);
    GPUComputePassEncoder beginComputePass(optional GPUComputePassDescriptor descriptor = {});

    undefined copyBufferToBuffer(
        GPUBuffer source,
        GPUBuffer destination,
        optional GPUSize64 size);
    undefined copyBufferToBuffer(
        GPUBuffer source,
        GPUSize64 sourceOffset,
        GPUBuffer destination,
        GPUSize64 destinationOffset,
        optional GPUSize64 size);

    undefined copyBufferToTexture(
        GPUTexelCopyBufferInfo source,
        GPUTexelCopyTextureInfo destination,
        GPUExtent3D copySize);

    undefined copyTextureToBuffer(
        GPUTexelCopyTextureInfo source,
        GPUTexelCopyBufferInfo destination,
        GPUExtent3D copySize);

    undefined copyTextureToTexture(
        GPUTexelCopyTextureInfo source,
        GPUTexelCopyTextureInfo destination,
        GPUExtent3D copySize);

    undefined clearBuffer(
        GPUBuffer buffer,
        optional GPUSize64 offset = 0,
        optional GPUSize64 size);

    undefined resolveQuerySet(
        GPUQuerySet querySet,
        GPUSize32 firstQuery,
        GPUSize32 queryCount,
        GPUBuffer destination,
        GPUSize64 destinationOffset);

    GPUCommandBuffer finish(optional GPUCommandBufferDescriptor descriptor = {});
};
GPUCommandEncoder includes GPUObjectBase;
GPUCommandEncoder includes GPUCommandsMixin;
GPUCommandEncoder includes GPUDebugCommandsMixin;

dictionary GPUCommandEncoderDescriptor
         : GPUObjectDescriptorBase {
};

interface mixin GPUBindingCommandsMixin {
    undefined setBindGroup(GPUIndex32 index, GPUBindGroup? bindGroup,
        optional sequence<GPUBufferDynamicOffset> dynamicOffsets = []);

    undefined setBindGroup(GPUIndex32 index, GPUBindGroup? bindGroup,
        [AllowShared] Uint32Array dynamicOffsetsData,
        GPUSize64 dynamicOffsetsDataStart,
        GPUSize32 dynamicOffsetsDataLength);
};

interface mixin GPUDebugCommandsMixin {
    undefined pushDebugGroup(USVString groupLabel);
    undefined popDebugGroup();
    undefined insertDebugMarker(USVString markerLabel);
};

[Exposed=(Window, Worker), SecureContext]
interface GPUComputePassEncoder {
    undefined setPipeline(GPUComputePipeline pipeline);
    undefined dispatchWorkgroups(GPUSize32 workgroupCountX, optional GPUSize32 workgroupCountY = 1, optional GPUSize32 workgroupCountZ = 1);
    undefined dispatchWorkgroupsIndirect(GPUBuffer indirectBuffer, GPUSize64 indirectOffset);

    undefined end();
};
GPUComputePassEncoder includes GPUObjectBase;
GPUComputePassEncoder includes GPUCommandsMixin;
GPUComputePassEncoder includes GPUDebugCommandsMixin;
GPUComputePassEncoder includes GPUBindingCommandsMixin;

dictionary GPUComputePassTimestampWrites {
    required GPUQuerySet querySet;
    GPUSize32 beginningOfPassWriteIndex;
    GPUSize32 endOfPassWriteIndex;
};

dictionary GPUComputePassDescriptor
         : GPUObjectDescriptorBase {
    GPUComputePassTimestampWrites timestampWrites;
};

[Exposed=(Window, Worker), SecureContext]
interface GPURenderPassEncoder {
    undefined setViewport(float x, float y,
        float width, float height,
        float minDepth, float maxDepth);

    undefined setScissorRect(GPUIntegerCoordinate x, GPUIntegerCoordinate y,
                        GPUIntegerCoordinate width, GPUIntegerCoordinate height);

    undefined setBlendConstant(GPUColor color);
    undefined setStencilReference(GPUStencilValue reference);

    undefined beginOcclusionQuery(GPUSize32 queryIndex);
    undefined endOcclusionQuery();

    undefined executeBundles(sequence<GPURenderBundle> bundles);
    undefined end();
};
GPURenderPassEncoder includes GPUObjectBase;
GPURenderPassEncoder includes GPUCommandsMixin;
GPURenderPassEncoder includes GPUDebugCommandsMixin;
GPURenderPassEncoder includes GPUBindingCommandsMixin;
GPURenderPassEncoder includes GPURenderCommandsMixin;

dictionary GPURenderPassTimestampWrites {
    required GPUQuerySet querySet;
    GPUSize32 beginningOfPassWriteIndex;
    GPUSize32 endOfPassWriteIndex;
};

dictionary GPURenderPassDescriptor
         : GPUObjectDescriptorBase {
    required sequence<GPURenderPassColorAttachment?> colorAttachments;
    GPURenderPassDepthStencilAttachment depthStencilAttachment;
    GPUQuerySet occlusionQuerySet;
    GPURenderPassTimestampWrites timestampWrites;
    GPUSize64 maxDrawCount = 50000000;
};

dictionary GPURenderPassColorAttachment {
    required (GPUTexture or GPUTextureView) view;
    GPUIntegerCoordinate depthSlice;
    (GPUTexture or GPUTextureView) resolveTarget;

    GPUColor clearValue;
    required GPULoadOp loadOp;
    required GPUStoreOp storeOp;
};

dictionary GPURenderPassDepthStencilAttachment {
    required (GPUTexture or GPUTextureView) view;

    float depthClearValue;
    GPULoadOp depthLoadOp;
    GPUStoreOp depthStoreOp;
    boolean depthReadOnly = false;

    GPUStencilValue stencilClearValue = 0;
    GPULoadOp stencilLoadOp;
    GPUStoreOp stencilStoreOp;
    boolean stencilReadOnly = false;
};

enum GPULoadOp {
    "load",
    "clear",
};

enum GPUStoreOp {
    "store",
    "discard",
};

dictionary GPURenderPassLayout
         : GPUObjectDescriptorBase {
    required sequence<GPUTextureFormat?> colorFormats;
    GPUTextureFormat depthStencilFormat;
    GPUSize32 sampleCount = 1;
};

interface mixin GPURenderCommandsMixin {
    undefined setPipeline(GPURenderPipeline pipeline);

    undefined setIndexBuffer(GPUBuffer buffer, GPUIndexFormat indexFormat, optional GPUSize64 offset = 0, optional GPUSize64 size);
    undefined setVertexBuffer(GPUIndex32 slot, GPUBuffer? buffer, optional GPUSize64 offset = 0, optional GPUSize64 size);

    undefined draw(GPUSize32 vertexCount, optional GPUSize32 instanceCount = 1,
        optional GPUSize32 firstVertex = 0, optional GPUSize32 firstInstance = 0);
    undefined drawIndexed(GPUSize32 indexCount, optional GPUSize32 instanceCount = 1,
        optional GPUSize32 firstIndex = 0,
        optional GPUSignedOffset32 baseVertex = 0,
        optional GPUSize32 firstInstance = 0);

    undefined drawIndirect(GPUBuffer indirectBuffer, GPUSize64 indirectOffset);
    undefined drawIndexedIndirect(GPUBuffer indirectBuffer, GPUSize64 indirectOffset);
};

[Exposed=(Window, Worker), SecureContext]
interface GPURenderBundle {
};
GPURenderBundle includes GPUObjectBase;

dictionary GPURenderBundleDescriptor
         : GPUObjectDescriptorBase {
};

[Exposed=(Window, Worker), SecureContext]
interface GPURenderBundleEncoder {
    GPURenderBundle finish(optional GPURenderBundleDescriptor descriptor = {});
};
GPURenderBundleEncoder includes GPUObjectBase;
GPURenderBundleEncoder includes GPUCommandsMixin;
GPURenderBundleEncoder includes GPUDebugCommandsMixin;
GPURenderBundleEncoder includes GPUBindingCommandsMixin;
GPURenderBundleEncoder includes GPURenderCommandsMixin;

dictionary GPURenderBundleEncoderDescriptor
         : GPURenderPassLayout {
    boolean depthReadOnly = false;
    boolean stencilReadOnly = false;
};

dictionary GPUQueueDescriptor
         : GPUObjectDescriptorBase {
};

[Exposed=(Window, Worker), SecureContext]
interface GPUQueue {
    undefined submit(sequence<GPUCommandBuffer> commandBuffers);

    Promise<undefined> onSubmittedWorkDone();

    undefined writeBuffer(
        GPUBuffer buffer,
        GPUSize64 bufferOffset,
        AllowSharedBufferSource data,
        optional GPUSize64 dataOffset = 0,
        optional GPUSize64 size);

    undefined writeTexture(
        GPUTexelCopyTextureInfo destination,
        AllowSharedBufferSource data,
        GPUTexelCopyBufferLayout dataLayout,
        GPUExtent3D size);

    undefined copyExternalImageToTexture(
        GPUCopyExternalImageSourceInfo source,
        GPUCopyExternalImageDestInfo destination,
        GPUExtent3D copySize);
};
GPUQueue includes GPUObjectBase;

[Exposed=(Window, Worker), SecureContext]
interface GPUQuerySet {
    undefined destroy();

    readonly attribute GPUQueryType type;
    readonly attribute GPUSize32Out count;
};
GPUQuerySet includes GPUObjectBase;

dictionary GPUQuerySetDescriptor
         : GPUObjectDescriptorBase {
    required GPUQueryType type;
    required GPUSize32 count;
};

enum GPUQueryType {
    "occlusion",
    "timestamp",
};

[Exposed=(Window, Worker), SecureContext]
interface GPUCanvasContext {
    readonly attribute (HTMLCanvasElement or OffscreenCanvas) canvas;

    undefined configure(GPUCanvasConfiguration configuration);
    undefined unconfigure();

    GPUCanvasConfiguration? getConfiguration();
    GPUTexture getCurrentTexture();
};

enum GPUCanvasAlphaMode {
    "opaque",
    "premultiplied",
};

enum GPUCanvasToneMappingMode {
    "standard",
    "extended",
};

dictionary GPUCanvasToneMapping {
  GPUCanvasToneMappingMode mode = "standard";
};

dictionary GPUCanvasConfiguration {
    required GPUDevice device;
    required GPUTextureFormat format;
    GPUTextureUsageFlags usage = 0x10;  // GPUTextureUsage.RENDER_ATTACHMENT
    sequence<GPUTextureFormat> viewFormats = [];
    PredefinedColorSpace colorSpace = "srgb";
    GPUCanvasToneMapping toneMapping = {};
    GPUCanvasAlphaMode alphaMode = "opaque";
};

enum GPUDeviceLostReason {
    "unknown",
    "destroyed",
};

[Exposed=(Window, Worker), SecureContext]
interface GPUDeviceLostInfo {
    readonly attribute GPUDeviceLostReason reason;
    readonly attribute DOMString message;
};

partial interface GPUDevice {
    readonly attribute Promise<GPUDeviceLostInfo> lost;
};

[Exposed=(Window, Worker), SecureContext]
interface GPUError {
    readonly attribute DOMString message;
};

[Exposed=(Window, Worker), SecureContext]
interface GPUValidationError
        : GPUError {
    constructor(DOMString message);
};

[Exposed=(Window, Worker), SecureContext]
interface GPUOutOfMemoryError
        : GPUError {
    constructor(DOMString message);
};

[Exposed=(Window, Worker), SecureContext]
interface GPUInternalError
        : GPUError {
    constructor(DOMString message);
};

enum GPUErrorFilter {
    "validation",
    "out-of-memory",
    "internal",
};

partial interface GPUDevice {
    undefined pushErrorScope(GPUErrorFilter filter);
    Promise<GPUError?> popErrorScope();
};

[Exposed=(Window, Worker), SecureContext]
interface GPUUncapturedErrorEvent : Event {
    constructor(
        DOMString type,
        GPUUncapturedErrorEventInit gpuUncapturedErrorEventInitDict
    );
    [SameObject] readonly attribute GPUError error;
};

dictionary GPUUncapturedErrorEventInit : EventInit {
    required GPUError error;
};

partial interface GPUDevice {
    attribute EventHandler onuncapturederror;
};

typedef [EnforceRange] unsigned long GPUBufferDynamicOffset;
typedef [EnforceRange] unsigned long GPUStencilValue;
typedef [EnforceRange] unsigned long GPUSampleMask;
typedef [EnforceRange] long GPUDepthBias;

typedef [EnforceRange] unsigned long long GPUSize64;
typedef [EnforceRange] unsigned long GPUIntegerCoordinate;
typedef [EnforceRange] unsigned long GPUIndex32;
typedef [EnforceRange] unsigned long GPUSize32;
typedef [EnforceRange] long GPUSignedOffset32;

typedef unsigned long long GPUSize64Out;
typedef unsigned long GPUIntegerCoordinateOut;
typedef unsigned long GPUSize32Out;

typedef unsigned long GPUFlagsConstant;

dictionary GPUColorDict {
    required double r;
    required double g;
    required double b;
    required double a;
};
typedef (sequence<double> or GPUColorDict) GPUColor;

dictionary GPUOrigin2DDict {
    GPUIntegerCoordinate x = 0;
    GPUIntegerCoordinate y = 0;
};
typedef (sequence<GPUIntegerCoordinate> or GPUOrigin2DDict) GPUOrigin2D;

dictionary GPUOrigin3DDict {
    GPUIntegerCoordinate x = 0;
    GPUIntegerCoordinate y = 0;
    GPUIntegerCoordinate z = 0;
};
typedef (sequence<GPUIntegerCoordinate> or GPUOrigin3DDict) GPUOrigin3D;

dictionary GPUExtent3DDict {
    required GPUIntegerCoordinate width;
    GPUIntegerCoordinate height = 1;
    GPUIntegerCoordinate depthOrArrayLayers = 1;
};
typedef (sequence<GPUIntegerCoordinate> or GPUExtent3DDict) GPUExtent3D;