forked from markus-wa/demoinfocs-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsing.go
267 lines (210 loc) · 6.57 KB
/
parsing.go
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
package demoinfocs
import (
"errors"
"fmt"
"io"
common "github.com/markus-wa/demoinfocs-golang/common"
events "github.com/markus-wa/demoinfocs-golang/events"
)
const maxOsPath = 260
const (
playerWeaponPrefix = "m_hMyWeapons."
playerWeaponPrePrefix = "bcc_nonlocaldata."
)
const (
msgHeaderNotParsed = "Tried to parse tick before parsing header"
)
// Parsing errors
var (
// ErrCancelled signals that parsing was cancelled via Parser.Cancel()
ErrCancelled = errors.New("Parsing was cancelled before it finished (ErrCancelled)")
// ErrUnexpectedEndOfDemo signals that the demo is incomplete / corrupt -
// these demos may still be useful, check the how far the parser got.
ErrUnexpectedEndOfDemo = errors.New("Demo stream ended unexpectedly (ErrUnexpectedEndOfDemo)")
// ErrInvalidFileType signals that the input isn't a valid CS:GO demo.
ErrInvalidFileType = errors.New("Invalid File-Type; expecting HL2DEMO in the first 8 bytes")
)
// ParseHeader attempts to parse the header of the demo.
// Returns error if the filestamp (first 8 bytes) doesn't match HL2DEMO.
func (p *Parser) ParseHeader() (common.DemoHeader, error) {
var h common.DemoHeader
h.Filestamp = p.bitReader.ReadCString(8)
h.Protocol = p.bitReader.ReadSignedInt(32)
h.NetworkProtocol = p.bitReader.ReadSignedInt(32)
h.ServerName = p.bitReader.ReadCString(maxOsPath)
h.ClientName = p.bitReader.ReadCString(maxOsPath)
h.MapName = p.bitReader.ReadCString(maxOsPath)
h.GameDirectory = p.bitReader.ReadCString(maxOsPath)
h.PlaybackTime = p.bitReader.ReadFloat()
h.PlaybackTicks = p.bitReader.ReadSignedInt(32)
h.PlaybackFrames = p.bitReader.ReadSignedInt(32)
h.SignonLength = p.bitReader.ReadSignedInt(32)
if h.Filestamp != "HL2DEMO" {
return h, ErrInvalidFileType
}
// Initialize queue if the buffer size wasn't specified, the amount of ticks
// seems to be a good indicator of how many events we'll get
if p.msgQueue == nil {
p.initMsgQueue(h.PlaybackTicks)
}
p.header = &h
// TODO: Deprecated, remove this + HeaderParsedEvent in 1.0.0
p.eventDispatcher.Dispatch(events.HeaderParsedEvent{Header: h})
return h, nil
}
// ParseToEnd attempts to parse the demo until the end.
// Aborts and returns ErrCancelled if Cancel() is called before the end.
// May return ErrUnexpectedEndOfDemo for incomplete / corrupt demos.
// May panic if the demo is corrupt in some way.
func (p *Parser) ParseToEnd() (err error) {
defer func() {
if err == nil {
err = recoverFromUnexpectedEOF(recover())
}
}()
if p.header == nil {
panic(msgHeaderNotParsed)
}
for {
select {
case <-p.cancelChan:
return ErrCancelled
default:
if !p.parseFrame() {
// Make sure all the messages of the demo are handled
p.msgDispatcher.SyncQueues(p.msgQueue)
// Close msgQueue
close(p.msgQueue)
return p.error()
}
}
if pErr := p.error(); pErr != nil {
return pErr
}
}
}
func recoverFromUnexpectedEOF(r interface{}) error {
if r != nil {
if r == io.ErrUnexpectedEOF {
return ErrUnexpectedEndOfDemo
}
panic(r)
}
return nil
}
// Cancel aborts ParseToEnd(). All information that was already read
// up to this point will still be used (and new events may still be sent).
func (p *Parser) Cancel() {
p.cancelChan <- struct{}{}
}
// ParseNextFrame attempts to parse the next frame / demo-tick (not ingame tick).
// Returns true unless the demo command 'stop' or an error was encountered.
// May return ErrUnexpectedEndOfDemo for incomplete / corrupt demos.
// Panics if header hasn't been parsed yet - see Parser.ParseHeader().
func (p *Parser) ParseNextFrame() (b bool, err error) {
defer func() {
if err == nil {
err = recoverFromUnexpectedEOF(recover())
}
}()
if p.header == nil {
panic(msgHeaderNotParsed)
}
b = p.parseFrame()
// Make sure all the messages of the frame are handled
p.msgDispatcher.SyncQueues(p.msgQueue)
// Close msgQueue if we are done
if !b {
close(p.msgQueue)
}
err = p.error()
return
}
// Demo commands as documented at https://developer.valvesoftware.com/wiki/DEM_Format
type demoCommand byte
const (
dcSignon demoCommand = 1
dcPacket demoCommand = 2
dcSynctick demoCommand = 3
dcConsoleCommand demoCommand = 4
dcUserCommand demoCommand = 5
dcDataTables demoCommand = 6
dcStop demoCommand = 7
dcCustomData demoCommand = 8
dcStringTables demoCommand = 9
)
func (p *Parser) parseFrame() bool {
cmd := demoCommand(p.bitReader.ReadSingleByte())
// Send ingame tick number update
p.msgQueue <- ingameTickNumber(p.bitReader.ReadSignedInt(32))
// Skip 'player slot'
p.bitReader.Skip(8)
debugDemoCommand(cmd)
switch cmd {
case dcSynctick:
// Ignore
case dcStop:
return false
case dcConsoleCommand:
// Skip
p.bitReader.Skip(p.bitReader.ReadSignedInt(32) << 3)
case dcDataTables:
p.msgDispatcher.SyncQueues(p.msgQueue)
p.bitReader.BeginChunk(p.bitReader.ReadSignedInt(32) << 3)
p.stParser.ParsePacket(p.bitReader)
p.bitReader.EndChunk()
p.mapEquipment()
p.bindEntities()
p.eventDispatcher.Dispatch(events.DataTablesParsedEvent{})
case dcStringTables:
p.msgDispatcher.SyncQueues(p.msgQueue)
p.parseStringTables()
case dcUserCommand:
// Skip
p.bitReader.Skip(32)
p.bitReader.Skip(p.bitReader.ReadSignedInt(32) << 3)
case dcSignon:
fallthrough
case dcPacket:
p.parsePacket()
case dcCustomData:
// Might as well panic since we'll be way off if we dont skip the whole thing
panic("Found CustomData but not handled")
default:
panic(fmt.Sprintf("Canny handle it anymoe (command %v unknown)", cmd))
}
// Queue up some post processing
p.msgQueue <- frameParsedToken
return true
}
type frameParsedTokenType struct{}
var frameParsedToken = new(frameParsedTokenType)
func (p *Parser) handleFrameParsed(*frameParsedTokenType) {
defer func() {
p.setError(recoverFromUnexpectedEOF(recover()))
}()
for k, rp := range p.rawPlayers {
if rp == nil {
continue
}
// We need to re-map the players from their entityID to their UID.
// This is necessary because we don't always have the UID when the player connects (or something like that, not really sure tbh).
if pl := p.entityIDToPlayers[k]; pl != nil {
pl.Name = rp.name
pl.SteamID = rp.xuid
pl.IsBot = rp.isFakePlayer
pl.AdditionalPlayerInformation = &p.additionalPlayerInfo[pl.EntityID]
if pl.IsAlive() {
pl.LastAlivePosition = pl.Position
}
if p.gameState.players[rp.userID] == nil {
p.gameState.players[rp.userID] = pl
if pl.SteamID != 0 {
p.eventDispatcher.Dispatch(events.PlayerBindEvent{Player: pl})
}
}
}
}
p.currentFrame++
p.eventDispatcher.Dispatch(events.TickDoneEvent{})
}