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
//! The Protocol is used to define all the types that can be sent over the network
//! # Protocol
//!
//! Protocol is the main struct that defines the various channels, inputs, messages and components that will be used in the game.
//! Inputs, Messages and Components are all data structures that can be serialized and sent over the network.
//! Channels are an abstraction over how the data will be sent over the network (reliability, ordering, etc.)

use std::fmt::Debug;

use bevy::prelude::App;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::channel::builder::{Channel, ChannelSettings};
use crate::inputs::UserInput;
use crate::protocol::channel::ChannelRegistry;
use crate::protocol::component::{ComponentProtocol, ComponentProtocolKind};
use crate::protocol::message::MessageProtocol;
use crate::serialize::reader::ReadBuffer;
use crate::serialize::writer::WriteBuffer;
use crate::shared::replication::ReplicationSend;

/// Defines the various channels that can be used to send data over the network
pub(crate) mod channel;

/// Defines the various components that can be sent over the network
pub(crate) mod component;

/// Defines the various messages that can be sent over the network
pub(crate) mod message;

/// Provides a mapping from a type to a unique identifier that can be serialized
pub(crate) mod registry;

// TODO: how to make components or messages or inputs optional? Just by having an implementation for () ?
/// The [`Protocol`] trait defines the various channels, inputs, messages and components that will be used in the game.
///
/// # Examples
///
/// Here is an example of a protocol that defines a single channel, a single message and a single component:
/// ```
///# use serde::{Serialize, Deserialize};
///# use bevy::prelude::Component;
///# use lightyear::prelude::*;
///
///#[derive(Message, Serialize, Deserialize, Clone, PartialEq)]
///pub struct Message1(pub String);
///
///#[message_protocol(protocol = "MyProtocol")]
///pub enum MyMessageProtocol {
///    Message1(Message1),
///}
///
///#[derive(Component, Message, Serialize, Deserialize, Clone, PartialEq)]
///pub struct Component1;
///
///#[component_protocol(protocol = "MyProtocol")]
///pub enum MyComponentsProtocol {
///    Component1(Component1),
///}
///
///protocolize! {
///    Self = MyProtocol,
///    Message = MyMessageProtocol,
///    Component = MyComponentsProtocol,
///}
///
///# fn main() {}
/// ```
pub trait Protocol: Send + Sync + Clone + Debug + 'static {
    type Input: UserInput;
    type Message: MessageProtocol<Protocol = Self>;
    type Components: ComponentProtocol<Protocol = Self>;
    type ComponentKinds: ComponentProtocolKind<Protocol = Self>;

    fn add_channel<C: Channel>(&mut self, settings: ChannelSettings) -> &mut Self;
    fn channel_registry(&self) -> &ChannelRegistry;
    fn add_per_component_replication_send_systems<R: ReplicationSend<Self>>(app: &mut App);
}

// TODO: give an option to change names of types

/// This macro is used to build the Protocol struct
#[macro_export]
macro_rules! protocolize {

    (
        Self = $protocol:ident,
        Message = $message:ty,
        Component = $components:ty,
        Input = $input:ty,
        Crate = $shared_crate_name:ident,
    ) => {
        use $shared_crate_name::_reexport::paste;
        paste! {
        mod [<$protocol:lower _module>] {
            use super::*;
            use bevy::prelude::*;
            use $shared_crate_name::prelude::*;
            use $shared_crate_name::_reexport::*;

            #[derive(Debug, Clone)]
            pub struct $protocol {
                channel_registry: ChannelRegistry,
            }

            impl Protocol for $protocol {
                type Input = $input;
                type Message = $message;
                type Components = $components;
                type ComponentKinds = [<$components Kind>];

                fn add_channel<C: Channel>(&mut self, settings: ChannelSettings) -> &mut Self {
                    self.channel_registry.add::<C>(settings);
                    self
                }

                fn channel_registry(&self) -> &ChannelRegistry {
                    &self.channel_registry
                }

                fn add_per_component_replication_send_systems<R: ReplicationSend<Self>>(app: &mut App) {
                    Self::Components::add_per_component_replication_send_systems::<R>(app);
                }
            }

            impl Default for $protocol {
                fn default() -> Self {
                    let mut protocol = Self {
                        channel_registry: ChannelRegistry::default(),
                    };
                    protocol.add_channel::<EntityActionsChannel>(ChannelSettings {
                        mode: ChannelMode::UnorderedReliable(ReliableSettings::default()),
                        direction: ChannelDirection::Bidirectional,
                    });
                    protocol.add_channel::<EntityUpdatesChannel>(ChannelSettings {
                        mode: ChannelMode::UnorderedUnreliableWithAcks,
                        direction: ChannelDirection::Bidirectional,
                    });
                    protocol.add_channel::<PingChannel>(ChannelSettings {
                        mode: ChannelMode::SequencedUnreliable,
                        direction: ChannelDirection::Bidirectional,
                    });
                    protocol.add_channel::<InputChannel>(ChannelSettings {
                        mode: ChannelMode::SequencedUnreliable,
                        direction: ChannelDirection::ClientToServer,
                    });
                    protocol.add_channel::<DefaultUnorderedUnreliableChannel>(ChannelSettings {
                        mode: ChannelMode::UnorderedUnreliable,
                        direction: ChannelDirection::Bidirectional,
                    });
                    protocol.add_channel::<TickBufferChannel>(ChannelSettings {
                        mode: ChannelMode::TickBuffered,
                        direction: ChannelDirection::ClientToServer,
                    });
                    protocol
                }
            }
        }
        pub use [<$protocol:lower _module>]::$protocol;
        }
    };

    (
        Self = $protocol:ident,
        Message = $message:ty,
        Component = $components:ty,
        Crate = $shared_crate_name:ident,
    ) => {
        protocolize!{
            Self = $protocol,
            Message = $message,
            Component = $components,
            Input = (),
            Crate = $shared_crate_name,
        }
    };

    (
        Self = $protocol:ident,
        Message = $message:ty,
        Component = $components:ty,
        Input = $input:ty,
    ) => {
        protocolize!{
            Self = $protocol,
            Message = $message,
            Component = $components,
            Input = $input,
            Crate = lightyear,
        }
    };

    (
        Self = $protocol:ident,
        Message = $message:ty,
        Component = $components:ty,
    ) => {
        protocolize!{
            Self = $protocol,
            Message = $message,
            Component = $components,
            Input = (),
            Crate = lightyear,
        }
    };


}

