Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Merged by Bors] - Allow iterating over with EntityRef over the entire World #6843

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions crates/bevy_ecs/src/world/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use crate::{
component::{
Component, ComponentDescriptor, ComponentId, ComponentInfo, Components, TickCells,
},
entity::{AllocAtWithoutReplacement, Entities, Entity},
entity::{AllocAtWithoutReplacement, Entities, Entity, EntityLocation},
query::{QueryState, ReadOnlyWorldQuery, WorldQuery},
storage::{ResourceData, SparseSet, Storages},
system::Resource,
Expand Down Expand Up @@ -323,11 +323,20 @@ impl World {
///
/// This is useful in contexts where you only have read-only access to the [`World`].
#[inline]
pub fn iter_entities(&self) -> impl Iterator<Item = Entity> + '_ {
self.archetypes
.iter()
.flat_map(|archetype| archetype.entities().iter())
.map(|archetype_entity| archetype_entity.entity())
pub fn iter_entities(&self) -> impl Iterator<Item = EntityRef<'_>> + '_ {
self.archetypes.iter().flat_map(|archetype| {
archetype
.entities()
.iter()
.enumerate()
.map(|(index, archetype_entity)| {
let location = EntityLocation {
archetype_id: archetype.id(),
index,
};
EntityRef::new(self, archetype_entity.entity(), location)
})
})
}

/// Retrieves an [`EntityMut`] that exposes read and write operations for the given `entity`.
Expand Down Expand Up @@ -1870,7 +1879,7 @@ mod tests {
let iterate_and_count_entities = |world: &World, entity_counters: &mut HashMap<_, _>| {
entity_counters.clear();
for entity in world.iter_entities() {
let counter = entity_counters.entry(entity).or_insert(0);
let counter = entity_counters.entry(entity.id()).or_insert(0);
*counter += 1;
}
};
Expand Down
2 changes: 1 addition & 1 deletion crates/bevy_scene/src/dynamic_scene.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ impl DynamicScene {
let mut builder =
DynamicSceneBuilder::from_world_with_type_registry(world, type_registry.clone());

builder.extract_entities(world.iter_entities());
builder.extract_entities(world.iter_entities().map(|entity| entity.id()));

builder.build()
}
Expand Down