mln-rs-engine 0.0.23

Part of mln-rs, a MapLibre map renderer written in Rust. Depend on mln-rs instead.
Documentation
use std::sync::Arc;

use mln_style::bitmap::{AlphaImage, PremultipliedImage};
use mln_style::hash::HashSet;
use mln_style::image::StyleImage;
use mln_style::size::Size;

use super::{DynamicTextureAtlas, GlyphPage, ImagePage};
use crate::draw::dynamic_texture::{QueuedPixels, TextureHandle};
use crate::image::image_store::{ImageMap, ImageType};
use crate::text::atlas::ImagePosition;
use crate::text::glyph::{Glyph, GlyphID, GlyphMap, GlyphMetrics, Glyphs};

fn glyph(code: char) -> Arc<Glyph> {
    Arc::new(Glyph {
        id: GlyphID::from_char(code).unwrap(),
        bitmap: AlphaImage::new(Size::new(8, 8)),
        metrics: GlyphMetrics { width: 8, height: 8, ..Default::default() },
    })
}

fn font(glyph: &Arc<Glyph>) -> Glyphs {
    Glyphs::from([(glyph.id, Some(Arc::clone(glyph)))])
}

/// An image named `id`, each of whose revisions is another.
fn image(id: &str, sdf: bool, size: Size) -> Arc<StyleImage> {
    let image =
        StyleImage::new(id.to_owned(), PremultipliedImage::new(size), 1.0, sdf, vec![], vec![], None, None, None);
    Arc::new(image.expect("an image"))
}

fn image_16(id: &str) -> Arc<StyleImage> {
    image(id, false, Size::new(16, 16))
}

/// A 16×16 image named `id` whose pixel (x, y) is `[x, y, 0, 255]`.
fn gradient(id: &str) -> Arc<StyleImage> {
    let mut pixels = PremultipliedImage::new(Size::new(16, 16));
    for (i, pixel) in pixels.data.as_chunks_mut::<4>().0.iter_mut().enumerate() {
        *pixel = [(i % 16) as u8, (i / 16) as u8, 0, 255];
    }
    Arc::new(StyleImage::new(id.to_owned(), pixels, 1.0, false, vec![], vec![], None, None, None).expect("an image"))
}

fn map(image: &Arc<StyleImage>) -> ImageMap {
    ImageMap::from([(image.id.clone(), Arc::clone(image))])
}

/// An atlas, and the pages it packed, which keep their bins as the layouts
/// that use them would.
struct Pages {
    atlas: DynamicTextureAtlas,
    images: Vec<ImagePage>,
    glyphs: Vec<GlyphPage>,
}

impl Pages {
    fn new() -> Self {
        Pages { atlas: DynamicTextureAtlas::new(), images: Vec::new(), glyphs: Vec::new() }
    }

    fn glyphs(&mut self, glyphs: &GlyphMap) -> &GlyphPage {
        let page = self.atlas.pack_glyphs(glyphs);
        self.glyphs.push(page);
        self.glyphs.last().unwrap()
    }

    fn images(&mut self, icons: &ImageMap, patterns: &ImageMap) -> &ImagePage {
        let page = self.atlas.pack_images(icons, patterns);
        self.images.push(page);
        self.images.last().unwrap()
    }

    /// Packs `image` as `usage` alone; its bin's handle.
    fn image(&mut self, image: &Arc<StyleImage>, usage: ImageType) -> TextureHandle {
        let page = match usage {
            ImageType::Icon => self.images(&map(image), &ImageMap::new()),
            ImageType::Pattern => self.images(&ImageMap::new(), &map(image)),
        };
        handle(page)
    }
}

fn handle(page: &ImagePage) -> TextureHandle {
    page.lease.texture_handles()[0]
}

