Skip to main content

mln_runtime/render/
target.rs

1//! What a render session renders into, and how it attaches.
2
3use std::sync::Arc;
4
5use mln_gfx::Window;
6pub use mln_gfx::backend::Type as BackendType;
7pub use mln_gfx::{
8    ConsumerSync, DmaBufFormat, DmaBufPlane, ExportKind, ExportKinds, ExportedImage, ExportedRing, GpuSync, SyncKind,
9    SyncKinds,
10};
11use mln_util::error::Error;
12use mln_util::size::Size;
13
14/// A callback that tells the host about something it should act on, such as
15/// frame results to drain. It runs on a library thread and must not block.
16pub type Wake = Arc<dyn Fn() + Send + Sync>;
17
18/// The thread that runs a render session's graphics work.
19#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
20pub enum Driver {
21    /// A thread of the session's own.
22    #[default]
23    CoreWorker,
24    /// The host's graphics thread, which runs the work through the session's
25    /// [`DriverWork`](crate::DriverWork).
26    CallerThread,
27}
28
29/// How a session attaches to its map.
30#[derive(Clone, Default)]
31pub struct AttachOptions {
32    pub driver: Driver,
33    /// Runs when frame results wait for
34    /// [`drain_frame_results`](crate::RenderSession::drain_frame_results),
35    /// and not again until a drain takes them.
36    pub frame_wake: Option<Wake>,
37    /// Runs when the map has something new to draw, and not again until the
38    /// host demands a frame, or while the session has no target.
39    pub redraw_wake: Option<Wake>,
40    /// Runs when a [`Driver::CallerThread`] session has work for
41    /// [`DriverWork::service`](crate::DriverWork::service), and not again
42    /// until a service starts.
43    pub driver_work_wake: Option<Wake>,
44    /// The kinds of sync that the host can wait for before it reads a
45    /// borrowed ring's frame. The session picks the one of them that its
46    /// target supports and that waits least: see [`SyncKinds::pick`].
47    pub producer_sync_kinds: SyncKinds,
48}
49
50impl std::fmt::Debug for AttachOptions {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        f.debug_struct("AttachOptions")
53            .field("driver", &self.driver)
54            .field("frame_wake", &self.frame_wake.is_some())
55            .field("redraw_wake", &self.redraw_wake.is_some())
56            .field("driver_work_wake", &self.driver_work_wake.is_some())
57            .field("producer_sync_kinds", &self.producer_sync_kinds)
58            .finish()
59    }
60}
61
62/// What a render session renders into. The session builds it into the
63/// backend's objects on the thread that renders, on `device`, or on a device
64/// that [`Device::new`] makes when that is `None`. The device's backend is
65/// the session's.
66#[derive(Debug)]
67pub enum RenderTarget {
68    /// An image of `size` logical pixels, rendered at the map's pixel ratio,
69    /// whose pixels [`read_texture`](crate::RenderSession::read_texture)
70    /// reads.
71    Offscreen { size: Size, device: Option<Device> },
72    /// A surface of `size` logical pixels, rendered at the map's pixel ratio,
73    /// that shows each frame that the session renders. Without a device, a
74    /// window renders on the platform's native backend where that takes
75    /// windows, and on WebGPU otherwise (on Apple's platforms, whose Metal
76    /// takes a layer); a Metal layer renders on Metal.
77    ///
78    /// A frame finishes as
79    /// [`TargetNotReady`](crate::FrameDisposition::TargetNotReady) while the
80    /// surface can't show it: while a window is minimized or has no client
81    /// area, or the surface has an empty extent or gives no image for it.
82    ///
83    /// [`release_target`](crate::RenderSession::release_target) lets go of
84    /// the surface, and [`set_surface`](crate::RenderSession::set_surface)
85    /// gives the session another one.
86    Surface { size: Size, surface: Surface, device: Option<Device> },
87    /// A ring of the host's textures of `size` logical pixels, on `device`,
88    /// whose backend is the ring's. Each frame goes to the host, which
89    /// takes it with [`acquire_frame`](crate::RenderSession::acquire_frame)
90    /// and gives it back once it has read it. The ring's textures set the
91    /// size in pixels, and [`set_ring`](crate::RenderSession::set_ring)
92    /// gives the session new ones.
93    Borrowed { size: Size, ring: BorrowedRing, device: Device },
94    /// A ring of images of `size` logical pixels, rendered at the map's
95    /// pixel ratio, that the session allocates on `device` and shares with
96    /// the host in a kind of `ring.kinds`: the first, by
97    /// [`ExportKind::BY_PREFERENCE`], that the device exports. Without a
98    /// device, the session renders on the first of [`Device::new`]'s
99    /// backends whose device exports one. Each frame goes to the host, which
100    /// takes it with [`acquire_frame`](crate::RenderSession::acquire_frame)
101    /// and gives it back once it has read it.
102    /// [`resize`](crate::RenderSession::resize) gives the ring images of a
103    /// new size, and the frames that the host holds keep theirs.
104    Exported { size: Size, ring: ExportedRing, device: Option<Device> },
105}
106
107/// A ring of the host's textures, of one backend.
108#[derive(Clone, Debug, PartialEq)]
109pub struct BorrowedRing {
110    pub(crate) kind: RingKind,
111}
112
113#[derive(Clone, Debug, PartialEq)]
114pub(crate) enum RingKind {
115    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
116    Vulkan(mln_vulkan::BorrowedImages),
117    #[cfg(all(feature = "metal", target_vendor = "apple"))]
118    Metal(mln_mtl::BorrowedTextures),
119    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
120    Gl(mln_gl::BorrowedTextures),
121    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
122    WebGpu(mln_webgpu::BorrowedTextures),
123}
124
125/// The host's texture that an acquired frame was rendered into, of `size`
126/// pixels.
127#[derive(Clone, Debug, PartialEq, Eq)]
128pub struct FrameTexture {
129    pub size: Size,
130    pub kind: FrameTextureKind,
131}
132
133/// A [`FrameTexture`]'s backend objects.
134#[derive(Clone, Debug, PartialEq, Eq)]
135#[non_exhaustive]
136pub enum FrameTextureKind {
137    /// A `VkImage` and its `VkImageView` of a `VkDevice`, in a `VkFormat`,
138    /// left in a `VkImageLayout`.
139    Vulkan { image: u64, view: u64, device: u64, format: i32, layout: i32 },
140    /// An `id<MTLTexture>` of an `id<MTLDevice>`, in an `MTLPixelFormat`.
141    Metal { texture: u64, device: u64, pixel_format: u64 },
142    /// An OpenGL texture name, of a texture target.
143    OpenGl { texture: u32, target: u32 },
144    /// A WebGPU texture: the host's at the frame's slot of its ring.
145    WebGpu,
146    /// An image of an exported ring, and its shared memory.
147    Exported(ExportedImage),
148}
149
150impl BorrowedRing {
151    /// A ring of the host's Vulkan images.
152    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
153    #[must_use]
154    pub fn vulkan(images: mln_vulkan::BorrowedImages) -> BorrowedRing {
155        BorrowedRing { kind: RingKind::Vulkan(images) }
156    }
157
158    /// A ring of the host's Metal textures.
159    #[cfg(all(feature = "metal", target_vendor = "apple"))]
160    pub fn metal(textures: mln_mtl::BorrowedTextures) -> BorrowedRing {
161        BorrowedRing { kind: RingKind::Metal(textures) }
162    }
163
164    /// A ring of the host's OpenGL textures, in the share group of a device
165    /// that wraps the host's context.
166    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
167    #[must_use]
168    pub fn gl(textures: mln_gl::BorrowedTextures) -> BorrowedRing {
169        BorrowedRing { kind: RingKind::Gl(textures) }
170    }
171
172    /// A ring of the host's WebGPU textures, of the WebGPU device that
173    /// renders into them.
174    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
175    #[must_use]
176    pub fn webgpu(textures: mln_webgpu::BorrowedTextures) -> BorrowedRing {
177        BorrowedRing { kind: RingKind::WebGpu(textures) }
178    }
179
180    /// The backend whose device renders into the ring.
181    #[must_use]
182    pub fn backend(&self) -> BackendType {
183        match self.kind {
184            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
185            RingKind::Vulkan(_) => BackendType::Vulkan,
186            #[cfg(all(feature = "metal", target_vendor = "apple"))]
187            RingKind::Metal(_) => BackendType::Metal,
188            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
189            RingKind::Gl(_) => BackendType::OpenGL,
190            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
191            RingKind::WebGpu(_) => BackendType::WebGPU,
192            // The browser build renders into no ring.
193            #[allow(unreachable_patterns)]
194            _ => BackendType::WebGPU,
195        }
196    }
197
198    /// How many textures the ring has.
199    #[must_use]
200    pub fn depth(&self) -> usize {
201        match &self.kind {
202            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
203            RingKind::Vulkan(images) => images.images.len(),
204            #[cfg(all(feature = "metal", target_vendor = "apple"))]
205            RingKind::Metal(textures) => textures.textures.len(),
206            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
207            RingKind::Gl(textures) => textures.textures.len(),
208            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
209            RingKind::WebGpu(textures) => textures.textures.len(),
210            #[allow(unreachable_patterns)]
211            _ => 0,
212        }
213    }
214
215    /// The textures' size in pixels.
216    #[must_use]
217    pub fn physical_size(&self) -> Size {
218        match &self.kind {
219            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
220            RingKind::Vulkan(images) => images.size,
221            #[cfg(all(feature = "metal", target_vendor = "apple"))]
222            RingKind::Metal(textures) => textures.size,
223            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
224            RingKind::Gl(textures) => textures.size,
225            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
226            RingKind::WebGpu(textures) => textures.size,
227            #[allow(unreachable_patterns)]
228            _ => Size::default(),
229        }
230    }
231
232    /// Whether the texture at `slot` is the one at `other`'s `other_slot`.
233    #[cfg_attr(target_family = "wasm", allow(unused_variables))]
234    pub(crate) fn same_texture(&self, slot: usize, other: &BorrowedRing, other_slot: usize) -> bool {
235        #[allow(unreachable_patterns)]
236        match (&self.kind, &other.kind) {
237            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
238            (RingKind::Vulkan(images), RingKind::Vulkan(others)) => images
239                .images
240                .get(slot)
241                .zip(others.images.get(other_slot))
242                .is_some_and(|(image, other)| image.image == other.image),
243            #[cfg(all(feature = "metal", target_vendor = "apple"))]
244            (RingKind::Metal(textures), RingKind::Metal(others)) => {
245                textures.textures.get(slot).zip(others.textures.get(other_slot)).is_some_and(|(texture, other)| {
246                    std::ptr::eq(
247                        mln_mtl::objc2::rc::Retained::as_ptr(texture),
248                        mln_mtl::objc2::rc::Retained::as_ptr(other),
249                    )
250                })
251            }
252            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
253            (RingKind::Gl(textures), RingKind::Gl(others)) => {
254                textures.textures.get(slot).is_some_and(|texture| others.textures.get(other_slot) == Some(texture))
255            }
256            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
257            (RingKind::WebGpu(textures), RingKind::WebGpu(others)) => {
258                textures.textures.get(slot).is_some_and(|texture| others.textures.get(other_slot) == Some(texture))
259            }
260            _ => false,
261        }
262    }
263
264    /// The texture at `slot`, which sessions on `device` render into.
265    #[cfg_attr(target_family = "wasm", allow(unused_variables))]
266    #[must_use]
267    pub fn texture(&self, slot: usize, device: &Device) -> Option<FrameTexture> {
268        #[allow(unreachable_patterns)]
269        match (&self.kind, device) {
270            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
271            (RingKind::Vulkan(images), Device::Vulkan(device)) => {
272                use mln_vulkan::ash::vk::Handle as _;
273                images.images.get(slot).map(|image| FrameTexture {
274                    size: images.size,
275                    kind: FrameTextureKind::Vulkan {
276                        image: image.image.as_raw(),
277                        view: image.view.as_raw(),
278                        device: device.raw().device.as_raw(),
279                        format: images.format.as_raw(),
280                        layout: images.final_layout.as_raw(),
281                    },
282                })
283            }
284            #[cfg(all(feature = "metal", target_vendor = "apple"))]
285            (RingKind::Metal(textures), Device::Metal(device)) => {
286                use mln_mtl::objc2::rc::Retained;
287                textures.textures.get(slot).map(|texture| FrameTexture {
288                    size: textures.size,
289                    kind: FrameTextureKind::Metal {
290                        texture: Retained::as_ptr(texture) as usize as u64,
291                        device: Retained::as_ptr(device.device()) as usize as u64,
292                        pixel_format: textures.pixel_format().0 as u64,
293                    },
294                })
295            }
296            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
297            (RingKind::Gl(textures), Device::Gl(_)) => textures.textures.get(slot).map(|&texture| FrameTexture {
298                size: textures.size,
299                // GL_TEXTURE_2D.
300                kind: FrameTextureKind::OpenGl { texture, target: 0x0DE1 },
301            }),
302            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
303            (RingKind::WebGpu(textures), Device::WebGpu(_)) => textures
304                .textures
305                .get(slot)
306                .map(|_| FrameTexture { size: textures.size, kind: FrameTextureKind::WebGpu }),
307            _ => None,
308        }
309    }
310}
311
312/// What a surface session presents to.
313pub struct Surface {
314    pub(crate) kind: SurfaceKind,
315}
316
317pub(crate) enum SurfaceKind {
318    Window(Arc<dyn Window>),
319    #[cfg(all(feature = "metal", target_vendor = "apple"))]
320    MetalLayer(mln_mtl::Layer),
321    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
322    Wgpu(wgpu::Surface<'static>),
323    /// The host's `VkSurfaceKHR`, of the instance of the session's device.
324    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
325    Vulkan(mln_vulkan::HostSurface),
326    /// The host's `EGLSurface`, of the display of the session's device.
327    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
328    Gl(mln_gl::HostSurface),
329}
330
331impl Surface {
332    /// A window, which the session makes its surface on. The window must
333    /// outlive the session's use of it: until a
334    /// [`set_surface`](crate::RenderSession::set_surface) or
335    /// [`release_target`](crate::RenderSession::release_target) replaces it,
336    /// or the session detaches or is abandoned.
337    pub fn window(window: impl Window + 'static) -> Surface {
338        Surface { kind: SurfaceKind::Window(Arc::new(window)) }
339    }
340
341    /// A `CAMetalLayer`, which a session on Metal presents to. It must
342    /// outlive the session's use of it, as a window must.
343    #[cfg(all(feature = "metal", target_vendor = "apple"))]
344    #[must_use]
345    pub fn metal_layer(layer: mln_mtl::Layer) -> Surface {
346        Surface { kind: SurfaceKind::MetalLayer(layer) }
347    }
348
349    /// A surface that the host made with the instance of the WebGPU
350    /// [`Device`] that the session renders on.
351    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
352    pub fn wgpu(surface: wgpu::Surface<'static>) -> Surface {
353        Surface { kind: SurfaceKind::Wgpu(surface) }
354    }
355
356    /// The host's `VkSurfaceKHR`, which a session on the Vulkan device
357    /// whose instance made it presents to. The surface stays the host's.
358    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
359    #[must_use]
360    pub fn vulkan(surface: mln_vulkan::HostSurface) -> Surface {
361        Surface { kind: SurfaceKind::Vulkan(surface) }
362    }
363
364    /// The host's `EGLSurface`, which a session on the OpenGL device that
365    /// wraps the host's context presents to. The surface stays the host's.
366    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
367    #[must_use]
368    pub fn gl(surface: mln_gl::HostSurface) -> Surface {
369        Surface { kind: SurfaceKind::Gl(surface) }
370    }
371
372    /// The backend of the device whose instance or share group a host's
373    /// surface is of, or `None` for a window or layer.
374    #[must_use]
375    pub fn host_backend(&self) -> Option<BackendType> {
376        match self.kind {
377            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
378            SurfaceKind::Vulkan(_) => Some(BackendType::Vulkan),
379            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
380            SurfaceKind::Gl(_) => Some(BackendType::OpenGL),
381            #[allow(unreachable_patterns)]
382            _ => None,
383        }
384    }
385
386    /// The surface again, if it is a window, or a surface that a new
387    /// backend presents to.
388    pub(crate) fn clone_window(&self) -> Option<Surface> {
389        match &self.kind {
390            SurfaceKind::Window(window) => Some(Surface { kind: SurfaceKind::Window(window.clone()) }),
391            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
392            SurfaceKind::Gl(surface) => Some(Surface { kind: SurfaceKind::Gl(*surface) }),
393            #[allow(unreachable_patterns)]
394            _ => None,
395        }
396    }
397
398    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a
399    /// window that has no area to present to: a minimized Win32 window, or
400    /// one whose client area is empty ([`mln_gfx::window::has_area`]).
401    pub(crate) fn check_area(&self) -> Result<(), Error> {
402        if let SurfaceKind::Window(window) = &self.kind
403            && !mln_gfx::window::has_area(&**window)
404        {
405            return Err(Error::invalid_state("the window is minimized or has no client area"));
406        }
407        Ok(())
408    }
409
410    /// The window, for a surface of one.
411    pub(crate) fn host_window(&self) -> Option<Arc<dyn Window>> {
412        match &self.kind {
413            SurfaceKind::Window(window) => Some(window.clone()),
414            #[allow(unreachable_patterns)]
415            _ => None,
416        }
417    }
418
419    /// Whether the session can make the surface without the host's device.
420    pub(crate) fn needs_no_device(&self) -> bool {
421        match self.kind {
422            SurfaceKind::Window(_) => true,
423            #[cfg(all(feature = "metal", target_vendor = "apple"))]
424            SurfaceKind::MetalLayer(_) => true,
425            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
426            SurfaceKind::Wgpu(_) => false,
427            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
428            SurfaceKind::Vulkan(_) => false,
429            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
430            SurfaceKind::Gl(_) => false,
431        }
432    }
433}
434
435impl std::fmt::Debug for Surface {
436    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
437        f.debug_struct("Surface").finish_non_exhaustive()
438    }
439}
440
441/// A GPU that sessions on many maps and threads share: one backend's
442/// device. Sessions on it keep working after the last handle drops, until
443/// they detach.
444#[derive(Clone, Debug)]
445#[non_exhaustive]
446pub enum Device {
447    /// A WebGPU device: the library's, through wgpu, or the host's
448    /// ([`Device::webgpu`]).
449    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
450    WebGpu(mln_webgpu::Device),
451    /// A Metal device and command queue.
452    #[cfg(all(feature = "metal", target_vendor = "apple"))]
453    Metal(mln_mtl::Device),
454    /// A Vulkan GPU.
455    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
456    Vulkan(mln_vulkan::Device),
457    /// An OpenGL share group, or the one context that its sessions take
458    /// turns in.
459    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
460    Gl(mln_gl::Device),
461}
462
463/// How to create a [`Device`].
464#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
465pub struct DeviceOptions {
466    /// The GPU to use. `None` picks the default one.
467    pub adapter: Option<Adapter>,
468    /// The API that an OpenGL device renders with. Only Linux's and
469    /// FreeBSD's EGL renders desktop OpenGL. Other backends ignore it.
470    pub gl_api: GlApi,
471    /// Whether the sessions of an OpenGL device take turns in one context
472    /// instead of having one each. Other backends ignore it.
473    pub gl_single_context: bool,
474}
475
476/// The OpenGL API that an OpenGL device renders with.
477#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
478pub enum GlApi {
479    /// OpenGL ES 3.0 or later.
480    #[default]
481    Gles,
482    /// Desktop OpenGL 3.3 or later.
483    Gl,
484}
485
486/// A GPU, by what names it to a backend.
487#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
488pub enum Adapter {
489    /// An index into the backend's list of GPUs.
490    Index(usize),
491    /// The GPU's 16-byte UUID, as Vulkan's
492    /// `VkPhysicalDeviceIDProperties.deviceUUID` reports it.
493    Uuid([u8; 16]),
494    /// The GPU's 8-byte LUID, as Vulkan's
495    /// `VkPhysicalDeviceIDProperties.deviceLUID` reports it: on Windows, its
496    /// DXGI adapter's.
497    Luid([u8; 8]),
498}
499
500/// A kind of window or layer that a session presents to.
501#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
502#[non_exhaustive]
503pub enum SurfaceType {
504    /// A `CAMetalLayer`.
505    MetalLayer,
506    /// A Win32 window.
507    Win32,
508    /// An X11 window, through Xlib.
509    Xlib,
510    /// An X11 window, through XCB.
511    Xcb,
512    /// A Wayland surface.
513    Wayland,
514    /// An Android `ANativeWindow`.
515    AndroidNdk,
516    /// An `OpenHarmony` `OHNativeWindow`.
517    OhosNdk,
518}
519
520impl SurfaceType {
521    /// Whether a device of `backend` presents to the surfaces of this type
522    /// on this platform, in this build.
523    #[must_use]
524    pub fn presents_with(self, backend: BackendType) -> bool {
525        let windowing = match self {
526            SurfaceType::MetalLayer => false,
527            SurfaceType::Win32 => cfg!(windows),
528            SurfaceType::Xlib | SurfaceType::Xcb | SurfaceType::Wayland => {
529                cfg!(all(unix, not(target_vendor = "apple"), not(target_os = "android"), not(target_env = "ohos")))
530            }
531            SurfaceType::AndroidNdk => cfg!(target_os = "android"),
532            SurfaceType::OhosNdk => cfg!(target_env = "ohos"),
533        };
534        match backend {
535            BackendType::Metal => {
536                cfg!(all(feature = "metal", target_vendor = "apple")) && self == SurfaceType::MetalLayer
537            }
538            BackendType::Vulkan => {
539                cfg!(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm")))) && windowing
540            }
541            BackendType::OpenGL => {
542                cfg!(all(feature = "gl", unix, not(target_vendor = "apple")))
543                    && windowing
544                    && matches!(
545                        self,
546                        SurfaceType::Xlib | SurfaceType::Wayland | SurfaceType::AndroidNdk | SurfaceType::OhosNdk
547                    )
548            }
549            // wgpu's Vulkan backend makes no OpenHarmony surface, and this
550            // build has no wgpu GLES backend.
551            BackendType::WebGPU => {
552                cfg!(all(feature = "webgpu", not(target_family = "wasm"))) && windowing && self != SurfaceType::OhosNdk
553            }
554            #[allow(unreachable_patterns)]
555            _ => false,
556        }
557    }
558
559    /// The Vulkan instance extension that makes the surfaces of this type.
560    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
561    fn vulkan_extension(self) -> Option<&'static std::ffi::CStr> {
562        use mln_vulkan::ash::khr;
563        match self {
564            SurfaceType::MetalLayer => None,
565            SurfaceType::Win32 => Some(khr::win32_surface::NAME),
566            SurfaceType::Xlib => Some(khr::xlib_surface::NAME),
567            SurfaceType::Xcb => Some(khr::xcb_surface::NAME),
568            SurfaceType::Wayland => Some(khr::wayland_surface::NAME),
569            SurfaceType::AndroidNdk => Some(khr::android_surface::NAME),
570            SurfaceType::OhosNdk => Some(mln_vulkan::device::OHOS_SURFACE),
571        }
572    }
573
574    /// Whether a device of any backend of this build presents to the
575    /// surfaces of this type.
576    #[must_use]
577    pub fn presents_with_any(self) -> bool {
578        [BackendType::Metal, BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
579            .into_iter()
580            .any(|backend| self.presents_with(backend))
581    }
582
583    /// Whether a session of this build presents to the surfaces of this
584    /// type without the host's device: on the device that a surface session
585    /// makes when it gets none.
586    #[must_use]
587    pub fn presents_without_device(self) -> bool {
588        match self {
589            SurfaceType::MetalLayer => self.presents_with(BackendType::Metal),
590            _ if cfg!(target_vendor = "apple") => self.presents_with(BackendType::WebGPU),
591            _ => [BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
592                .into_iter()
593                .any(|backend| self.presents_with(backend)),
594        }
595    }
596}
597
598/// Whether a backend that failed with `error` is missing, so the next one
599/// may take its place.
600#[cfg(not(target_family = "wasm"))]
601fn missing(error: &Error) -> bool {
602    error.kind == mln_util::ErrorKind::Unsupported
603}
604
605impl Device {
606    /// The library's device, on the platform's native backend: Metal on
607    /// Apple's platforms, and Vulkan elsewhere, or OpenGL where there is no
608    /// Vulkan. WebGPU (wgpu) takes the place of a native backend that isn't
609    /// there. A backend that can't name the GPU that `options` names is
610    /// skipped: OpenGL names none, and only Vulkan names one by UUID or LUID.
611    /// So is OpenGL where it can't render with `options.gl_api`.
612    ///
613    /// Fails with [`ErrorKind::NotFound`](mln_util::ErrorKind) when
614    /// the options name no GPU, with
615    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) when no backend has a
616    /// GPU or in the browser, where a session renders on the page's device,
617    /// and with [`ErrorKind::Native`](mln_util::ErrorKind) when the GPU
618    /// can't create the device.
619    pub fn new(options: DeviceOptions) -> Result<Device, Error> {
620        #[cfg(target_family = "wasm")]
621        {
622            let _ = options;
623            Err(Error::unsupported("the browser has no library devices"))
624        }
625        #[cfg(not(target_family = "wasm"))]
626        {
627            let mut error = Error::unsupported("this build has no backend");
628            for backend in Self::native_order() {
629                match Self::with_backend(*backend, options) {
630                    Ok(device) => return Ok(device),
631                    Err(e) if missing(&e) => error = e,
632                    Err(e) => return Err(e),
633                }
634            }
635            Err(error)
636        }
637    }
638
639    /// The library's device on `backend`.
640    ///
641    /// Fails as [`new`](Self::new) does, and with
642    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a backend that
643    /// isn't in this build or on this platform.
644    pub fn with_backend(backend: BackendType, options: DeviceOptions) -> Result<Device, Error> {
645        let DeviceOptions { adapter, gl_api, gl_single_context } = options;
646        // Only Vulkan names its GPUs by ID here.
647        let index = |adapter: Option<Adapter>| match adapter {
648            None => Ok(None),
649            Some(Adapter::Index(index)) => Ok(Some(index)),
650            Some(_) => Err(Error::unsupported(format!("{backend:?} names no GPU by UUID or LUID"))),
651        };
652        match backend {
653            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
654            BackendType::WebGPU => mln_webgpu::Device::new(index(adapter)?).map(Device::WebGpu),
655            #[cfg(all(feature = "metal", target_vendor = "apple"))]
656            BackendType::Metal => mln_mtl::Device::new(index(adapter)?).map(Device::Metal),
657            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
658            BackendType::Vulkan => match adapter {
659                Some(Adapter::Uuid(uuid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Uuid(uuid)),
660                Some(Adapter::Luid(luid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Luid(luid)),
661                _ => mln_vulkan::Device::new(index(adapter)?),
662            }
663            .map(Device::Vulkan),
664            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
665            BackendType::OpenGL => {
666                if adapter.is_some() {
667                    return Err(Error::unsupported("OpenGL picks no GPU"));
668                }
669                let api = match gl_api {
670                    GlApi::Gles => mln_gl::Api::Gles,
671                    GlApi::Gl => mln_gl::Api::Gl,
672                };
673                let options = mln_gl::DeviceOptions { api, single_context: gl_single_context };
674                mln_gl::Device::with_options(options).map(Device::Gl)
675            }
676            #[allow(unreachable_patterns)]
677            _ => {
678                let _ = (index, adapter, gl_api, gl_single_context);
679                Err(Error::unsupported(format!("this build has no {backend:?} backend")))
680            }
681        }
682    }
683
684    /// The kinds of sync with which the host can wait for a frame of `ring`
685    /// on the device (the producer's), and with which a session waits for
686    /// the host's reads (the consumer's).
687    ///
688    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
689    /// device can't render into the ring: one of another backend, or one the
690    /// device lacks a feature for.
691    pub fn borrowed_sync_kinds(&self, ring: &BorrowedRing) -> Result<(SyncKinds, SyncKinds), Error> {
692        #[allow(unreachable_patterns)]
693        match (self, &ring.kind) {
694            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
695            (Device::Vulkan(device), RingKind::Vulkan(images)) => {
696                images.check(device)?;
697                Ok(device.sync_kinds())
698            }
699            #[cfg(all(feature = "metal", target_vendor = "apple"))]
700            (Device::Metal(device), RingKind::Metal(textures)) => {
701                textures.check(device)?;
702                Ok(mln_mtl::BorrowedTextures::sync_kinds(device))
703            }
704            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
705            (Device::Gl(device), RingKind::Gl(_)) => {
706                if !device.is_host() {
707                    return Err(Error::unsupported(
708                        "an OpenGL ring renders on a device in the share group of the host's context",
709                    ));
710                }
711                Ok(mln_gl::BorrowedTextures::sync_kinds())
712            }
713            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
714            (Device::WebGpu(_), RingKind::WebGpu(textures)) => {
715                textures.check()?;
716                Ok(mln_webgpu::BorrowedTextures::sync_kinds())
717            }
718            _ => Err(Error::unsupported(format!(
719                "a {:?} device renders into no ring of {:?} textures",
720                self.backend(),
721                ring.backend()
722            ))),
723        }
724    }
725
726    /// The kinds of exported ring that sessions on the device share their
727    /// images in: those that the device has exported an image of.
728    #[must_use]
729    pub fn export_kinds(&self) -> ExportKinds {
730        match self {
731            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
732            Device::Vulkan(device) => device.export_kinds(),
733            #[cfg(all(feature = "metal", target_vendor = "apple"))]
734            Device::Metal(device) => mln_mtl::exported_target::export_kinds(device),
735            #[cfg(all(feature = "gl", unix, not(target_vendor = "apple"), not(target_os = "android")))]
736            Device::Gl(device) => mln_gl::exported_target::export_kinds(device),
737            #[allow(unreachable_patterns)]
738            _ => ExportKinds::NONE,
739        }
740    }
741
742    /// The kind that a session on the device shares `ring`'s images in, and
743    /// the kinds of sync with which the host can wait for a frame (the
744    /// producer's) and a session for the host's reads (the consumer's).
745    ///
746    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
747    /// device exports none of the ring's kinds.
748    pub fn export_plan(&self, ring: &ExportedRing) -> Result<(ExportKind, SyncKinds, SyncKinds), Error> {
749        #[allow(unreachable_patterns)]
750        match self {
751            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
752            Device::Vulkan(device) => {
753                let kind = mln_vulkan::exported_target::plan(device, ring)?;
754                let (producer, consumer) = mln_vulkan::exported_target::sync_kinds(device);
755                Ok((kind, producer, consumer))
756            }
757            #[cfg(all(feature = "metal", target_vendor = "apple"))]
758            Device::Metal(device) => {
759                let kind = mln_mtl::exported_target::plan(device, ring)?;
760                let (producer, consumer) = mln_mtl::exported_target::sync_kinds(device);
761                Ok((kind, producer, consumer))
762            }
763            #[cfg(all(feature = "gl", unix, not(target_vendor = "apple"), not(target_os = "android")))]
764            Device::Gl(device) => {
765                let kind = mln_gl::exported_target::plan(device, ring)?;
766                let (producer, consumer) = mln_gl::exported_target::sync_kinds();
767                Ok((kind, producer, consumer))
768            }
769            _ => {
770                let _ = ring;
771                Err(Error::unsupported(format!("a {:?} device exports no ring", self.backend())))
772            }
773        }
774    }
775
776    /// The kinds of sync with which the host can wait for an exported
777    /// ring's frame (the producer's) and a session for the host's reads (the
778    /// consumer's), on a device that exports a ring.
779    #[must_use]
780    pub fn export_sync_kinds(&self) -> (SyncKinds, SyncKinds) {
781        if self.export_kinds().is_empty() {
782            return (SyncKinds::NONE, SyncKinds::NONE);
783        }
784        #[allow(unreachable_patterns)]
785        match self {
786            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
787            Device::Vulkan(device) => mln_vulkan::exported_target::sync_kinds(device),
788            #[cfg(all(feature = "metal", target_vendor = "apple"))]
789            Device::Metal(device) => mln_mtl::exported_target::sync_kinds(device),
790            #[cfg(all(feature = "gl", unix, not(target_vendor = "apple"), not(target_os = "android")))]
791            Device::Gl(_) => mln_gl::exported_target::sync_kinds(),
792            _ => (SyncKinds::NONE, SyncKinds::NONE),
793        }
794    }
795
796    /// The library's device for `ring`: on the first of [`new`](Self::new)'s
797    /// backends whose device exports one of the ring's kinds.
798    ///
799    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when no
800    /// backend's device does, and as [`new`](Self::new) does.
801    pub fn for_exported_ring(ring: &ExportedRing) -> Result<Device, Error> {
802        #[cfg(target_family = "wasm")]
803        {
804            let _ = ring;
805            Err(Error::unsupported("the browser has no library devices"))
806        }
807        #[cfg(not(target_family = "wasm"))]
808        {
809            let mut error = Error::unsupported("no backend of this build exports the ring's kinds of image");
810            for backend in Self::native_order() {
811                match Self::with_backend(*backend, DeviceOptions::default()) {
812                    Ok(device) => match device.export_plan(ring) {
813                        Ok(_) => return Ok(device),
814                        Err(e) => error = e,
815                    },
816                    Err(e) if missing(&e) => {}
817                    Err(e) => return Err(e),
818                }
819            }
820            Err(error)
821        }
822    }
823
824    /// Whether sessions on the device present to the host's own surfaces:
825    /// a Vulkan device's `VkSurfaceKHR`s, or the `EGLSurface`s of an OpenGL
826    /// device that wraps the host's context.
827    #[must_use]
828    pub fn presents_to_host_surfaces(&self) -> bool {
829        match self {
830            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
831            Device::Vulkan(device) => device.presents(),
832            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
833            Device::Gl(device) => device.is_host(),
834            #[allow(unreachable_patterns)]
835            _ => false,
836        }
837    }
838
839    /// Whether sessions on the device present to the surfaces of
840    /// `surface`'s type: a Vulkan device's instance needs the type's surface
841    /// extension, which the loader may lack.
842    #[must_use]
843    pub fn presents_to(&self, surface: SurfaceType) -> bool {
844        if !surface.presents_with(self.backend()) {
845            return false;
846        }
847        match self {
848            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
849            Device::Vulkan(device) => surface.vulkan_extension().is_some_and(|name| device.presents_through(name)),
850            #[allow(unreachable_patterns)]
851            _ => true,
852        }
853    }
854
855    /// The backends [`new`](Self::new) tries, in order.
856    #[cfg(not(target_family = "wasm"))]
857    fn native_order() -> &'static [BackendType] {
858        if cfg!(target_vendor = "apple") {
859            &[BackendType::Metal, BackendType::WebGPU]
860        } else {
861            &[BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
862        }
863    }
864
865    /// The host's WebGPU device and queue, which `instance` made. The
866    /// session configures its surfaces with `format`, which each surface
867    /// must support.
868    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
869    #[must_use]
870    pub fn webgpu(
871        instance: wgpu::Instance,
872        device: wgpu::Device,
873        queue: wgpu::Queue,
874        format: wgpu::TextureFormat,
875    ) -> Device {
876        Device::WebGpu(mln_webgpu::Device::from_wgpu(Some(instance), device, queue, Some(format)))
877    }
878
879    /// The backend the device is of.
880    #[must_use]
881    pub fn backend(&self) -> BackendType {
882        match *self {
883            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
884            Device::WebGpu(_) => BackendType::WebGPU,
885            #[cfg(all(feature = "metal", target_vendor = "apple"))]
886            Device::Metal(_) => BackendType::Metal,
887            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
888            Device::Vulkan(_) => BackendType::Vulkan,
889            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
890            Device::Gl(_) => BackendType::OpenGL,
891        }
892    }
893}