mln-rs-runtime 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
#[cfg(target_family = "wasm")]
use std::cell::Cell;
use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::thread::ThreadId;

use mln_engine::exec::thread::Joined;
use mln_style::error::Error;
use parking_lot::Mutex;

use super::shared::{RingSlot, SessionId, SessionShared, SessionState, wake_unlocked, with_unlocked_wakes};
use super::{RenderSession, RenderSessionCapabilities, RenderSessionState, SessionHandle};
use crate::completion::Completion;
use crate::map::Map;
use crate::render::target::{AttachOptions, Device, Driver, RenderTarget, SentSurface, SyncKinds};
use crate::render::worker::{self, Init, SessionQueue, TargetInit};

/// Attaches a session to `map`, as [`Map::attach`] documents, and runs `then`
/// with the session and the attach's completion before the session's thread
/// may deliver that, as [`Map::attach_then`] documents.
pub(crate) fn attach<R>(
    map: &Map,
    target: RenderTarget,
    options: AttachOptions,
    then: impl FnOnce(&RenderSession, Completion<()>) -> R,
) -> Result<R, Error> {
    // The wakes that the attach runs, such as a caller-driven session's
    // driver-work wake, wait for the release of the session's sending lock,
    // so a host's wake that services the session can't wait for it.
    with_unlocked_wakes(|| attach_unlocked(map, target, options, then))
}

fn attach_unlocked<R>(
    map: &Map,
    target: RenderTarget,
    options: AttachOptions,
    then: impl FnOnce(&RenderSession, Completion<()>) -> R,
) -> Result<R, Error> {
    static NEXT_ID: AtomicU64 = AtomicU64::new(1);
    let id = SessionId(NEXT_ID.fetch_add(1, Ordering::Relaxed));
    let mut ring = None;
    let mut export_kind = None;
    let (size, target) = match target {
        RenderTarget::Offscreen { size, device } => (size, TargetInit::Offscreen(device)),
        RenderTarget::Surface { size, surface, device } => {
            if device.is_none() && !surface.needs_no_device() {
                return Err(Error::invalid_argument("a surface that the host made needs the host's device"));
            }
            surface.check_area()?;
            surface.check_pixel_format(device.as_ref())?;
            (size, TargetInit::Surface { surface: SentSurface::new(surface, id), device })
        }
        RenderTarget::Borrowed { size, ring: borrowed, device } => {
            let (producer, consumer) = device.borrowed_sync_kinds(&borrowed)?;
            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
                Error::unsupported("render target supports none of the requested producer sync kinds")
            })?;
            if borrowed.depth() == 0 || borrowed.physical_size().is_empty() {
                return Err(Error::invalid_argument("a borrowed ring needs textures of a size"));
            }
            ring = Some((borrowed.depth(), picked, consumer));
            (size, TargetInit::Borrowed { ring: borrowed, device, producer: picked })
        }
        RenderTarget::Exported { size, ring: exported, device } => {
            if exported.depth == 0 {
                return Err(Error::invalid_argument("an exported ring needs at least one image"));
            }
            if exported.kinds.is_empty() {
                return Err(Error::invalid_argument("an exported ring needs a kind of image to share"));
            }
            if size.is_empty() {
                return Err(Error::invalid_argument("the target's size must not be empty"));
            }
            let device = match device {
                Some(device) => device,
                None => Device::for_exported_ring(&exported)?,
            };
            let (kind, producer, consumer) = device.export_plan(&exported)?;
            let picked = options.producer_sync_kinds.pick(producer).ok_or_else(|| {
                Error::unsupported("render target supports none of the requested producer sync kinds")
            })?;
            ring = Some((exported.depth, picked, consumer));
            export_kind = Some(kind);
            (size, TargetInit::Exported { ring: exported, device, kind, producer: picked })
        }
    };
    if size.is_empty() {
        return Err(Error::invalid_argument("the target's size must not be empty"));
    }
    let (target, lease) = target.lease();
    let presentation = matches!(target, TargetInit::Surface { .. });
    let queue = SessionQueue::default();
    let driver_armed = Arc::new(AtomicBool::new(true));
    if options.driver == Driver::CallerThread
        && let Some(wake) = options.driver_work_wake
    {
        let armed = Arc::clone(&driver_armed);
        queue.set_waker(Some(Arc::new(move || {
            if armed.swap(false, Ordering::SeqCst) {
                wake_unlocked(&wake);
            }
        })));
    }
    let scale_factor = map.scale_factor();
    let shared = Arc::new(SessionShared {
        id,
        driver: options.driver,
        queue: queue.clone(),
        thread: Arc::default(),
        runtime_thread: map.runtime_thread(),
        state: Mutex::new(SessionState {
            lifecycle: RenderSessionState::Attaching,
            released: false,
            size,
            scale_factor,
            sent_scale_factor: scale_factor,
            generation: 1,
            frame_generation: 0,
            failure: None,
            has_target: true,
            results: Vec::new(),
            frame_woken: false,
            redraw_armed: true,
            pending_demands: 0,
            pacing: None,
            attach: None,
            detach_waiters: Vec::new(),
            release_waiters: Vec::new(),
            pending: BTreeMap::new(),
            next_work: 0,
            map: Some(map.clone()),
            init: Some(Box::new(Init {
                target,
                size,
                scale_factor,
                glyph_cache: map.glyph_cache(),
                font_face_engine: map.font_face_engine(),
                registry: Arc::clone(map.registry()),
                tile_cache_enabled: map.tile_cache_enabled(),
                tile_worker_instances: map.tile_worker_instances(),
                local_glyphs: map.local_glyphs(),
                failure: None,
                pool: map.pool(),
            })),
            resizes_sent: 0,
            graphics_objects: 0,
            keep_graphics: false,
            abandon_keeps_graphics: false,
            ring: vec![RingSlot::default(); ring.map_or(0, |(depth, _, _)| depth)],
            acquired_frames: 0,
            pending_retargets: 0,
            views: 0,
            viewed_teardown: false,
        }),
        gate: Mutex::new(()),
        lease,
        frame_wake: options.frame_wake,
        redraw_wake: options.redraw_wake,
        capabilities: RenderSessionCapabilities {
            driver: options.driver,
            texture_ring_depth: ring.map_or(1, |(depth, _, _)| depth as u32),
            frame_acquisition: ring.is_some(),
            readback: !presentation && ring.is_none(),
            presentation,
            producer_sync_kind: ring.map(|(_, producer, _)| producer),
            consumer_sync_kinds: ring.map_or(SyncKinds::NONE, |(_, _, consumer)| consumer),
            export_kind,
        },
        driver_work_taken: AtomicBool::new(false),
        driver_armed,
        awaited_command: Arc::new(AtomicU64::new(u64::MAX)),
        preparing: AtomicBool::new(false),
        in_call: AtomicBool::new(false),
        sending: Mutex::new(()),
    });
    let (completion, resolver) = shared.completion();
    shared.state.lock().attach = Some(resolver);
    // Held until `then` returns: the session's thread delivers the attach's
    // result after, inside its driver call.
    let sending = Arc::clone(&shared);
    let held = sending.hold_sending();
    map.claim_session(id, Arc::downgrade(&shared))?;
    let mut thread_end = None;
    if options.driver == Driver::CoreWorker {
        match start_thread(Arc::clone(&shared)) {
            Ok((thread, end)) => {
                let _ = shared.thread.set(thread);
                thread_end = end.map(Arc::new);
            }
            Err(error) => {
                map.release_session_claim(id);
                return Err(error);
            }
        }
    }
    let session = RenderSession { handle: Arc::new(SessionHandle { shared, thread_end }) };
    if let Err(error) = map.bind_session(id, queue, Arc::clone(&session.shared().awaited_command), size) {
        // The map was released meanwhile: the session lets go of it. Its
        // drop waits for its thread, which waits for the sending lock.
        drop(held);
        drop(session);
        return Err(error);
    }
    if options.driver == Driver::CallerThread {
        #[cfg(target_family = "wasm")]
        prepare_caller_driven(session.shared());
        // The first service builds the renderer, which is work that is ready
        // now: this wakes the host, unless the map's first update, posted
        // from the runtime's thread, woke it already.
        session.shared().queue.wake();
    }
    let attached = then(&session, completion);
    // Before the session, whose drop may wait for its thread, which waits
    // for the sending lock.
    drop(held);
    Ok(attached)
}

