mln-rs-renderer 0.0.13

Part of mln-rs, a Rust port of the MapLibre Native map rendering core. Depend on mln-rs instead.
Documentation
use std::cell::RefCell;
use std::rc::Rc;

use mln_gfx::gpu::{Gpu, GpuError, SamplerId, TextureDesc, TextureFormat, TextureId, TextureRegion, TextureUsage};
use mln_gfx::released::Released;
use mln_gfx::texture2d::SamplerState;
use mln_util::image::PremultipliedImage;
use mln_util::size::Size;

use crate::gfx::context::Context;

/// A texture of the renderer: its size, format and sampler state, the image
/// it waits to upload, and once made, a texture of the backend's
/// [`Gpu`](mln_gfx::gpu::Gpu), which goes back to the context to destroy when
/// the texture is dropped or replaced (see [`Released`]).
pub(crate) struct Texture2D {
    texture: Option<TextureId>,
    size: Size,
    format: TextureFormat,
    render_target: bool,
    sampler: SamplerState,
    /// The context's sampler of `sampler`, once a draw bound it.
    sampler_id: Option<SamplerId>,
    /// The image the next [`upload`](Self::upload) writes.
    image: Option<Rc<PremultipliedImage>>,
    released: Rc<Released>,
}

/// A shared texture, which tweakers mutate through the shared handle (e.g.
/// its sampler state), hence the `RefCell`.
pub(crate) type Texture2DPtr = Rc<RefCell<Texture2D>>;

impl Texture2D {
    /// An RGBA texture without a size, which goes back to `released` once
    /// made.
    #[must_use]
    pub(crate) fn new(released: Rc<Released>) -> Texture2D {
        Texture2D {
            texture: None,
            size: Size::new(0, 0),
            format: TextureFormat::Rgba8Unorm,
            render_target: false,
            sampler: SamplerState::default(),
            sampler_id: None,
            image: None,
            released,
        }
    }

    #[must_use]
    pub(crate) fn size(&self) -> Size {
        self.size
    }

    /// Sets the size the texture is made with. A texture made with another
    /// size goes.
    pub(crate) fn set_size(&mut self, size: Size) {
        if size != self.size {
            self.release();
            self.size = size;
        }
    }

    #[must_use]
    pub(crate) fn format(&self) -> TextureFormat {
        self.format
    }

    /// Sets the format the texture is made with. A texture made with
    /// another format goes.
    pub(crate) fn set_format(&mut self, format: TextureFormat) {
        if format != self.format {
            self.release();
            self.format = format;
        }
    }

    /// Makes the texture one that passes draw into, as well as one that
    /// shaders sample.
    pub(crate) fn set_render_target(&mut self) {
        self.render_target = true;
    }

    /// Sets how shaders sample the texture, with an anisotropy of at least 1.
    pub(crate) fn set_sampler(&mut self, sampler: SamplerState) {
        let sampler = SamplerState { max_anisotropy: sampler.max_anisotropy.max(1), ..sampler };
        if sampler != self.sampler {
            self.sampler = sampler;
            self.sampler_id = None;
        }
    }

    /// Sets the RGBA image the next [`upload`](Self::upload) writes, and the
    /// texture's size to the image's.
    pub(crate) fn set_image(&mut self, image: Option<Rc<PremultipliedImage>>) {
        if let Some(image) = &image {
            self.set_size(image.size);
            self.set_format(TextureFormat::Rgba8Unorm);
        }
        self.image = image;
    }

    /// Makes the backend's texture of the size and format set, unless it is
    /// made. Fails for an empty size.
    pub(crate) fn create(&mut self, context: &Context) -> Result<TextureId, GpuError> {
        self.create_in(&mut *context.gpu(), context)
    }

    /// [`create`](Self::create) through `gpu`, the context's.
    fn create_in(&mut self, gpu: &mut dyn Gpu, context: &Context) -> Result<TextureId, GpuError> {
        if let Some(texture) = self.texture {
            return Ok(texture);
        }
        let desc = TextureDesc {
            label: if self.render_target { "render target" } else { "texture" },
            size: self.size,
            format: self.format,
            usage: TextureUsage { sampled: true, render_target: self.render_target, copy_src: self.render_target },
        };
        let texture = gpu.create_texture(&desc)?;
        let mut stats = context.rendering_stats();
        stats.num_created_textures += 1;
        stats.num_active_textures += 1;
        stats.mem_textures += self.bytes() as i32;
        self.texture = Some(texture);
        Ok(texture)
    }

