tickflare 0.0.0-stage → 0.1.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 (117) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/LICENSE +21 -0
  3. package/README.md +110 -2
  4. package/dist/binary.d.ts +91 -0
  5. package/dist/binary.js +466 -0
  6. package/dist/binary.js.map +1 -0
  7. package/dist/client/accounts.d.ts +193 -0
  8. package/dist/client/accounts.js +306 -0
  9. package/dist/client/accounts.js.map +1 -0
  10. package/dist/client/draft.d.ts +17 -0
  11. package/dist/client/draft.js +133 -0
  12. package/dist/client/draft.js.map +1 -0
  13. package/dist/client/index.d.ts +161 -0
  14. package/dist/client/index.js +436 -0
  15. package/dist/client/index.js.map +1 -0
  16. package/dist/client/interpolate.d.ts +31 -0
  17. package/dist/client/interpolate.js +59 -0
  18. package/dist/client/interpolate.js.map +1 -0
  19. package/dist/client/lockstep.d.ts +86 -0
  20. package/dist/client/lockstep.js +339 -0
  21. package/dist/client/lockstep.js.map +1 -0
  22. package/dist/client/matchmaking.d.ts +21 -0
  23. package/dist/client/matchmaking.js +55 -0
  24. package/dist/client/matchmaking.js.map +1 -0
  25. package/dist/client/pacer.d.ts +22 -0
  26. package/dist/client/pacer.js +65 -0
  27. package/dist/client/pacer.js.map +1 -0
  28. package/dist/client/predict.d.ts +75 -0
  29. package/dist/client/predict.js +203 -0
  30. package/dist/client/predict.js.map +1 -0
  31. package/dist/client/token.d.ts +10 -0
  32. package/dist/client/token.js +15 -0
  33. package/dist/client/token.js.map +1 -0
  34. package/dist/lockstep.d.ts +154 -0
  35. package/dist/lockstep.js +140 -0
  36. package/dist/lockstep.js.map +1 -0
  37. package/dist/patch.d.ts +54 -0
  38. package/dist/patch.js +186 -0
  39. package/dist/patch.js.map +1 -0
  40. package/dist/protocol.d.ts +230 -0
  41. package/dist/protocol.js +50 -0
  42. package/dist/protocol.js.map +1 -0
  43. package/dist/server/accounts.d.ts +320 -0
  44. package/dist/server/accounts.js +1223 -0
  45. package/dist/server/accounts.js.map +1 -0
  46. package/dist/server/delta.d.ts +50 -0
  47. package/dist/server/delta.js +426 -0
  48. package/dist/server/delta.js.map +1 -0
  49. package/dist/server/frames.d.ts +15 -0
  50. package/dist/server/frames.js +23 -0
  51. package/dist/server/frames.js.map +1 -0
  52. package/dist/server/gateway.d.ts +80 -0
  53. package/dist/server/gateway.js +144 -0
  54. package/dist/server/gateway.js.map +1 -0
  55. package/dist/server/index.d.ts +21 -0
  56. package/dist/server/index.js +22 -0
  57. package/dist/server/index.js.map +1 -0
  58. package/dist/server/limiter.d.ts +12 -0
  59. package/dist/server/limiter.js +43 -0
  60. package/dist/server/limiter.js.map +1 -0
  61. package/dist/server/lockstep.d.ts +126 -0
  62. package/dist/server/lockstep.js +544 -0
  63. package/dist/server/lockstep.js.map +1 -0
  64. package/dist/server/matches.d.ts +31 -0
  65. package/dist/server/matches.js +69 -0
  66. package/dist/server/matches.js.map +1 -0
  67. package/dist/server/matchmaker.d.ts +121 -0
  68. package/dist/server/matchmaker.js +479 -0
  69. package/dist/server/matchmaker.js.map +1 -0
  70. package/dist/server/room.d.ts +383 -0
  71. package/dist/server/room.js +1766 -0
  72. package/dist/server/room.js.map +1 -0
  73. package/dist/server/signals.d.ts +18 -0
  74. package/dist/server/signals.js +37 -0
  75. package/dist/server/signals.js.map +1 -0
  76. package/dist/server/storage.d.ts +117 -0
  77. package/dist/server/storage.js +330 -0
  78. package/dist/server/storage.js.map +1 -0
  79. package/dist/server/tokens.d.ts +74 -0
  80. package/dist/server/tokens.js +117 -0
  81. package/dist/server/tokens.js.map +1 -0
  82. package/dist/server/tracked.d.ts +47 -0
  83. package/dist/server/tracked.js +270 -0
  84. package/dist/server/tracked.js.map +1 -0
  85. package/dist/world.d.ts +20 -0
  86. package/dist/world.js +21 -0
  87. package/dist/world.js.map +1 -0
  88. package/package.json +74 -4
  89. package/src/binary.ts +496 -0
  90. package/src/client/accounts.ts +423 -0
  91. package/src/client/draft.ts +138 -0
  92. package/src/client/index.ts +573 -0
  93. package/src/client/interpolate.ts +60 -0
  94. package/src/client/lockstep.ts +398 -0
  95. package/src/client/matchmaking.ts +61 -0
  96. package/src/client/pacer.ts +67 -0
  97. package/src/client/predict.ts +239 -0
  98. package/src/client/token.ts +22 -0
  99. package/src/lockstep.ts +285 -0
  100. package/src/patch.ts +188 -0
  101. package/src/protocol.ts +260 -0
  102. package/src/server/accounts.ts +1474 -0
  103. package/src/server/delta.ts +467 -0
  104. package/src/server/frames.ts +23 -0
  105. package/src/server/gateway.ts +213 -0
  106. package/src/server/index.ts +85 -0
  107. package/src/server/limiter.ts +41 -0
  108. package/src/server/lockstep.ts +611 -0
  109. package/src/server/matches.ts +99 -0
  110. package/src/server/matchmaker.ts +537 -0
  111. package/src/server/room.ts +1867 -0
  112. package/src/server/signals.ts +46 -0
  113. package/src/server/storage.ts +392 -0
  114. package/src/server/tokens.ts +184 -0
  115. package/src/server/tracked.ts +260 -0
  116. package/src/world.ts +29 -0
  117. package/tools/rooms-report.mjs +168 -0
