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
pub mod client_event;
pub mod server_event;
#[cfg(test)]
mod test_events;

use std::{
    fmt::{self, Display, Formatter},
    marker::PhantomData,
    time::Duration,
};

use bevy::{ecs::entity::EntityMap, prelude::*, reflect::TypeRegistryInternal};
use bevy_renet::renet::SendType;

/// Holds a channel ID for `T`.
#[derive(Resource)]
pub struct EventChannel<T> {
    pub id: u8,
    marker: PhantomData<T>,
}

impl<T> EventChannel<T> {
    fn new(id: u8) -> Self {
        Self {
            id,
            marker: PhantomData,
        }
    }
}

/// Creates a struct implements serialization for the event using [`TypeRegistryInternal`].
pub trait BuildEventSerializer<T> {
    type EventSerializer<'a>
    where
        T: 'a;

    fn new<'a>(event: &'a T, registry: &'a TypeRegistryInternal) -> Self::EventSerializer<'a>;
}

/// Creates a struct implements deserialization for the event using [`TypeRegistryInternal`].
pub trait BuildEventDeserializer {
    type EventDeserializer<'a>;

    fn new(registry: &TypeRegistryInternal) -> Self::EventDeserializer<'_>;
}

/// Event delivery guarantee.
#[derive(Clone, Copy, Debug)]
pub enum SendPolicy {
    /// Unreliable and unordered
    Unreliable,
    /// Reliable and unordered
    Unordered,
    /// Reliable and ordered
    Ordered,
}

impl From<SendPolicy> for SendType {
    fn from(policy: SendPolicy) -> Self {
        const RESEND_TIME: Duration = Duration::from_millis(300);
        match policy {
            SendPolicy::Unreliable => SendType::Unreliable,
            SendPolicy::Unordered => SendType::ReliableUnordered {
                resend_time: RESEND_TIME,
            },
            SendPolicy::Ordered => SendType::ReliableOrdered {
                resend_time: RESEND_TIME,
            },
        }
    }
}

pub trait MapEventEntities {
    fn map_entities(&mut self, entity_map: &EntityMap) -> Result<(), MapError>;
}

pub struct MapError(pub Entity);

impl Display for MapError {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "unable to map entity {:?}", self.0)
    }
}