use bevy_asset::{Assets, Handle, RenderAssetUsages};
use bevy_image::{prelude::*, ImageSampler, ToExtents};
use bevy_math::{IVec2, UVec2};
use bevy_platform::collections::HashMap;
use wgpu_types::{TextureDimension, TextureFormat};
use crate::{FontSmoothing, GlyphAtlasLocation, TextError};
pub struct FontAtlas {
pub dynamic_texture_atlas_builder: DynamicTextureAtlasBuilder,
pub glyph_to_atlas_index: HashMap<cosmic_text::CacheKey, GlyphAtlasLocation>,
pub texture_atlas: Handle<TextureAtlasLayout>,
pub texture: Handle<Image>,
}
impl FontAtlas {
pub fn new(
textures: &mut Assets<Image>,
texture_atlases_layout: &mut Assets<TextureAtlasLayout>,
size: UVec2,
font_smoothing: FontSmoothing,
) -> FontAtlas {
let mut image = Image::new_fill(
size.to_extents(),
TextureDimension::D2,
&[0, 0, 0, 0],
TextureFormat::Rgba8UnormSrgb,
RenderAssetUsages::MAIN_WORLD | RenderAssetUsages::RENDER_WORLD,
);
if font_smoothing == FontSmoothing::None {
image.sampler = ImageSampler::nearest();
}
let texture = textures.add(image);
let texture_atlas = texture_atlases_layout.add(TextureAtlasLayout::new_empty(size));
Self {
texture_atlas,
glyph_to_atlas_index: HashMap::default(),
dynamic_texture_atlas_builder: DynamicTextureAtlasBuilder::new(size, 1),
texture,
}
}
pub fn get_glyph_index(&self, cache_key: cosmic_text::CacheKey) -> Option<GlyphAtlasLocation> {
self.glyph_to_atlas_index.get(&cache_key).copied()
}
pub fn has_glyph(&self, cache_key: cosmic_text::CacheKey) -> bool {
self.glyph_to_atlas_index.contains_key(&cache_key)
}
pub fn add_glyph(
&mut self,
textures: &mut Assets<Image>,
atlas_layouts: &mut Assets<TextureAtlasLayout>,
cache_key: cosmic_text::CacheKey,
texture: &Image,
offset: IVec2,
) -> Result<(), TextError> {
let atlas_layout = atlas_layouts.get_mut(&self.texture_atlas).unwrap();
let atlas_texture = textures.get_mut(&self.texture).unwrap();
if let Ok(glyph_index) =
self.dynamic_texture_atlas_builder
.add_texture(atlas_layout, texture, atlas_texture)
{
self.glyph_to_atlas_index.insert(
cache_key,
GlyphAtlasLocation {
glyph_index,
offset,
},
);
Ok(())
} else {
Err(TextError::FailedToAddGlyph(cache_key.glyph_id))
}
}
}
impl core::fmt::Debug for FontAtlas {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("FontAtlas")
.field("glyph_to_atlas_index", &self.glyph_to_atlas_index)
.field("texture_atlas", &self.texture_atlas)
.field("texture", &self.texture)
.field("dynamic_texture_atlas_builder", &"[...]")
.finish()
}
}