@matchomag/cs2-replay 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +3 -447
  2. package/package.json +4 -4
  3. package/FORMAT.md +0 -350
package/README.md CHANGED
@@ -1,454 +1,10 @@
1
1
  # @matchomag/cs2-replay
2
2
 
3
- CS2 demo replays in the browser: a 2D radar view and a 3D grey-box view of
4
- the same replay, and a parser that turns `.dem` files into replays, either in
5
- the browser or on a server.
6
-
7
- - **2D**: players with view cones, grenades and their smokes and fires, kills,
8
- the bomb, rosters, a scoreboard and a timeline you can scrub, on the game's
9
- radar. No dependencies; about 13 KB gzipped.
10
- - **3D**: the same on a grey-box model of the map, with fly and orbit cameras.
11
- Needs [three.js](https://threejs.org).
12
- - **Demos**: `.dem` files parsed in a Web Worker (WebAssembly), or ahead of
13
- time on a server with the bundled `demo-replay` program. The replay format
14
- is documented in [FORMAT.md](./FORMAT.md).
15
-
16
- ## Install
3
+ CS2 demo replay viewers (a 2D radar and a 3D view), an in-browser demo parser
4
+ and the `demo-replay` CLI.
17
5
 
18
6
  ```sh
19
7
  npm install @matchomag/cs2-replay
20
- npm install three # only for the 3D view
21
- ```
22
-
23
- ## Entry points
24
-
25
- | Import | What | Needs |
26
- | --- | --- | --- |
27
- | `@matchomag/cs2-replay` | `loadReplay`, `readReplay`, `createModel`, `Playback`, `FLAG`, types | nothing |
28
- | `@matchomag/cs2-replay/2d` | `createRadarViewer`, `radarPoint`, plus everything from the core | nothing |
29
- | `@matchomag/cs2-replay/3d` | `createWorldViewer`, `toWorld`, plus everything from the core | `three` |
30
- | `@matchomag/cs2-replay/maps` | `GameMapStore`, `detectGameMapSupport`, `fetchGameMapIndex`, `gameMapFiles`, `greyboxMapUrl`, `pickMapBuild`: hosted maps (grey-boxes, game-look tiers, sizes, storage) | nothing |
31
- | `@matchomag/cs2-replay/parse` | `openReplay`, `parseDemo` | a 15 MB (3 MB gzipped) WebAssembly parser, loaded on first use |
32
-
33
- They're separate bundles: importing `/2d` or `/maps` never loads three.js or the parser.
34
- Everything is typed (TypeScript declarations are included).
35
-
36
- ## Play a replay on the radar
37
-
38
- ```js
39
- import { createRadarViewer, loadReplay } from "@matchomag/cs2-replay/2d";
40
-
41
- const replay = await loadReplay("/replays/m80-vs-mouz-overpass.replay"); // also .replay.gz
42
- const viewer = createRadarViewer(document.getElementById("replay"), {
43
- replay,
44
- radar: {
45
- // From the game's resource/overviews/de_overpass.txt:
46
- x: -4831, y: 1781, scale: 5.2, // pos_x, pos_y, scale
47
- image: "/radars/de_overpass.webp", // the overview image, 1024×1024
48
- // Maps with a second floor, e.g. Nuke:
49
- // lower: { image: "/radars/de_nuke_lower.webp", below: -495 },
50
- crop: [13, 0, 81, 100], // optional: part to show, in percent (left, top, width, height)
51
- sites: { a: [-2572, 642, 484], b: [-1166, -94, 104] }, // optional: site letters at these positions
52
- },
53
- });
54
- ```
55
-
56
- The viewer fills its host element, so give the host a size, e.g.
57
- `#replay { height: 70vh }`. The package has no radar images or map numbers:
58
- they're Valve's, so the page provides them.
59
-
60
- **Controls.** Keyboard shortcuts work while the viewer has focus:
61
-
62
- | Key | Action |
63
- | --- | --- |
64
- | K, P, Space | play / pause |
65
- | ← / → | 5 s back / forward (with Shift: 1 s) |
66
- | , / . | one frame back / forward |
67
- | [ / ] | previous / next round |
68
- | − / = | slower / faster |
69
- | L | back to the live edge (live matches) |
70
-
71
- On the radar: the wheel or a pinch zooms, dragging pans, and a double click
72
- or Esc resets the view. Clicking a player in a roster follows them.
73
-
74
- ## Open a `.dem` file in the browser
75
-
76
- `openReplay()` takes a replay or a demo and parses demos in a Web Worker.
77
- A page that lets people pick a demo from their disk:
78
-
79
- ```js
80
- import { createRadarViewer } from "@matchomag/cs2-replay/2d";
81
- import { openReplay } from "@matchomag/cs2-replay/parse";
82
-
83
- input.addEventListener("change", async () => {
84
- const replay = await openReplay(input.files[0], {
85
- onProgress: ({ phase, loaded }) => (status.textContent = `${phase}: ${Math.round(loaded / 1e6)} MB`),
86
- });
87
- // radars: your RadarConfig for each map name, as in the example above.
88
- createRadarViewer(host, { replay, radar: radars[replay.map] });
89
- });
90
- ```
91
-
92
- - **What it takes:** a `File`/`Blob`, a URL, or bytes, as `.dem`, `.dem.gz`,
93
- `.replay` or `.replay.gz`. Other archives (`.zip`, `.rar`, `.bz2`) need
94
- unpacking first.
95
- - **Speed:** a 300 MB demo takes about 30 s on a desktop. The page itself
96
- stays around 35 MB of memory, because the worker reads the file in chunks.
97
- - **Keeping the result:** `parseDemo(file)` also returns the replay file's
98
- bytes (`{ replay, bytes, summary }`), to cache or upload so the demo isn't
99
- parsed again.
100
- - **Bundlers:** Vite, webpack 5 and Rollup copy the worker and the `.wasm`
101
- automatically. With Vite's dev server, add
102
- `optimizeDeps: { exclude: ["@matchomag/cs2-replay"] }`, or the worker's URL
103
- breaks.
104
- - **Hosting:** if you serve the files yourself, pass
105
- `workerUrl` to point at `dist/parse/worker.js` (the `.wasm` sits next to it
106
- in `wasm/`). The largest file is 15 MB, which fits static hosts like
107
- Cloudflare Pages (25 MiB per file).
108
-
109
- ## Follow a live match
110
-
111
- `openPlaycast()` follows a match while it's played, from a CSTV+ playcast URL
112
- (what the game plays with `playcast "<url>"`). The parser runs in the same
113
- worker as for demos, fetching the broadcast's fragments as they come, and
114
- `live.replay` grows. Give it to any viewer:
115
-
116
- ```js
117
- import { createRadarViewer } from "@matchomag/cs2-replay/2d";
118
- import { openPlaycast } from "@matchomag/cs2-replay/parse";
119
-
120
- const live = await openPlaycast("https://cs2-maps.matchomag.workers.dev/live/<match id>", {
121
- from: "live", // or "start": catch up from the first fragment, then follow
122
- // proxy: "https://cs2-maps.matchomag.workers.dev/v1/playcast-proxy?url=", for relays without CORS
123
- });
124
- const viewer = createRadarViewer(host, { replay: live.replay, radar: radars[live.replay.map] });
125
- live.on("end", ({ reason }) => {}); // "over", "map" (open the URL again for the next map), "idle", "error", "closed"
126
- ```
127
-
128
- The viewer plays about a fragment behind the newest frame and shows a LIVE
129
- badge on the stage. Seeking back works over everything since joining; the
130
- badge (or <kbd>L</kbd>) goes back to live. A viewer at the live edge downloads
131
- what the server broadcasts, 70–150 KB/s. GOTV addresses (`connect ip:port`)
132
- aren't supported.
133
-
134
- The maps Worker (`worker/`) is a relay for servers we run
135
- (`tv_broadcast_url "<origin>/live/<id>"`) and has the CORS pass-through. See
136
- the docs site's "Live matches" page for the server cvars, and for testing with
137
- a demo instead of a server (`extractor/cmd/dem2playcast`, the dev server's
138
- `?playcast=`).
139
-
140
- ## 3D
141
-
142
- ```js
143
- import { createWorldViewer, loadReplay } from "@matchomag/cs2-replay/3d";
144
-
145
- const viewer = createWorldViewer(host, {
146
- replay: await loadReplay("/replays/match.replay"), // optional: leave out to only look at the map
147
- map: "/maps/de_overpass.glb", // a grey-box from this repo's pipeline
148
- mode: "fly", // or "orbit"
149
- });
150
- await viewer.loaded;
151
- ```
152
-
153
- Click the view for mouse look, then WASD to fly (Space/E up, C/Q down, Shift
154
- faster, wheel for speed). O and F switch between orbit and fly.
155
-
156
- **Players and effects.** Both looks, the grey-box and the game look below,
157
- draw the same players and effects; only the map differs. Players are
158
- skeletally animated CT and T characters holding their weapons, driven by the
159
- replay (speed-matched gait, strafing, crouching, jumps, aim from shots,
160
- recoil, grenade throws, hit flinches, planting, defusing, flash blindness,
161
- directional deaths). Gunfire gets muzzle flashes, tracers and brass; grenades
162
- get their projectile, smoke, fire, HE and flash effects; the bomb is a prop
163
- with its LED, and a planted one also gets a ring that shows through walls.
164
- Each grenade's flight path is a line in the theme's grenade colour. In the
165
- grey-box, smokes are billboard puffs and players have a soft shadow under them;
166
- the game look has volumetric smoke, sun shadows and probe lighting.
167
- `players: "markers"` draws team-coloured capsules instead of characters, in
168
- either look, for devices that struggle with the triangles (about 310k for 10
169
- players).
170
-
171
- The grey-box shows the map as soon as it's in. The players' code (about 28 KB
172
- gzipped, no extra files: models and textures are generated) loads in its own
173
- chunk, and their models are built a piece at a time while the map downloads.
174
-
175
- **Camera views.** With a replay, a switch at the top of the player list picks
176
- the view, and V cycles through them (Shift+V goes back):
177
-
178
- - **1st**: the followed player's eyes. The pitch comes from their last shot
179
- (replays with `shots`, see FORMAT.md) and is level otherwise, and each shot
180
- punches the view up a little. When they die the camera pulls back over the
181
- body, and it returns to their eyes when they respawn. You see the weapon
182
- they hold, in gloved hands at the bottom right: it switches
183
- when they switch, kicks back with every shot (a spray keeps it kicking),
184
- flashes at its muzzle, winds up and throws grenades, slashes with the knife,
185
- lowers while they plant or defuse, and hides while they're scoped in.
186
- - **3rd**: behind the followed player, turning with them. Drag to look
187
- around; the camera eases back behind them when you let go. The wheel sets
188
- the distance.
189
- - **Free**: the fly or orbit camera.
190
-
191
- Picking a player in the list follows them: in third person from the free
192
- view, else in the current view. Picking 1st or 3rd with nobody followed takes
193
- the last player followed, or else the first alive one. While following, a
194
- click on the view goes to the next alive player and a right click to the
195
- previous one (Tab and Shift+Tab while the view has focus). WASD or Esc switch
196
- to the free camera, starting where the camera is. Both looks work the same: in
197
- first person the player's own character (or marker) is hidden. In a narrow
198
- viewer the player list is hidden and only the switch stays, in the bottom
199
- right corner.
200
-
201
- Hosted grey-boxes are listed in the same index as the game look, by map build:
202
-
203
- ```js
204
- import { fetchGameMapIndex, greyboxMapUrl } from "@matchomag/cs2-replay/maps";
205
-
206
- const index = await fetchGameMapIndex("https://maps.example.com/maps/index.json");
207
- const map = greyboxMapUrl(index, replay.map, { protocol: replay.protocol }); // null if not hosted
208
- ```
209
-
210
- Every picker takes `{ protocol }` (the demo's game version), `{ date }` (when
211
- the match was played: `"2026-11-10"`, an ISO timestamp or a `Date`) or
212
- `{ build }`. `protocol` gives the newest build converted at or before that
213
- patch, `date` the newest build released on or before that day, and a demo
214
- older than every build gets the oldest one. Without them it's the latest
215
- build. `pickMapBuild(index, map, "greybox" | "game", opts)` returns the build
216
- itself (`{ id, build }`). The hosted maps' Worker (`worker/` in the repo)
217
- answers the same question at `/v1/maps/<map>?protocol=…|date=…|build=…`.
218
-
219
- ### Game look (experimental)
220
-
221
- `look: "game"` renders a map converted by the repo's `scripts/game-map.sh`
222
- instead of a grey-box: the map's own textures and materials (including
223
- two-layer blends), its baked lightmaps (irradiance, directional irradiance,
224
- the sun's baked shadow), its reflection probes (box-projected per volume),
225
- its sky, sun, fog and wind (foliage sways), through an HDR pipeline with
226
- CS2's own tone curve, auto exposure range and bloom from the map's
227
- post-processing settings. Smokes are volumetric and fill the game's own voxel
228
- cloud (replays from this extractor carry it; see FORMAT.md): they pour
229
- around corners, stop at walls and open up where an HE goes off. The players
230
- and effects are the same as in the grey-box (above), lit by the light probes
231
- the converter bakes and shadowed by the sun. The look's map code is a chunk
232
- of its own, so the grey-box doesn't download it.
233
-
234
- ```js
235
- const viewer = createWorldViewer(host, {
236
- replay,
237
- map: "/maps/de_overpass/de_overpass.gltf", // out/<map>/game/ from scripts/game-map.sh
238
- look: "game",
239
- transcoderPath: "/basis/", // three.js's examples/jsm/libs/basis (KTX2); default: jsDelivr
240
- });
241
- ```
242
-
243
- **Keeping it light.** The game look draws at most 60 frames per second
244
- (`maxFps`), and only while something changes: when paused, it stops shortly
245
- after the camera last moved, once auto exposure has settled. It renders at
246
- most 1.5 pixels per CSS pixel (`pixelRatio`) through one MSAA target. Smokes
247
- are ray-marched at half resolution, only where they are on screen, with their
248
- self-shadowing baked when they appear. A map shows once its shaders are
249
- compiled (in parallel where the browser has `KHR_parallel_shader_compile`,
250
- as Chrome does), and its geometry and textures go to the GPU a few
251
- milliseconds at a time, so the page keeps drawing while the map loads.
252
-
253
- The converted map is large (Overpass: ~4M triangles, 2.6 GB as converted)
254
- and derived from Valve's files, so it is made from your own copy of the game
255
- and never shipped in this package. The characters and their weapons are
256
- original procedural models, not CS2's agents.
257
-
258
- #### Serving maps to a site: tiers, sizes, storage
259
-
260
- `scripts/pack-map.sh <map>` packs a converted map for a static bucket such as
261
- Cloudflare R2 (`scripts/upload-maps.sh`). Sites offer one game-look quality,
262
- the `low` tier, and that's all it packs by default. `--tiers low,medium,high`
263
- still builds the bigger ones. Overpass:
264
-
265
- | Tier | Textures | Lightmaps | Download | GPU memory (estimate) |
266
- | --- | --- | --- | --- | --- |
267
- | `low` (default) | up to 512 px | 4K | 208 MB | 0.5 GB |
268
- | `medium` | up to 1024 px | 4K | 417 MB | 1.1 GB |
269
- | `high` | up to 2048 px | 8K (as the game) | 908 MB | 2.5 GB |
270
-
271
- The lightmaps are Valve's own BC6H/BC7/BC1 blocks, which desktop GPUs sample
272
- directly. GPUs without those formats (phones) get smaller RGB9E5/R8/PNG
273
- lightmaps instead (`low`: 213 MB, `medium`: 421 MB); `high` needs BC.
274
-
275
- The page itself doesn't hold on to the map. Once a texture, lightmap or mesh is
276
- on the GPU, the viewer frees its JavaScript copy, and it stops the texture
277
- transcoder's workers when the last texture is in. On Overpass `low`
278
- (headless Chromium), the page's renderer process settles at about 0.47 GB
279
- instead of 1.15 GB, with the same image. If the browser drops the WebGL
280
- context (phones do this under memory pressure), the map is loaded again, from
281
- the store when there is one. `keepCpuCopies: true` keeps the copies, if you
282
- read the map's vertices or texels yourself (e.g. to raycast against it).
283
-
284
- Point `map` at the build's `manifest.json` and pick a tier. With a store,
285
- downloaded files stay on the device (Cache Storage), so a map is downloaded
286
- once per device:
287
-
288
- ```js
289
- import { createWorldViewer } from "@matchomag/cs2-replay/3d";
290
- import { GameMapStore, detectGameMapSupport, fetchGameMapIndex, fetchGameMapManifest, gameMapManifestUrl } from "@matchomag/cs2-replay/maps";
291
-
292
- const index = await fetchGameMapIndex("https://maps.example.com/maps/index.json");
293
- const url = gameMapManifestUrl(index, replay.map, { protocol: replay.protocol }); // the map as the demo was played
294
- const support = detectGameMapSupport(); // { webgl2, bc, tiers, recommended, … }
295
- const store = await GameMapStore.open(); // null without Cache Storage
296
- const manifest = await fetchGameMapManifest(url, store);
297
- const status = await store?.status(manifest, "low", support.lightmaps);
298
- // { totalBytes, cachedBytes, missingBytes, freeBytes, fits }: fits === false → not enough space
299
-
300
- const viewer = createWorldViewer(host, {
301
- replay, map: url, look: "game", tier: "low", store,
302
- onProgress: ({ phase, loaded, total }) => (bar.value = loaded / total), // bytes of the whole tier
303
- });
304
- ```
305
-
306
- `@matchomag/cs2-replay/maps` has no three.js, so a page can show the choice
307
- (sizes from the index or `store.status()`, `support.tiers`, free space)
308
- before it loads the 3D viewer. The map shows once its geometry and lighting
309
- are in (Overpass: 112 MB) and its shaders are compiled; textures stream in
310
- after, biggest surfaces first. `store.list()` shows what's on the device and
311
- `store.remove(manifestUrl)` deletes a map (keeping textures other maps
312
- share); `store.persist()` asks the browser not to evict it. Without
313
- `persist()` browsers may evict under storage pressure, and Safari clears a
314
- site's storage after 7 days without a visit; missing files are just
315
- downloaded again. A full disk doesn't stop playback: `store.full` turns true,
316
- `store.onFull` fires, and the rest is streamed without being kept.
317
-
318
- Serve the bucket through the repo's Worker (`worker/`, which sends CORS
319
- headers for any site), or from a public bucket domain with CORS for the
320
- site's origin (GET, HEAD). Its layout and the manifest format are described
321
- at the top of `scripts/pack-game-map.mjs`.
322
-
323
- Replays with `shots` (see FORMAT.md) get muzzle flashes, tracers and aim in
324
- both looks; older replays still play, without them. Smokes from
325
- older replays (no `voxels`) are filled around the map's geometry instead, so
326
- for those the viewer keeps the map's vertex positions in memory (~60 MB on
327
- Overpass).
328
- To render frame by frame (e.g. a video), pause, set
329
- `viewer.gameStage.fixedDelta = 1 / fps` and `seek()` each frame. `gameStage`
330
- is null until the game look's code has loaded; it's set once `loaded`
331
- resolves.
332
-
333
- ## Viewer API
334
-
335
- Both `createRadarViewer` and `createWorldViewer` return a `Viewer`:
336
-
337
- ```ts
338
- viewer.play(); viewer.pause(); viewer.toggle();
339
- viewer.seek(frame); // fractional frames are fine
340
- viewer.gotoRound(12); // round number as in game, a few seconds before freeze time ends
341
- viewer.speed = 2;
342
- viewer.frame; viewer.round; viewer.playing;
343
- viewer.on("round", ({ index, round }) => {}); // also "frame", "play", "pause", "player"
344
- viewer.setTheme({ ct: "#4a86d8" });
345
- viewer.destroy(); // removes it and all its listeners
346
- viewer.live; viewer.following; viewer.goLive(); // live matches, see above; event "live"
347
- ```
348
-
349
- The 3D viewer adds the camera views:
350
-
351
- ```ts
352
- viewer.setView("third", 3); // "first" | "third" | "free"; the player (index into replay.players) is optional
353
- viewer.view; viewer.followed; // the view, and the followed player (null in "free")
354
- viewer.on("view", ({ view, player }) => {}); // any change: the switch, keys, the list, the API
355
- viewer.setMode("orbit"); // the free camera, "fly" or "orbit"; switches to "free"
356
- ```
357
-
358
- Options, besides `replay` and `radar`/`map`:
359
-
360
- | Option | Default | |
361
- | --- | --- | --- |
362
- | `round` | first round | Round number to start at. |
363
- | `autoplay` | `false` | |
364
- | `speed`, `speeds` | `1`, `[0.25 … 16]` | Starting speed, and the steps of the speed menu. |
365
- | `keyboard` | `"focus"` | `"global"` for shortcuts anywhere on the page, `false` for none. |
366
- | `hud` | all on | `{ scoreboard, killFeed, roster, controls }`, each can be `false`. |
367
- | `theme` | | Colors and fonts, see below. |
368
- | `roundTime`, `bombTime` | `115`, `40` | Seconds on the round and bomb timers. |
369
- | `names` (2D) | `true` | Player names next to the dots. |
370
- | `killLines` (2D) | `3` | Seconds a killer-to-victim line stays; `0` for none. |
371
- | `view`, `camera`, `hide`, `categories`, `help`, `sky` (3D) | | Initial camera, hidden mesh categories, panels, background. |
372
- | `look`, `transcoderPath` (3D) | `"greybox"` | `"game"` for a converted map, see "Game look". |
373
- | `tier`, `store`, `lightmaps`, `onProgress` (3D) | `"low"` | Packed maps, see "Serving maps to a site". |
374
- | `pixelRatio` (3D) | screen's, at most 1.5 in the game look | Pixels per CSS pixel. The game look caps it (1 with `quality: "low"`). |
375
- | `maxFps` | 60 in the game look, else none | Frames per second at most; `0` for every display refresh. |
376
- | `keepCpuCopies` (3D) | `false` | Game look: keep the map's JavaScript copies once it's on the GPU, see "Serving maps to a site". |
377
-
378
- For a custom renderer, the core's `createModel(replay).snapshot(frame)` gives
379
- everything a frame shows, independent of how it's drawn: interpolated players,
380
- grenades and their effects, the bomb, the round clock, the score and recent
381
- kills. `Playback` handles time.
382
-
383
- ## Theming
384
-
385
- Every color and font is a CSS custom property, read from the host element or
386
- any ancestor. So a page can map its own design tokens, including dark mode,
387
- without JavaScript:
388
-
389
- ```css
390
- #replay {
391
- --replay-ct: var(--brand-blue);
392
- --replay-t: var(--brand-yellow);
393
- --replay-bg: var(--surface);
394
- --replay-panel: var(--surface-raised);
395
- --replay-text: var(--text);
396
- }
397
8
  ```
