Skip to main content

wgpu_core/
global.rs

1use alloc::{borrow::ToOwned as _, sync::Arc};
2use core::fmt;
3
4use crate::{
5    hub::{Hub, HubReport},
6    instance::{Instance, Surface},
7    registry::{Registry, RegistryReport},
8    resource_log,
9};
10
11#[derive(Debug, PartialEq, Eq)]
12pub struct GlobalReport {
13    pub surfaces: RegistryReport,
14    pub hub: HubReport,
15}
16
17impl GlobalReport {
18    pub fn surfaces(&self) -> &RegistryReport {
19        &self.surfaces
20    }
21    pub fn hub_report(&self) -> &HubReport {
22        &self.hub
23    }
24}
25
26pub struct Global {
27    pub(crate) surfaces: Registry<Arc<Surface>>,
28    pub(crate) hub: Hub,
29    // the instance must be dropped last
30    pub instance: Instance,
31}
32
33impl Global {
34    pub fn new(
35        name: &str,
36        instance_desc: wgt::InstanceDescriptor,
37        telemetry: Option<hal::Telemetry>,
38    ) -> Self {
39        profiling::scope!("Global::new");
40        Self {
41            instance: Instance::new(name, instance_desc, telemetry),
42            surfaces: Registry::new(),
43            hub: Hub::new(),
44        }
45    }
46
47    /// # Safety
48    ///
49    /// Refer to the creation of wgpu-hal Instance for every backend.
50    pub unsafe fn from_hal_instance<A: hal::Api>(name: &str, hal_instance: A::Instance) -> Self {
51        profiling::scope!("Global::new");
52
53        Self {
54            instance: Instance::from_hal_instance::<A>(name.to_owned(), hal_instance),
55            surfaces: Registry::new(),
56            hub: Hub::new(),
57        }
58    }
59
60    /// # Safety
61    ///
62    /// - The raw instance handle returned must not be manually destroyed.
63    pub unsafe fn instance_as_hal<A: hal::Api>(&self) -> Option<&A::Instance> {
64        unsafe { self.instance.as_hal::<A>() }
65    }
66
67    /// # Safety
68    ///
69    /// - The raw handles obtained from the Instance must not be manually destroyed
70    pub unsafe fn from_instance(instance: Instance) -> Self {
71        profiling::scope!("Global::new");
72        Self {
73            instance,
74            surfaces: Registry::new(),
75            hub: Hub::new(),
76        }
77    }
78
79    pub fn generate_report(&self) -> GlobalReport {
80        GlobalReport {
81            surfaces: self.surfaces.generate_report(),
82            hub: self.hub.generate_report(),
83        }
84    }
85}
86
87/// Implement [`Send`] + [`Sync`] for [`Global`], and check that all of its fields are.
88///
89/// This is identical to the “auto trait” implementation that Rust would provide, except that
90/// it is eager rather than lazy: its requirements are checked now (in
91/// `_global_fields_are_send_sync`), when this crate is compiled, rather than whenever a dependent
92/// wants to know whether `Global: Send` holds.
93///
94/// This improves compilation performance and avoids a risk of dependents running into the default
95/// [`recursion_limit`] when checking types containing [`Global`]. This risk will become greater
96/// when Rust’s “next solver” is stabilized.
97///
98/// [`recursion_limit`]: https://doc.rust-lang.org/reference/attributes/limits.html#the-recursion_limit-attribute
99#[cfg(send_sync)]
100mod global_send_sync {
101    use super::Global;
102
103    // SAFETY: Bounds checked below
104    unsafe impl Send for Global {}
105
106    // SAFETY: Bounds checked below
107    unsafe impl Sync for Global {}
108
109    /// This function will fail to compile if any field is not `Send + Sync`, or if a new field is
110    /// added to `Global`.
111    ///
112    /// This technique is modeled after the macro library `non_structural_derive`, with permission
113    /// (see
114    /// <https://github.com/fee1-dead/non_structural_derive/issues/1#issuecomment-5250905440>).
115    /// We only need it once, so it’s cheaper to write out the same code the macro would generate.
116    fn _global_fields_are_send_sync(global: &Global) {
117        fn _check_bound<T: Send + Sync>(_: &T) {}
118
119        let Global {
120            surfaces,
121            hub,
122            instance,
123        } = global;
124        _check_bound(surfaces);
125        _check_bound(hub);
126        _check_bound(instance);
127    }
128}
129
130impl fmt::Debug for Global {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        f.debug_struct("Global").finish()
133    }
134}
135
136impl Drop for Global {
137    fn drop(&mut self) {
138        profiling::scope!("Global::drop");
139        resource_log!("Global::drop");
140    }
141}