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 matches over the backends' enums list a variant per backend that the
8// build's features and target have, so whether their `_` arm is unreachable,
9// or matches a single variant, and whether a `let` of one variant is
10// irrefutable, depends on the build.
11#![allow(
12    unreachable_patterns,
13    irrefutable_let_patterns,
14    clippy::match_wildcard_for_single_variants,
15    reason = "the backends' variants depend on the build's features and target"
16)]
17#![cfg_attr(
18    all(target_family = "wasm", not(feature = "webgpu")),
19    expect(dead_code, reason = "WebGL2 renders only into a canvas, whose target makes its backend")
20)]
21
22use std::sync::Arc;
23
24use mln_engine::{Renderer, UpdateParameters};
25use mln_gfx::gpu::Gpu;
26#[cfg(not(target_family = "wasm"))]
27use mln_gfx::offscreen_target::OffscreenTarget;
28use mln_gfx::rendering_stats::RenderingStats;
29use mln_gfx::ring::{self, Exporter, RingBackend};
30use mln_gfx::{
31    ConsumerSync, ExportKind, ExportedFrame, ExportedRing, FrameImage, FrameTarget, GpuSync, Handoff, RendererBackend,
32    SyncKind, Window,
33};
34use mln_style::bitmap::PremultipliedImage;
35use mln_style::error::Error;
36use mln_style::size::Size;
37
38use super::target::{
39    BorrowedRing, Device, DeviceOptions, FrameTexture, RingKind, Surface, SurfaceKind, SurfaceOverlay,
40};
41use super::{gfx_error, gfx_size};
42
43/// A target of the backend `B` that a session draws into.
44type Target<B> = Box<dyn FrameTarget<Gpu = <B as RendererBackend>::Gpu>>;
45
46/// Frames given back to the host: a ring of its textures, on the backend
47/// `B`.
48trait Borrowed<B: LocalBackend>: FrameTarget<Gpu = B::Gpu> {
49    fn select(&mut self, slot: usize);
50    fn release(&mut self, gpu: &mut B::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), mln_gfx::Error>;
51    fn discard(&mut self, gpu: &mut B::Gpu, slot: usize);
52    /// Renders into `textures` from now on, and returns the sync after
53    /// which the host may use the textures that it let go of.
54    fn replace(&mut self, gpu: &mut B::Gpu, textures: B::RingTextures) -> Result<GpuSync, mln_gfx::Error>;
55    /// Lets go of its textures, and returns the sync after which the host
56    /// may use them. It keeps what the sync names until the next release or
57    /// replacement, or until it goes, and draws no frame until then.
58    fn release_textures(&mut self, gpu: &mut B::Gpu) -> Result<GpuSync, mln_gfx::Error>;
59}
60
61/// Frames queued for the host: a ring of the target's own images, which it
62/// exports, on the backend `B`.
63trait Exported<B: RendererBackend>: FrameTarget<Gpu = B::Gpu> {
64    fn select(&mut self, slot: usize);
65    fn release(&mut self, gpu: &mut B::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), mln_gfx::Error>;
66    fn discard(&mut self, gpu: &mut B::Gpu, slot: usize);
67    fn resize_images(&mut self, backend: &mut B, size: mln_gfx::Size, held: &[usize]) -> Result<bool, mln_gfx::Error>;
68    fn size(&self) -> mln_gfx::Size;
69    fn image(&self, slot: usize) -> Option<ExportedFrame>;
70}
71
72impl<R: RingBackend + 'static> Borrowed<R::Renderer> for ring::BorrowedTarget<R>
73where
74    R::Renderer: LocalBackend<RingTextures = R::Textures>,
75{
76    fn select(&mut self, slot: usize) {
77        ring::BorrowedTarget::select(self, slot);
78    }
79    fn release(&mut self, gpu: &mut R::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), mln_gfx::Error> {
80        ring::BorrowedTarget::release(self, gpu, slot, consumer)
81    }
82    fn discard(&mut self, gpu: &mut R::Gpu, slot: usize) {
83        ring::BorrowedTarget::discard(self, gpu, slot);
84    }
85    fn replace(&mut self, gpu: &mut R::Gpu, textures: R::Textures) -> Result<GpuSync, mln_gfx::Error> {
86        ring::BorrowedTarget::replace(self, gpu, textures)
87    }
88    fn release_textures(&mut self, gpu: &mut R::Gpu) -> Result<GpuSync, mln_gfx::Error> {
89        ring::BorrowedTarget::release_textures(self, gpu)
90    }
91}
92
93#[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
94impl Borrowed<mln_webgpu::RendererBackend> for mln_webgpu::BorrowedTarget {
95    fn select(&mut self, slot: usize) {
96        mln_webgpu::BorrowedTarget::select(self, slot);
97    }
98    fn release(
99        &mut self,
100        _gpu: &mut mln_webgpu::WebGpu,
101        slot: usize,
102        consumer: ConsumerSync,
103    ) -> Result<(), mln_gfx::Error> {
104        mln_webgpu::BorrowedTarget::release(self, slot, consumer)
105    }
106    fn discard(&mut self, _gpu: &mut mln_webgpu::WebGpu, slot: usize) {
107        mln_webgpu::BorrowedTarget::discard(self, slot);
108    }
109    fn replace(
110        &mut self,
111        gpu: &mut mln_webgpu::WebGpu,
112        textures: mln_webgpu::BorrowedTextures,
113    ) -> Result<GpuSync, mln_gfx::Error> {
114        mln_webgpu::BorrowedTarget::replace(self, gpu, textures)
115    }
116    fn release_textures(&mut self, gpu: &mut mln_webgpu::WebGpu) -> Result<GpuSync, mln_gfx::Error> {
117        mln_webgpu::BorrowedTarget::release_textures(self, gpu)
118    }
119}
120
121#[cfg(all(feature = "gl", not(target_family = "wasm")))]
122impl Borrowed<mln_gl::RendererBackend> for mln_gl::BorrowedTarget {
123    fn select(&mut self, slot: usize) {
124        mln_gl::BorrowedTarget::select(self, slot);
125    }
126    fn release(&mut self, gpu: &mut mln_gl::GlGpu, slot: usize, consumer: ConsumerSync) -> Result<(), mln_gfx::Error> {
127        mln_gl::BorrowedTarget::release(self, gpu, slot, consumer)
128    }
129    fn discard(&mut self, gpu: &mut mln_gl::GlGpu, slot: usize) {
130        mln_gl::BorrowedTarget::discard(self, gpu, slot);
131    }
132    fn replace(
133        &mut self,
134        gpu: &mut mln_gl::GlGpu,
135        textures: mln_gl::BorrowedTextures,
136    ) -> Result<GpuSync, mln_gfx::Error> {
137        mln_gl::BorrowedTarget::replace(self, gpu, textures)
138    }
139    fn release_textures(&mut self, gpu: &mut mln_gl::GlGpu) -> Result<GpuSync, mln_gfx::Error> {
140        mln_gl::BorrowedTarget::release_textures(self, gpu)
141    }
142}
143
144impl<E: Exporter> Exported<<E::Ring as RingBackend>::Renderer> for ring::ExportedTarget<E> {
145    fn select(&mut self, slot: usize) {
146        ring::ExportedTarget::select(self, slot);
147    }
148    fn release(
149        &mut self,
150        gpu: &mut <E::Ring as RingBackend>::Gpu,
151        slot: usize,
152        consumer: ConsumerSync,
153    ) -> Result<(), mln_gfx::Error> {
154        ring::ExportedTarget::release(self, gpu, slot, consumer)
155    }
156    fn discard(&mut self, gpu: &mut <E::Ring as RingBackend>::Gpu, slot: usize) {
157        ring::ExportedTarget::discard(self, gpu, slot);
158    }
159    fn resize_images(
160        &mut self,
161        backend: &mut <E::Ring as RingBackend>::Renderer,
162        size: mln_gfx::Size,
163        held: &[usize],
164    ) -> Result<bool, mln_gfx::Error> {
165        ring::ExportedTarget::resize(self, backend, size, held)
166    }
167    fn size(&self) -> mln_gfx::Size {
168        ring::ExportedTarget::size(self)
169    }
170    fn image(&self, slot: usize) -> Option<ExportedFrame> {
171        ring::ExportedTarget::image(self, slot)
172    }
173}
174
175#[cfg(all(feature = "gl", unix, not(target_vendor = "apple")))]
176impl Exported<mln_gl::RendererBackend> for mln_gl::ExportedTarget {
177    fn select(&mut self, slot: usize) {
178        mln_gl::ExportedTarget::select(self, slot);
179    }
180    fn release(&mut self, gpu: &mut mln_gl::GlGpu, slot: usize, consumer: ConsumerSync) -> Result<(), mln_gfx::Error> {
181        mln_gl::ExportedTarget::release(self, gpu, slot, consumer)
182    }
183    fn discard(&mut self, gpu: &mut mln_gl::GlGpu, slot: usize) {
184        mln_gl::ExportedTarget::discard(self, gpu, slot);
185    }
186    fn resize_images(
187        &mut self,
188        backend: &mut mln_gl::RendererBackend,
189        size: mln_gfx::Size,
190        held: &[usize],
191    ) -> Result<bool, mln_gfx::Error> {
192        mln_gl::ExportedTarget::resize(self, &mut backend.gpu(), size, held)
193    }
194    fn size(&self) -> mln_gfx::Size {
195        mln_gl::ExportedTarget::size(self)
196    }
197    fn image(&self, slot: usize) -> Option<ExportedFrame> {
198        mln_gl::ExportedTarget::image(self, slot)
199    }
200}
201
202/// What a [`BackendGfx`] draws into, which it makes on its backend.
203enum FramesInit<'a> {
204    Offscreen(mln_gfx::Size),
205    Borrowed(BorrowedRing, SyncKind),
206    Exported { device: &'a Device, ring: &'a ExportedRing, kind: ExportKind, size: mln_gfx::Size, producer: SyncKind },
207    Surface(Surface, Option<SurfaceOverlay>, mln_gfx::Size),
208}
209
210fn no_ring() -> Error {
211    Error::unsupported("the session's backend renders into no ring of this kind")
212}
213
214fn no_surface() -> Error {
215    Error::unsupported("the session's backend presents to no surface of this kind")
216}
217
218/// A backend of the build, and the targets that the session makes on it.
219/// A kind of target that a backend has none of fails with `Unsupported`.
220trait LocalBackend: RendererBackend + Sized {
221    /// The host's textures of a ring that the backend renders into.
222    type RingTextures;
223
224    /// The backend's textures of `ring`, `None` for another backend's.
225    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures>;
226
227    /// The backend, by its type.
228    fn by_type(&self) -> BackendRef<'_>;
229
230    /// A target on the backend that renders into the ring of `textures`,
231    /// handing frames over with sync of the kind `producer`.
232    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
233        let _ = (textures, producer);
234        Err(no_ring())
235    }
236
237    /// A target on the backend that renders into a ring of `ring.depth`
238    /// images of `size` pixels, which it exports as `kind`, and hands frames
239    /// over with sync of the kind `producer`.
240    fn exported(
241        &mut self,
242        device: &Device,
243        ring: &ExportedRing,
244        kind: ExportKind,
245        size: mln_gfx::Size,
246        producer: SyncKind,
247    ) -> Result<Box<dyn Exported<Self>>, Error> {
248        let _ = (device, ring, kind, size, producer);
249        Err(Error::unsupported("the session's backend exports no ring"))
250    }
251
252    /// A target on the backend that presents to `surface`, at `size`
253    /// pixels, with `overlay` drawn over its frames. Fails with
254    /// `Unsupported` when only a backend of the target's own can present to
255    /// it: see [`surface_backend`].
256    fn surface(
257        &mut self,
258        surface: Surface,
259        overlay: Option<SurfaceOverlay>,
260        size: mln_gfx::Size,
261    ) -> Result<Target<Self>, Error> {
262        let _ = (surface, overlay, size);
263        Err(no_surface())
264    }
265}
266
267#[cfg(feature = "webgpu")]
268impl LocalBackend for mln_webgpu::RendererBackend {
269    #[cfg(not(target_family = "wasm"))]
270    type RingTextures = mln_webgpu::BorrowedTextures;
271    #[cfg(target_family = "wasm")]
272    type RingTextures = std::convert::Infallible;
273
274    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
275        match ring {
276            #[cfg(not(target_family = "wasm"))]
277            RingKind::WebGpu(textures) => Some(textures),
278            _ => None,
279        }
280    }
281
282    fn by_type(&self) -> BackendRef<'_> {
283        BackendRef::WebGpu(self)
284    }
285
286    #[cfg(not(target_family = "wasm"))]
287    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
288        Ok(Box::new(mln_webgpu::BorrowedTarget::new(self, textures, producer).map_err(gfx_error)?))
289    }
290
291    fn surface(
292        &mut self,
293        surface: Surface,
294        overlay: Option<SurfaceOverlay>,
295        size: mln_gfx::Size,
296    ) -> Result<Target<Self>, Error> {
297        let kind = surface.kind;
298        #[cfg(target_family = "wasm")]
299        let format = match &kind {
300            SurfaceKind::WebCanvas { format: Some(format), .. } => Some(match format {
301                super::target::CanvasFormat::Bgra8Unorm => wgpu::TextureFormat::Bgra8Unorm,
302                super::target::CanvasFormat::Rgba8Unorm => wgpu::TextureFormat::Rgba8Unorm,
303                super::target::CanvasFormat::Rgba16Float => wgpu::TextureFormat::Rgba16Float,
304            }),
305            _ => None,
306        };
307        #[cfg(not(target_family = "wasm"))]
308        let format = None;
309        let overlay = overlay_of(overlay, |overlay| {
310            if let SurfaceOverlay::WebGpu(overlay) = overlay { Ok(overlay) } else { Err(overlay) }
311        })?;
312        let target = webgpu_surface(self, kind)?;
313        let options = mln_webgpu::SurfaceOptions {
314            cap_frame_rate: surface.cap_frame_rate,
315            format,
316            ..mln_webgpu::SurfaceOptions::default()
317        };
318        let mut target = mln_webgpu::SurfaceTarget::new(self, target, size, options).map_err(gfx_error)?;
319        target.set_overlay(overlay);
320        Ok(Box::new(target))
321    }
322}
323
324#[cfg(all(feature = "metal", target_vendor = "apple"))]
325impl LocalBackend for mln_mtl::RendererBackend {
326    type RingTextures = mln_mtl::BorrowedTextures;
327
328    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
329        if let RingKind::Metal(textures) = ring { Some(textures) } else { None }
330    }
331
332    fn by_type(&self) -> BackendRef<'_> {
333        BackendRef::Metal(self)
334    }
335
336    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
337        Ok(Box::new(mln_mtl::BorrowedTarget::new(self, textures, producer).map_err(gfx_error)?))
338    }
339
340    fn exported(
341        &mut self,
342        _device: &Device,
343        ring: &ExportedRing,
344        kind: ExportKind,
345        size: mln_gfx::Size,
346        producer: SyncKind,
347    ) -> Result<Box<dyn Exported<Self>>, Error> {
348        Ok(Box::new(mln_mtl::ExportedTarget::new(self, ring, kind, size, producer).map_err(gfx_error)?))
349    }
350
351    fn surface(
352        &mut self,
353        surface: Surface,
354        overlay: Option<SurfaceOverlay>,
355        size: mln_gfx::Size,
356    ) -> Result<Target<Self>, Error> {
357        let layer = match surface.kind {
358            SurfaceKind::MetalLayer(layer) => layer,
359            SurfaceKind::Window(window) => mln_mtl::Layer::of_window(&*window).map_err(gfx_error)?,
360            _ => return Err(no_surface()),
361        };
362        let overlay =
363            overlay_of(
364                overlay,
365                |overlay| {
366                    if let SurfaceOverlay::Metal(overlay) = overlay { Ok(overlay) } else { Err(overlay) }
367                },
368            )?;
369        let mut target = mln_mtl::SurfaceTarget::new(self, layer, size, surface.cap_frame_rate);
370        target.set_overlay(overlay);
371        Ok(Box::new(target))
372    }
373}
374
375#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
376impl LocalBackend for mln_vulkan::RendererBackend {
377    type RingTextures = mln_vulkan::BorrowedImages;
378
379    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
380        if let RingKind::Vulkan(images) = ring { Some(images) } else { None }
381    }
382
383    fn by_type(&self) -> BackendRef<'_> {
384        BackendRef::Vulkan(self)
385    }
386
387    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
388        Ok(Box::new(mln_vulkan::BorrowedTarget::new(self, textures, producer).map_err(gfx_error)?))
389    }
390
391    fn exported(
392        &mut self,
393        _device: &Device,
394        ring: &ExportedRing,
395        kind: ExportKind,
396        size: mln_gfx::Size,
397        producer: SyncKind,
398    ) -> Result<Box<dyn Exported<Self>>, Error> {
399        Ok(Box::new(mln_vulkan::ExportedTarget::new(self, ring, kind, size, producer).map_err(gfx_error)?))
400    }
401
402    fn surface(
403        &mut self,
404        surface: Surface,
405        overlay: Option<SurfaceOverlay>,
406        size: mln_gfx::Size,
407    ) -> Result<Target<Self>, Error> {
408        let overlay = vulkan_overlay(overlay)?;
409        let mut target = match surface.kind {
410            SurfaceKind::Window(window) => {
411                mln_vulkan::SurfaceTarget::new(self, window, size, surface.cap_frame_rate).map_err(gfx_error)?
412            }
413            SurfaceKind::Vulkan(host) => {
414                mln_vulkan::SurfaceTarget::on_host_surface(self, host, size, surface.cap_frame_rate)
415                    .map_err(gfx_error)?
416            }
417            _ => return Err(no_surface()),
418        };
419        target.set_overlay(self.gpu(), overlay);
420        Ok(Box::new(target))
421    }
422}
423
424#[cfg(all(feature = "d3d12", windows))]
425impl LocalBackend for mln_d3d12::RendererBackend {
426    type RingTextures = mln_d3d12::BorrowedTextures;
427
428    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
429        if let RingKind::D3d12(textures) = ring { Some(textures) } else { None }
430    }
431
432    fn by_type(&self) -> BackendRef<'_> {
433        BackendRef::D3d12(self)
434    }
435
436    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
437        Ok(Box::new(mln_d3d12::BorrowedTarget::new(self, textures, producer).map_err(gfx_error)?))
438    }
439
440    fn exported(
441        &mut self,
442        _device: &Device,
443        ring: &ExportedRing,
444        kind: ExportKind,
445        size: mln_gfx::Size,
446        producer: SyncKind,
447    ) -> Result<Box<dyn Exported<Self>>, Error> {
448        Ok(Box::new(mln_d3d12::ExportedTarget::new(self, ring, kind, size, producer).map_err(gfx_error)?))
449    }
450
451    fn surface(
452        &mut self,
453        surface: Surface,
454        overlay: Option<SurfaceOverlay>,
455        size: mln_gfx::Size,
456    ) -> Result<Target<Self>, Error> {
457        let overlay = || {
458            overlay_of(overlay, |overlay| match overlay {
459                SurfaceOverlay::D3d12(overlay) => Ok(overlay),
460                other => Err(other),
461            })
462        };
463        let (mut target, overlay) = match surface.kind {
464            SurfaceKind::Window(window) => {
465                let overlay = overlay()?;
466                (mln_d3d12::SurfaceTarget::new(self, window, size).map_err(gfx_error)?, overlay)
467            }
468            SurfaceKind::D3d12Composition { composition, thread } => {
469                if composition.is_swap_chain_panel() && thread != std::thread::current().id() {
470                    return Err(Error::unsupported(
471                        "a SwapChainPanel takes its swap chain on its UI thread, which made the surface: attach it \
472                         with Driver::CallerThread, serviced there",
473                    ));
474                }
475                let overlay = overlay()?;
476                (mln_d3d12::SurfaceTarget::for_composition(self, composition, size).map_err(gfx_error)?, overlay)
477            }
478            _ => return Err(no_surface()),
479        };
480        target.set_overlay(self.gpu(), overlay);
481        Ok(Box::new(target))
482    }
483}
484
485#[cfg(feature = "gl")]
486impl LocalBackend for mln_gl::RendererBackend {
487    #[cfg(not(target_family = "wasm"))]
488    type RingTextures = mln_gl::BorrowedTextures;
489    #[cfg(target_family = "wasm")]
490    type RingTextures = std::convert::Infallible;
491
492    fn ring_textures(ring: RingKind) -> Option<Self::RingTextures> {
493        match ring {
494            #[cfg(not(target_family = "wasm"))]
495            RingKind::Gl(textures) => Some(textures),
496            _ => None,
497        }
498    }
499
500    fn by_type(&self) -> BackendRef<'_> {
501        BackendRef::Gl(self)
502    }
503
504    #[cfg(not(target_family = "wasm"))]
505    fn borrowed(&mut self, textures: Self::RingTextures, producer: SyncKind) -> Result<Box<dyn Borrowed<Self>>, Error> {
506        Ok(Box::new(mln_gl::BorrowedTarget::new(textures, producer).map_err(gfx_error)?))
507    }
508
509    #[cfg(all(unix, not(target_vendor = "apple")))]
510    fn exported(
511        &mut self,
512        device: &Device,
513        ring: &ExportedRing,
514        kind: ExportKind,
515        size: mln_gfx::Size,
516        producer: SyncKind,
517    ) -> Result<Box<dyn Exported<Self>>, Error> {
518        // Irrefutable in a build with OpenGL alone, which has no other kind
519        // of device, and refutable in one with other backends.
520        let Device::Gl(device) = device else {
521            return Err(Error::unsupported("an OpenGL backend renders on an OpenGL device"));
522        };
523        Ok(Box::new(mln_gl::ExportedTarget::new(self, device, ring, kind, size, producer).map_err(gfx_error)?))
524    }
525}
526
527/// What a session draws with and into, whatever its backend: the methods of
528/// [`LocalTarget`] that reach the backend, each one dynamic call.
529trait Gfx {
530    fn backend(&self) -> BackendRef<'_>;
531    fn frames(&self) -> FramesKind;
532    fn renderer(&self) -> Option<&Renderer>;
533    fn renderer_mut(&mut self) -> Option<&mut Renderer>;
534    fn renderer_or(&mut self, make: &mut dyn FnMut(&dyn Gpu) -> Renderer) -> &mut Renderer;
535    fn with_gpu(&mut self, f: &mut dyn FnMut(&mut dyn Gpu, Option<&mut Renderer>));
536    fn tear_down_renderer(&mut self) -> Option<RenderingStats>;
537    fn render(&mut self, update: &Arc<UpdateParameters>) -> Option<Handoff>;
538    fn ready_for_frame(&mut self) -> bool;
539    fn with_frame(&mut self, draw: &mut dyn FnMut(&mut dyn Gpu, &FrameImage));
540    fn select_slot(&mut self, slot: usize) -> Result<(), Error>;
541    fn release_slot(&mut self, slot: usize, consumer: ConsumerSync) -> Result<(), Error>;
542    fn discard_slot(&mut self, slot: usize) -> Result<(), Error>;
543    fn exported_size(&self) -> Option<mln_gfx::Size>;
544    fn resize_exported(&mut self, size: mln_gfx::Size, held: &[usize]) -> Result<bool, Error>;
545    fn exported_image(&self, slot: usize) -> Option<ExportedFrame>;
546    fn set_ring(&mut self, ring: BorrowedRing) -> Result<GpuSync, Error>;
547    fn resize(&mut self, size: mln_gfx::Size);
548    fn read_image(&mut self) -> Result<PremultipliedImage, Error>;
549    fn release_surface(&mut self) -> Result<Option<GpuSync>, Error>;
550    fn set_surface(
551        &mut self,
552        surface: Surface,
553        overlay: Option<SurfaceOverlay>,
554        size: mln_gfx::Size,
555    ) -> Result<(), Error>;
556}
557
558/// What a session draws into.
559#[derive(Clone, Copy, PartialEq, Eq)]
560enum FramesKind {
561    Offscreen,
562    Presenting,
563    Borrowed { released: bool },
564    Exported,
565}
566
567/// A backend's GPU objects, which the session owns by value: the backend,
568/// the target it draws into, and the renderer that draws, once there is
569/// one. Each call that reaches the backend's `Gpu` lends it, for its scope,
570/// to the renderer and the target. Dropping it tears the renderer and the
571/// target down on the `Gpu`, and drops the target before the backend.
572struct BackendGfx<B: LocalBackend> {
573    // Fields drop in order: the target's native objects, such as a swap
574    // chain, go while the backend's device and `Gpu` live.
575    frames: Frames<B>,
576    renderer: Option<Renderer>,
577    backend: B,
578}
579
580/// What a [`BackendGfx`] draws into.
581enum Frames<B: LocalBackend> {
582    /// None in the browser, which renders into canvases only.
583    #[cfg(not(target_family = "wasm"))]
584    Offscreen(OffscreenTarget<B::Gpu>),
585    /// `None` once the surface is released.
586    Presenting(Option<Target<B>>),
587    /// `released` once the target let go of the ring's textures, which it
588    /// keeps without them until it gets new ones.
589    Borrowed {
590        target: Box<dyn Borrowed<B>>,
591        released: bool,
592        producer: SyncKind,
593    },
594    Exported(Box<dyn Exported<B>>),
595}
596
597impl<B: LocalBackend> Frames<B> {
598    /// The target to draw into, or `None` while there is no surface or ring.
599    fn target(&mut self) -> Option<&mut dyn FrameTarget<Gpu = B::Gpu>> {
600        match self {
601            #[cfg(not(target_family = "wasm"))]
602            Frames::Offscreen(target) => Some(target),
603            Frames::Presenting(target) => Some(&mut **target.as_mut()?),
604            Frames::Borrowed { target, released: false, .. } => Some(&mut **target),
605            Frames::Borrowed { released: true, .. } => None,
606            Frames::Exported(target) => Some(&mut **target),
607        }
608    }
609
610    /// The ring that the frames draw into.
611    fn ring(&mut self) -> Result<&mut dyn Borrowed<B>, Error> {
612        match self {
613            Frames::Borrowed { target, released: false, .. } => Ok(&mut **target),
614            Frames::Borrowed { released: true, .. } => Err(Error::invalid_state("the ring was released")),
615            _ => Err(Error::unsupported("the target has no ring")),
616        }
617    }
618}
619
620/// `backend`, and what `init` says it draws into, made on it.
621fn gfx<B: LocalBackend>(mut backend: B, init: FramesInit<'_>) -> Result<Box<dyn Gfx>, Error> {
622    let frames = match init {
623        #[cfg(not(target_family = "wasm"))]
624        FramesInit::Offscreen(size) => Frames::Offscreen(OffscreenTarget::new(size)),
625        #[cfg(target_family = "wasm")]
626        FramesInit::Offscreen(size) => {
627            let _ = size;
628            return Err(Error::unsupported("the browser build renders into canvases only"));
629        }
630        FramesInit::Borrowed(ring, producer) => {
631            let textures = B::ring_textures(ring.kind).ok_or_else(no_ring)?;
632            Frames::Borrowed { target: backend.borrowed(textures, producer)?, released: false, producer }
633        }
634        FramesInit::Exported { device, ring, kind, size, producer } => {
635            Frames::Exported(backend.exported(device, ring, kind, size, producer)?)
636        }
637        FramesInit::Surface(surface, overlay, size) => {
638            Frames::Presenting(Some(backend.surface(surface, overlay, size)?))
639        }
640    };
641    Ok(Box::new(BackendGfx { backend, frames, renderer: None }))
642}
643
644/// `backend`, presenting with `target`.
645#[cfg_attr(
646    not(any(feature = "gl", all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))),
647    expect(dead_code, reason = "only Vulkan and OpenGL make backends of a surface's own")
648)]
649fn presenting<B: LocalBackend>(backend: B, target: impl FrameTarget<Gpu = B::Gpu> + 'static) -> Box<dyn Gfx> {
650    Box::new(BackendGfx { backend, frames: Frames::Presenting(Some(Box::new(target))), renderer: None })
651}
652
653impl<B: LocalBackend> Gfx for BackendGfx<B> {
654    fn backend(&self) -> BackendRef<'_> {
655        self.backend.by_type()
656    }
657
658    fn frames(&self) -> FramesKind {
659        match &self.frames {
660            #[cfg(not(target_family = "wasm"))]
661            Frames::Offscreen(_) => FramesKind::Offscreen,
662            Frames::Presenting(_) => FramesKind::Presenting,
663            Frames::Borrowed { released, .. } => FramesKind::Borrowed { released: *released },
664            Frames::Exported(_) => FramesKind::Exported,
665        }
666    }
667
668    fn renderer(&self) -> Option<&Renderer> {
669        self.renderer.as_ref()
670    }
671
672    fn renderer_mut(&mut self) -> Option<&mut Renderer> {
673        self.renderer.as_mut()
674    }
675
676    fn renderer_or(&mut self, make: &mut dyn FnMut(&dyn Gpu) -> Renderer) -> &mut Renderer {
677        let BackendGfx { backend, renderer, .. } = self;
678        renderer.get_or_insert_with(|| make(&*backend.gpu()))
679    }
680
681    fn with_gpu(&mut self, f: &mut dyn FnMut(&mut dyn Gpu, Option<&mut Renderer>)) {
682        f(&mut *self.backend.gpu(), self.renderer.as_mut());
683    }
684
685    fn tear_down_renderer(&mut self) -> Option<RenderingStats> {
686        let renderer = self.renderer.take()?;
687        Some(renderer.tear_down(&mut *self.backend.gpu()))
688    }
689
690    fn render(&mut self, update: &Arc<UpdateParameters>) -> Option<Handoff> {
691        let renderer = self.renderer.as_mut()?;
692        let target = self.frames.target()?;
693        let mut gpu = self.backend.gpu();
694        let gpu = &mut *gpu;
695        let frame = renderer.update(gpu, update)?;
696        let image = target.begin_frame(gpu)?;
697        let drawn = renderer.render(gpu, &image, frame);
698        let handoff = target.end_frame(gpu);
699        renderer.finish_frame(gpu, drawn, handoff);
700        Some(handoff)
701    }
702
703    fn ready_for_frame(&mut self) -> bool {
704        let Some(target) = self.frames.target() else { return false };
705        target.begin_frame(&mut self.backend.gpu()).is_some()
706    }
707
708    fn with_frame(&mut self, draw: &mut dyn FnMut(&mut dyn Gpu, &FrameImage)) {
709        let Some(target) = self.frames.target() else { return };
710        let mut gpu = self.backend.gpu();
711        if let Some(image) = target.begin_frame(&mut gpu) {
712            draw(&mut *gpu, &image);
713        }
714    }
715
716    fn select_slot(&mut self, slot: usize) -> Result<(), Error> {
717        match &mut self.frames {
718            Frames::Exported(target) => target.select(slot),
719            frames => frames.ring()?.select(slot),
720        }
721        Ok(())
722    }
723
724    fn release_slot(&mut self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
725        let gpu = &mut *self.backend.gpu();
726        match &mut self.frames {
727            Frames::Exported(target) => target.release(gpu, slot, consumer),
728            frames => frames.ring()?.release(gpu, slot, consumer),
729        }
730        .map_err(gfx_error)
731    }
732
733    fn discard_slot(&mut self, slot: usize) -> Result<(), Error> {
734        let gpu = &mut *self.backend.gpu();
735        match &mut self.frames {
736            Frames::Exported(target) => target.discard(gpu, slot),
737            frames => frames.ring()?.discard(gpu, slot),
738        }
739        Ok(())
740    }
741
742    fn exported_size(&self) -> Option<mln_gfx::Size> {
743        match &self.frames {
744            Frames::Exported(target) => Some(target.size()),
745            _ => None,
746        }
747    }
748
749    fn resize_exported(&mut self, size: mln_gfx::Size, held: &[usize]) -> Result<bool, Error> {
750        match &mut self.frames {
751            Frames::Exported(target) => target.resize_images(&mut self.backend, size, held).map_err(gfx_error),
752            _ => Err(Error::unsupported("the target exports no ring")),
753        }
754    }
755
756    fn exported_image(&self, slot: usize) -> Option<ExportedFrame> {
757        match &self.frames {
758            Frames::Exported(target) => target.image(slot),
759            _ => None,
760        }
761    }
762
763    fn set_ring(&mut self, ring: BorrowedRing) -> Result<GpuSync, Error> {
764        let Frames::Borrowed { target, released, producer } = &mut self.frames else {
765            return Err(Error::unsupported("the target has no ring"));
766        };
767        let textures = B::ring_textures(ring.kind).ok_or_else(no_ring)?;
768        if !*released {
769            return target.replace(&mut self.backend.gpu(), textures).map_err(gfx_error);
770        }
771        // The released target, which kept what its release's sync names
772        // until now, goes once its frames are done.
773        let next = self.backend.borrowed(textures, *producer)?;
774        std::mem::replace(target, next).tear_down(&mut self.backend.gpu());
775        *released = false;
776        Ok(GpuSync::of(SyncKind::CpuComplete))
777    }
778
779    fn resize(&mut self, size: mln_gfx::Size) {
780        if let Some(target) = self.frames.target() {
781            target.resize(&mut self.backend.gpu(), size);
782        }
783    }
784
785    fn read_image(&mut self) -> Result<PremultipliedImage, Error> {
786        match &mut self.frames {
787            #[cfg(not(target_family = "wasm"))]
788            Frames::Offscreen(target) => {
789                let pixels = target.read_image(&mut self.backend.gpu()).map_err(gfx_error)?;
790                Ok(PremultipliedImage::from_vec(Size::new(pixels.size.width, pixels.size.height), pixels.data))
791            }
792            Frames::Presenting(_) => Err(Error::unsupported("a surface session can't read its frames back")),
793            Frames::Borrowed { .. } | Frames::Exported(_) => {
794                Err(Error::unsupported("a ring's frames are the host's to read"))
795            }
796        }
797    }
798
799    fn release_surface(&mut self) -> Result<Option<GpuSync>, Error> {
800        let gpu = &mut *self.backend.gpu();
801        match &mut self.frames {
802            Frames::Presenting(target) => {
803                if let Some(mut target) = target.take() {
804                    target.tear_down(gpu);
805                }
806                Ok(None)
807            }
808            Frames::Borrowed { released: true, .. } => Ok(Some(GpuSync::of(SyncKind::CpuComplete))),
809            Frames::Borrowed { target, released, .. } => {
810                let sync = target.release_textures(gpu).map_err(gfx_error)?;
811                *released = true;
812                Ok(Some(sync))
813            }
814            #[cfg(not(target_family = "wasm"))]
815            Frames::Offscreen(_) => Ok(None),
816            Frames::Exported(_) => Ok(None),
817        }
818    }
819
820    fn set_surface(
821        &mut self,
822        surface: Surface,
823        overlay: Option<SurfaceOverlay>,
824        size: mln_gfx::Size,
825    ) -> Result<(), Error> {
826        let target = self.backend.surface(surface, overlay, size)?;
827        if let Frames::Presenting(old) = &mut self.frames
828            && let Some(mut old) = old.take()
829        {
830            old.tear_down(&mut self.backend.gpu());
831        }
832        self.frames = Frames::Presenting(Some(target));
833        Ok(())
834    }
835}
836
837impl<B: LocalBackend> Drop for BackendGfx<B> {
838    fn drop(&mut self) {
839        let mut gpu = self.backend.gpu();
840        if let Some(renderer) = self.renderer.take() {
841            renderer.tear_down(&mut *gpu);
842        }
843        // A released ring keeps the objects that its release's sync names.
844        if let Frames::Borrowed { target, .. } = &mut self.frames {
845            target.tear_down(&mut gpu);
846        } else if let Some(target) = self.frames.target() {
847            target.tear_down(&mut gpu);
848        }
849    }
850}
851
852/// A backend on `device`, and what `init` says it draws into.
853fn new_gfx(device: &Device, init: FramesInit<'_>) -> Result<Box<dyn Gfx>, Error> {
854    match device {
855        #[cfg(feature = "webgpu")]
856        Device::WebGpu(device) => gfx(mln_webgpu::RendererBackend::new(device), init),
857        #[cfg(all(feature = "metal", target_vendor = "apple"))]
858        Device::Metal(device) => gfx(mln_mtl::RendererBackend::new(device), init),
859        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
860        Device::Vulkan(device) => gfx(mln_vulkan::RendererBackend::new(device).map_err(gfx_error)?, init),
861        #[cfg(all(feature = "d3d12", windows))]
862        Device::D3d12(device) => {
863            gfx(mln_d3d12::RendererBackend::new(device).map_err(|error| Error::failed(error.to_string()))?, init)
864        }
865        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
866        Device::Gl(device) => gfx(mln_gl::RendererBackend::new(device).map_err(gfx_error)?, init),
867        #[cfg(all(feature = "gl", target_family = "wasm"))]
868        Device::WebGl => {
869            drop(init);
870            Err(Error::unsupported("WebGL2 renders only into a canvas, with the canvas's own context"))
871        }
872    }
873}
874
875/// The overlay of the backend that `own` picks out of `overlay`. Fails with
876/// `Unsupported` for another backend's.
877#[cfg_attr(
878    not(any(
879        feature = "webgpu",
880        all(feature = "metal", target_vendor = "apple"),
881        all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))),
882        all(feature = "d3d12", windows),
883        all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))),
884    )),
885    expect(dead_code, reason = "a build without a backend that takes overlays uses none")
886)]
887fn overlay_of<T>(
888    overlay: Option<SurfaceOverlay>,
889    own: impl FnOnce(SurfaceOverlay) -> Result<T, SurfaceOverlay>,
890) -> Result<Option<T>, Error> {
891    overlay
892        .map(own)
893        .transpose()
894        .map_err(|_| Error::unsupported("the surface's overlay is for another backend than the session's"))
895}
896
897#[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
898fn vulkan_overlay(overlay: Option<SurfaceOverlay>) -> Result<Option<Box<dyn mln_vulkan::Overlay>>, Error> {
899    overlay_of(overlay, |overlay| match overlay {
900        SurfaceOverlay::Vulkan(overlay) => Ok(overlay),
901        other => Err(other),
902    })
903}
904
905/// A wgpu surface of `kind`, made with the instance of `backend`'s device
906/// where the host didn't make it.
907#[cfg(feature = "webgpu")]
908fn webgpu_surface(backend: &mln_webgpu::RendererBackend, kind: SurfaceKind) -> Result<wgpu::Surface<'static>, Error> {
909    let instance = || {
910        backend
911            .device()
912            .instance()
913            .ok_or_else(|| Error::invalid_argument("the session's device has no instance to make a surface with"))
914    };
915    let made = match kind {
916        #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
917        SurfaceKind::Wgpu(surface) => return Ok(surface),
918        SurfaceKind::Window(window) => instance()?.create_surface(window),
919        #[cfg(target_family = "wasm")]
920        SurfaceKind::WebCanvas { canvas, .. } => {
921            use wasm_bindgen::JsCast as _;
922            let target = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
923                Ok(canvas) => wgpu::SurfaceTarget::OffscreenCanvas(canvas),
924                Err(canvas) => wgpu::SurfaceTarget::Canvas(canvas.unchecked_into()),
925            };
926            instance()?.create_surface(target)
927        }
928        #[cfg(all(feature = "metal", target_vendor = "apple"))]
929        SurfaceKind::MetalLayer(_) => return Err(Error::unsupported("a Metal layer presents on a Metal device")),
930        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
931        SurfaceKind::Vulkan(_) => return Err(Error::unsupported("a Vulkan surface presents on a Vulkan device")),
932        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
933        SurfaceKind::Gl(_) => return Err(Error::unsupported("an EGL surface presents on an OpenGL device")),
934        #[cfg(all(feature = "d3d12", windows))]
935        SurfaceKind::D3d12Composition { .. } => {
936            return Err(Error::unsupported("a composition swap chain presents on a D3D12 device"));
937        }
938    };
939    made.map_err(|error| Error::failed(format!("can't make a surface on the window: {error}")))
940}
941
942/// A backend of the target's own on `device` and a target that presents to
943/// `surface` with `overlay` drawn over its frames, for the backends whose
944/// context or device is made for the window: Vulkan's, whose instance and
945/// device take the window's surface extensions, and OpenGL ES's, whose
946/// context is of the window's display.
947fn surface_backend(
948    device: &Device,
949    surface: Surface,
950    overlay: Option<SurfaceOverlay>,
951    size: mln_gfx::Size,
952) -> Result<Box<dyn Gfx>, Error> {
953    let cap_frame_rate = surface.cap_frame_rate;
954    match (device, surface.kind) {
955        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
956        (Device::Vulkan(device), SurfaceKind::Window(window)) => {
957            let overlay = vulkan_overlay(overlay)?;
958            let (mut backend, mut target) =
959                mln_vulkan::SurfaceTarget::with_backend(device, window, size, cap_frame_rate).map_err(gfx_error)?;
960            target.set_overlay(backend.gpu(), overlay);
961            Ok(presenting(backend, target))
962        }
963        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
964        (Device::Vulkan(device), kind @ SurfaceKind::Vulkan(_)) => gfx(
965            mln_vulkan::RendererBackend::presenting(device).map_err(gfx_error)?,
966            FramesInit::Surface(Surface { kind, cap_frame_rate }, overlay, size),
967        ),
968        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
969        (Device::Gl(device), SurfaceKind::Gl(host)) => {
970            if overlay.is_some() {
971                return Err(Error::unsupported("a host's EGL surface takes no overlay"));
972            }
973            let (backend, target) = mln_gl::HostSurfaceTarget::with_backend(device, host, size).map_err(gfx_error)?;
974            Ok(presenting(backend, target))
975        }
976        #[cfg(all(feature = "gl", any(windows, all(unix, not(target_vendor = "apple")))))]
977        (Device::Gl(_), SurfaceKind::Window(window)) => {
978            let overlay = overlay_of(overlay, |overlay| match overlay {
979                SurfaceOverlay::Gl(overlay) => Ok(overlay),
980                other => Err(other),
981            })?;
982            let (mut backend, mut target) =
983                mln_gl::SurfaceTarget::with_backend(window, size, cap_frame_rate).map_err(gfx_error)?;
984            target.set_overlay(&mut backend.gpu(), overlay);
985            Ok(presenting(backend, target))
986        }
987        #[cfg(all(feature = "gl", target_family = "wasm"))]
988        (Device::WebGl, SurfaceKind::WebCanvas { canvas, .. }) => {
989            use wasm_bindgen::JsCast as _;
990            // WebGL draws no overlay.
991            let canvas = match canvas.dyn_into::<web_sys::OffscreenCanvas>() {
992                Ok(canvas) => mln_gl::WebCanvas::Offscreen(canvas),
993                Err(canvas) => mln_gl::WebCanvas::Element(canvas.unchecked_into()),
994            };
995            let (backend, target) = mln_gl::CanvasTarget::with_backend(canvas, size).map_err(gfx_error)?;
996            Ok(presenting(backend, target))
997        }
998        (_, kind) => new_gfx(device, FramesInit::Surface(Surface { kind, cap_frame_rate }, overlay, size)),
999    }
1000}
1001
1002/// A target's backend, by its type, for a host that reads what the backend
1003/// tells of its device.
1004#[non_exhaustive]
1005pub enum BackendRef<'a> {
1006    #[cfg(feature = "webgpu")]
1007    WebGpu(&'a mln_webgpu::RendererBackend),
1008    #[cfg(all(feature = "metal", target_vendor = "apple"))]
1009    Metal(&'a mln_mtl::RendererBackend),
1010    #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1011    Vulkan(&'a mln_vulkan::RendererBackend),
1012    #[cfg(all(feature = "d3d12", windows))]
1013    D3d12(&'a mln_d3d12::RendererBackend),
1014    #[cfg(feature = "gl")]
1015    Gl(&'a mln_gl::RendererBackend),
1016}
1017
1018/// A render target built on this thread: the backend, on the target's
1019/// device, the frames it draws into, and the renderer that draws them,
1020/// which the target owns and lends the backend's `Gpu` to.
1021pub struct LocalTarget {
1022    device: Device,
1023    gfx: Box<dyn Gfx>,
1024    /// The window that a surface target presents to, if it presents to one.
1025    window: Option<Arc<dyn Window>>,
1026}
1027
1028impl LocalTarget {
1029    /// An offscreen target of `size` pixels on `device`, or on a device that
1030    /// [`Device::new`] makes when that is `None`.
1031    ///
1032    /// Fails as [`Device::new`] does, and with the backend's error when it
1033    /// can't render on the device.
1034    pub fn offscreen(device: Option<Device>, size: Size) -> Result<LocalTarget, Error> {
1035        let device = match device {
1036            Some(device) => device,
1037            None => Device::new(DeviceOptions::default())?,
1038        };
1039        let gfx = new_gfx(&device, FramesInit::Offscreen(gfx_size(size)))?;
1040        Ok(LocalTarget { device, gfx, window: None })
1041    }
1042
1043    /// A target of `size` pixels that presents to `surface`, with `overlay`
1044    /// drawn over its frames, on `device` or, when that is `None`, on the
1045    /// device the surface's kind takes
1046    /// ([`RenderTarget::Surface`](super::RenderTarget::Surface)).
1047    ///
1048    /// Fails with [`ErrorKind::InvalidArgument`](mln_style::error::ErrorKind) for a
1049    /// surface that the host made without the host's device, with
1050    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) for a window or
1051    /// surface without an area to present to, such as a minimized window,
1052    /// with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the device
1053    /// can't present to the surface or draw the overlay, and with the error
1054    /// of the device or the window's surface.
1055    pub fn surface(
1056        surface: Surface,
1057        overlay: Option<SurfaceOverlay>,
1058        device: Option<Device>,
1059        size: Size,
1060    ) -> Result<LocalTarget, Error> {
1061        surface.check_area()?;
1062        let window = surface.host_window();
1063        let device = match device {
1064            Some(device) => device,
1065            None => default_surface_device(&surface)?,
1066        };
1067        let gfx = surface_backend(&device, surface, overlay, gfx_size(size))?;
1068        Ok(LocalTarget { device, gfx, window })
1069    }
1070
1071    /// A target of `size` pixels on `device` that renders into the host's
1072    /// `ring`, and hands each frame over with sync of the kind `producer`.
1073    ///
1074    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the
1075    /// device can't render into the ring with `producer`, and with the
1076    /// backend's error.
1077    pub fn borrowed(device: Device, ring: BorrowedRing, producer: SyncKind) -> Result<LocalTarget, Error> {
1078        let gfx = new_gfx(&device, FramesInit::Borrowed(ring, producer))?;
1079        Ok(LocalTarget { device, gfx, window: None })
1080    }
1081
1082    /// A target on `device` that renders into a ring of `ring.depth` images
1083    /// of `size` pixels, which it exports as `kind`, one that
1084    /// [`Device::export_plan`] picked, and hands each frame over with sync of
1085    /// the kind `producer`.
1086    ///
1087    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) when the
1088    /// device can't export `kind` or hand frames over with `producer`, and
1089    /// with the backend's error.
1090    pub fn exported(
1091        device: Device,
1092        ring: &ExportedRing,
1093        kind: ExportKind,
1094        size: Size,
1095        producer: SyncKind,
1096    ) -> Result<LocalTarget, Error> {
1097        let gfx =
1098            new_gfx(&device, FramesInit::Exported { device: &device, ring, kind, size: gfx_size(size), producer })?;
1099        Ok(LocalTarget { device, gfx, window: None })
1100    }
1101
1102    /// The device the target renders on.
1103    #[must_use]
1104    pub fn device(&self) -> &Device {
1105        &self.device
1106    }
1107
1108    /// The backend the target and its renderer draw with.
1109    #[must_use]
1110    pub fn backend(&self) -> BackendRef<'_> {
1111        self.gfx.backend()
1112    }
1113
1114    /// Runs `f` with the backend's `Gpu`, as when the host waits for the
1115    /// frames drawn so far.
1116    pub fn with_gpu(&mut self, mut f: impl FnMut(&mut dyn Gpu)) {
1117        self.gfx.with_gpu(&mut |gpu, _| f(gpu));
1118    }
1119
1120    /// The renderer that draws into the target, which `make` makes with the
1121    /// backend's `Gpu` unless the target has one: the renderer draws with
1122    /// that `Gpu` only.
1123    pub fn renderer_or(&mut self, mut make: impl FnMut(&dyn Gpu) -> Renderer) -> &mut Renderer {
1124        self.gfx.renderer_or(&mut make)
1125    }
1126
1127    /// The renderer that draws into the target, if it has one.
1128    #[must_use]
1129    pub fn renderer(&self) -> Option<&Renderer> {
1130        self.gfx.renderer()
1131    }
1132
1133    /// The renderer that draws into the target, if it has one.
1134    pub fn renderer_mut(&mut self) -> Option<&mut Renderer> {
1135        self.gfx.renderer_mut()
1136    }
1137
1138    /// Runs `f` with the target's renderer and the backend's `Gpu`, which the
1139    /// renderer's calls that make, draw or free its GPU objects take, or
1140    /// returns `None` without a renderer.
1141    pub fn with_renderer<R>(&mut self, f: impl FnOnce(&mut Renderer, &mut dyn Gpu) -> R) -> Option<R> {
1142        self.gfx.renderer()?;
1143        let (mut f, mut result) = (Some(f), None);
1144        self.gfx.with_gpu(&mut |gpu, renderer| {
1145            if let (Some(renderer), Some(f)) = (renderer, f.take()) {
1146                result = Some(f(renderer, gpu));
1147            }
1148        });
1149        result
1150    }
1151
1152    /// Tears the renderer down on the backend's `Gpu`, if the target has
1153    /// one, and returns its rendering stats as it leaves them.
1154    pub fn tear_down_renderer(&mut self) -> Option<RenderingStats> {
1155        self.gfx.tear_down_renderer()
1156    }
1157
1158    /// Draws `update` with the target's renderer into a frame: the target
1159    /// begins the frame, the renderer draws into it, and the target ends
1160    /// it. Returns where the frame went, or `None` when nothing was drawn:
1161    /// there is no renderer, the target had nothing to draw into, or there
1162    /// was nothing to draw.
1163    pub fn render(&mut self, update: &Arc<UpdateParameters>) -> Option<Handoff> {
1164        self.gfx.render(update)
1165    }
1166
1167    /// Runs `draw` with the backend's `Gpu` and the textures of the target's
1168    /// frame, to draw into them alongside the map. The frame is the one the
1169    /// next render draws into, which the target begins unless it has
1170    /// begun it. `None` when the target has nothing to draw into now.
1171    pub fn with_frame<R>(&mut self, draw: impl FnOnce(&mut dyn Gpu, &FrameImage) -> R) -> Option<R> {
1172        let (mut draw, mut result) = (Some(draw), None);
1173        self.gfx.with_frame(&mut |gpu, image| result = draw.take().map(|draw| draw(gpu, image)));
1174        result
1175    }
1176
1177    /// Whether the target can take a frame now: its window, if any, has an
1178    /// area to present to, and it begins a frame, which a surface needs a
1179    /// texture for, and which the next render draws into.
1180    pub fn ready_for_frame(&mut self) -> bool {
1181        self.window_has_area() && self.gfx.ready_for_frame()
1182    }
1183
1184    /// Whether the target can take a frame as far as its window says: it
1185    /// presents to no window, or to one with an area to present to
1186    /// ([`mln_gfx::window::has_area`]).
1187    #[must_use]
1188    pub fn window_has_area(&self) -> bool {
1189        self.window.as_deref().is_none_or(mln_gfx::window::has_area)
1190    }
1191
1192    /// Whether frames are presented to a window or surface.
1193    #[must_use]
1194    pub fn is_presenting(&self) -> bool {
1195        self.gfx.frames() == FramesKind::Presenting
1196    }
1197
1198    /// Whether frames go to the host in images of the target's own.
1199    #[must_use]
1200    pub fn is_exported(&self) -> bool {
1201        self.gfx.frames() == FramesKind::Exported
1202    }
1203
1204    /// Whether frames go to the host's ring.
1205    #[must_use]
1206    pub fn is_borrowed(&self) -> bool {
1207        matches!(self.gfx.frames(), FramesKind::Borrowed { .. })
1208    }
1209
1210    /// Whether the target is a ring that let go of its textures.
1211    #[must_use]
1212    pub fn ring_released(&self) -> bool {
1213        self.gfx.frames() == FramesKind::Borrowed { released: true }
1214    }
1215
1216    /// Whether frames are read back rather than presented.
1217    #[must_use]
1218    pub fn is_offscreen(&self) -> bool {
1219        self.gfx.frames() == FramesKind::Offscreen
1220    }
1221
1222    /// Has the next frame render into the ring's texture at `slot`.
1223    pub fn select_slot(&mut self, slot: usize) -> Result<(), Error> {
1224        self.gfx.select_slot(slot)
1225    }
1226
1227    /// The host gave the ring's texture at `slot` back: the next frame
1228    /// rendered into it waits for `consumer`.
1229    pub fn release_slot(&mut self, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
1230        self.gfx.release_slot(slot, consumer)
1231    }
1232
1233    /// The host gave up the ring's texture at `slot`, which the target
1234    /// renders into no more.
1235    pub fn discard_slot(&mut self, slot: usize) -> Result<(), Error> {
1236        self.gfx.discard_slot(slot)
1237    }
1238
1239    /// The size in pixels of an exported ring's images, or `None` for
1240    /// another target.
1241    #[must_use]
1242    pub fn exported_size(&self) -> Option<Size> {
1243        self.gfx.exported_size().map(|size| Size::new(size.width, size.height))
1244    }
1245
1246    /// Renders an exported ring's next frames into images of `size` pixels.
1247    /// The frames that the host holds, at `held` slots, keep their images.
1248    /// Returns whether the ring has new images, which it doesn't when they
1249    /// have `size` already.
1250    ///
1251    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1252    /// target that isn't an exported ring, and with the backend's error, when
1253    /// the ring keeps its images.
1254    pub fn resize_exported(&mut self, size: Size, held: &[usize]) -> Result<bool, Error> {
1255        self.gfx.resize_exported(gfx_size(size), held)
1256    }
1257
1258    /// The exported image of the frame at `slot`, of the size it has.
1259    #[must_use]
1260    pub fn exported_texture(&self, slot: usize) -> Option<FrameTexture> {
1261        let image = self.gfx.exported_image(slot)?;
1262        Some(FrameTexture::exported(image, &self.device))
1263    }
1264
1265    /// Renders into `ring` from now on, in place of the ring's textures, and
1266    /// returns the sync after which the host may use the textures that it
1267    /// let go of: of the target's producer kind, or
1268    /// [`SyncKind::CpuComplete`] when it had none since a release.
1269    ///
1270    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1271    /// target that isn't a ring, or a ring of another format, and with the
1272    /// backend's error. The target then keeps its textures.
1273    pub(crate) fn set_ring(&mut self, ring: BorrowedRing) -> Result<GpuSync, Error> {
1274        self.gfx.set_ring(ring)
1275    }
1276
1277    /// Draws the next frame at `size` pixels.
1278    pub fn resize(&mut self, size: Size) {
1279        self.gfx.resize(gfx_size(size));
1280    }
1281
1282    /// The last frame's pixels.
1283    ///
1284    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for a
1285    /// target that presents its frames, with
1286    /// [`ErrorKind::InvalidState`](mln_style::error::ErrorKind) before a frame, and
1287    /// with [`ErrorKind::Failed`](mln_style::error::ErrorKind) where the backend
1288    /// reads nothing back.
1289    pub fn read_image(&mut self) -> Result<PremultipliedImage, Error> {
1290        self.gfx.read_image()
1291    }
1292
1293    /// Lets go of a surface target's surface, or of a ring's textures, and
1294    /// returns, for a ring, the sync after which the host may use them. The
1295    /// backend and its renderer stay.
1296    ///
1297    /// Fails with [`ErrorKind::Failed`](mln_style::error::ErrorKind) when a ring
1298    /// can't submit its work on the textures, which it keeps then.
1299    pub(crate) fn release_surface(&mut self) -> Result<Option<GpuSync>, Error> {
1300        let sync = self.gfx.release_surface()?;
1301        if self.is_presenting() {
1302            self.window = None;
1303        }
1304        Ok(sync)
1305    }
1306
1307    /// Presents to `surface` at `size` pixels from now on, with `overlay`
1308    /// drawn over its frames, in place of the surface the target has, if
1309    /// any: on the same backend where it can present to `surface`, and on a
1310    /// new one of the device otherwise, which the target then returns true
1311    /// for, and which draws no overlay. The renderer on the old backend is
1312    /// torn down with it, and the target has none until one is made again
1313    /// on the new backend ([`renderer_or`](Self::renderer_or)).
1314    ///
1315    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind) for an
1316    /// offscreen target or when the device can't present to `surface`, and
1317    /// as [`surface`](Self::surface) does. The target then keeps what it
1318    /// had.
1319    pub fn set_surface(
1320        &mut self,
1321        surface: Surface,
1322        overlay: Option<SurfaceOverlay>,
1323        size: Size,
1324    ) -> Result<bool, Error> {
1325        if !self.is_presenting() {
1326            return Err(Error::unsupported("only a surface target presents to another surface"));
1327        }
1328        surface.check_area()?;
1329        let window = surface.host_window();
1330        let retry = surface.clone_window();
1331        let size = gfx_size(size);
1332        let new_backend = match self.gfx.set_surface(surface, overlay, size) {
1333            Ok(()) => false,
1334            Err(error) if error.kind == mln_style::error::ErrorKind::Unsupported => {
1335                let surface = retry.ok_or(error)?;
1336                self.gfx = surface_backend(&self.device, surface, None, size)?;
1337                true
1338            }
1339            Err(error) => return Err(error),
1340        };
1341        self.window = window;
1342        Ok(new_backend)
1343    }
1344}
1345
1346/// The device a surface renders on without the host's: the native one where
1347/// its backend takes the surface's kind.
1348fn default_surface_device(surface: &Surface) -> Result<Device, Error> {
1349    match surface.kind {
1350        SurfaceKind::Window(_) => Device::new(DeviceOptions::default()),
1351        #[cfg(all(feature = "metal", target_vendor = "apple"))]
1352        SurfaceKind::MetalLayer(_) => Device::with_backend(super::target::BackendType::Metal, DeviceOptions::default()),
1353        #[cfg(all(feature = "webgpu", not(target_family = "wasm")))]
1354        SurfaceKind::Wgpu(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
1355        #[cfg(all(feature = "vulkan", not(any(target_vendor = "apple", target_family = "wasm"))))]
1356        SurfaceKind::Vulkan(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
1357        #[cfg(all(feature = "gl", not(target_family = "wasm")))]
1358        SurfaceKind::Gl(_) => Err(Error::invalid_argument("a surface that the host made needs the host's device")),
1359        #[cfg(all(feature = "d3d12", windows))]
1360        SurfaceKind::D3d12Composition { .. } => {
1361            Device::with_backend(super::target::BackendType::D3D12, DeviceOptions::default())
1362        }
1363        // A WebGPU build asked the browser for a device before the build.
1364        #[cfg(all(target_family = "wasm", feature = "gl"))]
1365        SurfaceKind::WebCanvas { .. } => Ok(Device::WebGl),
1366        #[cfg(all(target_family = "wasm", not(feature = "gl")))]
1367        SurfaceKind::WebCanvas { .. } => Err(Error::invalid_state("the browser's WebGPU device isn't there yet")),
1368    }
1369}