398
9
 
399
- | Property | `theme` key | Used for |
400
- | --- | --- | --- |
401
- | `--replay-ct`, `--replay-t` | `ct`, `t` | The sides: players, names, scores, round winners |
402
- | `--replay-bg` | `background` | Behind the radar or map |
403
- | `--replay-panel`, `--replay-border` | `panel`, `border` | Scoreboard, rosters, kill feed, controls |
404
- | `--replay-text`, `--replay-muted` | `text`, `muted` | Text |
405
- | `--replay-track`, `--replay-track-alt` | `track`, `trackAlt` | Timeline rounds, alternating |
406
- | `--replay-accent` | `accent` | Timeline playhead, focus rings |
407
- | `--replay-bomb` | `bomb` | The bomb, plant markers |
408
- | `--replay-hp-high`, `-mid`, `-low` | `hpHigh`, `hpMid`, `hpLow` | Health bars |
409
- | `--replay-smoke`, `-flash`, `-he`, `-fire`, `-decoy` | `smoke`, `flash`, `he`, `fire`, `decoy` | Grenades |
410
- | `--replay-font`, `--replay-mono` | `font`, `mono` | Fonts |
411
-
412
- The `theme` option overrides the CSS. The viewer redraws when the color
413
- scheme or the `class`/`style` of `<html>` or `<body>` changes. After other
414
- changes, call `viewer.setTheme()`.
415
-
416
- ## Parsing on a server
417
-
418
- For sites that host the demos, parse each demo once and serve the replay.
419
- That's 2.5 MB gzipped instead of a 300 MB download plus 30 s of parsing for
420
- every viewer. The package includes the parser as a program for Linux, macOS
421
- and Windows:
422
-
423
- ```sh
424
- npx demo-replay [-hz 16] [-json] match.dem match.replay
425
- npx demo-replay [-from live|start] -playcast <url> match.replay # record a live match until it ends
426
- ```
427
-
428
- - **Builds:** `npx` runs the one for the machine it's on. To run it without
429
- Node, use `node_modules/@matchomag/cs2-replay/bin/demo-replay-<os>-<arch>`
430
- directly. The builds are `linux-amd64`, `linux-arm64`, `darwin-amd64`,
431
- `darwin-arm64` and `windows-amd64.exe`. They're static, with no
432
- dependencies. The GitHub releases have the same files. A build downloaded
433
- with a browser on macOS won't open until you run
434
- `xattr -d com.apple.quarantine demo-replay-darwin-arm64`, because it isn't
435
- notarized. Builds installed with npm, `curl` or `gh release download` work as
436
- they are.
437
- - **Output:** it writes the replay atomically (a temporary file, then a
438
- rename).
439
- - **Summary:** with `-json` it prints one JSON object on stdout: `map`, `hz`,
440
- `frames`, `players`, `rounds`, `kills`, `grenades`, `bytes` and, for demos
441
- that end in a parse error, `warning`. Those still produce a replay of what
442
- could be read.
443
- - **Exit codes:** `1` on failure, with the error on stderr; `2` for wrong
444
- arguments.
445
- - **Speed:** a 300 MB demo takes about 3 s.
446
-
447
- Serve the result gzipped, either compressed on the fly or stored as
448
- `.replay.gz` and sent with `Content-Encoding: gzip`. `loadReplay()` reads it
449
- either way.
450
-
451
- ## License and assets
452
-
453
- Unlicensed (all rights reserved). The package contains no Valve assets: radar images and
454
- map models are provided by the page that uses it.
10
+ Unlicensed (all rights reserved). The package contains no Valve assets.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matchomag/cs2-replay",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "CS2 demo replay viewers: a 2D radar and a 3D grey-box view on one replay format, plus an in-browser demo parser.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -10,8 +10,7 @@
10
10
  },
