Skip to main content

mln_runtime/render/
target.rs

1//! What a render session renders into, and how it attaches.
2
3// The matches over the backends' enums list a variant per backend that the
4// build's features and target have, so whether their `_` arm is unreachable,
5// or matches a single variant, and whether a `let` of one variant is
6// irrefutable, depends on the build.
7#![allow(
8    unreachable_patterns,
9    irrefutable_let_patterns,
10    clippy::match_wildcard_for_single_variants,
11    reason = "the backends' variants depend on the build's features and target"
12)]
13
14use std::sync::Arc;
15
16use mln_gfx::Window;
17pub use mln_gfx::backend::Type as BackendType;
18pub use mln_gfx::{
19    ConsumerSync, DepthStencilFormat, DepthStencilFormats, DmaBufFormat, DmaBufPlane, ExportKind, ExportKinds,
20    ExportedImage, ExportedRing, FrameDepth, GpuSync, NativeTexture, SyncKind, SyncKinds,
21};
22use mln_util::error::Error;
23use mln_util::size::Size;
24
25// The browser's one device of a backend crate is WebGPU's, which
26// `request_web_gpu` makes.
27#[cfg(not(target_family = "wasm"))]
28use super::gfx_error;
29
30/// A callback that tells the host about something it should act on, such as
31/// frame results to drain. It runs on a library thread and must not block.
32pub type Wake = Arc<dyn Fn() + Send + Sync>;
33
34/// The thread that runs a render session's graphics work.
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
36pub enum Driver {
37    /// A thread of the session's own.
38    #[default]
39    CoreWorker,
40    /// The host's graphics thread, which runs the work through the session's
41    /// [`DriverWork`](crate::DriverWork).
42    CallerThread,
43}
44
45/// How a session attaches to its map.
46#[derive(Clone, Default)]
47pub struct AttachOptions {
48    pub driver: Driver,
49    /// Runs when frame results wait for
50    /// [`drain_frame_results`](crate::RenderSession::drain_frame_results),
51    /// and not again until a drain takes them.
52    pub frame_wake: Option<Wake>,
53    /// Runs when the map has something new to draw, and not again until the
54    /// host demands a frame, or while the session has no target. A session
55    /// without one can have a frame pacer demand its frames instead
56    /// ([`RenderSession::set_frame_pacer`](crate::RenderSession::set_frame_pacer)).
57    pub redraw_wake: Option<Wake>,
58    /// Runs when a [`Driver::CallerThread`] session has work for
59    /// [`DriverWork::service`](crate::DriverWork::service), and not again
60    /// until a service starts.
61    pub driver_work_wake: Option<Wake>,
62    /// The kinds of sync that the host can wait for before it reads a
63    /// borrowed ring's frame. The session picks the one of them that its
64    /// target supports and that waits least: see [`SyncKinds::pick`].
65    pub producer_sync_kinds: SyncKinds,
66}
67
68impl std::fmt::Debug for AttachOptions {
69    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
70        f.debug_struct("AttachOptions")
71            .field("driver", &self.driver)
72            .field("frame_wake", &self.frame_wake.is_some())
73            .field("redraw_wake", &self.redraw_wake.is_some())
74            .field("driver_work_wake", &self.driver_work_wake.is_some())
75            .field("producer_sync_kinds", &self.producer_sync_kinds)
76            .finish()
77    }
78}
79
80/// What a render session renders into. The session builds it into the
81/// backend's objects on the thread that renders, on `device`, or on a device
82/// that [`Device::new`] makes when that is `None`. The device's backend is
83/// the session's.
84#[derive(Debug)]
85pub enum RenderTarget {
86    /// An image of `size` logical pixels, rendered at the map's pixel ratio,
87    /// whose pixels [`read_texture`](crate::RenderSession::read_texture)
88    /// reads.
89    Offscreen { size: Size, device: Option<Device> },
90    /// A surface of `size` logical pixels, rendered at the map's pixel ratio,
91    /// that shows each frame that the session renders. Without a device, a
92    /// window renders on the platform's native backend where that takes
93    /// windows, and on WebGPU otherwise (on Apple's platforms, whose Metal
94    /// takes a layer); a Metal layer renders on Metal.
95    ///
96    /// A frame finishes as
97    /// [`TargetNotReady`](crate::FrameDisposition::TargetNotReady) while the
98    /// surface can't show it: while a window is minimized or has no client
99    /// area, or the surface has an empty extent or gives no image for it.
100    ///
101    /// [`release_target`](crate::RenderSession::release_target) lets go of
102    /// the surface, and [`set_surface`](crate::RenderSession::set_surface)
103    /// gives the session another one.
104    Surface { size: Size, surface: Surface, device: Option<Device> },
105    /// A ring of the host's textures of `size` logical pixels, on `device`,
106    /// whose backend is the ring's. Each frame goes to the host, which
107    /// takes it with [`acquire_frame`](crate::RenderSession::acquire_frame)
108    /// and gives it back once it has read it. The ring's textures set the
109    /// size in pixels, and [`set_ring`](crate::RenderSession::set_ring)
110    /// gives the session new ones.
111    Borrowed { size: Size, ring: BorrowedRing, device: Device },
112    /// A ring of images of `size` logical pixels, rendered at the map's
113    /// pixel ratio, that the session allocates on `device` and shares with
114    /// the host in a kind of `ring.kinds`: the first, by
115    /// [`ExportKind::BY_PREFERENCE`], that the device exports. Without a
116    /// device, the session renders on the first of [`Device::new`]'s
117    /// backends whose device exports one. Each frame goes to the host, which
118    /// takes it with [`acquire_frame`](crate::RenderSession::acquire_frame)
119    /// and gives it back once it has read it.
120    /// [`resize`](crate::RenderSession::resize) gives the ring images of a
121    /// new size, and the frames that the host holds keep theirs.
122    Exported { size: Size, ring: ExportedRing, device: Option<Device> },
123}
124
125/// A ring of the host's textures, of one backend.
126#[derive(Clone, Debug, PartialEq)]
127pub struct BorrowedRing {
128    pub(crate) kind: RingKind,
129}
130
131#[derive(Clone, Debug, PartialEq)]
132pub(crate) enum RingKind {
133    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
134    Vulkan(mln_vulkan::BorrowedImages),
135    #[cfg(all(feature = "metal", target_vendor = "apple"))]
136    Metal(mln_mtl::BorrowedTextures),
137    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
138    Gl(mln_gl::BorrowedTextures),
139    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
140    WebGpu(mln_webgpu::BorrowedTextures),
141    #[cfg(all(feature = "d3d12", windows))]
142    D3d12(mln_d3d12::BorrowedTextures),
143}
144
145/// The host's texture that an acquired frame was rendered into, of `size`
146/// pixels.
147#[derive(Clone, Debug, PartialEq, Eq)]
148pub struct FrameTexture {
149    pub size: mln_gfx::Size,
150    pub kind: FrameTextureKind,
151    /// An exported ring's image as the API of the session's device names it,
152    /// for a host on the device, or `None` for a borrowed ring's texture.
153    pub native: Option<FrameTextureKind>,
154    /// The texture that holds the frame's depth and stencil: a borrowed
155    /// ring's depth texture, or an exported ring's that keeps depth.
156    pub depth: Option<FrameDepth>,
157}
158
159impl FrameTexture {
160    /// The frame's texture as the API of the session's device names it: a
161    /// borrowed ring's, or an exported ring's on its device.
162    #[must_use]
163    pub fn native_kind(&self) -> Option<&FrameTextureKind> {
164        match &self.kind {
165            FrameTextureKind::Exported(_) => self.native.as_ref(),
166            kind => Some(kind),
167        }
168    }
169
170    /// An exported ring's frame, of the session's `device`.
171    pub(crate) fn exported(frame: mln_gfx::ExportedFrame, device: &Device) -> FrameTexture {
172        FrameTexture {
173            size: frame.size,
174            kind: FrameTextureKind::Exported(frame.image),
175            native: native_kind(frame.texture, device),
176            depth: frame.depth,
177        }
178    }
179}
180
181/// `texture`, which `device` drew into, with the device.
182fn native_kind(texture: NativeTexture, device: &Device) -> Option<FrameTextureKind> {
183    match (texture, device) {
184        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
185        (NativeTexture::Vulkan { image, view, format, layout }, Device::Vulkan(device)) => {
186            use mln_vulkan::ash::vk::Handle as _;
187            Some(FrameTextureKind::Vulkan { image, view, device: device.raw().device.as_raw(), format, layout })
188        }
189        #[cfg(all(feature = "metal", target_vendor = "apple"))]
190        (NativeTexture::Metal { texture, pixel_format }, Device::Metal(device)) => Some(FrameTextureKind::Metal {
191            texture,
192            device: mln_mtl::objc2::rc::Retained::as_ptr(device.device()) as usize as u64,
193            pixel_format,
194        }),
195        (NativeTexture::OpenGl { texture, target, .. }, _) => Some(FrameTextureKind::OpenGl { texture, target }),
196        #[cfg(all(feature = "d3d12", windows))]
197        (NativeTexture::D3d12 { resource, format, state }, Device::D3d12(device)) => {
198            use mln_d3d12::windows::core::Interface as _;
199            Some(FrameTextureKind::D3d12 { resource, device: device.device().as_raw() as usize as u64, format, state })
200        }
201        _ => None,
202    }
203}
204
205/// A [`FrameTexture`]'s backend objects.
206#[derive(Clone, Debug, PartialEq, Eq)]
207#[non_exhaustive]
208pub enum FrameTextureKind {
209    /// A `VkImage` and its `VkImageView` of a `VkDevice`, in a `VkFormat`,
210    /// left in a `VkImageLayout`.
211    Vulkan { image: u64, view: u64, device: u64, format: i32, layout: i32 },
212    /// An `id<MTLTexture>` of an `id<MTLDevice>`, in an `MTLPixelFormat`.
213    Metal { texture: u64, device: u64, pixel_format: u64 },
214    /// An OpenGL texture name, of a texture target.
215    OpenGl { texture: u32, target: u32 },
216    /// A WebGPU texture: the host's at the frame's slot of its ring.
217    WebGpu,
218    /// An `ID3D12Resource*` of an `ID3D12Device*`, in a `DXGI_FORMAT`, left
219    /// in a `D3D12_RESOURCE_STATES`.
220    D3d12 { resource: u64, device: u64, format: u32, state: u32 },
221    /// An image of an exported ring, and its shared memory.
222    Exported(ExportedImage),
223}
224
225impl BorrowedRing {
226    /// A ring of the host's Vulkan images.
227    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
228    #[must_use]
229    pub fn vulkan(images: mln_vulkan::BorrowedImages) -> BorrowedRing {
230        BorrowedRing { kind: RingKind::Vulkan(images) }
231    }
232
233    /// A ring of the host's Metal textures.
234    #[cfg(all(feature = "metal", target_vendor = "apple"))]
235    #[must_use]
236    pub fn metal(textures: mln_mtl::BorrowedTextures) -> BorrowedRing {
237        BorrowedRing { kind: RingKind::Metal(textures) }
238    }
239
240    /// A ring of the host's OpenGL textures, in the share group of a device
241    /// that wraps the host's context.
242    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
243    #[must_use]
244    pub fn gl(textures: mln_gl::BorrowedTextures) -> BorrowedRing {
245        BorrowedRing { kind: RingKind::Gl(textures) }
246    }
247
248    /// A ring of the host's WebGPU textures, of the WebGPU device that
249    /// renders into them.
250    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
251    #[must_use]
252    pub fn webgpu(textures: mln_webgpu::BorrowedTextures) -> BorrowedRing {
253        BorrowedRing { kind: RingKind::WebGpu(textures) }
254    }
255
256    /// A ring of the host's D3D12 textures, of the D3D12 device that renders
257    /// into them.
258    #[cfg(all(feature = "d3d12", windows))]
259    #[must_use]
260    pub fn d3d12(textures: mln_d3d12::BorrowedTextures) -> BorrowedRing {
261        BorrowedRing { kind: RingKind::D3d12(textures) }
262    }
263
264    /// The backend whose device renders into the ring.
265    #[must_use]
266    pub fn backend(&self) -> BackendType {
267        match self.kind {
268            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
269            RingKind::Vulkan(_) => BackendType::Vulkan,
270            #[cfg(all(feature = "metal", target_vendor = "apple"))]
271            RingKind::Metal(_) => BackendType::Metal,
272            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
273            RingKind::Gl(_) => BackendType::OpenGL,
274            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
275            RingKind::WebGpu(_) => BackendType::WebGPU,
276            #[cfg(all(feature = "d3d12", windows))]
277            RingKind::D3d12(_) => BackendType::D3D12,
278            // The browser build renders into no ring.
279            _ => BackendType::WebGPU,
280        }
281    }
282
283    /// How many textures the ring has.
284    #[must_use]
285    pub fn depth(&self) -> usize {
286        match &self.kind {
287            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
288            RingKind::Vulkan(images) => images.images.len(),
289            #[cfg(all(feature = "metal", target_vendor = "apple"))]
290            RingKind::Metal(textures) => textures.textures.len(),
291            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
292            RingKind::Gl(textures) => textures.textures.len(),
293            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
294            RingKind::WebGpu(textures) => textures.textures.len(),
295            #[cfg(all(feature = "d3d12", windows))]
296            RingKind::D3d12(textures) => textures.textures.len(),
297            _ => 0,
298        }
299    }
300
301    /// The textures' size in pixels.
302    #[must_use]
303    pub fn physical_size(&self) -> mln_gfx::Size {
304        match &self.kind {
305            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
306            RingKind::Vulkan(images) => images.size,
307            #[cfg(all(feature = "metal", target_vendor = "apple"))]
308            RingKind::Metal(textures) => textures.size,
309            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
310            RingKind::Gl(textures) => textures.size,
311            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
312            RingKind::WebGpu(textures) => textures.size,
313            #[cfg(all(feature = "d3d12", windows))]
314            RingKind::D3d12(textures) => textures.size,
315            _ => mln_gfx::Size::default(),
316        }
317    }
318
319    /// Whether `device` draws into the ring's depth textures: true for a ring
320    /// without them, or of OpenGL textures, whose names say no format, and
321    /// otherwise whether their format is one of the device's
322    /// [`depth_stencil_formats`](Device::depth_stencil_formats).
323    #[must_use]
324    pub fn takes_depth_on(&self, device: &Device) -> bool {
325        // Irrefutable in a build with OpenGL alone, and refutable in one
326        // with other backends.
327        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
328        if let RingKind::Gl(_) = self.kind {
329            return true;
330        }
331        !self.has_depth()
332            || self.depth_stencil_format().is_some_and(|format| device.depth_stencil_formats().contains(format))
333    }
334
335    /// The format of the ring's depth textures, when it has them and their
336    /// format is a depth and stencil one that an API names.
337    #[must_use]
338    pub fn depth_stencil_format(&self) -> Option<DepthStencilFormat> {
339        match &self.kind {
340            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
341            RingKind::Vulkan(images) => {
342                images.depth.as_ref().and_then(|depth| mln_vulkan::device::depth_stencil_format(depth.format))
343            }
344            #[cfg(all(feature = "metal", target_vendor = "apple"))]
345            RingKind::Metal(textures) => (textures.depth_pixel_format()
346                == Some(mln_mtl::objc2_metal::MTLPixelFormat::Depth32Float_Stencil8))
347            .then_some(DepthStencilFormat::Depth32FloatStencil8),
348            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
349            RingKind::WebGpu(textures) => {
350                textures.depth_textures.first().and_then(|texture| mln_webgpu::depth_stencil_format(texture.format()))
351            }
352            #[cfg(all(feature = "d3d12", windows))]
353            RingKind::D3d12(textures) => textures.depth_format().and_then(mln_d3d12::depth_stencil_format),
354            _ => None,
355        }
356    }
357
358    /// Whether the ring has depth textures.
359    #[must_use]
360    pub fn has_depth(&self) -> bool {
361        match &self.kind {
362            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
363            RingKind::Vulkan(images) => images.depth.is_some(),
364            #[cfg(all(feature = "metal", target_vendor = "apple"))]
365            RingKind::Metal(textures) => !textures.depth_textures.is_empty(),
366            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
367            RingKind::Gl(textures) => !textures.depth_textures.is_empty(),
368            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
369            RingKind::WebGpu(textures) => !textures.depth_textures.is_empty(),
370            #[cfg(all(feature = "d3d12", windows))]
371            RingKind::D3d12(textures) => !textures.depth_textures.is_empty(),
372            _ => false,
373        }
374    }
375
376    /// Whether the texture at `slot` is the one at `other`'s `other_slot`.
377    #[cfg_attr(target_family = "wasm", expect(unused_variables, reason = "the browser build borrows no ring"))]
378    pub(crate) fn same_texture(&self, slot: usize, other: &BorrowedRing, other_slot: usize) -> bool {
379        match (&self.kind, &other.kind) {
380            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
381            (RingKind::Vulkan(images), RingKind::Vulkan(others)) => images
382                .images
383                .get(slot)
384                .zip(others.images.get(other_slot))
385                .is_some_and(|(image, other)| image.image == other.image),
386            #[cfg(all(feature = "metal", target_vendor = "apple"))]
387            (RingKind::Metal(textures), RingKind::Metal(others)) => {
388                textures.textures.get(slot).zip(others.textures.get(other_slot)).is_some_and(|(texture, other)| {
389                    std::ptr::eq(
390                        mln_mtl::objc2::rc::Retained::as_ptr(texture),
391                        mln_mtl::objc2::rc::Retained::as_ptr(other),
392                    )
393                })
394            }
395            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
396            (RingKind::Gl(textures), RingKind::Gl(others)) => {
397                textures.textures.get(slot).is_some_and(|texture| others.textures.get(other_slot) == Some(texture))
398            }
399            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
400            (RingKind::WebGpu(textures), RingKind::WebGpu(others)) => {
401                textures.textures.get(slot).is_some_and(|texture| others.textures.get(other_slot) == Some(texture))
402            }
403            #[cfg(all(feature = "d3d12", windows))]
404            (RingKind::D3d12(textures), RingKind::D3d12(others)) => {
405                textures.textures.get(slot).is_some_and(|texture| others.textures.get(other_slot) == Some(texture))
406            }
407            _ => false,
408        }
409    }
410
411    /// The texture at `slot`, which sessions on `device` render into.
412    #[cfg_attr(target_family = "wasm", expect(unused_variables, reason = "the browser build borrows no ring"))]
413    #[must_use]
414    pub fn texture(&self, slot: usize, device: &Device) -> Option<FrameTexture> {
415        match (&self.kind, device) {
416            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
417            (RingKind::Vulkan(images), Device::Vulkan(device)) => {
418                use mln_vulkan::ash::vk::Handle as _;
419                let depth = images.depth.as_ref().and_then(|depth| {
420                    depth.images.get(slot).map(|image| FrameDepth {
421                        texture: NativeTexture::Vulkan {
422                            image: image.image.as_raw(),
423                            view: image.view.as_raw(),
424                            format: depth.format.as_raw(),
425                            layout: depth.final_layout.as_raw(),
426                        },
427                        export: None,
428                    })
429                });
430                images.images.get(slot).map(|image| FrameTexture {
431                    size: images.size,
432                    kind: FrameTextureKind::Vulkan {
433                        image: image.image.as_raw(),
434                        view: image.view.as_raw(),
435                        device: device.raw().device.as_raw(),
436                        format: images.format.as_raw(),
437                        layout: images.final_layout.as_raw(),
438                    },
439                    native: None,
440                    depth,
441                })
442            }
443            #[cfg(all(feature = "metal", target_vendor = "apple"))]
444            (RingKind::Metal(textures), Device::Metal(device)) => {
445                use mln_mtl::objc2::rc::Retained;
446                textures.textures.get(slot).map(|texture| FrameTexture {
447                    size: textures.size,
448                    kind: FrameTextureKind::Metal {
449                        texture: Retained::as_ptr(texture) as usize as u64,
450                        device: Retained::as_ptr(device.device()) as usize as u64,
451                        pixel_format: textures.pixel_format().0 as u64,
452                    },
453                    native: None,
454                    depth: textures.depth_textures.get(slot).zip(textures.depth_pixel_format()).map(
455                        |(depth, pixel_format)| FrameDepth {
456                            texture: NativeTexture::Metal {
457                                texture: Retained::as_ptr(depth) as usize as u64,
458                                pixel_format: pixel_format.0 as u64,
459                            },
460                            export: None,
461                        },
462                    ),
463                })
464            }
465            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
466            // GL_TEXTURE_2D.
467            (RingKind::Gl(textures), Device::Gl(_)) => textures.textures.get(slot).map(|&texture| FrameTexture {
468                size: textures.size,
469                kind: FrameTextureKind::OpenGl { texture, target: 0x0DE1 },
470                native: None,
471                depth: textures.depth_textures.get(slot).map(|&depth| FrameDepth {
472                    texture: NativeTexture::OpenGl { texture: depth, target: 0x0DE1, internal_format: 0 },
473                    export: None,
474                }),
475            }),
476            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
477            (RingKind::WebGpu(textures), Device::WebGpu(_)) => textures.textures.get(slot).map(|_| FrameTexture {
478                size: textures.size,
479                kind: FrameTextureKind::WebGpu,
480                native: None,
481                depth: (!textures.depth_textures.is_empty())
482                    .then_some(FrameDepth { texture: NativeTexture::WebGpu, export: None }),
483            }),
484            #[cfg(all(feature = "d3d12", windows))]
485            (RingKind::D3d12(textures), Device::D3d12(device)) => {
486                use mln_d3d12::windows::core::Interface as _;
487                let depth =
488                    textures.depth_textures.get(slot).zip(textures.depth_format()).map(|(depth, format)| FrameDepth {
489                        texture: NativeTexture::D3d12 {
490                            resource: depth.as_raw() as usize as u64,
491                            format: format.0 as u32,
492                            state: textures.depth_state.0 as u32,
493                        },
494                        export: None,
495                    });
496                textures.textures.get(slot).map(|texture| FrameTexture {
497                    size: textures.size,
498                    kind: FrameTextureKind::D3d12 {
499                        resource: texture.as_raw() as usize as u64,
500                        device: device.device().as_raw() as usize as u64,
501                        format: textures.format().0 as u32,
502                        state: textures.state.0 as u32,
503                    },
504                    native: None,
505                    depth,
506                })
507            }
508            _ => None,
509        }
510    }
511}
512
513/// What a surface session presents to.
514///
515/// In the browser, a canvas's surface stays on the instance's thread, as
516/// its canvas does.
517pub struct Surface {
518    pub(crate) kind: SurfaceKind,
519    /// Whether presenting waits for the display: see
520    /// [`without_frame_rate_cap`](Self::without_frame_rate_cap).
521    pub(crate) cap_frame_rate: bool,
522}
523
524/// What a host draws over each frame that a surface session presents, after
525/// the map and before the frame is presented (and read back): the overlay
526/// of the backend that the session presents with
527/// ([`DriverWork::set_overlay`](crate::DriverWork::set_overlay)).
528pub enum SurfaceOverlay {
529    #[cfg(feature = "webgpu")]
530    WebGpu(mln_webgpu::Overlay),
531    #[cfg(all(feature = "metal", target_vendor = "apple"))]
532    Metal(mln_mtl::surface_target::Overlay),
533    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
534    Vulkan(Box<dyn mln_vulkan::Overlay>),
535    #[cfg(all(feature = "d3d12", windows))]
536    D3d12(Box<dyn mln_d3d12::Overlay>),
537    #[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
538    Gl(mln_gl::Overlay),
539}
540
541pub(crate) enum SurfaceKind {
542    Window(Arc<dyn Window>),
543    #[cfg(all(feature = "metal", target_vendor = "apple"))]
544    MetalLayer(mln_mtl::Layer),
545    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
546    Wgpu(wgpu::Surface<'static>),
547    /// The host's `VkSurfaceKHR`, of the instance of the session's device.
548    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
549    Vulkan(mln_vulkan::HostSurface),
550    /// The host's `EGLSurface`, of the display of the session's device.
551    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
552    Gl(mln_gl::HostSurface),
553    /// What shows a D3D12 composition swap chain: a `DirectComposition`
554    /// visual or a XAML `SwapChainPanel`, and the thread that made the
555    /// surface, which a `SwapChainPanel` takes its swap chain on.
556    #[cfg(all(feature = "d3d12", windows))]
557    D3d12Composition {
558        composition: mln_d3d12::Composition,
559        thread: std::thread::ThreadId,
560    },
561    /// In the browser, an `OffscreenCanvas` or an `HTMLCanvasElement`, on
562    /// the instance's one thread.
563    #[cfg(target_family = "wasm")]
564    WebCanvas {
565        canvas: wasm_bindgen::JsValue,
566        format: Option<CanvasFormat>,
567    },
568}
569
570/// A `GPUTextureFormat` that a WebGPU canvas takes.
571#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
572pub enum CanvasFormat {
573    /// `bgra8unorm`.
574    Bgra8Unorm,
575    /// `rgba8unorm`.
576    Rgba8Unorm,
577    /// `rgba16float`.
578    Rgba16Float,
579}
580
581impl CanvasFormat {
582    /// The format by its `GPUTextureFormat` name, if a canvas takes it.
583    #[must_use]
584    pub fn from_name(name: &str) -> Option<CanvasFormat> {
585        match name {
586            "bgra8unorm" => Some(CanvasFormat::Bgra8Unorm),
587            "rgba8unorm" => Some(CanvasFormat::Rgba8Unorm),
588            "rgba16float" => Some(CanvasFormat::Rgba16Float),
589            _ => None,
590        }
591    }
592}
593
594impl Surface {
595    fn of(kind: SurfaceKind) -> Surface {
596        Surface { kind, cap_frame_rate: true }
597    }
598
599    /// The surface, presenting frames as they finish instead of one per
600    /// refresh of the display, where the backend and the surface can: a
601    /// benchmark's way to measure frame times. Metal on macOS, Vulkan,
602    /// WebGPU outside the browser and OpenGL on a window take it; the
603    /// others keep the display's pace.
604    #[must_use]
605    pub fn without_frame_rate_cap(self) -> Surface {
606        Surface { cap_frame_rate: false, ..self }
607    }
608
609    /// A window, which the session makes its surface on. The window must
610    /// outlive the session's use of it: until a
611    /// [`set_surface`](crate::RenderSession::set_surface) or
612    /// [`release_target`](crate::RenderSession::release_target) replaces it,
613    /// or the session detaches or is abandoned.
614    ///
615    /// On Apple platforms, the session presents to a `CAMetalLayer` that it
616    /// puts in the window's view, which only the main thread may do: attach
617    /// the window with [`Driver::CallerThread`], serviced there, or make the
618    /// layer yourself and attach `Surface::metal_layer`.
619    pub fn window(window: impl Window + 'static) -> Surface {
620        Surface::of(SurfaceKind::Window(Arc::new(window)))
621    }
622
623    /// In the browser, a canvas that the session presents to with its
624    /// device's backend: an `OffscreenCanvas`, such as one that the page
625    /// transferred to the instance's Web Worker, or an `HTMLCanvasElement`
626    /// when the instance runs on the page's thread. The session makes the
627    /// canvas's "webgpu" or "webgl2" context, and sizes the canvas to the
628    /// target's size at the map's scale factor. Without a device, it renders
629    /// with the browser's WebGPU where the build has it, and with WebGL2
630    /// otherwise.
631    ///
632    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for
633    /// anything else.
634    ///
635    /// A WebGPU session configures the canvas with `format`, or else with a
636    /// format that its device's adapter prefers. Other backends ignore it.
637    #[cfg(target_family = "wasm")]
638    pub fn web_canvas(canvas: wasm_bindgen::JsValue, format: Option<CanvasFormat>) -> Result<Surface, Error> {
639        use wasm_bindgen::JsCast as _;
640        if !canvas.is_instance_of::<web_sys::OffscreenCanvas>()
641            && !canvas.is_instance_of::<web_sys::HtmlCanvasElement>()
642        {
643            return Err(Error::invalid_argument("a web canvas is an OffscreenCanvas or an HTMLCanvasElement"));
644        }
645        Ok(Surface::of(SurfaceKind::WebCanvas { canvas, format }))
646    }
647
648    /// A `CAMetalLayer`, which a session on Metal presents to. It must
649    /// outlive the session's use of it, as a window must.
650    #[cfg(all(feature = "metal", target_vendor = "apple"))]
651    #[must_use]
652    pub fn metal_layer(layer: mln_mtl::Layer) -> Surface {
653        Surface::of(SurfaceKind::MetalLayer(layer))
654    }
655
656    /// A surface that the host made with the instance of the WebGPU
657    /// [`Device`] that the session renders on.
658    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
659    pub fn wgpu(surface: wgpu::Surface<'static>) -> Surface {
660        Surface::of(SurfaceKind::Wgpu(surface))
661    }
662
663    /// The host's `VkSurfaceKHR`, which a session on the Vulkan device
664    /// whose instance made it presents to. The surface stays the host's.
665    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
666    #[must_use]
667    pub fn vulkan(surface: mln_vulkan::HostSurface) -> Surface {
668        Surface::of(SurfaceKind::Vulkan(surface))
669    }
670
671    /// The host's `EGLSurface`, which a session on the OpenGL device that
672    /// wraps the host's context presents to. The surface stays the host's.
673    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
674    #[must_use]
675    pub fn gl(surface: mln_gl::HostSurface) -> Surface {
676        Surface::of(SurfaceKind::Gl(surface))
677    }
678
679    /// A composition swap chain that a session on D3D12 makes and presents
680    /// to, which `composition` shows: a `DirectComposition` visual shows it
681    /// once the host commits its device after the attach, and a XAML
682    /// `SwapChainPanel` at once. The composition must outlive the session's
683    /// use of it, as a window must. The swap chain has the target's size in
684    /// pixels, with premultiplied alpha; the host scales its visual for the
685    /// display's scale factor.
686    ///
687    /// A `SwapChainPanel` takes its swap chain only on its UI thread: make
688    /// the surface there, and attach it with [`Driver::CallerThread`],
689    /// serviced on that thread. A session that makes its swap chain on
690    /// another thread fails with
691    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind).
692    #[cfg(all(feature = "d3d12", windows))]
693    #[must_use]
694    pub fn d3d12_composition(composition: mln_d3d12::Composition) -> Surface {
695        Surface::of(SurfaceKind::D3d12Composition { composition, thread: std::thread::current().id() })
696    }
697
698    /// The backend of the device whose instance or share group a host's
699    /// surface is of, or `None` for a window or layer.
700    #[must_use]
701    pub fn host_backend(&self) -> Option<BackendType> {
702        match self.kind {
703            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
704            SurfaceKind::Vulkan(_) => Some(BackendType::Vulkan),
705            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
706            SurfaceKind::Gl(_) => Some(BackendType::OpenGL),
707            _ => None,
708        }
709    }
710
711    /// The surface again, if it is a window, or a surface that a new
712    /// backend presents to.
713    pub(crate) fn clone_window(&self) -> Option<Surface> {
714        let kind = match &self.kind {
715            SurfaceKind::Window(window) => SurfaceKind::Window(Arc::clone(window)),
716            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
717            SurfaceKind::Gl(surface) => SurfaceKind::Gl(*surface),
718            _ => return None,
719        };
720        Some(Surface { kind, cap_frame_rate: self.cap_frame_rate })
721    }
722
723    /// Fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a
724    /// window that has no area to present to: a minimized Win32 window, or
725    /// one whose client area is empty ([`mln_gfx::window::has_area`]).
726    pub(crate) fn check_area(&self) -> Result<(), Error> {
727        if let SurfaceKind::Window(window) = &self.kind
728            && !mln_gfx::window::has_area(&**window)
729        {
730            return Err(Error::invalid_state("the window is minimized or has no client area"));
731        }
732        Ok(())
733    }
734
735    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
736    /// Win32 window whose pixel format isn't the library's when OpenGL
737    /// presents to it: on `device`, or without a device, in a build whose
738    /// first backend is OpenGL. Windows doesn't let a pixel format change.
739    /// A session that falls back to OpenGL because Vulkan and D3D12 are
740    /// missing finds out as it starts.
741    #[cfg_attr(
742        not(all(feature = "gl", windows)),
743        expect(clippy::unnecessary_wraps, reason = "only OpenGL on Windows checks the window's pixel format")
744    )]
745    pub(crate) fn check_pixel_format(&self, device: Option<&Device>) -> Result<(), Error> {
746        #[cfg(all(feature = "gl", windows))]
747        if let SurfaceKind::Window(window) = &self.kind
748            && device.map_or(cfg!(not(any(feature = "vulkan", feature = "d3d12"))), |device| {
749                device.backend() == BackendType::OpenGL
750            })
751        {
752            mln_gl::SurfaceTarget::check_window(&**window).map_err(gfx_error)?;
753        }
754        #[cfg(not(all(feature = "gl", windows)))]
755        let _ = (self, device);
756        Ok(())
757    }
758
759    /// The window, for a surface of one.
760    pub(crate) fn host_window(&self) -> Option<Arc<dyn Window>> {
761        match &self.kind {
762            SurfaceKind::Window(window) => Some(Arc::clone(window)),
763            _ => None,
764        }
765    }
766
767    /// Whether the session can make the surface without the host's device.
768    pub(crate) fn needs_no_device(&self) -> bool {
769        match self.kind {
770            SurfaceKind::Window(_) => true,
771            #[cfg(all(feature = "metal", target_vendor = "apple"))]
772            SurfaceKind::MetalLayer(_) => true,
773            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
774            SurfaceKind::Wgpu(_) => false,
775            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
776            SurfaceKind::Vulkan(_) => false,
777            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
778            SurfaceKind::Gl(_) => false,
779            #[cfg(all(feature = "d3d12", windows))]
780            SurfaceKind::D3d12Composition { .. } => true,
781            #[cfg(target_family = "wasm")]
782            SurfaceKind::WebCanvas { .. } => true,
783        }
784    }
785}
786
787/// A surface on its way to the worker of a session, which takes it on the
788/// session's thread.
789///
790/// In the browser, a canvas waits on the instance's thread, in the
791/// session's side there (`crate::web`), and the surface carries its key.
792#[cfg(not(target_family = "wasm"))]
793pub(crate) struct SentSurface(Surface);
794
795/// A surface on its way to the worker of a session, which takes it on the
796/// session's thread.
797///
798/// In the browser, a canvas waits on the instance's thread, in the
799/// session's side there (`crate::web`), and the surface carries its key.
800#[cfg(target_family = "wasm")]
801pub(crate) enum SentSurface {
802    Window(Arc<dyn Window>),
803    WebCanvas { canvas: crate::web::HandedCanvas, format: Option<CanvasFormat> },
804}
805
806impl SentSurface {
807    /// `surface`, on its way to the worker of session `session`.
808    pub(crate) fn new(surface: Surface, session: super::SessionId) -> SentSurface {
809        #[cfg(not(target_family = "wasm"))]
810        {
811            let _ = session;
812            SentSurface(surface)
813        }
814        #[cfg(target_family = "wasm")]
815        match surface.kind {
816            SurfaceKind::Window(window) => SentSurface::Window(window),
817            SurfaceKind::WebCanvas { canvas, format } => {
818                SentSurface::WebCanvas { canvas: crate::web::hand_canvas(session, canvas), format }
819            }
820        }
821    }
822
823    /// The surface, on the session's thread. In the browser, fails with
824    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) when its canvas no
825    /// longer waits there.
826    #[cfg_attr(
827        not(target_family = "wasm"),
828        expect(clippy::unnecessary_wraps, reason = "only the browser's canvases wait for their session's thread")
829    )]
830    pub(crate) fn receive(self) -> Result<Surface, Error> {
831        #[cfg(not(target_family = "wasm"))]
832        {
833            Ok(self.0)
834        }
835        #[cfg(target_family = "wasm")]
836        match self {
837            SentSurface::Window(window) => Ok(Surface::of(SurfaceKind::Window(window))),
838            SentSurface::WebCanvas { canvas, format } => {
839                let canvas = canvas.take().ok_or_else(|| Error::invalid_state("the surface's canvas is gone"))?;
840                Ok(Surface::of(SurfaceKind::WebCanvas { canvas, format }))
841            }
842        }
843    }
844
845    /// In the browser, whether a session without a device presents to the
846    /// surface with WebGPU.
847    #[cfg(target_family = "wasm")]
848    pub(crate) fn presents_with_web_gpu(&self) -> bool {
849        matches!(self, SentSurface::WebCanvas { .. }) && cfg!(feature = "webgpu")
850    }
851}
852
853impl std::fmt::Debug for Surface {
854    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
855        f.debug_struct("Surface").finish_non_exhaustive()
856    }
857}
858
859/// A GPU that sessions on many maps and threads share: one backend's
860/// device. Sessions on it keep working after the last handle drops, until
861/// they detach.
862#[derive(Clone, Debug)]
863#[non_exhaustive]
864pub enum Device {
865    /// A WebGPU device: the library's, through wgpu, or the host's
866    /// (`Device::webgpu`). In the browser, the browser's
867    /// (`Device::request_web_gpu`).
868    #[cfg(feature = "webgpu")]
869    WebGpu(mln_webgpu::Device),
870    /// A Metal device and command queue.
871    #[cfg(all(feature = "metal", target_vendor = "apple"))]
872    Metal(mln_mtl::Device),
873    /// A Vulkan GPU.
874    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
875    Vulkan(mln_vulkan::Device),
876    /// A D3D12 device and its direct queue.
877    #[cfg(all(feature = "d3d12", windows))]
878    D3d12(mln_d3d12::Device),
879    /// An OpenGL share group, or the one context that its sessions take
880    /// turns in.
881    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
882    Gl(mln_gl::Device),
883    /// In the browser, WebGL2: each session renders with the context of its
884    /// canvas, which it makes unless the host made one ([`Device::web_gl`]).
885    #[cfg(all(feature = "gl", target_family = "wasm"))]
886    WebGl,
887}
888
889/// How to create a [`Device`].
890#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
891pub struct DeviceOptions {
892    /// The GPU to use. `None` picks the default one.
893    pub adapter: Option<Adapter>,
894    /// The API that an OpenGL device renders with. Only Linux's and
895    /// FreeBSD's EGL renders desktop OpenGL, and Windows' WGL renders it
896    /// only. Other backends ignore it.
897    pub gl_api: GlApi,
898    /// Whether the sessions of an OpenGL device take turns in one context
899    /// instead of having one each. Other backends ignore it.
900    pub gl_single_context: bool,
901}
902
903/// The OpenGL API that an OpenGL device renders with. By default the
904/// platform's: desktop OpenGL on Windows, and OpenGL ES elsewhere.
905#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
906pub enum GlApi {
907    /// OpenGL ES 3.0 or later.
908    Gles,
909    /// Desktop OpenGL 3.3 or later.
910    Gl,
911}
912
913impl Default for GlApi {
914    fn default() -> GlApi {
915        if cfg!(windows) { GlApi::Gl } else { GlApi::Gles }
916    }
917}
918
919/// A GPU, by what names it to a backend.
920#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
921pub enum Adapter {
922    /// An index into the backend's list of GPUs.
923    Index(usize),
924    /// The GPU's 16-byte UUID, as Vulkan's
925    /// `VkPhysicalDeviceIDProperties.deviceUUID` reports it.
926    Uuid([u8; 16]),
927    /// The GPU's 8-byte LUID, as Vulkan's
928    /// `VkPhysicalDeviceIDProperties.deviceLUID` reports it: on Windows, its
929    /// DXGI adapter's.
930    Luid([u8; 8]),
931}
932
933/// A kind of window or layer that a session presents to.
934#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
935#[non_exhaustive]
936pub enum SurfaceType {
937    /// A `CAMetalLayer`.
938    MetalLayer,
939    /// A Win32 window.
940    Win32,
941    /// An X11 window, through Xlib.
942    Xlib,
943    /// An X11 window, through XCB.
944    Xcb,
945    /// A Wayland surface.
946    Wayland,
947    /// An Android `ANativeWindow`.
948    AndroidNdk,
949    /// An `OpenHarmony` `OHNativeWindow`.
950    OhosNdk,
951}
952
953impl SurfaceType {
954    /// Whether a device of `backend` presents to the surfaces of this type
955    /// on this platform, in this build.
956    #[must_use]
957    pub fn presents_with(self, backend: BackendType) -> bool {
958        let windowing = match self {
959            SurfaceType::MetalLayer => false,
960            SurfaceType::Win32 => cfg!(windows),
961            SurfaceType::Xlib | SurfaceType::Xcb | SurfaceType::Wayland => {
962                cfg!(all(unix, not(target_vendor = "apple"), not(target_os = "android"), not(target_env = "ohos")))
963            }
964            SurfaceType::AndroidNdk => cfg!(target_os = "android"),
965            SurfaceType::OhosNdk => cfg!(target_env = "ohos"),
966        };
967        match backend {
968            BackendType::Metal => {
969                cfg!(all(feature = "metal", target_vendor = "apple")) && self == SurfaceType::MetalLayer
970            }
971            BackendType::Vulkan => {
972                cfg!(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm")))) && windowing
973            }
974            // EGL presents to these windows, and on Windows WGL to Win32
975            // windows.
976            BackendType::OpenGL => {
977                cfg!(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))
978                    && windowing
979                    && matches!(
980                        self,
981                        SurfaceType::Win32
982                            | SurfaceType::Xlib
983                            | SurfaceType::Wayland
984                            | SurfaceType::AndroidNdk
985                            | SurfaceType::OhosNdk
986                    )
987            }
988            // wgpu's Vulkan backend makes no OpenHarmony surface, and this
989            // build has no wgpu GLES backend.
990            BackendType::WebGPU => {
991                cfg!(all(feature = "webgpu", not(target_family = "wasm"))) && windowing && self != SurfaceType::OhosNdk
992            }
993            BackendType::D3D12 => cfg!(all(feature = "d3d12", windows)) && self == SurfaceType::Win32,
994        }
995    }
996
997    /// The Vulkan instance extension that makes the surfaces of this type.
998    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
999    fn vulkan_extension(self) -> Option<&'static std::ffi::CStr> {
1000        use mln_vulkan::ash::khr;
1001        match self {
1002            SurfaceType::MetalLayer => None,
1003            SurfaceType::Win32 => Some(khr::win32_surface::NAME),
1004            SurfaceType::Xlib => Some(khr::xlib_surface::NAME),
1005            SurfaceType::Xcb => Some(khr::xcb_surface::NAME),
1006            SurfaceType::Wayland => Some(khr::wayland_surface::NAME),
1007            SurfaceType::AndroidNdk => Some(khr::android_surface::NAME),
1008            SurfaceType::OhosNdk => Some(mln_vulkan::device::OHOS_SURFACE),
1009        }
1010    }
1011
1012    /// Whether a device of any backend of this build presents to the
1013    /// surfaces of this type.
1014    #[must_use]
1015    pub fn presents_with_any(self) -> bool {
1016        [BackendType::Metal, BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
1017            .into_iter()
1018            .any(|backend| self.presents_with(backend))
1019    }
1020
1021    /// Whether a session of this build presents to the surfaces of this
1022    /// type without the host's device: on the device that a surface session
1023    /// makes when it gets none.
1024    #[must_use]
1025    pub fn presents_without_device(self) -> bool {
1026        match self {
1027            SurfaceType::MetalLayer => self.presents_with(BackendType::Metal),
1028            _ => [BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
1029                .into_iter()
1030                .any(|backend| self.presents_with(backend)),
1031        }
1032    }
1033}
1034
1035/// Whether a backend that failed with `error` is missing, so the next one
1036/// may take its place.
1037#[cfg(not(target_family = "wasm"))]
1038fn missing(error: &Error) -> bool {
1039    error.kind == mln_util::ErrorKind::Unsupported
1040}
1041
1042/// A session's hold on what its [`Device`] shares with the host: a Vulkan
1043/// device's hold on the host's queue lock. [`DeviceLease::revoke`] ends it.
1044#[derive(Debug, Default)]
1045pub(crate) struct DeviceLease {
1046    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1047    queue: Option<mln_vulkan::QueueLease>,
1048}
1049
1050impl DeviceLease {
1051    /// Ends the hold: the leased device calls the host's queue lock no more,
1052    /// and lets go of it.
1053    #[cfg_attr(
1054        not(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm")))),
1055        expect(clippy::unused_self, reason = "only a Vulkan device holds the host's queue lock")
1056    )]
1057    pub(crate) fn revoke(&self) {
1058        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1059        if let Some(queue) = &self.queue {
1060            queue.revoke();
1061        }
1062    }
1063}
1064
1065impl Device {
1066    /// The device for one session, and the session's lease on it, which
1067    /// ends the session's hold on what the device shares with the host when
1068    /// the session lets go of the device without dropping it: an abandon
1069    /// that keeps its graphics objects.
1070    pub(crate) fn lease(self) -> (Device, DeviceLease) {
1071        match self {
1072            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1073            Device::Vulkan(device) => {
1074                let (device, queue) = device.lease();
1075                (Device::Vulkan(device), DeviceLease { queue: Some(queue) })
1076            }
1077            device => (device, DeviceLease::default()),
1078        }
1079    }
1080
1081    /// Why the device was lost, once the library's WebGPU device is: the
1082    /// failure of the sessions that render on it.
1083    pub(crate) fn lost(&self) -> Option<Error> {
1084        match *self {
1085            #[cfg(feature = "webgpu")]
1086            Device::WebGpu(ref device) => device.lost().map(|message| Error::target_lost(message.to_owned())),
1087            _ => None,
1088        }
1089    }
1090
1091    /// Whether an abandon keeps a session's graphics objects on the device
1092    /// until the process exits, which only a detach frees: OpenGL's and
1093    /// WebGPU's, as the C API promises, since only the session's own thread
1094    /// may destroy them, and the host's graphics objects behind them may be
1095    /// going away.
1096    pub(crate) fn abandon_keeps_graphics(&self) -> bool {
1097        match *self {
1098            #[cfg(feature = "webgpu")]
1099            Device::WebGpu(_) => true,
1100            #[cfg(all(feature = "metal", target_vendor = "apple"))]
1101            Device::Metal(_) => false,
1102            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1103            Device::Vulkan(_) => false,
1104            #[cfg(all(feature = "d3d12", windows))]
1105            Device::D3d12(_) => false,
1106            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
1107            Device::Gl(_) => true,
1108            #[cfg(all(feature = "gl", target_family = "wasm"))]
1109            Device::WebGl => true,
1110        }
1111    }
1112
1113    /// The library's device, on the platform's native backend: Metal on
1114    /// Apple's platforms, and Vulkan elsewhere, then D3D12 on Windows, or
1115    /// OpenGL where there is neither, and last WebGPU (wgpu) in a build with
1116    /// the `webgpu` feature. A backend that can't name the GPU that
1117    /// `options` names is skipped: only Vulkan names one by UUID, and only
1118    /// Vulkan and D3D12 by LUID. OpenGL lists one GPU, the one its
1119    /// display renders on, at index 0.
1120    /// So is OpenGL where it can't render with `options.gl_api`.
1121    ///
1122    /// Fails with [`ErrorKind::NotFound`](mln_util::ErrorKind) when
1123    /// the options name no GPU, with
1124    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) when no backend has a
1125    /// GPU or in the browser, where a session renders on the page's device,
1126    /// and with [`ErrorKind::Native`](mln_util::ErrorKind) when the GPU
1127    /// can't create the device.
1128    pub fn new(options: DeviceOptions) -> Result<Device, Error> {
1129        #[cfg(target_family = "wasm")]
1130        {
1131            let _ = options;
1132            Err(Error::unsupported("the browser has no library devices"))
1133        }
1134        #[cfg(not(target_family = "wasm"))]
1135        {
1136            let mut error = Error::unsupported("this build has no backend");
1137            for backend in Self::native_order() {
1138                match Self::with_backend(*backend, options) {
1139                    Ok(device) => return Ok(device),
1140                    Err(e) if missing(&e) => error = e,
1141                    Err(e) => return Err(e),
1142                }
1143            }
1144            Err(error)
1145        }
1146    }
1147
1148    /// The library's device on `backend`.
1149    ///
1150    /// Fails as [`new`](Self::new) does, and with
1151    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a backend that
1152    /// isn't in this build or on this platform.
1153    ///
1154    /// In the browser, only OpenGL's: `Device::WebGl`. The browser makes
1155    /// a WebGPU device asynchronously (`Device::request_web_gpu`).
1156    pub fn with_backend(backend: BackendType, options: DeviceOptions) -> Result<Device, Error> {
1157        let DeviceOptions { adapter, gl_api, gl_single_context } = options;
1158        // Only Vulkan names its GPUs by ID here, and D3D12 by LUID.
1159        let index = |adapter: Option<Adapter>| match adapter {
1160            None => Ok(None),
1161            Some(Adapter::Index(index)) => Ok(Some(index)),
1162            Some(_) => Err(Error::unsupported(format!("{backend:?} names no GPU by UUID or LUID"))),
1163        };
1164        match backend {
1165            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
1166            BackendType::WebGPU => mln_webgpu::Device::new(index(adapter)?).map(Device::WebGpu).map_err(gfx_error),
1167            #[cfg(all(feature = "metal", target_vendor = "apple"))]
1168            BackendType::Metal => mln_mtl::Device::new(index(adapter)?).map(Device::Metal).map_err(gfx_error),
1169            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1170            BackendType::Vulkan => match adapter {
1171                Some(Adapter::Uuid(uuid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Uuid(uuid)),
1172                Some(Adapter::Luid(luid)) => mln_vulkan::Device::with_adapter_id(mln_vulkan::AdapterId::Luid(luid)),
1173                _ => mln_vulkan::Device::new(index(adapter)?),
1174            }
1175            .map(Device::Vulkan)
1176            .map_err(gfx_error),
1177            #[cfg(all(feature = "d3d12", windows))]
1178            BackendType::D3D12 => match adapter {
1179                Some(Adapter::Luid(luid)) => mln_d3d12::Device::with_luid(luid),
1180                Some(Adapter::Uuid(_)) => Err(mln_gfx::Error::unsupported("D3D12 names no GPU by UUID")),
1181                _ => mln_d3d12::Device::new(index(adapter)?),
1182            }
1183            .map(Device::D3d12)
1184            .map_err(gfx_error),
1185            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
1186            BackendType::OpenGL => {
1187                // An OpenGL device renders on the one GPU of its display, so
1188                // its list of GPUs holds that one.
1189                match index(adapter)? {
1190                    None | Some(0) => {}
1191                    Some(index) => {
1192                        return Err(Error::not_found(format!("adapter_index {index} is past OpenGL's one GPU")));
1193                    }
1194                }
1195                let api = match gl_api {
1196                    GlApi::Gles => mln_gl::Api::Gles,
1197                    GlApi::Gl => mln_gl::Api::Gl,
1198                };
1199                let options = mln_gl::DeviceOptions { api, single_context: gl_single_context };
1200                mln_gl::Device::with_options(options).map(Device::Gl).map_err(gfx_error)
1201            }
1202            #[cfg(all(feature = "gl", target_family = "wasm"))]
1203            BackendType::OpenGL if adapter.is_none() => Ok(Device::WebGl),
1204            _ => {
1205                let _ = (index, adapter, gl_api, gl_single_context);
1206                Err(Error::unsupported(format!("this build has no {backend:?} backend")))
1207            }
1208        }
1209    }
1210
1211    /// The kinds of sync with which the host can wait for a frame of `ring`
1212    /// on the device (the producer's), and with which a session waits for
1213    /// the host's reads (the consumer's).
1214    ///
1215    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
1216    /// device can't render into the ring: one of another backend, or one the
1217    /// device lacks a feature for.
1218    pub fn borrowed_sync_kinds(&self, ring: &BorrowedRing) -> Result<(SyncKinds, SyncKinds), Error> {
1219        match (self, &ring.kind) {
1220            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1221            (Device::Vulkan(device), RingKind::Vulkan(images)) => {
1222                images.check(device).map_err(gfx_error)?;
1223                Ok(device.sync_kinds())
1224            }
1225            #[cfg(all(feature = "metal", target_vendor = "apple"))]
1226            (Device::Metal(device), RingKind::Metal(textures)) => {
1227                textures.check(device).map_err(gfx_error)?;
1228                Ok(mln_mtl::BorrowedTextures::sync_kinds(device))
1229            }
1230            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
1231            (Device::Gl(device), RingKind::Gl(_)) => {
1232                if !device.is_host() {
1233                    return Err(Error::unsupported(
1234                        "an OpenGL ring renders on a device in the share group of the host's context",
1235                    ));
1236                }
1237                Ok(mln_gl::BorrowedTextures::sync_kinds())
1238            }
1239            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
1240            (Device::WebGpu(_), RingKind::WebGpu(textures)) => {
1241                textures.check().map_err(gfx_error)?;
1242                Ok(mln_webgpu::BorrowedTextures::sync_kinds())
1243            }
1244            #[cfg(all(feature = "d3d12", windows))]
1245            (Device::D3d12(device), RingKind::D3d12(textures)) => {
1246                textures.check(device).map_err(gfx_error)?;
1247                Ok(mln_d3d12::BorrowedTextures::sync_kinds())
1248            }
1249            _ => Err(Error::unsupported(format!(
1250                "a {:?} device renders into no ring of {:?} textures",
1251                self.backend(),
1252                ring.backend()
1253            ))),
1254        }
1255    }
1256
1257    /// The formats of the depth textures that a borrowed ring takes on the
1258    /// device.
1259    #[must_use]
1260    pub fn depth_stencil_formats(&self) -> DepthStencilFormats {
1261        match *self {
1262            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1263            Device::Vulkan(ref device) => device.depth_stencil_formats(),
1264            #[cfg(all(feature = "d3d12", windows))]
1265            Device::D3d12(_) => mln_d3d12::BorrowedTextures::depth_stencil_formats(),
1266            #[cfg(all(feature = "metal", target_vendor = "apple"))]
1267            Device::Metal(_) => mln_mtl::BorrowedTextures::depth_stencil_formats(),
1268            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
1269            Device::Gl(_) => mln_gl::BorrowedTextures::depth_stencil_formats(),
1270            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
1271            Device::WebGpu(ref device) => mln_webgpu::BorrowedTextures::depth_stencil_formats(device.device()),
1272            #[cfg(target_family = "wasm")]
1273            _ => DepthStencilFormats::NONE,
1274        }
1275    }
1276
1277    /// The kinds of [`export_kinds`](Self::export_kinds) whose rings also
1278    /// share each frame's depth texture, when they keep depth: only
1279    /// [`ExportKind::OpaqueFd`], since an `IOSurface`, a dmabuf or an Android
1280    /// hardware buffer holds no depth format. A ring of those keeps its depth
1281    /// on the device.
1282    #[must_use]
1283    pub fn depth_export_kinds(&self) -> ExportKinds {
1284        match self {
1285            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1286            Device::Vulkan(device) => device.depth_export_kinds(),
1287            _ => ExportKinds::NONE,
1288        }
1289    }
1290
1291    /// The kinds of exported ring that sessions on the device share their
1292    /// images in: those that the device has exported an image of.
1293    #[must_use]
1294    pub fn export_kinds(&self) -> ExportKinds {
1295        match self {
1296            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1297            Device::Vulkan(device) => device.export_kinds(),
1298            #[cfg(all(feature = "metal", target_vendor = "apple"))]
1299            Device::Metal(device) => mln_mtl::exported_target::export_kinds(device),
1300            #[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
1301            Device::Gl(device) => mln_gl::exported_target::export_kinds(device),
1302            #[cfg(all(feature = "d3d12", windows))]
1303            Device::D3d12(device) => device.export_kinds(),
1304            _ => ExportKinds::NONE,
1305        }
1306    }
1307
1308    /// The kind that a session on the device shares `ring`'s images in, and
1309    /// the kinds of sync with which the host can wait for a frame (the
1310    /// producer's) and a session for the host's reads (the consumer's).
1311    ///
1312    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
1313    /// device exports none of the ring's kinds.
1314    pub fn export_plan(&self, ring: &ExportedRing) -> Result<(ExportKind, SyncKinds, SyncKinds), Error> {
1315        match self {
1316            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1317            Device::Vulkan(device) => {
1318                let kind = mln_vulkan::exported_target::plan(device, ring).map_err(gfx_error)?;
1319                let (producer, consumer) = mln_vulkan::exported_target::sync_kinds(device);
1320                Ok((kind, producer, consumer))
1321            }
1322            #[cfg(all(feature = "metal", target_vendor = "apple"))]
1323            Device::Metal(device) => {
1324                let kind = mln_mtl::exported_target::plan(device, ring).map_err(gfx_error)?;
1325                let (producer, consumer) = mln_mtl::exported_target::sync_kinds(device);
1326                Ok((kind, producer, consumer))
1327            }
1328            #[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
1329            Device::Gl(device) => {
1330                let kind = mln_gl::exported_target::plan(device, ring).map_err(gfx_error)?;
1331                let (producer, consumer) = mln_gl::exported_target::sync_kinds(device);
1332                Ok((kind, producer, consumer))
1333            }
1334            #[cfg(all(feature = "d3d12", windows))]
1335            Device::D3d12(device) => {
1336                let kind = mln_d3d12::exported_target::plan(device, ring).map_err(gfx_error)?;
1337                let (producer, consumer) = mln_d3d12::exported_target::sync_kinds();
1338                Ok((kind, producer, consumer))
1339            }
1340            _ => {
1341                let _ = ring;
1342                Err(Error::unsupported(format!("a {:?} device exports no ring", self.backend())))
1343            }
1344        }
1345    }
1346
1347    /// The kinds of sync with which the host can wait for an exported
1348    /// ring's frame (the producer's) and a session for the host's reads (the
1349    /// consumer's), on a device that exports a ring.
1350    #[must_use]
1351    pub fn export_sync_kinds(&self) -> (SyncKinds, SyncKinds) {
1352        if self.export_kinds().is_empty() {
1353            return (SyncKinds::NONE, SyncKinds::NONE);
1354        }
1355        match self {
1356            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1357            Device::Vulkan(device) => mln_vulkan::exported_target::sync_kinds(device),
1358            #[cfg(all(feature = "metal", target_vendor = "apple"))]
1359            Device::Metal(device) => mln_mtl::exported_target::sync_kinds(device),
1360            #[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
1361            Device::Gl(device) => mln_gl::exported_target::sync_kinds(device),
1362            #[cfg(all(feature = "d3d12", windows))]
1363            Device::D3d12(_) => mln_d3d12::exported_target::sync_kinds(),
1364            _ => (SyncKinds::NONE, SyncKinds::NONE),
1365        }
1366    }
1367
1368    /// The library's device for `ring`: on the first of [`new`](Self::new)'s
1369    /// backends whose device exports one of the ring's kinds.
1370    ///
1371    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when no
1372    /// backend's device does, and as [`new`](Self::new) does.
1373    pub fn for_exported_ring(ring: &ExportedRing) -> Result<Device, Error> {
1374        #[cfg(target_family = "wasm")]
1375        {
1376            let _ = ring;
1377            Err(Error::unsupported("the browser has no library devices"))
1378        }
1379        #[cfg(not(target_family = "wasm"))]
1380        {
1381            let mut error = Error::unsupported("no backend of this build exports the ring's kinds of image");
1382            for backend in Self::native_order() {
1383                match Self::with_backend(*backend, DeviceOptions::default()) {
1384                    Ok(device) => match device.export_plan(ring) {
1385                        Ok(_) => return Ok(device),
1386                        Err(e) => error = e,
1387                    },
1388                    Err(e) if missing(&e) => {}
1389                    Err(e) => return Err(e),
1390                }
1391            }
1392            Err(error)
1393        }
1394    }
1395
1396    /// Whether sessions on the device present to the host's own surfaces:
1397    /// a Vulkan device's `VkSurfaceKHR`s, or the `EGLSurface`s of an OpenGL
1398    /// device that wraps the host's context.
1399    #[must_use]
1400    pub fn presents_to_host_surfaces(&self) -> bool {
1401        match self {
1402            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1403            Device::Vulkan(device) => device.presents(),
1404            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
1405            Device::Gl(device) => device.is_host(),
1406            _ => false,
1407        }
1408    }
1409
1410    /// Whether sessions on the device present to the surfaces of
1411    /// `surface`'s type: a Vulkan device's instance needs the type's surface
1412    /// extension, which the loader may lack.
1413    #[must_use]
1414    pub fn presents_to(&self, surface: SurfaceType) -> bool {
1415        if !surface.presents_with(self.backend()) {
1416            return false;
1417        }
1418        match self {
1419            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1420            Device::Vulkan(device) => surface.vulkan_extension().is_some_and(|name| device.presents_through(name)),
1421            _ => true,
1422        }
1423    }
1424
1425    /// The backends [`new`](Self::new) tries, in order. Vulkan comes before
1426    /// D3D12 on Windows, as it renders frames faster on the GPUs measured.
1427    #[cfg(not(target_family = "wasm"))]
1428    fn native_order() -> &'static [BackendType] {
1429        if cfg!(target_vendor = "apple") {
1430            &[BackendType::Metal, BackendType::WebGPU]
1431        } else if cfg!(windows) {
1432            &[BackendType::Vulkan, BackendType::D3D12, BackendType::OpenGL, BackendType::WebGPU]
1433        } else {
1434            &[BackendType::Vulkan, BackendType::OpenGL, BackendType::WebGPU]
1435        }
1436    }
1437
1438    /// The host's WebGPU device and queue, which `instance` made. The
1439    /// session configures its surfaces with `format`, which each surface
1440    /// must support.
1441    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
1442    #[must_use]
1443    pub fn webgpu(
1444        instance: wgpu::Instance,
1445        device: wgpu::Device,
1446        queue: wgpu::Queue,
1447        format: wgpu::TextureFormat,
1448    ) -> Device {
1449        Device::WebGpu(mln_webgpu::Device::from_wgpu(Some(instance), device, queue, Some(format)))
1450    }
1451
1452    /// The backend the device is of.
1453    #[must_use]
1454    pub fn backend(&self) -> BackendType {
1455        match *self {
1456            #[cfg(feature = "webgpu")]
1457            Device::WebGpu(_) => BackendType::WebGPU,
1458            #[cfg(all(feature = "metal", target_vendor = "apple"))]
1459            Device::Metal(_) => BackendType::Metal,
1460            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1461            Device::Vulkan(_) => BackendType::Vulkan,
1462            #[cfg(all(feature = "d3d12", windows))]
1463            Device::D3d12(_) => BackendType::D3D12,
1464            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
1465            Device::Gl(_) => BackendType::OpenGL,
1466            #[cfg(all(feature = "gl", target_family = "wasm"))]
1467            Device::WebGl => BackendType::OpenGL,
1468        }
1469    }
1470
1471    /// In the browser, a WebGL device for the host's
1472    /// `WebGL2RenderingContext`. Its sessions take turns in the context when
1473    /// they present to the context's own canvas, which hands them the
1474    /// context it has: give them that canvas
1475    /// ([`Surface::web_canvas`]). A session on another canvas renders with
1476    /// that canvas's context.
1477    ///
1478    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) when
1479    /// `context` isn't a `WebGL2RenderingContext`.
1480    #[cfg(all(feature = "gl", target_family = "wasm"))]
1481    pub fn web_gl(context: &wasm_bindgen::JsValue) -> Result<Device, Error> {
1482        if !wasm_bindgen::JsCast::is_instance_of::<web_sys::WebGl2RenderingContext>(context) {
1483            return Err(Error::invalid_argument("a WebGL device wraps a WebGL2RenderingContext"));
1484        }
1485        Ok(Device::WebGl)
1486    }
1487
1488    /// In the browser, the library's device on the browser's WebGPU, which
1489    /// arrives asynchronously. A surface session on a canvas without a
1490    /// device asks for one itself, and attaches once it has it.
1491    ///
1492    /// Fails as [`mln_webgpu::Device::request`] does.
1493    #[cfg(all(feature = "webgpu", target_family = "wasm"))]
1494    pub async fn request_web_gpu() -> Result<Device, Error> {
1495        mln_webgpu::Device::request().await.map(Device::WebGpu).map_err(super::gfx_error)
1496    }
1497}