WebGPU

W3C 候选推荐草案,

关于本文档的更多信息
此版本:
https://www.w3.org/TR/2026/CRD-webgpu-20260109/
最新发布版本:
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存档)发送评论。本草案突出了工作组仍需讨论的一些待决问题,目前尚未就其结果作出决定,包括其有效性。

本文档由 Web GPU 工作组 以候选推荐草案(Candidate Recommendation Draft)形式发布,采用了 推荐流程。本文件将至少在 前保持候选推荐状态。

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

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

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

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

本文档受 2025年8月18日 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 接口在其所有子对象都被垃圾回收之前可能会一直存活,这会导致某些资源的分配时间比预期更长。

如果需要可预测地释放已分配的资源,应优先调用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 会话 兼容。

[[default feature level]],类型为 功能级别字符串,只读

表示由此适配器创建的设备的默认功能级别。

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

[[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 接口实例。

要从 adapter adapter 创建一个 新设备,并携带 GPUDeviceDescriptor descriptor,请按照以下 设备时序 步骤操作:
  1. features集合 descriptor.requiredFeatures 中的所有值。

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

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

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

    1. 追加 "rg11b10ufloat-renderable"features

  4. 将所有默认 GPUFeatureNameadapter.[[default feature level]] 的定义追加到 features

  5. limits 为一个新的 supported limits 对象,使用 adapter.[[default feature level]] 定义的默认limits。

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

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

      1. 设置 limits[key] 为 value

  7. 设置 limits.maxStorageBuffersPerShaderStage 为 max(limits.maxStorageBuffersPerShaderStagelimits.maxStorageBuffersInVertexStagelimits.maxStorageBuffersInFragmentStage)。

  8. 设置 limits.maxStorageTexturesPerShaderStage 为 max(limits.maxStorageTexturesPerShaderStagelimits.maxStorageTexturesInVertexStagelimits.maxStorageTexturesInFragmentStage)。

  9. 如果 features 包含 "core-features-and-limits"

    1. 设置 limits.maxStorageBuffersInVertexStagelimits.maxStorageBuffersInFragmentStagelimits.maxStorageBuffersPerShaderStage

    2. 设置 limits.maxStorageTexturesInVertexStagelimits.maxStorageTexturesInFragmentStagelimits.maxStorageTexturesPerShaderStage

  10. device 为一个设备对象。

  11. 设置 device.[[adapter]]adapter

  12. 设置 device.[[features]]features

  13. 设置 device.[[limits]]limits

  14. 返回 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 调用将根据这些特性(而非适配器的特性)进行校验:

当且仅当 GPUFeatureName feature 满足 GPUObjectBase object[[device]].[[features]] 包含 feature 时, 对其启用

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

注意: 即使某些功能受支持,启用它们也未必可取,因为这可能会带来性能影响。 因此,为了提升在不同设备和实现之间的可移植性,应用一般只应请求它们实际可能需要的功能。

3.6.2. 限制

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

注意: 即使受支持,设置“更高”限制也未必可取,因为这样做可能会影响性能。 因此,为了提升不同设备和实现之间的可移植性,应用一般只应在确有需要时才请求高于默认值的限制。

每个限制项都有一个默认值和一个兼容模式默认值。

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

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

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

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

最大值

该限制对传入 API 的某个值施加最大限制。

数值越高越

只允许设置为大于等于默认值的数值。 更小的数值会被钳制为默认值

对齐

该限制对传入 API 的某个值要求最小对齐,也就是说,该值必须是该限制的倍数。

数值越低越

只允许设置为不大于默认值的 2 的幂。 不是 2 的幂的数值无效。 更大的 2 的幂会被钳制为默认值

支持的限制 对象拥有 WebGPU 定义的每一个限制的取值:

限制名称 类型 限制类别 默认值 兼容模式默认值
maxTextureDimension1D GPUSize32 最大值 8192 4096
使用 size.width 的允许最大值,适用于通过 dimension 设置为 "1d" 创建的 texture
maxTextureDimension2D GPUSize32 最大值 8192 4096
使用 size.widthsize.height 的允许最大值,适用于通过 dimension 设置为 "2d" 创建的 texture
maxTextureDimension3D GPUSize32 最大值 2048
使用 sizewidthsizeheight 以及 sizedepthOrArrayLayers 的允许最大值,适用于通过 dimension 设置为 "3d" 创建的 texture
maxTextureArrayLayers GPUSize32 最大值 256
使用 sizedepthOrArrayLayers 的允许最大值,适用于通过 dimension 设置为 "2d" 创建的 texture
maxBindGroups GPUSize32 最大值 4
创建 GPUPipelineLayout 时, 在 bindGroupLayouts 中允许的 GPUBindGroupLayouts 的最大数量。
maxBindGroupsPlusVertexBuffers GPUSize32 最大值 24
同时使用的绑定组和顶点缓冲槽的最大数量,计入最高索引以下的任何空槽。 在 createRenderPipeline()绘制调用 中进行验证。
maxBindingsPerBindGroup GPUSize32 最大值 1000
创建 GPUBindGroupLayout 时可用的绑定索引数量。

注意: 该限制是规范性的,但具有任意性。 在默认的 绑定槽上限 下,不可能在一个绑定组中使用 1000 个绑定,但这允许 GPUBindGroupLayoutEntry.binding 值高达 999。 该限制允许实现将绑定空间视为数组(在合理的内存空间内),而不是稀疏映射结构。

maxDynamicUniformBuffersPerPipelineLayout GPUSize32 最大值 8
GPUPipelineLayout 中, 作为具有动态偏移的 uniform buffers 的 GPUBindGroupLayoutEntry 条目的最大数量。 参见 超过绑定槽上限
maxDynamicStorageBuffersPerPipelineLayout GPUSize32 最大值 4
GPUPipelineLayout 中, 作为具有动态偏移的 storage buffers 的 GPUBindGroupLayoutEntry 条目的最大数量。 参见 超过绑定槽上限
maxSampledTexturesPerShaderStage GPUSize32 最大值 16
对于每个可能的 GPUShaderStage stage,作为采样纹理的 GPUBindGroupLayoutEntry 条目在 GPUPipelineLayout 中的最大数量。 参见 超过绑定槽上限
maxSamplersPerShaderStage GPUSize32 最大值 16
对于每个可能的 GPUShaderStage stage,作为采样器的 GPUBindGroupLayoutEntry 条目在 GPUPipelineLayout 中的最大数量。 参见 超过绑定槽上限
maxStorageBuffersPerShaderStage GPUSize32 最大值 8
对于每个可能的 GPUShaderStage stage,作为 storage buffers 的 GPUBindGroupLayoutEntry 条目在 GPUPipelineLayout 中的最大数量。 参见 超过绑定槽上限

注意: 该限制适用于所有阶段。 在 设备初始化 时, 它会与 maxStorageBuffersInVertexStagemaxStorageBuffersInFragmentStage 进行标准化,以便在验证算法中,每个阶段只需针对三者中的一个限制进行检查。

maxStorageBuffersInVertexStage GPUSize32 最大值 8 0
对于顶点阶段,作为 storage buffers 的 GPUBindGroupLayoutEntry 条目在 GPUPipelineLayout 中的最大数量。 参见 超过绑定槽上限
maxStorageBuffersInFragmentStage GPUSize32 最大值 8 4
对于片段阶段,作为 storage buffers 的 GPUBindGroupLayoutEntry 条目在 GPUPipelineLayout 中的最大数量。 参见 超过绑定槽上限
maxStorageTexturesPerShaderStage GPUSize32 最大值 4
对于每个可能的 GPUShaderStage stage,作为 storage textures 的 GPUBindGroupLayoutEntry 条目在 GPUPipelineLayout 中的最大数量。 参见 超过绑定槽上限

注意: 该限制适用于所有阶段。 在 设备初始化 时, 它会与 maxStorageTexturesInVertexStagemaxStorageTexturesInFragmentStage 进行标准化,以便在验证算法中,每个阶段只需针对三者中的一个限制进行检查。

maxStorageTexturesInVertexStage GPUSize32 最大值 4 0
对于顶点阶段,作为 storage textures 的 GPUBindGroupLayoutEntry 条目在 GPUPipelineLayout 中的最大数量。 参见 超过绑定槽上限
maxStorageTexturesInFragmentStage GPUSize32 最大值 4
对于片段阶段,作为 storage textures 的 GPUBindGroupLayoutEntry 条目在 GPUPipelineLayout 中的最大数量。 参见 超过绑定槽上限
maxUniformBuffersPerShaderStage GPUSize32 最大值 12
对于每个可能的 GPUShaderStage stage,作为 uniform buffers 的 GPUBindGroupLayoutEntry 条目在 GPUPipelineLayout 中的最大数量。 参见 超过绑定槽上限
maxUniformBufferBindingSize GPUSize64 最大值 65536 bytes 16384 bytes
对于具有 GPUBufferBinding.size 的绑定,当相应的 GPUBindGroupLayoutEntryentryentry.buffer?.type"uniform" 时的最大值。
maxStorageBufferBindingSize GPUSize64 最大值 134217728 bytes (128 MiB)
对于具有 GPUBufferBinding.size 的绑定,当相应的 GPUBindGroupLayoutEntryentryentry.buffer?.type"storage""read-only-storage" 时的最大值。
minUniformBufferOffsetAlignment GPUSize32 对齐 256 bytes
对于具有 GPUBufferBindingoffset 以及在 setBindGroup() 中提供的动态偏移, 当相应的 GPUBindGroupLayoutEntryentryentry.buffer?.type"uniform" 时所需的对齐。
minStorageBufferOffsetAlignment GPUSize32 对齐 256 bytes
对于具有 GPUBufferBindingoffset 以及在 setBindGroup() 中提供的动态偏移, 当相应的 GPUBindGroupLayoutEntryentryentry.buffer?.type"storage""read-only-storage" 时所需的对齐。
maxVertexBuffers GPUSize32 最大值 8
创建 GPURenderPipeline 时, 最大的 buffers 数量。
maxBufferSize GPUSize64 最大值 268435456 bytes (256 MiB)
创建 GPUBuffersize 的最大值。
maxVertexAttributes GPUSize32 最大值 16
创建 GPURenderPipeline 时, 在所有 buffers 中总计允许的 attributes 的最大数量。
maxVertexBufferArrayStride GPUSize32 最大值 2048 bytes
创建 GPURenderPipeline 时允许的最大的 arrayStride
maxInterStageShaderVariables GPUSize32 最大值 16 15
用于阶段间通信(例如顶点输出或片段输入)的输入或输出变量的最大允许数量。
maxColorAttachments GPUSize32 最大值 8 4
GPURenderPipelineDescriptor.fragment.targetsGPURenderPassDescriptor.colorAttachments, 以及 GPURenderPassLayout.colorFormats 中允许的颜色附件的最大数量。
maxColorAttachmentBytesPerSample GPUSize32 最大值 32
渲染管线输出数据中,跨所有颜色附件保存一个采样(像素或子像素)所需的最大字节数。
maxComputeWorkgroupStorageSize GPUSize32 最大值 16384 bytes
一个 compute 阶段 workgroup 存储可使用的最大字节数, 针对 GPUShaderModule 的入口点。
maxComputeInvocationsPerWorkgroup GPUSize32 最大值 256 128
对于 compute 阶段 workgroup_size 维度乘积的最大允许值,针对 GPUShaderModule 的入口点。
maxComputeWorkgroupSizeX GPUSize32 最大值 256 128
对于 compute 阶段入口点,workgroup_size 的 X 维度的最大允许值,针对 GPUShaderModule 的入口点。
maxComputeWorkgroupSizeY GPUSize32 最大值 256 128
对于 compute 阶段入口点,workgroup_size 的 Y 维度的最大允许值,针对 GPUShaderModule 的入口点。
maxComputeWorkgroupSizeZ GPUSize32 最大值 64
对于 compute 阶段入口点,workgroup_size 的 Z 维度的最大允许值,针对 GPUShaderModule 的入口点。
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 maxStorageBuffersInVertexStage;
    readonly attribute unsigned long maxStorageBuffersInFragmentStage;
    readonly attribute unsigned long maxStorageTexturesPerShaderStage;
    readonly attribute unsigned long maxStorageTexturesInVertexStage;
    readonly attribute unsigned long maxStorageTexturesInFragmentStage;
    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 是一个 类集合接口。其 集合条目 是适配器或设备支持的 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. 特性检测

本节为非规范性内容。

完整实现本规范需要实现其规定的所有内容,除非另有说明(如 § 3.6 可选能力)。

然而,由于新的“核心”补充会在实现公开之前添加到本规范中,许多特性被设计为可供应用进行特性检测:

3.8. 扩展文档

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

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

3.9. 源限制(Origin Restrictions)

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

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

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

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

3.10. 任务源(Task Sources)

3.10.1. WebGPU 任务源

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

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

3.10.2. 自动过期任务源

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

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

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

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

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

3.11. 色彩空间与编码

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

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

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

注意:
如上所述,GPUTexture不是色彩管理的。这包括 -srgb 格式,尽管它们并没有被标记为 sRGB 色彩空间(如 PredefinedColorSpace 和 CSS 色彩空间 srgbsrgb-linear 所描述的那样)。

然而,-srgb 纹理格式确实具有与 "srgb""display-p3" 进行伽马编码时算法上非常接近的伽马编码/解码特性。例如,片元着色器可以向 -srgb 格式纹理输出 "sRGB-linear" 编码(物理线性)的颜色值,当写入时会进行伽马编码。这样,纹理中的该值将被正确编码,可用于 "srgb" 标记(近似感知线性)的画布上。

同样,也可以利用这些特性,使用 copyExternalImageToTexture();详细信息请参见其描述。

超出色域的预乘 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.11.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.11.2. 色彩空间转换省略

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

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

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

3.12. 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)

向用户代理请求一个适配器。 用户代理决定是否返回适配器,如果返回,则会根据所提供的选项进行选择。

Called on: GPU this.

Arguments:

Arguments for the GPU.requestAdapter(options) method.
Parameter Type Nullable Optional Description
options GPURequestAdapterOptions 用于选择 adapter 的条件。

Returns: Promise<GPUAdapter?>

Content timeline 步骤:

  1. contentTimeline 为当前的 Content timeline

  2. promise一个新的 promise

  3. Device timeline 上对 this 执行 initialization steps

  4. 返回 promise

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

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

    如果有任何条件不满足:

    1. adapternull,在 contentTimeline 上执行 resolution steps,并返回。

  2. 如果 options.featureLevel"compatibility"

    1. options.featureLevel 设为 如果用户代理选择支持则为 "compatibility",否则为 "core"

      注:这不会修改应用传入的 JavaScript 对象。

  3. adapter 设为以下两者之一:

    如果返回了 adapter,按其定义初始化各属性。

    1. 根据适配器支持的能力设置 adapter.[[limits]]adapter.[[features]]

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

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

    4. adapter.[[default feature level]] 设置为 options.featureLevel

  4. contentTimeline 上执行 resolution steps

内容时间线 解决步骤
  1. 如果 adapter 不为 null

    1. resolve promise,其值为封装 adapter 的新 GPUAdapter

    否则:

    1. resolve promise,其值为 null

getPreferredCanvasFormat()

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

返回的值可以作为 format 传递给 configure() 调用,从而确保关联的画布能够高效地显示其内容。

注意: 未显示到屏幕的画布可能使用该格式时有或没有益处。

Called on: GPU this.

Returns: GPUTextureFormat

Content timeline 步骤:

  1. 返回 "rgba8unorm""bgra8unorm", 具体取决于哪种格式在本系统上最适合显示 WebGPU 画布。

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"

请求返回至少支持特定一组能力的适配器(adapter)。 这会影响通过此适配器创建的设备的 [[default feature level]]。 各级别的能力定义见下文,具体步骤见 requestAdapter() 及“新建设备”部分。

如果实现或系统不支持请求的功能级别中的全部能力,requestAdapter() 将返回 null

注: 应用通常只需以其最低支持的 feature level 调用一次 requestAdapter(), 然后检测该适配器是否具备可选的额外能力,并在 requestDevice() 中请求使用这些能力。

允许的 feature level 字符串值为:

"core"

包含如下能力:

注: 含此 [[default feature level]] 的适配器可称为“Core-defaulting”。

"compatibility"

包含如下能力:

如果实现无法强制执行更严格的“兼容模式”校验规则, requestAdapter() 会忽略本请求并视为请求 "core"

注: 含此 [[default feature level]] 的适配器可称为“Compatibility-defaulting”。

powerPreference 类型为 GPUPowerPreference

可选地提供一个提示,指明系统应从可用适配器中选择哪类适配器

该提示值可影响最终选择哪一个适配器,但不会影响是否返回适配器。

注: 该提示的主要作用是影响在多 GPU 系统中具体使用哪一块 GPU。 例如有些笔记本包含低功耗集成 GPU 和高性能独显。 该选项也可能影响所选 GPU 的供电/性能模式,以匹配 powerPreference 的要求。

注: 具体的硬件配置(如电池状态、外接显示器或可拔插GPU等)会影响用户代理在相同 power preference 下所选的适配器, 一般应保证同一硬件与状态和同一 powerPreference,选的适配器也相同。

只能为以下值之一:

undefined(或未设置该项)

不给用户代理任何提示。

"low-power"

表示倾向于选择低功耗、节能优先的适配器。

注: 通常,若绘制性能并非瓶颈(如每秒只渲染一帧,场景简单或使用小画布),内容应使用本值。 如果条件允许,开发者强烈推荐采用本选项,可显著延长便携设备的续航。

"high-performance"

表示优先选择高性能、计算/渲染能力更强的适配器。

注: 选用本值时,开发者需注意在该适配器上创建的设备,用户代理出于省电的考虑更可能强制设备丢失,以切换到低功耗适配器。 除非确有必要,否则只推荐在确实需要高性能时设置此值,否则可能大幅缩短续航。

forceFallbackAdapter类型为 boolean,默认值为 false

true 时仅允许返回回退适配器。如果用户代理不支持回退适配器,则 requestAdapter() 将 resolve 为 null

注: 即使 requestAdapter() 未设置 forceFallbackAdapter 或为 false, 若没有其他合适的适配器,或者用户代理主动决定,也 可能返回回退适配器。 若开发者希望禁止应用运行在回退适配器上,应在请求 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)

