mln-rs-runtime 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::sync::Arc;

use mln_style::error::Error;

use super::shared::{Published, SessionShared, with_unlocked_wakes};
use super::{RenderSessionState, ThreadEnd};
use crate::render::frame::FrameResult;
use crate::render::target::{ConsumerSync, FrameTexture, GpuSync, SyncKind};
use crate::render::worker;

/// A frame of a borrowed ring that the host acquired, until it gives it
/// back. Dropping it gives it back as [`release`](Self::release) with
/// [`SyncKind::CpuComplete`] does.
pub struct AcquiredFrame {
    pub(super) shared: Arc<SessionShared>,
    /// Dropped after the frame is given back.
    pub(super) thread_end: ThreadEnd,
    pub(super) slot: usize,
    pub(super) frame: Published,
    pub(super) done: bool,
}

impl std::fmt::Debug for AcquiredFrame {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AcquiredFrame").field("slot", &self.slot).field("frame", &self.frame).finish_non_exhaustive()
    }
}

impl AcquiredFrame {
    /// The index of the frame's texture in the ring.
    #[must_use]
    pub fn slot(&self) -> usize {
        self.slot
    }

    /// The result of the demand that rendered the frame.
    #[must_use]
    pub fn result(&self) -> &FrameResult {
        &self.frame.result
    }

    /// What to wait for before reading the frame's texture. The object it
    /// names is the session's, and stays valid until the frame is given
    /// back.
    #[must_use]
    pub fn producer_sync(&self) -> GpuSync {
        self.frame.sync
    }

    /// The host's texture that holds the frame.
    #[must_use]
    pub fn texture(&self) -> Option<&FrameTexture> {
        self.frame.texture.as_ref()
    }

    /// Whether [`release`](Self::release) takes a sync of `kind`.
    #[must_use]
    pub fn accepts(&self, kind: SyncKind) -> bool {
        self.shared.capabilities.consumer_sync_kinds.contains(kind)
    }

    /// Opens a view of the frame, which keeps the frame's texture and sync
    /// objects in place until the view drops: an
    /// [`abandon`](super::RenderSession::abandon) fails while one is open, and a
    /// dispose of the session keeps them until the last view ends. Keep the
    /// frame until its views end.
    ///
    /// Fails with [`ErrorKind::TargetLost`](mln_style::error::ErrorKind) once the
    /// session can no longer render.
    pub fn view(&self) -> Result<FrameView, Error> {
        let mut state = self.shared.state.lock();
        if !matches!(
            state.lifecycle,
            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
        ) {
            return Err(Error::target_lost("the render session failed, or was detached, abandoned, or disposed"));
        }
        state.views += 1;
        Ok(FrameView { shared: Arc::clone(&self.shared), _thread_end: self.thread_end.clone() })
    }

    /// Whether the session can still render: the frame's objects stay valid
    /// until it ends.
    #[must_use]
    pub fn session_live(&self) -> bool {
        matches!(
            self.shared.state.lock().lifecycle,
            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
        )
    }

    /// Gives the frame back once the host's reads of its texture reach
    /// `consumer`: the session waits for it before it renders into the
    /// texture again, and takes the sync file or GL fence that it names.
    ///
    /// Fails with [`ErrorKind::Unsupported`](mln_style::error::ErrorKind), handing
    /// back the frame and `consumer`, for a kind that the session's
    /// [`consumer_sync_kinds`](super::RenderSessionCapabilities::consumer_sync_kinds)
    /// lacks.
    #[expect(
        clippy::result_large_err,
        reason = "the error hands back the frame and the consumer's sync, so that the caller can release it another way"
    )]
    pub fn release(mut self, consumer: ConsumerSync) -> Result<(), (AcquiredFrame, ConsumerSync, Error)> {
        if !self.shared.capabilities.consumer_sync_kinds.contains(consumer.sync.kind) {
            return Err((self, consumer, Error::unsupported("render backend does not support this gpu sync kind")));
        }
        self.done = true;
        give_back(&self.shared, self.slot, Some(consumer));
        Ok(())
    }

    /// Gives the frame up without saying when the host's reads end: the
    /// session never renders into its texture again, even when
    /// [`set_ring`](super::RenderSession::set_ring) gives the ring the texture
    /// again, until a [`release_target`](super::RenderSession::release_target) of
    /// the ring.
    pub fn discard(mut self) {
        self.done = true;
        give_back(&self.shared, self.slot, None);
    }
}

/// A view of an acquired frame, which [`AcquiredFrame::view`] opens, until
/// it drops.
pub struct FrameView {
    shared: Arc<SessionShared>,
    /// Dropped after the view ends.
    _thread_end: ThreadEnd,
}

impl std::fmt::Debug for FrameView {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FrameView").finish_non_exhaustive()
    }
}

impl Drop for FrameView {
    fn drop(&mut self) {
        let release = {
            let mut state = self.shared.state.lock();
            state.views = state.views.saturating_sub(1);
            state.views == 0 && std::mem::take(&mut state.viewed_teardown)
        };
        if release {
            worker::post(&self.shared.queue, |worker, _| worker.release_viewed());
        }
    }
}

impl Drop for AcquiredFrame {
    fn drop(&mut self) {
        if !self.done {
            give_back(&self.shared, self.slot, Some(ConsumerSync::of(GpuSync::of(SyncKind::CpuComplete))));
        }
    }
}

/// Gives the ring's `slot` back to the session, with the host's `consumer`
/// sync, or discarded without one.
fn give_back(shared: &Arc<SessionShared>, slot: usize, consumer: Option<ConsumerSync>) {
    with_unlocked_wakes(|| {
        let mut state = shared.state.lock();
        state.acquired_frames = state.acquired_frames.saturating_sub(1);
        let live = matches!(
            state.lifecycle,
            RenderSessionState::Attaching | RenderSessionState::Attached | RenderSessionState::Detaching
        );
        if !live {
            if let Some(entry) = state.ring.get_mut(slot) {
                entry.acquired = false;
                // The host's GPU may still read a texture whose wait never
                // ran.
                entry.quarantined |=
                    consumer.as_ref().is_none_or(|consumer| consumer.sync.kind != SyncKind::CpuComplete);
            }
            // A sync file that no backend waits on closes with `consumer`.
            return;
        }
        if let Some(sync) = consumer {
            worker::post(&shared.queue, move |worker, outbox| worker.release_slot(slot, sync, outbox));
        } else {
            if let Some(entry) = state.ring.get_mut(slot) {
                entry.acquired = false;
                entry.quarantined = !entry.retired;
                entry.retired = false;
            }
            worker::post(&shared.queue, move |worker, outbox| worker.discard_slot(slot, outbox));
        }
    });
}