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_builtins::sources::GeoJSONData;
use mln_engine::Renderer;
use mln_gfx::{ConsumerSync, GpuSync, SyncKind};
use mln_style::bitmap::PremultipliedImage;
use mln_style::error::Error;
use mln_style::size::Size;
use mln_style::source::SourceData;
use mln_style::sources::GeoJsonSourceType;

use super::frames::RingPick;
use super::{Worker, post, target_lost};
use crate::render::frame::FrameDisposition;
use crate::render::session::{Published, RenderSessionState, physical_size};
use crate::render::target::{BorrowedRing, Surface};
use crate::runtime::Outbox;

impl Worker {
    // MARK: - Borrowed rings

    /// Picks the ring's texture that the next frame renders into, and marks
    /// it as rendering: one that holds no frame, or else the one with the
    /// oldest frame that the host didn't acquire.
    pub(super) fn pick_slot(&self) -> RingPick {
        let mut state = self.shared.state.lock();
        if state.ring.is_empty() {
            return RingPick::None;
        }
        if state.ring.iter().all(|slot| slot.quarantined) {
            return RingPick::Quarantined;
        }
        let free = state.ring.iter().enumerate().filter(|(_, slot)| !slot.busy());
        let index = free
            .clone()
            .find(|(_, slot)| slot.frame.is_none())
            .or_else(|| {
                free.min_by_key(|(_, slot)| slot.frame.as_ref().map_or(0, |frame| frame.result.frame_generation))
            })
            .map(|(index, _)| index);
        let Some(index) = index else { return RingPick::Full };
        let slot = &mut state.ring[index];
        slot.rendering = true;
        slot.frame = None;
        RingPick::Slot(index)
    }

    /// Ends a frame rendered into the ring's `slot`, which then holds
    /// `published` for the host to acquire.
    pub(super) fn end_slot(&self, slot: usize, published: Option<Published>) {
        let mut state = self.shared.state.lock();
        if let Some(entry) = state.ring.get_mut(slot) {
            entry.rendering = false;
            entry.frame = published;
        }
    }

    /// The host gave the ring's `slot` back with its `consumer` sync: the
    /// next frame rendered into it waits for that. A sync the target can't
    /// wait for fails the session, and the slot is never rendered into
    /// again, since the host's GPU may still read it. A slot that comes back
    /// after the ring let go of its textures has nothing to wait in, so it
    /// is only quarantined, unless its reads are done.
    pub(crate) fn release_slot(&mut self, slot: usize, consumer: ConsumerSync, outbox: &mut Outbox) {
        let kind = consumer.sync.kind;
        let released = match self.gfx.as_mut() {
            Some(gfx) if gfx.target.ring_released() => {
                let mut state = self.shared.state.lock();
                if let Some(entry) = state.ring.get_mut(slot) {
                    entry.acquired = false;
                    entry.quarantined |= kind != SyncKind::CpuComplete;
                }
                drop(state);
                return self.pump(outbox);
            }
            Some(gfx) => gfx.target.release_slot(slot, consumer),
            None => Err(Error::target_lost("the render session lost its renderer")),
        };
        let failure = {
            let mut state = self.shared.state.lock();
            if let Some(entry) = state.ring.get_mut(slot) {
                entry.acquired = false;
                entry.quarantined |= released.is_err() && kind != SyncKind::CpuComplete && !entry.retired;
                entry.retired = false;
            }
            match &released {
                Err(error) if self.gfx.is_some() && state.lifecycle == RenderSessionState::Attached => {
                    state.lifecycle = RenderSessionState::Failed;
                    state.failure = Some(error.clone());
                    true
                }
                _ => false,
            }
        };
        if failure {
            self.end_demands(FrameDisposition::Failed, outbox);
            self.drop_gfx();
            return self.run_queued(outbox);
        }
        self.pump(outbox);
    }