11
11
  "files": [
12
12
  "dist",
13
- "bin",
14
- "FORMAT.md"
13
+ "bin"
15
14
  ],
16
15
  "bin": {
17
16
  "demo-replay": "bin/demo-replay.js"
@@ -49,7 +48,8 @@
49
48
  "build:bin": "scripts/build-bin.sh",
50
49
  "test": "vitest run",
51
50
  "typecheck": "tsc --noEmit",
52
- "prepublishOnly": "npm run build"
51
+ "pack:npm": "node scripts/pack.mjs",
52
+ "prepublishOnly": "echo 'Publish the tarball from `npm run pack:npm` (see .github/workflows/replay.yml), which has the npm README.' >&2 && exit 1"
53
53
  },
54
54
  "peerDependencies": {
55
55
  "three": ">=0.160.0"
package/FORMAT.md DELETED
@@ -1,350 +0,0 @@
1
- # Replay file format (`CSRP`, version 1)
2
-
3
- A replay is a compact timeline of one map of a CS2 demo: where every player
4
- was and what state they were in, sampled at a fixed rate, plus the round,
5
- kill, grenade and bomb events. It's what the viewers of `@matchomag/cs2-replay`
6
- play. The extractor (`extractor/replay/extract.go`) writes it, either natively
7
- (`demo-replay`) or in the browser (`parseDemo()`). `readReplay()` in
8
- `src/core/format.ts` reads it.
9
-
10
- For the 305 MB, 16-round sample demo, the replay is 8.0 MB, or 2.5 MB gzipped.
11
- A replay is **not plain JSON**. It's a small binary container: a JSON header
12
- with everything that happens once, followed by flat typed arrays with
13
- everything that happens every frame.
14
-
15
- ```
16
- offset size content
17
- 0 4 magic "CSRP" (ASCII)
18
- 4 4 u32 format version (1)
19
- 8 4 u32 byte length of the JSON header (n)
20
- 12 n JSON header, UTF-8
21
- 12+n 0–3 zero padding to a multiple of 4
22
- ticks 4 × F i32 ticks[F]
23
- pos 16 × F × P f32 pos[F][P][4] x, y, z, yaw
24
- state 4 × F × P u8 state[F][P][4] hp, flags, weapon, armor
25
- 0–3 zero padding to a multiple of 4
26
- bomb 12 × F f32 bomb[F][3] x, y, z
27
- ```
28
-
29
- `F` is `header.frames` and `P` is `header.players.length`. All numbers are
30
- little endian. The start of each array (`ticks`, `pos`, `state`, `bomb`) is
31
- `header.offsets`, in bytes from the start of the file. Use the offsets rather
32
- than computing them, so a reader keeps working if padding changes. Every
33
- offset is a multiple of 4, so the arrays can be read as typed-array views on
34
- the file's buffer without copying.
35
-
36
- Files are often stored or served gzipped (`.replay.gz`, or
37
- `Content-Encoding: gzip`). `loadReplay()` handles both.
38
-
39
- ## Conventions
40
-
41
- - **Frames.** A frame is one sample. Frame `i` is at in-game tick `ticks[i]`.
42
- Samples are taken every `tickRate / hz` ticks (4 ticks at 64 tick and
43
- 16 Hz), but the spacing can vary slightly, so use `ticks` for time. The
44
- seconds between frames `a` and `b` are `(ticks[b] - ticks[a]) / tickRate`.
45
- - **Event frames.** An event's frame (`f`, `start`, `live`, `end`, `effectAt`,
46
- …) is the index of the first frame sampled *after* the event. So the event
47
- happened between frame `f - 1` and frame `f`. Positions "at the moment of a
48
- kill" are best taken from frame `f - 1`.
49
- - **Players** are referenced by their index in `header.players`. `-1` means
50
- nobody (the world, no assister, no thrower).
51
- - **Coordinates** are game units (1 unit = 1 inch), in the map's own world
52
- coordinates, Z up. Player positions are at the feet.
53
- - **Yaw** is in degrees, `0` = +x, increasing counter-clockwise seen from
54
- above (towards +y), in `(-180, 180]`. Interpolate it the short way round
55
- (`lerpAngle()`).
56
- - **Recording** starts at the first round start after warmup. If the match is
57
- restarted (`mp_restartgame`, e.g. after a knife round), the rounds recorded
58
- until then are dropped from `rounds`, but their frames stay. So frames before
59
- `rounds[0].start` belong to no round.
60
- - **Optional fields** are left out when they're false, zero or unknown, as noted
61
- below.
62
-
63
- ## JSON header
64
-
65
- Example, from the sample replay (arrays shortened):
66
-
67
- ```json
68
- {
69
- "map": "de_overpass",
70
- "server": "MatchZy | Team_A vs Team_B",
71
- "protocol": 14163,
72
- "tickRate": 64,
73
- "hz": 16,
74
- "frames": 32727,
75
- "players": [
76
- { "name": "xelex", "steamId": "76561198998266210" },
77
- { "name": "Lake", "steamId": "76561198337484196" }
78
- ],
79
- "weapons": ["", "USP-S", "C4", "Glock-18", "Knife", "Smoke Grenade"],
80
- "rounds": [
81
- { "num": 1, "start": 0, "live": 424, "end": 2192, "winner": "CT", "reason": "elimination",
82
- "scoreT": 0, "scoreCT": 0, "teamT": "M80", "teamCT": "MOUZ" }
83
- ],
84
- "kills": [
85
- { "f": 726, "killer": 9, "victim": 8, "assister": -1, "weapon": "USP-S", "hs": true }
86
- ],
87
- "grenades": [
88
- { "type": "Smoke Grenade", "thrower": 3, "start": 462,
89
- "path": [-2101.3, 974.5, 589.3, -2077, 944.8, 623.2],
90
- "effectAt": 584, "effectEnd": 937, "effectPos": [-548.4, -730.4, 16.2] }
91
- ],
92
- "bomb": [
93
- { "f": 8665, "event": "plant", "player": 1, "site": "B", "pos": [-1251.9, 5, 103.5] }
94
- ],
95
- "offsets": { "ticks": 964848, "pos": 1095756, "state": 6332076, "bomb": 7641156 }
96
- }
97
- ```
98
-
99
- ### Top level
100
-
101
- | Field | Type | Meaning |
102
- | --- | --- | --- |
103
- | `map` | string | Map name from the demo header, e.g. `de_overpass`. |
104
- | `server` | string | Server name from the demo header. |
105
- | `protocol` | number | The demo's network protocol, which is the game's patch version without dots (14163 = 1.41.6.3). It tells you which version of the map the demo was played on. |
106
- | `tickRate` | number | Server ticks per second, usually 64. |
107
- | `hz` | number | Samples per second, 16 unless the extractor ran with `-hz`. |
108
- | `frames` | number | Number of frames, `F`. |
109
- | `players` | [Player] | Everyone who played on T or CT, in the order first seen. |
110
- | `weapons` | [string] | Weapon names, referenced by index from `state`. Index 0 is `""`, no weapon. |
111
- | `rounds` | [Round] | Rounds in order. |
112
- | `kills` | [Kill] | Kills in order. |
113
- | `grenades` | [Grenade] | Thrown grenades in the order thrown. |
114
- | `bomb` | [BombEvent] | Plants, defuses and explosions in order. |
115
- | `shots` | Shots? | Every weapon fired, as parallel arrays. Left out by older extractors. |
116
- | `hurts` | Hurts? | Every time a player took damage, as parallel arrays. Left out by older extractors. |
117
- | `offsets` | object | Byte offsets of the arrays: `ticks`, `pos`, `state`, `bomb`. |
118
-
119
- ### Player
120
-
121
- | Field | Type | Meaning |
122
- | --- | --- | --- |
123
- | `name` | string | Last name seen in the demo. |
124
- | `steamId` | string | SteamID64 as a decimal string. Bots have `""` and are told apart by name. |
125
-
126
- ### Round
127
-
128
- | Field | Type | Meaning |
129
- | --- | --- | --- |
130
- | `num` | number | Round number as the game counts it, from 1. Overtime rounds continue the count. |
131
- | `start` | frame | Round start: freeze time begins. |
132
- | `live` | frame | Freeze time ends, or `-1` if it never did. |
133
- | `end` | frame | The round's winner is known. For a round that never ended, it's the next round's `start` or, at the end of the demo, the last frame. `-1` in a live replay while the round is being played. |
134
- | `winner` | `"T"` \| `"CT"` | The side that won. Left out if the round never ended. |
135
- | `reason` | string | How it was won: `elimination`, `bomb` (exploded), `defuse`, `time`, `surrender`, or the game's reason number as a string. Left out if the round never ended. |
136
- | `scoreT`, `scoreCT` | number | Each side's score at the start of the round. Add 1 to the winner's after `end`. |
137
- | `teamT`, `teamCT` | string | Team names by side in this round, which swap at halftime. `""` when the server set none. |
138
-
139
- Frames from `end` up to the next round's `start` are the time after the round
140
- is won.
141
-
142
- ### Kill
143
-
144
- | Field | Type | Meaning |
145
- | --- | --- | --- |
146
- | `f` | frame | When the kill happened. |
147
- | `killer` | player | `-1` for the world (fall damage, the bomb). Equal to `victim` for a suicide. |
148
- | `victim` | player | |
149
- | `assister` | player | `-1` if none. |
150
- | `weapon` | string | E.g. `AK-47`, `AWP`, `HE Grenade`. `""` if unknown. |
151
- | `hs` | true? | Headshot. |
152
- | `wb` | true? | Through a wall (wallbang). |
153
- | `smoke` | true? | Through a smoke. |
154
- | `noscope` | true? | Scoped weapon fired without scope. |
155
- | `flash` | true? | The victim was flashed by an assisting teammate. |
156
-
157
- ### Grenade
158
-
159
- | Field | Type | Meaning |
160
- | --- | --- | --- |
161
- | `type` | string | `Smoke Grenade`, `Flashbang`, `HE Grenade`, `Molotov`, `Incendiary Grenade` or `Decoy Grenade`. |
162
- | `thrower` | player | `-1` if unknown. |
163
- | `start` | frame | When it was thrown: the frame of the first path point. |
164
- | `path` | [number] | The projectile's position, `x, y, z` for each frame from `start` while it existed. Point `k` is at frame `start + k`, so `path.length / 3` points in all. Empty for a fire whose throw happened before recording started. |
165
- | `effectAt` | frame? | When it went off: smoke spreads, fire starts, flash or HE explodes, decoy starts. Left out if it never did. |
166
- | `effectEnd` | frame? | When the effect ended: smoke fades, fire burns out, decoy stops. Equal to `effectAt` for flashes and HEs. |
167
- | `effectPos` | [x, y, z]? | Where it went off. |
168
- | `voxels` | SmokeVoxels? | Smokes: the game's own voxel cloud. Left out for other grenades and for replays from older extractors. |
169
-
170
- The projectile flies from `start` until `min(effectAt, start + path.length/3 - 1)`.
171
-
172
- ### SmokeVoxels
173
-
174
- CS2 networks each smoke's cloud on its projectile (`m_VoxelFrameData`): an
175
- append-only log of the flood fill's seed cells and of 4×4×4 bricks of world
176
- geometry, sent as the cloud reaches them. The grid is 32³ cells of 20 game
177
- units, centred on `origin` (cell `i` spans `origin + (i - 16) * 20` to
178
- `origin + (i - 15) * 20` on each axis). Clients fill the cloud from the seeds
179
- through open cells; bricks never sent were never reached.
180
-
181
- | Field | Type | Meaning |
182
- | --- | --- | --- |
183
- | `origin` | [x, y, z] | Grid centre, game units (`m_vSmokeDetonationPos`, within a unit of `effectPos`). |
184
- | `data` | base64 | The log merged into one keyframe in the game's layout, little endian: `u8 0`, `u8 3`, `u8 seeds`, then `seeds` × 8 bytes `[x, y, z, density, 0, 0, 0, 0]` (cells; density 0 means unused), `u16 bricks`, then `bricks` × 10 bytes `[u16 brick, u64 solid]`, then `u8 0`. A brick index is the Morton code (bits x, y, z, x, y, z, …) of the brick in the 8³ brick grid; bit `k` of `solid` is the cell whose Morton code within the brick is `k`. A set bit is world geometry. |
185
-
186
- The viewer's fill (`src/3d/smoke/voxels.ts`) is fitted to which bricks the
187
- server sent: a Dijkstra fill over 26 neighbours with Euclidean step costs,
188
- upward steps costing double, no corner cutting, reaching 6 cells from the
189
- seeds.
190
-
191
- ### BombEvent
192
-
193
- | Field | Type | Meaning |
194
- | --- | --- | --- |
195
- | `f` | frame | When it happened. |
196
- | `event` | `"plant"` \| `"defuse"` \| `"explode"` | |
197
- | `player` | player | Who planted or defused, `-1` for explosions. |
198
- | `site` | `"A"` \| `"B"`? | The bomb site. |
199
- | `pos` | [x, y, z] | Where the bomb was. |
200
-
201
- ### Shots
202
-
203
- One entry per `weapon_fire` event: gunshots (one per bullet), knife swings,
204
- grenade throws, the Zeus. Stored as parallel arrays, so entry `i` is
205
- `tick[i]`, `p[i]`, … They are in tick order.
206
-
207
- | Field | Type | Meaning |
208
- | --- | --- | --- |
209
- | `tick` | [number] | In-game tick of the shot. Shots fall between frames: find the frame with `ticks`. |
210
- | `p` | [player] | Who fired. |
211
- | `w` | [number] | Weapon, an index into `weapons`. |
212
- | `yaw` | [number] | View yaw at the shot, degrees, like the per-frame yaw. |
213
- | `pitch` | [number] | View pitch at the shot, degrees in `(-180, 180]`; positive looks down. |
214
-
215
- ### Hurts
216
-
217
- One entry per `player_hurt` event, as parallel arrays in tick order.
218
-
219
- | Field | Type | Meaning |
220
- | --- | --- | --- |
221
- | `tick` | [number] | In-game tick. |
222
- | `victim` | [player] | Who was hurt. |
223
- | `attacker` | [player] | Who did it; `-1` for the world (falls, the bomb). |
224
- | `dmg` | [number] | Health lost. |
225
- | `hit` | [number] | Hit group: 0 generic, 1 head, 2 chest, 3 stomach, 4 left arm, 5 right arm, 6 left leg, 7 right leg, 8 neck. |
226
-
227
- ## Per-frame arrays
228
-
229
- **`ticks[F]`** (i32): the in-game tick of each frame.
230
-
231
- **`pos[F][P][4]`** (f32): for frame `f` and player `p`, the values start at
232
- `(f * P + p) * 4`: `x, y, z, yaw`. Dead players keep a position (usually where
233
- they died), so check the alive flag before drawing them. A player who isn't on
234
- the server, or is spectating, is all zeros in that frame.
235
-
236
- **`state[F][P][4]`** (u8): at the same index as `pos`:
237
-
238
- | Byte | Meaning |
239
- | --- | --- |
240
- | 0 | Health, 0–100. |
241
- | 1 | Flags, see below. |
242
- | 2 | Active weapon, an index into `weapons` (0 = none). |
243
- | 3 | Armor, 0–100. |
244
-
245
- | Flag bit | Value | Meaning |
246
- | --- | --- | --- |
247
- | 0 | 1 | Alive |
248
- | 1 | 2 | Counter-terrorist (otherwise terrorist) |
249
- | 2 | 4 | Ducking |
250
- | 3 | 8 | Blinded by a flash |
251
- | 4 | 16 | Carrying the bomb |
252
- | 5 | 32 | Defusing |
253
- | 6 | 64 | Scoped |
254
- | 7 | 128 | Has a defuse kit |
255
-
256
- A player's side is in their flags, frame by frame, so it changes at halftime
257
- and in overtime.
258
-
259
- **`bomb[F][3]`** (f32): the bomb's position, which is the carrier's position
260
- while carried. All zeros when there is no bomb (e.g. before it's given out).
261
-
262
- ## Versions
263
-
264
- The version after the magic changes when the binary layout or the meaning of
265
- an existing field changes. Readers must reject versions newer than they know
266
- (`readReplay()` throws). New optional JSON fields may be added without a new
267
- version, so readers should ignore fields they don't know.
268
-
269
- ## Live updates (`CSRU`)
270
-
271
- A live match (a CSTV+ broadcast) arrives as a stream of updates instead of one
272
- file. The extractor's live mode writes one every few seconds, whenever it has
273
- parsed everything the broadcast has sent so far. Applied in order, the updates
274
- add up to the replay above: same header fields, same frames.
275
-
276
- An update has the replay's layout, with its own magic and version:
277
-
278
- ```
279
- "CSRU" | u32 version (1) | u32 jsonLen | JSON | pad
280
- i32 ticks[F] | f32 pos[F][P][4] | u8 state[F][P][4] | pad | f32 bomb[F][3]
281
- ```
282
-
283
- `F` is the update's `frames` and `P` its `players.length`. The JSON:
284
-
285
- | Field | Type | Meaning |
286
- | --- | --- | --- |
287
- | `map`, `server`, `protocol`, `tickRate`, `hz` | | As in the replay. A broadcast has no file header: the map comes from the playcast, the server is its CSTV name, and `protocol` is the server's network protocol. |
288
- | `start` | number | Index of this update's first frame: the frame count before it. |
289
- | `frames` | number | Frames in this update. |
290
- | `players`, `weapons` | arrays | The whole lists so far. Players only join: a player's index never changes, and earlier frames have zeros in a new player's slot. |
291
- | `rounds` | `{ from, items }` | Rounds from index `from` on are replaced by `items` (the current round changes as it's played; a restart drops the rounds before it). |
292
- | `kills`, `bomb` | `{ from, items }` | Added to the list at index `from` (its length before). |
293
- | `shots`, `hurts` | `{ from, …arrays }` | The parallel arrays, added at index `from`. |
294
- | `grenades` | array | Grenades that changed: each a grenade with its index `i`, and its path from point `pathFrom` on (`path` holds only the new points). `voxels` is there only when they changed: a smoke's cloud is sent again as it spreads. |
295
- | `final` | boolean | The broadcast is over; nothing follows. The last round and lasting effects are closed in it. |
296
- | `offsets` | object | Byte offsets of the four blocks, as in the replay. |
297
-
298
- Lists an update doesn't change are left out. In a live replay the current
299
- round has `end` `-1`, and a smoke or fire still burning has no `effectEnd`.
300
-
301
- `LiveReplay` from this package applies updates to one `Replay` object that
302
- grows in place (`openPlaycast()` does this for you):
303
-
304
- ```js
305
- import { LiveReplay } from "@matchomag/cs2-replay";
306
-
307
- const live = new LiveReplay();
308
- for (const chunk of updates) live.apply(chunk); // Uint8Array, "CSRU"
309
- live.replay; // the replay so far
310
- ```
311
-
312
- ## Reading a replay
313
-
314
- In JavaScript, with this package:
315
-
316
- ```js
317
- import { readReplay, FLAG } from "@matchomag/cs2-replay";
318
-
319
- const replay = readReplay(new Uint8Array(await file.arrayBuffer()));
320
- const P = replay.players.length;
321
- const f = replay.rounds[0].live, p = 0;
322
- const [x, y, z, yaw] = replay.pos.subarray((f * P + p) * 4, (f * P + p) * 4 + 4);
323
- const alive = (replay.state[(f * P + p) * 4 + 1] & FLAG.Alive) !== 0;
324
- ```
325
-
326
- `createModel(replay).snapshot(frame)` gives the same data already interpreted:
327
- interpolated positions, the round clock, the bomb state, grenades in the air
328
- and kills in the last few seconds.
329
-
330
- Without it, e.g. in Python with only the standard library:
331
-
332
- ```python
333
- import gzip, json, struct
334
-
335
- data = open("match.replay", "rb").read()
336
- if data[:2] == b"\x1f\x8b":
337
- data = gzip.decompress(data)
338
- assert data[:4] == b"CSRP" and struct.unpack_from("<I", data, 4)[0] == 1
339
- n = struct.unpack_from("<I", data, 8)[0]
340
- header = json.loads(data[12 : 12 + n])
341
- F, P, o = header["frames"], len(header["players"]), header["offsets"]
342
-
343
- def player(f, p):
344
- x, y, z, yaw = struct.unpack_from("<4f", data, o["pos"] + (f * P + p) * 16)
345
- hp, flags, weapon, armor = data[o["state"] + (f * P + p) * 4 : o["state"] + (f * P + p) * 4 + 4]
346
- return {"x": x, "y": y, "z": z, "yaw": yaw, "hp": hp, "alive": bool(flags & 1),
347
- "side": "CT" if flags & 2 else "T", "weapon": header["weapons"][weapon], "armor": armor}
348
-
349
- print(header["map"], player(header["rounds"][0]["live"], 0))
350
- ```