@matchomag/cs2-replay 0.0.0-stage → 0.3.0

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 (74) hide show
  1. package/FORMAT.md +350 -0
  2. package/README.md +453 -2
  3. package/bin/demo-replay-darwin-amd64 +0 -0
  4. package/bin/demo-replay-darwin-arm64 +0 -0
  5. package/bin/demo-replay-linux-amd64 +0 -0
  6. package/bin/demo-replay-linux-arm64 +0 -0
  7. package/bin/demo-replay-windows-amd64.exe +0 -0
  8. package/bin/demo-replay.js +22 -0
  9. package/dist/2d/index.js +1 -0
  10. package/dist/3d/index.js +11 -0
  11. package/dist/chunks/actors-EZRYEB4I.js +177 -0
  12. package/dist/chunks/chunk-5BFKVD63.js +1 -0
  13. package/dist/chunks/chunk-D5ST2XVO.js +106 -0
  14. package/dist/chunks/chunk-DQPOBPMK.js +1 -0
  15. package/dist/chunks/chunk-FBSLUYGT.js +1 -0
  16. package/dist/chunks/chunk-Q37CWKZX.js +12 -0
  17. package/dist/chunks/chunk-VSIECNZM.js +1 -0
  18. package/dist/chunks/chunk-YJG3LSSB.js +1 -0
  19. package/dist/chunks/chunk-YO73RW3Y.js +1 -0
  20. package/dist/chunks/look-2WBUGHMJ.js +669 -0
  21. package/dist/index.js +1 -0
  22. package/dist/maps/index.js +1 -0
  23. package/dist/parse/index.js +1 -0
  24. package/dist/parse/wasm/replay.wasm +0 -0
  25. package/dist/parse/worker.js +1 -0
  26. package/dist/types/2d/index.d.ts +17 -0
  27. package/dist/types/2d/radar.d.ts +35 -0
  28. package/dist/types/3d/actors.d.ts +90 -0
  29. package/dist/types/3d/characters/anim.d.ts +93 -0
  30. package/dist/types/3d/characters/ao.d.ts +3 -0
  31. package/dist/types/3d/characters/body.d.ts +37 -0
  32. package/dist/types/3d/characters/builder.d.ts +82 -0
  33. package/dist/types/3d/characters/index.d.ts +74 -0
  34. package/dist/types/3d/characters/rig.d.ts +73 -0
  35. package/dist/types/3d/characters/textures.d.ts +4 -0
  36. package/dist/types/3d/characters/viewmodel.d.ts +51 -0
  37. package/dist/types/3d/characters/weapons.d.ts +25 -0
  38. package/dist/types/3d/follow.d.ts +43 -0
  39. package/dist/types/3d/fx/batch.d.ts +87 -0
  40. package/dist/types/3d/fx/context.d.ts +34 -0
  41. package/dist/types/3d/fx/explosion.d.ts +14 -0
  42. package/dist/types/3d/fx/fire.d.ts +11 -0
  43. package/dist/types/3d/fx/index.d.ts +84 -0
  44. package/dist/types/3d/fx/lights.d.ts +25 -0
  45. package/dist/types/3d/fx/meshes.d.ts +18 -0
  46. package/dist/types/3d/fx/misc.d.ts +15 -0
  47. package/dist/types/3d/fx/random.d.ts +21 -0
  48. package/dist/types/3d/fx/smoke.d.ts +10 -0
  49. package/dist/types/3d/fx/textures.d.ts +29 -0
  50. package/dist/types/3d/fx/types.d.ts +117 -0
  51. package/dist/types/3d/greybox.d.ts +22 -0
  52. package/dist/types/3d/index.d.ts +127 -0
  53. package/dist/types/3d/look.d.ts +49 -0
  54. package/dist/types/3d/markers.d.ts +23 -0
  55. package/dist/types/3d/smoke/volume.d.ts +95 -0
  56. package/dist/types/3d/smoke/voxels.d.ts +87 -0
  57. package/dist/types/3d/world/index.d.ts +179 -0
  58. package/dist/types/3d/world/look.d.ts +16 -0
  59. package/dist/types/3d/world/material.d.ts +128 -0
  60. package/dist/types/3d/world/post.d.ts +75 -0
  61. package/dist/types/3d/world/probes.d.ts +39 -0
  62. package/dist/types/3d/world/release.d.ts +28 -0
  63. package/dist/types/3d/world/stage.d.ts +84 -0
  64. package/dist/types/core/format.d.ts +163 -0
  65. package/dist/types/core/live.d.ts +115 -0
  66. package/dist/types/core/model.d.ts +164 -0
  67. package/dist/types/core/playback.d.ts +82 -0
  68. package/dist/types/core/theme.d.ts +46 -0
  69. package/dist/types/index.d.ts +6 -0
  70. package/dist/types/maps/index.d.ts +258 -0
  71. package/dist/types/parse/index.d.ts +108 -0
  72. package/dist/types/ui/shell.d.ts +131 -0
  73. package/dist/types/ui/styles.d.ts +1 -0
  74. package/package.json +68 -4
