lightyear 0.3.0

Server-client networking library for the Bevy game engine
Documentation
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*! Defines a [`ConnectionEvents`] struct that is used to store all events that are received from a [`Connection`](crate::connection::Connection).
*/
use std::iter;

use bevy::prelude::{Component, Entity};
use bevy::utils::{EntityHashMap, HashMap, HashSet};
use tracing::{info, trace};

use crate::packet::message::Message;
use crate::prelude::{Named, Tick};
use crate::protocol::channel::ChannelKind;
use crate::protocol::component::IntoKind;
use crate::protocol::message::{MessageBehaviour, MessageKind};
use crate::protocol::{EventContext, Protocol};
use crate::shared::ping::message::{Ping, Pong, SyncMessage};

// TODO: don't make fields pub but instead make accessors
#[derive(Debug)]
pub struct ConnectionEvents<P: Protocol> {
    // netcode
    // we put disconnections outside of there because `ConnectionEvents` gets removed upon disconnection
    pub connection: bool,

    // messages
    pub messages: HashMap<MessageKind, HashMap<ChannelKind, Vec<P::Message>>>,
    // replication
    pub spawns: Vec<Entity>,
    pub despawns: Vec<Entity>,

    // TODO: [IMPORTANT]: add ticks as well?
    // - should we just return the latest update for a given component/entity, or all of them?
    // - should we have a way to get the updates/inserts/removes for a given entity?

    // TODO: key by entity or by kind?
    // TODO: include the actual value in the event, or just the type? let's just include the type for now
    pub component_inserts: HashMap<P::ComponentKinds, Vec<Entity>>,
    // pub insert_components: HashMap<Entity, Vec<P::Components>>,
    pub component_removes: HashMap<P::ComponentKinds, Vec<Entity>>,
    // TODO: here as well, we could only include the type.. we already apply the changes to the entity directly, so users could keep track of changes
    //  let's just start with the kind...
    //  also, normally the updates are sequenced
    pub component_updates: HashMap<P::ComponentKinds, Vec<Entity>>,
    // // TODO: what happens if we receive on the same frame an Update for tick 4 and update for tick 10?
    // //  can we just discard the older one? what about for inserts/removes?
    // pub component_updates: EntityHashMap<Entity, HashMap<P::ComponentKinds, Tick>>,
    // components_with_updates: HashSet<P::ComponentKinds>,

    // How can i easily get the events (inserts/adds/removes) for a given entity? add components on that entity
    // that track that?
    empty: bool,
}

impl<P: Protocol> Default for ConnectionEvents<P> {
    fn default() -> Self {
        Self::new()
    }
}

impl<P: Protocol> ConnectionEvents<P> {
    pub fn new() -> Self {
        Self {
            // netcode
            connection: false,
            // inputs
            // inputs: InputBuffer::default(),
            // messages
            messages: HashMap::new(),
            // replication
            spawns: Vec::new(),
            despawns: Vec::new(),
            component_inserts: Default::default(),
            component_removes: Default::default(),
            component_updates: Default::default(),
            // components_with_updates: Default::default(),
            // bookkeeping
            empty: true,
        }
    }

    pub fn clear(&mut self) {
        self.connection = false;
        self.messages.clear();
        self.spawns.clear();
        self.despawns.clear();
        self.component_inserts.clear();
        self.component_removes.clear();
        self.component_updates.clear();
        self.empty = true;
    }

    /// If true, the connection was established
    pub fn has_connection(&self) -> bool {
        self.connection
    }

    pub fn push_connection(&mut self) {
        self.connection = true;
        self.empty = false;
    }

    pub fn is_empty(&self) -> bool {
        self.empty
    }
    pub fn push_message(&mut self, channel_kind: ChannelKind, message: P::Message) {
        trace!("Received message: {:?}", message.name());
        #[cfg(feature = "metrics")]
        {
            let message_name = message.name();
            metrics::increment_counter!("message", "kind" => message_name);
        }
        self.messages
            .entry(message.kind())
            .or_default()
            .entry(channel_kind)
            .or_default()
            .push(message);
        self.empty = false;
    }

