use super::*;
impl GlyphAtlas {
pub fn get_or_rasterize(&mut self, key: GlyphKey) -> &RasterizedGlyph {
if !self.get_glyphs().contains_key(&key) {
let glyph: RasterizedGlyph = rasterize_glyph(key);
self.get_mut_glyphs().insert(key, glyph);
let next_rev: u64 = self.get_revision().wrapping_add(1);
self.set_revision(next_rev);
}
&self.get_glyphs()[&key]
}
#[must_use]
pub fn len(&self) -> usize {
self.get_glyphs().len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.get_glyphs().is_empty()
}
pub fn get_or_rasterize_with(
&mut self,
key: GlyphKey,
provider: &dyn SystemFontProvider,
) -> &RasterizedGlyph {
if !self.get_glyphs().contains_key(&key) {
let glyph: RasterizedGlyph = provider
.rasterize(key)
.unwrap_or_else(|| rasterize_glyph(key));
self.get_mut_glyphs().insert(key, glyph);
let next_rev: u64 = self.get_revision().wrapping_add(1);
self.set_revision(next_rev);
}
&self.get_glyphs()[&key]
}
#[must_use]
pub fn pack_rgba_atlas(&self) -> PackedGlyphAtlas {
let atlas_w: u32 = ATLAS_DEFAULT_WIDTH;
let glyph_count: usize = self.get_glyphs().len();
let mut cursor_x: u32 = 1;
let mut cursor_y: u32 = 1;
let mut shelf_h: u32 = 0;
let mut regions: HashMap<GlyphKey, (u32, u32, u32, u32)> =
HashMap::with_capacity(glyph_count);
let mut placements: Vec<(&RasterizedGlyph, u32, u32)> = Vec::with_capacity(glyph_count);
for (key, glyph) in self.get_glyphs().iter() {
let gw: u32 = glyph.get_width();
let gh: u32 = glyph.get_height();
if cursor_x + gw + 1 > atlas_w {
cursor_x = 1;
cursor_y += shelf_h + 1;
shelf_h = 0;
}
regions.insert(*key, (cursor_x, cursor_y, gw, gh));
placements.push((glyph, cursor_x, cursor_y));
cursor_x += gw + 1;
shelf_h = shelf_h.max(gh);
}
let atlas_h: u32 = (cursor_y + shelf_h + 1).max(16);
let atlas_w_usize: usize = atlas_w as usize;
let mut pixels: Vec<u8> = vec![0; atlas_w_usize * (atlas_h as usize) * 4];
for (glyph, rx, ry) in placements.into_iter() {
let gw: usize = glyph.get_width() as usize;
let gh: usize = glyph.get_height() as usize;
let cov: &[u8] = glyph.get_coverage().as_slice();
for py in 0..gh {
let src_row: &[u8] = &cov[py * gw..(py + 1) * gw];
let dst_start: usize = (((ry as usize) + py) * atlas_w_usize + (rx as usize)) * 4;
let dst_row: &mut [u8] = &mut pixels[dst_start..dst_start + gw * 4];
for (alpha, dst_px) in src_row
.iter()
.copied()
.zip(dst_row.as_chunks_mut::<4>().0.iter_mut())
{
*dst_px = [255, 255, 255, alpha];
}
}
}
PackedGlyphAtlas::new(atlas_w, atlas_h, pixels, regions, self.get_revision())
}
pub fn clear(&mut self) {
self.get_mut_glyphs().clear();
let next_rev: u64 = self.get_revision().wrapping_add(1);
self.set_revision(next_rev);
}
}