tickflare 0.1.0 → 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 (62) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +5 -2
  3. package/dist/client/buffered.d.ts +108 -0
  4. package/dist/client/buffered.js +252 -0
  5. package/dist/client/buffered.js.map +1 -0
  6. package/dist/client/clock.d.ts +36 -0
  7. package/dist/client/clock.js +83 -0
  8. package/dist/client/clock.js.map +1 -0
  9. package/dist/client/index.d.ts +83 -5
  10. package/dist/client/index.js +254 -15
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/client/interpolate.d.ts +6 -5
  13. package/dist/client/interpolate.js +6 -5
  14. package/dist/client/interpolate.js.map +1 -1
  15. package/dist/client/lockstep.d.ts +23 -4
  16. package/dist/client/lockstep.js +47 -4
  17. package/dist/client/lockstep.js.map +1 -1
  18. package/dist/client/predict.js +16 -3
  19. package/dist/client/predict.js.map +1 -1
  20. package/dist/lockstep.d.ts +43 -4
  21. package/dist/lockstep.js +33 -0
  22. package/dist/lockstep.js.map +1 -1
  23. package/dist/protocol.d.ts +131 -5
  24. package/dist/protocol.js +16 -3
  25. package/dist/protocol.js.map +1 -1
  26. package/dist/server/gateway.d.ts +5 -0
  27. package/dist/server/gateway.js +14 -0
  28. package/dist/server/gateway.js.map +1 -1
  29. package/dist/server/index.d.ts +4 -3
  30. package/dist/server/index.js +3 -2
  31. package/dist/server/index.js.map +1 -1
  32. package/dist/server/lockstep.d.ts +30 -4
  33. package/dist/server/lockstep.js +78 -6
  34. package/dist/server/lockstep.js.map +1 -1
  35. package/dist/server/room.d.ts +138 -2
  36. package/dist/server/room.js +701 -44
  37. package/dist/server/room.js.map +1 -1
  38. package/dist/server/schema.d.ts +67 -0
  39. package/dist/server/schema.js +44 -0
  40. package/dist/server/schema.js.map +1 -0
  41. package/dist/server/spectators.d.ts +74 -0
  42. package/dist/server/spectators.js +190 -0
  43. package/dist/server/spectators.js.map +1 -0
  44. package/dist/server/storage.d.ts +13 -1
  45. package/dist/server/storage.js +23 -5
  46. package/dist/server/storage.js.map +1 -1
  47. package/package.json +1 -1
  48. package/src/client/buffered.ts +294 -0
  49. package/src/client/clock.ts +86 -0
  50. package/src/client/index.ts +296 -15
  51. package/src/client/interpolate.ts +6 -5
  52. package/src/client/lockstep.ts +68 -7
  53. package/src/client/predict.ts +16 -3
  54. package/src/lockstep.ts +67 -4
  55. package/src/protocol.ts +134 -4
  56. package/src/server/gateway.ts +14 -0
  57. package/src/server/index.ts +7 -0
  58. package/src/server/lockstep.ts +77 -7
  59. package/src/server/room.ts +735 -45
  60. package/src/server/schema.ts +101 -0
  61. package/src/server/spectators.ts +221 -0
  62. package/src/server/storage.ts +33 -6
