Expand description
wgpu is a cross-platform, safe, pure-Rust graphics API. It runs natively on
Vulkan, Metal, D3D12, and OpenGL; and on top of WebGL2 and WebGPU on wasm.
The API is based on the WebGPU standard, but is a fully native Rust library. It serves as the core of the WebGPU integration in Firefox, Servo, and Deno.
§Getting Started
The main entry point to the API is the Instance type, from which you can create Adapter, Device, and Surface.
If you are new to wgpu and graphics programming, we recommend starting with Learn Wgpu.
Additionally, WebGPU Fundamentals is a tutorial for WebGPU which is very similar to our API, minus differences between Rust and Javascript.
We have a wiki which has information on useful architecture patterns, debugging tips, and more getting started information.
There are examples for this version available on GitHub.
The API is refcounted, so all handles are cloneable, and if you create a resource which references another, it will automatically keep dependent resources alive.
wgpu uses the coordinate systems of D3D and Metal. Depth ranges from [0, 1].
| Render | Texture |
|---|---|
![]() | ![]() |
wgpu’s MSRV is 1.87.
§Extension Specifications
While the core of wgpu is based on the WebGPU standard, we also support extensions that allow for features that the standard does not have yet.
For high-level documentation on how to use these extensions, see documentation on Features or the relevant specification:
🧪EXPERIMENTAL🧪 APIs are subject to change and may allow undefined behavior if used incorrectly.
- 🧪EXPERIMENTAL🧪 Ray Tracing.
- 🧪EXPERIMENTAL🧪 Mesh Shading.
§Shader Support
wgpu can consume shaders in WGSL, SPIR-V, and GLSL.
Both HLSL and GLSL
have compilers to target SPIR-V. All of these shader languages can be used with any backend as we handle all of the conversions. Additionally, support for these shader inputs is not going away.
While WebGPU does not support any shading language other than WGSL, we will automatically convert your non-WGSL shaders if you’re running on WebGPU.
WGSL is always supported by default, but GLSL and SPIR-V need features enabled to compile in support.
To enable WGSL shaders, enable the wgsl feature of wgpu (enabled by default).
To enable SPIR-V shaders, enable the spirv feature of wgpu.
To enable GLSL shaders, enable the glsl feature of wgpu.
§Feature flags
§Backends
dx12(enabled by default) — Enables the DX12 backend on Windows.metal(enabled by default) — Enables the Metal backend on macOS & iOS.vulkan(enabled by default) — Enables the Vulkan backend on Windows, Linux, and Android.gles(enabled by default) — Enables the OpenGL/GLES backend on Windows, Linux, Android, and Emscripten.webgpu(enabled by default) — Enables the WebGPU backend on WebAssembly.
§Conditional Backends
angle— Enables the GLES backend on macOS only for use with ANGLE.vulkan-portability— Enables the Vulkan backend on macOS & iOS only for use with MoltenVK.webgl— Enables the GLES backend on WebAssembly only.
§Backend features
-
drm— Support creating textures from DRM display/window handles. -
noop— Enables the noop backend for testing.This backend allows creating resources such as buffers and textures, but performs no computation. Because it lacks basic functionality, it is only actually used if explicitly enabled through
NoopBackendOptions.
Note: In the documentation, if you see that an item depends on a backend, it means that the item is only available when that backend is enabled and the backend is supported on the current platform.
§Shading language support
These features enable support for that input language on all platforms. We will translate the input language to whatever the backend requires.
spirv— Enable accepting SPIR-V shaders as input.glsl— Enable accepting GLSL shaders as input.wgsl(enabled by default) — Enable accepting WGSL shaders as input.naga-ir— Enable accepting naga IR shaders as input.
§Assertions and Serialization
strict_asserts— Apply run-time checks, even in release builds. These are in addition to the validation carried out at public APIs in all builds.serde— Enables serialization viaserdeon common wgpu types.
§External libraries
The following features facilitate integration with third-party supporting libraries.
-
static-dxc— Enables statically linking DXC.Normally, to use the modern DXC shader compiler with wgpu, the final application must be shipped alongside
dxcompiler.dll(min v1.8.2502) (which can be downloaded from Microsoft’s GitHub). This feature statically links a version of DXC so that no external binaries are required to compile DX12 shaders.
§Other
-
counters— Internally count resources and events for debugging purposes. If the counters feature is disabled, the counting infrastructure is removed from the build and the exposed counters always return 0. -
fragile-send-sync-non-atomic-wasm— ImplementSendandSyncon Wasm, but only if atomics are not enabled.WebGL/WebGPU objects can not be shared between threads. However, it can be useful to artificially mark them as
SendandSyncanyways to make it easier to write cross-platform code. This is technically very unsafe in a multithreaded environment, but on a wasm binary compiled without atomics is a definitionally single-threaded environment. -
web(enabled by default) — Use web-specific libraries on WASMThose libraries (wasm-bindgen, web-sys, js-sys) can only be used when there is a JavaScript context around the WASM VM, e.g., when the WASM binary is used in a browser.
-
std(enabled by default) — Enables use of the standard library withinwgpuand its dependencies.This can allow for better error reporting and for improved multithreading support.
-
parking_lot(enabled by default) — Usesparking_lotas the implementation for locking primitives.This is a recommended feature for most users and should only be disabled when required, e.g., for
no_stdsupport. If disabled, eitherstd::sync::Mutexorcore::cell::RefCellwill be used, based on whetherstdis enabled or not. -
exhaust— Enablesexhaustmethod forTextureFormatofwgpu-types.This is relevant for
wgpu-info.
§Feature Aliases
These features aren’t actually features on the crate itself, but a convenient shorthand for complicated cases.
wgpu_core— Enabled when there is any non-webgpu backend enabled on the platform.naga— Enabled when targetglslorspirvinput is enabled, or whenwgpu_coreis enabled.
Re-exports§
pub extern crate wgpu_hal as hal;pub extern crate wgpu_core as wgc;pub extern crate wgpu_types as wgt;
Re-exports§
Re-exports§pub use ::wgc::naga;wgpu_coreornagapub use raw_window_handle as rwh;
Modules§
Modules§api 🔒Types and functions which define our public api and their helper functionality.backend 🔒cmp 🔒We need to implPartialEq,Eq,PartialOrd,Ord, andHashfor all handle types in wgpu.customcustomProvides wrappers custom backend implementationsdispatch 🔒Infrastructure for dispatching calls to the appropriate “backend”. The “backends” are:macros 🔒Convenience macrosutilUtility structures and functions that are built on top of the mainwgpuAPI.
Macros§
Macros§include_spirv_ raw Macro to load raw SPIR-V data statically, for use withFeatures::PASSTHROUGH_SHADERS.include_wgsl Load WGSL source code from a file at compile time.vertex_attr_ array Macro to produce an array ofVertexAttribute.
Structs§
Structs§AdapterHandle to a physical graphics and/or compute device.AdapterInfo Information about an adapter.AllocatorReport A report that can be generated for informational purposes usingAllocator::generate_report().BackendOptions Options that are passed to a given backend.BackendsRepresents the backends that wgpu will use.BindGroup Handle to a binding group.BindGroup Descriptor Describes a group of bindings and the resources to be bound.BindGroup Entry An element of aBindGroupDescriptor, consisting of a bindable resource and the slot to bind it to.BindGroup Layout Handle to a binding group layout.BindGroup Layout Descriptor Describes aBindGroupLayout.BindGroup Layout Entry Describes a single binding inside a bind group.BlasBottom Level Acceleration Structure (BLAS).BlasAabb Geometry Definition for an axis-aligned bounding box geometry group for a bottom level acceleration structure.BlasAsync Error Error occurred when trying to asynchronously prepare a blas for compaction.BlasBuild Entry Builds the given sets of geometry into the given Blas.BlasTriangle Geometry Definition for a triangle geometry for a Bottom Level Acceleration Structure (BLAS).BlendComponent Describes a blend component of aBlendState.BlendState Describe the blend state of a render pipeline, withinColorTargetState.BufferHandle to a GPU-accessible buffer.BufferAsync Error Error occurred when trying to async map a buffer.BufferBinding Describes the segment of a buffer to bind.BufferSlice A slice of aBuffer, to be mapped, used for vertex or index data, or the like.BufferTexture Copy Info Information about a copy between a buffer and a texture.BufferTransition A buffer transition for use withCommandEncoder::transition_resources.BufferUsages Different ways that you can use a buffer.BufferUses Similar toBufferUsages, but used only forCommandEncoder::transition_resources.BufferView A read-only view of a mapped buffer’s bytes.BufferView Mut A write-only view of a mapped buffer’s bytes.ColorRGBA double precision color.ColorTarget State Describes the color state of a render pipeline.ColorWrites Color write mask. Disabled color channels will not be written to.CommandBuffer Handle to a command buffer on the GPU.CommandBuffer Descriptor Describes aCommandBuffer.CommandEncoder Encodes a series of GPU operations.CompilationInfo Compilation information for a shader module.CompilationMessage A single message from the shader compilation process.ComputePass In-progress recording of a compute pass.ComputePass Descriptor Describes the attachments of a compute pass.ComputePass Timestamp Writes Describes the timestamp writes of a compute pass.ComputePipeline Handle to a compute pipeline.ComputePipeline Descriptor Describes a compute pipeline.ContextBlas Aabb Geometry Context version of BlasAabbGeometry.ContextBlas Build Entry Context version see BlasBuildEntry.ContextBlas Triangle Geometry Context version of BlasTriangleGeometry.CooperativeMatrix Properties Describes a supported cooperative matrix configuration.CopyExternal Image Dest Info View of a texture which can be used to copy to a texture, including color space and alpha premultiplication information.CoreCounters wgpu-core’s part ofInternalCounters.CreateSurface Error Instance::create_surface()or a related function failed.DepthBias State Describes the biasing setting for the depth target.DepthStencil State Describes the depth/stencil state in a render pipeline.DeviceOpen connection to a graphics and/or compute device.DownlevelCapabilities Lists various ways the underlying platform does not conform to the WebGPU standard.DownlevelFlags Binary flags listing features that may or may not be present on downlevel adapters.DownlevelLimits Represents the sets of additional limits on an adapter, which take place when running on downlevel backends.Dx12Backend Options Configuration for the DX12 backend.ErrorScope Guard Guard for an error scope pushed withDevice::push_error_scope().ExperimentalFeatures Token of the user agreeing to access experimental features.Extent3dExtent of a texture related operation.ExternalTexture Handle to an external texture on the GPU.ExternalTexture Transfer Function Parameters describing a gamma encoding transfer function in the form tf = { k * linear | linear < b { a * pow(linear, 1/g) - (a-1) | linear >= bFeaturesFeatures that are not guaranteed to be supported.FeaturesWGPUFeatures that are not guaranteed to be supported.FeaturesWebGPU Features that are not guaranteed to be supported.ForceShader Model Token Used to force wgpu to expose certain features on passthrough shaders even when those features aren’t present on runtime-compiled shadersFragmentState Describes the fragment processing in a render pipeline.GlBackendOptions Configuration for the OpenGL/OpenGLES backend.HalCounterswgpu-hal’s part ofInternalCounters.ImageSubresource Range Subresource range within an imageInstanceContains the various entry points to start interacting with the system’s GPUs.InstanceDescriptor Options for creating an instance.InstanceFlags Instance debugging flags.InternalCounters All internal counters, exposed for debugging purposes.LimitsRepresents the sets of limits an adapter/device supports.LoadOpDont Care Token of the user agreeing to useLoadOp::DontCare.MapRangeError Error returned byBufferSlice::get_mapped_rangeandBufferSlice::get_mapped_range_mut.MemoryBudget Thresholds Memory budget thresholds used by backends to try to avoid high memory pressure situations.MeshPipeline Descriptor Describes a mesh shader (graphics) pipeline.MeshState Describes the mesh shader stage in a mesh shader pipeline.MultisampleState Describes the multi-sampling state of a render pipeline.NoopBackend Options Configuration for the noop backend.OperationsPair of load and store operations for an attachment aspect.Origin2dOrigin of a copy from a 2D image.Origin3dOrigin of a copy to/from a texture.PassthroughShader Entry Point Describes a single entry point in a passthrough shader descriptor.PipelineCache Handle to a pipeline cache, which is used to accelerate creatingRenderPipelines andComputePipelines in subsequent executionsPipelineCache Descriptor Describes a pipeline cache, which allows reusing compilation work between program runs.PipelineCompilation Options Advanced options for use when a pipeline is compiledPipelineLayout Handle to a pipeline layout.PipelineLayout Descriptor Describes aPipelineLayout.PipelineStatistics Types Flags for which pipeline data should be recorded in a query.PresentationTimestamp Nanosecond timestamp used by the presentation engine.PrimitiveState Describes the state of primitive assembly and rasterization in a render pipeline.QuerySet Handle to a query set.QueueHandle to a command queue on a device.QueueWrite Buffer View A write-only view into a staging buffer.RenderBundle Pre-prepared reusable bundle of GPU operations.RenderBundle Depth Stencil Describes the depth/stencil attachment for render bundles.RenderBundle Encoder Encodes a series of GPU operations into a reusable “render bundle”.RenderBundle Encoder Descriptor Describes aRenderBundleEncoder.RenderPass In-progress recording of a render pass: a list of render commands in aCommandEncoder.RenderPass Color Attachment Describes a color attachment to aRenderPass.RenderPass Depth Stencil Attachment Describes a depth/stencil attachment to aRenderPass.RenderPass Descriptor Describes the attachments of a render pass.RenderPass Timestamp Writes Describes the timestamp writes of a render pass.RenderPipeline Handle to a rendering (graphics) pipeline.RenderPipeline Descriptor Describes a render (graphics) pipeline.RequestAdapter Options Base Options for requesting adapter.RequestDevice Error Requesting a device from anAdapterfailed.SamplerHandle to a sampler.ShaderModule Handle to a compiled shader module.ShaderModule Descriptor Descriptor for use withDevice::create_shader_module.ShaderRuntime Checks Describes how shader bound checks should be performed.ShaderStages Describes the shader stages that a binding will be visible from.SourceLocation A human-readable representation for a span, tailored for text source.StencilFace State Describes stencil state in a render pipeline.StencilState State of the stencil operation (fixed-pipeline stage).SubmissionIndex Identifier for a particular call toQueue::submit. Can be used as part of an argument toDevice::pollto block for a particular submission to finish.SurfaceHandle to a presentable surface.SurfaceCapabilities Defines the capabilities of a given surface and adapter.SurfaceTexture Surface texture that can be rendered to. Result of a successful call toSurface::get_current_texture.TaskState Describes the task shader stage in a mesh shader pipeline.TexelCopy Buffer Info Base View of a buffer which can be used to copy to/from a texture.TexelCopy Buffer Layout Layout of a texture in a buffer’s memory.TexelCopy Texture Info Base View of a texture which can be used to copy to/from a buffer/texture.TextureHandle to a texture on the GPU.TextureChannel Represents the different format channels of a texture format.TextureFormat Feature Flags Feature flags for a texture format.TextureFormat Features Features supported by a given texture formatTextureTransition A texture transition for use withCommandEncoder::transition_resources.TextureUsages Different ways that you can use a texture.TextureUses Similar toTextureUsages, but used only forCommandEncoder::transition_resources.TextureView Handle to a texture view.TlasTop Level Acceleration Structure (TLAS).TlasInstance Safe instance for a Tlas.VertexAttribute Vertex inputs (attributes) to shaders.VertexBuffer Layout Specifies an interpretation of the bytes of a vertex buffer as vertex attributes.VertexState Describes the vertex processing in a render pipeline.WgslLanguage Features WGSL language extensions.WriteOnly Like&'a mut T, but allows only write operations.WriteOnly Iter Iterator over the elements ofWriteOnly<[T]>.
Enums§
Enums§AddressMode How edges should be handled in texture addressing.AstcBlock ASTC block dimensionsAstcChannel ASTC RGBA channelBackendBackends supported by wgpu.BindingResource Resource to be bound by aBindGroupfor use with a pipeline.BindingType Type of a binding in a bind group layout.BlasGeometries Contains the sets of geometry that go into a Blas.BlendFactor Alpha blend factor.BlendOperation Alpha blend operation.BufferBinding Type Specific type of a buffer binding.CompareFunction Comparison function used for depth and stencil operations.CompilationMessage Type The type of a compilation message.CompositeAlpha Mode Specifies how the alpha channel of the textures should be handled during compositing.ContextBlas Geometries Context version of BlasGeometries.CooperativeScalar Type The underlying scalar type of the cooperative matrix component.CurrentSurface Texture Result of a call toSurface::get_current_texture.DeviceLost Reason Corresponds to aGPUDeviceLostReason.DeviceType Supported physical device types.Dx12Compiler Selects which DX12 shader compiler to use.Dx12Swapchain Kind Selects which kind of swapchain to use on DX12.Dx12UseFrame Latency Waitable Object Whether and how to use a waitable handle obtained fromGetFrameLatencyWaitableObject.DxcShaderModel DXC shader model.ErrorErrors resulting from usage of GPU APIs.ErrorFilter Kinds ofErrors aDevice::push_error_scope()may be configured to catch.ExternalTexture Format Format of anExternalTexture. This indicates the number of underlying planes used by theExternalTextureas well as each plane’s format.FaceFace of a vertex.FilterMode Texel mixing mode when sampling between texels.FrontFace Vertex winding order which classifies the “front” face of a triangle.GlDebugFns Controls whether OpenGL debug functions are enabled.GlFenceBehavior Dictate the behavior of fences in OpenGL.Gles3Minor Version Selects which OpenGL ES 3 minor version to request.IndexFormat Format of indices used with pipeline.LoadOpOperation to perform to the output attachment at the start of a render pass.MapModeType of buffer mapping.MemoryHints Hints to the device about the memory allocation strategy.MipmapFilter Mode Texel mixing mode when sampling between texels.PollError Error states after a device poll.PollStatus Status of device poll operation.PolygonMode Type of drawing mode for polygonsPowerPreference Power Preference when choosing a physical adapter.PredefinedColor Space Color spaces supported on the web.PresentMode Timing and queueing with which frames are actually displayed to the user.PrimitiveTopology Primitive type the input mesh is composed of.QueryType Type of queries contained in aQuerySet.RequestAdapter Error Error whenInstance::request_adapter()fails.SamplerBinding Type Specific type of a sampler binding.SamplerBorder Color Color variation to use when sampler addressing mode isAddressMode::ClampToBorderShaderModel Collections of shader features a device supports if they support less than WebGPU normally allows.ShaderSource Source of a shader module.StencilOperation Operation to perform on the stencil value.StorageTexture Access Specific type of a sample in a texture binding.StoreOpOperation to perform to the output attachment at the end of a render pass.SurfaceStatus Status of the received surface image.SurfaceTarget The window/canvas/surface/swap-chain/etc. a surface is attached to, for use with safe surface creation.SurfaceTarget Unsafe The window/canvas/surface/swap-chain/etc. a surface is attached to, for use with unsafe surface creation.TextureAspect Selects a subset of the data aTextureholds.TextureDimension Dimensionality of a texture.TextureFormat Format in which a texture’s texels are stored in GPU memory.TextureSample Type Specific type of a sample in a texture binding.TextureView Dimension Dimensions of a particular texture view.TraceControls API call tracing and specifies where the trace is written.VertexFormat Vertex Format for aVertexAttribute(input).VertexStep Mode Whether a vertex buffer is indexed by vertex or by instance.
Constants§
Constants§AABB_GEOMETRY_ MIN_ STRIDE Minimum stride for AABB geometry (24 bytes: twovec3<f32>). Minimum stride for AABB geometry (24 bytes: twovec3<f32>).COPY_BUFFER_ ALIGNMENT Buffer to buffer copy as well as buffer clear offsets and sizes must be aligned to this number.COPY_BYTES_ PER_ ROW_ ALIGNMENT Buffer-texture copies must havebytes_per_rowaligned to this number.IMMEDIATE_DATA_ ALIGNMENT Ranges of writes to immediate data must be at least this aligned.MAP_ALIGNMENT Minimum alignment of buffer mappings.MAXIMUM_SUBGROUP_ MAX_ SIZE The maximum allowed value forAdapterInfo::subgroup_max_size.MINIMUM_SUBGROUP_ MIN_ SIZE The minimum allowed value forAdapterInfo::subgroup_min_size.QUERY_RESOLVE_ BUFFER_ ALIGNMENT An offset into the query resolve buffer has to be aligned to this.QUERY_SET_ MAX_ QUERIES Maximum number of query result slots that can be requested in aQuerySetDescriptor.QUERY_SIZE Size in bytes of a single piece of query data.VERTEX_ALIGNMENT Vertex buffer offsets and strides have to be a multiple of this number.VERTEX_STRIDE_ ALIGNMENT Deprecated Vertex buffer strides have to be a multiple of this number.
Traits§
Traits§DisplayAndWindow Handle Super trait for a pair of display and window handles as used inSurfaceTarget.UncapturedError Handler The callback ofDevice::on_uncaptured_error().WasmNotSend WasmNotSend Sync WasmNotSync WindowHandle Send/Syncblanket trait for [HasWindowHandle] used inSurfaceTarget.
Type Aliases§
Type Aliases§AccelerationStructure Flags Flags for an acceleration structure.AccelerationStructure Geometry Flags Flags for a geometry inside a bottom level acceleration structure.AccelerationStructure Update Mode Update mode for acceleration structure builds.BlasAABBGeometry Size Descriptor Descriptor for the size defining attributes of an AABB geometry group in a bottom level acceleration structure.BlasGeometry Size Descriptors Descriptor for the size defining attributes, for a bottom level acceleration structure.BlasTriangle Geometry Size Descriptor Descriptor for the size defining attributes of a triangle geometry, for a bottom level acceleration structure.BufferAddress Integral type used forBufferoffsets and sizes.BufferDescriptor Describes aBuffer.BufferSize Integral type used forBufferSlicesizes.CommandEncoder Descriptor Describes aCommandEncoder.CreateBlas Descriptor Descriptor to create bottom level acceleration structures.CreateTlas Descriptor Descriptor to create top level acceleration structures.DeviceDescriptor Describes aDevice.DynamicOffset Integral type used for dynamic bind group offsets.ErrorSource Lower level source of the error.ExternalTexture Descriptor Describes anExternalTexture.LabelObject debugging label.PollType Passed toDevice::pollto control how and if it should block.QuerySetDescriptor Describes aQuerySet.RenderBundle Descriptor Describes aRenderBundle.RequestAdapter Options Additional information required when requesting an adapter.SamplerDescriptor Describes aSampler.ShaderLocation Integral type used for binding locations in shaders.ShaderModule Descriptor Passthrough Descriptor for a shader module given by any of several sources. At least one of the shader types that may be used by the backend must beSomeSurfaceConfiguration Describes aSurface.TexelCopy Buffer Info View of a buffer which can be used to copy to/from a texture.TexelCopy Texture Info View of a texture which can be used to copy to/from a buffer/texture.TextureDescriptor Describes aTexture.TextureView Descriptor Describes aTextureView.