@@ -0,0 +1,239 @@
1
+ import { produce } from "./draft.js";
2
+ import type { RoomClient } from "./index.js";
3
+
4
+ /** How a `Predictor` works out what the room will do with this player's commands. */
5
+ export interface PredictorOptions<View, Command> {
6
+ /**
7
+ * What one of this player's commands does to the state, written the way
8
+ * the room's `onCommand` is: change `state` in place. It is given a draft
9
+ * of the room's state, so the room's state itself is never touched, and
10
+ * `you` is this player's id. If the room would refuse the command, change
11
+ * nothing.
12
+ */
13
+ apply(state: View, command: Command, you: string): void;
14
+ /**
15
+ * What one tick does to what this player controls, written the way the
16
+ * room's `onTick` is. Give it for a game in which a command sets something
17
+ * in motion that the simulation then carries on with, such as a unit that
18
+ * walks to where it was sent: the prediction then runs as far ahead of the
19
+ * room's state as a command takes to come back, and the player's own unit
20
+ * moves the moment they act. Leave the other players' units alone: where
21
+ * they will be is not this player's to know.
22
+ */
23
+ tick?(state: View, you: string): void;
24
+ /**
25
+ * The room's state changed, or a command was sent, applied or refused.
26
+ * With `tick` the prediction also moves on with time: read `state` when
27
+ * you draw, rather than wait for this.
28
+ */
29
+ onState?(state: View): void;
30
+ /** The clock, in milliseconds. Defaults to `Date.now`. */
31
+ now?(): number;
32
+ }
33
+
34
+ /** How many of the latest frames' arrival times the room's clock is read from. */
35
+ const FRAMES_KEPT = 20;
36
+ /** A frame this much later than the earliest is taken for a room that started ticking again, not for a slow network. */
37
+ const RESTART_MS = 1000;
38
+ /** How many of the latest commands the lead is worked out from. */
39
+ const LEADS_KEPT = 7;
40
+
41
+ /**
42
+ * Shows a player the effect of their own commands at once, instead of when
43
+ * the room's answer arrives.
44
+ *
45
+ * `state` is the room's state with this player's unconfirmed commands
46
+ * applied on top, by the `apply` you give. When the room's state arrives it
47
+ * replaces the guess: commands the room has applied are part of it, commands
48
+ * it refused are dropped, and those still on their way are applied again. So
49
+ * a wrong guess lasts until the room's answer, and never longer.
50
+ *
51
+ * const predicted = new Predictor(room, {
52
+ * apply(state, command, you) {
53
+ * if (command.type === "move") state.units[you].target = command.to;
54
+ * },
55
+ * });
56
+ * button.onclick = () => predicted.send({ type: "move", to });
57
+ * draw(predicted.state);
58
+ *
59
+ * Send through `predicted.send`, and draw from `predicted.state` where you
60
+ * drew from `room.state`. Parts of the state the prediction did not change
61
+ * are the same objects as in `room.state`.
62
+ */
63
+ export class Predictor<View = unknown, Command = unknown> {
64
+ readonly #room: RoomClient<View, Command>;
65
+ readonly #options: PredictorOptions<View, Command>;
66
+ readonly #stop: () => void;
67
+ /** The tick each command of this predictor's was sent at, by the room's reckoning, by command id. */
68
+ #sentAt = new Map<number, number>();
69
+ /** For the latest frames: when each arrived, less the time its tick stands for. The least is the room's clock. */
70
+ #arrivals: number[] = [];
71
+ #lastTick = -1;
72
+ /** How many ticks went by before each of the latest commands showed in the room's state. */
73
+ #leads: number[] = [];
74
+ #lead = 1;
75
+ /** The state `onState` was last called with. */
76
+ #told: View | undefined;
77
+ /** The last prediction, and what it was made from. */
78
+ #made: { base: View | undefined; pending: unknown; from: number; to: number; lead: number; state: View | undefined } | undefined;
79
+
80
+ constructor(room: RoomClient<View, Command>, options: PredictorOptions<View, Command>) {
81
+ this.#room = room;
82
+ this.#options = options;
83
+ this.#stop = room.on("state", () => {
84
+ this.#hear();
85
+ this.#changed();
86
+ });
87
+ if (room.state !== undefined) this.#hear();
88
+ }
89
+
90
+ /**
91
+ * The room's state as it will be once the room has applied this player's
92
+ * unconfirmed commands. Undefined until the room's first state arrives.
93
+ */
94
+ get state(): View | undefined {
95
+ const room = this.#room;
96
+ const base = room.state;
97
+ const pending = room.unconfirmed;
98
+ const { apply, tick } = this.#options;
99
+ const you = room.you ?? "";
100
+ const ticking = tick !== undefined && room.tickRate > 0 && base !== undefined;
101
+
102
+ // With `tick`: the prediction is of the tick at which a command sent now would first show.
103
+ let from = 0;
104
+ let to = 0;
105
+ if (ticking) {
106
+ const now = this.#roomTick();
107
+ // If frames have stopped coming, the state is taken to be a few ticks old at most: nothing
108
+ // in this player's view changed in the ticks without a frame.
109
+ from = Math.max(room.tick, now - this.#mostBehind());
110
+ to = now + this.#lead;
111
+ }
112
+
113
+ const made = this.#made;
114
+ if (made && made.base === base && made.pending === pending && made.from === from && made.to === to && made.lead === this.#lead) {
115
+ return made.state;
116
+ }
117
+ let state = base;
118
+ if (base !== undefined && (pending.length > 0 || to > from)) {
119
+ state = produce(base, (draft) => {
120
+ let next = 0;
121
+ const applyDue = (before: number) => {
122
+ while (next < pending.length && (this.#sentAt.get(pending[next]!.id) ?? 0) + this.#lead <= before) {
123
+ this.#try(() => apply(draft, pending[next]!.command, you));
124
+ next += 1;
125
+ }
126
+ };
127
+ for (let at = from + 1; at <= to; at++) {
128
+ applyDue(at);
129
+ this.#try(() => tick!(draft, you));
130
+ }
131
+ applyDue(Number.POSITIVE_INFINITY);
132
+ });
133
+ }
134
+ this.#made = { base, pending, from, to, lead: this.#lead, state };
135
+ return state;
136
+ }
137
+
138
+ /**
139
+ * With `tick`: how many ticks ahead of the room's state the prediction
140
+ * runs, which is how long a command takes to show there. Measured from the
141
+ * commands sent so far; 1 before the first has come back.
142
+ */
143
+ get lead(): number {
144
+ return this.#lead;
145
+ }
146
+
147
+ /**
148
+ * Send a command, and show its effect at once. Resolves and rejects as
149
+ * `RoomClient.send` does. If the room refuses the command, its effect is
150
+ * taken back.
151
+ */
152
+ send(command: Command): Promise<void> {
153
+ const room = this.#room;
154
+ const before = room.unconfirmed;
155
+ const sent = room.send(command);
156
+ // Not sent at all when there is no connection: then there is nothing to predict.
157
+ const id = room.unconfirmed === before ? undefined : room.unconfirmed[room.unconfirmed.length - 1]!.id;
158
+ const at = Math.max(room.tick, this.#roomTick());
159
+ if (id !== undefined) this.#sentAt.set(id, at);
160
+ const settle = (applied: boolean) => {
161
+ if (id === undefined) return;
162
+ this.#sentAt.delete(id);
163
+ // The room's tick is now the one that first showed the command.
164
+ if (applied && this.#options.tick && room.tickRate > 0) this.#learn(room.tick - at);
165
+ this.#changed();
166
+ };
167
+ sent.then(
168
+ () => settle(true),
169
+ () => settle(false),
170
+ );
171
+ this.#changed();
172
+ return sent;
173
+ }
174
+
175
+ /** Stop following the room. The room itself stays connected. */
176
+ close(): void {
177
+ this.#stop();
178
+ }
179
+
180
+ #changed(): void {
181
+ const { onState } = this.#options;
182
+ if (!onState) return;
183
+ const state = this.state;
184
+ if (state === undefined || state === this.#told) return;
185
+ this.#told = state;
186
+ onState(state);
187
+ }
188
+
189
+ #try(change: () => void): void {
190
+ try {
191
+ change();
192
+ } catch (err) {
193
+ // A prediction that fails is a prediction not made: the room's answer will show what happened.
194
+ console.warn("[tickflare] a prediction threw, and was left out:", err);
195
+ }
196
+ }
197
+
198
+ /** A frame arrived: note when, to tell what tick the room is at between frames. */
199
+ #hear(): void {
200
+ const room = this.#room;
201
+ if (!this.#options.tick || room.tickRate <= 0 || room.tick === this.#lastTick) return;
202
+ this.#lastTick = room.tick;
203
+ const arrival = this.#now() - (room.tick * 1000) / room.tickRate;
204
+ if (this.#arrivals.length > 0 && arrival - Math.min(...this.#arrivals) > RESTART_MS) this.#arrivals = [];
205
+ this.#arrivals.push(arrival);
206
+ if (this.#arrivals.length > FRAMES_KEPT) this.#arrivals.shift();
207
+ }
208
+
209
+ /**
210
+ * The tick the room's latest frame would be of, were one to arrive now.
211
+ * Frames are late by as much as the network holds them up, so the one that
212
+ * was held up least says when ticks happen.
213
+ */
214
+ #roomTick(): number {
215
+ const room = this.#room;
216
+ if (this.#arrivals.length === 0 || room.tickRate <= 0) return room.tick;
217
+ // A hair is added so that the frame the clock was read from is not put a tick early by rounding.
218
+ const ticks = Math.floor(((this.#now() - Math.min(...this.#arrivals)) * room.tickRate) / 1000 + 1e-6);
219
+ return Math.max(room.tick, ticks);
220
+ }
221
+
222
+ /** How many ticks without a frame are taken for a frame that is late, rather than for nothing having changed. */
223
+ #mostBehind(): number {
224
+ return Math.max(2, Math.ceil(this.#room.tickRate / 4));
225
+ }
226
+
227
+ /** A command took `ticks` ticks to show in the room's state. The lead is the middle of the latest few. */
228
+ #learn(ticks: number): void {
229
+ if (!Number.isFinite(ticks)) return;
230
+ this.#leads.push(Math.max(1, Math.min(ticks, 2 * this.#room.tickRate)));
231
+ if (this.#leads.length > LEADS_KEPT) this.#leads.shift();
232
+ const sorted = [...this.#leads].sort((a, b) => a - b);
233
+ this.#lead = sorted[Math.floor(sorted.length / 2)]!;
234
+ }
235
+
236
+ #now(): number {
237
+ return this.#options.now ? this.#options.now() : Date.now();
238
+ }
239
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Where a client gets its join token from. Called before every connection
3
+ * attempt with the id of the room being connected to, so a long session
4
+ * outlives any one token and a token scoped to a room can follow a handover.
5
+ */
6
+ export type TokenSource = (room: string) => string | Promise<string>;
7
+
8
+ /** The room a room URL points at: the last segment of its path. */
9
+ export function roomIn(url: string): string {
10
+ return new URL(url).pathname.replace(/\/+$/, "").split("/").pop() ?? "";
11
+ }
12
+
13
+ /** `url` with a token just asked for as its `token` query parameter, replacing any it had. */
14
+ export async function withFreshToken(url: string, room: string, token: TokenSource): Promise<string> {
15
+ const value = await token(room);
16
+ if (typeof value !== "string" || value === "") {
17
+ throw new TypeError("token() must return a non-empty string");
18
+ }
19
+ const next = new URL(url);
20
+ next.searchParams.set("token", value);
21
+ return next.toString();
22
+ }
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Lockstep: the room does not simulate. It puts everyone's inputs in order,
3
+ * cuts them into numbered turns and sends every player the same turns. Each
4
+ * client runs the same deterministic simulation over them.
5
+ */
6
+
7
+ /** One thing that happened in a turn: a player's input, or a player coming or going. */
8
+ export interface TurnEntry<Input = unknown> {
9
+ /** Who it was. */
10
+ player: string;
11
+ /** Their input, as the room's `parseInput` returned it. */
12
+ input?: Input;
13
+ /** Set instead of `input` when the player joined, left, dropped or came back. */
14
+ event?: "join" | "leave" | "disconnect" | "reconnect";
15
+ }
16
+
17
+ /** What clients see of a lockstep room. */
18
+ export interface LockstepView<Input = unknown> {
19
+ /** Seed for the simulation's random numbers. The same for every player and every replay. */
20
+ seed: number;
21
+ /** The latest turn. */
22
+ turn: number;
23
+ /** What happened in the latest turn, in the order every client must apply it. */
24
+ entries: TurnEntry<Input>[];
25
+ /** Set once two players reported different hashes for the same turn. */
26
+ desync: {
27
+ /** The first turn two players' hashes differed on. */
28
+ turn: number;
29
+ } | null;
30
+ /**
31
+ * Set to `"players"` by a room whose `turnClock` is `"players"`: the room
32
+ * sleeps between turns, and closes them when a player's client asks.
33
+ */
34
+ clock?: "players";
35
+ /**
36
+ * How many turns go by between snapshots, when the room keeps them: a
37
+ * client whose simulation has `save` and `load` sends one each time the
38
+ * turn is a multiple of this.
39
+ */
40
+ snapshotEvery?: number;
41
+ }
42
+
43
+ /**
44
+ * What a room with `turnClock = "players"` sends when it closes turns: turns
45
+ * `n` to `n + c - 1`, all empty but the last, which has `e`.
46
+ */
47
+ export interface TurnsMessage<Input = unknown> {
48
+ /** Marks the message as this one, among any the game sends itself. */
49
+ tickflare: "turns";
50
+ /** The first turn closed. */
51
+ n: number;
52
+ /** How many were closed. */
53
+ c: number;
54
+ /** What happened in the last of them. */
55
+ e: TurnEntry<Input>[];
56
+ /** The player whose request closed them, when it was a request. */
57
+ b?: string;
58
+ }
59
+
60
+ /** Everything needed to run a match again: the seed and every turn in which something happened. */
61
+ export interface Replay<Input = unknown> {
62
+ /** Format version. Recordings made before 0.1 are version 1; `runReplay` reads both. */
63
+ v: 2;
64
+ /** The simulation's seed. */
65
+ seed: number;
66
+ /** Turns per second. */
67
+ turnRate: number;
68
+ /** The last turn of the recording. Turns missing from `turns` were empty. */
69
+ turn: number;
70
+ /** Every turn in which something happened, in order, with what happened in it. */
71
+ turns: [turn: number, entries: TurnEntry<Input>[]][];
72
+ }
73
+
74
+ /**
75
+ * A simulation as it stood after one turn, saved by a player's client and
76
+ * kept by the room, so that someone joining late starts from it instead of
77
+ * from turn 1.
78
+ */
79
+ export interface Snapshot {
80
+ /** The turn the simulation was at. */
81
+ turn: number;
82
+ /** The simulation's hash at that turn, as the players connected then reported it. */
83
+ hash: string;
84
+ /** What the simulation's `save` returned, as JSON text. */
85
+ data: string;
86
+ }
87
+
88
+ /**
89
+ * What a room answers a client that is catching up: the recording, or only
90
+ * the end of it. With `from` set, `turns` has the turns after `from` and
91
+ * nothing earlier: the client continues from the simulation it has, or from
92
+ * `snapshot` when there is one.
93
+ */
94
+ export interface CatchUp<Input = unknown> extends Replay<Input> {
95
+ /** The turn `turns` continues from. Absent when it is the whole recording. */
96
+ from?: number;
97
+ /** A simulation saved at turn `from`, to start from. */
98
+ snapshot?: Snapshot;
99
+ /**
100
+ * Names the run of the room that answered. A client sends it back with
101
+ * the turn its simulation is at, and is given only the turns after that
102
+ * if the room has not restarted since.
103
+ */
104
+ epoch?: string;
105
+ }
106
+
107
+ /**
108
+ * A deterministic game: how to start it from a seed and how to advance it by
109
+ * one turn. Clients run it live with `LockstepClient`; `runReplay` runs it
110
+ * over a recording.
111
+ */
112
+ export interface Simulation<Input, Sim> {
113
+ /** Build the simulation at turn 0. Everything random must come from `seed`. */
114
+ create(seed: number): Sim;
115
+ /** Advance by one turn. Must be deterministic: same simulation and entries in, same simulation out. */
116
+ step(sim: Sim, entries: TurnEntry<Input>[], turn: number): void;
117
+ /**
118
+ * The simulation as JSON: everything `step` reads, the random generator's
119
+ * `state` included. With `load`, it lets a player who joins or reloads
120
+ * late start from a recent snapshot instead of from turn 1.
121
+ */
122
+ save?(sim: Sim): unknown;
123
+ /** The simulation `save` was given, rebuilt from what it returned. */
124
+ load?(saved: unknown): Sim;
125
+ }
126
+
127
+ /** Runs a recording from the start and returns the simulation as it stands after turn `upTo`. */
128
+ export function runReplay<Input, Sim>(
129
+ replay: Replay<Input>,
130
+ simulation: Simulation<Input, Sim>,
131
+ upTo = replay.turn,
132
+ ): Sim {
133
+ const sim = simulation.create(replay.seed);
134
+ stepThrough(sim, replay, simulation, 0, upTo);
135
+ return sim;
136
+ }
137
+
138
+ /**
139
+ * Advances `sim`, which is at turn `from`, to turn `upTo` over a recording.
140
+ * The recording may start anywhere at or before `from`.
141
+ */
142
+ export function stepThrough<Input, Sim>(
143
+ sim: Sim,
144
+ replay: Replay<Input>,
145
+ simulation: Simulation<Input, Sim>,
146
+ from: number,
147
+ upTo = replay.turn,
148
+ ): void {
149
+ const legacy = (replay as { v: number }).v === 1;
150
+ let next = 0;
151
+ while (next < replay.turns.length && replay.turns[next]![0] <= from) next += 1;
152
+ for (let turn = from + 1; turn <= upTo; turn++) {
153
+ const recorded = replay.turns[next];
154
+ if (recorded && recorded[0] === turn) {
155
+ simulation.step(sim, legacy ? recorded[1].map(fromVersion1<Input>) : recorded[1], turn);
156
+ next += 1;
157
+ } else {
158
+ simulation.step(sim, [], turn);
159
+ }
160
+ }
161
+ }
162
+
163
+ /** Version 1 recordings spelled entries `{ p, i, e }`. */
164
+ function fromVersion1<Input>(entry: unknown): TurnEntry<Input> {
165
+ const { p, i, e } = entry as { p: string; i?: Input; e?: TurnEntry["event"] };
166
+ return e === undefined ? { player: p, input: i } : { player: p, event: e };
167
+ }
168
+
169
+ /** A generator made by `seededRandom`: call it for the next number in [0, 1). */
170
+ export interface SeededRandom {
171
+ (): number;
172
+ /**
173
+ * Where the generator stands: one whole number. `seededRandom(state)`
174
+ * makes a generator that carries on from here, which is how a simulation's
175
+ * `save` and `load` keep its randomness.
176
+ */
177
+ readonly state: number;
178
+ }
179
+
180
+ /**
181
+ * A small deterministic random number generator (mulberry32). `Math.random`
182
+ * differs on every machine; this gives every client the same sequence for the
183
+ * same seed. Returns numbers in [0, 1).
184
+ */
185
+ export function seededRandom(seed: number): SeededRandom {
186
+ let a = seed >>> 0;
187
+ const next = () => {
188
+ a = (a + 0x6d2b79f5) >>> 0;
189
+ let t = a;
190
+ t = Math.imul(t ^ (t >>> 15), t | 1);
191
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
192
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
193
+ };
194
+ return Object.defineProperty(next, "state", { get: () => a, enumerable: true }) as SeededRandom;
195
+ }
196
+
197
+ /**
198
+ * A fingerprint of anything JSON can hold: the first 32 hex digits of the
199
+ * SHA-256 of its JSON text. Two simulations that save to the same JSON have
200
+ * the same one, and nobody can make a different simulation that has it too,
201
+ * which is what makes it the right `hash` for snapshots. It is what
202
+ * `LockstepClient` uses when a simulation has `save` and no `hash`.
203
+ *
204
+ * It reads the whole value each time: about a millisecond for 100 KB of
205
+ * JSON. For a very large simulation, report it less often (`hashEvery`).
206
+ */
207
+ export function fingerprint(value: unknown): string {
208
+ return fingerprintOfText(JSON.stringify(value) ?? "");
209
+ }
210
+
211
+ /** `fingerprint` of a value whose JSON text is at hand already. */
212
+ export function fingerprintOfText(text: string): string {
213
+ return sha256(new TextEncoder().encode(text)).slice(0, 32);
214
+ }
215
+
216
+ const K = new Int32Array([
217
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be,
218
+ 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa,
219
+ 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85,
220
+ 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
221
+ 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f,
222
+ 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
223
+ ]);
224
+
225
+ /**
226
+ * SHA-256, as hex. Written out because a simulation is hashed in the middle
227
+ * of a turn, and the one browsers offer, `crypto.subtle.digest`, answers
228
+ * later.
229
+ */
230
+ function sha256(bytes: Uint8Array): string {
231
+ const length = bytes.length;
232
+ const padded = new Uint8Array(((length + 9 + 63) >> 6) << 6);
233
+ padded.set(bytes);
234
+ padded[length] = 0x80;
235
+ const view = new DataView(padded.buffer);
236
+ view.setUint32(padded.length - 8, Math.floor(length / 0x20000000));
237
+ view.setUint32(padded.length - 4, (length << 3) >>> 0);
238
+ const w = new Int32Array(64);
239
+ const rotate = (n: number, by: number) => (n >>> by) | (n << (32 - by));
240
+ let h0 = 0x6a09e667;
241
+ let h1 = 0xbb67ae85 | 0;
242
+ let h2 = 0x3c6ef372;
243
+ let h3 = 0xa54ff53a | 0;
244
+ let h4 = 0x510e527f;
245
+ let h5 = 0x9b05688c | 0;
246
+ let h6 = 0x1f83d9ab;
247
+ let h7 = 0x5be0cd19;
248
+ for (let at = 0; at < padded.length; at += 64) {
249
+ for (let i = 0; i < 16; i++) w[i] = view.getInt32(at + i * 4);
250
+ for (let i = 16; i < 64; i++) {
251
+ const x = w[i - 15]!;
252
+ const y = w[i - 2]!;
253
+ w[i] = (w[i - 16]! + (rotate(x, 7) ^ rotate(x, 18) ^ (x >>> 3)) + w[i - 7]! + (rotate(y, 17) ^ rotate(y, 19) ^ (y >>> 10))) | 0;
254
+ }
255
+ let a = h0;
256
+ let b = h1;
257
+ let c = h2;
258
+ let d = h3;
259
+ let e = h4;
260
+ let f = h5;
261
+ let g = h6;
262
+ let h = h7;
263
+ for (let i = 0; i < 64; i++) {
264
+ const t1 = (h + (rotate(e, 6) ^ rotate(e, 11) ^ rotate(e, 25)) + ((e & f) ^ (~e & g)) + K[i]! + w[i]!) | 0;
265
+ const t2 = ((rotate(a, 2) ^ rotate(a, 13) ^ rotate(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) | 0;
266
+ h = g;
267
+ g = f;
268
+ f = e;
269
+ e = (d + t1) | 0;
270
+ d = c;
271
+ c = b;
272
+ b = a;
273
+ a = (t1 + t2) | 0;
274
+ }
275
+ h0 = (h0 + a) | 0;
276
+ h1 = (h1 + b) | 0;
277
+ h2 = (h2 + c) | 0;
278
+ h3 = (h3 + d) | 0;
279
+ h4 = (h4 + e) | 0;
280
+ h5 = (h5 + f) | 0;
281
+ h6 = (h6 + g) | 0;
282
+ h7 = (h7 + h) | 0;
283
+ }
284
+ return [h0, h1, h2, h3, h4, h5, h6, h7].map((n) => (n >>> 0).toString(16).padStart(8, "0")).join("");
285
+ }