mln_engine/draw/
after_gpu.rs1use std::cell::Cell;
4use std::rc::{Rc, Weak};
5
6use mln_gfx::gpu::Gpu;
7
8use crate::log_target;
9
10#[derive(Clone)]
20pub struct AfterGpu(Weak<Cell<Vec<Work>>>);
21
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum GpuEnd {
25 Finished,
27 Lost,
30}
31
32type Work = Box<dyn FnOnce(GpuEnd)>;
34
35impl AfterGpu {
36 pub fn push(&self, work: impl FnOnce(GpuEnd) + 'static) {
40 match self.0.upgrade() {
41 Some(queue) => {
42 let mut waiting = queue.take();
43 waiting.push(Box::new(work));
44 queue.set(waiting);
45 }
46 None => work(GpuEnd::Lost),
47 }
48 }
49}
50
51pub(crate) struct AfterGpuQueue {
54 work: Rc<Cell<Vec<Work>>>,
55 handle: AfterGpu,
56}
57
58impl AfterGpuQueue {
59 pub(crate) fn new() -> Self {
60 let work = Rc::default();
61 let handle = AfterGpu(Rc::downgrade(&work));
62 AfterGpuQueue { work, handle }
63 }
64
65 pub(crate) fn handle(&self) -> &AfterGpu {
67 &self.handle
68 }
69
70 fn take(&self) -> Vec<Work> {
73 self.work.take()
74 }
75
76 pub(crate) fn finish(&self, gpu: &mut dyn Gpu) {
79 let work = self.take();
80 if work.is_empty() {
81 return;
82 }
83 if let Err(error) = gpu.flush(true) {
84 log::error!(target: log_target::RENDER, "Waiting for the GPU before the work after it failed: {error}");
85 }
86 for work in work {
87 work(GpuEnd::Finished);
88 }
89 }
90
91 pub(crate) fn lose(&self) {
94 loop {
95 let work = self.take();
96 if work.is_empty() {
97 return;
98 }
99 for work in work {
100 work(GpuEnd::Lost);
101 }
102 }
103 }
104}
105
106impl Drop for AfterGpuQueue {
107 fn drop(&mut self) {
108 self.lose();
109 }
110}
111
112#[cfg(test)]
113mod tests {
114 use std::cell::RefCell;
115 use std::rc::Rc;
116
117 use super::{AfterGpu, AfterGpuQueue, GpuEnd};
118
119 type Ends = Rc<RefCell<Vec<(&'static str, GpuEnd)>>>;
120
121 fn record(after: &AfterGpu, ends: &Ends, name: &'static str) {
123 let ends = Rc::clone(ends);
124 after.push(move |end| ends.borrow_mut().push((name, end)));
125 }
126
127 #[test]
128 fn work_runs_once_in_order_and_as_lost_once_the_queue_goes() {
129 let ends = Ends::default();
130 let queue = AfterGpuQueue::new();
131 let after = queue.handle().clone();
132 record(&after, &ends, "first");
133 record(&after, &ends, "second");
134 queue.lose();
135 queue.lose();
136 assert_eq!(ends.take(), [("first", GpuEnd::Lost), ("second", GpuEnd::Lost)]);
137
138 record(&after, &ends, "waiting");
139 drop(queue);
140 record(&after, &ends, "late");
141 assert_eq!(ends.take(), [("waiting", GpuEnd::Lost), ("late", GpuEnd::Lost)]);
142 }
143}