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
package/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
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.3.0
6
+
7
+ - A command is no longer lost, or applied twice, when the connection drops on its way. `RoomClient` names itself when it connects and numbers its commands; the room remembers how far it got with them, in the same write as the state, and says so when the client is back (protocol version 5: `c`, `from` and `refused` in `welcome`). The client settles the commands the room handled and sends the others again, so the promise from `send()` resolves or rejects as if the connection had held, through a deploy or a restart of the room too. A command waits for at most `keepCommandsMs`, ten seconds by default. It costs no rows beyond the saves a room makes anyway, but for one when a page is loaded again while its player holds a seat. Lockstep rooms and the Godot and Unity clients do not take part yet, and a room opts out with `rememberCommands = false`. See [When the connection drops](https://tickflare.gridpaper.dev/guide/client#when-the-connection-drops).
8
+
9
+ - A ticking room can simulate more often than it sends. Set `patchRate` below `tickRate` (60 ticks and 20 patches a second, say) and the room runs every tick but sends each player what changed only that many times a second, in one patch for the ticks in between. What a patch costs, `view()` for every player, the comparison and the bytes, is paid that much less often. A command is acknowledged with the patch that shows it, and messages sent from `onTick` wait for it too; nothing waits when the simulation stops. `RoomClient.patchRate` says how often patches come, `BufferedInterpolator` keeps one patch more of a delay by itself, and an `Interpolator` should glide for `1000 / room.patchRate` ms. The Godot and Unity clients work with such a room but do not read the rate yet. See [Sending less often than you simulate](https://tickflare.gridpaper.dev/guide/state-sync#sending-less-often-than-you-simulate).
10
+ - `parseWith(schema, raw)` checks a command against a schema from any library that implements Standard Schema, such as Zod, Valibot or ArkType: `protected parseCommand(raw: unknown) { return parseWith(Command, raw); }`. The room gets what the schema gives back, and what does not fit is refused with the first thing the schema found wrong and where, as `invalid_command: Expected number (at x)`. It works for `parseInput` in a lockstep room too, and Tickflare depends on none of the libraries. See [Checking commands with a schema](https://tickflare.gridpaper.dev/guide/rooms#checking-commands-with-a-schema).
11
+ - A lockstep desync now says whose simulations differed and where. `desync.players` in the view names the two players whose hashes differed, and `onDesync` gets them, on the server as `onDesync(turn, players)` and in `LockstepClient` as `onDesync(turn, desync)`. With a simulation that has `save`, the two clients then send the room what they had saved at that turn, and the room puts the first eight places where the two differ in `desync.differs`, as a path into what `save` returns and the two values: `units.tank.x`, `"14"` and `"14.5"`. `onDesyncExplained` runs on the server and in every client when it is known. A client with a `hash` of its own takes part with `explainDesyncs: true`. `differences(a, b)`, the comparison itself, is exported for tests of your own. See [Finding a desync](https://tickflare.gridpaper.dev/guide/lockstep#finding-a-desync).
12
+ - A ticking room can keep the state of its last ticks and judge a command by the one its player was looking at, which is what lag compensation needs. Set `historyTicks` (12 at 60 ticks a second is 200 ms) and `stateAt(tick)` returns the state as that tick left it, or `undefined` when the room does not have it. On the client, `BufferedInterpolator.drawnTick()` says which tick is on screen, to send with the command. Keeping the ticks costs no work in a tick, only memory, and `historyTicks` is also as far back as a client can claim to have seen. See [Judging a command by what its player saw](https://tickflare.gridpaper.dev/guide/state-sync#judging-a-command-by-what-its-player-saw).
13
+ - Spectators: connections that watch a room without a seat in it. Set `maxSpectators` on the room and connect with `new RoomClient(url, { spectate: true })`. A spectator is sent the room's `spectatorView()`, kept up to date like a player's view, with who is here and what the room broadcasts; they are not among `players`, no seat hook runs for them, and what they send is refused. `spectatorDelayMs` keeps them that far behind the players, in everything, so that watching is no help to someone who plays. `onSpectate(player)` decides who may watch, and a room with a `view()` of its own takes no spectators until it has a `spectatorView()`. Not for lockstep rooms, and not yet in the Godot and Unity clients. On the wire a spectator asks with `spectate=1` and is answered with a `spectating` frame in place of `welcome`; a gateway of your own should hand such a request to the room under `x-tickflare-spectator`, as `routeToRoom` does. See [Spectators](https://tickflare.gridpaper.dev/guide/spectators).
14
+ - `RoomClient.send()` and `leave()` wait for a connection instead of rejecting with `not_connected` at once. A command sent while the client is connecting, the first time or again, is held, shows in `unconfirmed`, and goes out when the room answers; it rejects with `not_connected` only after `keepCommandsMs` without one. A command that was in flight when the connection dropped rejects with `disconnected` only when the client could not find out what became of it, and no longer at the moment of the drop. Pass `keepCommandsMs: 0` to keep the old behaviour.
15
+
16
+ ## 0.2.0
17
+
18
+ - `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).
19
+ - 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).
20
+
21
+ - 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).
22
+
5
23
  ## 0.1.0
6
24
 
7
25
  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
@@ -59,16 +59,17 @@ The room saves every change before anyone hears about it, rolls back what `rejec
59
59
  ## What's in it
60
60
 
61
61
  - **Three sync modes** on one room kernel: [event mode](docs/guide/rooms.md) for turn-based games, [state sync](docs/guide/state-sync.md) for real-time ones, [lockstep](docs/guide/lockstep.md) for strategy games with many units.
62
- - **Patches, not snapshots**: a player is sent what changed in their own [view](docs/guide/state-and-views.md) of the state, after a move as after a tick.
62
+ - **Patches, not snapshots**: a player is sent what changed in their own [view](docs/guide/state-and-views.md) of the state, after a move as after a tick, and a room can [simulate more often than it sends](docs/guide/state-sync.md#sending-less-often-than-you-simulate).
63
63
  - **[Lockstep snapshots](docs/guide/lockstep.md#snapshots)**: a player who joins or reloads late starts from a simulation the other players' clients saved and agreed on, not from the first turn.
64
64
  - **[Rooms that end](docs/guide/rooms.md#when-a-room-is-over)**: a hook for when the last player is gone, rooms that delete themselves with their storage, and matches that [play on](docs/guide/state-sync.md#playing-on-with-nobody-connected) with nobody connected.
65
+ - **[Spectators](docs/guide/spectators.md)**: connections that watch without a seat, with a view of their own, kept as many seconds behind the players as the room says.
65
66
  - **[Identity](docs/guide/identity.md)** decided once, at the gateway, with signed join tokens.
66
67
  - **[Accounts](docs/guide/accounts.md)** on D1: guests, sign-up, sessions, password recovery, player data, stats and leaderboards.
67
68
  - **[Matchmaking](docs/guide/matchmaking.md)** by skill and region, with parties and teams, which reserves a room near its players, and **[match results](docs/guide/match-results.md)** through a Queue into D1, with replays in R2.
68
69
  - **[Worlds across rooms](docs/guide/worlds.md)**: handover between rooms and seeing across borders.
69
70
  - **[A report of what each room cost](docs/guide/costs.md#checking-what-you-are-billed-for)**, from Cloudflare's own analytics, which marks rooms that stayed awake with nobody in them.
70
71
  - **[Clients for Godot and Unity](docs/guide/engines.md)**, with the browser client's interpolation and prediction, and **[a written-down protocol](docs/reference/protocol.md)** for other engines, with binary patches for those whose WebSocket is not compressed.
71
- - **[A client](docs/guide/client.md)** for browsers and Node that reconnects on its own, and **[prediction](docs/guide/state-sync.md#showing-a-players-own-moves-at-once)**: a player's own move shows on the click and is corrected by the room.
72
+ - **[A client](docs/guide/client.md)** for browsers and Node that reconnects on its own, with [no command lost or applied twice](docs/guide/client.md#when-the-connection-drops) on the way, and **[prediction](docs/guide/state-sync.md#showing-a-players-own-moves-at-once)**: a player's own move shows on the click and is corrected by the room. For shots, the room can [judge a command by the tick its player was looking at](docs/guide/state-sync.md#judging-a-command-by-what-its-player-saw).
72
73
  - **[Measured on Cloudflare](docs/guide/limits.md#the-same-rooms-on-cloudflare)**: what a room holds, such as five hundred players who each see their own part of the world at ten ticks a second, with every run written down, the ones that fell short included.
73
74
 
74
75
  ## Install
@@ -100,6 +101,8 @@ npm run docs:dev # the documentation site on http://localhost:5173
100
101
 
101
102
  [`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
103
 
104
+ 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.
105
+
103
106
  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
107
 
105
108
  ## Licence
@@ -0,0 +1,108 @@
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
+ /** Patches a second, when the room sends less often than it ticks: `RoomClient.patchRate`. */
8
+ readonly patchRate?: number;
9
+ /** The tick the room is on at `now`, by estimate, as `RoomClient.serverTick` gives it. */
10
+ serverTick?(now?: number): number | undefined;
11
+ }
12
+ /** Settings for `BufferedInterpolator`. */
13
+ export interface BufferedInterpolatorOptions<Field extends string> {
14
+ /**
15
+ * How far behind the newest state it expects to have, in ticks, before the
16
+ * margin for jitter is added. By default one tick more than there are
17
+ * between two patches, so that there are always two to draw between: 2
18
+ * for a room that sends after every tick, where a patch can then be a tick
19
+ * late or cover two ticks without anything having to be guessed, and 4
20
+ * for one that ticks 60 times a second and sends 20 times.
21
+ */
22
+ delayTicks?: number;
23
+ /**
24
+ * For how many ticks a thing keeps moving at its last speed when no newer
25
+ * state has arrived for it, before it stops where it got to. By default
26
+ * two ticks more than there are between two patches, which is 3 for a
27
+ * room that sends after every tick; 0 stops it at its last known place.
28
+ */
29
+ maxExtrapolationTicks?: number;
30
+ /**
31
+ * A change between two states in a row farther than this, measured over
32
+ * the fields that are not angles, is a jump: drawn as one, when the time
33
+ * comes, instead of a slide. Off by default. Set it above the farthest
34
+ * anything moves between two patches.
35
+ */
36
+ snapDistance?: number;
37
+ /** Fields that are angles in radians, which go the short way round through ±π. */
38
+ angles?: readonly Field[];
39
+ }
40
+ /**
41
+ * Smooths values that arrive once per tick by drawing them a little in the
42
+ * past, at an even pace, from the ticks they belong to.
43
+ *
44
+ * `Interpolator` glides to each new value as it arrives: it adds almost no
45
+ * delay, but things speed up when two patches arrive together and stop when
46
+ * one is late. This one keeps the last few states of each id, keyed by the
47
+ * room's tick, and draws the moment `delay` ticks behind the tick the room
48
+ * is on (`RoomClient.serverTick()`), blending the states on either side.
49
+ * Motion then keeps the pace of the room, whatever the network does to the
50
+ * patches, at the cost of the delay: two ticks and a margin for the jitter
51
+ * it measures, which it keeps adjusting. Against a room that sends less
52
+ * often than it ticks (`patchRate`), the two ticks become one more than
53
+ * there are between two patches.
54
+ *
55
+ * When the newest state is older than the moment it draws, it carries each
56
+ * thing on at its last speed for up to `maxExtrapolationTicks`, then holds
57
+ * it. A jump, such as a respawn, is drawn as one: say so with `snap(id)`, or
58
+ * set `snapDistance`.
59
+ *
60
+ * const glide = new BufferedInterpolator(room, ["x", "y"], { snapDistance: 200 });
61
+ * room.on("state", (state) => glide.update(state.units));
62
+ * // in the render loop:
63
+ * const { x, y } = glide.at(id) ?? state.units[id];
64
+ *
65
+ * Against a room older than 0.2, which does not say where its clock is, it
66
+ * times the patches as they arrive instead.
67
+ */
68
+ export declare class BufferedInterpolator<Field extends string> {
69
+ #private;
70
+ /**
71
+ * @param source where the ticks come from: the `RoomClient`
72
+ * @param fields the numeric fields to smooth, e.g. `["x", "y"]`
73
+ * @param options see `BufferedInterpolatorOptions`
74
+ */
75
+ constructor(source: TickSource, fields: readonly Field[], options?: BufferedInterpolatorOptions<Field>);
76
+ /** The delay it draws at right now, in ticks behind the room's clock: see the class. */
77
+ get delay(): number;
78
+ /**
79
+ * Feed the latest values, keyed by id, as of tick `tick`: the source's
80
+ * latest unless given. Ids missing from `targets` are forgotten.
81
+ *
82
+ * @param now when they arrived, from `performance.now()`
83
+ */
84
+ update(targets: Record<string, Record<Field, number>>, tick?: number, now?: number): void;
85
+ /**
86
+ * The latest values given for `id` were a jump, such as a respawn: draw
87
+ * them in one step when their tick comes, not as a slide. Call it after
88
+ * the `update` that brought them, for instance when a message says so:
89
+ * messages arrive after the patch of the same tick.
90
+ */
91
+ snap(id: string): void;
92
+ /** The values to draw for `id` right now, or undefined if it is not known. */
93
+ at(id: string, now?: number): Record<Field, number> | undefined;
94
+ /**
95
+ * The tick it draws at `now`, with its fraction: the moment of the room's
96
+ * time that `at` shows. Send it with a command that depends on what the
97
+ * player was looking at, a shot for one, and the room can judge the
98
+ * command by the state of that tick, which it keeps with `historyTicks`
99
+ * and reads with `stateAt(tick)`.
100
+ *
101
+ * While there is no clock to go by, and when the simulation has stopped,
102
+ * it is the tick of the latest state, since that is what `at` shows then.
103
+ * Undefined before the first `update`.
104
+ */
105
+ drawnTick(now?: number): number | undefined;
106
+ /** Forget everything, e.g. after moving to another room. */
107
+ clear(): void;
108
+ }
@@ -0,0 +1,252 @@
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. Against a room that sends less
16
+ * often than it ticks (`patchRate`), the two ticks become one more than
17
+ * there are between two patches.
18
+ *
19
+ * When the newest state is older than the moment it draws, it carries each
20
+ * thing on at its last speed for up to `maxExtrapolationTicks`, then holds
21
+ * it. A jump, such as a respawn, is drawn as one: say so with `snap(id)`, or
22
+ * set `snapDistance`.
23
+ *
24
+ * const glide = new BufferedInterpolator(room, ["x", "y"], { snapDistance: 200 });
25
+ * room.on("state", (state) => glide.update(state.units));
26
+ * // in the render loop:
27
+ * const { x, y } = glide.at(id) ?? state.units[id];
28
+ *
29
+ * Against a room older than 0.2, which does not say where its clock is, it
30
+ * times the patches as they arrive instead.
31
+ */
32
+ export class BufferedInterpolator {
33
+ #source;
34
+ #fields;
35
+ #angles;
36
+ #delayTicks;
37
+ #maxExtrapolation;
38
+ #snapDistance;
39
+ #tracks = new Map();
40
+ /** Times the patches as they arrive, for a room that does not say where its clock is. */
41
+ #arrivals = new ServerClock();
42
+ /** How many ticks behind the room's clock a state arrives, smoothed, and how much that varies. */
43
+ #lateness;
44
+ #jitter = 0;
45
+ #newestTick = -Infinity;
46
+ /** The latest moment drawn, and when it was asked for: what is drawn never goes back. */
47
+ #shown;
48
+ /**
49
+ * @param source where the ticks come from: the `RoomClient`
50
+ * @param fields the numeric fields to smooth, e.g. `["x", "y"]`
51
+ * @param options see `BufferedInterpolatorOptions`
52
+ */
53
+ constructor(source, fields, options = {}) {
54
+ this.#source = source;
55
+ this.#fields = fields;
56
+ this.#angles = new Set(options.angles ?? []);
57
+ this.#delayTicks = options.delayTicks === undefined ? undefined : Math.max(0, options.delayTicks);
58
+ this.#maxExtrapolation = options.maxExtrapolationTicks === undefined ? undefined : Math.max(0, options.maxExtrapolationTicks);
59
+ this.#snapDistance = options.snapDistance ?? Infinity;
60
+ }
61
+ /** The delay it draws at right now, in ticks behind the room's clock: see the class. */
62
+ get delay() {
63
+ return (this.#lateness ?? 0) + (this.#delayTicks ?? 1 + this.#ticksAPatch()) + 2 * this.#jitter;
64
+ }
65
+ /** How many ticks there are between two patches: 1, unless the room sends less often than it ticks. */
66
+ #ticksAPatch() {
67
+ const { tickRate, patchRate } = this.#source;
68
+ return patchRate !== undefined && patchRate > 0 && patchRate < tickRate ? Math.ceil(tickRate / patchRate) : 1;
69
+ }
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, tick = this.#source.tick, now = localNow()) {
77
+ if (tick < this.#newestTick) {
78
+ // The room went back to a save: what was kept is of a timeline that no longer is.
79
+ this.#tracks.clear();
80
+ this.#arrivals.reset();
81
+ this.#lateness = undefined;
82
+ this.#jitter = 0;
83
+ this.#shown = undefined;
84
+ }
85
+ if (tick > this.#newestTick) {
86
+ this.#newestTick = tick;
87
+ this.#measure(tick, now);
88
+ }
89
+ const drawn = this.#shown?.tick ?? -Infinity;
90
+ const tracks = new Map();
91
+ for (const id of Object.keys(targets)) {
92
+ const target = targets[id];
93
+ const values = {};
94
+ for (const field of this.#fields)
95
+ values[field] = target[field];
96
+ const track = this.#tracks.get(id) ?? [];
97
+ const last = track[track.length - 1];
98
+ if (last?.tick === tick) {
99
+ last.values = values;
100
+ }
101
+ else {
102
+ track.push({ tick, values, snap: last !== undefined && this.#distance(last.values, values) > this.#snapDistance });
103
+ }
104
+ // What lies behind the moment drawn is no longer needed, apart from the one it starts from.
105
+ let drop = 0;
106
+ while (drop < track.length - 2 && track[drop + 1].tick <= drawn)
107
+ drop += 1;
108
+ drop = Math.max(drop, track.length - MAX_SNAPSHOTS);
109
+ if (drop > 0)
110
+ track.splice(0, drop);
111
+ tracks.set(id, track);
112
+ }
113
+ this.#tracks = tracks;
114
+ }
115
+ /**
116
+ * The latest values given for `id` were a jump, such as a respawn: draw
117
+ * them in one step when their tick comes, not as a slide. Call it after
118
+ * the `update` that brought them, for instance when a message says so:
119
+ * messages arrive after the patch of the same tick.
120
+ */
121
+ snap(id) {
122
+ const track = this.#tracks.get(id);
123
+ const last = track?.[track.length - 1];
124
+ if (last && track.length > 1)
125
+ last.snap = true;
126
+ }
127
+ /** The values to draw for `id` right now, or undefined if it is not known. */
128
+ at(id, now = localNow()) {
129
+ const track = this.#tracks.get(id);
130
+ if (!track || track.length === 0)
131
+ return undefined;
132
+ const newest = track[track.length - 1];
133
+ const tick = this.#moment(now);
134
+ if (tick === undefined)
135
+ return { ...newest.values };
136
+ if (tick >= newest.tick) {
137
+ const before = track[track.length - 2];
138
+ const ahead = Math.min(tick - newest.tick, this.#maxExtrapolation ?? 2 + this.#ticksAPatch());
139
+ if (!before || newest.snap || ahead <= 0)
140
+ return { ...newest.values };
141
+ // Carried on at the speed it last had, for as long as that is allowed.
142
+ return this.#blend(before.values, newest.values, 1 + ahead / (newest.tick - before.tick));
143
+ }
144
+ let i = track.length - 1;
145
+ while (i > 0 && track[i - 1].tick > tick)
146
+ i -= 1;
147
+ const to = track[i];
148
+ const from = track[i - 1];
149
+ // Before the first it knows, it shows the first.
150
+ if (!from)
151
+ return { ...to.values };
152
+ if (to.snap)
153
+ return { ...from.values };
154
+ return this.#blend(from.values, to.values, (tick - from.tick) / (to.tick - from.tick));
155
+ }
156
+ /**
157
+ * The tick it draws at `now`, with its fraction: the moment of the room's
158
+ * time that `at` shows. Send it with a command that depends on what the
159
+ * player was looking at, a shot for one, and the room can judge the
160
+ * command by the state of that tick, which it keeps with `historyTicks`
161
+ * and reads with `stateAt(tick)`.
162
+ *
163
+ * While there is no clock to go by, and when the simulation has stopped,
164
+ * it is the tick of the latest state, since that is what `at` shows then.
165
+ * Undefined before the first `update`.
166
+ */
167
+ drawnTick(now = localNow()) {
168
+ if (this.#newestTick === -Infinity)
169
+ return undefined;
170
+ return this.#moment(now) ?? this.#newestTick;
171
+ }
172
+ /** Forget everything, e.g. after moving to another room. */
173
+ clear() {
174
+ this.#tracks.clear();
175
+ this.#arrivals.reset();
176
+ this.#lateness = undefined;
177
+ this.#jitter = 0;
178
+ this.#newestTick = -Infinity;
179
+ this.#shown = undefined;
180
+ }
181
+ /** The room's tick at `now`, from its clock if it says where that is, else from when patches arrive. */
182
+ #clockTick(now) {
183
+ const told = this.#source.serverTick?.(now);
184
+ if (told !== undefined) {
185
+ // A clock that stands still: the simulation has stopped, and the latest state is final.
186
+ if (this.#source.serverTick(now + 1000) === told)
187
+ return Infinity;
188
+ return told;
189
+ }
190
+ return this.#arrivals.tick(now);
191
+ }
192
+ /** A state of `tick` arrived at `now`: how late was it, by the room's clock? */
193
+ #measure(tick, now) {
194
+ const rate = this.#source.tickRate;
195
+ if (!(rate > 0))
196
+ return;
197
+ if (this.#source.serverTick?.(now) === undefined)
198
+ this.#arrivals.reading(tick, rate, 0, 0, now);
199
+ const clock = this.#clockTick(now);
200
+ if (clock === undefined || clock === Infinity)
201
+ return;
202
+ const late = clock - tick;
203
+ if (this.#lateness === undefined) {
204
+ this.#lateness = late;
205
+ return;
206
+ }
207
+ // As TCP smooths its round trip: the mean takes an eighth of each sample, the spread a quarter.
208
+ this.#jitter += (Math.abs(late - this.#lateness) - this.#jitter) / 4;
209
+ this.#lateness += (late - this.#lateness) / 8;
210
+ }
211
+ /** The tick drawn at `now`, with its fraction. Undefined when there is no clock to go by. */
212
+ #moment(now) {
213
+ if (!(this.#source.tickRate > 0))
214
+ return undefined;
215
+ const clock = this.#clockTick(now);
216
+ if (clock === undefined || clock === Infinity)
217
+ return undefined;
218
+ let tick = clock - this.delay;
219
+ const shown = this.#shown;
220
+ // A delay that grows would take what is drawn back in time. It waits for the clock instead.
221
+ if (shown && now >= shown.now)
222
+ tick = Math.max(tick, shown.tick);
223
+ if (!shown || now >= shown.now)
224
+ this.#shown = { tick, now };
225
+ return tick;
226
+ }
227
+ #blend(from, to, t) {
228
+ const shown = {};
229
+ for (const field of this.#fields) {
230
+ const a = from[field];
231
+ const b = to[field];
232
+ shown[field] = this.#angles.has(field) ? wrap(a + wrap(b - a) * t) : a + (b - a) * t;
233
+ }
234
+ return shown;
235
+ }
236
+ #distance(a, b) {
237
+ if (this.#snapDistance === Infinity)
238
+ return 0;
239
+ let sum = 0;
240
+ for (const field of this.#fields) {
241
+ if (!this.#angles.has(field))
242
+ sum += (b[field] - a[field]) ** 2;
243
+ }
244
+ return Math.sqrt(sum);
245
+ }
246
+ }
247
+ /** An angle in radians, brought into (-π, π]. */
248
+ function wrap(angle) {
249
+ const turned = angle - 2 * Math.PI * Math.floor((angle + Math.PI) / (2 * Math.PI));
250
+ return turned === -Math.PI ? Math.PI : turned;
251
+ }
252
+ //# 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;AAkDnD,6DAA6D;AAC7D,MAAM,aAAa,GAAG,EAAE,C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CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC;QACvF,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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