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;
4use std::sync::Arc;
5use std::sync::atomic::Ordering;
6
7use mln_actor::RunLoop;
8use mln_util::error::Error;
9use mln_util::sync::MutexExt;
10
11use super::session::{Abandoner, RenderSessionState, SessionShared};
12use super::worker::{self, Slot, Worker};
13use crate::runtime::Outbox;
14
15/// The graphics work of a render session that attached with
16/// [`Driver::CallerThread`](crate::Driver::CallerThread), which runs only
17/// when the host's graphics thread calls [`service`](Self::service).
18///
19/// It stays on the thread that took it from
20/// [`RenderSession::take_driver_work`](crate::RenderSession::take_driver_work),
21/// where the session's renderer and graphics objects live. Service it each
22/// time the session's
23/// [`driver_work_wake`](crate::AttachOptions::driver_work_wake) runs, until
24/// it [`is_finished`](Self::is_finished).
25///
26/// Dropping it before then abandons the session, as
27/// [`RenderSession::abandon`](crate::RenderSession::abandon) does, and lets
28/// go of the graphics objects on this thread.
29pub struct DriverWork {
30    shared: Arc<SessionShared>,
31    run_loop: RunLoop,
32    slot: Slot,
33    servicing: Cell<bool>,
34    finished: Cell<bool>,
35}
36
37impl std::fmt::Debug for DriverWork {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        f.debug_struct("DriverWork").field("finished", &self.finished.get()).finish_non_exhaustive()
40    }
41}
42
43fn ended() -> Error {
44    Error::invalid_state("the render session ended")
45}
46
47impl DriverWork {
48    pub(crate) fn new(shared: Arc<SessionShared>, run_loop: RunLoop) -> DriverWork {
49        DriverWork { shared, run_loop, slot: Slot::default(), servicing: Cell::new(false), finished: Cell::new(false) }
50    }
51
52    /// Runs the session's work that is ready, and returns once none is: the
53    /// attach, frames, the work that the handle sent, and the detach. The
54    /// first service builds the session's renderer. The session's
55    /// completions and wakes may run inside it, on this thread.
56    ///
57    /// Fails with [`ErrorKind::Busy`](mln_util::ErrorKind) inside a service
58    /// that is running, which takes the work instead, and with
59    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once the session
60    /// ended before the call: its detach or release completed, or it was
61    /// abandoned. A service of an abandoned session lets go of its graphics
62    /// objects before it fails.
63    pub fn service(&self) -> Result<(), Error> {
64        if self.finished.get() {
65            return Err(ended());
66        }
67        if self.servicing.replace(true) {
68            return Err(Error::busy("the render session's driver work is running on this thread"));
69        }
70        let abandoned = self.shared.state.lock_unpoisoned().lifecycle == RenderSessionState::Abandoned;
71        self.shared.driver_armed.store(true, Ordering::SeqCst);
72        {
73            let _current = self.run_loop.enter();
74            let _worker = worker::enter(&self.slot);
75            worker::build(&self.shared, &self.slot);
76            while self.run_loop.run_once() {}
77            if abandoned || self.slot.borrow().as_ref().is_some_and(Worker::is_done) {
78                self.end();
79            }
80        }
81        self.servicing.set(false);
82        if abandoned { Err(ended()) } else { Ok(()) }
83    }
84
85    /// Whether the session ended, so the host needn't service it again.
86    pub fn is_finished(&self) -> bool {
87        self.finished.get()
88    }
89
90    /// Lets go of the session's renderer and graphics objects, with the
91    /// session's loop current.
92    fn end(&self) {
93        self.finished.set(true);
94        self.shared.run_loop.set_waker(None);
95        let mut outbox = Outbox::default();
96        let gate = self.shared.gate.lock_unpoisoned();
97        let worker = self.slot.borrow_mut().take();
98        if let Some(worker) = worker {
99            worker.close(&mut outbox);
100        }
101        drop(gate);
102        outbox.deliver();
103    }
104}
105
106impl Drop for DriverWork {
107    fn drop(&mut self) {
108        if self.finished.get() {
109            return;
110        }
111        let _ = self.shared.abandon(Abandoner::Library);
112        let _current = self.run_loop.enter();
113        let _worker = worker::enter(&self.slot);
114        self.end();
115    }
116}