1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use std::{
    any::Any,
    collections::{HashMap, HashSet},
    default::Default,
};

use bevy_ecs::{
    entity::Entity,
    prelude::Resource,
    world::{FromWorld, World},
};

use naia_shared::{Protocolize, ReplicateSafe};

use super::component_access::{ComponentAccess, ComponentAccessor};

#[derive(Resource)]
pub struct WorldData<P: Protocolize> {
    entities: HashSet<Entity>,
    kind_to_accessor_map: HashMap<P::Kind, Box<dyn Any>>,
}

unsafe impl<P: Protocolize> Send for WorldData<P> {}
unsafe impl<P: Protocolize> Sync for WorldData<P> {}

impl<P: Protocolize> FromWorld for WorldData<P> {
    fn from_world(_world: &mut World) -> Self {
        Self {
            entities: HashSet::default(),
            kind_to_accessor_map: HashMap::default(),
        }
    }
}

impl<P: Protocolize> WorldData<P> {
    // Entities //

    pub(crate) fn entities(&self) -> Vec<Entity> {
        let mut output = Vec::new();

        for entity in &self.entities {
            output.push(*entity);
        }

        output
    }

    pub(crate) fn spawn_entity(&mut self, entity: &Entity) {
        self.entities.insert(*entity);
    }

    pub(crate) fn despawn_entity(&mut self, entity: &Entity) {
        self.entities.remove(entity);
    }

    // Components

    #[allow(clippy::borrowed_box)]
    pub(crate) fn component_access(
        &self,
        component_kind: &P::Kind,
    ) -> Option<&Box<dyn ComponentAccess<P>>> {
        if let Some(accessor_any) = self.kind_to_accessor_map.get(component_kind) {
            return accessor_any.downcast_ref::<Box<dyn ComponentAccess<P>>>();
        }
        None
    }

    pub(crate) fn has_kind(&self, component_kind: &P::Kind) -> bool {
        self.kind_to_accessor_map.contains_key(component_kind)
    }

    pub(crate) fn put_kind<R: ReplicateSafe<P>>(&mut self, component_kind: &P::Kind) {
        self.kind_to_accessor_map
            .insert(*component_kind, ComponentAccessor::<P, R>::create());
    }
}