Skip to main content

azalea_entity/plugin/
indexing.rs

1//! Stuff related to entity indexes and keeping track of entities in the world.
2
3use std::{
4    collections::{HashMap, HashSet},
5    fmt::{self, Debug},
6};
7
8use azalea_core::{entity_id::MinecraftEntityId, position::ChunkPos};
9use azalea_world::{World, WorldName, Worlds};
10use bevy_ecs::prelude::*;
11use derive_more::{Deref, DerefMut};
12use nohash_hasher::IntMap;
13use tracing::{debug, trace, warn};
14use uuid::Uuid;
15
16use super::LoadedBy;
17use crate::{EntityUuid, LocalEntity, Position};
18
19#[derive(Default, Resource)]
20pub struct EntityUuidIndex {
21    /// An index of entities by their UUIDs
22    entity_by_uuid: HashMap<Uuid, Entity>,
23}
24impl EntityUuidIndex {
25    pub fn new() -> Self {
26        Self {
27            entity_by_uuid: HashMap::default(),
28        }
29    }
30
31    pub fn get(&self, uuid: &Uuid) -> Option<Entity> {
32        self.entity_by_uuid.get(uuid).copied()
33    }
34
35    pub fn contains_key(&self, uuid: &Uuid) -> bool {
36        self.entity_by_uuid.contains_key(uuid)
37    }
38
39    pub fn insert(&mut self, uuid: Uuid, entity: Entity) {
40        self.entity_by_uuid.insert(uuid, entity);
41    }
42
43    pub fn remove(&mut self, uuid: &Uuid) -> Option<Entity> {
44        self.entity_by_uuid.remove(uuid)
45    }
46}
47
48/// An index of Minecraft entity IDs to Azalea ECS entities.
49///
50/// This is a `Component` so local players can keep track of entity IDs
51/// independently from the world.
52///
53/// If you need a per-world instead of per-client version of this, you can
54/// use [`World::entity_by_id`].
55#[derive(Component, Default)]
56pub struct EntityIdIndex {
57    /// An index of entities by their MinecraftEntityId
58    entity_by_id: IntMap<MinecraftEntityId, Entity>,
59    id_by_entity: HashMap<Entity, MinecraftEntityId>,
60}
61
62impl EntityIdIndex {
63    pub fn get_by_minecraft_entity(&self, id: MinecraftEntityId) -> Option<Entity> {
64        self.entity_by_id.get(&id).copied()
65    }
66    pub fn get_by_ecs_entity(&self, entity: Entity) -> Option<MinecraftEntityId> {
67        self.id_by_entity.get(&entity).copied()
68    }
69
70    pub fn contains_minecraft_entity(&self, id: MinecraftEntityId) -> bool {
71        self.entity_by_id.contains_key(&id)
72    }
73    pub fn contains_ecs_entity(&self, id: Entity) -> bool {
74        self.id_by_entity.contains_key(&id)
75    }
76
77    pub fn insert(&mut self, id: MinecraftEntityId, entity: Entity) {
78        if let Some(previous) = self.entity_by_id.insert(id, entity) {
79            self.id_by_entity.remove(&previous);
80        }
81        if let Some(previous) = self.id_by_entity.insert(entity, id) {
82            self.entity_by_id.remove(&previous);
83        }
84        trace!("Inserted {id} -> {entity:?} into a client's EntityIdIndex");
85    }
86
87    pub fn remove_by_minecraft_entity(&mut self, id: MinecraftEntityId) -> Option<Entity> {
88        if let Some(entity) = self.entity_by_id.remove(&id) {
89            trace!(
90                "Removed {id} -> {entity:?} from a client's EntityIdIndex (using EntityIdIndex::remove)"
91            );
92            self.id_by_entity.remove(&entity);
93            Some(entity)
94        } else {
95            trace!(
96                "Failed to remove {id} from a client's EntityIdIndex (using EntityIdIndex::remove)"
97            );
98            None
99        }
100    }
101
102    pub fn remove_by_ecs_entity(&mut self, entity: Entity) -> Option<MinecraftEntityId> {
103        if let Some(id) = self.id_by_entity.remove(&entity) {
104            trace!(
105                "Removed {id} -> {entity:?} from a client's EntityIdIndex (using EntityIdIndex::remove_by_ecs_entity)."
106            );
107            self.entity_by_id.remove(&id);
108            Some(id)
109        } else {
110            // this is expected to happen when despawning entities if it was
111            // already despawned for another reason (like because the client
112            // received a remove_entities packet, or if we're in a shared world
113            // where entity ids are different for each client)
114            trace!(
115                "Failed to remove {entity:?} from a client's EntityIdIndex (using EntityIdIndex::remove_by_ecs_entity). This may be expected behavior."
116            );
117            None
118        }
119    }
120}
121
122impl Debug for EntityUuidIndex {
123    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124        f.debug_struct("EntityUuidIndex").finish()
125    }
126}
127
128/// The chunk position that an entity is currently in.
129#[derive(Component, Debug, Deref, DerefMut)]
130pub struct EntityChunkPos(pub ChunkPos);
131
132/// Update the chunk position indexes in [`World::entities_by_chunk`].
133///
134/// [`World::entities_by_chunk`]: azalea_world::World::entities_by_chunk
135pub fn update_entity_chunk_positions(
136    mut query: Query<(Entity, &Position, &WorldName, &mut EntityChunkPos), Changed<Position>>,
137    worlds: Res<Worlds>,
138) {
139    for (entity, pos, world_name, mut entity_chunk_pos) in query.iter_mut() {
140        let old_chunk = **entity_chunk_pos;
141        let new_chunk = ChunkPos::from(*pos);
142        if old_chunk != new_chunk {
143            **entity_chunk_pos = new_chunk;
144
145            if old_chunk != new_chunk {
146                let Some(world_lock) = worlds.get(world_name) else {
147                    continue;
148                };
149                let mut world = world_lock.write();
150
151                // move the entity from the old chunk to the new one
152                if let Some(entities) = world.entities_by_chunk.get_mut(&old_chunk) {
153                    entities.remove(&entity);
154                }
155                world
156                    .entities_by_chunk
157                    .entry(new_chunk)
158                    .or_default()
159                    .insert(entity);
160                trace!("Entity {entity:?} moved from {old_chunk:?} to {new_chunk:?}");
161            }
162        }
163    }
164}
165
166/// Insert new entities into [`World::entities_by_chunk`].
167pub fn insert_entity_chunk_position(
168    query: Query<(Entity, &Position, &WorldName), Added<EntityChunkPos>>,
169    worlds: Res<Worlds>,
170) {
171    for (entity, pos, world_name) in query.iter() {
172        let Some(world_lock) = worlds.get(world_name) else {
173            // entity must've been despawned already
174            continue;
175        };
176        let mut world = world_lock.write();
177
178        let chunk = ChunkPos::from(*pos);
179        world
180            .entities_by_chunk
181            .entry(chunk)
182            .or_default()
183            .insert(entity);
184    }
185}
186
187/// Despawn entities that aren't being loaded by anything.
188#[allow(clippy::type_complexity)]
189pub fn remove_despawned_entities_from_indexes(
190    mut commands: Commands,
191    mut entity_uuid_index: ResMut<EntityUuidIndex>,
192    worlds: Res<Worlds>,
193    query: Query<
194        (
195            Entity,
196            &EntityUuid,
197            &MinecraftEntityId,
198            &EntityChunkPos,
199            &WorldName,
200            &LoadedBy,
201        ),
202        (Changed<LoadedBy>, Without<LocalEntity>),
203    >,
204    mut entity_id_index_query: Query<&mut EntityIdIndex>,
205) {
206    for (entity, uuid, minecraft_id, chunk_pos, world_name, loaded_by) in &query {
207        let Some(world_lock) = worlds.get(world_name) else {
208            // the world isn't even loaded by any of our clients, so we can
209            // safely delete the entity
210            debug!("Despawned entity {entity:?} because it's in a world that isn't loaded anymore");
211
212            despawn_entity(
213                entity,
214                **uuid,
215                *minecraft_id,
216                **chunk_pos,
217                None,
218                &mut commands,
219                &mut entity_uuid_index,
220                &mut entity_id_index_query,
221            );
222            continue;
223        };
224
225        // if the entity is being loaded by any of our clients, don't despawn it
226        if !loaded_by.is_empty() {
227            continue;
228        }
229
230        let mut world = world_lock.write();
231        despawn_entity(
232            entity,
233            **uuid,
234            *minecraft_id,
235            **chunk_pos,
236            Some(&mut world),
237            &mut commands,
238            &mut entity_uuid_index,
239            &mut entity_id_index_query,
240        );
241    }
242}
243
244#[allow(clippy::too_many_arguments)]
245fn despawn_entity(
246    entity: Entity,
247    uuid: Uuid,
248    minecraft_id: MinecraftEntityId,
249    chunk: ChunkPos,
250    world: Option<&mut World>,
251    commands: &mut Commands,
252    entity_uuid_index: &mut ResMut<EntityUuidIndex>,
253    entity_id_index_query: &mut Query<&mut EntityIdIndex>,
254) {
255    if let Some(world) = world {
256        remove_entity_from_chunk_index(world, chunk, entity);
257
258        if world.entity_by_id.remove(&minecraft_id).is_none() {
259            debug!(
260                "Tried to remove entity {entity:?} from the per-world entity id index but it was not there. This may be expected if you're in a shared world."
261            );
262        }
263    }
264
265    // remove it from the uuid index
266    if entity_uuid_index.entity_by_uuid.remove(&uuid).is_none() {
267        warn!("Tried to remove entity {entity:?} from the uuid index but it was not there.");
268    }
269
270    // remove it from every client's EntityIdIndex
271    for mut entity_id_index in entity_id_index_query.iter_mut() {
272        entity_id_index.remove_by_ecs_entity(entity);
273    }
274
275    // and now remove the entity from the ecs
276    commands.entity(entity).despawn();
277    debug!("Despawned entity {entity:?} because it was not loaded by anything.");
278}
279
280fn remove_entity_from_chunk_index(world: &mut World, chunk: ChunkPos, entity: Entity) {
281    if let Some(entities_in_chunk) = world.entities_by_chunk.get_mut(&chunk) {
282        if entities_in_chunk.remove(&entity) {
283            // remove the chunk if there's no entities in it anymore
284            if entities_in_chunk.is_empty() {
285                world.entities_by_chunk.remove(&chunk);
286            }
287        } else {
288            // search all the other chunks for it :(
289            let mut found_in_other_chunks = HashSet::new();
290            for (other_chunk, entities_in_other_chunk) in &mut world.entities_by_chunk {
291                if entities_in_other_chunk.remove(&entity) {
292                    found_in_other_chunks.insert(other_chunk);
293                }
294            }
295            if found_in_other_chunks.is_empty() {
296                warn!(
297                    "Tried to remove entity {entity:?} from chunk {chunk:?} but the entity was not there or in any other chunks."
298                );
299            } else {
300                warn!(
301                    "Tried to remove entity {entity:?} from chunk {chunk:?} but the entity was not there. Found in and removed from other chunk(s): {found_in_other_chunks:?}"
302                );
303            }
304        }
305    } else {
306        let mut found_in_other_chunks = HashSet::new();
307        for (other_chunk, entities_in_other_chunk) in &mut world.entities_by_chunk {
308            if entities_in_other_chunk.remove(&entity) {
309                found_in_other_chunks.insert(other_chunk);
310            }
311        }
312        if found_in_other_chunks.is_empty() {
313            warn!(
314                "Tried to remove entity {entity:?} from chunk {chunk:?} but the chunk was not found and the entity wasn't in any other chunks."
315            );
316        } else {
317            warn!(
318                "Tried to remove entity {entity:?} from chunk {chunk:?} but the chunk was not found. Entity found in and removed from other chunk(s): {found_in_other_chunks:?}"
319            );
320        }
321    }
322}
323
324pub fn add_entity_to_indexes(
325    entity_id: MinecraftEntityId,
326    ecs_entity: Entity,
327    entity_uuid: Option<Uuid>,
328    entity_id_index: &mut EntityIdIndex,
329    entity_uuid_index: &mut EntityUuidIndex,
330    world: &mut World,
331) {
332    // per-client id index
333    entity_id_index.insert(entity_id, ecs_entity);
334
335    // per-world id index
336    world.entity_by_id.insert(entity_id, ecs_entity);
337
338    if let Some(uuid) = entity_uuid {
339        // per-world uuid index
340        entity_uuid_index.insert(uuid, ecs_entity);
341    }
342}