text: font atlas generation. initial Drawable boilerplate. temporary font atlas debug example
This commit is contained in:
parent
5f0363a4f5
commit
516cf9ddf0
@ -171,6 +171,10 @@ path = "examples/shader/shader_defs.rs"
|
|||||||
name = "text"
|
name = "text"
|
||||||
path = "examples/ui/text.rs"
|
path = "examples/ui/text.rs"
|
||||||
|
|
||||||
|
[[example]]
|
||||||
|
name = "font_atlas_debug"
|
||||||
|
path = "examples/ui/font_atlas_debug.rs"
|
||||||
|
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "ui"
|
name = "ui"
|
||||||
path = "examples/ui/ui.rs"
|
path = "examples/ui/ui.rs"
|
||||||
|
@ -6,88 +6,69 @@ use guillotiere::{size2, AllocId, Allocation, AtlasAllocator};
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
pub struct DynamicTextureAtlasBuilder {
|
pub struct DynamicTextureAtlasBuilder {
|
||||||
pub texture_allocations: HashMap<Handle<Texture>, Allocation>,
|
|
||||||
pub allocation_textures: HashMap<AllocId, Handle<Texture>>,
|
pub allocation_textures: HashMap<AllocId, Handle<Texture>>,
|
||||||
pub atlas_allocator: AtlasAllocator,
|
pub atlas_allocator: AtlasAllocator,
|
||||||
pub atlas_texture: Texture,
|
|
||||||
pub max_size: Vec2,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for DynamicTextureAtlasBuilder {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new(Vec2::new(256., 256.), Vec2::new(2048., 2048.))
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const FORMAT_SIZE: usize = 4; // TODO: get this from an actual format type
|
const FORMAT_SIZE: usize = 4; // TODO: get this from an actual format type
|
||||||
impl DynamicTextureAtlasBuilder {
|
impl DynamicTextureAtlasBuilder {
|
||||||
pub fn new(initial_size: Vec2, max_size: Vec2) -> Self {
|
pub fn new(size: Vec2) -> Self {
|
||||||
Self {
|
Self {
|
||||||
texture_allocations: Default::default(),
|
|
||||||
allocation_textures: Default::default(),
|
allocation_textures: Default::default(),
|
||||||
atlas_allocator: AtlasAllocator::new(to_size2(initial_size)),
|
atlas_allocator: AtlasAllocator::new(to_size2(size)),
|
||||||
atlas_texture: Texture::new_fill(initial_size, &[0,0,0,0]),
|
|
||||||
max_size,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_texture(&mut self, texture_handle: Handle<Texture>, textures: &Assets<Texture>) -> bool {
|
pub fn add_texture(
|
||||||
let texture = textures.get(&texture_handle).unwrap();
|
&mut self,
|
||||||
let mut queued_textures= vec![texture_handle];
|
texture_atlas: &mut TextureAtlas,
|
||||||
let mut resized = false;
|
textures: &mut Assets<Texture>,
|
||||||
loop {
|
texture: &Texture,
|
||||||
let mut failed_textures = Vec::new();
|
) -> Option<u32> {
|
||||||
while let Some(texture_handle) = queued_textures.pop() {
|
let allocation = self
|
||||||
let allocation = self
|
.atlas_allocator
|
||||||
.atlas_allocator
|
.allocate(size2(texture.size.x() as i32, texture.size.y() as i32));
|
||||||
.allocate(size2(texture.size.x() as i32, texture.size.y() as i32));
|
if let Some(allocation) = allocation {
|
||||||
if let Some(allocation) = allocation {
|
let atlas_texture = textures.get_mut(&texture_atlas.texture).unwrap();
|
||||||
self.place_texture(allocation, texture_handle, texture);
|
self.place_texture(atlas_texture, allocation, texture);
|
||||||
} else {
|
texture_atlas.add_texture(allocation.rectangle.into());
|
||||||
failed_textures.push(texture_handle);
|
Some((texture_atlas.len() - 1) as u32)
|
||||||
}
|
} else {
|
||||||
}
|
None
|
||||||
|
|
||||||
if failed_textures.len() == 0 {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
queued_textures = failed_textures;
|
|
||||||
|
|
||||||
// if allocation failed, resize the atlas
|
|
||||||
resized = true;
|
|
||||||
let new_size = self.atlas_texture.size * 2.0;
|
|
||||||
if new_size > self.max_size {
|
|
||||||
panic!(
|
|
||||||
"Ran out of space in Atlas. This atlas cannot be larger than: {:?}",
|
|
||||||
self.max_size
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
let new_size2 = to_size2(new_size);
|
|
||||||
self.atlas_texture = Texture::new_fill(new_size, &[0,0,0,0]);
|
|
||||||
let change_list = self.atlas_allocator.resize_and_rearrange(new_size2);
|
|
||||||
|
|
||||||
for change in change_list.changes {
|
|
||||||
if let Some(changed_texture_handle) = self.allocation_textures.remove(&change.old.id) {
|
|
||||||
self.texture_allocations.remove(&changed_texture_handle);
|
|
||||||
let changed_texture = textures.get(&changed_texture_handle).unwrap();
|
|
||||||
self.place_texture(change.new, changed_texture_handle, changed_texture);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for failure in change_list.failures {
|
|
||||||
let failed_texture = self.allocation_textures.remove(&failure.id).unwrap();
|
|
||||||
queued_textures.push(failed_texture);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return resized;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn place_texture(&mut self, allocation: Allocation, texture_handle: Handle<Texture>, texture: &Texture) {
|
// fn resize(
|
||||||
|
// &mut self,
|
||||||
|
// texture_atlas: &mut TextureAtlas,
|
||||||
|
// textures: &mut Assets<Texture>,
|
||||||
|
// size: Vec2,
|
||||||
|
// ) {
|
||||||
|
// let new_size2 = to_size2(new_size);
|
||||||
|
// self.atlas_texture = Texture::new_fill(new_size, &[0,0,0,0]);
|
||||||
|
// let change_list = self.atlas_allocator.resize_and_rearrange(new_size2);
|
||||||
|
|
||||||
|
// for change in change_list.changes {
|
||||||
|
// if let Some(changed_texture_handle) = self.allocation_textures.remove(&change.old.id) {
|
||||||
|
// let changed_texture = textures.get(&changed_texture_handle).unwrap();
|
||||||
|
// self.place_texture(change.new, changed_texture_handle, changed_texture);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// for failure in change_list.failures {
|
||||||
|
// let failed_texture = self.allocation_textures.remove(&failure.id).unwrap();
|
||||||
|
// queued_textures.push(failed_texture);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
fn place_texture(
|
||||||
|
&mut self,
|
||||||
|
atlas_texture: &mut Texture,
|
||||||
|
allocation: Allocation,
|
||||||
|
texture: &Texture,
|
||||||
|
) {
|
||||||
let rect = allocation.rectangle;
|
let rect = allocation.rectangle;
|
||||||
let atlas_width = self.atlas_texture.size.x() as usize;
|
let atlas_width = atlas_texture.size.x() as usize;
|
||||||
let rect_width = rect.width() as usize;
|
let rect_width = rect.width() as usize;
|
||||||
|
|
||||||
for (texture_y, bound_y) in (rect.min.y..rect.max.y).map(|i| i as usize).enumerate() {
|
for (texture_y, bound_y) in (rect.min.y..rect.max.y).map(|i| i as usize).enumerate() {
|
||||||
@ -95,34 +76,9 @@ impl DynamicTextureAtlasBuilder {
|
|||||||
let end = begin + rect_width * FORMAT_SIZE;
|
let end = begin + rect_width * FORMAT_SIZE;
|
||||||
let texture_begin = texture_y * rect_width * FORMAT_SIZE;
|
let texture_begin = texture_y * rect_width * FORMAT_SIZE;
|
||||||
let texture_end = texture_begin + rect_width * FORMAT_SIZE;
|
let texture_end = texture_begin + rect_width * FORMAT_SIZE;
|
||||||
self.atlas_texture.data[begin..end]
|
atlas_texture.data[begin..end]
|
||||||
.copy_from_slice(&texture.data[texture_begin..texture_end]);
|
.copy_from_slice(&texture.data[texture_begin..texture_end]);
|
||||||
}
|
}
|
||||||
|
|
||||||
self.allocation_textures.insert(allocation.id, texture_handle);
|
|
||||||
self.texture_allocations.insert(texture_handle, allocation);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn remove_texture(&mut self, texture_handle: Handle<Texture>) {
|
|
||||||
if let Some(allocation) = self.texture_allocations.remove(&texture_handle) {
|
|
||||||
self.allocation_textures.remove(&allocation.id);
|
|
||||||
self.atlas_allocator.deallocate(allocation.id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn finish(self, textures: &mut Assets<Texture>) -> TextureAtlas {
|
|
||||||
let mut texture_rects = Vec::with_capacity(self.texture_allocations.len());
|
|
||||||
let mut texture_handles = HashMap::with_capacity(self.texture_allocations.len());
|
|
||||||
for (index, (handle, allocation)) in self.texture_allocations.iter().enumerate() {
|
|
||||||
texture_rects.push(allocation.rectangle.into());
|
|
||||||
texture_handles.insert(*handle, index);
|
|
||||||
}
|
|
||||||
TextureAtlas {
|
|
||||||
dimensions: to_vec2(self.atlas_allocator.size()),
|
|
||||||
texture: textures.add(self.atlas_texture),
|
|
||||||
textures: texture_rects,
|
|
||||||
texture_handles: Some(texture_handles),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -135,10 +91,6 @@ impl From<guillotiere::Rectangle> for Rect {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn to_vec2(size: guillotiere::Size) -> Vec2 {
|
|
||||||
Vec2::new(size.width as f32, size.height as f32)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_size2(vec2: Vec2) -> guillotiere::Size {
|
fn to_size2(vec2: Vec2) -> guillotiere::Size {
|
||||||
guillotiere::Size::new(vec2.x() as i32, vec2.y() as i32)
|
guillotiere::Size::new(vec2.x() as i32, vec2.y() as i32)
|
||||||
}
|
}
|
||||||
|
@ -11,8 +11,8 @@ layout(set = 0, binding = 0) uniform Camera2d {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// TODO: merge dimensions into "sprites" buffer when that is supported in the Uniforms derive abstraction
|
// TODO: merge dimensions into "sprites" buffer when that is supported in the Uniforms derive abstraction
|
||||||
layout(set = 1, binding = 0) uniform TextureAtlas_dimensions {
|
layout(set = 1, binding = 0) uniform TextureAtlas_size {
|
||||||
vec2 Dimensions;
|
vec2 AtlasSize;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct Rect {
|
struct Rect {
|
||||||
@ -41,6 +41,6 @@ void main() {
|
|||||||
vec2(sprite_rect.end.x, sprite_rect.begin.y),
|
vec2(sprite_rect.end.x, sprite_rect.begin.y),
|
||||||
sprite_rect.end
|
sprite_rect.end
|
||||||
);
|
);
|
||||||
v_Uv = uvs[gl_VertexIndex] / Dimensions;
|
v_Uv = uvs[gl_VertexIndex] / AtlasSize;
|
||||||
gl_Position = ViewProj * vec4(vertex_position, 1.0);
|
gl_Position = ViewProj * vec4(vertex_position, 1.0);
|
||||||
}
|
}
|
@ -12,7 +12,7 @@ use std::collections::HashMap;
|
|||||||
pub struct TextureAtlas {
|
pub struct TextureAtlas {
|
||||||
pub texture: Handle<Texture>,
|
pub texture: Handle<Texture>,
|
||||||
// TODO: add support to Uniforms derive to write dimensions and sprites to the same buffer
|
// TODO: add support to Uniforms derive to write dimensions and sprites to the same buffer
|
||||||
pub dimensions: Vec2,
|
pub size: Vec2,
|
||||||
#[render_resources(buffer)]
|
#[render_resources(buffer)]
|
||||||
pub textures: Vec<Rect>,
|
pub textures: Vec<Rect>,
|
||||||
#[render_resources(ignore)]
|
#[render_resources(ignore)]
|
||||||
@ -30,6 +30,15 @@ pub struct TextureAtlasSprite {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl TextureAtlas {
|
impl TextureAtlas {
|
||||||
|
pub fn new_empty(texture: Handle<Texture>, dimensions: Vec2) -> Self {
|
||||||
|
Self {
|
||||||
|
texture,
|
||||||
|
size: dimensions,
|
||||||
|
texture_handles: None,
|
||||||
|
textures: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn from_grid(
|
pub fn from_grid(
|
||||||
texture: Handle<Texture>,
|
texture: Handle<Texture>,
|
||||||
size: Vec2,
|
size: Vec2,
|
||||||
@ -51,13 +60,21 @@ impl TextureAtlas {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
TextureAtlas {
|
TextureAtlas {
|
||||||
dimensions: size,
|
size,
|
||||||
textures: sprites,
|
textures: sprites,
|
||||||
texture,
|
texture,
|
||||||
texture_handles: None,
|
texture_handles: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn add_texture(&mut self, rect: Rect) {
|
||||||
|
self.textures.push(rect);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.textures.len()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn get_texture_index(&self, texture: Handle<Texture>) -> Option<usize> {
|
pub fn get_texture_index(&self, texture: Handle<Texture>) -> Option<usize> {
|
||||||
self.texture_handles
|
self.texture_handles
|
||||||
.as_ref()
|
.as_ref()
|
||||||
|
@ -128,7 +128,7 @@ impl TextureAtlasBuilder {
|
|||||||
self.place_texture(&mut atlas_texture, texture, packed_location);
|
self.place_texture(&mut atlas_texture, texture, packed_location);
|
||||||
}
|
}
|
||||||
Ok(TextureAtlas {
|
Ok(TextureAtlas {
|
||||||
dimensions: atlas_texture.size,
|
size: atlas_texture.size,
|
||||||
texture: textures.add(atlas_texture),
|
texture: textures.add(atlas_texture),
|
||||||
textures: texture_rects,
|
textures: texture_rects,
|
||||||
texture_handles: Some(texture_handles),
|
texture_handles: Some(texture_handles),
|
||||||
|
@ -8,8 +8,11 @@ edition = "2018"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
bevy_app = { path = "../bevy_app" }
|
bevy_app = { path = "../bevy_app" }
|
||||||
|
bevy_core = { path = "../bevy_core" }
|
||||||
bevy_asset = { path = "../bevy_asset" }
|
bevy_asset = { path = "../bevy_asset" }
|
||||||
bevy_render = { path = "../bevy_render" }
|
bevy_render = { path = "../bevy_render" }
|
||||||
|
bevy_sprite = { path = "../bevy_sprite" }
|
||||||
|
|
||||||
ab_glyph = "0.2.2"
|
ab_glyph = "0.2.2"
|
||||||
glam = "0.8.7"
|
glam = "0.8.7"
|
||||||
anyhow = "1.0"
|
anyhow = "1.0"
|
70
crates/bevy_text/src/draw.rs
Normal file
70
crates/bevy_text/src/draw.rs
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
use crate::{Font, FontAtlasSet};
|
||||||
|
use bevy_asset::{Assets, Handle};
|
||||||
|
use bevy_render::{
|
||||||
|
draw::{DrawError, Drawable},
|
||||||
|
Color,
|
||||||
|
};
|
||||||
|
use bevy_sprite::TextureAtlas;
|
||||||
|
use glam::Vec2;
|
||||||
|
|
||||||
|
pub struct TextStyle {
|
||||||
|
pub font_size: f32,
|
||||||
|
pub color: Color,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[allow(dead_code)]
|
||||||
|
pub struct DrawableText<'a> {
|
||||||
|
font_handle: Handle<Font>,
|
||||||
|
fonts: &'a Assets<Font>,
|
||||||
|
font_atlas_sets: &'a Assets<FontAtlasSet>,
|
||||||
|
texture_atlases: &'a Assets<TextureAtlas>,
|
||||||
|
position: Vec2,
|
||||||
|
style: &'a TextStyle,
|
||||||
|
text: &'a str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> DrawableText<'a> {
|
||||||
|
pub fn new(
|
||||||
|
font_handle: Handle<Font>,
|
||||||
|
fonts: &'a Assets<Font>,
|
||||||
|
font_atlas_sets: &'a Assets<FontAtlasSet>,
|
||||||
|
texture_atlases: &'a Assets<TextureAtlas>,
|
||||||
|
position: Vec2,
|
||||||
|
style: &'a TextStyle,
|
||||||
|
text: &'a str,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
font_handle,
|
||||||
|
fonts,
|
||||||
|
font_atlas_sets,
|
||||||
|
texture_atlases,
|
||||||
|
position,
|
||||||
|
style,
|
||||||
|
text,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Drawable for DrawableText<'a> {
|
||||||
|
fn draw(&mut self, _draw: &mut bevy_render::draw::DrawContext) -> Result<(), DrawError> {
|
||||||
|
// draw.set_pipeline(bevy_sprite::SPRITE_SHEET_PIPELINE_HANDLE)?;
|
||||||
|
// let render_resource_context = draw.render_resource_context;
|
||||||
|
// // TODO: add draw.set_mesh(slot)
|
||||||
|
// let quad_vertex_buffer = render_resource_context
|
||||||
|
// .get_asset_resource(bevy_sprite::QUAD_HANDLE, mesh::VERTEX_BUFFER_ASSET_INDEX)
|
||||||
|
// .unwrap();
|
||||||
|
// let quad_index_buffer = render_resource_context
|
||||||
|
// .get_asset_resource(bevy_sprite::QUAD_HANDLE, mesh::INDEX_BUFFER_ASSET_INDEX)
|
||||||
|
// .unwrap();
|
||||||
|
// draw.set_vertex_buffer(0, quad_vertex_buffer, 0);
|
||||||
|
// draw.set_index_buffer(quad_index_buffer, 0);
|
||||||
|
// draw.set_global_bind_groups()?;
|
||||||
|
|
||||||
|
// // TODO: ideally the TexureAtlas bind group is automatically generated by AssetRenderResourcesNode and is retrievable
|
||||||
|
// // here using render_resource_context.get_asset_render_resource_set(texture_atlas)
|
||||||
|
// let mut atlas_set = RenderResourceSet::build()
|
||||||
|
// .add_assignment(0, draw.get_uniform_buffer(&10)?)
|
||||||
|
// .finish();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
@ -1,4 +1,4 @@
|
|||||||
use ab_glyph::{FontVec, Glyph, InvalidFont, Point, PxScale, ScaleFont};
|
use ab_glyph::{FontVec, Glyph, InvalidFont, OutlinedGlyph, Point, PxScale, ScaleFont};
|
||||||
use bevy_render::{texture::Texture, Color};
|
use bevy_render::{texture::Texture, Color};
|
||||||
use glam::Vec2;
|
use glam::Vec2;
|
||||||
|
|
||||||
@ -15,6 +15,39 @@ impl Font {
|
|||||||
Ok(Font { font })
|
Ok(Font { font })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn get_outlined_glyph_texture(outlined_glyph: OutlinedGlyph) -> Texture {
|
||||||
|
let bounds = outlined_glyph.px_bounds();
|
||||||
|
let width = bounds.width() as usize;
|
||||||
|
let height = bounds.height() as usize;
|
||||||
|
let mut alpha = vec![0.0; width * height];
|
||||||
|
outlined_glyph.draw(|x, y, v| {
|
||||||
|
alpha[y as usize * width + x as usize] = v;
|
||||||
|
});
|
||||||
|
|
||||||
|
// TODO: make this texture grayscale
|
||||||
|
let color = Color::WHITE;
|
||||||
|
let color_u8 = [
|
||||||
|
(color.r * 255.0) as u8,
|
||||||
|
(color.g * 255.0) as u8,
|
||||||
|
(color.b * 255.0) as u8,
|
||||||
|
];
|
||||||
|
Texture::new(
|
||||||
|
alpha
|
||||||
|
.iter()
|
||||||
|
.map(|a| {
|
||||||
|
vec![
|
||||||
|
color_u8[0],
|
||||||
|
color_u8[1],
|
||||||
|
color_u8[2],
|
||||||
|
(color.a * a * 255.0) as u8,
|
||||||
|
]
|
||||||
|
})
|
||||||
|
.flatten()
|
||||||
|
.collect::<Vec<u8>>(),
|
||||||
|
Vec2::new(width as f32, height as f32),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// adapted from ab_glyph example: https://github.com/alexheretic/ab-glyph/blob/master/dev/examples/image.rs
|
// adapted from ab_glyph example: https://github.com/alexheretic/ab-glyph/blob/master/dev/examples/image.rs
|
||||||
pub fn render_text(
|
pub fn render_text(
|
||||||
&self,
|
&self,
|
||||||
@ -75,7 +108,7 @@ impl Font {
|
|||||||
})
|
})
|
||||||
.flatten()
|
.flatten()
|
||||||
.collect::<Vec<u8>>(),
|
.collect::<Vec<u8>>(),
|
||||||
Vec2::new(width as f32, height as f32)
|
Vec2::new(width as f32, height as f32),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
49
crates/bevy_text/src/font_atlas.rs
Normal file
49
crates/bevy_text/src/font_atlas.rs
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
use bevy_asset::{Assets, Handle};
|
||||||
|
use bevy_render::texture::Texture;
|
||||||
|
use bevy_sprite::{DynamicTextureAtlasBuilder, TextureAtlas};
|
||||||
|
use glam::Vec2;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
pub struct FontAtlas {
|
||||||
|
pub dynamic_texture_atlas_builder: DynamicTextureAtlasBuilder,
|
||||||
|
pub glyph_to_index: HashMap<char, u32>,
|
||||||
|
pub texture_atlas: Handle<TextureAtlas>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FontAtlas {
|
||||||
|
pub fn new(
|
||||||
|
textures: &mut Assets<Texture>,
|
||||||
|
texture_atlases: &mut Assets<TextureAtlas>,
|
||||||
|
size: Vec2,
|
||||||
|
) -> FontAtlas {
|
||||||
|
let atlas_texture = textures.add(Texture::new_fill(size, &[0, 0, 0, 0]));
|
||||||
|
let texture_atlas = TextureAtlas::new_empty(atlas_texture, size);
|
||||||
|
Self {
|
||||||
|
texture_atlas: texture_atlases.add(texture_atlas),
|
||||||
|
glyph_to_index: HashMap::new(),
|
||||||
|
dynamic_texture_atlas_builder: DynamicTextureAtlasBuilder::new(size),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_char_index(&self, character: char) -> Option<u32> {
|
||||||
|
self.glyph_to_index.get(&character).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_char(
|
||||||
|
&mut self,
|
||||||
|
textures: &mut Assets<Texture>,
|
||||||
|
texture_atlases: &mut Assets<TextureAtlas>,
|
||||||
|
character: char,
|
||||||
|
texture: &Texture,
|
||||||
|
) {
|
||||||
|
let texture_atlas = texture_atlases.get_mut(&self.texture_atlas).unwrap();
|
||||||
|
if let Some(index) =
|
||||||
|
self.dynamic_texture_atlas_builder
|
||||||
|
.add_texture(texture_atlas, textures, texture)
|
||||||
|
{
|
||||||
|
self.glyph_to_index.insert(character, index);
|
||||||
|
} else {
|
||||||
|
panic!("ran out of space in font atlas");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
84
crates/bevy_text/src/font_atlas_set.rs
Normal file
84
crates/bevy_text/src/font_atlas_set.rs
Normal file
@ -0,0 +1,84 @@
|
|||||||
|
use crate::{Font, FontAtlas};
|
||||||
|
use ab_glyph::ScaleFont;
|
||||||
|
use bevy_asset::{Assets, Handle};
|
||||||
|
use bevy_core::float_ord::FloatOrd;
|
||||||
|
use bevy_render::texture::Texture;
|
||||||
|
use bevy_sprite::TextureAtlas;
|
||||||
|
use glam::Vec2;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
// work around rust's f32 order/hash limitations
|
||||||
|
type FontSizeKey = FloatOrd;
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct FontAtlasSet {
|
||||||
|
font: Handle<Font>,
|
||||||
|
font_atlases: HashMap<FontSizeKey, FontAtlas>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct GlyphAtlasInfo {
|
||||||
|
pub texture_atlas: Handle<TextureAtlas>,
|
||||||
|
pub char_index: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FontAtlasSet {
|
||||||
|
pub fn new(font: Handle<Font>) -> Self {
|
||||||
|
Self {
|
||||||
|
font,
|
||||||
|
font_atlases: HashMap::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn iter(&self) -> impl Iterator<Item = (&FontSizeKey, &FontAtlas)> {
|
||||||
|
self.font_atlases.iter()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn has_char(&self, character: char, font_size: f32) -> bool {
|
||||||
|
self.font_atlases
|
||||||
|
.get(&FloatOrd(font_size))
|
||||||
|
.map_or(false, |font_atlas| {
|
||||||
|
font_atlas.get_char_index(character).is_some()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn add_glyphs_to_atlas(
|
||||||
|
&mut self,
|
||||||
|
fonts: &Assets<Font>,
|
||||||
|
texture_atlases: &mut Assets<TextureAtlas>,
|
||||||
|
textures: &mut Assets<Texture>,
|
||||||
|
font_size: f32,
|
||||||
|
text: &str,
|
||||||
|
) {
|
||||||
|
let font = fonts.get(&self.font).unwrap();
|
||||||
|
let scaled_font = ab_glyph::Font::as_scaled(&font.font, font_size);
|
||||||
|
let font_atlas = self
|
||||||
|
.font_atlases
|
||||||
|
.entry(FloatOrd(font_size))
|
||||||
|
.or_insert_with(|| FontAtlas::new(textures, texture_atlases, Vec2::new(512.0, 512.0)));
|
||||||
|
for character in text.chars() {
|
||||||
|
if character.is_control() || font_atlas.get_char_index(character).is_some() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let glyph = scaled_font.scaled_glyph(character);
|
||||||
|
if let Some(outlined_glyph) = scaled_font.outline_glyph(glyph) {
|
||||||
|
let glyph_texture = Font::get_outlined_glyph_texture(outlined_glyph);
|
||||||
|
font_atlas.add_char(textures, texture_atlases, character, &glyph_texture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_glyph_atlas_info(&self, font_size: f32, character: char) -> Option<GlyphAtlasInfo> {
|
||||||
|
self.font_atlases
|
||||||
|
.get(&FloatOrd(font_size))
|
||||||
|
.and_then(|font_atlas| {
|
||||||
|
font_atlas
|
||||||
|
.get_char_index(character)
|
||||||
|
.map(|char_index| GlyphAtlasInfo {
|
||||||
|
texture_atlas: font_atlas.texture_atlas,
|
||||||
|
char_index,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
@ -1,8 +1,15 @@
|
|||||||
mod font;
|
mod font;
|
||||||
mod font_loader;
|
mod font_loader;
|
||||||
|
mod font_atlas;
|
||||||
|
mod font_atlas_set;
|
||||||
|
mod draw;
|
||||||
|
|
||||||
pub use font::*;
|
pub use font::*;
|
||||||
pub use font_loader::*;
|
pub use font_loader::*;
|
||||||
|
pub use font_atlas::*;
|
||||||
|
pub use font_atlas_set::*;
|
||||||
|
pub use draw::*;
|
||||||
|
|
||||||
|
|
||||||
use bevy_app::{AppBuilder, AppPlugin};
|
use bevy_app::{AppBuilder, AppPlugin};
|
||||||
use bevy_asset::AddAsset;
|
use bevy_asset::AddAsset;
|
||||||
@ -13,6 +20,7 @@ pub struct TextPlugin;
|
|||||||
impl AppPlugin for TextPlugin {
|
impl AppPlugin for TextPlugin {
|
||||||
fn build(&self, app: &mut AppBuilder) {
|
fn build(&self, app: &mut AppBuilder) {
|
||||||
app.add_asset::<Font>()
|
app.add_asset::<Font>()
|
||||||
|
.add_asset::<FontAtlasSet>()
|
||||||
.add_asset_loader::<Font, FontLoader>();
|
.add_asset_loader::<Font, FontLoader>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -23,7 +23,8 @@ pub struct UiPlugin;
|
|||||||
impl AppPlugin for UiPlugin {
|
impl AppPlugin for UiPlugin {
|
||||||
fn build(&self, app: &mut AppBuilder) {
|
fn build(&self, app: &mut AppBuilder) {
|
||||||
app.add_system_to_stage(stage::POST_UPDATE, ui_update_system())
|
app.add_system_to_stage(stage::POST_UPDATE, ui_update_system())
|
||||||
.add_system_to_stage(stage::POST_UPDATE, Label::label_system.system());
|
.add_system_to_stage(stage::POST_UPDATE, Label::label_system.system())
|
||||||
|
.add_system_to_stage(bevy_render::stage::DRAW, Label::draw_label_system.system());
|
||||||
|
|
||||||
let resources = app.resources();
|
let resources = app.resources();
|
||||||
let mut render_graph = resources.get_mut::<RenderGraph>().unwrap();
|
let mut render_graph = resources.get_mut::<RenderGraph>().unwrap();
|
||||||
|
@ -1,22 +1,30 @@
|
|||||||
use bevy_asset::{Assets, Handle};
|
use bevy_asset::{Assets, Handle};
|
||||||
use bevy_render::{texture::Texture, Color};
|
use bevy_render::{
|
||||||
use bevy_sprite::{ColorMaterial, Quad};
|
draw::Draw,
|
||||||
use bevy_text::Font;
|
pipeline::PipelineDescriptor,
|
||||||
|
render_resource::{RenderResourceAssignments, SharedBuffers},
|
||||||
|
renderer::RenderResources,
|
||||||
|
texture::Texture,
|
||||||
|
Color,
|
||||||
|
};
|
||||||
|
use bevy_sprite::{ColorMaterial, ComMut, Quad, TextureAtlas};
|
||||||
|
use bevy_text::{Font, FontAtlasSet, TextStyle};
|
||||||
use legion::prelude::{Com, Res, ResMut};
|
use legion::prelude::{Com, Res, ResMut};
|
||||||
|
|
||||||
pub struct Label {
|
pub struct Label {
|
||||||
pub text: String,
|
pub text: String,
|
||||||
pub color: Color,
|
|
||||||
pub font_size: f32,
|
|
||||||
pub font: Handle<Font>,
|
pub font: Handle<Font>,
|
||||||
|
pub style: TextStyle,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Label {
|
impl Default for Label {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Label {
|
Label {
|
||||||
text: String::new(),
|
text: String::new(),
|
||||||
color: Color::WHITE,
|
style: TextStyle {
|
||||||
font_size: 12.0,
|
color: Color::WHITE,
|
||||||
|
font_size: 12.0,
|
||||||
|
},
|
||||||
font: Handle::default(),
|
font: Handle::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -28,6 +36,8 @@ impl Label {
|
|||||||
mut color_materials: ResMut<Assets<ColorMaterial>>,
|
mut color_materials: ResMut<Assets<ColorMaterial>>,
|
||||||
mut textures: ResMut<Assets<Texture>>,
|
mut textures: ResMut<Assets<Texture>>,
|
||||||
fonts: Res<Assets<Font>>,
|
fonts: Res<Assets<Font>>,
|
||||||
|
mut font_atlas_sets: ResMut<Assets<FontAtlasSet>>,
|
||||||
|
mut texture_atlases: ResMut<Assets<TextureAtlas>>,
|
||||||
label: Com<Label>,
|
label: Com<Label>,
|
||||||
quad: Com<Quad>,
|
quad: Com<Quad>,
|
||||||
color_material_handle: Com<Handle<ColorMaterial>>,
|
color_material_handle: Com<Handle<ColorMaterial>>,
|
||||||
@ -37,10 +47,21 @@ impl Label {
|
|||||||
let height = quad.size.y().max(1.0);
|
let height = quad.size.y().max(1.0);
|
||||||
|
|
||||||
if let Some(font) = fonts.get(&label.font) {
|
if let Some(font) = fonts.get(&label.font) {
|
||||||
|
let font_atlases = font_atlas_sets
|
||||||
|
.get_or_insert_with(Handle::from_id(label.font.id), || {
|
||||||
|
FontAtlasSet::new(label.font)
|
||||||
|
});
|
||||||
|
font_atlases.add_glyphs_to_atlas(
|
||||||
|
&fonts,
|
||||||
|
&mut texture_atlases,
|
||||||
|
&mut textures,
|
||||||
|
label.style.font_size,
|
||||||
|
&label.text,
|
||||||
|
);
|
||||||
let texture = font.render_text(
|
let texture = font.render_text(
|
||||||
&label.text,
|
&label.text,
|
||||||
label.color,
|
label.style.color,
|
||||||
label.font_size,
|
label.style.font_size,
|
||||||
width as usize,
|
width as usize,
|
||||||
height as usize,
|
height as usize,
|
||||||
);
|
);
|
||||||
@ -55,4 +76,37 @@ impl Label {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn draw_label_system(
|
||||||
|
_pipelines: Res<Assets<PipelineDescriptor>>,
|
||||||
|
_render_resource_assignments: Res<RenderResourceAssignments>,
|
||||||
|
_render_resources: Res<RenderResources>,
|
||||||
|
_shared_buffers: Res<SharedBuffers>,
|
||||||
|
_fonts: Res<Assets<Font>>,
|
||||||
|
_font_atlas_sets: Res<Assets<FontAtlasSet>>,
|
||||||
|
_texture_atlases: Res<Assets<TextureAtlas>>,
|
||||||
|
mut _draw: ComMut<Draw>,
|
||||||
|
_label: Com<Label>,
|
||||||
|
_quad: Com<Quad>,
|
||||||
|
) {
|
||||||
|
// let context = &*render_resources.context;
|
||||||
|
// let mut draw_context = draw.get_context(
|
||||||
|
// &pipelines,
|
||||||
|
// context,
|
||||||
|
// &render_resource_assignments,
|
||||||
|
// &shared_buffers,
|
||||||
|
// );
|
||||||
|
|
||||||
|
// // TODO: getting a font mutably will send out font change events. the atlas should be split from the font to avoid this
|
||||||
|
// let mut drawable_text = DrawableText::new(
|
||||||
|
// label.font,
|
||||||
|
// &fonts,
|
||||||
|
// &font_atlas_sets,
|
||||||
|
// &texture_atlases,
|
||||||
|
// quad.position,
|
||||||
|
// &label.style,
|
||||||
|
// &label.text,
|
||||||
|
// );
|
||||||
|
// draw_context.draw(&mut drawable_text).unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
94
examples/ui/font_atlas_debug.rs
Normal file
94
examples/ui/font_atlas_debug.rs
Normal file
@ -0,0 +1,94 @@
|
|||||||
|
use bevy::{prelude::*, text::FontAtlasSet};
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
App::build()
|
||||||
|
.init_resource::<State>()
|
||||||
|
.add_default_plugins()
|
||||||
|
.add_startup_system(setup.system())
|
||||||
|
.add_system(text_update_system.system())
|
||||||
|
.add_system(atlas_render_system.system())
|
||||||
|
.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
struct State {
|
||||||
|
added: bool,
|
||||||
|
handle: Handle<Font>,
|
||||||
|
timer: Timer,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for State {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
added: false,
|
||||||
|
handle: Handle::default(),
|
||||||
|
timer: Timer::from_seconds(0.05),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn atlas_render_system(
|
||||||
|
command_buffer: &mut CommandBuffer,
|
||||||
|
mut state: ResMut<State>,
|
||||||
|
mut materials: ResMut<Assets<ColorMaterial>>,
|
||||||
|
font_atlas_sets: Res<Assets<FontAtlasSet>>,
|
||||||
|
texture_atlases: Res<Assets<TextureAtlas>>,
|
||||||
|
) {
|
||||||
|
if state.added {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(set) = font_atlas_sets.get(&Handle::from_id(state.handle.id)) {
|
||||||
|
for (_size, atlas) in set.iter() {
|
||||||
|
state.added = true;
|
||||||
|
let atlas = texture_atlases.get(&atlas.texture_atlas).unwrap();
|
||||||
|
command_buffer.build().add_entity(SpriteEntity {
|
||||||
|
material: materials.add(atlas.texture.into()),
|
||||||
|
quad: Quad {
|
||||||
|
position: Vec2::new(-300.0, 0.),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
sprite: Sprite { scale: 1.0 },
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text_update_system(mut state: ResMut<State>, time: Res<Time>, mut label: ComMut<Label>) {
|
||||||
|
state.timer.tick(time.delta_seconds);
|
||||||
|
if state.timer.finished {
|
||||||
|
label.text = format!("{}", rand::random::<u8>() as char);
|
||||||
|
state.timer.reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup(
|
||||||
|
command_buffer: &mut CommandBuffer,
|
||||||
|
asset_server: Res<AssetServer>,
|
||||||
|
mut state: ResMut<State>,
|
||||||
|
) {
|
||||||
|
let font_handle = asset_server.load("assets/fonts/FiraSans-Bold.ttf").unwrap();
|
||||||
|
state.handle = font_handle;
|
||||||
|
command_buffer
|
||||||
|
.build()
|
||||||
|
// 2d camera
|
||||||
|
.add_entity(OrthographicCameraEntity::default())
|
||||||
|
.add_entity(OrthographicCameraEntity::ui())
|
||||||
|
// texture
|
||||||
|
.add_entity(LabelEntity {
|
||||||
|
node: Node::new(
|
||||||
|
math::vec2(0.0, 0.0),
|
||||||
|
Anchors::TOP_LEFT,
|
||||||
|
Margins::new(0.0, 250.0, 0.0, 60.0),
|
||||||
|
),
|
||||||
|
label: Label {
|
||||||
|
text: "a".to_string(),
|
||||||
|
font: font_handle,
|
||||||
|
style: TextStyle {
|
||||||
|
font_size: 60.0,
|
||||||
|
color: Color::WHITE,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
}
|
@ -36,8 +36,10 @@ fn setup(command_buffer: &mut CommandBuffer, asset_server: Res<AssetServer>) {
|
|||||||
label: Label {
|
label: Label {
|
||||||
text: "FPS:".to_string(),
|
text: "FPS:".to_string(),
|
||||||
font: font_handle,
|
font: font_handle,
|
||||||
font_size: 60.0,
|
style: TextStyle {
|
||||||
color: Color::WHITE,
|
font_size: 60.0,
|
||||||
|
color: Color::WHITE,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
|
@ -79,8 +79,10 @@ fn setup(
|
|||||||
label: Label {
|
label: Label {
|
||||||
text: "Text Label".to_string(),
|
text: "Text Label".to_string(),
|
||||||
font: font_handle,
|
font: font_handle,
|
||||||
font_size: 30.0,
|
style: TextStyle {
|
||||||
..Default::default()
|
font_size: 30.0,
|
||||||
|
color: Color::WHITE,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})
|
})
|
||||||
|
@ -35,7 +35,7 @@ pub use crate::{
|
|||||||
entity::{SpriteEntity, SpriteSheetEntity},
|
entity::{SpriteEntity, SpriteSheetEntity},
|
||||||
ColorMaterial, Quad, Sprite, TextureAtlas, TextureAtlasSprite,
|
ColorMaterial, Quad, Sprite, TextureAtlas, TextureAtlasSprite,
|
||||||
},
|
},
|
||||||
text::Font,
|
text::{Font, TextStyle},
|
||||||
transform::prelude::*,
|
transform::prelude::*,
|
||||||
type_registry::RegisterType,
|
type_registry::RegisterType,
|
||||||
ui::{entity::*, widget::Label, Anchors, Margins, Node},
|
ui::{entity::*, widget::Label, Anchors, Margins, Node},
|
||||||
|
Loading…
Reference in New Issue
Block a user