package/README.md CHANGED
@@ -1,3 +1,454 @@
1
- # Temporary Holding Version
1
+ # @matchomag/cs2-replay
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
17
+
18
+ ```sh
19
+ 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
+ ```
398
+
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.
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,22 @@
1
+ #!/usr/bin/env node
2
+ // `npx demo-replay [-hz 16] [-json] in.dem out.replay`: runs the build of the
3
+ // demo-replay CLI next to this file that matches this machine.
4
+ import { spawnSync } from "node:child_process";
5
+ import { existsSync } from "node:fs";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ const os = { linux: "linux", darwin: "darwin", win32: "windows" }[process.platform];
9
+ const arch = { x64: "amd64", arm64: "arm64" }[process.arch];
10
+ const exe = fileURLToPath(new URL(`./demo-replay-${os}-${arch}${os === "windows" ? ".exe" : ""}`, import.meta.url));
11
+
12
+ if (!os || !arch || !existsSync(exe)) {
13
+ console.error(`demo-replay: this package has no build for ${process.platform}-${process.arch}`);
14
+ process.exit(1);
15
+ }
16
+ const run = spawnSync(exe, process.argv.slice(2), { stdio: "inherit" });
17
+ if (run.error) {
18
+ console.error("demo-replay:", run.error.message);
19
+ process.exit(1);
20
+ }
21
+ if (run.signal) process.kill(process.pid, run.signal);
22
+ process.exit(run.status ?? 1);
@@ -0,0 +1 @@
1
+ import{b as S}from"../chunks/chunk-D5ST2XVO.js";import{a as ie,b as ne,c as oe,e as w}from"../chunks/chunk-5BFKVD63.js";import{a as G,b as N,c as X,d as J,e as Q,f as Z,g as ee,h as te}from"../chunks/chunk-FBSLUYGT.js";import{a as $,b as q,c as Y,d as B,e as F}from"../chunks/chunk-VSIECNZM.js";import{a as W,b as j,c as O,d as V,e as D,f as L,g as H,h as U,i as K,j as _}from"../chunks/chunk-YJG3LSSB.js";function k(f,a,r,s){let n=f.size??1024;return{level:f.lower&&s<f.lower.below?1:0,u:(a-f.x)/f.scale/n,v:(f.y-r)/f.scale/n}}var M=f=>f.scale*(f.size??1024);function he(f,a){return S(f,a.replay,a,{rosterLayout:"sides",createRenderer:r=>new P(r,a)})}var T=144,I=120,E=175,z=80,C=28,v="rgba(5, 7, 12, 0.9)",A=28*Math.PI/180,P=class{constructor(a,r){this.ctx=a;this.options=r;let s=document.createElement("canvas");s.setAttribute("aria-label",`${r.replay.map} radar`),this.element=s,this.c=s.getContext("2d");let n=r.radar,o=n.crop??[0,0,100,100];this.crop=[o[0]/100,o[1]/100,o[2]/100,o[3]/100];let e=d=>{let c=new Image;return c.decoding="async",c.onload=()=>a.invalidate(),c.src=d,c};this.levels=[n.image,...n.lower?[n.lower.image]:[]].map(d=>({image:e(d),x:0,y:0,w:0,h:0})),this.listen()}ctx;options;element;c;width=0;height=0;levels;crop;view={k:1,ox:0,oy:0};follow=-1;pointers=new Map;pinch=null;cleanups=[];resize(a,r){this.width=a,this.height=r;let s=devicePixelRatio||1;this.element.width=Math.round(a*s),this.element.height=Math.round(r*s),this.layout(),this.clampView()}layout(){let s=Math.max(1,this.width-16),n=Math.max(1,this.height-16),o=this.crop[2]/this.crop[3]||1,e=this.levels.length,d=(b,u)=>Math.min(b/o,u),c=d((s-8*(e-1))/e,n),m=d(s,(n-8*(e-1))/e),h=e>1&&c>=m,y=Math.max(1,h?c:m),t=y*o,i=h?t*e+8*(e-1):t,l=h?y:y*e+8*(e-1),p=8+(s-i)/2,x=8+(n-l)/2;for(let b of this.levels)Object.assign(b,{x:p,y:x,w:t,h:y}),h?p+=t+8:x+=y+8}get unit(){return this.levels[0].w/(this.crop[2]*M(this.options.radar))}project(a,r,s){let n=k(this.options.radar,a,r,s),o=this.levels[Math.min(n.level,this.levels.length-1)];return{level:n.level,x:o.x+(n.u-this.crop[0])/this.crop[2]*o.w,y:o.y+(n.v-this.crop[1])/this.crop[3]*o.h}}clampView(){let a=this.view;a.k=Math.max(1,Math.min(10,a.k)),a.ox=Math.min(0,Math.max(this.width-this.width*a.k,a.ox)),a.oy=Math.min(0,Math.max(this.height-this.height*a.k,a.oy))}zoomAt(a,r,s){let n=this.view,o=Math.max(1,Math.min(10,s));n.ox=a-(a-n.ox)*o/n.k,n.oy=r-(r-n.oy)*o/n.k,n.k=o,this.clampView(),this.ctx.invalidate()}listen(){let a=this.element,r=(n,o,e)=>{a.addEventListener(n,o,e),this.cleanups.push(()=>a.removeEventListener(n,o))};r("wheel",n=>{n.preventDefault(),this.follow=-1,this.zoomAt(n.offsetX,n.offsetY,this.view.k*Math.exp(-n.deltaY*(n.deltaMode?.05:.0015)))},{passive:!1}),r("dblclick",()=>{this.follow=-1,this.view={k:1,ox:0,oy:0},this.ctx.invalidate()}),r("pointerdown",n=>{if(a.setPointerCapture(n.pointerId),this.pointers.set(n.pointerId,{x:n.offsetX,y:n.offsetY}),this.pointers.size===2){let[o,e]=[...this.pointers.values()];this.pinch={dist:Math.hypot(o.x-e.x,o.y-e.y)||1,k:this.view.k,mx:(o.x+e.x)/2,my:(o.y+e.y)/2}}}),r("pointermove",n=>{let o=this.pointers.get(n.pointerId);if(!o)return;let e={x:n.offsetX,y:n.offsetY};if(this.pointers.set(n.pointerId,e),this.pinch&&this.pointers.size===2){let[d,c]=[...this.pointers.values()],m=this.pinch.k*(Math.hypot(d.x-c.x,d.y-c.y)/this.pinch.dist);this.follow=-1,this.zoomAt(this.pinch.mx,this.pinch.my,m)}else this.pointers.size===1&&this.view.k>1&&(this.follow=-1,this.view.ox+=e.x-o.x,this.view.oy+=e.y-o.y,this.clampView(),this.ctx.invalidate())});let s=n=>{this.pointers.delete(n.pointerId),this.pointers.size<2&&(this.pinch=null)};r("pointerup",s),r("pointercancel",s)}focusPlayer(a){this.follow=this.follow===a?-1:a,this.follow>=0?this.view.k=Math.max(this.view.k,2.5):this.view={k:1,ox:0,oy:0},this.ctx.invalidate()}handleKey(a){return a.code==="Escape"&&(this.follow>=0||this.view.k>1)?(this.follow=-1,this.view={k:1,ox:0,oy:0},this.ctx.invalidate(),!0):!1}render({snapshot:a,theme:r}){let s=this.c,n=devicePixelRatio||1;if(s.setTransform(n,0,0,n,0,0),s.fillStyle=r.background,s.fillRect(0,0,this.width,this.height),!this.width||!a)return;if(this.follow>=0){let h=a.players[this.follow],y=h&&(h.alive?h:h.death);if(y){let t=this.project(y.x,y.y,y.z);this.view.ox=this.width/2-t.x*this.view.k,this.view.oy=this.height/2-t.y*this.view.k,this.clampView()}}let{k:o,ox:e,oy:d}=this.view;s.setTransform(n*o,0,0,n*o,n*e,n*d);let c=1/Math.sqrt(o),m=Math.max(4,Math.min(10,this.levels[0].w*.011))*c;this.levels.forEach((h,y)=>{s.save(),s.beginPath(),s.rect(h.x,h.y,h.w,h.h),s.clip();let t=h.image;if(t.complete&&t.naturalWidth){let i=t.naturalWidth,l=t.naturalHeight;s.drawImage(t,this.crop[0]*i,this.crop[1]*l,this.crop[2]*i,this.crop[3]*l,h.x,h.y,h.w,h.h)}else s.fillStyle=r.track,s.fillRect(h.x,h.y,h.w,h.h);this.drawLevel(y,a,r,m,c),s.restore(),this.levels.length>1&&(s.font=`700 ${11*c}px ${r.font}`,s.fillStyle=r.muted,s.fillText(y===0?"UPPER":"LOWER",h.x+6*c,h.y+14*c))})}drawLevel(a,r,s,n,o){let e=this.c,d=this.unit,c=(t,i,l)=>{let p=this.project(t,i,l);return p.level===a?p:null};for(let[t,i]of Object.entries(this.options.radar.sites??{})){let l=c(i[0],i[1],i[2]);l&&(e.font=`700 ${18*o}px ${s.font}`,e.textAlign="center",e.textBaseline="middle",e.fillStyle="rgba(255,255,255,0.5)",e.fillText(t.toUpperCase(),l.x,l.y))}e.textAlign="left",e.textBaseline="alphabetic";for(let t of r.grenades){let i=t.effect;if(!i)continue;let l=c(i.x,i.y,i.z);if(!l)continue;let p=R(s,i.kind);if(e.beginPath(),i.kind==="smoke"){let x=Math.min(1,i.age/1.2);e.arc(l.x,l.y,T*d*x,0,Math.PI*2),e.globalAlpha=.62*Math.min(1,i.remaining/2),e.fillStyle=p,e.fill(),e.globalAlpha*=.9,e.lineWidth=1.5*o,e.strokeStyle=w(s,t.throwerSide),e.stroke()}else if(i.kind==="fire"){let x=Math.min(1,i.age/1.5);e.arc(l.x,l.y,I*d*x,0,Math.PI*2),e.globalAlpha=.42*Math.min(1,i.remaining),e.fillStyle=p,e.fill(),e.globalAlpha=.8*Math.min(1,i.remaining),e.lineWidth=1.5*o,e.strokeStyle=p,e.stroke()}else if(i.kind==="he"||i.kind==="flash"){let x=(i.kind==="he"?E:z)*d*Math.sqrt(Math.max(.02,i.burst));e.arc(l.x,l.y,x,0,Math.PI*2),e.globalAlpha=.5*(1-i.burst),e.fillStyle=p,e.fill(),e.globalAlpha=1-i.burst,e.lineWidth=2*o,e.strokeStyle=p,e.stroke()}else e.arc(l.x,l.y,C*d,0,Math.PI*2),e.globalAlpha=.45,e.fillStyle=p,e.fill();e.globalAlpha=1}e.lineCap="round",e.lineJoin="round";for(let t of r.grenades){let i=R(s,t.kind);if(t.trail&&t.trail.count>0){let{path:l,count:p,fade:x}=t.trail;e.beginPath();let b=!1;for(let u=0;u<p;u++){let g=c(l[u*3],l[u*3+1],l[u*3+2]);if(!g){b=!1;continue}b?e.lineTo(g.x,g.y):e.moveTo(g.x,g.y),b=!0}if(t.projectile&&b){let u=c(t.projectile.x,t.projectile.y,t.projectile.z);u&&e.lineTo(u.x,u.y)}e.globalAlpha=.85*x,e.lineWidth=1.5*o,e.strokeStyle=i,e.stroke(),e.globalAlpha=1}if(t.projectile){let l=c(t.projectile.x,t.projectile.y,t.projectile.z);if(!l)continue;e.beginPath(),e.arc(l.x,l.y,2.8*o,0,Math.PI*2),e.fillStyle=i,e.fill(),e.lineWidth=1*o,e.strokeStyle=v,e.stroke()}}let m=this.options.killLines??3;if(m>0&&r.round){e.setLineDash([4*o,3*o]);for(let t of r.kills){if(!t.killerPos||t.age>m||t.f<r.round.start)continue;let i=c(t.killerPos.x,t.killerPos.y,t.killerPos.z),l=c(t.victimPos.x,t.victimPos.y,t.victimPos.z);!i||!l||(e.beginPath(),e.moveTo(i.x,i.y),e.lineTo(l.x,l.y),e.globalAlpha=.9*(1-t.age/m),e.lineWidth=1.5*o,e.strokeStyle=w(s,t.killerSide),e.stroke())}e.setLineDash([]),e.globalAlpha=1}for(let t of r.players){if(!t.death)continue;let i=c(t.death.x,t.death.y,t.death.z);if(!i)continue;let l=n*.75;e.beginPath(),e.moveTo(i.x-l,i.y-l),e.lineTo(i.x+l,i.y+l),e.moveTo(i.x+l,i.y-l),e.lineTo(i.x-l,i.y+l),e.lineWidth=4*o,e.strokeStyle=v,e.stroke(),e.lineWidth=2*o,e.strokeStyle=w(s,t.death.side),e.stroke()}let h=r.bomb;if(h.state!=="hidden"&&h.state!=="carried"){let t=c(h.x,h.y,h.z);if(t){if(h.state==="planted"){let p=h.sincePlant%1;e.beginPath(),e.arc(t.x,t.y,n*(1+2.6*p),0,Math.PI*2),e.globalAlpha=.9*(1-p),e.lineWidth=2*o,e.strokeStyle=s.bomb,e.stroke(),e.globalAlpha=1}let i=n*1.1;e.beginPath(),e.rect(t.x-i/2,t.y-i/2,i,i);let l=h.state==="planted"&&Math.floor(h.sincePlant*4)%2===1;e.fillStyle=h.state==="defused"?s.ct:l?"#ffffff":s.bomb,e.globalAlpha=h.state==="exploded"?.5:1,e.fill(),e.lineWidth=1.5*o,e.strokeStyle=v,e.stroke(),e.globalAlpha=1}}let y=this.options.names!==!1&&this.levels[0].w*this.view.k>=420;for(let t of r.players){if(!t.alive)continue;let i=c(t.x,t.y,t.z);if(!i)continue;let l=w(s,t.side),p=-t.yaw*Math.PI/180;e.beginPath(),e.moveTo(i.x,i.y),e.arc(i.x,i.y,n*3.4,p-A,p+A),e.closePath(),e.globalAlpha=.3,e.fillStyle=l,e.fill(),e.globalAlpha=1,e.beginPath(),e.arc(i.x,i.y,n,0,Math.PI*2),e.fillStyle=t.blind?"#ffffff":l,e.fill(),e.lineWidth=(this.follow===t.index?3:1.5)*o,e.strokeStyle=this.follow===t.index?s.accent:v,e.stroke(),e.beginPath(),e.moveTo(i.x+Math.cos(p)*n*.35,i.y+Math.sin(p)*n*.35),e.lineTo(i.x+Math.cos(p)*n*1.5,i.y+Math.sin(p)*n*1.5),e.lineWidth=2*o,e.strokeStyle=v,e.stroke(),t.hasBomb&&(e.beginPath(),e.arc(i.x+n*.8,i.y-n*.8,n*.45,0,Math.PI*2),e.fillStyle=s.bomb,e.fill(),e.lineWidth=1*o,e.strokeStyle=v,e.stroke()),t.defusing&&(e.beginPath(),e.setLineDash([2*o,2*o]),e.arc(i.x,i.y,n*1.7,0,Math.PI*2),e.lineWidth=1.5*o,e.strokeStyle=s.ct,e.stroke(),e.setLineDash([])),y&&(e.font=`600 ${10.5*o}px ${s.font}`,e.textAlign="center",e.lineWidth=3*o,e.strokeStyle=v,e.strokeText(t.name,i.x,i.y+n+11*o),e.fillStyle="#ffffff",e.fillText(t.name,i.x,i.y+n+11*o),e.textAlign="left")}}destroy(){this.cleanups.forEach(a=>a())}};function R(f,a){switch(a){case"smoke":return f.smoke;case"flash":return f.flash;case"he":return f.he;case"fire":return f.fire;case"decoy":return f.decoy;default:return f.muted}}export{N as DEFAULT_SPEEDS,G as Emitter,W as FLAG,j as FORMAT_VERSION,te as LiveReplay,X as Playback,O as ReplayFormatError,J as UPDATE_VERSION,F as createModel,he as createRadarViewer,ie as defaultTheme,ee as emptyReplay,B as formatClock,q as grenadeKind,U as gunzip,D as isDemoFile,L as isGzip,Q as isLiveUpdate,V as isReplayFile,Y as lerpAngle,_ as loadReplay,k as radarPoint,M as radarUnits,H as readReplay,K as readSource,Z as readUpdate,oe as resolveTheme,$ as roundEnd,ne as themeVars};
@@ -0,0 +1,11 @@
1
+ import{a as K,b as z}from"../chunks/chunk-D5ST2XVO.js";import{a as Te,b as Se,c as He,f as D}from"../chunks/chunk-5BFKVD63.js";import{a as ge,b as Ee,c as we,d as ve,e as be,f as Me,g as Re,h as xe}from"../chunks/chunk-FBSLUYGT.js";import{a as M,b as F,c as W,d as V,e as O}from"../chunks/chunk-DQPOBPMK.js";import{a as Ve,b as ke,c as Ce,d as Pe,e as Le,f as De,g as Ke,h as ze,i as Fe,j as We,k as Oe}from"../chunks/chunk-YO73RW3Y.js";import{a as me,b as L,c as ue,d as fe,e as ye}from"../chunks/chunk-VSIECNZM.js";import{a as ae,b as re,c as se,d as oe,e as ne,f as le,g as ce,h as he,i as de,j as pe}from"../chunks/chunk-YJG3LSSB.js";import*as o from"three";import{OrbitControls as N}from"three/addons/controls/OrbitControls.js";import{CSS2DObject as j,CSS2DRenderer as U}from"three/addons/renderers/CSS2DRenderer.js";import*as h from"three";import{MeshoptDecoder as Y}from"three/addons/libs/meshopt_decoder.module.js";import{GLTFLoader as B}from"three/addons/loaders/GLTFLoader.js";var H=class{constructor(e,a,t){this.gl=e;this.scene=a;this.camera=t;this.sun.position.set(.5,1,.3),a.add(this.fill,this.sun),e.toneMapping=h.ACESFilmicToneMapping,e.toneMappingExposure=_}gl;scene;camera;prepareFirst=!1;game=null;fill=new h.HemisphereLight(14542591,5588019,1.2);sun=new h.DirectionalLight(16777215,1.6);root=null;async load(e,a,t){let i=await fetch(e);if(!i.ok)throw new Error(`cs2-replay: ${e}: HTTP ${i.status}`);let r=await i.arrayBuffer();t?.();let l=(await new B().setMeshoptDecoder(Y).parseAsync(r,h.LoaderUtils.extractUrlBase(e))).scene,n=new Map,c=0,u=0,y=new h.Box3().setFromObject(l),T={value:new h.Vector2(y.min.y,y.max.y)},g=[];return l.traverse(m=>m.isLight&&g.push(m)),g.forEach(m=>m.removeFromParent()),l.traverse(m=>{let f=m;if(!f.isMesh)return;u++;let w=f.geometry;c+=(w.index?w.index.count:w.attributes.position.count)/3*(m.isInstancedMesh?m.count:1);let p=f.material,v=m.userData.category??m.parent?.userData?.category??p.userData?.category??p.name??"mesh";n.has(v)||n.set(v,[]),n.get(v).push(f);let S=new h.MeshLambertMaterial({color:p.color??new h.Color(.8,.8,.8),flatShading:!0,side:h.DoubleSide,transparent:p.transparent,opacity:p.opacity,depthWrite:!p.transparent});S.name=p.name,S.toneMapped=!1,p.transparent&&(f.renderOrder=1),S.onBeforeCompile=b=>{b.uniforms.heightRange=T,b.vertexShader=b.vertexShader.replace("#include <common>",`#include <common>
2
+ varying float vWorldY;`).replace("#include <worldpos_vertex>",`#include <worldpos_vertex>
3
+ vWorldY = (modelMatrix * vec4(transformed, 1.0)).y;`),b.fragmentShader=b.fragmentShader.replace("#include <common>",`#include <common>
4
+ varying float vWorldY;
5
+ uniform vec2 heightRange;`).replace("#include <color_fragment>",`#include <color_fragment>
6
+ float h = clamp((vWorldY - heightRange.x) / (heightRange.y - heightRange.x), 0.0, 1.0);
7
+ diffuseColor.rgb *= mix(0.65, 1.0, h);`)},f.material=S}),this.root&&this.scene.remove(this.root),this.root=l,this.scene.add(l),{root:l,drawCalls:u,triangles:Math.round(c),categories:n,actors:{lighting:{sun:this.sun,hemi:this.fill,ambient:new h.Color(0),smokeBrightness:q},blobShadows:!0}}}render(){this.gl.render(this.scene,this.camera)}setSize(){}dispose(){this.root?.traverse(e=>{let a=e;a.isMesh&&(a.geometry.dispose(),a.material.dispose())})}},_=1.25,q=.4;function Ue(d,e){let a,t=z(d,e.replay??null,e,{rosterLayout:"overlay",createRenderer:i=>a=new P(i,e)});return Object.defineProperties(t,{loaded:{get:()=>a.loaded},scene:{get:()=>a.scene},camera:{get:()=>a.camera},gameStage:{get:()=>a.gameStage},view:{get:()=>a.view},followed:{get:()=>a.followed},setView:{value:(i,r)=>a.setView(i,r)},setFollow:{value:(i,r=!1)=>a.setView(i===null?"free":r?"first":"third",i??void 0)},setCamera:{value:(i,r,s,l=0,n=0)=>a.setCamera(i,r,s,l,n)},setMode:{value:i=>a.setMode(i)}})}var x=.0254,R=(d,e,a,t=new o.Vector3)=>t.set(e*x,a*x,d*x),X=new Set(["KeyW","KeyA","KeyS","KeyD","KeyE","KeyQ","KeyC","Space","ShiftLeft","ShiftRight"]),Q=new Set(["KeyW","KeyA","KeyS","KeyD"]),A=64*x,Z=46*x,k=.2,G=4.5,$=.65,J=.45,ee={first:["1st","First person"],third:["3rd","Third person"],free:["Free","Free camera"]},te=1.5,P=class{constructor(e,a){this.ctx=e;this.options=a;let t=document.createElement("div");t.className="cs2r-layer",this.element=t;let i=a.look==="game";this.gl=new o.WebGLRenderer({antialias:!i,powerPreference:"high-performance"});let r=devicePixelRatio||1;if(this.gl.setPixelRatio(a.pixelRatio??(i?Math.min(r,a.quality==="low"?1:1.5):r)),this.maxFps=i?60:0,this.settle=i?te:0,this.gl.domElement.style.cssText="position:absolute;inset:0;width:100%;height:100%;display:block",t.append(this.gl.domElement),Object.assign(this.labels.domElement.style,{position:"absolute",top:"0",left:"0",pointerEvents:"none"}),t.append(this.labels.domElement),this.scene.background=new o.Color(a.sky??"#9fb4c7"),this.camera.rotation.order="YXZ",this.orbit=new N(this.camera,this.gl.domElement),this.orbit.addEventListener("change",()=>e.invalidate()),this.mode=a.mode??"fly",this.replayRoot.name="replay",this.scene.add(this.replayRoot),this.bombRing=new o.Mesh(new o.RingGeometry(.85,1,40).rotateX(-Math.PI/2),new o.MeshBasicMaterial({color:16719904,transparent:!0,depthWrite:!1,depthTest:!1,side:o.DoubleSide,toneMapped:!1})),this.bombRing.renderOrder=10,this.replayRoot.add(this.bombRing),e.model){this.buildLabels(),this.aim=new O(e.model.replay),this.rosterControls=this.buildViewSwitch();let s=e.model,l={quality:a.quality==="low"?"low":"high",players:a.players,wait:async()=>{await this.parsing}};this.actorsReady=import("../chunks/actors-EZRYEB4I.js").then(({GameActors:n})=>n.create(s,l)),this.actorsReady.catch(()=>{})}this.listen(),a.help&&(this.helpEl=document.createElement("div"),this.helpEl.className="cs2r-panel cs2r-help",e.stage.append(this.helpEl)),this.setMode(this.mode),this.loaded=this.loadMap()}ctx;options;element;maxFps;settle;scene=new o.Scene;camera=new o.PerspectiveCamera(70,1,.05,5e3);loaded;gl;labels=new U;orbit;mode;speed=8;keys=new Set;groups=new Map;toggles=[];helpEl=null;cleanups=[];replayRoot=new o.Group;players=[];trails=new Map;themeKey="";bombRing;va=new o.Vector3;look=null;get gameStage(){return this.look?.game??null}actorsReady=null;actors=null;parsing=null;size=null;destroyed=!1;texturesPending=!1;followMoving=!1;get continuous(){return this.keys.size>0||this.texturesPending||this.followMoving}cameraView="free";follow=null;lastFollowed=null;pov=-1;aim=null;thirdDist=3;drag=null;rosterControls;viewButtons=new Map;followPos=new o.Vector3;applyTheme(e){let a=`${e.t}|${e.ct}|${e.bomb}|${e.smoke}|${e.flash}|${e.he}|${e.fire}|${e.decoy}|${e.muted}`;if(a!==this.themeKey){this.themeKey=a,this.bombRing.material.color.copy(C(e.bomb));for(let t of this.players)t.key="";for(let t of this.trails.values())t.removeFromParent(),t.geometry.dispose(),t.material.dispose();this.trails.clear()}}buildLabels(){let e=this.ctx.model.replay.players;for(let a=this.players.length;a<e.length;a++){let t=document.createElement("div");t.className="cs2r-plabel",t.innerHTML='<span class="n"></span><span class="cs2r-plabel-hp"><i></i></span>';let i=new j(t);i.visible=!1,this.replayRoot.add(i),this.players.push({label:i,name:t.querySelector(".n"),hp:t.querySelector("i"),key:""})}}replayChanged(){this.buildLabels(),this.aim?.sync(),this.actors?.sync(),this.ctx.invalidate()}trail(e,a){let t=this.trails.get(e),i=this.ctx.model.replay.grenades[e];if(t&&t.userData.points===i.path.length)return t;t&&(t.removeFromParent(),t.geometry.dispose(),t.material.dispose());let r=new Float32Array(i.path.length);for(let n=0;n<i.path.length;n+=3)R(i.path[n],i.path[n+1],i.path[n+2],this.va),r[n]=this.va.x,r[n+1]=this.va.y,r[n+2]=this.va.z;let s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(r,3));let l=C(ie(a,L(i.type)));return t=new o.Line(s,new o.LineBasicMaterial({color:l,transparent:!0,opacity:.7,depthWrite:!1,toneMapped:!1})),t.frustumCulled=!1,t.renderOrder=20,t.userData.points=i.path.length,this.replayRoot.add(t),this.trails.set(e,t),t}async createStage(){let e=this.options;if(e.look!=="game")return new H(this.gl,this.scene,this.camera);let{GameLook:a}=await import("../chunks/look-2WBUGHMJ.js"),t=e.quality==="low";return new a(this.gl,this.scene,this.camera,{transcoderPath:e.transcoderPath,samples:t?0:4,shadowMapSize:t?1024:2048,quality:t?"low":"high",tier:e.tier,lightmaps:e.lightmaps,store:e.store,onProgress:e.onProgress,keepCpuCopies:e.keepCpuCopies},this.ctx.model?.replay??null)}async loadMap(){let e=performance.now(),a=await this.createStage();if(this.destroyed)throw a.dispose(),new Error("cs2-replay: the viewer was destroyed while the map loaded");this.look=a,this.size&&a.setSize(...this.size);let t=async n=>{let c=await this.actorsReady;!c||this.destroyed||(c.setStage(n.actors),c!==this.actors&&(this.actors=c,c.sync(),c.setPov(this.pov),this.scene.add(c.object)),this.ctx.invalidate())},i=()=>{},r=()=>{this.parsing=new Promise(n=>i=n)},s=await a.load(this.options.map,a.prepareFirst?t:null,a.prepareFirst?void 0:r).finally(()=>{i(),this.parsing=null});if(a.prepareFirst||t(s).catch(n=>console.warn(`cs2-replay: players and effects didn't load: ${n}`)),s.textures&&(this.texturesPending=!0,s.textures.finally(()=>{this.texturesPending=!1,this.ctx.invalidate()})),s.categories){this.groups=s.categories;let n=new Set(this.options.hide??[]);for(let[c,u]of this.groups)u.forEach(y=>y.visible=!n.has(c));this.options.categories&&this.buildCategories(n)}let l=new o.Box3().setFromObject(s.root);return this.placeCamera(l),this.ctx.invalidate(),{url:this.options.map,drawCalls:s.drawCalls,triangles:s.triangles,size:l.getSize(new o.Vector3).toArray(),loadMs:performance.now()-e,textures:s.textures,...s.tier?{tier:s.tier,lightmapMode:s.lightmapMode,bytes:s.bytes}:{}}}placeCamera(e){if(this.cameraView!=="free")return;let a=e.getSize(new o.Vector3),t=e.getCenter(new o.Vector3),i=this.options.camera;i?this.setCamera(i[0],i[1],i[2],i[3]??0,i[4]??0):this.options.view==="top"?this.setCamera(t.x,t.y+Math.max(a.x,a.z)*.9,t.z,0,-89.9):(this.camera.position.set(t.x+a.x*.45,t.y+a.y*4,t.z+a.z*.7),this.camera.lookAt(t)),this.setMode(this.mode),this.mode==="orbit"&&!i&&(this.orbit.target.copy(t),this.orbit.update())}buildCategories(e){let a=document.createElement("div");a.className="cs2r-panel cs2r-categories";for(let[t,i]of this.groups){let r=document.createElement("label"),s=document.createElement("input");s.type="checkbox",s.checked=!e.has(t),s.addEventListener("change",()=>{i.forEach(c=>c.visible=s.checked),this.ctx.invalidate()});let l=document.createElement("span");l.className="cs2r-swatch",l.style.background="#"+i[0].material.color.getHexString();let n=i.reduce((c,u)=>c+(u.geometry.index?.count??0)/3,0);r.append(s,l,`${this.toggles.length+1} ${t}`),r.title=`${Math.round(n).toLocaleString()} triangles`,a.append(r),this.toggles.push(s)}this.ctx.stage.append(a)}buildViewSwitch(){let e=document.createElement("div");e.className="cs2r-seg",e.setAttribute("role","group"),e.setAttribute("aria-label","Camera view");for(let a of M){let[t,i]=ee[a],r=document.createElement("button");r.type="button",r.className="cs2r-btn",r.textContent=t,r.title=`${i} (V cycles)`,r.setAttribute("aria-label",i),r.addEventListener("click",()=>this.setView(a)),e.append(r),this.viewButtons.set(a,r)}return this.updateSwitch(),e}updateSwitch(){for(let[e,a]of this.viewButtons)a.setAttribute("aria-pressed",String(e===this.cameraView))}get view(){return this.cameraView}get followed(){return this.follow?.index??null}setView(e,a){let t={view:this.cameraView,player:this.followed};if(e==="free")this.follow=null;else{let i=this.ctx.snapshot(),r=a??this.follow?.index??(i?W(i.players,this.lastFollowed):null);if(r===null||!this.ctx.model?.replay.players[r])return;this.follow?.index!==r&&(this.follow={index:r,target:new o.Vector3,yaw:0,dist:this.thirdDist,elev:k,eye:A,lookYaw:0,lookPitch:0,snap:!0,t:0}),this.lastFollowed=r}this.cameraView=e,!(t.view===e&&t.player===this.followed)&&(this.keys.clear(),this.drag=null,document.pointerLockElement===this.gl.domElement&&document.exitPointerLock(),e==="free"?this.setMode(this.mode):this.orbit.enabled=!1,this.updateSwitch(),this.updateHelp(),this.ctx.invalidate(),this.ctx.emit("view",{view:e,player:this.followed}))}cycle(e){let a=this.ctx.snapshot();if(!a||!this.follow)return;let t=F(a.players,this.follow.index,e);t!==null&&this.setView(this.cameraView,t)}setMode(e){if(this.mode=e,this.ctx.invalidate(),this.cameraView!=="free")return this.setView("free");if(this.orbit.enabled=e==="orbit",e==="orbit"){document.exitPointerLock?.();let a=this.camera.getWorldDirection(new o.Vector3);this.orbit.target.copy(this.camera.position).addScaledVector(a,30),this.orbit.update()}this.updateHelp()}setCamera(e,a,t,i=0,r=0){this.camera.position.set(e,a,t),this.camera.rotation.set(o.MathUtils.degToRad(r),o.MathUtils.degToRad(i),0),this.cameraView!=="free"?this.setView("free"):this.mode==="orbit"&&this.setMode("orbit"),this.ctx.invalidate()}updateHelp(){if(!this.helpEl)return;let e=this.cameraView;this.helpEl.textContent=e!=="free"?`${e==="first"?"FIRST":"THIRD"} PERSON click / right click or Tab / Shift+Tab: next / previous player
8
+ drag: look around${e==="third"?" wheel: distance":""} WASD/Esc: free camera`:this.mode==="fly"?`FLY click = mouse look (Esc releases) WASD move Space/E up C/Q down
9
+ Shift \xD74 wheel = speed (${this.speed.toFixed(1)} m/s) O = orbit 1\u20139 categories`:"ORBIT drag rotate right-drag pan wheel zoom F = fly 1\u20139 categories",this.ctx.model&&(this.helpEl.textContent+=`
10
+ DEMO K play/pause \u2190/\u2192 \xB15 s (Shift \xB11 s) [ / ] round \u2212/= speed`,this.helpEl.textContent+=`
11
+ VIEW V: 1st \u2192 3rd \u2192 free (Shift+V back) click a player in the list to follow them`)}listen(){let e=this.gl.domElement,a=this.ctx.root,t=(r,s,l,n)=>{r.addEventListener(s,l,n),this.cleanups.push(()=>r.removeEventListener(s,l))};t(e,"click",()=>{this.cameraView==="free"&&this.mode==="fly"&&e.requestPointerLock()}),t(document,"mousemove",r=>{this.cameraView!=="free"||this.mode!=="fly"||document.pointerLockElement!==e||(this.ctx.invalidate(),this.camera.rotation.y-=r.movementX*.0022,this.camera.rotation.x=Math.max(-1.55,Math.min(1.55,this.camera.rotation.x-r.movementY*.0022)))}),t(e,"pointerdown",r=>{this.cameraView==="free"||r.button!==0&&r.button!==2||(this.drag={id:r.pointerId,x:r.clientX,y:r.clientY,button:r.button,moved:!1},e.setPointerCapture?.(r.pointerId))}),t(e,"pointermove",r=>{let s=this.drag,l=this.follow;if(!s||!l||r.pointerId!==s.id)return;let n=r.clientX-s.x,c=r.clientY-s.y;!s.moved&&n*n+c*c<25||(s.moved=!0,s.x=r.clientX,s.y=r.clientY,l.lookYaw-=n*.005,l.lookPitch=Math.max(-1.2,Math.min(1.2,l.lookPitch-c*.005)),this.ctx.invalidate())});let i=r=>{let s=this.drag;!s||r.pointerId!==s.id||(this.drag=null,this.ctx.invalidate(),r.type==="pointerup"&&!s.moved&&this.cycle(s.button===2?-1:1))};t(e,"pointerup",i),t(e,"pointercancel",i),t(e,"contextmenu",r=>this.cameraView!=="free"&&r.preventDefault()),t(e,"wheel",r=>{if(this.cameraView==="third"){r.preventDefault(),this.thirdDist=Math.max(1.2,Math.min(12,this.thirdDist*(r.deltaY<0?1/1.15:1.15))),this.ctx.invalidate();return}this.cameraView!=="free"||this.mode!=="fly"||(r.preventDefault(),this.speed=Math.max(.5,Math.min(200,this.speed*(r.deltaY<0?1.2:1/1.2))),this.updateHelp())},{passive:!1}),t(a,"keyup",r=>this.keys.delete(r.code)),t(a,"focusout",()=>this.keys.clear()),t(window,"blur",()=>this.keys.clear())}handleKey(e){let a=this.cameraView!=="free";if(e.code==="KeyV"&&this.ctx.model){let i=M.length;return this.setView(M[(M.indexOf(this.cameraView)+(e.shiftKey?i-1:1))%i]),!0}if(a&&e.code==="Tab"&&e.target===this.ctx.root)return this.cycle(e.shiftKey?-1:1),e.preventDefault(),!0;if(a&&e.code==="Escape")return this.setView("free"),!0;if(a&&!e.repeat&&Q.has(e.code)&&this.setView("free"),e.code==="KeyO")return this.setMode("orbit"),!0;if(e.code==="KeyF")return this.setMode("fly"),!0;let t=Number(e.key);return t>=1&&t<=9&&this.toggles[t-1]?(this.toggles[t-1].click(),!0):this.cameraView==="free"&&this.mode==="fly"&&X.has(e.code)?(this.keys.add(e.code),e.preventDefault(),!0):!1}fly(e){let a=this.keys,t=new o.Vector3((a.has("KeyD")?1:0)-(a.has("KeyA")?1:0),(a.has("Space")||a.has("KeyE")?1:0)-(a.has("KeyC")||a.has("KeyQ")?1:0),(a.has("KeyS")?1:0)-(a.has("KeyW")?1:0));if(!t.lengthSq())return;let i=this.speed*(a.has("ShiftLeft")||a.has("ShiftRight")?4:1)*e,r=this.camera.getWorldDirection(new o.Vector3),s=new o.Vector3().crossVectors(r,this.camera.up).normalize();this.camera.position.addScaledVector(r,-t.z*i).addScaledVector(s,t.x*i),this.camera.position.y+=t.y*i}resize(e,a){this.camera.aspect=e/a,this.camera.updateProjectionMatrix(),this.gl.setSize(e,a,!1),this.size=[e,a],this.look?.setSize(e,a),this.labels.setSize(e,a)}updateFollow(e,a){let t=this.follow,i=e.players[t.index],r=(e.t-t.t)/this.ctx.model.replay.hz;t.t=e.t;let s=i?.present?i.alive?R(i.x,i.y,i.z,this.va):i.death?R(i.death.x,i.death.y,i.death.z,this.va):null:null;if(!s)return;let l=t.snap||r<0||r>1;t.snap=!1;let n=r>0?r:a,c=p=>l?1:1-Math.exp(-n/p);if(!this.drag?.moved){let p=Math.exp(-a/.3);t.lookYaw*=p,t.lookPitch*=p}let u=i.ducking?Z:A;i.alive&&(t.eye+=(u-t.eye)*c(.08));let y=o.MathUtils.degToRad(i.yaw),T=Math.abs(t.lookYaw)>1e-4||Math.abs(t.lookPitch)>1e-4;if(this.cameraView==="first"&&i.alive){let p=o.MathUtils.degToRad(this.aim?.pitch(t.index,e.t)??0),v=o.MathUtils.degToRad(J)*(this.aim?.recoil(t.index,e.t)??0);this.camera.position.set(s.x,s.y+t.eye,s.z),this.camera.rotation.set(Math.max(-1.55,Math.min(1.55,p+v+t.lookPitch)),y+Math.PI+t.lookYaw,0),t.target.copy(this.camera.position),t.yaw=y,t.dist=0,t.elev=-p,this.followMoving=T||Math.abs(u-t.eye)>.001;return}let g=this.followPos.copy(s);g.y+=i.alive?t.eye+.15:.35,t.target.distanceToSquared(g)>25&&(l=!0),(i.alive||l)&&(t.yaw+=V(y,t.yaw)*c(.3)),t.dist+=((i.alive?this.thirdDist:G)-t.dist)*c(.25),t.elev+=((i.alive?k:$)-t.elev)*c(.25),t.target.lerp(g,c(.05)),this.followMoving=T||i.alive&&(Math.abs(V(y,t.yaw))>1e-4||Math.abs(u-t.eye)>.001)||Math.abs((i.alive?this.thirdDist:G)-t.dist)>.001||Math.abs((i.alive?k:$)-t.elev)>1e-4||t.target.distanceToSquared(g)>1e-6;let m=Math.max(-.4,Math.min(1.4,t.elev-t.lookPitch)),f=t.yaw+t.lookYaw,w=Math.cos(m)*t.dist;this.camera.position.set(t.target.x-Math.sin(f)*w,t.target.y+Math.sin(m)*t.dist,t.target.z-Math.cos(f)*w),this.camera.rotation.set(-m,f+Math.PI,0)}setPov(e){e!==this.pov&&(this.actors?.setPov(e),this.pov=e)}focusPlayer(e){this.setView(this.cameraView==="free"?"third":this.cameraView,e)}render({snapshot:e,theme:a,dt:t}){if(this.cameraView==="free"&&(this.mode==="fly"?this.fly(t):this.orbit.update()),e){this.followMoving=!1,this.follow&&this.updateFollow(e,t);let i=this.follow;this.setPov(i&&this.cameraView==="first"&&e.players[i.index]?.alive?i.index:-1),this.applyTheme(a),this.updateReplay(e,a)}this.look?this.look.render():this.gl.render(this.scene,this.camera),this.labels.render(this.scene,this.camera)}updateReplay(e,a){this.actors?.update(e,this.camera,a,C);for(let i of e.players){let r=this.players[i.index];r.label.visible=i.alive&&i.index!==this.pov,r.label.visible&&(R(i.x,i.y,i.z,r.label.position).y+=i.ducking?1.75:2.15);let s=`${i.side}${i.hp}${i.hasBomb}${i.defusing}${i.blind}`;s!==r.key&&(r.key=s,r.name.innerHTML=(i.hasBomb?"[C4] ":"")+K(i.name)+(i.defusing?" \u2702":"")+(i.blind?" \u2736":""),r.name.style.color=i.side==="CT"?a.ct:a.t,r.hp.style.width=`${i.hp}%`,r.hp.style.background=D(a,i.hp))}let t=e.bomb;if(this.bombRing.visible=t.state==="planted",this.bombRing.visible){let i=t.sincePlant%1;R(t.x,t.y,t.z,this.bombRing.position).y+=.08,this.bombRing.scale.setScalar(.5+2.5*i),this.bombRing.material.opacity=.9*(1-i)}for(let i of this.trails.values())i.visible=!1;for(let i of e.grenades){if(!i.trail)continue;let r=this.trail(i.index,a);r.visible=!0,r.geometry.setDrawRange(0,i.trail.count),r.material.opacity=.7*i.trail.fade}}destroy(){this.destroyed=!0,this.actors?.dispose(),this.actors||this.actorsReady?.then(e=>e.dispose(),()=>{}),this.cleanups.forEach(e=>e()),document.pointerLockElement===this.gl.domElement&&document.exitPointerLock(),this.orbit.dispose(),this.look?.dispose(),this.gl.dispose()}};function ie(d,e){return{smoke:d.smoke,flash:d.flash,he:d.he,fire:d.fire,decoy:d.decoy,other:d.muted}[e]}var I=new Map,E=null;function C(d){let e=I.get(d);if(e)return e;if(E??=Object.assign(document.createElement("canvas"),{width:1,height:1}).getContext("2d",{willReadFrequently:!0}),e=new o.Color(16777215),E){E.clearRect(0,0,1,1),E.fillStyle="#fff",E.fillStyle=d,E.fillRect(0,0,1,1);let[a,t,i]=E.getImageData(0,0,1,1).data;e.setRGB(a/255,t/255,i/255,o.SRGBColorSpace)}return I.set(d,e),e}export{Ee as DEFAULT_SPEEDS,ge as Emitter,ae as FLAG,re as FORMAT_VERSION,Ve as GAME_MAP_TIERS,Fe as GameMapStore,xe as LiveReplay,we as Playback,se as ReplayFormatError,ve as UPDATE_VERSION,ye as createModel,Ue as createWorldViewer,Te as defaultTheme,ze as detectGameMapSupport,Re as emptyReplay,ke as fetchGameMapIndex,De as fetchGameMapManifest,Oe as formatBytes,fe as formatClock,Ke as gameMapFiles,Pe as gameMapManifestUrl,L as grenadeKind,Le as greyboxMapUrl,he as gunzip,ne as isDemoFile,le as isGzip,be as isLiveUpdate,oe as isReplayFile,ue as lerpAngle,pe as loadReplay,Ce as pickMapBuild,We as readBody,ce as readReplay,de as readSource,Me as readUpdate,He as resolveTheme,me as roundEnd,Se as themeVars,R as toWorld};