scal-runtime 1.2.1

Runtime for SCAL- easy animation system focused on code.
//! GPU readback ring buffer.
//!
//! # Synchronization
//!
//! A fixed set of [`Slot`]s is allocated once during [`init_buffers`]. Each slot
//! contains a [`wgpu::Buffer`] with `MAP_READ` usage.
//!
//! # Why slots?
//!
//! Mapping a GPU buffer for reading is a synchronous operation that stalls the
//! GPU if the buffer is still in use. By rotating through N slots we can have
//! one slot being mapped/read by the CPU while the GPU writes into another.
//!
//! # Why mapping happens later
//!
//! Mapping is initiated in `copy_texture_to_buffer()` / `run_and_copy()` right
//! after the copy/compute commands are submitted. The call to
//! `device.poll(wgpu::PollType::WaitIndefinitely)` blocks until the map is
//! complete, ensuring the data is available before the frame is sent to the
//! encoder.
//!
//! # Why unmapping occurs when it does
//!
//! After reading the mapped range, [`unmap`] is called immediately so the
//! buffer becomes available for the next frame's copy operation. The buffer
//! index is then sent back through the free-slots channel.

use std::sync::OnceLock;

use anyhow::{Context, Result, bail};
use wgpu::*;

pub(crate) struct Slot {
    pub buffer: Buffer,
    pub id: usize,
}
pub(crate) static SLOTS: OnceLock<Vec<Slot>> = OnceLock::new();

pub(crate) fn init_buffers(slot_count: u32, size: usize, device: &wgpu::Device) -> Result<()> {
    if SLOTS
        .set(
            (0..slot_count)
                .map(|id| Slot {
                    id: id as usize,
                    buffer: device.create_buffer(&BufferDescriptor {
                        label: Some("readback"),

                        size: size as u64,

                        usage: BufferUsages::COPY_DST | BufferUsages::MAP_READ,

                        mapped_at_creation: false,
                    }),
                })
                .collect(),
        )
        .is_err()
    {
        bail!(
            "SLOTS were already initialized! they should be initialized only once to avoid any issues "
        )
    }
    Ok(())
}
pub(crate) struct ReadbackRing {
    free_slots: tokio::sync::mpsc::Receiver<usize>,
}

impl ReadbackRing {
    pub fn new(free_buffers: tokio::sync::mpsc::Receiver<usize>) -> Self {
        Self {
            free_slots: free_buffers,
        }
    }

    pub async fn next(&mut self) -> Result<&Slot> {
        let id = self
            .free_slots
            .recv()
            .await
            .context("free_buffers channel was closed")?;
        SLOTS
            .get()
            .context("SLOTS weren't yet initialized")?
            .get(id)
            .context("buffer index was out of bounds")
    }
}