source2-demo 0.4.2

Dota 2 / Deadlock / CS2 replay parser written in Rust
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
mod context;
mod demo;
mod observer;

pub use context::*;
pub use demo::runner::*;
pub use observer::*;

use crate::error::*;
use crate::proto::*;
use crate::reader::*;
use std::cell::RefCell;
use std::rc::Rc;

use crate::parser::demo::DemoCommands;
use crate::try_observers;
#[cfg(feature = "dota")]
use std::collections::VecDeque;

/// Main parser for Source 2 demo files.
///
/// The parser maintains the replay state and processes demo commands sequentially.
/// It supports multiple observers that can react to different types of events.
///
/// # Examples
///
/// ## Basic usage with chat messages
///
/// ```no_run
/// use source2_demo::prelude::*;
///
/// #[derive(Default)]
/// struct ChatLogger;
///
/// #[observer]
/// impl ChatLogger {
///     #[on_message]
///     fn on_chat(&mut self, ctx: &Context, msg: CDotaUserMsgChatMessage) -> ObserverResult {
///         println!("{}", msg.message_text());
///         Ok(())
///     }
/// }
///
/// fn main() -> anyhow::Result<()> {
///     let replay = std::fs::File::open("replay.dem")?;
///
///     let mut parser = Parser::from_reader(&replay)?;
///     parser.register_observer::<ChatLogger>();
///     parser.run_to_end()?;
///
///     Ok(())
/// }
/// ```
///
/// ## Processing entities
///
/// ```no_run
/// use source2_demo::prelude::*;
///
/// #[derive(Default)]
/// struct HeroTracker;
///
/// impl Observer for HeroTracker {
///     fn interests(&self) -> Interests {
///         Interests::ENABLE_ENTITY | Interests::TRACK_ENTITY
///     }
///
///     fn on_entity(&mut self, ctx: &Context, event: EntityEvents, entity: &Entity) -> ObserverResult {
///         if entity.class().name().starts_with("CDOTA_Unit_Hero_") {
///             let health: i32 = property!(entity, "m_iHealth");
///             println!("Hero {} health: {}", entity.class().name(), health);
///         }
///         Ok(())
///     }
/// }
/// # fn main() {}
/// ```
pub struct Parser<'a, R = SliceReader<'a>>
where
    R: BitsReader + MessageReader,
{
    pub(crate) reader: R,
    pub(crate) field_reader: FieldReader,

    pub(crate) observers: Vec<Rc<RefCell<dyn Observer + 'a>>>,
    pub(crate) observer_masks: Vec<Interests>,
    pub(crate) global_mask: Interests,

    #[cfg(feature = "dota")]
    pub(crate) combat_log: VecDeque<CMsgDotaCombatLogEntry>,

    pub(crate) prologue_completed: bool,
    pub(crate) skip_deltas: bool,

    pub(crate) replay_info: CDemoFileInfo,
    pub(crate) last_tick: u32,
    pub(crate) context: Context,

    _phantom: std::marker::PhantomData<&'a ()>,
}

impl<'a> Parser<'a, SliceReader<'a>> {
    /// Creates a new parser instance from replay bytes.
    ///
    /// This method validates the replay file format and reads the file header.
    /// The replay data should remain valid for the lifetime of the parser.
    ///
    /// # Arguments
    ///
    /// * `replay` - Byte slice containing the demo file data (typically memory-mapped)
    ///
    /// # Errors
    ///
    /// Returns [`ParserError::WrongMagic`] if the file is not a valid Source 2 demo file.
    /// Returns [`ParserError::ReplayEncodingError`] if the file header is corrupted.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use source2_demo::prelude::*;
    /// use std::fs::File;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// // Using memory-mapped file (recommended for large files)
    /// let file = File::open("replay.dem")?;
    /// let replay = unsafe { memmap2::Mmap::map(&file)? };
    /// let parser = Parser::new(&replay)?;
    ///
    /// // Or read into memory (for small files)
    /// let replay = std::fs::read("replay.dem")?;
    /// let parser = Parser::new(&replay)?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(replay: &'a [u8]) -> Result<Self, ParserError> {
        let mut reader = SliceReader::new(replay);

        if replay.len() < 16 || reader.read_bytes(8) != b"PBDEMS2\0" {
            return Err(ParserError::WrongMagic);
        };

        reader.read_bytes(8);

        let replay_info = reader.read_replay_info()?;
        let last_tick = replay_info.playback_ticks() as u32;

        reader.seek(16);

        Ok(Parser {
            reader,
            field_reader: FieldReader::default(),

            observers: Vec::default(),
            observer_masks: Vec::default(),
            global_mask: Interests::empty(),

            #[cfg(feature = "dota")]
            combat_log: VecDeque::default(),

            prologue_completed: false,
            skip_deltas: false,

            context: Context::new(replay_info.clone()),

            replay_info,
            last_tick,
            _phantom: std::marker::PhantomData,
        })
    }

    /// Creates a new parser from replay bytes (same as `new`).
    ///
    /// This is an alias for [`Parser::new`] that makes it explicit if you're using a slice.
    ///
    /// # Arguments
    ///
    /// * `replay` - Byte slice containing the demo file data
    ///
    /// # Errors
    ///
    /// Returns [`ParserError::WrongMagic`] if the file is not a valid Source 2 demo file.
    #[inline]
    pub fn from_slice(replay: &'a [u8]) -> Result<Self, ParserError> {
        Self::new(replay)
    }
}

