mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
craft-gpu-device: choose and open a wgpu device
Adds the adapter preference (Auto, low power, a named adapter, software) with a key that survives a reordered adapter list and a driver update, wgpu's adapter rule with corrections for drivers that crash, a ranked fallback order ending in a software adapter, a capability report, and device health that records a loss or an uncaptured error without a lock.
This commit is contained in:
1 parent
0649a07aa1
commit
a7d402ff95
14 files changed
+2283
No files matched your search
@@ -141,3 +141,7 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
|
||||
## HTTP Archive reader
|
||||
|
||||
`crates/har` preserves Craft Anything `crates/formats/src/har.rs` from `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Brandon Thomas introduced the typed reader in `f64ae3bf3c8863a982af1304e06de20653803968`; BFlat added UTF-8 BOM compatibility in `cb0bb9d8fa4536ba44ef2c86f5ed759b879cc2d3`. Both source snapshots retain primary author attribution. Shared wiring, explicit byte admission and its tests are subsequent Dylan M. Taylor changes. Redaction and analysis remain app-owned.
|
||||
|
||||
## GPU device selection
|
||||
|
||||
`crates/gpu-device` comes from StudioCraft `crates/craft-gpu-device` at `17e2120f7d79bb677e2871a4192ba1ced1dab57a` (MIT OR Apache-2.0). Its adapter rule and driver corrections come from FilmCraft `crates/gpu/src/adapter.rs` at `93a88a839aae370740b09434fdec410abb8c24ca`, and its device health from PhotoCraft `crates/gpu/src/health.rs` at `01a5b5a389acc93f081e5ce6a8d0580d6438774a`, both MIT OR Apache-2.0; `crates/gpu-device/NOTICE` names both.
|
||||
Generated
+11
@@ -2106,6 +2106,17 @@ dependencies = [
|
||||
"image",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gpu-device"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"pollster 0.4.0",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "craft-gridcraft-format"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -27,6 +27,7 @@ acadrust = "=0.6.6"
|
||||
log = "0.4"
|
||||
# internal: add each crate here as `craft-<name> = { path = "crates/<name>" }`
|
||||
craft-plist = { path = "crates/plist" }
|
||||
craft-gpu-device = { path = "crates/gpu-device" }
|
||||
craft-platform = { path = "crates/platform" }
|
||||
craft-aep = { path = "crates/aep" }
|
||||
craft-affinity = { path = "crates/affinity" }
|
||||
|
||||
@@ -184,6 +184,11 @@ See the [release notes](CHANGELOG.md) for included functionality and known limit
|
||||
every frame's position, delay, disposal and transparent colour, the loop count and the first
|
||||
frame's colour table, without decompressing pixels. Tells an animation from a still and whether
|
||||
a file can hold the picture it declares before a decoder runs.
|
||||
- [`craft-gpu-device`](crates/gpu-device/README.md): choosing and opening a wgpu device: Auto,
|
||||
low power, a named adapter that survives a reordered list and a driver update, or software;
|
||||
corrections for drivers that crash; the next adapter and then a software one when a device fails
|
||||
to open; a capability report; device-loss and error recording without panics; and what to reopen
|
||||
after a loss. Settings pages and the window stay in each app.
|
||||
- [`craft-gridcraft-format`](crates/gridcraft-format/README.md): GridCraft's native JSON workbook
|
||||
(`.json`, `.scjson`): the extensions, the reader, the pretty writer, and newer entries kept
|
||||
unread and written back into a list. The workbook model and what follows a read stay in GridCraft.
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
[package]
|
||||
name = "craft-gpu-device"
|
||||
description = "Choosing and opening a wgpu device: an adapter choice the user can set (Auto, high performance, low power, a named adapter, software), fixes for drivers that crash, a software fallback, a capability report, and device health with recovery after a device loss"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = ["serde"]
|
||||
# Reading and writing `Preference` and `AdapterKey` with serde.
|
||||
serde = ["dep:serde"]
|
||||
|
||||
[dependencies]
|
||||
wgpu = "30"
|
||||
log = { workspace = true }
|
||||
serde = { workspace = true, optional = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
|
||||
pollster = "0.4"
|
||||
|
||||
[dev-dependencies]
|
||||
# The noop backend opens devices without a GPU in the tests.
|
||||
wgpu = { version = "30", features = ["noop"] }
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,10 @@
|
||||
craft-gpu-device
|
||||
Licensed under the MIT license or the Apache License, Version 2.0, at your option.
|
||||
|
||||
The adapter rule and its driver corrections (src/adapter.rs) come from FilmCraft's
|
||||
`crates/gpu/src/adapter.rs` (https://github.com/storytold/filmcraft, commit
|
||||
93a88a839aae370740b09434fdec410abb8c24ca), MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and
|
||||
the FilmCraft contributors.
|
||||
Device health (src/health.rs) comes from PhotoCraft's `crates/gpu/src/health.rs`
|
||||
(https://github.com/storytold/photocraft, commit 01a5b5a389acc93f081e5ce6a8d0580d6438774a),
|
||||
MIT OR Apache-2.0, Copyright (c) 2026 ArtCraft Team and the PhotoCraft contributors.
|
||||
@@ -0,0 +1,55 @@
|
||||
# craft-gpu-device
|
||||
|
||||
Choosing and opening a wgpu device for a Craft app: an adapter choice the user can set, fixes for
|
||||
drivers that crash, a software fallback, a capability report, and device health with recovery
|
||||
after a device loss. The crate depends on `wgpu` 30, `pollster` and `log`, with `serde` as an
|
||||
optional feature (on by default). It depends on no app crate.
|
||||
|
||||
Licensed under MIT OR Apache-2.0.
|
||||
|
||||
## Contents
|
||||
|
||||
| Item | What |
|
||||
|---|---|
|
||||
| `Candidate` | one listed adapter as plain data: name, backend, device type, PCI vendor, device and bus, driver, feature count, and whether it can draw to the window's surface |
|
||||
| `list(instance, surface)` | every adapter the instance lists, as `wgpu::Adapter`s and as `Candidate`s |
|
||||
| `native_instance`, `native_descriptor` | a wgpu instance over Vulkan, Metal and DirectX 12, plus OpenGL except on Windows; wgpu's `WGPU_*` flag variables apply |
|
||||
| `choose(candidates, power)` | wgpu's own adapter rule with two corrections: the newest version of a driver that lists one GPU twice, and DirectX 12 instead of Vulkan on Intel Gen 9 to Gen 11 integrated GPUs (`intel_gen9_to_gen11`) |
|
||||
| `Preference` | `Auto` (high performance), `LowPower`, `Adapter(AdapterKey)` or `Software`; serde form `{"kind":"auto"}`, `{"kind":"adapter","name":…,"backend":…,"vendor":…,"device":…,"pciBusId":…,"driver":…}` |
|
||||
| `AdapterKey` | what identifies an adapter across runs: backend, PCI vendor, device and bus, the Vulkan driver's name, and the name when the backend reports no PCI ids |
|
||||
| `select(candidates, preference)` | the adapter to draw with, as a `Selection` with its `Notice`s |
|
||||
| `ranked(candidates, preference)` | the order in which to try opening a device: the selection, then the other usable adapters by type with software after hardware, never an older version of a driver listed twice, or the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver |
|
||||
| `open(instance, surface, preference, request)` | native only, like `list`: opens a device through `ranked`, then wgpu's fallback adapter; returns `Opened` (adapter, device, queue, `Capabilities`, `DeviceHealth`, notices) or `OpenError` |
|
||||
| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector` |
|
||||
| `Capabilities`, `Vendor` | NV12 and P010 (sampled only in wgpu 30), 16-bit norm, `f16` and timestamp support, the largest texture and buffer, the vendor, and whether the adapter is a software one |
|
||||
| `DeviceHealth`, `Fault`, `WaitOutcome` | records a device loss or an uncaptured error instead of panicking; polls and bounded waits that do not touch a lost device |
|
||||
| `Recovery`, `RecoveryPolicy` | the preference to open after a loss: the user's own, and `Software` once the device was lost 3 times in 10 minutes (both values can be set) |
|
||||
| `Notice` | the adapter asked for is missing, no software adapter is listed, only a software adapter can draw, an adapter failed to open, or drawing moved to software after losses; the `Display` text is English, for the log |
|
||||
|
||||
## Failure cases
|
||||
|
||||
- With no usable adapter, `select` returns `None` and `open` returns `OpenError::NoAdapter`.
|
||||
- An adapter that lacks `Request::required_features`, or whose `request_device` fails, adds a
|
||||
`Notice::DeviceFailed`, and `open` tries the next one. When every adapter fails, the error lists
|
||||
each failure.
|
||||
- A named adapter that is no longer listed, or can no longer draw to the surface, gives the
|
||||
automatic choice and `Notice::AdapterMissing`.
|
||||
- A driver that ends the process cannot be caught. `choose` and `ranked` never use an older
|
||||
version of a driver that lists one GPU twice, or the Vulkan entry of an Intel Gen 9 to Gen 11
|
||||
GPU on Intel's Windows driver. When those are the only adapters that can draw and wgpu's
|
||||
fallback adapter does not open either, `open` returns `OpenError::UnsafeDriver` with their
|
||||
names. When a
|
||||
driver reports no bus id, a second GPU of the same model on the same driver looks like an
|
||||
older version, and is used through its other backend (DirectX 12 on Windows, OpenGL
|
||||
elsewhere).
|
||||
- Only an error that says the device is lost counts as a loss. An error about a destroyed buffer
|
||||
or texture is recorded as an error.
|
||||
- `DeviceHealth::watch` replaces the device's uncaptured-error handler. Polls catch the panic that
|
||||
`Device::poll` raises on a lost device and record the loss.
|
||||
|
||||
## Tests
|
||||
|
||||
The selection tests run on `Candidate` lists from real machines. The `open` tests use wgpu's noop
|
||||
backend (the `noop` feature, enabled for tests only), so they do not need a GPU. One test compares
|
||||
`choose` with wgpu's own `request_adapter` on the machine that runs it, and passes when no adapter
|
||||
is listed.
|
||||
@@ -0,0 +1,581 @@
|
||||
//! Which adapter wgpu's own rule would draw with, and two corrections to it for drivers that crash.
|
||||
//!
|
||||
//! On Windows the Vulkan loader takes one driver from each display adapter's driver package. A PC
|
||||
//! whose GPUs were installed from different packages of one vendor (a laptop with an integrated
|
||||
//! and a discrete AMD GPU, the first on the manufacturer's old package and the second on a current
|
||||
//! one) loads two versions of that driver, and the newer GPU is listed once through each. wgpu
|
||||
//! takes the first entry of the device type it prefers, which is whichever version the loader
|
||||
//! listed first; a window drawn through the stale one ends the process inside the driver
|
||||
//! (`amdvlk64.dll`, 0xc0000005), where no Rust error handling runs.
|
||||
//!
|
||||
//! [`choose`] is wgpu's own rule (`Instance::request_adapter`: the adapters that can draw to the
|
||||
//! surface, by device type for the power preference, then as enumerated) with one addition: when
|
||||
//! the adapter that rule picks is listed again by the same driver, the entry exposing the most
|
||||
//! features is used, which is the newer version. Without such a duplicate the choice is wgpu's own.
|
||||
//! Entries of one GPU from different drivers (RADV and AMDVLK, a vendor's driver and Dozen) are
|
||||
//! left alone, and wgpu's order between them stays.
|
||||
//!
|
||||
//! An Intel Gen 9 to Gen 11 integrated GPU draws through its DirectX 12 entry rather than Vulkan
|
||||
//! ([`intel_gen9_to_gen11`]). Intel's Vulkan driver for them (`igvk64.dll`) ends the process with
|
||||
//! 0xc0000005 when the device is created, after the adapters are listed.
|
||||
|
||||
use std::cmp::Reverse;
|
||||
use std::fmt;
|
||||
|
||||
use wgpu::{Adapter, Backend, DeviceType, PowerPreference, Surface};
|
||||
|
||||
/// One enumerated adapter as plain data, so that [`choose`] and [`crate::select`] are pure
|
||||
/// functions that tests run without a GPU.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Candidate {
|
||||
pub name: String,
|
||||
pub backend: Backend,
|
||||
pub device_type: DeviceType,
|
||||
/// PCI vendor and device ids; both zero when the backend reports none (OpenGL).
|
||||
pub vendor: u32,
|
||||
pub device: u32,
|
||||
/// PCI bus id such as `0000:03:00.0`; empty when the driver reports none.
|
||||
pub pci_bus_id: String,
|
||||
/// The driver's name (Vulkan) or version (DirectX 12).
|
||||
pub driver: String,
|
||||
/// More about the driver, for the log.
|
||||
pub driver_info: String,
|
||||
/// How many wgpu features the driver exposes; a newer version of one driver exposes more.
|
||||
pub features: u32,
|
||||
/// Whether the surface can be drawn through this adapter (true without a surface).
|
||||
pub usable: bool,
|
||||
}
|
||||
|
||||
impl Candidate {
|
||||
pub fn of(adapter: &Adapter, surface: Option<&Surface<'_>>) -> Self {
|
||||
let info = adapter.get_info();
|
||||
Candidate {
|
||||
name: info.name,
|
||||
backend: info.backend,
|
||||
device_type: info.device_type,
|
||||
vendor: info.vendor,
|
||||
device: info.device,
|
||||
pci_bus_id: info.device_pci_bus_id,
|
||||
driver: info.driver,
|
||||
driver_info: info.driver_info,
|
||||
features: adapter.features().bits().0.iter().map(|word| word.count_ones()).sum(),
|
||||
usable: surface.is_none_or(|s| adapter.is_surface_supported(s)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the adapter draws on the CPU (WARP, llvmpipe, lavapipe, SwiftShader).
|
||||
pub fn is_software(&self) -> bool {
|
||||
self.device_type == DeviceType::Cpu
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Candidate {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let kind = match self.device_type {
|
||||
DeviceType::DiscreteGpu => "discrete GPU",
|
||||
DeviceType::IntegratedGpu => "integrated GPU",
|
||||
DeviceType::VirtualGpu => "virtual GPU",
|
||||
DeviceType::Cpu => "software",
|
||||
DeviceType::Other => "unknown type",
|
||||
};
|
||||
let driver = format!("{} {}", self.driver, self.driver_info);
|
||||
write!(f, "\"{}\" ({:?}, {kind}, driver {}, {} features", self.name, self.backend, driver.trim(), self.features)?;
|
||||
if !self.pci_bus_id.is_empty() {
|
||||
write!(f, ", bus {}", self.pci_bus_id)?;
|
||||
}
|
||||
if !self.usable {
|
||||
write!(f, ", cannot draw to the window")?;
|
||||
}
|
||||
write!(f, ")")
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `a` and `b` are one GPU listed twice by one driver, through two installed versions of
|
||||
/// it: the same backend, device type, PCI vendor and device and driver name, and the same bus id
|
||||
/// when both report one. Adapters without PCI ids (OpenGL reports zeros) are never the same: two
|
||||
/// of them cannot be told apart.
|
||||
pub(crate) fn same_gpu_and_driver(a: &Candidate, b: &Candidate) -> bool {
|
||||
let identified = a.vendor != 0 || a.device != 0;
|
||||
let same_bus = a.pci_bus_id.is_empty() || b.pci_bus_id.is_empty() || a.pci_bus_id == b.pci_bus_id;
|
||||
identified
|
||||
&& a.backend == b.backend
|
||||
&& a.device_type == b.device_type
|
||||
&& a.vendor == b.vendor
|
||||
&& a.device == b.device
|
||||
&& a.driver == b.driver
|
||||
&& same_bus
|
||||
}
|
||||
|
||||
/// wgpu's device type order for `power` (wgpu-core's `Instance::request_adapter`): lower first.
|
||||
/// Without a preference the adapters stay as enumerated.
|
||||
pub(crate) fn type_order(device_type: DeviceType, power: PowerPreference) -> u8 {
|
||||
let prefer_integrated = match power {
|
||||
PowerPreference::LowPower => true,
|
||||
PowerPreference::HighPerformance => false,
|
||||
PowerPreference::None => return 0,
|
||||
};
|
||||
match device_type {
|
||||
DeviceType::DiscreteGpu if prefer_integrated => 2,
|
||||
DeviceType::IntegratedGpu if prefer_integrated => 1,
|
||||
DeviceType::DiscreteGpu => 1,
|
||||
DeviceType::IntegratedGpu => 2,
|
||||
DeviceType::Other => 3,
|
||||
DeviceType::VirtualGpu => 4,
|
||||
DeviceType::Cpu => 5,
|
||||
}
|
||||
}
|
||||
|
||||
/// The index of the adapter wgpu's `request_adapter` picks: the first usable one of the best
|
||||
/// device type for `power`. `None` without a usable adapter.
|
||||
pub(crate) fn wgpu_choice(candidates: &[Candidate], power: PowerPreference) -> Option<usize> {
|
||||
let usable = candidates.iter().enumerate().filter(|(_, c)| c.usable);
|
||||
usable.min_by_key(|(index, c)| (type_order(c.device_type, power), *index)).map(|(index, _)| index)
|
||||
}
|
||||
|
||||
/// A wgpu instance over the native backends (Vulkan, Metal, DirectX 12), and OpenGL except on
|
||||
/// Windows. On Windows, OpenGL starts a WGL context thread inside the vendor driver (NVIDIA's
|
||||
/// `nvoglv64` is both its OpenGL driver and its Vulkan driver), and instances created and devices
|
||||
/// dropped at the same time can then deadlock in that driver.
|
||||
pub fn native_instance() -> wgpu::Instance {
|
||||
wgpu::Instance::new(native_descriptor())
|
||||
}
|
||||
|
||||
/// [`native_instance`]'s descriptor. wgpu's environment variables apply to its flags and backend
|
||||
/// options: `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER=1` lists a Vulkan driver that reports no
|
||||
/// conformance version, such as Mesa's Dozen (the only one on WSL2), and `WGPU_VALIDATION`,
|
||||
/// `WGPU_DX12_COMPILER` and the others work too. The backends stay as above whatever
|
||||
/// `WGPU_BACKEND` says.
|
||||
///
|
||||
/// The descriptor has no display handle, which a headless instance does not need. OpenGL on
|
||||
/// Wayland needs one to draw to a window: add it with `InstanceDescriptor::with_display_handle`,
|
||||
/// or pass the descriptor to egui-wgpu as `WgpuSetupCreateNew::instance_descriptor`, where eframe
|
||||
/// fills in the window's display handle.
|
||||
pub fn native_descriptor() -> wgpu::InstanceDescriptor {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL };
|
||||
desc.flags = desc.flags.with_env();
|
||||
desc.backend_options = desc.backend_options.with_env();
|
||||
desc
|
||||
}
|
||||
|
||||
/// The index of the adapter to draw with for `power`: [`wgpu_choice`], or the entry exposing the
|
||||
/// most features among those that are the same GPU listed by the same driver (the first of them
|
||||
/// when several expose as many). For an Intel Gen 9 to Gen 11 GPU on Intel's Windows Vulkan
|
||||
/// driver it is the same GPU's DirectX 12 entry, or without one the best other usable adapter.
|
||||
/// `None` without a usable adapter, and when that Intel Vulkan entry is the only one.
|
||||
pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option<usize> {
|
||||
let first = wgpu_choice(candidates, power)?;
|
||||
let preferred = candidates.get(first)?;
|
||||
let index = corrected(candidates, first, preferred);
|
||||
if candidates.get(index).is_some_and(intel_vulkan_crashes) {
|
||||
// No usable DirectX 12 entry for that GPU: the best other adapter wgpu would take.
|
||||
let safe = candidates.iter().enumerate().filter(|(_, c)| c.usable && !intel_vulkan_crashes(c));
|
||||
let (other, c) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?;
|
||||
return Some(corrected(candidates, other, c));
|
||||
}
|
||||
Some(index)
|
||||
}
|
||||
|
||||
/// `index` (the entry `preferred`), or the entry to draw with instead of it.
|
||||
pub(crate) fn corrected(candidates: &[Candidate], index: usize, preferred: &Candidate) -> usize {
|
||||
if let Some(dx12) = dx12_instead(candidates, preferred) {
|
||||
return dx12;
|
||||
}
|
||||
let versions = candidates.iter().enumerate().filter(|(_, c)| c.usable && same_gpu_and_driver(preferred, c));
|
||||
versions.max_by_key(|(index, c)| (c.features, Reverse(*index))).map_or(index, |(index, _)| index)
|
||||
}
|
||||
|
||||
/// Whether the entry at `index` is one [`choose`] never draws with: the Vulkan entry of an Intel
|
||||
/// Gen 9 to Gen 11 GPU on Intel's Windows driver, or an older version of a driver that lists one
|
||||
/// GPU twice. Creating a device or drawing through either can end the process, so it is never
|
||||
/// tried as a fallback either. A second GPU of the same model on the same driver, when the
|
||||
/// driver reports no bus id for either, looks like an older version; it is still listed through
|
||||
/// the other backends (DirectX 12 on Windows, OpenGL elsewhere).
|
||||
pub(crate) fn avoided(candidates: &[Candidate], index: usize) -> bool {
|
||||
let Some(c) = candidates.get(index) else {
|
||||
return true;
|
||||
};
|
||||
intel_vulkan_crashes(c) || corrected(candidates, index, c) != index
|
||||
}
|
||||
|
||||
/// PCI vendor id of Intel.
|
||||
pub(crate) const INTEL: u32 = 0x8086;
|
||||
|
||||
/// Whether `device` is an Intel Gen 9 to Gen 11 integrated GPU: 6th to 10th generation Core, and
|
||||
/// the Atom, Pentium and Celeron graphics of those years (Skylake, Broxton, Gemini Lake, Kaby
|
||||
/// Lake, Coffee Lake, Whiskey Lake, Comet Lake, Cannon Lake, Ice Lake, Elkhart Lake, Jasper Lake),
|
||||
/// by the PCI device ids of Linux's `include/drm/intel/pciids.h`: these prefixes hold those
|
||||
/// families and no others, except `0x0a84` (Broxton), whose prefix Haswell shares.
|
||||
///
|
||||
/// Their Windows Vulkan driver ends the process with 0xc0000005 in `igvk64.dll` when a device is
|
||||
/// created, on every version reported, from 25.20.100.6576 (2019) to 31.0.101.2145, the legacy
|
||||
/// branch that is the last driver Intel ships for them. DirectX 12 works on the same GPUs.
|
||||
pub fn intel_gen9_to_gen11(device: u32) -> bool {
|
||||
matches!(device >> 8, 0x19 | 0x1a | 0x31 | 0x3e | 0x45 | 0x4e | 0x59 | 0x5a | 0x87 | 0x8a | 0x9b) || device == 0x0a84
|
||||
}
|
||||
|
||||
/// Whether `c` is an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan
|
||||
/// driver ([`intel_gen9_to_gen11`]). Mesa's Vulkan driver for the same GPUs on Linux reports a
|
||||
/// driver name with "Mesa" in it and is not included.
|
||||
pub(crate) fn intel_vulkan_crashes(c: &Candidate) -> bool {
|
||||
c.backend == Backend::Vulkan
|
||||
&& c.device_type == DeviceType::IntegratedGpu
|
||||
&& c.vendor == INTEL
|
||||
&& intel_gen9_to_gen11(c.device)
|
||||
&& !c.driver.to_ascii_lowercase().contains("mesa")
|
||||
}
|
||||
|
||||
/// For an Intel Gen 9 to Gen 11 integrated GPU listed through Intel's Windows Vulkan driver, the
|
||||
/// index of the same GPU's usable DirectX 12 entry, if there is one.
|
||||
fn dx12_instead(candidates: &[Candidate], preferred: &Candidate) -> Option<usize> {
|
||||
if !intel_vulkan_crashes(preferred) {
|
||||
return None;
|
||||
}
|
||||
candidates.iter().position(|c| c.usable && c.backend == Backend::Dx12 && c.vendor == INTEL && c.device == preferred.device)
|
||||
}
|
||||
|
||||
/// Write the adapters and the choice to the log, with a warning when a correction applied.
|
||||
pub(crate) fn log_choice(candidates: &[Candidate], index: usize, power: PowerPreference) {
|
||||
for candidate in candidates {
|
||||
log::info!("graphics adapter available: {candidate}");
|
||||
}
|
||||
let Some(chosen) = candidates.get(index) else {
|
||||
return;
|
||||
};
|
||||
let others = candidates.iter().enumerate().filter(|(i, c)| *i != index && c.usable && same_gpu_and_driver(chosen, c)).count();
|
||||
if others > 0 {
|
||||
log::warn!(
|
||||
"{:?} lists \"{}\" {} times: several versions of its driver are installed, and a window drawn through a stale one can crash. Using the one with the most features; installing one driver package for every GPU removes the others.",
|
||||
chosen.backend,
|
||||
chosen.name,
|
||||
others.saturating_add(1)
|
||||
);
|
||||
}
|
||||
if let Some(wgpu_own) = wgpu_choice(candidates, power).and_then(|i| candidates.get(i))
|
||||
&& wgpu_own.backend == Backend::Vulkan
|
||||
&& chosen.backend == Backend::Dx12
|
||||
&& wgpu_own.vendor == INTEL
|
||||
&& wgpu_own.device == chosen.device
|
||||
{
|
||||
log::warn!("Intel's Vulkan driver for \"{}\" crashes when the device is created: drawing through DirectX 12", wgpu_own.name);
|
||||
}
|
||||
log::info!("graphics adapter chosen: {chosen}");
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use wgpu::Backend::{Dx12, Gl, Vulkan};
|
||||
use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu, Other};
|
||||
use wgpu::PowerPreference::{HighPerformance, LowPower};
|
||||
|
||||
pub(crate) const AMD: u32 = 0x1002;
|
||||
pub(crate) const RX_6800M: u32 = 0x73df;
|
||||
pub(crate) const RADEON_IGPU: u32 = 0x1638;
|
||||
const POWERS: [PowerPreference; 3] = [PowerPreference::None, LowPower, HighPerformance];
|
||||
|
||||
#[expect(clippy::too_many_arguments, reason = "one line per adapter in the listings below")]
|
||||
pub(crate) fn gpu(
|
||||
name: &str,
|
||||
backend: Backend,
|
||||
device_type: DeviceType,
|
||||
vendor: u32,
|
||||
device: u32,
|
||||
bus: &str,
|
||||
driver: &str,
|
||||
driver_info: &str,
|
||||
features: u32,
|
||||
) -> Candidate {
|
||||
Candidate {
|
||||
name: name.into(),
|
||||
backend,
|
||||
device_type,
|
||||
vendor,
|
||||
device,
|
||||
pci_bus_id: bus.into(),
|
||||
driver: driver.into(),
|
||||
driver_info: driver_info.into(),
|
||||
features,
|
||||
usable: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A laptop with an integrated Radeon on a 2021 driver package and an RX 6800M on a 2026 one,
|
||||
/// as wgpu 30 lists it: the Vulkan loader has both versions of AMD's driver, and the 2021 one
|
||||
/// lists the RX 6800M first. A window drawn through that entry ended inside `amdvlk64.dll`
|
||||
/// (0xc0000005) on every launch.
|
||||
pub(crate) fn two_amd_drivers() -> Vec<Candidate> {
|
||||
let amd = "AMD proprietary driver";
|
||||
vec![
|
||||
gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2", 60),
|
||||
gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", amd, "26.9.2 (AMD proprietary shader compiler)", 68),
|
||||
gpu("AMD Radeon(TM) Graphics", Vulkan, IntegratedGpu, AMD, RADEON_IGPU, "", amd, "21.30.02.13", 56),
|
||||
gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, AMD, RX_6800M, "0000:03:00.0", "32.0.21045.11001", "", 36),
|
||||
gpu("AMD Radeon(TM) Graphics", Dx12, IntegratedGpu, AMD, RADEON_IGPU, "0000:08:00.0", "30.0.13002.13003", "", 36),
|
||||
gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9549", "", 36),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gpu_listed_through_two_versions_of_its_driver_draws_with_the_newer_one() {
|
||||
let adapters = two_amd_drivers();
|
||||
for power in [HighPerformance, PowerPreference::None] {
|
||||
assert_eq!(wgpu_choice(&adapters, power), Some(0), "wgpu takes the stale entry, which crashed");
|
||||
assert_eq!(choose(&adapters, power), Some(1));
|
||||
}
|
||||
// whichever version the loader lists first
|
||||
let mut newer_first = adapters.clone();
|
||||
newer_first.swap(0, 1);
|
||||
assert_eq!(choose(&newer_first, HighPerformance), Some(0));
|
||||
// two entries exposing as much: wgpu's, the first
|
||||
let mut equal = adapters.clone();
|
||||
if let Some(c) = equal.get_mut(1) {
|
||||
c.features = 60;
|
||||
}
|
||||
assert_eq!(choose(&equal, HighPerformance), Some(0));
|
||||
// three versions: the one exposing the most
|
||||
let mut three = adapters.clone();
|
||||
three.insert(1, gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, "", "AMD proprietary driver", "24.1.1", 64));
|
||||
assert_eq!(choose(&three, HighPerformance), Some(2));
|
||||
// the stale entries are avoided, the newest is not
|
||||
assert!(avoided(&three, 0) && avoided(&three, 1) && !avoided(&three, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_version_never_overtakes_another_gpu_or_backend() {
|
||||
assert_eq!(choose(&two_amd_drivers(), LowPower), Some(2));
|
||||
let mut dx12_first = two_amd_drivers();
|
||||
dx12_first.rotate_left(3);
|
||||
for power in [HighPerformance, PowerPreference::None] {
|
||||
assert_eq!(choose(&dx12_first, power), Some(0));
|
||||
}
|
||||
assert_eq!(choose(&dx12_first, LowPower), wgpu_choice(&dx12_first, LowPower));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_two_versions_of_one_driver_the_choice_is_wgpus() {
|
||||
let nvidia = |backend, bus, driver, features| gpu("NVIDIA GeForce RTX 4070", backend, DiscreteGpu, 0x10de, 0x2786, bus, driver, "", features);
|
||||
let intel =
|
||||
|backend, bus, driver, features| gpu("Intel(R) UHD Graphics 770", backend, IntegratedGpu, 0x8086, 0x4680, bus, driver, "", features);
|
||||
let radeon = |bus, driver, features| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, AMD, 0x744c, bus, driver, "", features);
|
||||
let gl = |name: &str, features| gpu(name, Gl, Other, 0, 0, "", "", "", features);
|
||||
let without = |skip: usize| two_amd_drivers().into_iter().enumerate().filter(|(i, _)| *i != skip).map(|(_, c)| c).collect::<Vec<_>>();
|
||||
let listings: Vec<Vec<Candidate>> = vec![
|
||||
vec![],
|
||||
vec![nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)],
|
||||
// a laptop with two GPUs, through Vulkan and DirectX 12
|
||||
vec![
|
||||
intel(Vulkan, "0000:00:02.0", "Intel Corporation", 60),
|
||||
nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70),
|
||||
nvidia(Dx12, "0000:01:00.0", "32.0.15.6094", 36),
|
||||
intel(Dx12, "0000:00:02.0", "31.0.101.5186", 36),
|
||||
gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.1", "", 36),
|
||||
],
|
||||
// one GPU through two different drivers: Linux with AMDVLK and RADV
|
||||
vec![radeon("0000:03:00.0", "AMD open-source driver", 58), radeon("0000:03:00.0", "radv", 71)],
|
||||
// a vendor's driver and Dozen (Vulkan on DirectX 12)
|
||||
vec![nvidia(Vulkan, "", "Dozen", 75), nvidia(Vulkan, "0000:01:00.0", "NVIDIA", 70)],
|
||||
// two cards of one model, on their own buses
|
||||
vec![radeon("0000:03:00.0", "AMD proprietary driver", 60), radeon("0000:04:00.0", "AMD proprietary driver", 68)],
|
||||
// OpenGL reports no ids: two adapters cannot be told apart
|
||||
vec![gl("ANGLE", 20), gl("ANGLE", 30)],
|
||||
vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)],
|
||||
without(0),
|
||||
without(1),
|
||||
];
|
||||
for adapters in &listings {
|
||||
for power in POWERS {
|
||||
assert_eq!(choose(adapters, power), wgpu_choice(adapters, power), "{power:?} over {adapters:#?}");
|
||||
}
|
||||
}
|
||||
assert_eq!(choose(&[], HighPerformance), None);
|
||||
}
|
||||
|
||||
/// An Intel UHD Graphics 630 (Coffee Lake) on driver 25.20.100.6576 as wgpu 30 lists it. A
|
||||
/// Vulkan device on it ended inside `igvk64.dll` (0xc0000005) as it was created.
|
||||
pub(crate) fn uhd_630() -> Vec<Candidate> {
|
||||
vec![
|
||||
gpu("Intel(R) UHD Graphics 630", Vulkan, IntegratedGpu, INTEL, 0x3e91, "", "Intel Corporation", "Intel driver", 44),
|
||||
gpu("Intel(R) UHD Graphics 630", Dx12, IntegratedGpu, INTEL, 0x3e91, "0000:00:02.0", "25.20.100.6576", "", 36),
|
||||
gpu("Microsoft Basic Render Driver", Dx12, Cpu, 0x1414, 0x8c, "", "10.0.26100.9711", "", 36),
|
||||
]
|
||||
}
|
||||
|
||||
fn uhd_630_as(name: &str, device: u32) -> Vec<Candidate> {
|
||||
uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { name: name.into(), device, ..c } } else { c }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_intel_gen9_to_gen11_gpu_draws_through_directx_12() {
|
||||
for power in POWERS {
|
||||
assert_eq!(wgpu_choice(&uhd_630(), power), Some(0), "wgpu takes Vulkan, which crashed");
|
||||
assert_eq!(choose(&uhd_630(), power), Some(1), "{power:?}");
|
||||
}
|
||||
for (name, device) in [("Intel(R) HD Graphics 520", 0x1916), ("Intel(R) Iris(R) Plus Graphics", 0x8a5a)] {
|
||||
assert_eq!(choose(&uhd_630_as(name, device), HighPerformance), Some(1), "{name}");
|
||||
}
|
||||
let mut dx12_first = uhd_630();
|
||||
dx12_first.swap(0, 1);
|
||||
assert_eq!(choose(&dx12_first, HighPerformance), Some(0));
|
||||
// without a usable DirectX 12 entry, the Vulkan entry is still never drawn with
|
||||
let vulkan_only: Vec<Candidate> = uhd_630().into_iter().take(1).collect();
|
||||
assert_eq!(choose(&vulkan_only, HighPerformance), None);
|
||||
assert!(avoided(&vulkan_only, 0));
|
||||
let mut dx12_unusable = uhd_630();
|
||||
if let Some(c) = dx12_unusable.get_mut(1) {
|
||||
c.usable = false;
|
||||
}
|
||||
assert_eq!(choose(&dx12_unusable, HighPerformance), Some(2), "the software adapter");
|
||||
// Mesa's Vulkan driver for the same GPU on Linux is drawn with
|
||||
let mesa = vec![gpu(
|
||||
"Intel(R) UHD Graphics 630 (CFL GT2)",
|
||||
Vulkan,
|
||||
IntegratedGpu,
|
||||
INTEL,
|
||||
0x3e91,
|
||||
"0000:00:02.0",
|
||||
"Intel open-source Mesa driver",
|
||||
"Mesa 25.2.4",
|
||||
44,
|
||||
)];
|
||||
assert_eq!(choose(&mesa, HighPerformance), Some(0));
|
||||
assert!(!avoided(&mesa, 0));
|
||||
// beside a discrete GPU: high performance keeps it; low power takes the Intel GPU's DirectX 12 entry
|
||||
let mut laptop = uhd_630();
|
||||
laptop.insert(1, gpu("NVIDIA GeForce MX250", Vulkan, DiscreteGpu, 0x10de, 0x1d13, "0000:01:00.0", "NVIDIA", "", 70));
|
||||
assert_eq!(choose(&laptop, HighPerformance), Some(1));
|
||||
assert_eq!(choose(&laptop, LowPower), Some(2));
|
||||
assert!(avoided(&laptop, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn later_intel_gpus_keep_wgpus_choice() {
|
||||
for (name, device) in [("Intel(R) Iris(R) Xe Graphics", 0x9a49), ("Intel(R) UHD Graphics 770", 0x4680), ("Intel(R) Arc(TM) Graphics", 0x7d55)]
|
||||
{
|
||||
let adapters = uhd_630_as(name, device);
|
||||
for power in POWERS {
|
||||
assert_eq!(choose(&adapters, power), Some(0), "{name} {power:?}");
|
||||
}
|
||||
}
|
||||
let discrete: Vec<Candidate> =
|
||||
uhd_630().into_iter().map(|c| if c.vendor == INTEL { Candidate { device_type: DiscreteGpu, ..c } } else { c }).collect();
|
||||
assert_eq!(choose(&discrete, HighPerformance), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gen9_to_gen11_ids() {
|
||||
for id in [0x1916, 0x0a84, 0x5a85, 0x3184, 0x5917, 0x87c0, 0x3e91, 0x3ea0, 0x9b41, 0x5a52, 0x8a5a, 0x4571, 0x4e61] {
|
||||
assert!(intel_gen9_to_gen11(id), "{id:#06x}");
|
||||
}
|
||||
for id in [0x0a16, 0x0a1e, 0x1616, 0x9a49, 0x4c8a, 0x4680, 0x46a6, 0xa780, 0x4905, 0x56a0, 0x7d55, 0x64a0, 0xe20b, 0xb080] {
|
||||
assert!(!intel_gen9_to_gen11(id), "{id:#06x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_entries_are_one_gpu_only_with_the_same_ids_type_driver_and_bus() {
|
||||
let stale = two_amd_drivers().swap_remove(0);
|
||||
let newer = two_amd_drivers().swap_remove(1);
|
||||
assert!(same_gpu_and_driver(&stale, &newer) && same_gpu_and_driver(&stale, &stale));
|
||||
let on_bus = |bus: &str| Candidate { pci_bus_id: bus.into(), ..newer.clone() };
|
||||
assert!(same_gpu_and_driver(&stale, &on_bus("0000:03:00.0")));
|
||||
assert!(same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:03:00.0")));
|
||||
assert!(!same_gpu_and_driver(&on_bus("0000:03:00.0"), &on_bus("0000:04:00.0")));
|
||||
for other in [
|
||||
Candidate { backend: Dx12, ..newer.clone() },
|
||||
Candidate { device_type: IntegratedGpu, ..newer.clone() },
|
||||
Candidate { vendor: 0x10de, ..newer.clone() },
|
||||
Candidate { device: RADEON_IGPU, ..newer.clone() },
|
||||
Candidate { driver: "radv".into(), ..newer.clone() },
|
||||
] {
|
||||
assert!(!same_gpu_and_driver(&stale, &other), "{other}");
|
||||
}
|
||||
let unidentified = Candidate { vendor: 0, device: 0, ..newer };
|
||||
assert!(!same_gpu_and_driver(&unidentified, &unidentified));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adapters_that_cannot_draw_to_the_window_are_left_out() {
|
||||
let unusable = |which: &dyn Fn(usize, &Candidate) -> bool| {
|
||||
let mut adapters = two_amd_drivers();
|
||||
for (i, c) in adapters.iter_mut().enumerate() {
|
||||
c.usable = !which(i, c);
|
||||
}
|
||||
adapters
|
||||
};
|
||||
assert_eq!(choose(&unusable(&|i, _| i == 1), HighPerformance), Some(0));
|
||||
assert_eq!(choose(&unusable(&|i, _| i == 0), HighPerformance), Some(1));
|
||||
assert_eq!(choose(&unusable(&|_, c| c.backend == Vulkan), HighPerformance), Some(3));
|
||||
assert_eq!(choose(&unusable(&|_, _| true), HighPerformance), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidates_describe_themselves_for_the_log() {
|
||||
let adapters = two_amd_drivers();
|
||||
let text = adapters.get(1).map(ToString::to_string).unwrap_or_default();
|
||||
assert_eq!(
|
||||
text,
|
||||
"\"AMD Radeon RX 6800M\" (Vulkan, discrete GPU, driver AMD proprietary driver 26.9.2 (AMD proprietary shader compiler), 68 features)"
|
||||
);
|
||||
let offscreen = adapters.get(4).map(|c| Candidate { usable: false, ..c.clone() }.to_string()).unwrap_or_default();
|
||||
assert_eq!(
|
||||
offscreen,
|
||||
"\"AMD Radeon(TM) Graphics\" (Dx12, integrated GPU, driver 30.0.13002.13003, 36 features, bus 0000:08:00.0, cannot draw to the window)"
|
||||
);
|
||||
assert!(adapters.get(5).is_some_and(Candidate::is_software));
|
||||
assert!(!adapters.first().is_some_and(Candidate::is_software));
|
||||
}
|
||||
|
||||
/// The instance reads wgpu's flag variables and keeps its own backends whatever `WGPU_BACKEND`
|
||||
/// says. Runs in a child process, which has them set.
|
||||
#[test]
|
||||
fn native_descriptor_reads_wgpu_flags_but_keeps_its_backends() {
|
||||
const CHILD: &str = "CRAFT_GPU_DEVICE_TEST_NATIVE_DESCRIPTOR_CHILD";
|
||||
if std::env::var_os(CHILD).is_none() {
|
||||
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "adapter::tests::native_descriptor_reads_wgpu_flags_but_keeps_its_backends", "--nocapture"])
|
||||
.env(CHILD, "1")
|
||||
.env("WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER", "1")
|
||||
.env("WGPU_BACKEND", "gl")
|
||||
.output()
|
||||
.unwrap();
|
||||
let stdout = String::from_utf8_lossy(&out.stdout);
|
||||
assert!(out.status.success() && stdout.contains("1 passed"), "{stdout}\n{}", String::from_utf8_lossy(&out.stderr));
|
||||
return;
|
||||
}
|
||||
let desc = native_descriptor();
|
||||
assert!(desc.flags.contains(wgpu::InstanceFlags::ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER), "{:?}", desc.flags);
|
||||
let backends = if cfg!(windows) { wgpu::Backends::PRIMARY } else { wgpu::Backends::PRIMARY | wgpu::Backends::GL };
|
||||
assert_eq!(desc.backends, backends);
|
||||
}
|
||||
|
||||
/// Against the adapters of the machine running the tests: [`wgpu_choice`] is what wgpu's
|
||||
/// `request_adapter` returns, and [`choose`] returns that adapter too, a version of it exposing
|
||||
/// more features, or for an Intel Gen 9 to Gen 11 GPU its DirectX 12 entry. Passes without
|
||||
/// adapters.
|
||||
#[test]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn on_this_host_the_choice_is_wgpus_unless_a_correction_applies() {
|
||||
let backends = wgpu::Backends::PRIMARY;
|
||||
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { backends, ..wgpu::InstanceDescriptor::new_without_display_handle() });
|
||||
let adapters = pollster::block_on(instance.enumerate_adapters(backends));
|
||||
let candidates: Vec<Candidate> = adapters.iter().map(|a| Candidate::of(a, None)).collect();
|
||||
for power in POWERS {
|
||||
let options = wgpu::RequestAdapterOptions { power_preference: power, ..Default::default() };
|
||||
let wgpu_own = pollster::block_on(instance.request_adapter(&options)).ok().map(|a| Candidate::of(&a, None));
|
||||
assert_eq!(wgpu_choice(&candidates, power).and_then(|i| candidates.get(i)), wgpu_own.as_ref(), "{power:?} over {candidates:#?}");
|
||||
let picked = choose(&candidates, power).and_then(|i| candidates.get(i));
|
||||
match (&wgpu_own, picked) {
|
||||
(Some(wgpu_own), Some(picked)) if wgpu_own != picked => {
|
||||
let newer_version = same_gpu_and_driver(wgpu_own, picked) && picked.features > wgpu_own.features;
|
||||
let intel_dx12 = wgpu_own.vendor == INTEL
|
||||
&& intel_gen9_to_gen11(wgpu_own.device)
|
||||
&& picked.backend == Backend::Dx12
|
||||
&& picked.device == wgpu_own.device;
|
||||
assert!(newer_version || intel_dx12, "{power:?}: {picked} instead of {wgpu_own}");
|
||||
}
|
||||
_ => assert_eq!(picked, wgpu_own.as_ref(), "{power:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
//! What an adapter can do, for choosing a pipeline and for the settings and the log.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use wgpu::{AdapterInfo, Backend, DeviceType, Features, Limits};
|
||||
|
||||
/// The maker of a GPU, from its PCI vendor id (or the Khronos vendor id some Vulkan drivers
|
||||
/// report instead).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum Vendor {
|
||||
Nvidia,
|
||||
Amd,
|
||||
Intel,
|
||||
Apple,
|
||||
Qualcomm,
|
||||
Arm,
|
||||
ImgTec,
|
||||
/// Microsoft's software adapter (WARP) and its virtual GPUs.
|
||||
Microsoft,
|
||||
/// Mesa's software drivers (llvmpipe, lavapipe).
|
||||
Mesa,
|
||||
/// Another id, or none (0).
|
||||
Other(u32),
|
||||
}
|
||||
|
||||
impl Vendor {
|
||||
pub fn from_id(id: u32) -> Vendor {
|
||||
match id {
|
||||
0x10de => Vendor::Nvidia,
|
||||
0x1002 | 0x1022 => Vendor::Amd,
|
||||
0x8086 => Vendor::Intel,
|
||||
0x106b => Vendor::Apple,
|
||||
0x5143 => Vendor::Qualcomm,
|
||||
0x13b5 => Vendor::Arm,
|
||||
0x1010 => Vendor::ImgTec,
|
||||
0x1414 => Vendor::Microsoft,
|
||||
0x10005 => Vendor::Mesa,
|
||||
other => Vendor::Other(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Vendor {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let name = match self {
|
||||
Vendor::Nvidia => "NVIDIA",
|
||||
Vendor::Amd => "AMD",
|
||||
Vendor::Intel => "Intel",
|
||||
Vendor::Apple => "Apple",
|
||||
Vendor::Qualcomm => "Qualcomm",
|
||||
Vendor::Arm => "Arm",
|
||||
Vendor::ImgTec => "Imagination",
|
||||
Vendor::Microsoft => "Microsoft",
|
||||
Vendor::Mesa => "Mesa",
|
||||
Vendor::Other(0) => return f.write_str("unknown vendor"),
|
||||
Vendor::Other(id) => return write!(f, "vendor {id:#06x}"),
|
||||
};
|
||||
f.write_str(name)
|
||||
}
|
||||
}
|
||||
|
||||
/// What an adapter reports it can do.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Capabilities {
|
||||
pub name: String,
|
||||
pub backend: Backend,
|
||||
pub device_type: DeviceType,
|
||||
pub vendor: Vendor,
|
||||
/// The adapter draws on the CPU.
|
||||
pub software: bool,
|
||||
/// NV12 textures (8-bit 4:2:0, a luma plane and an interleaved chroma plane) can be created
|
||||
/// and sampled through plane views. wgpu 30 does not render to them: draw the planes into
|
||||
/// `R8Unorm` and `Rg8Unorm` textures instead.
|
||||
pub nv12: bool,
|
||||
/// P010 textures (10 bits in 16-bit words, 4:2:0) can be created and sampled through plane
|
||||
/// views. wgpu 30 does not render to them: draw the planes into `R16Unorm` and `Rg16Unorm`
|
||||
/// textures ([`norm16`](Self::norm16)) instead.
|
||||
pub p010: bool,
|
||||
/// `R16Unorm`, `Rg16Unorm` and `Rgba16Unorm` textures, for 10-bit and higher planes without
|
||||
/// P010.
|
||||
pub norm16: bool,
|
||||
/// `f16` in shaders.
|
||||
pub shader_f16: bool,
|
||||
/// Timestamp queries, for measuring GPU time per pass.
|
||||
pub timestamps: bool,
|
||||
/// The widest and tallest 2D texture.
|
||||
pub max_texture_2d: u32,
|
||||
/// The largest buffer, in bytes.
|
||||
pub max_buffer_size: u64,
|
||||
}
|
||||
|
||||
impl Capabilities {
|
||||
/// From an adapter's (or a device's) info, features and limits.
|
||||
pub fn from_parts(info: &AdapterInfo, features: Features, limits: &Limits) -> Self {
|
||||
Capabilities {
|
||||
name: info.name.clone(),
|
||||
backend: info.backend,
|
||||
device_type: info.device_type,
|
||||
vendor: Vendor::from_id(info.vendor),
|
||||
software: info.device_type == DeviceType::Cpu,
|
||||
nv12: features.contains(Features::TEXTURE_FORMAT_NV12),
|
||||
p010: features.contains(Features::TEXTURE_FORMAT_P010),
|
||||
norm16: features.contains(Features::TEXTURE_FORMAT_16BIT_NORM),
|
||||
shader_f16: features.contains(Features::SHADER_F16),
|
||||
timestamps: features.contains(Features::TIMESTAMP_QUERY),
|
||||
max_texture_2d: limits.max_texture_dimension_2d,
|
||||
max_buffer_size: limits.max_buffer_size,
|
||||
}
|
||||
}
|
||||
|
||||
/// What `adapter` can do.
|
||||
pub fn of_adapter(adapter: &wgpu::Adapter) -> Self {
|
||||
Self::from_parts(&adapter.get_info(), adapter.features(), &adapter.limits())
|
||||
}
|
||||
|
||||
/// What a device opened on `adapter` can do: the features and limits it was opened with.
|
||||
pub fn of_device(adapter: &wgpu::Adapter, device: &wgpu::Device) -> Self {
|
||||
Self::from_parts(&adapter.get_info(), device.features(), &device.limits())
|
||||
}
|
||||
|
||||
/// Whether a `width` × `height` texture fits.
|
||||
pub fn fits(&self, width: u32, height: u32) -> bool {
|
||||
width > 0 && height > 0 && width <= self.max_texture_2d && height <= self.max_texture_2d
|
||||
}
|
||||
|
||||
/// Whether 10-bit planes can be drawn: 16-bit normalized textures. P010 textures can only be
|
||||
/// sampled.
|
||||
pub fn ten_bit(&self) -> bool {
|
||||
self.norm16
|
||||
}
|
||||
|
||||
/// The features from `wanted` this adapter has, to ask for when opening a device.
|
||||
pub fn available(adapter_features: Features, wanted: Features) -> Features {
|
||||
adapter_features & wanted
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Capabilities {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "\"{}\" ({}, {:?}", self.name, self.vendor, self.backend)?;
|
||||
if self.software {
|
||||
f.write_str(", software")?;
|
||||
}
|
||||
let flags =
|
||||
[(self.nv12, "NV12"), (self.p010, "P010"), (self.norm16, "16-bit norm"), (self.shader_f16, "f16"), (self.timestamps, "timestamps")];
|
||||
for (on, name) in flags {
|
||||
if on {
|
||||
write!(f, ", {name}")?;
|
||||
}
|
||||
}
|
||||
write!(f, ", textures up to {} px)", self.max_texture_2d)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn info(name: &str, vendor: u32, device_type: DeviceType) -> AdapterInfo {
|
||||
AdapterInfo { name: name.into(), vendor, ..AdapterInfo::new(device_type, Backend::Vulkan) }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vendors_from_pci_and_khronos_ids() {
|
||||
assert_eq!(Vendor::from_id(0x10de), Vendor::Nvidia);
|
||||
assert_eq!(Vendor::from_id(0x1002), Vendor::Amd);
|
||||
assert_eq!(Vendor::from_id(0x8086), Vendor::Intel);
|
||||
assert_eq!(Vendor::from_id(0x10005), Vendor::Mesa);
|
||||
assert_eq!(Vendor::from_id(0x1414), Vendor::Microsoft);
|
||||
assert_eq!(Vendor::from_id(0), Vendor::Other(0));
|
||||
assert_eq!(Vendor::Other(0).to_string(), "unknown vendor");
|
||||
assert_eq!(Vendor::from_id(0x1234).to_string(), "vendor 0x1234");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn features_and_limits_become_capabilities() {
|
||||
let features = Features::TEXTURE_FORMAT_NV12 | Features::TEXTURE_FORMAT_16BIT_NORM | Features::TIMESTAMP_QUERY;
|
||||
let limits = Limits { max_texture_dimension_2d: 16384, ..Limits::default() };
|
||||
let c = Capabilities::from_parts(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits);
|
||||
assert!(c.nv12 && !c.p010 && c.norm16 && c.timestamps && !c.shader_f16 && !c.software);
|
||||
assert!(c.ten_bit());
|
||||
assert_eq!(c.vendor, Vendor::Nvidia);
|
||||
assert!(c.fits(7680, 4320) && c.fits(16384, 16384));
|
||||
assert!(!c.fits(16385, 1) && !c.fits(0, 1080) && !c.fits(1920, 0));
|
||||
assert_eq!(c.to_string(), "\"NVIDIA GeForce RTX 4070\" (NVIDIA, Vulkan, NV12, 16-bit norm, timestamps, textures up to 16384 px)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_software_adapter_without_extras() {
|
||||
let limits = Limits::downlevel_defaults();
|
||||
let c = Capabilities::from_parts(&info("llvmpipe (LLVM 19.1.0, 256 bits)", 0x10005, DeviceType::Cpu), Features::empty(), &limits);
|
||||
assert!(c.software && !c.ten_bit() && !c.nv12);
|
||||
// P010 alone is sampled, not drawn to
|
||||
let p010 = Capabilities::from_parts(&info("x", 0x8086, DeviceType::IntegratedGpu), Features::TEXTURE_FORMAT_P010, &limits);
|
||||
assert!(p010.p010 && !p010.ten_bit());
|
||||
assert_eq!(c.max_texture_2d, 2048);
|
||||
assert!(!c.fits(3840, 2160));
|
||||
assert!(c.to_string().contains("software"));
|
||||
let wanted = Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16;
|
||||
assert_eq!(Capabilities::available(Features::SHADER_F16 | Features::TIMESTAMP_QUERY, wanted), Features::SHADER_F16);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,488 @@
|
||||
//! Device health: notices a lost wgpu device or an uncaptured wgpu error, so callers stop issuing
|
||||
//! GPU work and reopen a device or fall back, instead of panicking.
|
||||
//!
|
||||
//! wgpu's default uncaptured-error handler panics, and `Device::poll` panics on a lost device
|
||||
//! whatever the handler. [`DeviceHealth::watch`] replaces the handler with one that records the
|
||||
//! fault and registers the device-lost callback, and the polls here run only while the device is
|
||||
//! healthy, catching the poll's panic as a last resort. Every GPU entry point checks
|
||||
//! [`DeviceHealth::fault`] first.
|
||||
//!
|
||||
//! Builds for the web too: the callbacks only touch atomics and a mutex.
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Outcome of a bounded wait for submitted GPU work.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum WaitOutcome {
|
||||
/// The submitted work finished before the deadline.
|
||||
Finished,
|
||||
/// The deadline passed (or the device faulted) before the work finished.
|
||||
TimedOut,
|
||||
/// The caller canceled the wait before the work finished.
|
||||
Canceled,
|
||||
}
|
||||
|
||||
/// Why the GPU cannot be used any more.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Fault {
|
||||
/// The device was lost (driver reset, the OS ended a submission, `Device::destroy`).
|
||||
Lost(String),
|
||||
/// An uncaptured wgpu error (out of memory, validation, internal): the GPU output cannot be
|
||||
/// trusted, and on most drivers the device is about to be lost anyway.
|
||||
Error(String),
|
||||
}
|
||||
|
||||
impl Fault {
|
||||
/// Whether the device itself was lost (rather than an error reported).
|
||||
pub fn is_lost(&self) -> bool {
|
||||
matches!(self, Fault::Lost(_))
|
||||
}
|
||||
|
||||
/// An out-of-memory error on a device that still works: freeing memory and trying again can
|
||||
/// succeed, unlike after a loss or a validation error. Only wgpu's own out-of-memory error is
|
||||
/// recorded with exactly [`OUT_OF_MEMORY`]; a validation error that mentions memory is not
|
||||
/// one.
|
||||
pub fn is_out_of_memory(&self) -> bool {
|
||||
matches!(self, Fault::Error(s) if s == OUT_OF_MEMORY)
|
||||
}
|
||||
|
||||
/// The driver's or wgpu's message.
|
||||
pub fn detail(&self) -> &str {
|
||||
match self {
|
||||
Fault::Lost(s) | Fault::Error(s) => s,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Fault {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Fault::Lost(s) if s.is_empty() => f.write_str("GPU device lost"),
|
||||
Fault::Lost(s) => write!(f, "GPU device lost: {s}"),
|
||||
Fault::Error(s) => write!(f, "GPU error: {s}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The message an out-of-memory [`Fault::Error`] carries (wgpu's `Error::OutOfMemory`).
|
||||
pub const OUT_OF_MEMORY: &str = "Out of Memory";
|
||||
|
||||
/// The state wgpu's callbacks write and callers read, without a lock: flags in atomics and each
|
||||
/// fault's text in a [`OnceLock`], whose `get` does not wait. A `set` that races another `set`
|
||||
/// of the same slot waits only for that one store.
|
||||
#[derive(Default)]
|
||||
struct Inner {
|
||||
faulted: AtomicBool,
|
||||
/// The first device loss.
|
||||
lost: OnceLock<String>,
|
||||
/// An out-of-memory error was seen.
|
||||
out_of_memory: AtomicBool,
|
||||
/// The first other error.
|
||||
error: OnceLock<String>,
|
||||
errors: AtomicU64,
|
||||
/// wgpu itself reported the device lost (see [`DeviceHealth::device_lost`]).
|
||||
device_lost: AtomicBool,
|
||||
}
|
||||
|
||||
/// Shared health flag of one wgpu device. Cheap to clone; every clone sees the same state.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct DeviceHealth(Arc<Inner>);
|
||||
|
||||
impl fmt::Debug for DeviceHealth {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("DeviceHealth").field("fault", &self.fault()).field("errors", &self.errors()).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl DeviceHealth {
|
||||
/// A healthy flag not attached to a device (tests, CPU-only callers).
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Watch `device`: its device-lost callback and uncaptured errors mark the returned flag
|
||||
/// instead of panicking. Replaces any handler set before (wgpu keeps one of each).
|
||||
pub fn watch(device: &wgpu::Device) -> Self {
|
||||
let health = Self::new();
|
||||
let lost = health.clone();
|
||||
// Called by wgpu with its own locks held: only record, never call back into wgpu.
|
||||
device.set_device_lost_callback(move |reason, message| {
|
||||
let detail = match (reason, message.is_empty()) {
|
||||
(wgpu::DeviceLostReason::Destroyed, true) => "device destroyed".to_string(),
|
||||
(_, true) => "lost by the driver".to_string(),
|
||||
(_, false) => message,
|
||||
};
|
||||
log::error!("wgpu device lost ({reason:?}): {detail}");
|
||||
lost.0.device_lost.store(true, Ordering::Release);
|
||||
lost.mark(Fault::Lost(detail));
|
||||
});
|
||||
let errors = health.clone();
|
||||
device.on_uncaptured_error(Arc::new(move |e: wgpu::Error| errors.uncaptured(&e)));
|
||||
health
|
||||
}
|
||||
|
||||
/// Record an uncaptured wgpu error.
|
||||
fn uncaptured(&self, e: &wgpu::Error) {
|
||||
self.0.errors.fetch_add(1, Ordering::Relaxed);
|
||||
log::error!("uncaptured wgpu error: {e}");
|
||||
self.mark(fault_of(e));
|
||||
}
|
||||
|
||||
/// Record an error an error scope caught.
|
||||
///
|
||||
/// The uncaptured-error handler never sees a scoped error, so without this a watched device
|
||||
/// would keep being handed work after it failed. Polls first: a lost device is a
|
||||
/// [`Fault::Lost`], and its callback may not have run yet (it runs on a poll). The poll does
|
||||
/// not block.
|
||||
pub fn caught(&self, device: &wgpu::Device, error: &wgpu::Error) {
|
||||
if self.lost() {
|
||||
return;
|
||||
}
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
self.poll(device);
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = device;
|
||||
if self.lost() {
|
||||
return;
|
||||
}
|
||||
self.mark(fault_of(error));
|
||||
}
|
||||
|
||||
fn lost(&self) -> bool {
|
||||
self.fault().is_some_and(|f| f.is_lost())
|
||||
}
|
||||
|
||||
/// Mark the device unusable. The first fault is kept; a later device loss replaces an error,
|
||||
/// and a later out-of-memory error replaces another error, so a caller can still free memory
|
||||
/// and recover after a validation error in the same frame.
|
||||
pub fn mark(&self, fault: Fault) {
|
||||
if fault.is_out_of_memory() {
|
||||
self.0.out_of_memory.store(true, Ordering::Release);
|
||||
} else {
|
||||
// A slot already set keeps its first text.
|
||||
let _ = match fault {
|
||||
Fault::Lost(text) => self.0.lost.set(text),
|
||||
Fault::Error(text) => self.0.error.set(text),
|
||||
};
|
||||
}
|
||||
self.0.faulted.store(true, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Whether the device may still be used.
|
||||
pub fn is_ok(&self) -> bool {
|
||||
!self.0.faulted.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Why the device cannot be used, if it cannot.
|
||||
pub fn fault(&self) -> Option<Fault> {
|
||||
if self.is_ok() {
|
||||
return None;
|
||||
}
|
||||
if let Some(text) = self.0.lost.get() {
|
||||
return Some(Fault::Lost(text.clone()));
|
||||
}
|
||||
if self.0.out_of_memory.load(Ordering::Acquire) {
|
||||
return Some(Fault::Error(OUT_OF_MEMORY.into()));
|
||||
}
|
||||
self.0.error.get().map(|text| Fault::Error(text.clone()))
|
||||
}
|
||||
|
||||
/// Uncaptured wgpu errors seen so far.
|
||||
pub fn errors(&self) -> u64 {
|
||||
self.0.errors.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Whether wgpu itself reported the device lost: its device-lost callback ran, or polling it
|
||||
/// panicked. A fault recorded with [`mark`](Self::mark) is not one. After a real loss nothing
|
||||
/// drawn with the device reaches the screen, the window's own frames included.
|
||||
pub fn device_lost(&self) -> bool {
|
||||
self.0.device_lost.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Non-blocking poll that runs even after a fault was recorded, so a device that is lost
|
||||
/// later (a driver reset while the app sat idle, or the PC slept) is noticed before the next
|
||||
/// frame is drawn with it. Skipped once [`device_lost`](Self::device_lost).
|
||||
pub fn probe(&self, device: &wgpu::Device) {
|
||||
if self.device_lost() {
|
||||
return;
|
||||
}
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() {
|
||||
self.lost_by_poll();
|
||||
}
|
||||
}
|
||||
|
||||
/// `Device::poll` panicked: wgpu found the device lost.
|
||||
fn lost_by_poll(&self) {
|
||||
self.0.device_lost.store(true, Ordering::Release);
|
||||
self.mark(Fault::Lost("the device stopped responding".into()));
|
||||
}
|
||||
|
||||
/// Block until `index` (or all submitted work) finished, unless the device is unusable.
|
||||
/// Returns whether the work finished with the device still healthy: `false` when the device
|
||||
/// was unusable, when it faulted, and when the poll itself failed, so the work may still be
|
||||
/// running. A panic in `Device::poll` is caught and recorded as a loss. Native only: the web
|
||||
/// has no blocking wait.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn wait(&self, device: &wgpu::Device, index: Option<wgpu::SubmissionIndex>) -> bool {
|
||||
if !self.is_ok() {
|
||||
return false;
|
||||
}
|
||||
let poll =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Wait { submission_index: index, timeout: None })));
|
||||
match poll {
|
||||
Ok(Ok(_)) => self.is_ok(),
|
||||
Ok(Err(e)) => {
|
||||
log::warn!("wgpu poll: {e}");
|
||||
false
|
||||
}
|
||||
Err(_) => {
|
||||
self.lost_by_poll();
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Non-blocking poll (reclaims staging memory), skipped once the device is unusable.
|
||||
pub fn poll(&self, device: &wgpu::Device) {
|
||||
if !self.is_ok() {
|
||||
return;
|
||||
}
|
||||
if std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| device.poll(wgpu::PollType::Poll))).is_err() {
|
||||
self.lost_by_poll();
|
||||
}
|
||||
}
|
||||
|
||||
/// Like [`Self::wait`], but bounded: returns whether the submitted work finished within
|
||||
/// `timeout`. A timeout marks the device faulted, so later work stops going to a GPU that no
|
||||
/// longer answers. A submission index the device never issued returns `false` and leaves the
|
||||
/// device healthy. A zero `timeout`, or
|
||||
/// one that passes before the first poll, returns `false` and leaves the device healthy. A
|
||||
/// device that was already faulted returns `false` unchanged.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn wait_timeout(&self, device: &wgpu::Device, index: Option<wgpu::SubmissionIndex>, timeout: Duration) -> bool {
|
||||
self.wait_timeout_cancelable(device, index, timeout, &|| false) == WaitOutcome::Finished
|
||||
}
|
||||
|
||||
/// [`Self::wait_timeout`] that polls in slices of at most 100 ms and checks `canceled` between
|
||||
/// them, keeping the same overall deadline. A slice that times out means the work has not
|
||||
/// finished yet; only the overall deadline (or a poll that panics) marks the device faulted.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn wait_timeout_cancelable(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
index: Option<wgpu::SubmissionIndex>,
|
||||
timeout: Duration,
|
||||
canceled: &(dyn Fn() -> bool + Sync),
|
||||
) -> WaitOutcome {
|
||||
if !self.is_ok() {
|
||||
return WaitOutcome::TimedOut;
|
||||
}
|
||||
let mut wrong_index = false;
|
||||
let mut polled = false;
|
||||
let outcome = wait_slices(timeout, canceled, |slice| {
|
||||
polled = true;
|
||||
let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||
device.poll(wgpu::PollType::Wait { submission_index: index.clone(), timeout: Some(slice) })
|
||||
}));
|
||||
match poll {
|
||||
Ok(Ok(_)) => {
|
||||
if self.is_ok() {
|
||||
SlicePoll::Done
|
||||
} else {
|
||||
SlicePoll::Failed
|
||||
}
|
||||
}
|
||||
Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending,
|
||||
// A submission index the device never issued: the caller's mistake, not the GPU's.
|
||||
Ok(Err(e)) => {
|
||||
log::warn!("wgpu poll: {e}");
|
||||
wrong_index = true;
|
||||
SlicePoll::Failed
|
||||
}
|
||||
Err(_) => {
|
||||
self.lost_by_poll();
|
||||
SlicePoll::Failed
|
||||
}
|
||||
}
|
||||
});
|
||||
// A deadline that passed before the first poll says nothing about the device.
|
||||
if outcome == WaitOutcome::TimedOut && polled && !wrong_index && self.is_ok() {
|
||||
self.mark(Fault::Lost(format!("GPU wait timed out after {:.1} s", timeout.as_secs_f64())));
|
||||
}
|
||||
outcome
|
||||
}
|
||||
}
|
||||
|
||||
/// What one bounded poll reported.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum SlicePoll {
|
||||
Done,
|
||||
Pending,
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Wait for `total`, polling in slices no longer than 100 ms and checking `canceled` between
|
||||
/// them. A slice that times out is pending, not a failure; only the overall deadline or a failed
|
||||
/// poll ends the wait early.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn wait_slices(total: Duration, canceled: &(dyn Fn() -> bool + Sync), mut poll: impl FnMut(Duration) -> SlicePoll) -> WaitOutcome {
|
||||
const SLICE: Duration = Duration::from_millis(100);
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if canceled() {
|
||||
return WaitOutcome::Canceled;
|
||||
}
|
||||
let remaining = total.saturating_sub(start.elapsed());
|
||||
if remaining.is_zero() {
|
||||
return WaitOutcome::TimedOut;
|
||||
}
|
||||
match poll(remaining.min(SLICE)) {
|
||||
SlicePoll::Done => return WaitOutcome::Finished,
|
||||
SlicePoll::Pending => {}
|
||||
SlicePoll::Failed => return WaitOutcome::TimedOut,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The fault a wgpu error stands for. An error that names a lost device follows a device loss
|
||||
/// whose callback may not have run yet (it runs on the next poll), so it counts as a loss rather
|
||||
/// than as an error. An error about a destroyed buffer or texture is an error. Only wgpu's own
|
||||
/// out-of-memory error is [`OUT_OF_MEMORY`].
|
||||
fn fault_of(e: &wgpu::Error) -> Fault {
|
||||
let text = e.to_string();
|
||||
let lower = text.to_ascii_lowercase();
|
||||
if matches!(e, wgpu::Error::OutOfMemory { .. }) {
|
||||
Fault::Error(OUT_OF_MEMORY.into())
|
||||
} else if lower.contains("device is lost") {
|
||||
Fault::Lost(first_line(&text))
|
||||
} else {
|
||||
Fault::Error(first_line(&text))
|
||||
}
|
||||
}
|
||||
|
||||
fn first_line(s: &str) -> String {
|
||||
let line = s.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("");
|
||||
let mut out: String = line.chars().take(200).collect();
|
||||
if line.chars().count() > 200 {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn first_fault_wins_but_loss_replaces_an_error() {
|
||||
let h = DeviceHealth::new();
|
||||
assert!(h.is_ok());
|
||||
assert_eq!(h.fault(), None);
|
||||
h.mark(Fault::Error("out of memory".into()));
|
||||
assert!(!h.is_ok());
|
||||
let c = h.clone();
|
||||
c.mark(Fault::Error("second".into()));
|
||||
assert_eq!(h.fault(), Some(Fault::Error("out of memory".into())));
|
||||
c.mark(Fault::Lost("reset".into()));
|
||||
assert_eq!(h.fault(), Some(Fault::Lost("reset".into())));
|
||||
c.mark(Fault::Lost("later".into()));
|
||||
assert_eq!(h.fault().map(|f| f.to_string()).as_deref(), Some("GPU device lost: reset"));
|
||||
// a recorded loss is not wgpu reporting the device lost
|
||||
assert!(!h.device_lost());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn wait_slices_cancel_timeout_and_completion() {
|
||||
let never = || false;
|
||||
assert_eq!(wait_slices(Duration::ZERO, &never, |_| SlicePoll::Done), WaitOutcome::TimedOut);
|
||||
assert_eq!(wait_slices(Duration::from_secs(1), &never, |_| SlicePoll::Done), WaitOutcome::Finished);
|
||||
assert_eq!(wait_slices(Duration::from_secs(1), &never, |_| SlicePoll::Failed), WaitOutcome::TimedOut);
|
||||
|
||||
let mut polls = 0;
|
||||
let outcome = wait_slices(Duration::from_secs(1), &never, |_| {
|
||||
polls += 1;
|
||||
if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done }
|
||||
});
|
||||
assert_eq!(outcome, WaitOutcome::Finished);
|
||||
assert_eq!(polls, 3, "a timed-out slice is retried, not treated as a failure");
|
||||
|
||||
let canceled = || true;
|
||||
let mut called = false;
|
||||
assert_eq!(
|
||||
wait_slices(Duration::from_secs(1), &canceled, |_| {
|
||||
called = true;
|
||||
SlicePoll::Done
|
||||
}),
|
||||
WaitOutcome::Canceled
|
||||
);
|
||||
assert!(!called, "cancellation is checked before polling");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn wait_slices_observes_cancel_while_pending() {
|
||||
let flag = AtomicBool::new(false);
|
||||
let canceled = || flag.load(Ordering::SeqCst);
|
||||
let mut polls = 0;
|
||||
let outcome = wait_slices(Duration::from_secs(1), &canceled, |_| {
|
||||
polls += 1;
|
||||
flag.store(true, Ordering::SeqCst);
|
||||
SlicePoll::Pending
|
||||
});
|
||||
assert_eq!(outcome, WaitOutcome::Canceled);
|
||||
assert_eq!(polls, 1, "a cancel set during a pending poll ends the wait");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fault_text() {
|
||||
assert_eq!(Fault::Lost(String::new()).to_string(), "GPU device lost");
|
||||
assert_eq!(Fault::Error("x".into()).to_string(), "GPU error: x");
|
||||
assert_eq!(first_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid");
|
||||
assert_eq!(first_line(&"a".repeat(300)).chars().count(), 201);
|
||||
assert!(Fault::Error("Out of Memory".into()).is_out_of_memory());
|
||||
assert!(!Fault::Error("Validation Error".into()).is_out_of_memory());
|
||||
assert!(!Fault::Error("Validation Error: buffer allocation would run out of memory".into()).is_out_of_memory());
|
||||
let h = DeviceHealth::new();
|
||||
h.mark(Fault::Error("Validation Error".into()));
|
||||
h.mark(Fault::Error(OUT_OF_MEMORY.into()));
|
||||
assert!(h.fault().is_some_and(|f| f.is_out_of_memory()));
|
||||
h.mark(Fault::Lost("reset".into()));
|
||||
h.mark(Fault::Error(OUT_OF_MEMORY.into()));
|
||||
assert!(h.fault().is_some_and(|f| f.is_lost()));
|
||||
assert!(!Fault::Lost("out of memory".into()).is_out_of_memory());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_from_several_threads_keep_the_loss() {
|
||||
let h = DeviceHealth::new();
|
||||
let threads: Vec<_> = (0..8)
|
||||
.map(|i| {
|
||||
let h = h.clone();
|
||||
std::thread::spawn(move || h.mark(if i == 5 { Fault::Lost("reset".into()) } else { Fault::Error(format!("e{i}")) }))
|
||||
})
|
||||
.collect();
|
||||
for t in threads {
|
||||
t.join().unwrap();
|
||||
}
|
||||
assert_eq!(h.fault(), Some(Fault::Lost("reset".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_lost_device_counts_as_a_loss() {
|
||||
let validation =
|
||||
|description: &str| wgpu::Error::Validation { source: Box::new(std::io::Error::other("x")), description: description.into() };
|
||||
let lost = validation("Validation Error\n\nCaused by:\n In Device::create_buffer\n Parent device is lost\n");
|
||||
assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost));
|
||||
let destroyed = validation("Validation Error\n\nCaused by:\n In Queue::submit\n Buffer 'pc' has been destroyed\n");
|
||||
assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error".into()));
|
||||
let texture = validation("Validation Error\n\nCaused by:\n Texture with 'frame' label has been destroyed\n");
|
||||
assert!(!fault_of(&texture).is_lost());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
//! Choosing and opening a wgpu device for a Craft app.
|
||||
//!
|
||||
//! - [`list`] gives every adapter as plain [`Candidate`] data for a settings page, and
|
||||
//! [`AdapterKey`] identifies one across runs.
|
||||
//! - [`select`] and [`ranked`] choose an adapter for a [`Preference`] (Auto, low power, a named
|
||||
//! adapter, software) with wgpu's own rule and two corrections for drivers that crash
|
||||
//! ([`choose`]); [`Notice`] says when the choice was not the one asked for.
|
||||
//! - [`open`] opens a device, moving to the next adapter and last to a software one when a device
|
||||
//! fails to open. [`pick`] fits egui-wgpu's adapter selector for a window. `list` and `open`
|
||||
//! block on wgpu's futures and are native only; a browser build picks with [`pick`].
|
||||
//! - [`Capabilities`] reports what the device can do (NV12 and P010 textures, 16-bit norm
|
||||
//! formats, `f16`, timestamps, sizes).
|
||||
//! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and
|
||||
//! [`Recovery`] says what to open after a loss.
|
||||
//!
|
||||
//! The selection functions are pure, so tests run without a GPU.
|
||||
|
||||
mod adapter;
|
||||
mod caps;
|
||||
mod health;
|
||||
mod open;
|
||||
mod preference;
|
||||
mod recovery;
|
||||
|
||||
pub use adapter::{Candidate, choose, intel_gen9_to_gen11, native_descriptor, native_instance};
|
||||
pub use caps::{Capabilities, Vendor};
|
||||
pub use health::{DeviceHealth, Fault, OUT_OF_MEMORY, WaitOutcome};
|
||||
pub use open::{OpenError, Opened, Request, pick};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub use open::{list, open};
|
||||
pub use preference::{AdapterKey, Notice, Preference, Selection, backend_name, ranked, select};
|
||||
pub use recovery::{Recovery, RecoveryPolicy, RecoveryStep};
|
||||
@@ -0,0 +1,304 @@
|
||||
//! Listing adapters and opening a device, trying the next adapter when one fails.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use wgpu::Instance;
|
||||
use wgpu::{Adapter, Features, Limits, Surface};
|
||||
|
||||
use crate::adapter::{Candidate, avoided, log_choice};
|
||||
use crate::caps::Capabilities;
|
||||
use crate::health::DeviceHealth;
|
||||
use crate::preference::{Notice, Preference, Selection, select};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::preference::{asked_for, ranked};
|
||||
|
||||
/// What the device is opened with.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Request<'a> {
|
||||
pub label: Option<&'a str>,
|
||||
/// Features the device must have. An adapter without them is skipped.
|
||||
pub required_features: Features,
|
||||
/// Features asked for when the adapter has them.
|
||||
pub optional_features: Features,
|
||||
/// The limits to ask for; `None` asks for the adapter's own limits.
|
||||
pub limits: Option<Limits>,
|
||||
}
|
||||
|
||||
/// An opened device.
|
||||
#[derive(Debug)]
|
||||
pub struct Opened {
|
||||
pub adapter: Adapter,
|
||||
pub device: wgpu::Device,
|
||||
pub queue: wgpu::Queue,
|
||||
/// The adapter as plain data.
|
||||
pub candidate: Candidate,
|
||||
/// What the device was opened with.
|
||||
pub caps: Capabilities,
|
||||
/// Watches the device for a loss and for uncaptured errors.
|
||||
pub health: DeviceHealth,
|
||||
/// What to tell the user about the choice.
|
||||
pub notices: Vec<Notice>,
|
||||
}
|
||||
|
||||
/// Why no device could be opened.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum OpenError {
|
||||
/// No adapter is listed that can draw (to the surface, when there is one).
|
||||
NoAdapter,
|
||||
/// Every adapter tried failed to open a device; each failure is a [`Notice::DeviceFailed`].
|
||||
NoDevice(Vec<Notice>),
|
||||
/// The only adapters that can draw are ones [`choose`](crate::choose) never draws with,
|
||||
/// because their driver can end the process; these are their names.
|
||||
UnsafeDriver(Vec<String>),
|
||||
}
|
||||
|
||||
impl fmt::Display for OpenError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
OpenError::NoAdapter => f.write_str("no graphics adapter is available"),
|
||||
OpenError::NoDevice(notices) => {
|
||||
f.write_str("no graphics adapter could be opened")?;
|
||||
for n in notices {
|
||||
if let Notice::DeviceFailed { adapter, error } = n {
|
||||
write!(f, "; \"{adapter}\": {error}")?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
OpenError::UnsafeDriver(names) => {
|
||||
let names = names.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>().join(", ");
|
||||
write!(f, "the only graphics adapters that can draw ({names}) use a driver that can crash; update the graphics driver")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for OpenError {}
|
||||
|
||||
/// Every adapter `instance` lists over its backends, as adapters and as plain data. `surface`
|
||||
/// marks the adapters that cannot draw to it as unusable. Native only: it blocks on wgpu's
|
||||
/// future, which on the web would wait on the thread that must resolve it.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec<Adapter>, Vec<Candidate>) {
|
||||
let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all()));
|
||||
let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect();
|
||||
(adapters, candidates)
|
||||
}
|
||||
|
||||
/// The adapter to draw with for `preference`, from adapters already listed, with the choice in the
|
||||
/// log. This fits egui-wgpu's `native_adapter_selector` for a window, which then opens the device
|
||||
/// itself.
|
||||
pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), String> {
|
||||
let candidates: Vec<Candidate> = adapters.iter().map(|a| Candidate::of(a, surface)).collect();
|
||||
let Some(selection) = select(&candidates, preference) else {
|
||||
let left_out = left_out(&candidates);
|
||||
if !left_out.is_empty() {
|
||||
return Err(OpenError::UnsafeDriver(left_out).to_string());
|
||||
}
|
||||
let listed = candidates.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ");
|
||||
return Err(format!("no usable graphics adapter among {}: {listed}", candidates.len()));
|
||||
};
|
||||
log_choice(&candidates, selection.index, preference.power());
|
||||
for notice in &selection.notices {
|
||||
log::warn!("{notice}");
|
||||
}
|
||||
let adapter =
|
||||
adapters.get(selection.index).cloned().ok_or_else(|| format!("graphics adapter {} of {} is missing", selection.index, adapters.len()))?;
|
||||
Ok((adapter, selection))
|
||||
}
|
||||
|
||||
/// Open a device for `preference`: the selected adapter first, then the others in [`ranked`]
|
||||
/// order, and last wgpu's fallback adapter (a software one) when none of those opened. An adapter
|
||||
/// without `request.required_features`, or whose device fails to open, adds a
|
||||
/// [`Notice::DeviceFailed`] and the next one is tried. Native only, like [`list`].
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference, request: &Request<'_>) -> Result<Opened, OpenError> {
|
||||
let (adapters, candidates) = list(instance, surface);
|
||||
// Whether drawing is in software depends on the adapter that opens, which `finish` knows.
|
||||
let mut notices: Vec<Notice> =
|
||||
select(&candidates, preference).map(|s| s.notices).unwrap_or_default().into_iter().filter(|n| *n != Notice::SoftwareOnly).collect();
|
||||
let order = ranked(&candidates, preference);
|
||||
if let Some(first) = order.first() {
|
||||
log_choice(&candidates, *first, preference.power());
|
||||
}
|
||||
let mut tried_software = false;
|
||||
for index in order {
|
||||
let (Some(adapter), Some(candidate)) = (adapters.get(index), candidates.get(index)) else {
|
||||
continue;
|
||||
};
|
||||
tried_software |= candidate.is_software();
|
||||
match open_on(adapter, request) {
|
||||
Ok((device, queue)) => return Ok(finish(adapter.clone(), device, queue, candidate.clone(), preference, notices)),
|
||||
Err(error) => {
|
||||
log::warn!("graphics adapter {candidate} could not be opened: {error}");
|
||||
notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error });
|
||||
}
|
||||
}
|
||||
}
|
||||
if !tried_software {
|
||||
let options = wgpu::RequestAdapterOptions { force_fallback_adapter: true, compatible_surface: surface, ..Default::default() };
|
||||
if let Ok(adapter) = pollster::block_on(instance.request_adapter(&options)) {
|
||||
let candidate = Candidate::of(&adapter, surface);
|
||||
match open_on(&adapter, request) {
|
||||
Ok((device, queue)) => {
|
||||
log::info!("graphics adapter chosen: {candidate}");
|
||||
return Ok(finish(adapter, device, queue, candidate, preference, notices));
|
||||
}
|
||||
Err(error) => notices.push(Notice::DeviceFailed { adapter: candidate.name.clone(), error }),
|
||||
}
|
||||
}
|
||||
}
|
||||
if notices.iter().any(|n| matches!(n, Notice::DeviceFailed { .. })) {
|
||||
return Err(OpenError::NoDevice(notices));
|
||||
}
|
||||
let left_out = left_out(&candidates);
|
||||
if left_out.is_empty() { Err(OpenError::NoAdapter) } else { Err(OpenError::UnsafeDriver(left_out)) }
|
||||
}
|
||||
|
||||
/// The names of the adapters that can draw but that [`choose`](crate::choose) never draws with.
|
||||
fn left_out(candidates: &[Candidate]) -> Vec<String> {
|
||||
candidates.iter().enumerate().filter(|(i, c)| c.usable && avoided(candidates, *i)).map(|(_, c)| c.name.clone()).collect()
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn finish(
|
||||
adapter: Adapter,
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
candidate: Candidate,
|
||||
preference: &Preference,
|
||||
mut notices: Vec<Notice>,
|
||||
) -> Opened {
|
||||
let caps = Capabilities::of_device(&adapter, &device);
|
||||
if candidate.is_software() && !asked_for(preference, &candidate) {
|
||||
notices.push(Notice::SoftwareOnly);
|
||||
}
|
||||
for notice in ¬ices {
|
||||
log::warn!("{notice}");
|
||||
}
|
||||
log::info!("graphics device opened: {caps}");
|
||||
let health = DeviceHealth::watch(&device);
|
||||
Opened { adapter, device, queue, candidate, caps, health, notices }
|
||||
}
|
||||
|
||||
/// Open a device on `adapter`, or say why it cannot be.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_on(adapter: &Adapter, request: &Request<'_>) -> Result<(wgpu::Device, wgpu::Queue), String> {
|
||||
let has = adapter.features();
|
||||
if !has.contains(request.required_features) {
|
||||
return Err(format!("it lacks the features {:?}", request.required_features - has));
|
||||
}
|
||||
let required_limits = request.limits.clone().unwrap_or_else(|| adapter.limits());
|
||||
let desc = wgpu::DeviceDescriptor {
|
||||
label: request.label,
|
||||
required_features: request.required_features | (request.optional_features & has),
|
||||
required_limits,
|
||||
..Default::default()
|
||||
};
|
||||
pollster::block_on(adapter.request_device(&desc)).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(target_arch = "wasm32")))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::preference::AdapterKey;
|
||||
|
||||
/// An instance whose only adapter is wgpu's noop one, which opens devices without a GPU. wgpu
|
||||
/// 30 lists it as a software adapter whatever `NoopBackendOptions::device_type` says.
|
||||
fn noop(features: Option<Features>) -> Instance {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = wgpu::Backends::NOOP;
|
||||
desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, features, ..Default::default() };
|
||||
Instance::new(desc)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_device_opens_with_the_optional_features_the_adapter_has() {
|
||||
let instance = noop(Some(Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY));
|
||||
let request = Request { optional_features: Features::TEXTURE_FORMAT_NV12 | Features::SHADER_F16, ..Default::default() };
|
||||
let opened = open(&instance, None, &Preference::Software, &request).unwrap();
|
||||
assert!(opened.caps.nv12, "{}", opened.caps);
|
||||
assert!(!opened.caps.shader_f16 && !opened.caps.timestamps, "only the features asked for: {}", opened.caps);
|
||||
assert!(opened.notices.is_empty(), "{:?}", opened.notices);
|
||||
assert!(opened.health.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_adapter_without_a_required_feature_is_reported() {
|
||||
let instance = noop(Some(Features::empty()));
|
||||
let request = Request { required_features: Features::SHADER_F16, ..Default::default() };
|
||||
let err = open(&instance, None, &Preference::Auto, &request).unwrap_err();
|
||||
let OpenError::NoDevice(notices) = &err else { panic!("{err}") };
|
||||
assert!(notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. } if error.contains("SHADER_F16"))), "{notices:?}");
|
||||
assert!(err.to_string().starts_with("no graphics adapter could be opened"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_software_adapter_is_reported_unless_it_was_asked_for() {
|
||||
let cpu = noop(None);
|
||||
let opened = open(&cpu, None, &Preference::Auto, &Request::default()).unwrap();
|
||||
assert!(opened.caps.software);
|
||||
assert_eq!(opened.notices, vec![Notice::SoftwareOnly]);
|
||||
let asked = open(&cpu, None, &Preference::Software, &Request::default()).unwrap();
|
||||
assert!(asked.notices.is_empty(), "{:?}", asked.notices);
|
||||
// the software adapter picked by name is what was asked for
|
||||
let named = open(&cpu, None, &Preference::Adapter(AdapterKey::of(&asked.candidate)), &Request::default()).unwrap();
|
||||
assert!(named.notices.is_empty(), "{:?}", named.notices);
|
||||
// a named adapter that is gone: the automatic choice, with both notices
|
||||
let gone =
|
||||
AdapterKey { name: "gone".into(), backend: "vulkan".into(), vendor: 0x10de, device: 1, pci_bus_id: String::new(), driver: String::new() };
|
||||
let opened = open(&cpu, None, &Preference::Adapter(gone.clone()), &Request::default()).unwrap();
|
||||
assert_eq!(opened.notices, vec![Notice::AdapterMissing(gone), Notice::SoftwareOnly]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_adapter_is_an_error() {
|
||||
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
|
||||
desc.backends = wgpu::Backends::NOOP;
|
||||
let instance = Instance::new(desc);
|
||||
assert_eq!(open(&instance, None, &Preference::Auto, &Request::default()).unwrap_err(), OpenError::NoAdapter);
|
||||
assert_eq!(OpenError::NoAdapter.to_string(), "no graphics adapter is available");
|
||||
assert_eq!(
|
||||
OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()]).to_string(),
|
||||
"the only graphics adapters that can draw (\"Intel(R) UHD Graphics 630\") use a driver that can crash; update the graphics driver"
|
||||
);
|
||||
assert!(pick(&[], None, &Preference::Auto).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_timeout_leaves_a_healthy_device_healthy() {
|
||||
let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap();
|
||||
assert!(!opened.health.wait_timeout(&opened.device, None, std::time::Duration::ZERO));
|
||||
assert!(opened.health.is_ok(), "{:?}", opened.health.fault());
|
||||
assert!(opened.health.wait_timeout(&opened.device, None, std::time::Duration::from_secs(5)));
|
||||
// an index from another device's queue is one this device never issued
|
||||
let other = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap();
|
||||
other.queue.submit([]);
|
||||
let index = other.queue.submit([]);
|
||||
assert!(!opened.health.wait_timeout(&opened.device, Some(index), std::time::Duration::from_secs(5)));
|
||||
assert!(opened.health.is_ok(), "{:?}", opened.health.fault());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lost_device_is_seen_by_its_health() {
|
||||
let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap();
|
||||
let health = opened.health.clone();
|
||||
opened.device.destroy();
|
||||
health.probe(&opened.device);
|
||||
assert!(health.fault().is_some_and(|f| f.is_lost()), "{health:?}");
|
||||
assert!(!health.is_ok());
|
||||
// a later wait does not touch the lost device
|
||||
assert!(!health.wait(&opened.device, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pick_returns_the_selected_adapter() {
|
||||
let instance = noop(None);
|
||||
let (adapters, candidates) = list(&instance, None);
|
||||
assert_eq!(candidates.len(), 1);
|
||||
let (adapter, selection) = pick(&adapters, None, &Preference::Auto).unwrap();
|
||||
assert_eq!(selection.index, 0);
|
||||
assert_eq!(Candidate::of(&adapter, None), candidates[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,404 @@
|
||||
//! The adapter the user asked for, and what was drawn with instead when it is not there.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
use wgpu::{Backend, PowerPreference};
|
||||
|
||||
use crate::adapter::{Candidate, avoided, choose, corrected, intel_vulkan_crashes, type_order};
|
||||
|
||||
/// Which adapter to draw with.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", tag = "kind"))]
|
||||
pub enum Preference {
|
||||
/// The fastest adapter: a discrete GPU before an integrated one, hardware before software.
|
||||
#[default]
|
||||
Auto,
|
||||
/// An integrated GPU before a discrete one, for battery life.
|
||||
LowPower,
|
||||
/// One adapter the user picked from [`crate::list`].
|
||||
Adapter(AdapterKey),
|
||||
/// A software adapter that draws on the CPU.
|
||||
Software,
|
||||
}
|
||||
|
||||
impl Preference {
|
||||
/// The power preference that orders the adapters for this preference: low power for
|
||||
/// [`Preference::LowPower`], high performance otherwise.
|
||||
pub fn power(&self) -> PowerPreference {
|
||||
match self {
|
||||
Preference::LowPower => PowerPreference::LowPower,
|
||||
_ => PowerPreference::HighPerformance,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What identifies an adapter across runs: the backend, the PCI ids and bus, the driver name, and
|
||||
/// the name. The order in which the system lists adapters can change between runs, so an index
|
||||
/// cannot be kept.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(rename_all = "camelCase", default))]
|
||||
pub struct AdapterKey {
|
||||
pub name: String,
|
||||
/// wgpu's lowercase backend name (`vulkan`, `dx12`, `metal`, `gl`).
|
||||
pub backend: String,
|
||||
pub vendor: u32,
|
||||
pub device: u32,
|
||||
/// Empty when the driver reports none.
|
||||
pub pci_bus_id: String,
|
||||
/// The Vulkan driver's name, which tells apart two Vulkan drivers for one GPU (such as two on
|
||||
/// Linux) and stays the same across versions of a driver. Empty on the other backends, and
|
||||
/// when the driver reports none.
|
||||
pub driver: String,
|
||||
}
|
||||
|
||||
impl AdapterKey {
|
||||
pub fn of(candidate: &Candidate) -> Self {
|
||||
AdapterKey {
|
||||
name: candidate.name.clone(),
|
||||
backend: backend_name(candidate.backend).to_string(),
|
||||
vendor: candidate.vendor,
|
||||
device: candidate.device,
|
||||
pci_bus_id: candidate.pci_bus_id.clone(),
|
||||
// DirectX 12 reports the driver's version here, which changes with every update.
|
||||
driver: if candidate.backend == Backend::Vulkan { candidate.driver.clone() } else { String::new() },
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `candidate` is this adapter: the same backend and PCI ids, the same bus and the
|
||||
/// same driver when both report one, and the same name when the backend reports no PCI ids.
|
||||
pub fn matches(&self, candidate: &Candidate) -> bool {
|
||||
let identified = self.vendor != 0 || self.device != 0;
|
||||
let same = |a: &str, b: &str| a.is_empty() || b.is_empty() || a == b;
|
||||
self.backend == backend_name(candidate.backend)
|
||||
&& self.vendor == candidate.vendor
|
||||
&& self.device == candidate.device
|
||||
&& same(&self.pci_bus_id, &candidate.pci_bus_id)
|
||||
&& same(&self.driver, &candidate.driver)
|
||||
&& (identified || self.name == candidate.name)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for AdapterKey {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "\"{}\" ({})", self.name, self.backend)
|
||||
}
|
||||
}
|
||||
|
||||
/// wgpu's lowercase name of `backend`.
|
||||
pub fn backend_name(backend: Backend) -> &'static str {
|
||||
backend.to_str()
|
||||
}
|
||||
|
||||
/// Something the app tells the user about the adapter it draws with. The [`fmt::Display`] text is
|
||||
/// English, for the log; an app shows its own translated text for each variant.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Notice {
|
||||
/// The adapter the user picked is not listed (unplugged, disabled, or its driver removed).
|
||||
/// The automatic choice draws instead.
|
||||
AdapterMissing(AdapterKey),
|
||||
/// Software was asked for and no software adapter is listed. The automatic choice draws
|
||||
/// instead.
|
||||
NoSoftwareAdapter,
|
||||
/// The only adapter that can draw is a software one: drawing is slower and uses the CPU.
|
||||
SoftwareOnly,
|
||||
/// An adapter could not open a device, and the next one was tried.
|
||||
DeviceFailed { adapter: String, error: String },
|
||||
/// The device was lost this many times in a short time, so drawing moved to software.
|
||||
SoftwareAfterLosses(u32),
|
||||
}
|
||||
|
||||
impl fmt::Display for Notice {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Notice::AdapterMissing(key) => write!(f, "the graphics adapter {key} is not available; using the automatic choice"),
|
||||
Notice::NoSoftwareAdapter => f.write_str("no software graphics adapter is available; using the automatic choice"),
|
||||
Notice::SoftwareOnly => f.write_str("no graphics hardware can be used; drawing in software, which is slower"),
|
||||
Notice::DeviceFailed { adapter, error } => {
|
||||
write!(f, "the graphics adapter \"{adapter}\" could not be opened ({error}); trying the next one")
|
||||
}
|
||||
Notice::SoftwareAfterLosses(n) => write!(f, "the graphics device stopped working {n} times; drawing in software"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The adapter chosen for a preference, and what the user should be told about it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Selection {
|
||||
/// Index into the candidates.
|
||||
pub index: usize,
|
||||
pub notices: Vec<Notice>,
|
||||
}
|
||||
|
||||
/// The adapter to draw with for `preference`, or `None` when no adapter is usable.
|
||||
///
|
||||
/// - [`Preference::Auto`] and [`Preference::LowPower`] use [`choose`].
|
||||
/// - [`Preference::Adapter`] uses the usable entry that matches the key (the one exposing the most
|
||||
/// features when a driver lists it twice), with [`choose`]'s corrections; without one, or when
|
||||
/// it is an Intel Vulkan entry [`choose`] never draws with, the automatic choice and
|
||||
/// [`Notice::AdapterMissing`].
|
||||
/// - [`Preference::Software`] uses the first usable software adapter; without one, the automatic
|
||||
/// choice and [`Notice::NoSoftwareAdapter`].
|
||||
///
|
||||
/// A software adapter that the automatic choice took adds [`Notice::SoftwareOnly`].
|
||||
pub fn select(candidates: &[Candidate], preference: &Preference) -> Option<Selection> {
|
||||
let mut notices = Vec::new();
|
||||
let wanted = match preference {
|
||||
Preference::Auto | Preference::LowPower => None,
|
||||
Preference::Adapter(key) => {
|
||||
// An entry that reports no bus id matches any saved bus. When it is the same model on
|
||||
// the same driver it cannot be told apart from an older version of that driver, and
|
||||
// the correction draws with the entry exposing the most features.
|
||||
let found =
|
||||
candidates.iter().enumerate().filter(|(_, c)| c.usable && key.matches(c)).max_by_key(|(i, c)| (c.features, std::cmp::Reverse(*i)));
|
||||
match found.map(|(index, c)| corrected(candidates, index, c)) {
|
||||
Some(index) if !candidates.get(index).is_some_and(intel_vulkan_crashes) => Some(index),
|
||||
_ => {
|
||||
notices.push(Notice::AdapterMissing(key.clone()));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
Preference::Software => {
|
||||
let found = candidates.iter().position(|c| c.usable && c.is_software());
|
||||
if found.is_none() {
|
||||
notices.push(Notice::NoSoftwareAdapter);
|
||||
}
|
||||
found
|
||||
}
|
||||
};
|
||||
let index = match wanted {
|
||||
Some(index) => index,
|
||||
None => {
|
||||
let index = choose(candidates, preference.power())?;
|
||||
if candidates.get(index).is_some_and(Candidate::is_software) {
|
||||
notices.push(Notice::SoftwareOnly);
|
||||
}
|
||||
index
|
||||
}
|
||||
};
|
||||
Some(Selection { index, notices })
|
||||
}
|
||||
|
||||
/// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key
|
||||
/// of this adapter.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn asked_for(preference: &Preference, candidate: &Candidate) -> bool {
|
||||
match preference {
|
||||
Preference::Software => candidate.is_software(),
|
||||
Preference::Adapter(key) => key.matches(candidate),
|
||||
Preference::Auto | Preference::LowPower => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// The order in which to try opening a device for `preference`: [`select`]'s choice first, then
|
||||
/// every other usable adapter by device type for the preference's power (software after
|
||||
/// hardware), leaving out the entries [`choose`] never draws with: an older version of a driver
|
||||
/// listed twice, and the Vulkan entry of an Intel Gen 9 to Gen 11 GPU on Intel's Windows driver.
|
||||
/// Empty when no adapter is usable.
|
||||
pub fn ranked(candidates: &[Candidate], preference: &Preference) -> Vec<usize> {
|
||||
let Some(first) = select(candidates, preference).map(|s| s.index) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let power = preference.power();
|
||||
let mut rest: Vec<usize> =
|
||||
(0..candidates.len()).filter(|&i| i != first && candidates.get(i).is_some_and(|c| c.usable) && !avoided(candidates, i)).collect();
|
||||
rest.sort_by_key(|&i| (candidates.get(i).map_or(u8::MAX, |c| type_order(c.device_type, power)), i));
|
||||
let mut order = vec![first];
|
||||
order.extend(rest);
|
||||
order
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::adapter::tests::{gpu, two_amd_drivers, uhd_630};
|
||||
use wgpu::Backend::{Dx12, Vulkan};
|
||||
use wgpu::DeviceType::{Cpu, DiscreteGpu, IntegratedGpu};
|
||||
|
||||
fn key_of(candidates: &[Candidate], index: usize) -> AdapterKey {
|
||||
candidates.get(index).map(AdapterKey::of).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auto_and_low_power_are_the_corrected_wgpu_choice() {
|
||||
let adapters = two_amd_drivers();
|
||||
assert_eq!(select(&adapters, &Preference::Auto), Some(Selection { index: 1, notices: vec![] }));
|
||||
assert_eq!(select(&adapters, &Preference::LowPower).map(|s| s.index), Some(2));
|
||||
assert_eq!(select(&[], &Preference::Auto), None);
|
||||
assert_eq!(Preference::default(), Preference::Auto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_adapter_is_found_wherever_it_is_listed() {
|
||||
let adapters = two_amd_drivers();
|
||||
// the integrated Radeon through DirectX 12, picked by the user
|
||||
let key = key_of(&adapters, 4);
|
||||
assert_eq!(select(&adapters, &Preference::Adapter(key.clone())).map(|s| s.index), Some(4));
|
||||
// listed in another order on the next run
|
||||
let mut reordered = adapters.clone();
|
||||
reordered.reverse();
|
||||
assert_eq!(select(&reordered, &Preference::Adapter(key)).map(|s| s.index), Some(1));
|
||||
// the stale Vulkan entry of the RX 6800M stored as the choice: the newer version draws
|
||||
let stale = key_of(&adapters, 0);
|
||||
assert_eq!(select(&adapters, &Preference::Adapter(stale)).map(|s| s.index), Some(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_intel_gen9_vulkan_entry_draws_through_directx_12() {
|
||||
let adapters = uhd_630();
|
||||
let vulkan = key_of(&adapters, 0);
|
||||
assert_eq!(select(&adapters, &Preference::Adapter(vulkan.clone())).map(|s| s.index), Some(1));
|
||||
// without the DirectX 12 entry, the named Vulkan entry is not available
|
||||
let mut dx12_unusable = adapters.clone();
|
||||
dx12_unusable[1].usable = false;
|
||||
let s = select(&dx12_unusable, &Preference::Adapter(vulkan.clone()));
|
||||
assert_eq!(s.map(|s| (s.index, s.notices)), Some((2, vec![Notice::AdapterMissing(vulkan), Notice::SoftwareOnly])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_named_adapter_falls_back_to_auto_with_a_notice() {
|
||||
let adapters = two_amd_drivers();
|
||||
let gone = AdapterKey {
|
||||
name: "NVIDIA GeForce RTX 4090".into(),
|
||||
backend: "vulkan".into(),
|
||||
vendor: 0x10de,
|
||||
device: 0x2684,
|
||||
pci_bus_id: String::new(),
|
||||
driver: "NVIDIA".into(),
|
||||
};
|
||||
let s = select(&adapters, &Preference::Adapter(gone.clone()));
|
||||
assert_eq!(s, Some(Selection { index: 1, notices: vec![Notice::AdapterMissing(gone.clone())] }));
|
||||
// listed but unable to draw to the window counts as missing
|
||||
let mut unusable = adapters.clone();
|
||||
for c in &mut unusable {
|
||||
c.usable = c.backend != Vulkan;
|
||||
}
|
||||
let vulkan_key = key_of(&adapters, 1);
|
||||
let s = select(&unusable, &Preference::Adapter(vulkan_key.clone()));
|
||||
assert_eq!(s.map(|s| (s.index, s.notices)), Some((3, vec![Notice::AdapterMissing(vulkan_key)])));
|
||||
// nothing usable at all
|
||||
assert_eq!(select(&[], &Preference::Adapter(gone)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_tell_apart_backends_buses_and_unidentified_names() {
|
||||
let adapters = two_amd_drivers();
|
||||
let dx12 = key_of(&adapters, 3);
|
||||
assert!(dx12.matches(&adapters[3]));
|
||||
assert!(!dx12.matches(&adapters[1]), "same GPU, other backend");
|
||||
let other_bus = Candidate { pci_bus_id: "0000:04:00.0".into(), ..adapters[3].clone() };
|
||||
assert!(!dx12.matches(&other_bus));
|
||||
// a key stored without a bus id still matches an entry that reports one
|
||||
let no_bus = AdapterKey { pci_bus_id: String::new(), ..dx12.clone() };
|
||||
assert!(no_bus.matches(&adapters[3]));
|
||||
// two Vulkan drivers for one GPU are told apart by the driver name; a key saved without
|
||||
// one matches either
|
||||
let radv = gpu("AMD Radeon RX 6800M (RADV NAVI22)", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "radv", "Mesa 25.2.4", 70);
|
||||
let amdvlk = gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "AMD open-source driver", "2025.Q2.1", 72);
|
||||
let two = vec![radv.clone(), amdvlk.clone()];
|
||||
assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&radv))).map(|s| s.index), Some(0));
|
||||
assert_eq!(select(&two, &Preference::Adapter(AdapterKey::of(&amdvlk))).map(|s| s.index), Some(1));
|
||||
let old = AdapterKey { driver: String::new(), ..AdapterKey::of(&radv) };
|
||||
assert!(old.matches(&radv) && old.matches(&amdvlk));
|
||||
// a DirectX 12 key keeps matching after a driver update changes the reported version
|
||||
assert!(dx12.driver.is_empty());
|
||||
let updated = Candidate { driver: "32.0.21045.12000".into(), ..adapters[3].clone() };
|
||||
assert!(dx12.matches(&updated));
|
||||
// OpenGL reports no ids: the name decides
|
||||
let angle = gpu("ANGLE (D3D11)", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20);
|
||||
let swiftshader = gpu("SwiftShader", wgpu::Backend::Gl, wgpu::DeviceType::Other, 0, 0, "", "", "", 20);
|
||||
let key = AdapterKey::of(&angle);
|
||||
assert!(key.matches(&angle) && !key.matches(&swiftshader));
|
||||
assert_eq!(dx12.to_string(), "\"AMD Radeon RX 6800M\" (dx12)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn software_is_used_when_asked_and_reported_when_it_is_all_there_is() {
|
||||
let adapters = two_amd_drivers();
|
||||
assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 5, notices: vec![] }));
|
||||
let hardware_only: Vec<Candidate> = adapters.iter().filter(|c| !c.is_software()).cloned().collect();
|
||||
assert_eq!(select(&hardware_only, &Preference::Software), Some(Selection { index: 1, notices: vec![Notice::NoSoftwareAdapter] }));
|
||||
let llvmpipe = vec![gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "", 50)];
|
||||
assert_eq!(select(&llvmpipe, &Preference::Auto), Some(Selection { index: 0, notices: vec![Notice::SoftwareOnly] }));
|
||||
assert_eq!(select(&llvmpipe, &Preference::Software), Some(Selection { index: 0, notices: vec![] }));
|
||||
// picked by name, it is what was asked for
|
||||
let named = Preference::Adapter(AdapterKey::of(&llvmpipe[0]));
|
||||
assert_eq!(select(&llvmpipe, &named), Some(Selection { index: 0, notices: vec![] }));
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
assert!(asked_for(&named, &llvmpipe[0]) && asked_for(&Preference::Software, &llvmpipe[0]));
|
||||
assert!(!asked_for(&Preference::Auto, &llvmpipe[0]) && !asked_for(&Preference::Software, &adapters[1]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fallback_order_never_tries_entries_that_can_crash() {
|
||||
let adapters = two_amd_drivers();
|
||||
// the newer RX 6800M, then the other hardware by type for high performance, then software;
|
||||
// the stale RX 6800M entry is never tried
|
||||
assert_eq!(ranked(&adapters, &Preference::Auto), vec![1, 3, 2, 4, 5]);
|
||||
assert_eq!(ranked(&adapters, &Preference::LowPower), vec![2, 4, 1, 3, 5]);
|
||||
assert_eq!(ranked(&adapters, &Preference::Software), vec![5, 1, 3, 2, 4]);
|
||||
// two cards of one model on one driver, one without a Vulkan bus id: the second card's
|
||||
// Vulkan entry looks like an older version, and the card is tried through DirectX 12
|
||||
let card = |bus: &str| gpu("AMD Radeon RX 7900 XT", Vulkan, DiscreteGpu, 0x1002, 0x744c, bus, "AMD proprietary driver", "", 68);
|
||||
let dx12 = |bus: &str| gpu("AMD Radeon RX 7900 XT", Dx12, DiscreteGpu, 0x1002, 0x744c, bus, "32.0.21045.11001", "", 36);
|
||||
let twins = vec![card("0000:03:00.0"), card(""), dx12("0000:03:00.0"), dx12("0000:04:00.0")];
|
||||
assert_eq!(ranked(&twins, &Preference::Auto), vec![0, 2, 3]);
|
||||
// the same bus id on both entries: one GPU, and the older version is never tried
|
||||
let mut versions = vec![card("0000:03:00.0"), card("0000:03:00.0")];
|
||||
versions[1].features = 70;
|
||||
assert_eq!(ranked(&versions, &Preference::Auto), vec![1]);
|
||||
// a third entry without a bus id and with more features: both older entries are left out
|
||||
versions.push(card(""));
|
||||
versions[2].features = 80;
|
||||
assert_eq!(ranked(&versions, &Preference::Auto), vec![2]);
|
||||
// two GPUs on different buses are both tried
|
||||
let cards = vec![card("0000:03:00.0"), card("0000:04:00.0")];
|
||||
assert_eq!(ranked(&cards, &Preference::Auto), vec![0, 1]);
|
||||
// the Intel Gen 9 Vulkan entry is never tried, with or without a usable DirectX 12 entry
|
||||
assert_eq!(ranked(&uhd_630(), &Preference::Auto), vec![1, 2]);
|
||||
let mut dx12_unusable = uhd_630();
|
||||
dx12_unusable[1].usable = false;
|
||||
assert_eq!(ranked(&dx12_unusable, &Preference::Auto), vec![2]);
|
||||
assert!(ranked(&uhd_630()[..1], &Preference::Auto).is_empty());
|
||||
assert!(ranked(&[], &Preference::Auto).is_empty());
|
||||
let unusable: Vec<Candidate> = adapters.iter().map(|c| Candidate { usable: false, ..c.clone() }).collect();
|
||||
assert!(ranked(&unusable, &Preference::Auto).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_laptop_with_two_vendors_keeps_the_named_gpu_across_reorders() {
|
||||
let intel = gpu("Intel(R) UHD Graphics 770", Dx12, IntegratedGpu, 0x8086, 0x4680, "0000:00:02.0", "31.0.101.5186", "", 36);
|
||||
let nvidia = gpu("NVIDIA GeForce RTX 4070 Laptop GPU", Dx12, DiscreteGpu, 0x10de, 0x2820, "0000:01:00.0", "32.0.15.6094", "", 36);
|
||||
let a = vec![intel.clone(), nvidia.clone()];
|
||||
let b = vec![nvidia, intel];
|
||||
let picked = Preference::Adapter(key_of(&a, 0));
|
||||
assert_eq!(select(&a, &picked).map(|s| s.index), Some(0));
|
||||
assert_eq!(select(&b, &picked).map(|s| s.index), Some(1));
|
||||
assert_eq!(ranked(&b, &picked), vec![1, 0]);
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[test]
|
||||
fn preferences_read_back_what_they_write() {
|
||||
let key = AdapterKey {
|
||||
name: "AMD Radeon RX 6800M".into(),
|
||||
backend: "dx12".into(),
|
||||
vendor: 0x1002,
|
||||
device: 0x73df,
|
||||
pci_bus_id: "0000:03:00.0".into(),
|
||||
driver: String::new(),
|
||||
};
|
||||
for p in [Preference::Auto, Preference::LowPower, Preference::Software, Preference::Adapter(key)] {
|
||||
let text = serde_json::to_string(&p).unwrap();
|
||||
assert_eq!(serde_json::from_str::<Preference>(&text).unwrap(), p, "{text}");
|
||||
}
|
||||
assert_eq!(serde_json::to_string(&Preference::Auto).unwrap(), r#"{"kind":"auto"}"#);
|
||||
// a key written by an older version without some fields
|
||||
let p: Preference = serde_json::from_str(r#"{"kind":"adapter","name":"x","backend":"vulkan"}"#).unwrap();
|
||||
assert_eq!(p, Preference::Adapter(AdapterKey { name: "x".into(), backend: "vulkan".into(), ..Default::default() }));
|
||||
assert!(serde_json::from_str::<Preference>(r#"{"kind":"fastest"}"#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! What to open after a device loss.
|
||||
//!
|
||||
//! A device is lost when the driver resets the GPU, the OS ends a long submission, the PC sleeps,
|
||||
//! or the GPU is unplugged. The app drops everything it made with the device and opens a new one.
|
||||
//! [`Recovery`] decides with what preference: the user's own, until the device has been lost
|
||||
//! [`RecoveryPolicy::max_losses`] times within [`RecoveryPolicy::window`], and software after that,
|
||||
//! so a GPU that keeps failing does not stop the app from drawing.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::preference::{Notice, Preference};
|
||||
|
||||
/// When repeated losses move drawing to software.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RecoveryPolicy {
|
||||
/// Losses within [`window`](Self::window) after which the next device is a software one.
|
||||
/// 0 never moves to software.
|
||||
pub max_losses: u32,
|
||||
pub window: Duration,
|
||||
}
|
||||
|
||||
impl Default for RecoveryPolicy {
|
||||
fn default() -> Self {
|
||||
RecoveryPolicy { max_losses: 3, window: Duration::from_secs(600) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The preference to open the next device with.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct RecoveryStep {
|
||||
pub preference: Preference,
|
||||
/// [`Notice::SoftwareAfterLosses`] when this step moved drawing to software.
|
||||
pub notice: Option<Notice>,
|
||||
}
|
||||
|
||||
/// Device losses seen so far, against the user's preference.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Recovery {
|
||||
preference: Preference,
|
||||
policy: RecoveryPolicy,
|
||||
/// When each loss inside the window happened, oldest first.
|
||||
losses: VecDeque<Duration>,
|
||||
software: bool,
|
||||
}
|
||||
|
||||
impl Recovery {
|
||||
pub fn new(preference: Preference, policy: RecoveryPolicy) -> Self {
|
||||
Recovery { preference, policy, losses: VecDeque::new(), software: false }
|
||||
}
|
||||
|
||||
/// The preference to open a device with now.
|
||||
pub fn preference(&self) -> &Preference {
|
||||
if self.software { &Preference::Software } else { &self.preference }
|
||||
}
|
||||
|
||||
/// The user changed the preference: losses counted so far no longer apply.
|
||||
pub fn set_preference(&mut self, preference: Preference) {
|
||||
self.preference = preference;
|
||||
self.losses.clear();
|
||||
self.software = false;
|
||||
}
|
||||
|
||||
/// Record a loss at `at`, a monotonic time the caller keeps (since the app started), and
|
||||
/// return what to open next. A time earlier than the last loss counts as the same time.
|
||||
pub fn lost(&mut self, at: Duration) -> RecoveryStep {
|
||||
let at = self.losses.back().map_or(at, |last| at.max(*last));
|
||||
self.losses.push_back(at);
|
||||
// Only the last `max_losses` losses decide anything, so no more are kept.
|
||||
let keep = usize::try_from(self.policy.max_losses.max(1)).unwrap_or(usize::MAX);
|
||||
while self.losses.len() > keep || self.losses.front().is_some_and(|first| at.saturating_sub(*first) > self.policy.window) {
|
||||
self.losses.pop_front();
|
||||
}
|
||||
let count = u32::try_from(self.losses.len()).unwrap_or(u32::MAX);
|
||||
let mut notice = None;
|
||||
if !self.software && self.policy.max_losses > 0 && count >= self.policy.max_losses && self.preference != Preference::Software {
|
||||
self.software = true;
|
||||
notice = Some(Notice::SoftwareAfterLosses(count));
|
||||
}
|
||||
RecoveryStep { preference: self.preference().clone(), notice }
|
||||
}
|
||||
|
||||
/// Losses inside the window, as of the last one, counting at most
|
||||
/// [`RecoveryPolicy::max_losses`] (at least 1).
|
||||
pub fn recent_losses(&self) -> usize {
|
||||
self.losses.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn s(secs: u64) -> Duration {
|
||||
Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_third_loss_in_ten_minutes_moves_to_software() {
|
||||
let mut r = Recovery::new(Preference::Auto, RecoveryPolicy::default());
|
||||
assert_eq!(r.lost(s(10)), RecoveryStep { preference: Preference::Auto, notice: None });
|
||||
assert_eq!(r.lost(s(100)), RecoveryStep { preference: Preference::Auto, notice: None });
|
||||
assert_eq!(r.lost(s(300)), RecoveryStep { preference: Preference::Software, notice: Some(Notice::SoftwareAfterLosses(3)) });
|
||||
// it stays on software, and says so once
|
||||
assert_eq!(r.lost(s(400)), RecoveryStep { preference: Preference::Software, notice: None });
|
||||
assert_eq!(r.preference(), &Preference::Software);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn losses_outside_the_window_are_forgotten() {
|
||||
let mut r = Recovery::new(Preference::LowPower, RecoveryPolicy::default());
|
||||
r.lost(s(0));
|
||||
r.lost(s(500));
|
||||
// the first loss is more than 600 s before this one
|
||||
assert_eq!(r.lost(s(601)).preference, Preference::LowPower);
|
||||
assert_eq!(r.recent_losses(), 2);
|
||||
// a clock that goes back counts as the last loss's time
|
||||
assert_eq!(r.lost(s(1)).preference, Preference::Software);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_preference_starts_over() {
|
||||
let mut r = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 2, window: s(60) });
|
||||
r.lost(s(1));
|
||||
assert_eq!(r.lost(s(2)).preference, Preference::Software);
|
||||
r.set_preference(Preference::LowPower);
|
||||
assert_eq!(r.preference(), &Preference::LowPower);
|
||||
assert_eq!(r.recent_losses(), 0);
|
||||
assert_eq!(r.lost(s(3)).preference, Preference::LowPower);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn software_and_a_zero_limit_never_add_a_notice() {
|
||||
let mut r = Recovery::new(Preference::Software, RecoveryPolicy::default());
|
||||
for t in 0..5 {
|
||||
assert_eq!(r.lost(s(t)), RecoveryStep { preference: Preference::Software, notice: None });
|
||||
}
|
||||
let mut never = Recovery::new(Preference::Auto, RecoveryPolicy { max_losses: 0, window: s(60) });
|
||||
for t in 0..10 {
|
||||
assert_eq!(never.lost(s(t)).preference, Preference::Auto);
|
||||
}
|
||||
assert_eq!(never.recent_losses(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_loss_history_stays_bounded() {
|
||||
let mut r = Recovery::new(Preference::Software, RecoveryPolicy { max_losses: 3, window: Duration::MAX });
|
||||
for _ in 0..10_000 {
|
||||
r.lost(s(5));
|
||||
}
|
||||
assert_eq!(r.recent_losses(), 3);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user