    /// Writes `data`, the texels of a texture of `size` in rows from the top,
    /// to the whole texture, first making it of that size. Empty `data`
    /// leaves the texels unspecified, and an empty size makes no texture.
    pub(crate) fn upload_data(&mut self, context: &Context, data: &[u8], size: Size) -> Result<(), GpuError> {
        self.upload_data_in(&mut *context.gpu(), context, data, size)
    }

    /// [`upload_data`](Self::upload_data) through `gpu`, the context's.
    fn upload_data_in(
        &mut self,
        gpu: &mut dyn Gpu,
        context: &Context,
        data: &[u8],
        size: Size,
    ) -> Result<(), GpuError> {
        self.set_size(size);
        if size.is_empty() {
            return Ok(());
        }
        let texture = self.create_in(gpu, context)?;
        if data.is_empty() {
            return Ok(());
        }
        Self::write(gpu, context, texture, data, TextureRegion { x: 0, y: 0, size })
    }

    /// Writes `data`, the texels of a region of `size` in rows from the top,
    /// at `x`, `y` of the texture, first making it.
    pub(crate) fn upload_sub_region(
        &mut self,
        context: &Context,
        data: &[u8],
        size: Size,
        x: u16,
        y: u16,
    ) -> Result<(), GpuError> {
        let mut gpu = context.gpu();
        let texture = self.create_in(&mut *gpu, context)?;
        Self::write(&mut *gpu, context, texture, data, TextureRegion { x: u32::from(x), y: u32::from(y), size })
    }

    /// Writes `data` to `region` of `texture`, and counts the write.
    fn write(
        gpu: &mut dyn Gpu,
        context: &Context,
        texture: TextureId,
        data: &[u8],
        region: TextureRegion,
    ) -> Result<(), GpuError> {
        gpu.write_texture(texture, region, data)?;
        let mut stats = context.rendering_stats();
        stats.num_texture_updates += 1;
        stats.texture_update_bytes += data.len();
        Ok(())
    }

    /// Writes the image [`set_image`](Self::set_image) set, if any.
    pub(crate) fn upload(&mut self, context: &Context) -> Result<(), GpuError> {
        if self.image.is_none() {
            return Ok(());
        }
        self.upload_in(&mut *context.gpu(), context)
    }

    /// [`upload`](Self::upload) through `gpu`, the context's.
    fn upload_in(&mut self, gpu: &mut dyn Gpu, context: &Context) -> Result<(), GpuError> {
        match self.image.take() {
            Some(image) if image.valid() => self.upload_data_in(gpu, context, &image.data, image.size),
            _ => Ok(()),
        }
    }

    /// What a draw binds, through `gpu`, the context's: the texture, made
    /// and holding its image, and the sampler of its state.
    pub(crate) fn binding(&mut self, gpu: &mut dyn Gpu, context: &Context) -> Result<(TextureId, SamplerId), GpuError> {
        self.upload_in(gpu, context)?;
        let texture = self.create_in(gpu, context)?;
        let sampler = match self.sampler_id {
            Some(sampler) => sampler,
            None => *self.sampler_id.insert(context.sampler(gpu, self.sampler)?),
        };
        Ok((texture, sampler))
    }

    /// The bytes the texture takes.
    fn bytes(&self) -> usize {
        let texel = self.format.bytes_per_texel().unwrap_or(4) as usize;
        self.size.width as usize * self.size.height as usize * texel
    }

    /// Lets go of the backend's texture.
    fn release(&mut self) {
        if let Some(texture) = self.texture.take() {
            self.released.texture(texture, self.bytes());
        }
    }
}

impl Drop for Texture2D {
    fn drop(&mut self) {
        self.release();
    }
}

/// Writes a premultiplied RGBA image to `texture`, setting its format.
pub(crate) fn upload_image(
    context: &Context,
    texture: &mut Texture2D,
    image: &PremultipliedImage,
) -> Result<(), GpuError> {
    texture.set_format(TextureFormat::Rgba8Unorm);
    texture.upload_data(context, &image.data, image.size)
}