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
use std::fmt::Debug;

use bitcode::encoding::{Fixed, Gamma};
use bytes::Bytes;

use crate::packet::packet::FRAGMENT_SIZE;
use crate::protocol::EventContext;
use crate::serialize::reader::ReadBuffer;
use crate::serialize::writer::WriteBuffer;
use crate::shared::replication::entity_map::MapEntities;
use crate::shared::tick_manager::Tick;
use crate::utils::named::Named;
use crate::utils::wrapping_id;
use crate::utils::wrapping_id::wrapping_id;

// strategies to avoid copying:
// - have a net_id for each message or component
//   be able to take a reference to a M and serialize it into bytes (so we can cheaply clone)
//   in the serialized message, include the net_id (for decoding)
//   no bit padding

// Internal id that we assign to each message sent over the network
wrapping_id!(MessageId);

pub type FragmentIndex = u8;

/// Struct to keep track of which messages/slices have been received by the remote
#[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) struct MessageAck {
    pub(crate) message_id: MessageId,
    pub(crate) fragment_id: Option<FragmentIndex>,
}

/// A Message is a logical unit of data that should be transmitted over a network
///
/// The message can be small (multiple messages can be sent in a single packet)
/// or big (a single message can be split between multiple packets)
///
/// A Message knows how to serialize itself (messageType + Data)
/// and knows how many bits it takes to serialize itself
///
/// In the message container, we already store the serialized representation of the message.
/// The main reason is so that we can avoid copies, by directly serializing references into raw bits
// #[derive(Serialize, Deserialize)]
// #[derive(Clone, PartialEq, Debug)]
// pub struct MessageContainer<P: BitSerializable> {
//     pub(crate) id: Option<MessageId>,
//     // we use bytes so we can cheaply copy the message container (for example in reliable sender)
//     pub(crate) message: Bytes,
//     // TODO: we use num_bits to avoid padding each message to a full byte when serializing
//     // num_bits: usize,
//     // message: P,
//     marker: PhantomData<P>,
// }
//
// impl<P: BitSerializable> MessageContainer<P> {
//     /// Serialize the message into a bytes buffer
//     /// Returns the number of bits written
//     pub(crate) fn encode(&self, writer: &mut impl WriteBuffer) -> anyhow::Result<usize> {
//         let num_bits_before = writer.num_bits_written();
//         writer.serialize(&self.id)?;
//         // TODO: only serialize the bits that matter (without padding!)
//         self.message.as_ref().encode(writer)?;
//         let num_bits_written = writer.num_bits_written() - num_bits_before;
//         Ok(num_bits_written)
//     }
//
//     /// Deserialize from the bytes buffer into a Message
//     pub(crate) fn decode(reader: &mut impl ReadBuffer) -> anyhow::Result<Self> {
//         let id = reader.deserialize::<Option<MessageId>>()?;
//         let raw_bytes = <[u8]>::decode(reader)?;
//         let message = Bytes::from(raw_bytes);
//         Ok(Self {
//             id,
//             message,
//             marker: Default::default(),
//         })
//     }
//
//     pub fn new<P: BitSerializable>(message: &P) -> Self {
//         // TODO: reuse the same buffer for writing message containers
//         let mut buffer = WriteWordBuffer::with_capacity(1024);
//         buffer.start_write();
//         message.encode(&mut buffer).unwrap();
//         let bytes = buffer.finish_write();
//         // let num_bits_written = buffer.num_bits_written();
//         MessageContainer {
//             id: None,
//             message: Bytes::from(bytes),
//             marker: Default::default(),
//         }
//     }
//
//     pub fn set_id(&mut self, id: MessageId) {
//         self.id = Some(id);
//     }
//
//     pub fn inner(self) -> P {
//         // TODO: have a way to do this without any copy?
//         let mut reader = ReadWordBuffer::start_read(self.message.as_ref());
//         P::decode(&mut reader).unwrap()
//     }
// }

