Skip to main content

molgfx_gpu/
device.rs

1//! The device trait: the root of the hardware abstraction.
2//!
3//! `Device` carries every backend resource as an associated type, so the
4//! renderer is generic over it and pays no dynamic dispatch on the hot path.
5//! Behavior traits (`Queue`, `CommandEncoder`, `Surface`) take the device as
6//! a type parameter to name those resource types in their signatures.
7
8use crate::capabilities::Capabilities;
9use crate::descriptors::{
10    BindGroupDesc, BindGroupLayoutDesc, BufferDesc, ComputePipelineDesc, RenderPipelineDesc,
11    SamplerDesc, ShaderModuleDesc, TextureDesc, TextureViewDesc,
12};
13use crate::encoder::CommandEncoder;
14use crate::error::GpuError;
15use crate::queue::Queue;
16use crate::surface::Surface;
17use crate::{
18    BlasDesc, RayQueryBindGroupDesc, RayQueryBindGroupLayoutDesc, RayQueryLimits, TlasDesc,
19    TlasInstance,
20};
21use raw_window_handle::{HasDisplayHandle, HasWindowHandle};
22use std::future::Future;
23#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
24use std::sync::Arc;
25
26/// Anything a presentation surface can be created from. Embedders hand the
27/// engine their window behind this trait; the engine never names a
28/// windowing toolkit.
29///
30/// Native window handles may cross worker threads. Browser canvas handles are
31/// bound to the JavaScript main thread, so requiring `Send + Sync` there would
32/// reject the platform's real WebGPU resources.
33#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
34pub trait WindowSource: HasWindowHandle + HasDisplayHandle + std::fmt::Debug + Send + Sync {}
35#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
36impl<T: HasWindowHandle + HasDisplayHandle + std::fmt::Debug + Send + Sync> WindowSource for T {}
37
38/// Browser presentation source, intentionally confined to the JavaScript
39/// thread that owns its canvas.
40#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
41pub trait WindowSource: HasWindowHandle + HasDisplayHandle + std::fmt::Debug {}
42#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
43impl<T: HasWindowHandle + HasDisplayHandle + std::fmt::Debug> WindowSource for T {}
44
45/// A shared native window handle, alive for as long as its surface.
46#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
47pub type WindowTarget = Arc<dyn WindowSource>;
48
49/// A browser canvas supplied and owned by the host page.
50#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
51pub type WindowTarget = web_sys::HtmlCanvasElement;
52
53/// Which adapter class to prefer when several are present.
54#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
55pub enum PowerPreference {
56    /// The fastest available adapter; the default for a rendering engine.
57    #[default]
58    HighPerformance,
59    /// The most efficient adapter.
60    LowPower,
61}
62
63/// Options for opening a device.
64#[derive(Clone, Copy, Debug, Default)]
65pub struct DeviceDesc {
66    /// Adapter preference.
67    pub power: PowerPreference,
68    /// Optional hard ceiling for live buffer and texture bytes owned by the device.
69    pub resource_memory_limit_bytes: Option<u64>,
70}
71
72/// Live physical resources allocated through a device.
73#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
74pub struct ResourceMemory {
75    /// Live buffer bytes.
76    pub buffer_bytes: u64,
77    /// Live texture bytes, including all layers.
78    pub texture_bytes: u64,
79    /// Highest live total observed since device creation.
80    pub peak_bytes: u64,
81}
82
83impl ResourceMemory {
84    /// Current accounted device bytes.
85    #[must_use]
86    pub const fn total_bytes(self) -> u64 {
87        self.buffer_bytes.saturating_add(self.texture_bytes)
88    }
89}
90
91/// The result of opening a device: the device, its queue, and a surface
92/// when a window was supplied.
93#[derive(Debug)]
94pub struct Opened<D: Device> {
95    /// The device.
96    pub device: D,
97    /// Its submission queue.
98    pub queue: D::Queue,
99    /// The presentation surface, when opened against a window.
100    pub surface: Option<D::Surface>,
101}
102
103/// A GPU device: resource creation and capability report.
104///
105/// Everything created here is created at load and reused; the trait offers
106/// no per-frame conveniences by design.
107pub trait Device: Sized + 'static {
108    /// GPU buffer.
109    type Buffer: std::fmt::Debug;
110    /// GPU texture.
111    type Texture: std::fmt::Debug;
112    /// View over a texture, bindable or attachable.
113    type TextureView: std::fmt::Debug;
114    /// Texture sampler.
115    type Sampler: std::fmt::Debug;
116    /// Compiled shader module.
117    type ShaderModule: std::fmt::Debug;
118    /// Bind-group layout.
119    type BindGroupLayout: std::fmt::Debug;
120    /// Bind group.
121    type BindGroup: std::fmt::Debug;
122    /// Render or compute pipeline.
123    type Pipeline: std::fmt::Debug;
124    /// Timestamp or occlusion query storage.
125    type QuerySet: std::fmt::Debug;
126    /// Bottom-level acceleration structure. Portable devices may use a
127    /// zero-sized placeholder and return a capability error from every
128    /// ray-query operation.
129    type Blas: std::fmt::Debug;
130    /// Top-level acceleration structure. Portable devices may use a
131    /// zero-sized placeholder and return a capability error from every
132    /// ray-query operation.
133    type Tlas: std::fmt::Debug;
134    /// Command encoder.
135    type CommandEncoder: CommandEncoder<Self>;
136    /// Submission queue.
137    type Queue: Queue<Self>;
138    /// Presentation surface.
139    type Surface: Surface<Self>;
140
141    /// Selects an adapter and asynchronously opens a device, with a surface
142    /// when a window is supplied.
143    ///
144    /// # Errors
145    ///
146    /// No compatible adapter, or device creation failed.
147    fn open_async(
148        desc: &DeviceDesc,
149        window: Option<WindowTarget>,
150    ) -> impl Future<Output = Result<Opened<Self>, GpuError>>;
151
152    /// Native convenience for callers that do not already run an async
153    /// executor. Browser builds expose only asynchronous device opening.
154    ///
155    /// # Errors
156    ///
157    /// No compatible adapter, or device creation failed.
158    #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
159    fn open_blocking(
160        desc: &DeviceDesc,
161        window: Option<WindowTarget>,
162    ) -> Result<Opened<Self>, GpuError>;
163
164    /// Creates a buffer.
165    ///
166    /// # Errors
167    ///
168    /// The buffer exceeded device limits.
169    fn create_buffer(&self, desc: &BufferDesc) -> Result<Self::Buffer, GpuError>;
170
171    /// Creates a 2-D texture.
172    ///
173    /// # Errors
174    ///
175    /// The texture exceeded device limits.
176    fn create_texture(&self, desc: &TextureDesc) -> Result<Self::Texture, GpuError>;
177
178    /// Creates a view over a texture.
179    fn create_texture_view(
180        &self,
181        texture: &Self::Texture,
182        desc: &TextureViewDesc,
183    ) -> Self::TextureView;
184
185    /// Creates a sampler.
186    fn create_sampler(&self, desc: &SamplerDesc) -> Self::Sampler;
187
188    /// Compiles a WGSL shader module.
189    ///
190    /// # Errors
191    ///
192    /// Compilation failed; the error carries the backend's detail.
193    fn create_shader_module(
194        &self,
195        desc: &ShaderModuleDesc<'_>,
196    ) -> Result<Self::ShaderModule, GpuError>;
197
198    /// Creates a bind-group layout.
199    fn create_bind_group_layout(&self, desc: &BindGroupLayoutDesc<'_>) -> Self::BindGroupLayout;
200
201    /// Creates a bind group over a layout.
202    fn create_bind_group(&self, desc: &BindGroupDesc<'_, Self>) -> Self::BindGroup;
203
204    /// Creates a render pipeline. Created at load, cached by the caller.
205    ///
206    /// # Errors
207    ///
208    /// Pipeline creation failed (most often shader/interface mismatch).
209    fn create_render_pipeline(
210        &self,
211        desc: &RenderPipelineDesc<'_, Self>,
212    ) -> Result<Self::Pipeline, GpuError>;
213
214    /// Creates a compute pipeline.
215    ///
216    /// # Errors
217    ///
218    /// Pipeline creation failed.
219    fn create_compute_pipeline(
220        &self,
221        desc: &ComputePipelineDesc<'_, Self>,
222    ) -> Result<Self::Pipeline, GpuError>;
223
224    /// Creates a command encoder for one frame or task.
225    fn create_command_encoder(&self) -> Self::CommandEncoder;
226
227    /// Creates a timestamp query set when the capability is available.
228    ///
229    /// # Errors
230    ///
231    /// Returns a capability error when timestamp queries are unavailable.
232    fn create_timestamp_query_set(&self, count: u32) -> Result<Self::QuerySet, GpuError>;
233
234    /// The opened device's capability report.
235    fn capabilities(&self) -> &Capabilities;
236
237    /// Reports asynchronous backend failures observed since the last check.
238    ///
239    /// # Errors
240    ///
241    /// Returns the first pending runtime diagnostic or a sticky device loss.
242    fn check_errors(&self) -> Result<(), GpuError> {
243        Ok(())
244    }
245
246    /// Returns live physical resource accounting when the backend supports it.
247    fn resource_memory(&self) -> ResourceMemory {
248        ResourceMemory::default()
249    }
250
251    /// Returns negotiated acceleration-structure ceilings.
252    ///
253    /// # Errors
254    ///
255    /// Returns a capability error when ray queries were not negotiated.
256    fn ray_query_limits(&self) -> Result<RayQueryLimits, GpuError> {
257        Err(GpuError::Capability { name: "ray query" })
258    }
259
260    /// Allocates a BLAS with fixed geometry ceilings.
261    ///
262    /// # Errors
263    ///
264    /// Returns capability, size or backend allocation failures.
265    fn create_blas(&self, _desc: &BlasDesc<'_>) -> Result<Self::Blas, GpuError> {
266        Err(GpuError::Capability { name: "ray query" })
267    }
268
269    /// Allocates a TLAS with a fixed instance ceiling.
270    ///
271    /// # Errors
272    ///
273    /// Returns capability, size or backend allocation failures.
274    fn create_tlas(&self, _desc: &TlasDesc) -> Result<Self::Tlas, GpuError> {
275        Err(GpuError::Capability { name: "ray query" })
276    }
277
278    /// Replaces or clears one TLAS instance.
279    ///
280    /// # Errors
281    ///
282    /// Returns a capability error or an out-of-range instance failure.
283    fn set_tlas_instance(
284        &self,
285        _tlas: &mut Self::Tlas,
286        _index: u32,
287        _instance: Option<TlasInstance<'_, Self>>,
288    ) -> Result<(), GpuError> {
289        Err(GpuError::Capability { name: "ray query" })
290    }
291
292    /// Creates a layout containing acceleration-structure slots.
293    ///
294    /// # Errors
295    ///
296    /// Returns a capability or backend layout failure.
297    fn create_ray_query_bind_group_layout(
298        &self,
299        _desc: &RayQueryBindGroupLayoutDesc<'_>,
300    ) -> Result<Self::BindGroupLayout, GpuError> {
301        Err(GpuError::Capability { name: "ray query" })
302    }
303
304    /// Creates a bind group containing TLAS resources.
305    ///
306    /// # Errors
307    ///
308    /// Returns a capability or backend binding failure.
309    fn create_ray_query_bind_group(
310        &self,
311        _desc: &RayQueryBindGroupDesc<'_, Self>,
312    ) -> Result<Self::BindGroup, GpuError> {
313        Err(GpuError::Capability { name: "ray query" })
314    }
315}
316
317/// Device extension for hardware acceleration structures and WGSL ray queries.
318///
319/// Implementations must return [`GpuError::Capability`] when the opened device
320/// did not negotiate the ray-query feature. Keeping this separate from
321/// [`Device`] lets portable mocks and browser-only backends remain minimal.
322pub trait RayQueryDevice: Device {
323    /// Returns negotiated acceleration-structure ceilings.
324    ///
325    /// # Errors
326    ///
327    /// Returns a capability error when ray queries were not negotiated.
328    fn ray_query_limits(&self) -> Result<RayQueryLimits, GpuError> {
329        Device::ray_query_limits(self)
330    }
331
332    /// Allocates a BLAS with fixed geometry ceilings.
333    ///
334    /// # Errors
335    ///
336    /// Returns capability, size or backend allocation failures.
337    fn create_blas(&self, desc: &BlasDesc<'_>) -> Result<Self::Blas, GpuError> {
338        Device::create_blas(self, desc)
339    }
340
341    /// Allocates a TLAS with a fixed instance ceiling.
342    ///
343    /// # Errors
344    ///
345    /// Returns capability, size or backend allocation failures.
346    fn create_tlas(&self, desc: &TlasDesc) -> Result<Self::Tlas, GpuError> {
347        Device::create_tlas(self, desc)
348    }
349
350    /// Replaces or clears one TLAS instance without exposing backend types.
351    ///
352    /// # Errors
353    ///
354    /// Returns a capability error or an out-of-range instance failure.
355    fn set_tlas_instance(
356        &self,
357        tlas: &mut Self::Tlas,
358        index: u32,
359        instance: Option<TlasInstance<'_, Self>>,
360    ) -> Result<(), GpuError> {
361        Device::set_tlas_instance(self, tlas, index, instance)
362    }
363
364    /// Creates a layout containing acceleration-structure slots.
365    ///
366    /// # Errors
367    ///
368    /// Returns a capability or backend layout failure.
369    fn create_ray_query_bind_group_layout(
370        &self,
371        desc: &RayQueryBindGroupLayoutDesc<'_>,
372    ) -> Result<Self::BindGroupLayout, GpuError> {
373        Device::create_ray_query_bind_group_layout(self, desc)
374    }
375
376    /// Creates a bind group containing TLAS resources.
377    ///
378    /// # Errors
379    ///
380    /// Returns a capability or backend binding failure.
381    fn create_ray_query_bind_group(
382        &self,
383        desc: &RayQueryBindGroupDesc<'_, Self>,
384    ) -> Result<Self::BindGroup, GpuError> {
385        Device::create_ray_query_bind_group(self, desc)
386    }
387}
388
389impl<D: Device> RayQueryDevice for D {}