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
//! Traits and structures relating to and for managing commands. Commands are messages sent from
//! outside the physics simulation to alter how the physics simulation runs. For example, causing a
//! rigid body for a player to jump requires a jump command, and causing a player to spawn requires
//! a spawn command.

use crate::timestamp::{Timestamp, Timestamped};
use serde::{de::DeserializeOwned, Serialize};
use std::{cmp::Reverse, collections::BTreeMap, fmt::Debug, ops::Range};
use tracing::warn;

/// A command is a request to change the physics simulation in some way, issued from outside the
/// physics simulation. It is the way in which players and any non-physics game logic can interact
/// with the physics simulation.
///
/// # Example
///
/// ```
/// use crystalorb::command::Command;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize, Debug, Clone)]
/// struct Player(usize);
///
/// #[derive(Serialize, Deserialize, Debug, Clone)]
/// enum GameCommand {
///     Spawn(Player),
///     Despawn(Player),
///     Jump(Player),
///     Left(Player),
///     Right(Player),
/// }
///
/// impl Command for GameCommand {};
/// ```
pub trait Command: Clone + Sync + Send + 'static + Serialize + DeserializeOwned + Debug {}

/// A handy structure for receiving commands out-of-order, and consuming them in-order. This also
/// unintuitively keeps track of the "current" timestamp for whatever uses this [`CommandBuffer`].
/// This is because the [`CommandBuffer`] needs to maintain an acceptable window of command
/// timestamps centered around the current timestamp, or else the command timestamps would be too
/// far about and [wouldn't be
/// comparable](crate::timestamp::Timestamp::comparable_range_with_midpoint).
#[derive(Clone, Debug)]
pub(crate) struct CommandBuffer<CommandType: Command> {
    map: BTreeMap<Reverse<Timestamp>, Vec<CommandType>>,
    timestamp: Timestamp,
}

impl<CommandType: Command> Default for CommandBuffer<CommandType> {
    fn default() -> Self {
        Self {
            map: BTreeMap::new(),
            timestamp: Timestamp::default(),
        }
    }
}

impl<CommandType: Command> CommandBuffer<CommandType> {
    pub fn new() -> Self {
        Self::default()
    }

    /// The command buffer attempts to sort the commands by their timestamp, but the timestamps
    /// uses a wrapped difference to calculate the ordering. In order to prevent stale commands
    /// from being replayed, and in order to keep the commands transitively consistently
    /// ordered, we restrict the command buffer to only half of the available timestamp
    /// datasize.
    pub fn acceptable_timestamp_range(&self) -> Range<Timestamp> {
        Timestamp::comparable_range_with_midpoint(self.timestamp)
    }

    pub fn timestamp(&self) -> Timestamp {
        self.timestamp
    }

    pub fn update_timestamp(&mut self, timestamp: Timestamp) {
        self.timestamp = timestamp;

        // Now we discard commands that fall outside of the acceptable timestamp range.
        // (1) future commands are still accepted into the command buffer without breaking the
        // transitivity laws.
        // (2) stale commands are discarded so that they don't wrap around and replayed again like
        // a ghost.

        let acceptable_timestamp_range = self.acceptable_timestamp_range();

        // Discard stale commands.
        let stale_commands = self
            .map
            .split_off(&Reverse(acceptable_timestamp_range.start - 1));
        if !stale_commands.is_empty() {
            warn!(
                "Discarded {:?} stale commands due to timestamp update! This should rarely happen. The commands were {:?}",
                stale_commands.len(),
                stale_commands
            );
        }

        // In case we rewind the midpoint timestamp, discard commands too far in the future.
        loop {
            // Note: since the map is reversed, the latest command is ordered first.
            if let Some((key, value)) = self.map.first_key_value() {
                if key.0 >= acceptable_timestamp_range.end {
                    warn!("Discarding future command {:?} after timestamp update! This should rarely happen", value);
                    let key_to_remove = *key;
                    self.map.remove(&key_to_remove);
                    continue;
                }
            }
            break;
        }
    }

    pub fn insert(&mut self, command: &Timestamped<CommandType>) {
        if self
            .acceptable_timestamp_range()
            .contains(&command.timestamp())
        {
            if let Some(commands_at_timestamp) = self.map.get_mut(&Reverse(command.timestamp())) {
                commands_at_timestamp.push(command.inner().clone());
            } else {
                self.map
                    .insert(Reverse(command.timestamp()), vec![command.inner().clone()]);
            }
        } else {
            warn!(
                "Tried to insert a command of timestamp {:?} outside of the acceptable range {:?}. The command {:?} is dropped",
                command.timestamp(),
                self.acceptable_timestamp_range(),
                command
            );
        }
    }

