Skip to main content

mln_runtime/render/
session.rs

1//! The handle of a render session, and the state that its thread shares
2//! with the handle.
3
4use std::any::Any;
5use std::cell::RefCell;
6use std::collections::BTreeMap;
7use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
8use std::sync::{Arc, Mutex, OnceLock};
9use std::thread::ThreadId;
10
11use mln_actor::{RunLoop, RunLoopHandle};
12use mln_map::LogicalExtent;
13use mln_renderer::query::{RenderedQueryOptions, SourceQueryOptions};
14use mln_util::error::Error;
15use mln_util::feature::Feature;
16use mln_util::image::PremultipliedImage;
17use mln_util::size::Size;
18use mln_util::sync::MutexExt;
19
20use super::driver::DriverWork;
21use super::frame::{FrameDemand, FrameResult};
22use super::local::Pending;
23use super::query::RenderedQueryGeometry;
24use super::target::{
25    AttachOptions, BorrowedRing, ConsumerSync, Device, Driver, ExportKind, FrameTexture, GpuSync, RenderTarget,
26    Surface, SyncKind, SyncKinds, Wake,
27};
28use super::worker::{self, Init, TargetInit, Worker};
29use crate::completion::{Completion, Home, Resolver};
30use crate::map::{Applied, Map};
31use crate::runtime::Outbox;
32
33/// The ID of a render session, unique in the process.
34#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
35pub(crate) struct SessionId(u64);
36
37/// Where a render session is in its life.
38#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
39pub enum RenderSessionState {
40    /// The session is starting: it builds its renderer and binds to its map.
41    Attaching,
42    Attached,
43    /// A detach or release is on its way.
44    Detaching,
45    /// The session let go of its map and its graphics objects.
46    Detached,
47    /// The session couldn't build its renderer. Its snapshot says why.
48    Failed,
49    Abandoned,
50}
51
52/// The state of a render session at one moment.
53#[derive(Clone, Debug, PartialEq)]
54pub struct RenderSessionSnapshot {
55    pub state: RenderSessionState,
56    /// The target's logical size, and the map's pixel ratio.
57    pub extent: LogicalExtent,
58    /// Grows each time the target changes size or is replaced.
59    pub generation: u64,
60    /// Counts the frames that the session rendered.
61    pub frame_generation: u64,
62    /// Why the session failed.
63    pub failure: Option<Error>,
64    /// Whether the session is attached and has a target to render to. It is
65    /// false from a [`release_target`](RenderSession::release_target) until
66    /// a [`set_surface`](RenderSession::set_surface) gives it a new one.
67    pub has_target: bool,
68    /// How many of a borrowed ring's frames the host holds.
69    pub acquired_frames: u32,
70}
71
72/// What a render session can do.
73#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
74pub struct RenderSessionCapabilities {
75    pub driver: Driver,
76    /// How many textures the session's texture ring has.
77    pub texture_ring_depth: u32,
78    /// Whether the host can take the frames it renders.
79    pub frame_acquisition: bool,
80    /// Whether [`RenderSession::read_texture`] can read its pixels.
81    pub readback: bool,
82    /// Whether it shows frames on a surface.
83    pub presentation: bool,
84    /// The kind of sync that a borrowed ring's frames carry.
85    pub producer_sync_kind: Option<SyncKind>,
86    /// The kinds of sync that [`AcquiredFrame::release`] takes.
87    pub consumer_sync_kinds: SyncKinds,
88    /// How an exported ring shares its images, for an exported ring.
89    pub export_kind: Option<ExportKind>,
90}
91
92/// A frame of a borrowed ring that the session published, and what the
93/// host waits for before it reads it.
94#[derive(Clone, Debug)]
95pub(crate) struct Published {
96    pub(crate) result: FrameResult,
97    pub(crate) sync: GpuSync,
98    pub(crate) texture: Option<FrameTexture>,
99}
100
101/// One texture of a borrowed ring.
102#[derive(Clone, Debug, Default)]
103pub(crate) struct RingSlot {
104    /// The newest frame rendered into the texture, which the host hasn't
105    /// acquired.
106    pub(crate) frame: Option<Published>,
107    pub(crate) acquired: bool,
108    pub(crate) rendering: bool,
109    /// The host's GPU may still read the texture, so the session renders
110    /// into it no more, even when a new ring has it again, until a release
111    /// of the ring.
112    pub(crate) quarantined: bool,
113    /// The host holds an exported ring's image from before a resize, which
114    /// gave the slot a new one that never reached the host: giving the old
115    /// one up quarantines nothing.
116    pub(crate) retired: bool,
117}
118
119impl RingSlot {
120    pub(crate) fn busy(&self) -> bool {
121        self.acquired || self.rendering || self.quarantined
122    }
123}
124
125/// Work sent to a session's thread, whose completion an abandon can fail at
126/// once instead of waiting for the thread to run it.
127pub(crate) trait PendingWork: Send {
128    fn fail(self: Box<Self>, error: Error);
129    fn into_any(self: Box<Self>) -> Box<dyn Any + Send>;
130}
131
132impl<T: Send + 'static> PendingWork for Resolver<T> {
133    fn fail(self: Box<Self>, error: Error) {
134        (*self).resolve(Err(error));
135    }
136
137    fn into_any(self: Box<Self>) -> Box<dyn Any + Send> {
138        self
139    }
140}
141
142/// The ID of a piece of work that waits for a session's thread.
143#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
144pub(crate) struct WorkId(u64);
145
146/// The state that a session's handle and its thread share.
147pub(crate) struct SessionState {
148    pub(crate) lifecycle: RenderSessionState,
149    pub(crate) released: bool,
150    pub(crate) size: Size,
151    /// The scale factor that the target has, as `size` does.
152    pub(crate) scale_factor: f64,
153    /// The scale factor of the last resize sent, which a later resize that
154    /// names none keeps.
155    pub(crate) sent_scale_factor: f64,
156    pub(crate) generation: u64,
157    pub(crate) frame_generation: u64,
158    pub(crate) failure: Option<Error>,
159    /// Whether the session has a target to render to: false from a release
160    /// of its target until it gets a new one.
161    pub(crate) has_target: bool,
162    /// The frame results that wait for a drain.
163    pub(crate) results: Vec<FrameResult>,
164    /// Whether the frame wake ran since the last drain.
165    pub(crate) frame_woken: bool,
166    /// Whether the redraw wake may run: from the last demand until it runs.
167    pub(crate) redraw_armed: bool,
168    /// The attach's completion, until the map binds the session.
169    pub(crate) attach: Option<Resolver<()>>,
170    /// The completions of the detaches on their way.
171    pub(crate) detach_waiters: Vec<Resolver<()>>,
172    /// The completions of the releases on their way.
173    pub(crate) release_waiters: Vec<Resolver<()>>,
174    /// The completions of the work that waits for the session's thread.
175    pending: BTreeMap<WorkId, Box<dyn PendingWork>>,
176    next_work: u64,
177    /// The session's map, until the session lets go of it.
178    pub(crate) map: Option<Map>,
179    /// What the session's thread builds the renderer from, until it does:
180    /// an [`Init`]. It is boxed as `Any` so that the state names no
181    /// graphics types, whose auto traits are deep to prove for every type
182    /// that holds a map handle.
183    pub(crate) init: Option<Box<dyn Any + Send>>,
184    /// Counts the resizes sent, which run on the map's thread before they
185    /// reach the session's.
186    pub(crate) resizes_sent: u64,
187    /// How many graphics objects the session's thread holds.
188    pub(crate) graphics_objects: u32,
189    /// Whether the session's thread keeps its graphics objects until the
190    /// process exits, instead of freeing them, when the session ends.
191    pub(crate) keep_graphics: bool,
192    /// The slots of a borrowed ring, and none for another target.
193    pub(crate) ring: Vec<RingSlot>,
194    /// How many of the ring's frames the host holds.
195    pub(crate) acquired_frames: u32,
196    /// The ring replacements and releases on their way: no frame is
197    /// acquired until they ran, since the frames published before one name
198    /// textures it replaces or lets go of.
199    pub(crate) pending_retargets: u32,
200    /// How many views are open on the session's acquired frames.
201    pub(crate) views: u32,
202    /// Whether the session's thread keeps graphics objects that the open
203    /// views name, which it lets go of once the last view ends.
204    pub(crate) viewed_teardown: bool,
205}
206
207impl SessionState {
208    /// Keeps `resolver` until the session's thread takes it.
209    fn register<T: Send + 'static>(&mut self, resolver: Resolver<T>) -> WorkId {
210        self.next_work += 1;
211        let id = WorkId(self.next_work);
212        self.pending.insert(id, Box::new(resolver));
213        id
214    }
215
216    /// What an end of the session completes, once the state is unlocked.
217    pub(crate) fn take_waiters(&mut self) -> Waiters {
218        Waiters {
219            attach: self.attach.take(),
220            pending: std::mem::take(&mut self.pending).into_values().collect(),
221            detaches: std::mem::take(&mut self.detach_waiters),
222            releases: std::mem::take(&mut self.release_waiters),
223        }
224    }
225}
226
227/// The completions that wait for a session when it ends.
228pub(crate) struct Waiters {
229    attach: Option<Resolver<()>>,
230    pending: Vec<Box<dyn PendingWork>>,
231    detaches: Vec<Resolver<()>>,
232    releases: Vec<Resolver<()>>,
233}
234
235impl Waiters {
236    /// Completes the releases, and the detaches with `detached`. The attach
237    /// and the work that never ran fail with `lost`.
238    pub(crate) fn settle(self, detached: &Result<(), Error>, lost: impl Fn() -> Error) {
239        if let Some(attach) = self.attach {
240            attach.resolve(Err(lost()));
241        }
242        for work in self.pending {
243            work.fail(lost());
244        }
245        for waiter in self.detaches {
246            waiter.resolve(detached.clone());
247        }
248        for waiter in self.releases {
249            waiter.resolve(Ok(()));
250        }
251    }
252}
253
254/// Who abandons a session.
255#[derive(Clone, Copy, PartialEq, Eq)]
256pub(crate) enum Abandoner {
257    /// The host, through the handle.
258    Host,
259    /// The library, for a session that the host released, or stopped
260    /// servicing.
261    Library,
262}
263
264pub(crate) struct SessionShared {
265    pub(crate) id: SessionId,
266    pub(crate) driver: Driver,
267    pub(crate) run_loop: RunLoopHandle,
268    /// The thread that runs the session's work, once it is known: a core
269    /// worker's from the attach, and a caller thread's from when the host
270    /// takes the driver work.
271    pub(crate) thread: Arc<OnceLock<ThreadId>>,
272    /// The thread of the map's runtime, which runs the map's side of the
273    /// session's work.
274    runtime_thread: ThreadId,
275    pub(crate) state: Mutex<SessionState>,
276    /// Held while the session's thread runs a task, so an abandon waits for
277    /// the graphics work in progress.
278    pub(crate) gate: Mutex<()>,
279    pub(crate) frame_wake: Option<Wake>,
280    pub(crate) redraw_wake: Option<Wake>,
281    capabilities: RenderSessionCapabilities,
282    driver_work_taken: AtomicBool,
283    /// Whether the driver-work wake may run: from the start of the last
284    /// service until it runs.
285    pub(crate) driver_armed: Arc<AtomicBool>,
286}
287
288impl SessionShared {
289    /// A completion that the session's thread resolves.
290    fn completion<T: Send + 'static>(&self) -> (Completion<T>, Resolver<T>) {
291        Completion::at(Home::Later(self.thread.clone(), self.runtime_thread))
292    }
293
294    /// The completion of the work `id`, unless an end of the session
295    /// completed it first.
296    pub(crate) fn take_work<T: Send + 'static>(&self, id: WorkId) -> Option<Resolver<T>> {
297        let work = self.state.lock_unpoisoned().pending.remove(&id)?;
298        work.into_any().downcast::<Resolver<T>>().ok().map(|resolver| *resolver)
299    }
300
301    pub(crate) fn is_released(&self) -> bool {
302        self.state.lock_unpoisoned().released
303    }
304
305    /// Starts a detach on the session's thread, after the work sent before.
306    /// The state is locked, and the session usable or failed.
307    fn start_detach(&self, state: &mut SessionState) {
308        state.lifecycle = RenderSessionState::Detaching;
309        worker::post(&self.run_loop, worker::Worker::detach);
310    }
311
312    /// Releases the session without waiting: it detaches, unless it is
313    /// detached or abandoned already, and every call on it fails after. A
314    /// caller-driven session that isn't attached is abandoned instead, so the
315    /// release doesn't wait for the host to service it.
316    fn dispose(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
317        with_unlocked_wakes(|| self.dispose_locked(done))
318    }
319
320    /// Releases the session without waiting and without graphics calls past
321    /// the one in progress: a session that hasn't ended is abandoned, and
322    /// keeps its graphics objects until the process exits.
323    fn dispose_keeping_graphics(&self) -> Result<(), Error> {
324        with_unlocked_wakes(|| {
325            {
326                let mut state = self.state.lock_unpoisoned();
327                if state.released {
328                    return Err(released());
329                }
330                state.released = true;
331                state.keep_graphics = true;
332                if matches!(state.lifecycle, RenderSessionState::Detached | RenderSessionState::Abandoned) {
333                    return Ok(());
334                }
335            }
336            if self.abandon_locked(Abandoner::Library, true).is_err() {
337                // Only the session's own work could hold the gate here: the
338                // session detaches after it, keeping its graphics objects.
339                let mut state = self.state.lock_unpoisoned();
340                if !matches!(
341                    state.lifecycle,
342                    RenderSessionState::Detaching | RenderSessionState::Detached | RenderSessionState::Abandoned
343                ) {
344                    self.start_detach(&mut state);
345                }
346            }
347            Ok(())
348        })
349    }
350
351    fn dispose_locked(&self, done: Option<Resolver<()>>) -> Result<(), Error> {
352        let mut state = self.state.lock_unpoisoned();
353        if state.released {
354            return Err(released());
355        }
356        state.released = true;
357        match state.lifecycle {
358            RenderSessionState::Detached | RenderSessionState::Abandoned => {
359                drop(state);
360                if let Some(done) = done {
361                    done.resolve(Ok(()));
362                }
363                return Ok(());
364            }
365            RenderSessionState::Detaching => {}
366            RenderSessionState::Attaching | RenderSessionState::Failed if self.driver == Driver::CallerThread => {
367                state.release_waiters.extend(done);
368                drop(state);
369                if self.abandon(Abandoner::Library).is_err() {
370                    // Only the session's own work could hold the gate here.
371                    let mut state = self.state.lock_unpoisoned();
372                    if state.lifecycle != RenderSessionState::Abandoned {
373                        self.start_detach(&mut state);
374                    }
375                }
376                return Ok(());
377            }
378            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Failed => {
379                self.start_detach(&mut state);
380            }
381        }
382        state.release_waiters.extend(done);
383        Ok(())
384    }
385
386    /// Stops the session at once, as [`RenderSession::abandon`] documents.
387    /// The library may abandon a released session too.
388    pub(crate) fn abandon(&self, by: Abandoner) -> Result<(), Error> {
389        with_unlocked_wakes(|| self.abandon_locked(by, false)).map(drop)
390    }
391
392    /// Abandons the session, which keeps its graphics objects until the
393    /// process exits if `keep_graphics`, and returns how many it keeps.
394    fn abandon_locked(&self, by: Abandoner, keep_graphics: bool) -> Result<u32, Error> {
395        let on_driver = self.thread.get() == Some(&std::thread::current().id());
396        let gate = if on_driver {
397            self.gate.try_lock().map_err(|_| Error::busy("the render session is rendering on this thread"))?
398        } else {
399            self.gate.lock_unpoisoned()
400        };
401        let (waiters, map, kept) = {
402            let mut state = self.state.lock_unpoisoned();
403            if by == Abandoner::Host && state.released {
404                return Err(released());
405            }
406            match state.lifecycle {
407                RenderSessionState::Attaching
408                | RenderSessionState::Attached
409                | RenderSessionState::Detaching
410                | RenderSessionState::Failed => {}
411                RenderSessionState::Detached | RenderSessionState::Abandoned => {
412                    return Err(Error::invalid_state("the render session was detached or abandoned"));
413                }
414            }
415            // The views keep the frames' sync objects in place, which the
416            // abandon would let go of. A library's abandon, of a session
417            // that the host released, keeps them until the views end.
418            if by == Abandoner::Host && state.views != 0 {
419                return Err(Error::busy("a view is open on one of the render session's acquired frames"));
420            }
421            state.lifecycle = RenderSessionState::Abandoned;
422            state.keep_graphics |= keep_graphics;
423            let kept = if state.keep_graphics { state.graphics_objects } else { 0 };
424            (state.take_waiters(), state.map.take(), kept)
425        };
426        match &map {
427            // The map unbinds the session before another can attach.
428            Some(map) => {
429                map.unbind_session_then(self.id, self.run_loop.clone(), super::worker::Worker::finish);
430                map.release_session_claim(self.id);
431            }
432            None => worker::post(&self.run_loop, worker::Worker::finish),
433        }
434        // A core worker lets go of its graphics objects at its next task,
435        // which runs before this returns: the host may destroy what they were
436        // made on once it does.
437        let torn_down = (self.driver == Driver::CoreWorker && !on_driver).then(|| {
438            let (sender, receiver) = std::sync::mpsc::sync_channel::<()>(1);
439            worker::post(&self.run_loop, move |_, _| {
440                let _ = sender.send(());
441            });
442            receiver
443        });
444        drop(gate);
445        if let Some(receiver) = torn_down {
446            // A worker that ended drops the task, and the sender with it.
447            let _ = receiver.recv();
448        }
449        let lost = || Error::target_lost("the render session was abandoned");
450        waiters.settle(&Err(lost()), lost);
451        drop(map);
452        Ok(kept)
453    }
454}
455
456fn released() -> Error {
457    Error::invalid_state("the render session was released")
458}
459
460/// Fails unless the session takes work: it is attaching or attached, and
461/// not released.
462fn check_usable(state: &SessionState) -> Result<(), Error> {
463    if state.released {
464        return Err(released());
465    }
466    match state.lifecycle {
467        RenderSessionState::Attaching | RenderSessionState::Attached => Ok(()),
468        RenderSessionState::Failed => {
469            Err(state.failure.clone().unwrap_or_else(|| Error::native("the render session failed")))
470        }
471        RenderSessionState::Detaching | RenderSessionState::Detached | RenderSessionState::Abandoned => {
472            Err(Error::invalid_state("the render session is not attached: it was detached or abandoned"))
473        }
474    }
475}
476
477thread_local! {
478    /// The driver wakes that this thread's posts asked for during a handle
479    /// call, which may hold the session's locks.
480    static DEFERRED_WAKES: RefCell<Option<Vec<Wake>>> = const { RefCell::new(None) };
481}
482
483/// Runs `call`, which may post to a session's loop with the session's locks
484/// held, then the driver wakes that its posts asked for, with nothing locked.
485fn with_unlocked_wakes<R>(call: impl FnOnce() -> R) -> R {
486    let outer = DEFERRED_WAKES.with(|deferred| deferred.borrow_mut().replace(Vec::new()));
487    let result = call();
488    let wakes = DEFERRED_WAKES.with(|deferred| {
489        let mut deferred = deferred.borrow_mut();
490        let wakes = deferred.take().unwrap_or_default();
491        match outer {
492            // The outer call runs them.
493            Some(mut outer) => {
494                outer.extend(wakes);
495                *deferred = Some(outer);
496                Vec::new()
497            }
498            None => wakes,
499        }
500    });
501    for wake in wakes {
502        wake();
503    }
504    result
505}
506
507/// Runs `wake` now, or once the handle call on this thread returns.
508fn wake_unlocked(wake: &Wake) {
509    let deferred = DEFERRED_WAKES.with(|deferred| match deferred.borrow_mut().as_mut() {
510        Some(wakes) => {
511            wakes.push(wake.clone());
512            true
513        }
514        None => false,
515    });
516    if !deferred {
517        wake();
518    }
519}
520
521/// Sizes in pixels a target of `size` logical pixels at `pixel_ratio`.
522pub(crate) fn physical_size(size: Size, pixel_ratio: f32) -> Size {
523    Size::new((size.width as f32 * pixel_ratio) as u32, (size.height as f32 * pixel_ratio) as u32)
524}
525
526/// A render session: a renderer that draws a map into a target, on a thread
527/// of its own or on the host's.
528///
529/// The host demands frames, which finish with [`FrameResult`]s that
530/// [`drain_frame_results`](Self::drain_frame_results) takes. A demand shows
531/// the map's commands sent before it, except the changes that an open
532/// command group holds back. The session's work runs on its thread in the
533/// order it was sent, and reports through a [`Completion`]. `Clone` is
534/// another handle to the same session, and any thread may use one.
535///
536/// A session that attached with [`Driver::CallerThread`] runs its work only
537/// when the host services its [`DriverWork`], which
538/// [`take_driver_work`](Self::take_driver_work) hands out.
539///
540/// The session lives until [`detach`](Self::detach),
541/// [`release`](Self::release), [`dispose`](Self::dispose) or
542/// [`abandon`](Self::abandon), or until its last handle drops, and it holds
543/// its map until then. A call that sends work to a session that no longer
544/// takes it fails with [`ErrorKind::InvalidState`](mln_util::ErrorKind), or
545/// with the failure of a session that failed.
546#[derive(Clone)]
547pub struct RenderSession {
548    handle: Arc<SessionHandle>,
549}
550
551/// Disposes of the session when the last handle drops.
552struct SessionHandle {
553    shared: Arc<SessionShared>,
554}
555
556impl Drop for SessionHandle {
557    fn drop(&mut self) {
558        let _ = self.shared.dispose(None);
559    }
560}
561
562impl std::fmt::Debug for RenderSession {
563    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
564        f.debug_struct("RenderSession").field("id", &self.shared().id).finish()
565    }
566}
567
568impl PartialEq for RenderSession {
569    fn eq(&self, other: &RenderSession) -> bool {
570        Arc::ptr_eq(&self.handle, &other.handle)
571    }
572}
573
574impl Eq for RenderSession {}
575
576/// Attaches a session to `map`, as [`Map::attach`] documents.
577pub(crate) fn attach(
578    map: &Map,
579    target: RenderTarget,
580    options: AttachOptions,
581) -> Result<(RenderSession, Completion<()>), Error> {
582    static NEXT_ID: AtomicU64 = AtomicU64::new(1);
583    let mut ring = None;
584    let mut export_kind = None;
585    let (size, target) = match target {
586        RenderTarget::Offscreen { size, device } => (size, TargetInit::Offscreen(device)),
587        RenderTarget::Surface { size, surface, device } => {
588            if device.is_none() && !surface.needs_no_device() {
589                return Err(Error::invalid_argument("a surface that the host made needs the host's device"));
590            }
591            surface.check_area()?;
592            (size, TargetInit::Surface { surface, device })
593        }
594        RenderTarget::Borrowed { size, ring: borrowed, device } => {
595            let (producer, consumer) = device.borrowed_sync_kinds(&borrowed)?;
596            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
597                Error::unsupported("render target supports none of the requested producer sync kinds")
598            })?;
599            if borrowed.depth() == 0 || borrowed.physical_size().is_empty() {
600                return Err(Error::invalid_argument("a borrowed ring needs textures of a size"));
601            }
602            ring = Some((borrowed.depth(), picked, consumer));
603            (size, TargetInit::Borrowed { ring: borrowed, device, producer: picked })
604        }
605        RenderTarget::Exported { size, ring: exported, device } => {
606            if exported.depth == 0 {
607                return Err(Error::invalid_argument("an exported ring needs at least one image"));
608            }
609            if exported.kinds.is_empty() {
610                return Err(Error::invalid_argument("an exported ring needs a kind of image to share"));
611            }
612            if size.is_empty() {
613                return Err(Error::invalid_argument("the target's size must not be empty"));
614            }
615            let device = match device {
616                Some(device) => device,
617                None => Device::for_exported_ring(&exported)?,
618            };
619            let (kind, producer, consumer) = device.export_plan(&exported)?;
620            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
621                Error::unsupported("render target supports none of the requested producer sync kinds")
622            })?;
623            ring = Some((exported.depth, picked, consumer));
624            export_kind = Some(kind);
625            (size, TargetInit::Exported { ring: exported, device, kind, producer: picked })
626        }
627    };
628    if size.is_empty() {
629        return Err(Error::invalid_argument("the target's size must not be empty"));
630    }
631    let presentation = matches!(target, TargetInit::Surface { .. });
632    let run_loop = RunLoopHandle::new();
633    let driver_armed = Arc::new(AtomicBool::new(true));
634    if options.driver == Driver::CallerThread
635        && let Some(wake) = options.driver_work_wake
636    {
637        let armed = driver_armed.clone();
638        run_loop.set_waker(Some(Arc::new(move || {
639            if armed.swap(false, Ordering::SeqCst) {
640                wake_unlocked(&wake);
641            }
642        })));
643    }
644    let id = SessionId(NEXT_ID.fetch_add(1, Ordering::Relaxed));
645    let scale_factor = map.scale_factor();
646    let shared = Arc::new(SessionShared {
647        id,
648        driver: options.driver,
649        run_loop: run_loop.clone(),
650        thread: Arc::default(),
651        runtime_thread: map.runtime_thread(),
652        state: Mutex::new(SessionState {
653            lifecycle: RenderSessionState::Attaching,
654            released: false,
655            size,
656            scale_factor,
657            sent_scale_factor: scale_factor,
658            generation: 1,
659            frame_generation: 0,
660            failure: None,
661            has_target: true,
662            results: Vec::new(),
663            frame_woken: false,
664            redraw_armed: true,
665            attach: None,
666            detach_waiters: Vec::new(),
667            release_waiters: Vec::new(),
668            pending: BTreeMap::new(),
669            next_work: 0,
670            map: Some(map.clone()),
671            init: Some(Box::new(Init {
672                target,
673                size,
674                scale_factor,
675                glyph_cache: map.glyph_cache(),
676                tile_cache_enabled: map.tile_cache_enabled(),
677            })),
678            resizes_sent: 0,
679            graphics_objects: 0,
680            keep_graphics: false,
681            ring: vec![RingSlot::default(); ring.map_or(0, |(depth, _, _)| depth)],
682            acquired_frames: 0,
683            pending_retargets: 0,
684            views: 0,
685            viewed_teardown: false,
686        }),
687        gate: Mutex::new(()),
688        frame_wake: options.frame_wake,
689        redraw_wake: options.redraw_wake,
690        capabilities: RenderSessionCapabilities {
691            driver: options.driver,
692            texture_ring_depth: ring.map_or(1, |(depth, _, _)| depth as u32),
693            frame_acquisition: ring.is_some(),
694            readback: !presentation && ring.is_none(),
695            presentation,
696            producer_sync_kind: ring.map(|(_, producer, _)| producer),
697            consumer_sync_kinds: ring.map_or(SyncKinds::NONE, |(_, _, consumer)| consumer),
698            export_kind,
699        },
700        driver_work_taken: AtomicBool::new(false),
701        driver_armed,
702    });
703    let (completion, resolver) = shared.completion();
704    shared.state.lock_unpoisoned().attach = Some(resolver);
705    map.claim_session(id, Arc::downgrade(&shared))?;
706    if options.driver == Driver::CoreWorker {
707        match start_thread(shared.clone()) {
708            Ok(thread) => {
709                let _ = shared.thread.set(thread);
710            }
711            Err(error) => {
712                map.release_session_claim(id);
713                return Err(error);
714            }
715        }
716    }
717    let session = RenderSession { handle: Arc::new(SessionHandle { shared }) };
718    if let Err(error) = map.bind_session(id, run_loop, size) {
719        // The map was released meanwhile: the session lets go of it.
720        drop(session);
721        return Err(error);
722    }
723    Ok((session, completion))
724}
725
726/// Starts a core worker's thread, which builds the session's renderer, then
727/// runs the session's loop until the session ends.
728fn start_thread(shared: Arc<SessionShared>) -> Result<ThreadId, Error> {
729    let thread = mln_util::thread::builder("RenderSession")
730        .spawn(move || {
731            let Some(run_loop) = RunLoop::adopt(&shared.run_loop) else { return };
732            let _current = run_loop.enter();
733            let slot = worker::Slot::default();
734            let entered = worker::enter(&slot);
735            worker::build(&shared, &slot);
736            // The worker holds the session from here on.
737            drop(shared);
738            run_loop.run();
739            let worker = slot.borrow_mut().take();
740            drop(worker);
741            drop(entered);
742        })
743        .map_err(|error| Error::native(format!("can't start the render session's thread: {error}")))?;
744    let thread_id = thread.thread().id();
745    // The thread ends by itself once the session ends, so nothing joins it.
746    drop(thread);
747    Ok(thread_id)
748}
749
750impl RenderSession {
751    fn shared(&self) -> &Arc<SessionShared> {
752        &self.handle.shared
753    }
754
755    /// Sends `task` to the session's thread, after the work sent before,
756    /// resizes included, and completes with its result. A session that lost
757    /// its graphics objects before the task runs completes it with
758    /// [`ErrorKind::TargetLost`](mln_util::ErrorKind).
759    fn operation<T: Send + 'static>(
760        &self,
761        task: impl FnOnce(&mut Worker, &mut Outbox) -> Result<T, Error> + Send + 'static,
762    ) -> Result<Completion<T>, Error> {
763        self.settled_operation(|worker, outbox| task(worker, outbox).map(|value| (value, None)))
764    }
765
766    /// Sends `task` as [`operation`](Self::operation) does, and completes
767    /// once the host's reads that it returns end, or a second passes.
768    fn settled_operation<T: Send + 'static>(
769        &self,
770        task: impl FnOnce(&mut Worker, &mut Outbox) -> Result<(T, Pending), Error> + Send + 'static,
771    ) -> Result<Completion<T>, Error> {
772        let shared = self.shared();
773        with_unlocked_wakes(|| {
774            let mut state = shared.state.lock_unpoisoned();
775            check_usable(&state)?;
776            let (completion, resolver) = shared.completion();
777            let work = state.register(resolver);
778            let resizes = state.resizes_sent;
779            worker::post(&shared.run_loop, move |worker, outbox| {
780                let task: worker::Task = Box::new(move |worker, outbox| {
781                    let Some(resolver) = worker.take_work(work) else { return };
782                    match task(worker, outbox) {
783                        Ok((value, pending)) => worker.settle_then(
784                            pending,
785                            move |outbox, settled| outbox.resolve(resolver, settled.map(|()| value)),
786                            outbox,
787                        ),
788                        Err(error) => outbox.resolve(resolver, Err(error)),
789                    }
790                });
791                worker.after_resizes(resizes, task, outbox);
792            });
793            drop(state);
794            Ok(completion)
795        })
796    }
797
798    /// Hands out the work of a [`Driver::CallerThread`] session, for the
799    /// calling thread to run: the session's graphics work runs only in its
800    /// [`service`](DriverWork::service), and on no other thread.
801    ///
802    /// Take it once, on the host's graphics thread, from the attach on: the
803    /// attach itself completes in a service. It stays available after a
804    /// release, which the host services to its end.
805    ///
806    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
807    /// session on a core worker, and with
808    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once it was taken.
809    pub fn take_driver_work(&self) -> Result<DriverWork, Error> {
810        let shared = self.shared();
811        if shared.driver != Driver::CallerThread {
812            return Err(Error::unsupported("the render session runs on a core worker"));
813        }
814        if shared.driver_work_taken.swap(true, Ordering::SeqCst) {
815            return Err(Error::invalid_state("the render session's driver work was taken already"));
816        }
817        let run_loop = RunLoop::adopt(&shared.run_loop)
818            .ok_or_else(|| Error::invalid_state("the render session's driver work was taken already"))?;
819        let _ = shared.thread.set(std::thread::current().id());
820        Ok(DriverWork::new(shared.clone(), run_loop))
821    }
822
823    /// What the session can do. Fails with
824    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once it is released.
825    pub fn capabilities(&self) -> Result<RenderSessionCapabilities, Error> {
826        let state = self.shared().state.lock_unpoisoned();
827        if state.released {
828            return Err(released());
829        }
830        Ok(self.shared().capabilities)
831    }
832
833    /// The session's state now. Fails with
834    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once it is released.
835    pub fn snapshot(&self) -> Result<RenderSessionSnapshot, Error> {
836        let state = self.shared().state.lock_unpoisoned();
837        if state.released {
838            return Err(released());
839        }
840        Ok(RenderSessionSnapshot {
841            state: state.lifecycle,
842            extent: LogicalExtent { size: state.size, scale_factor: state.scale_factor },
843            generation: state.generation,
844            frame_generation: state.frame_generation,
845            failure: state.failure.clone(),
846            has_target: state.lifecycle == RenderSessionState::Attached && state.has_target,
847            acquired_frames: state.acquired_frames,
848        })
849    }
850
851    /// Takes the newest frame that a borrowed ring rendered, if one waits:
852    /// the older frames that the host didn't acquire are dropped, and the
853    /// session may render into their textures again. While the host holds a
854    /// frame in every texture, demands wait for a release.
855    ///
856    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
857    /// session without a ring, and as a call that sends work does once the
858    /// session no longer takes work.
859    pub fn acquire_frame(&self) -> Result<Option<AcquiredFrame>, Error> {
860        let shared = self.shared();
861        let mut state = shared.state.lock_unpoisoned();
862        check_usable(&state)?;
863        if !shared.capabilities.frame_acquisition {
864            return Err(Error::unsupported("render session does not expose acquired texture frames"));
865        }
866        if state.pending_retargets != 0 {
867            return Ok(None);
868        }
869        let newest = state
870            .ring
871            .iter()
872            .enumerate()
873            .filter(|(_, slot)| !slot.acquired && slot.frame.is_some())
874            .max_by_key(|(_, slot)| slot.frame.as_ref().map_or(0, |frame| frame.result.frame_generation))
875            .map(|(index, _)| index);
876        let Some(index) = newest else { return Ok(None) };
877        for (other, slot) in state.ring.iter_mut().enumerate() {
878            if other != index && !slot.acquired {
879                slot.frame = None;
880            }
881        }
882        let slot = &mut state.ring[index];
883        let Some(frame) = slot.frame.take() else { return Ok(None) };
884        slot.acquired = true;
885        state.acquired_frames += 1;
886        Ok(Some(AcquiredFrame { shared: shared.clone(), slot: index, frame, done: false }))
887    }
888
889    /// Gives a borrowed ring new textures, of `size` logical pixels: as many
890    /// as it has, of its format. Once the completion reports success, the
891    /// session no longer uses the old textures, and no longer waits for the
892    /// consumer sync that they were given back with: the host may reuse or
893    /// destroy them. The session's thread polls that sync on its later turns,
894    /// for a second at most, and logs a wait that runs out. Frames wait for
895    /// it meanwhile.
896    ///
897    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
898    /// session without a borrowed ring, with
899    /// [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for another number
900    /// of textures, and with [`ErrorKind::InvalidState`](mln_util::ErrorKind)
901    /// while the host holds one of the ring's frames. Completes with
902    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) for textures of
903    /// another format or kind.
904    pub fn set_ring(&self, size: Size, ring: BorrowedRing) -> Result<Completion<Applied>, Error> {
905        let shared = self.shared().clone();
906        {
907            let mut state = shared.state.lock_unpoisoned();
908            check_usable(&state)?;
909            if shared.capabilities.readback {
910                return Err(Error::unsupported("an offscreen session keeps its target"));
911            }
912            if !shared.capabilities.frame_acquisition {
913                return Err(Error::unsupported("a surface session takes no caller-owned texture"));
914            }
915            if shared.capabilities.export_kind.is_some() {
916                return Err(Error::unsupported("an exported ring resizes instead of taking new textures"));
917            }
918            if state.acquired_frames != 0 {
919                return Err(Error::invalid_state("cannot replace the render target while a texture frame is acquired"));
920            }
921            if ring.depth() != state.ring.len() {
922                return Err(Error::invalid_argument(
923                    "texture_count must equal the ring depth the session attached with",
924                ));
925            }
926            state.pending_retargets += 1;
927        }
928        let guard = RetargetGuard(shared.clone());
929        // The guard goes with the closure, whether the closure runs or the
930        // resize drops it.
931        self.resize_then(size, None, move |worker, size, scale_factor, outbox| {
932            let _guard = guard;
933            worker.set_ring(size, scale_factor, &ring, outbox)
934        })
935    }
936
937    /// Asks the session to render a frame, which shows the map commands sent
938    /// before the call, except the changes that an open command group holds
939    /// back. A demand sent while the session attaches waits for it.
940    ///
941    /// Every demand finishes with one [`FrameResult`] that carries its token.
942    /// A demand that isn't [`DemandMode::Force`](super::DemandMode::Force)
943    /// replaces the demands with the same mode still on their way, which
944    /// finish as [`FrameDisposition::Superseded`](super::FrameDisposition).
945    /// While the session has no target, or a surface has no texture to
946    /// render into, a demand finishes as
947    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
948    pub fn demand_frame(&self, demand: FrameDemand) -> Result<(), Error> {
949        let shared = self.shared();
950        with_unlocked_wakes(|| {
951            let mut state = shared.state.lock_unpoisoned();
952            check_usable(&state)?;
953            if !state.ring.is_empty() && state.ring.iter().all(|slot| slot.quarantined) {
954                return Err(Error::invalid_state(
955                    "every texture of the ring is quarantined: give the session new textures",
956                ));
957            }
958            let sequence = state.map.as_ref().map_or(0, Map::sent_sequence);
959            state.redraw_armed = true;
960            worker::post(&shared.run_loop, move |worker, outbox| worker.demand(demand, sequence, outbox));
961            Ok(())
962        })
963    }
964
965    /// Takes the frame results that wait, oldest first. Fails with
966    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) once the session is
967    /// released.
968    pub fn drain_frame_results(&self) -> Result<Vec<FrameResult>, Error> {
969        let mut state = self.shared().state.lock_unpoisoned();
970        if state.released {
971            return Err(released());
972        }
973        state.frame_woken = false;
974        Ok(std::mem::take(&mut state.results))
975    }
976
977    /// Resizes the target, and the map with it, to `extent`'s size in
978    /// logical pixels, and sets the map's scale factor to `extent`'s, such
979    /// as when a window moves to a display of another density. The map keeps
980    /// its tiles, and the renderer draws the next frame at the new scale
981    /// factor. A later demand shows the new extent, and one sent before
982    /// shows the old. An exported ring gets images of the new size, and the
983    /// frames that the host holds keep theirs until it gives them back.
984    ///
985    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
986    /// empty size, or a scale factor that isn't finite and positive, and
987    /// with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a borrowed
988    /// ring, which [`set_ring`](Self::set_ring) resizes.
989    pub fn resize(&self, extent: LogicalExtent) -> Result<Completion<Applied>, Error> {
990        let capabilities = self.shared().capabilities;
991        if capabilities.frame_acquisition && capabilities.export_kind.is_none() {
992            return Err(Error::unsupported("a borrowed ring is sized by its owner: give it new textures instead"));
993        }
994        let LogicalExtent { size, scale_factor } = extent;
995        if !scale_factor.is_finite() || scale_factor <= 0.0 {
996            return Err(Error::invalid_argument(format!("scale factor {scale_factor} isn't finite and positive")));
997        }
998        self.resize_then(size, Some(scale_factor), |worker, size, scale_factor, outbox| {
999            worker.resize(size, scale_factor, outbox).map(|()| None)
1000        })
1001    }
1002
1003    /// Sends a map command that resizes the map to `size`, at
1004    /// `scale_factor` or the session's when that is `None`, then runs
1005    /// `change` on the session's thread, which resizes or replaces the
1006    /// target.
1007    fn resize_then(
1008        &self,
1009        size: Size,
1010        scale_factor: Option<f64>,
1011        change: impl FnOnce(&mut Worker, Size, f64, &mut Outbox) -> Result<Pending, Error> + Send + 'static,
1012    ) -> Result<Completion<Applied>, Error> {
1013        if size.is_empty() {
1014            return Err(Error::invalid_argument("the target's size must not be empty"));
1015        }
1016        let shared = self.shared();
1017        with_unlocked_wakes(|| {
1018            let mut state = shared.state.lock_unpoisoned();
1019            check_usable(&state)?;
1020            let map = state.map.clone().ok_or_else(|| Error::invalid_state("the render session has no map"))?;
1021            let scale_factor = scale_factor.unwrap_or(state.sent_scale_factor);
1022            state.sent_scale_factor = scale_factor;
1023            let (completion, resolver) = shared.completion();
1024            let work = state.register(resolver);
1025            // The work sent after waits for the resize to land, which it
1026            // does even when the map drops it.
1027            state.resizes_sent += 1;
1028            let landing = worker::ResizeLanding::new(shared.run_loop.clone());
1029            let sent =
1030                map.resize_for_session(size, scale_factor, shared.run_loop.clone(), move |worker, result, outbox| {
1031                    if let Some(resolver) = worker.take_work::<Applied>(work) {
1032                        match result.and_then(|applied| Ok((applied, change(worker, size, scale_factor, outbox)?))) {
1033                            // A replacement of a ring's textures completes
1034                            // once the host's reads of those it let go of end.
1035                            Ok((applied, pending)) => worker.settle_then(
1036                                pending,
1037                                move |outbox, settled| outbox.resolve(resolver, settled.map(|()| applied)),
1038                                outbox,
1039                            ),
1040                            Err(error) => outbox.resolve(resolver, Err(error)),
1041                        }
1042                    }
1043                    landing.land(worker, outbox);
1044                });
1045            if let Err(error) = sent {
1046                state.pending.remove(&work);
1047                return Err(error);
1048            }
1049            drop(state);
1050            Ok(completion)
1051        })
1052    }
1053
1054    /// Lets go of a surface session's surface, and keeps the rest of the
1055    /// session, such as when the platform takes the window away. The demands
1056    /// on their way, and later ones until
1057    /// [`set_surface`](Self::set_surface) gives the session a surface again,
1058    /// finish as [`FrameDisposition::TargetNotReady`](super::FrameDisposition).
1059    /// Once the release completes, the session no longer uses the surface or
1060    /// the window it was made from, or a ring's textures, and no longer waits
1061    /// for the consumer sync that the textures were given back with: the host
1062    /// may reuse or destroy them. The session's thread polls that sync on its
1063    /// later turns, for a second at most, and logs a wait that runs out. The
1064    /// session keeps nothing of the released textures: one that a later ring
1065    /// has again starts fresh, even one that the host gave up.
1066    ///
1067    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for an
1068    /// offscreen session or an exported ring, whose targets are their own.
1069    pub fn release_target(&self) -> Result<Completion<()>, Error> {
1070        if self.shared().capabilities.export_kind.is_some() {
1071            return Err(Error::unsupported("an exported ring keeps its images until the session ends"));
1072        }
1073        let shared = self.shared().clone();
1074        let capabilities = shared.capabilities;
1075        if !capabilities.presentation && !capabilities.frame_acquisition {
1076            check_usable(&shared.state.lock_unpoisoned())?;
1077            return Err(Error::unsupported("an offscreen session keeps its target"));
1078        }
1079        let guard = {
1080            let mut state = shared.state.lock_unpoisoned();
1081            check_usable(&state)?;
1082            if state.acquired_frames != 0 {
1083                return Err(Error::invalid_state("release every acquired frame before the target"));
1084            }
1085            // No frame is acquired until the release runs: its textures go
1086            // with it.
1087            capabilities.frame_acquisition.then(|| {
1088                state.pending_retargets += 1;
1089                RetargetGuard(shared.clone())
1090            })
1091        };
1092        self.settled_operation(move |worker, outbox| {
1093            let _guard = guard;
1094            worker.release_target(outbox).map(|pending| ((), pending))
1095        })
1096    }
1097
1098    /// Gives a surface session a new surface of `size` logical pixels, after
1099    /// [`release_target`](Self::release_target), or in place of the one it
1100    /// has, and resizes the map to it. Once the completion reports success,
1101    /// the session no longer uses the old surface. The session presents to
1102    /// it on its device: a window becomes a surface of the device's backend,
1103    /// and a `Surface::wgpu` must come from the instance of a WebGPU
1104    /// device. Where the backend made for the old surface can't present to
1105    /// the new one, as OpenGL ES's context can't to another window, the
1106    /// session makes its backend and renderer again.
1107    ///
1108    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
1109    /// empty size, with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for
1110    /// an offscreen session, and with
1111    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) for a window that is
1112    /// minimized or has no client area. Completes with
1113    /// [`ErrorKind::Unsupported`](mln_util::ErrorKind) when the session's
1114    /// device can't present to the surface in the format that the session
1115    /// renders in: attach a new session instead. Completes with
1116    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) when the window had no
1117    /// area to present to by then. The session then keeps the surface it had,
1118    /// at the new size.
1119    pub fn set_surface(&self, size: Size, surface: Surface) -> Result<Completion<Applied>, Error> {
1120        check_usable(&self.shared().state.lock_unpoisoned())?;
1121        let capabilities = self.shared().capabilities;
1122        if capabilities.frame_acquisition {
1123            return Err(Error::unsupported("a borrowed texture session takes no native surface"));
1124        }
1125        if !capabilities.presentation {
1126            return Err(Error::unsupported("an offscreen session keeps its target"));
1127        }
1128        surface.check_area()?;
1129        self.resize_then(size, None, move |worker, size, scale_factor, outbox| {
1130            worker.set_surface(size, scale_factor, surface, outbox).map(|()| None)
1131        })
1132    }
1133
1134    /// Ends the frame demands on their way, including those that wait for a
1135    /// map update, which finish as
1136    /// [`FrameDisposition::NoUpdate`](super::FrameDisposition), and completes
1137    /// once the work sent before it has run.
1138    pub fn barrier(&self) -> Result<Completion<()>, Error> {
1139        self.operation(|worker, outbox| {
1140            worker.end_demands(super::FrameDisposition::NoUpdate, outbox);
1141            Ok(())
1142        })
1143    }
1144
1145    /// Frees memory that the renderer can rebuild, such as caches.
1146    pub fn reduce_memory_use(&self) -> Result<Completion<()>, Error> {
1147        self.operation(|worker, _| worker.reduce_memory_use())
1148    }
1149
1150    /// Clears what the renderer holds, such as loaded tiles, so that the
1151    /// next frame loads and draws the map again.
1152    pub fn clear_data(&self) -> Result<Completion<()>, Error> {
1153        self.operation(worker::Worker::clear_data)
1154    }
1155
1156    /// Logs the renderer's sources and tiles.
1157    pub fn dump_debug_logs(&self) -> Result<Completion<()>, Error> {
1158        self.operation(|worker, _| worker.dump_debug_logs())
1159    }
1160
1161    /// The pixels of the last frame that an offscreen session rendered:
1162    /// premultiplied RGBA, in rows from top to bottom, at the target's size
1163    /// in pixels.
1164    ///
1165    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind) for a
1166    /// surface session. Completes with
1167    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) when the session
1168    /// hasn't rendered a frame since it attached or resized.
1169    pub fn read_texture(&self) -> Result<Completion<PremultipliedImage>, Error> {
1170        check_usable(&self.shared().state.lock_unpoisoned())?;
1171        if !self.shared().capabilities.readback {
1172            return Err(Error::unsupported("a surface session can't read its frames back"));
1173        }
1174        self.operation(|worker, _| worker.read_texture())
1175    }
1176
1177    /// The features that the session drew in an area of the screen, in its
1178    /// last frame. A feature that several layers draw appears once for each.
1179    /// A box covers only its part inside the target, so one past every edge
1180    /// covers the whole target.
1181    ///
1182    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for a
1183    /// point that isn't finite or a line string without points.
1184    pub fn query_rendered_features(
1185        &self,
1186        geometry: RenderedQueryGeometry,
1187        options: RenderedQueryOptions,
1188    ) -> Result<Completion<Vec<Feature>>, Error> {
1189        geometry.points()?;
1190        self.operation(move |worker, _| match geometry.within(worker.size()).map(|geometry| geometry.points()) {
1191            Some(points) => worker.renderer()?.query_rendered_features(&points?, &options),
1192            None => Ok(Vec::new()),
1193        })
1194    }
1195
1196    /// The features of the source `source_id` in the tiles that it loaded
1197    /// for the current view. A source loads tiles only while a visible layer
1198    /// uses it.
1199    ///
1200    /// Fails with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind) for an
1201    /// empty `source_id`.
1202    pub fn query_source_features(
1203        &self,
1204        source_id: impl Into<String>,
1205        options: SourceQueryOptions,
1206    ) -> Result<Completion<Vec<Feature>>, Error> {
1207        let source_id = source_id_of(source_id)?;
1208        self.operation(move |worker, _| worker.renderer()?.query_source_features(&source_id, &options))
1209    }
1210
1211    /// The clusters and points that a cluster of a clustered GeoJSON source
1212    /// splits into at the next zoom level. `cluster_id` is a cluster
1213    /// feature's `cluster_id` property.
1214    ///
1215    /// The query reads the source as the session's most recent render
1216    /// attempt had it. A cluster ID belongs to one version of the source's
1217    /// data, so query the features again after the data changes.
1218    ///
1219    /// Completes with [`ErrorKind::NotFound`](mln_util::ErrorKind) when that
1220    /// render had no source `source_id`, or the source has no cluster
1221    /// `cluster_id`, and with [`ErrorKind::InvalidArgument`](mln_util::ErrorKind)
1222    /// when the source isn't a clustered GeoJSON source.
1223    pub fn cluster_children(
1224        &self,
1225        source_id: impl Into<String>,
1226        cluster_id: u32,
1227    ) -> Result<Completion<Vec<feature::Feature<f64>>>, Error> {
1228        let source_id = source_id_of(source_id)?;
1229        self.operation(move |worker, _| worker.cluster(&source_id, cluster_id, |_, children| Ok(children)))
1230    }
1231
1232    /// The points in a cluster of a clustered GeoJSON source: it skips the
1233    /// first `offset`, then holds up to `limit`. It fails as
1234    /// [`cluster_children`](Self::cluster_children) does.
1235    pub fn cluster_leaves(
1236        &self,
1237        source_id: impl Into<String>,
1238        cluster_id: u32,
1239        limit: u32,
1240        offset: u32,
1241    ) -> Result<Completion<Vec<feature::Feature<f64>>>, Error> {
1242        let source_id = source_id_of(source_id)?;
1243        self.operation(move |worker, _| {
1244            worker.cluster(&source_id, cluster_id, |index, _| index.get_leaves(cluster_id, limit, offset))
1245        })
1246    }
1247
1248    /// The zoom level at which a cluster of a clustered GeoJSON source splits
1249    /// into two or more clusters or points. It fails as
1250    /// [`cluster_children`](Self::cluster_children) does.
1251    pub fn cluster_expansion_zoom(
1252        &self,
1253        source_id: impl Into<String>,
1254        cluster_id: u32,
1255    ) -> Result<Completion<u8>, Error> {
1256        let source_id = source_id_of(source_id)?;
1257        self.operation(move |worker, _| {
1258            worker.cluster(&source_id, cluster_id, |index, _| index.get_cluster_expansion_zoom(cluster_id))
1259        })
1260    }
1261
1262    /// Detaches the session from its map and frees its graphics objects. The
1263    /// demands on their way finish as
1264    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once
1265    /// the detach completes, another session can attach to the map.
1266    pub fn detach(&self) -> Result<Completion<()>, Error> {
1267        let shared = self.shared();
1268        with_unlocked_wakes(|| {
1269            let mut state = shared.state.lock_unpoisoned();
1270            if !matches!(state.lifecycle, RenderSessionState::Failed) {
1271                check_usable(&state)?;
1272            } else if state.released {
1273                return Err(released());
1274            }
1275            if state.acquired_frames != 0 {
1276                return Err(Error::invalid_state("release every acquired frame before the session detaches"));
1277            }
1278            let (completion, resolver) = shared.completion();
1279            state.detach_waiters.push(resolver);
1280            shared.start_detach(&mut state);
1281            Ok(completion)
1282        })
1283    }
1284
1285    /// Stops the session at once, without its pending graphics work: that
1286    /// work completes with [`ErrorKind::TargetLost`](mln_util::ErrorKind)
1287    /// before this returns, and the demands on their way finish as
1288    /// [`FrameDisposition::TargetNotReady`](super::FrameDisposition). Once it
1289    /// returns, the session renders no more, and another session can attach
1290    /// to the map. Release the session afterward.
1291    ///
1292    /// A caller-driven session lets go of its graphics objects on the host's
1293    /// thread, at its next service or when its [`DriverWork`] drops.
1294    ///
1295    /// It waits for a frame that the session is rendering. Fails with
1296    /// [`ErrorKind::Busy`](mln_util::ErrorKind) on the session's own thread
1297    /// while that runs, and with [`ErrorKind::InvalidState`](mln_util::ErrorKind)
1298    /// once the session is detached, abandoned or released.
1299    pub fn abandon(&self) -> Result<(), Error> {
1300        self.shared().abandon(Abandoner::Host)
1301    }
1302
1303    /// Abandons the session as [`abandon`](Self::abandon) does, but makes no
1304    /// graphics call: the session keeps its graphics objects until the
1305    /// process exits. Returns how many it keeps, such as its renderer and
1306    /// the backend it draws with.
1307    ///
1308    /// This is for a host whose shutdown may already have destroyed the
1309    /// graphics objects behind the session.
1310    pub fn abandon_keeping_graphics(&self) -> Result<u32, Error> {
1311        with_unlocked_wakes(|| self.shared().abandon_locked(Abandoner::Host, true))
1312    }
1313
1314    /// Releases the session, detaching it first when it is attached. The
1315    /// completion reports when the session has let go of its map and its
1316    /// graphics objects. Every call on the session fails with
1317    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind) after.
1318    ///
1319    /// A caller-driven session detaches at the host's next service, so keep
1320    /// servicing it until the release completes. One that isn't attached,
1321    /// such as while it attaches or after it failed, is abandoned instead,
1322    /// and so is one whose map is released before that service.
1323    pub fn release(&self) -> Result<Completion<()>, Error> {
1324        {
1325            let state = self.shared().state.lock_unpoisoned();
1326            let live = matches!(state.lifecycle, RenderSessionState::Attaching | RenderSessionState::Attached);
1327            if live && !state.released && state.acquired_frames != 0 {
1328                return Err(Error::invalid_state("release every acquired frame before the session is released"));
1329            }
1330        }
1331        let (completion, resolver) = self.shared().completion();
1332        self.shared().dispose(Some(resolver))?;
1333        Ok(completion)
1334    }
1335
1336    /// Releases the session in any state, without waiting. Dropping the last
1337    /// handle does the same.
1338    pub fn dispose(&self) -> Result<(), Error> {
1339        self.shared().dispose(None)
1340    }
1341
1342    /// Releases the session in any state, without waiting and without a
1343    /// graphics call past the one in progress. A session that hasn't ended
1344    /// is abandoned, keeping its graphics objects until the process exits,
1345    /// as [`abandon_keeping_graphics`](Self::abandon_keeping_graphics) does.
1346    pub fn dispose_keeping_graphics(&self) -> Result<(), Error> {
1347        self.shared().dispose_keeping_graphics()
1348    }
1349}
1350
1351/// Counts a ring replacement or release on its way until it runs, or never
1352/// will.
1353struct RetargetGuard(Arc<SessionShared>);
1354
1355impl Drop for RetargetGuard {
1356    fn drop(&mut self) {
1357        let mut state = self.0.state.lock_unpoisoned();
1358        state.pending_retargets = state.pending_retargets.saturating_sub(1);
1359    }
1360}
1361
1362/// A frame of a borrowed ring that the host acquired, until it gives it
1363/// back. Dropping it gives it back as [`release`](Self::release) with
1364/// [`SyncKind::CpuComplete`] does.
1365pub struct AcquiredFrame {
1366    shared: Arc<SessionShared>,
1367    slot: usize,
1368    frame: Published,
1369    done: bool,
1370}
1371
1372impl std::fmt::Debug for AcquiredFrame {
1373    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1374        f.debug_struct("AcquiredFrame").field("slot", &self.slot).field("frame", &self.frame).finish_non_exhaustive()
1375    }
1376}
1377
1378impl AcquiredFrame {
1379    /// The index of the frame's texture in the ring.
1380    #[must_use]
1381    pub fn slot(&self) -> usize {
1382        self.slot
1383    }
1384
1385    /// The result of the demand that rendered the frame.
1386    #[must_use]
1387    pub fn result(&self) -> &FrameResult {
1388        &self.frame.result
1389    }
1390
1391    /// What to wait for before reading the frame's texture. The object it
1392    /// names is the session's, and stays valid until the frame is given
1393    /// back.
1394    #[must_use]
1395    pub fn producer_sync(&self) -> GpuSync {
1396        self.frame.sync
1397    }
1398
1399    /// The host's texture that holds the frame.
1400    #[must_use]
1401    pub fn texture(&self) -> Option<&FrameTexture> {
1402        self.frame.texture.as_ref()
1403    }
1404
1405    /// Whether [`release`](Self::release) takes a sync of `kind`.
1406    #[must_use]
1407    pub fn accepts(&self, kind: SyncKind) -> bool {
1408        self.shared.capabilities.consumer_sync_kinds.contains(kind)
1409    }
1410
1411    /// Opens a view of the frame, which keeps the frame's texture and sync
1412    /// objects in place until the view drops: an
1413    /// [`abandon`](RenderSession::abandon) fails while one is open, and a
1414    /// dispose of the session keeps them until the last view ends. Keep the
1415    /// frame until its views end.
1416    ///
1417    /// Fails with [`ErrorKind::TargetLost`](mln_util::ErrorKind) once the
1418    /// session can no longer render.
1419    pub fn view(&self) -> Result<FrameView, Error> {
1420        let mut state = self.shared.state.lock_unpoisoned();
1421        if !matches!(
1422            state.lifecycle,
1423            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1424        ) {
1425            return Err(Error::target_lost("the render session failed, or was detached, abandoned, or disposed"));
1426        }
1427        state.views += 1;
1428        Ok(FrameView { shared: self.shared.clone() })
1429    }
1430
1431    /// Whether the session can still render: the frame's objects stay valid
1432    /// until it ends.
1433    #[must_use]
1434    pub fn session_live(&self) -> bool {
1435        matches!(
1436            self.shared.state.lock_unpoisoned().lifecycle,
1437            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1438        )
1439    }
1440
1441    /// Gives the frame back once the host's reads of its texture reach
1442    /// `consumer`: the session waits for it before it renders into the
1443    /// texture again, and takes the sync file or GL fence that it names.
1444    ///
1445    /// Fails with [`ErrorKind::Unsupported`](mln_util::ErrorKind), handing
1446    /// back the frame and `consumer`, for a kind that the session's
1447    /// [`consumer_sync_kinds`](RenderSessionCapabilities::consumer_sync_kinds)
1448    /// lacks.
1449    #[allow(clippy::result_large_err)]
1450    pub fn release(mut self, consumer: ConsumerSync) -> Result<(), (AcquiredFrame, ConsumerSync, Error)> {
1451        if !self.shared.capabilities.consumer_sync_kinds.contains(consumer.sync.kind) {
1452            return Err((self, consumer, Error::unsupported("render backend does not support this gpu sync kind")));
1453        }
1454        self.done = true;
1455        give_back(&self.shared, self.slot, Some(consumer));
1456        Ok(())
1457    }
1458
1459    /// Gives the frame up without saying when the host's reads end: the
1460    /// session never renders into its texture again, even when
1461    /// [`set_ring`](RenderSession::set_ring) gives the ring the texture
1462    /// again, until a [`release_target`](RenderSession::release_target) of
1463    /// the ring.
1464    pub fn discard(mut self) {
1465        self.done = true;
1466        give_back(&self.shared, self.slot, None);
1467    }
1468}
1469
1470/// A view of an acquired frame, which [`AcquiredFrame::view`] opens, until
1471/// it drops.
1472pub struct FrameView {
1473    shared: Arc<SessionShared>,
1474}
1475
1476impl std::fmt::Debug for FrameView {
1477    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1478        f.debug_struct("FrameView").finish_non_exhaustive()
1479    }
1480}
1481
1482impl Drop for FrameView {
1483    fn drop(&mut self) {
1484        let release = {
1485            let mut state = self.shared.state.lock_unpoisoned();
1486            state.views = state.views.saturating_sub(1);
1487            state.views == 0 && std::mem::take(&mut state.viewed_teardown)
1488        };
1489        if release {
1490            worker::post(&self.shared.run_loop, |worker, _| worker.release_viewed());
1491        }
1492    }
1493}
1494
1495impl Drop for AcquiredFrame {
1496    fn drop(&mut self) {
1497        if !self.done {
1498            give_back(&self.shared, self.slot, Some(ConsumerSync::of(GpuSync::of(SyncKind::CpuComplete))));
1499        }
1500    }
1501}
1502
1503/// Gives the ring's `slot` back to the session, with the host's `consumer`
1504/// sync, or discarded without one.
1505fn give_back(shared: &Arc<SessionShared>, slot: usize, consumer: Option<ConsumerSync>) {
1506    with_unlocked_wakes(|| {
1507        let mut state = shared.state.lock_unpoisoned();
1508        state.acquired_frames = state.acquired_frames.saturating_sub(1);
1509        let live = matches!(
1510            state.lifecycle,
1511            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
1512        );
1513        if !live {
1514            if let Some(entry) = state.ring.get_mut(slot) {
1515                entry.acquired = false;
1516                // The host's GPU may still read a texture whose wait never
1517                // ran.
1518                entry.quarantined |=
1519                    consumer.as_ref().is_none_or(|consumer| consumer.sync.kind != SyncKind::CpuComplete);
1520            }
1521            // A sync file that no backend waits on closes with `consumer`.
1522            return;
1523        }
1524        if let Some(sync) = consumer {
1525            worker::post(&shared.run_loop, move |worker, outbox| worker.release_slot(slot, sync, outbox));
1526        } else {
1527            if let Some(entry) = state.ring.get_mut(slot) {
1528                entry.acquired = false;
1529                entry.quarantined = !entry.retired;
1530                entry.retired = false;
1531            }
1532            worker::post(&shared.run_loop, move |worker, outbox| worker.discard_slot(slot, outbox));
1533        }
1534    });
1535}
1536
1537fn source_id_of(source_id: impl Into<String>) -> Result<String, Error> {
1538    let source_id = source_id.into();
1539    if source_id.is_empty() {
1540        return Err(Error::invalid_argument("the source ID must not be empty"));
1541    }
1542    Ok(source_id)
1543}
1544
1545// Handles cross threads; the renderer never leaves its own.
1546const _: () = {
1547    const fn assert_send_sync<T: Send + Sync>() {}
1548    assert_send_sync::<RenderSession>();
1549};