blit-gui 0.1.0

2d drawing for blit
Documentation
//! image data, display options, and renderer resources

use alloc::{boxed::Box, rc::Rc};
use core::hash::{Hash, Hasher};

use blit::{LogicalRect, Paint, PhysicalRect, Rect, Scale2, Size, Ui, Widget, state};

use crate::color::Color;

blit::builder! {
    /// image drawn into a layout area
    #[derive(Clone, Debug, PartialEq)]
    pub struct Image {
        new(#[into] image: ImageHandle),
        #[into]
        intrinsic: Option<Size<f32>> = None,
        fit: ImageFit = ImageFit::Fill,
        sampling: ImageSampling = ImageSampling::Nearest,
        opacity: f32 = 1.0,
        colorize: Option<Color> = None,
        nine_slice: Option<NineSlice> = None,
        horizontal_tiling: ImageTiling = ImageTiling::None,
        vertical_tiling: ImageTiling = ImageTiling::None,
    }
}

impl<C> Widget<C, state::Insert> for Image
where
    C: Paint<Self, Scalar = f32>,
{
    type Response = ();

    fn build(self, mut ui: Ui<'_, C, state::Insert>) {
        let pixels = self.image.size();
        let intrinsic = self.intrinsic;
        let contain = self.fit == ImageFit::Contain
            && self.nine_slice.is_none()
            && self.horizontal_tiling == ImageTiling::None
            && self.vertical_tiling == ImageTiling::None;
        ui.measure(move |_, constraints| {
            let natural = Size::new(pixels.width as f32, pixels.height as f32);
            let mut size = intrinsic.unwrap_or(natural);
            if contain {
                size.width = size.width.min(constraints.max.width);
                size.height = size.height.min(constraints.max.height);
                let scale = (size.width / natural.width).min(size.height / natural.height).max(0.0);
                size = Size::new(natural.width * scale, natural.height * scale);
            }
            constraints.constrain(size)
        });
        ui.paint(move |cx, area| cx.context_mut().paint(area, &self));
    }
}

impl Image {
    /// resolves image fit and slicing into patches for renderer backends
    pub fn for_each_patch(&self, area: LogicalRect, scale_factor: f32, mut emit: impl FnMut(ImagePatch)) {
        let source_size = self.image.size();
        let geometry = area.to_physical(Scale2::uniform(scale_factor));
        let source = Rect {
            x: 0,
            y: 0,
            width: source_size.width,
            height: source_size.height,
        };
        if geometry.width <= 0 || geometry.height <= 0 || source.width == 0 || source.height == 0 || self.opacity <= 0.0
        {
            return;
        }

        let mut emit = |patch: ImagePatch| {
            if patch.source.width > 0
                && patch.source.height > 0
                && patch.display.width > 0
                && patch.display.height > 0
                && patch.bounds.width > 0
                && patch.bounds.height > 0
            {
                emit(patch);
            }
        };

        if let Some(slice) = self.nine_slice.filter(|slice| {
            u32::from(slice.left) + u32::from(slice.right) <= source.width
                && u32::from(slice.top) + u32::from(slice.bottom) <= source.height
        }) {
            let fit_borders = |first: i32, second: i32, available: i32| {
                if first + second <= available {
                    (first, second)
                } else {
                    let first = libm::roundf(first as f32 * available as f32 / (first + second) as f32) as i32;
                    (first, available - first)
                }
            };
            let (left, right) = fit_borders(
                libm::roundf(slice.left as f32 * scale_factor) as i32,
                libm::roundf(slice.right as f32 * scale_factor) as i32,
                geometry.width,
            );
            let (top, bottom) = fit_borders(
                libm::roundf(slice.top as f32 * scale_factor) as i32,
                libm::roundf(slice.bottom as f32 * scale_factor) as i32,
                geometry.height,
            );
            let source_x = [
                0,
                u32::from(slice.left),
                source.width - u32::from(slice.right),
                source.width,
            ];
            let source_y = [
                0,
                u32::from(slice.top),
                source.height - u32::from(slice.bottom),
                source.height,
            ];
            let destination_x = [
                geometry.x,
                geometry.x + left,
                geometry.x + geometry.width - right,
                geometry.x + geometry.width,
            ];
            let destination_y = [
                geometry.y,
                geometry.y + top,
                geometry.y + geometry.height - bottom,
                geometry.y + geometry.height,
            ];
            for row in 0..3 {
                for column in 0..3 {
                    let source = Rect {
                        x: source_x[column],
                        y: source_y[row],
                        width: source_x[column + 1] - source_x[column],
                        height: source_y[row + 1] - source_y[row],
                    };
                    let display = PhysicalRect {
                        x: destination_x[column],
                        y: destination_y[row],
                        width: destination_x[column + 1] - destination_x[column],
                        height: destination_y[row + 1] - destination_y[row],
                    };
                    emit(ImagePatch {
                        source,
                        display,
                        bounds: display,
                        horizontal_tiling: if column == 1 {
                            self.horizontal_tiling
                        } else {
                            ImageTiling::None
                        },
                        vertical_tiling: if row == 1 {
                            self.vertical_tiling
                        } else {
                            ImageTiling::None
                        },
                    });
                }
            }
            return;
        }

        let tiled = self.horizontal_tiling != ImageTiling::None || self.vertical_tiling != ImageTiling::None;
        let display = if tiled {
            geometry
        } else {
            match self.fit {
                ImageFit::Fill => geometry,
                ImageFit::Contain | ImageFit::Cover => {
                    let horizontal = geometry.width as f32 / source.width as f32;
                    let vertical = geometry.height as f32 / source.height as f32;
                    let scale = if self.fit == ImageFit::Contain {
                        horizontal.min(vertical)
                    } else {
                        horizontal.max(vertical)
                    };
                    let width = libm::roundf(source.width as f32 * scale).max(1.0) as i32;
                    let height = libm::roundf(source.height as f32 * scale).max(1.0) as i32;
                    PhysicalRect {
                        x: geometry.x + (geometry.width - width) / 2,
                        y: geometry.y + (geometry.height - height) / 2,
                        width,
                        height,
                    }
                }
            }
        };
        let bounds = if self.fit == ImageFit::Cover || tiled {
            display.intersection(geometry).unwrap_or_default()
        } else {
            display
        };
        emit(ImagePatch {
            source,
            display,
            bounds,
            horizontal_tiling: self.horizontal_tiling,
            vertical_tiling: self.vertical_tiling,
        });
    }
}

impl Hash for Image {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.image.id().hash(state);
        (if self.opacity == 0.0 { 0 } else { self.opacity.to_bits() }).hash(state);
        core::mem::discriminant(&self.fit).hash(state);
        core::mem::discriminant(&self.sampling).hash(state);
        core::mem::discriminant(&self.horizontal_tiling).hash(state);
        core::mem::discriminant(&self.vertical_tiling).hash(state);
        self.colorize.hash(state);
        self.nine_slice
            .map(|slice| [slice.top, slice.right, slice.bottom, slice.left])
            .hash(state);
    }
}