adapter 请求一个 device

这是一次性操作:如果成功返回了设备,则该适配器将变为“已消耗”状态。

调用对象: GPUAdapter this.

参数:

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

返回: Promise<GPUDevice>

Content timeline 步骤:

  1. contentTimeline 为当前的 Content timeline

  2. promise一个新的 promise

  3. adapterthis.[[adapter]]

  4. thisDevice timeline 发出 初始化步骤

  5. 返回 promise

Device timeline初始化步骤
  1. 如果下列任一要求未被满足:

    则在 contentTimeline 上发出以下步骤并返回:

    Content timeline 的步骤:
    1. 拒绝 promise,并使用 TypeError

    注:如果浏览器根本不认识某个特性名称(在其 GPUFeatureName 定义中), 也会产生相同的错误。这使得当浏览器不支持某个特性与某个特定 adapter 不支持该特性时的行为一致。

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

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

    2. 对于 descriptor.requiredLimits 中的每个 [key, value],若 value 不是 undefined,则:

      1. key 必须supported limits 的成员名。

      2. value 必须 不得比 adapter.[[limits]][key] 更优。

      3. 如果 keyclassalignment,则 value 必须 为小于 232 的 2 的幂。

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

    如果有任何不满足,则在 contentTimeline 上发出以下步骤并返回:

    Content timeline 的步骤:
    1. 拒绝 promise,并使用 OperationError

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

    1. device 为一个新的 device

    2. Lose the device(device, "unknown").

    3. Assert adapter.[[state]]"expired"

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

    否则:

    1. device 为使用 descriptoradapter 创建 一个新 device 的结果。

    2. Expire adapter

  4. contentTimeline 上发出后续步骤。

Content timeline 的步骤:
  1. gpuDevice 为一个新的 GPUDevice 实例。

  2. gpuDevice.[[device]] 设为 device

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

  4. gpuDevice.label 设为 descriptor.label

  5. 解决 promise,并返回 gpuDevice

    注: 如果由于 adapter 无法满足请求而设备已丢失,device.lost 已在 promise 解析之前被解决。

请求带有默认特性和限制的 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",
    "primitive-index",
    "texture-component-swizzle",
};

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;
    readonly attribute (GPUTextureViewDimension or undefined) textureBindingViewDimension;
};
GPUTexture includes GPUObjectBase;

GPUTexture 拥有如下不可变属性

width类型为 GPUIntegerCoordinateOut,只读

GPUTexture 的宽度。

height类型为 GPUIntegerCoordinateOut,只读

GPUTexture 的高度。

depthOrArrayLayers类型为 GPUIntegerCoordinateOut,只读

GPUTexture 的深度或层数。

mipLevelCount类型为 GPUIntegerCoordinateOut,只读

GPUTexture 的 mip 级别数量。

sampleCount类型为 GPUSize32Out,只读

GPUTexture 的采样数。

dimension类型为 GPUTextureDimension,只读

GPUTexture 各子资源的纹素集的维度。

format类型为 GPUTextureFormat,只读

GPUTexture 的格式。

usage类型为 GPUFlagsConstant,只读

GPUTexture 的允许用法。

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

用于在此 GPUTexture 上创建视图时,可以作为 GPUTextureViewDescriptor.formatGPUTextureFormat 的集合。

textureBindingViewDimension 类型为 (GPUTextureViewDimension 或 undefined),只读
在没有 "core-features-and-limits" 的设备上, 由该纹理创建的视图必须将其作为 dimension

在具备 "core-features-and-limits" 的设备上, 此属性为 undefined,且没有此类限制。

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 = [];
    GPUTextureViewDimension textureBindingViewDimension;
};

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" 且不带-srgb后缀的纹理。 其他系统和格式组合也存在类似的注意事项。

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

若有两个 GPUTextureFormat formatviewFormat,则当如下条件满足时认为它们在特定 device纹理视图格式兼容
textureBindingViewDimension 类型为 GPUTextureViewDimension
在不支持 "core-features-and-limits" 的设备上, 由该纹理创建的视图必须将此作为其 dimension。 如果未指定,则会选用默认值。

在支持 "core-features-and-limits" 的设备上, 该属性会被忽略,也不存在此类限制。

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.widthdescriptor.size.width

  6. 设置 t.heightdescriptor.size.height

  7. 设置 t.depthOrArrayLayersdescriptor.size.depthOrArrayLayers

  8. 设置 t.mipLevelCountdescriptor.mipLevelCount

  9. 设置 t.sampleCountdescriptor.sampleCount

  10. 设置 t.dimensiondescriptor.dimension

  11. 设置 t.formatdescriptor.format

  12. 设置 t.usagedescriptor.usage

  13. 如果 t.[[device]].[[features]]包含 "core-features-and-limits"
    1. descriptor.textureBindingViewDimension 被提供

      1. 设置 t.textureBindingViewDimensiondescriptor.textureBindingViewDimension

      否则,若 descriptor.dimension 为:

      "1d"

      设置 t.textureBindingViewDimension"1d"

      "2d"

      t数组层数 为 1:

      否则:

      "3d"

      设置 t.textureBindingViewDimension"3d"

  14. 设备时间线 上执行 初始化步骤,目标为 this

  15. 返回 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;

    // Requires "texture-component-swizzle" feature.
    DOMString swizzle = "rgba";
};

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 开始,该视图可访问的数组层数量。

swizzle, 类型为 DOMString,默认值为 "rgba"

一个长度为四的字符串,其每个字符分别映射到该纹理视图的红/绿/蓝/alpha 通道。

当由着色器访问时,红/绿/蓝/alpha 通道将分别被 swizzle[0]swizzle[1]swizzle[2]swizzle[3] 指定分量所对应的值替换:

  • "r":取自该纹理的红色通道的值。

  • "g":取自该纹理的绿色通道的值。

  • "b":取自该纹理的蓝色通道的值。

  • "a":取自该纹理的 alpha 通道的值。

  • "0":强制其值为 0。

  • "1":强制其值为 1。

需要启用 "texture-component-swizzle" 功能。

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 个数组层,这些层的行为与一个 "cube" 视图相同, 总共为 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) 方法的参数:
参数 类型 可空 可选 描述
descriptor GPUTextureViewDescriptor 要创建的 GPUTextureView 的描述。

返回值: view,类型为 GPUTextureView

内容 时间线 步骤:

  1. ? 校验贴图格式所需功能 descriptor.formatthis.[[device]]

  2. ? 校验 swizzle 字符串 descriptor.swizzle

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

  4. 设备时间线 上执行 初始化步骤, 针对 this

  5. 返回 view

设备时间线 初始化步骤
  1. descriptor解析 GPUTextureViewDescriptor 默认值 的结果,参数为 thisdescriptor

  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.formatformat

  3. 如果 resolved.mipLevelCount 没有 提供: 设置 resolved.mipLevelCounttexture.mipLevelCountresolved.baseMipLevel

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

    "1d"

    设置 resolved.dimension"1d"

    "2d"

    如果 texture数组层数 为 1 :

    否则:

    "3d"

    设置 resolved.dimension"3d"

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

    "1d""2d""3d"

    设置 resolved.arrayLayerCount1

    "cube"

    设置 resolved.arrayLayerCount6

    "2d-array""cube-array"

    设置 resolved.arrayLayerCounttexture数组层数resolved.baseArrayLayer

  6. 如果 resolved.usage 等于 0: 设置 resolved.usagetexture.usage

  7. 返回 resolved

若要确定 GPUTexture texture数组层数,请执行以下步骤:
  1. 如果 texture.dimension 为:

    "1d""3d"

    返回 1

    "2d"

    返回 texture.depthOrArrayLayers

要对 DOMString swizzle 进行swizzle 字符串验证, 按照以下内容流程步骤执行:
  1. 如果 swizzle 不符合 [ECMAScript] 正则表达式 ^[rgba01]{4}$

    1. 抛出 TypeError

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

GPUBindGroupLayout 中用于资源绑定的唯一标识符, 对应于 GPUBindGroupEntry.binding@binding 属性,以及 GPUShaderModule 中的定义。

visibility, 类型为 GPUShaderStageFlags

GPUShaderStage 成员的位集合。 每个被设置的位代表该 GPUBindGroupLayoutEntry 的资源可在对应着色器阶段被访问。

buffer, 类型为 GPUBufferBindingLayout
sampler, 类型为 GPUSamplerBindingLayout
texture, 类型为 GPUTextureBindingLayout
storageTexture, 类型为 GPUStorageTextureBindingLayout
externalTexture, 类型为 GPUExternalTextureBindingLayout

这些成员中必须有且只有一个被设置,用于指明绑定类型。 该成员的内容指定了此类型的特定选项。

createBindGroup() 中对应的资源 需要该绑定对应的 绑定资源类型

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

绑定组条目在计算着色器中可访问。

绑定成员GPUBindGroupLayoutEntryGPUBindGroupLayoutEntry 中定义的成员决定: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. 对于每个在 entries 中且 entry.visibility 包含 stageentry,如果:

      entry.buffer?.type"uniform"

      视为使用 1 个 maxUniformBuffersPerShaderStage 插槽。

      entry.buffer?.type"storage""read-only-storage"

      如果 stage 为:

      VERTEX

      视为使用 1 个 maxStorageBuffersInVertexStage 插槽。

      FRAGMENT

      视为使用 1 个 maxStorageBuffersInFragmentStage 插槽。

      COMPUTE

      视为使用 1 个 maxStorageBuffersPerShaderStage 插槽。

      entry.sampler提供

      视为使用 1 个 maxSamplersPerShaderStage 插槽。

      entry.texture提供

      视为使用 1 个 maxSampledTexturesPerShaderStage 插槽。

      entry.storageTexture提供

      如果 stage 为:

      VERTEX

      视为使用 1 个 maxStorageTexturesInVertexStage 插槽。

      FRAGMENT

      视为使用 1 个 maxStorageTexturesInFragmentStage 插槽。

      COMPUTE

      视为使用 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]],类型为 ordered map<GPUSize32, GPUBindGroupLayoutEntry>, 只读

GPUBindGroupLayout 描述的绑定索引到 GPUBindGroupLayoutEntry 的映射。

[[dynamicOffsetCount]],类型为 GPUSize32, 只读

GPUBindGroupLayout 中具有动态偏移量的 buffer 绑定数量。

