From f59124f3f64c270601654b79e97cb93e565fd338 Mon Sep 17 00:00:00 2001 From: Connor Fitzgerald Date: Mon, 16 Mar 2026 20:43:32 -0400 Subject: [PATCH] Add support for the D3D12 Agility SDK (#9130) --- .../actions/install-agility-sdk/action.yml | 11 ++ .github/workflows/ci.yml | 4 + CHANGELOG.md | 29 +++ tests/src/init.rs | 6 +- wgpu-hal/src/dx12/adapter.rs | 8 +- wgpu-hal/src/dx12/device_creation.rs | 176 ++++++++++++++++++ wgpu-hal/src/dx12/instance.rs | 40 ++-- wgpu-hal/src/dx12/mod.rs | 53 ++++++ wgpu-types/src/backend.rs | 164 ++++++++++++++++ xtask/src/install_agility_sdk.rs | 113 +++++++++++ xtask/src/main.rs | 15 +- xtask/src/test.rs | 56 ++++-- 12 files changed, 623 insertions(+), 52 deletions(-) create mode 100644 .github/actions/install-agility-sdk/action.yml create mode 100644 wgpu-hal/src/dx12/device_creation.rs create mode 100644 xtask/src/install_agility_sdk.rs diff --git a/.github/actions/install-agility-sdk/action.yml b/.github/actions/install-agility-sdk/action.yml new file mode 100644 index 000000000..ba05465ec --- /dev/null +++ b/.github/actions/install-agility-sdk/action.yml @@ -0,0 +1,11 @@ +name: "Install Agility SDK" +description: "Install the D3D12 Agility SDK and export its environment variables" +runs: + using: "composite" + steps: + - shell: bash + run: | + set -e + + cargo xtask install-agility-sdk >> "$GITHUB_ENV" + echo WGPU_DX12_AGILITY_SDK_REQUIRE=1 >> "$GITHUB_ENV" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2642b7468..c864629f0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -641,6 +641,10 @@ jobs: with: target-dir: "target/llvm-cov-target/debug" + - name: (Windows) Install Agility SDK + if: matrix.os == 'windows-2022' + uses: ./.github/actions/install-agility-sdk + - name: (Windows) Install Mesa if: matrix.os == 'windows-2022' uses: ./.github/actions/install-mesa diff --git a/CHANGELOG.md b/CHANGELOG.md index 63795190d..63f23c4ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,35 @@ depth_stencil: Some(wgpu::DepthStencilState::stencil( )), ``` +#### D3D12 Agility SDK support + +Added support for loading a specific [DirectX 12 Agility SDK](https://devblogs.microsoft.com/directx/directx12agility/) runtime via the [Independent Devices API](https://devblogs.microsoft.com/directx/d3d12-independent-devices/). The Agility SDK lets applications ship a newer D3D12 runtime alongside their binary, unlocking the latest D3D12 features without waiting for an OS update. + +Configure it programmatically: + +```rust +let options = wgpu::Dx12BackendOptions { + agility_sdk: Some(wgpu::Dx12AgilitySDK { + sdk_version: 619, + sdk_path: "path/to/sdk/bin/x64".into(), + }), + ..Default::default() +}; +``` + +Or via environment variables: + +``` +WGPU_DX12_AGILITY_SDK_PATH=path/to/sdk/bin/x64 +WGPU_DX12_AGILITY_SDK_VERSION=619 +``` + +The `sdk_version` must match the version of the `D3D12Core.dll` in the provided path exactly, or loading will fail. + +If the Agility SDK fails to load (e.g. version mismatch, missing DLL, or unsupported OS), wgpu logs a warning and falls back to the system D3D12 runtime. + +By @cwfitzgerald in [#9130](https://github.com/gfx-rs/wgpu/pull/9130). + #### `WriteOnly` To ensure memory safety when accessing mapped GPU memory, `MapMode::Write` buffer mappings (`BufferViewMut` and also `QueueWriteBufferView`) can no longer be dereferenced to Rust `&mut [u8]`. Instead, they must be used through the new pointer type `wgpu::WriteOnly<[u8]>`, which does not allow reading at all. diff --git a/tests/src/init.rs b/tests/src/init.rs index 2748d92b4..92b881ec4 100644 --- a/tests/src/init.rs +++ b/tests/src/init.rs @@ -64,8 +64,7 @@ pub fn initialize_instance(backends: wgpu::Backends, params: &TestParameters) -> wgpu::GlFenceBehavior::Normal }, ..Default::default() - } - .with_env(), + }, // Allow the noop backend to be used in tests. This will not be used unless // WGPU_GPU_TESTS_USE_NOOP_BACKEND env var is set, because wgpu-info will not // enumerate the noop backend. @@ -75,7 +74,8 @@ pub fn initialize_instance(backends: wgpu::Backends, params: &TestParameters) -> noop: wgpu::NoopBackendOptions { enable: !cfg!(target_arch = "wasm32"), }, - }, + } + .with_env(), #[cfg(not(all( target_arch = "wasm32", any(target_os = "emscripten", feature = "webgl") diff --git a/wgpu-hal/src/dx12/adapter.rs b/wgpu-hal/src/dx12/adapter.rs index 5c81552d0..a254069f6 100644 --- a/wgpu-hal/src/dx12/adapter.rs +++ b/wgpu-hal/src/dx12/adapter.rs @@ -23,7 +23,10 @@ use crate::{ self, dxgi::{factory::DxgiAdapter, result::HResult}, }, - dx12::{dcomp::DCompLib, shader_compilation, FeatureLevel, ShaderModel, SurfaceTarget}, + dx12::{ + dcomp::DCompLib, device_creation::DeviceFactory, shader_compilation, FeatureLevel, + ShaderModel, SurfaceTarget, + }, }; impl Drop for super::Adapter { @@ -62,6 +65,7 @@ impl super::Adapter { pub(super) fn expose( adapter: DxgiAdapter, library: &Arc, + device_factory: &Arc, dcomp_lib: &Arc, instance_flags: wgt::InstanceFlags, memory_budget_thresholds: wgt::MemoryBudgetThresholds, @@ -86,7 +90,7 @@ impl super::Adapter { // Create the device so that we can get the capabilities. let res = { profiling::scope!("ID3D12Device::create_device"); - library.create_device(&adapter, Direct3D::D3D_FEATURE_LEVEL_11_0) + device_factory.create_device(library, &adapter, Direct3D::D3D_FEATURE_LEVEL_11_0) }; if let Some(telemetry) = telemetry { if let Err(err) = res { diff --git a/wgpu-hal/src/dx12/device_creation.rs b/wgpu-hal/src/dx12/device_creation.rs new file mode 100644 index 000000000..dc5cdf9e2 --- /dev/null +++ b/wgpu-hal/src/dx12/device_creation.rs @@ -0,0 +1,176 @@ +use alloc::sync::Arc; +use core::ops::Deref; + +use windows::core::Interface as _; +use windows::Win32::Graphics::{Direct3D, Direct3D12}; + +use super::D3D12Lib; +use crate::auxil::dxgi::factory::DxgiAdapter; + +/// Abstraction over D3D12 device creation. +/// +/// Supports two paths: +/// - **Independent**: Uses `ID3D12DeviceFactory` from the Agility SDK's Independent Devices API. +/// - **Legacy**: Uses the traditional `D3D12CreateDevice` export. +pub(super) enum DeviceFactory { + /// Uses `ID3D12DeviceFactory` from the Independent Devices API. + Independent(Direct3D12::ID3D12DeviceFactory), + /// Uses the traditional `D3D12CreateDevice` export. + Legacy, +} + +impl DeviceFactory { + /// Create a new `DeviceFactory`. + /// + /// If `agility_sdk` is `Some`, attempts to set up the Independent Devices API path. + /// On failure, the behavior depends on + /// [`on_load_failure`](wgt::Dx12AgilitySDKLoadFailure): + /// - [`Fallback`](wgt::Dx12AgilitySDKLoadFailure::Fallback): logs a warning and + /// returns `Ok(Legacy)`. + /// - [`Error`](wgt::Dx12AgilitySDKLoadFailure::Error): returns an `Err`. + pub(super) fn new( + lib: &D3D12Lib, + agility_sdk: Option<&wgt::Dx12AgilitySDK>, + ) -> Result { + let Some(agility_sdk) = agility_sdk else { + log::debug!("No D3D12 Agility SDK configuration provided; using system D3D12 runtime"); + return Ok(Self::Legacy); + }; + + match Self::try_create_independent(lib, agility_sdk) { + Ok(factory) => { + log::debug!( + "Using D3D12 Agility SDK v{} from '{}'", + agility_sdk.sdk_version, + agility_sdk.sdk_path + ); + Ok(Self::Independent(factory)) + } + Err(err) => { + let message = format!( + "Failed to initialize D3D12 Agility SDK (v{} at '{}'): {err}", + agility_sdk.sdk_version, agility_sdk.sdk_path + ); + + match agility_sdk.on_load_failure { + wgt::Dx12AgilitySDKLoadFailure::Fallback => { + log::warn!("{message}; falling back to system D3D12 runtime"); + Ok(Self::Legacy) + } + wgt::Dx12AgilitySDKLoadFailure::Error => { + Err(crate::InstanceError::new(message)) + } + } + } + } + } + + fn try_create_independent( + lib: &D3D12Lib, + agility_sdk: &wgt::Dx12AgilitySDK, + ) -> Result { + // Step 1: Get ID3D12SDKConfiguration1 via D3D12GetInterface + let sdk_config: Direct3D12::ID3D12SDKConfiguration1 = lib + .get_interface(&Direct3D12::CLSID_D3D12SDKConfiguration) + .map_err(DeviceFactoryError::GetInterface)?; + + // Step 2: Create device factory with the specified SDK version and path + let sdk_path = std::ffi::CString::new(agility_sdk.sdk_path.as_bytes()) + .map_err(|_| DeviceFactoryError::InvalidPath)?; + let factory: Direct3D12::ID3D12DeviceFactory = unsafe { + sdk_config.CreateDeviceFactory( + agility_sdk.sdk_version, + windows::core::PCSTR(sdk_path.as_ptr().cast::()), + ) + } + .map_err(DeviceFactoryError::CreateDeviceFactory)?; + + Ok(factory) + } + + /// Enable the D3D12 debug layer and optionally GPU-based validation. + /// + /// - **Legacy**: configures debug globally via `D3D12GetDebugInterface`. + /// - **Independent**: uses `GetConfigurationInterface` to get an + /// `ID3D12Debug` scoped to the factory. + pub(super) fn enable_debug_layer(&self, lib: &D3D12Lib, flags: wgt::InstanceFlags) { + if !flags + .intersects(wgt::InstanceFlags::VALIDATION | wgt::InstanceFlags::GPU_BASED_VALIDATION) + { + return; + } + + let debug_controller = match self { + Self::Independent(factory) => { + match unsafe { + factory.GetConfigurationInterface::( + &Direct3D12::CLSID_D3D12Debug, + ) + } { + Ok(debug) => debug, + Err(err) => { + log::warn!("Failed to get debug interface from device factory: {err}"); + return; + } + } + } + Self::Legacy => match lib.debug_interface() { + Ok(Some(debug)) => debug, + Ok(None) => return, + Err(err) => { + log::warn!("Failed to get debug interface: {err}"); + return; + } + }, + }; + + if flags.intersects(wgt::InstanceFlags::VALIDATION) { + unsafe { debug_controller.EnableDebugLayer() } + } + if flags.intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION) { + if let Ok(debug1) = debug_controller.cast::() { + unsafe { debug1.SetEnableGPUBasedValidation(true) } + } else { + log::warn!("Failed to enable GPU-based validation"); + } + } + } + + /// Create a D3D12 device using the appropriate method. + pub(super) fn create_device( + &self, + lib: &Arc, + adapter: &DxgiAdapter, + feature_level: Direct3D::D3D_FEATURE_LEVEL, + ) -> Result { + match self { + Self::Independent(factory) => { + let mut result__: Option = None; + unsafe { factory.CreateDevice(adapter.deref(), feature_level, &mut result__) } + .map_err(|e| super::CreateDeviceError::D3D12CreateDevice(e.into()))?; + + result__.ok_or(super::CreateDeviceError::RetDeviceIsNull) + } + Self::Legacy => lib.create_device(adapter, feature_level), + } + } +} + +impl core::fmt::Debug for DeviceFactory { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Independent(_) => write!(f, "DeviceFactory::Independent"), + Self::Legacy => write!(f, "DeviceFactory::Legacy"), + } + } +} + +#[derive(Debug, thiserror::Error)] +enum DeviceFactoryError { + #[error("failed to get ID3D12SDKConfiguration1: {0}")] + GetInterface(super::GetInterfaceError), + #[error("SDK path contains null bytes")] + InvalidPath, + #[error("CreateDeviceFactory failed: {0}")] + CreateDeviceFactory(windows::core::Error), +} diff --git a/wgpu-hal/src/dx12/instance.rs b/wgpu-hal/src/dx12/instance.rs index e2327f082..6c3a33b59 100644 --- a/wgpu-hal/src/dx12/instance.rs +++ b/wgpu-hal/src/dx12/instance.rs @@ -1,18 +1,14 @@ use alloc::{string::String, sync::Arc, vec::Vec}; use parking_lot::RwLock; -use windows::{ - core::Interface as _, - Win32::{ - Foundation, - Graphics::{Direct3D12, Dxgi}, - }, -}; +use windows::Win32::{Foundation, Graphics::Dxgi}; use super::SurfaceTarget; use crate::{ auxil, - dx12::{shader_compilation::CompilerContainer, D3D12Lib, DCompLib}, + dx12::{ + device_creation::DeviceFactory, shader_compilation::CompilerContainer, D3D12Lib, DCompLib, + }, }; impl crate::Instance for super::Instance { @@ -24,27 +20,11 @@ impl crate::Instance for super::Instance { crate::InstanceError::with_source(String::from("failed to load d3d12.dll"), e) })?; - if desc - .flags - .intersects(wgt::InstanceFlags::VALIDATION | wgt::InstanceFlags::GPU_BASED_VALIDATION) - { - // Enable debug layer - if let Ok(Some(debug_controller)) = lib_main.debug_interface() { - if desc.flags.intersects(wgt::InstanceFlags::VALIDATION) { - unsafe { debug_controller.EnableDebugLayer() } - } - if desc - .flags - .intersects(wgt::InstanceFlags::GPU_BASED_VALIDATION) - { - if let Ok(debug1) = debug_controller.cast::() { - unsafe { debug1.SetEnableGPUBasedValidation(true) } - } else { - log::warn!("Failed to enable GPU-based validation"); - } - } - } - } + // Create DeviceFactory first so we know which debug path to use + let device_factory = + DeviceFactory::new(&lib_main, desc.backend_options.dx12.agility_sdk.as_ref())?; + + device_factory.enable_debug_layer(&lib_main, desc.flags); let (lib_dxgi, factory) = auxil::dxgi::factory::create_factory(desc.flags)?; @@ -133,6 +113,7 @@ impl crate::Instance for super::Instance { factory, factory_media, library: Arc::new(lib_main), + device_factory: Arc::new(device_factory), dcomp_lib: Arc::new(DCompLib::new()), presentation_system: desc.backend_options.dx12.presentation_system, _lib_dxgi: lib_dxgi, @@ -193,6 +174,7 @@ impl crate::Instance for super::Instance { super::Adapter::expose( raw, &self.library, + &self.device_factory, &self.dcomp_lib, self.flags, self.memory_budget_thresholds, diff --git a/wgpu-hal/src/dx12/mod.rs b/wgpu-hal/src/dx12/mod.rs index 446b6d94e..ac520b270 100644 --- a/wgpu-hal/src/dx12/mod.rs +++ b/wgpu-hal/src/dx12/mod.rs @@ -78,6 +78,7 @@ mod conv; mod dcomp; mod descriptor; mod device; +mod device_creation; mod instance; mod pipeline_desc; mod sampler; @@ -266,8 +267,55 @@ impl D3D12Lib { result__.ok_or(crate::DeviceError::Unexpected).map(Some) } + + /// Calls D3D12GetInterface to obtain a COM interface by CLSID and IID. + /// + /// This is used by the Independent Devices API to obtain `ID3D12SDKConfiguration1`. + fn get_interface( + &self, + clsid: &windows_core::GUID, + ) -> Result { + // Calls windows::Win32::Graphics::Direct3D12::D3D12GetInterface on d3d12.dll + type Fun = extern "system" fn( + rclsid: *const windows_core::GUID, + riid: *const windows_core::GUID, + ppvdebug: *mut *mut ffi::c_void, + ) -> windows_core::HRESULT; + let func: libloading::Symbol = + unsafe { self.lib.get(c"D3D12GetInterface".to_bytes()) } + .map_err(|_| GetInterfaceError::GetProcAddress)?; + + let mut result__: Option = None; + + let res = (func)(clsid, &T::IID, <*mut _>::cast(&mut result__)); + + if res.is_err() { + return Err(GetInterfaceError::D3D12GetInterface(res)); + } + + result__.ok_or(GetInterfaceError::RetIsNull) + } } +#[derive(Clone, Copy, Debug)] +pub(super) enum GetInterfaceError { + GetProcAddress, + D3D12GetInterface(windows_core::HRESULT), + RetIsNull, +} + +impl fmt::Display for GetInterfaceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::GetProcAddress => write!(f, "D3D12GetInterface not found in d3d12.dll"), + Self::D3D12GetInterface(hr) => write!(f, "D3D12GetInterface failed: {hr}"), + Self::RetIsNull => write!(f, "D3D12GetInterface returned null"), + } + } +} + +impl core::error::Error for GetInterfaceError {} + #[derive(Debug)] pub(super) struct DxgiLib { lib: DynLib, @@ -466,6 +514,11 @@ const ZERO_BUFFER_SIZE: wgt::BufferAddress = 256 << 10; pub struct Instance { factory: DxgiFactory, factory_media: Option, + // `device_factory` must be dropped before `library` because the COM + // object's Release call goes through the d3d12.dll vtable. If + // `library` (which unloads d3d12.dll) is dropped first the Release + // segfaults. + device_factory: Arc, library: Arc, dcomp_lib: Arc, supports_allow_tearing: bool, diff --git a/wgpu-types/src/backend.rs b/wgpu-types/src/backend.rs index 91d192549..a0dd58b87 100644 --- a/wgpu-types/src/backend.rs +++ b/wgpu-types/src/backend.rs @@ -382,6 +382,154 @@ impl ForceShaderModelToken { } } +/// Behavior when the Agility SDK fails to load. +/// +/// See [`Dx12AgilitySDK`] for details on the Agility SDK. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub enum Dx12AgilitySDKLoadFailure { + /// Log a warning and fall back to the system-installed D3D12 runtime. + /// + /// This is the default behavior and is appropriate for most applications. + #[default] + Fallback, + /// Fail instance creation entirely if the Agility SDK cannot be loaded. + /// + /// Use this in environments where you are shipping the Agility SDK alongside your application + /// and want to ensure that it is being loaded correctly. + Error, +} + +impl Dx12AgilitySDKLoadFailure { + /// Read the load failure behavior from the environment variable + /// `WGPU_DX12_AGILITY_SDK_REQUIRE`. + /// + /// When set to `1`, returns [`Error`](Self::Error). + /// When set to `0`, returns [`Fallback`](Self::Fallback). + #[must_use] + pub fn from_env() -> Option { + let value = crate::env::var("WGPU_DX12_AGILITY_SDK_REQUIRE")?; + match value.as_str() { + "1" => Some(Self::Error), + "0" => Some(Self::Fallback), + _ => None, + } + } + + /// Takes the given setting, modifies it based on the + /// `WGPU_DX12_AGILITY_SDK_REQUIRE` environment variable, and returns the result. + /// + /// See [`from_env`](Self::from_env) for more information. + #[must_use] + pub fn with_env(self) -> Self { + if let Some(v) = Self::from_env() { + v + } else { + self + } + } +} + +/// Configuration for loading a specific [DirectX 12 Agility SDK] runtime. +/// +/// The Agility SDK allows applications to ship a newer version of the D3D12 runtime +/// (`D3D12Core.dll`) alongside the application, enabling access to the latest D3D12 +/// features without waiting for the OS to update its built-in runtime. This is the +/// standard way for games and applications to adopt new D3D12 functionality on older +/// Windows versions. +/// +/// Downloads and release notes are available at the [DirectX 12 Agility SDK] page. +/// +/// wgpu loads the Agility SDK via the [Independent Devices API], which allows +/// specifying the SDK path and version at runtime without requiring exported constants +/// or developer mode. The [`sdk_version`](Self::sdk_version) must match the version of +/// the `D3D12Core.dll` in the provided path exactly, or loading will fail, irrespective of +/// the OS's built-in runtime version. +/// +/// If the shipped SDK is older than the system runtime, the system runtime will be used. +/// This allows applications to ship a minimum SDK version while still benefiting from SDK updates on the user's system. +/// +/// If the Agility SDK fails to load (version mismatch, missing DLL, unsupported OS, +/// etc.), the behavior is controlled by [`on_load_failure`](Self::on_load_failure). +/// By default, wgpu logs a warning and falls back to the system-installed D3D12 runtime. +/// Set it to [`Error`](Dx12AgilitySDKLoadFailure::Error) to fail instance creation instead +/// (useful in CI/testing). +/// +/// ## OS requirements +/// +/// The Independent Devices API requires a Windows update from August/September 2023 +/// or newer: +/// +/// - [Windows 11 21H2+ (KB5029332)][win11-21h2] +/// - [Windows 10 22H2+ (KB5029331)][win10-22h2] +/// - [Windows Server 2022+ (KB5030216)][server-2022] +/// +/// On older OS builds the Agility SDK will not load and wgpu will log a warning and +/// fall back to the system runtime (or error, per [`on_load_failure`](Self::on_load_failure)). +/// +/// [DirectX 12 Agility SDK]: https://devblogs.microsoft.com/directx/directx12agility/ +/// [Independent Devices API]: https://devblogs.microsoft.com/directx/d3d12-independent-devices/ +/// [win11-21h2]: https://support.microsoft.com/en-us/topic/august-22-2023-kb5029332-os-build-22000-2360-preview-8f8aec64-77b4-4225-9a0f-f0153204ae28 +/// [win10-22h2]: https://support.microsoft.com/en-gb/topic/august-22-2023-kb5029331-os-build-19045-3393-preview-9f6c1dbd-0ee6-469b-af24-f9d0bf35ca18 +/// [server-2022]: https://support.microsoft.com/en-au/topic/september-12-2023-kb5030216-os-build-20348-1970-34d4aff3-fd05-4270-b288-4ab6379c7f81 +#[derive(Clone, Debug)] +pub struct Dx12AgilitySDK { + /// The Agility SDK version number (e.g., 614 for SDK version 1.614.0). + /// + /// This must match the version of the `D3D12Core.dll` at [`sdk_path`](Self::sdk_path) + /// exactly, or the runtime will fail to load. + pub sdk_version: u32, + /// Path to the directory containing the Agility SDK's `D3D12Core.dll`. + pub sdk_path: String, + /// What to do if the Agility SDK fails to load. + /// + /// Defaults to [`Fallback`](Dx12AgilitySDKLoadFailure::Fallback). + /// + /// Can also be set via the `WGPU_DX12_AGILITY_SDK_REQUIRE` environment variable + /// (`1` for [`Error`](Dx12AgilitySDKLoadFailure::Error), + /// `0` for [`Fallback`](Dx12AgilitySDKLoadFailure::Fallback)). + pub on_load_failure: Dx12AgilitySDKLoadFailure, +} + +impl Dx12AgilitySDK { + /// Read Agility SDK configuration from environment variables. + /// + /// Reads `WGPU_DX12_AGILITY_SDK_PATH`, `WGPU_DX12_AGILITY_SDK_VERSION`, + /// and `WGPU_DX12_AGILITY_SDK_REQUIRE`. + /// Both path and version must be set for this to return `Some`. + #[must_use] + pub fn from_env() -> Option { + let sdk_path = crate::env::var("WGPU_DX12_AGILITY_SDK_PATH")?; + let sdk_version_str = crate::env::var("WGPU_DX12_AGILITY_SDK_VERSION")?; + let sdk_version = sdk_version_str.parse::().ok()?; + let on_load_failure = Dx12AgilitySDKLoadFailure::from_env().unwrap_or_default(); + Some(Self { + sdk_version, + sdk_path, + on_load_failure, + }) + } + + /// Takes the given configuration, overrides fields with environment variables if present, + /// and returns the result. + /// + /// Reads `WGPU_DX12_AGILITY_SDK_PATH`, `WGPU_DX12_AGILITY_SDK_VERSION`, + /// and `WGPU_DX12_AGILITY_SDK_REQUIRE`. + /// Each variable overrides the corresponding field independently. + #[must_use] + pub fn with_env(mut self) -> Self { + if let Some(sdk_path) = crate::env::var("WGPU_DX12_AGILITY_SDK_PATH") { + self.sdk_path = sdk_path; + } + if let Some(sdk_version_str) = crate::env::var("WGPU_DX12_AGILITY_SDK_VERSION") { + if let Ok(sdk_version) = sdk_version_str.parse::() { + self.sdk_version = sdk_version; + } + } + self.on_load_failure = self.on_load_failure.with_env(); + self + } +} + /// Configuration for the DX12 backend. /// /// Part of [`BackendOptions`]. @@ -398,6 +546,15 @@ pub struct Dx12BackendOptions { /// /// This does not override the device's shader model version, only the external shader compiler's version. pub force_shader_model: ForceShaderModelToken, + /// Optional Agility SDK configuration for using the Independent Devices API. + /// + /// When set, wgpu will attempt to load the specified D3D12 runtime via the + /// Independent Devices API. If the API is unavailable or the configuration is + /// invalid, it falls back to the system-installed D3D12 runtime. + /// + /// Can also be set via `WGPU_DX12_AGILITY_SDK_PATH` and `WGPU_DX12_AGILITY_SDK_VERSION` + /// environment variables. + pub agility_sdk: Option, } impl Dx12BackendOptions { @@ -410,11 +567,13 @@ impl Dx12BackendOptions { let presentation_system = Dx12SwapchainKind::from_env().unwrap_or_default(); let latency_waitable_object = Dx12UseFrameLatencyWaitableObject::from_env().unwrap_or_default(); + let agility_sdk = Dx12AgilitySDK::from_env(); Self { shader_compiler: compiler, presentation_system, latency_waitable_object, force_shader_model: ForceShaderModelToken::default(), + agility_sdk, } } @@ -426,11 +585,16 @@ impl Dx12BackendOptions { let shader_compiler = self.shader_compiler.with_env(); let presentation_system = self.presentation_system.with_env(); let latency_waitable_object = self.latency_waitable_object.with_env(); + let agility_sdk = self + .agility_sdk + .map(|s| s.with_env()) + .or_else(Dx12AgilitySDK::from_env); Self { shader_compiler, presentation_system, latency_waitable_object, force_shader_model: ForceShaderModelToken::default(), + agility_sdk, } } } diff --git a/xtask/src/install_agility_sdk.rs b/xtask/src/install_agility_sdk.rs new file mode 100644 index 000000000..7990debfe --- /dev/null +++ b/xtask/src/install_agility_sdk.rs @@ -0,0 +1,113 @@ +use anyhow::Context; +use pico_args::Arguments; +use xshell::Shell; + +/// Keep this in sync with the version used in CI +const AGILITY_SDK_VERSION: &str = "1.619.0"; +const AGILITY_SDK_FEATURE_VERSION: u32 = 619; + +pub struct AgilitySDKInfo { + pub sdk_path: String, + pub sdk_version: u32, +} + +/// Run the install-agility-sdk subcommand +pub fn run_install_agility_sdk(shell: Shell, _args: Arguments) -> anyhow::Result<()> { + if cfg!(not(target_os = "windows")) { + anyhow::bail!("Agility SDK installation is only supported on Windows"); + } + + let info = install_agility_sdk(&shell)?; + + println!("WGPU_DX12_AGILITY_SDK_PATH={}", info.sdk_path); + println!("WGPU_DX12_AGILITY_SDK_VERSION={}", info.sdk_version); + + Ok(()) +} + +/// Returns the Agility SDK NuGet package's architecture directory name +/// for the current target architecture. +fn sdk_arch_dir() -> &'static str { + if cfg!(target_arch = "x86_64") { + "x64" + } else if cfg!(target_arch = "aarch64") { + "arm64" + } else if cfg!(target_arch = "x86") { + "win32" + } else { + panic!("Unsupported target architecture for D3D12 Agility SDK") + } +} + +/// Install the D3D12 Agility SDK on Windows. +/// +/// This downloads the Microsoft.Direct3D.D3D12 NuGet package and extracts +/// the native binaries into `target/agility-sdk/`. +pub fn install_agility_sdk(shell: &Shell) -> anyhow::Result { + let sdk_dir = "target/agility-sdk"; + let version_file = format!("{sdk_dir}/version.txt"); + let arch = sdk_arch_dir(); + let bin_subdir = format!("build/native/bin/{arch}"); + + // Check if the SDK is already installed with the correct version + if let Ok(installed_version) = shell.read_file(&version_file) { + if installed_version.trim() == AGILITY_SDK_VERSION { + log::info!("Agility SDK {AGILITY_SDK_VERSION} already installed, skipping download"); + let sdk_path = shell.current_dir().join(sdk_dir).join(&bin_subdir); + return Ok(AgilitySDKInfo { + sdk_path: sdk_path.to_string_lossy().into_owned(), + sdk_version: AGILITY_SDK_FEATURE_VERSION, + }); + } else { + log::info!( + "Agility SDK version mismatch (installed: {}, required: {}), re-downloading", + installed_version.trim(), + AGILITY_SDK_VERSION + ); + } + } + + log::info!("Installing Agility SDK {AGILITY_SDK_VERSION}"); + + let url = format!( + "https://www.nuget.org/api/v2/package/Microsoft.Direct3D.D3D12/{AGILITY_SDK_VERSION}" + ); + + // Download the NuGet package + log::info!("Downloading Agility SDK from {url}"); + shell + .cmd("curl.exe") + .args(["-L", "--retry", "5", &url, "-o", "target/agility-sdk.zip"]) + .run() + .context("Failed to download Agility SDK package")?; + + // Create target directory + shell + .create_dir(sdk_dir) + .context("Failed to create target/agility-sdk directory")?; + + // Extract the native binaries using tar (available on Windows 10+) + log::info!("Extracting Agility SDK ({arch})"); + shell + .cmd("tar") + .args(["-xf", "target/agility-sdk.zip", "-C", sdk_dir, &bin_subdir]) + .run() + .context("Failed to extract Agility SDK using tar")?; + + // Write version file to track installed version + shell + .write_file(&version_file, AGILITY_SDK_VERSION) + .context("Failed to write version file")?; + + // Cleanup + let _ = shell.remove_path("target/agility-sdk.zip"); + + let sdk_path = shell.current_dir().join(sdk_dir).join(&bin_subdir); + + log::info!("Agility SDK installation complete"); + + Ok(AgilitySDKInfo { + sdk_path: sdk_path.to_string_lossy().into_owned(), + sdk_version: AGILITY_SDK_FEATURE_VERSION, + }) +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index 6786db75d..2628f0ea1 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -8,6 +8,7 @@ use pico_args::Arguments; mod changelog; mod cts; +mod install_agility_sdk; mod install_warp; mod miri; mod run_wasm; @@ -55,9 +56,10 @@ Commands: test Run tests - --llvm-cov Run tests with LLVM code coverage using the llvm-cov tool - --list List all of the tests and their executables without running them - --retries Number of times to retry failing tests + --llvm-cov Run tests with LLVM code coverage using the llvm-cov tool + --list List all of the tests and their executables without running them + --retries Number of times to retry failing tests + --no-require-agility-sdk Don't fail if the D3D12 Agility SDK cannot be loaded (fall back to system runtime) All extra arguments will be forwarded to cargo-nextest (NOT wgpu-info) @@ -97,6 +99,12 @@ Commands: Note: Cannot specify both --target-dir and --profile + install-agility-sdk + Download and install the D3D12 Agility SDK for testing with a specific D3D12 runtime version. + + Prints the required environment variables (WGPU_DX12_AGILITY_SDK_PATH and + WGPU_DX12_AGILITY_SDK_VERSION) to stdout after installation. + Options: -h, --help Print help "; @@ -145,6 +153,7 @@ fn main() -> anyhow::Result { Some("miri") => miri::run_miri(shell, args)?, Some("test") => test::run_tests(shell, args, passthrough_args)?, Some("vendor-web-sys") => vendor_web_sys::run_vendor_web_sys(shell, args)?, + Some("install-agility-sdk") => install_agility_sdk::run_install_agility_sdk(shell, args)?, Some("install-warp") => install_warp::run_install_warp(shell, args)?, Some(subcommand) => { bad_arguments!("Unknown subcommand: {}", subcommand) diff --git a/xtask/src/test.rs b/xtask/src/test.rs index efd84a0db..1c0d73223 100644 --- a/xtask/src/test.rs +++ b/xtask/src/test.rs @@ -4,7 +4,27 @@ use anyhow::Context; use pico_args::Arguments; use xshell::Shell; -use crate::{install_warp, util::flatten_args}; +use crate::{install_agility_sdk, install_warp, util::flatten_args}; + +/// Apply Agility SDK environment variables to a command. +fn apply_agility_sdk_env<'a>( + cmd: xshell::Cmd<'a>, + agility_sdk_info: &Option, + require: bool, +) -> xshell::Cmd<'a> { + let Some(info) = agility_sdk_info else { + return cmd; + }; + let cmd = cmd.env("WGPU_DX12_AGILITY_SDK_PATH", &info.sdk_path).env( + "WGPU_DX12_AGILITY_SDK_VERSION", + info.sdk_version.to_string(), + ); + if require { + cmd.env("WGPU_DX12_AGILITY_SDK_REQUIRE", "1") + } else { + cmd + } +} pub fn run_tests( shell: Shell, @@ -13,6 +33,7 @@ pub fn run_tests( ) -> anyhow::Result<()> { let llvm_cov = args.contains("--llvm-cov"); let list = args.contains("--list"); + let no_require_agility_sdk = args.contains("--no-require-agility-sdk"); // Determine the build profile from arguments let is_release = args.contains("--release"); @@ -46,8 +67,8 @@ pub fn run_tests( // Retries handled by cargo nextest natively - // Install WARP on Windows for D3D12 testing - if cfg!(target_os = "windows") { + // Install WARP and Agility SDK on Windows for D3D12 testing + let agility_sdk_info = if cfg!(target_os = "windows") { let llvm_cov_dir = if llvm_cov { "target/llvm-cov-target" } else { @@ -55,7 +76,10 @@ pub fn run_tests( }; let target_dir = format!("{llvm_cov_dir}/{profile}"); install_warp::install_warp(&shell, &target_dir)?; - } + Some(install_agility_sdk::install_agility_sdk(&shell)?) + } else { + None + }; let test_suite_run_flags: &[_] = if llvm_cov { &["llvm-cov", "--no-cfg-coverage", "--no-report", "nextest"] @@ -71,7 +95,7 @@ pub fn run_tests( // and once for the cli binary. // // Needs to be kept in sync with the test in wgpu-info/src/tests.rs - shell + let mut gpuconfig_cmd = shell .cmd("cargo") .args(test_suite_run_flags) // Use the same build configuration as the main tests, so that we only build once. @@ -83,7 +107,10 @@ pub fn run_tests( // old or missing .gpuconfig files. .args(["-E", "binary(wgpu-info)", "generate_gpuconfig_report"]) // Turn on the env var for saving the .gpuconfig files - .env("WGPU_INFO_SAVE_GPUCONFIG_REPORT", "1") + .env("WGPU_INFO_SAVE_GPUCONFIG_REPORT", "1"); + gpuconfig_cmd = + apply_agility_sdk_env(gpuconfig_cmd, &agility_sdk_info, !no_require_agility_sdk); + gpuconfig_cmd .quiet() .run() .context("Failed to run tests to generate .gpuconfig")?; @@ -103,25 +130,24 @@ pub fn run_tests( if list { log::info!("Listing tests"); - shell + let mut list_cmd = shell .cmd("cargo") .args(["nextest", "list"]) .args(["-v", "--benches", "--tests", "--all-features"]) - .args(cargo_args) - .run() - .context("Failed to list tests")?; + .args(cargo_args); + list_cmd = apply_agility_sdk_env(list_cmd, &agility_sdk_info, !no_require_agility_sdk); + list_cmd.run().context("Failed to list tests")?; return Ok(()); } log::info!("Running cargo tests"); - shell + let mut test_cmd = shell .cmd("cargo") .args(test_suite_run_flags) .args(["--benches", "--tests", "--all-features"]) - .args(cargo_args) - .quiet() - .run() - .context("Tests failed")?; + .args(cargo_args); + test_cmd = apply_agility_sdk_env(test_cmd, &agility_sdk_info, !no_require_agility_sdk); + test_cmd.quiet().run().context("Tests failed")?; log::info!("Finished tests");