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 Ok(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(&wgpu::DeviceDescriptor {
90 label: None,
91 required_features,
92 ..Default::default()
93 })
94 .await
95 .map_err(GpuResourceError::DeviceRequestError)
96 .map(|(device, queue)| Self {
97 adapter,
98 device,
99 queue,
100 instance,
101 })
102 .map(|res| (res, surface)),
103 )
104 .unwrap();
105 on_result(window.id());
106 }
107 });
108 rx
109 }
110}
111
112/// Possible errors during GPU resource setup.
113#[derive(Debug)]
114pub enum GpuResourceError {
115 SurfaceCreationError(wgpu::CreateSurfaceError),
116 AdapterNotFoundError,
117 DeviceRequestError(wgpu::RequestDeviceError),
118}
119
120impl std::fmt::Display for GpuResourceError {
121 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
122 match self {
123 GpuResourceError::SurfaceCreationError(err) => {
124 write!(f, "Surface creation error: {err}")
125 }
126 GpuResourceError::AdapterNotFoundError => {
127 write!(f, "Failed to find a suitable GPU adapter")
128 }
129 GpuResourceError::DeviceRequestError(err) => write!(f, "Device request error: {err}"),
130 }
131 }
132}
133
134/// Spawns a future for execution, adapting to the target environment.
135///
136/// On WASM (`wasm32`), it uses `wasm_bindgen_futures::spawn_local` to avoid blocking
137/// the main thread. On other targets, it uses `pollster::block_on` to synchronously
138/// wait for the future to complete.
139pub fn spawn<F>(future: F)
140where
141 F: Future<Output = ()> + 'static,
142{
143 #[cfg(target_arch = "wasm32")]
144 wasm_bindgen_futures::spawn_local(future);
145 #[cfg(not(target_arch = "wasm32"))]
146 futures::executor::block_on(future)
147}