@super-line/plugin-multiplayer 0.1.0 → 0.2.1
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 +12 -0
- package/README.md +92 -13
- package/THIRD_PARTY_NOTICES.md +1 -0
- package/dist/chunk-GRDMIVAD.js +127 -0
- package/dist/{chunk-QG5AWEMR.js → chunk-SR5BFY5T.js} +27 -15
- package/dist/client.cjs +105 -45
- package/dist/client.d.cts +4 -2
- package/dist/client.d.ts +4 -2
- package/dist/client.js +71 -43
- package/dist/index.cjs +26 -15
- package/dist/index.d.cts +39 -3
- package/dist/index.d.ts +39 -3
- package/dist/index.js +1 -1
- package/dist/server.cjs +237 -47
- package/dist/server.d.cts +27 -3
- package/dist/server.d.ts +27 -3
- package/dist/server.js +102 -34
- package/package.json +4 -4
- package/dist/chunk-AUQT3TTM.js +0 -19
package/dist/client.cjs
CHANGED
|
@@ -260,7 +260,7 @@ var Predictor = class {
|
|
|
260
260
|
this.#world = world;
|
|
261
261
|
this.#source = source;
|
|
262
262
|
}
|
|
263
|
-
/** How many ticks
|
|
263
|
+
/** How many ticks after it is sent a command first shows: how far ahead of the clock the prediction runs. */
|
|
264
264
|
get lead() {
|
|
265
265
|
return this.#lead;
|
|
266
266
|
}
|
|
@@ -279,6 +279,15 @@ var Predictor = class {
|
|
|
279
279
|
this.#pending.push({ seq, command, sentAt, link: this.#link });
|
|
280
280
|
this.#version++;
|
|
281
281
|
}
|
|
282
|
+
/** The server applied a command to the state of `tick`, so it first shows at the tick after. */
|
|
283
|
+
applied(seq, tick) {
|
|
284
|
+
const p = this.#pending.find((q) => q.seq === seq);
|
|
285
|
+
if (!p) return;
|
|
286
|
+
p.at = tick + 1;
|
|
287
|
+
const { tickRate } = this.#source;
|
|
288
|
+
if (tickRate > 0 && p.link === this.#link) this.#learn(p.at - p.sentAt, tickRate);
|
|
289
|
+
this.#version++;
|
|
290
|
+
}
|
|
282
291
|
/** A command was rejected or its request failed: its effect goes at once. */
|
|
283
292
|
settle(seq) {
|
|
284
293
|
const at = this.#pending.findIndex((p) => p.seq === seq);
|
|
@@ -289,12 +298,7 @@ var Predictor = class {
|
|
|
289
298
|
/** A frame arrived, with the highest seq of this player's the server has handled. Call it after the source moved on. */
|
|
290
299
|
shown(acked) {
|
|
291
300
|
if (acked === void 0) return;
|
|
292
|
-
const
|
|
293
|
-
const kept = this.#pending.filter((p) => {
|
|
294
|
-
if (p.seq > acked) return true;
|
|
295
|
-
if (tickRate > 0 && p.link === this.#link) this.#learn(tick - p.sentAt, tickRate);
|
|
296
|
-
return false;
|
|
297
|
-
});
|
|
301
|
+
const kept = this.#pending.filter((p) => p.seq > acked);
|
|
298
302
|
if (kept.length === this.#pending.length) return;
|
|
299
303
|
this.#pending = kept;
|
|
300
304
|
this.#version++;
|
|
@@ -334,7 +338,7 @@ var Predictor = class {
|
|
|
334
338
|
let next = 0;
|
|
335
339
|
const base_ = { now: Date.now(), players: [seat], predicting: true, send: noop, broadcast: noop };
|
|
336
340
|
const applyDue = (before, at) => {
|
|
337
|
-
while (next < pending.length && pending[next].sentAt + this.#lead <= before) {
|
|
341
|
+
while (next < pending.length && (pending[next].at ?? pending[next].sentAt + this.#lead) <= before) {
|
|
338
342
|
const copy = structuredClone(state);
|
|
339
343
|
try {
|
|
340
344
|
world.onCommand(copy, pending[next].command, { ...base_, tick: at, player: seat, profile: void 0 });
|
|
@@ -359,13 +363,46 @@ var Predictor = class {
|
|
|
359
363
|
}
|
|
360
364
|
#learn(ticks, tickRate) {
|
|
361
365
|
if (!Number.isFinite(ticks)) return;
|
|
362
|
-
this.#leads.push(Math.max(
|
|
366
|
+
this.#leads.push(Math.max(-2 * tickRate, Math.min(ticks, 2 * tickRate)));
|
|
363
367
|
if (this.#leads.length > LEADS_KEPT) this.#leads.shift();
|
|
364
368
|
const sorted = [...this.#leads].sort((a, b) => a - b);
|
|
365
369
|
this.#lead = sorted[Math.floor(sorted.length / 2)];
|
|
366
370
|
}
|
|
367
371
|
};
|
|
368
372
|
|
|
373
|
+
// src/patch.ts
|
|
374
|
+
function applyPatch(base, patch) {
|
|
375
|
+
const out = isPlainObject(base) ? { ...base } : {};
|
|
376
|
+
for (const key of Object.keys(patch)) {
|
|
377
|
+
if (key === "__proto__") continue;
|
|
378
|
+
const change = patch[key];
|
|
379
|
+
if (change === 0) delete out[key];
|
|
380
|
+
else if (Array.isArray(change)) out[key] = change.length === 2 ? applyArrayPatch(own(out, key), change) : change[0];
|
|
381
|
+
else if (change) out[key] = applyPatch(own(out, key), change);
|
|
382
|
+
}
|
|
383
|
+
return out;
|
|
384
|
+
}
|
|
385
|
+
var INDEX = /^(0|[1-9][0-9]*)$/;
|
|
386
|
+
function applyArrayPatch(base, [changes, length]) {
|
|
387
|
+
const out = Array.isArray(base) ? base.slice(0, length) : [];
|
|
388
|
+
for (const key of Object.keys(changes)) {
|
|
389
|
+
const index = Number(key);
|
|
390
|
+
if (!INDEX.test(key) || index >= length) continue;
|
|
391
|
+
const change = changes[key];
|
|
392
|
+
if (Array.isArray(change)) out[index] = change.length === 2 ? applyArrayPatch(out[index], change) : change[0];
|
|
393
|
+
else out[index] = applyPatch(out[index], change);
|
|
394
|
+
}
|
|
395
|
+
for (let index = out.length; index < length; index++) out[index] = null;
|
|
396
|
+
for (let index = 0; index < length; index++) if (!(index in out)) out[index] = null;
|
|
397
|
+
return out;
|
|
398
|
+
}
|
|
399
|
+
function own(object, key) {
|
|
400
|
+
return Object.prototype.hasOwnProperty.call(object, key) ? object[key] : void 0;
|
|
401
|
+
}
|
|
402
|
+
function isPlainObject(value) {
|
|
403
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
404
|
+
}
|
|
405
|
+
|
|
369
406
|
// src/client.ts
|
|
370
407
|
var log = (0, import_logtape.getLogger)(["super-line", "plugin-multiplayer", "client"]);
|
|
371
408
|
var distance = (a, b) => {
|
|
@@ -391,7 +428,7 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
391
428
|
const joining = /* @__PURE__ */ new Map();
|
|
392
429
|
let nextSeq = 0;
|
|
393
430
|
let detached = false;
|
|
394
|
-
const open = (id, first
|
|
431
|
+
const open = (id, first) => {
|
|
395
432
|
const clock = new ServerClock();
|
|
396
433
|
const listeners = /* @__PURE__ */ new Map();
|
|
397
434
|
let joined = first;
|
|
@@ -406,7 +443,9 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
406
443
|
let correction;
|
|
407
444
|
let correctFrom;
|
|
408
445
|
let frameAt = localNow();
|
|
446
|
+
let wire = first.frame;
|
|
409
447
|
let sized;
|
|
448
|
+
let syncing = 0;
|
|
410
449
|
let frameBytes = 0;
|
|
411
450
|
const rate = { since: frameAt, frames: 0, perSecond: 0 };
|
|
412
451
|
const emit = (type, event) => {
|
|
@@ -418,11 +457,11 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
418
457
|
}
|
|
419
458
|
}
|
|
420
459
|
};
|
|
421
|
-
const adopt = (j
|
|
460
|
+
const adopt = (j) => {
|
|
422
461
|
const now = localNow();
|
|
423
462
|
joined = j;
|
|
424
|
-
latest = j.frame;
|
|
425
|
-
|
|
463
|
+
latest = wire = j.frame;
|
|
464
|
+
nextSeq = Math.max(nextSeq, j.frame.acks[j.seat] ?? 0);
|
|
426
465
|
clock.reading(j.frame.tick, j.tickRate, j.frame.ms, j.frame.epoch, now);
|
|
427
466
|
buffer.update(j.frame.state, j.frame.tick, now);
|
|
428
467
|
};
|
|
@@ -434,8 +473,10 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
434
473
|
count.sent++;
|
|
435
474
|
return dyn.mpCommand({ world: id, seq, command }).then(
|
|
436
475
|
(result) => {
|
|
437
|
-
if (result.applied)
|
|
438
|
-
|
|
476
|
+
if (result.applied) {
|
|
477
|
+
count.applied++;
|
|
478
|
+
predictor.applied(seq, result.tick);
|
|
479
|
+
} else {
|
|
439
480
|
count.rejected++;
|
|
440
481
|
predictor.settle(seq);
|
|
441
482
|
emit("rejected", { seq, code: result.code, ...result.reason !== void 0 ? { reason: result.reason } : {} });
|
|
@@ -448,10 +489,14 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
448
489
|
}
|
|
449
490
|
);
|
|
450
491
|
};
|
|
492
|
+
const sendTick = (now) => {
|
|
493
|
+
const t = clock.tick(now);
|
|
494
|
+
return t === void 0 || !(joined.tickRate > 0) ? t : t + 0.5;
|
|
495
|
+
};
|
|
451
496
|
const untilNextTick = () => {
|
|
452
497
|
const msPerTick = 1e3 / joined.tickRate;
|
|
453
|
-
const t =
|
|
454
|
-
return t === void 0 ? msPerTick : (Math.floor(t) + 1 - t) * msPerTick;
|
|
498
|
+
const t = sendTick();
|
|
499
|
+
return t === void 0 ? msPerTick : Math.ceil((Math.floor(t) + 1 - t) * msPerTick);
|
|
455
500
|
};
|
|
456
501
|
const flush = () => {
|
|
457
502
|
flushTimer = void 0;
|
|
@@ -507,20 +552,20 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
507
552
|
if (entityId !== joined.seat || !game.lerp || !(joined.tickRate > 0)) return buffer.at(entityId);
|
|
508
553
|
const now = localNow();
|
|
509
554
|
const state = predictor.predicted(now);
|
|
510
|
-
const
|
|
511
|
-
if (
|
|
555
|
+
const own2 = game.entity?.(state, entityId);
|
|
556
|
+
if (own2 === void 0) return void 0;
|
|
512
557
|
if (state !== glidedFrom) {
|
|
513
558
|
glidedFrom = state;
|
|
514
|
-
glide.to(
|
|
559
|
+
glide.to(own2, now);
|
|
515
560
|
}
|
|
516
561
|
return glide.at(now);
|
|
517
562
|
},
|
|
518
563
|
serverTick: (now) => clock.tick(now),
|
|
519
564
|
stats() {
|
|
520
565
|
const now = localNow();
|
|
521
|
-
if (sized !==
|
|
522
|
-
sized =
|
|
523
|
-
frameBytes = encodedBytes(JSON.stringify({ t: "evt", e: "mp.state", d:
|
|
566
|
+
if (sized !== wire) {
|
|
567
|
+
sized = wire;
|
|
568
|
+
frameBytes = encodedBytes(JSON.stringify({ t: "evt", e: "mp.state", d: wire }));
|
|
524
569
|
}
|
|
525
570
|
if (correctFrom !== void 0) {
|
|
526
571
|
const after = predictor.predicted(now);
|
|
@@ -577,11 +622,36 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
577
622
|
});
|
|
578
623
|
}
|
|
579
624
|
};
|
|
625
|
+
const sync = () => {
|
|
626
|
+
syncing++;
|
|
627
|
+
dyn.mpJoin({ world: id }).then(
|
|
628
|
+
(j) => {
|
|
629
|
+
syncing--;
|
|
630
|
+
if (closed) return;
|
|
631
|
+
adopt(j);
|
|
632
|
+
emit("frame", latest);
|
|
633
|
+
},
|
|
634
|
+
(error) => {
|
|
635
|
+
syncing--;
|
|
636
|
+
if (failedWith(error, "DISCONNECTED")) return;
|
|
637
|
+
log.warn("re-joining world {world} failed: {error}", { world: id, error });
|
|
638
|
+
handle.close("disconnected");
|
|
639
|
+
}
|
|
640
|
+
);
|
|
641
|
+
};
|
|
580
642
|
const handle = {
|
|
581
643
|
world,
|
|
582
644
|
emit,
|
|
583
|
-
frame(
|
|
645
|
+
frame(received) {
|
|
584
646
|
if (closed) return;
|
|
647
|
+
let f;
|
|
648
|
+
if ("patch" in received) {
|
|
649
|
+
if (syncing || received.n <= (latest.n ?? -1)) return;
|
|
650
|
+
if (received.n !== latest.n + 1) return sync();
|
|
651
|
+
const { patch, ...rest } = received;
|
|
652
|
+
f = { ...rest, state: applyPatch(latest.state, patch) };
|
|
653
|
+
} else f = received;
|
|
654
|
+
wire = received;
|
|
585
655
|
const now = localNow();
|
|
586
656
|
const made = predictor.made;
|
|
587
657
|
correctFrom = game.entity && joined.tickRate > 0 && made && made.base === latest.state ? made.state : void 0;
|
|
@@ -602,21 +672,9 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
602
672
|
if (closed) return;
|
|
603
673
|
clock.reset();
|
|
604
674
|
predictor.reconnected();
|
|
605
|
-
|
|
606
|
-
dyn.mpJoin({ world: id }).then(
|
|
607
|
-
(j) => {
|
|
608
|
-
if (closed) return;
|
|
609
|
-
adopt(j, sent);
|
|
610
|
-
emit("frame", latest);
|
|
611
|
-
},
|
|
612
|
-
(error) => {
|
|
613
|
-
if (failedWith(error, "DISCONNECTED")) return;
|
|
614
|
-
log.warn("re-joining world {world} failed: {error}", { world: id, error });
|
|
615
|
-
handle.close("disconnected");
|
|
616
|
-
}
|
|
617
|
-
);
|
|
675
|
+
sync();
|
|
618
676
|
},
|
|
619
|
-
close(reason) {
|
|
677
|
+
close(reason, detail) {
|
|
620
678
|
if (closed) return;
|
|
621
679
|
closed = reason;
|
|
622
680
|
handles.delete(id);
|
|
@@ -629,15 +687,15 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
629
687
|
predictor.clear();
|
|
630
688
|
buffer.clear();
|
|
631
689
|
glide.clear();
|
|
632
|
-
emit("closed", { reason });
|
|
690
|
+
emit("closed", detail === void 0 ? { reason } : { reason, detail });
|
|
633
691
|
}
|
|
634
692
|
};
|
|
635
|
-
const predictor = new Predictor(game, world);
|
|
693
|
+
const predictor = new Predictor(game, Object.create(world, { serverTick: { value: sendTick } }));
|
|
636
694
|
const buffer = new BufferedInterpolator(game, world);
|
|
637
695
|
const glide = new Glide((a, b, t) => game.lerp ? game.lerp(a, b, t) : b, 1e3 / (first.tickRate || 1));
|
|
638
696
|
let glidedFrom;
|
|
639
|
-
adopt(first
|
|
640
|
-
if (first.tickRate > 0)
|
|
697
|
+
adopt(first);
|
|
698
|
+
if (first.tickRate > 0) ping();
|
|
641
699
|
return handle;
|
|
642
700
|
};
|
|
643
701
|
const offs = [
|
|
@@ -647,7 +705,10 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
647
705
|
"mp.seat",
|
|
648
706
|
(e) => handles.get(e.world)?.emit("seat", { player: e.player, change: e.change })
|
|
649
707
|
),
|
|
650
|
-
dyn.on(
|
|
708
|
+
dyn.on(
|
|
709
|
+
"mp.closed",
|
|
710
|
+
(e) => handles.get(e.world)?.close(e.reason, e.detail)
|
|
711
|
+
),
|
|
651
712
|
dyn.onReconnect(() => {
|
|
652
713
|
for (const h of handles.values()) h.rejoin();
|
|
653
714
|
})
|
|
@@ -659,14 +720,13 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
659
720
|
if (held) return Promise.resolve(held.world);
|
|
660
721
|
const inFlight = joining.get(world);
|
|
661
722
|
if (inFlight) return inFlight;
|
|
662
|
-
const sent = localNow();
|
|
663
723
|
const p = dyn.mpJoin({ world }).then((j) => {
|
|
664
724
|
if (detached) {
|
|
665
725
|
void dyn.mpLeave({ world }).catch(() => {
|
|
666
726
|
});
|
|
667
727
|
throw new import_core.SuperLineError("DISCONNECTED", "Multiplayer client closed");
|
|
668
728
|
}
|
|
669
|
-
const h = open(world, j
|
|
729
|
+
const h = open(world, j);
|
|
670
730
|
handles.set(world, h);
|
|
671
731
|
return h.world;
|
|
672
732
|
}).finally(() => joining.delete(world));
|
package/dist/client.d.cts
CHANGED
|
@@ -16,13 +16,15 @@ interface WorldEvents<W extends AnyWorld> {
|
|
|
16
16
|
code: string;
|
|
17
17
|
reason?: string;
|
|
18
18
|
};
|
|
19
|
+
/** `detail` is the server's reason for a `removed` seat. */
|
|
19
20
|
closed: {
|
|
20
21
|
reason: WorldCloseReason;
|
|
22
|
+
detail?: string;
|
|
21
23
|
};
|
|
22
24
|
}
|
|
23
25
|
/** What a world handle measures, read with `world.stats()`. Durations are local milliseconds. */
|
|
24
26
|
interface WorldStats {
|
|
25
|
-
/** Smoothed round trip of the
|
|
27
|
+
/** Smoothed round trip of the clock requests, ms. Undefined until one has come back, and in a world with no tick. */
|
|
26
28
|
rttMs: number | undefined;
|
|
27
29
|
/** How far clock readings land from the client's estimate of the server clock, smoothed, ms. Lower is steadier. */
|
|
28
30
|
clockErrorMs: number | undefined;
|
|
@@ -34,7 +36,7 @@ interface WorldStats {
|
|
|
34
36
|
latenessMs: number | undefined;
|
|
35
37
|
/** How much that lateness varies, smoothed, ms. */
|
|
36
38
|
jitterMs: number;
|
|
37
|
-
/** How many ticks ahead of the
|
|
39
|
+
/** How many ticks after it is sent a command first shows: how far ahead of the server's clock the prediction runs. */
|
|
38
40
|
predictionLeadTicks: number;
|
|
39
41
|
/** State frames received per second, over about the last second. */
|
|
40
42
|
framesPerSecond: number;
|
package/dist/client.d.ts
CHANGED
|
@@ -16,13 +16,15 @@ interface WorldEvents<W extends AnyWorld> {
|
|
|
16
16
|
code: string;
|
|
17
17
|
reason?: string;
|
|
18
18
|
};
|
|
19
|
+
/** `detail` is the server's reason for a `removed` seat. */
|
|
19
20
|
closed: {
|
|
20
21
|
reason: WorldCloseReason;
|
|
22
|
+
detail?: string;
|
|
21
23
|
};
|
|
22
24
|
}
|
|
23
25
|
/** What a world handle measures, read with `world.stats()`. Durations are local milliseconds. */
|
|
24
26
|
interface WorldStats {
|
|
25
|
-
/** Smoothed round trip of the
|
|
27
|
+
/** Smoothed round trip of the clock requests, ms. Undefined until one has come back, and in a world with no tick. */
|
|
26
28
|
rttMs: number | undefined;
|
|
27
29
|
/** How far clock readings land from the client's estimate of the server clock, smoothed, ms. Lower is steadier. */
|
|
28
30
|
clockErrorMs: number | undefined;
|
|
@@ -34,7 +36,7 @@ interface WorldStats {
|
|
|
34
36
|
latenessMs: number | undefined;
|
|
35
37
|
/** How much that lateness varies, smoothed, ms. */
|
|
36
38
|
jitterMs: number;
|
|
37
|
-
/** How many ticks ahead of the
|
|
39
|
+
/** How many ticks after it is sent a command first shows: how far ahead of the server's clock the prediction runs. */
|
|
38
40
|
predictionLeadTicks: number;
|
|
39
41
|
/** State frames received per second, over about the last second. */
|
|
40
42
|
framesPerSecond: number;
|
package/dist/client.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
|
+
applyPatch,
|
|
2
3
|
encodedBytes
|
|
3
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-GRDMIVAD.js";
|
|
4
5
|
|
|
5
6
|
// src/client.ts
|
|
6
7
|
import { getLogger } from "@logtape/logtape";
|
|
@@ -224,7 +225,7 @@ var Predictor = class {
|
|
|
224
225
|
this.#world = world;
|
|
225
226
|
this.#source = source;
|
|
226
227
|
}
|
|
227
|
-
/** How many ticks
|
|
228
|
+
/** How many ticks after it is sent a command first shows: how far ahead of the clock the prediction runs. */
|
|
228
229
|
get lead() {
|
|
229
230
|
return this.#lead;
|
|
230
231
|
}
|
|
@@ -243,6 +244,15 @@ var Predictor = class {
|
|
|
243
244
|
this.#pending.push({ seq, command, sentAt, link: this.#link });
|
|
244
245
|
this.#version++;
|
|
245
246
|
}
|
|
247
|
+
/** The server applied a command to the state of `tick`, so it first shows at the tick after. */
|
|
248
|
+
applied(seq, tick) {
|
|
249
|
+
const p = this.#pending.find((q) => q.seq === seq);
|
|
250
|
+
if (!p) return;
|
|
251
|
+
p.at = tick + 1;
|
|
252
|
+
const { tickRate } = this.#source;
|
|
253
|
+
if (tickRate > 0 && p.link === this.#link) this.#learn(p.at - p.sentAt, tickRate);
|
|
254
|
+
this.#version++;
|
|
255
|
+
}
|
|
246
256
|
/** A command was rejected or its request failed: its effect goes at once. */
|
|
247
257
|
settle(seq) {
|
|
248
258
|
const at = this.#pending.findIndex((p) => p.seq === seq);
|
|
@@ -253,12 +263,7 @@ var Predictor = class {
|
|
|
253
263
|
/** A frame arrived, with the highest seq of this player's the server has handled. Call it after the source moved on. */
|
|
254
264
|
shown(acked) {
|
|
255
265
|
if (acked === void 0) return;
|
|
256
|
-
const
|
|
257
|
-
const kept = this.#pending.filter((p) => {
|
|
258
|
-
if (p.seq > acked) return true;
|
|
259
|
-
if (tickRate > 0 && p.link === this.#link) this.#learn(tick - p.sentAt, tickRate);
|
|
260
|
-
return false;
|
|
261
|
-
});
|
|
266
|
+
const kept = this.#pending.filter((p) => p.seq > acked);
|
|
262
267
|
if (kept.length === this.#pending.length) return;
|
|
263
268
|
this.#pending = kept;
|
|
264
269
|
this.#version++;
|
|
@@ -298,7 +303,7 @@ var Predictor = class {
|
|
|
298
303
|
let next = 0;
|
|
299
304
|
const base_ = { now: Date.now(), players: [seat], predicting: true, send: noop, broadcast: noop };
|
|
300
305
|
const applyDue = (before, at) => {
|
|
301
|
-
while (next < pending.length && pending[next].sentAt + this.#lead <= before) {
|
|
306
|
+
while (next < pending.length && (pending[next].at ?? pending[next].sentAt + this.#lead) <= before) {
|
|
302
307
|
const copy = structuredClone(state);
|
|
303
308
|
try {
|
|
304
309
|
world.onCommand(copy, pending[next].command, { ...base_, tick: at, player: seat, profile: void 0 });
|
|
@@ -323,7 +328,7 @@ var Predictor = class {
|
|
|
323
328
|
}
|
|
324
329
|
#learn(ticks, tickRate) {
|
|
325
330
|
if (!Number.isFinite(ticks)) return;
|
|
326
|
-
this.#leads.push(Math.max(
|
|
331
|
+
this.#leads.push(Math.max(-2 * tickRate, Math.min(ticks, 2 * tickRate)));
|
|
327
332
|
if (this.#leads.length > LEADS_KEPT) this.#leads.shift();
|
|
328
333
|
const sorted = [...this.#leads].sort((a, b) => a - b);
|
|
329
334
|
this.#lead = sorted[Math.floor(sorted.length / 2)];
|
|
@@ -355,7 +360,7 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
355
360
|
const joining = /* @__PURE__ */ new Map();
|
|
356
361
|
let nextSeq = 0;
|
|
357
362
|
let detached = false;
|
|
358
|
-
const open = (id, first
|
|
363
|
+
const open = (id, first) => {
|
|
359
364
|
const clock = new ServerClock();
|
|
360
365
|
const listeners = /* @__PURE__ */ new Map();
|
|
361
366
|
let joined = first;
|
|
@@ -370,7 +375,9 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
370
375
|
let correction;
|
|
371
376
|
let correctFrom;
|
|
372
377
|
let frameAt = localNow();
|
|
378
|
+
let wire = first.frame;
|
|
373
379
|
let sized;
|
|
380
|
+
let syncing = 0;
|
|
374
381
|
let frameBytes = 0;
|
|
375
382
|
const rate = { since: frameAt, frames: 0, perSecond: 0 };
|
|
376
383
|
const emit = (type, event) => {
|
|
@@ -382,11 +389,11 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
382
389
|
}
|
|
383
390
|
}
|
|
384
391
|
};
|
|
385
|
-
const adopt = (j
|
|
392
|
+
const adopt = (j) => {
|
|
386
393
|
const now = localNow();
|
|
387
394
|
joined = j;
|
|
388
|
-
latest = j.frame;
|
|
389
|
-
|
|
395
|
+
latest = wire = j.frame;
|
|
396
|
+
nextSeq = Math.max(nextSeq, j.frame.acks[j.seat] ?? 0);
|
|
390
397
|
clock.reading(j.frame.tick, j.tickRate, j.frame.ms, j.frame.epoch, now);
|
|
391
398
|
buffer.update(j.frame.state, j.frame.tick, now);
|
|
392
399
|
};
|
|
@@ -398,8 +405,10 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
398
405
|
count.sent++;
|
|
399
406
|
return dyn.mpCommand({ world: id, seq, command }).then(
|
|
400
407
|
(result) => {
|
|
401
|
-
if (result.applied)
|
|
402
|
-
|
|
408
|
+
if (result.applied) {
|
|
409
|
+
count.applied++;
|
|
410
|
+
predictor.applied(seq, result.tick);
|
|
411
|
+
} else {
|
|
403
412
|
count.rejected++;
|
|
404
413
|
predictor.settle(seq);
|
|
405
414
|
emit("rejected", { seq, code: result.code, ...result.reason !== void 0 ? { reason: result.reason } : {} });
|
|
@@ -412,10 +421,14 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
412
421
|
}
|
|
413
422
|
);
|
|
414
423
|
};
|
|
424
|
+
const sendTick = (now) => {
|
|
425
|
+
const t = clock.tick(now);
|
|
426
|
+
return t === void 0 || !(joined.tickRate > 0) ? t : t + 0.5;
|
|
427
|
+
};
|
|
415
428
|
const untilNextTick = () => {
|
|
416
429
|
const msPerTick = 1e3 / joined.tickRate;
|
|
417
|
-
const t =
|
|
418
|
-
return t === void 0 ? msPerTick : (Math.floor(t) + 1 - t) * msPerTick;
|
|
430
|
+
const t = sendTick();
|
|
431
|
+
return t === void 0 ? msPerTick : Math.ceil((Math.floor(t) + 1 - t) * msPerTick);
|
|
419
432
|
};
|
|
420
433
|
const flush = () => {
|
|
421
434
|
flushTimer = void 0;
|
|
@@ -482,9 +495,9 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
482
495
|
serverTick: (now) => clock.tick(now),
|
|
483
496
|
stats() {
|
|
484
497
|
const now = localNow();
|
|
485
|
-
if (sized !==
|
|
486
|
-
sized =
|
|
487
|
-
frameBytes = encodedBytes(JSON.stringify({ t: "evt", e: "mp.state", d:
|
|
498
|
+
if (sized !== wire) {
|
|
499
|
+
sized = wire;
|
|
500
|
+
frameBytes = encodedBytes(JSON.stringify({ t: "evt", e: "mp.state", d: wire }));
|
|
488
501
|
}
|
|
489
502
|
if (correctFrom !== void 0) {
|
|
490
503
|
const after = predictor.predicted(now);
|
|
@@ -541,11 +554,36 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
541
554
|
});
|
|
542
555
|
}
|
|
543
556
|
};
|
|
557
|
+
const sync = () => {
|
|
558
|
+
syncing++;
|
|
559
|
+
dyn.mpJoin({ world: id }).then(
|
|
560
|
+
(j) => {
|
|
561
|
+
syncing--;
|
|
562
|
+
if (closed) return;
|
|
563
|
+
adopt(j);
|
|
564
|
+
emit("frame", latest);
|
|
565
|
+
},
|
|
566
|
+
(error) => {
|
|
567
|
+
syncing--;
|
|
568
|
+
if (failedWith(error, "DISCONNECTED")) return;
|
|
569
|
+
log.warn("re-joining world {world} failed: {error}", { world: id, error });
|
|
570
|
+
handle.close("disconnected");
|
|
571
|
+
}
|
|
572
|
+
);
|
|
573
|
+
};
|
|
544
574
|
const handle = {
|
|
545
575
|
world,
|
|
546
576
|
emit,
|
|
547
|
-
frame(
|
|
577
|
+
frame(received) {
|
|
548
578
|
if (closed) return;
|
|
579
|
+
let f;
|
|
580
|
+
if ("patch" in received) {
|
|
581
|
+
if (syncing || received.n <= (latest.n ?? -1)) return;
|
|
582
|
+
if (received.n !== latest.n + 1) return sync();
|
|
583
|
+
const { patch, ...rest } = received;
|
|
584
|
+
f = { ...rest, state: applyPatch(latest.state, patch) };
|
|
585
|
+
} else f = received;
|
|
586
|
+
wire = received;
|
|
549
587
|
const now = localNow();
|
|
550
588
|
const made = predictor.made;
|
|
551
589
|
correctFrom = game.entity && joined.tickRate > 0 && made && made.base === latest.state ? made.state : void 0;
|
|
@@ -566,21 +604,9 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
566
604
|
if (closed) return;
|
|
567
605
|
clock.reset();
|
|
568
606
|
predictor.reconnected();
|
|
569
|
-
|
|
570
|
-
dyn.mpJoin({ world: id }).then(
|
|
571
|
-
(j) => {
|
|
572
|
-
if (closed) return;
|
|
573
|
-
adopt(j, sent);
|
|
574
|
-
emit("frame", latest);
|
|
575
|
-
},
|
|
576
|
-
(error) => {
|
|
577
|
-
if (failedWith(error, "DISCONNECTED")) return;
|
|
578
|
-
log.warn("re-joining world {world} failed: {error}", { world: id, error });
|
|
579
|
-
handle.close("disconnected");
|
|
580
|
-
}
|
|
581
|
-
);
|
|
607
|
+
sync();
|
|
582
608
|
},
|
|
583
|
-
close(reason) {
|
|
609
|
+
close(reason, detail) {
|
|
584
610
|
if (closed) return;
|
|
585
611
|
closed = reason;
|
|
586
612
|
handles.delete(id);
|
|
@@ -593,15 +619,15 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
593
619
|
predictor.clear();
|
|
594
620
|
buffer.clear();
|
|
595
621
|
glide.clear();
|
|
596
|
-
emit("closed", { reason });
|
|
622
|
+
emit("closed", detail === void 0 ? { reason } : { reason, detail });
|
|
597
623
|
}
|
|
598
624
|
};
|
|
599
|
-
const predictor = new Predictor(game, world);
|
|
625
|
+
const predictor = new Predictor(game, Object.create(world, { serverTick: { value: sendTick } }));
|
|
600
626
|
const buffer = new BufferedInterpolator(game, world);
|
|
601
627
|
const glide = new Glide((a, b, t) => game.lerp ? game.lerp(a, b, t) : b, 1e3 / (first.tickRate || 1));
|
|
602
628
|
let glidedFrom;
|
|
603
|
-
adopt(first
|
|
604
|
-
if (first.tickRate > 0)
|
|
629
|
+
adopt(first);
|
|
630
|
+
if (first.tickRate > 0) ping();
|
|
605
631
|
return handle;
|
|
606
632
|
};
|
|
607
633
|
const offs = [
|
|
@@ -611,7 +637,10 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
611
637
|
"mp.seat",
|
|
612
638
|
(e) => handles.get(e.world)?.emit("seat", { player: e.player, change: e.change })
|
|
613
639
|
),
|
|
614
|
-
dyn.on(
|
|
640
|
+
dyn.on(
|
|
641
|
+
"mp.closed",
|
|
642
|
+
(e) => handles.get(e.world)?.close(e.reason, e.detail)
|
|
643
|
+
),
|
|
615
644
|
dyn.onReconnect(() => {
|
|
616
645
|
for (const h of handles.values()) h.rejoin();
|
|
617
646
|
})
|
|
@@ -623,14 +652,13 @@ function multiplayerClient(client, fragment, opts = {}) {
|
|
|
623
652
|
if (held) return Promise.resolve(held.world);
|
|
624
653
|
const inFlight = joining.get(world);
|
|
625
654
|
if (inFlight) return inFlight;
|
|
626
|
-
const sent = localNow();
|
|
627
655
|
const p = dyn.mpJoin({ world }).then((j) => {
|
|
628
656
|
if (detached) {
|
|
629
657
|
void dyn.mpLeave({ world }).catch(() => {
|
|
630
658
|
});
|
|
631
659
|
throw new SuperLineError("DISCONNECTED", "Multiplayer client closed");
|
|
632
660
|
}
|
|
633
|
-
const h = open(world, j
|
|
661
|
+
const h = open(world, j);
|
|
634
662
|
handles.set(world, h);
|
|
635
663
|
return h.world;
|
|
636
664
|
}).finally(() => joining.delete(world));
|
package/dist/index.cjs
CHANGED
|
@@ -62,6 +62,15 @@ var hostSchema = (schema) => {
|
|
|
62
62
|
return result.value;
|
|
63
63
|
}).meta(shape);
|
|
64
64
|
};
|
|
65
|
+
var isJson = (value) => {
|
|
66
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
67
|
+
if (typeof value === "number") return Number.isFinite(value);
|
|
68
|
+
if (Array.isArray(value)) return value.every(isJson);
|
|
69
|
+
if (typeof value !== "object") return false;
|
|
70
|
+
const proto = Object.getPrototypeOf(value);
|
|
71
|
+
if (proto !== Object.prototype && proto !== null) return false;
|
|
72
|
+
return Object.values(value).every(isJson);
|
|
73
|
+
};
|
|
65
74
|
|
|
66
75
|
// src/index.ts
|
|
67
76
|
var CommandRejected = class extends Error {
|
|
@@ -77,15 +86,6 @@ var CommandRejected = class extends Error {
|
|
|
77
86
|
function reject(code, reason) {
|
|
78
87
|
throw new CommandRejected(code, reason);
|
|
79
88
|
}
|
|
80
|
-
var isJson = (value) => {
|
|
81
|
-
if (value === null || typeof value === "string" || typeof value === "boolean") return true;
|
|
82
|
-
if (typeof value === "number") return Number.isFinite(value);
|
|
83
|
-
if (Array.isArray(value)) return value.every(isJson);
|
|
84
|
-
if (typeof value !== "object") return false;
|
|
85
|
-
const proto = Object.getPrototypeOf(value);
|
|
86
|
-
if (proto !== Object.prototype && proto !== null) return false;
|
|
87
|
-
return Object.values(value).every(isJson);
|
|
88
|
-
};
|
|
89
89
|
function defineWorld(world) {
|
|
90
90
|
const { maxPlayers, tickRate, sendRate } = world;
|
|
91
91
|
if (!Number.isFinite(maxPlayers) || maxPlayers <= 0) throw new TypeError("maxPlayers must be a positive number");
|
|
@@ -107,15 +107,20 @@ var rowSchema = z2.strictObject({
|
|
|
107
107
|
seats: z2.array(z2.strictObject({ player, profile: z2.unknown() })),
|
|
108
108
|
updatedAt: z2.number()
|
|
109
109
|
});
|
|
110
|
+
var element = z2.lazy(
|
|
111
|
+
() => z2.union([patchSchema, z2.tuple([z2.unknown()]), z2.tuple([z2.record(z2.string(), element), z2.number().int().min(0)])])
|
|
112
|
+
);
|
|
113
|
+
var patchSchema = z2.record(z2.string(), z2.union([element, z2.literal(0)]));
|
|
110
114
|
var surfaceOf = (world) => {
|
|
111
|
-
const
|
|
115
|
+
const head = {
|
|
112
116
|
world: worldId,
|
|
113
117
|
tick,
|
|
114
118
|
ms: z2.number().int().min(0).optional(),
|
|
115
119
|
epoch: z2.string().max(64).optional(),
|
|
116
|
-
acks: z2.record(player, z2.number().int().min(0))
|
|
117
|
-
|
|
118
|
-
|
|
120
|
+
acks: z2.record(player, z2.number().int().min(0))
|
|
121
|
+
};
|
|
122
|
+
const count = z2.number().int().min(0);
|
|
123
|
+
const frame = z2.strictObject({ ...head, n: count.optional(), state: hostSchema(world.state) });
|
|
119
124
|
const rate = z2.number().min(0);
|
|
120
125
|
const n = z2.number().min(0);
|
|
121
126
|
const stats = z2.strictObject({
|
|
@@ -154,7 +159,7 @@ var surfaceOf = (world) => {
|
|
|
154
159
|
}
|
|
155
160
|
},
|
|
156
161
|
serverToClient: {
|
|
157
|
-
"mp.state": { payload: frame },
|
|
162
|
+
"mp.state": { payload: z2.union([frame, z2.strictObject({ ...head, n: count, patch: patchSchema })]) },
|
|
158
163
|
"mp.message": {
|
|
159
164
|
payload: z2.strictObject({ world: worldId, message: world.message ? hostSchema(world.message) : z2.never() })
|
|
160
165
|
},
|
|
@@ -165,7 +170,13 @@ var surfaceOf = (world) => {
|
|
|
165
170
|
change: z2.enum(["joined", "left", "dropped", "resumed"])
|
|
166
171
|
})
|
|
167
172
|
},
|
|
168
|
-
"mp.closed": {
|
|
173
|
+
"mp.closed": {
|
|
174
|
+
payload: z2.strictObject({
|
|
175
|
+
world: worldId,
|
|
176
|
+
reason: z2.enum(["deleted", "replaced", "lost", "removed"]),
|
|
177
|
+
detail: z2.string().optional()
|
|
178
|
+
})
|
|
179
|
+
}
|
|
169
180
|
}
|
|
170
181
|
};
|
|
171
182
|
};
|