    pub(crate) fn push_spawn(&mut self, entity: Entity) {
        trace!(?entity, "Received entity spawn");
        #[cfg(feature = "metrics")]
        {
            metrics::increment_counter!("entity_spawn");
        }
        self.spawns.push(entity);
        self.empty = false;
    }

    pub(crate) fn push_despawn(&mut self, entity: Entity) {
        trace!(?entity, "Received entity despawn");
        #[cfg(feature = "metrics")]
        {
            metrics::increment_counter!("entity_despawn");
        }
        self.despawns.push(entity);
        self.empty = false;
    }

    pub(crate) fn push_insert_component(
        &mut self,
        entity: Entity,
        component: P::ComponentKinds,
        tick: Tick,
    ) {
        trace!(?entity, ?component, "Received insert component");
        #[cfg(feature = "metrics")]
        {
            metrics::increment_counter!("component_insert", "kind" => component);
        }
        self.component_inserts
            .entry(component)
            .or_default()
            .push(entity);
        // .push((entity, tick));
        self.empty = false;
    }

    pub(crate) fn push_remove_component(
        &mut self,
        entity: Entity,
        component: P::ComponentKinds,
        tick: Tick,
    ) {
        trace!(?entity, ?component, "Received remove component");
        #[cfg(feature = "metrics")]
        {
            metrics::increment_counter!("component_remove", "kind" => component);
        }
        self.component_removes
            .entry(component)
            .or_default()
            .push(entity);
        // .push((entity, tick));
        self.empty = false;
    }

    // TODO: how do distinguish between multiple updates for the same component/entity? add ticks?
    pub(crate) fn push_update_component(
        &mut self,
        entity: Entity,
        component: P::ComponentKinds,
        tick: Tick,
    ) {
        trace!(?entity, ?component, "Received update component");
        #[cfg(feature = "metrics")]
        {
            metrics::increment_counter!("component_update", "kind" => component);
        }
        // self.components_with_updates.insert(component.clone());
        // self.component_updates
        //     .entry(entity)
        //     .or_default()
        //     .entry(component)
        //     .and_modify(|t| {
        //         if tick > *t {
        //             *t = tick;
        //         }
        //     })
        //     .or_insert(tick);

        self.component_updates
            .entry(component)
            .or_default()
            .push(entity);
        // .push((entity, tick));
        self.empty = false;
    }
}

pub trait IterMessageEvent<P: Protocol, Ctx: EventContext = ()> {
    fn into_iter_messages<M: Message>(&mut self) -> Box<dyn Iterator<Item = (M, Ctx)> + '_>
    where
        P::Message: TryInto<M, Error = ()>;

    fn has_messages<M: Message>(&self) -> bool;
}

impl<P: Protocol> IterMessageEvent<P> for ConnectionEvents<P> {
    fn into_iter_messages<M: Message>(&mut self) -> Box<dyn Iterator<Item = (M, ())>>
    where
        // TODO: should we change this to `Into`
        P::Message: TryInto<M, Error = ()>,
    {
        let message_kind = MessageKind::of::<M>();
        if let Some(data) = self.messages.remove(&message_kind) {
            return Box::new(data.into_iter().flat_map(|(_, messages)| {
                messages.into_iter().map(|message| {
                    // SAFETY: we checked via message kind that only messages of the type M
                    // are in the list
                    (message.try_into().unwrap(), ())
                })
            }));
        }
        Box::new(iter::empty())
    }

    fn has_messages<M: Message>(&self) -> bool {
        let message_kind = MessageKind::of::<M>();
        self.messages.contains_key(&message_kind)
    }
}

pub trait IterEntitySpawnEvent<Ctx: EventContext = ()> {
    fn into_iter_entity_spawn(&mut self) -> Box<dyn Iterator<Item = (Entity, Ctx)> + '_>;
    fn has_entity_spawn(&self) -> bool;
}

impl<P: Protocol> IterEntitySpawnEvent for ConnectionEvents<P> {
    fn into_iter_entity_spawn(&mut self) -> Box<dyn Iterator<Item = (Entity, ())> + '_> {
        let spawns = std::mem::take(&mut self.spawns);
        Box::new(spawns.into_iter().map(|entity| (entity, ())))
    }

    fn has_entity_spawn(&self) -> bool {
        !self.spawns.is_empty()
    }
}

