Skip to content

Commit

Permalink
text: font atlas generation. initial Drawable boilerplate. temporary …
Browse files Browse the repository at this point in the history
…font atlas debug example
  • Loading branch information
cart committed Jun 14, 2020
1 parent 5f0363a commit 516cf9d
Show file tree
Hide file tree
Showing 17 changed files with 493 additions and 120 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,10 @@ path = "examples/shader/shader_defs.rs"
name = "text"
path = "examples/ui/text.rs"

[[example]]
name = "font_atlas_debug"
path = "examples/ui/font_atlas_debug.rs"

[[example]]
name = "ui"
path = "examples/ui/ui.rs"
Expand Down
146 changes: 49 additions & 97 deletions crates/bevy_sprite/src/dynamic_texture_atlas_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,123 +6,79 @@ use guillotiere::{size2, AllocId, Allocation, AtlasAllocator};
use std::collections::HashMap;

pub struct DynamicTextureAtlasBuilder {
pub texture_allocations: HashMap<Handle<Texture>, Allocation>,
pub allocation_textures: HashMap<AllocId, Handle<Texture>>,
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
impl DynamicTextureAtlasBuilder {
pub fn new(initial_size: Vec2, max_size: Vec2) -> Self {
pub fn new(size: Vec2) -> Self {
Self {
texture_allocations: Default::default(),
allocation_textures: Default::default(),
atlas_allocator: AtlasAllocator::new(to_size2(initial_size)),
atlas_texture: Texture::new_fill(initial_size, &[0,0,0,0]),
max_size,
atlas_allocator: AtlasAllocator::new(to_size2(size)),
}
}

pub fn add_texture(&mut self, texture_handle: Handle<Texture>, textures: &Assets<Texture>) -> bool {
let texture = textures.get(&texture_handle).unwrap();
let mut queued_textures= vec![texture_handle];
let mut resized = false;
loop {
let mut failed_textures = Vec::new();
while let Some(texture_handle) = queued_textures.pop() {
let allocation = self
.atlas_allocator
.allocate(size2(texture.size.x() as i32, texture.size.y() as i32));
if let Some(allocation) = allocation {
self.place_texture(allocation, texture_handle, texture);
} else {
failed_textures.push(texture_handle);
}
}

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);
}
pub fn add_texture(
&mut self,
texture_atlas: &mut TextureAtlas,
textures: &mut Assets<Texture>,
texture: &Texture,
) -> Option<u32> {
let allocation = self
.atlas_allocator
.allocate(size2(texture.size.x() as i32, texture.size.y() as i32));
if let Some(allocation) = allocation {
let atlas_texture = textures.get_mut(&texture_atlas.texture).unwrap();
self.place_texture(atlas_texture, allocation, texture);
texture_atlas.add_texture(allocation.rectangle.into());
Some((texture_atlas.len() - 1) as u32)
} else {
None
}

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 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;

for (texture_y, bound_y) in (rect.min.y..rect.max.y).map(|i| i as usize).enumerate() {
let begin = (bound_y * atlas_width + rect.min.x as usize) * FORMAT_SIZE;
let end = begin + rect_width * FORMAT_SIZE;
let texture_begin = texture_y * 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]);
}

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),
}
}
}

Expand All @@ -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 {
guillotiere::Size::new(vec2.x() as i32, vec2.y() as i32)
}
6 changes: 3 additions & 3 deletions crates/bevy_sprite/src/render/sprite_sheet.vert
Original file line number Diff line number Diff line change
Expand Up @@ -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
layout(set = 1, binding = 0) uniform TextureAtlas_dimensions {
vec2 Dimensions;
layout(set = 1, binding = 0) uniform TextureAtlas_size {
vec2 AtlasSize;
};

struct Rect {
Expand Down Expand Up @@ -41,6 +41,6 @@ void main() {
vec2(sprite_rect.end.x, sprite_rect.begin.y),
sprite_rect.end
);
v_Uv = uvs[gl_VertexIndex] / Dimensions;
v_Uv = uvs[gl_VertexIndex] / AtlasSize;
gl_Position = ViewProj * vec4(vertex_position, 1.0);
}
21 changes: 19 additions & 2 deletions crates/bevy_sprite/src/texture_atlas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use std::collections::HashMap;
pub struct TextureAtlas {
pub texture: Handle<Texture>,
// TODO: add support to Uniforms derive to write dimensions and sprites to the same buffer
pub dimensions: Vec2,
pub size: Vec2,
#[render_resources(buffer)]
pub textures: Vec<Rect>,
#[render_resources(ignore)]
Expand All @@ -30,6 +30,15 @@ pub struct TextureAtlasSprite {
}

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(
texture: Handle<Texture>,
size: Vec2,
Expand All @@ -51,13 +60,21 @@ impl TextureAtlas {
}
}
TextureAtlas {
dimensions: size,
size,
textures: sprites,
texture,
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> {
self.texture_handles
.as_ref()
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_sprite/src/texture_atlas_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ impl TextureAtlasBuilder {
self.place_texture(&mut atlas_texture, texture, packed_location);
}
Ok(TextureAtlas {
dimensions: atlas_texture.size,
size: atlas_texture.size,
texture: textures.add(atlas_texture),
textures: texture_rects,
texture_handles: Some(texture_handles),
Expand Down
3 changes: 3 additions & 0 deletions crates/bevy_text/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,11 @@ edition = "2018"

[dependencies]
bevy_app = { path = "../bevy_app" }
bevy_core = { path = "../bevy_core" }
bevy_asset = { path = "../bevy_asset" }
bevy_render = { path = "../bevy_render" }
bevy_sprite = { path = "../bevy_sprite" }

ab_glyph = "0.2.2"
glam = "0.8.7"
anyhow = "1.0"
70 changes: 70 additions & 0 deletions crates/bevy_text/src/draw.rs
Original file line number Diff line number Diff line change
@@ -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(())
}
}
Loading

0 comments on commit 516cf9d

Please sign in to comment.