/// Starts a core worker's thread, which builds the session's renderer, then
/// runs the session's queue until the session ends.
#[cfg(not(target_family = "wasm"))]
fn start_thread(shared: Arc<SessionShared>) -> Result<(ThreadId, Option<Joined>), Error> {
    let thread = mln_engine::exec::thread::spawn("RenderSession", move || {
        let queue = shared.queue.clone();
        let mut worker = None;
        worker::build(&shared, &mut worker, &mut None);
        // The worker holds the session from here on.
        drop(shared);
        queue.run(&mut worker);
        // The session's work that comes from now on drops at once, so tasks
        // that hold the queue can't keep it alive.
        queue.close();
        drop(worker);
    })
    .map_err(|error| Error::failed(format!("can't start the render session's thread: {error}")))?;
    let thread_id = thread.thread().id();
    // The thread ends by itself once the session ends.
    Ok((thread_id, Some(Joined::new(thread))))
}

/// Runs a core worker on this thread, the browser's one, in the instance's
/// pump: it builds the session's renderer once its device is ready, which
/// may take the browser's WebGPU a while, then runs the session's queue until
/// the session ends.
#[cfg(target_family = "wasm")]
#[expect(clippy::unnecessary_wraps, reason = "the threads of other builds can fail to start")]
fn start_thread(shared: Arc<SessionShared>) -> Result<(ThreadId, Option<Joined>), Error> {
    let prepared = worker::prepare(&shared);
    wasm_bindgen_futures::spawn_local(async move {
        prepared.await;
        let queue = shared.queue.clone();
        let mut worker = None;
        worker::build(&shared, &mut worker, &mut None);
        let id = shared.id;
        // The worker holds the session from here on.
        drop(shared);
        let worker = Cell::new(worker);
        crate::web::drive_session(id, queue.clone(), move || {
            let mut current = worker.take();
            queue.run_once(&mut current);
            if queue.is_stopped() {
                queue.close();
                drop(current);
            } else {
                worker.set(current);
            }
        });
    });
    Ok((std::thread::current().id(), None))
}

/// In the browser, asks for the device that a caller-driven session's build
/// needs, as a core worker does before it builds, and wakes the host to
/// service the session once the device is there.
#[cfg(target_family = "wasm")]
fn prepare_caller_driven(shared: &Arc<SessionShared>) {
    shared.preparing.store(true, Ordering::SeqCst);
    let prepared = worker::prepare(shared);
    let shared = Arc::downgrade(shared);
    wasm_bindgen_futures::spawn_local(async move {
        prepared.await;
        if let Some(shared) = shared.upgrade() {
            shared.preparing.store(false, Ordering::SeqCst);
            shared.queue.wake();
        }
    });
}