d3d12
Low level D3D12 API wrapper
22.0.0
5.7M downloads/mo
#4274 most downloaded on crates.io
gfx-rs/wgpu
What this package is like to depend on
Last release 2 years ago
no release in 18 months
Ships fairly regularly
a new release about every 6 months
Most releases are documented
notes for 11 of 13 stable releases
Nothing withdrawn
no release was ever pulled
8 years old
13 releases · first in 2018
0 releases in the last 12 months
see the full history below
Release timeline
13 releases · Dec 2018 to Jul 2024Releases
latest 13-
22.0.018 Jul 2024Release notes
Open source →Overview
Our first major version release!
For the first time ever, wgpu is being released with a major version (i.e., 22.* instead of 0.22.*)! Maintainership has decided to fully adhere to Semantic Versioning's recommendations for versioning production software. According to SemVer 2.0.0's Q&A about when to use 1.0.0 versions (and beyond):
How do I know when to release 1.0.0?
If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backward compatibility, you should probably already be 1.0.0.
It is a well-known fact that wgpu has been used for applications and platforms already in production for years, at this point. We are often concerned with tracking breaking changes, and affecting these consumers' ability to ship. By releasing our first major version, we publicly acknowledge that this is the case. We encourage other projects in the Rust ecosystem to follow suit.
Note that while we start to use the major version number, wgpu is not "going stable", as many Rust projects do. We anticipate many breaking changes before we fully comply with the WebGPU spec., which we expect to take a small number of years.
Overview
A major (pun intended) theme of this release is incremental improvement. Among the typically large set of bug fixes, new features, and other adjustments to wgpu by the many contributors listed below, @wumpf and @teoxoy have merged a series of many simplifications to wgpu's internals and, in one case, to the render and compute pass recording APIs. Many of these change wgpu to use atomically reference-counted resource tracking (i.e.,
Arc<…>), rather than using IDs to manage the lifetimes of platform-specific graphics resources in a registry of separate reference counts. This has led us to diagnose and fix many long-standing bugs, and net some neat performance improvements on the order of 40% or more of some workloads.While the above is exciting, we acknowledge already finding and fixing some (easy-to-fix) regressions from the above work. If you migrate to wgpu 22 and encounter such bugs, please engage us in the issue tracker right away!
Major Changes
Lifetime bounds on
wgpu::RenderPass&wgpu::ComputePasswgpu::RenderPass&wgpu::ComputePassrecording methods (e.g.wgpu::RenderPass:set_render_pipeline) no longer impose a lifetime constraint to objects passed to a pass (like pipelines/buffers/bindgroups/query-sets etc.).This means the following pattern works now as expected:
let mut pipelines: Vec<wgpu::RenderPipeline> = ...; // ... let mut cpass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default()); cpass.set_pipeline(&pipelines[123]); // Change pipeline container - this requires mutable access to `pipelines` while one of the pipelines is in use. pipelines.push(/* ... */); // Continue pass recording. cpass.set_bindgroup(...);Previously, a set pipeline (or other resource) had to outlive pass recording which often affected wider systems, meaning that users needed to prove to the borrow checker that
Vec<wgpu::RenderPipeline>(or similar constructs) aren't accessed mutably for the duration of pass recording.Furthermore, you can now opt out of
wgpu::RenderPass/wgpu::ComputePass's lifetime dependency on its parentwgpu::CommandEncoderusingwgpu::RenderPass::forget_lifetime/wgpu::ComputePass::forget_lifetime:fn independent_cpass<'enc>(encoder: &'enc mut wgpu::CommandEncoder) -> wgpu::ComputePass<'static> { let cpass: wgpu::ComputePass<'enc> = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor::default()); cpass.forget_lifetime() }⚠️ As long as a
wgpu::RenderPass/wgpu::ComputePassis pending for a givenwgpu::CommandEncoder, creation of a compute or render pass is an error and invalidates thewgpu::CommandEncoder.forget_lifetimecan be very useful for library authors, but opens up an easy way for incorrect use, so use with care. This method doesn't add any additional overhead and has no side effects on pass recording.By @wumpf in #5569, #5575, #5620, #5768 (together with @kpreid), #5671, #5794, #5884.
Querying shader compilation errors
Wgpu now supports querying shader compilation info.
This allows you to get more structured information about compilation errors, warnings and info:
... let lighting_shader = ctx.device.create_shader_module(include_wgsl!("lighting.wgsl")); let compilation_info = lighting_shader.get_compilation_info().await; for message in compilation_info .messages .iter() .filter(|m| m.message_type == wgpu::CompilationMessageType::Error) { let line = message.location.map(|l| l.line_number).unwrap_or(1); println!("Compile error at line {line}"); }By @stefnotch in #5410
64 bit integer atomic support in shaders.
Add support for 64 bit integer atomic operations in shaders.
Add the following flags to
wgpu_types::Features:-
SHADER_INT64_ATOMIC_ALL_OPSenables all atomic operations onatomic<i64>andatomic<u64>values. -
SHADER_INT64_ATOMIC_MIN_MAXis a subset of the above, enabling onlyAtomicFunction::MinandAtomicFunction::Maxoperations onatomic<i64>andatomic<u64>values in theStorageaddress space. These are the only 64-bit atomic operations available on Metal as of 3.1.
Add corresponding flags to
naga::valid::Capabilities. These are supported by the WGSL front end, and all naga backends.Platform support:
-
On Direct3d 12, in
D3D12_FEATURE_DATA_D3D12_OPTIONS9, ifAtomicInt64OnTypedResourceSupportedandAtomicInt64OnGroupSharedSupportedare both available, then both wgpu features described above are available. -
On Metal,
SHADER_INT64_ATOMIC_MIN_MAXis available on Apple9 hardware, and on hardware that advertises both Apple8 and Mac2 support. This also requires Metal Shading Language 2.4 or later. Metal does not yet support the more generalSHADER_INT64_ATOMIC_ALL_OPS. -
On Vulkan, if the
VK_KHR_shader_atomic_int64extension is available with both theshader_buffer_int64_atomicsandshader_shared_int64_atomicsfeatures, then both wgpu features described above are available.
By @atlv24 in #5383
A compatible surface is now required for
request_adapter()on WebGL2 +enumerate_adapters()is now native only.When targeting WebGL2, it has always been the case that a surface had to be created before calling
request_adapter(). We now make this requirement explicit.Validation was also added to prevent configuring the surface with a device that doesn't share the same underlying WebGL2 context since this has never worked.
Calling
enumerate_adapters()when targeting WebGPU used to return an emptyVecand since we now require users to pass a compatible surface when targeting WebGL2, havingenumerate_adapters()doesn't make sense.By @teoxoy in #5901
New features
General
- Added
as_halforBufferto access wgpu created buffers form wgpu-hal. By @JasondeWolff in #5724 include_wgsl!is now callable in const contexts by @9SMTM6 in #5872- Added memory allocation hints to
DeviceDescriptorby @nical in #5875MemoryHints::Performance, the default, favors performance over memory usage and will likely cause large amounts of VRAM to be allocated up-front. This hint is typically good for games.MemoryHints::MemoryUsagefavors memory usage over performance. This hint is typically useful for smaller applications or UI libraries.MemoryHints::Manualallows the user to specify parameters for the underlying GPU memory allocator. These parameters are subject to change.- These hints may be ignored by some backends. Currently only the Vulkan and D3D12 backends take them into account.
- Add
HTMLImageElementandImageDataas external source for copying images. By @Valaphee in #5668
naga
-
Added -D, --defines option to naga CLI to define preprocessor macros by @theomonnom in #5859
-
Added type upgrades to SPIR-V atomic support. Added related infrastructure. Tracking issue is here. By @schell in #5775.
-
Implement
WGSL'sunpack4xI8,unpack4xU8,pack4xI8andpack4xU8. By @VlaDexa in #5424 -
Began work adding support for atomics to the SPIR-V frontend. Tracking issue is here. By @schell in #5702.
-
In hlsl-out, allow passing information about the fragment entry point to omit vertex outputs that are not in the fragment inputs. By @Imberflur in #5531
-
In spv-out, allow passing
acceleration_structureas a function argument. By @kvark in #5961let writer: naga::back::hlsl::Writer = /* ... */; -writer.write(&module, &module_info); +writer.write(&module, &module_info, None); -
HLSL & MSL output can now be added conditionally on the target via the
msl-out-if-target-appleandhlsl-out-if-target-windowsfeatures. This is used in wgpu-hal to no longer compile with MSL output whenmetalis enabled & MacOS isn't targeted and no longer compile with HLSL output whendx12is enabled & Windows isn't targeted. By @wumpf in #5919
Vulkan
- Added a
PipelineCacheresource to allow using Vulkan pipeline caches. By @DJMcNab in #5319
WebGPU
- Added support for pipeline-overridable constants to the WebGPU backend by @DouglasDwyer in #5688
Changes
General
- Unconsumed vertex outputs are now always allowed. Removed
StageError::InputNotConsumed,Features::SHADER_UNUSED_VERTEX_OUTPUT, and associated validation. By @Imberflur in #5531 - Avoid introducing spurious features for optional dependencies. By @bjorn3 in #5691
wgpu::Erroris nowSync, making it possible to be wrapped inanyhow::Errororeyre::Report. By @nolanderc in #5820- Added benchmark suite. By @cwfitzgerald in #5694, compute passes by @wumpf in #5767
- Improve performance of
.submit()by 39-64% (.submit()+.poll()by 22-32%). By @teoxoy in #5910 - The
tracewgpu feature has been temporarily removed. By @teoxoy in #5975
Metal
-
Removed the
linkCargo feature.This was used to allow weakly linking frameworks. This can be achieved with putting something like the following in your
.cargo/config.tomlinstead:[target.'cfg(target_vendor = "apple")'] rustflags = ["-C", "link-args=-weak_framework Metal -weak_framework QuartzCore -weak_framework CoreGraphics"]By @madsmtm in #5752
Bug Fixes
General
- Ensure render pipelines have at least 1 target. By @ErichDonGubler in #5715
wgpu::ComputePassnow internally takes ownership ofQuerySetfor bothwgpu::ComputePassTimestampWritesas well as timestamp writes and statistics query, fixing crashes when destroyingQuerySetbefore ending the pass. By @wumpf in #5671- Validate resources passed during compute pass recording for mismatching device. By @wumpf in #5779
- Fix staging buffers being destroyed too early. By @teoxoy in #5910
- Fix attachment byte cost validation panicking with native only formats. By @teoxoy in #5934
- [wgpu] Fix leaks from auto layout pipelines. By @teoxoy in #5971
- [wgpu-core] Fix length of copy in
queue_write_texture(causing UB). By @teoxoy in #5973 - Add missing same device checks. By @teoxoy in #5980
GLES / OpenGL
- Fix
ClearColorF,ClearColorUandClearColorIcommands being issued beforeSetDrawColorBuffers#5666 - Replace
glClearwithglClearBufferFbecauseglDrawBuffersrequires that the ith buffer must beCOLOR_ATTACHMENTiorNONE#5666 - Return the unmodified version in driver_info. By @Valaphee in #5753
naga
-
-
0.20.028 Apr 2024Release notes
Open source →Major Changes
Pipeline overridable constants
Wgpu supports now pipeline-overridable constants
This allows you to define constants in wgsl like this:
override some_factor: f32 = 42.1337; // Specifies a default of 42.1337 if it's not set.And then set them at runtime like so on your pipeline consuming this shader:
// ... fragment: Some(wgpu::FragmentState { compilation_options: wgpu::PipelineCompilationOptions { constants: &[("some_factor".to_owned(), 0.1234)].into(), // Sets `some_factor` to 0.1234. ..Default::default() }, // ... }), // ...By @teoxoy & @jimblandy in #5500
Changed feature requirements for timestamps
Due to a specification change
write_timestampis no longer supported on WebGPU.wgpu::CommandEncoder::write_timestamprequires now the newwgpu::Features::TIMESTAMP_QUERY_INSIDE_ENCODERSfeature which is available on all native backends but not on WebGPU.By @wumpf in #5188
Wgsl const evaluation for many more built-ins
Many numeric built-ins have had a constant evaluation implementation added for them, which allows them to be used in a
constcontext:abs,acos,acosh,asin,asinh,atan,atanh,cos,cosh,round,saturate,sin,sinh,sqrt,step,tan,tanh,ceil,countLeadingZeros,countOneBits,countTrailingZeros,degrees,exp,exp2,floor,fract,fma,inverseSqrt,log,log2,max,min,radians,reverseBits,sign,truncBy @ErichDonGubler in #4879, #5098
New native-only wgsl features
Subgroup operations
The following subgroup operations are available in wgsl now:
subgroupBallot,subgroupAll,subgroupAny,subgroupAdd,subgroupMul,subgroupMin,subgroupMax,subgroupAnd,subgroupOr,subgroupXor,subgroupExclusiveAdd,subgroupExclusiveMul,subgroupInclusiveAdd,subgroupInclusiveMul,subgroupBroadcastFirst,subgroupBroadcast,subgroupShuffle,subgroupShuffleDown,subgroupShuffleUp,subgroupShuffleXorAvailability is governed by the following feature flags:
wgpu::Features::SUBGROUPfor all operations exceptsubgroupBarrierin fragment & compute, supported on Vulkan, DX12 and Metal.wgpu::Features::SUBGROUP_VERTEX, for all operations exceptsubgroupBarriergeneral operations in vertex shaders, supported on Vulkanwgpu::Features::SUBGROUP_BARRIER, for support of thesubgroupBarrieroperation, supported on Vulkan & Metal
Note that there currently some differences between wgpu's native-only implementation and the open WebGPU proposal.
By @exrook and @lichtso in #5301
Signed and unsigned 64 bit integer support in shaders.
wgpu::Features::SHADER_INT64enables 64 bit integer signed and unsigned integer variables in wgsl (i64andu64respectively). Supported on Vulkan, DX12 (requires DXC) and Metal (with MSL 2.3+ support).By @atlv24 and @cwfitzgerald in #5154
New features
General
- Implemented the
Unorm10_10_10_2VertexFormat by @McMackety in #5477 wgpu-types'straceandreplayfeatures have been replaced by theserdefeature. By @KirmesBude in #5149wgpu-core'sserial-passfeature has been removed. Useserdeinstead. By @KirmesBude in #5149- Added
InstanceFlags::GPU_BASED_VALIDATION, which enables GPU-based validation for shaders. This is currently only supported on the DX12 and Vulkan backends; other platforms ignore this flag, for now. By @ErichDonGubler in #5146, #5046.- When set, this flag implies
InstanceFlags::VALIDATION. - This has been added to the set of flags set by
InstanceFlags::advanced_debugging. Since the overhead is potentially very large, the flag is not enabled by default in debug builds when usingInstanceFlags::from_build_config. - As with other instance flags, this flag can be changed in calls to
InstanceFlags::with_envwith the newWGPU_GPU_BASED_VALIDATIONenvironment variable.
- When set, this flag implies
wgpu::Instancecan now report whichwgpu::Backendsare available based on the build configuration. By @wumpf #5167-wgpu::Instance::any_backend_feature_enabled() +!wgpu::Instance::enabled_backend_features().is_empty()- Breaking change:
wgpu_core::pipeline::ProgrammableStageDescriptoris now optional. By @ErichDonGubler in #5305. Features::downlevel{_webgl2,}_featureswas made const by @MultisampledNight in #5343- Breaking change:
wgpu_core::pipeline::ShaderErrorhas been moved tonaga. By @stefnotch in #5410 - More as_hal methods and improvements by @JMS55 in #5452
- Added
wgpu::CommandEncoder::as_hal_mut - Added
wgpu::TextureView::as_hal wgpu::Texture::as_halnow returns a user-defined type to match the other as_hal functions
- Added
naga
- Allow user to select which MSL version to use via
--metal-versionwith naga CLI. By @pcleavelin in #5392 - Support
arrayLengthfor runtime-sized arrays inside binding arrays (for WGSL input and SPIR-V output). By @kvark in #5428 - Added
--shader-stageand--input-kindoptions to naga-cli for specifying vertex/fragment/compute shaders, and frontend. by @ratmice in #5411 - Added a
create_validatorfunction to wgpu_coreDeviceto create nagaValidators. By @atlv24 #5606
WebGPU
- Implement the
device_set_device_lost_callbackmethod forContextWebGpu. By @suti in #5438 - Add support for storage texture access modes
ReadOnlyandReadWrite. By @JolifantoBambla in #5434
GLES / OpenGL
- Log an error when GLES texture format heuristics fail. By @PolyMeilex in #5266
- Cache the sample count to keep
get_texture_format_featurescheap. By @Dinnerbone in #5346 - Mark
DEPTH32FLOAT_STENCIL8as supported in GLES. By @Dinnerbone in #5370 - Desktop GL now also supports
TEXTURE_COMPRESSION_ETC2. By @Valaphee in #5568 - Don't create a program for shader-clearing if that workaround isn't required. By @Dinnerbone in #5348.
- OpenGL will now be preferred over OpenGL ES on EGL, making it consistent with WGL. By @valaphee in #5482
- Fill out
driveranddriver_info, with the OpenGL flavor and version, similar to Vulkan. By @valaphee in #5482
Metal
- Metal 3.0 and 3.1 detection. By @atlv24 in #5497
DX12
- Shader Model 6.1-6.7 detection. By @atlv24 in #5498
Other performance improvements
- Simplify and speed up the allocation of internal IDs. By @nical in #5229
- Use memory pooling for UsageScopes to avoid frequent large allocations. by @robtfm in #5414
- Eager release of GPU resources comes from device.trackers. By @bradwerth in #5075
- Support disabling zero-initialization of workgroup local memory in compute shaders. By @DJMcNab in #5508
Documentation
- Improved
wgpu_haldocumentation. By @jimblandy in #5516, #5524, #5562, #5563, #5566, #5617, #5618 - Add mention of primitive restart in the description of
PrimitiveState::strip_index_format. By @cpsdqs in #5350 - Document and tweak precise behaviour of
SourceLocation. By @stefnotch in #5386 and #5410 - Give short example of WGSL
push_constantsyntax. By @waywardmonkeys in #5393 - Fix incorrect documentation of
Limits::max_compute_workgroup_storage_sizedefault value. By @atlv24 in #5601
Bug Fixes
General
- Fix
serdefeature not compiling forwgpu-types. By @KirmesBude in #5149 - Fix the validation of vertex and index ranges. By @nical in #5144 and #5156
- Fix panic when creating a surface while no backend is available. By @wumpf #5166
- Correctly compute minimum buffer size for array-typed
storageanduniformvars. By @jimblandy #5222 - Fix timeout when presenting a surface where no work has been done. By @waywardmonkeys in #5200
- Fix registry leaks with de-duplicated resources. By @nical in #5244
- Fix linking when targeting android. By @ashdnazg in #5326.
- Failing to set the device lost closure will call the closure before returning. By @bradwerth in #5358.
- Fix deadlocks caused by recursive read-write lock acquisitions #5426.
- Remove exposed C symbols (
extern "C"+ [no_mangle]) from RenderPass & ComputePass recording. By @wumpf in #5409. - Fix surfaces being only compatible with first backend enabled on an instance, causing failures when manually specifying an adapter. By @Wumpf in #5535.
naga
- In spv-in, remove unnecessary "gl_PerVertex" name check so unused builtins will always be skipped. Prevents validation errors caused by capability requirements of these builtins #4915. By @Imberflur in #5227.
- In spv-out, check for acceleration and ray-query types when enabling ray-query extension to prevent validation error. By @Vecvec in #5463
- Add a limit for curly brace nesting in WGSL parsing, plus a note about stack size requirements. By @ErichDonGubler in #5447.
- In hlsl-out, fix accesses on zero value expressions by generating helper functions for
Expression::ZeroValue. By @Imberflur in #5587. - Fix behavior of
extractBitsandinsertBitswhenoffset + countoverflows the bit width. By @cwfitzgerald in #5305 - Fix behavior of integer
clampwhenminargument >maxargument. By @cwfitzgerald in #5300. - Fix
TypeInner::scalar_widthto be consistent with the rest of the codebase and return values in bytes not bits. By @atlv24 in #5532.
GLES / OpenGL
- GLSL 410 does not support layout(binding = ...), enable only for GLSL 420. By @bes in #5357
- Fixes for being able to use an OpenGL 4.1 core context provided by macOS with wgpu. By @bes in #5331.
- Fix crash when holding multiple devices on wayland/surfaceless. By @ashdnazg in #5351.
- Fix
first_instancegetting ignored in draw indexed whenARB_shader_draw_parametersfeature is present andbase_vertexis 0. By @valaphee in #5482
Vulkan
- Set object labels when the DEBUG flag is set, even if the VALIDATION flag is disabled. By @DJMcNab in #5345.
- Add safety check to
wgpu_hal::vulkan::CommandEncoderto make surediscard_encodingis not called in the closed state. By @villuna in #5557 - Fix SPIR-V type capability requests to not depend on
LocalTypecaching. By @atlv24 in #5590 - Upgrade
ashto0.38. By @MarijnS95 in #5504.
Tests
- Fix intermittent crashes on Linux in the
multithreaded_computetest. By @jimblandy in #5129. - Refactor tests to read feature flags by name instead of a hardcoded hexadecimal u64. By @atlv24 in #5155.
- Add test that verifies that we can drop the queue before using the device to create a command encoder. By @Davidster in #5211
-
0.19.017 Jan 2024Release notes
Open source →This release includes:
wgpuwgpu-corewgpu-halwgpu-typeswgpu-infonaga(skipped from 0.14 to 0.19)naga-cli(skipped from 0.14 to 0.19)d3d12(skipped from 0.7 to 0.19)
Improved Multithreading through internal use of Reference Counting
Large refactoring of wgpu’s internals aiming at reducing lock contention, and providing better performance when using wgpu on multiple threads.
By @gents83 in #3626 and thanks also to @jimblandy, @nical, @Wumpf, @Elabajaba & @cwfitzgerald
All Public Dependencies are Re-Exported
All of wgpu's public dependencies are now re-exported at the top level so that users don't need to take their own dependencies. This includes:
- wgpu-core
- wgpu-hal
- naga
- raw_window_handle
- web_sys
Feature Flag Changes
WebGPU & WebGL in the same Binary
Enabling
webglno longer removes thewebgpubackend.Instead, there's a new (default enabled)
webgpufeature that allows to explicitly opt-out ofwebgpuif so desired. If bothwebgl&webgpuare enabled,wgpu::Instancedecides upon creation whether to target wgpu-core/WebGL or WebGPU. This means that adapter selection is not handled as with regular adapters, but still allows to decide at runtime whetherwebgpuor thewebglbackend should be used using a single wasm binary. By @wumpf in #5044naga-irDedicated FeatureThe
naga-irfeature has been added to allow you to add naga module shaders without guessing about what other features needed to be enabled to get access to it. By @cwfitzgerald in #5063.expose-idsFeature available unconditionallyThis feature allowed you to call
global_idon any wgpu opaque handle to get a unique hashable identity for the given resource. This is now available without the feature flag. By @cwfitzgerald in #4841.dx12andmetalBackend Crate Featureswgpu now exposes backend feature for the Direct3D 12 (
dx12) and Metal (metal) backend. These are enabled by default, but don't do anything when not targeting the corresponding OS. By @daxpedda in #4815.Direct3D 11 Backend Removal
This backend had no functionality, and with the recent support for GL on Desktop, which allows wgpu to run on older devices, there was no need to keep this backend. By @valaphee in #4828.
WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTEREnvironment VariableThis adds a way to allow a Vulkan driver which is non-compliant per
VK_KHR_driver_propertiesto be enumerated. This is intended for testing new Vulkan drivers which are not Vulkan compliant yet. By @i509VCB in #4754.DeviceExt::create_texture_with_dataallows Mip-Major DataPreviously,
DeviceExt::create_texture_with_dataonly allowed data to be provided in layer major order. There is now aorderparameter which allows you to specify if the data is in layer major or mip major order.let tex = ctx.device.create_texture_with_data( &queue, &descriptor, + wgpu::util::TextureDataOrder::LayerMajor, src_data, );By @cwfitzgerald in #4780.
Safe & unified Surface Creation
It is now possible to safely create a
wgpu::Surfacewithwgpu::Instance::create_surface()by lettingwgpu::Surfacehold a lifetime towindow. Passing an owned valuewindowtoSurfacewill return awgpu::Surface<'static>.All possible safe variants (owned windows and web canvases) are grouped using
wgpu::SurfaceTarget. Conversion towgpu::SurfaceTargetis automatic for any type implementingraw-window-handle'sHasWindowHandle&HasDisplayHandletraits, i.e. most window types. For web canvas types this has to be done explicitly:let surface: wgpu::Surface<'static> = instance.create_surface(wgpu::SurfaceTarget::Canvas(my_canvas))?;All unsafe variants are now grouped under
wgpu::Instance::create_surface_unsafewhich takes thewgpu::SurfaceTargetUnsafeenum and always returnswgpu::Surface<'static>.In order to create a
wgpu::Surface<'static>without passing ownership of the window usewgpu::SurfaceTargetUnsafe::from_window:let surface = unsafe { instance.create_surface_unsafe(wgpu::SurfaceTargetUnsafe::from_window(&my_window))? };The easiest way to make this code safe is to use shared ownership:
let window: Arc<winit::Window>; // ... let surface = instance.create_surface(window.clone())?;All platform specific surface creation using points have moved into
SurfaceTargetUnsafeas well. For example:Safety by @daxpedda in #4597 Unification by @wumpf in #4984
Add partial Support for WGSL Abstract Types
Abstract types make numeric literals easier to use, by automatically converting literals and other constant expressions from abstract numeric types to concrete types when safe and necessary. For example, to build a vector of floating-point numbers, naga previously made you write:
vec3<f32>(1.0, 2.0, 3.0)With this change, you can now simply write:
vec3<f32>(1, 2, 3)Even though the literals are abstract integers, naga recognizes that it is safe and necessary to convert them to
f32values in order to build the vector. You can also use abstract values as initializers for global constants and global and local variables, like this:var unit_x: vec2<f32> = vec2(1, 0);The literals
1and0are abstract integers, and the expressionvec2(1, 0)is an abstract vector. However, naga recognizes that it can convert that to the concrete typevec2<f32>to satisfy the given type ofunit_x. The WGSL specification permits abstract integers and floating-point values in almost all contexts, but naga's support for this is still incomplete. Many WGSL operators and builtin functions are specified to produce abstract results when applied to abstract inputs, but for now naga simply concretizes them all before applying the operation. We will expand naga's abstract type support in subsequent pull requests. As part of this work, the public typesnaga::ScalarKindandnaga::Literalnow have new variants,AbstractIntandAbstractFloat.By @jimblandy in #4743, #4755.
Instance::enumerate_adaptersnow returnsVec<Adapter>instead of anExactSizeIteratorThis allows us to support WebGPU and WebGL in the same binary.
- let adapters: Vec<Adapter> = instance.enumerate_adapters(wgpu::Backends::all()).collect(); + let adapters: Vec<Adapter> = instance.enumerate_adapters(wgpu::Backends::all());By @wumpf in #5044
device.poll()now returns aMaintainResultinstead of aboolThis is a forward looking change, as we plan to add more information to the
MaintainResultin the future. This enum has the same data as the boolean, but with some useful helper functions.- let queue_finished: bool = device.poll(wgpu::Maintain::Wait); + let queue_finished: bool = device.poll(wgpu::Maintain::Wait).is_queue_empty();By @cwfitzgerald in #5053
New Features
General
- Added
DownlevelFlags::VERTEX_AND_INSTANCE_INDEX_RESPECTS_RESPECTIVE_FIRST_VALUE_IN_INDIRECT_DRAWto know if@builtin(vertex_index)and@builtin(instance_index)will respect thefirst_vertex/first_instancein indirect calls. If this is not present, both will always start counting from 0. Currently enabled on all backends except DX12. By @cwfitzgerald in #4722. - Added support for the
FLOAT32_FILTERABLEfeature (web and native, corresponds to WebGPU'sfloat32-filterable). By @almarklein in #4759. - GPU buffer memory is released during "lose the device". By @bradwerth in #4851.
- wgpu and wgpu-core cargo feature flags are now documented on docs.rs. By @wumpf in #4886.
- DeviceLostClosure is guaranteed to be invoked exactly once. By @bradwerth in #4862.
- Log vulkan validation layer messages during instance creation and destruction: By @exrook in #4586.
TextureFormat::block_sizeis deprecated, useTextureFormat::block_copy_sizeinstead: By @wumpf in #4647.- Rename of
DispatchIndirect,DrawIndexedIndirect, andDrawIndirecttypes in thewgpu::utilmodule toDispatchIndirectArgs,DrawIndexedIndirectArgs, andDrawIndirectArgs. By @cwfitzgerald in #4723. - Make the size parameter of
encoder.clear_bufferanOption<u64>instead ofOption<NonZero<u64>>. By @nical in #4737. - Reduce the
infolog level noise. By @nical in #4769, #4711 and #4772 - Rename
features&limitsfields ofDeviceDescriptortorequired_features&required_limits. By @teoxoy in #4803. SurfaceConfigurationnow exposesdesired_maximum_frame_latencywhich was previously hard-coded to 2. By setting it to 1 you can reduce latency under the risk of making GPU & CPU work sequential. Currently, on DX12 this affects theMaximumFrameLatency, on all other backends except OpenGL the size of the swapchain (on OpenGL this has no effect). By @emilk & @wumpf in #4899
OpenGL
@builtin(instance_index)now properly reflects the range provided in the draw call instead of always counting from 0. By @cwfitzgerald in #4722.- Desktop GL now supports
POLYGON_MODE_LINEandPOLYGON_MODE_POINT. By @valaphee in #4836.
naga
- naga's WGSL front end now allows operators to produce values with abstract types, rather than concretizing their operands. By @jimblandy in #4850 and #4870.
- naga's WGSL front and back ends now have experimental support for 64-bit floating-point literals:
1.0lfdenotes anf64value. There has been experimental support for anf64type for a while, but until now there was no syntax for writing literals with that type. As before, naga module validation rejectsf64values unlessnaga::valid::Capabilities::FLOAT64is requested. By @jimblandy in #4747. - naga constant evaluation can now process binary operators whose operands are both vectors. By @jimblandy in #4861.
- Add
--bulk-validateoption to naga CLI. By @jimblandy in #4871. - naga's
cargo xtask validatenow runs validation jobs in parallel, using the jobserver protocol to limit concurrency, and offers avalidate allsubcommand, which runs all available validation types. By @jimblandy in #4902. - Remove
spanandvalidatefeatures. Always fully validate shader modules, and always track source positions for use in error messages. By @teoxoy in #4706. - Introduce a new
Scalarstruct type for use in naga's IR, and update all frontend, middle, and backend code appropriately. By @jimblandy in #4673. - Add more metal keywords. By @fornwall in #4707.
- Add a new
naga::Literalvariant,I64, for signed 64-bit literals. #4711. - Emit and init
structmember padding always. By @ErichDonGubler in #4701. - In WGSL output, always include the
isuffix oni32literals. By @jimblandy in #4863. - In WGSL output, always include the
fsuffix onf32literals. By @jimblandy in #4869.
Bug Fixes
General
BufferMappedRangetrait is nowWasmNotSendSync, i.e. it isSend/Syncif not on wasm orfragile-send-sync-non-atomic-wasmis enabled. By @wumpf in #4818.- Align
wgpu_types::CompositeAlphaModeserde serialization to spec. By @littledivy in #4940. - Fix error message of
ConfigureSurfaceError::TooLarge. By @Dinnerbone in #4960. - Fix dropping of
DeviceLostCallbackCparams. By @bradwerth in #5032. - Fixed a number of panics. By @nical in #4999, #5014, #5024, #5025, #5026, #5027, #5028 and #5042.
- No longer validate surfaces against their allowed extent range on configure. This caused warnings that were almost impossible to avoid. As before, the resulting behavior depends on the compositor. By @wumpf in #4796.
DX12
- Fixed D3D12_SUBRESOURCE_FOOTPRINT calculation for block compressed textures which caused a crash with
Queue::write_textureon DX12. By @DTZxPorter in #4990.
Vulkan
- Use
VK_EXT_robustness2only when not using an outdated intel iGPU driver. By @TheoDulka in #4602.
WebGPU
- Allow calling
BufferSlice::get_mapped_rangemultiple times on the same buffer slice (instead of throwing a Javascript exception). By @DouglasDwyer in #4726.
WGL
- Create a hidden window per
wgpu::Instanceinstead of sharing a global one. By @Zoxc in #4603
naga
- Make module compaction preserve the module's named types, even if they are unused. By @jimblandy in #4734.
- Improve algorithm used by module compaction. By @jimblandy in #4662.
- When reading GLSL, fix the argument types of the double-precision floating-point overloads of the
dot,reflect,distance, andldexpbuiltin functions. Correct the WGSL generated for constructing 64-bit floating-point matrices. Add tests for all the above. By @jimblandy in #4684. - Allow naga's IR types to represent matrices with elements elements of any scalar kind. This makes it possible for naga IR types to represent WGSL abstract matrices. By @jimblandy in #4735.
- Preserve the source spans for constants and expressions correctly across module compaction. By @jimblandy in #4696.
- Record the names of WGSL
aliasdeclarations in naga IRTypes. By @jimblandy in #4733.
Metal
- Allow the
COPY_SRCusage flag in surface configuration. By @Toqozz in #4852.
Examples
-
0.7.018 Jul 2023Nothing published for this version
-
0.6.025 Jan 2023Release notes
Open source →- add helpers for IDXGIFactoryMedia
- add
create_swapchain_for_composition_surface_handle
- add
- add helpers for IDXGIFactoryMedia
-
0.5.001 Jul 2022 -
0.4.118 Aug 2021Release notes
Open source →- expose all indirect argument types
- expose methods for setting root constants
- expose all indirect argument types
-
0.4.029 Apr 2021 -
0.3.219 Aug 2020Nothing published for this version
-
0.3.107 Jul 2020Release notes
Open source →- create shader from IL
- fix default doc target
- debug impl for root descriptors
- create shader from IL
-
0.3.001 Nov 2019 -
0.2.204 Oct 2019 -
0.1.027 Dec 2018