This repository has been archived by the owner on Sep 22, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 78
/
DemoParser.cs
1491 lines (1227 loc) · 43.6 KB
/
DemoParser.cs
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using DemoInfo.DP;
using DemoInfo.DT;
using DemoInfo.Messages;
using DemoInfo.ST;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace DemoInfo
{
#if DEBUG
#warning The DemoParser is very slow when compiled in Debug-Mode, since we use it as that: We perform many integrity checks during runtime.
#warning Build this in Relase-Mode for more performance if you're not working the internals of the parser. (If you are, create a pull request when you're done!)
#endif
#if SAVE_PROP_VALUES
#warning You're compiling in the SavePropValues-Mode. This is a mode intended for Debugging and nothing else. It's cool to take a (entity-)dump here to find out how things work, but don't use this in production
#endif
public class DemoParser : IDisposable
{
const int MAX_EDICT_BITS = 11;
internal const int INDEX_MASK = ( ( 1 << MAX_EDICT_BITS ) - 1 );
internal const int MAX_ENTITIES = ( ( 1 << MAX_EDICT_BITS ) );
const int MAXPLAYERS = 64;
const int MAXWEAPONS = 64;
#region Events
/// <summary>
/// Raised once when the Header of the demo is parsed
/// </summary>
public event EventHandler<HeaderParsedEventArgs> HeaderParsed;
/// <summary>
/// Occurs when the match started, so when the "begin_new_match"-GameEvent is dropped.
/// This usually right before the freezetime of the 1st round. Be careful, since the players
/// usually still have warmup-money when this drops.
/// </summary>
public event EventHandler<MatchStartedEventArgs> MatchStarted;
/// <summary>
/// Occurs when the first round of a new match start "round_announce_match_start"
/// </summary>
public event EventHandler<RoundAnnounceMatchStartedEventArgs> RoundAnnounceMatchStarted;
/// <summary>
/// Occurs when round starts, on the round_start event of the demo. Usually the players haven't spawned yet, but have recieved the money for the next round.
/// </summary>
public event EventHandler<RoundStartedEventArgs> RoundStart;
/// <summary>
/// Occurs when round ends
/// </summary>
public event EventHandler<RoundEndedEventArgs> RoundEnd;
/// <summary>
/// Occurs at the end of the match, when the scoreboard is shown
/// </summary>
public event EventHandler<WinPanelMatchEventArgs> WinPanelMatch;
/// <summary>
/// Occurs when it's the last round of a match
/// </summary>
public event EventHandler<RoundFinalEventArgs> RoundFinal;
/// <summary>
/// Occurs at the half of a side
/// </summary>
public event EventHandler<LastRoundHalfEventArgs> LastRoundHalf;
/// <summary>
/// Occurs when round really ended
/// </summary>
public event EventHandler<RoundOfficiallyEndedEventArgs> RoundOfficiallyEnd;
/// <summary>
/// Occurs on round end with the MVP
/// </summary>
public event EventHandler<RoundMVPEventArgs> RoundMVP;
/// <summary>
/// Occurs when a player take control of a bot
/// </summary>
public event EventHandler<BotTakeOverEventArgs> BotTakeOver;
/// <summary>
/// Occurs when freezetime ended. Raised on "round_freeze_end"
/// </summary>
public event EventHandler<FreezetimeEndedEventArgs> FreezetimeEnded;
/// <summary>
/// Occurs on the end of every tick, after the gameevents were processed and the packet-entities updated
/// </summary>
public event EventHandler<TickDoneEventArgs> TickDone;
/// <summary>
/// This is raised when a player is killed. Not that the killer might be dead by the time is raised (e.g. nade-kills),
/// also note that the killed player is still alive when this is killed
/// </summary>
public event EventHandler<PlayerKilledEventArgs> PlayerKilled;
/// <summary>
/// Occurs when a player select a team
/// </summary>
public event EventHandler<PlayerTeamEventArgs> PlayerTeam;
/// <summary>
/// Occurs when a weapon is fired.
/// </summary>
public event EventHandler<WeaponFiredEventArgs> WeaponFired;
/// <summary>
/// Occurs when smoke nade started.
/// </summary>
public event EventHandler<SmokeEventArgs> SmokeNadeStarted;
/// <summary>
/// Occurs when smoke nade ended.
/// Hint: When a round ends, this is *not* caĺled.
/// Make sure to clear nades yourself at the end of rounds
/// </summary>
public event EventHandler<SmokeEventArgs> SmokeNadeEnded;
/// <summary>
/// Occurs when decoy nade started.
/// </summary>
public event EventHandler<DecoyEventArgs> DecoyNadeStarted;
/// <summary>
/// Occurs when decoy nade ended.
/// Hint: When a round ends, this is *not* caĺled.
/// Make sure to clear nades yourself at the end of rounds
/// </summary>
public event EventHandler<DecoyEventArgs> DecoyNadeEnded;
/// <summary>
/// Occurs when a fire nade (incendiary / molotov) started.
/// This currently *doesn't* contain who it threw since this is for some weird reason not networked
/// </summary>
public event EventHandler<FireEventArgs> FireNadeStarted;
/// <summary>
/// FireNadeStarted, but with correct ThrownBy player.
/// Hint: Raised at the end of inferno_startburn tick instead of exactly when the event is parsed
/// </summary>
public event EventHandler<FireEventArgs> FireNadeWithOwnerStarted;
/// <summary>
/// Occurs when fire nade ended.
/// Hint: When a round ends, this is *not* caĺled.
/// Make sure to clear nades yourself at the end of rounds
/// </summary>
public event EventHandler<FireEventArgs> FireNadeEnded;
/// <summary>
/// Occurs when flash nade exploded.
/// </summary>
public event EventHandler<FlashEventArgs> FlashNadeExploded;
/// <summary>
/// Occurs when explosive nade exploded.
/// </summary>
public event EventHandler<GrenadeEventArgs> ExplosiveNadeExploded;
/// <summary>
/// Occurs when any nade reached it's target.
/// </summary>
public event EventHandler<NadeEventArgs> NadeReachedTarget;
/// <summary>
/// Occurs when bomb is being planted.
/// </summary>
public event EventHandler<BombEventArgs> BombBeginPlant;
/// <summary>
/// Occurs when the plant is aborted
/// </summary>
public event EventHandler<BombEventArgs> BombAbortPlant;
/// <summary>
/// Occurs when the bomb has been planted.
/// </summary>
public event EventHandler<BombEventArgs> BombPlanted;
/// <summary>
/// Occurs when the bomb has been defused.
/// </summary>
public event EventHandler<BombEventArgs> BombDefused;
/// <summary>
/// Occurs when bomb has exploded.
/// </summary>
public event EventHandler<BombEventArgs> BombExploded;
/// <summary>
/// Occurs when someone begins to defuse the bomb.
/// </summary>
public event EventHandler<BombDefuseEventArgs> BombBeginDefuse;
/// <summary>
/// Occurs when someone aborts to defuse the bomb.
/// </summary>
public event EventHandler<BombDefuseEventArgs> BombAbortDefuse;
/// <summary>
/// Occurs when an player is attacked by another player.
/// Hint: Only occurs in GOTV-demos.
/// </summary>
public event EventHandler<PlayerHurtEventArgs> PlayerHurt;
/// <summary>
/// Occurs when player is blinded by flashbang
/// Hint: The order of the blind event and FlashNadeExploded event is not always the same
/// </summary>
public event EventHandler<BlindEventArgs> Blind;
/// <summary>
/// Occurs when the player object is first updated to reference all the necessary information
/// Hint: Event will be raised when any player with a SteamID connects, not just PlayingParticipants
/// </summary>
public event EventHandler<PlayerBindEventArgs> PlayerBind;
/// <summary>
/// Occurs when a player disconnects from the server.
/// </summary>
public event EventHandler<PlayerDisconnectEventArgs> PlayerDisconnect;
/// <summary>
/// Occurs when the server uses the "say" command
/// </summary>
public event EventHandler<SayTextEventArgs> SayText;
/// <summary>
/// Occurs when a player uses the "say" command
/// </summary>
public event EventHandler<SayText2EventArgs> SayText2;
/// <summary>
/// Occurs when the server display a player rank
/// </summary>
public event EventHandler<RankUpdateEventArgs> RankUpdate;
#endregion
/// <summary>
/// The mapname of the Demo. Only avaible after the header is parsed.
/// Is a string like "de_dust2".
/// </summary>
/// <value>The map.</value>
public string Map {
get { return Header.MapName; }
}
/// <summary>
/// The header of the demo, containing some useful information.
/// </summary>
/// <value>The header.</value>
public DemoHeader Header { get; private set; }
/// <summary>
/// Gets the participants of this game
/// </summary>
/// <value>The participants.</value>
public IEnumerable<Player> Participants {
get {
return Players.Values;
}
}
/// <summary>
/// Gets all the participants of this game, that aren't spectating.
/// </summary>
/// <value>The playing participants.</value>
public IEnumerable<Player> PlayingParticipants {
get {
return Players.Values.Where(a => a.Team != Team.Spectate);
}
}
/// <summary>
/// The stream of the demo - all the information go here
/// </summary>
private readonly IBitStream BitStream;
/// <summary>
/// A parser for DataTables. This contains the ServerClasses and DataTables.
/// </summary>
internal DataTableParser SendTableParser = new DataTableParser();
/// <summary>
/// A parser for DEM_STRINGTABLES-Packets
/// </summary>
StringTableParser StringTables = new StringTableParser();
/// <summary>
/// This maps an ServerClass to an Equipment.
/// Note that this is wrong for the CZ,M4A1 and USP-S, there is an additional fix for those
/// </summary>
internal Dictionary<ServerClass, EquipmentElement> equipmentMapping = new Dictionary<ServerClass, EquipmentElement>();
internal Dictionary<int, Player> Players = new Dictionary<int, Player>();
/// <summary>
/// Containing info about players, accessible by the entity-id
/// </summary>
internal Player[] PlayerInformations = new Player[MAXPLAYERS];
/// <summary>
/// Contains information about the players, accessible by the userid.
/// </summary>
internal PlayerInfo[] RawPlayers = new PlayerInfo[MAXPLAYERS];
/// <summary>
/// All entities currently alive in the demo.
/// </summary>
internal Entity[] Entities = new Entity[MAX_ENTITIES]; //Max 2048 entities.
/// <summary>
/// The modelprecache. With this we can tell which model an entity has.
/// Useful for finding out whetere a weapon is a P250 or a CZ
/// </summary>
internal List<string> modelprecache = new List<string> ();
/// <summary>
/// The string tables sent by the server.
/// </summary>
internal List<CreateStringTable> stringTables = new List<CreateStringTable>();
/// <summary>
/// An map entity <-> weapon. Used to remember whether a weapon is a p250,
/// how much ammonition it has, etc.
/// </summary>
Equipment[] weapons = new Equipment[MAX_ENTITIES];
/// <summary>
/// The indicies of the bombsites - useful to find out
/// where the bomb is planted
/// </summary>
internal int bombsiteAIndex = -1, bombsiteBIndex = -1;
internal Vector bombsiteACenter, bombsiteBCenter;
/// <summary>
/// The ID of the CT-Team
/// </summary>
internal int ctID = -1;
/// <summary>
/// The ID of the terrorist team
/// </summary>
internal int tID = -1;
/// <summary>
/// The Rounds the Counter-Terrorists have won at this point.
/// </summary>
/// <value>The CT score.</value>
public int CTScore {
get;
private set;
}
/// <summary>
/// The Rounds the Terrorists have won at this point.
/// </summary>
/// <value>The T score.</value>
public int TScore {
get;
private set;
}
/// <summary>
/// The clan name of the Counter-Terrorists
/// </summary>
/// <value>The name of the CT clan.</value>
public string CTClanName {
get;
private set;
}
/// <summary>
/// The clan name of the Terrorists
/// </summary>
/// <value>The name of the T clan.</value>
public string TClanName {
get;
private set;
}
/// <summary>
/// The flag of the Counter-Terrorists
/// </summary>
/// <value>The flag of the CT clan.</value>
public string CTFlag
{
get;
private set;
}
/// <summary>
/// The flag of the Terrorists
/// </summary>
/// <value>The flag of the T clan.</value>
public string TFlag
{
get;
private set;
}
/// <summary>
/// And GameEvent is just sent with ID |--> Value, but we need Name |--> Value.
/// Luckily these contain a map ID |--> Name.
/// </summary>
internal Dictionary<int, GameEventList.Descriptor> GEH_Descriptors = null;
/// <summary>
/// The blind players, so we can tell who was flashed by a flashbang.
/// previous blind implementation
/// </summary>
internal List<Player> GEH_BlindPlayers = new List<Player>();
/// <summary>
/// Holds inferno_startburn event args so they can be matched with player
/// </summary>
internal Queue<Tuple<int, FireEventArgs>> GEH_StartBurns = new Queue<Tuple<int, FireEventArgs>>();
// These could be Dictionary<int, RecordedPropertyUpdate[]>, but I was too lazy to
// define that class. Also: It doesn't matter anyways, we always have to cast.
/// <summary>
/// The preprocessed baselines, useful to create entities fast
/// </summary>
internal Dictionary<int, object[]> PreprocessedBaselines = new Dictionary<int, object[]>();
/// <summary>
/// The instance baselines.
/// When a new edict is created one would need to send all the information twice.
/// Since this is (was) expensive, valve sends an instancebaseline, which contains defaults
/// for all the properties.
/// </summary>
internal Dictionary<int, byte[]> instanceBaseline = new Dictionary<int, byte[]>();
/// <summary>
/// The tickrate *of the demo* (16 for normal GOTV-demos)
/// </summary>
/// <value>The tick rate.</value>
public float TickRate {
get { return this.Header.PlaybackFrames / this.Header.PlaybackTime; }
}
/// <summary>
/// How long a tick of the demo is in s^-1
/// </summary>
/// <value>The tick time.</value>
public float TickTime {
get { return this.Header.PlaybackTime / this.Header.PlaybackFrames; }
}
/// <summary>
/// Gets the parsing progess. 0 = beginning, ~1 = finished (it can actually be > 1, so be careful!)
/// </summary>
/// <value>The parsing progess.</value>
public float ParsingProgess {
get { return (CurrentTick / (float)Header.PlaybackFrames); }
}
/// <summary>
/// The current tick the parser has seen. So if it's a 16-tick demo,
/// it will have 16 after one second.
/// </summary>
/// <value>The current tick.</value>
public int CurrentTick { get; private set; }
/// <summary>
/// The current ingame-tick as reported by the demo-file.
/// </summary>
/// <value>The current tick.</value>
public int IngameTick { get; internal set; }
/// <summary>
/// How far we've advanced in the demo in seconds.
/// </summary>
/// <value>The current time.</value>
public float CurrentTime { get { return CurrentTick * TickTime; } }
/// <summary>
/// This contains additional informations about each player, such as Kills, Deaths, etc.
/// This is networked seperately from the player, so we need to cache it somewhere else.
/// </summary>
private AdditionalPlayerInformation[] additionalInformations = new AdditionalPlayerInformation[MAXPLAYERS];
/// <summary>
/// Initializes a new DemoParser. Right point if you want to start analyzing demos.
/// Hint: ParseHeader() is propably what you want to look into next.
/// </summary>
/// <param name="input">An input-stream.</param>
public DemoParser(Stream input)
{
BitStream = BitStreamUtil.Create(input);
for (int i = 0; i < MAXPLAYERS; i++) {
additionalInformations [i] = new AdditionalPlayerInformation ();
}
}
/// <summary>
/// Parses the header (first few hundret bytes) of the demo.
/// </summary>
public void ParseHeader()
{
var header = DemoHeader.ParseFrom(BitStream);
if (header.Filestamp != "HL2DEMO")
throw new InvalidDataException("Invalid File-Type - expecting HL2DEMO");
if (header.GameDirectory != "csgo")
throw new InvalidDataException("Invalid Demo-Game");
if (header.Protocol != 4)
throw new InvalidDataException("Invalid Demo-Protocol");
Header = header;
if (HeaderParsed != null)
HeaderParsed(this, new HeaderParsedEventArgs(Header));
}
/// <summary>
/// Parses this file until the end of the demo is reached.
/// Useful if you have subscribed to events
/// </summary>
public void ParseToEnd()
{
ParseToEnd(CancellationToken.None);
}
/// <summary>
/// Same as ParseToEnd() but accepts a CancellationToken to be able to cancel parsing
/// </summary>
/// <param name="token"></param>
public void ParseToEnd(CancellationToken token)
{
while (ParseNextTick())
{
if (token.IsCancellationRequested) return;
}
}
/// <summary>
/// Parses the next tick of the demo.
/// </summary>
/// <returns><c>true</c>, if this wasn't the last tick, <c>false</c> otherwise.</returns>
public bool ParseNextTick()
{
if (Header == null)
throw new InvalidOperationException ("You need to call ParseHeader first before you call ParseToEnd or ParseNextTick!");
bool b = ParseTick();
for (int i = 0; i < RawPlayers.Length; i++) {
if (RawPlayers[i] == null)
continue;
var rawPlayer = RawPlayers[i];
int id = rawPlayer.UserID;
if (PlayerInformations[i] != null) { //There is an good entity for this
bool newplayer = false;
if (!Players.ContainsKey(id)){
Players[id] = PlayerInformations[i];
newplayer = true;
}
Player p = Players[id];
p.Name = rawPlayer.Name;
p.SteamID = rawPlayer.XUID;
p.AdditionaInformations = additionalInformations [p.EntityID];
if (p.IsAlive) {
p.LastAlivePosition = p.Position.Copy();
}
if (newplayer && p.SteamID != 0){
PlayerBindEventArgs bind = new PlayerBindEventArgs();
bind.Player = p;
RaisePlayerBind(bind);
}
}
}
while (GEH_StartBurns.Count > 0) {
var fireTup = GEH_StartBurns.Dequeue();
fireTup.Item2.ThrownBy = InfernoOwners[fireTup.Item1];
RaiseFireWithOwnerStart(fireTup.Item2);
}
if (b) {
if (TickDone != null)
TickDone(this, new TickDoneEventArgs());
}
return b;
}
/// <summary>
/// Parses the tick internally
/// </summary>
/// <returns><c>true</c>, if tick was parsed, <c>false</c> otherwise.</returns>
private bool ParseTick()
{
DemoCommand command = (DemoCommand)BitStream.ReadByte();
IngameTick = (int)BitStream.ReadInt(32); // tick number
BitStream.ReadByte(); // player slot
this.CurrentTick++; // = TickNum;
switch (command) {
case DemoCommand.Synctick:
break;
case DemoCommand.Stop:
return false;
case DemoCommand.ConsoleCommand:
BitStream.BeginChunk(BitStream.ReadSignedInt(32) * 8);
BitStream.EndChunk();
break;
case DemoCommand.DataTables:
BitStream.BeginChunk (BitStream.ReadSignedInt (32) * 8);
SendTableParser.ParsePacket (BitStream);
BitStream.EndChunk ();
//Map the weapons in the equipmentMapping-Dictionary.
MapEquipment ();
//And now we have the entities, we can bind events on them.
BindEntites();
break;
case DemoCommand.StringTables:
BitStream.BeginChunk(BitStream.ReadSignedInt(32) * 8);
StringTables.ParsePacket(BitStream, this);
BitStream.EndChunk();
break;
case DemoCommand.UserCommand:
BitStream.ReadInt(32);
BitStream.BeginChunk(BitStream.ReadSignedInt(32) * 8);
BitStream.EndChunk();
break;
case DemoCommand.Signon:
case DemoCommand.Packet:
ParseDemoPacket();
break;
default:
throw new Exception("Can't handle Demo-Command " + command);
}
return true;
}
/// <summary>
/// Parses a DEM_Packet.
/// </summary>
private void ParseDemoPacket()
{
//Read a command-info. Contains no really useful information afaik.
CommandInfo.Parse(BitStream);
BitStream.ReadInt(32); // SeqNrIn
BitStream.ReadInt(32); // SeqNrOut
BitStream.BeginChunk(BitStream.ReadSignedInt(32) * 8);
DemoPacketParser.ParsePacket(BitStream, this);
BitStream.EndChunk();
}
/// <summary>
/// Binds the events for entities. And Entity has many properties.
/// You can subscribe to when an entity of a specific class is created,
/// and then you can subscribe to updates of properties of this entity.
/// This is a bit complex, but very fast.
/// </summary>
private void BindEntites()
{
//Okay, first the team-stuff.
HandleTeamScores();
HandleBombSites();
HandlePlayers();
HandleWeapons ();
HandleInfernos();
}
private void HandleTeamScores()
{
SendTableParser.FindByName("CCSTeam")
.OnNewEntity += (object sender, EntityCreatedEventArgs e) => {
string team = null;
string teamName = null;
string teamFlag = null;
int teamID = -1;
int score = 0;
e.Entity.FindProperty("m_scoreTotal").IntRecived += (xx, update) => {
score = update.Value;
};
e.Entity.FindProperty("m_iTeamNum").IntRecived += (xx, update) => {
teamID = update.Value;
if(team == "CT")
{
this.ctID = teamID;
CTScore = score;
foreach(var p in PlayerInformations.Where(a => a != null && a.TeamID == teamID))
p.Team = Team.CounterTerrorist;
}
if(team == "TERRORIST")
{
this.tID = teamID;
TScore = score;
foreach(var p in PlayerInformations.Where(a => a != null && a.TeamID == teamID))
p.Team = Team.Terrorist;
}
};
e.Entity.FindProperty("m_szTeamname").StringRecived += (sender_, recivedTeamName) => {
team = recivedTeamName.Value;
//We got the name. Lets bind the updates accordingly!
if(recivedTeamName.Value == "CT")
{
CTScore = score;
CTClanName = teamName;
e.Entity.FindProperty("m_scoreTotal").IntRecived += (xx, update) => {
CTScore = update.Value;
};
if(teamID != -1)
{
this.ctID = teamID;
foreach(var p in PlayerInformations.Where(a => a != null && a.TeamID == teamID))
p.Team = Team.CounterTerrorist;
}
}
else if(recivedTeamName.Value == "TERRORIST")
{
TScore = score;
TClanName = teamName;
e.Entity.FindProperty("m_scoreTotal").IntRecived += (xx, update) => {
TScore = update.Value;
};
if(teamID != -1)
{
this.tID = teamID;
foreach(var p in PlayerInformations.Where(a => a != null && a.TeamID == teamID))
p.Team = Team.Terrorist;
}
}
};
e.Entity.FindProperty("m_szTeamFlagImage").StringRecived += (sender_, recivedTeamFlag) => {
teamFlag = recivedTeamFlag.Value;
if (team == "CT")
{
CTFlag = teamFlag;
}
else if (team == "TERRORIST")
{
TFlag = teamFlag;
}
};
e.Entity.FindProperty("m_szClanTeamname").StringRecived += (sender_, recivedClanName) => {
teamName = recivedClanName.Value;
if(team == "CT")
{
CTClanName = recivedClanName.Value;
}
else if(team == "TERRORIST")
{
TClanName = recivedClanName.Value;
}
};
};
}
private void HandlePlayers()
{
SendTableParser.FindByName("CCSPlayer").OnNewEntity += (object sender, EntityCreatedEventArgs e) => HandleNewPlayer (e.Entity);
SendTableParser.FindByName("CCSPlayerResource").OnNewEntity += (blahblah, playerResources) => {
for(int i = 0; i < 64; i++)
{
//Since this is passed as reference to the delegates
int iForTheMethod = i;
string iString = i.ToString().PadLeft(3, '0');
playerResources.Entity.FindProperty("m_szClan."+iString).StringRecived += (sender, e) => {
additionalInformations[iForTheMethod].Clantag = e.Value;
};
playerResources.Entity.FindProperty("m_iPing."+iString).IntRecived += (sender, e) => {
additionalInformations[iForTheMethod].Ping = e.Value;
};
playerResources.Entity.FindProperty("m_iScore."+iString).IntRecived += (sender, e) => {
additionalInformations[iForTheMethod].Score = e.Value;
};
playerResources.Entity.FindProperty("m_iKills."+iString).IntRecived += (sender, e) => {
additionalInformations[iForTheMethod].Kills = e.Value;
};
playerResources.Entity.FindProperty("m_iDeaths."+iString).IntRecived += (sender, e) => {
additionalInformations[iForTheMethod].Deaths = e.Value;
};
playerResources.Entity.FindProperty("m_iAssists."+iString).IntRecived += (sender, e) => {
additionalInformations[iForTheMethod].Assists = e.Value;
};
playerResources.Entity.FindProperty("m_iMVPs."+iString).IntRecived += (sender, e) => {
additionalInformations[iForTheMethod].MVPs = e.Value;
};
playerResources.Entity.FindProperty("m_iTotalCashSpent."+iString).IntRecived += (sender, e) => {
additionalInformations[iForTheMethod].TotalCashSpent = e.Value;
};
#if DEBUG
playerResources.Entity.FindProperty("m_iArmor."+iString).IntRecived += (sender, e) => {
additionalInformations[iForTheMethod].ScoreboardArmor = e.Value;
};
playerResources.Entity.FindProperty("m_iHealth."+iString).IntRecived += (sender, e) => {
additionalInformations[iForTheMethod].ScoreboardHP = e.Value;
};
#endif
}
};
}
private void HandleNewPlayer(Entity playerEntity)
{
Player p = null;
if (this.PlayerInformations [playerEntity.ID - 1] != null) {
p = this.PlayerInformations [playerEntity.ID - 1];
} else {
p = new Player ();
this.PlayerInformations [playerEntity.ID - 1] = p;
p.SteamID = -1;
p.Name = "unconnected";
}
p.EntityID = playerEntity.ID;
p.Entity = playerEntity;
p.Position = new Vector();
p.Velocity = new Vector();
//position update
playerEntity.FindProperty("cslocaldata.m_vecOrigin").VectorRecived += (sender, e) => {
p.Position.X = e.Value.X;
p.Position.Y = e.Value.Y;
};
playerEntity.FindProperty("cslocaldata.m_vecOrigin[2]").FloatRecived += (sender, e) => {
p.Position.Z = e.Value;
};
//team update
//problem: Teams are networked after the players... How do we solve that?
playerEntity.FindProperty("m_iTeamNum").IntRecived += (sender, e) => {
p.TeamID = e.Value;
if (e.Value == ctID)
p.Team = Team.CounterTerrorist;
else if (e.Value == tID)
p.Team = Team.Terrorist;
else
p.Team = Team.Spectate;
};
//update some stats
playerEntity.FindProperty("m_iHealth").IntRecived += (sender, e) => p.HP = e.Value;
playerEntity.FindProperty("m_ArmorValue").IntRecived += (sender, e) => p.Armor = e.Value;
playerEntity.FindProperty("m_bHasDefuser").IntRecived += (sender, e) => p.HasDefuseKit = e.Value == 1;
playerEntity.FindProperty("m_bHasHelmet").IntRecived += (sender, e) => p.HasHelmet = e.Value == 1;
playerEntity.FindProperty("localdata.m_Local.m_bDucking").IntRecived += (sender, e) => p.IsDucking = e.Value == 1;
playerEntity.FindProperty("m_iAccount").IntRecived += (sender, e) => p.Money = e.Value;
playerEntity.FindProperty("m_angEyeAngles[1]").FloatRecived += (sender, e) => p.ViewDirectionX = e.Value;
playerEntity.FindProperty("m_angEyeAngles[0]").FloatRecived += (sender, e) => p.ViewDirectionY = e.Value;
playerEntity.FindProperty("m_flFlashDuration").FloatRecived += (sender, e) => p.FlashDuration = e.Value;
playerEntity.FindProperty("localdata.m_vecVelocity[0]").FloatRecived += (sender, e) => p.Velocity.X = e.Value;
playerEntity.FindProperty("localdata.m_vecVelocity[1]").FloatRecived += (sender, e) => p.Velocity.Y = e.Value;
playerEntity.FindProperty("localdata.m_vecVelocity[2]").FloatRecived += (sender, e) => p.Velocity.Z = e.Value;
playerEntity.FindProperty("m_unCurrentEquipmentValue").IntRecived += (sender, e) => p.CurrentEquipmentValue = e.Value;
playerEntity.FindProperty("m_unRoundStartEquipmentValue").IntRecived += (sender, e) => p.RoundStartEquipmentValue = e.Value;
playerEntity.FindProperty("m_unFreezetimeEndEquipmentValue").IntRecived += (sender, e) => p.FreezetimeEndEquipmentValue = e.Value;
//Weapon attribution
string weaponPrefix = "m_hMyWeapons.";
if (playerEntity.Props.All (a => a.Entry.PropertyName != "m_hMyWeapons.000"))
weaponPrefix = "bcc_nonlocaldata.m_hMyWeapons.";
int[] cache = new int[MAXWEAPONS];
for(int i = 0; i < MAXWEAPONS; i++)
{
int iForTheMethod = i; //Because else i is passed as reference to the delegate.
playerEntity.FindProperty(weaponPrefix + i.ToString().PadLeft(3, '0')).IntRecived += (sender, e) => {
int index = e.Value & INDEX_MASK;
if (index != INDEX_MASK) {
if(cache[iForTheMethod] != 0) //Player already has a weapon in this slot.
{
p.rawWeapons.Remove(cache[iForTheMethod]);
cache[iForTheMethod] = 0;
}
cache[iForTheMethod] = index;
AttributeWeapon(index, p);
} else {
if (cache[iForTheMethod] != 0 && p.rawWeapons.ContainsKey(cache[iForTheMethod]))
{
p.rawWeapons[cache[iForTheMethod]].Owner = null;
}
p.rawWeapons.Remove(cache[iForTheMethod]);
cache[iForTheMethod] = 0;
}
};
}
playerEntity.FindProperty("m_hActiveWeapon").IntRecived += (sender, e) => p.ActiveWeaponID = e.Value & INDEX_MASK;
for (int i = 0; i < 32; i++) {
int iForTheMethod = i;
playerEntity.FindProperty ("m_iAmmo." + i.ToString ().PadLeft (3, '0')).IntRecived += (sender, e) => {
p.AmmoLeft [iForTheMethod] = e.Value;
};
}
}
private void MapEquipment()
{
for (int i = 0; i < SendTableParser.ServerClasses.Count; i++) {
var sc = SendTableParser.ServerClasses[i];
if (sc.BaseClasses.Count > 6 && sc.BaseClasses [6].Name == "CWeaponCSBase") {
//It is a "weapon" (Gun, C4, ... (...is the cz still a "weapon" after the nerf? (fml, it was buffed again)))
if (sc.BaseClasses.Count > 7) {
if (sc.BaseClasses [7].Name == "CWeaponCSBaseGun") {
//it is a ratatatata-weapon.
var s = sc.DTName.Substring (9).ToLower ();
equipmentMapping.Add (sc, Equipment.MapEquipment (s));
} else if (sc.BaseClasses [7].Name == "CBaseCSGrenade") {
//"boom"-weapon.
equipmentMapping.Add (sc, Equipment.MapEquipment (sc.DTName.Substring (3).ToLower ()));
}
} else if (sc.Name == "CC4") {
//Bomb is neither "ratatata" nor "boom", its "booooooom".
equipmentMapping.Add (sc, EquipmentElement.Bomb);
} else if (sc.Name == "CKnife" || (sc.BaseClasses.Count > 6 && sc.BaseClasses [6].Name == "CKnife")) {
//tsching weapon
equipmentMapping.Add (sc, EquipmentElement.Knife);
} else if (sc.Name == "CWeaponNOVA" || sc.Name == "CWeaponSawedoff" || sc.Name == "CWeaponXM1014") {
equipmentMapping.Add (sc, Equipment.MapEquipment (sc.Name.Substring (7).ToLower()));
}
}
}