source2-demo 0.5.0

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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
use crate::parser::Context;
use crate::proto::*;
use crate::{Entity, EntityEvents, GameEvent, StringTable};
use std::cell::RefCell;
use std::rc::Rc;

#[cfg(feature = "dota")]
use crate::event::CombatLogEntry;

/// Result type for observer callbacks.
///
/// This is a convenience alias for `anyhow::Result<()>`.
///
/// Methods generated by the `#[observer]` macro may also return
/// `Result<(), ParserError>` or another `Result` whose error can convert into
/// `anyhow::Error`. Concrete error types, including `ParserError`, are kept
/// inside the `anyhow::Error` and can be recovered with downcasting from
/// [`ParserError::ObserverError`](crate::error::ParserError::ObserverError).
///
/// # Examples
///
/// ```no_run
/// use source2_demo::prelude::*;
///
/// #[derive(Default)]
/// struct FailingObserver;
///
/// #[observer]
/// impl FailingObserver {
///     #[on_tick_start]
///     fn on_tick_start(&mut self) -> Result<(), ParserError> {
///         Err(ParserError::WrongMagic)
///     }
/// }
///
/// let mut parser = Parser::from_reader(std::fs::File::open("replay.dem")?)?;
/// parser.register_observer::<FailingObserver>();
///
/// match parser.run_to_end() {
///     Err(ParserError::ObserverError(error)) => {
///         if let Some(ParserError::WrongMagic) = error.downcast_ref::<ParserError>() {
///             println!("observer returned ParserError::WrongMagic");
///         }
///     }
///     Err(error) => {
///         println!("parser error: {error}");
///     }
///     Ok(()) => {}
/// }
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub type ObserverResult = anyhow::Result<()>;

bitflags::bitflags! {
    /// Bitflags for declaring observer interests.
    ///
    /// Use these flags in the [`Observer::interests`] method to specify which
    /// events your observer wants to receive. This allows the parser to skip
    /// unnecessary processing for events no observer cares about.
    ///
    /// # Examples
    ///
    /// ```
    /// use source2_demo::prelude::*;
    ///
    /// #[derive(Default)]
    /// struct EntityTracker;
    ///
    /// impl Observer for EntityTracker {
    ///     fn interests(&self) -> Interests {
    ///         // Track entities and receive tick events
    ///         Interests::ENTITY_STATE | Interests::ENTITY_EVENTS | Interests::TICK_START
    ///     }
    ///
    ///     fn on_entity(&mut self, ctx: &Context, event: EntityEvents, entity: &Entity) -> ObserverResult {
    ///         // Handle entity updates
    ///         Ok(())
    ///     }
    ///
    ///     fn on_tick_start(&mut self, ctx: &Context) -> ObserverResult {
    ///         // Handle tick start
    ///         Ok(())
    ///     }
    /// }
    /// ```
    #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
    pub struct Interests: u64 {
        /// Interest in outer demo messages (`EDemoCommands`).
        const DEMO_MESSAGE = 1 << 0;
        /// Interest in net messages (`NetMessages`).
        const NET_MESSAGE = 1 << 1;
        /// Interest in SVC messages (`SvcMessages`).
        const SVC_MESSAGE = 1 << 2;

        /// Interest in base user messages (`EBaseUserMessages`).
        const BASE_USER_MESSAGE = 1 << 3;
        /// Interest in base game events (`EBaseGameEvents`) and decoded game events.
        const BASE_GAME_EVENT = 1 << 4;

        /// Interest in tick start events.
        const TICK_START = 1 << 5;
        /// Interest in tick end events.
        const TICK_END = 1 << 6;

        /// Maintain entity state while parsing.
        const ENTITY_STATE = 1 << 7;
        /// Interest in entity create/update/delete events.
        const ENTITY_EVENTS = 1 << 8;
        /// Maintain string table state while parsing.
        const STRING_TABLE_STATE = 1 << 9;
        /// Interest in string table update events.
        const STRING_TABLE_ENTRIES = 1 << 10;

        /// Interest in the replay end event.
        const REPLAY_END = 1 << 11;

        #[cfg(feature = "dota")]
        /// Interest in Dota 2 user messages (`EDotaUserMessages`).
        const DOTA_USER_MESSAGE = 1 << 12;

        #[cfg(feature = "dota")]
        /// Interest in combat log entries (Dota 2 only).
        const COMBAT_LOG_ENTRIES = 1 << 13;


        #[cfg(feature = "deadlock")]
        /// Interest in Citadel/Deadlock user messages (`CitadelUserMessageIds`).
        const CITADEL_USER_MESSAGE = 1 << 14;

        #[cfg(feature = "deadlock")]
        /// Interest in Citadel/Deadlock game events (`ECitadelGameEvents`).
        const CITADEL_GAME_EVENT = 1 << 15;

        #[cfg(feature = "cs2")]
        /// Interest in CS2 user messages (`ECstrike15UserMessages`).
        const CS2_USER_MESSAGE = 1 << 16;

        #[cfg(feature = "cs2")]
        /// Interest in CS2 game events (`ECsgoGameEvents`).
        const CS2_GAME_EVENT = 1 << 17;
    }
}