[[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已绑定缓冲区范围, 给定 list<GPUBufferDynamicOffset> dynamicOffsets,按如下步骤计算:
  1. result 为新的 set<(GPUBindGroupLayoutEntry, GPUBufferBinding)>。

  2. dynamicOffsetIndex 为 0。

  3. 对于 bindGroup.[[entries]] 中,按照 bindGroupEntry.binding 排序的每一个 GPUBindGroupEntry bindGroupEntry

    1. bindGroupLayoutEntrybindGroup.[[layout]].[[entryMap]][bindGroupEntry.binding]。

    2. 如果 bindGroupLayoutEntry.buffer提供,则继续

    3. bound以 buffer 绑定方式获取(bindGroupEntry.resource)。

    4. 如果 bindGroupLayoutEntry.buffer.hasDynamicOffset

      1. bound.offset 增加 dynamicOffsets[dynamicOffsetIndex]。

      2. dynamicOffsetIndex 加 1。

    5. result 添加(bindGroupLayoutEntry, bound)。

  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. bindingDescriptor.[[prevalidatedSize]]layoutBinding 所定义的 绑定成员bufferlayoutBinding.buffer.minBindingSize0 时为 false,否则为 true

以纹理视图获取(resource)

参数:

返回值: GPUTextureView

  1. 断言 resourceGPUTextureGPUTextureView

  2. 如果 resource 是:

    GPUTexture
    1. 返回 resource.createView()

    GPUTextureView
    1. 返回 resource

以 buffer 绑定方式获取(resource)

参数:

返回值: GPUBufferBinding

  1. 断言 resourceGPUBufferGPUBufferBinding

  2. 如果 resource 是:

    GPUBuffer
    1. bufferBinding 为新的 GPUBufferBinding

    2. 设置 bufferBinding.bufferresource

    3. 返回 bufferBinding

    GPUBufferBinding
    1. 返回 resource

有效 buffer 绑定大小(binding)

参数:

返回值: GPUSize64

  1. 如果 binding.size提供

    1. 返回 max(0, binding.buffer.size - binding.offset);

  2. 返回 binding.size

两个 GPUBufferBinding 对象 ab 满足下列所有条件时,被认为是 buffer 绑定别名

注意:做此计算时,任何动态偏移量都已经应用到范围上。

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. limitsthis.[[device]].[[limits]]

  2. bindGroupLayouts 为大小为 limits.maxBindGroups, 每项为 nulllist, 元素类型为 GPUBindGroupLayout

  3. 对于 descriptor.bindGroupLayouts 中下标为 ibindGroupLayout

    1. 如果 bindGroupLayout 不为 nullbindGroupLayout.[[descriptor]].entries为空

      1. 设置 bindGroupLayouts[i] 为 bindGroupLayout

  4. allEntries 为所有非 null bglbindGroupLayouts 中, bgl.[[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;
};

GPUCompilationMessage 是由 GPUShaderModule 编译器生成的信息、警告或错误消息。这些消息旨在便于开发者阅读,以帮助他们诊断着色器 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"

          否则:

          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 为根的着色器阶段中的函数中的每一次对纹理内建函数的调用 call

    1. textureBindingcall 所用的纹理绑定。

    2. 如果 textureBinding 类型为 采样纹理深度纹理,且 call 用到类型为 sampler(不包括sampler_comparison)的采样器绑定 samplerBinding

      1. texture 为与 textureBinding 对应的 GPUBindGroupLayoutEntry

      2. sampler 为与 samplerBinding 对应的 GPUBindGroupLayoutEntry

      3. 如果 sampler.type"filtering", 那么 texture.sampleType 必须"float"

      注意: "comparison" 类型采样器也只能和 "depth" 纹理搭配使用,因为只有这种纹理类型可以绑定到 WGSL 的 texture_depth_* 绑定。

    3. 如果 device.[[features]]包含 "core-features-and-limits"
      1. 如果 calltextureLoad 的调用, 则 textureBinding 不能是 深度纹理 类型。

      2. 如果 call 用到了采样器绑定 samplerBindingtextureBinding深度纹理类型, 那么 samplerBinding 必须为 sampler_comparison 类型。

  6. 对于 descriptor.constants 中的每个 keyvalue

    1. key 必须等于着色器模块 descriptor.module 中以WGSL 标识符比较规则定义的某个可管线重载常量的 可管线重载常量标识符字符串。 该可管线重载常量不要求entryPoint静态使用。 设该常量类型为 T

    2. IDL值 value 转为WGSL类型 T不得抛出 TypeError

  7. 对于被 entryPoint 静态使用 的每个 可管线重载常量标识符字符串 key

  8. 管线创建程序错误不得[WGSL] 规范中的规则产生。

  9. 如果 device.[[features]]包含 "core-features-and-limits"
    1. sum 为 0。

    2. 对于任意在以 entryPoint 为根的着色器阶段中的函数的任一纹理内建调用中用到的唯一纹理或外部纹理绑定 textureBinding:

      1. samplerBindings 为在任一上述纹理内建调用中与 textureBinding 一起使用的采样器绑定的集合。

      2. numPairsmax(1, samplerBindings 的元素数量)

      3. 如果 textureBinding 是外部纹理绑定:

        1. numPairs = 1 + 3 * numPairs

      4. sum = sum + numPairs

    3. sum必须device.limits.maxSampledTexturesPerShaderStage

    4. sum必须device.limits.maxSamplersPerShaderStage

校验着色器绑定(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 中每个非 nullcolorState

      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(descriptor, layout, device)

参数:

设备时间线 步骤:

  1. 仅当以下所有条件都满足时,返回 true

校验兼容模式着色器绑定(variable)

参数:

返回值: boolean

设备时间线步骤:

  1. 如果 variable插值类型linear,返回 false

  2. 如果 variable插值类型flat插值采样不是 either,返回 false

  3. 如果 variable插值采样sample,返回 false

  4. 返回 true

校验阶段间接口(device, descriptor)

参数:

返回值: boolean

设备时间线 步骤:

  1. maxVertexShaderOutputVariablesdevice.limits.maxInterStageShaderVariables

  2. maxVertexShaderOutputLocationdevice.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

    • descriptor.vertex 的用户自定义输出数量不得超过 maxVertexShaderOutputVariables

    • 每个 descriptor.vertex 的用户自定义输出的 location 必须 ≤ maxVertexShaderOutputLocation

  6. 如果 device.[[features]]包含 "core-features-and-limits"

    1. 对于 descriptor.vertex 的每个用户自定义 output

      1. 如果 校验兼容模式着色器绑定(output) 失败,则返回 false

  7. 如果 descriptor.fragment 已提供

    1. maxFragmentShaderInputVariablesdevice.limits.maxInterStageShaderVariables

    2. 对于 descriptor.fragment 的每个 阶段间内建变量输入:

      1. maxFragmentShaderInputVariables 减 1。

    3. 如未满足以下某一要求,返回 false

      • 对于 descriptor.fragment 的每个用户自定义输入, 必须存在 descriptor.vertex 的用户自定义输出,其 location、类型和 插值方式 与输入一致。

        注意:仅顶点管线可以在顶点阶段有用户自定义输出;这些值会被丢弃。

      • descriptor.fragment 的用户自定义输入不得超过 maxFragmentShaderInputVariables

    4. 断言 descriptor.fragment 的每个用户自定义输入的 location 小于 device.limits.maxInterStageShaderVariables。 (由上述规则保证)

    5. 如果 device.[[features]]包含 "core-features-and-limits"

      1. 对于 descriptor.fragment 的每个用户自定义 input

        1. 如果 校验兼容模式着色器绑定(input) 失败,返回 false

  8. 返回 true

以下 内置变量阶段间内置值,在片元着色器中使用时会计入 maxInterStageShaderVariables 限制:

创建一个简单的 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";

    // Requires "depth-clip-control" feature.
    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(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 仅与 colorAttachmentsdepthStencilAttachment) 拥有匹配 sampleCount 的附件纹理兼容。

mask类型为 GPUSampleMask,默认值为 0xFFFFFFFF

决定哪些采样点会被写入的掩码。

alphaToCoverageEnabled类型为 boolean,默认值为 false

当为 true 时,表示片元的 alpha 通道应被用于生成采样覆盖掩码。

校验 GPUMultisampleState(descriptor) 参数:

设备时间线步骤:

  1. 当且仅当以下所有条件满足时返回 true

10.3.4. 片元状态(Fragment State)

dictionary GPUFragmentState
         : GPUProgrammableStage {
    required sequence<GPUColorTargetState?> targets;
};
targets类型为 sequence<GPUColorTargetState?>

一个 GPUColorTargetState 列表,定义本管线写入的颜色目标的格式和行为。

校验 GPUFragmentState(device, descriptor, layout)

参数:

设备时间线步骤:

  1. 当且仅当以下所有要求满足时返回 true

校验 GPUFragmentState 的 color attachment 每采样字节数(device, targets)

参数:

设备时间线步骤:

  1. formats 为一个空的 list<GPUTextureFormat?>。

  2. 对于 targets 中的每个 target

    1. 如果 targetundefined,则 continue。

    2. target.format 添加到 formats

  3. 计算 color attachment 每采样字节数(formats) 必须 ≤ device.[[limits]].maxColorAttachmentBytesPerSample

注意: 片元着色器可能会输出比管线实际使用更多的值。这种情况下对应的值会被忽略。

GPUBlendComponent component 是逻辑 device device 下的 有效 GPUBlendComponent,若满足以下要求:

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

    否则,如 formatfloat 格式:

    1. bias(float)state.depthBias * 2^(exp(primitive 最大深度) - r) + state.depthBiasSlopeScale * maxDepthSlope

  5. state.depthBiasClamp > 0

    1. bias 设为 min(state.depthBiasClamp, bias)

    否则,如 state.depthBiasClamp < 0

    1. bias 设为 max(state.depthBiasClamp, bias)

  6. state.depthBias0state.depthBiasSlopeScale0

    1. 将片元深度值设为 片元深度值 + bias

校验 GPUDepthStencilState(device, 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(device, descriptor)

参数:

设备时间线步骤:

  1. 仅当以下所有条件都满足时,返回 true

校验 GPUVertexState(device, descriptor, layout)

参数:

设备时间线步骤:

  1. entryPoint = 获取入口点(VERTEX, descriptor)。

  2. 断言 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. totalEffectiveVertexAttributes 为 所有 descriptor.buffers 中每个 vertexBufferattributes.size 的总和。

    5. 如果 device.[[features]]包含 "core-features-and-limits"
      1. 如果 vertex_index 内建变量是 descriptor.vertex着色器阶段输入

        • totalEffectiveVertexAttributes 加 1

      2. 如果 instance_index 内建变量是 descriptor.vertex着色器阶段输入

        • totalEffectiveVertexAttributes 加 1

    6. totalEffectiveVertexAttributes 必须device.[[device]].[[limits]].maxVertexAttributes

    7. 对于每一个被 entryPoint 静态使用 的顶点属性声明(位置为 location,类型为 T), 必须有且仅有一组 (i, j) 满足 descriptor.buffers[i] ?.attributes[j].shaderLocation == location

      attrib 为该 GPUVertexAttribute

    8. T 必须attrib.format顶点数据类型兼容:

      "unorm", "snorm", or "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 复制 操作 作用于纹理/"图像" 数据,而不是字节。

WebGPU 提供“缓冲” GPUCommandEncoder 命令:

以及“即时” GPUQueue 操作:

在 texel 复制中,写入目标 texel 块的字节将具有一个 等价的 texel 表示 与源值相同。

Texel 复制仅保证源中的有效、有限、非次正规(non-subnormal)数值在目标中具有相同的数值。 具体来说,texel 块可以以只保留这些值的方式被解码并重新编码。 在可能有多种字节表示的情况下,表示的选择由实现定义。

注: 对于支持 RENDER_ATTACHMENTSTORAGE_BINDING, 的格式,这可以被视为类似于,并可能通过使用 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时会用到。

在字节数组与纹理之间拷贝时,总是以整个 元数据块为操作单位,不能只更新 元数据块的一部分。

元数据块元数据块行 里的线性内存布局中紧密排列,每个 元数据块 紧随前一个 元数据块,没有填充。这包括 拷贝到/从 深度或模板格式纹理的特定 aspect:模板值以字节数组紧密排列,深度值以合适的数据类型("depth16unorm" 或 "depth32float")的数组紧密排列。

offset类型为 GPUSize64,默认值为 0

以字节为单位,表示对元数据源(比如 GPUTexelCopyBufferInfo.buffer) 的偏移量,即确定元数据在该源中的起始位置。

bytesPerRow类型为 GPUSize32

每个 元数据块行 的起始位置到下一个 元数据块行 起始位置之间的字节跨度(步长)。

若有多行 元数据块行(即拷贝高度或深度多于一个 block),则必须指定。

rowsPerImage类型为 GPUSize32

每个 纹理元数据块图像 所包含的 元数据块行 数量。rowsPerImage × bytesPerRow 表示每个数据 元数据块图像 到下一个 元数据块图像 的字节跨度。

若有多个 元数据块图像(即拷贝深度多于一个),则必须指定。

11.2.2. GPUTexelCopyBufferInfo

"GPUTexelCopyBufferInfo" 描述了作为“缓冲区”源或目标的 GPUBufferGPUTexelCopyBufferLayout 的“参数信息”,用于“纹素复制”操作。 它与 copySize 一起描述了 GPUBuffer 中某一区域纹素的内存布局。

dictionary GPUTexelCopyBufferInfo
         : GPUTexelCopyBufferLayout {
    required GPUBuffer buffer;
};
buffer类型为 GPUBuffer

根据所调用的方法,该缓冲区要么包含要被复制的纹素数据,要么用于存储被复制的纹素数据。

校验 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 用于 index 深度切片或数组层 的 GPUTexelCopyTextureInfo copyTexture,通过运行下列步骤确定:
  1. texturecopyTexture.texture

  2. 如果 texture.dimension 为:

    1d
    1. 断言 index0

    2. depthSliceOrLayertexture

    2d

    depthSliceOrLayertexture 的数组层 index

    3d

    depthSliceOrLayertexture 的深度切片 index

  3. textureMipdepthSliceOrLayercopyTexture.mipLevel

  4. 返回 textureMipcopyTexture.aspect

texel block byte offset 对应于 GPUTexelCopyBufferLayout bufferLayout 所描述的数据,对于 GPUTexture texture 的深度切片或数组层 z 上的 texel blockx, y,通过运行以下步骤确定:
  1. blockBytestexture.formattexel block copy footprint

  2. imageOffset 为 (z × bufferLayout.rowsPerImage × bufferLayout.bytesPerRow) + bufferLayout.offset

  3. rowOffset 为 (y × bufferLayout.bytesPerRow) + imageOffset

  4. blockOffset 为 (x × blockBytes) + rowOffset

  5. 返回 blockOffset

校验 GPUTexelCopyTextureInfo(texelCopyTextureInfo, copySize)

参数:

返回值: boolean

设备时间线 步骤:

  1. blockWidthtexelCopyTextureInfo.texture.formattexel block width

  2. blockHeighttexelCopyTextureInfo.texture.formattexel block height

  3. 当且仅当下列所有条件均适用时返回 true

校验 texture buffer copy(texelCopyTextureInfo, bufferLayout, dataLength, copySize, textureUsage, aligned)

参数:

返回值: boolean

设备时间线 步骤:

  1. texturetexelCopyTextureInfo.texture

  2. aspectSpecificFormat = texture.format

  3. offsetAlignment = texel block copy footprint 对应于 texture.format 的值。

  4. 当且仅当下列所有条件均适用时返回 true

    1. validating GPUTexelCopyTextureInfo(texelCopyTextureInfo, copySize) 返回 true

    2. texture.sampleCount 必须为 1。

    3. texture.usage 包含 textureUsage

    4. 如果 texture.formatdepth-or-stencil format

      1. texelCopyTextureInfo.aspect 必须引用 texture.format 的单个 aspect。

      2. 如果 textureUsage 为:

        COPY_SRC

        该 aspect 必须依据 § 26.1.2 Depth-stencil formats 为有效的 texel copy 源。

        COPY_DST

        该 aspect 必须依据 § 26.1.2 Depth-stencil formats 为有效的 texel copy 目标。

      3. aspectSpecificFormat 设为依据 § 26.1.2 Depth-stencil formatsaspect-specific format

      4. offsetAlignment 设为 4。

    5. 如果 alignedtrue

      1. bufferLayout.offset 必须是 offsetAlignment 的倍数。

    6. validating linear texture data(bufferLayout, dataLength, aspectSpecificFormat, copySize) 成功。

11.2.4. GPUCopyExternalImageDestInfo

WebGPU 纹理保存的是原始数值数据,并未带有描述颜色的语义元数据。 然而,copyExternalImageToTexture() 是从带有颜色描述的信息源进行拷贝的。

GPUCopyExternalImageDestInfo” 描述了“destination”操作的“info”信息,即 “copyExternalImageToTexture()” 操作的目标相关信息。 它是一个 GPUTexelCopyTextureInfo, 并额外标记了色彩空间/编码和 alpha 预乘的元数据,以便在拷贝时保留语义化的颜色数据。 这些元数据只影响拷贝操作的语义,不影响目标纹理对象的状态或语义。

dictionary GPUCopyExternalImageDestInfo
         : GPUTexelCopyTextureInfo {
    PredefinedColorSpace colorSpace = "srgb";
    boolean premultipliedAlpha = false;
};
colorSpace类型为 PredefinedColorSpace,默认值为 "srgb"

描述用于将数据编码进目标纹理时所用的色彩空间和编码方式。

可能导致写入目标纹理的值超出 [0, 1] 范围(如果其格式支持),否则结果将会被限制在目标纹理格式的范围内。

注意: 如果 colorSpace 与源图像一致,可能无需进行转换。参见§ 3.11.2 色彩空间转换省略

premultipliedAlpha类型为 boolean,默认值为 false

描述写入纹理的数据是否应将其 RGB 通道按 alpha 通道进行预乘。

如果此选项为 truesource 也是预乘的,则即使源 RGB 值超过对应的 alpha 值,也必须保留源 RGB 值。

注意: 如果 premultipliedAlpha 与源图像一致,可能无需进行转换。参见§ 3.11.2 色彩空间转换省略

11.2.5. GPUCopyExternalImageSourceInfo

GPUCopyExternalImageSourceInfo” 描述了“source”操作的“info”信息,即 “copyExternalImageToTexture()”操作的源相关信息。

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

要拷贝的纹理范围(extent)。

Device timeline 步骤:

  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

纹理拷贝的尺寸。

Device timeline 步骤:

  1. blockWidthtexelCopyTextureInfo.texture.format纹素块宽度

  2. blockHeighttexelCopyTextureInfo.texture.format纹素块高度

  3. subresourceSizetexelCopyTextureInfo物理子资源大小

  4. 返回下列条件是否全部满足:

    注意: 纹理拷贝范围是相对于压缩格式的 物理(向上取整)大小来校验的,允许拷贝访问并不完全位于纹理内部的纹素块。

Two GPUTextureFormats format1 and format2 are copy-compatible if:
The 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

当前被任何正在执行的渲染通道指令使用的状态。

[[used_bind_groups]], 类型为 set<GPUBindGroup>, 只读

一个 集合,包含此命令缓冲区使用的所有 GPUBindGroup

12.1.1. 命令缓冲区创建(Command Buffer Creation)

dictionary GPUCommandBufferDescriptor
 : GPUObjectDescriptorBase {
};

13. 命令编码(Command Encoding)

13.1. GPUCommandsMixin

GPUCommandsMixin 定义了所有编码命令接口的通用状态。它没有方法。

interface mixin GPUCommandsMixin {
};

GPUCommandsMixin 具有以下设备时间轴属性

[[state]],类型为 编码器状态,初始值为 "open"

编码器的当前状态。

[[commands]],类型为 list<GPU 指令>,初始值为 []

一个 列表,包含在包含这些指令的 GPUCommandBuffer 被提交时,要在队列时间线上执行的 GPU 指令

[[used_bind_groups]], 类型为 set<GPUBindGroup>, 初始为空;

一个 集合,包含命令编码期间通过 setBindGroup() 设置的所有 GPUBindGroup

编码器状态(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

设备时间线 initialization steps:
  1. 验证编码器状态this 上。 如果返回 false,使 pass 失效并返回。

  2. this.[[state]] 设为 "locked"。

  3. attachmentRegions 为一个最初为空的 列表,元素为 [texture subresource, depthSlice?] 对。每一对描述要渲染到的纹理区域,其中仅对 "3d" 纹理包括单个深度切片。

  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]] 上给出的 有效使用 规则。

    • attachmentRegions 中的纹理区域集合必须两两不相交。 即,不得有两个纹理区域重叠。

  6. AddattachmentRegions 中的每个 texture subresource 添加到 pass.[[usage scope]] ,使用 attachment 作为用法。

  7. depthStencilAttachmentdescriptor.depthStencilAttachment

  8. 如果 depthStencilAttachment 不为 null

    1. depthStencilViewdepthStencilAttachment.view

    2. Adddepthsubresource(若存在) 添加到 pass.[[usage scope]] ;如果 depthStencilAttachment.depthReadOnly 为 true,则用法为 attachment-read,否则为 attachment

    3. Addstencilsubresource(若存在) 添加到 pass.[[usage scope]] ;如果 depthStencilAttachment.stencilReadOnly 为 true,则用法为 attachment-read,否则为 attachment

    4. pass.[[depthReadOnly]] 设为 depthStencilAttachment.depthReadOnly

    5. pass.[[stencilReadOnly]] 设为 depthStencilAttachment.stencilReadOnly

  9. pass.[[layout]] 设为 从 pass 推导渲染目标布局(descriptor)。

  10. 如果 descriptor.timestampWrites提供

    1. timestampWritesdescriptor.timestampWrites

    2. 如果 timestampWrites.beginningOfPassWriteIndex提供, 则向 this.[[commands]] 附加一个包含下列步骤的 GPU command

      1. 在 pass 命令开始执行之前,将 当前队列时间戳 写入 timestampWrites.beginningOfPassWriteIndex 指定的 timestampWrites.querySet 的索引位置。

    3. 如果 timestampWrites.endOfPassWriteIndex提供,则将 pass.[[endTimestampWrite]] 设为一个包含下列步骤的 GPU command

      1. 在 pass 命令执行完成之后,将 当前队列时间戳 写入 timestampWrites.endOfPassWriteIndex 指定的 timestampWrites.querySet 的索引位置。

  11. pass.[[drawCount]] 设为 0。

  12. pass.[[maxDrawCount]] 设为 descriptor.maxDrawCount

  13. pass.[[maxDrawCount]] 设为 descriptor.maxDrawCount

  14. this 上入列一个命令,该命令在执行时将在 队列时间线 上发出随后的步骤。

队列时间线 步骤:
  1. 令当前执行中的 GPUCommandBuffer[[renderState]] 为一个新的 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 的内容被载入其关联的 帧缓冲存储器

      "clear"

      colorSubregion 相关联的 帧缓冲存储器 中的每个 纹素 设置为 colorAttachment.clearValue

  5. 如果 depthStencilAttachment 不为 null

    1. 如果 depthStencilAttachment.depthLoadOp 为:

      提供

      断言 depthStencilAttachment.depthReadOnlytrue,并确保 depthStencilViewdepth 子资源 内容被载入其关联的 帧缓冲存储器

      "load"

      确保 depthStencilViewdepth 子资源 内容被载入其关联的 帧缓冲存储器

      "clear"

      depthStencilViewdepth 子资源 相关的 帧缓冲存储器 的每个 纹素 设置为 depthStencilAttachment.depthClearValue

    2. 如果 depthStencilAttachment.stencilLoadOp 为:

      提供

      断言 depthStencilAttachment.stencilReadOnlytrue,并确保 depthStencilViewstencil 子资源 内容被载入其关联的 帧缓冲存储器

      "load"

      确保 depthStencilViewstencil 子资源 内容被载入其关联的 帧缓冲存储器

      "clear"

      depthStencilViewstencil 子资源 相关的 帧缓冲存储器 的每个 纹素 设置为 depthStencilAttachment.stencilClearValue

注意: 只读深度模版附件会被隐式等同于 load 操作。 针对只读附件必须不能提供 loadOp 的校验在 GPURenderPassDepthStencilAttachment 有效使用中完成。

beginComputePass(descriptor)

开始编码由 descriptor 描述的计算通道(compute pass)。

调用于: GPUCommandEncoder this

参数:

参数 - GPUCommandEncoder.beginComputePass(descriptor) 方法。
参数名 类型 可为 null 可选 描述
descriptor GPUComputePassDescriptor

返回值: GPUComputePassEncoder

内容时间线 步骤:

  1. pass 为新的 GPUComputePassEncoder 对象。

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

  3. 返回 pass

设备时间线 初始化步骤
  1. 校验编码器状态this)。 若返回 false,则 使 pass 失效并返回。

  2. 设置 this.[[state]] 为 "locked"。

  3. 如果下列任一要求不满足,则 使 pass 失效并返回。

  4. descriptor.timestampWrites提供

    1. timestampWrites = descriptor.timestampWrites

    2. timestampWrites.beginningOfPassWriteIndex提供, 则向 this.[[commands]] 添加一个 GPU 命令,其步骤如下:

      1. 在 pass 命令开始执行前,将 当前队列时间戳 写入 timestampWrites.beginningOfPassWriteIndex 所在 timestampWrites.querySet 的索引。

    3. timestampWrites.endOfPassWriteIndex提供,则设置 pass.[[endTimestampWrite]] 为一个带如下步骤的 GPU 命令

      1. 在 pass 命令执行完毕后,将 当前队列时间戳 写入 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 source 中以字节为单位的起始偏移量。
destination GPUBuffer 要拷贝到的 GPUBuffer
destinationOffset GPUSize64 以字节为单位,destination中放置拷贝数据的位置偏移。
size GPUSize64 要拷贝的字节数。

返回值: undefined

内容时间线步骤:

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

设备时间线 步骤:
  1. 校验编码器状态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. this 入列一个命令,该命令执行时将在 队列时间线 上继续后续步骤。

队列时间线 步骤:
  1. source 中自 sourceOffset 起的 size 字节数据复制到 destination,起始于 destinationOffset

clearBuffer(buffer, offset, size)

GPUCommandEncoder 编码一条命令,用零填充 GPUBuffer 的子区域。

调用于: GPUCommandEncoder this

参数:

GPUCommandEncoder.clearBuffer(buffer, offset, size) 方法的参数。
参数名 类型 可为 null 可选 描述
buffer GPUBuffer 要清零的 GPUBuffer
offset GPUSize64 buffer 的字节偏移位置开始清零。
size GPUSize64 要清零的子区域字节大小。默认为 buffer 的大小减去 offset

返回值: undefined

内容时间线 步骤:

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

设备时间线 步骤:
  1. 校验编码器状态this)。如果返回 false,直接返回。

  2. 如果缺少 size,则设为 max(0, buffer.size - offset)

  3. 如果下列任一条件不满足,则使 this 失效并返回。

    • buffer 必须可与 this 一起使用。

    • buffer.usage 包含 COPY_DST

    • size 必须为 4 的倍数。

    • offset 必须为 4 的倍数。

    • buffer.size ≥ (offset + size)。

  4. 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 共同定义目标缓冲区的区域。
copySize GPUExtent3D

返回值: undefined

内容时间线 步骤:

  1. ? 校验 GPUOrigin3D 结构(source.origin).

  2. ? 校验 GPUExtent3D 结构(copySize).

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

设备时间线 步骤:
  1. 校验编码器状态this)。如果返回 false,直接返回。

  2. alignedtrue

  3. dataLength = destination.buffer.size

  4. 如果下列任一条件不满足,使 this 失效并返回。

  5. this 入列一个命令,该命令执行时 在 队列时间线 上执行后续步骤。

队列时间线 步骤:
  1. blockWidthsource.texture纹素块宽度

  2. blockHeightsource.texture纹素块高度

  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. 对于区间 [0, copySize.depthOrArrayLayers − 1] 上的每个 z

    1. srcSubregiontexture copy sub-region(z + srcOrigin.z) of source

    2. 对于区间 [0, blockRows − 1] 上的每个 y

      1. 对于区间 [0, blockColumns − 1] 上的每个 x

        1. blockOffsetdestination 在 (x, y, z) 位置上的 纹素块字节偏移,对于 source.texture

        2. destination.bufferblockOffset 处的数据,设置为与 纹素块 (srcBlockOriginX + x, srcBlockOriginY + y) of srcSubregion等价纹素表示

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. 校验编码器状态this)。如果返回 false,则返回。

  2. 如果下列任一条件未满足,使 this 失效并返回。

  3. 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. 对于区间 [0, copySize.depthOrArrayLayers − 1] 上的每个 z

    1. srcSubregiontexture copy sub-region(z + srcOrigin.z) of source

    2. dstSubregiontexture copy sub-region(z + dstOrigin.z) of destination

    3. 对于区间 [0, blockRows − 1] 上的每个 y

      1. 对于区间 [0, blockColumns − 1] 上的每个 x

        1. dstSubregion 的 (dstBlockOriginX + x, dstBlockOriginY + y) 的 纹素块 设置为与 srcSubregion 的 (srcBlockOriginX + x, srcBlockOriginY + y) 等价纹素表示