pub trait IterEntityDespawnEvent<Ctx: EventContext = ()> {
    fn into_iter_entity_despawn(&mut self) -> Box<dyn Iterator<Item = (Entity, Ctx)> + '_>;
    fn has_entity_despawn(&self) -> bool;
}

impl<P: Protocol> IterEntityDespawnEvent for ConnectionEvents<P> {
    fn into_iter_entity_despawn(&mut self) -> Box<dyn Iterator<Item = (Entity, ())> + '_> {
        let despawns = std::mem::take(&mut self.despawns);
        Box::new(despawns.into_iter().map(|entity| (entity, ())))
    }

    fn has_entity_despawn(&self) -> bool {
        !self.despawns.is_empty()
    }
}

/// Iterate through all the events for a given entity
pub trait IterComponentUpdateEvent<P: Protocol, Ctx: EventContext = ()> {
    /// Find all the updates of component C
    fn iter_component_update<C: Component>(
        &mut self,
    ) -> Box<dyn Iterator<Item = (Entity, Ctx)> + '_>
    where
        C: IntoKind<P::ComponentKinds>;

    /// Is there any update for component C
    fn has_component_update<C: Component>(&self) -> bool
    where
        C: IntoKind<P::ComponentKinds>;

    /// Find all the updates of component C for a given entity
    fn get_component_update<C: Component>(&self, entity: Entity) -> Option<Ctx>
    where
        C: IntoKind<P::ComponentKinds>;
}

impl<P: Protocol> IterComponentUpdateEvent<P> for ConnectionEvents<P> {
    fn iter_component_update<C: Component>(&mut self) -> Box<dyn Iterator<Item = (Entity, ())> + '_>
    where
        C: IntoKind<P::ComponentKinds>,
    {
        let component_kind = C::into_kind();
        if let Some(data) = self.component_updates.remove(&component_kind) {
            return Box::new(data.into_iter().map(|entity| (entity, ())));
        }
        Box::new(iter::empty())
        // Box::new(
        //     self.component_updates
        //         .iter()
        //         .filter_map(|(entity, updates)| {
        //             updates.get(&C::into_kind()).map(|tick| (*entity, *tick))
        //         }),
        // )
    }

    fn has_component_update<C: Component>(&self) -> bool
    where
        C: IntoKind<P::ComponentKinds>,
    {
        let component_kind = C::into_kind();
        self.component_updates.contains_key(&component_kind)
        // self.components_with_updates.contains(&C::into_kind())
    }

    // TODO: is it possible to receive multiple updates for the same component/entity?
    //  it shouldn't be possible for a Sequenced channel,
    //  maybe just take the first value that matches, then?
    fn get_component_update<C: Component>(&self, entity: Entity) -> Option<()>
    where
        C: IntoKind<P::ComponentKinds>,
    {
        todo!()
        // self.component_updates
        //     .get(&entity)
        //     .map(|updates| updates.get(&C::into_kind()).cloned())
        //     .flatten()
    }
}

pub trait IterComponentRemoveEvent<P: Protocol, Ctx: EventContext = ()> {
    fn into_iter_component_remove<C: Component>(
        &mut self,
    ) -> Box<dyn Iterator<Item = (Entity, Ctx)> + '_>
    where
        C: IntoKind<P::ComponentKinds>;
    fn has_component_remove<C: Component>(&self) -> bool
    where
        C: IntoKind<P::ComponentKinds>;
}

// TODO: move these implementations to client?
impl<P: Protocol> IterComponentRemoveEvent<P> for ConnectionEvents<P> {
    fn into_iter_component_remove<C: Component>(
        &mut self,
    ) -> Box<dyn Iterator<Item = (Entity, ())> + '_>
    where
        C: IntoKind<P::ComponentKinds>,
    {
        let component_kind = C::into_kind();
        if let Some(data) = self.component_removes.remove(&component_kind) {
            return Box::new(data.into_iter().map(|entity| (entity, ())));
        }
        Box::new(iter::empty())
    }