@@ -0,0 +1,190 @@
1
+ import { applyPatch } from "../patch.js";
2
+ import { DeltaSender } from "./delta.js";
3
+ /** Marks the socket of a spectator. With no tag that is a player's id, the room takes it for nobody's. */
4
+ export const SPECTATOR_TAG = "\u0001spectator";
5
+ /** Starts the tag that says who a spectator is. */
6
+ export const SPECTATOR_ID_TAG = "\u0001s=";
7
+ /**
8
+ * How long the line goes on with nobody watching. A spectator whose
9
+ * connection dropped and who is back within this finds the line where it
10
+ * was, and misses only what was let out while they were away.
11
+ */
12
+ export const LINGER_MS = 20_000;
13
+ /**
14
+ * The most that may be waiting to be let out, in characters of frames. A
15
+ * line that holds more than this has a delay too long for how fast its room
16
+ * changes: it starts over, so that the room does not run out of memory.
17
+ */
18
+ const MAX_QUEUED_CHARS = 16_000_000;
19
+ /**
20
+ * What a room's spectators are sent, and when: everything, the same for all
21
+ * of them, and `delayMs` after the players were sent it.
22
+ *
23
+ * Each time the room sends its players something, the line takes the
24
+ * spectators' view of that moment, works out the patch from the view it took
25
+ * before, and queues the frame. A timer lets the frames out in order when
26
+ * their time has come, to every spectator connected then. Who is here and
27
+ * what the room broadcasts go through the same queue, so that nothing
28
+ * reaches a spectator sooner than the view it belongs with.
29
+ *
30
+ * Since all spectators are sent the same frames, the line also knows what
31
+ * every one of them holds: the latest view it let out, which is what one who
32
+ * connects is welcomed with. When the line starts there is no such view yet.
33
+ * Its first frame is a whole view, and a spectator welcomed before that has
34
+ * come due is told to wait for it.
35
+ *
36
+ * What waits is kept as the text that will be sent, and nothing else: with a
37
+ * long delay there is a lot of it. The view the spectators hold is worked
38
+ * out from the frames as they are let out.
39
+ *
40
+ * The line runs while someone watches and for `LINGER_MS` after. All of it
41
+ * is in memory: a room that restarts starts the line again, with a whole
42
+ * view for whoever is still connected.
43
+ */
44
+ export class SpectatorLine {
45
+ #watching;
46
+ #sender = new DeltaSender();
47
+ /** What `#sender` last sent. It sends to `#tape`, which keeps the frame instead. */
48
+ #caught;
49
+ #tape = {
50
+ send: (frame) => {
51
+ this.#caught = frame;
52
+ },
53
+ };
54
+ #queue = [];
55
+ #queuedChars = 0;
56
+ #shown;
57
+ #players;
58
+ #running = false;
59
+ #idleSince;
60
+ #timer;
61
+ /** @param watching the open sockets of the spectators, asked for whenever something is let out */
62
+ constructor(watching) {
63
+ this.#watching = watching;
64
+ }
65
+ /** Whether views are being taken. */
66
+ get running() {
67
+ return this.#running;
68
+ }
69
+ /** The latest view let out, which is what every spectator holds. Undefined until the first has been. */
70
+ get shown() {
71
+ return this.#shown;
72
+ }
73
+ /** Who the spectators have been told is here. Undefined until they have been. */
74
+ get players() {
75
+ return this.#players;
76
+ }
77
+ /**
78
+ * Whether the line goes on, now that someone is watching or nobody is: it
79
+ * stops once nobody has for `LINGER_MS`.
80
+ */
81
+ keep(watched, now = Date.now()) {
82
+ if (watched) {
83
+ this.#idleSince = undefined;
84
+ return true;
85
+ }
86
+ this.#idleSince ??= now;
87
+ if (now - this.#idleSince < LINGER_MS)
88
+ return true;
89
+ this.stop();
90
+ return false;
91
+ }
92
+ /**
93
+ * Takes the spectators' view as it is now, to be let out in `delayMs`.
94
+ * The first one taken starts the line and goes out whole, the others as
95
+ * what changed. `view` may be the room's own objects: what is kept is a
96
+ * copy.
97
+ */
98
+ take(view, seq, tick, delayMs, now = Date.now()) {
99
+ this.#running = true;
100
+ this.#caught = undefined;
101
+ this.#sender.send([{ ws: this.#tape, id: "spectators", arrays: true }], seq, tick, undefined, () => view);
102
+ const frame = this.#caught;
103
+ this.#caught = undefined;
104
+ // Nothing a spectator sees has changed.
105
+ if (frame === undefined)
106
+ return;
107
+ this.#push({ at: now + delayMs, frame, view: true }, now);
108
+ }
109
+ /** Queues who is here, as the whole list. */
110
+ tell(players, delayMs, now = Date.now()) {
111
+ this.#push({ at: now + delayMs, frame: JSON.stringify({ t: "presence", players }), players }, now);
112
+ }
113
+ /** Queues a frame as it is: a message the room broadcast. */
114
+ say(frame, delayMs, now = Date.now()) {
115
+ this.#push({ at: now + delayMs, frame }, now);
116
+ }
117
+ /** Forgets everything. The next view taken starts a new line. */
118
+ stop() {
119
+ if (this.#timer !== undefined)
120
+ clearTimeout(this.#timer);
121
+ this.#timer = undefined;
122
+ this.#queue = [];
123
+ this.#queuedChars = 0;
124
+ this.#shown = undefined;
125
+ this.#players = undefined;
126
+ this.#running = false;
127
+ this.#idleSince = undefined;
128
+ this.#sender.reset();
129
+ }
130
+ #push(entry, now) {
131
+ const last = this.#queue[this.#queue.length - 1];
132
+ // In the order they were queued in, whatever the delay has been changed to since.
133
+ if (last && entry.at < last.at)
134
+ entry.at = last.at;
135
+ this.#queue.push(entry);
136
+ this.#queuedChars += entry.frame.length;
137
+ if (this.#queuedChars > MAX_QUEUED_CHARS) {
138
+ console.error(`[tickflare] more than ${MAX_QUEUED_CHARS} characters are waiting to be sent to spectators; their view starts over. The delay is too long for how fast this room's state changes.`);
139
+ this.stop();
140
+ return;
141
+ }
142
+ this.release(now);
143
+ }
144
+ /** A frame that brings a view is let out: the spectators hold what it leaves them with. */
145
+ #hold(frame) {
146
+ const sent = JSON.parse(frame);
147
+ if (sent.t === "state") {
148
+ this.#shown = { seq: sent.seq, tick: sent.tick, view: sent.state };
149
+ }
150
+ else if (this.#shown) {
151
+ this.#shown = { seq: sent.seq, tick: sent.tick, view: applyPatch(this.#shown.view, sent.p) };
152
+ }
153
+ }
154
+ /** Lets out what has come due by `now`, and sets the timer for what has not. */
155
+ release(now = Date.now()) {
156
+ if (this.#timer !== undefined)
157
+ clearTimeout(this.#timer);
158
+ this.#timer = undefined;
159
+ let sockets;
160
+ while (this.#queue.length > 0 && this.#queue[0].at <= now) {
161
+ const entry = this.#queue.shift();
162
+ this.#queuedChars -= entry.frame.length;
163
+ if (entry.view)
164
+ this.#hold(entry.frame);
165
+ if (entry.players)
166
+ this.#players = entry.players;
167
+ for (const ws of (sockets ??= this.#watching())) {
168
+ try {
169
+ ws.send(entry.frame);
170
+ }
171
+ catch {
172
+ // Socket is closing.
173
+ }
174
+ }
175
+ }
176
+ const next = this.#queue[0];
177
+ if (!next)
178
+ return;
179
+ this.#timer = setTimeout(() => {
180
+ this.#timer = undefined;
181
+ try {
182
+ this.release();
183
+ }
184
+ catch (err) {
185
+ console.error("[tickflare] could not send to the spectators:", err);
186
+ }
187
+ }, Math.max(0, next.at - Date.now()));
188
+ }
189
+ }
190
+ //# sourceMappingURL=spectators.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"spectators.js","sourceRoot":"","sources":["../../src/server/spectators.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAc,MAAM,aAAa,CAAC;AAErD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,0GAA0G;AAC1G,MAAM,CAAC,MAAM,aAAa,GAAG,iBAAiB,CAAC;AAC/C,mDAAmD;AACnD,MAAM,CAAC,MAAM,gBAAgB,GAAG,UAAU,CAAC;AAqB3C;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,MAAM,CAAC;AAEhC;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,UAAU,CAAC;AAEpC;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,OAAO,aAAa;IACf,SAAS,CAAoB;IACtC,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;QACH,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QAC5B,IAAI,CAAC,IAAI;YAAE,OAAO;QAClB,IAAI,CAAC,MAAM,GAAG,UAAU,CACtB,GAAG,EAAE;YACH,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;YACxB,IAAI,CAAC;gBACH,IAAI,CAAC,OAAO,EAAE,CAAC;YACjB,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,OAAO,CAAC,KAAK,CAAC,+CAA+C,EAAE,GAAG,CAAC,CAAC;YACtE,CAAC;QACH,CAAC,EACD,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,CAClC,CAAC;IACJ,CAAC;CACF"}
@@ -6,6 +6,13 @@ export interface StoredRoom {
6
6
  roster: string;
7
7
  /** How many times the simulation has ticked. 0 in a room that does not tick. */
8
8
  tick: number;
9
+ /**
10
+ * Which commands of each client the room had handled when this state was
11
+ * saved, as JSON, or "" for none: what keeps a command that is sent again
12
+ * after a lost connection from being applied twice. In the same row as
13
+ * the state, so that the two are never of different moments.
14
+ */
15
+ handled: string;
9
16
  }
10
17
  /** Something a committed hook promised to deliver: a finished match, or a player handed to another room. */
11
18
  export type OutboxEntry = {
@@ -38,7 +45,7 @@ export interface Forward {
38
45
  * nothing behind.
39
46
  *
40
47
  * Tables:
41
- * tickflare_room one row: seq, state, seats, tick counter
48
+ * tickflare_room one row: seq, state, seats, tick counter, commands handled
42
49
  * tickflare_parts the rest of a state or a delivery too long for one row
43
50
  * tickflare_timers named timers and when they fire
44
51
  * tickflare_meta small values by key (room id, invited players)
@@ -81,6 +88,11 @@ export declare class RoomStorage {
81
88
  * 1.5 MB.
82
89
  */
83
90
  writeRoom(room: StoredRoom): void;
91
+ /**
92
+ * Writes which commands were handled, and nothing else of the room: one
93
+ * row, however long the state is. False if the room has no row yet.
94
+ */
95
+ writeHandled(handled: string): boolean;
84
96
  /** Timer names and when they fire, ordered by name. */
85
97
  timers(): [name: string, firesAt: number][];
86
98
  /** Makes the stored timers match `timers`, writing only the ones that differ: reads are all but free, rows written are not. */
@@ -9,7 +9,7 @@
9
9
  * nothing behind.
10
10
  *
11
11
  * Tables:
12
- * tickflare_room one row: seq, state, seats, tick counter
12
+ * tickflare_room one row: seq, state, seats, tick counter, commands handled
13
13
  * tickflare_parts the rest of a state or a delivery too long for one row
14
14
  * tickflare_timers named timers and when they fire
15
15
  * tickflare_meta small values by key (room id, invited players)
@@ -79,6 +79,14 @@ export class RoomStorage {
79
79
  catch {
80
80
  sql.exec("ALTER TABLE tickflare_room ADD COLUMN tick INTEGER NOT NULL DEFAULT 0");
81
81
  }
82
+ // Which commands were handled came with protocol version 5. It is a column of the room's row
83
+ // for the same reason: one row a save.
84
+ try {
85
+ sql.exec("SELECT handled FROM tickflare_room LIMIT 0");
86
+ }
87
+ catch {
88
+ sql.exec("ALTER TABLE tickflare_room ADD COLUMN handled TEXT NOT NULL DEFAULT ''");
89
+ }
82
90
  }
83
91
  /** Creates the tables, before the first thing is written. */
84
92
  #make() {
@@ -89,7 +97,8 @@ export class RoomStorage {
89
97
  seq INTEGER NOT NULL,
90
98
  state TEXT NOT NULL,
91
99
  players TEXT NOT NULL,
92
- tick INTEGER NOT NULL DEFAULT 0
100
+ tick INTEGER NOT NULL DEFAULT 0,
101
+ handled TEXT NOT NULL DEFAULT ''
93
102
  )`);
94
103
  this.#tables();
95
104
  this.#made = true;
@@ -164,9 +173,9 @@ export class RoomStorage {
164
173
  if (!this.#made)
165
174
  return undefined;
166
175
  const row = this.#sql
167
- .exec("SELECT seq, state, players, tick FROM tickflare_room WHERE id = 1")
176
+ .exec("SELECT seq, state, players, tick, handled FROM tickflare_room WHERE id = 1")
168
177
  .toArray()[0];
169
- return row && { seq: row.seq, state: row.state + this.#rest("state"), roster: row.players, tick: row.tick };
178
+ return (row && { seq: row.seq, state: row.state + this.#rest("state"), roster: row.players, tick: row.tick, handled: row.handled });
170
179
  }
171
180
  /**
172
181
  * One row, whatever changed: this is what a save costs. A state too long
@@ -176,9 +185,18 @@ export class RoomStorage {
176
185
  writeRoom(room) {
177
186
  this.#make();
178
187
  const [first, ...rest] = pieces(room.state);
179
- this.#sql.exec("INSERT OR REPLACE INTO tickflare_room (id, seq, state, players, tick) VALUES (1, ?, ?, ?, ?)", room.seq, first, room.roster, room.tick);
188
+ this.#sql.exec("INSERT OR REPLACE INTO tickflare_room (id, seq, state, players, tick, handled) VALUES (1, ?, ?, ?, ?, ?)", room.seq, first, room.roster, room.tick, room.handled);
180
189
  this.#putRest("state", rest);
181
190
  }
191
+ /**
192
+ * Writes which commands were handled, and nothing else of the room: one
193
+ * row, however long the state is. False if the room has no row yet.
194
+ */
195
+ writeHandled(handled) {
196
+ if (!this.#made)
197
+ return false;
198
+ return this.#sql.exec("UPDATE tickflare_room SET handled = ? WHERE id = 1", handled).rowsWritten > 0;
199
+ }
182
200
  /** What follows the first piece of a text that was split, or "" for one that was not. */
183
201
  #rest(owner) {
184
202
  if (!this.#split.has(owner))
@@ -1 +1 @@
1
- {"version":3,"file":"storage.js","sourceRoot":"","sources":["../../src/server/storage.ts"],"names":[],"mappings":"AAyBA;;;;;;;;;;;;;;;;;;GAkBG;AACH;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,SAAS,CAAC;AAEnC;;;;;GAKG;AACH,MAAM,UAAU,MAAM,CAAC,IAAY,EAAE,KAAK,GAAG,SAAS;IACpD,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,IAAI,KAAK;QAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5C,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,KAAK,CAAC,CAAC;IACrC,MAAM,GAAG,GAAa,EAAE,CAAC;IACzB,KAAK,IAAI,EAAE,GAAG,CAAC,EAAE,EAAE,GAA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AC,IAAI,CAAC,KAAK;YAAE,OAAO;QACxB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,4DAA4D,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IAChG,CAAC;IAED,aAAa,CAAC,MAAc;QAC1B,IAAI,CAAC,IAAI,CAAC,KAAK;YAAE,OAAO;QACxB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,iDAAiD,EAAE,MAAM,CAAC,CAAC;IAC5E,CAAC;IAED,oDAAoD;IACpD,aAAa,CAAC,GAAW;QACvB,IAAI,CAAC,IAAI,CAAC,KAAK;YAAE,OAAO;QACxB,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,2EAA2E,EAAE,GAAG,CAAC,CAAC;IACnG,CAAC;CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tickflare",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Multiplayer game framework for Cloudflare Workers and Durable Objects",
5
5
  "license": "MIT",
6
6
  "homepage": "https://tickflare.gridpaper.dev",
@@ -0,0 +1,294 @@
1
+ import { ServerClock, localNow } from "./clock.js";
2
+
3
+ /** What `BufferedInterpolator` reads the ticks from: a `RoomClient` will do. */
4
+ export interface TickSource {
5
+ /** The tick of the latest state: read when `update` is called. */
6
+ readonly tick: number;
7
+ /** Ticks a second; 0 in event mode. */
8
+ readonly tickRate: number;
9
+ /** Patches a second, when the room sends less often than it ticks: `RoomClient.patchRate`. */
10
+ readonly patchRate?: number;
11
+ /** The tick the room is on at `now`, by estimate, as `RoomClient.serverTick` gives it. */
12
+ serverTick?(now?: number): number | undefined;
13
+ }
14
+
15
+ /** Settings for `BufferedInterpolator`. */
16
+ export interface BufferedInterpolatorOptions<Field extends string> {
17
+ /**
18
+ * How far behind the newest state it expects to have, in ticks, before the
19
+ * margin for jitter is added. By default one tick more than there are
20
+ * between two patches, so that there are always two to draw between: 2
21
+ * for a room that sends after every tick, where a patch can then be a tick
22
+ * late or cover two ticks without anything having to be guessed, and 4
23
+ * for one that ticks 60 times a second and sends 20 times.
24
+ */
25
+ delayTicks?: number;
26
+ /**
27
+ * For how many ticks a thing keeps moving at its last speed when no newer
28
+ * state has arrived for it, before it stops where it got to. By default
29
+ * two ticks more than there are between two patches, which is 3 for a
30
+ * room that sends after every tick; 0 stops it at its last known place.
31
+ */
32
+ maxExtrapolationTicks?: number;
33
+ /**
34
+ * A change between two states in a row farther than this, measured over
35
+ * the fields that are not angles, is a jump: drawn as one, when the time
36
+ * comes, instead of a slide. Off by default. Set it above the farthest
37
+ * anything moves between two patches.
38
+ */
39
+ snapDistance?: number;
40
+ /** Fields that are angles in radians, which go the short way round through ±π. */
41
+ angles?: readonly Field[];
42
+ }
43
+
44
+ interface Snapshot<Field extends string> {
45
+ tick: number;
46
+ values: Record<Field, number>;
47
+ /** It was a jump from the one before. */
48
+ snap: boolean;
49
+ }
50
+
51
+ /** Snapshots kept per id at the most, whatever the delay. */
52
+ const MAX_SNAPSHOTS = 64;
53
+
54
+ /**
55
+ * Smooths values that arrive once per tick by drawing them a little in the
56
+ * past, at an even pace, from the ticks they belong to.
57
+ *
58
+ * `Interpolator` glides to each new value as it arrives: it adds almost no
59
+ * delay, but things speed up when two patches arrive together and stop when
60
+ * one is late. This one keeps the last few states of each id, keyed by the
61
+ * room's tick, and draws the moment `delay` ticks behind the tick the room
62
+ * is on (`RoomClient.serverTick()`), blending the states on either side.
63
+ * Motion then keeps the pace of the room, whatever the network does to the
64
+ * patches, at the cost of the delay: two ticks and a margin for the jitter
65
+ * it measures, which it keeps adjusting. Against a room that sends less
66
+ * often than it ticks (`patchRate`), the two ticks become one more than
67
+ * there are between two patches.
68
+ *
69
+ * When the newest state is older than the moment it draws, it carries each
70
+ * thing on at its last speed for up to `maxExtrapolationTicks`, then holds
71
+ * it. A jump, such as a respawn, is drawn as one: say so with `snap(id)`, or
72
+ * set `snapDistance`.
73
+ *
74
+ * const glide = new BufferedInterpolator(room, ["x", "y"], { snapDistance: 200 });
75
+ * room.on("state", (state) => glide.update(state.units));
76
+ * // in the render loop:
77
+ * const { x, y } = glide.at(id) ?? state.units[id];
78
+ *
79
+ * Against a room older than 0.2, which does not say where its clock is, it
80
+ * times the patches as they arrive instead.
81
+ */
82
+ export class BufferedInterpolator<Field extends string> {
83
+ readonly #source: TickSource;
84
+ readonly #fields: readonly Field[];
85
+ readonly #angles: ReadonlySet<Field>;
86
+ readonly #delayTicks: number | undefined;
87
+ readonly #maxExtrapolation: number | undefined;
88
+ readonly #snapDistance: number;
89
+ #tracks = new Map<string, Snapshot<Field>[]>();
90
+ /** Times the patches as they arrive, for a room that does not say where its clock is. */
91
+ #arrivals = new ServerClock();
92
+ /** How many ticks behind the room's clock a state arrives, smoothed, and how much that varies. */
93
+ #lateness: number | undefined;
94
+ #jitter = 0;
95
+ #newestTick = -Infinity;
96
+ /** The latest moment drawn, and when it was asked for: what is drawn never goes back. */
97
+ #shown: { tick: number; now: number } | undefined;
98
+
99
+ /**
100
+ * @param source where the ticks come from: the `RoomClient`
101
+ * @param fields the numeric fields to smooth, e.g. `["x", "y"]`
102
+ * @param options see `BufferedInterpolatorOptions`
103
+ */
104
+ constructor(source: TickSource, fields: readonly Field[], options: BufferedInterpolatorOptions<Field> = {}) {
105
+ this.#source = source;
106
+ this.#fields = fields;
107
+ this.#angles = new Set(options.angles ?? []);
108
+ this.#delayTicks = options.delayTicks === undefined ? undefined : Math.max(0, options.delayTicks);
109
+ this.#maxExtrapolation = options.maxExtrapolationTicks === undefined ? undefined : Math.max(0, options.maxExtrapolationTicks);
110
+ this.#snapDistance = options.snapDistance ?? Infinity;
111
+ }
112
+
113
+ /** The delay it draws at right now, in ticks behind the room's clock: see the class. */
114
+ get delay(): number {
115
+ return (this.#lateness ?? 0) + (this.#delayTicks ?? 1 + this.#ticksAPatch()) + 2 * this.#jitter;
116
+ }
117
+
118
+ /** How many ticks there are between two patches: 1, unless the room sends less often than it ticks. */
119
+ #ticksAPatch(): number {
120
+ const { tickRate, patchRate } = this.#source;
121
+ return patchRate !== undefined && patchRate > 0 && patchRate < tickRate ? Math.ceil(tickRate / patchRate) : 1;
122
+ }
123
+
124
+ /**
125
+ * Feed the latest values, keyed by id, as of tick `tick`: the source's
126
+ * latest unless given. Ids missing from `targets` are forgotten.
127
+ *
128
+ * @param now when they arrived, from `performance.now()`
129
+ */
130
+ update(targets: Record<string, Record<Field, number>>, tick = this.#source.tick, now = localNow()): void {
131
+ if (tick < this.#newestTick) {
132
+ // The room went back to a save: what was kept is of a timeline that no longer is.
133
+ this.#tracks.clear();
134
+ this.#arrivals.reset();
135
+ this.#lateness = undefined;
136
+ this.#jitter = 0;
137
+ this.#shown = undefined;
138
+ }
139
+ if (tick > this.#newestTick) {
140
+ this.#newestTick = tick;
141
+ this.#measure(tick, now);
142
+ }
143
+ const drawn = this.#shown?.tick ?? -Infinity;
144
+ const tracks = new Map<string, Snapshot<Field>[]>();
145
+ for (const id of Object.keys(targets)) {
146
+ const target = targets[id]!;
147
+ const values = {} as Record<Field, number>;
148
+ for (const field of this.#fields) values[field] = target[field];
149
+ const track = this.#tracks.get(id) ?? [];
150
+ const last = track[track.length - 1];
151
+ if (last?.tick === tick) {
152
+ last.values = values;
153
+ } else {
154
+ track.push({ tick, values, snap: last !== undefined && this.#distance(last.values, values) > this.#snapDistance });
155
+ }
156
+ // What lies behind the moment drawn is no longer needed, apart from the one it starts from.
157
+ let drop = 0;
158
+ while (drop < track.length - 2 && track[drop + 1]!.tick <= drawn) drop += 1;
159
+ drop = Math.max(drop, track.length - MAX_SNAPSHOTS);
160
+ if (drop > 0) track.splice(0, drop);
161
+ tracks.set(id, track);
162
+ }
163
+ this.#tracks = tracks;
164
+ }
165
+
166
+ /**
167
+ * The latest values given for `id` were a jump, such as a respawn: draw
168
+ * them in one step when their tick comes, not as a slide. Call it after
169
+ * the `update` that brought them, for instance when a message says so:
170
+ * messages arrive after the patch of the same tick.
171
+ */
172
+ snap(id: string): void {
173
+ const track = this.#tracks.get(id);
174
+ const last = track?.[track.length - 1];
175
+ if (last && track!.length > 1) last.snap = true;
176
+ }
177
+
178
+ /** The values to draw for `id` right now, or undefined if it is not known. */
179
+ at(id: string, now = localNow()): Record<Field, number> | undefined {
180
+ const track = this.#tracks.get(id);
181
+ if (!track || track.length === 0) return undefined;
182
+ const newest = track[track.length - 1]!;
183
+ const tick = this.#moment(now);
184
+ if (tick === undefined) return { ...newest.values };
185
+
186
+ if (tick >= newest.tick) {
187
+ const before = track[track.length - 2];
188
+ const ahead = Math.min(tick - newest.tick, this.#maxExtrapolation ?? 2 + this.#ticksAPatch());
189
+ if (!before || newest.snap || ahead <= 0) return { ...newest.values };
190
+ // Carried on at the speed it last had, for as long as that is allowed.
191
+ return this.#blend(before.values, newest.values, 1 + ahead / (newest.tick - before.tick));
192
+ }
193
+ let i = track.length - 1;
194
+ while (i > 0 && track[i - 1]!.tick > tick) i -= 1;
195
+ const to = track[i]!;
196
+ const from = track[i - 1];
197
+ // Before the first it knows, it shows the first.
198
+ if (!from) return { ...to.values };
199
+ if (to.snap) return { ...from.values };
200
+ return this.#blend(from.values, to.values, (tick - from.tick) / (to.tick - from.tick));
201
+ }
202
+
203
+ /**
204
+ * The tick it draws at `now`, with its fraction: the moment of the room's
205
+ * time that `at` shows. Send it with a command that depends on what the
206
+ * player was looking at, a shot for one, and the room can judge the
207
+ * command by the state of that tick, which it keeps with `historyTicks`
208
+ * and reads with `stateAt(tick)`.
209
+ *
210
+ * While there is no clock to go by, and when the simulation has stopped,
211
+ * it is the tick of the latest state, since that is what `at` shows then.
212
+ * Undefined before the first `update`.
213
+ */
214
+ drawnTick(now = localNow()): number | undefined {
215
+ if (this.#newestTick === -Infinity) return undefined;
216
+ return this.#moment(now) ?? this.#newestTick;
217
+ }
218
+
219
+ /** Forget everything, e.g. after moving to another room. */
220
+ clear(): void {
221
+ this.#tracks.clear();
222
+ this.#arrivals.reset();
223
+ this.#lateness = undefined;
224
+ this.#jitter = 0;
225
+ this.#newestTick = -Infinity;
226
+ this.#shown = undefined;
227
+ }
228
+
229
+ /** The room's tick at `now`, from its clock if it says where that is, else from when patches arrive. */
230
+ #clockTick(now: number): number | undefined {
231
+ const told = this.#source.serverTick?.(now);
232
+ if (told !== undefined) {
233
+ // A clock that stands still: the simulation has stopped, and the latest state is final.
234
+ if (this.#source.serverTick!(now + 1000) === told) return Infinity;
235
+ return told;
236
+ }
237
+ return this.#arrivals.tick(now);
238
+ }
239
+
240
+ /** A state of `tick` arrived at `now`: how late was it, by the room's clock? */
241
+ #measure(tick: number, now: number): void {
242
+ const rate = this.#source.tickRate;
243
+ if (!(rate > 0)) return;
244
+ if (this.#source.serverTick?.(now) === undefined) this.#arrivals.reading(tick, rate, 0, 0, now);
245
+ const clock = this.#clockTick(now);
246
+ if (clock === undefined || clock === Infinity) return;
247
+ const late = clock - tick;
248
+ if (this.#lateness === undefined) {
249
+ this.#lateness = late;
250
+ return;
251
+ }
252
+ // As TCP smooths its round trip: the mean takes an eighth of each sample, the spread a quarter.
253
+ this.#jitter += (Math.abs(late - this.#lateness) - this.#jitter) / 4;
254
+ this.#lateness += (late - this.#lateness) / 8;
255
+ }
256
+
257
+ /** The tick drawn at `now`, with its fraction. Undefined when there is no clock to go by. */
258
+ #moment(now: number): number | undefined {
259
+ if (!(this.#source.tickRate > 0)) return undefined;
260
+ const clock = this.#clockTick(now);
261
+ if (clock === undefined || clock === Infinity) return undefined;
262
+ let tick = clock - this.delay;
263
+ const shown = this.#shown;
264
+ // A delay that grows would take what is drawn back in time. It waits for the clock instead.
265
+ if (shown && now >= shown.now) tick = Math.max(tick, shown.tick);
266
+ if (!shown || now >= shown.now) this.#shown = { tick, now };
267
+ return tick;
268
+ }
269
+
270
+ #blend(from: Record<Field, number>, to: Record<Field, number>, t: number): Record<Field, number> {
271
+ const shown = {} as Record<Field, number>;
272
+ for (const field of this.#fields) {
273
+ const a = from[field];
274
+ const b = to[field];
275
+ shown[field] = this.#angles.has(field) ? wrap(a + wrap(b - a) * t) : a + (b - a) * t;
276
+ }
277
+ return shown;
278
+ }
279
+
280
+ #distance(a: Record<Field, number>, b: Record<Field, number>): number {
281
+ if (this.#snapDistance === Infinity) return 0;
282
+ let sum = 0;
283
+ for (const field of this.#fields) {
284
+ if (!this.#angles.has(field)) sum += (b[field] - a[field]) ** 2;
285
+ }
286
+ return Math.sqrt(sum);
287
+ }
288
+ }
289
+
290
+ /** An angle in radians, brought into (-π, π]. */
291
+ function wrap(angle: number): number {
292
+ const turned = angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
293
+ return turned === -Math.PI ? Math.PI : turned;
294
+ }