13.6. 查询(Queries)

resolveQuerySet(querySet, firstQuery, queryCount, destination, destinationOffset)

GPUQuerySet 的查询结果写入 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. 校验编码器状态this)。如果返回 false,直接返回。

  2. 如果下列任一条件不满足,则使 this 失效并返回。

    • querySet 必须可与 this 一起使用。

    • destination 必须可与 this 一起使用。

    • destination.usage 包含 QUERY_RESOLVE

    • firstQuery < querySet 中的查询数量。

    • (firstQuery + queryCount) ≤ querySet 中的查询数量。

    • destinationOffset 必须为 256 的倍数。

    • destinationOffset + 8 × queryCountdestination.size

  3. 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. 如以下所有要求都满足,则令 validationSucceededtrue,否则为 false

  2. this.[[state]] 设为 "ended"。

  3. 如果 validationSucceededfalse,则:

    1. 生成校验错误

    2. 返回被使失效GPUCommandBuffer

  4. commandBuffer.[[command_list]] 设为 this.[[commands]]

  5. commandBuffer.[[used_bind_groups]] 设为 this.[[used_bind_groups]]

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, of type GPUIndex32, non-nullable, required

要设置绑定组的索引。

bindGroup, of type GPUBindGroup, nullable, required

用于后续渲染或计算命令的绑定组。

dynamicOffsets, of type sequence<GPUBufferDynamicOffset>, non-nullable, defaulting to []

包含字节为单位的缓冲区偏移的数组,针对 bindGroup 中每个标记为 buffer.hasDynamicOffset 的条目, 按 GPUBindGroupLayoutEntry.binding 的顺序排列。 有关详细信息,请参见 注释

返回: undefined

内容时间线 步骤:

  1. this.[[device]]设备时间线 上发出后续步骤。

设备时间线 步骤:
  1. this 调用 验证编码器状态。如果返回 false,则返回。

  2. 如果 bindGroupnull,则令 dynamicOffsetCount 为 0,否则令其为 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. bindGroup 添加到 this.[[used_bind_groups]]

    5. 如果 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的条目,以字节为单位的缓冲区偏移量,排列顺序为GPUBindGroupLayoutEntry.binding。更多详细信息请参见说明
dynamicOffsetsDataStart GPUSize64 dynamicOffsetsData中开始缓冲区偏移数据的位置,单位为元素个数的偏移。
dynamicOffsetsDataLength GPUSize32 要从dynamicOffsetsData读取的缓冲区偏移数量。

返回: undefined

内容时间线 步骤:

  1. 如果下列任一要求未满足,则抛出一个 RangeError 并返回。

    • dynamicOffsetsDataStart 必须 ≥ 0。

    • dynamicOffsetsDataStart + dynamicOffsetsDataLength 必须 ≤ dynamicOffsetsData.length.

  2. dynamicOffsets 为一个 列表,包含从索引 dynamicOffsetsDataStart 开始的 dynamicOffsetsDataLength 个元素的 复制(来自 dynamicOffsetsData)。

  3. 调用 this.setBindGroup(index, bindGroup, dynamicOffsets)。

注:
动态偏移按 GPUBindGroupLayoutEntry.binding 的顺序应用。

这意味着如果 dynamic bindingsGPUBindGroupLayoutEntry 列表,来自 GPUBindGroupLayout 中且其 buffer?.hasDynamicOffset 被设置为 true 的条目,并按 GPUBindGroupLayoutEntry.binding 排序, 那么传递给 setBindGroup()dynamic offset[i] 将对应于 dynamic bindings[i]

对于使用以下调用创建的 GPUBindGroupLayout
// Note the bindings are listed out-of-order in this array, but it
// doesn't matter because they will be sorted by binding index.
let layout = gpuDevice.createBindGroupLayout({
    entries: [{
        binding: 1,
        buffer: {},
    }, {
        binding: 2,
        buffer: { dynamicOffset: true },
    }, {
        binding: 0,
        buffer: { dynamicOffset: true },
    }]
});

由以下调用创建并使用的 GPUBindGroup

// Like above, the array order doesn't matter here.
// It doesn't even need to match the order used in the 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]);

将应用以下缓冲区偏移:

绑定 缓冲区 偏移量
0 bufferC 1024(动态)
1 bufferA 256(静态)
2 bufferB 2560(静态 + 动态)
要在给定的 GPUBindGroup bindGroup 中对每个动态绑定偏移执行给定的 steps,请运行以下 设备时间线 步骤:
  1. dynamicOffsetIndex0

  2. layoutbindGroup.[[layout]]

  3. 对于 bindGroup.[[entries]] 中按 entry.binding 增加顺序排列的每个 GPUBindGroupEntry entry

    1. bindingDescriptorlayout.[[entryMap]][entry.binding] 的 GPUBindGroupLayoutEntry

    2. 如果 bindingDescriptor.buffer?.hasDynamicOffsettrue

      1. bufferBindingget as buffer binding(entry.resource)。

      2. bufferLayoutbindingDescriptor.buffer

      3. bufferBindingbufferLayoutdynamicOffsetIndex 调用 steps

      4. dynamicOffsetIndexdynamicOffsetIndex + 1

