Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

7.2 KB
Raw Blame
//! Per-page GPU objects, addressed from JS by integer ids.
//!
//! Ids are `index | generation << INDEX_BITS`: slots are reused, and a stale id (an object the
//! page dropped whose slot now holds something else) fails the generation check instead of
//! aliasing the new object.
use std::ops::Range;

pub const INDEX_BITS: u32 = 22;
const INDEX_MASK: u32 = (1 << INDEX_BITS) - 1;
const GEN_MASK: u32 = (1 << (32 - INDEX_BITS)) - 1;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MapState {
    Unmapped,
    Pending,
    Mapped,
}

pub struct BufferRes {
    pub buf: wgpu::Buffer,
    pub size: u64,
    pub usage: wgpu::BufferUsages,
    pub map: MapState,
    /// mapped range and whether it is writable (MAP_WRITE or mappedAtCreation)
    pub map_range: Range<u64>,
    pub map_write: bool,
    /// token of the pending/current mapAsync (late callbacks of aborted maps are ignored)
    pub map_token: f64,
    pub destroyed: bool,
}

pub struct TextureRes {
    pub tex: wgpu::Texture,
    pub format: wgpu::TextureFormat,
    pub size: wgpu::Extent3d,
    pub mips: u32,
    pub samples: u32,
    pub dimension: wgpu::TextureDimension,
    pub usage: wgpu::TextureUsages,
    /// a canvas texture: cleared lazily on first use in a frame
    pub canvas: bool,
}

pub struct ViewRes {
    pub view: wgpu::TextureView,
    /// id of the texture (for canvas lazy clears)
    pub texture: u32,
}

pub struct ShaderRes {
    pub module: wgpu::ShaderModule,
}

pub struct QuerySetRes {
    pub set: wgpu::QuerySet,
    pub ty: wgpu::QueryType,
    pub count: u32,
}

pub enum Res {
    Buffer(BufferRes),
    Texture(TextureRes),
    View(ViewRes),
    Sampler(wgpu::Sampler),
    BindGroupLayout(wgpu::BindGroupLayout),
    PipelineLayout(wgpu::PipelineLayout),
    BindGroup(wgpu::BindGroup),
    Shader(ShaderRes),
    RenderPipeline(wgpu::RenderPipeline),
    ComputePipeline(wgpu::ComputePipeline),
    QuerySet(QuerySetRes),
    /// `None` once submitted (a command buffer can be submitted once) or when encoding failed
    /// the recorded command stream, replayed into the frame's encoder at submit (`None`: invalid or submitted)
    CommandBuffer(Option<Vec<u32>>),
}

impl Res {
    pub fn kind(&self) -> &'static str {
        match self {
            Res::Buffer(_) => "GPUBuffer",
            Res::Texture(_) => "GPUTexture",
            Res::View(_) => "GPUTextureView",
            Res::Sampler(_) => "GPUSampler",
            Res::BindGroupLayout(_) => "GPUBindGroupLayout",
            Res::PipelineLayout(_) => "GPUPipelineLayout",
            Res::BindGroup(_) => "GPUBindGroup",
            Res::Shader(_) => "GPUShaderModule",
            Res::RenderPipeline(_) => "GPURenderPipeline",
            Res::ComputePipeline(_) => "GPUComputePipeline",
            Res::QuerySet(_) => "GPUQuerySet",
            Res::CommandBuffer(_) => "GPUCommandBuffer",
        }
    }
}

struct Slot {
    generation: u32,
    res: Option<Res>,
}

#[derive(Default)]
pub struct Slab {
    slots: Vec<Slot>,
    free: Vec<u32>,
    pub live: usize,
}

macro_rules! getter {
    ($name:ident, $variant:ident, $ty:ty) => {
        pub fn $name(&self, id: u32) -> Result<&$ty, String> {
            match self.get(id) {
                Some(Res::$variant(x)) => Ok(x),
                Some(other) => Err(format!("object {id} is a {}, expected {}", other.kind(), stringify!($variant))),
                None => Err(format!("invalid or destroyed object id {id} (expected {})", stringify!($variant))),
            }
        }
    };
}

