1. Introduction
This section is non-normative.
Graphics Processing Units, or GPUs for short, have been essential in enabling rich rendering and computational applications in personal computing. WebGPU is an API that exposes the capabilities of GPU hardware for the Web. The API is designed from the ground up to efficiently map to the Vulkan, Direct3D 12, and Metal native GPU APIs. WebGPU is not related to WebGL and does not explicitly target OpenGL ES.
WebGPU sees physical GPU hardware as GPUAdapters. It provides a connection to an adapter via GPUDevice, which manages resources, and the device’s GPUQueues, which execute commands. GPUDevice may have its own memory with high-speed access to the processing units. GPUBuffer and GPUTexture are the physical resources backed by GPU memory. GPUCommandBuffer and GPURenderBundle are containers for user-recorded commands. GPUShaderModule contains shader code. The other resources,
such as GPUSampler or GPUBindGroup, configure the way physical resources are used by the GPU.
GPUs execute commands encoded in GPUCommandBuffers by feeding data through a pipeline,
which is a mix of fixed-function and programmable stages. Programmable stages execute shaders, which are special programs designed to run on GPU hardware.
Most of the state of a pipeline is defined by
a GPURenderPipeline or a GPUComputePipeline object. The state not included
in these pipeline objects is set during encoding with commands,
such as beginRenderPass() or setBlendColor().
2. Security considerations
2.1. CPU-based undefined behavior
A WebGPU implementation translates the workloads issued by the user into API commands specific to the target platform. Native APIs specify the valid usage for the commands (for example, see vkCreateDescriptorSetLayout) and generally don’t guarantee any outcome if the valid usage rules are not followed. This is called "undefined behavior", and it can be exploited by an attacker to access memory they don’t own, or force the driver to execute arbitrary code.
In order to disallow insecure usage, the range of allowed WebGPU behaviors is defined for any input.
An implementation has to validate all the input from the user and only reach the driver
with the valid workloads. This document specifies all the error conditions and handling semantics.
For example, specifying the same buffer with intersecting ranges in both "source" and "destination"
of copyBufferToBuffer() results in GPUCommandEncoder generating an error, and no other operation occurring.
See § 20 Errors & Debugging for more information about error handling.
2.2. GPU-based undefined behavior
WebGPU shaders are executed by the compute units inside GPU hardware. In native APIs, some of the shader instructions may result in undefined behavior on the GPU. In order to address that, the shader instruction set and its defined behaviors are strictly defined by WebGPU. When a shader is provided, the WebGPU implementation has to validate it before doing any translation (to platform-specific shaders) or transformation passes.
2.3. Out-of-bounds access in shaders
Shaders can access physical resources either directly or via texture units, which are fixed-function hardware blocks that handle texture coordinate conversions. Validation on the API side can only guarantee that all the inputs to the shader are provided and they have the correct usage and types. The API side can not guarantee that the data is accessed within bounds if the texture units are not involved.
In order to prevent the shaders from accessing GPU memory an application doesn’t own, the WebGPU implementation may enable a special mode (called "robust buffer access") in the driver that guarantees that the access is limited to buffer bounds. Alternatively, an implementation may transform the shader code by inserting manual bounds checks.
If the shader attempts to load data outside of physical resource bounds, the implementation is allowed to:
-
return a value at a different location within the resource bounds
-
return a value vector of "(0, 0, 0, X)" with any "X"
-
partially discard the draw or dispatch call
If the shader attempts to write data outside of physical resource bounds, the implementation is allowed to:
-
write the value to a different location within the resource bounds
-
discard the write operation
-
partially discard the draw or dispatch call
2.4. Invalid data
When uploading floating-point data from CPU to GPU, or generating it on the GPU, we may end up with a binary representation that doesn’t correspond to a valid number, such as infinity or NaN (not-a-number). The GPU behavior in this case is subject to the accuracy of the GPU hardware implementation of the IEEE-754 standard. WebGPU guarantees that introducing invalid floating-point numbers would only affect the results of arithmetic computations and will not have other side effects.
2.5. Driver bugs
GPU drivers are subject to bugs like any other software. If a bug occurs, an attacker could possibly exploit the incorrect behavior of the driver to get access to unprivileged data. In order to reduce the risk, the WebGPU working group will coordinate with GPU vendors to integrate the WebGPU Conformance Test Suite (CTS) as part of their driver testing process, like it was done for WebGL. WebGPU implementations are expected to have workarounds for some of the discovered bugs, and support blacklisting particular drivers from using some of the native API backends.
2.6. Timing attacks
WebGPU is designed for multi-threaded use via Web Workers. Some of the objects,
like GPUBuffer, have shared state which can be simultaneously accessed.
This allows race conditions to occur, similar to those of accessing a SharedArrayBuffer
from multiple Web Workers, which makes the thread scheduling observable
and allows the creation of high-precision timers.
The theoretical attack vectors are a subset of those of SharedArrayBuffer.
2.7. Denial of service
WebGPU applications have access to GPU memory and compute units. A WebGPU implementation may limit the available GPU memory to an application, in order to keep other applications responsive. For GPU processing time, a WebGPU implementation may set up "watchdog" timer that makes sure an application doesn’t cause GPU unresponsiveness for more than a few seconds. These measures are similar to those used in WebGL.
2.8. Fingerprinting
WebGPU defines the required limits and capabilities of any GPUAdapter.
and encourages applications to target these standard limits. The actual result from requestAdapter() may have better limits, and could be subject to fingerprinting.
3. Terminology & Conventions
3.1. Dot Syntax
In this specification, the . ("dot") syntax, common in programming languages, is used.
The phrasing "Foo.Bar" means "the Bar member of the value (or interface) Foo."
For example, where buffer is a GPUBuffer, buffer.[[device]].[[adapter]] means
"the [[adapter]] internal slot of the [[device]] internal slot of buffer.
3.2. Coordinate Systems
WebGPU’s coordinate systems match DirectX and Metal’s coordinate systems in a graphics pipeline.
-
Y-axis is up in normalized device coordinate (NDC): point(-1.0, -1.0) in NDC is located at the bottom-left corner of NDC. In addition, x and y in NDC should be between -1.0 and 1.0 inclusive, while z in NDC should be between 0.0 and 1.0 inclusive. Vertices out of this range in NDC will not introduce any errors, but they will be clipped.
-
Y-axis is down in framebuffer coordinate, viewport coordinate and fragment/pixel coordinate: origin(0, 0) is located at the top-left corner in these coordinate systems.
-
Window/present coordinate matches framebuffer coordinate.
-
UV of origin(0, 0) in texture coordinate represents the first texel (the lowest byte) in texture memory.
3.3. Internal Objects
An internal object is a conceptual, non-exposed WebGPU object. Internal objects track the state of an API object and hold any underlying implementation. If the state of a particular internal object can change in parallel from multiple agents, those changes are always atomic with respect to all agents.
Note: An "agent" refers to a JavaScript "thread" (i.e. main thread, or Web Worker).
3.3.1. Invalid Objects
If an object is sucessfully created, it is valid at that moment. An internal object may be invalid. It may become invalid during its lifetime, but it will never become valid again.
-
If there is an error in the creation of an object, it is immediately invalid. This can happen, for example, if the object descriptor doesn’t describe a valid object, or if there is not enough memory to allocate a resource.
-
If an object is explicitly destroyed (e.g.
GPUBuffer.destroy()), it becomes invalid. -
If the device that owns an object is lost, the object becomes invalid.
3.4. WebGPU Interfaces
A WebGPU interface is an exposed interface which encapsulates an internal object. It provides the interface through which the internal object's state is changed.
As a matter of convention, if a WebGPU interface is referred to as invalid, it means that the internal object it encapsulates is invalid.
Any interface which includes GPUObjectBase is a WebGPU interface.
interface mixin {GPUObjectBase attribute DOMString ?label ; };
GPUObjectBase has the following attributes:
label, of type DOMString, nullable-
A label which can be used by development tools (such as error/warning messages, browser developer tools, or platform debugging utilities) to identify the underlying internal object to the developer. It has no specified format, and therefore cannot be reliably machine-parsed.
In any given situation, the user agent may or may not choose to use this label.
GPUObjectBase has the following internal slots:
[[device]], of type device, readonly-
An internal slot holding the device which owns the internal object.
3.5. Object Descriptors
An object descriptor holds the information needed to create an object,
which is typically done via one of the create* methods of GPUDevice.
dictionary {GPUObjectDescriptorBase DOMString label ; };
GPUObjectDescriptorBase has the following members:
label, of type DOMString-
The initial value of
GPUObjectBase.label.
4. Programming Model
4.1. Timelines
This section is non-normative.
A computer system with a user agent at the front-end and GPU at the back-end has components working on different timelines in parallel:
- Content timeline
-
Associated with the execution of the Web script. It includes calling all methods described by this specification.
- Device timeline
-
Associated with the GPU device operations that are issued by the user agent. It includes creation of adapters, devices, and GPU resources and state objects, which are typically synchronous operations from the point of view of the user agent part that controls the GPU, but can live in a separate OS process.
- Queue timeline
-
Associated with the execution of operations on the compute units of the GPU. It includes actual draw, copy, and compute jobs that run on the GPU.
In this specification, asynchronous operations are used when the result value depends on work that happens on any timeline other than the Content timeline. They are represented by callbacks and promises in JavaScript.
GPUComputePassEncoder.dispatch():
-
User encodes a
dispatchcommand by calling a method of theGPUComputePassEncoderwhich happens on the Content timeline. -
User issues
GPUQueue.submit()that hands over theGPUCommandBufferto the user agent, which processes it on the Device timeline by calling the OS driver to do a low-level submission. -
The submit gets dispatched by the GPU thread scheduler onto the actual compute units for execution, which happens on the Queue timeline.
GPUDevice.createBuffer():
-
User fills out a
GPUBufferDescriptorand creates aGPUBufferwith it, which happens on the Content timeline. -
User agent creates a low-level buffer on the Device timeline.
GPUBuffer.mapReadAsync():
-
User requests to map a
GPUBufferon the Content timeline and gets a promise in return. -
User agent checks if the buffer is currently used by the GPU and makes a reminder to itself to check back when this usage is over.
-
After the GPU operating on Queue timeline is done using the buffer, the user agent maps it to memory and resolves the promise.
4.2. Memory
This section is non-normative.
Once a GPUDevice has been obtained during an application initialization routine,
we can describe the WebGPU platform as consisting of the following layers:
-
User agent implementing the specification.
-
Operating system with low-level native API drivers for this device.
-
Actual CPU and GPU hardware.
Each layer of the WebGPU platform may have different memory types that the user agent needs to consider when implementing the specification:
-
The script-owned memory, such as an
ArrayBuffercreated by the script, is generally not accessible by a GPU driver. -
A user agent may have different processes responsible for running the content and communication to the GPU driver. In this case, it uses inter-process shared memory to transfer data.
-
Dedicated GPUs have their own memory with high bandwidth, while integrated GPUs typically share memory with the system.
Most physical resources are allocated in the memory of type that is efficient for computation or rendering by the GPU. When the user needs to provide new data to the GPU, the data may first need to cross the process boundary in order to reach the user agent part that communicates with the GPU driver. Then it may need to be made visible to the driver, which sometimes requires a copy into driver-allocated staging memory. Finally, it may need to be transferred to the dedicated GPU memory, potentially changing the internal layout into one that is most efficient for GPUs to operate on.
All of these transitions are done by the WebGPU implementation of the user agent.
Note: This example describes the worst case, while in practice
the implementation may not need to cross the process boundary,
or may be able to expose the driver-managed memory directly to
the user behind an ArrayBuffer, thus avoiding any data copies.
4.3. Resource usage
Buffers and textures can be used by the GPU in multiple ways, which can be split into two groups:
- Read-only usages
-
Usages like
GPUBufferUsage.VERTEXorGPUTextureUsage.SAMPLEDdon’t change the contents of a resource. - Mutating usages
-
Usages like
GPUBufferUsage.STORAGEdo change the contents of a resource.
Consider merging all read-only usages. <https://github.com/gpuweb/gpuweb/issues/296>
Textures may consist of separate mipmap levels and array layers, which can be used differently at any given time. For the matter of usage validation, we’ll call them subresources.
The main usage rule is that any subresource at any given time can only be in either:
-
a combination of read-only usages
-
a single mutating usage
Enforcing this rule allows the API to limit when data races can occur when working with memory. That property makes applications written against WebGPU more likely to run without modification on different platforms.
Generally, when an implementation processes an operation that uses a subresource in a different way than its current usage allows, it schedules a transition of the resource
into the new state. In some cases, like within an open GPURenderPassEncoder, such a
transition is impossible due to the hardware limitations.
We define these places as usage scopes:
each subresource must not change usage within the usage scope.
For example, binding the same buffer for GPUBufferUsage.STORAGE as well as for GPUBufferUsage.VERTEX within the same GPURenderPassEncoder would put the encoder
as well as the owning GPUCommandEncoder into the error state. Since GPUBufferUsage.STORAGE is the only mutating usage for a buffer
that is valid inside a render pass, if it’s present,
this buffer can’t be used in any other way within this pass.
The subresources of textures included in the views provided to GPURenderPassColorAttachmentDescriptor.attachment and GPURenderPassColorAttachmentDescriptor.resolveTarget are considered to have OUTPUT_ATTACHMENT for the usage scope of this render pass.
The physical size of a GPUTexture subresource is the dimension of the GPUTexture subresource in texels that includes the possible extra paddings to form complete texel blocks in the subresource.
-
For pixel-based
GPUTextureFormats, the physical size is always equal to the size of the subresource used in the sampling hardwares. -
GPUTextures in block-based compressedGPUTextureFormats always have a mipmap level 0 whose[[textureSize]]is a multiple of the texel block size, but the lower mipmap levels might not be the multiple of the texel block size and can have paddings.
GPUTexture in BC format whose [[textureSize]] is {60, 60, 1}, when sampling
the GPUTexture at mipmap level 2, the sampling hardware uses {15, 15, 1} as the size of the subresource,
while its physical size is {16, 16, 1} as the block-compression algorithm can only operate on 4x4 texel blocks. Document read-only states for depth views. <https://github.com/gpuweb/gpuweb/issues/514>
4.4. Synchronization
For each subresource of a physical resource, its set of usage flags is tracked on the Queue timeline. Usage flags are GPUBufferUsage or GPUTextureUsage flags,
according to the type of the subresource.
This section will need to be revised to support multiple queues.
On the Queue timeline, there is an ordered sequence of usage scopes. Each item on the timeline is contained within exactly one scope. For the duration of each scope, the set of usage flags of any given subresource is constant. A subresource may transition to new usages at the boundaries between usage scopes.
This specification defines the following usage scopes:
-
an individual command on a
GPUCommandEncoder, such asGPUCommandEncoder.copyBufferToTexture. -
an individual command on a
GPUComputePassEncoder, such asGPUProgrammablePassEncoder.setBindGroup. -
the whole
GPURenderPassEncoder.
Note: calling GPUProgrammablePassEncoder.setBindGroup adds the [[usedBuffers]] and [[usedTextures]] to the usage scope regarless of whether the shader or GPUPipelineLayout actually depends on these bindings.
Similarly GPURenderEncoderBase.setIndexBuffer add the index buffer to the usage scope (as GPUBufferUsage.INDEX)
regarless of whether the indexed draw calls are used afterwards.
The usage scopes are validated at GPUCommandEncoder.finish time.
The implementation performs the usage scope validation by composing
the set of all usage flags of each subresource used in the usage scope.
A GPUValidationError is generated in the current scope with an appropriate error message
if that union contains a mutating usage combined with any other usage.
5. Core Internal Objects
5.1. Adapters
An adapter represents an implementation of WebGPU on the system. Each adapter identifies both an instance of a hardware accelerator (e.g. GPU or CPU) and an instance of a browser’s implementation of WebGPU on top of that accelerator.
If an adapter becomes unavailable, it becomes invalid. Once invalid, it never becomes valid again. Any devices on the adapter, and internal objects owned by those devices, also become invalid.
Note: An adapter may be a physical display adapter (GPU), but it could also be
a software renderer.
A returned adapter could refer to different physical adapters, or to
different browser codepaths or system drivers on the same physical adapters.
Applications can hold onto multiple adapters at once (via GPUAdapter)
(even if some are invalid),
and two of these could refer to different instances of the same physical
configuration (e.g. if the GPU was reset or disconnected and reconnected).
An adapter has the following internal slots:
[[extensions]], of type sequence<GPUExtensionName>, readonly-
The extensions which can be used to create devices on this adapter.
[[limits]], of typeGPULimits, readonly-
The best limits which can be used to create devices on this adapter.
Each adapter limit must be the same or better than its default value in
GPULimits.
Adapters are exposed via GPUAdapter.
5.2. Devices
A device is the logical instantiation of an adapter, through which internal objects are created. It can be shared across multiple agents (e.g. dedicated workers).
A device is the exclusive owner of all internal objects created from it:
when the device is lost, it and all objects created on it (directly, e.g. createTexture(), or indirectly, e.g. createView()) become invalid.
A device has the following internal slots:
[[adapter]], of type adapter, readonly-
The adapter from which this device was created.
[[extensions]], of type sequence<GPUExtensionName>, readonly-
The extensions which can be used on this device. No additional extensions can be used, even if the underlying adapter can support them.
[[limits]], of typeGPULimits, readonly-
The limits which can be used on this device. No better limits can be used, even if the underlying adapter can support them.
GPUDeviceDescriptor descriptor:
-
Set device.
[[adapter]]to adapter. -
Set device.
[[extensions]]to descriptor.extensions. -
Set device.
[[limits]]to descriptor.limits.
Devices are exposed via GPUDevice.
6. Initialization
6.1. Examples
Need a robust example like the one in ErrorHandling.md, which handles all situations. Possibly also include a simple example with no handling.
6.2. navigator.gpu
A GPU object is available via navigator.gpu on the Window:
[Exposed =Window ]partial interface Navigator { [SameObject ]readonly attribute GPU ; };gpu
... as well as on dedicated workers:
[Exposed =DedicatedWorker ]partial interface WorkerNavigator { [SameObject ]readonly attribute GPU ; };gpu
6.3. GPU
GPU is the entry point to WebGPU.
[Exposed =(Window ,DedicatedWorker )]interface GPU {Promise <GPUAdapter >requestAdapter (optional GPURequestAdapterOptions = {}); };options
GPU has the methods defined by the following sections.
6.3.1. requestAdapter(options)
-
optional
GPURequestAdapterOptionsoptions = {}
Returns: promise, of type Promise<GPUAdapter>.
Requests an adapter from the user agent. The user agent chooses whether to return an adapter, and, if so, chooses according to the provided options.
Returns a new promise, promise. On the Device timeline, the following steps occur:
-
If the user agent chooses to return an adapter:
-
The user agent chooses an adapter adapter according to the rules in § 6.3.1.1 Adapter Selection.
-
promise resolves with a new
GPUAdapterencapsulating adapter.
-
-
Otherwise, promise rejects with an
OperationError.
6.3.1.1. Adapter Selection
GPURequestAdapterOptions provides hints to the user agent indicating what
configuration is suitable for the application.
dictionary GPURequestAdapterOptions {GPUPowerPreference powerPreference ; };
enum {GPUPowerPreference "low-power" ,"high-performance" };
GPURequestAdapterOptions has the following members:
powerPreference, of type GPUPowerPreference-
Optionally provides a hint indicating what class of adapter should be selected from the system’s available adapters.
The value of this hint may influence which adapter is chosen, but it must not influence whether an adapter is returned or not.
Note: The primary utility of this hint is to influence which GPU is used in a multi-GPU system. For instance, some laptops have a low-power integrated GPU and a high-performance discrete GPU.
Note: Depending on the exact hardware configuration, such as battery status and attached displays or removable GPUs, the user agent may select different adapters given the same power preference. Typically, given the same hardware configuration and state and
powerPreference, the user agent is likely to select the same adapter.It must be one of the following values:
undefined(or not present)-
Provides no hint to the user agent.
"low-power"-
Indicates a request to prioritize power savings over performance.
Note: Generally, content should use this if it is unlikely to be constrained by drawing performance; for example, if it renders only one frame per second, draws only relatively simple geometry with simple shaders, or uses a small HTML canvas element. Developers are encouraged to use this value if their content allows, since it may significantly improve battery life on portable devices.
"high-performance"-
Indicates a request to prioritize performance over power consumption.
Note: By choosing this value, developers should be aware that, for devices created on the resulting adapter, user agents are more likely to force device loss, in order to save power by switching to a lower-power adapter. Developers are encouraged to only specify this value if they believe it is absolutely necessary, since it may significantly decrease battery life on portable devices.
6.4. GPUAdapter
A GPUAdapter encapsulates an adapter,
and describes its capabilities (extensions and limits).
To get a GPUAdapter, use requestAdapter().
interface GPUAdapter {readonly attribute DOMString name ;readonly attribute FrozenArray <GPUExtensionName >extensions ; //readonly attribute GPULimits limits; Don’t expose higher limits for now.Promise <GPUDevice >requestDevice (optional GPUDeviceDescriptor = {}); };descriptor
GPUAdapter has:
-
These attributes:
name, of type DOMString, readonly-
A human-readable name identifying the adapter. The contents are implementation-defined.
extensions, of type FrozenArray<GPUExtensionName>, readonly-
Accessor for
this.[[adapter]].[[extensions]].
-
These internal slots:
[[adapter]], of type adapter, readonly-
An internal slot holding the adapter to which this
GPUAdapterrefers.
-
The methods defined by the following sub-sections.
6.4.1. requestDevice(optional descriptor)
GPUAdapter.
Arguments:
-
optional
GPUDeviceDescriptordescriptor = {}
Returns: promise, of type Promise<GPUDevice>.
Requests a device from the adapter.
Returns a new promise, promise. On the Device timeline, the following steps occur:
-
If the user agent can fulfill the request and the Valid Usage rules are met:
-
promise resolves to a new
GPUDeviceobject encapsulating a new device with the capabilities described by descriptor.
-
-
Otherwise, promise rejects with an
OperationError.
Let adapter be this.[[adapter]].
-
The set of
GPUExtensionNamevalues in descriptor.extensionsmust be a subset of those in adapter.[[extensions]]. -
For each type of limit in
GPULimits, the value of that limit in descriptor.limitsmust be no better than the value of that limit in adapter.[[limits]].
6.4.1.1. GPUDeviceDescriptor
GPUDeviceDescriptor describes a device request.
dictionary GPUDeviceDescriptor :GPUObjectDescriptorBase {sequence <GPUExtensionName >extensions = [];GPULimits limits = {}; };
extensions, of type sequence<GPUExtensionName>, defaulting to[]-
The set of
GPUExtensionNamevalues in this sequence defines the exact set of extensions that must be enabled on the device. limits, of type GPULimits, defaulting to{}-
Defines the exact limits that must be enabled on the device.
6.4.1.2. GPUExtensionName
Each GPUExtensionName identifies a set of functionality which, if available,
allows additional usages of WebGPU that would have otherwise been invalid.
enum GPUExtensionName {"texture-compression-bc" };
6.4.1.3. GPULimits
GPULimits describes various limits in the usage of WebGPU on a device.
One limit value may be better than another. For each limit, "better" is defined.
Note: Setting "better" limits may not necessarily be desirable. While they enable strictly more programs to be valid, they may have a performance impact. Because of this, and to improve portability across devices and implementations, applications should generally request the "worst" limits that work for their content.
dictionary GPULimits {GPUSize32 maxBindGroups = 4;GPUSize32 maxDynamicUniformBuffersPerPipelineLayout = 8;GPUSize32 maxDynamicStorageBuffersPerPipelineLayout = 4;GPUSize32 maxSampledTexturesPerShaderStage = 16;GPUSize32 maxSamplersPerShaderStage = 16;GPUSize32 maxStorageBuffersPerShaderStage = 4;GPUSize32 maxStorageTexturesPerShaderStage = 4;GPUSize32 maxUniformBuffersPerShaderStage = 12; };
maxBindGroups, of type GPUSize32, defaulting to4-
The maximum number of
GPUBindGroupLayoutsallowed inbindGroupLayoutswhen creating aGPUPipelineLayout.Higher is better.
maxDynamicUniformBuffersPerPipelineLayout, of type GPUSize32, defaulting to8-
The maximum number of
entriesfor which:-
typeis"uniform-buffer", and -
hasDynamicOffsetis true,
across all
bindGroupLayoutswhen creating aGPUPipelineLayout.Higher is better.
-
maxDynamicStorageBuffersPerPipelineLayout, of type GPUSize32, defaulting to4-
The maximum number of
entriesfor which:-
typeis"storage-buffer", and -
hasDynamicOffsetis true,
across all
bindGroupLayoutswhen creating aGPUPipelineLayout.Higher is better.
-
maxSampledTexturesPerShaderStage, of type GPUSize32, defaulting to16-
For each possible
GPUShaderStagestage, the maximum number ofentriesfor which:-
typeis"sampled-texture", and -
visibilityincludesstage,
across all
bindGroupLayoutswhen creating aGPUPipelineLayout.Higher is better.
-
maxSamplersPerShaderStage, of type GPUSize32, defaulting to16-
For each possible
GPUShaderStagestage, the maximum number ofentriesfor which:-
typeis"sampler"or"comparison-sampler", and -
visibilityincludesstage,
across all
bindGroupLayoutswhen creating aGPUPipelineLayout.Higher is better.
-
maxStorageBuffersPerShaderStage, of type GPUSize32, defaulting to4-
For each possible
GPUShaderStagestage, the maximum number ofentriesfor which:-
typeis"storage-buffer", and -
visibilityincludesstage,
across all
bindGroupLayoutswhen creating aGPUPipelineLayout.Higher is better.
-
maxStorageTexturesPerShaderStage, of type GPUSize32, defaulting to4-
For each possible
GPUShaderStagestage, the maximum number ofentriesfor which:-
typeis"readonly-storage-texture"or"writeonly-storage-texture", and -
visibilityincludesstage,
across all
bindGroupLayoutswhen creating aGPUPipelineLayout.Higher is better.
-
maxUniformBuffersPerShaderStage, of type GPUSize32, defaulting to12-
For each possible
GPUShaderStagestage, the maximum number ofentriesfor which:-
typeisuniform-buffer, and -
visibilityincludesstage,
across all
bindGroupLayoutswhen creating aGPUPipelineLayout.Higher is better.
-
6.5. GPUDevice
A GPUDevice encapsulates a device and exposes
the functionality of that device.
GPUDevice is the top-level interface through which WebGPU interfaces are created.
To get a GPUDevice, use requestDevice().
[Exposed =(Window ,DedicatedWorker ),Serializable ]interface GPUDevice :EventTarget { [SameObject ]readonly attribute GPUAdapter adapter ;readonly attribute FrozenArray <GPUExtensionName >extensions ;readonly attribute object limits ; [SameObject ]readonly attribute GPUQueue ;defaultQueue GPUBuffer createBuffer (GPUBufferDescriptor );descriptor GPUMappedBuffer createBufferMapped (GPUBufferDescriptor );descriptor GPUTexture (createTexture GPUTextureDescriptor );descriptor GPUSampler createSampler (optional GPUSamplerDescriptor = {});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 GPUCommandEncoder (createCommandEncoder optional GPUCommandEncoderDescriptor = {});descriptor GPURenderBundleEncoder (createRenderBundleEncoder GPURenderBundleEncoderDescriptor ); };descriptor GPUDevice includes GPUObjectBase ;
GPUDevice has:
-
These attributes:
adapter, of type GPUAdapter, readonly-
The
GPUAdapterfrom which this device was created. extensions, of type FrozenArray<GPUExtensionName>, readonly-
A sequence containing the
GPUExtensionNames of the extensions supported by the device (i.e. the ones with which it was created). limits, of type object, readonly-
A
GPULimitsobject exposing the limits supported by the device (i.e. the ones with which it was created).
-
These internal slots:
-
The methods listed in its WebIDL definition above, which are defined elsewhere in this document.
GPUDevice objects are serializable objects.
-
If forStorage is true, throw a "
DataCloneError". -
Set serialized.device to the value of value.
[[device]].
-
Set value.
[[device]]to serialized.device.
7. Buffers
7.1. GPUBuffer
define buffer (internal object)
A GPUBuffer represents a block of memory that can be used in GPU operations.
Data is stored in linear layout, meaning that each byte of the allocation can be
addressed by its offset from the start of the GPUBuffer, subject to alignment
restrictions depending on the operation. Some GPUBuffers can be
mapped which makes the block of memory accessible via an ArrayBuffer called
its mapping.
GPUBuffers can be created via the following functions:
-
GPUDevice.createBuffer(descriptor)that returns a new buffer in the unmapped state. -
GPUDevice.createBufferMapped(descriptor)that returns a new buffer in the mapped for writing state and its mapping.
[Serializable ]interface GPUBuffer {Promise <ArrayBuffer >();mapReadAsync Promise <ArrayBuffer >();mapWriteAsync void unmap ();void destroy (); };GPUBuffer includes GPUObjectBase ;
GPUBuffer has the following internal slots:
[[size]]of typeGPUSize64.-
The length of the
GPUBufferallocation in bytes. [[usage]]of typeGPUBufferUsageFlags.-
The allowed usages for this
GPUBuffer. [[state]]of type buffer state.-
The current state of the
GPUBuffer. [[mapping]]of typeArrayBufferorPromiseornull.-
The mapping for this
GPUBuffer.
Each GPUBuffer has a current buffer state on the Content timeline which is one of the following:
-
"mapped for reading" where the
GPUBufferis available for CPU operations reading its content. -
"mapped for writing" where the
GPUBufferis available for CPU operations writing its content. -
"mapping pending for reading" where the
GPUBufferis being made available for reading its content. -
"mapping pending for writing" where the
GPUBufferis being made available for writing its content. -
"unmapped" where the
GPUBufferis available for GPU operations. -
"destroyed" where the
GPUBufferis no longer available for any operations exceptdestroy.
Note: [[size]] and [[usage]] are immutable once the GPUBuffer has been created.
GPUBuffer has a state machine where the states are:
-
unmapped and destroyed with a
null[[mapping]] -
mapped for reading and mapped for writing with an
ArrayBuffertyped[[mapping]]. -
mapping pending for reading and mapping pending for writing with a
Promisetyped[[mapping]].
GPUBuffer is Serializable. It is a reference to an internal buffer
object, and Serializable means that the reference can be copied between
realms (threads/workers), allowing multiple realms to access it concurrently.
Since GPUBuffer has internal state (mapped, destroyed), that state is
internally-synchronized - these state changes occur atomically across realms.
7.2. Buffer Creation
7.2.1. GPUBufferDescriptor
This specifies the options to use in creating a GPUBuffer.
dictionary :GPUBufferDescriptor GPUObjectDescriptorBase {required GPUSize64 ;size required GPUBufferUsageFlags ; };usage
- validating GPUBufferDescriptor(device, descriptor)
7.2.2. GPUDevice.createBuffer(descriptor)
createBuffer(descriptor)-
-
If the result of validating GPUBufferDescriptor(this, descriptor) is false:
-
Let b be a new
GPUBufferobject. -
Set the
[[size]]slot of b to the value of thesizeattribute of descriptor. -
Set the
[[usage]]slot of b to the value of theusageattribute of descriptor. -
Set the
[[mapping]]internal slot of b tonull. -
Set each byte of b’s allocation to zero.
-
Return b.
-
7.2.3. GPUDevice.createBufferMapped(descriptor)
createBufferMapped(descriptor)-
-
If the result of validating GPUBufferDescriptor(this, descriptor) is false:
-
Record a validation error in the current scope.
-
Create an invalid
GPUBufferand return the result.
-
-
Let b be a new
GPUBufferobject. -
Set the
[[size]]slot of b to the value of thesizeattribute of descriptor. -
Let m be a zero-filled
ArrayBufferof size the[[size]]slot of b. -
Set the
[[usage]]slot of b to the value of theusageattribute of descriptor. -
Set the
[[state]]internal slot of b to mapped for writing. -
Set the
[[mapping]]internal slot of b to m. -
Set each byte of b’s allocation to zero.
-
Return a sequence containing b and m in that order.
-
7.3. Buffer Destruction
An application that no longer requires a GPUBuffer can choose to lose
access to it before garbage collection by calling destroy().
Note: This allows the user agent to reclaim the GPU memory associated with the GPUBuffer once all previously submitted operations using it are complete.
7.3.1. destroy()
-
If the
[[state]]slot of this is mapped for reading or mapped for writing:-
Run the steps to unmap
"this"
-
7.4. Buffer Usage
typedef [EnforceRange ]unsigned long ;GPUBufferUsageFlags interface {GPUBufferUsage const GPUBufferUsageFlags = 0x0001;MAP_READ const GPUBufferUsageFlags = 0x0002;MAP_WRITE const GPUBufferUsageFlags = 0x0004;COPY_SRC const GPUBufferUsageFlags = 0x0008;COPY_DST const GPUBufferUsageFlags = 0x0010;INDEX const GPUBufferUsageFlags = 0x0020;VERTEX const GPUBufferUsageFlags = 0x0040;UNIFORM const GPUBufferUsageFlags = 0x0080;STORAGE const GPUBufferUsageFlags = 0x0100; };INDIRECT
7.5. Buffer Mapping
An application can request to map a GPUBuffer to get its mapping which is
an ArrayBuffer representing the GPUBuffer's allocation. Mappings are
requested asynchronously so that the user agent can ensure the GPU finished
using the GPUBuffer before the application gets its mapping. Mappings can
be requested for reading with mapReadAsync or writing with mapWriteAsync. A mapped GPUBuffer cannot be used by the GPU
and must be unmapped using unmap before it can be used on the Queue timeline.
Add client-side validation that a mapped buffer can only be unmapped and destroyed on the worker on which it was mapped.
7.5.1. GPUDevice.mapReadAsync
-
If the
[[usage]]slot of this doesn’t contain theMAP_READbit or if[[state]]isn’t unmapped:-
Record a validation error on the current scope.
-
Return a promise rejected with an
AbortError.
-
-
Let p be a new
Promise. -
Set the
[[mapping]]slot of this to p. -
Set the
[[state]]slot of this to mapping pending for reading. -
Enqueue an operation on the Queue timeline that will execute the following:
-
Let m be a new
ArrayBufferof size the[[size]]of this. -
Set the content of m to the content of this’s allocation.
-
Set the
[[state]]slot of this to mapped for reading. -
If p is pending:
-
Resolve p with m.
-
-
-
Return p.
7.5.2. GPUDevice.mapWriteAsync
Handle error buffers once we have a description of the error monad.
-
If the
[[usage]]slot of this doesn’t contain theMAP_WRITEbit or if[[state]]isn’t unmapped:-
Record a validation error on the current scope.
-
Return a promise rejected with an
AbortError.
-
-
Let p be a new
Promise. -
Set the
[[mapping]]slot of this to p. -
Set the
[[state]]slot of this to mapping pending for writing. -
Enqueue an operation on the Queue timeline that will execute the following:
-
Let m be a new
ArrayBufferof size the[[size]]of this that is filled with zeroes. -
Set the
[[state]]slot of this to mapped for writing. -
If p is pending:
-
Resolve p with m.
-
-
-
Return p.
7.5.3. unmap()
-
If the
[[state]]slot of this is unmapped or destroyed:-
Record a validation error on the current scope.
-
Return.
-
-
If the
[[mapping]]slot of this is aPromise:-
Reject
[[mapping]]with anAbortError. -
Set the
[[mapping]]slot of this to null.
-
-
If the
[[mapping]]slot of this is anArrayBuffer:-
If the
[[state]]slot of this is mapped for writing:-
Enqueue an operation on the Queue timeline that updates this’s allocation to the content of the
ArrayBufferin the[[mapping]]slot of this.
-
-
Detach this.
[[mapping]]from its content. -
Set the
[[mapping]]slot of this to null.
-
8. Textures and Texture Views
define texture (internal object)
define mipmap level, array layer, slice (concepts)
8.1. GPUTexture
[Serializable ]interface GPUTexture {GPUTextureView createView (optional GPUTextureViewDescriptor = {});descriptor void (); };destroy GPUTexture includes GPUObjectBase ;
GPUTexture has the following internal slots:
[[textureSize]]of typeGPUExtent3D.-
The size of the
GPUTexturein texels in mipmap level 0. [[mipLevelCount]]of typeGPUIntegerCoordinate.-
The total number of the mipmap levels of the
GPUTexture. [[sampleCount]]of typeGPUSize32.-
The number of samples in each texel of the
GPUTexture. [[dimension]]of typeGPUTextureDimension.-
The dimension of the
GPUTexture. [[format]]of typeGPUTextureFormat.-
The format of the
GPUTexture. [[textureUsage]]of typeGPUTextureUsageFlags.-
The allowed usages for this
GPUTexture.
8.1.1. Texture Creation
dictionary :GPUTextureDescriptor GPUObjectDescriptorBase {required GPUExtent3D ;size GPUIntegerCoordinate = 1;mipLevelCount GPUSize32 = 1;sampleCount GPUTextureDimension = "2d";dimension required GPUTextureFormat ;format required GPUTextureUsageFlags ; };usage
enum {GPUTextureDimension ,"1d" ,"2d" };"3d"
typedef [EnforceRange ]unsigned long ;GPUTextureUsageFlags interface {GPUTextureUsage const GPUTextureUsageFlags = 0x01;COPY_SRC const GPUTextureUsageFlags = 0x02;COPY_DST const GPUTextureUsageFlags = 0x04;SAMPLED const GPUTextureUsageFlags = 0x08;STORAGE const GPUTextureUsageFlags = 0x10; };OUTPUT_ATTACHMENT
8.2. GPUTextureView
interface { };GPUTextureView GPUTextureView includes GPUObjectBase ;
8.2.1. Texture View Creation
dictionary :GPUTextureViewDescriptor GPUObjectDescriptorBase {GPUTextureFormat ;format GPUTextureViewDimension ;dimension GPUTextureAspect = "all";aspect GPUIntegerCoordinate = 0;baseMipLevel GPUIntegerCoordinate = 0;mipLevelCount GPUIntegerCoordinate = 0;baseArrayLayer GPUIntegerCoordinate = 0; };arrayLayerCount
Make this a standalone algorithm used in the createView algorithm.
The references to GPUTextureDescriptor here should actually refer to internal slots of a texture internal object once we have one.
-
dimension: If unspecified: -
mipLevelCount: If 0, defaults to texture.mipLevelCount−baseMipLevel. -
arrayLayerCount: If 0, defaults to texture.size.depth −baseArrayLayer.
enum {GPUTextureViewDimension ,"1d" ,"2d" ,"2d-array" ,"cube" ,"cube-array" };"3d"
enum {GPUTextureAspect ,"all" ,"stencil-only" };"depth-only"
8.2.2. GPUTexture.createView(descriptor)
GPUTexture.
Arguments:
-
optional
GPUTextureViewDescriptordescriptor
Returns: view, of type GPUTextureView.
8.3. Texture Formats
The name of the format specifies the order of components, bits per component, and data type for the component.
-
r,g,b,a= red, green, blue, alpha -
unorm= unsigned normalized -
snorm= signed normalized -
uint= unsigned int -
sint= signed int -
float= floating point
If the format has the -srgb suffix, then sRGB conversions from gamma to linear
and vice versa are applied during the reading and writing of color values in the
shader. Compressed texture formats are provided by extensions. Their naming
should follow the convention here, with the texture name as a prefix. e.g. etc2-rgba8unorm.
The texel block is a single addressable element of the textures in pixel-based GPUTextureFormats,
and a single compressed block of the textures in block-based compressed GPUTextureFormats.
The texel block width and texel block height specifies the dimension of one texel block.
-
For pixel-based
GPUTextureFormats, the texel block width and texel block height are always 1. -
For block-based compressed
GPUTextureFormats, the texel block width is the number of texels in each row of one texel block, and the texel block height is the number of texel rows in one texel block.
The texel block size of a GPUTextureFormat is the number of bytes to store one texel block.
The texel block size of each GPUTextureFormat is constant except for "depth24plus" and "depth24plus-stencil8".
enum { // 8-bit formatsGPUTextureFormat ,"r8unorm" ,"r8snorm" ,"r8uint" , // 16-bit formats"r8sint" ,"r16uint" ,"r16sint" ,"r16float" ,"rg8unorm" ,"rg8snorm" ,"rg8uint" , // 32-bit formats"rg8sint" ,"r32uint" ,"r32sint" ,"r32float" ,"rg16uint" ,"rg16sint" ,"rg16float" ,"rgba8unorm" ,"rgba8unorm-srgb" ,"rgba8snorm" ,"rgba8uint" ,"rgba8sint" ,"bgra8unorm" , // Packed 32-bit formats"bgra8unorm-srgb" ,"rgb10a2unorm" , // 64-bit formats"rg11b10float" ,"rg32uint" ,"rg32sint" ,"rg32float" ,"rgba16uint" ,"rgba16sint" , // 128-bit formats"rgba16float" ,"rgba32uint" ,"rgba32sint" , // Depth and stencil formats"rgba32float" ,"depth32float" ,"depth24plus" };"depth24plus-stencil8"
-
The
depth24plusfamily of formats (depth24plusanddepth24plus-stencil8) must have a depth-component precision of 1 ULP ≤ 1 / (224).Note: This is unlike the 24-bit unsigned normalized format family typically found in native APIs, which has a precision of 1 ULP = 1 / (224 − 1).
enum {GPUTextureComponentType ,"float" ,"sint" };"uint"
9. Samplers
9.1. GPUSampler
interface { };GPUSampler GPUSampler includes GPUObjectBase ;
GPUSampler has the following internal slots:
[[compareEnable]]of typeboolean.-
Whether the
GPUSampleris used as a comparison sampler.
9.1.1. Creation
dictionary :GPUSamplerDescriptor GPUObjectDescriptorBase {GPUAddressMode = "clamp-to-edge";addressModeU GPUAddressMode = "clamp-to-edge";addressModeV GPUAddressMode = "clamp-to-edge";addressModeW GPUFilterMode = "nearest";magFilter GPUFilterMode = "nearest";minFilter GPUFilterMode = "nearest";mipmapFilter float = 0;lodMinClamp float = 0xffffffff; // TODO: What should this be? Was Number.MAX_VALUE.lodMaxClamp GPUCompareFunction ; };compare
9.1.2. GPUDevice.createSampler(descriptor)
-
optional
GPUSamplerDescriptordescriptor = {}
Returns: GPUSampler
-
Let s be a new
GPUSamplerobject. -
Set the
[[compareEnable]]slot of s to false if thecompareattribute of descriptor is null or undefined. Otherwise, set it to true. -
Return s.
enum {GPUAddressMode ,"clamp-to-edge" ,"repeat" };"mirror-repeat"
enum {GPUFilterMode ,"nearest" };"linear"
enum {GPUCompareFunction ,"never" ,"less" ,"equal" ,"less-equal" ,"greater" ,"not-equal" ,"greater-equal" };"always"
10. Resource Binding
10.1. GPUBindGroupLayout
A GPUBindGroupLayout defines the interface between a set of resources bound in a GPUBindGroup and their accessibility in shader stages.
[Serializable ]interface { };GPUBindGroupLayout GPUBindGroupLayout includes GPUObjectBase ;
10.1.1. Creation
A GPUBindGroupLayout is created via GPUDevice.createBindGroupLayout().
dictionary :GPUBindGroupLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayoutEntry >; };entries
A GPUBindGroupLayoutEntry describes a single shader resource binding to be included in a GPUBindGroupLayout.
dictionary {GPUBindGroupLayoutEntry required GPUIndex32 ;binding required GPUShaderStageFlags ;visibility required GPUBindingType ;type GPUTextureViewDimension = "2d";viewDimension GPUTextureComponentType = "float";textureComponentType GPUTextureFormat ;storageTextureFormat boolean =multisampled false ;boolean =hasDynamicOffset false ; };
-
binding: A unique identifier for a resource binding within aGPUBindGroupLayoutEntry, a correspondingGPUBindGroupEntry, and shader stages. -
visibility: A bitset of the members ofGPUShaderStage. Each set bit indicates that aGPUBindGroupLayoutEntry's resource will be accessible from the associated shader stage.
typedef [EnforceRange ]unsigned long ;GPUShaderStageFlags interface {GPUShaderStage const GPUShaderStageFlags = 0x1;VERTEX const GPUShaderStageFlags = 0x2;FRAGMENT const GPUShaderStageFlags = 0x4; };COMPUTE
-
type: A member ofGPUBindingTypethat indicates the intended usage of a resource binding in its visibleGPUShaderStages.
enum {GPUBindingType ,"uniform-buffer" ,"storage-buffer" ,"readonly-storage-buffer" ,"sampler" ,"comparison-sampler" ,"sampled-texture" ,"readonly-storage-texture" // TODO: other binding types };"writeonly-storage-texture"
-
viewDimension,multisampled: Describes the dimensionality of texture view bindings, and indicates if they are multisampled.Note: This allows Metal-based implementations to back the respective bind groups with
MTLArgumentBufferobjects that are more efficient to bind at run-time. -
hasDynamicOffset: Foruniform-buffer,storage-buffer, andreadonly-storage-bufferbindings, indicates that the binding has a dynamic offset. One offset must be passed to setBindGroup for each dynamic binding in increasing order ofbindingnumber.
A GPUBindGroupLayout object has the following internal slots:
[[entries]]of type sequence<GPUBindGroupLayoutEntry>.-
The set of
GPUBindGroupLayoutEntrys thisGPUBindGroupLayoutdescribes.
10.1.2. GPUDevice.createBindGroupLayout(GPUBindGroupLayoutDescriptor)
GPUDevice.
Arguments:
-
GPUBindGroupLayoutDescriptordescriptor
Returns: GPUBindGroupLayout.
The createBindGroupLayout(descriptor) method is used to create GPUBindGroupLayouts.
-
Ensure device validation is not violated.
-
Let layout be a new valid
GPUBindGroupLayoutobject. -
For each
GPUBindGroupLayoutEntrybindingDescriptor in descriptor.entries:-
Ensure bindingDescriptor.
bindingdoes not violate binding validation. -
If bindingDescriptor.
visibilityincludesVERTEX, ensure vertex shader binding validation is not violated. -
If bindingDescriptor.
typeisuniform-buffer:-
Ensure uniform buffer validation is not violated.
-
If bindingDescriptor.
hasDynamicOffsetistrue, ensure dynamic uniform buffer validation is not violated.
-
-
If bindingDescriptor.
typeisstorage-bufferorreadonly-storage-buffer:-
Ensure storage buffer validation is not violated.
-
If bindingDescriptor.
hasDynamicOffsetistrue, ensure dynamic storage buffer validation is not violated.
-
-
If bindingDescriptor.
typeissampled-texture, ensure sampled texture validation is not violated. -
If bindingDescriptor.
typeisreadonly-storage-textureorwriteonly-storage-texture, ensure storage texture validation is not violated. -
If bindingDescriptor.
typeissampler, ensure sampler validation is not violated. -
Insert bindingDescriptor into layout.
[[entries]].
-
-
Return layout.
If any of the following conditions are violated:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Create a new invalid
GPUBindGroupLayoutand return the result.
device validation: The GPUDevice must not be lost.
binding validation: Each bindingDescriptor.binding in descriptor must be unique.
vertex shader binding validation: storage-buffer is not allowed.
uniform buffer validation: There must be GPULimits.maxUniformBuffersPerShaderStage or
fewer bindingDescriptors of type uniform-buffer visible on each shader stage in descriptor.
dynamic uniform buffer validation: There must be GPULimits.maxDynamicUniformBuffersPerPipelineLayout or
fewer bindingDescriptors of type uniform-buffer with hasDynamicOffset set to true in descriptor that are visible to any shader stage.
storage buffer validation: There must be GPULimits.maxStorageBuffersPerShaderStage or
fewer bindingDescriptors of type storage-buffer visible on each shader stage in descriptor.
dynamic storage buffer validation: There must be GPULimits.maxDynamicStorageBuffersPerPipelineLayout or
fewer bindingDescriptors of type storage-buffer with hasDynamicOffset set to true in descriptor that are visible to any shader stage.
sampled texture validation: There must be GPULimits.maxSampledTexturesPerShaderStage or
fewer bindingDescriptors of type sampled-texture visible on each shader stage in descriptor. bindingDescriptor.hasDynamicOffset must be false.
storage texture validation: There must be GPULimits.maxStorageTexturesPerShaderStage or
fewer bindingDescriptors of type readonly-storage-texture and writeonly-storage-texture visible on each shader stage in descriptor. bindingDescriptor.hasDynamicOffset must be false.
sampler validation: There must be GPULimits.maxSamplersPerShaderStage or
fewer bindingDescriptors of type sampler visible on each shader stage in descriptor. bindingDescriptor.hasDynamicOffset must be false.
10.2. GPUBindGroup
A GPUBindGroup defines a set of resources to be bound together in a group
and how the resources are used in shader stages.
interface { };GPUBindGroup GPUBindGroup includes GPUObjectBase ;
10.2.1. Bind Group Creation
A GPUBindGroup is created via GPUDevice.createBindGroup().
dictionary :GPUBindGroupDescriptor GPUObjectDescriptorBase {required GPUBindGroupLayout ;layout required sequence <GPUBindGroupEntry >; };entries
A GPUBindGroupEntry describes a single resource to be bound in a GPUBindGroup.
typedef (GPUSampler or GPUTextureView or GPUBufferBinding );GPUBindingResource dictionary {GPUBindGroupEntry required GPUIndex32 ;binding required GPUBindingResource ; };resource
dictionary {GPUBufferBinding required GPUBuffer ;buffer GPUSize64 = 0;offset GPUSize64 ; };size
A GPUBindGroup object has the following internal slots:
[[layout]]of typeGPUBindGroupLayout.-
The
GPUBindGroupLayoutassociated with thisGPUBindGroup. [[entries]]of type sequence<GPUBindGroupEntry>.-
The set of
GPUBindGroupEntrys thisGPUBindGroupdescribes. [[usedBuffers]]of type maplike<GPUBuffer,GPUBufferUsage>.-
The set of buffers used by this bind group and the corresponding usage flags.
[[usedTextures]]of type maplike<GPUTexturesubresource,GPUTextureUsage>.-
The set of texure subresources used by this bind group. Each subresource is stored with the union of usage flags that apply to it.
10.2.2. GPUDevice.createBindGroup(GPUBindGroupDescriptor)
-
GPUBindGroupDescriptordescriptor
Returns: GPUBindGroup.
The createBindGroup(descriptor) method is used to create GPUBindGroups.
If any of the conditions below are violated:
-
Generate a
GPUValidationErrorin the current scope with appropriate error message. -
Create a new invalid
GPUBindGroupand return the result.
-
Ensure bind group device validation is not violated.
-
Ensure descriptor.
layoutis a validGPUBindGroupLayout. -
Ensure the number of
entriesof descriptor.layoutexactly equals to the number of descriptor.entries. -
For each
GPUBindGroupEntrybindingDescriptor in descriptor.entries:-
Ensure there is exactly one
GPUBindGroupLayoutEntrylayoutBinding inentriesof descriptor.layoutsuch that layoutBinding.bindingequals to bindingDescriptor.binding. -
If layoutBinding.
typeis"sampler":-
Ensure bindingDescriptor.
resourceis a validGPUSamplerobject and[[compareEnable]]is false.
-
-
If layoutBinding.
typeis"comparison-sampler":-
Ensure bindingDescriptor.
resourceis a validGPUSamplerobject and[[compareEnable]]is true.
-
-
If layoutBinding.
typeis"sampled-texture"or"readonly-storage-texture"or"writeonly-storage-texture".-
Ensure bindingDescriptor.
resourceis a validGPUTextureViewobject. -
Ensure texture view binding validation is not violated.
-
Ensure bindingDescriptor.
storageTextureFormatis a validGPUTextureFormat.
-
-
If layoutBinding.
typeis"uniform-buffer"or"storage-buffer"or"readonly-storage-buffer".-
Ensure bindingDescriptor.
resourceis a validGPUBufferBindingobject. -
Ensure buffer binding validation is not violated.
-
-
-
Return a new
GPUBindGroupobject with:-
[[layout]]= descriptor.layout -
[[entries]]= descriptor.entries -
[[usedBuffers]]= union of the buffer usages across all entries -
[[usedTextures]]= union of the texture subresource usages across all entries
-
bind group device validation: The GPUDevice must not be lost.
texture view binding validation: Let view be bindingDescriptor.resource, a GPUTextureView.
This layoutBinding must be compatible with this view. This requires:
-
Its layoutBinding.
viewDimensionmust equal view’sdimension. -
Its layoutBinding.
textureComponentTypemust be compatible with view’sformat. -
If layoutBinding.
multisampledistrue, view’s texture’ssampleCountmust be greater than 1. Otherwise, if bindingDescriptor.multisampledisfalse, view’s texture’ssampleCountmust be 1. -
If layoutBinding.
typeis"sampled-texture", view’s texture’susagemust includeSAMPLED. Each texture subresource seen by view is added to[[usedTextures]]withSAMPLEDflag. -
If layoutBinding.
typeis"readonly-storage-texture"or"writeonly-storage-texture", view’s texture’susagemust includeSTORAGE. Each texture subresource seen by view is added to[[usedTextures]]withSTORAGEflag.
buffer binding validation: Let bufferBinding be bindingDescriptor.resource, a GPUBufferBinding.
This layoutBinding must be compatible with this bufferBinding. This requires:
-
If layoutBinding.
typeis"uniform-buffer", the bufferBinding.buffer'susagemust includeUNIFORM. The buffer is added to the[[usedBuffers]]map withUNIFORMflag. -
If layoutBinding.
typeis"storage-buffer"or"readonly-storage-buffer", the bufferBinding.buffer'susagemust includeSTORAGE. The buffer is added to the[[usedBuffers]]map withSTORAGEflag. -
The bound part designated by bufferBinding.
offsetand bufferBinding.sizemust reside inside the buffer.
10.3. GPUPipelineLayout
interface { };GPUPipelineLayout GPUPipelineLayout includes GPUObjectBase ;
10.3.1. Creation
dictionary :GPUPipelineLayoutDescriptor GPUObjectDescriptorBase {required sequence <GPUBindGroupLayout >; };bindGroupLayouts
11. Shader Modules
11.1. GPUShaderModule
[Serializable ]interface { };GPUShaderModule GPUShaderModule includes GPUObjectBase ;
GPUShaderModule is Serializable. It is a reference to an internal
shader module object, and Serializable means that the reference can be copied between realms (threads/workers), allowing multiple realms to access
it concurrently. Since GPUShaderModule is immutable, there are no race
conditions.
11.1.1. Shader Module Creation
dictionary :GPUShaderModuleDescriptor GPUObjectDescriptorBase {required DOMString ; };code
12. Pipelines
dictionary :GPUPipelineDescriptorBase GPUObjectDescriptorBase {required GPUPipelineLayout ; };layout
dictionary {GPUProgrammableStageDescriptor required GPUShaderModule ;module required DOMString ; // TODO: other stuff like specialization constants? };entryPoint
12.1. GPUComputePipeline
[Serializable ]interface { };GPUComputePipeline GPUComputePipeline includes GPUObjectBase ;
12.1.1. Creation
dictionary :GPUComputePipelineDescriptor GPUPipelineDescriptorBase {required GPUProgrammableStageDescriptor ; };computeStage
12.2. GPURenderPipeline
[Serializable ]interface { };GPURenderPipeline GPURenderPipeline includes GPUObjectBase ;
12.2.1. Creation
dictionary :GPURenderPipelineDescriptor GPUPipelineDescriptorBase {required GPUProgrammableStageDescriptor ;vertexStage GPUProgrammableStageDescriptor ;fragmentStage required GPUPrimitiveTopology ;primitiveTopology GPURasterizationStateDescriptor = {};rasterizationState required sequence <GPUColorStateDescriptor >;colorStates GPUDepthStencilStateDescriptor ;depthStencilState GPUVertexStateDescriptor = {};vertexState GPUSize32 = 1;sampleCount GPUSampleMask = 0xFFFFFFFF;sampleMask boolean =alphaToCoverageEnabled false ; // TODO: other properties };
-
sampleCount: Number of MSAA samples.
12.2.2. Primitive Topology
enum {GPUPrimitiveTopology ,"point-list" ,"line-list" ,"line-strip" ,"triangle-list" };"triangle-strip"
12.2.3. Rasterization State
dictionary {GPURasterizationStateDescriptor GPUFrontFace = "ccw";frontFace GPUCullMode = "none";cullMode GPUDepthBias = 0;depthBias float = 0;depthBiasSlopeScale float = 0; };depthBiasClamp
enum {GPUFrontFace ,"ccw" };"cw"
enum {GPUCullMode ,"none" ,"front" };"back"
12.2.4. Color State
dictionary {GPUColorStateDescriptor required GPUTextureFormat ;format GPUBlendDescriptor = {};alphaBlend GPUBlendDescriptor = {};colorBlend GPUColorWriteFlags = 0xF; // GPUColorWrite.ALL };writeMask
typedef [EnforceRange ]unsigned long ;GPUColorWriteFlags interface {GPUColorWrite const GPUColorWriteFlags = 0x1;RED const GPUColorWriteFlags = 0x2;GREEN const GPUColorWriteFlags = 0x4;BLUE const GPUColorWriteFlags = 0x8;ALPHA const GPUColorWriteFlags = 0xF; };ALL
12.2.4.1. Blend State
dictionary {GPUBlendDescriptor GPUBlendFactor = "one";srcFactor GPUBlendFactor = "zero";dstFactor GPUBlendOperation = "add"; };operation
enum {GPUBlendFactor ,"zero" ,"one" ,"src-color" ,"one-minus-src-color" ,"src-alpha" ,"one-minus-src-alpha" ,"dst-color" ,"one-minus-dst-color" ,"dst-alpha" ,"one-minus-dst-alpha" ,"src-alpha-saturated" ,"blend-color" };"one-minus-blend-color"
enum {GPUBlendOperation ,"add" ,"subtract" ,"reverse-subtract" ,"min" };"max"
enum {GPUStencilOperation ,"keep" ,"zero" ,"replace" ,"invert" ,"increment-clamp" ,"decrement-clamp" ,"increment-wrap" };"decrement-wrap"
12.2.5. Depth/Stencil State
dictionary {GPUDepthStencilStateDescriptor required GPUTextureFormat ;format boolean =depthWriteEnabled false ;GPUCompareFunction = "always";depthCompare GPUStencilStateFaceDescriptor = {};stencilFront GPUStencilStateFaceDescriptor = {};stencilBack GPUStencilValue = 0xFFFFFFFF;stencilReadMask GPUStencilValue = 0xFFFFFFFF; };stencilWriteMask
dictionary {GPUStencilStateFaceDescriptor GPUCompareFunction = "always";compare GPUStencilOperation = "keep";failOp GPUStencilOperation = "keep";depthFailOp GPUStencilOperation = "keep"; };passOp
12.2.6. Vertex State
enum {GPUIndexFormat ,"uint16" };"uint32"
12.2.6.1. Vertex Formats
The name of the format specifies the data type of the component, the number of values, and whether the data is normalized.
-
uchar= unsigned 8-bit value -
char= signed 8-bit value -
ushort= unsigned 16-bit value -
short= signed 16-bit value -
half= half-precision 16-bit floating point value -
float= 32-bit floating point value -
uint= unsigned 32-bit integer value -
int= signed 32-bit integer value
If no number of values is given in the name, a single value is provided.
If the format has the -bgra suffix, it means the values are arranged as
blue, green, red and alpha values.
enum {GPUVertexFormat ,"uchar2" ,"uchar4" ,"char2" ,"char4" ,"uchar2norm" ,"uchar4norm" ,"char2norm" ,"char4norm" ,"ushort2" ,"ushort4" ,"short2" ,"short4" ,"ushort2norm" ,"ushort4norm" ,"short2norm" ,"short4norm" ,"half2" ,"half4" ,"float" ,"float2" ,"float3" ,"float4" ,"uint" ,"uint2" ,"uint3" ,"uint4" ,"int" ,"int2" ,"int3" };"int4"
enum {GPUInputStepMode ,"vertex" };"instance"
dictionary {GPUVertexStateDescriptor GPUIndexFormat = "uint32";indexFormat sequence <GPUVertexBufferLayoutDescriptor ?>= []; };vertexBuffers
A vertex buffer is, conceptually, a view into buffer memory as an array of structures. arrayStride is the stride, in bytes, between elements of that array.
Each element of a vertex buffer is like a structure with a memory layout defined by its attributes, which describe the members of the structure.
Each GPUVertexAttributeDescriptor describes its format and its offset, in bytes, within the structure.
Each attribute appears as a separate input in a vertex shader, each bound by a numeric location,
which is specified by shaderLocation.
Every location must be unique within the GPUVertexStateDescriptor.
dictionary {GPUVertexBufferLayoutDescriptor required GPUSize64 ;arrayStride GPUInputStepMode = "vertex";stepMode required sequence <GPUVertexAttributeDescriptor >; };attributes
dictionary {GPUVertexAttributeDescriptor required GPUVertexFormat ;format required GPUSize64 ;offset required GPUIndex32 ; };shaderLocation
13. Command Buffers
13.1. GPUCommandBuffer
interface { };GPUCommandBuffer GPUCommandBuffer includes GPUObjectBase ;
13.1.1. Creation
dictionary :GPUCommandBufferDescriptor GPUObjectDescriptorBase { };
14. Command Encoding
14.1. GPUCommandEncoder
interface {GPUCommandEncoder GPURenderPassEncoder (beginRenderPass GPURenderPassDescriptor );descriptor GPUComputePassEncoder (beginComputePass optional GPUComputePassDescriptor = {});descriptor void copyBufferToBuffer (GPUBuffer ,source GPUSize64 ,sourceOffset GPUBuffer ,destination GPUSize64 ,destinationOffset GPUSize64 );size void (copyBufferToTexture GPUBufferCopyView ,source GPUTextureCopyView ,destination GPUExtent3D );copySize void (copyTextureToBuffer GPUTextureCopyView ,source GPUBufferCopyView ,destination GPUExtent3D );copySize void (copyTextureToTexture GPUTextureCopyView ,source GPUTextureCopyView ,destination GPUExtent3D );copySize void inlineUpdateBuffer (ArrayBuffer ,source GPUSize64 ,sourceOffset GPUBuffer ,destination GPUSize64 ,destinationOffset GPUSize64 );size void (pushDebugGroup DOMString );groupLabel void ();popDebugGroup void (insertDebugMarker DOMString );markerLabel GPUCommandBuffer (finish optional GPUCommandBufferDescriptor = {}); };descriptor GPUCommandEncoder includes GPUObjectBase ;
14.1.1. Creation
dictionary :GPUCommandEncoderDescriptor GPUObjectDescriptorBase { // TODO: reusability flag? };
14.2. Copy Commands
14.2.1. GPUBufferCopyView
dictionary GPUBufferCopyView {required GPUBuffer ;buffer GPUSize64 = 0;offset required GPUSize32 bytesPerRow ;GPUSize32 rowsPerImage = 0; };
A GPUBufferCopyView is a view of a buffer as an array of images,
used when copying data between a texture and a buffer.
-
For
2dtextures, data is copied between one image and one array layer. -
For
3dtextures, data is copied between one image and one depth slice.
bytesPerRow, of type GPUSize32-
The stride, in bytes, between the beginning of each row of data and the subsequent row.
rowsPerImage, of type GPUSize32, defaulting to0-
rowsPerImage×bytesPerRowis the stride, in bytes, between the beginning of each image of data and the subsequent image.Note:
rowsPerImagemust be zero for copies with acopySize.depthof 1, and must be greater than zero otherwise.
14.2.2. GPUTextureCopyView
dictionary GPUTextureCopyView {required GPUTexture ;texture GPUIntegerCoordinate = 0;mipLevel GPUIntegerCoordinate = 0;arrayLayer GPUOrigin3D = {}; };origin
A GPUTextureCopyView is a view of a sub-region of a texture subresource with the initial offset GPUOrigin3D in
texels, used when copying data from or to a GPUTexture.
-
For
2dtextures, data is copied from or to one mipmap level and one array layer of the texture. -
origin: If unspecified, defaults to[0, 0, 0].
Define the copies with 1d and 3d textures. <https://github.com/gpuweb/gpuweb/issues/69>
14.2.3. GPUImageBitmapCopyView
dictionary GPUImageBitmapCopyView {required ImageBitmap ;imageBitmap GPUOrigin2D = {}; };origin
-
origin: If unspecified, defaults to[0, 0].
14.2.4. copyBufferToBuffer(source, sourceOffset, destination, destinationOffset, size)
Arguments:
-
GPUBuffersource -
GPUSize64sourceOffset -
GPUBufferdestination -
GPUSize64destinationOffset -
GPUSize64size
Returns: void
Encode a command into the GPUCommandEncoder that copies size bytes of data from the sourceOffset of a GPUBuffer source to the destinationOffset of another GPUBuffer destination.
Given a GPUCommandEncoder encoder and the arguments GPUBuffer source, GPUSize64 sourceOffset, GPUBuffer destination, GPUSize64 destinationOffset, GPUSize64 size, the following validation rules apply:
-
encoder must be a valid
GPUCommandEncoder. -
encoder.
copyBufferToBuffer()must not be called when aGPURenderPassEncoderis active on encoder. -
encoder.
copyBufferToBuffer()must not be called when aGPUComputePassEncoderis active on encoder. -
size must be a multiple of 4.
-
sourceOffset must be a multiple of 4.
-
destinationOffset must be a multiple of 4.
-
(sourceOffset + size) must not overflow a
GPUSize64. -
(destinationOffset + size) must not overflow a
GPUSize64. -
The
[[size]]of source must be greater than or equal to (sourceOffset + size). -
The
[[size]]of destination must be greater than or equal to (destinationOffset + size). -
If source and destination are the same buffer, the copy range from sourceOffset to (sourceOffset + size) must not overlap with the copy range from destinationOffset to (destinationOffset + size).
Define the state machine for GPUCommandEncoder. <https://github.com/gpuweb/gpuweb/issues/21>
figure out how to handle overflows in the spec. <https://github.com/gpuweb/gpuweb/issues/69>
14.2.5. inlineUpdateBuffer(source, sourceOffset, destination, destinationOffset, size)
It’s often useful for applications to update buffer data prior to draw or compute operations. For example, updating model-view and projection matrices before or interleaved with rendering of a scene. When these uploads are small, it’s viable to inline the update data into the command buffer. This does require more copies than other upload paths, but for small data sizes this overhead is negligible. Implementations are expected to warn against using this for medium-to-large buffer updates. (e.g. >64k)
In Vulkan, this is similar to vkCmdUpdateBuffer. In D3D12, implementations can leverage |ID3D12GraphicsCommandList2::WriteBufferImmediate|. Metal might use |makeBuffer(bytesNoCopy:length:options:deallocator:)| around some section of shared command buffer serialization memory.
Arguments:
-
ArrayBuffersource -
GPUSize64sourceOffset -
GPUBufferdestination -
GPUSize64destinationOffset -
GPUSize64size
Returns: void
Embed a copy of source from sourceOffset to size into the GPUCommandEncoder.
Encode a command into the GPUCommandEncoder that copies size bytes of data from embedded copy to the destinationOffset of another GPUBuffer destination.
Given a GPUCommandEncoder encoder and the arguments ArrayBuffer source, GPUSize64 sourceOffset, GPUBuffer destination, GPUSize64 destinationOffset, GPUSize64 size, the following validation rules apply:
-
encoder must be a valid
GPUCommandEncoder. -
encoder.
inlineUpdateBuffer()must not be called when aGPURenderPassEncoderis active on encoder. -
encoder.
inlineUpdateBuffer()must not be called when aGPUComputePassEncoderis active on encoder. -
size must be a multiple of 4.
-
sourceOffset must be a multiple of 4.
-
destinationOffset must be a multiple of 4.
-
(sourceOffset + size) must not overflow a
GPUSize64. -
(destinationOffset + size) must not overflow a
GPUSize64. -
The
byteLengthof source must be greater than or equal to (sourceOffset + size). -
The
[[size]]of destination must be greater than or equal to (destinationOffset + size).
14.3. Programmable Passes
interface mixin {GPUProgrammablePassEncoder void (setBindGroup GPUIndex32 ,index GPUBindGroup ,bindGroup optional sequence <GPUBufferDynamicOffset >= []);dynamicOffsets void (setBindGroup GPUIndex32 ,index GPUBindGroup ,bindGroup Uint32Array ,dynamicOffsetsData GPUSize64 ,dynamicOffsetsDataStart GPUSize32 );dynamicOffsetsDataLength void (pushDebugGroup DOMString );groupLabel void ();popDebugGroup void (insertDebugMarker DOMString ); };markerLabel
Debug groups in a GPUCommandEncoder or GPUProgrammablePassEncoder must be well nested.
15. Compute Passes
15.1. GPUComputePassEncoder
interface {GPUComputePassEncoder void (setPipeline GPUComputePipeline );pipeline void (dispatch GPUSize32 ,x optional GPUSize32 = 1,y optional GPUSize32 = 1);z void (dispatchIndirect GPUBuffer ,indirectBuffer GPUSize64 );indirectOffset void (); };endPass GPUComputePassEncoder includes GPUObjectBase ;GPUComputePassEncoder includes GPUProgrammablePassEncoder ;
15.1.1. Creation
dictionary :GPUComputePassDescriptor GPUObjectDescriptorBase { };
16. Render Passes
16.1. GPURenderPassEncoder
interface mixin {GPURenderEncoderBase void (setPipeline GPURenderPipeline );pipeline void (setIndexBuffer GPUBuffer ,buffer optional GPUSize64 = 0,offset optional GPUSize64 = 0);size void (setVertexBuffer GPUIndex32 ,slot GPUBuffer ,buffer optional GPUSize64 = 0,offset optional GPUSize64 = 0);size void (draw GPUSize32 ,vertexCount GPUSize32 ,instanceCount GPUSize32 ,firstVertex GPUSize32 );firstInstance void (drawIndexed GPUSize32 ,indexCount GPUSize32 ,instanceCount GPUSize32 ,firstIndex GPUSignedOffset32 ,baseVertex GPUSize32 );firstInstance void (drawIndirect GPUBuffer ,indirectBuffer GPUSize64 );indirectOffset void (drawIndexedIndirect GPUBuffer ,indirectBuffer GPUSize64 ); };indirectOffset interface {GPURenderPassEncoder void (setViewport float ,x float ,y float ,width float ,height float ,minDepth float );maxDepth void (setScissorRect GPUIntegerCoordinate ,x GPUIntegerCoordinate ,y GPUIntegerCoordinate ,width GPUIntegerCoordinate );height void (setBlendColor GPUColor );color void (setStencilReference GPUStencilValue );reference void (executeBundles sequence <GPURenderBundle >);bundles void (); };endPass GPURenderPassEncoder includes GPUObjectBase ;GPURenderPassEncoder includes GPUProgrammablePassEncoder ;GPURenderPassEncoder includes GPURenderEncoderBase ;
-
setIndexBuffer()/setVertexBuffer():-
If
sizeis zero, the remaining size (afteroffset) of theGPUBufferis used.
-
-
In indirect draw calls, the base instance field (inside the indirect buffer data) must be set to zero.
-
-
An error is generated if
widthorheightis not greater than 0.
-
When a GPURenderPassEncoder is created, it has the following default state:
-
Viewport:
-
x, y=0.0, 0.0 -
width, height= the dimensions of the pass’s render targets -
minDepth, maxDepth=0.0, 1.0
-
-
Scissor rectangle:
-
x, y=0, 0 -
width, height= the dimensions of the pass’s render targets
-
When a GPURenderBundle is executed, it does not inherit the pass’s pipeline,
bind groups, or vertex or index buffers. After a GPURenderBundle has executed,
the pass’s pipeline, bind groups, and vertex and index buffers are cleared. If zero GPURenderBundles are executed, the command buffer state is unchanged.
16.1.1. Creation
dictionary :GPURenderPassDescriptor GPUObjectDescriptorBase {required sequence <GPURenderPassColorAttachmentDescriptor >;colorAttachments GPURenderPassDepthStencilAttachmentDescriptor ; };depthStencilAttachment
16.1.1.1. Color Attachments
dictionary {GPURenderPassColorAttachmentDescriptor required GPUTextureView ;attachment GPUTextureView ;resolveTarget required (GPULoadOp or GPUColor );loadValue GPUStoreOp = "store"; };storeOp
16.1.1.2. Depth/Stencil Attachments
dictionary {GPURenderPassDepthStencilAttachmentDescriptor required GPUTextureView ;attachment required (GPULoadOp or float );depthLoadValue required GPUStoreOp ;depthStoreOp required (GPULoadOp or GPUStencilValue );stencilLoadValue required GPUStoreOp ; };stencilStoreOp
16.1.2. Load & Store Operations
enum {GPULoadOp };"load"
enum {GPUStoreOp ,"store" };"clear"
17. Bundles
17.1. GPURenderBundle
interface { };GPURenderBundle GPURenderBundle includes GPUObjectBase ;
17.1.1. Creation
dictionary :GPURenderBundleDescriptor GPUObjectDescriptorBase { };
interface {GPURenderBundleEncoder GPURenderBundle (finish optional GPURenderBundleDescriptor = {}); };descriptor GPURenderBundleEncoder includes GPUObjectBase ;GPURenderBundleEncoder includes GPUProgrammablePassEncoder ;GPURenderBundleEncoder includes GPURenderEncoderBase ;
17.1.2. Encoding
dictionary :GPURenderBundleEncoderDescriptor GPUObjectDescriptorBase {required sequence <GPUTextureFormat >;colorFormats GPUTextureFormat ;depthStencilFormat GPUSize32 = 1; };sampleCount
18. Queues
interface {GPUQueue void (submit sequence <GPUCommandBuffer >);commandBuffers GPUFence (createFence optional GPUFenceDescriptor = {});descriptor void (signal GPUFence ,fence GPUFenceValue );signalValue void (copyImageBitmapToTexture GPUImageBitmapCopyView ,source GPUTextureCopyView ,destination GPUExtent3D ); };copySize GPUQueue includes GPUObjectBase ;
submit(commandBuffers) does nothing and produces an error if any of the following is true:
-
Any
GPUBufferreferenced in any element ofcommandBuffersisn’t in the"unmapped"buffer state. -
Any of the usage scopes contained in the command buffers fail the usage scope validation.
18.1. GPUFence
interface {GPUFence GPUFenceValue ();getCompletedValue Promise <void >(onCompletion GPUFenceValue ); };completionValue GPUFence includes GPUObjectBase ;
18.1.1. Creation
dictionary :GPUFenceDescriptor GPUObjectDescriptorBase {GPUFenceValue = 0; };initialValue
19. Canvas Rendering & Swap Chains
interface {GPUCanvasContext GPUSwapChain (configureSwapChain GPUSwapChainDescriptor );descriptor Promise <GPUTextureFormat >(getSwapChainPreferredFormat GPUDevice ); };device
-
configureSwapChain(): Configures the swap chain for this canvas, and returns a newGPUSwapChainobject representing it. Destroys any swapchain previously returned byconfigureSwapChain, including all of the textures it has produced.
dictionary :GPUSwapChainDescriptor GPUObjectDescriptorBase {required GPUDevice ;device required GPUTextureFormat ;format GPUTextureUsageFlags = 0x10; // GPUTextureUsage.OUTPUT_ATTACHMENT };usage
interface {GPUSwapChain GPUTexture (); };getCurrentTexture GPUSwapChain includes GPUObjectBase ;
In the "update the rendering [of the] Document" step of the "Update the rendering" HTML processing
model, the contents of the GPUTexture most recently returned by getCurrentTexture() are used to update the rendering for the canvas, and it is as
if destroy() were called on it (making it unusable elsewhere in WebGPU).
Before this drawing buffer is presented for compositing, the implementation shall ensure that all rendering operations have been flushed to the drawing buffer.
20. Errors & Debugging
20.1. Fatal Errors
interface {GPUDeviceLostInfo readonly attribute DOMString ; };message partial interface GPUDevice {readonly attribute Promise <GPUDeviceLostInfo >; };lost
20.2. Error Scopes
enum {GPUErrorFilter ,"none" ,"out-of-memory" };"validation"
interface {GPUOutOfMemoryError (); };constructor interface {GPUValidationError (constructor DOMString );message readonly attribute DOMString ; };message typedef (GPUOutOfMemoryError or GPUValidationError );GPUError
partial interface GPUDevice {void (pushErrorScope GPUErrorFilter );filter Promise <GPUError ?>(); };popErrorScope
popErrorScope() throws OperationError if there are no error scopes on the stack. popErrorScope() rejects with OperationError if the device is lost.
20.3. Telemetry
[
Exposed =(Window , DedicatedWorker )
]
interface GPUUncapturedErrorEvent : Event {
constructor (
DOMString type ,
GPUUncapturedErrorEventInit gpuUncapturedErrorEventInitDict
);
[SameObject ] readonly attribute GPUError error ;
};
dictionary GPUUncapturedErrorEventInit : EventInit {
required GPUError error ;
};
partial interface GPUDevice { [Exposed =(Window ,DedicatedWorker )]attribute EventHandler ; };onuncapturederror
21. Type Definitions
typedef [EnforceRange ]unsigned long ;GPUBufferDynamicOffset typedef [EnforceRange ]unsigned long long ;GPUFenceValue 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
21.1. Colors & Vectors
dictionary {GPUColorDict required double ;r required double ;g required double ;b required double ; };a typedef (sequence <double >or GPUColorDict );GPUColor
Note: double is large enough to precisely hold 32-bit signed/unsigned
integers and single-precision floats.
dictionary {GPUOrigin2DDict GPUIntegerCoordinate = 0;x GPUIntegerCoordinate = 0; };y typedef (sequence <GPUIntegerCoordinate >or GPUOrigin2DDict );GPUOrigin2D
dictionary {GPUOrigin3DDict GPUIntegerCoordinate = 0;x GPUIntegerCoordinate = 0;y GPUIntegerCoordinate = 0; };z typedef (sequence <GPUIntegerCoordinate >or GPUOrigin3DDict );GPUOrigin3D
dictionary {GPUExtent3DDict required GPUIntegerCoordinate ;width required GPUIntegerCoordinate ;height required GPUIntegerCoordinate ; };depth typedef (sequence <GPUIntegerCoordinate >or GPUExtent3DDict );GPUExtent3D
An Extent3D is a GPUExtent3D. Extent3D is a spec namespace for the following definitions:
GPUExtent3D value extent, depending on its type, the syntax:
-
extent.width refers to either
GPUExtent3DDict.widthor the first item of the sequence. -
extent.height refers to either
GPUExtent3DDict.heightor the second item of the sequence. -
extent.depth refers to either
GPUExtent3DDict.depthor the third item of the sequence.
typedef sequence <(GPUBuffer or ArrayBuffer )>;GPUMappedBuffer
GPUMappedBuffer is always a sequence of 2 elements, of types GPUBuffer and ArrayBuffer, respectively.
22. Temporary usages of non-exported dfns
Eventually all of these should disappear but they are useful to avoid warning while building the specification.