验证编码器绑定组(encoder, pipeline)

参数:

GPUBindingCommandsMixin encoder

其绑定组将被验证的编码器。

GPUPipelineBase pipeline

要验证 encoder 的绑定组是否与之兼容的管线。

设备时间线 步骤:

  1. 如果下列任一条件不满足,则返回 false

否则返回 true

编码器绑定组是否别名到可写资源(encoder, pipeline) 如果任何可写缓冲绑定范围与同一缓冲区的任何其他绑定范围重叠,或任何可写纹理绑定在 纹理子资源 中与任何其他纹理绑定重叠(可能使用相同或不同的 GPUTextureView 对象),则返回 true。

注: 此算法限制了 使用范围存储例外(usage scope storage exception) 的使用。

参数:

GPUBindingCommandsMixin encoder

其绑定组将被验证的编码器。

GPUPipelineBase pipeline

要验证 encoder 的绑定组是否与之兼容的管线。

设备时间线 步骤:

  1. 对于 [VERTEX, FRAGMENT, COMPUTE] 中的每个 stage

    1. bufferBindings 为一个 列表,其元素为 (GPUBufferBinding, boolean) 对,后者指示该资源是否被作为可写使用。

    2. textureViews 为一个 列表,其元素为 (GPUTextureView, boolean) 对,后者指示该资源是否被作为可写使用。

    3. 对于 pipeline.[[layout]].[[bindGroupLayouts]] 中的每一对 (GPUIndex32 bindGroupIndex, GPUBindGroupLayout bindGroupLayout):

      1. bindGroupencoder.[[bind_groups]][bindGroupIndex]。

      2. bindGroupLayoutEntriesbindGroupLayout.[[descriptor]].entries

      3. bufferRanges 为在给定动态偏移下 bindGroup绑定缓冲区范围, 其中动态偏移为 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 bindGroupLayoutEntry,以及在 bindGroup 中相应的 GPUTextureView resource,其中 bindGroupLayoutEntry.visibility 包含 stage

        1. 如果 bindGroupLayoutEntry.storageTexture 未被 提供,则 继续

        2. resourceWritablebindGroupLayoutEntry.storageTexture.access 是否为可写访问模式。

        3. 对于 textureViews 中的每一对 (GPUTextureView pastResource, boolean pastResourceWritable):

          1. 如果 (resourceWritablepastResourceWritable) 为 true,且 pastResourceresource 存在 纹理视图别名(texture-view-aliasing), 则返回 true

        4. (resource, resourceWritable) 追加到 textureViews

  2. 返回 false

注: 强烈建议实现方对该算法进行优化。

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)

开始一个带标签的调试组,包含随后的命令。

调用对象: GPUDebugCommandsMixin this.

参数:

方法 GPUDebugCommandsMixin.pushDebugGroup(groupLabel) 的参数。
参数 类型 可为空 可选 描述
groupLabel USVString 命令组的标签。

返回: undefined

内容时间线 步骤:

  1. this.[[device]]设备时间线 上发出后续步骤。

设备时间线 步骤:
  1. 验证 this 的编码器状态。如果返回 false,则返回。

  2. groupLabel 推入 this.[[debug_group_stack]]

popDebugGroup()

结束最近由 pushDebugGroup() 启动的带标签调试组。

调用对象: GPUDebugCommandsMixin this.

返回: undefined

内容时间线 步骤:

  1. this.[[device]]设备时间线 上发出后续步骤。

设备时间线 步骤:
  1. 验证 this 的编码器状态。如果返回 false,则返回。

  2. 如果下列任一要求未满足,则对 this 执行 使其失效 并返回。

  3. this.[[debug_group_stack]] 弹出一项。

insertDebugMarker(markerLabel)

用标签标记命令流中的一个点。

调用对象: GPUDebugCommandsMixin this.

参数:

方法 GPUDebugCommandsMixin.insertDebugMarker(markerLabel) 的参数。
参数 类型 可为空 可选 描述
markerLabel USVString 要插入的标签。

返回: undefined

内容时间线 步骤:

  1. this.[[device]]设备时间线 上发出后续步骤。

设备时间线 步骤:
  1. 验证 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) 方法的参数。
参数 类型 可为空 可选 描述
pipeline GPUComputePipeline 用于后续 dispatch 命令的计算管线。

返回: undefined

内容时间线 步骤:

  1. this.[[device]]设备时间线 上发出后续步骤。

设备时间线 步骤:
  1. 验证编码器状态this)。如果返回 false,则直接返回。

  2. 如果下列任一条件未满足,则 使 this 失效 并返回。

    • pipeline 必须 可以与 this 搭配使用。

  3. this.[[pipeline]] 设为 pipeline

dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ)

使用当前的 GPUComputePipeline 派发要执行的工作。详细规范参见§ 23.1 计算

调用对象: GPUComputePassEncoder this.

参数:

GPUComputePassEncoder.dispatchWorkgroups(workgroupCountX, workgroupCountY, workgroupCountZ) 方法的参数。
参数 类型 可为空 可选 描述
workgroupCountX GPUSize32 要分派工作组的 X 维度数量。
workgroupCountY GPUSize32 要分派工作组的 Y 维度数量。
workgroupCountZ GPUSize32 要分派工作组的 Z 维度数量。
注:
传递给 xyz 的值, 在 dispatchWorkgroups()dispatchWorkgroupsIndirect() 方法中是各个维度上分派 工作组(workgroups) 的数量,不是每个维度上执行的着色器调用(invocations)数量。这与现代 GPU 原生 API 行为一致,但不同于 OpenCL 行为。

这意味着如果 GPUShaderModule 声明入口为 @workgroup_size(4, 4), 并以 computePass.dispatchWorkgroups(8, 8); 派发,则总共会调用 1024 次入口点:分派 4x4 的工作组,在 X 与 Y 轴各 8 组。(即 4*4*8*8=1024

返回: undefined

内容时间线 步骤:

  1. this.[[device]]设备时间线 上发出后续步骤。

设备时间线 步骤:
  1. 验证编码器状态this)。如果返回 false,则直接返回。

  2. usageScope 为一个空的 使用范围(usage scope)

  3. 对于 this.[[bind_groups]] 中的每个 bindGroup合并 bindGroup.[[usedResources]]this.[[usage scope]]

  4. 如果下列任一条件不满足,则 使 this 失效 并返回。

  5. bindingStatethis 当前状态的快照。

  6. this 上入队命令,以便在 队列时间线 上执行后续步骤。

队列时间线 步骤:
  1. 以 [workgroupCountX, workgroupCountY, workgroupCountZ] 维度, 并使用 bindingState.[[pipeline]]bindingState.[[bind_groups]] 执行一组工作组。

dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset)

使用当前 GPUComputePipeline, 并从 GPUBuffer 读取参数,分派要执行的工作。详细规范参见§ 23.1 计算

缓冲区中编码的 indirect dispatch parameters(间接分派参数) 必须是紧密排列的三个 32 位无符号整数值(共 12 字节), 顺序与 dispatchWorkgroups() 参数一致。例如:

let dispatchIndirectParameters = new Uint32Array(3);
dispatchIndirectParameters[0] = workgroupCountX;
dispatchIndirectParameters[1] = workgroupCountY;
dispatchIndirectParameters[2] = workgroupCountZ;
调用对象: GPUComputePassEncoder this.

参数:

GPUComputePassEncoder.dispatchWorkgroupsIndirect(indirectBuffer, indirectOffset) 方法的参数。
参数 类型 可为空 可选 描述
indirectBuffer GPUBuffer 包含indirect dispatch parameters 的缓冲区。
indirectOffset GPUSize64 指示 indirectBuffer 中分派数据起始的字节偏移。

返回: undefined

内容时间线 步骤:

  1. this.[[device]]设备时间线 上发出后续步骤。

设备时间线 步骤:
  1. 验证编码器状态this)。如果返回 false,则直接返回。

  2. usageScope 为一个空的 使用范围(usage scope)

  3. 对于 this.[[bind_groups]] 中的每个 bindGroup合并 bindGroup.[[usedResources]]this.[[usage scope]]

  4. indirectBuffer 以用途 input 添加到 usageScope

  5. 如果下列任一条件不满足,则 使 this 失效 并返回。

  6. bindingStatethis 当前状态的快照。

  7. this 上入队命令,以便在 队列时间线 上执行后续步骤。

队列时间线 步骤:
  1. indirectBufferindirectOffset 字节处读取一个无符号 32 位整数,作为 workgroupCountX

  2. indirectBufferindirectOffset + 4 字节处读取一个无符号 32 位整数,作为 workgroupCountY

  3. indirectBufferindirectOffset + 8 字节处读取一个无符号 32 位整数,作为 workgroupCountZ

  4. 如果 workgroupCountXworkgroupCountYworkgroupCountZ 大于 this.device.limits.maxComputeWorkgroupsPerDimension,则返回。

  5. 以 [workgroupCountX, workgroupCountY, workgroupCountZ] 维度, 并使用 bindingState.[[pipeline]]bindingState.[[bind_groups]] 执行一组工作组。

16.1.3. 结束(Finalization)

计算通道编码器可以通过调用 end() 结束,表示用户已完成本通道的命令录制。一旦调用 end(),该计算通道编码器不可再使用。

end()

完成计算过程命令序列的录制。

调用对象: GPUComputePassEncoder this.

返回: undefined

内容时间线 步骤:

  1. this.[[device]]设备时间线 上发出后续步骤。

设备时间线 步骤:
  1. parentEncoderthis.[[command_encoder]]

  2. 如果下列任一要求未满足, 生成验证错误 并返回。

  3. this.[[state]] 设为 "ended"。

  4. parentEncoder.[[state]] 设为 "open"。

  5. 扩展 parentEncoder.[[used_bind_groups]] 并加入 this.[[used_bind_groups]]

  6. 如果下列任一要求未满足,使 parentEncoder 失效 并返回。

  7. 扩展 parentEncoder.[[commands]] 并加入 this.[[commands]]

  8. 如果 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 的颜色附件每采样字节数(device, this.colorAttachments) 成功。

  6. 所有 view 都在 this.colorAttachments 的非 null 成员中,以及 this.depthStencilAttachment.view (如有)必须具有相同的 sampleCount

  7. 对于 this.colorAttachments 的非 null 成员中的每个 view 以及 this.depthStencilAttachment.view (如有),其 [[renderExtent]] 必须一致。

  8. 如果 this.occlusionQuerySet提供

    1. this.occlusionQuerySet 必须 可与 device 搭配使用。

    2. this.occlusionQuerySet.type 必须为 occlusion

  9. 如果 this.timestampWrites提供

验证 GPURenderPassDescriptor 的颜色附件每采样字节数(device, colorAttachments)

参数:

设备时间线 步骤:

  1. formats 为一个空的 列表<GPUTextureFormat?>

  2. 对于 colorAttachments 中的每个 colorAttachment

    1. 如果 colorAttachmentundefined,则继续。

    2. colorAttachment.view.[[descriptor]].format 添加到 formats

  3. 计算颜色附件每采样字节数(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 或 GPUTextureView)

描述该颜色附件将被输出到的纹理子资源(subresource)子资源 由调用 get as texture view(view) 确定。

depthSlice, 类型为 GPUIntegerCoordinate

指示该颜色附件输出到 "3d" view 的深度切片索引。

resolveTarget, 类型为 (GPUTexture 或 GPUTextureView)

描述该颜色附件为多重采样时,最终输出将被解析到的纹理子资源view 如果是多采样,解析目标就会生效。 子资源 由调用 get as texture view(resolveTarget) 确定。

clearValue, 类型为 GPUColor

表示在执行渲染通道前,将 view 清除为的值。如果未提供,默认为 {r: 0, g: 0, b: 0, a: 0}。当 loadOp 不是 "clear" 时被忽略。

clearValue 的所有分量都是 double 类型。 这些分量会转换为与渲染附件匹配的纹理格式的像素值。 如果转换失败,则会生成校验错误(validation error)。

loadOp, 类型为 GPULoadOp

指出在执行渲染通道前,对 view 执行的加载操作。

注: 建议优先使用清除,细节参见 "clear" 说明。

storeOp, 类型为 GPUStoreOp

在执行渲染通道后,对 view 执行的存储操作。

GPURenderPassColorAttachment 合法用法

给定 GPURenderPassColorAttachment this

  1. renderViewDescriptorthis.view.[[descriptor]]

  2. renderTexturethis.view.[[texture]]

  3. 以下所有步骤中的要求 均需 满足。

    1. renderViewDescriptor.format 必须颜色可渲染格式

    2. this.view 必须可渲染纹理视图

    3. 如果 renderViewDescriptor.dimension"3d"

      1. this.depthSlice 必须被提供,并且 必须 小于 逻辑指定 mip 级别的纹理范围 depthOrArrayLayers。 该 逻辑 mip 级别指定的纹理范围 针对 renderTexture子资源,在 mipmap 级别 renderViewDescriptor.baseMipLevel

      否则:

      1. this.depthSlice 不可提供

    4. 如果 this.loadOp"clear"

      1. 将 IDL 值 this.clearValue 转换为像素值renderViewDescriptor.format不得 抛出 TypeError

        注: 如果值超出该格式范围,但在对应 WGSL 基本类型(f32i32u32)范围内,则不会抛出错误。

    5. 如果 this.resolveTarget提供

      1. resolveViewDescriptorthis.resolveTarget.[[descriptor]]

      2. resolveTexturethis.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可渲染纹理视图 当且仅当,以下 设备时间线 步骤均满足时成立:
  1. descriptorview.[[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]] 的所有方面

  7. descriptor.swizzle 必须为 "rgba"

计算颜色附件每采样字节数(formats)

参数:

返回: GPUSize32

  1. total 为 0。

  2. 对于 formats 中每个非 null 的 format

    1. 断言format 是一种颜色可渲染格式

    2. renderTargetPixelByteCost渲染目标像素字节成本format)。

    3. renderTargetComponentAlignment渲染目标分量对齐format)。

    4. total 向上舍入为大于等于 total 的最小 renderTargetComponentAlignment 的倍数。

    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.sampleCount 设为 colorAttachment.view.[[texture]].sampleCount

      2. colorAttachment.view.[[descriptor]].format 添加到 layout.colorFormats

      否则:

      1. null 添加到 layout.colorFormats

  3. depthStencilAttachmentdescriptor.depthStencilAttachment

  4. 如果 depthStencilAttachment 不为 null

    1. viewdepthStencilAttachment.view

    2. layout.sampleCount 设为 view.[[texture]].sampleCount

    3. layout.depthStencilFormat 设为 view.[[descriptor]].format

  5. 返回 layout

从管线推导渲染目标布局

参数:

返回: GPURenderPassLayout

设备时间线 步骤:

  1. layout 为一个新的 GPURenderPassLayout 对象。

  2. layout.sampleCount 设为 descriptor.multisample.count

  3. 如果 descriptor.depthStencil提供

    1. layout.depthStencilFormat 设为 descriptor.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. parentEncoderthis.[[command_encoder]]

  2. 如果下列任一要求未满足,生成验证错误 并返回。

  3. this.[[state]] 设置为 "ended"。

  4. parentEncoder.[[state]] 设置为 "open"。

  5. 扩展 parentEncoder.[[used_bind_groups]] 并加入 this.[[used_bind_groups]]

  6. 如果下列任一要求未满足,使 parentEncoder 失效 并返回。

  7. 扩展 parentEncoder.[[commands]] 并加入 this.[[commands]]

  8. 如果 this.[[endTimestampWrite]] 不为 null

    1. 扩展 parentEncoder.[[commands]] 并加入 this.[[endTimestampWrite]]

  9. this 上入队渲染命令, 执行时在 队列时间线 上使用 renderState 执行后续步骤。

