tickflare 0.1.0 → 0.2.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  How versions work before 1.0: a new minor version (0.2, 0.3) can change the API in ways that need changes in your code, and each such change is listed here with what to change. A patch version (0.1.1) fixes things and changes nothing you call. The [protocol](https://tickflare.gridpaper.dev/reference/protocol) has a version of its own: the room says which one it speaks, and keeps answering clients of older ones.
4
4
 
5
+ ## 0.2.0
6
+
7
+ - `BufferedInterpolator` draws what moves at the room's own pace: it keeps the last few states of each thing by tick and draws a moment a little behind the room's clock, with a delay that adapts to the jitter it measures. When updates stop it carries things on at their last speed for a few ticks, it draws a jump as one (`snap(id)` or `snapDistance`), and it turns angles the short way round. It has the same `update` and `at` as `Interpolator`, which stays for a player's own predicted moves. See [Drawing at the room's pace](https://tickflare.gridpaper.dev/guide/state-sync#drawing-at-the-room-s-pace).
8
+ - A ticking room keeps to a fixed clock. When it wakes late, because a tick or an event took long or the machine was busy, it runs every tick that has come due since, each with the same `dt`, and sends one patch for them all, so a room that falls behind now and then gets back on time instead of slowing the game down. After a stall of more than `maxCatchUpTicks` ticks (5 by default) it runs that many and lets the rest go. `onTick` can therefore run several times back to back; set `maxCatchUpTicks = 1` to keep the old behaviour. See [Keeping time](https://tickflare.gridpaper.dev/guide/state-sync#keeping-time).
9
+
10
+ - Rooms tell clients their clock: protocol version 4 adds the clock to `welcome` and a `clock` frame, and `RoomClient.serverTick()` estimates the tick the room is on right now, using `RoomClient.rtt`, the smoothed round trip. Clients of version 3 and earlier, including the Godot and Unity clients, are sent nothing new. See [The room's clock](https://tickflare.gridpaper.dev/reference/protocol#the-room-s-clock).
11
+
5
12
  ## 0.1.0
6
13
 
7
14
  The first public release, on npm as `tickflare`, with its documentation at <https://tickflare.gridpaper.dev> and the four examples deployed to play from the [examples page](https://tickflare.gridpaper.dev/guide/examples).
package/README.md CHANGED
@@ -100,6 +100,8 @@ npm run docs:dev # the documentation site on http://localhost:5173
100
100
 
101
101
  [`bench/`](bench) holds a room in which everything moves on every tick and the scripts that load it; the *Measure on Cloudflare* workflow deploys it under a key made for the run, measures, can ask Cloudflare for a CPU profile of a room, and deletes it.
102
102
 
103
+ Releases are automatic: each change that lands on `main` with a [changelog fragment](CONTRIBUTING.md#what-a-pull-request-needs) is released to npm, with its section in the changelog and a GitHub release.
104
+
103
105
  The documentation lives in [`docs/`](docs): guides in Markdown, and an API reference generated from the doc comments in `src/`. Every export needs a doc comment, or the docs build fails. [`docs.yml`](.github/workflows/docs.yml) builds the site on every change and deploys it to Cloudflare from `main`.
104
106
 
105
107
  ## Licence
@@ -0,0 +1,88 @@
1
+ /** What `BufferedInterpolator` reads the ticks from: a `RoomClient` will do. */
2
+ export interface TickSource {
3
+ /** The tick of the latest state: read when `update` is called. */
4
+ readonly tick: number;
5
+ /** Ticks a second; 0 in event mode. */
6
+ readonly tickRate: number;
7
+ /** The tick the room is on at `now`, by estimate, as `RoomClient.serverTick` gives it. */
8
+ serverTick?(now?: number): number | undefined;
9
+ }
10
+ /** Settings for `BufferedInterpolator`. */
11
+ export interface BufferedInterpolatorOptions<Field extends string> {
12
+ /**
13
+ * How far behind the newest state it expects to have, in ticks, before the
14
+ * margin for jitter is added. 2 by default: a patch can be a tick late, or
15
+ * cover two ticks, without anything having to be guessed.
16
+ */
17
+ delayTicks?: number;
18
+ /**
19
+ * For how many ticks a thing keeps moving at its last speed when no newer
20
+ * state has arrived for it, before it stops where it got to. 3 by default;
21
+ * 0 stops it at its last known place.
22
+ */
23
+ maxExtrapolationTicks?: number;
24
+ /**
25
+ * A change between two states in a row farther than this, measured over
26
+ * the fields that are not angles, is a jump: drawn as one, when the time
27
+ * comes, instead of a slide. Off by default. Set it above the farthest
28
+ * anything moves between two patches.
29
+ */
30
+ snapDistance?: number;
31
+ /** Fields that are angles in radians, which go the short way round through ±π. */
32
+ angles?: readonly Field[];
33
+ }
34
+ /**
35
+ * Smooths values that arrive once per tick by drawing them a little in the
36
+ * past, at an even pace, from the ticks they belong to.
37
+ *
38
+ * `Interpolator` glides to each new value as it arrives: it adds almost no
39
+ * delay, but things speed up when two patches arrive together and stop when
40
+ * one is late. This one keeps the last few states of each id, keyed by the
41
+ * room's tick, and draws the moment `delay` ticks behind the tick the room
42
+ * is on (`RoomClient.serverTick()`), blending the states on either side.
43
+ * Motion then keeps the pace of the room, whatever the network does to the
44
+ * patches, at the cost of the delay: two ticks and a margin for the jitter
45
+ * it measures, which it keeps adjusting.
46
+ *
47
+ * When the newest state is older than the moment it draws, it carries each
48
+ * thing on at its last speed for up to `maxExtrapolationTicks`, then holds
49
+ * it. A jump, such as a respawn, is drawn as one: say so with `snap(id)`, or
50
+ * set `snapDistance`.
51
+ *
52
+ * const glide = new BufferedInterpolator(room, ["x", "y"], { snapDistance: 200 });
53
+ * room.on("state", (state) => glide.update(state.units));
54
+ * // in the render loop:
55
+ * const { x, y } = glide.at(id) ?? state.units[id];
56
+ *
57
+ * Against a room older than 0.2, which does not say where its clock is, it
58
+ * times the patches as they arrive instead.
59
+ */
60
+ export declare class BufferedInterpolator<Field extends string> {
61
+ #private;
62
+ /**
63
+ * @param source where the ticks come from: the `RoomClient`
64
+ * @param fields the numeric fields to smooth, e.g. `["x", "y"]`
65
+ * @param options see `BufferedInterpolatorOptions`
66
+ */
67
+ constructor(source: TickSource, fields: readonly Field[], options?: BufferedInterpolatorOptions<Field>);
68
+ /** The delay it draws at right now, in ticks behind the room's clock: see the class. */
69
+ get delay(): number;
70
+ /**
71
+ * Feed the latest values, keyed by id, as of tick `tick`: the source's
72
+ * latest unless given. Ids missing from `targets` are forgotten.
73
+ *
74
+ * @param now when they arrived, from `performance.now()`
75
+ */
76
+ update(targets: Record<string, Record<Field, number>>, tick?: number, now?: number): void;
77
+ /**
78
+ * The latest values given for `id` were a jump, such as a respawn: draw
79
+ * them in one step when their tick comes, not as a slide. Call it after
80
+ * the `update` that brought them, for instance when a message says so:
81
+ * messages arrive after the patch of the same tick.
82
+ */
83
+ snap(id: string): void;
84
+ /** The values to draw for `id` right now, or undefined if it is not known. */
85
+ at(id: string, now?: number): Record<Field, number> | undefined;
86
+ /** Forget everything, e.g. after moving to another room. */
87
+ clear(): void;
88
+ }
@@ -0,0 +1,229 @@
1
+ import { ServerClock, localNow } from "./clock.js";
2
+ /** Snapshots kept per id at the most, whatever the delay. */
3
+ const MAX_SNAPSHOTS = 64;
4
+ /**
5
+ * Smooths values that arrive once per tick by drawing them a little in the
6
+ * past, at an even pace, from the ticks they belong to.
7
+ *
8
+ * `Interpolator` glides to each new value as it arrives: it adds almost no
9
+ * delay, but things speed up when two patches arrive together and stop when
10
+ * one is late. This one keeps the last few states of each id, keyed by the
11
+ * room's tick, and draws the moment `delay` ticks behind the tick the room
12
+ * is on (`RoomClient.serverTick()`), blending the states on either side.
13
+ * Motion then keeps the pace of the room, whatever the network does to the
14
+ * patches, at the cost of the delay: two ticks and a margin for the jitter
15
+ * it measures, which it keeps adjusting.
16
+ *
17
+ * When the newest state is older than the moment it draws, it carries each
18
+ * thing on at its last speed for up to `maxExtrapolationTicks`, then holds
19
+ * it. A jump, such as a respawn, is drawn as one: say so with `snap(id)`, or
20
+ * set `snapDistance`.
21
+ *
22
+ * const glide = new BufferedInterpolator(room, ["x", "y"], { snapDistance: 200 });
23
+ * room.on("state", (state) => glide.update(state.units));
24
+ * // in the render loop:
25
+ * const { x, y } = glide.at(id) ?? state.units[id];
26
+ *
27
+ * Against a room older than 0.2, which does not say where its clock is, it
28
+ * times the patches as they arrive instead.
29
+ */
30
+ export class BufferedInterpolator {
31
+ #source;
32
+ #fields;
33
+ #angles;
34
+ #delayTicks;
35
+ #maxExtrapolation;
36
+ #snapDistance;
37
+ #tracks = new Map();
38
+ /** Times the patches as they arrive, for a room that does not say where its clock is. */
39
+ #arrivals = new ServerClock();
40
+ /** How many ticks behind the room's clock a state arrives, smoothed, and how much that varies. */
41
+ #lateness;
42
+ #jitter = 0;
43
+ #newestTick = -Infinity;
44
+ /** The latest moment drawn, and when it was asked for: what is drawn never goes back. */
45
+ #shown;
46
+ /**
47
+ * @param source where the ticks come from: the `RoomClient`
48
+ * @param fields the numeric fields to smooth, e.g. `["x", "y"]`
49
+ * @param options see `BufferedInterpolatorOptions`
50
+ */
51
+ constructor(source, fields, options = {}) {
52
+ this.#source = source;
53
+ this.#fields = fields;
54
+ this.#angles = new Set(options.angles ?? []);
55
+ this.#delayTicks = Math.max(0, options.delayTicks ?? 2);
56
+ this.#maxExtrapolation = Math.max(0, options.maxExtrapolationTicks ?? 3);
57
+ this.#snapDistance = options.snapDistance ?? Infinity;
58
+ }
59
+ /** The delay it draws at right now, in ticks behind the room's clock: see the class. */
60
+ get delay() {
61
+ return (this.#lateness ?? 0) + this.#delayTicks + 2 * this.#jitter;
62
+ }
63
+ /**
64
+ * Feed the latest values, keyed by id, as of tick `tick`: the source's
65
+ * latest unless given. Ids missing from `targets` are forgotten.
66
+ *
67
+ * @param now when they arrived, from `performance.now()`
68
+ */
69
+ update(targets, tick = this.#source.tick, now = localNow()) {
70
+ if (tick < this.#newestTick) {
71
+ // The room went back to a save: what was kept is of a timeline that no longer is.
72
+ this.#tracks.clear();
73
+ this.#arrivals.reset();
74
+ this.#lateness = undefined;
75
+ this.#jitter = 0;
76
+ this.#shown = undefined;
77
+ }
78
+ if (tick > this.#newestTick) {
79
+ this.#newestTick = tick;
80
+ this.#measure(tick, now);
81
+ }
82
+ const drawn = this.#shown?.tick ?? -Infinity;
83
+ const tracks = new Map();
84
+ for (const id of Object.keys(targets)) {
85
+ const target = targets[id];
86
+ const values = {};
87
+ for (const field of this.#fields)
88
+ values[field] = target[field];
89
+ const track = this.#tracks.get(id) ?? [];
90
+ const last = track[track.length - 1];
91
+ if (last?.tick === tick) {
92
+ last.values = values;
93
+ }
94
+ else {
95
+ track.push({ tick, values, snap: last !== undefined && this.#distance(last.values, values) > this.#snapDistance });
96
+ }
97
+ // What lies behind the moment drawn is no longer needed, apart from the one it starts from.
98
+ let drop = 0;
99
+ while (drop < track.length - 2 && track[drop + 1].tick <= drawn)
100
+ drop += 1;
101
+ drop = Math.max(drop, track.length - MAX_SNAPSHOTS);
102
+ if (drop > 0)
103
+ track.splice(0, drop);
104
+ tracks.set(id, track);
105
+ }
106
+ this.#tracks = tracks;
107
+ }
108
+ /**
109
+ * The latest values given for `id` were a jump, such as a respawn: draw
110
+ * them in one step when their tick comes, not as a slide. Call it after
111
+ * the `update` that brought them, for instance when a message says so:
112
+ * messages arrive after the patch of the same tick.
113
+ */
114
+ snap(id) {
115
+ const track = this.#tracks.get(id);
116
+ const last = track?.[track.length - 1];
117
+ if (last && track.length > 1)
118
+ last.snap = true;
119
+ }
120
+ /** The values to draw for `id` right now, or undefined if it is not known. */
121
+ at(id, now = localNow()) {
122
+ const track = this.#tracks.get(id);
123
+ if (!track || track.length === 0)
124
+ return undefined;
125
+ const newest = track[track.length - 1];
126
+ const tick = this.#drawnTick(now);
127
+ if (tick === undefined)
128
+ return { ...newest.values };
129
+ if (tick >= newest.tick) {
130
+ const before = track[track.length - 2];
131
+ const ahead = Math.min(tick - newest.tick, this.#maxExtrapolation);
132
+ if (!before || newest.snap || ahead <= 0)
133
+ return { ...newest.values };
134
+ // Carried on at the speed it last had, for as long as that is allowed.
135
+ return this.#blend(before.values, newest.values, 1 + ahead / (newest.tick - before.tick));
136
+ }
137
+ let i = track.length - 1;
138
+ while (i > 0 && track[i - 1].tick > tick)
139
+ i -= 1;
140
+ const to = track[i];
141
+ const from = track[i - 1];
142
+ // Before the first it knows, it shows the first.
143
+ if (!from)
144
+ return { ...to.values };
145
+ if (to.snap)
146
+ return { ...from.values };
147
+ return this.#blend(from.values, to.values, (tick - from.tick) / (to.tick - from.tick));
148
+ }
149
+ /** Forget everything, e.g. after moving to another room. */
150
+ clear() {
151
+ this.#tracks.clear();
152
+ this.#arrivals.reset();
153
+ this.#lateness = undefined;
154
+ this.#jitter = 0;
155
+ this.#newestTick = -Infinity;
156
+ this.#shown = undefined;
157
+ }
158
+ /** The room's tick at `now`, from its clock if it says where that is, else from when patches arrive. */
159
+ #clockTick(now) {
160
+ const told = this.#source.serverTick?.(now);
161
+ if (told !== undefined) {
162
+ // A clock that stands still: the simulation has stopped, and the latest state is final.
163
+ if (this.#source.serverTick(now + 1000) === told)
164
+ return Infinity;
165
+ return told;
166
+ }
167
+ return this.#arrivals.tick(now);
168
+ }
169
+ /** A state of `tick` arrived at `now`: how late was it, by the room's clock? */
170
+ #measure(tick, now) {
171
+ const rate = this.#source.tickRate;
172
+ if (!(rate > 0))
173
+ return;
174
+ if (this.#source.serverTick?.(now) === undefined)
175
+ this.#arrivals.reading(tick, rate, 0, 0, now);
176
+ const clock = this.#clockTick(now);
177
+ if (clock === undefined || clock === Infinity)
178
+ return;
179
+ const late = clock - tick;
180
+ if (this.#lateness === undefined) {
181
+ this.#lateness = late;
182
+ return;
183
+ }
184
+ // As TCP smooths its round trip: the mean takes an eighth of each sample, the spread a quarter.
185
+ this.#jitter += (Math.abs(late - this.#lateness) - this.#jitter) / 4;
186
+ this.#lateness += (late - this.#lateness) / 8;
187
+ }
188
+ /** The tick drawn at `now`, with its fraction. Undefined when there is no clock to go by. */
189
+ #drawnTick(now) {
190
+ if (!(this.#source.tickRate > 0))
191
+ return undefined;
192
+ const clock = this.#clockTick(now);
193
+ if (clock === undefined || clock === Infinity)
194
+ return undefined;
195
+ let tick = clock - this.delay;
196
+ const shown = this.#shown;
197
+ // A delay that grows would take what is drawn back in time. It waits for the clock instead.
198
+ if (shown && now >= shown.now)
199
+ tick = Math.max(tick, shown.tick);
200
+ if (!shown || now >= shown.now)
201
+ this.#shown = { tick, now };
202
+ return tick;
203
+ }
204
+ #blend(from, to, t) {
205
+ const shown = {};
206
+ for (const field of this.#fields) {
207
+ const a = from[field];
208
+ const b = to[field];
209
+ shown[field] = this.#angles.has(field) ? wrap(a + wrap(b - a) * t) : a + (b - a) * t;
210
+ }
211
+ return shown;
212
+ }
213
+ #distance(a, b) {
214
+ if (this.#snapDistance === Infinity)
215
+ return 0;
216
+ let sum = 0;
217
+ for (const field of this.#fields) {
218
+ if (!this.#angles.has(field))
219
+ sum += (b[field] - a[field]) ** 2;
220
+ }
221
+ return Math.sqrt(sum);
222
+ }
223
+ }
224
+ /** An angle in radians, brought into (-π, π]. */
225
+ function wrap(angle) {
226
+ const turned = angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
227
+ return turned === -Math.PI ? Math.PI : turned;
228
+ }
229
+ //# sourceMappingURL=buffered.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buffered.js","sourceRoot":"","sources":["../../src/client/buffered.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AA4CnD,6DAA6D;AAC7D,MAAM,aAAa,GAAG,EAAE,CAAC;AAEzB;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,OAAO,oBAAoB;IACtB,OAAO,CAAa;IACpB,OAAO,CAAmB;IAC1B,OAAO,CAAqB;IAC5B,WAAW,CAAS;IACpB,iBAAiB,CAAS;IAC1B,aAAa,CAAS;IAC/B,OAAO,GAAG,IAAI,GAAG,EAA6B,CAAC;IAC/C,yFAAyF;IACzF,SAAS,GAAG,IAAI,WAAW,EAAE,CAAC;IAC9B,kGAAkG;IAClG,SAAS,CAAqB;IAC9B,OAAO,GAAG,CAAC,CAAC;IACZ,WAAW,GAAG,CAAC,QAAQ,CAAC;IACxB,yFAAyF;IACzF,MAAM,CAA4C;IAElD;;;;OAIG;IACH,YAAY,MAAkB,EAAE,MAAwB,EAAE,OAAO,GAAuC,EAAE;QACxG,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,IAAI,EAAE,CAAC,CAAC;QAC7C,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ACvF,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,SAAS,CAAC,CAAwB,EAAE,CAAwB;QAC1D,IAAI,IAAI,CAAC,aAAa,KAAK,QAAQ;YAAE,OAAO,CAAC,CAAC;QAC9C,IAAI,GAAG,GAAG,CAAC,CAAC;QACZ,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;YACjC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC;gBAAE,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC;QAClE,CAAC;QACD,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACxB,CAAC;CACF;AAED,iDAAiD;AACjD,SAAS,IAAI,CAAC,KAAa;IACzB,MAAM,MAAM,GAAG,KAAK,GAAG,CAAC,GAAG,IAAI,CAAC,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;IACnF,OAAO,MAAM,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC;AAChD,CAAC"}
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Keeps an estimate of which tick a room is on, from the clock readings the
3
+ * room sends and the round trip to it.
4
+ *
5
+ * A reading says that tick `tick` fell due `ms` milliseconds before the
6
+ * frame was sent. The frame took about half a round trip to arrive, so on
7
+ * this machine `tick` fell due `ms + rtt / 2` before it arrived, and the room
8
+ * has gone on at `tickRate` ticks a second since. Readings of one epoch are
9
+ * averaged, so that one frame held up on the way moves the estimate only a
10
+ * little; a new epoch replaces the estimate.
11
+ */
12
+ export declare class ServerClock {
13
+ #private;
14
+ /** How much of a new reading's difference from the estimate is taken in: the rest is the estimate's. */
15
+ static readonly SMOOTHING = 0.25;
16
+ /** The smoothed round trip to the room, in milliseconds. Undefined until one has been measured. */
17
+ get rtt(): number | undefined;
18
+ /** A round trip took `ms` milliseconds. Averaged with the earlier ones as TCP does: each new one counts for an eighth. */
19
+ roundTrip(ms: number): void;
20
+ /**
21
+ * The room said where its clock is, in a frame that arrived at `now`
22
+ * (local, from `performance.now()`). With `ms` absent the simulation has
23
+ * stopped at `tick`.
24
+ */
25
+ reading(tick: number, tickRate: number, ms: number | undefined, epoch: number | undefined, now?: number): void;
26
+ /** Forget the clock, keeping the round trip: the connection was lost, or the room told nothing yet. */
27
+ reset(): void;
28
+ /**
29
+ * The tick the room is on at `now` (local, from `performance.now()`), with
30
+ * the fraction of the next that has passed. The tick it stopped at while
31
+ * its simulation is stopped, and undefined when there is nothing to go on.
32
+ */
33
+ tick(now?: number): number | undefined;
34
+ }
35
+ /** A clock that only goes forward, in milliseconds. */
36
+ export declare function localNow(): number;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Keeps an estimate of which tick a room is on, from the clock readings the
3
+ * room sends and the round trip to it.
4
+ *
5
+ * A reading says that tick `tick` fell due `ms` milliseconds before the
6
+ * frame was sent. The frame took about half a round trip to arrive, so on
7
+ * this machine `tick` fell due `ms + rtt / 2` before it arrived, and the room
8
+ * has gone on at `tickRate` ticks a second since. Readings of one epoch are
9
+ * averaged, so that one frame held up on the way moves the estimate only a
10
+ * little; a new epoch replaces the estimate.
11
+ */
12
+ export class ServerClock {
13
+ #tickRate = 0;
14
+ #epoch;
15
+ /** The local time (`performance.now()`) at which `#base` fell due, before half the round trip is added. */
16
+ #baseAt;
17
+ #base = 0;
18
+ /** The tick the simulation stopped at, while it is stopped. */
19
+ #stopped;
20
+ #rtt;
21
+ /** How much of a new reading's difference from the estimate is taken in: the rest is the estimate's. */
22
+ static SMOOTHING = 0.25;
23
+ /** The smoothed round trip to the room, in milliseconds. Undefined until one has been measured. */
24
+ get rtt() {
25
+ return this.#rtt;
26
+ }
27
+ /** A round trip took `ms` milliseconds. Averaged with the earlier ones as TCP does: each new one counts for an eighth. */
28
+ roundTrip(ms) {
29
+ if (!Number.isFinite(ms) || ms < 0)
30
+ return;
31
+ this.#rtt = this.#rtt === undefined ? ms : this.#rtt + (ms - this.#rtt) / 8;
32
+ }
33
+ /**
34
+ * The room said where its clock is, in a frame that arrived at `now`
35
+ * (local, from `performance.now()`). With `ms` absent the simulation has
36
+ * stopped at `tick`.
37
+ */
38
+ reading(tick, tickRate, ms, epoch, now = localNow()) {
39
+ if (ms === undefined || !(tickRate > 0)) {
40
+ this.#stopped = tick;
41
+ this.#baseAt = undefined;
42
+ this.#epoch = undefined;
43
+ return;
44
+ }
45
+ this.#stopped = undefined;
46
+ const at = now - ms;
47
+ if (this.#baseAt === undefined || epoch !== this.#epoch || tickRate !== this.#tickRate) {
48
+ this.#tickRate = tickRate;
49
+ this.#epoch = epoch;
50
+ this.#base = tick;
51
+ this.#baseAt = at;
52
+ return;
53
+ }
54
+ // When `tick` fell due by the estimate so far, then a step towards the new reading.
55
+ const expected = this.#baseAt + ((tick - this.#base) * 1000) / tickRate;
56
+ this.#base = tick;
57
+ this.#baseAt = expected + (at - expected) * ServerClock.SMOOTHING;
58
+ }
59
+ /** Forget the clock, keeping the round trip: the connection was lost, or the room told nothing yet. */
60
+ reset() {
61
+ this.#baseAt = undefined;
62
+ this.#epoch = undefined;
63
+ this.#stopped = undefined;
64
+ }
65
+ /**
66
+ * The tick the room is on at `now` (local, from `performance.now()`), with
67
+ * the fraction of the next that has passed. The tick it stopped at while
68
+ * its simulation is stopped, and undefined when there is nothing to go on.
69
+ */
70
+ tick(now = localNow()) {
71
+ if (this.#stopped !== undefined)
72
+ return this.#stopped;
73
+ if (this.#baseAt === undefined)
74
+ return undefined;
75
+ const since = now - this.#baseAt + (this.#rtt ?? 0) / 2;
76
+ return this.#base + (since * this.#tickRate) / 1000;
77
+ }
78
+ }
79
+ /** A clock that only goes forward, in milliseconds. */
80
+ export function localNow() {
81
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
82
+ }
83
+ //# sourceMappingURL=clock.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clock.js","sourceRoot":"","sources":["../../src/client/clock.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,OAAO,WAAW;IACtB,SAAS,GAAG,CAAC,CAAC;IACd,MAAM,CAAqB;IAC3B,2GAA2G;IAC3G,OAAO,CAAqB;IAC5B,KAAK,GAAG,CAAC,CAAC;IACV,+DAA+D;IAC/D,QAAQ,CAAqB;IAC7B,IAAI,CAAqB;IAEzB,wGAAwG;IACxG,MAAM,CAAU,SAAS,GAAG,IAAI,CAAC;IAEjC,mGAAmG;IACnG,IAAI,GAAG;QACL,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED,0HAA0H;IAC1H,SAAS,CAAC,EAAU;QAClB,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,EAAE,CAAC,IAAI,EAAE,GAAG,CAAC;YAAE,OAAO;QAC3C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,EAAE,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC9E,CAAC;IAED;;;;OAIG;IACH,OAAO,CAAC,IAAY,EAAE,QAAgB,EAAE,EAAsB,EAAE,KAAyB,EAAE,GAAG,GAAG,QAAQ,EAAE;QACzG,IAAI,EAAE,KAAK,SAAS,IAAI,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,EAAE,CAAC;YACxC,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;YACrB,IAAI,CAAC,OAAO,GAAG,SAAS,CAAC;YACzB,IAAI,CAAC,MAAM,GAAG,SAAS,CAAC;YACxB,OAAO;QACT,CAAC;QACD,IAAI,CAAC,QAAQ,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GAAG,IAAI,CAAC,SAAS,CAAC,GAAG,IAAI,CAAC;IACtD,CAAC;CACF;AAED,uDAAuD;AACvD,MAAM,UAAU,QAAQ;IACtB,OAAO,OAAO,WAAW,KAAK,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC;AAC7E,CAAC"}
@@ -5,6 +5,8 @@ export { findMatch, type FindMatchOptions } from "./matchmaking.js";
5
5
  export type { TokenSource } from "./token.js";
6
6
  export { AccountClient, AccountRequestError, type Account, type AccountClientOptions, type Guest, type KeyValueStore, type Leaderboard, type LeaderboardLine, type Profile, } from "./accounts.js";
7
7
  export { Interpolator } from "./interpolate.js";
8
+ export { ServerClock } from "./clock.js";
9
+ export { BufferedInterpolator, type BufferedInterpolatorOptions, type TickSource } from "./buffered.js";
8
10
  export { Predictor, type PredictorOptions } from "./predict.js";
9
11
  export { produce } from "./draft.js";
10
12
  export { decodePatchFrame } from "../binary.js";
@@ -121,6 +123,25 @@ export declare class RoomClient<View = unknown, Command = unknown> {
121
123
  get tick(): number;
122
124
  /** The room's simulation rate in ticks per second; 0 in event mode. */
123
125
  get tickRate(): number;
126
+ /**
127
+ * The tick the room is on right now, by estimate, with the fraction of the
128
+ * next that has passed: for drawing the game in step with the room, or
129
+ * sending a command in time for a tick. Worked out from the clock the room
130
+ * sends (see `ClockFrame`) and the round trip to it, so it carries on
131
+ * between frames, and is usually ahead of `tick`, which is the latest the
132
+ * room has sent. While the room's simulation is stopped, the tick it
133
+ * stopped at. Undefined in event mode, before the room has said where its
134
+ * clock is, and with a room older than 0.2.
135
+ *
136
+ * @param now the moment to estimate it for, from `performance.now()`
137
+ */
138
+ serverTick(now?: number): number | undefined;
139
+ /**
140
+ * The round trip to the room in milliseconds, smoothed over the latest
141
+ * keepalives. Undefined until one has come back. In a ticking room the
142
+ * client measures it every few seconds; otherwise with the keepalive.
143
+ */
144
+ get rtt(): number | undefined;
124
145
  /** This player's id, as the server knows it. Set once connected. */
125
146
  get you(): string | undefined;
126
147
  /** Everyone with a seat in the room, in join order. */
@@ -8,12 +8,15 @@
8
8
  */
9
9
  import { BINARY_PATCHES, decodePatchFrame } from "../binary.js";
10
10
  import { applyPatch } from "../patch.js";
11
+ import { ServerClock, localNow } from "./clock.js";
11
12
  import { roomIn, withFreshToken } from "./token.js";
12
13
  import { CloseCode, PING, PONG, PROTOCOL_VERSION, isFatalCloseCode, } from "../protocol.js";
13
14
  export { CloseCode } from "../protocol.js";
14
15
  export { findMatch } from "./matchmaking.js";
15
16
  export { AccountClient, AccountRequestError, } from "./accounts.js";
16
17
  export { Interpolator } from "./interpolate.js";
18
+ export { ServerClock } from "./clock.js";
19
+ export { BufferedInterpolator } from "./buffered.js";
17
20
  export { Predictor } from "./predict.js";
18
21
  export { produce } from "./draft.js";
19
22
  export { decodePatchFrame } from "../binary.js";
@@ -57,6 +60,10 @@ export class RoomClient {
57
60
  #pingTimer;
58
61
  /** A keepalive was sent and nothing has come back since. */
59
62
  #unanswered = false;
63
+ /** When each `ping` that has not been answered yet was sent, oldest first, by `localNow()`. */
64
+ #pingsAt = [];
65
+ /** Which tick the room is on, from what it says of its clock. */
66
+ #clock = new ServerClock();
60
67
  constructor(url, options = {}) {
61
68
  this.#url = String(url);
62
69
  this.#options = options;
@@ -78,6 +85,29 @@ export class RoomClient {
78
85
  get tickRate() {
79
86
  return this.#tickRate;
80
87
  }
88
+ /**
89
+ * The tick the room is on right now, by estimate, with the fraction of the
90
+ * next that has passed: for drawing the game in step with the room, or
91
+ * sending a command in time for a tick. Worked out from the clock the room
92
+ * sends (see `ClockFrame`) and the round trip to it, so it carries on
93
+ * between frames, and is usually ahead of `tick`, which is the latest the
94
+ * room has sent. While the room's simulation is stopped, the tick it
95
+ * stopped at. Undefined in event mode, before the room has said where its
96
+ * clock is, and with a room older than 0.2.
97
+ *
98
+ * @param now the moment to estimate it for, from `performance.now()`
99
+ */
100
+ serverTick(now) {
101
+ return this.#clock.tick(now);
102
+ }
103
+ /**
104
+ * The round trip to the room in milliseconds, smoothed over the latest
105
+ * keepalives. Undefined until one has come back. In a ticking room the
106
+ * client measures it every few seconds; otherwise with the keepalive.
107
+ */
108
+ get rtt() {
109
+ return this.#clock.rtt;
110
+ }
81
111
  /** This player's id, as the server knows it. Set once connected. */
82
112
  get you() {
83
113
  return this.#you;
@@ -226,8 +256,12 @@ export class RoomClient {
226
256
  return;
227
257
  // Anything the server sends shows the connection is alive.
228
258
  this.#unanswered = false;
229
- if (data === PONG)
259
+ if (data === PONG) {
260
+ const sentAt = this.#pingsAt.shift();
261
+ if (sentAt !== undefined)
262
+ this.#clock.roundTrip(localNow() - sentAt);
230
263
  return;
264
+ }
231
265
  this.#handle(JSON.parse(data));
232
266
  });
233
267
  socket.addEventListener("close", (event) => {
@@ -246,6 +280,8 @@ export class RoomClient {
246
280
  #closed(code, reason) {
247
281
  this.#socket = undefined;
248
282
  this.#stopPing();
283
+ this.#pingsAt = [];
284
+ this.#clock.reset();
249
285
  this.#forget();
250
286
  if (code === CloseCode.Moved && reason && !this.#stopped) {
251
287
  // Handed over to another room: same URL, with that room's id as the last path segment.
@@ -302,7 +338,12 @@ export class RoomClient {
302
338
  this.#players = message.players;
303
339
  this.#tick = message.tick;
304
340
  this.#tickRate = message.tickRate;
341
+ this.#clock.reset();
342
+ if (message.ms !== undefined)
343
+ this.#clock.reading(message.tick, message.tickRate, message.ms, message.epoch);
305
344
  this.#startPing();
345
+ if (message.tickRate > 0)
346
+ this.#measure();
306
347
  this.#setStatus("open");
307
348
  this.#emit("presence", this.#players);
308
349
  this.#setState(message.state, message.seq);
@@ -327,6 +368,11 @@ export class RoomClient {
327
368
  this.#setState(applyPatch(this.#state, message.p), message.seq);
328
369
  this.#resolveUpTo(message.c);
329
370
  break;
371
+ case "clock":
372
+ this.#clock.reading(message.tick, this.#tickRate, message.ms, message.epoch);
373
+ if (message.ms !== undefined)
374
+ this.#measure();
375
+ break;
330
376
  case "presence":
331
377
  this.#players = message.players ?? withPresence(this.#players, message.set, message.gone);
332
378
  this.#emit("presence", this.#players);
@@ -399,9 +445,23 @@ export class RoomClient {
399
445
  return;
400
446
  }
401
447
  this.#unanswered = true;
448
+ this.#pingsAt.push(localNow());
402
449
  socket.send(PING);
403
450
  }, interval);
404
451
  }
452
+ /** Sends a `ping` to time the round trip, unless one is on its way already. Leaves the keepalive's watch alone. */
453
+ #measure() {
454
+ const socket = this.#socket;
455
+ if (socket?.readyState !== 1 || this.#pingsAt.length > 0)
456
+ return;
457
+ this.#pingsAt.push(localNow());
458
+ try {
459
+ socket.send(PING);
460
+ }
461
+ catch {
462
+ this.#pingsAt.pop();
463
+ }
464
+ }
405
465
  #stopPing() {
406
466
  if (this.#pingTimer !== undefined)
407
467
  clearInterval(this.#pingTimer);