Skip to content

Commit b2e2f8d

Browse files
authored
TextureAtlasBuilder now respects insertion order (#11474)
# Objective TextureAtlases are commonly used to drive animations described as a consecutive range of indices. The current TextureAtlasBuilder uses the AssetId of the image to determine the index of the texture in the TextureAtlas. The AssetId of an Image Asset can change between runs. The TextureAtlas exposes [`get_texture_index`](https://docs.rs/bevy/latest/bevy/sprite/struct.TextureAtlas.html#method.get_texture_index) to get the index from a given AssetId, but this needlessly complicates the process of creating a simple TextureAtlas animation. Fixes #2459 ## Solution - Use the (ordered) image_ids of the 'texture to place' vector to retrieve the packed locations and compose the textures of the TextureAtlas.
1 parent f8191be commit b2e2f8d

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

crates/bevy_sprite/src/texture_atlas_builder.rs

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,8 @@ impl TextureAtlasBuilder {
8484
}
8585

8686
/// Adds a texture to be copied to the texture atlas.
87+
///
88+
/// The insertion order will reflect the index of the added texture in the finished texture atlas.
8789
pub fn add_texture(&mut self, image_id: AssetId<Image>, texture: &Image) {
8890
self.textures_to_place
8991
.push((image_id, texture.texture_descriptor.size));
@@ -150,6 +152,7 @@ impl TextureAtlasBuilder {
150152
/// Consumes the builder, and returns the newly created texture handle and
151153
/// the assciated atlas layout.
152154
///
155+
/// Assigns indices to the textures based on the insertion order.
153156
/// Internally it copies all rectangles from the textures and copies them
154157
/// into a new texture.
155158
/// It is not useful to hold a strong handle to the texture afterwards else
@@ -259,7 +262,10 @@ impl TextureAtlasBuilder {
259262

260263
let mut texture_rects = Vec::with_capacity(rect_placements.packed_locations().len());
261264
let mut texture_ids = HashMap::default();
262-
for (image_id, (_, packed_location)) in rect_placements.packed_locations() {
265+
// We iterate through the textures to place to respect the insertion order for the texture indices
266+
for (image_id, _) in &self.textures_to_place {
267+
let (_, packed_location) = rect_placements.packed_locations().get(image_id).unwrap();
268+
263269
let texture = textures.get(*image_id).unwrap();
264270
let min = Vec2::new(packed_location.x() as f32, packed_location.y() as f32);
265271
let max = min

0 commit comments

Comments
 (0)