队列时间线 步骤:
  1. 对于 renderState.[[colorAttachments]] 中每个非 nullcolorAttachment

    1. colorViewcolorAttachment.view

    2. 如果 colorView.[[descriptor]].dimension 为:

      "3d"

      colorSubregioncolorAttachment.depthSlice (位于 colorView)。

      否则

      colorSubregioncolorView

    3. 如果 colorAttachment.resolveTarget 不为 null

      1. colorSubregion 的每个 texel 多重采样样本解析为单个样本,并复制到 colorAttachment.resolveTarget

    4. 如果 colorAttachment.storeOp 为:

      "store"

      确保与 colorSubregion 关联的 帧缓冲区内存 的内容被存储到 colorSubregion 中。

      "discard"

      colorSubregion 的每个 texel 置为零。

  2. depthStencilAttachmentrenderState.[[depthStencilAttachment]]

  3. 如果 depthStencilAttachment 不为 null

    1. 如果 depthStencilAttachment.depthStoreOp 为:

      提供

      断言 depthStencilAttachment.depthReadOnlytrue,并保持 depthStencilView 对应 深度 子资源 不变。

      "store"

      确保与 深度 子资源 相关的 帧缓冲内存 内容存储到 depthStencilView 中。

      "discard"

      depthStencilView深度 子资源 的所有 像素块 置为零。

    2. 如果 depthStencilAttachment.stencilStoreOp 为:

      提供

      断言 depthStencilAttachment.stencilReadOnlytrue,并保持 depthStencilView 对应 模板 子资源 不变。

      "store"

      确保与 模板 子资源 相关的 帧缓冲内存 内容存储到 depthStencilView 中。

      "discard"

      depthStencilView模板 子资源 的所有 像素块 置为零。

  4. renderStatenull

注: 被丢弃(discard)的附件表现好像被清零,但实现层并不要求在渲染通道结束时实际执行 clear 操作。详见 "discard" 的注释。

注: 只读深度模板附件可视为隐式采用 "store" 操作,但因为内容在渲染通道期间未变化,实际无需写回。校验要求只读附件不得显示设置 store op,见 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,初始为空

该渲染通道或 bundle 的使用范围(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]],类型为 有序映射(ordered map)<slot, GPUBuffer>, 初始为空

各 slot 当前用于读取顶点数据的 GPUBuffer

[[vertex_buffer_sizes]], 类型为 有序映射(ordered map)<slot, GPUSize64>, 初始为空

每个 slot 当前设置的 GPUBuffer 区段的字节数。

[[drawCount]],类型为 GPUSize64

该编码器记录的绘制指令数。

要在 GPURenderCommandsMixin encoder入队渲染命令,以 GPU Command commandRenderState renderState 为参数,执行如下 设备时间线 步骤:
  1. command 添加到 encoder.[[commands]]

  2. command 作为 GPUCommandBuffer commandBuffer 的一部分被执行时:

    1. commandBuffer.[[renderState]] 作为 renderState 执行 command 的步骤。

17.2.1. 绘制(Drawing)

setPipeline(pipeline)

设置当前的 GPURenderPipeline

调用于: GPURenderCommandsMixin this.

参数:

GPURenderCommandsMixin.setPipeline(pipeline) 方法的参数。
参数 类型 可为空 可选 描述
pipeline GPURenderPipeline 用于后续绘制命令的渲染管线。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. pipelineTargetsLayout从 pipeline 推导渲染目标布局(pipeline.[[descriptor]]).

  3. 如果下列任何条件不满足,则 使此失效 并返回。

  4. this.[[pipeline]] 设为 pipeline

setIndexBuffer(buffer, indexFormat, offset, size)

设置当前的索引缓冲区。

调用于: GPURenderCommandsMixin this.

参数:

GPURenderCommandsMixin.setIndexBuffer(buffer, indexFormat, offset, size) 方法的参数。
参数 类型 可为空 可选 描述
buffer GPUBuffer 包含要用于后续绘制命令的索引数据的缓冲区。
indexFormat GPUIndexFormat 缓冲区中索引数据的格式。
offset GPUSize64 索引数据在 buffer 中开始处的字节偏移量。默认为 0
size GPUSize64 缓冲区中索引数据的字节大小。默认为缓冲区大小减去偏移量。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 如果 size 缺失,则将 size 设为 max(0, buffer.size - offset)。

  3. 如果下列任何条件不满足,则 使此失效 并返回。

    • buffer可与 this 一起使用。

    • buffer.usage 包含 INDEX

    • offset 必须是 indexFormat 的字节大小的倍数。

    • offset + sizebuffer.size

  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)

为指定的插槽设置当前顶点缓冲区。

调用于: GPURenderCommandsMixin this.

参数:

GPURenderCommandsMixin.setVertexBuffer(slot, buffer, offset, size) 方法的参数。
参数 类型 可为空 可选 描述
slot GPUIndex32 要为其设置顶点缓冲区的顶点缓冲区插槽。
buffer GPUBuffer? 包含要用于后续绘制命令的顶点数据的缓冲区。
offset GPUSize64 顶点数据在 buffer 中开始处的字节偏移量。默认为 0
size GPUSize64 缓冲区中顶点数据的字节大小。默认为缓冲区大小减去偏移量。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. bufferSize 为:如果 buffernull 则为 0,否则为 buffer.size

  3. 如果 size 缺失,则将 size 设为 max(0, bufferSize - offset)。

  4. 如果下列任何要求不满足,则 使此失效 并返回。

  5. 如果 buffernull

    1. 移除 this.[[vertex_buffers]][slot]。

    2. 移除 this.[[vertex_buffer_sizes]][slot]。

    否则:

    1. 如果下列任何要求不满足,则 使此失效 并返回。

    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 Rendering

调用于: GPURenderCommandsMixin this.

参数:

GPURenderCommandsMixin.draw(vertexCount, instanceCount, firstVertex, firstInstance) 方法的参数。
参数 类型 可为空 可选 描述
vertexCount GPUSize32 要绘制的顶点数量。
instanceCount GPUSize32 要绘制的实例数量。
firstVertex GPUSize32 开始绘制的顶点缓冲区偏移(以顶点为单位)。
firstInstance GPUSize32 第一个要绘制的实例。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 下面各步中的所有要求 必须 满足。如果有任何不满足,则 使此失效 并返回。

    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. lastStride 为在 attributes 中每个 attribute 的 (attribute.offset + byteSize(attribute.format)) 的最大值;如果 attributes 为空,则为 0。

      6. strideCount 根据 buffers[slot].stepMode 计算:

        "vertex"

        firstVertex + vertexCount

        "instance"

        firstInstance + instanceCount

      7. 如果 strideCount0

        1. (strideCount1) × stride + lastStride 必须bufferSize

  3. this.[[drawCount]] 增加 1。

  4. bindingStatethis 的当前状态的快照。

  5. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. 使用来自 bindingStaterenderState 的状态,绘制从顶点 firstVertex 开始、包含 vertexCount 个顶点的图元,每次绘制 instanceCount 个实例,从实例 firstInstance 开始。

drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance)

绘制索引图元。 详细规范见 § 23.2 Rendering

调用于: GPURenderCommandsMixin this.

参数:

GPURenderCommandsMixin.drawIndexed(indexCount, instanceCount, firstIndex, baseVertex, firstInstance) 方法的参数。
参数 类型 可为空 可选 描述
indexCount GPUSize32 要绘制的索引数量。
instanceCount GPUSize32 要绘制的实例数量。
firstIndex GPUSize32 从索引缓冲区开始绘制的索引偏移(以索引为单位)。
baseVertex GPUSignedOffset32 在索引到顶点缓冲区索引之前加到每个索引值上的偏移。
firstInstance GPUSize32 第一个要绘制的实例。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 如果下列任何条件不满足,则 使此失效 并返回。

  3. this.[[drawCount]] 增加 1。

  4. bindingStatethis 的当前状态的快照。

  5. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. 使用来自 bindingStaterenderState 的状态,绘制从索引 firstIndex 开始、包含 indexCount 个索引的索引图元,每次绘制 instanceCount 个实例,从实例 firstInstance 开始,基于顶点 baseVertex

注意: WebGPU 应用程序不应对任何使用 GPUVertexStepMode "vertex" 的绑定顶点缓冲区使用越界的索引数据。 WebGPU 实现对这种情况的处理方式各不相同,因此允许一系列行为。 要么舍弃整个绘制调用,要么由 WGSL 的 无效内存引用 描述对越界属性的访问。

drawIndirect(indirectBuffer, indirectOffset)

使用从 GPUBuffer 中读取的参数来绘制图元。 详细规范见 § 23.2 Rendering

缓冲区中编码的 间接绘制参数 必须是一个紧密打包的块,包含四个 32 位无符号整数值(共 16 字节),其顺序与 draw() 的参数顺序相同。例如:

let drawIndirectParameters = new Uint32Array(4);
drawIndirectParameters[0] = vertexCount;
drawIndirectParameters[1] = instanceCount;
drawIndirectParameters[2] = firstVertex;
drawIndirectParameters[3] = firstInstance;

除非启用了 "indirect-first-instance" 特性,否则与 firstInstance 对应的值必须为 0。如果未启用该 特性 并且 firstInstance 非 0,则 drawIndirect() 调用将被视为无操作。

调用于: GPURenderCommandsMixin this.

参数:

GPURenderCommandsMixin.drawIndirect(indirectBuffer, indirectOffset) 方法的参数。
参数 类型 可为空 可选 描述
indirectBuffer GPUBuffer 包含 间接绘制参数 的缓冲区。
indirectOffset GPUSize64 绘制数据在 indirectBuffer 中开始处的字节偏移量。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 如果下列任何条件不满足,则 使此失效 并返回。

  3. indirectBuffer 添加到 [[usage scope]] ,用途为 input

  4. this.[[drawCount]] 增加 1。

  5. bindingStatethis 的当前状态的快照。

  6. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. vertexCount 为从 indirectBuffer 在字节位置 indirectOffset 读取的一个无符号 32 位整数。

  2. instanceCount 为从 indirectBuffer 在字节位置 (indirectOffset + 4) 读取的一个无符号 32 位整数。

  3. firstVertex 为从 indirectBuffer 在字节位置 (indirectOffset + 8) 读取的一个无符号 32 位整数。

  4. firstInstance 为从 indirectBuffer 在字节位置 (indirectOffset + 12) 读取的一个无符号 32 位整数。

  5. 使用来自 bindingStaterenderState 的状态,绘制从顶点 firstVertex 开始、包含 vertexCount 个顶点的图元,每次绘制 instanceCount 个实例,从实例 firstInstance 开始。

drawIndexedIndirect(indirectBuffer, indirectOffset)

使用从 GPUBuffer 中读取的参数来绘制索引图元。 详细规范见 § 23.2 Rendering

缓冲区中编码的 间接 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 is a signed value.
drawIndexedIndirectParametersSigned[3] = baseVertex;
drawIndexedIndirectParameters[4] = firstInstance;

除非启用了 "indirect-first-instance" 特性,否则与 firstInstance 对应的值必须为 0。如果未启用该 特性 并且 firstInstance 非 0,则 drawIndexedIndirect() 调用将被视为无操作。

调用于: GPURenderCommandsMixin this.

参数:

GPURenderCommandsMixin.drawIndexedIndirect(indirectBuffer, indirectOffset) 方法的参数。
参数 类型 可为空 可选 描述
indirectBuffer GPUBuffer 包含 间接 drawIndexed 参数 的缓冲区。
indirectOffset GPUSize64 绘制数据在 indirectBuffer 中开始处的字节偏移量。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 如果下列任何条件不满足,则 使此失效 并返回。

  3. indirectBuffer 添加到 [[usage scope]] ,用途为 input

  4. this.[[drawCount]] 增加 1。

  5. bindingStatethis 的当前状态的快照。

  6. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. indexCount 为从 indirectBuffer 在字节位置 indirectOffset 读取的一个无符号 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. 使用来自 bindingStaterenderState 的状态,绘制从索引 firstIndex 开始、包含 indexCount 个索引的索引图元,每次绘制 instanceCount 个实例,从实例 firstInstance 开始,基于顶点 baseVertex

要确定对于 GPURenderCommandsMixin 编码器 encoder 是否 可用于绘制, 请运行以下 设备时间线 步骤:
  1. 如果下列任何条件不满足,则返回 false

    否则,返回 true

要确定对于 GPURenderCommandsMixin 编码器 encoder 是否 可用于绘制索引图元, 请运行以下 设备时间线 步骤:
  1. 如果下列任何条件不满足,则返回 false

    否则,返回 true

17.2.2. 光栅化状态(Rasterization state)

GPURenderPassEncoder 拥有多种方法影响本编码器用于绘制命令的附件的光栅化过程。

setViewport(x, y, width, height, minDepth, maxDepth)

设置在光栅化阶段使用的视口,用于将归一化设备坐标线性映射到视口坐标

调用于: GPURenderPassEncoder this.

参数:

GPURenderPassEncoder.setViewport(x, y, width, height, minDepth, maxDepth) 方法的参数。
参数 类型 可为空 可选 描述
x float 视口在像素中的最小 X 值。
y float 视口在像素中的最小 Y 值。
width float 视口的宽度(像素)。
height float 视口的高度(像素)。
minDepth float 视口的最小深度值。
maxDepth float 视口的最大深度值。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. maxViewportRangethis.limits.maxTextureDimension2D × 2

  3. 如果下列任何条件不满足,则 使此失效 并返回。

    • x ≥ -maxViewportRange

    • y ≥ -maxViewportRange

    • 0widththis.limits.maxTextureDimension2D

    • 0heightthis.limits.maxTextureDimension2D

    • x + widthmaxViewportRange1

    • y + heightmaxViewportRange1

    • 0.0minDepth1.0

    • 0.0maxDepth1.0

    • minDepthmaxDepth

  4. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. xywidthheight 四者舍入到某个统一精度,精度不得小于整数舍入。

  2. renderState.[[viewport]] 设为范围 xywidthheightminDepthmaxDepth

setScissorRect(x, y, width, height)

设置在光栅化阶段使用的裁剪矩形。转换到视口坐标后,任何落在裁剪矩形外的片段将被丢弃。

调用于: GPURenderPassEncoder this.

参数:

GPURenderPassEncoder.setScissorRect(x, y, width, height) 方法的参数。
参数 类型 可为空 可选 描述
x GPUIntegerCoordinate 裁剪矩形在像素中的最小 X 值。
y GPUIntegerCoordinate 裁剪矩形在像素中的最小 Y 值。
width GPUIntegerCoordinate 裁剪矩形的宽度(像素)。
height GPUIntegerCoordinate 裁剪矩形的高度(像素)。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 如果下列任何条件不满足,则 使此失效 并返回。

  3. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. renderState.[[scissorRect]] 设为范围 xywidthheight

setBlendConstant(color)

设置用于混合操作中作为常量的颜色和 alpha 值,当使用 "constant""one-minus-constant"GPUBlendFactor 时使用。

调用于: GPURenderPassEncoder this.

参数:

GPURenderPassEncoder.setBlendConstant(color) 方法的参数。
参数 类型 可为空 可选 描述
color GPUColor 用于混合的颜色。

返回: undefined

内容时间线 步骤:

  1. ? 验证 GPUColor 形状(color).

  2. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. renderState.[[blendConstant]] 设为 color

