naia_server/world/
entity_mut.rs

1use std::hash::Hash;
2
3use naia_shared::{EntityAuthStatus, ReplicaMutWrapper, ReplicatedComponent, WorldMutType};
4
5use crate::{room::RoomKey, server::Server, ReplicationConfig};
6
7// EntityMut
8pub struct EntityMut<'s, E: Copy + Eq + Hash + Send + Sync, W: WorldMutType<E>> {
9    server: &'s mut Server<E>,
10    world: W,
11    entity: E,
12}
13
14impl<'s, E: Copy + Eq + Hash + Send + Sync, W: WorldMutType<E>> EntityMut<'s, E, W> {
15    pub(crate) fn new(server: &'s mut Server<E>, world: W, entity: &E) -> Self {
16        EntityMut {
17            server,
18            world,
19            entity: *entity,
20        }
21    }
22
23    pub fn id(&self) -> E {
24        self.entity
25    }
26
27    pub fn despawn(&mut self) {
28        self.server.despawn_entity(&mut self.world, &self.entity);
29    }
30
31    // Components
32
33    pub fn has_component<R: ReplicatedComponent>(&self) -> bool {
34        self.world.has_component::<R>(&self.entity)
35    }
36
37    pub fn component<R: ReplicatedComponent>(&mut self) -> Option<ReplicaMutWrapper<R>> {
38        self.world.component_mut::<R>(&self.entity)
39    }
40
41    pub fn insert_component<R: ReplicatedComponent>(&mut self, component_ref: R) -> &mut Self {
42        self.server
43            .insert_component(&mut self.world, &self.entity, component_ref);
44
45        self
46    }
47
48    pub fn insert_components<R: ReplicatedComponent>(
49        &mut self,
50        mut component_refs: Vec<R>,
51    ) -> &mut Self {
52        while let Some(component_ref) = component_refs.pop() {
53            self.insert_component(component_ref);
54        }
55
56        self
57    }
58
59    pub fn remove_component<R: ReplicatedComponent>(&mut self) -> Option<R> {
60        self.server
61            .remove_component::<R, W>(&mut self.world, &self.entity)
62    }
63
64    // Authority / Config
65
66    pub fn configure_replication(&mut self, config: ReplicationConfig) -> &mut Self {
67        self.server
68            .configure_entity_replication(&mut self.world, &self.entity, config);
69
70        self
71    }
72
73    pub fn replication_config(&self) -> Option<ReplicationConfig> {
74        self.server.entity_replication_config(&self.entity)
75    }
76
77    pub fn authority(&self) -> Option<EntityAuthStatus> {
78        self.server.entity_authority_status(&self.entity)
79    }
80
81    // Rooms
82
83    pub fn enter_room(&mut self, room_key: &RoomKey) -> &mut Self {
84        self.server.room_add_entity(room_key, &self.entity);
85
86        self
87    }
88
89    pub fn leave_room(&mut self, room_key: &RoomKey) -> &mut Self {
90        self.server.room_remove_entity(room_key, &self.entity);
91
92        self
93    }
94}