impl Slab {
    pub fn insert(&mut self, res: Res) -> u32 {
        self.live += 1;
        if let Some(index) = self.free.pop() {
            let slot = &mut self.slots[index as usize];
            slot.res = Some(res);
            return index | (slot.generation << INDEX_BITS);
        }
        // index 0 is never handed out, so 0 can mean "none" in the command stream
        if self.slots.is_empty() {
            self.slots.push(Slot { generation: 0, res: None });
        }
        let index = self.slots.len() as u32;
        if index > INDEX_MASK {
            // 4M live objects: the page leaks; hand out the "none" id (uses fail validation)
            self.live -= 1;
            return 0;
        }
        self.slots.push(Slot { generation: 0, res: Some(res) });
        index
    }

    fn slot(&self, id: u32) -> Option<&Slot> {
        let slot = self.slots.get((id & INDEX_MASK) as usize)?;
        if slot.generation != id >> INDEX_BITS {
            return None;
        }
        Some(slot)
    }

    #[inline]
    pub fn get(&self, id: u32) -> Option<&Res> {
        self.slot(id)?.res.as_ref()
    }

    pub fn get_mut(&mut self, id: u32) -> Option<&mut Res> {
        let slot = self.slots.get_mut((id & INDEX_MASK) as usize)?;
        if slot.generation != id >> INDEX_BITS {
            return None;
        }
        slot.res.as_mut()
    }

    pub fn remove(&mut self, id: u32) -> Option<Res> {
        let index = id & INDEX_MASK;
        let slot = self.slots.get_mut(index as usize)?;
        if slot.generation != id >> INDEX_BITS || slot.res.is_none() {
            return None;
        }
        let res = slot.res.take();
        slot.generation = (slot.generation + 1) & GEN_MASK;
        self.free.push(index);
        self.live -= 1;
        res
    }

    pub fn clear(&mut self) {
        self.slots.clear();
        self.free.clear();
        self.live = 0;
    }

    getter!(buffer, Buffer, BufferRes);
    getter!(texture, Texture, TextureRes);
    getter!(view, View, ViewRes);
    getter!(sampler, Sampler, wgpu::Sampler);
    getter!(bind_group_layout, BindGroupLayout, wgpu::BindGroupLayout);
    getter!(pipeline_layout, PipelineLayout, wgpu::PipelineLayout);
    getter!(bind_group, BindGroup, wgpu::BindGroup);
    getter!(shader, Shader, ShaderRes);
    getter!(render_pipeline, RenderPipeline, wgpu::RenderPipeline);
    getter!(compute_pipeline, ComputePipeline, wgpu::ComputePipeline);
    getter!(query_set, QuerySet, QuerySetRes);

    pub fn buffer_mut(&mut self, id: u32) -> Result<&mut BufferRes, String> {
        match self.get_mut(id) {
            Some(Res::Buffer(b)) => Ok(b),
            _ => Err(format!("invalid or destroyed buffer id {id}")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Slab bookkeeping is tested with command buffers in the "encoding failed" state, which
    // need no device.
    fn cb() -> Res {
        Res::CommandBuffer(None)
    }

    #[test]
    fn ids_are_generational() {
        let mut s = Slab::default();
        let a = s.insert(cb());
        assert_ne!(a, 0, "0 is reserved for 'none'");
        let b = s.insert(cb());
        assert!(s.get(a).is_some() && s.get(b).is_some());
        assert_eq!(s.live, 2);
        assert!(s.remove(a).is_some());
        assert!(s.get(a).is_none());
        assert!(s.remove(a).is_none(), "double free is ignored");
        let c = s.insert(cb());
        assert_eq!(c & INDEX_MASK, a & INDEX_MASK, "slot reused");
        assert_ne!(c, a, "with a new generation");
        assert!(s.get(a).is_none(), "the stale id does not alias the new object");
        assert!(s.get(c).is_some());
        assert_eq!(s.live, 2);
        assert!(s.buffer(c).err().unwrap().contains("GPUCommandBuffer"));
        assert!(s.get(0).is_none());
        assert!(s.get(u32::MAX).is_none());
    }
}