This repository has been archived by the owner on May 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
demo-parser.js
438 lines (352 loc) · 11.9 KB
/
demo-parser.js
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
const fs = require('fs')
const demofile = require('demofile')
const meta = {}
const playerMeta = new Map()
const teams = {}
let rounds = [ [] ]
const bombsiteCenters = {}
let checkEquipmentValueAtTick = -1
let replaceSteamIds = false
if (process.argv[3]) {
const segments = process.argv[3].split(',')
if (segments.length >= 2) {
replaceSteamIds = {
replace: segments.slice(1),
with: segments[0],
}
}
}
fs.readFile(process.argv[2], async (err, buffer) => {
const steamId = (player) => {
if (! player || ! player.steamId) return 'unknown_user'
if (replaceSteamIds && replaceSteamIds.replace.includes(player.steamId)) return replaceSteamIds.with
return (player.steamId === 'BOT')
? `BOT_${player.userId}`
: player.steamId
}
const teamData = (number) => {
return {
name: demoFile.teams[number].clanName,
score: demoFile.teams[number].score,
score_first_half: demoFile.teams[number].scoreFirstHalf,
score_second_half: demoFile.teams[number].scoreSecondHalf,
score_overtime: demoFile.teams[number].getProp('DT_Team', 'm_scoreOvertime'),
flag: demoFile.teams[number].flagImage,
players: demoFile.teams[number].members.map(steamId).filter((player) => {
return player !== 'unknown_user'
}),
}
}
const vectorInside = (v, min, max) => {
return v.x >= min.x && v.x <= max.x
&& v.y >= min.y && v.y <= max.y
&& v.z >= min.z && v.z <= max.z
}
const bombsiteName = (siteIndex, userid) => {
const entity = demoFile.entities.entities[siteIndex]
const vectorMin = entity.getProp('DT_CollisionProperty', 'm_vecMins')
const vectorMax = entity.getProp('DT_CollisionProperty', 'm_vecMaxs')
if (bombsiteCenters.a && vectorInside(bombsiteCenters.a, vectorMin, vectorMax)) return 'a'
if (bombsiteCenters.b && vectorInside(bombsiteCenters.b, vectorMin, vectorMax)) return 'b'
// if neither site is within the vector, take the one the interacting player is closer to
const user = demoFile.entities.getByUserId(userid)
const distanceA = Math.sqrt(
Math.pow(bombsiteCenters.a.x - user.position.x, 2),
Math.pow(bombsiteCenters.a.y - user.position.y, 2),
Math.pow(bombsiteCenters.a.z - user.position.z, 2),
)
const distanceB = Math.sqrt(
Math.pow(bombsiteCenters.b.x - user.position.x, 2),
Math.pow(bombsiteCenters.b.y - user.position.y, 2),
Math.pow(bombsiteCenters.b.z - user.position.z, 2),
)
return (distanceB < distanceA) ? 'b' : 'a'
}
const filterOutBots = (player) => {
return (player)
? player.steamId !== 'BOT'
: false
}
const demoFile = new demofile.DemoFile()
const log = (type, data) => {
rounds[rounds.length - 1].push(
Object.assign({ type, tick: demoFile.currentTick }, data)
)
}
const initTeamData = (force = false) => {
if (force || ! teams.t || ! teams.ct) {
teams.t = teamData(2)
teams.ct = teamData(3)
}
}
const assignOrSwapTeams = (forceNoSwap = false) => {
initTeamData()
let remainingPlayersCt = 0
for (const player of demoFile.teams[3].members) {
if (player && teams.ct.players.includes(player.steamId) && player.steamId !== 'BOT') remainingPlayersCt++
}
let remainingPlayersT = 0
for (const player of demoFile.teams[2].members) {
if (player && teams.t.players.includes(player.steamId) && player.steamId !== 'BOT') remainingPlayersT++
}
if (forceNoSwap
|| remainingPlayersT > demoFile.teams[2].members.filter(filterOutBots).length / 2
|| remainingPlayersCt > demoFile.teams[3].members.filter(filterOutBots).length / 2) {
// same teams, merge player arrays
teams.t = Object.assign(teamData(2), {
players: teams.t.players.concat(demoFile.teams[2].members.map(steamId).filter((player) => {
return ! teams.t.players.includes(player) && player !== 'unknown_user'
}))
})
teams.ct = Object.assign(teamData(3), {
players: teams.ct.players.concat(demoFile.teams[3].members.map(steamId).filter((player) => {
return ! teams.ct.players.includes(player) && player !== 'unknown_user'
}))
})
} else {
// teams switched (probably), swap teams (but don't discard players that were in the team before the switch but aren't anymore)
const previousTPlayers = teams.t.players.slice()
const previousCtPlayers = teams.ct.players.slice()
teams.t = Object.assign(teamData(2), {
players: previousCtPlayers.concat(demoFile.teams[2].members.map(steamId).filter((player) => {
return ! previousCtPlayers.includes(player) && player !== 'unknown_user'
}))
})
teams.ct = Object.assign(teamData(3), {
players: previousTPlayers.concat(demoFile.teams[3].members.map(steamId).filter((player) => {
return ! previousTPlayers.includes(player) && player !== 'unknown_user'
}))
})
}
}
// Meta
demoFile.on('start', () => {
meta.server_name = demoFile.header.serverName
meta.map = demoFile.header.mapName
meta.duration = demoFile.header.playbackTime
meta.ticks = demoFile.header.playbackTicks
meta.tickrate = demoFile.tickRate
})
// Player Data
demoFile.stringTables.on('update', (e) => {
if (e.table.name !== 'userinfo' || e.userData === null || (e.userData.guid === 'BOT' && e.userData.name === 'GOTV')) return
const guid = (e.userData.guid === 'BOT')
? `BOT_${e.userData.userId}`
: (
(replaceSteamIds && replaceSteamIds.replace.includes(e.userData.guid))
? replaceSteamIds.with
: e.userData.guid
)
playerMeta.set(guid, {
guid,
name: (e.userData.guid === 'BOT')
? `BOT ${e.userData.name}`
: e.userData.name,
userId: e.userData.userId,
bot: e.userData.guid === 'BOT',
})
})
demoFile.entities.on('change', (e) => {
if (e.tableName === 'DT_CSPlayerResource') {
if (e.varName === 'm_bombsiteCenterA') {
bombsiteCenters.a = e.newValue
} else if (e.varName === 'm_bombsiteCenterB') {
bombsiteCenters.b = e.newValue
}
}
})
// Round Start
demoFile.gameEvents.on('round_start', (e) => {
log('round_start', { number: demoFile.gameRules.roundsPlayed })
})
// Freeze Time ends
demoFile.gameEvents.on('round_freeze_end', (e) => {
const disallowedEventsThisRound = rounds[rounds.length - 1]
.filter(({ type }) => ! ['item_pickup', 'round_start'].includes(type))
if (disallowedEventsThisRound.length > 0) rounds.push([])
log('freeze_time_ended', { number: demoFile.gameRules.roundsPlayed })
assignOrSwapTeams()
checkEquipmentValueAtTick = demoFile.currentTick + 4 * demoFile.tickRate
})
// Money and Equipment Value
demoFile.on('tickend', (tick) => {
if (tick !== checkEquipmentValueAtTick) return
for (const player of demoFile.entities.players) {
if ((player.teamNumber !== 2 && player.teamNumber !== 3) || player.isHltv) continue
log('money_equipment', {
player: steamId(player),
money_remaining: player.account,
equipment_value: player.currentEquipmentValue,
})
}
})
// MVPs
demoFile.gameEvents.on('round_mvp', (e) => {
const mvp = demoFile.entities.getByUserId(e.userid)
log('mvp', { mvp: steamId(mvp) })
})
// Round Ended
demoFile.gameEvents.on('round_end', (e) => {
if (e.message === '#SFUI_Notice_Game_Commencing') return
log('round_winner', {
winner: e.winner,
reason: e.reason,
// message: e.message,
})
})
// Round Officially Ended
demoFile.gameEvents.on('round_officially_ended', () => {
rounds.push([])
if (process.stdout.isTTY) console.info(teams.t.score, 'T - CT', teams.ct.score)
})
// Player Flashed
demoFile.gameEvents.on('player_blind', (e) => {
let victim = demoFile.entities.getByUserId(e.userid)
if (! victim || ! victim.isAlive) return
log('flashed', {
attacker: steamId(demoFile.entities.getByUserId(e.attacker)),
victim: steamId(victim),
entity_id: e.entityid,
duration: e.blind_duration,
})
})
// Damage
demoFile.gameEvents.on('player_hurt', (e) => {
log('damage', {
attacker: steamId(demoFile.entities.getByUserId(e.attacker)),
victim: steamId(demoFile.entities.getByUserId(e.userid)),
damage: e.dmg_health,
armor: e.dmg_armor,
weapon: e.weapon,
hitbox: e.hitgroup,
})
})
// Freeze Time ended (first round)
demoFile.gameEvents.on('round_announce_match_start', (e) => {
if (process.stdout.isTTY) console.info('match started')
rounds = [ [] ]
initTeamData(true)
log('freeze_time_ended', { number: demoFile.gameRules.roundsPlayed })
})
// Kills/Deaths
demoFile.gameEvents.on('player_death', (e) => {
const assister = (e.assister === 0)
? false
: demoFile.entities.getByUserId(e.assister)
log('kill', {
attacker: steamId(demoFile.entities.getByUserId(e.attacker)),
victim: steamId(demoFile.entities.getByUserId(e.userid)),
assister: (assister === false) ? false : steamId(assister),
flash_assist: e.assistedflash,
weapon: e.weapon,
headshot: e.headshot,
through_wall: e.penetrated,
noscope: e.noscope,
through_smoke: e.thrusmoke,
attacker_flashed: e.attackerblind,
})
})
// Plants
demoFile.gameEvents.on('bomb_planted', (e) => {
log('plant', {
planter: steamId(demoFile.entities.getByUserId(e.userid)),
site: bombsiteName(e.site, e.userid),
})
})
// Defuses
demoFile.gameEvents.on('bomb_defused', (e) => {
log('defuse', {
defuser: steamId(demoFile.entities.getByUserId(e.userid)),
site: bombsiteName(e.site, e.userid),
})
})
// Bomb Explosions
demoFile.gameEvents.on('bomb_exploded', (e) => {
log('exploded', {
planter: steamId(demoFile.entities.getByUserId(e.userid)),
site: e.site,
})
})
// Smokes Detonated
demoFile.gameEvents.on('smokegrenade_detonate', (e) => {
log('smoke_detonated', {
thrower: steamId(demoFile.entities.getByUserId(e.userid)),
})
})
// HEs Detonated
demoFile.gameEvents.on('hegrenade_detonate', (e) => {
log('he_detonated', {
thrower: steamId(demoFile.entities.getByUserId(e.userid)),
})
})
// HEs Detonated
demoFile.gameEvents.on('flashbang_detonate', (e) => {
log('flashbang_detonated', {
thrower: steamId(demoFile.entities.getByUserId(e.userid)),
entity_id: e.entityid,
})
})
// Grenades thrown
demoFile.gameEvents.on('weapon_fire', (e) => {
if (! ['weapon_incgrenade', 'weapon_molotov', 'weapon_flashbang', 'weapon_smokegrenade', 'weapon_hegrenade'].includes(e.weapon)) return
const thrower = demoFile.entities.getByUserId(e.userid)
let grenade = e.weapon.substring(7)
if (grenade === 'incgrenade') grenade = 'molotov'
else if (grenade === 'hegrenade') grenade = 'he'
else if (grenade === 'smokegrenade') grenade = 'smoke'
log(`${grenade}_thrown`, {
thrower: steamId(thrower),
})
})
// Bot Takeovers
demoFile.gameEvents.on('bot_takeover', (e) => {
log('bot_takeover', {
human: steamId(demoFile.entities.getByUserId(e.userid)),
bot: steamId(demoFile.entities.getByUserId(e.botid)),
})
})
// Item Pickups
demoFile.gameEvents.on('item_pickup', (e) => {
log('item_pickup', {
player: steamId(demoFile.entities.getByUserId(e.userid)),
item: e.item,
})
})
demoFile.parse(buffer)
const applyFinalScore = (name, number) => {
if (! teams[name]) return teams[name] = teamData(number)
teams[name].score = demoFile.teams[number].score
teams[name].score_first_half = demoFile.teams[number].scoreFirstHalf
teams[name].score_second_half = demoFile.teams[number].scoreSecondHalf
teams[name].score_overtime = demoFile.teams[number].getProp('DT_Team', 'm_scoreOvertime')
}
demoFile.on('end', (e) => {
while (rounds[rounds.length - 1].length === 0) rounds.splice(rounds.length - 1)
assignOrSwapTeams(true)
applyFinalScore('t', 2)
applyFinalScore('ct', 3)
meta.game_mode = demoFile.conVars.vars.get('game_mode') || 0
meta.game_type = demoFile.conVars.vars.get('game_type') || 0
meta.max_rounds = demoFile.conVars.vars.get('mp_maxrounds')
meta.has_halftime = demoFile.conVars.vars.get('mp_halftime') === '1'
const json = JSON.stringify({
meta,
playerMeta: Object.fromEntries(playerMeta),
teams,
rounds,
})
if (! process.stdout.isTTY) {
return console.info(json)
}
fs.writeFile('demo.json', json, (err) => {
if (err) throw err
})
console.info({
meta,
playerMeta,
t: teams.t,
ct: teams.ct,
rounds: rounds.length,
})
})
})