floem_renderer/gpu_resources.rs
1//! Asynchronous GPU resource acquisition for rendering with wgpu.
2//!
3//! To support WebGPU on WASM, the GPU resources need to be acquired asynchronously because
4//! the wgpu library provides only asynchronous methods for requesting adapters and devices.
5//! In WASM, blocking the main thread is not an option, as the JavaScript
6//! execution model does not support thread blocking. Consequently, we must use asynchronous
7//! execution (via `wasm_bindgen_futures`) to handle these operations.
8//!
9//! Based on a [code snippet by Luke Petherbridge](https://github.com/rust-windowing/winit/issues/3560#issuecomment-2085754164).
10
11use std::{future::Future, sync::Arc};
12
13#[cfg(feature = "crossbeam")]
14use crossbeam::channel::{bounded as sync_channel, Receiver};
15#[cfg(not(feature = "crossbeam"))]
16use std::sync::mpsc::{sync_channel, Receiver};
17use wgpu::Backends;
18
19use winit::window::{Window, WindowId};
20
21/// The acquired GPU resources needed for rendering with wgpu.
22#[derive(Debug, Clone)]
23pub struct GpuResources {
24 /// The wgpu instance
25 pub instance: wgpu::Instance,
26
27 /// The adapter that represents the GPU or a rendering backend. It provides information about
28 /// the capabilities of the hardware and is used to request a logical device (`wgpu::Device`).
29 pub adapter: wgpu::Adapter,
30
31 /// The logical device that serves as an interface to the GPU. It is responsible for creating
32 /// resources such as buffers, textures, and pipelines, and manages the execution of commands.
33 /// The `device` provides a connection to the physical hardware represented by the `adapter`.
34 pub device: wgpu::Device,
35
36 /// The command queue that manages the submission of command buffers to the GPU for execution.
37 /// It is used to send rendering and computation commands to the device. The `queue` ensures
38 /// that commands are executed in the correct order and manages synchronization.
39 pub queue: wgpu::Queue,
40}
41
42impl GpuResources {
43 /// Request GPU resources
44 ///
45 /// # Parameters
46 /// - `on_result`: Function to notify upon completion or error.
47 /// - `window`: The window to associate with the created surface.
48 pub fn request<F: Fn(WindowId) + 'static>(
49 on_result: F,
50 required_features: wgpu::Features,
51 window: Arc<dyn Window>,
52 ) -> Receiver<Result<(Self, wgpu::Surface<'static>), GpuResourceError>> {
53 let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
54 backends: Backends::from_env().unwrap_or(Backends::all()),
55 ..Default::default()
56 });
57 // Channel passing to do async out-of-band within the winit event_loop since wasm can't
58 // execute futures with a return value
59 let (tx, rx) = sync_channel(1);
60
61 spawn({
62 async move {
63 let surface = match instance.create_surface(Arc::clone(&window)) {
64 Ok(surface) => surface,
65 Err(err) => {
66 tx.send(Err(GpuResourceError::SurfaceCreationError(err)))
67 .unwrap();
68 on_result(window.id());
69 return;
70 }
71 };
72
73 let Some(adapter) = instance
74 .request_adapter(&wgpu::RequestAdapterOptions {
75 power_preference: wgpu::PowerPreference::default(),
76 compatible_surface: Some(&surface),
77 force_fallback_adapter: false,
78 })
79 .await
80 else {
81 tx.send(Err(GpuResourceError::AdapterNotFoundError))
82 .unwrap();
83 on_result(window.id());
84 return;
85 };
86
87 tx.send(
88 adapter
89 .request_device(
90 &wgpu::DeviceDescriptor {
91 label: None,
92 required_features,
93 ..Default::default()
94 },
95 None,
96 )
97 .await
98 .map_err(GpuResourceError::DeviceRequestError)
99 .map(|(device, queue)| Self {
100 adapter,
101 device,
102 queue,
103 instance,
104 })
105 .map(|res| (res, surface)),
106 )
107 .unwrap();
108 on_result(window.id());
109 }
110 });
111 rx
112 }
113}
114
115/// Possible errors during GPU resource setup.
116#[derive(Debug)]
117pub enum GpuResourceError {
118 SurfaceCreationError(wgpu::CreateSurfaceError),
119 AdapterNotFoundError,
120 DeviceRequestError(wgpu::RequestDeviceError),
121}
122
123impl std::fmt::Display for GpuResourceError {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 match self {
126 GpuResourceError::SurfaceCreationError(err) => {
127 write!(f, "Surface creation error: {err}")
128 }
129 GpuResourceError::AdapterNotFoundError => {
130 write!(f, "Failed to find a suitable GPU adapter")
131 }
132 GpuResourceError::DeviceRequestError(err) => write!(f, "Device request error: {err}"),
133 }
134 }
135}
136
137/// Spawns a future for execution, adapting to the target environment.
138///
139/// On WASM (`wasm32`), it uses `wasm_bindgen_futures::spawn_local` to avoid blocking
140/// the main thread. On other targets, it uses `pollster::block_on` to synchronously
141/// wait for the future to complete.
142pub fn spawn<F>(future: F)
143where
144 F: Future<Output = ()> + 'static,
145{
146 #[cfg(target_arch = "wasm32")]
147 wasm_bindgen_futures::spawn_local(future);
148 #[cfg(not(target_arch = "wasm32"))]
149 futures::executor::block_on(future)
150}