impl<S> Parser<'static, SeekableReader<S>>
where
    S: std::io::Read + std::io::Seek,
{
    /// Creates a new parser from a reader.
    ///
    /// Uses SeekableReader for reading data from the reader, but internally uses
    /// SliceReader for parsing message buffers for maximum performance.
    ///
    /// # Arguments
    ///
    /// * `reader` - Any type implementing Read + Seek (e.g., File, Cursor, BufReader)
    ///
    /// # Errors
    ///
    /// Returns an error if reading from the reader fails or data is invalid.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use source2_demo::prelude::*;
    /// use std::fs::File;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let file = File::open("replay.dem")?;
    /// let mut parser = Parser::from_reader(file)?;
    /// parser.run_to_end()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_reader(reader: S) -> Result<Self, ParserError> {
        let mut reader = SeekableReader::new(reader)
            .map_err(|e| ParserError::IoError(e.to_string()))?;

        // Validate magic header
        let magic = reader.read_bytes(8);
        if magic != b"PBDEMS2\0" {
            return Err(ParserError::WrongMagic);
        }

        reader.read_bytes(8);

        // Read file info
        let replay_info = Self::read_file_info_from_reader(&mut reader)?;
        let last_tick = replay_info.playback_ticks() as u32;

        // Reset to position after header
        reader.seek(16);

        Ok(Parser {
            reader,
            field_reader: FieldReader::default(),
            observers: Vec::default(),
            observer_masks: Vec::default(),
            global_mask: Interests::empty(),

            #[cfg(feature = "dota")]
            combat_log: VecDeque::default(),

            prologue_completed: false,
            skip_deltas: false,

            context: Context::new(replay_info.clone()),
            
            replay_info,
            last_tick,
            _phantom: std::marker::PhantomData,
        })
    }

    fn read_file_info_from_reader(reader: &mut SeekableReader<S>) -> Result<CDemoFileInfo, ParserError> {
        reader.seek(8);
        let offset_bytes = reader.read_bytes(4);
        let offset = u32::from_le_bytes([offset_bytes[0], offset_bytes[1], offset_bytes[2], offset_bytes[3]]) as usize;

        reader.seek(offset);

        if let Some(msg) = reader.read_next_message()? {
            Ok(CDemoFileInfo::decode(msg.buf.as_slice())?)
        } else {
            Err(ParserError::ReplayEncodingError)
        }
    }
}