/// Something that can be serialized bit by bit
pub trait BitSerializable: Clone {
    fn encode(&self, writer: &mut impl WriteBuffer) -> anyhow::Result<()>;

    fn decode(reader: &mut impl ReadBuffer) -> anyhow::Result<Self>
    where
        Self: Sized;
}

// TODO: allow for either decode/encode directly, or use serde if we add an attribute with_serde?
impl<T> BitSerializable for T
where
    T: Serialize + DeserializeOwned + Clone,
{
    fn encode(&self, writer: &mut impl WriteBuffer) -> anyhow::Result<()> {
        writer.serialize(self)
    }

    fn decode(reader: &mut impl ReadBuffer) -> anyhow::Result<Self>
    where
        Self: Sized,
    {
        reader.deserialize::<Self>()
    }
}

/// Data that can be used in an Event
/// Same as `Event`, but we implement it automatically for all compatible types
pub trait EventContext: Send + Sync + 'static {}

impl<T: Send + Sync + 'static> EventContext for T {}

// #[cfg(test)]
// pub mod tests {
//     use bevy::prelude::Component;
//     use serde::Deserialize;
//
//     use lightyear_macros::{
//         component_protocol_internal, message_protocol_internal, ChannelInternal, MessageInternal,
//     };
//
//     use crate::prelude::{ChannelDirection, ChannelMode, ReliableSettings};
//
//     use super::*;
//
//     // Messages
//     #[derive(MessageInternal, Serialize, Deserialize, Debug, PartialEq, Clone)]
//     pub struct Message1(pub String);
//
//     #[derive(MessageInternal, Serialize, Deserialize, Debug, PartialEq, Clone)]
//     pub struct Message2(pub u32);
//
//     // #[derive(Debug, PartialEq)]
//     #[message_protocol_internal(protocol = "MyProtocol")]
//     pub enum MyMessageProtocol {
//         Message1(Message1),
//         Message2(Message2),
//     }
//
//     #[derive(Component, Serialize, Deserialize, Clone, Debug, PartialEq)]
//     pub struct Component1;
//
//     // TODO: because we add ShouldBePredicted to the enum, we cannot derive stuff for the enum anymore!
//     //  is it a problem? we could pass the derives through an attribute macro ...
//     // #[derive(Debug, PartialEq)]
//     #[component_protocol_internal(protocol = "MyProtocol")]
//     pub enum MyComponentsProtocol {
//         Component1(Component1),
//     }
//
//     protocolize! {
//         Self = MyProtocol,
//         Message = MyMessageProtocol,
//         Component = MyComponentsProtocol,
//         Crate = crate,
//     }
//
//     // Channels
//     #[derive(ChannelInternal)]
//     pub struct Channel1;
//
//     #[derive(ChannelInternal)]
//     pub struct Channel2;
//
//     pub fn test_protocol() -> MyProtocol {
//         let mut p = MyProtocol::default();
//         p.add_channel::<Channel1>(ChannelSettings {
//             mode: ChannelMode::OrderedReliable(ReliableSettings::default()),
//             direction: ChannelDirection::Bidirectional,
//         });
//         p.add_channel::<Channel2>(ChannelSettings {
//             mode: ChannelMode::UnorderedUnreliable,
//             direction: ChannelDirection::Bidirectional,
//         });
//         p
//     }
// }