setStencilReference(reference)

设置在模版测试中使用的 [[stencilReference]] 值, 该值用于 "replace" GPUStencilOperation 操作。

调用于: GPURenderPassEncoder this.

参数:

GPURenderPassEncoder.setStencilReference(reference) 方法的参数。
参数 类型 可为空 可选 描述
reference GPUStencilValue 新的模版参考值。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]]) 上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. renderState.[[stencilReference]] 设为 reference

17.2.3. 查询(Queries)

beginOcclusionQuery(queryIndex)
调用于: GPURenderPassEncoder this.

参数:

GPURenderPassEncoder.beginOcclusionQuery(queryIndex) 方法的参数。
参数 类型 可为空 可选 描述
queryIndex GPUSize32 查询集内的查询索引。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]])上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 如果下列任何条件不满足,则 使此失效 并返回。

  3. this.[[occlusion_query_active]] 设为 true

  4. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. renderState.[[occlusionQueryIndex]] 设为 queryIndex

endOcclusionQuery()
调用于: GPURenderPassEncoder this.

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]])上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 如果下列任何条件不满足,则 使此失效 并返回。

  3. this.[[occlusion_query_active]] 设为 false

  4. 在此上入队一个渲染命令, 该命令在执行时会在 队列时间线 上使用 renderState 发出后续步骤。

队列时间线 步骤:
  1. 如果自上一次执行 beginOcclusionQuery() 命令以来有任何片段通过了所有像素片段测试,则 passingFragments 非零;否则为零。

    注意: 如果没有发生绘制调用,passingFragments 为零。

  2. passingFragments 写入 this.[[occlusion_query_set]]renderState.[[occlusionQueryIndex]] 索引处。

17.2.4. 渲染包(Bundles)

executeBundles(bundles)

执行之前记录到指定 GPURenderBundle 中的命令,作为本渲染通道的一部分。

GPURenderBundle 被执行时,它不会继承渲染通道的 pipeline、绑定组、或顶点和索引缓冲区。GPURenderBundle 执行结束后,渲染通道的 pipeline、绑定组和顶点/索引缓冲区状态会被清空(恢复为初始的空值)。

注意: 状态被清空,而不是恢复到执行前的状态。即使执行的 GPURenderBundle 数量为零,也会清空。

调用于: GPURenderPassEncoder this.

参数:

GPURenderPassEncoder.executeBundles(bundles) 方法的参数。
参数 类型 可为空 可选 描述
bundles sequence<GPURenderBundle> 要执行的渲染包列表。

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this.[[device]])上发出后续步骤。

设备时间线 步骤:
  1. 验证此的编码器状态。如果返回 false,则返回。

  2. 如果下列任何条件不满足,则 使此失效 并返回。

  3. bundles 中的每个 bundle

    1. this.[[drawCount]] 增加 bundle.[[drawCount]]

    2. 合并 bundle.[[usage scope]]this.[[usage scope]]

    3. 扩展 this.[[used_bind_groups]] ,包含 bundle.[[used_bind_groups]]

    4. 在此上入队一个渲染命令, 该命令在 队列时间线 上以 renderState 执行以下步骤:

      队列时间线 步骤:
      1. bundle.[[command_list]] 内的每个命令,使用 renderState 执行。

        注意: 执行渲染包不会改变 renderState。绑定状态已在包编码时捕获,在执行包时不会再使用。

  4. 重置渲染通道绑定状态this)。

重置渲染通道绑定状态 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>

一个 列表,包含要提交到 GPURenderPassEncoderGPU 命令,当执行 GPURenderBundle 时被提交。

[[used_bind_groups]], 类型为 set<GPUBindGroup>, 只读

本渲染包使用的所有 GPUBindGroup集合

[[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) 方法的参数。
参数 类型 可为空 可选 描述
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) 方法的参数。
参数 类型 可为空 可选 描述
descriptor GPURenderBundleDescriptor

返回: GPURenderBundle

内容时间线 步骤:

  1. renderBundle 为一个新的 GPURenderBundle

  2. this.[[device]]设备时间线 上执行 结束步骤

  3. 返回 renderBundle

设备时间线 结束步骤
  1. 若下述所有要求均满足,令 validationSucceededtrue,否则为 false

  2. this.[[state]] 设为 "ended"。

  3. validationSucceededfalse,则:

    1. 生成校验错误

    2. 返回一个无效化GPURenderBundle

  4. renderBundle.[[command_list]] 设为 this.[[commands]]

  5. renderBundle.[[used_bind_groups]] 设为 this.[[used_bind_groups]]

  6. renderBundle.[[usage scope]] 设为 this.[[usage scope]]

  7. 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) 方法的参数。
参数 类型 可为空 可选 描述
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. 设备时间线(位于 this)上执行后续步骤。

设备时间线 步骤:
  1. alignedfalse

  2. dataLengthdataBytes长度

  3. 如果下列任一条件不满足, 生成校验错误 并返回。

    注意:GPUCommandEncoder.copyBufferToTexture() 不同,这里对 dataLayout.bytesPerRowdataLayout.offset 无对齐要求。

  4. 队列时间线(位于 this)上执行后续步骤。

队列时间线 步骤:
  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. 断言 dstBlockOriginX, dstBlockOriginY, blockColumns, blockRows 为整数。

  9. 对于每个 z 在区间 [0, copySize.depthOrArrayLayers − 1]:

    1. dstSubregion = 纹理拷贝子区域z + dstOrigin.z),针对 destination

    2. 对于每个 y 在区间 [0, blockRows − 1]:

      1. 对于每个 x 在区间 [0, blockColumns − 1]:

        1. blockOffset = 纹素块字节偏移,由 dataLayout 及 (x, y, z), destination.texture 决定。

        2. dstSubregion纹素块 (dstBlockOriginX + x, dstBlockOriginY + y) 设为与 纹素块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, 则在 队列时间线(位于 this)上执行后续步骤。

队列时间线 步骤:
  1. 断言 destination.texture纹素块宽度为 1, 纹素块高度为 1,且 copySize.depthOrArrayLayers 为 1。

  2. srcOriginsource.origin

  3. dstOrigindestination.origin

  4. dstSubregion纹理拷贝子区域 (dstOrigin.z),针对 destination

  5. 对于 y 从 0 到 copySize.height − 1:

    1. 如果 source.flipYfalse,则 srcY = y;否则 srcY = copySize.height − 1 − y

    2. 对于 x 从 0 到 copySize.width − 1:

      1. srcColorsource.source 中 (srcOrigin.x + x, srcOrigin.y + srcY) 像素位置的色彩管理颜色值

      2. dstColor 为将 srcColor 经过 destination.colorSpacedestination.premultipliedAlpha 所需的颜色编码后得到的 RGBA 数字值。

      3. 如果 texture.format-srgb 类型:

        1. dstColor 设置为对其应用 sRGB 非线性到线性转换的结果。

        注意: 这会抵消后续写入 -srgb 格式时发生的 sRGB 线性到非线性转换,使得来自 sRGB 图像的线性色值不会丢失(通常使用 -srgb 格式就是为了读取原始图像的线性色值)。

      4. dstSubregion纹素块 (dstOrigin.x + x, dstOrigin.y + y) 设为 dstColor等价纹素表示

submit(commandBuffers)

安排 GPU 在此队列上执行命令缓冲区。

已提交的命令缓冲区不可再次使用。

调用于: GPUQueue this。

参数:

GPUQueue.submit(commandBuffers) 方法的参数。
参数 类型 可为空 可选 描述
commandBuffers sequence<GPUCommandBuffer>

返回: undefined

内容时间线 步骤:

  1. 设备时间线(位于 this)上执行后续步骤:

设备时间线 步骤:
  1. 如果下列任何要求不满足,则生成校验错误使 commandBuffers 中的每个 GPUCommandBuffer 无效,并返回。

  2. 对于 commandBuffers 中的每个 commandBuffer

    1. 使 commandBuffer 无效。

  3. 队列时间线(位于 this)上执行后续步骤:

队列时间线 步骤:
  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. this设备时间线 上执行 synchronization steps

  4. 返回 promise

设备时间线 synchronization steps
  1. event所有当前已入队操作完成时发生。

  2. 监听时间线事件 eventthis.[[device]], 由后续步骤在 contentTimeline 上处理。

内容时间线 步骤:
  1. 解析 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) 方法的参数。
参数 类型 可为空 可选 描述
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. 设备时间线 上对 this 执行 初始化步骤

  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 的写入索引成员 (beginningOfPassWriteIndex, endOfPassWriteIndex):

      • 至少有一个必须被指定

      • 对于那些被指定的成员:

        • 任意两个不能相等。

        • 每一个必须小于 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),只读

此上下文创建时所对应的 canvas。

[[configuration]],类型为 GPUCanvasConfiguration? ,初始值为 null

当前上下文的配置选项。

若上下文尚未配置或已被 unconfigure,则为 null

[[textureDescriptor]],类型为 GPUTextureDescriptor? ,初始值为 null

当前配置的纹理描述符,由 [[configuration]] 和 canvas 派生。

若上下文尚未配置或已被 unconfigure,则为 null

[[drawingBuffer]],一张图像,初始为与 canvas 尺寸相同的透明黑色图像

绘制缓冲区是 canvas 的工作副本图像数据。 通过 [[currentTexture]] (通过 getCurrentTexture() 获取)可将其作为可写视图访问。

绘制缓冲区用于获取上下文图像内容副本,即当 canvas 显示或被读取时发生。 即便 [[configuration]].alphaMode"opaque",绘制缓冲区也可能是透明的。 alphaMode 仅影响 “获取上下文图像内容副本” 算法的结果。

绘制缓冲区的生命周期长于 [[currentTexture]], 即使 canvas 已经展示,缓冲区仍包含之前渲染的内容。只有在替换绘制缓冲区时才会被清空。

任何时候读取绘制缓冲区时,实现必须确保所有之前提交的工作(如队列提交)都已通过 [[currentTexture]] 完成对缓冲区的写操作。

[[currentTexture]],类型为 GPUTexture? ,初始值为 null

用于当前帧绘制的 GPUTexture。 它暴露了底层 [[drawingBuffer]] 的可写视图。 getCurrentTexture() 若为 null 则填充该属性,并返回它。

在可见 canvas 的稳定状态下,通过 currentTexture 对绘制缓冲区的任何更改会在 更新 WebGPU 画布渲染 或更早时被展示。 此时,纹理也会被销毁,并且 [[currentTexture]] 被设为 null,表示下次调用 getCurrentTexture() 时将创建一个新的纹理。

销毁 currentTexture 不影响绘制缓冲区的内容,只会提前终止对绘制缓冲区的写入权限。 在同一帧内,getCurrentTexture() 仍会返回同一个被销毁的纹理。

释放 currentTexture 会将其设为 null。 该操作会在 configure()、调整 canvas 大小、 展示、transferToImageBitmap() 等操作时调用。

[[lastPresentedImage]],类型为 (只读 image)?,初始值为 null

此 canvas 最近一次在“更新 WebGPU 画布渲染” 中展示的图像。 如果设备丢失或销毁,在“获取上下文图像内容副本”时可能会作为回退使用,以防画布变为空白。

注意: 只有实现该回退机制的实现才需要存在此属性,此机制是可选的。

GPUCanvasContext 具有以下方法:

configure(configuration)

为此 canvas 配置上下文。 这会将绘制缓冲区清为透明黑色(见替换绘制缓冲区)。

详见 getConfiguration() 了解功能检测

调用于: GPUCanvasContext this

参数:

GPUCanvasContext.configure(configuration) 方法的参数。
参数 类型 可为空 可选 描述
configuration GPUCanvasConfiguration 上下文期望的配置。

返回: undefined

内容时间线 步骤:

  1. device 等于 configuration.device

  2. ? 校验 纹理格式需特性, 其中格式为 configuration.format ,设备为 device.[[device]]

  3. ? 针对 configuration.viewFormats 中的每个元素,校验 纹理格式需特性, 设备为 device.[[device]]

  4. 如果 支持的上下文格式包含 configuration.format, 则抛出 TypeError

  5. descriptor根据 canvas 和 configuration 的 GPUTextureDescriptor(this.canvas, configuration)。

  6. 设置 this.[[configuration]]configuration

    注: 这里只暴露实现对 GPUCanvasConfiguration 的定义里的成员。关于特性检测,详见成员的规范说明。

  7. 设置 this.[[textureDescriptor]]descriptor

  8. this 执行 替换绘制缓冲区 操作。

  9. device设备时间线 上执行后续步骤。

设备时间线 步骤:
  1. 若下列要求不满足,生成校验错误 并返回。

    注意: 只要未再次调用 configure() ,此早期校验一直有效, size 校验除外(因 canvas 大小时会变化)。

unconfigure()

移除上下文配置,并销毁配置期间产生的任何纹理。

调用于: GPUCanvasContext this

返回: undefined

内容时间线 步骤:

  1. this.[[configuration]] 设为 null

  2. this.[[textureDescriptor]] 设为 null

  3. 替换 this 的绘制缓冲区

getConfiguration()

返回上下文配置,当未配置时返回 null

注意: 此方法主要用于对 GPUCanvasConfiguration 成员(及其子成员)的 功能检测;有关细节请参见各成员说明。对于支持的成员返回原始传入值。

调用于: GPUCanvasContext this

返回: GPUCanvasConfigurationnull

内容时间线 步骤:

  1. configurationthis.[[configuration]] 的副本。

  2. 返回 configuration

getCurrentTexture()

获取下一个要由 GPUCanvasContext 合成到文档的 GPUTexture

注意:
应用应当在执行 canvas 纹理渲染的同一任务内调用 getCurrentTexture()。 否则,当前纹理在渲染尚未完成时,可能会因如下步骤而被销毁。

过期任务(如下定义)为可选实现。即便实现,任务源的优先级不做规范定义,因此可能最快在下一个任务执行,最慢等到所有其他任务源都为空时执行 (见 自动过期任务源)。 只有在可见 canvas 展示时 (更新 WebGPU 画布渲染)和其它调用 “释放 currentTexture” 时能保证过期。

调用于: GPUCanvasContext this

返回: GPUTexture

内容时间线 步骤:

  1. this.[[configuration]]null, 抛出 InvalidStateError 并返回。

  2. 断言 this.[[textureDescriptor]]null

  3. devicethis.[[configuration]].device

  4. this.[[currentTexture]]null

    1. 替换 this 的绘制缓冲区

    2. this.[[currentTexture]] 设为调用 device.createTexture() ,参数为 this.[[textureDescriptor]], 但 GPUTexture 的底层存储指向 this.[[drawingBuffer]]

      注意: 如果纹理创建失败(如校验不通过或内存不足),会生成错误并返回已失效GPUTexture。 此处的校验有部分与 configure() 重复。 实现不得跳过这些重复校验。

  5. 可选排队自动过期任务,传入 device device 及如下步骤:

    1. 释放 this 的 currentTexture

      注意: 如果此前在 更新 WebGPU 画布渲染 时已经触发,则无效。

  6. 返回 this.[[currentTexture]]

注意: 在“释放 currentTexture”运行前,每次调用 getCurrentTexture() 都会返回相同的 GPUTexture 对象, 即使该纹理已被销毁,校验失败,或分配失败。

获取上下文图像内容的副本

参数:

返回: 图像内容