// TODO: we could just store Bytes in MessageContainer to serialize very early
//  important thing is to re-use the Writer to allocate only once?
//  pros: we might not require messages/components to be clone anymore if we serialize them very early!
//  also we know the size of the message early, which is useful for fragmentation
// #[derive(Clone, PartialEq, Debug)]
// pub struct MessageContainer<P> {
//     pub(crate) id: Option<MessageId>,
//     message: P,
// }
#[derive(Debug, PartialEq)]
pub enum MessageContainer {
    Single(SingleData),
    Fragment(FragmentData),
}

impl From<FragmentData> for MessageContainer {
    fn from(value: FragmentData) -> Self {
        Self::Fragment(value)
    }
}

impl From<SingleData> for MessageContainer {
    fn from(value: SingleData) -> Self {
        Self::Single(value)
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
/// This structure contains the bytes for a single 'logical' message
///
/// We store the bytes instead of the message directly.
/// This lets us serialize the message very early and then pass it around with cheap clones
/// The message/component does not need to implement Clone anymore!
/// Also we know the size of the message early, which is useful for fragmentation.
pub struct SingleData {
    pub id: Option<MessageId>,
    // TODO: for now, we include the tick into every single data because it's easier
    //  for optimizing size later, we want the tick channels to use a different SingleData type that contains tick
    //  basically each channel should have either SingleData or TickData as associated type ?
    // NOTE: This is only used for tick buffered receiver, so that the message is read at the same exact tick it was sent
    pub tick: Option<Tick>,
    pub bytes: Bytes,
}

impl SingleData {
    pub fn new(id: Option<MessageId>, bytes: Bytes) -> Self {
        Self {
            id,
            tick: None,
            bytes,
        }
    }

    // pub(crate) fn num_bits(&self) -> usize {
    //     let bytes_bits = self.bytes.len() * (u8::BITS as usize);
    //     let id_bits = self.id.map_or(1, |_| (u16::BITS as usize) + 1);
    //     bytes_bits + id_bits
    // }

    pub(crate) fn encode(&self, writer: &mut impl WriteBuffer) -> anyhow::Result<usize> {
        let num_bits_before = writer.num_bits_written();
        writer.encode(&self.id, Fixed)?;
        writer.encode(&self.tick, Fixed)?;
        // Maybe we should just newtype Bytes so we could implement encode for it separately?

        // we encode Bytes by writing the length first
        // writer.encode(&(self.bytes.len() )?;
        // writer.encode(&self.bytes.to_vec(), Fixed)?;
        writer.encode(self.bytes.as_ref(), Fixed)?;
        // writer.serialize(self.bytes.as_ref())?;
        let num_bits_written = writer.num_bits_written() - num_bits_before;
        Ok(num_bits_written)
    }

    // TODO: are we doing an extra copy here?
    pub(crate) fn decode(reader: &mut impl ReadBuffer) -> anyhow::Result<Self> {
        let id = reader.decode::<Option<MessageId>>(Fixed)?;
        let tick = reader.decode::<Option<Tick>>(Fixed)?;

        // the encoding wrote the length as usize with gamma encoding
        // let num_bytes = reader.decode::<usize>(Gamma)?;
        // let num_bytes_non_zero = std::num::NonZeroUsize::new(num_bytes)
        //     .ok_or_else(|| anyhow::anyhow!("num_bytes is 0"))?;
        // let read_bytes = reader.read_bytes(num_bytes_non_zero)?;
        // let bytes = BytesMut::from(read_bytes).freeze();

        // let read_bytes =
        // TODO: ANNOYING; AVOID ALLOCATING HERE
        //  - we already do a copy from the network io into the ReadBuffer
        //  - then we do an allocation here to read the Bytes into SingleData
        //  - (we do a copy when composing the fragment from bytes)
        //  - we do an extra copy when allocating a new ReadBuffer from the SingleData Bytes

        // TODO: use ReadBuffer/WriteBuffer only when decoding/encoding messages the first time/final time!
        //  once we have the Bytes object, manually do memcpy, aligns the final bytes manually!
        //  (encode header, channel ids, message ids, etc. myself)
        //  maybe use BitVec to construct the final objects?

        // TODO: DO A FLOW OF THE DATA/COPIES/CLONES DURING ENCODE/DECODE TO DECIDE
        //  HOW THE LIFETIMES FLOW!
        // let read_bytes = <Vec<u8> as ReadBuffer>::decode(reader, Fixed)?;
        let read_bytes = reader.decode::<Vec<u8>>(Fixed)?;

        //
        // let bytes = reader.decode::<&[u8]>()?;
        Ok(Self {
            id,
            tick,
            bytes: Bytes::from(read_bytes),
            // bytes: Bytes::copy_from_slice(read_bytes),
        })
    }
}

#[derive(Clone, Debug, PartialEq)]
pub struct FragmentData {
    // we always need a message_id for fragment messages, for re-assembly
    pub message_id: MessageId,
    // TODO: separate this out?
    pub tick: Option<Tick>,
    pub fragment_id: FragmentIndex,
    pub num_fragments: FragmentIndex,
    /// Bytes data associated with the message that is too big
    pub bytes: Bytes,
}

impl FragmentData {
    pub(crate) fn encode(&self, writer: &mut impl WriteBuffer) -> anyhow::Result<usize> {
        let num_bits_before = writer.num_bits_written();
        writer.encode(&self.message_id, Fixed)?;
        writer.encode(&self.tick, Fixed)?;
        writer.encode(&self.fragment_id, Gamma)?;
        writer.encode(&self.num_fragments, Gamma)?;
        // TODO: be able to just concat the bytes to the buffer?
        if self.is_last_fragment() {
            // writing the slice includes writing the length of the slice
            writer.encode(self.bytes.as_ref(), Fixed)?;
            // writer.serialize(&self.bytes.to_vec());
            // writer.serialize(&self.fragment_message_bytes.as_ref());
        } else {
            let bytes_array: [u8; FRAGMENT_SIZE] = self.bytes.as_ref().try_into().unwrap();
            // Serde does not handle arrays well (https://github.com/serde-rs/serde/issues/573)
            writer.encode(&bytes_array, Fixed)?;
        }
        let num_bits_written = writer.num_bits_written() - num_bits_before;
        Ok(num_bits_written)
    }

    pub(crate) fn decode(reader: &mut impl ReadBuffer) -> anyhow::Result<Self>
    where
        Self: Sized,
    {
        let message_id = reader.decode::<MessageId>(Fixed)?;
        let tick = reader.decode::<Option<Tick>>(Fixed)?;
        let fragment_id = reader.decode::<FragmentIndex>(Gamma)?;
        let num_fragments = reader.decode::<FragmentIndex>(Gamma)?;
        let bytes = if fragment_id == num_fragments - 1 {
            // let num_bytes = reader.decode::<usize>(Gamma)?;
            // let num_bytes_non_zero = std::num::NonZeroUsize::new(num_bytes)
            //     .ok_or_else(|| anyhow::anyhow!("num_bytes is 0"))?;
            // let read_bytes = reader.read_bytes(num_bytes_non_zero)?;
            // reader.
            // let read_bytes = reader.decode::<&[u8]>()?;
            // TODO: avoid the extra copy
            //  - maybe have the encoding of bytes be
            let read_bytes = reader.decode::<Vec<u8>>(Fixed)?;
            Bytes::from(read_bytes)
        } else {
            // Serde does not handle arrays well (https://github.com/serde-rs/serde/issues/573)
            let read_bytes = reader.decode::<[u8; FRAGMENT_SIZE]>(Fixed)?;
            // TODO: avoid the extra copy
            let bytes_vec: Vec<u8> = read_bytes.to_vec();
            Bytes::from(bytes_vec)
        };
        Ok(Self {
            message_id,
            tick,
            fragment_id,
            num_fragments,
            bytes,
        })
    }

    pub(crate) fn is_last_fragment(&self) -> bool {
        self.fragment_id == self.num_fragments - 1
    }
}

impl MessageContainer {
    pub(crate) fn message_id(&self) -> Option<MessageId> {
        match &self {
            MessageContainer::Single(data) => data.id,
            MessageContainer::Fragment(data) => Some(data.message_id),
        }
    }

    /// Serialize the message into a bytes buffer
    /// Returns the number of bits written
    pub(crate) fn encode(&self, writer: &mut impl WriteBuffer) -> anyhow::Result<usize> {
        match &self {
            MessageContainer::Single(data) => data.encode(writer),
            MessageContainer::Fragment(data) => data.encode(writer),
        }
    }

    pub fn set_id(&mut self, id: MessageId) {
        match self {
            MessageContainer::Single(data) => data.id = Some(id),
            MessageContainer::Fragment(data) => data.message_id = id,
        };
    }

    /// Set the tick of the remote when this message was sent
    ///
    /// Note that in some cases the tick can be already set (for example for tick-buffered channel,
    /// or for reliable channels, since the tick set in the packet header might not correspond to the tick
    /// where the message was initially set)
    /// In those cases we don't override the tick
    pub fn set_tick(&mut self, tick: Tick) {
        match self {
            MessageContainer::Single(data) => {
                if data.tick.is_none() {
                    data.tick = Some(tick);
                }
            }
            MessageContainer::Fragment(data) => {
                if data.tick.is_none() {
                    data.tick = Some(tick);
                }
            }
        };
    }

    /// Get access to the underlying bytes (clone is a cheap operation for `Bytes`)
    pub fn bytes(&self) -> Bytes {
        match self {
            MessageContainer::Single(data) => data.bytes.clone(),
            MessageContainer::Fragment(data) => data.bytes.clone(),
        }
    }
}

// TODO: for now messages must be able to be used as events, since we output them in our message events
pub trait Message: EventContext + Named + MapEntities {}

#[cfg(test)]
mod tests {
    use crate::_reexport::{ReadWordBuffer, WriteWordBuffer};

    use super::*;

    // #[test]
    // fn test_single_data_num_bits() {
    //     let bytes = Bytes::from(vec![5; 10]);
    //     let data = SingleData::new(None, bytes.clone());
    //     let mut writer = WriteWordBuffer::with_capacity(10);
    //     let num_bits = data.encode(&mut writer).unwrap();
    //     assert_eq!(num_bits, data.num_bits());
    // }

    #[test]
    fn test_serde_single_data() {
        let data = SingleData::new(Some(MessageId(1)), vec![9, 3].into());
        let mut writer = WriteWordBuffer::with_capacity(10);
        let _a = data.encode(&mut writer).unwrap();
        // dbg!(a);
        let bytes = writer.finish_write();

        let mut reader = ReadWordBuffer::start_read(bytes);
        let decoded = SingleData::decode(&mut reader).unwrap();

        // dbg!(bitvec::vec::BitVec::<u8>::from_slice(&bytes));
        dbg!(&bytes);
        // dbg!(&writer.num_bits_written());
        // dbg!(&decoded.id);
        // dbg!(&decoded.bytes.as_ref());
        assert_eq!(decoded, data);
        dbg!(&writer.num_bits_written());
        // assert_eq!(writer.num_bits_written(), 5 * u8::BITS as usize);
    }

    #[test]
    fn test_serde_fragment_data() {
        let bytes = Bytes::from(vec![0; 10]);
        let data = FragmentData {
            message_id: MessageId(0),
            tick: None,
            fragment_id: 2,
            num_fragments: 3,
            bytes: bytes.clone(),
        };
        let mut writer = WriteWordBuffer::with_capacity(10);
        let _a = data.encode(&mut writer).unwrap();
        // dbg!(a);
        let bytes = writer.finish_write();

        let mut reader = ReadWordBuffer::start_read(bytes);
        let decoded = FragmentData::decode(&mut reader).unwrap();

        // dbg!(bitvec::vec::BitVec::<u8>::from_slice(&bytes));
        dbg!(&bytes);
        // dbg!(&writer.num_bits_written());
        // dbg!(&decoded.id);
        // dbg!(&decoded.bytes.as_ref());
        assert_eq!(decoded, data);
        dbg!(&writer.num_bits_written());
        // assert_eq!(writer.num_bits_written(), 5 * u8::BITS as usize);
    }
}