Skip to main content

mln_runtime/render/
local.rs

1//! A render target built on the thread that renders: a [`RenderTarget`]'s
2//! device and surface made into the backend's objects, which belong to that
3//! thread.
4//!
5//! [`RenderTarget`]: super::RenderTarget
6
7// The browser build has no backend for sessions.
8#![cfg_attr(target_family = "wasm", allow(unused_macros, unused_variables, unused_imports))]
9
10use std::rc::Rc;
11use std::sync::Arc;
12
13use mln_gfx::{ConsumerSync, ExportKind, ExportedImage, ExportedRing, FrameTarget, RendererBackend, SyncKind, Window};
14use mln_util::error::Error;
15use mln_util::image::PremultipliedImage;
16use mln_util::size::Size;
17
18use super::target::{
19    BorrowedRing, Device, DeviceOptions, FrameTexture, FrameTextureKind, RingKind, Surface, SurfaceKind,
20};
21
22/// Frames read back: an offscreen target.
23trait Offscreen: FrameTarget {
24    fn resize(&self, size: Size);
25    fn read_image(&self) -> Option<PremultipliedImage>;
26}
27
28/// Frames presented: a surface target.
29trait Presenting: FrameTarget {
30    fn resize(&self, size: Size);
31}
32
33#[cfg(all(feature = "metal", target_vendor = "apple"))]
34impl Borrowed for mln_mtl::BorrowedTarget {
35    fn select(&self, slot: usize) {
36        mln_mtl::BorrowedTarget::select(self, slot);
37    }
38    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
39        mln_mtl::BorrowedTarget::release(self, slot, consumer)
40    }
41    fn discard(&self, slot: usize) {
42        mln_mtl::BorrowedTarget::discard(self, slot);
43    }
44    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
45        #[allow(irrefutable_let_patterns)]
46        let RingKind::Metal(textures) = ring.kind else {
47            return Err(Error::unsupported("a ring of Metal textures takes Metal textures only"));
48        };
49        mln_mtl::BorrowedTarget::replace(self, textures).map(pending)
50    }
51    fn take_pending(&self) -> Pending {
52        pending(mln_mtl::BorrowedTarget::take_pending(self))
53    }
54}
55
56#[cfg(all(feature = "metal", target_vendor = "apple"))]
57impl PendingReads for mln_mtl::PendingReads {
58    fn poll(&mut self) -> bool {
59        mln_mtl::PendingReads::poll(self)
60    }
61}
62
63/// Frames given back to the host: a ring of its textures.
64trait Borrowed: FrameTarget {
65    fn select(&self, slot: usize);
66    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
67    fn discard(&self, slot: usize);
68    /// Renders into `ring` from now on, and returns the host's reads of the
69    /// textures that it let go of.
70    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error>;
71    /// Takes the host's reads of the textures that they still wait for, for
72    /// the ring to wait for before it lets go of them. A target that waits
73    /// for the host's reads as it takes each texture back has none.
74    fn take_pending(&self) -> Pending {
75        None
76    }
77}
78
79/// The host's reads of textures that a ring let go of, which the session
80/// waits for before the release or replacement completes. Dropping it stops
81/// waiting.
82pub(crate) trait PendingReads {
83    /// Whether every read ended, which it checks without blocking.
84    fn poll(&mut self) -> bool;
85}
86
87/// The host's reads that a ring waits for, if any.
88pub(crate) type Pending = Option<Box<dyn PendingReads>>;
89
90/// `reads`, unless they ended already.
91#[cfg(any(
92    all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
93    all(feature = "metal", target_vendor = "apple")
94))]
95fn pending(mut reads: impl PendingReads + 'static) -> Pending {
96    (!reads.poll()).then(|| Box::new(reads) as Box<dyn PendingReads>)
97}
98
99#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
100impl Borrowed for mln_vulkan::BorrowedTarget {
101    fn select(&self, slot: usize) {
102        mln_vulkan::BorrowedTarget::select(self, slot);
103    }
104    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
105        mln_vulkan::BorrowedTarget::release(self, slot, consumer)
106    }
107    fn discard(&self, slot: usize) {
108        mln_vulkan::BorrowedTarget::discard(self, slot);
109    }
110    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
111        #[allow(irrefutable_let_patterns)]
112        let RingKind::Vulkan(images) = ring.kind else {
113            return Err(Error::unsupported("a ring of Vulkan images takes Vulkan images only"));
114        };
115        mln_vulkan::BorrowedTarget::replace(self, images).map(pending)
116    }
117    fn take_pending(&self) -> Pending {
118        pending(mln_vulkan::BorrowedTarget::take_pending(self))
119    }
120}
121
122#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
123impl PendingReads for mln_vulkan::PendingReads {
124    fn poll(&mut self) -> bool {
125        mln_vulkan::PendingReads::poll(self)
126    }
127}
128
129/// Frames queued for the host: a ring of the target's own images, which it
130/// exports.
131trait Exported: FrameTarget {
132    fn select(&self, slot: usize);
133    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
134    fn discard(&self, slot: usize);
135    fn resize(&self, size: Size, held: &[usize]) -> Result<bool, Error>;
136    fn size(&self) -> Size;
137    fn image(&self, slot: usize) -> Option<(Size, ExportedImage)>;
138}
139
140macro_rules! exported {
141    ($type:ty) => {
142        impl Exported for $type {
143            fn select(&self, slot: usize) {
144                <$type>::select(self, slot);
145            }
146            fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
147                <$type>::release(self, slot, consumer)
148            }
149            fn discard(&self, slot: usize) {
150                <$type>::discard(self, slot);
151            }
152            fn resize(&self, size: Size, held: &[usize]) -> Result<bool, Error> {
153                <$type>::resize(self, size, held)
154            }
155            fn size(&self) -> Size {
156                <$type>::size(self)
157            }
158            fn image(&self, slot: usize) -> Option<(Size, ExportedImage)> {
159                <$type>::image(self, slot)
160            }
161        }
162    };
163}
164
165#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
166exported!(mln_vulkan::ExportedTarget);
167#[cfg(all(feature = "metal", target_vendor = "apple"))]
168exported!(mln_mtl::ExportedTarget);
169#[cfg(all(feature = "gl", unix, not(target_vendor = "apple"), not(target_os = "android")))]
170exported!(mln_gl::ExportedTarget);
171
172macro_rules! offscreen {
173    ($type:ty) => {
174        impl Offscreen for $type {
175            fn resize(&self, size: Size) {
176                <$type>::resize(self, size);
177            }
178            fn read_image(&self) -> Option<PremultipliedImage> {
179                <$type>::read_image(self)
180            }
181        }
182    };
183}
184
185macro_rules! presenting {
186    ($type:ty) => {
187        impl Presenting for $type {
188            fn resize(&self, size: Size) {
189                <$type>::resize(self, size);
190            }
191        }
192    };
193}
194
195#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
196offscreen!(mln_webgpu::OffscreenTarget);
197#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
198presenting!(mln_webgpu::SurfaceTarget);
199#[cfg(all(feature = "metal", target_vendor = "apple"))]
200offscreen!(mln_mtl::OffscreenTarget);
201#[cfg(all(feature = "metal", target_vendor = "apple"))]
202presenting!(mln_mtl::SurfaceTarget);
203#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
204offscreen!(mln_vulkan::OffscreenTarget);
205#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
206presenting!(mln_vulkan::SurfaceTarget);
207#[cfg(all(feature = "gl", not(target_family = "wasm")))]
208offscreen!(mln_gl::OffscreenTarget);
209#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
210presenting!(mln_gl::SurfaceTarget);
211#[cfg(all(feature = "gl", not(target_family = "wasm")))]
212presenting!(mln_gl::HostSurfaceTarget);
213
214#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
215impl Borrowed for mln_webgpu::BorrowedTarget {
216    fn select(&self, slot: usize) {
217        mln_webgpu::BorrowedTarget::select(self, slot);
218    }
219    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
220        mln_webgpu::BorrowedTarget::release(self, slot, consumer)
221    }
222    fn discard(&self, slot: usize) {
223        mln_webgpu::BorrowedTarget::discard(self, slot);
224    }
225    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
226        #[allow(irrefutable_let_patterns)]
227        let RingKind::WebGpu(textures) = ring.kind else {
228            return Err(Error::unsupported("a ring of WebGPU textures takes WebGPU textures only"));
229        };
230        mln_webgpu::BorrowedTarget::replace(self, textures).map(|()| None)
231    }
232}
233
234#[cfg(all(feature = "gl", not(target_family = "wasm")))]
235impl Borrowed for mln_gl::BorrowedTarget {
236    fn select(&self, slot: usize) {
237        mln_gl::BorrowedTarget::select(self, slot);
238    }
239    fn release(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
240        mln_gl::BorrowedTarget::release(self, slot, consumer)
241    }
242    fn discard(&self, slot: usize) {
243        mln_gl::BorrowedTarget::discard(self, slot);
244    }
245    fn replace(&self, ring: BorrowedRing) -> Result<Pending, Error> {
246        #[allow(irrefutable_let_patterns)]
247        let RingKind::Gl(textures) = ring.kind else {
248            return Err(Error::unsupported("a ring of OpenGL textures takes OpenGL textures only"));
249        };
250        mln_gl::BorrowedTarget::replace(self, textures).map(|()| None)
251    }
252}
253
254/// A backend, by its type.
255#[derive(Clone)]
256enum Backend {
257    #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
258    WebGpu(Rc<mln_webgpu::RendererBackend>),
259    #[cfg(all(feature = "metal", target_vendor = "apple"))]
260    Metal(Rc<mln_mtl::RendererBackend>),
261    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
262    Vulkan(Rc<mln_vulkan::RendererBackend>),
263    #[cfg(all(feature = "gl", not(target_family = "wasm")))]
264    Gl(Rc<mln_gl::RendererBackend>),
265}
266
267impl Backend {
268    fn as_dyn(&self) -> Rc<dyn RendererBackend> {
269        match *self {
270            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
271            Backend::WebGpu(ref backend) => backend.clone(),
272            #[cfg(all(feature = "metal", target_vendor = "apple"))]
273            Backend::Metal(ref backend) => backend.clone(),
274            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
275            Backend::Vulkan(ref backend) => backend.clone(),
276            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
277            Backend::Gl(ref backend) => backend.clone(),
278        }
279    }
280
281    /// A backend on `device`, for offscreen targets and the surfaces that
282    /// the device's backend makes on it.
283    fn new(device: &Device) -> Result<Backend, Error> {
284        match *device {
285            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
286            Device::WebGpu(ref device) => Ok(Backend::WebGpu(Rc::new(mln_webgpu::RendererBackend::new(device)))),
287            #[cfg(all(feature = "metal", target_vendor = "apple"))]
288            Device::Metal(ref device) => Ok(Backend::Metal(Rc::new(mln_mtl::RendererBackend::new(device)))),
289            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
290            Device::Vulkan(ref device) => Ok(Backend::Vulkan(Rc::new(mln_vulkan::RendererBackend::new(device)?))),
291            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
292            Device::Gl(ref device) => Ok(Backend::Gl(Rc::new(mln_gl::RendererBackend::new(device)?))),
293        }
294    }
295
296    /// A target on the backend that renders into `ring`, handing frames over
297    /// with sync of the kind `producer`.
298    fn borrowed(&self, ring: BorrowedRing, producer: SyncKind) -> Result<Box<dyn Borrowed>, Error> {
299        #[allow(unreachable_patterns)]
300        match (self, ring.kind) {
301            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
302            (Backend::Vulkan(backend), RingKind::Vulkan(images)) => {
303                Ok(Box::new(mln_vulkan::BorrowedTarget::new(backend.clone(), images, producer)?))
304            }
305            #[cfg(all(feature = "metal", target_vendor = "apple"))]
306            (Backend::Metal(backend), RingKind::Metal(textures)) => {
307                Ok(Box::new(mln_mtl::BorrowedTarget::new(backend.clone(), textures, producer)?))
308            }
309            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
310            (Backend::WebGpu(backend), RingKind::WebGpu(textures)) => {
311                Ok(Box::new(mln_webgpu::BorrowedTarget::new(backend.clone(), textures, producer)?))
312            }
313            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
314            (Backend::Gl(backend), RingKind::Gl(textures)) => {
315                Ok(Box::new(mln_gl::BorrowedTarget::new(backend.clone(), textures, producer)?))
316            }
317            _ => {
318                let _ = producer;
319                Err(Error::unsupported("the session's backend renders into no ring of this kind"))
320            }
321        }
322    }
323
324    /// A target on the backend that renders into a ring of `ring.depth`
325    /// images of `size` pixels, which it exports as `kind`, and hands frames
326    /// over with sync of the kind `producer`.
327    fn exported(
328        &self,
329        device: &Device,
330        ring: &ExportedRing,
331        kind: ExportKind,
332        size: Size,
333        producer: SyncKind,
334    ) -> Result<Box<dyn Exported>, Error> {
335        #[allow(unreachable_patterns)]
336        match self {
337            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
338            Backend::Vulkan(backend) => {
339                Ok(Box::new(mln_vulkan::ExportedTarget::new(backend.clone(), ring, kind, size, producer)?))
340            }
341            #[cfg(all(feature = "metal", target_vendor = "apple"))]
342            Backend::Metal(backend) => {
343                Ok(Box::new(mln_mtl::ExportedTarget::new(backend.clone(), ring, kind, size, producer)?))
344            }
345            #[cfg(all(feature = "gl", unix, not(target_vendor = "apple"), not(target_os = "android")))]
346            Backend::Gl(backend) => {
347                let Device::Gl(device) = device else {
348                    return Err(Error::unsupported("an OpenGL backend renders on an OpenGL device"));
349                };
350                Ok(Box::new(mln_gl::ExportedTarget::new(backend.clone(), device, ring, kind, size, producer)?))
351            }
352            _ => {
353                let _ = (device, ring, kind, size, producer);
354                Err(Error::unsupported("the session's backend exports no ring"))
355            }
356        }
357    }
358
359    /// An offscreen target of `size` pixels on the backend.
360    fn offscreen(&self, size: Size) -> Box<dyn Offscreen> {
361        match *self {
362            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
363            Backend::WebGpu(ref backend) => Box::new(mln_webgpu::OffscreenTarget::new(backend.clone(), size)),
364            #[cfg(all(feature = "metal", target_vendor = "apple"))]
365            Backend::Metal(ref backend) => Box::new(mln_mtl::OffscreenTarget::new(backend.clone(), size)),
366            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
367            Backend::Vulkan(ref backend) => Box::new(mln_vulkan::OffscreenTarget::new(backend.clone(), size)),
368            #[cfg(all(feature = "gl", not(target_family = "wasm")))]
369            Backend::Gl(ref backend) => Box::new(mln_gl::OffscreenTarget::new(backend.clone(), size)),
370        }
371    }
372
373    /// A target on the backend that presents to `surface`, at `size`
374    /// pixels. Fails with `Unsupported` when only a backend of the target's
375    /// own can present to it: see [`surface_backend`].
376    fn surface(&self, surface: Surface, size: Size) -> Result<Box<dyn Presenting>, Error> {
377        #[allow(unreachable_patterns)]
378        match (self, surface.kind) {
379            #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
380            (Backend::WebGpu(backend), kind) => {
381                let target = webgpu_surface(backend, kind)?;
382                let options = mln_webgpu::SurfaceOptions::default();
383                Ok(Box::new(mln_webgpu::SurfaceTarget::new(backend.clone(), target, size, options)?))
384            }
385            #[cfg(all(feature = "metal", target_vendor = "apple"))]
386            (Backend::Metal(backend), SurfaceKind::MetalLayer(layer)) => {
387                Ok(Box::new(mln_mtl::SurfaceTarget::new(backend, layer, size, true)))
388            }
389            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
390            (Backend::Vulkan(backend), SurfaceKind::Window(window)) => {
391                Ok(Box::new(mln_vulkan::SurfaceTarget::new(backend.clone(), window, size, true)?))
392            }
393            #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
394            (Backend::Vulkan(backend), SurfaceKind::Vulkan(surface)) => {
395                Ok(Box::new(mln_vulkan::SurfaceTarget::on_host_surface(backend.clone(), surface, size, true)?))
396            }
397            _ => {
398                let _ = size;
399                Err(Error::unsupported("the session's backend presents to no surface of this kind"))
400            }
401        }
402    }
403}
404
405/// A wgpu surface of `kind`, made with the instance of `backend`'s device
406/// where the host didn't make it.
407#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
408fn webgpu_surface(backend: &mln_webgpu::RendererBackend, kind: SurfaceKind) -> Result<wgpu::Surface<'static>, Error> {
409    let instance = || {
410        backend
411            .device()
412            .instance()
413            .ok_or_else(|| Error::invalid_argument("the session's device has no instance to make a surface with"))
414    };
415    let made = match kind {
416        SurfaceKind::Wgpu(surface) => return Ok(surface),
417        SurfaceKind::Window(window) => instance()?.create_surface(window),
418        #[cfg(all(feature = "metal", target_vendor = "apple"))]
419        SurfaceKind::MetalLayer(_) => return Err(Error::unsupported("a Metal layer presents on a Metal device")),
420        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
421        SurfaceKind::Vulkan(_) => return Err(Error::unsupported("a Vulkan surface presents on a Vulkan device")),
422        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
423        SurfaceKind::Gl(_) => return Err(Error::unsupported("an EGL surface presents on an OpenGL device")),
424    };
425    made.map_err(|error| Error::native(format!("can't make a surface on the window: {error}")))
426}
427
428/// A backend of the target's own on `device` and a target that presents to
429/// `surface`, for the backends whose context or device is made for the
430/// window: Vulkan's, whose instance and device take the window's surface
431/// extensions, and OpenGL ES's, whose context is of the window's display.
432fn surface_backend(device: &Device, surface: Surface, size: Size) -> Result<(Backend, Box<dyn Presenting>), Error> {
433    #[allow(unreachable_patterns)]
434    match (device, &surface.kind) {
435        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
436        (Device::Vulkan(device), SurfaceKind::Window(window)) => {
437            let (backend, target) = mln_vulkan::SurfaceTarget::with_backend(device, window.clone(), size, true)?;
438            Ok((Backend::Vulkan(backend), Box::new(target)))
439        }
440        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
441        (Device::Vulkan(device), SurfaceKind::Vulkan(_)) => {
442            let backend = Backend::Vulkan(Rc::new(mln_vulkan::RendererBackend::presenting(device)?));
443            let target = backend.surface(surface, size)?;
444            Ok((backend, target))
445        }
446        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
447        (Device::Gl(device), SurfaceKind::Gl(host)) => {
448            let (backend, target) = mln_gl::HostSurfaceTarget::with_backend(device, *host, size)?;
449            Ok((Backend::Gl(backend), Box::new(target)))
450        }
451        #[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
452        (Device::Gl(_), SurfaceKind::Window(window)) => {
453            let (backend, target) = mln_gl::SurfaceTarget::with_backend(window.clone(), size, true)?;
454            Ok((Backend::Gl(backend), Box::new(target)))
455        }
456        _ => {
457            let backend = Backend::new(device)?;
458            let target = backend.surface(surface, size)?;
459            Ok((backend, target))
460        }
461    }
462}
463
464enum Frames {
465    Offscreen(Box<dyn Offscreen>),
466    /// `None` once the surface is released.
467    Presenting(Option<Box<dyn Presenting>>),
468    /// `target` is `None` once the ring is released.
469    Borrowed {
470        target: Option<Box<dyn Borrowed>>,
471        producer: SyncKind,
472    },
473    Exported(Box<dyn Exported>),
474}
475
476/// A render target built on this thread: the backend that a renderer draws
477/// with, on the target's device, and the frames it draws into.
478pub struct LocalTarget {
479    device: Device,
480    backend: Backend,
481    frames: Frames,
482    /// The window that a surface target presents to, if it presents to one.
483    window: Option<Arc<dyn Window>>,
484}
485
486impl LocalTarget {
487    /// An offscreen target of `size` pixels on `device`, or on a device that
488    /// [`Device::new`] makes when that is `None`.
489    ///
490    /// Fails as [`Device::new`] does, and with the backend's error when it
491    /// can't render on the device.
492    pub fn offscreen(device: Option<Device>, size: Size) -> Result<LocalTarget, Error> {
493        let device = match device {
494            Some(device) => device,
495            None => Device::new(DeviceOptions::default())?,
496        };
497        let backend = Backend::new(&device)?;
498        let frames = Frames::Offscreen(backend.offscreen(size));
499        Ok(LocalTarget { device, backend, frames, window: None })
500    }
501
502    /// A target of `size` pixels that presents to `surface`, on `device` or,
503    /// when that is `None`, on the device the surface's kind takes
504    /// ([`RenderTarget::Surface`](super::RenderTarget::Surface)).
505    ///
506    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
507    /// surface that the host made without the host's device, with
508    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a window or
509    /// surface without an area to present to, such as a minimized window,
510    /// with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the device
511    /// can't present to the surface, and with the error of the device or the
512    /// window's surface.
513    pub fn surface(surface: Surface, device: Option<Device>, size: Size) -> Result<LocalTarget, Error> {
514        surface.check_area()?;
515        let window = surface.host_window();
516        let device = match device {
517            Some(device) => device,
518            None => default_surface_device(&surface)?,
519        };
520        let (backend, target) = surface_backend(&device, surface, size)?;
521        Ok(LocalTarget { device, backend, frames: Frames::Presenting(Some(target)), window })
522    }
523
524    /// A target of `size` pixels on `device` that renders into the host's
525    /// `ring`, and hands each frame over with sync of the kind `producer`.
526    ///
527    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
528    /// device can't render into the ring with `producer`, and with the
529    /// backend's error.
530    pub fn borrowed(device: Device, ring: BorrowedRing, producer: SyncKind) -> Result<LocalTarget, Error> {
531        let backend = Backend::new(&device)?;
532        let frames = Frames::Borrowed { target: Some(backend.borrowed(ring, producer)?), producer };
533        Ok(LocalTarget { device, backend, frames, window: None })
534    }
535
536    /// A target on `device` that renders into a ring of `ring.depth` images
537    /// of `size` pixels, which it exports as `kind`, one that
538    /// [`Device::export_plan`] picked, and hands each frame over with sync of
539    /// the kind `producer`.
540    ///
541    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the
542    /// device can't export `kind` or hand frames over with `producer`, and
543    /// with the backend's error.
544    pub fn exported(
545        device: Device,
546        ring: &ExportedRing,
547        kind: ExportKind,
548        size: Size,
549        producer: SyncKind,
550    ) -> Result<LocalTarget, Error> {
551        let backend = Backend::new(&device)?;
552        let frames = {
553            let scoped = backend.as_dyn();
554            let _scope = mln_gfx::BackendScope::new(&*scoped, mln_gfx::ScopeType::Explicit);
555            Frames::Exported(backend.exported(&device, ring, kind, size, producer)?)
556        };
557        Ok(LocalTarget { device, backend, frames, window: None })
558    }
559
560    /// The device the target renders on.
561    #[must_use]
562    pub fn device(&self) -> &Device {
563        &self.device
564    }
565
566    /// The backend that renderers drawing into the target draw with.
567    #[must_use]
568    pub fn backend(&self) -> Rc<dyn RendererBackend> {
569        self.backend.as_dyn()
570    }
571
572    /// The frames to draw into, or `None` while a surface target has no
573    /// surface.
574    #[must_use]
575    pub fn frames(&self) -> Option<&dyn FrameTarget> {
576        match &self.frames {
577            Frames::Offscreen(target) => Some(&**target),
578            Frames::Presenting(target) => target.as_deref().map(|target| target as &dyn FrameTarget),
579            Frames::Borrowed { target, .. } => target.as_deref().map(|target| target as &dyn FrameTarget),
580            Frames::Exported(target) => Some(&**target),
581        }
582    }
583
584    /// Whether the target can take a frame as far as its window says: it
585    /// presents to no window, or to one with an area to present to
586    /// ([`mln_gfx::window::has_area`]).
587    #[must_use]
588    pub fn window_has_area(&self) -> bool {
589        self.window.as_deref().is_none_or(mln_gfx::window::has_area)
590    }
591
592    /// Whether frames are presented to a window or surface.
593    #[must_use]
594    pub fn is_presenting(&self) -> bool {
595        matches!(self.frames, Frames::Presenting(_))
596    }
597
598    /// Whether frames go to the host in images of the target's own.
599    #[must_use]
600    pub fn is_exported(&self) -> bool {
601        matches!(self.frames, Frames::Exported(_))
602    }
603
604    /// Whether frames go to the host's ring.
605    #[must_use]
606    pub fn is_borrowed(&self) -> bool {
607        matches!(self.frames, Frames::Borrowed { .. })
608    }
609
610    /// Whether the target is a ring that let go of its textures.
611    #[must_use]
612    pub fn ring_released(&self) -> bool {
613        matches!(self.frames, Frames::Borrowed { target: None, .. })
614    }
615
616    fn ring(&self) -> Result<&dyn Borrowed, Error> {
617        match &self.frames {
618            Frames::Borrowed { target: Some(target), .. } => Ok(&**target),
619            Frames::Borrowed { target: None, .. } => Err(Error::invalid_state("the ring was released")),
620            _ => Err(Error::unsupported("the target has no ring")),
621        }
622    }
623
624    /// Has the next frame render into the ring's texture at `slot`.
625    pub fn select_slot(&self, slot: usize) -> Result<(), Error> {
626        if let Frames::Exported(target) = &self.frames {
627            target.select(slot);
628            return Ok(());
629        }
630        self.ring()?.select(slot);
631        Ok(())
632    }
633
634    /// The host gave the ring's texture at `slot` back: the next frame
635    /// rendered into it waits for `consumer`.
636    pub fn release_slot(&self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
637        if let Frames::Exported(target) = &self.frames {
638            return target.release(slot, consumer);
639        }
640        self.ring()?.release(slot, consumer)
641    }
642
643    /// The host gave up the ring's texture at `slot`, which the target
644    /// renders into no more.
645    pub fn discard_slot(&self, slot: usize) -> Result<(), Error> {
646        if let Frames::Exported(target) = &self.frames {
647            target.discard(slot);
648            return Ok(());
649        }
650        self.ring()?.discard(slot);
651        Ok(())
652    }
653
654    /// The size in pixels of an exported ring's images, or `None` for
655    /// another target.
656    #[must_use]
657    pub fn exported_size(&self) -> Option<Size> {
658        match &self.frames {
659            Frames::Exported(target) => Some(target.size()),
660            _ => None,
661        }
662    }
663
664    /// Renders an exported ring's next frames into images of `size` pixels.
665    /// The frames that the host holds, at `held` slots, keep their images.
666    /// Returns whether the ring has new images, which it doesn't when they
667    /// have `size` already.
668    ///
669    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
670    /// target that isn't an exported ring, and with the backend's error, when
671    /// the ring keeps its images.
672    pub fn resize_exported(&self, size: Size, held: &[usize]) -> Result<bool, Error> {
673        match &self.frames {
674            Frames::Exported(target) => target.resize(size, held),
675            _ => Err(Error::unsupported("the target exports no ring")),
676        }
677    }
678
679    /// The exported image of the frame at `slot`, of the size it has.
680    #[must_use]
681    pub fn exported_texture(&self, slot: usize) -> Option<FrameTexture> {
682        match &self.frames {
683            Frames::Exported(target) => {
684                target.image(slot).map(|(size, image)| FrameTexture { size, kind: FrameTextureKind::Exported(image) })
685            }
686            _ => None,
687        }
688    }
689
690    /// Renders into `ring` from now on, in place of the ring's textures, and
691    /// returns the host's reads of the textures that it let go of, which the
692    /// host may use once they end.
693    ///
694    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
695    /// target that isn't a ring, or a ring of another format, and with the
696    /// backend's error.
697    pub(crate) fn set_ring(&mut self, ring: BorrowedRing) -> Result<Pending, Error> {
698        match &mut self.frames {
699            Frames::Borrowed { target: Some(target), .. } => target.replace(ring),
700            Frames::Borrowed { target, producer } => {
701                *target = Some(self.backend.borrowed(ring, *producer)?);
702                Ok(None)
703            }
704            _ => Err(Error::unsupported("the target has no ring")),
705        }
706    }
707
708    /// Whether frames are read back rather than presented.
709    #[must_use]
710    pub fn is_offscreen(&self) -> bool {
711        matches!(self.frames, Frames::Offscreen(_))
712    }
713
714    /// Draws the next frame at `size` pixels.
715    pub fn resize(&self, size: Size) {
716        match &self.frames {
717            Frames::Offscreen(target) => target.resize(size),
718            Frames::Presenting(Some(target)) => target.resize(size),
719            Frames::Presenting(None) | Frames::Borrowed { .. } | Frames::Exported(_) => {}
720        }
721    }
722
723    /// The last frame's pixels.
724    ///
725    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
726    /// target that presents its frames, and with
727    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) before a frame.
728    pub fn read_image(&self) -> Result<PremultipliedImage, Error> {
729        match &self.frames {
730            Frames::Offscreen(target) => target
731                .read_image()
732                .ok_or_else(|| Error::invalid_state("the target has no frame since it was made or resized")),
733            Frames::Presenting(_) => Err(Error::unsupported("a surface session can't read its frames back")),
734            Frames::Borrowed { .. } | Frames::Exported(_) => {
735                Err(Error::unsupported("a ring's frames are the host's to read"))
736            }
737        }
738    }
739
740    /// Lets go of a surface target's surface, or of a ring's textures, and
741    /// returns the host's reads of the textures, which the host may use once
742    /// they end. The backend stays.
743    pub(crate) fn release_surface(&mut self) -> Pending {
744        match &mut self.frames {
745            Frames::Presenting(target) => {
746                drop(target.take());
747                self.window = None;
748                None
749            }
750            Frames::Borrowed { target, .. } => target.take().and_then(|target| target.take_pending()),
751            Frames::Offscreen(_) | Frames::Exported(_) => None,
752        }
753    }
754
755    /// Presents to `surface` at `size` pixels from now on, in place of the
756    /// surface the target has, if any: on the same backend where it can
757    /// present to `surface`, and on a new one of the device otherwise, which
758    /// the target then returns true for. A renderer on the old backend has
759    /// to be made again on the new one.
760    ///
761    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for an
762    /// offscreen target or when the device can't present to `surface`, and
763    /// as [`surface`](Self::surface) does. The target then keeps what it
764    /// had.
765    pub fn set_surface(&mut self, surface: Surface, size: Size) -> Result<bool, Error> {
766        if !matches!(self.frames, Frames::Presenting(_)) {
767            return Err(Error::unsupported("only a surface target presents to another surface"));
768        }
769        surface.check_area()?;
770        let window = surface.host_window();
771        let retry = surface.clone_window();
772        let (new_backend, target) = match self.backend.surface(surface, size) {
773            Ok(target) => (false, target),
774            Err(error) if error.kind == mln_util::ErrorKind::Unsupported => {
775                let surface = retry.ok_or(error)?;
776                let (backend, target) = surface_backend(&self.device, surface, size)?;
777                self.backend = backend;
778                (true, target)
779            }
780            Err(error) => return Err(error),
781        };
782        self.frames = Frames::Presenting(Some(target));
783        self.window = window;
784        Ok(new_backend)
785    }
786}
787
788/// The device a surface renders on without the host's: the native one where
789/// its backend takes the surface's kind.
790fn default_surface_device(surface: &Surface) -> Result<Device, Error> {
791    match surface.kind {
792        SurfaceKind::Window(_) if cfg!(target_vendor = "apple") => {
793            Device::with_backend(super::target::BackendType::WebGPU, DeviceOptions::default())
794        }
795        SurfaceKind::Window(_) => Device::new(DeviceOptions::default()),
796        #[cfg(all(feature = "metal", target_vendor = "apple"))]
797        SurfaceKind::MetalLayer(_) => Device::with_backend(super::target::BackendType::Metal, DeviceOptions::default()),
798        #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
799        SurfaceKind::Wgpu(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
800        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
801        SurfaceKind::Vulkan(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
802        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
803        SurfaceKind::Gl(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
804    }
805}