Path: blob/main/crates/bevy_image/src/dynamic_texture_atlas_builder.rs
6595 views
use crate::{Image, TextureAccessError, TextureAtlasLayout, TextureFormatPixelInfo as _};1use bevy_asset::RenderAssetUsages;2use bevy_math::{URect, UVec2};3use guillotiere::{size2, Allocation, AtlasAllocator};4use thiserror::Error;5use tracing::error;67/// An error produced by [`DynamicTextureAtlasBuilder`] when trying to add a new8/// texture to a [`TextureAtlasLayout`].9#[derive(Debug, Error)]10pub enum DynamicTextureAtlasBuilderError {11/// Unable to allocate space within the atlas for the new texture12#[error("Couldn't allocate space to add the image requested")]13FailedToAllocateSpace,14/// Attempted to add a texture to an uninitialized atlas15#[error("cannot add texture to uninitialized atlas texture")]16UninitializedAtlas,17/// Attempted to add an uninitialized texture to an atlas18#[error("cannot add uninitialized texture to atlas")]19UninitializedSourceTexture,20/// A texture access error occurred21#[error("texture access error: {0}")]22TextureAccess(#[from] TextureAccessError),23}2425/// Helper utility to update [`TextureAtlasLayout`] on the fly.26///27/// Helpful in cases when texture is created procedurally,28/// e.g: in a font glyph [`TextureAtlasLayout`], only add the [`Image`] texture for letters to be rendered.29pub struct DynamicTextureAtlasBuilder {30atlas_allocator: AtlasAllocator,31padding: u32,32}3334impl DynamicTextureAtlasBuilder {35/// Create a new [`DynamicTextureAtlasBuilder`]36///37/// # Arguments38///39/// * `size` - total size for the atlas40/// * `padding` - gap added between textures in the atlas, both in x axis and y axis41pub fn new(size: UVec2, padding: u32) -> Self {42Self {43atlas_allocator: AtlasAllocator::new(to_size2(size)),44padding,45}46}4748/// Add a new texture to `atlas_layout`.49///50/// It is the user's responsibility to pass in the correct [`TextureAtlasLayout`].51/// Also, the asset that `atlas_texture_handle` points to must have a usage matching52/// [`RenderAssetUsages::MAIN_WORLD`].53///54/// # Arguments55///56/// * `atlas_layout` - The atlas layout to add the texture to.57/// * `texture` - The source texture to add to the atlas.58/// * `atlas_texture` - The destination atlas texture to copy the source texture to.59pub fn add_texture(60&mut self,61atlas_layout: &mut TextureAtlasLayout,62texture: &Image,63atlas_texture: &mut Image,64) -> Result<usize, DynamicTextureAtlasBuilderError> {65let allocation = self.atlas_allocator.allocate(size2(66(texture.width() + self.padding).try_into().unwrap(),67(texture.height() + self.padding).try_into().unwrap(),68));69if let Some(allocation) = allocation {70assert!(71atlas_texture.asset_usage.contains(RenderAssetUsages::MAIN_WORLD),72"The atlas_texture image must have the RenderAssetUsages::MAIN_WORLD usage flag set"73);7475self.place_texture(atlas_texture, allocation, texture)?;76let mut rect: URect = to_rect(allocation.rectangle);77rect.max = rect.max.saturating_sub(UVec2::splat(self.padding));78Ok(atlas_layout.add_texture(rect))79} else {80Err(DynamicTextureAtlasBuilderError::FailedToAllocateSpace)81}82}8384fn place_texture(85&mut self,86atlas_texture: &mut Image,87allocation: Allocation,88texture: &Image,89) -> Result<(), DynamicTextureAtlasBuilderError> {90let mut rect = allocation.rectangle;91rect.max.x -= self.padding as i32;92rect.max.y -= self.padding as i32;93let atlas_width = atlas_texture.width() as usize;94let rect_width = rect.width() as usize;95let format_size = atlas_texture.texture_descriptor.format.pixel_size()?;9697let Some(ref mut atlas_data) = atlas_texture.data else {98return Err(DynamicTextureAtlasBuilderError::UninitializedAtlas);99};100let Some(ref data) = texture.data else {101return Err(DynamicTextureAtlasBuilderError::UninitializedSourceTexture);102};103for (texture_y, bound_y) in (rect.min.y..rect.max.y).map(|i| i as usize).enumerate() {104let begin = (bound_y * atlas_width + rect.min.x as usize) * format_size;105let end = begin + rect_width * format_size;106let texture_begin = texture_y * rect_width * format_size;107let texture_end = texture_begin + rect_width * format_size;108atlas_data[begin..end].copy_from_slice(&data[texture_begin..texture_end]);109}110Ok(())111}112}113114fn to_rect(rectangle: guillotiere::Rectangle) -> URect {115URect {116min: UVec2::new(117rectangle.min.x.try_into().unwrap(),118rectangle.min.y.try_into().unwrap(),119),120max: UVec2::new(121rectangle.max.x.try_into().unwrap(),122rectangle.max.y.try_into().unwrap(),123),124}125}126127fn to_size2(vec2: UVec2) -> guillotiere::Size {128guillotiere::Size::new(vec2.x as i32, vec2.y as i32)129}130131132