From 118a985ccd914f43ba23adb2bd7fba4c56351e4f Mon Sep 17 00:00:00 2001 From: Kevin Reid Date: Tue, 11 Feb 2025 09:13:31 -0800 Subject: [PATCH] Allow creating `Noop` backend through the normal mechanisms. --- CHANGELOG.md | 8 ++++ Cargo.toml | 1 + deno_webgpu/lib.rs | 1 + tests/src/init.rs | 2 + wgpu-core/Cargo.toml | 4 ++ wgpu-core/src/instance.rs | 2 + wgpu-hal/src/lib.rs | 1 + wgpu-hal/src/noop/mod.rs | 17 ++++++++- wgpu-types/src/instance.rs | 77 ++++++++++++++++++++++++++++++++++---- wgpu-types/src/lib.rs | 40 +++++++++++++++++++- wgpu/Cargo.toml | 8 ++++ wgpu/src/lib.rs | 2 +- 12 files changed, 151 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 234a8d65b..93961b42a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,14 @@ Bottom level categories: ### New Features +#### General + +- It is now possible to create a dummy `wgpu` device even when no GPU is available. This may be useful for testing of code which manages graphics resources. Currently, it supports reading and writing buffers, and other resource types can be created but do nothing. + + To use it, enable the `noop` feature of `wgpu`, and add `NoopBackendOptions { enable: true }` to the backend options; this is an additional safeguard beyond the `Backends` bits. + + By @kpreid in [#7063](https://github.com/gfx-rs/wgpu/pull/7063). + #### Naga - Support @must_use attribute on function declarations. By @turbocrime in [#6801](https://github.com/gfx-rs/wgpu/pull/6801). diff --git a/Cargo.toml b/Cargo.toml index 2b0a1d350..6d98d9904 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,6 +66,7 @@ wgpu = { version = "24.0.0", path = "./wgpu", default-features = false, features "metal", "static-dxc", "webgl", + "noop", # This should be removed if we ever have non-test crates that depend on wgpu ] } wgpu-core = { version = "24.0.0", path = "./wgpu-core" } wgpu-hal = { version = "24.0.0", path = "./wgpu-hal" } diff --git a/deno_webgpu/lib.rs b/deno_webgpu/lib.rs index d4c201bb0..2527c25c6 100644 --- a/deno_webgpu/lib.rs +++ b/deno_webgpu/lib.rs @@ -394,6 +394,7 @@ pub fn op_webgpu_request_adapter( shader_compiler: wgpu_types::Dx12Compiler::Fxc, }, gl: wgpu_types::GlBackendOptions::default(), + noop: wgpu_types::NoopBackendOptions::default(), }, }, ))); diff --git a/tests/src/init.rs b/tests/src/init.rs index 60639f67a..28c7f334a 100644 --- a/tests/src/init.rs +++ b/tests/src/init.rs @@ -43,6 +43,8 @@ pub fn initialize_instance(backends: wgpu::Backends, force_fxc: bool) -> Instanc shader_compiler: dx12_shader_compiler, }, gl: wgpu::GlBackendOptions::from_env_or_default(), + // TODO(https://github.com/gfx-rs/wgpu/issues/7119): Enable noop backend? + noop: wgpu::NoopBackendOptions::default(), }, }) } diff --git a/wgpu-core/Cargo.toml b/wgpu-core/Cargo.toml index 41481e3cd..29f1fd8df 100644 --- a/wgpu-core/Cargo.toml +++ b/wgpu-core/Cargo.toml @@ -113,6 +113,10 @@ gles = ["wgpu-hal/gles"] ## Enable the `dx12` backend. dx12 = ["wgpu-hal/dx12"] +## Enable the `noop` backend. +# TODO(https://github.com/gfx-rs/wgpu/issues/7120): there should be a hal feature +noop = [] + [dependencies] naga.workspace = true wgpu-hal.workspace = true diff --git a/wgpu-core/src/instance.rs b/wgpu-core/src/instance.rs index c19a51d58..bf413b04e 100644 --- a/wgpu-core/src/instance.rs +++ b/wgpu-core/src/instance.rs @@ -107,6 +107,8 @@ impl Instance { init(hal::api::Dx12, instance_desc, &mut instance_per_backend); #[cfg(gles)] init(hal::api::Gles, instance_desc, &mut instance_per_backend); + #[cfg(feature = "noop")] + init(hal::api::Noop, instance_desc, &mut instance_per_backend); Self { name: name.to_string(), diff --git a/wgpu-hal/src/lib.rs b/wgpu-hal/src/lib.rs index 99277747e..dd2ecb9de 100644 --- a/wgpu-hal/src/lib.rs +++ b/wgpu-hal/src/lib.rs @@ -246,6 +246,7 @@ pub mod gles; #[cfg(metal)] pub mod metal; /// A dummy API implementation. +// TODO(https://github.com/gfx-rs/wgpu/issues/7120): this should have a cfg pub mod noop; /// Vulkan API internals. #[cfg(vulkan)] diff --git a/wgpu-hal/src/noop/mod.rs b/wgpu-hal/src/noop/mod.rs index 232c890ea..9c0b5bdea 100644 --- a/wgpu-hal/src/noop/mod.rs +++ b/wgpu-hal/src/noop/mod.rs @@ -81,7 +81,22 @@ impl crate::Instance for Context { type A = Api; unsafe fn init(desc: &crate::InstanceDescriptor) -> Result { - Ok(Context) + let crate::InstanceDescriptor { + backend_options: + wgt::BackendOptions { + noop: wgt::NoopBackendOptions { enable }, + .. + }, + name: _, + flags: _, + } = *desc; + if enable { + Ok(Context) + } else { + Err(crate::InstanceError::new(String::from( + "noop backend disabled because NoopBackendOptions::enable is false", + ))) + } } unsafe fn create_surface( &self, diff --git a/wgpu-types/src/instance.rs b/wgpu-types/src/instance.rs index 7e417a723..68848ccaa 100644 --- a/wgpu-types/src/instance.rs +++ b/wgpu-types/src/instance.rs @@ -4,6 +4,9 @@ use alloc::string::String; use crate::Backends; +#[cfg(doc)] +use crate::Backend; + /// Options for creating an instance. #[derive(Clone, Debug)] pub struct InstanceDescriptor { @@ -181,12 +184,16 @@ impl InstanceFlags { } /// Options that are passed to a given backend. +/// +/// Part of [`InstanceDescriptor`]. #[derive(Clone, Debug, Default)] pub struct BackendOptions { - /// Options for the OpenGL/OpenGLES backend. + /// Options for the OpenGL/OpenGLES backend, [`Backend::Gl`]. pub gl: GlBackendOptions, - /// Options for the DX12 backend. + /// Options for the DX12 backend, [`Backend::Dx12`]. pub dx12: Dx12BackendOptions, + /// Options for the noop backend, [`Backend::Noop`]. + pub noop: NoopBackendOptions, } impl BackendOptions { @@ -195,9 +202,11 @@ impl BackendOptions { /// See those methods for more information. #[must_use] pub fn from_env_or_default() -> Self { - let gl = GlBackendOptions::from_env_or_default(); - let dx12 = Dx12BackendOptions::from_env_or_default(); - Self { gl, dx12 } + Self { + gl: GlBackendOptions::from_env_or_default(), + dx12: Dx12BackendOptions::from_env_or_default(), + noop: NoopBackendOptions::from_env_or_default(), + } } /// Takes the given options, modifies them based on the environment variables, and returns the result. @@ -205,13 +214,17 @@ impl BackendOptions { /// This is equivalent to calling `with_env` on every field. #[must_use] pub fn with_env(self) -> Self { - let gl = self.gl.with_env(); - let dx12 = self.dx12.with_env(); - Self { gl, dx12 } + Self { + gl: self.gl.with_env(), + dx12: self.dx12.with_env(), + noop: self.noop.with_env(), + } } } /// Configuration for the OpenGL/OpenGLES backend. +/// +/// Part of [`BackendOptions`]. #[derive(Clone, Debug, Default)] pub struct GlBackendOptions { /// Which OpenGL ES 3 minor version to request, if using OpenGL ES. @@ -248,6 +261,8 @@ impl GlBackendOptions { } /// Configuration for the DX12 backend. +/// +/// Part of [`BackendOptions`]. #[derive(Clone, Debug, Default)] pub struct Dx12BackendOptions { /// Which DX12 shader compiler to use. @@ -276,6 +291,52 @@ impl Dx12BackendOptions { } } +/// Configuration for the noop backend. +/// +/// Part of [`BackendOptions`]. +#[derive(Clone, Debug, Default)] +pub struct NoopBackendOptions { + /// Whether to allow the noop backend to be used. + /// + /// The noop backend stubs out all operations except for buffer creation and mapping, so + /// it must not be used when not expected. Therefore, it will not be used unless explicitly + /// enabled. + pub enable: bool, +} + +impl NoopBackendOptions { + /// Choose whether the noop backend is enabled from the environment. + /// + /// It will be enabled if the environment variable `WGPU_NOOP_BACKEND` has the value `1` + /// and not otherwise. Future versions may assign other meanings to other values. + #[must_use] + pub fn from_env_or_default() -> Self { + Self { + enable: Self::enable_from_env().unwrap_or(false), + } + } + + /// Takes the given options, modifies them based on the environment variables, and returns the + /// result. + /// + /// See [`from_env_or_default()`](Self::from_env_or_default) for the interpretation. + #[must_use] + pub fn with_env(self) -> Self { + Self { + enable: Self::enable_from_env().unwrap_or(self.enable), + } + } + + fn enable_from_env() -> Option { + let value = crate::env::var("WGPU_NOOP_BACKEND")?; + match value.as_str() { + "1" => Some(true), + "0" => Some(false), + _ => None, + } + } +} + /// Selects which DX12 shader compiler to use. /// /// If the `DynamicDxc` option is selected, but `dxcompiler.dll` and `dxil.dll` files aren't found, diff --git a/wgpu-types/src/lib.rs b/wgpu-types/src/lib.rs index a217127df..18e5ce5b8 100644 --- a/wgpu-types/src/lib.rs +++ b/wgpu-types/src/lib.rs @@ -71,11 +71,32 @@ pub const QUERY_SET_MAX_QUERIES: u32 = 4096; pub const QUERY_SIZE: u32 = 8; /// Backends supported by wgpu. +/// +/// See also [`Backends`]. #[repr(u8)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Backend { /// Dummy backend, which may be used for testing. + /// + /// It performs no rendering or computation, but allows creation of stub GPU resource types, + /// so that code which manages GPU resources can be tested without an available GPU. + /// Specifically, the following operations are implemented: + /// + /// * Enumerating adapters will always return one noop adapter, which can be used to create + /// devices. + /// * Buffers may be created, written, mapped, and copied to other buffers. + /// * Command encoders may be created, but only buffer operations are useful. + /// + /// Other resources can be created but are nonfunctional; notably, + /// + /// * Render passes and compute passes are not executed. + /// * Textures may be created, but do not store any texels. + /// * There are no compatible surfaces. + /// + /// An adapter using the noop backend can only be obtained if [`NoopBackendOptions`] + /// enables it, in addition to the ordinary requirement of [`Backends::NOOP`] being set. + /// This ensures that applications not desiring a non-functional backend will not receive it. Noop = 0, /// Vulkan API (Windows, Linux, Android, MacOS via `vulkan-portability`/MoltenVK) Vulkan = 1, @@ -148,22 +169,35 @@ bitflags::bitflags! { #[cfg_attr(feature = "serde", serde(transparent))] #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] pub struct Backends: u32 { + /// [`Backend::Noop`]. + const NOOP = 1 << Backend::Noop as u32; + + /// [`Backend::Vulkan`]. /// Supported on Windows, Linux/Android, and macOS/iOS via Vulkan Portability (with the Vulkan feature enabled) const VULKAN = 1 << Backend::Vulkan as u32; + + /// [`Backend::Gl`]. /// Supported on Linux/Android, the web through webassembly via WebGL, and Windows and /// macOS/iOS via ANGLE const GL = 1 << Backend::Gl as u32; - /// Supported on macOS/iOS + + /// [`Backend::Metal`]. + /// Supported on macOS and iOS. const METAL = 1 << Backend::Metal as u32; + + /// [`Backend::Dx12`]. /// Supported on Windows 10 and later const DX12 = 1 << Backend::Dx12 as u32; - /// Supported when targeting the web through webassembly with the `webgpu` feature enabled. + + /// [`Backend::BrowserWebGpu`]. + /// Supported when targeting the web through WebAssembly with the `webgpu` feature enabled. /// /// The WebGPU backend is special in several ways: /// It is not not implemented by `wgpu_core` and instead by the higher level `wgpu` crate. /// Whether WebGPU is targeted is decided upon the creation of the `wgpu::Instance`, /// *not* upon adapter creation. See `wgpu::Instance::new`. const BROWSER_WEBGPU = 1 << Backend::BrowserWebGpu as u32; + /// All the apis that wgpu offers first tier of support for. /// /// * [`Backends::VULKAN`] @@ -174,6 +208,7 @@ bitflags::bitflags! { | Self::METAL.bits() | Self::DX12.bits() | Self::BROWSER_WEBGPU.bits(); + /// All the apis that wgpu offers second tier of support for. These may /// be unsupported/still experimental. /// @@ -233,6 +268,7 @@ impl Backends { "metal" | "mtl" => Self::METAL, "opengl" | "gles" | "gl" => Self::GL, "webgpu" => Self::BROWSER_WEBGPU, + "noop" => Self::NOOP, b => { log::warn!("unknown backend string '{}'", b); continue; diff --git a/wgpu/Cargo.toml b/wgpu/Cargo.toml index a69809c64..5574fd5ee 100644 --- a/wgpu/Cargo.toml +++ b/wgpu/Cargo.toml @@ -57,6 +57,14 @@ vulkan-portability = ["wgpu-core?/vulkan"] ## * ⚠️ WIP: Currently will also enable GLES dependencies on any other targets. webgl = ["dep:wgpu-hal", "wgpu-core/gles"] +## 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`. +noop = ["wgpu-core/noop"] + #! **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. diff --git a/wgpu/src/lib.rs b/wgpu/src/lib.rs index cdfa2bbb1..ed0393c8a 100644 --- a/wgpu/src/lib.rs +++ b/wgpu/src/lib.rs @@ -67,7 +67,7 @@ pub use wgt::{ Dx12BackendOptions, Dx12Compiler, DynamicOffset, Extent3d, Face, Features, FeaturesWGPU, FeaturesWebGPU, FilterMode, FrontFace, GlBackendOptions, Gles3MinorVersion, HalCounters, ImageSubresourceRange, IndexFormat, InstanceDescriptor, InstanceFlags, InternalCounters, - Limits, MaintainResult, MemoryHints, MultisampleState, Origin2d, Origin3d, + Limits, MaintainResult, MemoryHints, MultisampleState, NoopBackendOptions, Origin2d, Origin3d, PipelineStatisticsTypes, PolygonMode, PowerPreference, PredefinedColorSpace, PresentMode, PresentationTimestamp, PrimitiveState, PrimitiveTopology, PushConstantRange, QueryType, RenderBundleDepthStencil, SamplerBindingType, SamplerBorderColor, ShaderLocation, ShaderModel,