Skip to main content

mln_runtime/render/
driver.rs

1//! The graphics work of a render session that the host's thread runs.
2
3use std::cell::{Cell, RefCell};
4use std::sync::Arc;
5use std::sync::atomic::Ordering;
6
7use mln_util::error::Error;
8
9use super::session::{Abandoner, RenderSessionState, SessionShared};
10use super::target::SurfaceOverlay;
11use super::worker::{self, Worker};
12use crate::runtime::Outbox;
13
14/// The graphics work of a render session that attached with
15/// [`Driver::CallerThread`](crate::Driver::CallerThread), which runs only
16/// when the host's graphics thread calls [`service`](Self::service).
17///
18/// It stays on the thread that took it from
19/// [`RenderSession::take_driver_work`](crate::RenderSession::take_driver_work),
20/// where the session's renderer and graphics objects live. Service it each
21/// time the session's
22/// [`driver_work_wake`](crate::AttachOptions::driver_work_wake) runs, until
23/// it [`is_finished`](Self::is_finished).
24///
25/// Dropping it before then abandons the session, as
26/// [`RenderSession::abandon`](crate::RenderSession::abandon) does, and lets
27/// go of the graphics objects on this thread.
28pub struct DriverWork {
29    shared: Arc<SessionShared>,
30    /// The session's worker, once the first service built it.
31    worker: RefCell<Option<Worker>>,
32    /// The overlay that [`set_overlay`](Self::set_overlay) gave, until a
33    /// service hands it to the worker.
34    overlay: Cell<Option<SurfaceOverlay>>,
35    servicing: Cell<bool>,
36    finished: Cell<bool>,
37}
38
39impl std::fmt::Debug for DriverWork {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.debug_struct("DriverWork").field("finished", &self.finished.get()).finish_non_exhaustive()
42    }
43}
44
45fn ended() -> Error {
46    Error::invalid_state("the render session ended")
47}
48
49impl DriverWork {
50    pub(crate) fn new(shared: Arc<SessionShared>) -> DriverWork {
51        DriverWork {
52            shared,
53            worker: RefCell::new(None),
54            overlay: Cell::new(None),
55            servicing: Cell::new(false),
56            finished: Cell::new(false),
57        }
58    }
59
60    /// Draws `overlay` over each frame presented to the next surface that
61    /// the session makes from the next service on: its first, which the
62    /// first service makes, or the one that a later
63    /// [`set_surface`](crate::RenderSession::set_surface) gives it. A
64    /// later call replaces an overlay that no surface took yet. Only the
65    /// backend whose overlay it is draws it: a surface of another backend's
66    /// fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind), as its
67    /// attach or `set_surface` reports.
68    pub fn set_overlay(&self, overlay: SurfaceOverlay) {
69        self.overlay.set(Some(overlay));
70    }
71
72    /// Runs the session's work that is ready, and returns once none is: the
73    /// attach, frames, the work that the handle sent, and the detach. The
74    /// first service builds the session's renderer: in the browser, the first
75    /// once the device that the session asked WebGPU for is there. The
76    /// session's completions and other wakes may run inside it, on this
77    /// thread, but its driver work wake doesn't: the service takes the work
78    /// that comes while it runs. Work that is ready after it runs the wake
79    /// again.
80    ///
81    /// Fails with [`ErrorKind::Busy`](mln_util::ErrorKind) inside a service
82    /// that is running, which takes the work instead, and with
83    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once the session
84    /// ended before the call: its detach or release completed, or it was
85    /// abandoned. A service of an abandoned session lets go of its graphics
86    /// objects before it fails.
87    pub fn service(&self) -> Result<(), Error> {
88        if self.finished.get() {
89            return Err(ended());
90        }
91        if self.servicing.replace(true) {
92            return Err(Error::busy("the render session's driver work is running on this thread"));
93        }
94        let abandoned = self.shared.state.lock().lifecycle == RenderSessionState::Abandoned;
95        let armed = &self.shared.driver_armed;
96        if !abandoned && self.shared.preparing.load(Ordering::SeqCst) {
97            armed.store(true, Ordering::SeqCst);
98            // The session's device is on its way, and the wake runs once it
99            // is here.
100            self.servicing.set(false);
101            return Ok(());
102        }
103        {
104            let _call = self.shared.enter_call();
105            let queue = &self.shared.queue;
106            // The wake waits while the service runs, and the service runs
107            // the work that comes meanwhile, so the wake never comes on this
108            // thread during a service. It's armed again only once the queue
109            // is empty; work that came just before that runs here too.
110            armed.store(false, Ordering::SeqCst);
111            let mut worker = self.worker.borrow_mut();
112            let mut overlay = self.overlay.take();
113            worker::build(&self.shared, &mut worker, &mut overlay);
114            match worker.as_mut() {
115                Some(worker) if overlay.is_some() => worker.overlay = overlay,
116                Some(_) => {}
117                None => self.overlay.set(overlay),
118            }
119            loop {
120                while queue.run_once(&mut worker) {}
121                armed.store(true, Ordering::SeqCst);
122                if !queue.has_pending() {
123                    break;
124                }
125                armed.store(false, Ordering::SeqCst);
126            }
127            let done = worker.as_ref().is_some_and(Worker::is_done);
128            drop(worker);
129            if abandoned || done {
130                self.end();
131            }
132        }
133        self.servicing.set(false);
134        if abandoned { Err(ended()) } else { Ok(()) }
135    }
136
137    /// Whether the session ended, so the host needn't service it again.
138    pub fn is_finished(&self) -> bool {
139        self.finished.get()
140    }
141
142    /// Lets go of the session's renderer and graphics objects, then of the
143    /// driver-work wake: its release tells the host that the session makes
144    /// no more graphics calls.
145    fn end(&self) {
146        self.finished.set(true);
147        let mut outbox = Outbox::default();
148        let gate = self.shared.gate.lock();
149        let worker = self.worker.borrow_mut().take();
150        if let Some(worker) = worker {
151            worker.close(&mut outbox);
152        }
153        drop(gate);
154        self.shared.queue.set_waker(None);
155        self.shared.wait_for_senders();
156        outbox.deliver();
157        // The session's work that waits, and that comes from now on, drops,
158        // so tasks that hold the queue can't keep it alive.
159        self.shared.queue.close();
160    }
161}
162
163impl Drop for DriverWork {
164    fn drop(&mut self) {
165        if self.finished.get() {
166            return;
167        }
168        let _ = self.shared.abandon(Abandoner::Library);
169        self.end();
170    }
171}