    fn has_component_remove<C: Component>(&self) -> bool
    where
        C: IntoKind<P::ComponentKinds>,
    {
        let component_kind = C::into_kind();
        self.component_removes.contains_key(&component_kind)
    }
}

pub trait IterComponentInsertEvent<P: Protocol, Ctx: EventContext = ()> {
    fn into_iter_component_insert<C: Component>(
        &mut self,
    ) -> Box<dyn Iterator<Item = (Entity, Ctx)> + '_>
    where
        C: IntoKind<P::ComponentKinds>;
    fn has_component_insert<C: Component>(&self) -> bool
    where
        C: IntoKind<P::ComponentKinds>;
}

impl<P: Protocol> IterComponentInsertEvent<P> for ConnectionEvents<P> {
    fn into_iter_component_insert<C: Component>(
        &mut self,
    ) -> Box<dyn Iterator<Item = (Entity, ())> + '_>
    where
        C: IntoKind<P::ComponentKinds>,
    {
        let component_kind = C::into_kind();
        if let Some(data) = self.component_inserts.remove(&component_kind) {
            return Box::new(data.into_iter().map(|entity| (entity, ())));
        }
        Box::new(iter::empty())
    }

    fn has_component_insert<C: Component>(&self) -> bool
    where
        C: IntoKind<P::ComponentKinds>,
    {
        let component_kind = C::into_kind();
        self.component_inserts.contains_key(&component_kind)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tests::protocol::*;
    use bevy::utils::HashSet;

    #[test]
    fn test_iter_messages() {
        let mut events = ConnectionEvents::<MyProtocol>::new();
        let channel_kind_1 = ChannelKind::of::<Channel1>();
        let channel_kind_2 = ChannelKind::of::<Channel2>();
        let message1_a = Message1("hello".to_string());
        let message1_b = Message1("world".to_string());
        events.push_message(
            channel_kind_1,
            MyMessageProtocol::Message1(message1_a.clone()),
        );
        events.push_message(
            channel_kind_2,
            MyMessageProtocol::Message1(message1_b.clone()),
        );
        events.push_message(channel_kind_1, MyMessageProtocol::Message2(Message2(1)));

        // check that we have the correct messages
        let messages: Vec<Message1> = events.into_iter_messages().map(|(m, _)| m).collect();
        assert!(messages.contains(&message1_a));
        assert!(messages.contains(&message1_b));

        // check that there are no more message of that kind in the events
        assert!(!events.messages.contains_key(&MessageKind::of::<Message1>()));

        // check that we still have the other message kinds
        assert!(events.messages.contains_key(&MessageKind::of::<Message2>()));
    }

    // #[test]
    // fn test_iter_component_updates() {
    //     let mut events = ConnectionEvents::<MyProtocol>::new();
    //     let channel_kind_1 = ChannelKind::of::<Channel1>();
    //     let channel_kind_2 = ChannelKind::of::<Channel2>();
    //     let entity_1 = Entity::from_raw(1);
    //     let entity_2 = Entity::from_raw(2);
    //     events.push_update_component(entity_1, MyComponentsProtocolKind::Component1, Tick(1));
    //     events.push_update_component(entity_1, MyComponentsProtocolKind::Component2, Tick(2));
    //     events.push_update_component(entity_2, MyComponentsProtocolKind::Component2, Tick(3));
    //
    //     assert!(events
    //         .get_component_update::<Component1>(entity_2)
    //         .is_none());
    //     assert_eq!(
    //         events.get_component_update::<Component2>(entity_2),
    //         Some(Tick(3))
    //     );
    //
    //     let component_1_updates: HashSet<(Entity, Tick)> =
    //         events.iter_component_update::<Component1>().collect();
    //     assert!(component_1_updates.contains(&(entity_1, Tick(1))));
    //
    //     let component_2_updates: HashSet<(Entity, Tick)> =
    //         events.iter_component_update::<Component2>().collect();
    //     assert!(component_2_updates.contains(&(entity_1, Tick(2))));
    //     assert!(component_2_updates.contains(&(entity_2, Tick(3))));
    //
    //     let component_3_updates: HashSet<(Entity, Tick)> =
    //         events.iter_component_update::<Component3>().collect();
    //     assert!(component_3_updates.is_empty());
    // }
}