/// A revision of an image shares its bin wherever it is packed, as an icon
/// or as a pattern. Every live revision has a bin of its own, though its
/// pixels and size are another's, so that a tile still drawing an older
/// layout draws the image it laid out with.
#[test]
fn each_live_image_revision_has_its_own_bin() {
    for usage in [ImageType::Icon, ImageType::Pattern] {
        let mut pages = Pages::new();
        let original = image_16("image");
        let first = pages.image(&original, usage);
        let shared = pages.image(&original, usage);
        assert_eq!((first.id(), first.rectangle()), (shared.id(), shared.rectangle()), "{usage:?}");

        let sdf = pages.image(&image("image", true, Size::new(16, 16)), usage);
        let same_again = pages.image(&image_16("image"), usage);
        assert_ne!(first.rectangle(), sdf.rectangle(), "{usage:?}");
        assert_ne!(first.rectangle(), same_again.rectangle(), "{usage:?}");
        assert_ne!(sdf.rectangle(), same_again.rectangle(), "{usage:?}");

        let ids: HashSet<_> = (0..64).map(|_| pages.image(&image_16("image"), usage).id()).collect();
        assert_eq!(ids.len(), 64, "{usage:?}");
    }
}

#[test]
fn an_image_used_as_icon_and_pattern_has_two_bins() {
    let mut pages = Pages::new();
    let image = image_16("image");
    let handles = pages.images(&map(&image), &map(&image)).lease.texture_handles();
    assert_eq!(2, handles.len());
    assert_ne!(handles[0].rectangle(), handles[1].rectangle());
}

#[test]
fn a_resized_image_of_the_same_area_gets_its_own_shape() {
    let mut pages = Pages::new();
    let tall = image("image", false, Size::new(10, 20));
    let wide = image("image", false, Size::new(20, 10));

    // The tall image's page still holds its bin while the wide one packs.
    pages.images(&map(&tall), &ImageMap::new());
    let position = &pages.images(&map(&wide), &ImageMap::new()).icons["image"];

    let padding = 2 * ImagePosition::PADDING;
    assert_eq!(u32::from(position.padded_rect.w - padding), wide.image.size.width);
    assert_eq!(u32::from(position.padded_rect.h - padding), wide.image.size.height);
}

/// A pack that fits no page takes a new one, as large as it needs.
#[test]
fn a_pack_that_fits_no_page_takes_a_new_one_as_large_as_it_needs() {
    let mut pages = Pages::new();
    let size = Size::new(600, 600);
    let first = pages.images(&map(&image("first", false, size)), &ImageMap::new()).lease.page();
    let page = pages.images(&map(&image("second", false, size)), &ImageMap::new());

    assert_ne!(page.lease.page(), first, "the first page holds the first image");
    let padding = 2 * ImagePosition::PADDING;
    let rect = page.icons["second"].padded_rect;
    assert_eq!((u32::from(rect.w - padding), u32::from(rect.h - padding)), (600, 600));
    assert_eq!(pages.atlas.page_count(), 2);
}

/// A revision is forgotten with its last lease, so packing it again packs
/// and uploads it under a new bin.
#[test]
fn a_released_revision_is_packed_again_into_a_new_bin() {
    let mut pages = Pages::new();
    // Keeps the page.
    pages.image(&image_16("other"), ImageType::Icon);
    let image = image_16("pattern");
    let released = pages.atlas.pack_images(&ImageMap::new(), &map(&image));
    let released_id = handle(&released).id();
    drop(released);

    assert_ne!(released_id, pages.image(&image, ImageType::Pattern).id());
}

/// Two font stacks' glyphs get bins of their own, whatever their font
/// stacks' hashes and code points, and share one for the same glyph.
#[test]
fn glyphs_share_a_bin_only_when_they_are_the_same_glyph() {
    let mut pages = Pages::new();
    let (b, a) = (glyph('B'), glyph('A'));
    let page = pages.glyphs(&GlyphMap::from([(0, font(&b)), (4, font(&a))]));
    let handles = page.lease.texture_handles();
    assert_eq!(handles.len(), 2);
    assert_ne!(handles[0].rectangle(), handles[1].rectangle());
    assert_ne!(page.positions[&0][&b.id].unwrap().rect, page.positions[&4][&a.id].unwrap().rect);

    let page = pages.glyphs(&GlyphMap::from([(1, font(&a)), (2, font(&a))]));
    let handles = page.lease.texture_handles();
    assert_eq!(handles.len(), 2);
    assert_eq!(handles[0].id(), handles[1].id());
}

