Skip to main content

naia_client/world/
entity_ref.rs

1use std::hash::Hash;
2
3use naia_shared::{EntityAuthStatus, ReplicaRefWrapper, ReplicatedComponent, WorldRefType};
4
5use crate::{world::entity_owner::EntityOwner, Client};
6use naia_shared::Publicity;
7
8/// Scoped read-only handle for a client entity.
9///
10/// Obtained from [`Client::entity`]. Provides read access to components,
11/// replication config, authority status, and ownership without borrowing the
12/// client mutably.
13pub struct EntityRef<'s, E: Copy + Eq + Hash + Send + Sync, W: WorldRefType<E>> {
14    client: &'s Client<E>,
15    world: W,
16    entity: E,
17}
18
19impl<'s, E: Copy + Eq + Hash + Send + Sync, W: WorldRefType<E>> EntityRef<'s, E, W> {
20    /// Creates a new `EntityRef` pointing at `entity` within `world`, backed by `client` for replication queries.
21    pub fn new(client: &'s Client<E>, world: W, entity: &E) -> Self {
22        Self {
23            client,
24            world,
25            entity: *entity,
26        }
27    }
28
29    /// Returns the underlying entity identifier.
30    pub fn id(&self) -> E {
31        self.entity
32    }
33
34    /// Returns `true` if the entity currently carries component `R`.
35    pub fn has_component<R: ReplicatedComponent>(&self) -> bool {
36        self.world.has_component::<R>(&self.entity)
37    }
38
39    /// Returns a read-only accessor for component `R`, or `None` if the
40    /// entity does not carry it.
41    pub fn component<R: ReplicatedComponent>(&'_ self) -> Option<ReplicaRefWrapper<'_, R>> {
42        self.world.component::<R>(&self.entity)
43    }
44
45    /// Returns the current [`Publicity`], or `None` if the entity is not
46    /// registered with the replication layer.
47    pub fn replication_config(&self) -> Option<Publicity> {
48        self.client.entity_replication_config(&self.entity)
49    }
50
51    /// Returns the current authority status for this entity, or `None` if the
52    /// entity is not configured as `Delegated`.
53    pub fn authority(&self) -> Option<EntityAuthStatus> {
54        self.client.entity_authority_status(&self.entity)
55    }
56
57    /// Returns the current [`EntityOwner`] — who holds authoritative control
58    /// over this entity right now.
59    pub fn owner(&self) -> EntityOwner {
60        self.client.entity_owner(&self.entity)
61    }
62}
63
64cfg_if! {
65    if #[cfg(feature = "interior_visibility")] {
66
67        use naia_shared::LocalEntity;
68
69        impl<'s, E: Copy + Eq + Hash + Send + Sync, W: WorldRefType<E>> EntityRef<'s, E, W> {
70
71            /// Returns the [`LocalEntity`] id the server assigned to this
72            /// entity, if it is currently in scope.
73            ///
74            /// Only available with the `interior_visibility` feature.
75            pub fn local_entity(&self) -> Option<LocalEntity> {
76                self.client.world_to_local_entity(&self.entity)
77            }
78        }
79    }
80}