/// Observer trait for handling demo file events.
///
/// Implement this trait to receive callbacks as the parser processes the demo
/// file. You can either implement it manually or use the `#[observer]`
/// attribute macro for a more convenient approach.
///
/// # Interest-based Filtering
///
/// The [`interests`](Observer::interests) method allows you to declare which
/// events your observer wants to receive. This is crucial for performance as it
/// allows the parser to skip processing events that no observer cares about.
///
/// # Examples
///
/// ## Using the `#[observer]` macro (recommended)
///
/// ```ignore
/// use source2_demo::prelude::*;
/// use source2_demo_protobufs::CDotaUserMsgChatMessage;
///
/// #[derive(Default)]
/// struct GameStats {
///     combat_logs: u32,
///     messages: u32,
/// }
///
/// #[observer]
/// impl GameStats {
///     #[on_message]
///     fn on_chat_msg(&mut self, ctx: &Context, msg: CDotaUserMsgChatMessage) -> ObserverResult {
///         self.messages += 1;
///         Ok(())
///     }
///
///     #[on_combat_log]
///     fn on_combat_log(&mut self, ctx: &Context, entry: &CombatLogEntry) -> ObserverResult {
///         self.combat_logs += 1;
///         Ok(())
///     }
/// }
/// ```
///
/// ## Manual implementation
///
/// ```no_run
/// use source2_demo::prelude::*;
///
/// #[derive(Default)]
/// struct EntityCounter {
///     count: usize,
/// }
///
/// impl Observer for EntityCounter {
///     fn interests(&self) -> Interests {
///         Interests::ENTITY_STATE | Interests::ENTITY_EVENTS
///     }
///
///     fn on_entity(
///         &mut self,
///         ctx: &Context,
///         event: EntityEvents,
///         entity: &Entity,
///     ) -> ObserverResult {
///         if event == EntityEvents::Created {
///             self.count += 1;
///         }
///         Ok(())
///     }
/// }
/// ```
///
/// ## Combining multiple interests
///
/// ```no_run
/// use source2_demo::prelude::*;
///
/// #[derive(Default)]
/// struct MultiObserver;
///
/// impl Observer for MultiObserver {
///     fn interests(&self) -> Interests {
///         Interests::TICK_START
///             | Interests::TICK_END
///             | Interests::ENTITY_STATE
///             | Interests::ENTITY_EVENTS
///     }
///
///     fn on_tick_start(&mut self, ctx: &Context) -> ObserverResult {
///         println!("Tick {}", ctx.tick());
///         Ok(())
///     }
///
///     fn on_entity(
///         &mut self,
///         ctx: &Context,
///         event: EntityEvents,
///         entity: &Entity,
///     ) -> ObserverResult {
///         // Process entities
///         Ok(())
///     }
/// }
/// ```
#[allow(unused_variables)]
pub trait Observer {
    /// Declares which events this observer is interested in.
    ///
    /// Return an empty [`Interests`] to receive no events, or combine flags
    /// using the `|` operator. This method is called once when the observer
    /// is registered.
    ///
    /// # Default
    ///
    /// Returns [`Interests::empty()`] by default (no events).
    fn interests(&self) -> Interests {
        Interests::empty()
    }