/// A glyph no font has stays missing, and one without a bitmap has its
/// metrics and no bin.
#[test]
fn missing_and_blank_glyphs_take_no_bin() {
    let mut pages = Pages::new();
    let drawn = glyph('A');
    let blank = Arc::new(Glyph {
        id: GlyphID::from_char(' ').unwrap(),
        bitmap: AlphaImage::default(),
        metrics: GlyphMetrics { advance: 6, ..Default::default() },
    });
    let mut glyphs = font(&drawn);
    glyphs.insert(blank.id, Some(Arc::clone(&blank)));
    glyphs.insert(GlyphID::from_char('B').unwrap(), None);
    let page = pages.glyphs(&GlyphMap::from([(1, glyphs)]));

    assert_eq!(page.lease.texture_handles().len(), 1);
    let positions = &page.positions[&1];
    assert!(positions[&GlyphID::from_char('B').unwrap()].is_none());
    let blank_position = positions[&blank.id].unwrap();
    assert_eq!((blank_position.rect.w, blank_position.metrics.advance), (0, 6));
    assert_ne!(positions[&drawn.id].unwrap().rect.w, 0);
}

/// Dropping the last lease on a page's bins frees them, and the page with
/// them, the next time the atlas packs or uploads.
#[test]
fn dropped_leases_free_their_bins_and_empty_pages() {
    let mut atlas = DynamicTextureAtlas::new();
    let image = image_16("icon");
    let first = atlas.pack_images(&map(&image), &ImageMap::new());
    let second = atlas.pack_images(&map(&image), &ImageMap::new());
    assert_eq!(first.lease.page(), second.lease.page());
    assert_eq!(atlas.page_count(), 1);

    drop(first);
    atlas.free_released();
    assert_eq!(atlas.page_count(), 1, "the second lease still holds the bin");
    drop(second);
    atlas.free_released();
    assert_eq!(atlas.page_count(), 0);

    // An empty pack takes the bin of a 1×1 page, which isn't packed into,
    // and goes with its last lease.
    let empty = atlas.pack_images(&ImageMap::new(), &ImageMap::new());
    assert_eq!(empty.lease.texture_handles().len(), 1);
    let second = atlas.pack_images(&ImageMap::new(), &ImageMap::new());
    assert_eq!(second.lease.page(), empty.lease.page());
    assert_eq!(atlas.page_count(), 0);
    let page = empty.lease.page();
    drop((empty, second));
    atlas.free_released();
    assert_ne!(atlas.pack_images(&ImageMap::new(), &ImageMap::new()).lease.page(), page);
}

/// A same-size image update copies the new pixels into the bins of the
/// revisions that layouts hold, with a pattern's wrapped edges; an update of
/// another size or another image queues nothing.
#[test]
fn a_patched_pattern_is_queued_for_its_bin() {
    let mut pages = Pages::new();
    let tex_handle = pages.image(&image_16("pattern"), ImageType::Pattern);
    let page = pages.images[0].lease.page();
    let queued = |pages: &Pages| pages.atlas.queued_uploads(page).unwrap()[&tex_handle.id()].clone();
    let original = queued(&pages);

    pages.atlas.patch_image(&image("pattern", false, Size::new(8, 8)));
    pages.atlas.patch_image(&gradient("other"));
    assert_eq!(queued(&pages), original);

    pages.atlas.patch_image(&gradient("pattern"));
    let (rect, QueuedPixels::Bytes(data)) = queued(&pages) else {
        panic!("a patch queues the bin's pixels");
    };
    assert_eq!(&rect, tex_handle.rectangle());

    // The image starts two pixels in: one of padding, one of wrapped edge.
    let pixel = |x: usize, y: usize| {
        let i = (y * usize::from(rect.w) + x) * 4;
        &data[i..i + 4]
    };
    assert_eq!(pixel(2 + 3, 2 + 5), [3, 5, 0, 255]);
    assert_eq!(pixel(1, 2 + 5), [15, 5, 0, 255]);
    assert_eq!(pixel(2 + 3, 2 + 16), [3, 0, 0, 255]);
}