    /// The host gave up the ring's `slot`, which the session quarantined.
    pub(crate) fn discard_slot(&mut self, slot: usize, outbox: &mut Outbox) {
        if let Some(gfx) = self.gfx.as_mut() {
            let _ = gfx.target.discard_slot(slot);
        }
        self.pump(outbox);
    }

    /// Renders into `ring` from now on, at `size` logical pixels, after the
    /// map resized. The ring's slots then hold no frames, and only the
    /// textures that were quarantined stay so.
    pub(crate) fn set_ring(
        &mut self,
        size: Size,
        scale_factor: f64,
        ring: &BorrowedRing,
        outbox: &mut Outbox,
    ) -> Result<GpuSync, Error> {
        self.set_scale_factor(scale_factor)?;
        let same_size = self.size() == size;
        let gfx = self.gfx.as_mut().ok_or_else(target_lost)?;
        // The ring it has already: nothing changes, and the frames it holds
        // stay.
        if self.ring.as_ref() == Some(ring) && !gfx.target.ring_released() && same_size {
            // The demands that wait keep waiting for an update past the
            // replacement's resize.
            let latest = self.latest_generation();
            for (_, seen) in &mut self.waiting {
                *seen = latest;
            }
            return Ok(GpuSync::of(SyncKind::CpuComplete));
        }
        let sync = gfx.target.set_ring(ring.clone())?;
        let old = self.ring.replace(ring.clone());
        {
            let mut state = self.shared.state.lock();
            // The host's GPU may still read a texture it gave up, wherever it
            // is in the new ring.
            let quarantined: Vec<bool> = (0..state.ring.len())
                .map(|slot| {
                    old.as_ref().is_some_and(|old| {
                        state
                            .ring
                            .iter()
                            .enumerate()
                            .any(|(old_slot, entry)| entry.quarantined && ring.same_texture(slot, old, old_slot))
                    })
                })
                .collect();
            for (entry, quarantined) in state.ring.iter_mut().zip(quarantined) {
                entry.frame = None;
                entry.quarantined = quarantined;
            }
        }
        self.target_changed(size, Some(true));
        self.wake_for_redraw(outbox);
        // The demands that wait for an update find a new target, which they
        // render to.
        let waiting: Vec<_> = self.waiting.drain(..).map(|(pending, _)| pending).collect();
        self.parked.extend(waiting);
        self.pump(outbox);
        // A still image that waits for a target gets its demand again, once
        // the replacement no longer counts as on its way.
        post(&self.shared.queue, Worker::still_image_changed);
        Ok(sync)
    }

    // MARK: - Target and renderer operations

    /// The target's size in logical pixels.
    pub(crate) fn size(&self) -> Size {
        self.shared.state.lock().size
    }

    pub(crate) fn renderer(&mut self) -> Result<&mut Renderer, Error> {
        self.gfx.as_mut().and_then(|gfx| gfx.target.renderer_mut()).ok_or_else(target_lost)
    }

    /// Resizes the target, and draws at `scale_factor`, after the map
    /// resized.
    pub(crate) fn resize(&mut self, size: Size, scale_factor: f64, outbox: &mut Outbox) -> Result<(), Error> {
        let physical = physical_size(size, scale_factor)?;
        self.set_scale_factor(scale_factor)?;
        let gfx = self.gfx.as_mut().ok_or_else(target_lost)?;
        match gfx.target.exported_size() {
            // An exported ring whose images have the size already keeps
            // them, with the frames they hold and the slots quarantined.
            Some(current) if current == physical => {}
            Some(_) => {
                // The frames that the host holds keep their images, and every
                // slot gets a new one. The frames it didn't acquire go first,
                // in the same step as the snapshot, so that none is acquired
                // with an image that the resize lets go of.
                let held: Vec<usize> = {
                    let mut state = self.shared.state.lock();
                    for slot in state.ring.iter_mut().filter(|slot| !slot.acquired) {
                        slot.frame = None;
                    }
                    state.ring.iter().enumerate().filter(|(_, slot)| slot.acquired).map(|(index, _)| index).collect()
                };
                let resized = { gfx.target.resize_exported(physical, &held) };
                match resized {
                    // Each slot has an image that never reached the host: a
                    // slot that the host gave up is free, and one it holds
                    // has its old image retired.
                    Ok(true) => {
                        let mut state = self.shared.state.lock();
                        for slot in &mut state.ring {
                            if slot.acquired {
                                slot.retired = true;
                            } else {
                                slot.quarantined = false;
                            }
                        }
                    }
                    Ok(false) => {}
                    // The map has the new size already, which the old images
                    // can't show.
                    Err(error) => {
                        self.fail(error.clone(), outbox);
                        return Err(error);
                    }
                }
            }
            None => gfx.target.resize(physical),
        }
        self.target_changed(size, None);
        Ok(())
    }

