Merge pull request #2089 from dotCooCoo/feat/craft-gpu-device

craft-gpu-device: choose and open a wgpu device
This commit is contained in:
BFlat authored and GitHub committed 2026-11-28 11:47:20 +07:00
commit 4fca07fd7a
19 files changed
+3056

No files matched your search

+4
View File
@@ -174,6 +174,10 @@ Sanitization, animation fitting and numeric output policy remain caller-owned.
`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`'s 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.
## Dalvik DEX inspection
`crates/dex` extracts Craft Anything `crates/formats/src/dex.rs` and `dex_ops.rs` at `5979f9b13f16dcf1df3c7ae7f8e7735f452866f2` (MIT OR Apache-2.0). Five source-history ports preserve Brandon Thomas, BFlat and Afloat as primary authors. Five regression imports retain BFlat/Afloat authors and exact source revisions. The checked byte-reader/MUTF-8 subset and synthetic DEX fixture come from that app's `bytes.rs` and `testkit/src/android.rs`; deterministic noise/mutations come from its testkit. No application file I/O, APK logic or execution is imported. Shared neutral errors and workspace wiring are subsequent changes; existing per-file strings, member/handler and bytecode payload budgets are retained.
Generated
+13
View File
@@ -1819,6 +1819,7 @@ dependencies = [
"craft-geom",
"craft-gif",
"craft-gpu",
"craft-gpu-device",
"craft-gpu-null",
"craft-gpu-providers",
"craft-gpu-wgpu",
@@ -2922,6 +2923,18 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-gpu-device"
version = "0.1.0"
dependencies = [
"craft-gpu",
"log",
"pollster 0.4.0",
"serde",
"serde_json",
"wgpu",
]
[[package]]
name = "craft-gpu-null"
version = "0.1.0"
+1
View File
@@ -37,6 +37,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-wasm = { path = "crates/wasm" }
craft-platform = { path = "crates/platform" }
craft-png = { path = "crates/png" }
+5
View File
@@ -211,6 +211,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.
+8
View File
@@ -222,6 +222,7 @@ craft-geom = { workspace = true, optional = true }
craft-suite-account = { workspace = true, optional = true }
craft-xfa = { workspace = true, optional = true }
craft-gpu = { workspace = true, optional = true }
craft-gpu-device = { workspace = true, optional = true }
craft-gpu-null = { workspace = true, optional = true }
craft-gpu-providers = { workspace = true, optional = true }
craft-gpu-wgpu = { workspace = true, optional = true }
@@ -533,6 +534,13 @@ gif-frames = ["gif", "craft-gif/frames"]
gpu = ["dep:craft-gpu"]
gpu-startup = ["gpu", "craft-gpu/startup"]
gpu-device = ["dep:craft-gpu-device"]
gpu-device-native-dx12 = ["gpu-device", "craft-gpu-device/native-dx12"]
gpu-device-native-gles = ["gpu-device", "craft-gpu-device/native-gles"]
gpu-device-native-metal = ["gpu-device", "craft-gpu-device/native-metal"]
gpu-device-native-vulkan = ["gpu-device", "craft-gpu-device/native-vulkan"]
gpu-device-serde = ["gpu-device", "craft-gpu-device/serde"]
gpu-null = ["dep:craft-gpu-null"]
gpu-providers = ["dep:craft-gpu-providers"]
+2
View File
@@ -161,6 +161,8 @@ pub use craft_geom as geom;
pub use craft_gif as gif;
#[cfg(feature = "gpu")]
pub use craft_gpu as gpu;
#[cfg(feature = "gpu-device")]
pub use craft_gpu_device as gpu_device;
#[cfg(feature = "gpu-null")]
pub use craft_gpu_null as gpu_null;
#[cfg(feature = "gpu-providers")]
+39
View File
@@ -0,0 +1,39 @@
[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"]
# Native wgpu backends, as in craft-gpu-wgpu. None is on by default; the app turns on the ones it
# ships, through this crate or through craft-gpu-wgpu.
native-vulkan = ["wgpu/vulkan"]
native-dx12 = ["wgpu/dx12"]
native-metal = ["wgpu/metal"]
native-gles = ["wgpu/gles"]
[dependencies]
craft-gpu = { workspace = true }
log = { workspace = true }
serde = { workspace = true, optional = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wgpu = { workspace = true, features = ["webgpu"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
pollster = { workspace = true }
wgpu = { workspace = true }
[dev-dependencies]
# The noop backend opens devices without a GPU in the tests.
wgpu = { workspace = true, features = ["noop"] }
serde_json = { workspace = true }
+10
View File
@@ -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.
+128
View File
@@ -0,0 +1,128 @@
# 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 `craft-gpu`, `wgpu` 30, `pollster` and `log`, with
`serde` as an optional feature (on by default). It depends on no app crate.
It uses the workspace's `wgpu`, which turns on no native backend, and the WebGPU backend on
`wasm32`. The `native-vulkan`, `native-dx12`, `native-metal` and `native-gles` features turn on
wgpu's backends, as the features of the same names in `craft-gpu-wgpu` do. Cargo merges the
features, so an app can turn them on through either crate.
The `gpu-device` feature of `craft` exports this crate as `craft::gpu_device`.
`native_instance` shares one instance across calls on native targets. It reads wgpu's environment
settings for flags and backend options when that instance is first created. `native_descriptor`
reads those settings on every call.
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` |
| `list_async`, `open_async` | `list` and `open` as futures, for a `wasm32` web worker as well as native; in a browser `list_async` gives the high-performance adapter, the one `open_async` opens for `Auto` and a named adapter |
| `pick(adapters, surface, preference)` | `select` over listed adapters, for egui-wgpu's `native_adapter_selector`; the error is an `OpenError` (convert it with `map_err(\|e\| e.to_string())` for that 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, read from the `craft_gpu::DeviceCaps` it holds (its fields are readable through `Deref`; `From` converts both ways) |
| `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) |
| `device_caps(device)`, `Opened::device_caps` | the `craft_gpu::DeviceCaps` of a device: its own limits, enabled feature names, vendor id and software flag, in the form `craft-gpu-wgpu` reports |
| `DeviceHealth::device_status` | a recorded loss as `craft_gpu::GpuFault::DeviceLost`, in the form of `GpuContext::device_status`; `Fault` converts to `GpuFault` (a loss to `DeviceLost`, an error to `Operation`) |
| `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` and `pick` return
`OpenError::NoAdapter`, or `OpenError::UnsafeDriver` when only a driver that can end the
process can draw.
- In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be
chosen. `open_async` asks for the adapter with `Preference::power()` as the power preference,
and gives the automatic choice with `Notice::AdapterMissing` for a named adapter. wgpu 30
does not pass the fallback-adapter option to the browser, so `Preference::Software` opens the
browser's adapter, with `Notice::NoSoftwareAdapter` unless that adapter is a software one, and
`Recovery` cannot move drawing to software there. `Capabilities` and
`Recovery` otherwise work there as they do on native, and so does `DeviceHealth` apart from `wait`,
`wait_timeout` and `wait_timeout_cancelable`, which are native only. On the browser backend,
wgpu 30 panics on an uncaptured `GPUInternalError` before the handler `DeviceHealth::watch`
installs runs, so such an error is not recorded. Validation and out-of-memory errors are.
- An adapter that lacks `Request::required_features`, whose limits are lower than
`Request::limits`, 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 whose cause is wgpu's "Parent device is lost" counts as a loss. The same words in
a resource's label do not count. An error about a destroyed buffer or texture is recorded as an
error.
- `wait`, `wait_timeout` and `wait_timeout_cancelable` wait for one submission index. To wait for
everything submitted so far, pass `queue.submit([])`; work submitted later does not extend the
wait.
- `wait` has no deadline. It polls in slices of at most 100 ms, and a loss or an error other than
out of memory that another clone of the `DeviceHealth` records ends it after the current slice.
- `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.
- wgpu keeps one device-lost callback per device, and a later `set_device_lost_callback`
replaces the one `DeviceHealth::watch` set. A `craft-gpu` context on a watched device reads
`DeviceHealth::device_status` instead of setting its own callback.
- After an out-of-memory error, polls and waits keep running, so staging memory is reclaimed.
The app reads `DeviceHealth::out_of_memory_count` when it handles the error, frees memory, and
passes the count to `DeviceHealth::clear_out_of_memory`. The device is then healthy again,
unless it was lost, another error was recorded, or a new out-of-memory error came in after the
count was read.
## After a device loss
`DeviceHealth::device_status` returns `GpuFault::DeviceLost` once a loss is recorded, and the
caller starts recovery then. `DeviceHealth::device_lost` turns true only when wgpu itself reported
the loss; it stays false for a loss the health layer recorded on its own, such as a bounded wait
that reached its deadline. Nothing made with the lost device can be used again, and wgpu keeps
none of its contents. The caller then:
1. Drops the old `Opened` and everything made with its device: buffers, textures and their
views, samplers, bind group layouts and bind groups, shader modules, pipeline layouts and
pipelines, query sets, unsubmitted command encoders, and any renderer that holds them (an
egui-wgpu `Renderer`, for example). Work submitted before the loss does not complete, and
waits on it return `false`.
2. Calls `Recovery::lost` with the time and opens a new device with `open` or `open_async`,
using the returned preference and the same `Request`. When the step has a notice
(`Notice::SoftwareAfterLosses`), the app shows it only if the new `Opened::caps.software()` is
true. Otherwise no software adapter opened (in a browser, or with none listed), and the new
`Opened::notices` say what was opened instead.
3. Reads the new `Opened::caps` before choosing pipelines again. The new device can be another
adapter, or a software one, with other features and limits: for example, without NV12 the
planes are drawn into `R8Unorm` and `Rg8Unorm` textures instead.
4. Configures each window surface again with the new device (`Surface::configure`). The surface
itself is kept when it was passed to `open`, which then opens only an adapter that can draw
to it. The new adapter may not support the old configuration (an HDR format, for example), so
the caller reads `Surface::get_capabilities` with the new adapter and picks a format, present
mode and alpha mode from it.
5. Builds the pipelines for the surface format picked in step 4, and the bind groups and
renderers, again, and uploads the textures and buffers again from the app's own copies of
their data.
6. Makes any `craft-gpu` context again on the new device, with the new `Opened::device_caps`, and
submits again the jobs and frames that did not complete.
7. Uses the new `Opened::health`. The old `DeviceHealth` keeps reporting 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.
+647
View File
@@ -0,0 +1,647 @@
//! 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.
///
/// On native targets, the first call creates one shared instance and reads wgpu's environment
/// settings for flags and backend options. Later calls return clones of that instance.
pub fn native_instance() -> wgpu::Instance {
#[cfg(not(target_arch = "wasm32"))]
{
static SHARED: std::sync::OnceLock<wgpu::Instance> = std::sync::OnceLock::new();
SHARED.get_or_init(|| wgpu::Instance::new(native_descriptor())).clone()
}
#[cfg(target_arch = "wasm32")]
{
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), repeated until the entry is its own newest version. 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. The result is never an entry `avoided` excludes.
pub fn choose(candidates: &[Candidate], power: PowerPreference) -> Option<usize> {
let first = wgpu_choice(candidates, power)?;
let index = settled(candidates, first);
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, _) = safe.min_by_key(|(i, c)| (type_order(c.device_type, power), *i))?;
return Some(settled(candidates, other));
}
Some(index)
}
/// [`corrected`] applied until it returns the entry it was given. An entry without a bus id can
/// be the same GPU as two entries on different buses, so one correction can land on an entry that
/// has a newer version of its own. Each step moves to an entry exposing more features (or the
/// same number at a lower index), or to a DirectX 12 entry, so the loop ends.
pub(crate) fn settled(candidates: &[Candidate], mut index: usize) -> usize {
for _ in 0..=candidates.len() {
let Some(c) = candidates.get(index) else {
return index;
};
let next = corrected(candidates, index, c);
if next == index {
return index;
}
index = next;
}
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 an_entry_without_a_bus_between_two_cards_is_never_drawn_with_when_avoided() {
// two cards of one model on their own buses, and an entry of the same driver without a bus
// id, which can be either card's other version
let radeon = |bus, features| gpu("AMD Radeon RX 6800M", Vulkan, DiscreteGpu, AMD, RX_6800M, bus, "AMD proprietary driver", "", features);
let adapters = vec![radeon("0000:03:00.0", 60), radeon("", 70), radeon("0000:04:00.0", 80)];
for power in POWERS {
let chosen = choose(&adapters, power);
assert_eq!(chosen, Some(2), "{power:?}");
assert!(chosen.is_some_and(|i| !avoided(&adapters, i)), "{power:?}");
}
assert!(avoided(&adapters, 0) && avoided(&adapters, 1) && !avoided(&adapters, 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));
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn native_instance_is_shared_across_callers() {
let gate = std::sync::Barrier::new(3);
std::thread::scope(|scope| {
let first = scope.spawn(|| {
gate.wait();
native_instance()
});
let second = scope.spawn(|| {
gate.wait();
native_instance()
});
gate.wait();
let first = first.join().unwrap();
assert_eq!(first, second.join().unwrap());
assert_eq!(first, native_instance());
});
}
/// 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, or, when wgpu's choice
/// is one [`avoided`] excludes, an adapter it does not exclude: a version exposing more
/// features, an Intel Gen 9 to Gen 11 GPU's DirectX 12 entry, or the best other adapter.
/// `None` only when every usable adapter is that Intel Vulkan 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 own_index = wgpu_choice(&candidates, power);
let chosen = choose(&candidates, power);
let picked = chosen.and_then(|i| candidates.get(i));
match (own_index, chosen) {
(Some(own), Some(index)) if own != index => {
assert!(avoided(&candidates, own), "{power:?}: {picked:?} instead of {wgpu_own:?}, which is not avoided");
assert!(!avoided(&candidates, index), "{power:?}: {picked:?} is avoided");
}
(Some(own), None) => {
let only_intel_vulkan = candidates.iter().filter(|c| c.usable).all(intel_vulkan_crashes);
assert!(only_intel_vulkan, "{power:?}: nothing instead of {:?}", candidates.get(own));
}
_ => assert_eq!(picked, wgpu_own.as_ref(), "{power:?}"),
}
}
}
}
+311
View File
@@ -0,0 +1,311 @@
//! What an adapter can do, for choosing a pipeline and for the settings and the log.
use std::fmt;
use std::ops::Deref;
use craft_gpu::DeviceCaps;
use wgpu::{AdapterInfo, 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 a device (or an adapter) can do, read from the [`DeviceCaps`] a `craft-gpu` context
/// reports. It holds only that `DeviceCaps`: the video formats, `f16` and timestamps come from its
/// feature names, the vendor from its vendor id, and its fields (the name, the backend and the
/// limits) can be read through `Deref`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Capabilities(DeviceCaps);
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(device_caps_of(info, features, limits))
}
/// What `adapter` offers, for a settings page before a device is opened. A `craft-gpu`
/// context reports [`of_device`](Self::of_device) instead: a device can be granted less.
pub fn of_adapter(adapter: &wgpu::Adapter) -> Self {
Self::from_parts(&adapter.get_info(), adapter.features(), &adapter.limits())
}
/// What `device` can do: the features and limits it was opened with.
pub fn of_device(device: &wgpu::Device) -> Self {
Self::from_parts(&device.adapter_info(), device.features(), &device.limits())
}
/// The `DeviceCaps` these capabilities read.
pub fn device_caps(&self) -> &DeviceCaps {
&self.0
}
pub fn into_device_caps(self) -> DeviceCaps {
self.0
}
/// Whether every feature in `features` is named in the caps.
fn has(&self, features: Features) -> bool {
features.iter_names().all(|(name, _)| self.0.has_feature(name))
}
/// 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 fn nv12(&self) -> bool {
self.has(Features::TEXTURE_FORMAT_NV12)
}
/// 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 fn p010(&self) -> bool {
self.has(Features::TEXTURE_FORMAT_P010)
}
/// `R16Unorm`, `Rg16Unorm` and `Rgba16Unorm` textures, for 10-bit and higher planes without
/// P010.
pub fn norm16(&self) -> bool {
self.has(Features::TEXTURE_FORMAT_16BIT_NORM)
}
/// `f16` in shaders.
pub fn shader_f16(&self) -> bool {
self.has(Features::SHADER_F16)
}
/// Timestamp queries, for measuring GPU time per pass.
pub fn timestamps(&self) -> bool {
self.has(Features::TIMESTAMP_QUERY)
}
pub fn vendor(&self) -> Vendor {
Vendor::from_id(self.0.vendor_id)
}
/// The adapter draws on the CPU.
pub fn software(&self) -> bool {
self.0.software
}
/// Whether a `width` × `height` texture fits.
pub fn fits(&self, width: u32, height: u32) -> bool {
let max = self.0.max_texture_dimension_2d;
width > 0 && height > 0 && width <= max && height <= max
}
/// 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 Deref for Capabilities {
type Target = DeviceCaps;
fn deref(&self) -> &DeviceCaps {
&self.0
}
}
impl From<DeviceCaps> for Capabilities {
fn from(caps: DeviceCaps) -> Self {
Capabilities(caps)
}
}
impl From<Capabilities> for DeviceCaps {
fn from(caps: Capabilities) -> Self {
caps.0
}
}
impl fmt::Display for Capabilities {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\"{}\" ({}, {}", self.0.device_name, self.vendor(), self.0.backend_name)?;
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.0.max_texture_dimension_2d)
}
}
/// The [`DeviceCaps`] a `craft-gpu` context reports for `device`: the limits and features the
/// device was opened with, not the adapter's, in the same form `craft-gpu-wgpu` reports for a
/// device it opens itself.
pub fn device_caps(device: &wgpu::Device) -> DeviceCaps {
Capabilities::of_device(device).into_device_caps()
}
fn device_caps_of(info: &AdapterInfo, features: Features, limits: &Limits) -> DeviceCaps {
DeviceCaps {
backend_name: format!("{:?}", info.backend),
device_name: info.name.clone(),
max_storage_buffer_binding_size: limits.max_storage_buffer_binding_size,
max_buffer_size: limits.max_buffer_size,
max_texture_dimension_2d: limits.max_texture_dimension_2d,
features: features.iter_names().map(|(name, _)| name.to_string()).collect(),
vendor_id: info.vendor,
software: info.device_type == DeviceType::Cpu,
}
}
#[cfg(test)]
mod tests {
use wgpu::Backend;
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_dimension_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);
}
#[test]
fn device_caps_carry_the_device_limits_and_feature_names() {
let limits =
Limits { max_texture_dimension_2d: 16384, max_buffer_size: 1 << 30, max_storage_buffer_binding_size: 1 << 28, ..Limits::default() };
let features = Features::TEXTURE_FORMAT_NV12 | Features::TIMESTAMP_QUERY;
let caps = device_caps_of(&info("NVIDIA GeForce RTX 4070", 0x10de, DeviceType::DiscreteGpu), features, &limits);
assert_eq!(caps.backend_name, "Vulkan");
assert_eq!(caps.device_name, "NVIDIA GeForce RTX 4070");
assert_eq!((caps.max_texture_dimension_2d, caps.max_buffer_size, caps.max_storage_buffer_binding_size), (16384, 1 << 30, 1 << 28));
assert_eq!((caps.vendor_id, caps.software), (0x10de, false));
let mut names = caps.features.clone();
names.sort();
assert_eq!(names, ["TEXTURE_FORMAT_NV12", "TIMESTAMP_QUERY"]);
// a device opened without features reports none
let bare = device_caps_of(&info("llvmpipe", 0x10005, DeviceType::Cpu), Features::empty(), &Limits::downlevel_defaults());
assert!(bare.features.is_empty());
assert_eq!(bare.max_texture_dimension_2d, 2048);
assert_eq!((bare.vendor_id, bare.software), (0x10005, true));
}
#[test]
fn caps_from_a_craft_gpu_context_read_as_capabilities() {
let caps = DeviceCaps {
backend_name: "Dx12".into(),
device_name: "Intel(R) Arc(TM) A770".into(),
features: vec!["TEXTURE_FORMAT_P010".into(), "SHADER_F16".into(), "TEXTURE_FORMAT_16BIT_NORM".into()],
vendor_id: 0x8086,
..DeviceCaps::default()
};
let c = Capabilities::from(caps.clone());
assert!(c.p010() && c.shader_f16() && c.ten_bit() && !c.nv12() && !c.timestamps() && !c.software());
assert_eq!(c.vendor(), Vendor::Intel);
assert_eq!(c.to_string(), "\"Intel(R) Arc(TM) A770\" (Intel, Dx12, P010, 16-bit norm, f16, textures up to 8192 px)");
assert_eq!(DeviceCaps::from(c), caps);
// the caps of a backend with no device claim nothing
let none = Capabilities::from(DeviceCaps::default());
assert!(!none.nv12() && !none.p010() && !none.norm16() && !none.shader_f16() && !none.timestamps() && !none.software());
assert_eq!(none.vendor(), Vendor::Other(0));
}
}
+764
View File
@@ -0,0 +1,764 @@
//! 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, or just after it, when wgpu read the
/// fence again at the end of the last poll.
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, calling
/// [`DeviceHealth::clear_out_of_memory`] with the count read from
/// [`DeviceHealth::out_of_memory_count`] and trying again can succeed, unlike after a loss or
/// a validation error. Polls and waits keep running meanwhile. 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}"),
}
}
}
/// A loss becomes [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost), and any other
/// fault becomes [`GpuFault::Operation`](craft_gpu::GpuFault::Operation), each with the fault's
/// text.
impl From<Fault> for craft_gpu::GpuFault {
fn from(fault: Fault) -> Self {
match fault {
Fault::Lost(s) => craft_gpu::GpuFault::DeviceLost(s),
Fault::Error(s) => craft_gpu::GpuFault::Operation(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 {
/// The first device loss.
lost: OnceLock<String>,
/// Out-of-memory errors seen.
out_of_memory_seen: AtomicU64,
/// Out-of-memory errors the caller cleared ([`DeviceHealth::clear_out_of_memory`]).
out_of_memory_cleared: AtomicU64,
/// 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). On the
/// browser backend, wgpu 30 panics on an uncaptured `GPUInternalError` before this handler
/// runs, so such an error is not recorded; validation and out-of-memory errors are.
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}");
// The loss first: a caller that sees `device_lost` then also sees the fault.
lost.mark(Fault::Lost(detail));
lost.0.device_lost.store(true, Ordering::Release);
});
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 is reported over another error, so a caller still sees
/// that freeing memory may help 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_seen.fetch_add(1, Ordering::AcqRel);
return;
}
// 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),
};
}
/// Out-of-memory errors recorded so far. Read it when handling an out-of-memory fault, and
/// pass it to [`clear_out_of_memory`](Self::clear_out_of_memory) once memory was freed.
pub fn out_of_memory_count(&self) -> u64 {
self.0.out_of_memory_seen.load(Ordering::Acquire)
}
/// Clear the out-of-memory errors up to `count` (from
/// [`out_of_memory_count`](Self::out_of_memory_count)) after the caller freed memory. One
/// recorded after `count` was read stays. The device counts as healthy again unless it was
/// lost or another error was recorded, which [`fault`](Self::fault) then reports.
pub fn clear_out_of_memory(&self, count: u64) {
let count = count.min(self.0.out_of_memory_seen.load(Ordering::Acquire));
self.0.out_of_memory_cleared.fetch_max(count, Ordering::AcqRel);
}
/// Whether an out-of-memory error is recorded and not cleared.
fn out_of_memory(&self) -> bool {
let cleared = self.0.out_of_memory_cleared.load(Ordering::Acquire);
self.0.out_of_memory_seen.load(Ordering::Acquire) > cleared
}
/// Whether the device may still be used: no fault was recorded, or only out-of-memory errors
/// that [`clear_out_of_memory`](Self::clear_out_of_memory) cleared.
pub fn is_ok(&self) -> bool {
self.0.lost.get().is_none() && self.0.error.get().is_none() && !self.out_of_memory()
}
/// Whether polls and waits still run: the device was not lost and reported no error other
/// than out of memory. A poll reclaims the staging memory that recovering from an
/// out-of-memory error needs.
fn pollable(&self) -> bool {
self.0.lost.get().is_none() && self.0.error.get().is_none()
}
/// Why the device cannot be used, if it cannot.
pub fn fault(&self) -> Option<Fault> {
if let Some(text) = self.0.lost.get() {
return Some(Fault::Lost(text.clone()));
}
if self.out_of_memory() {
return Some(Fault::Error(OUT_OF_MEMORY.into()));
}
self.0.error.get().map(|text| Fault::Error(text.clone()))
}
/// The device loss in the form of `craft_gpu::GpuContext::device_status`:
/// [`GpuFault::DeviceLost`](craft_gpu::GpuFault::DeviceLost) once a loss is recorded,
/// otherwise `Ok`. Other errors are reported by [`fault`](Self::fault). wgpu keeps one
/// device-lost callback per device, so a `craft-gpu` context on a device that
/// [`watch`](Self::watch) watches reads the loss here instead of setting its own callback.
pub fn device_status(&self) -> Result<(), craft_gpu::GpuFault> {
match self.0.lost.get() {
Some(text) => Err(craft_gpu::GpuFault::DeviceLost(text.clone())),
None => Ok(()),
}
}
/// 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.mark(Fault::Lost("the device stopped responding".into()));
self.0.device_lost.store(true, Ordering::Release);
}
/// Block until the work up to `index` finished, unless the device was lost or reported an
/// error other than out of memory. To wait for everything submitted so far, pass the index of
/// an empty submission (`queue.submit([])`); work submitted after it does not extend the
/// wait. Returns whether the work finished with the device still usable: `false` when it was
/// lost or reported such an error, before or during the wait, and when the poll itself
/// failed, so the work may still be running. After an out-of-memory error the wait still
/// runs. The wait has no deadline, but it polls in slices of at most 100 ms, so a loss or an
/// error other than out of memory that another clone records while the work has not finished
/// ends it after the current slice. 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: wgpu::SubmissionIndex) -> bool {
const SLICE: Duration = Duration::from_millis(100);
self.wait_unbounded(|| {
let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(SLICE) })
}));
match poll {
Ok(Ok(_)) => SlicePoll::Done,
Ok(Err(wgpu::PollError::Timeout)) => SlicePoll::Pending,
Ok(Err(e)) => {
log::warn!("wgpu poll: {e}");
SlicePoll::Failed
}
Err(_) => {
self.lost_by_poll();
SlicePoll::Failed
}
}
})
}
/// [`Self::wait`]'s loop: `poll` runs one slice and reports what wgpu returned. The loop ends
/// when a slice finished or failed, and before the next slice once a clone of this flag
/// recorded a loss or an error other than out of memory.
#[cfg(not(target_arch = "wasm32"))]
fn wait_unbounded(&self, mut poll: impl FnMut() -> SlicePoll) -> bool {
loop {
if !self.pollable() {
return false;
}
match poll() {
SlicePoll::Done => return self.pollable(),
SlicePoll::Pending => {}
SlicePoll::Failed => return false,
}
}
}
/// Non-blocking poll (reclaims staging memory), skipped once the device was lost or reported
/// an error other than out of memory.
pub fn poll(&self, device: &wgpu::Device) {
if !self.pollable() {
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 work up to `index` finished within
/// `timeout`. To wait for everything submitted so far, pass the index of an empty submission
/// (`queue.submit([])`); work submitted after it does not extend the wait. 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 lost, or that reported an error other than out of
/// memory, returns `false` unchanged.
#[cfg(not(target_arch = "wasm32"))]
pub fn wait_timeout(&self, device: &wgpu::Device, index: 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. Every slice waits for the same `index`. 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. A loss or an error other than out of memory that
/// another clone records during the wait ends it after the current slice, with
/// [`WaitOutcome::TimedOut`]. wgpu reads the fence again after a slice's own timeout, so work
/// that finishes in that gap, just after the deadline, is [`WaitOutcome::Finished`].
#[cfg(not(target_arch = "wasm32"))]
pub fn wait_timeout_cancelable(
&self,
device: &wgpu::Device,
index: wgpu::SubmissionIndex,
timeout: Duration,
canceled: &(dyn Fn() -> bool + Sync),
) -> WaitOutcome {
if !self.pollable() {
return WaitOutcome::TimedOut;
}
let mut wrong_index = false;
let mut polled = false;
let start = Instant::now();
let elapsed = || start.elapsed();
let outcome = wait_slices(timeout, canceled, elapsed, |slice| {
polled = true;
let poll = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
device.poll(wgpu::PollType::Wait { submission_index: Some(index.clone()), timeout: Some(slice) })
}));
match poll {
Ok(Ok(_)) => self.after_slice(true),
Ok(Err(wgpu::PollError::Timeout)) => self.after_slice(false),
// 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.pollable() {
self.mark(Fault::Lost(format!("GPU wait timed out after {:.1} s", timeout.as_secs_f64())));
}
outcome
}
/// What a slice that returned reports, `finished` or not: failed once a clone of this flag
/// recorded a loss or an error other than out of memory, so the next slice does not poll a
/// device that is not to be used.
#[cfg(not(target_arch = "wasm32"))]
fn after_slice(&self, finished: bool) -> SlicePoll {
if !self.pollable() {
SlicePoll::Failed
} else if finished {
SlicePoll::Done
} else {
SlicePoll::Pending
}
}
}
/// 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. `elapsed` gives the time since the wait started. 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 elapsed: impl FnMut() -> Duration,
mut poll: impl FnMut(Duration) -> SlicePoll,
) -> WaitOutcome {
const SLICE: Duration = Duration::from_millis(100);
loop {
if canceled() {
return WaitOutcome::Canceled;
}
let remaining = total.saturating_sub(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 whole message of wgpu's `DeviceError::Lost`.
const LOST_CAUSE: &str = "Parent device is lost";
/// Whether one of the errors that caused `e` (its `source` chain) is wgpu's `DeviceError::Lost`:
/// an error whose whole message is [`LOST_CAUSE`]. A resource label is part of another error's
/// message, so a label never matches.
fn caused_by_loss(e: &wgpu::Error) -> bool {
let source: &(dyn std::error::Error + 'static) = match e {
wgpu::Error::Validation { source, .. } | wgpu::Error::Internal { source, .. } => source.as_ref(),
_ => return false,
};
std::iter::successors(Some(source), |c| c.source()).any(|c| c.to_string().trim().eq_ignore_ascii_case(LOST_CAUSE))
}
/// The fault a wgpu error stands for. An error caused by a lost device ([`caused_by_loss`])
/// 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`]. The text keeps the causes
/// ([`one_line`]).
fn fault_of(e: &wgpu::Error) -> Fault {
let text = e.to_string();
if matches!(e, wgpu::Error::OutOfMemory { .. }) {
Fault::Error(OUT_OF_MEMORY.into())
} else if caused_by_loss(e) {
Fault::Lost(one_line(&text))
} else {
Fault::Error(one_line(&text))
}
}
/// wgpu's multi-line error text on one line: the heading and each cause, joined with ": ",
/// without wgpu's "Caused by:" line, cut to 200 characters.
fn one_line(s: &str) -> String {
const MAX: usize = 200;
let mut out = String::new();
let mut count = 0;
let lines = s.lines().map(str::trim).filter(|l| !l.is_empty() && !l.eq_ignore_ascii_case("Caused by:"));
for (i, line) in lines.enumerate() {
let separator = if i == 0 { "" } else { ": " };
for c in separator.chars().chain(line.chars()) {
if count == MAX {
out.push('…');
return out;
}
out.push(c);
count += 1;
}
}
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]
fn faults_in_the_craft_gpu_form() {
use craft_gpu::GpuFault;
let h = DeviceHealth::new();
assert_eq!(h.device_status(), Ok(()));
// an error, out of memory included, is not a loss
h.mark(Fault::Error(OUT_OF_MEMORY.into()));
h.mark(Fault::Error("Validation Error".into()));
assert_eq!(h.device_status(), Ok(()));
h.mark(Fault::Lost("reset".into()));
assert_eq!(h.device_status(), Err(GpuFault::DeviceLost("reset".into())));
assert_eq!(GpuFault::from(Fault::Lost("reset".into())), GpuFault::DeviceLost("reset".into()));
assert_eq!(GpuFault::from(Fault::Error(OUT_OF_MEMORY.into())), GpuFault::Operation(OUT_OF_MEMORY.into()));
assert_eq!(h.fault().map(GpuFault::from), Some(GpuFault::DeviceLost("reset".into())));
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn wait_slices_cancel_timeout_and_completion() {
let never = || false;
// a clock that does not move: only the polls end these waits
let still = || Duration::ZERO;
assert_eq!(wait_slices(Duration::ZERO, &never, still, |_| SlicePoll::Done), WaitOutcome::TimedOut);
assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Done), WaitOutcome::Finished);
assert_eq!(wait_slices(Duration::from_secs(1), &never, still, |_| SlicePoll::Failed), WaitOutcome::TimedOut);
let mut polls = 0;
let outcome = wait_slices(Duration::from_secs(1), &never, still, |_| {
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, still, |_| {
called = true;
SlicePoll::Done
}),
WaitOutcome::Canceled
);
assert!(!called, "cancellation is checked before polling");
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn wait_slices_end_at_the_deadline_of_a_moving_clock() {
let never = || false;
let now = std::cell::Cell::new(Duration::ZERO);
let mut slices = Vec::new();
let clock = || now.get();
let outcome = wait_slices(Duration::from_millis(250), &never, clock, |slice| {
slices.push(slice);
now.set(now.get() + slice);
SlicePoll::Pending
});
assert_eq!(outcome, WaitOutcome::TimedOut);
assert_eq!(slices, [Duration::from_millis(100), Duration::from_millis(100), Duration::from_millis(50)]);
}
#[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 still = || Duration::ZERO;
let outcome = wait_slices(Duration::from_secs(1), &canceled, still, |_| {
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]
#[cfg(not(target_arch = "wasm32"))]
fn a_fault_recorded_during_a_wait_stops_the_next_slice() {
let h = DeviceHealth::new();
assert_eq!(h.after_slice(false), SlicePoll::Pending);
assert_eq!(h.after_slice(true), SlicePoll::Done);
// out of memory alone: polls keep reclaiming memory
h.mark(Fault::Error(OUT_OF_MEMORY.into()));
assert_eq!(h.after_slice(false), SlicePoll::Pending);
// another clone records a validation error while a slice is pending
h.clone().mark(Fault::Error("Validation Error".into()));
assert_eq!(h.after_slice(false), SlicePoll::Failed, "the next slice must not poll");
assert_eq!(h.after_slice(true), SlicePoll::Failed);
let lost = DeviceHealth::new();
lost.clone().mark(Fault::Lost("reset".into()));
assert_eq!(lost.after_slice(false), SlicePoll::Failed);
}
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn a_fault_recorded_during_an_unbounded_wait_ends_it() {
let h = DeviceHealth::new();
let other = h.clone();
let mut polls = 0;
let finished = h.wait_unbounded(|| {
polls += 1;
if polls == 2 {
other.mark(Fault::Error("Validation Error".into()));
}
assert!(polls <= 2, "a slice ran after the fault");
SlicePoll::Pending
});
assert!(!finished);
assert_eq!(polls, 2);
// out of memory alone keeps the wait going until the work finishes
let oom = DeviceHealth::new();
oom.mark(Fault::Error(OUT_OF_MEMORY.into()));
let mut polls = 0;
assert!(oom.wait_unbounded(|| {
polls += 1;
if polls < 3 { SlicePoll::Pending } else { SlicePoll::Done }
}));
assert_eq!(polls, 3);
assert!(!DeviceHealth::new().wait_unbounded(|| SlicePoll::Failed));
}
#[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!(one_line("\n Buffer 'pc' is invalid\nmore"), "Buffer 'pc' is invalid: more");
assert_eq!(one_line(&"a".repeat(300)).chars().count(), 201);
assert_eq!(one_line(&"a".repeat(200)), "a".repeat(200));
assert_eq!(one_line(&format!("{}\nb", "a".repeat(199))), format!("{}:…", "a".repeat(199)));
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 out_of_memory_keeps_polls_running_until_cleared() {
let h = DeviceHealth::new();
h.mark(Fault::Error(OUT_OF_MEMORY.into()));
assert!(!h.is_ok());
assert!(h.pollable(), "polls reclaim the memory that recovery needs");
let seen = h.out_of_memory_count();
// one recorded while the caller freed memory is not cleared with the earlier ones
h.mark(Fault::Error(OUT_OF_MEMORY.into()));
h.clear_out_of_memory(seen);
assert!(h.fault().is_some_and(|f| f.is_out_of_memory()));
h.clear_out_of_memory(h.out_of_memory_count());
assert!(h.is_ok());
assert_eq!(h.fault(), None);
// a count larger than the ones recorded does not hide later errors
h.clear_out_of_memory(u64::MAX);
h.mark(Fault::Error(OUT_OF_MEMORY.into()));
assert!(!h.is_ok());
h.clear_out_of_memory(h.out_of_memory_count());
// an earlier error is still there once the out-of-memory error is cleared
h.mark(Fault::Error("Validation Error".into()));
assert!(!h.pollable());
h.mark(Fault::Error(OUT_OF_MEMORY.into()));
assert!(!h.pollable(), "a later out-of-memory error does not undo the earlier error");
h.clear_out_of_memory(h.out_of_memory_count());
assert_eq!(h.fault(), Some(Fault::Error("Validation Error".into())));
assert!(!h.is_ok() && !h.pollable());
let lost = DeviceHealth::new();
lost.mark(Fault::Error(OUT_OF_MEMORY.into()));
lost.mark(Fault::Lost("reset".into()));
assert!(!lost.pollable());
}
#[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())));
}
/// An error and the errors that caused it, outermost first, as wgpu-core chains them.
#[derive(Debug)]
struct Cause(&'static str, Option<Box<Cause>>);
impl fmt::Display for Cause {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.0)
}
}
impl std::error::Error for Cause {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.1.as_deref().map(|c| c as _)
}
}
/// A validation error with the causes `chain` and wgpu's description of them.
fn validation(chain: &[&'static str]) -> wgpu::Error {
let source = chain.iter().rev().fold(None, |inner, text| Some(Box::new(Cause(text, inner))));
let mut description = String::from("Validation Error\n\nCaused by:\n");
for c in chain {
description.push_str(&format!(" {c}\n"));
}
wgpu::Error::Validation { source: source.unwrap_or_else(|| Box::new(Cause("", None))), description }
}
#[test]
fn only_a_lost_device_counts_as_a_loss() {
let lost = validation(&["In Device::create_buffer", "Parent device is lost"]);
assert!(fault_of(&lost).is_lost(), "{:?}", fault_of(&lost));
let destroyed = validation(&["In Queue::submit", "Buffer 'pc' has been destroyed"]);
// the stored text names what failed, not only wgpu's heading
assert_eq!(fault_of(&destroyed), Fault::Error("Validation Error: In Queue::submit: Buffer 'pc' has been destroyed".into()));
assert_eq!(fault_of(&lost), Fault::Lost("Validation Error: In Device::create_buffer: Parent device is lost".into()));
let texture = validation(&["Texture with 'frame' label has been destroyed"]);
assert!(!fault_of(&texture).is_lost());
// a label is the caller's text, not the cause, even on a line of its own
let labeled = validation(&["In Queue::submit", "Buffer 'device is lost' has been destroyed"]);
assert_eq!(fault_of(&labeled), Fault::Error("Validation Error: In Queue::submit: Buffer 'device is lost' has been destroyed".into()));
for label in ["Buffer 'Parent device is lost' has been destroyed", "Buffer 'a\nParent device is lost\nb' has been destroyed"] {
let labeled = validation(&["In Queue::submit", label]);
assert!(!fault_of(&labeled).is_lost(), "{label:?}");
}
}
}
+43
View File
@@ -0,0 +1,43 @@
#![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; [`list_async`] and [`open_async`] are the same
//! as futures, for a `wasm32` web worker as well as native.
//! - In a browser, WebGPU offers one adapter for a power preference, so a named adapter cannot be
//! chosen, and wgpu 30 cannot ask for the browser's fallback (software) adapter. `open_async`
//! asks for the adapter with [`Preference::power`]. [`Capabilities`] and [`Recovery`] work
//! there as they do on native, and so does [`DeviceHealth`] apart from its blocking waits,
//! which are native only.
//! - [`Capabilities`] reads what the device can do (NV12 and P010 textures, 16-bit norm formats,
//! `f16`, timestamps, the vendor, a software adapter, sizes) from the `craft_gpu::DeviceCaps`
//! it holds, which [`device_caps`] and [`Opened::device_caps`] give for a `craft-gpu` context.
//! - [`DeviceHealth`] records a device loss or an uncaptured error instead of panicking, and
//! [`Recovery`] says what to open after a loss. [`DeviceHealth::device_status`] reports a loss
//! as `craft_gpu::GpuFault::DeviceLost`, and a [`Fault`] converts to a `craft_gpu::GpuFault`.
//!
//! 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, device_caps};
pub use health::{DeviceHealth, Fault, OUT_OF_MEMORY, WaitOutcome};
pub use open::{OpenError, Opened, Request, list_async, open_async, 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};
+474
View File
@@ -0,0 +1,474 @@
//! Listing adapters and opening a device, trying the next adapter when one fails.
use std::fmt;
use wgpu::{Adapter, Features, Instance, Limits, Surface};
use crate::adapter::{Candidate, avoided, log_choice};
use crate::caps::Capabilities;
use crate::health::DeviceHealth;
use crate::preference::{Notice, Preference, Selection, asked_for, ranked, select};
/// 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. Experimental features
/// (`Features::all_experimental_mask`) are left out here: the device descriptor does not
/// enable experimental features, and wgpu refuses a device that asks for one without that.
pub optional_features: Features,
/// The limits to ask for; `None` asks for the adapter's own limits. An adapter whose limits
/// are lower is skipped.
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, as the `craft_gpu::DeviceCaps` it reports.
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>,
}
impl Opened {
/// The device's [`DeviceCaps`](craft_gpu::DeviceCaps) for a `craft-gpu` context
/// ([`device_caps`](crate::device_caps)).
pub fn device_caps(&self) -> craft_gpu::DeviceCaps {
self.caps.device_caps().clone()
}
}
/// 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. [`list_async`] works
/// on both.
#[cfg(not(target_arch = "wasm32"))]
pub fn list(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec<Adapter>, Vec<Candidate>) {
pollster::block_on(list_async(instance, surface))
}
/// [`list`] as a future, for a `wasm32` web worker as well as native. In a browser, WebGPU offers
/// one adapter for a power preference, and the list holds the high-performance one, which
/// [`open_async`] opens for `Auto` and for a named adapter.
pub async fn list_async(instance: &Instance, surface: Option<&Surface<'_>>) -> (Vec<Adapter>, Vec<Candidate>) {
#[cfg(not(target_arch = "wasm32"))]
let adapters = instance.enumerate_adapters(wgpu::Backends::all()).await;
#[cfg(target_arch = "wasm32")]
let adapters = browser_adapter(instance, surface, wgpu::PowerPreference::HighPerformance).await;
let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect();
(adapters, candidates)
}
/// The adapter a browser offers for `power`, if any.
#[cfg(target_arch = "wasm32")]
async fn browser_adapter(instance: &Instance, surface: Option<&Surface<'_>>, power: wgpu::PowerPreference) -> Vec<Adapter> {
let options = wgpu::RequestAdapterOptions { power_preference: power, compatible_surface: surface, ..Default::default() };
instance.request_adapter(&options).await.into_iter().collect()
}
/// 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; that selector takes a `String` error, so convert with `map_err(|e| e.to_string())`.
/// With no usable adapter the error is [`OpenError::UnsafeDriver`] when only adapters that
/// [`choose`](crate::choose) never draws with can draw, and [`OpenError::NoAdapter`] otherwise,
/// with the listed adapters in the log.
pub fn pick(adapters: &[Adapter], surface: Option<&Surface<'_>>, preference: &Preference) -> Result<(Adapter, Selection), OpenError> {
let candidates: Vec<Candidate> = adapters.iter().map(|a| Candidate::of(a, surface)).collect();
let Some(selection) = select(&candidates, preference) else {
return Err(unselected(&candidates));
};
log_choice(&candidates, selection.index, preference.power());
for notice in &selection.notices {
log::warn!("{notice}");
}
let adapter = adapters.get(selection.index).cloned().ok_or(OpenError::NoAdapter)?;
Ok((adapter, selection))
}
/// The error for `candidates` among which `select` found no adapter, with the list in the log
/// when it is not [`OpenError::UnsafeDriver`].
fn unselected(candidates: &[Candidate]) -> OpenError {
let left_out = left_out(candidates);
if !left_out.is_empty() {
return OpenError::UnsafeDriver(left_out);
}
let listed = candidates.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ");
log::warn!("no usable graphics adapter among {}: {listed}", candidates.len());
OpenError::NoAdapter
}
/// 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`]; [`open_async`]
/// works on both.
#[cfg(not(target_arch = "wasm32"))]
pub fn open(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference, request: &Request<'_>) -> Result<Opened, OpenError> {
pollster::block_on(open_async(instance, surface, preference, request))
}
/// [`open`] as a future, for a `wasm32` web worker as well as native. On native it lists every
/// adapter, as `open` does. In a browser, WebGPU offers one adapter for a power preference, so
/// `open_async` asks for the adapter with [`Preference::power`]. A named adapter then gives the
/// automatic choice with [`Notice::AdapterMissing`]. wgpu 30 does not pass the fallback-adapter
/// option to the browser, so [`Preference::Software`] gives the browser's adapter with
/// [`Notice::NoSoftwareAdapter`] unless that adapter is itself a software one.
pub async fn open_async(
instance: &Instance,
surface: Option<&Surface<'_>>,
preference: &Preference,
request: &Request<'_>,
) -> Result<Opened, OpenError> {
let (adapters, candidates) = adapters_for(instance, surface, preference).await;
// 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: Vec<&Candidate> = Vec::new();
for index in order {
let (Some(adapter), Some(candidate)) = (adapters.get(index), candidates.get(index)) else {
continue;
};
tried.push(candidate);
match open_on(adapter, request).await {
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 });
}
}
}
// wgpu's fallback adapter, unless the loop above already tried it. In a browser the request
// below would ask for the same adapter again.
if cfg!(not(target_arch = "wasm32")) {
let options = wgpu::RequestAdapterOptions { force_fallback_adapter: true, compatible_surface: surface, ..Default::default() };
let fallback = instance.request_adapter(&options).await.ok().map(|a| (Candidate::of(&a, surface), a));
if let Some((candidate, adapter)) = fallback.filter(|(c, _)| !tried.contains(&c)) {
match open_on(&adapter, request).await {
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()
}
/// The adapters `open_async` chooses among: every listed one on native, and in a browser the one
/// it offers for the preference's power.
async fn adapters_for(instance: &Instance, surface: Option<&Surface<'_>>, preference: &Preference) -> (Vec<Adapter>, Vec<Candidate>) {
#[cfg(not(target_arch = "wasm32"))]
{
let _ = preference;
list_async(instance, surface).await
}
#[cfg(target_arch = "wasm32")]
{
let adapters = browser_adapter(instance, surface, preference.power()).await;
let candidates = adapters.iter().map(|a| Candidate::of(a, surface)).collect();
(adapters, candidates)
}
}
fn finish(
adapter: Adapter,
device: wgpu::Device,
queue: wgpu::Queue,
candidate: Candidate,
preference: &Preference,
mut notices: Vec<Notice>,
) -> Opened {
let caps = Capabilities::of_device(&device);
// wgpu's fallback adapter can be a software one that the listing did not show.
if candidate.is_software() {
notices.retain(|n| *n != Notice::NoSoftwareAdapter);
}
if candidate.is_software() && !asked_for(preference, &candidate) {
notices.push(Notice::SoftwareOnly);
}
for notice in &notices {
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.
async 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 & !Features::all_experimental_mask()),
required_limits,
..Default::default()
};
adapter.request_device(&desc).await.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());
// the craft-gpu caps name only the features the device was opened with
let caps = opened.device_caps();
assert_eq!(caps.features, ["TEXTURE_FORMAT_NV12"]);
assert_eq!(&caps, opened.caps.device_caps());
assert_eq!(caps, crate::device_caps(&opened.device));
assert_eq!(caps.max_texture_dimension_2d, opened.device.limits().max_texture_dimension_2d);
assert!(caps.software && caps.vendor_id == opened.candidate.vendor, "{caps:?}");
assert_eq!(opened.health.device_status(), Ok(()));
}
#[test]
fn open_async_opens_as_open_does() {
let instance = noop(Some(Features::TEXTURE_FORMAT_P010));
let request = Request { optional_features: Features::TEXTURE_FORMAT_P010 | Features::SHADER_F16, ..Default::default() };
let opened = pollster::block_on(open_async(&instance, None, &Preference::Auto, &request)).unwrap();
let blocking = open(&instance, None, &Preference::Auto, &request).unwrap();
assert!(opened.caps.p010() && !opened.caps.shader_f16(), "{}", opened.caps);
assert_eq!(opened.caps, blocking.caps);
assert_eq!(opened.notices, vec![Notice::SoftwareOnly]);
assert_eq!(opened.notices, blocking.notices);
let (adapters, candidates) = pollster::block_on(list_async(&instance, None));
assert_eq!((adapters.len(), candidates), (1, list(&instance, None).1));
// the same errors
let missing = Request { required_features: Features::SHADER_F16, ..Default::default() };
let err = pollster::block_on(open_async(&instance, None, &Preference::Auto, &missing)).unwrap_err();
assert!(matches!(&err, OpenError::NoDevice(n) if n.len() == 1), "{err}");
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
desc.backends = wgpu::Backends::NOOP;
let none = Instance::new(desc);
assert_eq!(pollster::block_on(open_async(&none, None, &Preference::Auto, &Request::default())).unwrap_err(), OpenError::NoAdapter);
}
#[test]
fn a_software_device_drops_the_no_software_notice() {
let instance = noop(None);
let opened = open(&instance, None, &Preference::Software, &Request::default()).unwrap();
assert!(opened.candidate.is_software());
// as when the listing showed no software adapter and wgpu's fallback adapter opened
let notices = vec![Notice::NoSoftwareAdapter];
let again = finish(opened.adapter, opened.device, opened.queue, opened.candidate, &Preference::Software, notices);
assert!(again.notices.is_empty(), "{:?}", again.notices);
}
#[test]
fn an_optional_experimental_feature_does_not_stop_the_device_opening() {
let instance = noop(Some(Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12));
let request = Request { optional_features: Features::EXPERIMENTAL_RAY_QUERY | Features::TEXTURE_FORMAT_NV12, ..Default::default() };
let opened = open(&instance, None, &Preference::Software, &request).unwrap();
assert!(opened.caps.nv12(), "{}", opened.caps);
assert!(!opened.device.features().contains(Features::EXPERIMENTAL_RAY_QUERY));
// a required one still fails as before
let required = Request { required_features: Features::EXPERIMENTAL_RAY_QUERY, ..Default::default() };
assert!(matches!(open(&instance, None, &Preference::Software, &required), Err(OpenError::NoDevice(_))));
}
#[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 an_adapter_below_the_requested_limits_is_reported() {
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
desc.backends = wgpu::Backends::NOOP;
desc.backend_options.noop = wgpu::NoopBackendOptions { enable: true, limits: Some(Limits::default()), ..Default::default() };
let instance = Instance::new(desc);
let over = Limits::default().max_texture_dimension_2d + 1;
let request = Request { limits: Some(Limits { max_texture_dimension_2d: over, ..Limits::default() }), ..Default::default() };
let err = open(&instance, None, &Preference::Software, &request).unwrap_err();
let OpenError::NoDevice(notices) = &err else { panic!("{err}") };
assert!(
notices.iter().any(|n| matches!(n, Notice::DeviceFailed { error, .. }
if error.contains("max_texture_dimension_2d"))),
"{notices:?}"
);
// limits within the adapter's still open
let within = Request { limits: Some(Limits::downlevel_defaults()), ..Default::default() };
assert!(open(&instance, None, &Preference::Software, &within).is_ok());
}
#[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_eq!(pick(&[], None, &Preference::Auto).unwrap_err(), OpenError::NoAdapter);
}
#[test]
fn pick_says_when_only_a_driver_that_can_crash_can_draw() {
let vulkan_only: Vec<Candidate> = crate::adapter::tests::uhd_630().into_iter().take(1).collect();
assert_eq!(select(&vulkan_only, &Preference::Auto), None);
assert_eq!(unselected(&vulkan_only), OpenError::UnsafeDriver(vec!["Intel(R) UHD Graphics 630".into()]));
assert_eq!(unselected(&[]), OpenError::NoAdapter);
}
#[test]
fn a_zero_timeout_leaves_a_healthy_device_healthy() {
let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap();
let everything = opened.queue.submit([]);
assert!(!opened.health.wait_timeout(&opened.device, everything.clone(), std::time::Duration::ZERO));
assert!(opened.health.is_ok(), "{:?}", opened.health.fault());
assert!(opened.health.wait_timeout(&opened.device, everything, 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, index, std::time::Duration::from_secs(5)));
assert!(opened.health.is_ok(), "{:?}", opened.health.fault());
}
#[test]
fn waits_run_after_an_out_of_memory_error() {
use crate::health::{Fault, OUT_OF_MEMORY};
let opened = open(&noop(None), None, &Preference::Software, &Request::default()).unwrap();
let health = opened.health.clone();
health.mark(Fault::Error(OUT_OF_MEMORY.into()));
let index = opened.queue.submit([]);
assert!(health.wait(&opened.device, index.clone()), "{health:?}");
assert!(health.wait_timeout(&opened.device, index.clone(), std::time::Duration::from_secs(5)), "{health:?}");
health.clear_out_of_memory(health.out_of_memory_count());
assert!(health.is_ok(), "{health:?}");
// any other error still stops them
health.mark(Fault::Error("Validation Error".into()));
assert!(!health.wait(&opened.device, index));
}
#[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();
let index = opened.queue.submit([]);
opened.device.destroy();
health.probe(&opened.device);
assert!(health.fault().is_some_and(|f| f.is_lost()), "{health:?}");
assert!(!health.is_ok());
assert!(matches!(health.device_status(), Err(craft_gpu::GpuFault::DeviceLost(_))), "{health:?}");
// a later wait does not touch the lost device
assert!(!health.wait(&opened.device, index));
}
#[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]);
}
}
+422
View File
@@ -0,0 +1,422 @@
//! 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, intel_vulkan_crashes, settled, 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, with [`choose`]'s
/// corrections; 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)));
let found = found.and_then(|(index, _)| drawn_with(candidates, index));
if found.is_none() {
notices.push(Notice::AdapterMissing(key.clone()));
}
found
}
Preference::Software => {
let found = candidates.iter().position(|c| c.usable && c.is_software()).and_then(|index| drawn_with(candidates, index));
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 })
}
/// The entry to draw with when the entry at `index` is asked for, with [`choose`]'s corrections:
/// the newest version of a driver that lists the GPU twice, or the DirectX 12 entry of an Intel
/// GPU whose Vulkan entry [`choose`] never draws with. `None` when that Intel Vulkan entry has no
/// usable DirectX 12 entry.
fn drawn_with(candidates: &[Candidate], index: usize) -> Option<usize> {
candidates.get(index)?;
let index = settled(candidates, index);
(!candidates.get(index).is_some_and(intel_vulkan_crashes)).then_some(index)
}
/// Whether `preference` asked for `candidate` itself: software for a software adapter, or the key
/// of this adapter.
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 software_draws_with_the_newer_version_of_a_driver_listed_twice() {
let stale = gpu("llvmpipe (LLVM 15.0.7, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 23.0.4", 40);
let newer = gpu("llvmpipe (LLVM 19.1.0, 256 bits)", Vulkan, Cpu, 0x10005, 0, "", "llvmpipe", "Mesa 25.2.4", 50);
let hardware = gpu("AMD Radeon RX 6800M", Dx12, DiscreteGpu, 0x1002, 0x73df, "0000:03:00.0", "32.0.21045.11001", "", 36);
let adapters = vec![stale, newer, hardware];
assert_eq!(select(&adapters, &Preference::Software), Some(Selection { index: 1, notices: vec![] }));
// the stale entry is never tried, and the newer one is not left out
assert_eq!(ranked(&adapters, &Preference::Software), vec![1, 2]);
}
#[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());
}
}
+153
View File
@@ -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);
}
}
+4
View File
@@ -46,6 +46,8 @@ fn probe_caps_native() -> DeviceCaps {
max_buffer_size: limits.max_buffer_size,
max_texture_dimension_2d: limits.max_texture_dimension_2d,
features: Vec::new(),
vendor_id: info.vendor,
software: info.device_type == wgpu::DeviceType::Cpu,
}
}
@@ -144,6 +146,8 @@ mod native {
max_buffer_size: device_limits.max_buffer_size,
max_texture_dimension_2d: device_limits.max_texture_dimension_2d,
features: device.features().iter_names().map(|(name, _)| name.to_string()).collect(),
vendor_id: info.vendor,
software: info.device_type == wgpu::DeviceType::Cpu,
};
let backing = Backing::Device(DeviceBacking { device, queue, buffers: Vec::new(), lost, pending: Vec::new() });
Some((caps, backing))
+16
View File
@@ -20,6 +20,20 @@ pub struct DeviceCaps {
/// never on what the adapter merely advertised.
#[serde(default)]
pub features: Vec<String>,
/// The PCI vendor id of the device's adapter (or the Khronos vendor id some Vulkan drivers
/// report instead); 0 when unknown or on backends with no device.
#[serde(default)]
pub vendor_id: u32,
/// The device draws on the CPU (a software adapter such as WARP, llvmpipe or lavapipe).
#[serde(default)]
pub software: bool,
}
impl DeviceCaps {
/// Whether the feature named `name` (as in [`features`](Self::features)) is enabled.
pub fn has_feature(&self, name: &str) -> bool {
self.features.iter().any(|f| f == name)
}
}
impl Default for DeviceCaps {
@@ -31,6 +45,8 @@ impl Default for DeviceCaps {
max_buffer_size: 256 * 1024 * 1024,
max_texture_dimension_2d: 8192,
features: Vec::new(),
vendor_id: 0,
software: false,
}
}
}
+12
View File
@@ -126,3 +126,15 @@ fn chunk_buffer_splits_on_storage_binding_limit() {
let chunks = chunk_buffer(&caps, b"abcdef").expect("chunk_buffer");
assert_eq!(chunks, vec![&b"abcd"[..], &b"ef"[..]]);
}
#[test]
fn caps_without_vendor_or_software_read_as_unknown_hardware() {
let json = r#"{"backend_name":"Vulkan","device_name":"gpu","max_storage_buffer_binding_size":1,"max_buffer_size":2,"max_texture_dimension_2d":3,"features":["TEXTURE_FORMAT_NV12"]}"#;
let caps: DeviceCaps = serde_json::from_str(json).expect("caps");
assert_eq!((caps.vendor_id, caps.software), (0, false));
assert!(caps.has_feature("TEXTURE_FORMAT_NV12"));
assert!(!caps.has_feature("TEXTURE_FORMAT_P010") && !caps.has_feature(""));
let software = DeviceCaps { vendor_id: 0x10005, software: true, ..caps };
let back: DeviceCaps = serde_json::from_str(&serde_json::to_string(&software).expect("json")).expect("caps");
assert_eq!(back, software);
}