wgpu_types/
backend.rs

1//! [`Backend`], [`Backends`], and backend-specific options.
2
3use alloc::string::String;
4use core::hash::Hash;
5
6#[cfg(any(feature = "serde", test))]
7use serde::{Deserialize, Serialize};
8
9use crate::link_to_wgpu_docs;
10
11#[cfg(doc)]
12use crate::InstanceDescriptor;
13
14/// Backends supported by wgpu.
15///
16/// See also [`Backends`].
17#[repr(u8)]
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20pub enum Backend {
21    /// Dummy backend, which may be used for testing.
22    ///
23    /// It performs no rendering or computation, but allows creation of stub GPU resource types,
24    /// so that code which manages GPU resources can be tested without an available GPU.
25    /// Specifically, the following operations are implemented:
26    ///
27    /// * Enumerating adapters will always return one noop adapter, which can be used to create
28    ///   devices.
29    /// * Buffers may be created, written, mapped, and copied to other buffers.
30    /// * Command encoders may be created, but only buffer operations are useful.
31    ///
32    /// Other resources can be created but are nonfunctional; notably,
33    ///
34    /// * Render passes and compute passes are not executed.
35    /// * Textures may be created, but do not store any texels.
36    /// * There are no compatible surfaces.
37    ///
38    /// An adapter using the noop backend can only be obtained if [`NoopBackendOptions`]
39    /// enables it, in addition to the ordinary requirement of [`Backends::NOOP`] being set.
40    /// This ensures that applications not desiring a non-functional backend will not receive it.
41    Noop = 0,
42    /// Vulkan API (Windows, Linux, Android, MacOS via `vulkan-portability`/MoltenVK)
43    Vulkan = 1,
44    /// Metal API (Apple platforms)
45    Metal = 2,
46    /// Direct3D-12 (Windows)
47    Dx12 = 3,
48    /// OpenGL 3.3+ (Windows), OpenGL ES 3.0+ (Linux, Android, MacOS via Angle), and WebGL2
49    Gl = 4,
50    /// WebGPU in the browser
51    BrowserWebGpu = 5,
52}
53
54impl Backend {
55    /// Array of all [`Backend`] values, corresponding to [`Backends::all()`].
56    pub const ALL: [Backend; Backends::all().bits().count_ones() as usize] = [
57        Self::Noop,
58        Self::Vulkan,
59        Self::Metal,
60        Self::Dx12,
61        Self::Gl,
62        Self::BrowserWebGpu,
63    ];
64
65    /// Returns the string name of the backend.
66    #[must_use]
67    pub const fn to_str(self) -> &'static str {
68        match self {
69            Backend::Noop => "noop",
70            Backend::Vulkan => "vulkan",
71            Backend::Metal => "metal",
72            Backend::Dx12 => "dx12",
73            Backend::Gl => "gl",
74            Backend::BrowserWebGpu => "webgpu",
75        }
76    }
77}
78
79impl core::fmt::Display for Backend {
80    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
81        f.write_str(self.to_str())
82    }
83}
84
85bitflags::bitflags! {
86    /// Represents the backends that wgpu will use.
87    #[repr(transparent)]
88    #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
89    #[cfg_attr(feature = "serde", serde(transparent))]
90    #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
91    pub struct Backends: u32 {
92        /// [`Backend::Noop`].
93        const NOOP = 1 << Backend::Noop as u32;
94
95        /// [`Backend::Vulkan`].
96        /// Supported on Windows, Linux/Android, and macOS/iOS via Vulkan Portability (with the Vulkan feature enabled)
97        const VULKAN = 1 << Backend::Vulkan as u32;
98
99        /// [`Backend::Gl`].
100        /// Supported on Linux/Android, the web through webassembly via WebGL, and Windows and
101        /// macOS/iOS via ANGLE
102        const GL = 1 << Backend::Gl as u32;
103
104        /// [`Backend::Metal`].
105        /// Supported on macOS and iOS.
106        const METAL = 1 << Backend::Metal as u32;
107
108        /// [`Backend::Dx12`].
109        /// Supported on Windows 10 and later
110        const DX12 = 1 << Backend::Dx12 as u32;
111
112        /// [`Backend::BrowserWebGpu`].
113        /// Supported when targeting the web through WebAssembly with the `webgpu` feature enabled.
114        ///
115        /// The WebGPU backend is special in several ways:
116        /// It is not not implemented by `wgpu_core` and instead by the higher level `wgpu` crate.
117        /// Whether WebGPU is targeted is decided upon the creation of the `wgpu::Instance`,
118        /// *not* upon adapter creation. See `wgpu::Instance::new`.
119        const BROWSER_WEBGPU = 1 << Backend::BrowserWebGpu as u32;
120
121        /// All the apis that wgpu offers first tier of support for.
122        ///
123        /// * [`Backends::VULKAN`]
124        /// * [`Backends::METAL`]
125        /// * [`Backends::DX12`]
126        /// * [`Backends::BROWSER_WEBGPU`]
127        const PRIMARY = Self::VULKAN.bits()
128            | Self::METAL.bits()
129            | Self::DX12.bits()
130            | Self::BROWSER_WEBGPU.bits();
131
132        /// All the apis that wgpu offers second tier of support for. These may
133        /// be unsupported/still experimental.
134        ///
135        /// * [`Backends::GL`]
136        const SECONDARY = Self::GL.bits();
137    }
138}
139
140impl Default for Backends {
141    fn default() -> Self {
142        Self::all()
143    }
144}
145
146impl From<Backend> for Backends {
147    fn from(backend: Backend) -> Self {
148        Self::from_bits(1 << backend as u32).unwrap()
149    }
150}
151
152impl Backends {
153    /// Gets a set of backends from the environment variable `WGPU_BACKEND`.
154    ///
155    /// See [`Self::from_comma_list()`] for the format of the string.
156    pub fn from_env() -> Option<Self> {
157        let env = crate::env::var("WGPU_BACKEND")?;
158        Some(Self::from_comma_list(&env))
159    }
160
161    /// Takes the given options, modifies them based on the `WGPU_BACKEND` environment variable, and returns the result.
162    pub fn with_env(&self) -> Self {
163        if let Some(env) = Self::from_env() {
164            env
165        } else {
166            *self
167        }
168    }
169
170    /// Generates a set of backends from a comma separated list of case-insensitive backend names.
171    ///
172    /// Whitespace is stripped, so both 'gl, dx12' and 'gl,dx12' are valid.
173    ///
174    /// Always returns WEBGPU on wasm over webgpu.
175    ///
176    /// Names:
177    /// - vulkan = "vulkan" or "vk"
178    /// - dx12   = "dx12" or "d3d12"
179    /// - metal  = "metal" or "mtl"
180    /// - gles   = "opengl" or "gles" or "gl"
181    /// - webgpu = "webgpu"
182    pub fn from_comma_list(string: &str) -> Self {
183        let mut backends = Self::empty();
184        for backend in string.to_lowercase().split(',') {
185            backends |= match backend.trim() {
186                "vulkan" | "vk" => Self::VULKAN,
187                "dx12" | "d3d12" => Self::DX12,
188                "metal" | "mtl" => Self::METAL,
189                "opengl" | "gles" | "gl" => Self::GL,
190                "webgpu" => Self::BROWSER_WEBGPU,
191                "noop" => Self::NOOP,
192                b => {
193                    log::warn!("unknown backend string '{b}'");
194                    continue;
195                }
196            }
197        }
198
199        if backends.is_empty() {
200            log::warn!("no valid backend strings found!");
201        }
202
203        backends
204    }
205}
206
207/// Options that are passed to a given backend.
208///
209/// Part of [`InstanceDescriptor`].
210#[derive(Clone, Debug, Default)]
211pub struct BackendOptions {
212    /// Options for the OpenGL/OpenGLES backend, [`Backend::Gl`].
213    pub gl: GlBackendOptions,
214    /// Options for the DX12 backend, [`Backend::Dx12`].
215    pub dx12: Dx12BackendOptions,
216    /// Options for the noop backend, [`Backend::Noop`].
217    pub noop: NoopBackendOptions,
218}
219
220impl BackendOptions {
221    /// Choose backend options by calling `from_env` on every field.
222    ///
223    /// See those methods for more information.
224    #[must_use]
225    pub fn from_env_or_default() -> Self {
226        Self {
227            gl: GlBackendOptions::from_env_or_default(),
228            dx12: Dx12BackendOptions::from_env_or_default(),
229            noop: NoopBackendOptions::from_env_or_default(),
230        }
231    }
232
233    /// Takes the given options, modifies them based on the environment variables, and returns the result.
234    ///
235    /// This is equivalent to calling `with_env` on every field.
236    #[must_use]
237    pub fn with_env(self) -> Self {
238        Self {
239            gl: self.gl.with_env(),
240            dx12: self.dx12.with_env(),
241            noop: self.noop.with_env(),
242        }
243    }
244}
245
246/// Configuration for the OpenGL/OpenGLES backend.
247///
248/// Part of [`BackendOptions`].
249#[derive(Clone, Debug, Default)]
250pub struct GlBackendOptions {
251    /// Which OpenGL ES 3 minor version to request, if using OpenGL ES.
252    pub gles_minor_version: Gles3MinorVersion,
253    /// Behavior of OpenGL fences. Affects how `on_completed_work_done` and `device.poll` behave.
254    pub fence_behavior: GlFenceBehavior,
255    /// Controls whether debug functions (`glPushDebugGroup`, `glPopDebugGroup`,
256    /// `glObjectLabel`, etc.) are enabled when supported by the driver.
257    ///
258    /// By default ([`GlDebugFns::Auto`]), debug functions are automatically
259    /// disabled on devices with known bugs (e.g., Mali GPUs can crash in
260    /// `glPushDebugGroup`). Use [`GlDebugFns::ForceEnabled`] to override this
261    /// behavior, or [`GlDebugFns::Disabled`] to disable debug functions entirely.
262    ///
263    /// See also [`InstanceFlags::DISCARD_HAL_LABELS`], which prevents debug
264    /// markers and labels from being sent to *any* backend, but without the
265    /// driver-specific bug workarounds provided here.
266    ///
267    /// [`InstanceFlags::DISCARD_HAL_LABELS`]: crate::InstanceFlags::DISCARD_HAL_LABELS
268    pub debug_fns: GlDebugFns,
269}
270
271impl GlBackendOptions {
272    /// Choose OpenGL backend options by calling `from_env` on every field.
273    ///
274    /// See those methods for more information.
275    #[must_use]
276    pub fn from_env_or_default() -> Self {
277        let gles_minor_version = Gles3MinorVersion::from_env().unwrap_or_default();
278        let debug_fns = GlDebugFns::from_env().unwrap_or_default();
279        Self {
280            gles_minor_version,
281            fence_behavior: GlFenceBehavior::Normal,
282            debug_fns,
283        }
284    }
285
286    /// Takes the given options, modifies them based on the environment variables, and returns the result.
287    ///
288    /// This is equivalent to calling `with_env` on every field.
289    #[must_use]
290    pub fn with_env(self) -> Self {
291        let gles_minor_version = self.gles_minor_version.with_env();
292        let fence_behavior = self.fence_behavior.with_env();
293        let debug_fns = self.debug_fns.with_env();
294        Self {
295            gles_minor_version,
296            fence_behavior,
297            debug_fns,
298        }
299    }
300}
301
302/// Controls whether OpenGL debug functions are enabled.
303///
304/// Debug functions include `glPushDebugGroup`, `glPopDebugGroup`, `glObjectLabel`, etc.
305/// These are useful for debugging but can cause crashes on some buggy drivers.
306#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
307pub enum GlDebugFns {
308    /// Automatically decide whether to enable debug functions.
309    ///
310    /// Debug functions will be enabled if supported by the driver, unless
311    /// running on a device known to have buggy debug function implementations
312    /// (e.g., Mali GPUs which can crash in `glPushDebugGroup`).
313    ///
314    /// This is the default behavior.
315    #[default]
316    Auto,
317    /// Force enable debug functions if supported by the driver.
318    ///
319    /// This ignores any device-specific workarounds and enables debug functions
320    /// on all devices that support them, including those with known bugs.
321    ForceEnabled,
322    /// Disable debug functions entirely.
323    ///
324    /// Debug functions will not be used even if supported by the driver.
325    Disabled,
326}
327
328impl GlDebugFns {
329    /// Choose debug functions setting from the environment variable `WGPU_GL_DEBUG_FNS`.
330    ///
331    /// Possible values (case insensitive):
332    /// - `auto` - automatically decide based on device
333    /// - `forceenabled`, `force_enabled`, or `enabled` - force enable
334    /// - `disabled` - disable entirely
335    ///
336    /// Use with `unwrap_or_default()` to get the default value if the environment variable is not set.
337    #[must_use]
338    pub fn from_env() -> Option<Self> {
339        let value = crate::env::var("WGPU_GL_DEBUG_FNS")
340            .as_deref()?
341            .to_lowercase();
342        match value.as_str() {
343            "auto" => Some(Self::Auto),
344            "forceenabled" | "force_enabled" | "enabled" => Some(Self::ForceEnabled),
345            "disabled" => Some(Self::Disabled),
346            _ => None,
347        }
348    }
349
350    /// Takes the given setting, modifies it based on the `WGPU_GL_DEBUG_FNS` environment variable, and returns the result.
351    ///
352    /// See `from_env` for more information.
353    #[must_use]
354    pub fn with_env(self) -> Self {
355        if let Some(debug_fns) = Self::from_env() {
356            debug_fns
357        } else {
358            self
359        }
360    }
361}
362
363/// Used to force wgpu to expose certain features on passthrough shaders even when
364/// those features aren't present on runtime-compiled shaders
365#[derive(Default, Clone, Debug)]
366pub struct ForceShaderModelToken {
367    inner: Option<DxcShaderModel>,
368}
369impl ForceShaderModelToken {
370    /// Creates an unsafe token, opting you in to seeing features that you may not necessarily use
371    /// on standard runtime-compiled shaders.
372    /// # Safety
373    /// Do not make use in runtime-compiled shaders of any features that may not be supported by the FXC or DXC
374    /// version you use.
375    pub unsafe fn with_shader_model(sm: DxcShaderModel) -> Self {
376        Self { inner: Some(sm) }
377    }
378
379    /// Returns the shader model version, if any, in this token.
380    pub fn get(&self) -> Option<DxcShaderModel> {
381        self.inner.clone()
382    }
383}
384
385/// Configuration for the DX12 backend.
386///
387/// Part of [`BackendOptions`].
388#[derive(Clone, Debug, Default)]
389pub struct Dx12BackendOptions {
390    /// Which DX12 shader compiler to use.
391    pub shader_compiler: Dx12Compiler,
392    /// Presentation system to use.
393    pub presentation_system: Dx12SwapchainKind,
394    /// Whether to wait for the latency waitable object before acquiring the next swapchain image.
395    pub latency_waitable_object: Dx12UseFrameLatencyWaitableObject,
396    /// For use with passthrough shaders. Expose features as if this shader model is present, even if you do not
397    /// intend to ship DXC with your app.
398    ///
399    /// This does not override the device's shader model version, only the external shader compiler's version.
400    pub force_shader_model: ForceShaderModelToken,
401}
402
403impl Dx12BackendOptions {
404    /// Choose DX12 backend options by calling `from_env` on every field.
405    ///
406    /// See those methods for more information.
407    #[must_use]
408    pub fn from_env_or_default() -> Self {
409        let compiler = Dx12Compiler::from_env().unwrap_or_default();
410        let presentation_system = Dx12SwapchainKind::from_env().unwrap_or_default();
411        let latency_waitable_object =
412            Dx12UseFrameLatencyWaitableObject::from_env().unwrap_or_default();
413        Self {
414            shader_compiler: compiler,
415            presentation_system,
416            latency_waitable_object,
417            force_shader_model: ForceShaderModelToken::default(),
418        }
419    }
420
421    /// Takes the given options, modifies them based on the environment variables, and returns the result.
422    ///
423    /// This is equivalent to calling `with_env` on every field.
424    #[must_use]
425    pub fn with_env(self) -> Self {
426        let shader_compiler = self.shader_compiler.with_env();
427        let presentation_system = self.presentation_system.with_env();
428        let latency_waitable_object = self.latency_waitable_object.with_env();
429        Self {
430            shader_compiler,
431            presentation_system,
432            latency_waitable_object,
433            force_shader_model: ForceShaderModelToken::default(),
434        }
435    }
436}
437
438/// Configuration for the noop backend.
439///
440/// Part of [`BackendOptions`].
441#[derive(Clone, Debug, Default)]
442pub struct NoopBackendOptions {
443    /// Whether to allow the noop backend to be used.
444    ///
445    /// The noop backend stubs out all operations except for buffer creation and mapping, so
446    /// it must not be used when not expected. Therefore, it will not be used unless explicitly
447    /// enabled.
448    pub enable: bool,
449}
450
451impl NoopBackendOptions {
452    /// Choose whether the noop backend is enabled from the environment.
453    ///
454    /// It will be enabled if the environment variable `WGPU_NOOP_BACKEND` has the value `1`
455    /// and not otherwise. Future versions may assign other meanings to other values.
456    #[must_use]
457    pub fn from_env_or_default() -> Self {
458        Self {
459            enable: Self::enable_from_env().unwrap_or(false),
460        }
461    }
462
463    /// Takes the given options, modifies them based on the environment variables, and returns the
464    /// result.
465    ///
466    /// See [`from_env_or_default()`](Self::from_env_or_default) for the interpretation.
467    #[must_use]
468    pub fn with_env(self) -> Self {
469        Self {
470            enable: Self::enable_from_env().unwrap_or(self.enable),
471        }
472    }
473
474    fn enable_from_env() -> Option<bool> {
475        let value = crate::env::var("WGPU_NOOP_BACKEND")?;
476        match value.as_str() {
477            "1" => Some(true),
478            "0" => Some(false),
479            _ => None,
480        }
481    }
482}
483
484#[derive(Clone, Debug, Default, Copy, PartialEq, Eq)]
485/// Selects which kind of swapchain to use on DX12.
486pub enum Dx12SwapchainKind {
487    /// Use a DXGI swapchain made directly from the window's HWND.
488    ///
489    /// This does not support transparency but has better support from developer tooling from RenderDoc.
490    #[default]
491    DxgiFromHwnd,
492    /// Use a DXGI swapchain made from a DirectComposition visual made automatically from the window's HWND.
493    ///
494    /// This creates a single [`IDCompositionVisual`] over the entire window that is used by the `Surface`.
495    /// If a user wants to manage the composition tree themselves, they should create their own device and
496    /// composition, and pass the relevant visual down via [`SurfaceTargetUnsafe::CompositionVisual`][CV].
497    ///
498    /// This supports transparent windows, but does not have support from RenderDoc.
499    ///
500    /// [`IDCompositionVisual`]: https://learn.microsoft.com/en-us/windows/win32/api/dcomp/nn-dcomp-idcompositionvisual
501    #[doc = link_to_wgpu_docs!(["CV"]: "struct.SurfaceTargetUnsafe.html#variant.CompositionVisual")]
502    DxgiFromVisual,
503}
504
505impl Dx12SwapchainKind {
506    /// Choose which presentation system to use from the environment variable `WGPU_DX12_PRESENTATION_SYSTEM`.
507    ///
508    /// Valid values, case insensitive:
509    /// - `DxgiFromVisual` or `Visual`
510    /// - `DxgiFromHwnd` or `Hwnd` for [`Self::DxgiFromHwnd`]
511    #[must_use]
512    pub fn from_env() -> Option<Self> {
513        let value = crate::env::var("WGPU_DX12_PRESENTATION_SYSTEM")
514            .as_deref()?
515            .to_lowercase();
516        match value.as_str() {
517            "dxgifromvisual" | "visual" => Some(Self::DxgiFromVisual),
518            "dxgifromhwnd" | "hwnd" => Some(Self::DxgiFromHwnd),
519            _ => None,
520        }
521    }
522
523    /// Takes the given presentation system, modifies it based on the `WGPU_DX12_PRESENTATION_SYSTEM` environment variable, and returns the result.
524    ///
525    /// See [`from_env`](Self::from_env) for more information.
526    #[must_use]
527    pub fn with_env(self) -> Self {
528        if let Some(presentation_system) = Self::from_env() {
529            presentation_system
530        } else {
531            self
532        }
533    }
534}
535
536/// DXC shader model.
537#[derive(Clone, Debug)]
538#[allow(missing_docs)]
539pub enum DxcShaderModel {
540    V6_0,
541    V6_1,
542    V6_2,
543    V6_3,
544    V6_4,
545    V6_5,
546    V6_6,
547    V6_7,
548    V6_8,
549    V6_9,
550}
551
552impl DxcShaderModel {
553    /// Get the shader model supported by a certain DXC version.
554    pub fn from_dxc_version(major: u32, minor: u32) -> Self {
555        // DXC version roughly has corresponded to shader model so far, where DXC 1.x supports SM 6.x.
556        // See discussion in https://discord.com/channels/590611987420020747/996417435374714920/1471234702206701650.
557        // Presumably DXC 2.0 and up will still support shader model 6.9.
558        if major > 1 {
559            Self::V6_9
560        } else {
561            Self::from_parts(6, minor)
562        }
563    }
564
565    /// Parse a DxcShaderModel from its version components.
566    pub fn from_parts(major: u32, minor: u32) -> Self {
567        if major > 6 || minor > 8 {
568            Self::V6_9
569        } else {
570            match minor {
571                0 => DxcShaderModel::V6_0,
572                1 => DxcShaderModel::V6_1,
573                2 => DxcShaderModel::V6_2,
574                3 => DxcShaderModel::V6_3,
575                4 => DxcShaderModel::V6_4,
576                5 => DxcShaderModel::V6_5,
577                6 => DxcShaderModel::V6_6,
578                7 => DxcShaderModel::V6_7,
579                8 => DxcShaderModel::V6_8,
580                9 => DxcShaderModel::V6_9,
581                // > 6.9
582                _ => DxcShaderModel::V6_9,
583            }
584        }
585    }
586}
587
588/// Selects which DX12 shader compiler to use.
589#[derive(Clone, Debug, Default)]
590pub enum Dx12Compiler {
591    /// The Fxc compiler (default) is old, slow and unmaintained.
592    ///
593    /// However, it doesn't require any additional .dlls to be shipped with the application.
594    Fxc,
595    /// The Dxc compiler is new, fast and maintained.
596    ///
597    /// However, it requires `dxcompiler.dll` to be shipped with the application.
598    /// These files can be downloaded from <https://github.com/microsoft/DirectXShaderCompiler/releases>.
599    ///
600    /// Minimum supported version: [v1.8.2502](https://github.com/microsoft/DirectXShaderCompiler/releases/tag/v1.8.2502)
601    ///
602    /// It also requires WDDM 2.1 (Windows 10 version 1607).
603    DynamicDxc {
604        /// Path to `dxcompiler.dll`.
605        dxc_path: String,
606    },
607    /// The statically-linked variant of Dxc.
608    ///
609    /// The `static-dxc` feature is required for this setting to be used successfully on DX12.
610    /// Not available on `windows-aarch64-pc-*` targets.
611    StaticDxc,
612    /// Use statically-linked DXC if available. Otherwise check for dynamically linked DXC on the PATH. Finally, fallback to FXC.
613    #[default]
614    Auto,
615}
616
617impl Dx12Compiler {
618    /// Helper function to construct a `DynamicDxc` variant with default paths.
619    ///
620    /// The dll must support at least shader model 6.8.
621    pub fn default_dynamic_dxc() -> Self {
622        Self::DynamicDxc {
623            dxc_path: String::from("dxcompiler.dll"),
624        }
625    }
626
627    /// Choose which DX12 shader compiler to use from the environment variable `WGPU_DX12_COMPILER`.
628    ///
629    /// Valid values, case insensitive:
630    /// - `Fxc`
631    /// - `Dxc` or `DynamicDxc`
632    /// - `StaticDxc`
633    #[must_use]
634    pub fn from_env() -> Option<Self> {
635        let value = crate::env::var("WGPU_DX12_COMPILER")
636            .as_deref()?
637            .to_lowercase();
638        match value.as_str() {
639            "dxc" | "dynamicdxc" => Some(Self::default_dynamic_dxc()),
640            "staticdxc" => Some(Self::StaticDxc),
641            "fxc" => Some(Self::Fxc),
642            "auto" => Some(Self::Auto),
643            _ => None,
644        }
645    }
646
647    /// Takes the given compiler, modifies it based on the `WGPU_DX12_COMPILER` environment variable, and returns the result.
648    ///
649    /// See `from_env` for more information.
650    #[must_use]
651    pub fn with_env(self) -> Self {
652        if let Some(compiler) = Self::from_env() {
653            compiler
654        } else {
655            self
656        }
657    }
658}
659
660/// Whether and how to use a waitable handle obtained from `GetFrameLatencyWaitableObject`.
661#[derive(Clone, Debug, Default)]
662pub enum Dx12UseFrameLatencyWaitableObject {
663    /// Do not obtain a waitable handle and do not wait for it. The swapchain will
664    /// be created without the `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT` flag.
665    None,
666    /// Obtain a waitable handle and wait for it before acquiring the next swapchain image.
667    #[default]
668    Wait,
669    /// Create the swapchain with the `DXGI_SWAP_CHAIN_FLAG_FRAME_LATENCY_WAITABLE_OBJECT` flag and
670    /// obtain a waitable handle, but do not wait for it before acquiring the next swapchain image.
671    /// This is useful if the application wants to wait for the waitable object itself.
672    DontWait,
673}
674
675impl Dx12UseFrameLatencyWaitableObject {
676    /// Choose whether to use a frame latency waitable object from the environment variable `WGPU_DX12_USE_FRAME_LATENCY_WAITABLE_OBJECT`.
677    ///
678    /// Valid values, case insensitive:
679    /// - `None`
680    /// - `Wait`
681    /// - `DontWait`
682    #[must_use]
683    pub fn from_env() -> Option<Self> {
684        let value = crate::env::var("WGPU_DX12_USE_FRAME_LATENCY_WAITABLE_OBJECT")
685            .as_deref()?
686            .to_lowercase();
687        match value.as_str() {
688            "none" => Some(Self::None),
689            "wait" => Some(Self::Wait),
690            "dontwait" => Some(Self::DontWait),
691            _ => None,
692        }
693    }
694
695    /// Takes the given setting, modifies it based on the `WGPU_DX12_USE_FRAME_LATENCY_WAITABLE_OBJECT` environment variable, and returns the result.
696    ///
697    /// See `from_env` for more information.
698    #[must_use]
699    pub fn with_env(self) -> Self {
700        if let Some(compiler) = Self::from_env() {
701            compiler
702        } else {
703            self
704        }
705    }
706}
707
708/// Selects which OpenGL ES 3 minor version to request.
709///
710/// When using ANGLE as an OpenGL ES/EGL implementation, explicitly requesting `Version1` can provide a non-conformant ES 3.1 on APIs like D3D11.
711#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
712pub enum Gles3MinorVersion {
713    /// No explicit minor version is requested, the driver automatically picks the highest available.
714    #[default]
715    Automatic,
716
717    /// Request an ES 3.0 context.
718    Version0,
719
720    /// Request an ES 3.1 context.
721    Version1,
722
723    /// Request an ES 3.2 context.
724    Version2,
725}
726
727impl Gles3MinorVersion {
728    /// Choose which minor OpenGL ES version to use from the environment variable `WGPU_GLES_MINOR_VERSION`.
729    ///
730    /// Possible values are `0`, `1`, `2` or `automatic`. Case insensitive.
731    ///
732    /// Use with `unwrap_or_default()` to get the default value if the environment variable is not set.
733    #[must_use]
734    pub fn from_env() -> Option<Self> {
735        let value = crate::env::var("WGPU_GLES_MINOR_VERSION")
736            .as_deref()?
737            .to_lowercase();
738        match value.as_str() {
739            "automatic" => Some(Self::Automatic),
740            "0" => Some(Self::Version0),
741            "1" => Some(Self::Version1),
742            "2" => Some(Self::Version2),
743            _ => None,
744        }
745    }
746
747    /// Takes the given compiler, modifies it based on the `WGPU_GLES_MINOR_VERSION` environment variable, and returns the result.
748    ///
749    /// See `from_env` for more information.
750    #[must_use]
751    pub fn with_env(self) -> Self {
752        if let Some(compiler) = Self::from_env() {
753            compiler
754        } else {
755            self
756        }
757    }
758}
759
760/// Dictate the behavior of fences in OpenGL.
761#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
762pub enum GlFenceBehavior {
763    /// Fences in OpenGL behave normally. If you don't know what to pick, this is what you want.
764    #[default]
765    Normal,
766    /// Fences in OpenGL are short-circuited to always return `true` immediately.
767    ///
768    /// This solves a very specific issue that arose due to a bug in wgpu-core that made
769    /// many WebGL programs work when they "shouldn't" have. If you have code that is trying
770    /// to call `device.poll(wgpu::PollType::Wait)` on WebGL, you need to enable this option
771    /// for the "Wait" to behave how you would expect.
772    ///
773    /// Previously all `poll(Wait)` acted like the OpenGL fences were signalled even if they weren't.
774    /// See <https://github.com/gfx-rs/wgpu/issues/4589> for more information.
775    ///
776    /// When this is set `Queue::on_completed_work_done` will always return the next time the device
777    /// is maintained, not when the work is actually done on the GPU.
778    AutoFinish,
779}
780
781impl GlFenceBehavior {
782    /// Returns true if the fence behavior is `AutoFinish`.
783    pub fn is_auto_finish(&self) -> bool {
784        matches!(self, Self::AutoFinish)
785    }
786
787    /// Returns true if the fence behavior is `Normal`.
788    pub fn is_normal(&self) -> bool {
789        matches!(self, Self::Normal)
790    }
791
792    /// Choose which minor OpenGL ES version to use from the environment variable `WGPU_GL_FENCE_BEHAVIOR`.
793    ///
794    /// Possible values are `Normal` or `AutoFinish`. Case insensitive.
795    ///
796    /// Use with `unwrap_or_default()` to get the default value if the environment variable is not set.
797    #[must_use]
798    pub fn from_env() -> Option<Self> {
799        let value = crate::env::var("WGPU_GL_FENCE_BEHAVIOR")
800            .as_deref()?
801            .to_lowercase();
802        match value.as_str() {
803            "normal" => Some(Self::Normal),
804            "autofinish" => Some(Self::AutoFinish),
805            _ => None,
806        }
807    }
808
809    /// Takes the given compiler, modifies it based on the `WGPU_GL_FENCE_BEHAVIOR` environment variable, and returns the result.
810    ///
811    /// See `from_env` for more information.
812    #[must_use]
813    pub fn with_env(self) -> Self {
814        if let Some(fence) = Self::from_env() {
815            fence
816        } else {
817            self
818        }
819    }
820}