impl<'a, R> Parser<'a, R>
where
    R: BitsReader + MessageReader,
{
    /// Returns a reference to the current parser context.
    ///
    /// The context contains the current state of the replay, including
    /// - Entities and their properties
    /// - String tables
    /// - Game events
    /// - Current tick and game build
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use source2_demo::prelude::*;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// # let replay = std::fs::File::open("replay.dem")?;
    /// let parser = Parser::from_reader(&replay)?;
    /// let ctx = parser.context();
    /// println!("Current tick: {}", ctx.tick());
    /// println!("Game build: {}", ctx.game_build());
    /// # Ok(())
    /// # }
    /// ```
    pub fn context(&self) -> &Context {
        &self.context
    }

    /// Returns replay file information.
    /// Contains metadata about the replay including:
    /// - Playback duration
    /// - Server information
    /// - Game-specific details
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use source2_demo::prelude::*;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// # let replay = std::fs::File::open("replay.dem")?;
    /// let parser = Parser::from_reader(&replay)?;
    /// let info = parser.replay_info();
    /// println!("Playback ticks: {}", info.playback_ticks());
    /// # Ok(())
    /// # }
    /// ```
    pub fn replay_info(&self) -> &CDemoFileInfo {
        &self.replay_info
    }

    /// Registers an observer and returns a reference-counted handle to it.
    ///
    /// Observers must implement the [`Observer`] trait and [`Default`].
    /// Use the `#[observer]` attribute macro to automatically implement the trait.
    ///
    /// The returned `Rc<RefCell<T>>` allows you to access the observer's state
    /// after parsing completes.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Observer type that implements [`Observer`] and [`Default`]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use source2_demo::prelude::*;
    /// use std::cell::RefCell;
    /// use std::rc::Rc;
    ///
    /// #[derive(Default)]
    /// struct Stats {
    ///     message_count: usize,
    /// }
    ///
    /// #[observer]
    /// impl Stats {
    ///     #[on_message]
    ///     fn on_chat(&mut self, ctx: &Context, msg: CDotaUserMsgChatMessage) -> ObserverResult {
    ///         self.message_count += 1;
    ///         Ok(())
    ///     }
    /// }
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// # let replay = std::fs::File::open("replay.dem")?;
    /// let mut parser = Parser::from_reader(&replay)?;
    /// let stats = parser.register_observer::<Stats>();
    /// parser.run_to_end()?;
    ///
    /// println!("Total messages: {}", stats.borrow().message_count);
    /// # Ok(())
    /// # }
    /// ```
    pub fn register_observer<T>(&mut self) -> Rc<RefCell<T>>
    where
        T: Observer + Default + 'a,
    {
        let rc = Rc::new(RefCell::new(T::default()));
        let mask = rc.borrow().interests();
        self.global_mask |= mask;
        self.observer_masks.push(mask);
        self.observers.push(rc.clone());
        rc.clone()
    }

    #[inline]
    fn anyone_interested(&self, flag: Interests) -> bool {
        self.global_mask.intersects(flag)
    }

    pub(crate) fn prologue(&mut self) -> Result<(), ParserError> {
        if self.prologue_completed && self.context.tick != u32::MAX {
            return Ok(());
        }

        while let Some(message) = self.reader.read_next_message()? {
            if self.prologue_completed
                && (message.msg_type == EDemoCommands::DemSendTables
                    || message.msg_type == EDemoCommands::DemClassInfo)
            {
                continue;
            }

            self.on_demo_command(message.msg_type, message.buf.as_slice())?;

            if message.msg_type == EDemoCommands::DemSyncTick {
                self.prologue_completed = true;
                break;
            }
        }

        Ok(())
    }

    pub(crate) fn on_demo_command(
        &mut self,
        msg_type: EDemoCommands,
        msg: &[u8],
    ) -> Result<(), ParserError> {
        match msg_type {
            EDemoCommands::DemSendTables => {
                self.dem_send_tables(CDemoSendTables::decode(msg)?)?;
            }
            EDemoCommands::DemClassInfo => {
                self.dem_class_info(CDemoClassInfo::decode(msg)?)?;
            }
            EDemoCommands::DemPacket | EDemoCommands::DemSignonPacket => {
                self.dem_packet(CDemoPacket::decode(msg)?)?;
            }
            EDemoCommands::DemFullPacket => self.dem_full_packet(CDemoFullPacket::decode(msg)?)?,
            EDemoCommands::DemStringTables => {
                self.dem_string_tables(CDemoStringTables::decode(msg)?)?
            }
            EDemoCommands::DemStop => {
                self.dem_stop()?;
            }
            _ => {}
        };

        try_observers!(self, DEMO, on_demo_command(&self.context, msg_type, msg))?;
        Ok(())
    }
}

impl<S> Parser<'static, SeekableReader<S>>
where
    S: std::io::Read + std::io::Seek,
{
    /// Extracts match details from a Deadlock replay.
    ///
    /// This method scans through the replay to find and extract post-match details
    /// specific to Deadlock games. It searches for the `KEUserMsgPostMatchDetails`
    /// message and returns the decoded match metadata.
    ///
    /// # Errors
    ///
    /// Returns `ParserError::MatchDetailsNotFound` if the match details message
    /// cannot be found in the replay.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use source2_demo::prelude::*;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let replay = std::fs::File::open("deadlock_replay.dem")?;
    /// let mut parser = Parser::from_reader(&replay)?;
    /// let match_details = parser.deadlock_match_details()?;
    /// println!("Match ID: {:?}", match_details.match_id());
    ///
    /// Ok(())
    /// }
    /// ```
    #[cfg(feature = "deadlock")]
    pub fn deadlock_match_details(&mut self) -> Result<CMsgMatchMetaDataContents, ParserError> {
        self.reader.read_deadlock_match_details()
    }
}

impl<'a> Parser<'a, SliceReader<'a>> {
    /// Extracts match details from a Deadlock replay.
    ///
    /// This method scans through the replay to find and extract post-match details
    /// specific to Deadlock games. It searches for the `KEUserMsgPostMatchDetails`
    /// message and returns the decoded match metadata.
    ///
    /// # Errors
    ///
    /// Returns `ParserError::MatchDetailsNotFound` if the match details message
    /// cannot be found in the replay.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use source2_demo::prelude::*;
    ///
    /// # fn main() -> anyhow::Result<()> {
    /// let replay = std::fs::read("deadlock_replay.dem")?;
    /// let mut parser = Parser::new(&replay)?;
    /// let match_details = parser.deadlock_match_details()?;
    /// println!("Match ID: {:?}", match_details.match_id());
    ///
    /// Ok(())
    /// }
    /// ```
    #[cfg(feature = "deadlock")]
    pub fn deadlock_match_details(&mut self) -> Result<CMsgMatchMetaDataContents, ParserError> {
        self.reader.read_deadlock_match_details()
    }
}