Skip to content

Commit

Permalink
Fix clear last entity alive
Browse files Browse the repository at this point in the history
In the `Entities` vec, an entity is considered alive if its index is equal to its position in the `Entities` vec
`clear` was always setting the last entity index to its position in the vec
This made `clear` always leaving an entity alive, without component
  • Loading branch information
leudz committed Jun 25, 2024
1 parent 853bc7b commit 6adcfc1
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
8 changes: 7 additions & 1 deletion src/entities/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,13 @@ impl Storage for Entities {
return;
}

let mut last_alive = self.data.len() as u64 - 1;
// the first value can be anything but self.data.len() - 1
// otherwise we would set data[len - 1].index to len - 1 and not delete it
let mut last_alive = if self.data.len() as u64 == EntityId::max_index() {
0
} else {
EntityId::max_index()
};
for (i, id) in self.data.iter_mut().enumerate().rev() {
let target = last_alive;
let id_before_bump = *id;
Expand Down
14 changes: 11 additions & 3 deletions tests/clear.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,23 @@ fn no_pack() {

let (mut entities, mut u32s) = world.borrow::<(EntitiesViewMut, ViewMut<U32>)>().unwrap();

entities.add_entity(&mut u32s, U32(0));
entities.add_entity(&mut u32s, U32(1));
entities.add_entity(&mut u32s, U32(2));
let e0 = entities.add_entity(&mut u32s, U32(0));
let e1 = entities.add_entity(&mut u32s, U32(1));
let e2 = entities.add_entity(&mut u32s, U32(2));

drop((entities, u32s));
world.borrow::<AllStoragesViewMut>().unwrap().clear();

let (mut entities, mut u32s) = world.borrow::<(EntitiesViewMut, ViewMut<U32>)>().unwrap();

assert!(u32s.get(e0).is_err());
assert!(u32s.get(e1).is_err());
assert!(u32s.get(e2).is_err());
assert!(!entities.is_alive(e0));
assert!(!entities.is_alive(e1));
assert!(!entities.is_alive(e2));
assert_eq!(entities.iter().count(), 0);

assert_eq!(u32s.len(), 0);
let entity0 = entities.add_entity(&mut u32s, U32(3));
let entity1 = entities.add_entity(&mut u32s, U32(4));
Expand Down

0 comments on commit 6adcfc1

Please sign in to comment.