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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use super::track::UpdateTracker;
use common::{resources::Time, uid::Uid};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use specs::{storage::AccessMut, Component, Entity, Join, ReadStorage, World, WorldExt};
use std::{
    convert::{TryFrom, TryInto},
    fmt::Debug,
    marker::PhantomData,
};
use tracing::error;

// TODO: apply_{insert,modify,remove} all take the entity and call
// `write_storage` once per entity per component, instead of once per update
// batch(e.g. in a system-like memory access pattern); if sync ends up being a
// bottleneck, try optimizing this
/// Implemented by type that carries component data for insertion and
/// modification The assocatied `Phantom` type only carries information about
/// which component type is of interest and is used to transmit deletion events
pub trait CompPacket: Clone + Debug + Send + 'static {
    type Phantom: Clone + Debug + Serialize + DeserializeOwned;

    fn apply_insert(self, entity: Entity, world: &World, force_update: bool);
    fn apply_modify(self, entity: Entity, world: &World, force_update: bool);
    fn apply_remove(phantom: Self::Phantom, entity: Entity, world: &World);
}

/// Useful for implementing CompPacket trait
pub fn handle_insert<C: Component>(comp: C, entity: Entity, world: &World) {
    if let Err(e) = world.write_storage::<C>().insert(entity, comp) {
        error!(?e, "Error inserting");
    }
}
/// Useful for implementing CompPacket trait
pub fn handle_modify<C: Component + Debug>(comp: C, entity: Entity, world: &World) {
    if let Some(mut c) = world.write_storage::<C>().get_mut(entity) {
        *c.access_mut() = comp
    } else {
        error!(
            ?comp,
            "Error modifying synced component, it doesn't seem to exist"
        );
    }
}
/// Useful for implementing CompPacket trait
pub fn handle_remove<C: Component>(entity: Entity, world: &World) {
    world.write_storage::<C>().remove(entity);
}

pub trait InterpolatableComponent: Component {
    type InterpData: Component;
    type ReadData;

    fn new_data(x: Self) -> Self::InterpData;
    fn update_component(&self, data: &mut Self::InterpData, time: f64, force_update: bool);
    #[must_use]
    fn interpolate(self, data: &Self::InterpData, time: f64, read_data: &Self::ReadData) -> Self;
}

pub fn handle_interp_insert<C: InterpolatableComponent + Clone>(
    comp: C,
    entity: Entity,
    world: &World,
    force_update: bool,
) {
    let mut interp_data = C::new_data(comp.clone());
    let time = world.read_resource::<Time>().0;
    comp.update_component(&mut interp_data, time, force_update);
    handle_insert(comp, entity, world);
    handle_insert(interp_data, entity, world);
}

pub fn handle_interp_modify<C: InterpolatableComponent + Debug>(
    comp: C,
    entity: Entity,
    world: &World,
    force_update: bool,
) {
    if let Some(mut interp_data) = world.write_storage::<C::InterpData>().get_mut(entity) {
        let time = world.read_resource::<Time>().0;
        comp.update_component(interp_data.access_mut(), time, force_update);
        handle_modify(comp, entity, world);
    } else {
        error!(
            ?comp,
            "Error modifying interpolation data for synced component, it doesn't seem to exist"
        );
    }
}

pub fn handle_interp_remove<C: InterpolatableComponent>(entity: Entity, world: &World) {
    handle_remove::<C>(entity, world);
    handle_remove::<C::InterpData>(entity, world);
}

#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
pub enum CompUpdateKind<P: CompPacket> {
    Inserted(P),
    Modified(P),
    Removed(P::Phantom),
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EntityPackage<P: CompPacket> {
    pub uid: Uid,
    pub comps: Vec<P>,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct EntitySyncPackage {
    pub created_entities: Vec<Uid>,
    pub deleted_entities: Vec<Uid>,
}
impl EntitySyncPackage {
    pub fn new(
        uids: &ReadStorage<'_, Uid>,
        uid_tracker: &UpdateTracker<Uid>,
        filter: impl Join + Copy,
        deleted_entities: Vec<Uid>,
    ) -> Self {
        // Add created and deleted entities
        let created_entities = (uids, filter, uid_tracker.inserted())
            .join()
            .map(|(uid, _, _)| *uid)
            .collect();

        Self {
            created_entities,
            deleted_entities,
        }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CompSyncPackage<P: CompPacket> {
    // TODO: this can be made to take less space by clumping updates for the same entity together
    pub comp_updates: Vec<(u64, CompUpdateKind<P>)>,
}

impl<P: CompPacket> CompSyncPackage<P> {
    #[allow(clippy::new_without_default)]
    pub fn new() -> Self {
        Self {
            comp_updates: Vec::new(),
        }
    }

    pub fn comp_inserted<C>(&mut self, uid: Uid, comp: C)
    where
        P: From<C>,
    {
        self.comp_updates
            .push((uid.into(), CompUpdateKind::Inserted(comp.into())));
    }

    pub fn comp_modified<C>(&mut self, uid: Uid, comp: C)
    where
        P: From<C>,
    {
        self.comp_updates
            .push((uid.into(), CompUpdateKind::Modified(comp.into())));
    }

    pub fn comp_removed<C>(&mut self, uid: Uid)
    where
        P::Phantom: From<PhantomData<C>>,
    {
        self.comp_updates
            .push((uid.into(), CompUpdateKind::Removed(PhantomData::<C>.into())));
    }

    pub fn add_component_updates<'a, C>(
        &mut self,
        uids: &ReadStorage<'a, Uid>,
        tracker: &UpdateTracker<C>,
        storage: &ReadStorage<'a, C>,
        filter: impl Join + Copy,
    ) where
        P: From<C>,
        C: Component + Clone + Send + Sync + TryFrom<P>,
        P::Phantom: From<PhantomData<C>>,
        P::Phantom: TryInto<PhantomData<C>>,
        C::Storage: specs::storage::Tracked,
    {
        tracker.get_updates_for(uids, storage, filter, &mut self.comp_updates);
    }

    /// If there was an update to the component `C` on the provided entity this
    /// will add the update to this package.
    pub fn add_component_update<C>(
        &mut self,
        tracker: &UpdateTracker<C>,
        storage: &ReadStorage<'_, C>,
        uid: u64,
        entity: Entity,
    ) where
        P: From<C>,
        C: Component + Clone + Send + Sync + TryFrom<P>,
        P::Phantom: From<PhantomData<C>>,
        P::Phantom: TryInto<PhantomData<C>>,
        C::Storage: specs::storage::Tracked,
    {
        if let Some(comp_update) = tracker.get_update(storage, entity) {
            self.comp_updates.push((uid, comp_update))
        }
    }

    /// Returns whether this package is empty, useful for not sending an empty
    /// message.
    pub fn is_empty(&self) -> bool { self.comp_updates.is_empty() }
}