Debian Codegraph @

third_party/rust/wgpu-hal/src/metal/surface.rs

raw
1 #![allow(clippy::let_unit_value)] // `let () =` being used to constrain result type
2
3 use alloc::borrow::ToOwned as _;
4 use core::mem::ManuallyDrop;
5 use core::ptr::NonNull;
6 use std::thread;
7
8 use core_graphics_types::{
9 base::CGFloat,
10 geometry::{CGRect, CGSize},
11 };
12 use metal::{foreign_types::ForeignType, MTLTextureType};
13 use objc::{
14 class, msg_send,
15 rc::{autoreleasepool, StrongPtr},
16 runtime::{Object, BOOL, NO, YES},
17 sel, sel_impl,
18 };
19 use parking_lot::{Mutex, RwLock};
20
21 use crate::metal::layer_observer::new_observer_layer;
22
23 #[link(name = "QuartzCore", kind = "framework")]
24 extern "C" {}
25
26 impl super::Surface {
27 fn new(layer: metal::MetalLayer) -> Self {
28 Self {
29 render_layer: Mutex::new(layer),
30 swapchain_format: RwLock::new(None),
31 extent: RwLock::new(wgt::Extent3d::default()),
32 main_thread_id: thread::current().id(),
33 present_with_transaction: false,
34 }
35 }
36
37 /// If not called on the main thread, this will panic.
38 #[allow(clippy::transmute_ptr_to_ref)]
39 pub unsafe fn from_view(view: NonNull<Object>) -> Self {
40 let layer = unsafe { Self::get_metal_layer(view) };
41 let layer = ManuallyDrop::new(layer);
42 // SAFETY: The layer is an initialized instance of `CAMetalLayer`, and
43 // we transfer the retain count to `MetalLayer` using `ManuallyDrop`.
44 let layer = unsafe { metal::MetalLayer::from_ptr(layer.cast()) };
45 Self::new(layer)
46 }
47
48 pub unsafe fn from_layer(layer: &metal::MetalLayerRef) -> Self {
49 let class = class!(CAMetalLayer);
50 let proper_kind: BOOL = msg_send![layer, isKindOfClass: class];
51 assert_eq!(proper_kind, YES);
52 Self::new(layer.to_owned())
53 }
54
55 /// Get or create a new `CAMetalLayer` associated with the given `NSView`
56 /// or `UIView`.
57 ///
58 /// # Panics
59 ///
60 /// If called from a thread that is not the main thread, this will panic.
61 ///
62 /// # Safety
63 ///
64 /// The `view` must be a valid instance of `NSView` or `UIView`.
65 pub(crate) unsafe fn get_metal_layer(view: NonNull<Object>) -> StrongPtr {
66 let is_main_thread: BOOL = msg_send![class!(NSThread), isMainThread];
67 if is_main_thread == NO {
68 panic!("get_metal_layer cannot be called in non-ui thread.");
69 }
70
71 // Ensure that the view is layer-backed.
72 // Views are always layer-backed in UIKit.
73 #[cfg(target_os = "macos")]
74 let () = msg_send![view.as_ptr(), setWantsLayer: YES];
75
76 let root_layer: *mut Object = msg_send![view.as_ptr(), layer];
77 // `-[NSView layer]` can return `NULL`, while `-[UIView layer]` should
78 // always be available.
79 assert!(!root_layer.is_null(), "failed making the view layer-backed");
80
81 // NOTE: We explicitly do not touch properties such as
82 // `layerContentsPlacement`, `needsDisplayOnBoundsChange` and
83 // `contentsGravity` etc. on the root layer, both since we would like
84 // to give the user full control over them, and because the default
85 // values suit us pretty well (especially the contents placement being
86 // `NSViewLayerContentsRedrawDuringViewResize`, which allows the view
87 // to receive `drawRect:`/`updateLayer` calls).
88
89 let is_metal_layer: BOOL = msg_send![root_layer, isKindOfClass: class!(CAMetalLayer)];
90 if is_metal_layer == YES {
91 // The view has a `CAMetalLayer` as the root layer, which can
92 // happen for example if user overwrote `-[NSView layerClass]` or
93 // the view is `MTKView`.
94 //
95 // This is easily handled: We take "ownership" over the layer, and
96 // render directly into that; after all, the user passed a view
97 // with an explicit Metal layer to us, so this is very likely what
98 // they expect us to do.
99 unsafe { StrongPtr::retain(root_layer) }
100 } else {
101 // The view does not have a `CAMetalLayer` as the root layer (this
102 // is the default for most views).
103 //
104 // This case is trickier! We cannot use the existing layer with
105 // Metal, so we must do something else. There are a few options,
106 // we do the same as outlined in:
107 // https://docs.rs/raw-window-metal/1.1.0/raw_window_metal/#reasoning-behind-creating-a-sublayer
108 unsafe { new_observer_layer(root_layer) }
109 }
110 }
111
112 pub(super) fn dimensions(&self) -> wgt::Extent3d {
113 let (size, scale): (CGSize, CGFloat) = unsafe {
114 let render_layer_borrow = self.render_layer.lock();
115 let render_layer = render_layer_borrow.as_ref();
116 let bounds: CGRect = msg_send![render_layer, bounds];
117 let contents_scale: CGFloat = msg_send![render_layer, contentsScale];
118 (bounds.size, contents_scale)
119 };
120
121 wgt::Extent3d {
122 width: (size.width * scale) as u32,
123 height: (size.height * scale) as u32,
124 depth_or_array_layers: 1,
125 }
126 }
127 }
128
129 impl crate::Surface for super::Surface {
130 type A = super::Api;
131
132 unsafe fn configure(
133 &self,
134 device: &super::Device,
135 config: &crate::SurfaceConfiguration,
136 ) -> Result<(), crate::SurfaceError> {
137 log::debug!("build swapchain {:?}", config);
138
139 let caps = &device.shared.private_caps;
140 *self.swapchain_format.write() = Some(config.format);
141 *self.extent.write() = config.extent;
142
143 let render_layer = self.render_layer.lock();
144 let framebuffer_only = config.usage == wgt::TextureUses::COLOR_TARGET;
145 let display_sync = match config.present_mode {
146 wgt::PresentMode::Fifo => true,
147 wgt::PresentMode::Immediate => false,
148 m => unreachable!("Unsupported present mode: {m:?}"),
149 };
150 let drawable_size = CGSize::new(config.extent.width as f64, config.extent.height as f64);
151
152 match config.composite_alpha_mode {
153 wgt::CompositeAlphaMode::Opaque => render_layer.set_opaque(true),
154 wgt::CompositeAlphaMode::PostMultiplied => render_layer.set_opaque(false),
155 _ => (),
156 }
157
158 let device_raw = device.shared.device.lock();
159 render_layer.set_device(&device_raw);
160 render_layer.set_pixel_format(caps.map_format(config.format));
161 render_layer.set_framebuffer_only(framebuffer_only);
162 render_layer.set_presents_with_transaction(self.present_with_transaction);
163 // opt-in to Metal EDR
164 // EDR potentially more power used in display and more bandwidth, memory footprint.
165 let wants_edr = config.format == wgt::TextureFormat::Rgba16Float;
166 if wants_edr != render_layer.wants_extended_dynamic_range_content() {
167 render_layer.set_wants_extended_dynamic_range_content(wants_edr);
168 }
169
170 // this gets ignored on iOS for certain OS/device combinations (iphone5s iOS 10.3)
171 render_layer.set_maximum_drawable_count(config.maximum_frame_latency as u64 + 1);
172 render_layer.set_drawable_size(drawable_size);
173 if caps.can_set_next_drawable_timeout {
174 let () = msg_send![*render_layer, setAllowsNextDrawableTimeout:false];
175 }
176 if caps.can_set_display_sync {
177 let () = msg_send![*render_layer, setDisplaySyncEnabled: display_sync];
178 }
179
180 Ok(())
181 }
182
183 unsafe fn unconfigure(&self, _device: &super::Device) {
184 *self.swapchain_format.write() = None;
185 }
186
187 unsafe fn acquire_texture(
188 &self,
189 _timeout_ms: Option<core::time::Duration>, //TODO
190 _fence: &super::Fence,
191 ) -> Result<Option<crate::AcquiredSurfaceTexture<super::Api>>, crate::SurfaceError> {
192 let render_layer = self.render_layer.lock();
193 let (drawable, texture) = match autoreleasepool(|| {
194 render_layer
195 .next_drawable()
196 .map(|drawable| (drawable.to_owned(), drawable.texture().to_owned()))
197 }) {
198 Some(pair) => pair,
199 None => return Ok(None),
200 };
201
202 let swapchain_format = self.swapchain_format.read().unwrap();
203 let extent = self.extent.read();
204 let suf_texture = super::SurfaceTexture {
205 texture: super::Texture {
206 raw: texture,
207 format: swapchain_format,
208 raw_type: MTLTextureType::D2,
209 array_layers: 1,
210 mip_levels: 1,
211 copy_size: crate::CopyExtent {
212 width: extent.width,
213 height: extent.height,
214 depth: 1,
215 },
216 },
217 drawable,
218 present_with_transaction: self.present_with_transaction,
219 };
220
221 Ok(Some(crate::AcquiredSurfaceTexture {
222 texture: suf_texture,
223 suboptimal: false,
224 }))
225 }
226
227 unsafe fn discard_texture(&self, _texture: super::SurfaceTexture) {}
228 }