    pub fn drain_up_to(&mut self, newest_timestamp_to_drain: Timestamp) -> Vec<CommandType> {
        self.map
            .split_off(&Reverse(newest_timestamp_to_drain))
            .values()
            .rev() // Our map is in reverse order.
            .flatten()
            .cloned()
            .collect()
    }

    pub fn drain_all(&mut self) -> Vec<CommandType> {
        let commands = self.map.values().rev().flatten().cloned().collect();
        self.map.clear();
        commands
    }

    #[allow(dead_code)]
    pub fn commands_at(&self, timestamp: Timestamp) -> Option<impl Iterator<Item = &CommandType>> {
        self.map
            .get(&Reverse(timestamp))
            .map(|commands| commands.iter())
    }

    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.map.len()
    }

    pub fn iter(&self) -> impl Iterator<Item = (Timestamp, &Vec<CommandType>)> {
        self.map
            .iter()
            .rev()
            .map(|(timestamp, commands)| (timestamp.0, commands))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    impl Command for i32 {}

    #[test]
    fn when_timestamp_incremented_then_command_buffer_discards_stale_commands() {
        // GIVEN a command buffer with old commands, one of which is at the lowest extreme of the
        // acceptable range.
        let mut command_buffer = CommandBuffer::<i32>::new();
        let acceptable_range = command_buffer.acceptable_timestamp_range();
        let t = [
            acceptable_range.start,
            acceptable_range.start + 1,
            acceptable_range.end - 2,
            acceptable_range.end - 1,
        ];
        command_buffer.insert(&Timestamped::new(0, t[0]));
        command_buffer.insert(&Timestamped::new(1, t[1]));
        command_buffer.insert(&Timestamped::new(2, t[2]));
        command_buffer.insert(&Timestamped::new(3, t[3]));
        assert_eq!(
            *command_buffer.commands_at(t[0]).unwrap().next().unwrap(),
            0
        );
        assert_eq!(
            *command_buffer.commands_at(t[1]).unwrap().next().unwrap(),
            1
        );
        assert_eq!(
            *command_buffer.commands_at(t[2]).unwrap().next().unwrap(),
            2
        );
        assert_eq!(
            *command_buffer.commands_at(t[3]).unwrap().next().unwrap(),
            3
        );

        // WHEN we increment the timestamp.
        command_buffer.update_timestamp(command_buffer.timestamp() + 1);

        // THEN only the one command that now falls outside of the new acceptable range gets
        // discared.
        assert!(command_buffer.commands_at(t[0]).is_none());
        assert_eq!(
            *command_buffer.commands_at(t[1]).unwrap().next().unwrap(),
            1
        );
        assert_eq!(
            *command_buffer.commands_at(t[2]).unwrap().next().unwrap(),
            2
        );
        assert_eq!(
            *command_buffer.commands_at(t[3]).unwrap().next().unwrap(),
            3
        );
    }

    #[test]
    fn when_timestamp_decremented_then_command_buffer_discards_unripe_commands() {
        // GIVEN a command buffer with old commands, one of which is at the highest extreme of the
        // acceptable range.
        let mut command_buffer = CommandBuffer::<i32>::new();
        let acceptable_range = command_buffer.acceptable_timestamp_range();
        let t = [
            acceptable_range.start,
            acceptable_range.start + 1,
            acceptable_range.end - 2,
            acceptable_range.end - 1,
        ];
        command_buffer.insert(&Timestamped::new(0, t[0]));
        command_buffer.insert(&Timestamped::new(1, t[1]));
        command_buffer.insert(&Timestamped::new(2, t[2]));
        command_buffer.insert(&Timestamped::new(3, t[3]));
        assert_eq!(
            *command_buffer.commands_at(t[0]).unwrap().next().unwrap(),
            0
        );
        assert_eq!(
            *command_buffer.commands_at(t[1]).unwrap().next().unwrap(),
            1
        );
        assert_eq!(
            *command_buffer.commands_at(t[2]).unwrap().next().unwrap(),
            2
        );
        assert_eq!(
            *command_buffer.commands_at(t[3]).unwrap().next().unwrap(),
            3
        );

        // WHEN we decrement the timestamp.
        command_buffer.update_timestamp(command_buffer.timestamp() - 1);

        // THEN only the one command that now falls outside of the new acceptable range gets
        // discared.
        assert_eq!(
            *command_buffer.commands_at(t[0]).unwrap().next().unwrap(),
            0
        );
        assert_eq!(
            *command_buffer.commands_at(t[1]).unwrap().next().unwrap(),
            1
        );
        assert_eq!(
            *command_buffer.commands_at(t[2]).unwrap().next().unwrap(),
            2
        );
        assert!(command_buffer.commands_at(t[3]).is_none());
    }

    #[test]
    fn when_inserting_command_outside_acceptable_range_then_command_is_discarded() {
        // GIVEN an empty command buffer
        let mut command_buffer = CommandBuffer::<i32>::new();

        // WHEN we insert commands, some of which are outside the acceptable range.
        let acceptable_range = command_buffer.acceptable_timestamp_range();
        let t = [
            acceptable_range.start - 1,
            acceptable_range.start,
            acceptable_range.end - 1,
            acceptable_range.end,
            acceptable_range.end + Timestamp::MAX_COMPARABLE_RANGE / 2,
        ];
        command_buffer.insert(&Timestamped::new(0, t[0]));
        command_buffer.insert(&Timestamped::new(1, t[1]));
        command_buffer.insert(&Timestamped::new(2, t[2]));
        command_buffer.insert(&Timestamped::new(3, t[3]));
        command_buffer.insert(&Timestamped::new(4, t[4]));
        assert!(command_buffer.commands_at(t[0]).is_none());
        assert_eq!(
            *command_buffer.commands_at(t[1]).unwrap().next().unwrap(),
            1
        );
        assert_eq!(
            *command_buffer.commands_at(t[2]).unwrap().next().unwrap(),
            2
        );
        assert!(command_buffer.commands_at(t[3]).is_none());
        assert!(command_buffer.commands_at(t[4]).is_none());
    }

    #[test]
    fn test_drain_up_to() {
        // GIVEN a command buffer with several commands.
        let mut command_buffer = CommandBuffer::<i32>::new();
        command_buffer.insert(&Timestamped::new(0, command_buffer.timestamp() + 1));
        command_buffer.insert(&Timestamped::new(1, command_buffer.timestamp() + 5));
        command_buffer.insert(&Timestamped::new(2, command_buffer.timestamp() + 2));
        command_buffer.insert(&Timestamped::new(3, command_buffer.timestamp() + 4));
        command_buffer.insert(&Timestamped::new(4, command_buffer.timestamp() + 8));
        command_buffer.insert(&Timestamped::new(5, command_buffer.timestamp() + 6));
        command_buffer.insert(&Timestamped::new(6, command_buffer.timestamp() + 7));
        command_buffer.insert(&Timestamped::new(7, command_buffer.timestamp() + 3));

        // WHEN we drain the command buffer up to a certain timestamp.
        let drained_commands = command_buffer.drain_up_to(command_buffer.timestamp() + 4);

        // THEN we get the commands up to and including the specified timestamp, in order.
        assert_eq!(drained_commands.len(), 4);
        assert_eq!(drained_commands[0], 0);
        assert_eq!(drained_commands[1], 2);
        assert_eq!(drained_commands[2], 7);
        assert_eq!(drained_commands[3], 3);

        // THEN we the command buffer will have discarded commands up to and including the
        // specified timestamp, while keeping the other commands.
        assert!(command_buffer
            .commands_at(command_buffer.timestamp() + 1)
            .is_none());
        assert!(command_buffer
            .commands_at(command_buffer.timestamp() + 2)
            .is_none());
        assert!(command_buffer
            .commands_at(command_buffer.timestamp() + 3)
            .is_none());
        assert!(command_buffer
            .commands_at(command_buffer.timestamp() + 4)
            .is_none());
        assert_eq!(
            *command_buffer
                .commands_at(command_buffer.timestamp() + 5)
                .unwrap()
                .next()
                .unwrap(),
            1
        );
        assert_eq!(
            *command_buffer
                .commands_at(command_buffer.timestamp() + 6)
                .unwrap()
                .next()
                .unwrap(),
            5
        );
        assert_eq!(
            *command_buffer
                .commands_at(command_buffer.timestamp() + 7)
                .unwrap()
                .next()
                .unwrap(),
            6
        );
        assert_eq!(
            *command_buffer
                .commands_at(command_buffer.timestamp() + 8)
                .unwrap()
                .next()
                .unwrap(),
            4
        );
    }
}