Skip to main content

mln_gfx/
ring.rs

1//! Ring targets: a [`BorrowedTarget`] draws frames into a ring of the host's
2//! textures and gives each back, and an [`ExportedTarget`] draws into a ring
3//! of images of its own, which it exports, through a borrowed target over
4//! each generation of them.
5//!
6//! A backend implements [`RingTextures`] for the host's textures,
7//! [`RingBackend`], which imports them into its `Gpu` and makes the sync with
8//! which each side waits for the other, and [`Exporter`], which allocates an
9//! exported ring's images. The targets here do the rest: which slot a frame
10//! draws into, which of the host's reads it waits for, what a texture that
11//! the ring has again keeps across a replacement, and the older generations
12//! that a resize leaves to the frames the host holds.
13
14use crate::error::Error;
15use crate::export::{ExportKind, ExportedFrame, ExportedRing, Generations};
16use crate::frame::{ConsumerSync, FrameImage, FrameTarget, GpuSync, Handoff, SyncKind};
17use crate::gpu::{Gpu, GpuError, ResourceId, TargetFormats, TextureDesc, TextureId, TextureUsage, destroy_unused};
18use crate::log_target;
19use crate::renderer_backend::RendererBackend;
20use crate::size::Size;
21
22/// The host's textures of a ring: one color texture for each slot, and
23/// either one depth and stencil texture for each slot or none, in which
24/// case frames draw into one of the target's own.
25pub trait RingTextures {
26    /// One of the host's color textures, as the backend's API names it.
27    type Image;
28
29    /// The color textures, one for each slot.
30    fn images(&self) -> &[Self::Image];
31
32    /// Whether `a` and `b` are the same texture of the host's.
33    fn same_image(a: &Self::Image, b: &Self::Image) -> bool;
34
35    /// The size of the textures, in physical pixels.
36    fn size(&self) -> Size;
37
38    /// Whether the host gave depth and stencil textures.
39    fn has_depth(&self) -> bool;
40}
41
42/// A backend's part of a [`BorrowedTarget`]: the objects that its frames
43/// signal, and how the host's textures and syncs become textures and waits
44/// of its `Gpu`.
45pub trait RingBackend: Sized {
46    /// The backend's `Gpu`, which the host's textures are imported into.
47    type Gpu: Gpu;
48    /// The backend that the target is built on.
49    type Renderer: RendererBackend<Gpu = Self::Gpu>;
50    /// The host's textures.
51    type Textures: RingTextures;
52    /// What the next frame drawn into a slot waits for: the host's reads of
53    /// the slot's texture.
54    type Wait;
55    /// What a slot's last frame handed the host and the target keeps until
56    /// the host gives the slot back, such as a sync file.
57    type Handed;
58
59    /// The ring's objects for frames drawn into `textures` on `backend` and
60    /// handed to the host with sync of the kind `producer`, once both are
61    /// checked: `textures` against the backend's device, and `producer`
62    /// against the kinds with which the backend hands frames over.
63    fn new(backend: &mut Self::Renderer, textures: &Self::Textures, producer: SyncKind) -> Result<Self, Error>;
64
65    /// Checks that `next`, as many textures as `current`, may replace them:
66    /// textures of their formats, with depth textures where they have them,
67    /// and as [`new`](Self::new) checks them.
68    fn check_replacement(&self, current: &Self::Textures, next: &Self::Textures) -> Result<(), Error>;
69
70    /// The formats that frames draw into `textures` in. Where the host gave
71    /// no depth textures, the depth and stencil format is that of the
72    /// target's own, which it names.
73    fn targets(gpu: &Self::Gpu, textures: &Self::Textures) -> Result<TargetFormats, Error>;
74
75    /// Imports the host's color texture at `slot` into `gpu`, or with
76    /// `depth`, its depth and stencil texture.
77    fn import(gpu: &mut Self::Gpu, textures: &Self::Textures, slot: usize, depth: bool) -> Result<TextureId, GpuError>;
78
79    /// What the next frame drawn into a slot waits for, once the host gave
80    /// the slot back with `consumer`, or `None` when it waits for nothing.
81    fn wait_for(&mut self, gpu: &mut Self::Gpu, consumer: ConsumerSync) -> Result<Option<Self::Wait>, Error>;
82
83    /// Has the next submit of `gpu` that draws into `texture` wait for
84    /// `wait`.
85    fn wait_before_using(gpu: &mut Self::Gpu, texture: TextureId, wait: &Self::Wait) -> Result<(), GpuError> {
86        let _ = (gpu, texture, wait);
87        Ok(())
88    }
89
90    /// Has the next submit of `gpu` wait for what `texture` waits for,
91    /// though nothing drew into it.
92    fn take_waits_into_next_submit(gpu: &mut Self::Gpu, texture: TextureId) {
93        let _ = (gpu, texture);
94    }
95
96    /// Drops what `texture` waits for, which no submit of `gpu` takes now.
97    /// Returns whether it waited for something, which no pass took: false
98    /// where a pass that drew into it took its waits into a submit.
99    fn forget_waits(gpu: &mut Self::Gpu, texture: TextureId) -> bool {
100        let _ = (gpu, texture);
101        false
102    }
103
104    /// A submit of `gpu` took `wait`, or may have, which the ring lets go of
105    /// once the work submitted so far and the next submit's is done.
106    fn waited(gpu: &mut Self::Gpu, wait: Self::Wait) {
107        let _ = (gpu, wait);
108    }
109
110    /// Prepares the ring's commands for submission, before the target flushes
111    /// and signals the producer's sync. `slot` is the slot of the frame
112    /// ending, or `None` when the target is releasing or replacing its
113    /// textures. Returning `false` drops the frame.
114    fn prepare_submit(&mut self, gpu: &mut Self::Gpu, textures: &Self::Textures, slot: Option<usize>) -> bool {
115        let _ = (gpu, textures, slot);
116        true
117    }
118
119    /// Has the next submit of `gpu` signal the object that the host waits
120    /// on for a frame, for a producer kind that names one.
121    fn signal_after_next_submit(&mut self, gpu: &mut Self::Gpu) {
122        let _ = gpu;
123    }
124
125    /// The sync that the host waits for, once the frame was submitted, for
126    /// a producer kind that names an object, and what the slot keeps of it
127    /// until the host gives it back. `None` when there is none, which drops
128    /// the frame. A frame that hands nothing to keep leaves what the slot
129    /// kept of an earlier frame until the host gives the slot back.
130    fn producer_sync(&mut self, gpu: &mut Self::Gpu) -> Option<(GpuSync, Option<Self::Handed>)> {
131        let _ = gpu;
132        None
133    }
134
135    /// Releases what a frame or texture release handed the host, with `gpu`,
136    /// when the target drops it before its own [`Drop`].
137    fn release_handed(gpu: &mut Self::Gpu, handed: Self::Handed) {
138        let _ = (gpu, handed);
139    }
140
141    /// Lets go of the objects that the frames signal once the work
142    /// submitted so far is done, as the target goes.
143    fn tear_down(&mut self, gpu: &mut Self::Gpu) {
144        let _ = gpu;
145    }
146
147    /// Blocks until the work submitted so far is done, where the backend
148    /// must before a target dropped without its tear-down, and so without
149    /// the `Gpu` to defer to, lets go of what the frames used. Logs `what`
150    /// was going on when the wait fails.
151    fn wait_for_frames(&self, what: &str) {
152        let _ = what;
153    }
154
155    /// Lets go of `wait`, which no submit takes.
156    fn forget(wait: Self::Wait) {
157        let _ = wait;
158    }
159}
160
161/// A ring's textures as textures of the backend's `Gpu`, with their depth
162/// and stencil textures: the host's, or one of the target's own.
163pub struct Imports {
164    size: Size,
165    targets: TargetFormats,
166    color: Vec<TextureId>,
167    /// The host's depth and stencil textures, one for each slot.
168    depth: Vec<TextureId>,
169    /// The target's own depth and stencil, when the host gave none.
170    own_depth: Option<TextureId>,
171}
172
173impl Imports {
174    /// Imports `textures` into `gpu`, and makes a depth and stencil texture
175    /// of the target's own where the host gave none.
176    ///
177    /// Fails as [`RingBackend::targets`] does, and with
178    /// [`ErrorKind::Failed`](crate::ErrorKind) when `gpu` can't import a
179    /// texture or make the depth and stencil texture. What it imported is
180    /// then destroyed.
181    pub fn new<B: RingBackend>(gpu: &mut B::Gpu, textures: &B::Textures) -> Result<Imports, Error> {
182        let mut imports = Imports {
183            size: textures.size(),
184            targets: B::targets(gpu, textures)?,
185            color: Vec::new(),
186            depth: Vec::new(),
187            own_depth: None,
188        };
189        match imports.import::<B>(gpu, textures) {
190            Ok(()) => Ok(imports),
191            Err(error) => {
192                imports.tear_down(gpu);
193                Err(error)
194            }
195        }
196    }
197
198    fn import<B: RingBackend>(&mut self, gpu: &mut B::Gpu, textures: &B::Textures) -> Result<(), Error> {
199        let import = |gpu: &mut B::Gpu, slot, depth| {
200            B::import(gpu, textures, slot, depth)
201                .map_err(|error| Error::failed(format!("Importing a borrowed texture failed: {error}")))
202        };
203        let slots = textures.images().len();
204        for slot in 0..slots {
205            self.color.push(import(gpu, slot, false)?);
206        }
207        if textures.has_depth() {
208            for slot in 0..slots {
209                self.depth.push(import(gpu, slot, true)?);
210            }
211        } else {
212            let format = self
213                .targets
214                .depth_stencil
215                .ok_or_else(|| Error::unsupported("the ring names no format of its depth and stencil"))?;
216            let desc = TextureDesc {
217                label: "BorrowedDepthStencil",
218                size: self.size,
219                format,
220                usage: TextureUsage { sampled: false, render_target: true, copy_src: false },
221                mipmapped: false,
222            };
223            let texture = gpu
224                .create_texture(&desc)
225                .map_err(|error| Error::failed(format!("Making the depth and stencil texture failed: {error}")))?;
226            self.own_depth = Some(texture);
227        }
228        Ok(())
229    }
230
231    /// The textures that a frame drawn into `slot` draws into.
232    fn frame_image(&self, slot: usize) -> Option<FrameImage> {
233        Some(FrameImage {
234            size: self.size,
235            color: *self.color.get(slot)?,
236            depth_stencil: self.own_depth.or_else(|| self.depth.get(slot).copied()),
237            targets: self.targets,
238        })
239    }
240
241    /// Destroys the imports in `gpu`, which keeps what the work submitted
242    /// so far uses until it finishes.
243    fn tear_down(&mut self, gpu: &mut (impl Gpu + ?Sized)) {
244        let textures = self.color.drain(..).chain(self.depth.drain(..)).chain(self.own_depth.take());
245        destroy_unused(gpu, textures.map(ResourceId::Texture));
246    }
247}
248
249/// What the next frame drawn into a slot waits for, and what the slot's
250/// last frame handed the host.
251struct Slot<B: RingBackend> {
252    wait: Option<B::Wait>,
253    /// The texture that has the next submit that draws into it wait for
254    /// `wait`, from the frame begun on the slot until it ends.
255    attached: Option<TextureId>,
256    handed: Option<B::Handed>,
257}
258
259impl<B: RingBackend> Slot<B> {
260    fn new(wait: Option<B::Wait>) -> Self {
261        Slot { wait, attached: None, handed: None }
262    }
263
264    /// Lets go of what the slot waits for, and of what the slot handed the
265    /// host: at once, unless a pass of a frame begun on the slot took the
266    /// wait into a submit, which the wait then outlives.
267    fn forget(&mut self, gpu: &mut B::Gpu) {
268        let taken = self.detach(gpu);
269        if let Some(wait) = self.wait.take() {
270            if taken { B::waited(gpu, wait) } else { B::forget(wait) }
271        }
272        if let Some(handed) = self.handed.take() {
273            B::release_handed(gpu, handed);
274        }
275    }
276
277    /// Ends the frame begun on the slot, if any, without a submit of its
278    /// own. Returns whether a pass that drew took the slot's wait into a
279    /// submit; otherwise the wait is the next frame's still.
280    fn detach(&mut self, gpu: &mut B::Gpu) -> bool {
281        self.attached.take().is_some_and(|texture| !B::forget_waits(gpu, texture))
282    }
283}
284
285/// Frames drawn into the host's textures, each given back to the host.
286pub struct BorrowedTarget<B: RingBackend> {
287    /// `None` once the target let go of them.
288    textures: Option<B::Textures>,
289    imports: Imports,
290    /// The slot the next frame draws into.
291    selected: usize,
292    slots: Vec<Slot<B>>,
293    producer: SyncKind,
294    /// What the sync of the last release or replacement of the textures
295    /// handed the host, until the next one or the target goes.
296    handed: Option<B::Handed>,
297    /// Whether a tear-down deferred the release of what the frames use,
298    /// after which dropping the target needs no wait.
299    torn_down: bool,
300    ring: B,
301}
302
303impl<B: RingBackend> BorrowedTarget<B> {
304    /// A target on `backend` that draws into `textures` and hands each frame
305    /// to the host with sync of the kind `producer`.
306    ///
307    /// Fails as [`RingBackend::new`] and [`Imports::new`] do.
308    pub fn new(backend: &mut B::Renderer, textures: B::Textures, producer: SyncKind) -> Result<Self, Error> {
309        let ring = B::new(backend, &textures, producer)?;
310        let imports = Imports::new::<B>(&mut backend.gpu(), &textures)?;
311        let slots = textures.images().iter().map(|_| Slot::new(None)).collect();
312        Ok(BorrowedTarget {
313            textures: Some(textures),
314            imports,
315            selected: 0,
316            slots,
317            producer,
318            handed: None,
319            torn_down: false,
320            ring,
321        })
322    }
323
324    /// Has the next frame draw into the texture at `slot`.
325    pub fn select(&mut self, slot: usize) {
326        self.selected = slot;
327    }
328
329    /// The size of the textures that frames draw into, or drew into last.
330    #[must_use]
331    pub fn size(&self) -> Size {
332        self.imports.size
333    }
334
335    /// The host gave the texture at `slot` back: the next frame drawn into
336    /// it waits for `consumer`, and the target lets go of what the slot's
337    /// last frame handed over.
338    ///
339    /// Fails with [`ErrorKind::InvalidArgument`](crate::ErrorKind) for a
340    /// slot the ring doesn't have, and as [`RingBackend::wait_for`] does,
341    /// after which the next frame drawn into the slot waits for nothing.
342    pub fn release(&mut self, gpu: &mut B::Gpu, slot: usize, consumer: ConsumerSync) -> Result<(), Error> {
343        let Some(state) = self.slots.get_mut(slot) else {
344            return Err(Error::invalid_argument("the ring has no such slot"));
345        };
346        state.forget(gpu);
347        state.wait = self.ring.wait_for(gpu, consumer)?;
348        Ok(())
349    }
350
351    /// The host gave up the texture at `slot` without saying when its reads
352    /// end: the target lets go of what the slot's last frame handed over,
353    /// and never draws into the texture again.
354    pub fn discard(&mut self, gpu: &mut B::Gpu, slot: usize) {
355        if let Some(state) = self.slots.get_mut(slot) {
356            state.forget(gpu);
357        }
358    }
359
360    /// Draws into `textures` from now on, which must be as many, and which
361    /// the backend checks as [`RingBackend::check_replacement`] does. A
362    /// texture that the new ring has again keeps what its next frame waits
363    /// for. Returns the sync after which the host may use the textures that
364    /// the ring let go of, as [`release_textures`](Self::release_textures)
365    /// does.
366    ///
367    /// Fails with [`ErrorKind::InvalidArgument`](crate::ErrorKind) for
368    /// another number of textures, with
369    /// [`ErrorKind::InvalidState`](crate::ErrorKind) once the target let
370    /// go of its textures, as the check and [`Imports::new`] do, and as
371    /// [`release_textures`](Self::release_textures) does. The target then
372    /// keeps its textures.
373    pub fn replace(&mut self, gpu: &mut B::Gpu, textures: B::Textures) -> Result<GpuSync, Error> {
374        let Some(current) = &self.textures else {
375            return Err(Error::invalid_state("the ring let go of its textures"));
376        };
377        if textures.images().len() != current.images().len() {
378            return Err(Error::invalid_argument("a ring keeps its depth"));
379        }
380        self.ring.check_replacement(current, &textures)?;
381        let mut imports = Imports::new::<B>(gpu, &textures)?;
382        let kept: Vec<Option<usize>> = current
383            .images()
384            .iter()
385            .map(|old| textures.images().iter().position(|image| B::Textures::same_image(old, image)))
386            .collect();
387        // A texture that the new ring has again keeps its wait for its
388        // next frame, unless a pass of the frame begun on it took it.
389        for (slot, _) in self.slots.iter_mut().zip(&kept).filter(|(_, kept)| kept.is_some()) {
390            if slot.detach(gpu)
391                && let Some(wait) = slot.wait.take()
392            {
393                B::waited(gpu, wait);
394            }
395        }
396        let sync = match self.end_work(gpu) {
397            Ok(sync) => sync,
398            Err(error) => {
399                imports.tear_down(gpu);
400                return Err(error);
401            }
402        };
403        std::mem::replace(&mut self.imports, imports).tear_down(gpu);
404        let mut slots: Vec<Slot<B>> = textures.images().iter().map(|_| Slot::new(None)).collect();
405        for (mut slot, kept) in std::mem::take(&mut self.slots).into_iter().zip(kept) {
406            match kept.and_then(|index| slots.get_mut(index)) {
407                Some(next) => {
408                    next.wait = slot.wait.take();
409                    if let Some(handed) = slot.handed.take() {
410                        B::release_handed(gpu, handed);
411                    }
412                }
413                None => slot.forget(gpu),
414            }
415        }
416        self.slots = slots;
417        self.textures = Some(textures);
418        Ok(sync)
419    }
420
421    /// Lets go of the textures, and returns the sync after which the host
422    /// may use them: the target's GPU work on them, and its waits for the
423    /// host, end there. The target keeps the objects that the sync names
424    /// until its next release or replacement of textures, or until it goes,
425    /// and draws no frame until then.
426    ///
427    /// Fails with [`ErrorKind::InvalidState`](crate::ErrorKind) once the
428    /// target let go of its textures, and with
429    /// [`ErrorKind::Failed`](crate::ErrorKind) when it can't submit the
430    /// work or make the sync. It keeps its textures then.
431    pub fn release_textures(&mut self, gpu: &mut B::Gpu) -> Result<GpuSync, Error> {
432        if self.textures.is_none() {
433            return Err(Error::invalid_state("the ring let go of its textures"));
434        }
435        let sync = self.end_work(gpu)?;
436        for mut slot in std::mem::take(&mut self.slots) {
437            slot.forget(gpu);
438        }
439        self.imports.tear_down(gpu);
440        self.textures = None;
441        Ok(sync)
442    }
443
444    /// Submits the work recorded so far, with a signal of the producer's
445    /// sync after it, and returns that sync, which ends the work on the
446    /// textures. A frame begun and not ended lets go of what its slot waits
447    /// for: a pass that drew took the wait into the submit, which the wait
448    /// outlives, and a frame that drew nothing waits for no host.
449    fn end_work(&mut self, gpu: &mut B::Gpu) -> Result<GpuSync, Error> {
450        for slot in self.slots.iter_mut().filter(|slot| slot.attached.is_some()) {
451            slot.forget(gpu);
452        }
453        if let Some(textures) = &self.textures {
454            let _ = self.ring.prepare_submit(gpu, textures, None);
455        }
456        self.ring.signal_after_next_submit(gpu);
457        let wait = self.producer == SyncKind::CpuComplete;
458        gpu.flush(wait).map_err(|error| Error::failed(format!("Submitting a ring's frames failed: {error}")))?;
459        let (sync, handed) =
460            self.producer_sync(gpu).ok_or_else(|| Error::failed("Making the sync of a ring's frames failed"))?;
461        if let Some(old) = std::mem::replace(&mut self.handed, handed) {
462            B::release_handed(gpu, old);
463        }
464        Ok(sync)
465    }
466
467    /// The sync that the host waits for, once the frame was submitted, and
468    /// what the slot keeps of it.
469    fn producer_sync(&mut self, gpu: &mut B::Gpu) -> Option<(GpuSync, Option<B::Handed>)> {
470        match self.producer {
471            SyncKind::QueueOrder => Some((GpuSync::of(SyncKind::QueueOrder), None)),
472            SyncKind::CpuComplete => Some((GpuSync::of(SyncKind::CpuComplete), None)),
473            _ => self.ring.producer_sync(gpu),
474        }
475    }
476}
477
478impl<B: RingBackend> FrameTarget for BorrowedTarget<B> {
479    type Gpu = B::Gpu;
480
481    /// The selected slot's texture, which the frame's first submit that
482    /// draws into it waits for the host's reads before.
483    fn begin_frame(&mut self, gpu: &mut B::Gpu) -> Option<FrameImage> {
484        let image = self.imports.frame_image(self.selected)?;
485        // A frame begun again keeps the wait it attached.
486        if let Some(state) = self.slots.get_mut(self.selected)
487            && state.attached != Some(image.color)
488            && let Some(wait) = &state.wait
489        {
490            if let Err(error) = B::wait_before_using(gpu, image.color, wait) {
491                tracing::error!(target: log_target::RENDER, error = %error, "Waiting for the host's reads failed");
492            }
493            state.attached = Some(image.color);
494        }
495        Some(image)
496    }
497
498    /// Submits what is left of the frame, signaling the producer's sync
499    /// after it.
500    fn end_frame(&mut self, gpu: &mut B::Gpu) -> Handoff {
501        let slot = self.selected;
502        let Some(color) = self.imports.color.get(slot).copied() else {
503            return Handoff::Dropped;
504        };
505        if let Some(textures) = &self.textures
506            && !self.ring.prepare_submit(gpu, textures, Some(slot))
507        {
508            return Handoff::Dropped;
509        }
510        // What no pass took yet, such as where the frame drew nothing.
511        B::take_waits_into_next_submit(gpu, color);
512        self.ring.signal_after_next_submit(gpu);
513        let submitted = gpu.flush(self.producer == SyncKind::CpuComplete);
514        // The frame's submits took what the slot waited for.
515        if let Some(state) = self.slots.get_mut(slot)
516            && state.attached.take() == Some(color)
517            && let Some(wait) = state.wait.take()
518        {
519            B::waited(gpu, wait);
520        }
521        if let Err(error) = submitted {
522            tracing::error!(target: log_target::RENDER, error = %error, "Submitting a borrowed texture's frame failed");
523            return Handoff::Dropped;
524        }
525        let Some((sync, handed)) = self.producer_sync(gpu) else {
526            return Handoff::Dropped;
527        };
528        if let Some(handed) = handed
529            && let Some(state) = self.slots.get_mut(slot)
530            && let Some(old) = state.handed.replace(handed)
531        {
532            B::release_handed(gpu, old);
533        }
534        Handoff::GivenBack { slot, sync }
535    }
536
537    /// Lets go of what the slots wait for, submits the work recorded so
538    /// far, and destroys the imports and the ring's objects once the frames
539    /// drawn so far are done, without blocking.
540    fn tear_down(&mut self, gpu: &mut B::Gpu) {
541        for mut slot in std::mem::take(&mut self.slots) {
542            slot.forget(gpu);
543        }
544        if let Some(handed) = self.handed.take() {
545            B::release_handed(gpu, handed);
546        }
547        if let Err(error) = gpu.flush(false) {
548            tracing::error!(
549                target: log_target::RENDER,
550                error = %error, "Submitting the frames before a borrowed target's deletion failed"
551            );
552        }
553        self.imports.tear_down(gpu);
554        self.ring.tear_down(gpu);
555        self.torn_down = true;
556    }
557}
558
559impl<B: RingBackend> Drop for BorrowedTarget<B> {
560    /// Lets go of what the slots wait for, after the frames drawn so far
561    /// where the backend must wait and no tear-down deferred it. The wait of a
562    /// frame begun and not ended drops without [`RingBackend::forget`],
563    /// which leaks what the backend made for it: a submit to come may have
564    /// taken it, and without the `Gpu` nothing defers its release past that
565    /// submit.
566    fn drop(&mut self) {
567        if !self.torn_down {
568            self.ring.wait_for_frames("borrowed target deletion");
569        }
570        for slot in self.slots.drain(..) {
571            if slot.attached.is_none()
572                && let Some(wait) = slot.wait
573            {
574                B::forget(wait);
575            }
576        }
577    }
578}
579
580/// A backend's part of an [`ExportedTarget`]: the images that it allocates
581/// and exports, and the host's textures over them, which a
582/// [`BorrowedTarget`] draws into.
583pub trait Exporter: Sized {
584    /// The backend's part of the borrowed target over a generation's images.
585    type Ring: RingBackend;
586    /// One generation's images, which go after the target that draws into
587    /// them.
588    type Images;
589
590    /// What allocates the images of `ring`, which the backend shares in
591    /// `kind` and hands over with sync of the kind `producer`.
592    ///
593    /// Fails with [`ErrorKind::Unsupported`](crate::ErrorKind) when the
594    /// backend can't export `kind` or hand frames over with `producer`.
595    fn new(
596        backend: &mut <Self::Ring as RingBackend>::Renderer,
597        ring: &ExportedRing,
598        kind: ExportKind,
599        producer: SyncKind,
600    ) -> Result<Self, Error>;
601
602    /// A generation of images of `size` pixels, and the textures over them
603    /// that frames draw into.
604    fn allocate(
605        &self,
606        backend: &mut <Self::Ring as RingBackend>::Renderer,
607        size: Size,
608    ) -> Result<(Self::Images, <Self::Ring as RingBackend>::Textures), Error>;
609
610    /// Lets go of `images`, which `gpu`'s frames drew into, once the work
611    /// submitted so far is done.
612    fn release_images(gpu: &mut <Self::Ring as RingBackend>::Gpu, images: Self::Images) {
613        let _ = gpu;
614        drop(images);
615    }
616
617    /// The frame at `slot` of a generation of `images`, whose textures are
618    /// `textures`.
619    fn frame(
620        &self,
621        images: &Self::Images,
622        textures: &<Self::Ring as RingBackend>::Textures,
623        slot: usize,
624    ) -> Option<ExportedFrame>;
625}
626
627/// One generation of an exported ring's images, of one size, and the
628/// borrowed target that draws into them.
629struct Generation<E: Exporter> {
630    // Before the images: dropping it without a tear-down waits, where the
631    // backend must, for the frames that drew into them.
632    target: BorrowedTarget<E::Ring>,
633    /// The images, until a tear-down hands them to the exporter.
634    images: Option<E::Images>,
635}
636
637impl<E: Exporter> Generation<E> {
638    fn new(
639        exporter: &E,
640        backend: &mut <E::Ring as RingBackend>::Renderer,
641        size: Size,
642        producer: SyncKind,
643    ) -> Result<Self, Error> {
644        let (images, textures) = exporter.allocate(backend, size)?;
645        match BorrowedTarget::new(backend, textures, producer) {
646            Ok(target) => Ok(Generation { target, images: Some(images) }),
647            Err(error) => {
648                E::release_images(&mut backend.gpu(), images);
649                Err(error)
650            }
651        }
652    }
653
654    /// Tears the target down, and lets the exporter release the images
655    /// once the frames that drew into them are done.
656    fn tear_down(&mut self, gpu: &mut <E::Ring as RingBackend>::Gpu) {
657        self.target.tear_down(gpu);
658        if let Some(images) = self.images.take() {
659            E::release_images(gpu, images);
660        }
661    }
662}
663
664/// Frames drawn into images of the target's own, which it exports, and
665/// queued for the host to acquire.
666pub struct ExportedTarget<E: Exporter> {
667    exporter: E,
668    producer: SyncKind,
669    generations: Generations<Generation<E>>,
670}
671
672impl<E: Exporter> ExportedTarget<E> {
673    /// A target on `backend` that draws into `ring.depth` images of `size`
674    /// pixels, exported as `kind`, and hands each frame over with sync of
675    /// the kind `producer`.
676    ///
677    /// Fails as [`Exporter::new`], [`Exporter::allocate`] and
678    /// [`BorrowedTarget::new`] do.
679    pub fn new(
680        backend: &mut <E::Ring as RingBackend>::Renderer,
681        ring: &ExportedRing,
682        kind: ExportKind,
683        size: Size,
684        producer: SyncKind,
685    ) -> Result<Self, Error> {
686        let exporter = E::new(backend, ring, kind, producer)?;
687        let current = Generation::new(&exporter, backend, size, producer)?;
688        Ok(ExportedTarget { exporter, producer, generations: Generations::new(current) })
689    }
690
691    /// Has the next frame draw into the image at `slot`.
692    pub fn select(&mut self, slot: usize) {
693        self.generations.current_mut().target.select(slot);
694    }
695
696    /// The host gave the frame at `slot` back, once its reads reach
697    /// `consumer`. A frame of an older generation lets go of its image,
698    /// which no frame draws into again.
699    ///
700    /// Fails as [`BorrowedTarget::release`] does.
701    pub fn release(
702        &mut self,
703        gpu: &mut <E::Ring as RingBackend>::Gpu,
704        slot: usize,
705        consumer: ConsumerSync,
706    ) -> Result<(), Error> {
707        if self.generations.give_back(slot, |mut generation| generation.tear_down(gpu)) {
708            return Ok(());
709        }
710        self.generations.current_mut().target.release(gpu, slot, consumer)
711    }
712
713    /// The host gave the frame at `slot` up without saying when its reads
714    /// end.
715    pub fn discard(&mut self, gpu: &mut <E::Ring as RingBackend>::Gpu, slot: usize) {
716        if !self.generations.give_back(slot, |mut generation| generation.tear_down(gpu)) {
717            self.generations.current_mut().target.discard(gpu, slot);
718        }
719    }
720
721    /// Draws into images of `size` pixels from now on. The frames that the
722    /// host holds, at `held` slots, keep their images. Returns whether the
723    /// ring has new images, which it doesn't when they have `size` already.
724    ///
725    /// Fails as [`new`](Self::new) does, and the target then keeps its own
726    /// images.
727    pub fn resize(
728        &mut self,
729        backend: &mut <E::Ring as RingBackend>::Renderer,
730        size: Size,
731        held: &[usize],
732    ) -> Result<bool, Error> {
733        if self.size() == size {
734            return Ok(false);
735        }
736        let next = Generation::new(&self.exporter, backend, size, self.producer)?;
737        let mut gpu = backend.gpu();
738        self.generations.replace(next, held, |mut generation| generation.tear_down(&mut gpu));
739        Ok(true)
740    }
741
742    /// The size of the images that frames draw into.
743    #[must_use]
744    pub fn size(&self) -> Size {
745        self.generations.current().target.size()
746    }
747
748    /// The images of the frame at `slot`: of the generation that the host
749    /// holds it in.
750    #[must_use]
751    pub fn image(&self, slot: usize) -> Option<ExportedFrame> {
752        let generations = &self.generations;
753        let generation = generations.retired(slot).unwrap_or(generations.current());
754        self.exporter.frame(generation.images.as_ref()?, generation.target.textures.as_ref()?, slot)
755    }
756}
757
758impl<E: Exporter> FrameTarget for ExportedTarget<E> {
759    type Gpu = <E::Ring as RingBackend>::Gpu;
760
761    fn begin_frame(&mut self, gpu: &mut Self::Gpu) -> Option<FrameImage> {
762        self.generations.current_mut().target.begin_frame(gpu)
763    }
764
765    fn end_frame(&mut self, gpu: &mut Self::Gpu) -> Handoff {
766        match self.generations.current_mut().target.end_frame(gpu) {
767            Handoff::GivenBack { slot, sync } => Handoff::Queued { slot, sync },
768            other => other,
769        }
770    }
771
772    fn tear_down(&mut self, gpu: &mut Self::Gpu) {
773        self.generations.clear(|generation| generation.tear_down(gpu));
774    }
775}
776
777#[cfg(test)]
778#[expect(clippy::disallowed_types, reason = "single-threaded test harness")]
779mod tests {
780    use std::any::Any;
781    use std::cell::RefCell;
782
783    use super::*;
784    use crate::export::{ExportedImage, NativeTexture};
785    use crate::gpu::{
786        BindingsDesc, BindingsId, BufferDesc, BufferId, Caps, ClipDepthRange, Draw, GeometryDesc, GeometryId, PassDesc,
787        PipelineDesc, PipelineId, ReadbackId, SamplerId, ShaderId, ShaderKey, SlotMap, TextureFormat, TextureRegion,
788    };
789    use crate::texture2d::SamplerState;
790    use crate::util_hash::HashMap;
791
792    /// A `Gpu` of textures alone, which records what its submits wait for.
793    #[derive(Default)]
794    struct FakeGpu {
795        /// Each texture, and the host's image it imports, if any.
796        textures: SlotMap<TextureId, Option<u32>>,
797        texture_waits: HashMap<TextureId, Vec<u32>>,
798        next_waits: Vec<u32>,
799        /// What each flush waited for.
800        submits: Vec<Vec<u32>>,
801        /// Whether each flush waited on the CPU.
802        flush_waits: Vec<bool>,
803        signals: u64,
804        /// The waits that the ring let go of after a submit.
805        waited: Vec<u32>,
806        /// The handed objects released with the `Gpu`.
807        released_handed: Vec<u64>,
808        /// The slots prepared before submission (`None` for release/replace).
809        prepared: Vec<Option<usize>>,
810        /// Whether `prepare_submit` fails for frames.
811        reject_prepare: bool,
812        /// Whether flushes fail, as on a lost device.
813        lost: bool,
814    }
815
816    impl FakeGpu {
817        fn imported(&self) -> Vec<u32> {
818            let mut images: Vec<u32> = self.textures.values().filter_map(|image| *image).collect();
819            images.sort_unstable();
820            images
821        }
822    }
823
824    fn unsupported<T>() -> Result<T, GpuError> {
825        Err(GpuError::Unsupported("a fake".to_owned()))
826    }
827
828    impl Gpu for FakeGpu {
829        fn caps(&self) -> &Caps {
830            const CAPS: Caps = Caps {
831                buffer_offset_alignment: 4,
832                max_texture_size: 4096,
833                half_float_render_targets: false,
834                clip_depth: ClipDepthRange::ZeroToOne,
835                render_target_depth: None,
836                clear_stencil_with_pass: false,
837                cpu_rasterizer: false,
838                max_line_width: 1.0,
839                binds_vertex_buffers: false,
840            };
841            &CAPS
842        }
843        fn create_buffer(&mut self, _: &BufferDesc<'_>) -> Result<BufferId, GpuError> {
844            unsupported()
845        }
846        fn write_buffer(&mut self, _: BufferId, _: u64, _: &[u8]) -> Result<(), GpuError> {
847            unsupported()
848        }
849        fn create_texture(&mut self, desc: &TextureDesc<'_>) -> Result<TextureId, GpuError> {
850            if desc.size.width == 0 {
851                return Err(GpuError::Invalid("an empty texture".to_owned()));
852            }
853            Ok(self.textures.insert(None))
854        }
855        fn write_texture(&mut self, _: TextureId, _: TextureRegion, _: &[u8]) -> Result<(), GpuError> {
856            unsupported()
857        }
858        fn generate_mipmaps(&mut self, _: TextureId) -> Result<(), GpuError> {
859            unsupported()
860        }
861        fn create_sampler(&mut self, _: SamplerState) -> Result<SamplerId, GpuError> {
862            unsupported()
863        }
864        fn create_shader(&mut self, _: &ShaderKey) -> Result<ShaderId, GpuError> {
865            unsupported()
866        }
867        fn create_pipeline(&mut self, _: &PipelineDesc<'_>) -> Result<PipelineId, GpuError> {
868            unsupported()
869        }
870        fn create_bindings(&mut self, _: &BindingsDesc<'_>) -> Result<BindingsId, GpuError> {
871            unsupported()
872        }
873        fn create_geometry(&mut self, _: &GeometryDesc<'_>) -> Result<GeometryId, GpuError> {
874            unsupported()
875        }
876        fn destroy(&mut self, resource: ResourceId) -> Result<(), GpuError> {
877            if let ResourceId::Texture(texture) = resource {
878                self.textures.remove(texture);
879                self.texture_waits.remove(&texture);
880            }
881            Ok(())
882        }
883        fn begin_pass(&mut self, _: &PassDesc<'_>) -> Result<(), GpuError> {
884            unsupported()
885        }
886        fn draw(&mut self, _: &Draw) -> Result<(), GpuError> {
887            unsupported()
888        }
889        fn lend(&mut self, _: &mut dyn FnMut(&mut dyn Any)) -> Result<(), GpuError> {
890            unsupported()
891        }
892        fn end_pass(&mut self) -> Result<(), GpuError> {
893            unsupported()
894        }
895        fn flush(&mut self, wait: bool) -> Result<(), GpuError> {
896            if self.lost {
897                return Err(GpuError::Invalid("lost".to_owned()));
898            }
899            self.submits.push(std::mem::take(&mut self.next_waits));
900            self.flush_waits.push(wait);
901            Ok(())
902        }
903        fn read_texture(&mut self, _: TextureId, _: TextureRegion) -> Result<ReadbackId, GpuError> {
904            unsupported()
905        }
906        fn take_readback(&mut self, _: ReadbackId, _: bool) -> Result<Option<Vec<u8>>, GpuError> {
907            unsupported()
908        }
909    }
910
911    #[derive(Default)]
912    struct FakeBackend {
913        gpu: FakeGpu,
914        /// The name of the next image that an exporter allocates.
915        next_image: u32,
916    }
917
918    impl RendererBackend for FakeBackend {
919        type Gpu = FakeGpu;
920        type Scope<'a> = &'a mut FakeGpu;
921
922        fn gpu(&mut self) -> &mut FakeGpu {
923            &mut self.gpu
924        }
925    }
926
927    /// The host's images, by name, and whether it gave depth textures,
928    /// which are named one past each image's name.
929    #[derive(Clone)]
930    struct Images {
931        names: Vec<u32>,
932        size: Size,
933        depth: bool,
934    }
935
936    fn images(names: &[u32]) -> Images {
937        Images { names: names.to_vec(), size: Size::new(4, 4), depth: false }
938    }
939
940    impl RingTextures for Images {
941        type Image = u32;
942
943        fn images(&self) -> &[u32] {
944            &self.names
945        }
946        fn same_image(a: &u32, b: &u32) -> bool {
947            a == b
948        }
949        fn size(&self) -> Size {
950            self.size
951        }
952        fn has_depth(&self) -> bool {
953            self.depth
954        }
955    }
956
957    /// What the test's rings did apart from their `Gpu`.
958    #[derive(Default)]
959    struct Record {
960        /// How many times they waited for the frames drawn so far.
961        frames_waited: usize,
962        /// How many times a tear-down deferred the release of their objects.
963        torn_down: usize,
964        /// The waits that they let go of without a submit.
965        forgotten: Vec<u32>,
966    }
967
968    thread_local! {
969        static RECORD: RefCell<Record> = RefCell::default();
970    }
971
972    fn frames_waited() -> usize {
973        RECORD.with_borrow(|record| record.frames_waited)
974    }
975
976    fn torn_down() -> usize {
977        RECORD.with_borrow(|record| record.torn_down)
978    }
979
980    fn forgotten() -> Vec<u32> {
981        RECORD.with_borrow(|record| record.forgotten.clone())
982    }
983
984    /// A ring whose waits are reads by number, and whose frames signal a
985    /// counter.
986    struct FakeRing {
987        value: u64,
988    }
989
990    impl RingBackend for FakeRing {
991        type Gpu = FakeGpu;
992        type Renderer = FakeBackend;
993        type Textures = Images;
994        type Wait = u32;
995        /// The value of the frame's signal.
996        type Handed = u64;
997
998        fn new(_: &mut FakeBackend, images: &Images, producer: SyncKind) -> Result<Self, Error> {
999            if images.names.is_empty() {
1000                return Err(Error::invalid_argument("no images"));
1001            }
1002            if producer == SyncKind::SyncFd {
1003                return Err(Error::unsupported("no sync files"));
1004            }
1005            Ok(FakeRing { value: 0 })
1006        }
1007        fn check_replacement(&self, current: &Images, next: &Images) -> Result<(), Error> {
1008            if current.depth == next.depth { Ok(()) } else { Err(Error::unsupported("a ring keeps its depth")) }
1009        }
1010        fn targets(_: &FakeGpu, _: &Images) -> Result<TargetFormats, Error> {
1011            Ok(TargetFormats {
1012                color: Some(TextureFormat::Rgba8Unorm),
1013                depth_stencil: Some(TextureFormat::Depth24PlusStencil8),
1014            })
1015        }
1016        fn import(gpu: &mut FakeGpu, images: &Images, slot: usize, depth: bool) -> Result<TextureId, GpuError> {
1017            let name = images.names.get(slot).ok_or(GpuError::UnknownId("slot"))? + u32::from(depth);
1018            Ok(gpu.textures.insert(Some(name)))
1019        }
1020        fn wait_for(&mut self, _: &mut FakeGpu, consumer: ConsumerSync) -> Result<Option<u32>, Error> {
1021            match consumer.sync.kind {
1022                SyncKind::QueueOrder => Ok(None),
1023                SyncKind::VulkanTimelineSemaphore => Ok(Some(consumer.sync.value as u32)),
1024                kind => Err(Error::unsupported(format!("no {kind:?}"))),
1025            }
1026        }
1027        fn wait_before_using(gpu: &mut FakeGpu, texture: TextureId, wait: &u32) -> Result<(), GpuError> {
1028            gpu.texture_waits.entry(texture).or_default().push(*wait);
1029            Ok(())
1030        }
1031        fn take_waits_into_next_submit(gpu: &mut FakeGpu, texture: TextureId) {
1032            gpu.next_waits.extend(gpu.texture_waits.remove(&texture).unwrap_or_default());
1033        }
1034        fn forget_waits(gpu: &mut FakeGpu, texture: TextureId) -> bool {
1035            gpu.texture_waits.remove(&texture).is_some()
1036        }
1037        fn waited(gpu: &mut FakeGpu, wait: u32) {
1038            gpu.waited.push(wait);
1039        }
1040        fn prepare_submit(&mut self, gpu: &mut FakeGpu, _textures: &Images, slot: Option<usize>) -> bool {
1041            gpu.prepared.push(slot);
1042            !(gpu.reject_prepare && slot.is_some())
1043        }
1044        fn signal_after_next_submit(&mut self, gpu: &mut FakeGpu) {
1045            self.value += 1;
1046            gpu.signals = self.value;
1047        }
1048        fn producer_sync(&mut self, _: &mut FakeGpu) -> Option<(GpuSync, Option<u64>)> {
1049            let sync = GpuSync { kind: SyncKind::VulkanTimelineSemaphore, handle: 1, value: self.value };
1050            Some((sync, Some(self.value)))
1051        }
1052        fn release_handed(gpu: &mut FakeGpu, handed: u64) {
1053            gpu.released_handed.push(handed);
1054        }
1055        fn tear_down(&mut self, _: &mut FakeGpu) {
1056            RECORD.with_borrow_mut(|record| record.torn_down += 1);
1057        }
1058        fn wait_for_frames(&self, _: &str) {
1059            RECORD.with_borrow_mut(|record| record.frames_waited += 1);
1060        }
1061        fn forget(wait: u32) {
1062            RECORD.with_borrow_mut(|record| record.forgotten.push(wait));
1063        }
1064    }
1065
1066    fn timeline(value: u64) -> ConsumerSync {
1067        ConsumerSync::of(GpuSync { kind: SyncKind::VulkanTimelineSemaphore, handle: 1, value })
1068    }
1069
1070    fn target(backend: &mut FakeBackend, names: &[u32]) -> BorrowedTarget<FakeRing> {
1071        BorrowedTarget::new(backend, images(names), SyncKind::VulkanTimelineSemaphore).expect("a ring")
1072    }
1073
1074    #[test]
1075    fn a_frame_waits_for_the_hosts_reads_of_its_slot_once() {
1076        let mut backend = FakeBackend::default();
1077        let mut ring = target(&mut backend, &[10, 20]);
1078        let gpu = &mut backend.gpu;
1079        assert_eq!(gpu.imported(), [10, 20]);
1080        ring.release(gpu, 1, timeline(7)).expect("a release");
1081        ring.select(1);
1082        let image = ring.begin_frame(gpu).expect("a frame");
1083        // A frame begun again attaches its wait once.
1084        assert_eq!(ring.begin_frame(gpu), Some(image));
1085        assert_eq!(gpu.texture_waits[&image.color], [7]);
1086        assert!(image.depth_stencil.is_some_and(|depth| gpu.textures.get(depth) == Some(&None)));
1087        assert_eq!(
1088            ring.end_frame(gpu),
1089            Handoff::GivenBack {
1090                slot: 1,
1091                sync: GpuSync { kind: SyncKind::VulkanTimelineSemaphore, handle: 1, value: 1 }
1092            }
1093        );
1094        assert_eq!(gpu.submits, [vec![7]]);
1095        assert_eq!(gpu.signals, 1);
1096        // The submit took the wait: the next frame waits for nothing.
1097        ring.begin_frame(gpu);
1098        ring.end_frame(gpu);
1099        assert_eq!(gpu.submits.last(), Some(&vec![]));
1100        // A slot that the host gave up waits for nothing, and a slot the ring
1101        // lacks fails.
1102        ring.release(gpu, 0, timeline(8)).expect("a release");
1103        ring.discard(gpu, 0);
1104        assert!(ring.release(gpu, 2, timeline(9)).is_err());
1105        ring.tear_down(gpu);
1106        assert!(gpu.textures.is_empty());
1107        // A torn-down ring has no slots.
1108        assert!(ring.release(gpu, 0, timeline(9)).is_err());
1109    }
1110
1111    #[test]
1112    fn a_ring_lets_go_of_each_wait_once() {
1113        let mut backend = FakeBackend::default();
1114        let mut ring = target(&mut backend, &[10, 20]);
1115        let gpu = &mut backend.gpu;
1116        // The submit that takes a frame's wait has it go after its work.
1117        ring.release(gpu, 0, timeline(7)).expect("a release");
1118        ring.begin_frame(gpu);
1119        ring.end_frame(gpu);
1120        assert_eq!(gpu.waited, [7]);
1121        // A release replaces the slot's wait, and one that fails leaves the
1122        // slot waiting for nothing.
1123        ring.release(gpu, 1, timeline(8)).expect("a release");
1124        ring.release(gpu, 1, timeline(9)).expect("a release");
1125        let fence = ConsumerSync::of(GpuSync { kind: SyncKind::D3d12Fence, handle: 1, value: 10 });
1126        assert!(ring.release(gpu, 1, fence).is_err());
1127        assert_eq!(forgotten(), [8, 9]);
1128        ring.select(1);
1129        let image = ring.begin_frame(gpu).expect("a frame");
1130        assert!(!gpu.texture_waits.contains_key(&image.color));
1131        ring.end_frame(gpu);
1132        assert_eq!(gpu.submits.last(), Some(&vec![]));
1133        // A tear-down lets go of the waits that no frame took at once.
1134        ring.release(gpu, 0, timeline(100)).expect("a release");
1135        ring.release(gpu, 1, timeline(11)).expect("a release");
1136        ring.tear_down(gpu);
1137        assert_eq!(forgotten(), [8, 9, 100, 11]);
1138        assert_eq!(gpu.waited, [7]);
1139    }
1140
1141    fn sync(value: u64) -> GpuSync {
1142        GpuSync { kind: SyncKind::VulkanTimelineSemaphore, handle: 1, value }
1143    }
1144
1145    // The host's reads don't hold up a release: its sync comes after the
1146    // ring's own work, which waits for them on the GPU.
1147    #[test]
1148    fn a_release_hands_over_the_sync_after_its_work_on_the_textures() {
1149        let mut backend = FakeBackend::default();
1150        let mut ring = target(&mut backend, &[10, 20]);
1151        let gpu = &mut backend.gpu;
1152        ring.release(gpu, 0, timeline(7)).expect("a release");
1153        ring.release(gpu, 1, timeline(8)).expect("a release");
1154        let image = ring.begin_frame(gpu).expect("a frame");
1155        // A pass of the frame took the wait into the work recorded so far.
1156        FakeRing::take_waits_into_next_submit(gpu, image.color);
1157        assert_eq!(ring.release_textures(gpu).expect("a release of the textures"), sync(1));
1158        assert_eq!((gpu.submits.clone(), gpu.signals), (vec![vec![7]], 1));
1159        assert_eq!((gpu.waited.clone(), forgotten()), (vec![7], vec![8]));
1160        // It keeps what the sync handed over, and draws no frame.
1161        assert_eq!(ring.handed, Some(1));
1162        assert!(gpu.textures.is_empty());
1163        assert_eq!(ring.begin_frame(gpu), None);
1164        assert_eq!(ring.end_frame(gpu), Handoff::Dropped);
1165        assert!(ring.release_textures(gpu).is_err());
1166        assert!(ring.replace(gpu, images(&[10, 20])).is_err());
1167        ring.tear_down(gpu);
1168        assert_eq!((frames_waited(), torn_down()), (0, 1));
1169    }
1170
1171    // A submit that fails, as on a lost device, gives no sync to wait for:
1172    // the release or replacement fails, and the ring keeps its textures.
1173    #[test]
1174    fn a_release_or_replacement_whose_submit_fails_keeps_the_textures() {
1175        let mut backend = FakeBackend::default();
1176        let mut ring = target(&mut backend, &[10, 20]);
1177        let gpu = &mut backend.gpu;
1178        gpu.lost = true;
1179        assert!(ring.replace(gpu, images(&[20, 30])).is_err());
1180        assert!(ring.release_textures(gpu).is_err());
1181        assert_eq!(gpu.imported(), [10, 20]);
1182        gpu.lost = false;
1183        assert_eq!(
1184            ring.replace(gpu, images(&[20, 30])).expect("a replacement").kind,
1185            SyncKind::VulkanTimelineSemaphore
1186        );
1187        assert_eq!(gpu.imported(), [20, 30]);
1188    }
1189
1190    // A tear-down or a replacement never blocks: the ring's objects go once
1191    // the frames are done. Only a target dropped without its tear-down, and
1192    // so without a `Gpu` to defer to, waits for its frames.
1193    #[test]
1194    fn a_ring_waits_for_its_frames_only_when_dropped_without_a_tear_down() {
1195        let mut backend = FakeBackend::default();
1196        let mut ring = target(&mut backend, &[10, 20]);
1197        ring.release(&mut backend.gpu, 0, timeline(7)).expect("a release");
1198        ring.replace(&mut backend.gpu, images(&[20, 30])).expect("a replacement");
1199        ring.tear_down(&mut backend.gpu);
1200        assert_eq!((frames_waited(), torn_down()), (0, 1));
1201        assert_eq!(forgotten(), [7]);
1202        drop(ring);
1203        assert_eq!(frames_waited(), 0);
1204        // Dropped without a tear-down, it waits as it drops.
1205        let mut ring = target(&mut backend, &[10]);
1206        ring.release(&mut backend.gpu, 0, timeline(8)).expect("a release");
1207        drop(ring);
1208        assert_eq!((frames_waited(), torn_down()), (1, 1));
1209        assert_eq!(forgotten(), [7, 8]);
1210    }
1211
1212    #[test]
1213    fn a_frame_left_unended_lets_go_of_a_wait_that_no_pass_took_at_once() {
1214        let mut backend = FakeBackend::default();
1215        let mut ring = target(&mut backend, &[10]);
1216        let gpu = &mut backend.gpu;
1217        ring.release(gpu, 0, timeline(7)).expect("a release");
1218        ring.begin_frame(gpu);
1219        // A tear-down submits the frame, which drew nothing and so waits for
1220        // no host, and lets go of the wait at once.
1221        ring.tear_down(gpu);
1222        assert_eq!(gpu.submits, [Vec::<u32>::new()]);
1223        assert_eq!((forgotten(), gpu.waited.clone()), (vec![7], vec![]));
1224        drop(ring);
1225        // Without a gpu, a drop leaves the wait to the backend.
1226        let mut ring = target(&mut backend, &[10]);
1227        ring.release(&mut backend.gpu, 0, timeline(8)).expect("a release");
1228        ring.begin_frame(&mut backend.gpu);
1229        drop(ring);
1230        assert_eq!(forgotten(), [7]);
1231    }
1232
1233    #[test]
1234    fn a_replaced_ring_keeps_the_waits_of_the_images_it_has_again() {
1235        let mut backend = FakeBackend::default();
1236        let mut ring = target(&mut backend, &[10, 20]);
1237        let gpu = &mut backend.gpu;
1238        ring.release(gpu, 0, timeline(7)).expect("a release");
1239        ring.release(gpu, 1, timeline(8)).expect("a release");
1240        // Of another depth, or with depth textures, the ring keeps its own.
1241        assert!(ring.replace(gpu, images(&[30])).is_err());
1242        assert!(ring.replace(gpu, Images { depth: true, ..images(&[20, 30]) }).is_err());
1243        assert_eq!(ring.replace(gpu, images(&[20, 30])).expect("a replacement"), sync(1));
1244        assert_eq!(gpu.imported(), [20, 30]);
1245        // The ring lets go of image 10's read at once.
1246        assert_eq!(forgotten(), [7]);
1247        // Image 20 keeps its read, at slot 0.
1248        let image = ring.begin_frame(gpu).expect("a frame");
1249        assert_eq!(gpu.texture_waits[&image.color], [8]);
1250        ring.end_frame(gpu);
1251        assert_eq!(gpu.submits.last(), Some(&vec![8]));
1252    }
1253
1254    #[test]
1255    fn a_ring_that_lets_go_of_a_begun_frame_submits_only_the_waits_that_it_drew_with() {
1256        let mut backend = FakeBackend::default();
1257        let mut ring = target(&mut backend, &[10, 20]);
1258        let gpu = &mut backend.gpu;
1259        ring.release(gpu, 0, timeline(7)).expect("a release");
1260        let image = ring.begin_frame(gpu).expect("a frame");
1261        // A pass of the frame took the wait into the work recorded so far.
1262        FakeRing::take_waits_into_next_submit(gpu, image.color);
1263        ring.replace(gpu, images(&[20, 30])).expect("a replacement");
1264        assert_eq!(gpu.submits, [vec![7]]);
1265        assert_eq!(gpu.waited, [7]);
1266        // A frame begun on a texture that the new ring has again, which
1267        // drew nothing, leaves the wait to the texture's next frame: the
1268        // replacement's submit waits for no host.
1269        ring.release(gpu, 0, timeline(8)).expect("a release");
1270        ring.begin_frame(gpu);
1271        ring.replace(gpu, images(&[20, 40])).expect("a replacement");
1272        assert_eq!(gpu.submits, [vec![7], vec![]]);
1273        let image = ring.begin_frame(gpu).expect("a frame");
1274        assert_eq!(gpu.texture_waits[&image.color], [8]);
1275        ring.end_frame(gpu);
1276        assert_eq!(gpu.submits.last(), Some(&vec![8]));
1277        assert_eq!(gpu.waited, [7, 8]);
1278        // A frame that drew nothing waits for no host as the ring goes, and
1279        // lets go of its wait at once.
1280        ring.release(gpu, 1, timeline(9)).expect("a release");
1281        ring.select(1);
1282        ring.begin_frame(gpu);
1283        ring.tear_down(gpu);
1284        assert_eq!(gpu.submits.last(), Some(&vec![]));
1285        assert_eq!(gpu.waited, [7, 8]);
1286        assert!(gpu.texture_waits.is_empty());
1287        assert_eq!(forgotten(), [9]);
1288    }
1289
1290    #[test]
1291    fn a_ring_imports_the_hosts_depth_or_makes_its_own() {
1292        let mut backend = FakeBackend::default();
1293        let ring = BorrowedTarget::<FakeRing>::new(
1294            &mut backend,
1295            Images { depth: true, ..images(&[10, 20]) },
1296            SyncKind::QueueOrder,
1297        )
1298        .expect("a ring");
1299        assert_eq!(backend.gpu.imported(), [10, 11, 20, 21]);
1300        drop(ring);
1301        // An own depth texture that fails leaves nothing imported.
1302        let empty = Images { size: Size::new(0, 4), ..images(&[10]) };
1303        assert!(Imports::new::<FakeRing>(&mut backend.gpu, &empty).is_err());
1304        assert_eq!(backend.gpu.imported(), [10, 11, 20, 21]);
1305        assert!(BorrowedTarget::<FakeRing>::new(&mut backend, images(&[10]), SyncKind::SyncFd).is_err());
1306    }
1307
1308    /// Images by name, of the backend's counter.
1309    struct FakeExporter {
1310        depth: usize,
1311    }
1312
1313    impl Exporter for FakeExporter {
1314        type Ring = FakeRing;
1315        type Images = ();
1316
1317        fn new(_: &mut FakeBackend, ring: &ExportedRing, _: ExportKind, _: SyncKind) -> Result<Self, Error> {
1318            Ok(FakeExporter { depth: ring.depth })
1319        }
1320        fn allocate(&self, backend: &mut FakeBackend, size: Size) -> Result<((), Images), Error> {
1321            let names = (0..self.depth)
1322                .map(|_| {
1323                    backend.next_image += 10;
1324                    backend.next_image
1325                })
1326                .collect();
1327            Ok(((), Images { names, size, depth: false }))
1328        }
1329        fn frame(&self, (): &(), images: &Images, slot: usize) -> Option<ExportedFrame> {
1330            let fd = *images.names.get(slot)? as i32;
1331            Some(ExportedFrame {
1332                size: images.size,
1333                image: ExportedImage::OpaqueFd { fd, allocation_size: 0, dedicated: true, format: 0 },
1334                texture: NativeTexture::WebGpu,
1335                depth: None,
1336            })
1337        }
1338    }
1339
1340    fn fd(frame: Option<ExportedFrame>) -> Option<i32> {
1341        match frame?.image {
1342            ExportedImage::OpaqueFd { fd, .. } => Some(fd),
1343            _ => None,
1344        }
1345    }
1346
1347    #[test]
1348    fn a_held_frame_keeps_its_generation_until_it_comes_back() {
1349        let mut backend = FakeBackend::default();
1350        let ring = ExportedRing {
1351            depth: 2,
1352            kinds: crate::export::ExportKinds::NONE,
1353            dma_buf_formats: Vec::new(),
1354            android_hardware_buffer_usage: 0,
1355            keep_depth: false,
1356        };
1357        let size = Size::new(4, 4);
1358        let mut target = ExportedTarget::<FakeExporter>::new(
1359            &mut backend,
1360            &ring,
1361            ExportKind::OpaqueFd,
1362            size,
1363            SyncKind::VulkanTimelineSemaphore,
1364        )
1365        .expect("a ring");
1366        target.select(1);
1367        target.begin_frame(&mut backend.gpu);
1368        assert!(matches!(target.end_frame(&mut backend.gpu), Handoff::Queued { slot: 1, .. }));
1369        assert!(!target.resize(&mut backend, size, &[1]).expect("no resize"));
1370        assert!(target.resize(&mut backend, Size::new(8, 8), &[1]).expect("a resize"));
1371        assert_eq!(target.size(), Size::new(8, 8));
1372        // The host holds slot 1 of the first generation.
1373        assert_eq!((fd(target.image(0)), fd(target.image(1))), (Some(30), Some(20)));
1374        assert_eq!(backend.gpu.imported(), [10, 20, 30, 40]);
1375        target.release(&mut backend.gpu, 1, timeline(7)).expect("a release");
1376        assert_eq!(backend.gpu.imported(), [30, 40]);
1377        assert_eq!(fd(target.image(1)), Some(40));
1378        // A frame of an older generation that the host gives up lets go of
1379        // its generation too.
1380        target.select(0);
1381        target.begin_frame(&mut backend.gpu);
1382        assert!(matches!(target.end_frame(&mut backend.gpu), Handoff::Queued { slot: 0, .. }));
1383        assert!(target.resize(&mut backend, size, &[0]).expect("a resize"));
1384        assert_eq!(backend.gpu.imported(), [30, 40, 50, 60]);
1385        target.discard(&mut backend.gpu, 0);
1386        assert_eq!(backend.gpu.imported(), [50, 60]);
1387        target.tear_down(&mut backend.gpu);
1388        assert!(backend.gpu.textures.is_empty());
1389    }
1390
1391    #[test]
1392    fn a_ring_releases_handed_objects_and_prepares_submits() {
1393        let mut backend = FakeBackend::default();
1394        let mut ring = target(&mut backend, &[10, 20]);
1395        let gpu = &mut backend.gpu;
1396        // Two frames into slot 0 replace the first handed object.
1397        ring.begin_frame(gpu);
1398        assert!(matches!(ring.end_frame(gpu), Handoff::GivenBack { slot: 0, .. }));
1399        ring.begin_frame(gpu);
1400        assert!(matches!(ring.end_frame(gpu), Handoff::GivenBack { slot: 0, .. }));
1401        assert_eq!(gpu.released_handed, [1]);
1402        assert_eq!(gpu.prepared, [Some(0), Some(0)]);
1403        // A failing prepare_submit drops the frame before flushing.
1404        gpu.reject_prepare = true;
1405        ring.begin_frame(gpu);
1406        assert_eq!(ring.end_frame(gpu), Handoff::Dropped);
1407        assert_eq!(gpu.submits.len(), 2);
1408        gpu.reject_prepare = false;
1409        // A frame in slot 1 followed by replace releases slot 0 (unkept) and slot 1 (kept).
1410        ring.select(1);
1411        ring.begin_frame(gpu);
1412        assert!(matches!(ring.end_frame(gpu), Handoff::GivenBack { slot: 1, .. }));
1413        ring.replace(gpu, images(&[20, 30])).expect("a replacement");
1414        assert_eq!(gpu.released_handed, [1, 2, 3]);
1415        assert_eq!(gpu.prepared.last(), Some(&None));
1416        // A release_textures replaces the previous self.handed (4) with 5, and tear_down releases 5.
1417        ring.release_textures(gpu).expect("release");
1418        assert_eq!(gpu.released_handed, [1, 2, 3, 4]);
1419        ring.tear_down(gpu);
1420        assert_eq!(gpu.released_handed, [1, 2, 3, 4, 5]);
1421    }
1422
1423    #[test]
1424    fn a_cpu_complete_ring_flushes_once_with_wait() {
1425        let mut backend = FakeBackend::default();
1426        let mut ring =
1427            BorrowedTarget::<FakeRing>::new(&mut backend, images(&[10]), SyncKind::CpuComplete).expect("a ring");
1428        let gpu = &mut backend.gpu;
1429        ring.begin_frame(gpu);
1430        assert_eq!(ring.end_frame(gpu), Handoff::GivenBack { slot: 0, sync: GpuSync::of(SyncKind::CpuComplete) });
1431        assert_eq!(gpu.flush_waits, [true]);
1432        assert_eq!(ring.release_textures(gpu).expect("release"), GpuSync::of(SyncKind::CpuComplete));
1433        assert_eq!(gpu.flush_waits, [true, true]);
1434        ring.tear_down(gpu);
1435    }
1436}