内容时间线 步骤:

  1. snapshot 为与 context.canvas 尺寸相同的透明黑色图像。

  2. configurationcontext.[[configuration]]

  3. 如果 configurationnull

    1. 返回 snapshot

    注意: 当上下文尚未配置或已被 unconfigured 时,configuration 会为 null。 这与 canvas 没有上下文时的行为是相同的。

  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。

      注意: 如果 [[currentTexture]] (如果有)已被销毁 (比如在 "Expire the current texture" 操作中),则 alpha 通道不可观察, 实现可以原地清除 alpha 通道。

    2. snapshot 标记为不透明。

    否则:

    1. alphaMode 标记 snapshot

  8. configurationcolorSpace 以及 toneMappingsnapshot 进行标记。

  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为何值。

注意:Canvas 配置不能使用 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, 但如果显式设置则不会自动包含。 如果你希望通过 getCurrentTexture() 返回的纹理作为渲染通道的颜色目标,请务必在自定义 usage 时包含 RENDER_ATTACHMENT

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

getCurrentTexture() 返回的纹理所创建视图可能使用的格式。

colorSpace 类型为 PredefinedColorSpace,默认值为 "srgb"

写入到 getCurrentTexture() 返回纹理的数据应以何种色彩空间显示。

toneMapping 类型为 GPUCanvasToneMapping,默认值为 {}

色调映射决定通过 getCurrentTexture() 返回纹理的内容应如何显示。

注意:
这是一个必需特性,但用户代理可能尚未实现,实际只支持默认的 GPUCanvasToneMapping。 在这种情况下,该成员在 GPUCanvasConfiguration 的实现中不应存在,以便可通过 功能检测 使用 getConfiguration() 检测。

这对本身具备 HDR 能力的实现尤为重要 (这些实现会暴露 dynamic-rangehigh)。

如果实现暴露该成员并支持 high 动态范围,则应当以 HDR 元素呈现 canvas,不应将值钳制在 HDR 显示的 SDR 区间内。

alphaMode 类型为 GPUCanvasAlphaMode,默认值为 "opaque"

决定在读取、显示或使用 getCurrentTexture() 返回的纹理作为图像源时,alpha 值将产生怎样的视觉效果。

配置一个 GPUCanvasContext 以配合特定的 GPUDevice, 并使用此上下文首选的格式:
const canvas = document.createElement('canvas');
const context = canvas.getContext('webgpu');

context.configure({
    device: gpuDevice,
    format: navigator.gpu.getPreferredCanvasFormat(),
});
canvas 和 configuration 的 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 error scope>

一个堆栈(stack) ,包含已被推送到 GPUDeviceGPU 错误作用域

当前错误作用域,针对 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. scope当前错误作用域,对应 errordevice

  2. 如果 scope 不为 undefined

    1. error 添加到 scope.[[errors]]

    2. 返回。

    否则,在内容时间线上执行以下步骤:

内容时间线 步骤:
  1. 如用户代理选择,可为 GPUDevice device 入队全局任务,带如下步骤:

    1. 触发 GPUUncapturedErrorEvent ,事件名为 "uncapturederror", 目标为 device,其 errorerror

注意: 在派发事件后,除非事件的 defaultPrevented 为 true,用户代理应当将未捕获错误暴露给开发者,例如在浏览器控制台中以警告方式提示。换句话说,调用 preventDefault() 应当消除该警告。

注意: 用户代理可能会选择节流或限制 GPUUncapturedErrorEvent 的触发频率,以防过多错误处理或日志影响性能。

pushErrorScope(filter)

将新的GPU 错误作用域 推入 this[[errorScopeStack]]

调用于: GPUDevice this

参数:

GPUDevice.pushErrorScope(filter) 方法的参数。
参数 类型 可为空 可选 描述
filter GPUErrorFilter 此错误作用域所观测的错误类型。

返回: undefined

内容时间线 步骤:

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

设备时间线 步骤:
  1. scope 为一个新的GPU 错误作用域

  2. 设置 scope.[[filter]]filter

  3. 推入 scopethis.[[errorScopeStack]]

popErrorScope()

this[[errorScopeStack]] 弹出一个GPU 错误作用域, 并返回一个 promise,该 promise 最终解析为此作用域内观测到的任意 GPUError,如果没有则为 null

promise 解析的顺序不保证。

调用于: GPUDevice this

返回: Promise<GPUError?>

内容时间线 步骤:

  1. contentTimeline 为当前内容时间线

  2. promise新的 promise

  3. this设备时间线 上执行 检查步骤

  4. 返回 promise

设备时间线 检查步骤
  1. 如果 this丢失

    1. contentTimeline 上执行如下步骤:

      内容时间线 步骤:
      1. promisenull 进行 resolve。

    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 无效), 更应倾向选择 E1 以便开发者更容易定位问题。因为两者都是 GPUValidationError, 区别只在 message 字段——该字段仅供人类阅读。

  5. 此时或稍后任意时机,在 contentTimeline 上执行后续步骤。

    注意: 由于 popErrorScope() 的解析顺序不保证, 也不规定所选错误,只需在规范要求的时间点观测状态即可。 这允许例如将着色器编译(仅依赖非状态输入)放到后台线程并同时执行其它设备时间线任务,稍后再报告错误。

内容时间线 步骤:
  1. promiseerror 进行 resolve。

使用错误作用域捕获 GPUDevice 操作中的校验错误示例:
gpuDevice.pushErrorScope('validation');

let sampler = gpuDevice.createSampler({
    maxAnisotropy: 0, // 非法,maxAnisotropy 必须至少为 1。
});

gpuDevice.popErrorScope().then((error) => {
    if (error) {
        // 创建采样器时出错,丢弃之。
        sampler = null;
        console.error(`An error occured while creating sampler: ${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

    否则:

    1. drawCall.vertexCount 个整数初始化 vertexIndexList

    2. 将每个 vertexIndexListi 设为 drawCall.firstVertex + i

  3. 返回 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插值不会受影响,其依据激发顶点, 由着色器中声明的插值采样模式决定。该输出值在整个图元中都相同,等于激发顶点的顶点输出。

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 开始)的顶点的 帧缓冲区 坐标。

    注: 本段使用“多边形”而非“三角形”一词, 因为 § 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. 确定多边形内部在帧缓冲区空间内的一组片元—— 这些位置将进行每片元操作。该过程称为“点采样”。 具体逻辑基于 descriptor.multisample 设置:

    未启用

    片元关联到像素中心。即所有坐标 C 满足 fract(C) = vector2(0.5, 0.5) 并位于多边形内部的位置均被包含。 若像素中心正好在多边形边界上,是否包含则未定义。

    注: 这会成为光栅化器精度相关的问题。

    已启用

    每个像素关联 descriptor.multisample.count 个采样位置,具体位置由实现自定义。 各像素采样位置顺序一致,且列表内容相同。每个采样位置对应于多重采样帧缓冲区内的一个片元。

    光栅化器会根据像素内命中的采样位置生成 mask,并以“sample-mask”形式作为内建输入传给片元着色器。

  6. 对于每个类型为FragmentDestination的片元:

    1. rp 为新建的 RasterizationPoint 对象

    2. 计算该片元的重心坐标 b(见 § 23.2.5.3 重心坐标)。 设置 rp.barycentricCoordinatesb

    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. targetDesctargets 中与 attachment 对应的项。

    3. 如果 targetDesc.blend提供

      1. colorBlendtargetDesc.blend.color

      2. alphaBlendtargetDesc.blend.alpha

      3. color 的 RGB 分量设置为通过执行 colorBlend.operation 描述的操作、并使用 colorBlend.srcFactorcolorBlend.dstFactor 描述的值计算得到的结果。

      4. color 的 alpha 分量设置为通过执行 alphaBlend.operation 描述的操作、并使用 alphaBlend.srcFactoralphaBlend.dstFactor 描述的值计算得到的结果。

    4. attachmentfragment.destination 处的值设置为 color

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 结构(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 结构(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

范围的深度或包含的数组层数。
如果与 GPUTextureGPUTextureDimension"3d" 时,表示纹理的深度。 如果与 GPUTextureGPUTextureDimension"2d" 时,表示纹理的数组层数。

对于给定的 GPUExtent3Dextent,根据其类型,下列语法:
验证 GPUExtent3D 结构(extent)

参数:

返回: undefined

内容时间线步骤:

  1. 在以下情况下抛出 TypeError

25. 特性索引(Feature Index)

25.1. "core-features-and-limits"

允许使用所有 Core WebGPU 特性和限制。

这始终可用,除非 featureLevel 被设置为 "compatibility", 在这种情况下它可能可用,也可能不可用(详见相关定义)。

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, 并且还允许该格式的纹理进行混合、多重采样和解析。

隐式允许 "rg11b10ufloat" 作为 copyExternalImageToTexture() 的目标格式。

此特性不会添加任何可选 API 接口

注意:此特性会被 "texture-formats-tier1" 自动启用, 而它又会被 "texture-formats-tier2" 自动启用。

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"

在创建设备时启用 "texture-formats-tier1" 将会启用 "rg11b10ufloat-renderable"。 下面内容是在此基础上的补充。

支持如下新的 GPUTextureFormat 可用于 RENDER_ATTACHMENT可混合(blendable)multisamplingSTORAGE_BINDING 能力,并支持 "read-only""write-only" GPUStorageTextureAccess

允许如下 RENDER_ATTACHMENT可混合(blendable)multisamplingresolve 能力用于如下 GPUTextureFormat

允许如下 "read-only""write-only" GPUStorageTextureAccess 用于如下 GPUTextureFormat

隐式允许以下新目标格式可用于 copyExternalImageToTexture()

注意:此特性会被 "texture-formats-tier2" 自动启用。

25.20. "texture-formats-tier2"

在创建设备时启用 "texture-formats-tier2" 将会启用 "texture-formats-tier1"。 以下内容是在此基础上的补充。

允许下列 GPUTextureFormat 使用 "read-write" GPUStorageTextureAccess

25.21. "primitive-index"

允许在 WGSL 中使用 primitive_index

该功能新增了以下 可选 API 接口

25.22. "texture-component-swizzle"

允许 GPUTextureView 在作为 TEXTURE_BINDING 使用时,重新排列或替换纹理的红/绿/蓝/alpha 通道的颜色分量。

还定义了在 § 26.1.2.1 读取和采样深度/模板纹理 时先前由实现定义的行为。

该特性增加了以下 可选 API 接口

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)相同。

格式 所需特性 GPUTextureSampleType RENDER_ATTACHMENT 可混合(blendable) 多重采样(multisampling) resolve STORAGE_BINDING 像素块拷贝开销(字节) 渲染目标单像素字节成本(字节)
"write-only" "read-only" "read-write"
每通道8位(1字节渲染目标通道对齐
r8unorm "float",
"unfilterable-float"
若已启用 "texture-formats-tier1" 若已启用 "texture-formats-tier2" 1
r8snorm "float",
"unfilterable-float"
若已启用 "texture-formats-tier1" 1
r8uint "uint" 若已启用 "core-features-and-limits" 若已启用 "texture-formats-tier1" 若已启用 "texture-formats-tier2" 1
r8sint "sint" 若已启用 "core-features-and-limits" 若已启用 "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" 若已启用 "core-features-and-limits" 若已启用 "texture-formats-tier1" 2
rg8sint "sint" 若已启用 "core-features-and-limits" 若已启用 "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 8
rgba8uint "uint" 若已启用 "core-features-and-limits" 若已启用 "texture-formats-tier2" 4
rgba8sint "sint" 若已启用 "core-features-and-limits" 若已启用 "texture-formats-tier2" 4
bgra8unorm "float",
"unfilterable-float"
若已启用 "bgra8unorm-storage" 4 8
bgra8unorm-srgb "core-features-and-limits" "float",
"unfilterable-float"
4 8
每通道16位(2字节渲染目标通道对齐
r16unorm "texture-formats-tier1" "unfilterable-float" 2
r16snorm "texture-formats-tier1" "unfilterable-float" 2
r16uint "uint" 若已启用 "core-features-and-limits" 若已启用 "texture-formats-tier1" 若已启用 "texture-formats-tier2" 2
r16sint "sint" 若已启用 "core-features-and-limits" 若已启用 "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" 若已启用 "core-features-and-limits" 若已启用 "texture-formats-tier1" 4
rg16sint "sint" 若已启用 "core-features-and-limits" 若已启用 "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" 若已启用 "core-features-and-limits" 若已启用 "texture-formats-tier2" 8
rgba16sint "sint" 若已启用 "core-features-and-limits" 若已启用 "texture-formats-tier2" 8
rgba16float "float",
"unfilterable-float"
若已启用 "core-features-and-limits" 若已启用 "texture-formats-tier2" 8
每通道32位(4字节渲染目标通道对齐
r32uint "uint" 4
r32sint "sint" 4
r32float

"float" 若已启用 "float32-filterable"

"unfilterable-float"

若已启用 "float32-blendable" 若已启用 "core-features-and-limits" 4
rg32uint "uint" 若已启用 "core-features-and-limits" 8
rg32sint "sint" 若已启用 "core-features-and-limits" 8
rg32float

"float" 若已启用 "float32-filterable"

"unfilterable-float"

若已启用 "float32-blendable" 若已启用 "core-features-and-limits" 8
rgba32uint "uint" 若已启用 "texture-formats-tier2" 16
rgba32sint "sint" 若已启用 "texture-formats-tier2" 16
rgba32float

"float" 若已启用 "float32-filterable"

"unfilterable-float"

若已启用 "float32-blendable" 若已启用 "texture-formats-tier2" 16
混合通道宽度,每像素32位(4字节渲染目标通道对齐
rgb10a2uint "uint" 若已启用 "core-features-and-limits" 若已启用 "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_* 绑定点,或绑定到其他非 depth 的 2d/cube 纹理类型。

stencil-aspect 的 GPUTextureView 必须绑定到普通纹理绑定类型。 sampleTypeGPUBindGroupLayout 中必须为 "uint"

如果已启用 "texture-component-swizzle" 特性,读取或采样纹理的 depth 或 stencil aspect 时,其行为等同于纹理内容为 (V, 0, 0, 1),其中 V 为实际的 depth 或 stencil 值。否则,内容为 (V, X, X, X),其中每个 X 是一个实现自定义的未指定值。

为减少实际中的兼容性问题,实现应当尽可能在所有场合提供 (V, 0, 0, 1),即使未启用 "texture-component-swizzle" 特性。

对 depth-aspect 绑定来说,未指定值不可通过 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年11月24日。工作草案(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 设备 API。2025年10月1日。CRD。URL:https://www.w3.org/TR/webxr/
[WGSL]
Alan Baker;Mehmet Oguz Derin;David Neto。WebGPU 着色语言。2026年1月6日。CRD。URL:https://www.w3.org/TR/WGSL/

参考性引用

[CSS-COLOR-4]
Chris Lilley;Tab Atkins Jr.;Lea Verou。CSS 色彩模块 4 级。2025年4月24日。CRD。URL:https://www.w3.org/TR/css-color-4/
[MEDIAQUERIES-5]
Dean Jackson 等。媒体查询 5 级。2021年12月18日。WD。URL:https://www.w3.org/TR/mediaqueries-5/
[SERVICE-WORKERS]
Monica CHINTALA; Yoshisato Yanagisawa。Service Workers Nightly。2025年12月12日。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 maxStorageBuffersInVertexStage;
    readonly attribute unsigned long maxStorageBuffersInFragmentStage;
    readonly attribute unsigned long maxStorageTexturesPerShaderStage;
    readonly attribute unsigned long maxStorageTexturesInVertexStage;
    readonly attribute unsigned long maxStorageTexturesInFragmentStage;
    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",
    "primitive-index",
    "texture-component-swizzle",
};

[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;
    readonly attribute (GPUTextureViewDimension or undefined) textureBindingViewDimension;
};
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 = [];
    GPUTextureViewDimension textureBindingViewDimension;
};

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;

    // Requires "texture-component-swizzle" feature.
    DOMString swizzle = "rgba";
};

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;