    /// Called when a demo command is received.
    ///
    /// Requires [`Interests::DEMO_MESSAGE`] to be set.
    #[cold]
    #[inline(never)]
    fn on_demo_command(
        &mut self,
        ctx: &Context,
        msg_type: EDemoCommands,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called when a net message is received.
    ///
    /// Requires [`Interests::NET_MESSAGE`] to be set.
    #[cold]
    #[inline(never)]
    fn on_net_message(
        &mut self,
        ctx: &Context,
        msg_type: NetMessages,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called when an SVC (server-to-client) message is received.
    ///
    /// Requires [`Interests::SVC_MESSAGE`] to be set.
    #[cold]
    #[inline(never)]
    fn on_svc_message(
        &mut self,
        ctx: &Context,
        msg_type: SvcMessages,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called when a base user message is received.
    ///
    /// Requires [`Interests::BASE_USER_MESSAGE`] to be set.
    #[cold]
    #[inline(never)]
    fn on_base_user_message(
        &mut self,
        ctx: &Context,
        msg_type: EBaseUserMessages,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called when a base game event is received.
    ///
    /// Requires [`Interests::BASE_GAME_EVENT`] to be set.
    #[cold]
    #[inline(never)]
    fn on_base_game_event(
        &mut self,
        ctx: &Context,
        msg_type: EBaseGameEvents,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called at the start of each tick.
    ///
    /// Requires [`Interests::TICK_START`] to be set.
    #[cold]
    #[inline(never)]
    fn on_tick_start(&mut self, ctx: &Context) -> ObserverResult {
        Ok(())
    }

    /// Called at the end of each tick.
    ///
    /// Requires [`Interests::TICK_END`] to be set.
    #[cold]
    #[inline(never)]
    fn on_tick_end(&mut self, ctx: &Context) -> ObserverResult {
        Ok(())
    }

    /// Called when an entity is created, updated, or deleted.
    ///
    /// Requires [`Interests::ENTITY_EVENTS`] and [`Interests::ENTITY_STATE`] to
    /// be set.
    #[cold]
    #[inline(never)]
    fn on_entity(&mut self, ctx: &Context, event: EntityEvents, entity: &Entity) -> ObserverResult {
        Ok(())
    }

    /// Called when a game event occurs.
    ///
    /// Requires [`Interests::BASE_GAME_EVENT`] to be set.
    #[cold]
    #[inline(never)]
    fn on_game_event(&mut self, ctx: &Context, ge: &GameEvent) -> ObserverResult {
        Ok(())
    }

    /// Called when a string table is updated.
    ///
    /// Requires [`Interests::STRING_TABLE_ENTRIES`] and
    /// [`Interests::STRING_TABLE_STATE`] to be set.
    #[cold]
    #[inline(never)]
    fn on_string_table(
        &mut self,
        ctx: &Context,
        st: &StringTable,
        modified: &[i32],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called when the replay ends.
    ///
    /// Requires [`Interests::REPLAY_END`] to be set.
    /// This is the last callback before parsing completes.
    ///
    /// # Arguments
    ///
    /// * `ctx` - Current replay context
    #[cold]
    #[inline(never)]
    fn on_stop(&mut self, ctx: &Context) -> ObserverResult {
        Ok(())
    }

    /// Called when a combat log entry is received (Dota 2 only).
    ///
    /// Combat log entries describe in-game events like damage, healing, kills,
    /// etc. Only available with the `dota` feature enabled.
    ///
    /// Requires [`Interests::COMBAT_LOG_ENTRIES`] to be set.
    #[cold]
    #[inline(never)]
    #[cfg(feature = "dota")]
    fn on_combat_log(&mut self, ctx: &Context, cle: &CombatLogEntry) -> ObserverResult {
        Ok(())
    }

    /// Called when a Dota 2 user message is received.
    ///
    /// Dota 2 specific user messages. Only available with the `dota` feature
    /// enabled.
    ///
    /// Requires [`Interests::DOTA_USER_MESSAGE`] to be set.
    #[cold]
    #[inline(never)]
    #[cfg(feature = "dota")]
    fn on_dota_user_message(
        &mut self,
        ctx: &Context,
        msg_type: EDotaUserMessages,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called when a Citadel/Deadlock game event is received.
    ///
    /// Deadlock specific game events. Only available with the `deadlock`
    /// feature enabled.
    ///
    /// Requires [`Interests::CITADEL_GAME_EVENT`] to be set.
    #[cold]
    #[inline(never)]
    #[cfg(feature = "deadlock")]
    fn on_citadel_game_event(
        &mut self,
        ctx: &Context,
        msg_type: ECitadelGameEvents,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called when a Citadel/Deadlock user message is received.
    ///
    /// Deadlock specific user messages. Only available with the `deadlock`
    /// feature enabled.
    ///
    /// Requires [`Interests::CITADEL_USER_MESSAGE`] to be set.
    #[cold]
    #[inline(never)]
    #[cfg(feature = "deadlock")]
    fn on_citadel_user_message(
        &mut self,
        ctx: &Context,
        msg_type: CitadelUserMessageIds,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called when a Counter-Strike 2 user message is received.
    ///
    /// CS2 specific user messages. Only available with the `cs2` feature
    /// enabled.
    ///
    /// Requires [`Interests::CS2_USER_MESSAGE`] to be set.
    #[cold]
    #[inline(never)]
    #[cfg(feature = "cs2")]
    fn on_cs2_user_message(
        &mut self,
        ctx: &Context,
        msg_type: ECstrike15UserMessages,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }

    /// Called when a Counter-Strike 2 game event is received.
    ///
    /// CS2 specific game events. Only available with the `cs2` feature enabled.
    ///
    /// Requires [`Interests::CS2_GAME_EVENT`] to be set.
    #[cold]
    #[inline(never)]
    #[cfg(feature = "cs2")]
    fn on_cs2_game_event(
        &mut self,
        ctx: &Context,
        msg_type: ECsgoGameEvents,
        msg: &[u8],
    ) -> ObserverResult {
        Ok(())
    }
}

impl<T> Observer for Rc<RefCell<T>>
where
    T: Observer,
{
    fn interests(&self) -> Interests {
        self.borrow().interests()
    }

    fn on_demo_command(
        &mut self,
        ctx: &Context,
        msg_type: EDemoCommands,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut().on_demo_command(ctx, msg_type, msg)
    }

    fn on_net_message(
        &mut self,
        ctx: &Context,
        msg_type: NetMessages,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut().on_net_message(ctx, msg_type, msg)
    }

    fn on_svc_message(
        &mut self,
        ctx: &Context,
        msg_type: SvcMessages,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut().on_svc_message(ctx, msg_type, msg)
    }

    fn on_base_user_message(
        &mut self,
        ctx: &Context,
        msg_type: EBaseUserMessages,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut().on_base_user_message(ctx, msg_type, msg)
    }

    fn on_base_game_event(
        &mut self,
        ctx: &Context,
        msg_type: EBaseGameEvents,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut().on_base_game_event(ctx, msg_type, msg)
    }

    fn on_tick_start(&mut self, ctx: &Context) -> ObserverResult {
        self.borrow_mut().on_tick_start(ctx)
    }

    fn on_tick_end(&mut self, ctx: &Context) -> ObserverResult {
        self.borrow_mut().on_tick_end(ctx)
    }

    fn on_entity(&mut self, ctx: &Context, event: EntityEvents, entity: &Entity) -> ObserverResult {
        self.borrow_mut().on_entity(ctx, event, entity)
    }

    fn on_game_event(&mut self, ctx: &Context, ge: &GameEvent) -> ObserverResult {
        self.borrow_mut().on_game_event(ctx, ge)
    }

    fn on_string_table(
        &mut self,
        ctx: &Context,
        st: &StringTable,
        modified: &[i32],
    ) -> ObserverResult {
        self.borrow_mut().on_string_table(ctx, st, modified)
    }

    fn on_stop(&mut self, ctx: &Context) -> ObserverResult {
        self.borrow_mut().on_stop(ctx)
    }

    #[cfg(feature = "dota")]
    fn on_combat_log(&mut self, ctx: &Context, cle: &CombatLogEntry) -> ObserverResult {
        self.borrow_mut().on_combat_log(ctx, cle)
    }

    #[cfg(feature = "dota")]
    fn on_dota_user_message(
        &mut self,
        ctx: &Context,
        msg_type: EDotaUserMessages,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut().on_dota_user_message(ctx, msg_type, msg)
    }

    #[cfg(feature = "deadlock")]
    fn on_citadel_game_event(
        &mut self,
        ctx: &Context,
        msg_type: ECitadelGameEvents,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut().on_citadel_game_event(ctx, msg_type, msg)
    }

    #[cfg(feature = "deadlock")]
    fn on_citadel_user_message(
        &mut self,
        ctx: &Context,
        msg_type: CitadelUserMessageIds,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut()
            .on_citadel_user_message(ctx, msg_type, msg)
    }

    #[cfg(feature = "cs2")]
    fn on_cs2_user_message(
        &mut self,
        ctx: &Context,
        msg_type: ECstrike15UserMessages,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut().on_cs2_user_message(ctx, msg_type, msg)
    }

    #[cfg(feature = "cs2")]
    fn on_cs2_game_event(
        &mut self,
        ctx: &Context,
        msg_type: ECsgoGameEvents,
        msg: &[u8],
    ) -> ObserverResult {
        self.borrow_mut().on_cs2_game_event(ctx, msg_type, msg)
    }
}