#[derive(Clone, Debug)]
pub struct ImageHandle(Rc<ImageInner>);

impl PartialEq for ImageHandle {
    fn eq(&self, other: &Self) -> bool {
        self.id() == other.id()
    }
}

impl From<&ImageHandle> for ImageHandle {
    fn from(image: &ImageHandle) -> Self {
        image.clone()
    }
}

impl ImageHandle {
    #[doc(hidden)]
    pub fn new(id: ImageId, size: Size<u32>) -> Self {
        Self(Rc::new(ImageInner { id, size }))
    }

    pub fn id(&self) -> ImageId {
        self.0.id
    }

    pub fn size(&self) -> Size<u32> {
        self.0.size
    }

    /// returns true when this is the only remaining handle to the image
    pub fn is_uniquely_owned(&self) -> bool {
        Rc::strong_count(&self.0) == 1
    }
}

#[derive(Debug, PartialEq)]
pub struct ImageData {
    pub pixels: ImagePixels,
    pub size: Size<u32>,
    pub texture_rect: Rect<u32>,
    pub stride_bytes: usize,
    pub format: ImageFormat,
}

impl ImageData {
    pub fn new(pixels: ImagePixels, format: ImageFormat, width: u32, height: u32) -> Self {
        let stride_bytes = (width as usize)
            .checked_mul(format.bytes_per_pixel())
            .expect("image width is too large");
        Self {
            pixels,
            size: Size { width, height },
            texture_rect: Rect {
                x: 0,
                y: 0,
                width,
                height,
            },
            stride_bytes,
            format,
        }
    }

    pub fn validate(&self) {
        assert!(self.size.width > 0 && self.size.height > 0);
        assert!(self.texture_rect.width > 0 && self.texture_rect.height > 0);
        assert!(
            self.texture_rect
                .x
                .checked_add(self.texture_rect.width)
                .is_some_and(|right| right <= self.size.width)
        );
        assert!(
            self.texture_rect
                .y
                .checked_add(self.texture_rect.height)
                .is_some_and(|bottom| bottom <= self.size.height)
        );
        let row_bytes = (self.texture_rect.width as usize)
            .checked_mul(self.format.bytes_per_pixel())
            .expect("image row is too large");
        assert!(self.stride_bytes >= row_bytes);
        let len = (self.texture_rect.height as usize - 1)
            .checked_mul(self.stride_bytes)
            .and_then(|offset| offset.checked_add(row_bytes))
            .expect("image data is too large");
        assert!(len <= self.pixels.bytes().len());
    }
}

#[derive(Debug, PartialEq)]
pub enum ImagePixels {
    Static(&'static [u8]),
    Owned(Box<[u8]>),
}

impl ImagePixels {
    pub fn bytes(&self) -> &[u8] {
        match self {
            Self::Static(bytes) => bytes,
            Self::Owned(bytes) => bytes,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImageFormat {
    Rgb8,
    Luma8,
    Rgba8,
    Rgba8Premultiplied,
    Alpha8(Color),
}

impl ImageFormat {
    pub fn bytes_per_pixel(self) -> usize {
        match self {
            Self::Rgb8 => 3,
            Self::Rgba8 | Self::Rgba8Premultiplied => 4,
            Self::Luma8 | Self::Alpha8(_) => 1,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NineSlice {
    pub top: u16,
    pub right: u16,
    pub bottom: u16,
    pub left: u16,
}

impl NineSlice {
    pub const fn uniform(value: u16) -> Self {
        Self {
            top: value,
            right: value,
            bottom: value,
            left: value,
        }
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ImageFit {
    #[default]
    Fill,
    Contain,
    Cover,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ImageSampling {
    #[default]
    Nearest,
    Bilinear,
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ImageTiling {
    #[default]
    None,
    Repeat,
    Round,
}

pub type ImageId = u64;

#[derive(Debug)]
struct ImageInner {
    id: ImageId,
    size: Size<u32>,
}

/// source and destination geometry for one image patch
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ImagePatch {
    pub source: Rect<u32>,
    pub display: PhysicalRect,
    pub bounds: PhysicalRect,
    pub horizontal_tiling: ImageTiling,
    pub vertical_tiling: ImageTiling,
}