    /// Draws at `scale_factor` from the next frame on, which the map took
    /// too: the renderer lays out the tiles it has again.
    fn set_scale_factor(&mut self, scale_factor: f64) -> Result<(), Error> {
        if scale_factor != self.scale_factor {
            self.renderer()?.set_pixel_ratio(scale_factor as f32);
            self.scale_factor = scale_factor;
        }
        Ok(())
    }

    /// The target changed to `size`, and has a surface again when
    /// `has_target` says so.
    fn target_changed(&mut self, size: Size, has_target: Option<bool>) {
        self.has_frame = false;
        let mut state = self.shared.state.lock();
        state.size = size;
        state.scale_factor = self.scale_factor;
        state.generation += 1;
        if let Some(has_target) = has_target {
            state.has_target = has_target;
        }
    }

    /// Lets go of a surface session's surface, or of a ring's textures, and
    /// ends the demands on their way. Returns, for a ring, the sync after
    /// which the host may use or destroy the textures, so a new ring keeps
    /// nothing of the old one: no texture of it stays quarantined.
    pub(crate) fn release_target(&mut self, outbox: &mut Outbox) -> Result<Option<GpuSync>, Error> {
        let gfx = self.gfx.as_mut().ok_or_else(target_lost)?;
        let sync = gfx.target.release_surface()?;
        self.has_frame = false;
        self.ring = None;
        {
            let mut state = self.shared.state.lock();
            state.has_target = false;
            for slot in &mut state.ring {
                slot.frame = None;
                slot.quarantined = false;
            }
        }
        self.end_demands(FrameDisposition::TargetNotReady, outbox);
        Ok(sync)
    }

    /// Presents to `surface` from now on, at `size` logical pixels, after
    /// the map resized. On failure the session keeps the surface that it
    /// had, if any, at the new size.
    pub(crate) fn set_surface(
        &mut self,
        size: Size,
        scale_factor: f64,
        surface: Surface,
        outbox: &mut Outbox,
    ) -> Result<(), Error> {
        let target = &self.gfx.as_ref().ok_or_else(target_lost)?.target;
        if target.is_offscreen() || target.is_borrowed() {
            return Err(Error::unsupported("only a surface session presents to another surface"));
        }
        let physical = physical_size(size, scale_factor)?;
        self.set_scale_factor(scale_factor)?;
        let gfx = self.gfx.as_mut().ok_or_else(target_lost)?;
        let tile_cache_enabled = gfx.target.renderer().is_some_and(Renderer::tile_cache_enabled);
        let replaced = gfx.target.set_surface(surface, self.overlay.take(), physical);
        match replaced {
            // The old backend's renderer went with it: one on the new
            // backend draws what the session set.
            Ok(true) => gfx.make_renderer(&self.renderer_events, scale_factor as f32, tile_cache_enabled),
            Ok(false) => {}
            Err(_) => gfx.target.resize(physical),
        }
        let replaced = replaced.map(drop);
        self.target_changed(size, replaced.is_ok().then_some(true));
        if replaced.is_ok() {
            self.wake_for_redraw(outbox);
            // A still image that waits for a target gets its demand again.
            post(&self.shared.queue, Worker::still_image_changed);
        }
        replaced
    }

    pub(crate) fn reduce_memory_use(&mut self) -> Result<(), Error> {
        let gfx = self.gfx.as_mut().ok_or_else(target_lost)?;
        gfx.target.with_renderer(|renderer, gpu| renderer.reduce_memory_use(gpu)).ok_or_else(target_lost)
    }

    pub(crate) fn clear_data(&mut self, outbox: &mut Outbox) -> Result<(), Error> {
        let gfx = self.gfx.as_mut().ok_or_else(target_lost)?;
        gfx.target.with_renderer(|renderer, gpu| renderer.clear_data(gpu)).ok_or_else(target_lost)?;
        self.rendered_update = 0;
        // The renderer loads what the image needs again, once it tries.
        if let Some(still) = self.still.as_mut() {
            still.tried = None;
            post(&self.shared.queue, Worker::still_image_changed);
        }
        self.wake_for_redraw(outbox);
        Ok(())
    }

    pub(crate) fn dump_debug_logs(&mut self) -> Result<(), Error> {
        self.renderer()?.dump_debug_logs();
        Ok(())
    }

    /// Runs `f` on the target's `Gpu`.
    #[cfg(feature = "bench")]
    pub(crate) fn with_gpu(&mut self, f: impl FnMut(&mut dyn mln_gfx::gpu::Gpu)) -> Result<(), Error> {
        self.gfx.as_mut().ok_or_else(target_lost)?.target.with_gpu(f);
        Ok(())
    }

    pub(crate) fn read_texture(&mut self) -> Result<PremultipliedImage, Error> {
        let gfx = self.gfx.as_mut().ok_or_else(target_lost)?;
        if !gfx.target.is_offscreen() {
            return Err(Error::unsupported("a surface session can't read its frames back"));
        }
        if !self.has_frame {
            return Err(Error::invalid_state("the render session has no rendered frame since it attached or resized"));
        }
        gfx.target.read_image()
    }

    /// Runs `read` on the data of the clustered GeoJSON source `source_id`
    /// of the last render, with the children of its cluster `cluster_id`.
    pub(crate) fn cluster<T>(
        &mut self,
        source_id: &str,
        cluster_id: u32,
        read: impl FnOnce(&dyn GeoJSONData, Vec<mln_style::feature::Feature<f64>>) -> Result<T, Error>,
    ) -> Result<T, Error> {
        // A cluster's ID holds its zoom plus one in its low five bits, so an
        // ID without them names no cluster, though it would find the points
        // at zoom 0 as children. An index of no points has no clusters.
        const ZOOM_BITS: u32 = 0x1F;

        self.renderer()?;
        let source =
            self.sources.as_ref().and_then(|sources| sources.get(source_id)).ok_or_else(|| {
                Error::not_found(format!("the session's last render has no source named {source_id}"))
            })?;
        let geojson = SourceData::<GeoJsonSourceType>::recover(source)
            .ok_or_else(|| Error::invalid_argument(format!("source {source_id} is not a GeoJSON source")))?;
        if !geojson.options.options.cluster {
            return Err(Error::invalid_argument(format!("GeoJSON source {source_id} does not cluster")));
        }
        let data = geojson.description::<Arc<dyn GeoJSONData>>().cloned();
        let children = data
            .as_ref()
            .filter(|_| cluster_id & ZOOM_BITS != 0)
            .and_then(|data| data.children(cluster_id).ok())
            .filter(|children| !children.is_empty());
        match (data, children) {
            (Some(data), Some(children)) => read(&*data, children),
            _ => Err(Error::not_found(format!("the source has no cluster with ID {cluster_id}"))),
        }
    }
}