@margoengine/netcode 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1306 -3
- package/dist/client.d.ts +167 -0
- package/dist/clock.d.ts +29 -0
- package/dist/extrapolate.d.ts +42 -0
- package/dist/extrapolate.js +25 -0
- package/dist/game.d.ts +68 -0
- package/dist/generate-rust.d.ts +14 -0
- package/dist/generate-rust.js +184 -0
- package/dist/generate.d.ts +25 -0
- package/dist/generate.js +156 -0
- package/dist/hitboxes.d.ts +74 -0
- package/dist/hitboxes.js +124 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +457 -0
- package/dist/interest.d.ts +101 -0
- package/dist/interest.js +166 -0
- package/dist/interpolation-delay.d.ts +114 -0
- package/dist/interpolation-delay.js +79 -0
- package/dist/interpolation-fields.d.ts +117 -0
- package/dist/interpolation-fields.js +147 -0
- package/dist/interpolation-timeline.d.ts +100 -0
- package/dist/interpolation-timeline.js +122 -0
- package/dist/interpolation.d.ts +39 -0
- package/dist/interpolation.js +61 -0
- package/dist/lag.d.ts +62 -0
- package/dist/lobby.d.ts +77 -0
- package/dist/lobby.js +96 -0
- package/dist/loopback.d.ts +92 -0
- package/dist/media.d.ts +197 -0
- package/dist/media.js +274 -0
- package/dist/migrate.d.ts +113 -0
- package/dist/migrate.js +289 -0
- package/dist/node.d.ts +101 -0
- package/dist/node.js +166 -0
- package/dist/physics.d.ts +133 -0
- package/dist/physics.js +169 -0
- package/dist/presence.d.ts +156 -0
- package/dist/presence.js +226 -0
- package/dist/protocol-asi_qndb.js +122 -0
- package/dist/protocol.d.ts +75 -0
- package/dist/relay.d.ts +152 -0
- package/dist/relay.js +235 -0
- package/dist/rollback.d.ts +131 -0
- package/dist/rollback.js +194 -0
- package/dist/rooms.d.ts +366 -0
- package/dist/rooms.js +479 -0
- package/dist/schema-CMfqK4Gu.js +616 -0
- package/dist/schema.d.ts +263 -0
- package/dist/server-DAVzHcWW.js +203 -0
- package/dist/server.d.ts +147 -0
- package/dist/shared/bytes.d.ts +36 -0
- package/dist/signal.d.ts +156 -0
- package/dist/signal.js +261 -0
- package/dist/smoothing.d.ts +76 -0
- package/dist/smoothing.js +155 -0
- package/dist/transport-DeQodwyv.js +49 -0
- package/dist/transport.d.ts +76 -0
- package/dist/webrtc.d.ts +32 -0
- package/dist/webrtc.js +64 -0
- package/dist/websocket.d.ts +27 -0
- package/dist/websocket.js +42 -0
- package/dist/webtransport.d.ts +83 -0
- package/dist/webtransport.js +120 -0
- package/package.json +140 -6
package/dist/signal.d.ts
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { type Connection } from './transport.js';
|
|
2
|
+
/** Options of {@link SignalServer}. */
|
|
3
|
+
export interface SignalServerOptions {
|
|
4
|
+
/** Most rooms at once (default 1,024); a join that would make one more is refused. */
|
|
5
|
+
maxRooms?: number;
|
|
6
|
+
/** Most peers in a room (default 16); the next join is refused. */
|
|
7
|
+
maxPeers?: number;
|
|
8
|
+
/** Largest message in bytes (default 65,536, room for a long offer); bigger closes with `CloseCode.rateLimit`. */
|
|
9
|
+
maxMessageBytes?: number;
|
|
10
|
+
/** Messages a second a peer may send on average (default 100); past that it closes with `CloseCode.rateLimit`. */
|
|
11
|
+
messagesPerSecond?: number;
|
|
12
|
+
/** Messages a peer may send at once (default 200): the burst of candidates at the start of a call. */
|
|
13
|
+
burst?: number;
|
|
14
|
+
/** Milliseconds a connection has to send its join (default 10,000), or it closes with `CloseCode.timeout`. */
|
|
15
|
+
joinTimeout?: number;
|
|
16
|
+
/** Return false to refuse a join; `token` is what the client passed. Default: anyone with the room's name joins. */
|
|
17
|
+
authorize?(room: string, token: string | undefined): boolean | Promise<boolean>;
|
|
18
|
+
/** The clock in milliseconds (default `performance.now`). */
|
|
19
|
+
now?: () => number;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Passes messages between the peers of a room. It sees only what peers choose to send through it, keeps no history,
|
|
23
|
+
* and says who sent each message itself, so a peer cannot pose as another.
|
|
24
|
+
*
|
|
25
|
+
* @example
|
|
26
|
+
* ```ts
|
|
27
|
+
* const signals = new SignalServer();
|
|
28
|
+
* const listener = await listenWebSocket({ port: 8788 });
|
|
29
|
+
* listener.onconnection = (connection) => signals.accept(connection);
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
export declare class SignalServer {
|
|
33
|
+
private readonly options;
|
|
34
|
+
private readonly rooms;
|
|
35
|
+
private readonly waiting;
|
|
36
|
+
private readonly maxRooms;
|
|
37
|
+
private readonly maxPeers;
|
|
38
|
+
private readonly maxBytes;
|
|
39
|
+
private readonly rate;
|
|
40
|
+
private readonly burst;
|
|
41
|
+
private readonly joinTimeout;
|
|
42
|
+
private readonly now;
|
|
43
|
+
private nextId;
|
|
44
|
+
private closed;
|
|
45
|
+
/** @throws RangeError for an option out of range. */
|
|
46
|
+
constructor(options?: SignalServerOptions);
|
|
47
|
+
/** How many rooms hold a peer. */
|
|
48
|
+
get roomCount(): number;
|
|
49
|
+
/** How many peers are in `room`. */
|
|
50
|
+
peers(room: string): number;
|
|
51
|
+
/**
|
|
52
|
+
* Takes a new connection: it has `joinTimeout` to join a room.
|
|
53
|
+
* @throws MargoError `disposed` once the server is closed.
|
|
54
|
+
*/
|
|
55
|
+
accept(connection: Connection): void;
|
|
56
|
+
private parse;
|
|
57
|
+
private join;
|
|
58
|
+
private refuse;
|
|
59
|
+
private leave;
|
|
60
|
+
private receive;
|
|
61
|
+
/** Closes every connection. */
|
|
62
|
+
close(): void;
|
|
63
|
+
/** Same as {@link SignalServer.close}, for `using`. */
|
|
64
|
+
[Symbol.dispose](): void;
|
|
65
|
+
}
|
|
66
|
+
/** Options of {@link SignalClient.join}. */
|
|
67
|
+
export interface SignalJoinOptions {
|
|
68
|
+
/** What the server's `authorize` gets. */
|
|
69
|
+
token?: string;
|
|
70
|
+
/** Aborts the join (it rejects with the signal's reason and closes the connection). */
|
|
71
|
+
signal?: AbortSignal;
|
|
72
|
+
}
|
|
73
|
+
/** One peer's place in a room of a {@link SignalServer}. */
|
|
74
|
+
export declare class SignalClient {
|
|
75
|
+
private readonly connection;
|
|
76
|
+
/** This peer's id in the room, given by the server. */
|
|
77
|
+
readonly id: number;
|
|
78
|
+
/** Called when a peer joins the room after this one. */
|
|
79
|
+
onpeer: ((id: number) => void) | null;
|
|
80
|
+
/** Called when a peer leaves the room. */
|
|
81
|
+
onleft: ((id: number) => void) | null;
|
|
82
|
+
/** Called with what a peer sent this one. It comes from another peer: check it before use. */
|
|
83
|
+
onsignal: ((from: number, data: unknown) => void) | null;
|
|
84
|
+
/** Called once when the connection to the server closes. */
|
|
85
|
+
onclose: ((code: number, reason: string) => void) | null;
|
|
86
|
+
/** The peers in the room now, this one aside. */
|
|
87
|
+
readonly peers: Set<number>;
|
|
88
|
+
private constructor();
|
|
89
|
+
/**
|
|
90
|
+
* Joins `room` over `connection` to a {@link SignalServer}.
|
|
91
|
+
* @throws MargoError `failed` (as a rejection) when the server refuses or the connection closes first; the signal's
|
|
92
|
+
* reason when `signal` aborts.
|
|
93
|
+
*/
|
|
94
|
+
static join(connection: Connection, room: string, { token, signal }?: SignalJoinOptions): Promise<SignalClient>;
|
|
95
|
+
private receive;
|
|
96
|
+
/** Sends `data` (any JSON value) to peer `to`, through the server. */
|
|
97
|
+
send(to: number, data: unknown): void;
|
|
98
|
+
/** Leaves the room. */
|
|
99
|
+
close(): void;
|
|
100
|
+
/** Same as {@link SignalClient.close}, for `using`. */
|
|
101
|
+
[Symbol.dispose](): void;
|
|
102
|
+
}
|
|
103
|
+
/** Options of {@link PeerMesh}. */
|
|
104
|
+
export interface PeerMeshOptions {
|
|
105
|
+
/** The peer connection's settings; put your STUN and TURN servers in `iceServers` (default none: same network only). */
|
|
106
|
+
configuration?: RTCConfiguration;
|
|
107
|
+
/** The RTCPeerConnection class (default the global one, in a browser). */
|
|
108
|
+
RTCPeerConnection?: typeof RTCPeerConnection;
|
|
109
|
+
/** Called with each peer's connection once its data channels are open. */
|
|
110
|
+
onconnection?(peer: number, connection: Connection): void;
|
|
111
|
+
/** Called when a peer's link could not be made or failed, or a peer sent something that is not a description or candidate. */
|
|
112
|
+
onerror?(peer: number, error: unknown): void;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* A WebRTC link to every peer of a room: joining peers offer to those already there, so two peers never offer to each
|
|
116
|
+
* other. Each link is two data channels (`@margoengine/netcode/webrtc`) wrapped as a `Connection`, ready for
|
|
117
|
+
* `GameClient`, `GameServer` or `RollbackSession`.
|
|
118
|
+
*
|
|
119
|
+
* @example
|
|
120
|
+
* ```ts
|
|
121
|
+
* const room = await SignalClient.join(await openWebSocket('wss://game.example.com/signal'), 'lobby-7');
|
|
122
|
+
* const mesh = new PeerMesh(room, {
|
|
123
|
+
* configuration: { iceServers: [{ urls: 'stun:stun.example.com' }] },
|
|
124
|
+
* onconnection: (peer, connection) => connection.send(new Uint8Array([1])),
|
|
125
|
+
* });
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
export declare class PeerMesh {
|
|
129
|
+
private readonly client;
|
|
130
|
+
private readonly options;
|
|
131
|
+
/** The open connection of each peer. */
|
|
132
|
+
readonly connections: Map<number, Connection>;
|
|
133
|
+
/** Called with a peer's RTCPeerConnection as soon as it exists (before any description), for example to add media tracks. */
|
|
134
|
+
onlink: ((peer: number, connection: RTCPeerConnection) => void) | null;
|
|
135
|
+
/** Called with a peer's RTCPeerConnection just before it is closed. */
|
|
136
|
+
onunlink: ((peer: number, connection: RTCPeerConnection) => void) | null;
|
|
137
|
+
private readonly links;
|
|
138
|
+
private readonly Peer;
|
|
139
|
+
private closed;
|
|
140
|
+
/** @throws MargoError `unsupported` when there is no RTCPeerConnection here. */
|
|
141
|
+
constructor(client: SignalClient, options?: PeerMeshOptions);
|
|
142
|
+
/** The RTCPeerConnection of each peer now (also those whose data channels are not open yet). */
|
|
143
|
+
get peerConnections(): ReadonlyMap<number, RTCPeerConnection>;
|
|
144
|
+
private report;
|
|
145
|
+
private link;
|
|
146
|
+
private step;
|
|
147
|
+
/** Sets and sends this end's description, then the candidates that waited for it. */
|
|
148
|
+
private describe;
|
|
149
|
+
private offer;
|
|
150
|
+
private signal;
|
|
151
|
+
private drop;
|
|
152
|
+
/** Closes every link. The room stays joined; close the {@link SignalClient} to leave it. */
|
|
153
|
+
close(): void;
|
|
154
|
+
/** Same as {@link PeerMesh.close}, for `using`. */
|
|
155
|
+
[Symbol.dispose](): void;
|
|
156
|
+
}
|
package/dist/signal.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
import { r as e, t } from "./transport-DeQodwyv.js";
|
|
2
|
+
import { createDataChannels as n, dataChannelConnection as r } from "./webrtc.js";
|
|
3
|
+
//#region src/signal.ts
|
|
4
|
+
var i = new TextEncoder(), a = new TextDecoder("utf-8", { fatal: !0 }), o = (e, t) => e.send(i.encode(JSON.stringify(t)), "reliable"), s = (e) => {
|
|
5
|
+
try {
|
|
6
|
+
let t = JSON.parse(a.decode(e));
|
|
7
|
+
return typeof t == "object" && t ? t : void 0;
|
|
8
|
+
} catch {
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
}, c = (e, t) => {
|
|
12
|
+
if (!Number.isInteger(t) || t < 1) throw RangeError(`SignalServer ${e} is ${t}; pass an integer above 0`);
|
|
13
|
+
return t;
|
|
14
|
+
}, l = class {
|
|
15
|
+
constructor(e = {}) {
|
|
16
|
+
this.options = e, this.rooms = /* @__PURE__ */ new Map(), this.waiting = /* @__PURE__ */ new Set(), this.nextId = 1, this.closed = !1, this.maxRooms = c("maxRooms", e.maxRooms ?? 1024), this.maxPeers = c("maxPeers", e.maxPeers ?? 16), this.maxBytes = c("maxMessageBytes", e.maxMessageBytes ?? 65536), this.rate = c("messagesPerSecond", e.messagesPerSecond ?? 100), this.burst = c("burst", e.burst ?? 200), this.joinTimeout = c("joinTimeout", e.joinTimeout ?? 1e4), this.now = e.now ?? (() => performance.now());
|
|
17
|
+
}
|
|
18
|
+
get roomCount() {
|
|
19
|
+
return this.rooms.size;
|
|
20
|
+
}
|
|
21
|
+
peers(e) {
|
|
22
|
+
return this.rooms.get(e)?.size ?? 0;
|
|
23
|
+
}
|
|
24
|
+
accept(n) {
|
|
25
|
+
if (this.closed) throw e("disposed", "SignalServer is closed; create a new SignalServer");
|
|
26
|
+
this.waiting.add(n);
|
|
27
|
+
let r = setTimeout(() => n.close(t.timeout, "no join in time"), this.joinTimeout);
|
|
28
|
+
r.unref?.(), n.onclose = () => {
|
|
29
|
+
clearTimeout(r), this.waiting.delete(n);
|
|
30
|
+
}, n.onmessage = (e) => {
|
|
31
|
+
n.onmessage = null, clearTimeout(r), this.waiting.delete(n);
|
|
32
|
+
let t = this.parse(n, e);
|
|
33
|
+
t && this.join(n, t);
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
parse(e, n) {
|
|
37
|
+
if (n.length > this.maxBytes) {
|
|
38
|
+
e.close(t.rateLimit, `message over ${this.maxBytes} bytes (maxMessageBytes)`);
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
let r;
|
|
42
|
+
try {
|
|
43
|
+
r = JSON.parse(a.decode(n));
|
|
44
|
+
} catch {
|
|
45
|
+
e.close(t.protocol, "not JSON text");
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (typeof r != "object" || !r) e.close(t.protocol, "not a signal message");
|
|
49
|
+
else return r;
|
|
50
|
+
}
|
|
51
|
+
async join(e, n) {
|
|
52
|
+
let { kind: r, room: i, token: a } = n;
|
|
53
|
+
if (r !== "join" || typeof i != "string" || !i || i.length > 128) return e.close(t.protocol, "join first, with a room name of 1 to 128 characters");
|
|
54
|
+
let s;
|
|
55
|
+
try {
|
|
56
|
+
s = await this.options.authorize?.(i, a) ?? !0;
|
|
57
|
+
} catch {
|
|
58
|
+
s = !1;
|
|
59
|
+
}
|
|
60
|
+
if (!e.open || this.closed) return;
|
|
61
|
+
if (!s) return this.refuse(e, "not allowed in this room");
|
|
62
|
+
let c = this.rooms.get(i);
|
|
63
|
+
if (!c && this.rooms.size >= this.maxRooms) return this.refuse(e, "the server holds its most rooms");
|
|
64
|
+
if (c && c.size >= this.maxPeers) return this.refuse(e, "the room is full");
|
|
65
|
+
let l = c ?? /* @__PURE__ */ new Map(), u = {
|
|
66
|
+
id: this.nextId++,
|
|
67
|
+
room: i,
|
|
68
|
+
connection: e,
|
|
69
|
+
tokens: this.burst,
|
|
70
|
+
refilled: this.now()
|
|
71
|
+
};
|
|
72
|
+
this.rooms.set(i, l), o(e, {
|
|
73
|
+
kind: "joined",
|
|
74
|
+
id: u.id,
|
|
75
|
+
peers: [...l.keys()]
|
|
76
|
+
});
|
|
77
|
+
for (let e of l.values()) o(e.connection, {
|
|
78
|
+
kind: "peer",
|
|
79
|
+
id: u.id
|
|
80
|
+
});
|
|
81
|
+
l.set(u.id, u), e.onmessage = (e) => this.receive(u, e), e.onclose = () => this.leave(u);
|
|
82
|
+
}
|
|
83
|
+
refuse(e, n) {
|
|
84
|
+
o(e, {
|
|
85
|
+
kind: "refused",
|
|
86
|
+
reason: n
|
|
87
|
+
}), e.close(t.normal, "refused");
|
|
88
|
+
}
|
|
89
|
+
leave(e) {
|
|
90
|
+
let t = this.rooms.get(e.room);
|
|
91
|
+
if (t?.delete(e.id)) {
|
|
92
|
+
t.size || this.rooms.delete(e.room);
|
|
93
|
+
for (let n of t.values()) o(n.connection, {
|
|
94
|
+
kind: "left",
|
|
95
|
+
id: e.id
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
receive(e, n) {
|
|
100
|
+
let r = this.now(), i = e.connection;
|
|
101
|
+
if (e.tokens = Math.min(this.burst, e.tokens + (r - e.refilled) * this.rate / 1e3), e.refilled = r, e.tokens < 1) return i.close(t.rateLimit, "too many messages");
|
|
102
|
+
e.tokens--;
|
|
103
|
+
let a = this.parse(i, n);
|
|
104
|
+
if (!a) return;
|
|
105
|
+
if (a.kind !== "signal" || !Number.isInteger(a.to)) return i.close(t.protocol, "expected a signal message");
|
|
106
|
+
let s = this.rooms.get(e.room)?.get(a.to);
|
|
107
|
+
s && o(s.connection, {
|
|
108
|
+
kind: "signal",
|
|
109
|
+
from: e.id,
|
|
110
|
+
data: a.data
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
close() {
|
|
114
|
+
if (!this.closed) {
|
|
115
|
+
this.closed = !0;
|
|
116
|
+
for (let e of [...this.waiting]) e.close(t.removed, "server closed");
|
|
117
|
+
for (let e of [...this.rooms.values()]) for (let n of [...e.values()]) n.connection.close(t.removed, "server closed");
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
[Symbol.dispose]() {
|
|
121
|
+
this.close();
|
|
122
|
+
}
|
|
123
|
+
}, u = class n {
|
|
124
|
+
constructor(e, t, n) {
|
|
125
|
+
this.connection = e, this.id = t, this.onpeer = null, this.onleft = null, this.onsignal = null, this.onclose = null, this.peers = /* @__PURE__ */ new Set();
|
|
126
|
+
for (let e of n) this.peers.add(e);
|
|
127
|
+
e.onmessage = (e) => this.receive(e), e.onclose = (e, t) => this.onclose?.(e, t);
|
|
128
|
+
}
|
|
129
|
+
static join(r, i, { token: a, signal: c } = {}) {
|
|
130
|
+
return new Promise((l, u) => {
|
|
131
|
+
if (c?.aborted) return r.close(t.normal, "aborted"), u(c.reason);
|
|
132
|
+
if (!r.open) return u(e("failed", "Signal connection is closed; open a new one and join"));
|
|
133
|
+
let d = () => {
|
|
134
|
+
r.onclose = null, r.close(t.normal, "aborted"), u(c?.reason);
|
|
135
|
+
};
|
|
136
|
+
c?.addEventListener("abort", d, { once: !0 }), r.onclose = (t, n) => {
|
|
137
|
+
c?.removeEventListener("abort", d), u(e("failed", `Signal connection closed before joining (${t} ${n}); check the server`));
|
|
138
|
+
}, r.onmessage = (i) => {
|
|
139
|
+
c?.removeEventListener("abort", d);
|
|
140
|
+
let a = s(i);
|
|
141
|
+
if (r.onclose = null, a?.kind === "joined" && Number.isInteger(a.id) && Array.isArray(a.peers)) return l(new n(r, a.id, a.peers));
|
|
142
|
+
if (a?.kind === "refused") return u(e("failed", `Signal join refused: ${String(a.reason)}; check the room name and token`));
|
|
143
|
+
r.close(t.protocol, "not a signal reply"), u(e("failed", "Signal server sent something that is not a join reply; check the server version"));
|
|
144
|
+
}, o(r, {
|
|
145
|
+
kind: "join",
|
|
146
|
+
room: i,
|
|
147
|
+
token: a
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
receive(e) {
|
|
152
|
+
let n = s(e);
|
|
153
|
+
if (!n) return this.connection.close(t.protocol, "not a signal message");
|
|
154
|
+
n.kind === "peer" ? (this.peers.add(n.id), this.onpeer?.(n.id)) : n.kind === "left" ? (this.peers.delete(n.id), this.onleft?.(n.id)) : n.kind === "signal" && this.onsignal?.(n.from, n.data);
|
|
155
|
+
}
|
|
156
|
+
send(e, t) {
|
|
157
|
+
o(this.connection, {
|
|
158
|
+
kind: "signal",
|
|
159
|
+
to: e,
|
|
160
|
+
data: t
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
close() {
|
|
164
|
+
this.connection.close(t.normal, "left");
|
|
165
|
+
}
|
|
166
|
+
[Symbol.dispose]() {
|
|
167
|
+
this.close();
|
|
168
|
+
}
|
|
169
|
+
}, d = class {
|
|
170
|
+
constructor(t, n = {}) {
|
|
171
|
+
this.client = t, this.options = n, this.connections = /* @__PURE__ */ new Map(), this.onlink = null, this.onunlink = null, this.links = /* @__PURE__ */ new Map(), this.closed = !1;
|
|
172
|
+
let r = n.RTCPeerConnection ?? globalThis.RTCPeerConnection;
|
|
173
|
+
if (!r) throw e("unsupported", "PeerMesh needs RTCPeerConnection; run it in a browser or pass the class");
|
|
174
|
+
this.Peer = r, t.onsignal = (e, t) => this.signal(e, t), t.onleft = (e) => {
|
|
175
|
+
this.connections.has(e) || this.drop(e);
|
|
176
|
+
};
|
|
177
|
+
for (let e of t.peers) this.offer(e);
|
|
178
|
+
}
|
|
179
|
+
get peerConnections() {
|
|
180
|
+
return new Map([...this.links].map(([e, t]) => [e, t.peer]));
|
|
181
|
+
}
|
|
182
|
+
report(e, t) {
|
|
183
|
+
this.options.onerror?.(e, t);
|
|
184
|
+
}
|
|
185
|
+
link(t) {
|
|
186
|
+
let i = this.links.get(t);
|
|
187
|
+
if (i) return i;
|
|
188
|
+
let a = new this.Peer(this.options.configuration), o = n(a), s = {
|
|
189
|
+
peer: a,
|
|
190
|
+
channels: o,
|
|
191
|
+
queue: Promise.resolve(),
|
|
192
|
+
held: [],
|
|
193
|
+
making: !1,
|
|
194
|
+
ignoring: !1
|
|
195
|
+
};
|
|
196
|
+
return this.links.set(t, s), a.addEventListener("icecandidate", (e) => {
|
|
197
|
+
if (!e.candidate) return;
|
|
198
|
+
let n = e.candidate.toJSON();
|
|
199
|
+
s.held ? s.held.push(n) : this.client.send(t, { candidate: n });
|
|
200
|
+
}), a.addEventListener("negotiationneeded", () => {
|
|
201
|
+
!this.closed && (a.localDescription || a.remoteDescription) && this.step(t, s, () => a.signalingState === "stable" ? this.describe(t, s) : Promise.resolve());
|
|
202
|
+
}), a.addEventListener("connectionstatechange", () => {
|
|
203
|
+
a.connectionState === "failed" && (this.report(t, e("failed", `The link to peer ${t} failed; check the STUN and TURN servers`)), this.drop(t));
|
|
204
|
+
}), o.reliable.addEventListener("open", () => {
|
|
205
|
+
let e = r(o);
|
|
206
|
+
this.connections.set(t, e), this.options.onconnection?.(t, e);
|
|
207
|
+
}, { once: !0 }), o.reliable.addEventListener("close", () => this.drop(t), { once: !0 }), this.onlink?.(t, a), s;
|
|
208
|
+
}
|
|
209
|
+
step(e, t, n) {
|
|
210
|
+
t.queue = t.queue.then(n).catch((t) => this.report(e, t));
|
|
211
|
+
}
|
|
212
|
+
async describe(e, t) {
|
|
213
|
+
t.making = !0;
|
|
214
|
+
try {
|
|
215
|
+
await t.peer.setLocalDescription();
|
|
216
|
+
} finally {
|
|
217
|
+
t.making = !1;
|
|
218
|
+
}
|
|
219
|
+
this.client.send(e, { description: t.peer.localDescription });
|
|
220
|
+
for (let n of t.held ?? []) this.client.send(e, { candidate: n });
|
|
221
|
+
t.held = null;
|
|
222
|
+
}
|
|
223
|
+
offer(e) {
|
|
224
|
+
let t = this.link(e);
|
|
225
|
+
this.step(e, t, () => this.describe(e, t));
|
|
226
|
+
}
|
|
227
|
+
signal(e, t) {
|
|
228
|
+
let { description: n, candidate: r } = t ?? {};
|
|
229
|
+
if (this.closed) return;
|
|
230
|
+
if (n === void 0 && r === void 0) return this.report(e, /* @__PURE__ */ TypeError("A peer sent neither a description nor a candidate"));
|
|
231
|
+
let i = this.link(e), a = this.client.id > e;
|
|
232
|
+
this.step(e, i, async () => {
|
|
233
|
+
if (r !== void 0) try {
|
|
234
|
+
return await i.peer.addIceCandidate(r);
|
|
235
|
+
} catch (e) {
|
|
236
|
+
if (!i.ignoring) throw e;
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
let t = i.peer.signalingState, o = n?.type === "offer" && (i.making || t !== void 0 && t !== "stable");
|
|
240
|
+
i.ignoring = !a && o, !i.ignoring && (await i.peer.setRemoteDescription(n), n?.type === "offer" && await this.describe(e, i));
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
drop(e) {
|
|
244
|
+
let n = this.links.get(e);
|
|
245
|
+
if (!n) return;
|
|
246
|
+
this.links.delete(e);
|
|
247
|
+
let r = this.connections.get(e);
|
|
248
|
+
this.connections.delete(e), r?.close(t.normal, "peer left"), this.onunlink?.(e, n.peer), n.peer.close();
|
|
249
|
+
}
|
|
250
|
+
close() {
|
|
251
|
+
if (!this.closed) {
|
|
252
|
+
this.closed = !0;
|
|
253
|
+
for (let e of [...this.links.keys()]) this.drop(e);
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
[Symbol.dispose]() {
|
|
257
|
+
this.close();
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
//#endregion
|
|
261
|
+
export { d as PeerMesh, u as SignalClient, l as SignalServer };
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { GameClient } from './client.js';
|
|
2
|
+
/** Options of {@link CorrectionSmoother}. */
|
|
3
|
+
export interface SmoothingOptions {
|
|
4
|
+
/** Milliseconds for an error to halve (default 50: gone from sight in about 6 frames at 60 Hz). */
|
|
5
|
+
halfLife?: number;
|
|
6
|
+
/**
|
|
7
|
+
* A second, faster half life for big errors, so one long stall does not drag on: `from` is the error size where it
|
|
8
|
+
* starts to blend in and `to` where it has taken over, in world units. Default none.
|
|
9
|
+
*/
|
|
10
|
+
fast?: {
|
|
11
|
+
readonly from: number;
|
|
12
|
+
readonly to: number;
|
|
13
|
+
readonly halfLife: number;
|
|
14
|
+
};
|
|
15
|
+
/** An error over this distance is not blended: a teleport or respawn jumps at once (default never). */
|
|
16
|
+
snap?: number;
|
|
17
|
+
/** An offset smaller than this is cleared (default 0.0001). */
|
|
18
|
+
settle?: number;
|
|
19
|
+
/** The clock in milliseconds (default `performance.now`). */
|
|
20
|
+
now?: () => number;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Draws a {@link GameClient}'s prediction with its corrections blended away instead of snapping. Every field the
|
|
24
|
+
* schema interpolates eases (`'linear'` in a line, `'angle'` the short way); the others, and everything in
|
|
25
|
+
* `client.predicted`, keep their exact values.
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* ```ts
|
|
29
|
+
* const smooth = new CorrectionSmoother(client);
|
|
30
|
+
* engine.onFrame(() => {
|
|
31
|
+
* client.update();
|
|
32
|
+
* drawMe(smooth.state().boxes.get(client.player));
|
|
33
|
+
* });
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
export declare class CorrectionSmoother<State, Input = unknown> {
|
|
37
|
+
private readonly client;
|
|
38
|
+
private offset;
|
|
39
|
+
private readonly schema;
|
|
40
|
+
private readonly stateType;
|
|
41
|
+
private readonly halfLife;
|
|
42
|
+
private readonly fast;
|
|
43
|
+
private readonly snap;
|
|
44
|
+
private readonly settle;
|
|
45
|
+
private readonly now;
|
|
46
|
+
private readonly chained;
|
|
47
|
+
private last;
|
|
48
|
+
private largest;
|
|
49
|
+
private closed;
|
|
50
|
+
/** @throws RangeError for an option out of range; TypeError when `client` is not a GameClient. */
|
|
51
|
+
constructor(client: GameClient<State, Input>, options?: SmoothingOptions);
|
|
52
|
+
/** The largest distance left to blend away after the newest {@link CorrectionSmoother.state}, 0 when settled. */
|
|
53
|
+
get error(): number;
|
|
54
|
+
private struct;
|
|
55
|
+
/** The offset that keeps `before + old` on screen now the value is `after`. */
|
|
56
|
+
private fold;
|
|
57
|
+
/** How far a struct's own `'linear'` numbers are off, as one distance. */
|
|
58
|
+
private distance;
|
|
59
|
+
/** What share of an error of size `size` is left after `ms`. */
|
|
60
|
+
private keep;
|
|
61
|
+
/** `offset` after `ms`, undefined once nothing is left. Numbers of one struct shrink as one vector. */
|
|
62
|
+
private shrink;
|
|
63
|
+
private add;
|
|
64
|
+
private correct;
|
|
65
|
+
/**
|
|
66
|
+
* What to draw now: `client.predicted` plus what is left of the corrections, which it returns as it is once they
|
|
67
|
+
* settled. Call it once per frame, after `client.update()`. Do not write to the result.
|
|
68
|
+
*/
|
|
69
|
+
state(): State;
|
|
70
|
+
/** Clears what is left to blend, so the next frame draws the exact prediction. */
|
|
71
|
+
reset(): void;
|
|
72
|
+
/** Stops following the client. */
|
|
73
|
+
close(): void;
|
|
74
|
+
/** Same as {@link CorrectionSmoother.close}, for `using`. */
|
|
75
|
+
[Symbol.dispose](): void;
|
|
76
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
//#region src/smoothing.ts
|
|
2
|
+
var e = 2 * Math.PI, t = (t) => t - e * Math.round(t / e), n = (e) => "interpolate" in e && e.interpolate !== "none", r = class {
|
|
3
|
+
constructor(e, t = {}) {
|
|
4
|
+
if (this.client = e, this.last = NaN, this.largest = 0, this.closed = !1, !e?.game) throw TypeError("CorrectionSmoother needs a GameClient; pass what GameClient.join gave you");
|
|
5
|
+
if (this.schema = e.game.schema, this.stateType = e.game.stateType, this.halfLife = t.halfLife ?? 50, this.fast = t.fast, this.snap = t.snap ?? Infinity, this.settle = t.settle ?? 1e-4, this.now = t.now ?? (() => performance.now()), !(this.halfLife > 0)) throw RangeError(`CorrectionSmoother halfLife is ${this.halfLife}; pass ms above 0`);
|
|
6
|
+
if (!(this.snap > 0)) throw RangeError(`CorrectionSmoother snap is ${this.snap}; pass a distance above 0`);
|
|
7
|
+
if (!(this.settle > 0)) throw RangeError(`CorrectionSmoother settle is ${this.settle}; pass a size above 0`);
|
|
8
|
+
let n = this.fast;
|
|
9
|
+
if (n && !(n.halfLife > 0 && n.from >= 0 && n.to > n.from)) throw RangeError("CorrectionSmoother fast needs halfLife above 0 and to above from; fix it");
|
|
10
|
+
this.chained = e.oncorrection, e.oncorrection = (e, t) => {
|
|
11
|
+
this.correct(e, t), this.chained?.(e, t);
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
get error() {
|
|
15
|
+
return this.largest;
|
|
16
|
+
}
|
|
17
|
+
struct(e) {
|
|
18
|
+
return this.schema.json.types[e];
|
|
19
|
+
}
|
|
20
|
+
fold(e, r, i, a) {
|
|
21
|
+
if (r !== void 0 && i !== void 0) {
|
|
22
|
+
if (n(e)) {
|
|
23
|
+
let n = r - i, o = (a ?? 0) + (e.interpolate === "angle" ? t(n) : n);
|
|
24
|
+
return o === 0 ? void 0 : o;
|
|
25
|
+
}
|
|
26
|
+
switch (e.type) {
|
|
27
|
+
case "struct": {
|
|
28
|
+
let t = {}, n = r, o = i, s = a, c = !1;
|
|
29
|
+
for (let [r, i] of Object.entries(this.struct(e.name))) {
|
|
30
|
+
let e = this.fold(i, n[r], o[r], s?.[r]);
|
|
31
|
+
e !== void 0 && (t[r] = e, c = !0);
|
|
32
|
+
}
|
|
33
|
+
return c ? t : void 0;
|
|
34
|
+
}
|
|
35
|
+
case "map": {
|
|
36
|
+
let t = /* @__PURE__ */ new Map(), n = r, o = a;
|
|
37
|
+
for (let [r, a] of i) {
|
|
38
|
+
let i = this.fold(e.of, n.get(r), a, o?.get(r));
|
|
39
|
+
i !== void 0 && t.set(r, i);
|
|
40
|
+
}
|
|
41
|
+
return t.size ? t : void 0;
|
|
42
|
+
}
|
|
43
|
+
case "array": {
|
|
44
|
+
let t = r, n = i;
|
|
45
|
+
if (t.length !== n.length) return;
|
|
46
|
+
let o = n.map((n, r) => this.fold(e.of, t[r], n, a?.[r]));
|
|
47
|
+
return o.some((e) => e !== void 0) ? o : void 0;
|
|
48
|
+
}
|
|
49
|
+
case "optional": return this.fold(e.of, r, i, a);
|
|
50
|
+
default: return;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
distance(e, t) {
|
|
55
|
+
let n = 0;
|
|
56
|
+
for (let [r, i] of Object.entries(t)) {
|
|
57
|
+
let t = e[r];
|
|
58
|
+
typeof i == "number" && "interpolate" in t && t.interpolate === "linear" && (n += i * i);
|
|
59
|
+
}
|
|
60
|
+
return Math.sqrt(n);
|
|
61
|
+
}
|
|
62
|
+
keep(e, t) {
|
|
63
|
+
let n = this.fast, r = this.halfLife;
|
|
64
|
+
if (n) {
|
|
65
|
+
let t = Math.min(1, Math.max(0, (e - n.from) / (n.to - n.from)));
|
|
66
|
+
r += (n.halfLife - r) * t;
|
|
67
|
+
}
|
|
68
|
+
return 2 ** (-t / r);
|
|
69
|
+
}
|
|
70
|
+
shrink(e, t, n, r) {
|
|
71
|
+
if (typeof t == "number") {
|
|
72
|
+
let e = t * (n === 0 ? 1 : r);
|
|
73
|
+
return Math.abs(e) < this.settle ? void 0 : (this.largest = Math.max(this.largest, Math.abs(e)), e);
|
|
74
|
+
}
|
|
75
|
+
switch (e.type) {
|
|
76
|
+
case "struct": {
|
|
77
|
+
let i = this.struct(e.name), a = t, o = this.distance(i, a), s = {};
|
|
78
|
+
if (o > this.snap) for (let [e, t] of Object.entries(a)) {
|
|
79
|
+
let n = i[e];
|
|
80
|
+
typeof t == "number" && "interpolate" in n && n.interpolate === "linear" && delete a[e];
|
|
81
|
+
}
|
|
82
|
+
let c = this.keep(o, n), l = !1;
|
|
83
|
+
for (let [e, t] of Object.entries(a)) {
|
|
84
|
+
let a = this.shrink(i[e], t, n, typeof t == "number" ? c : r);
|
|
85
|
+
a !== void 0 && (s[e] = a, l = !0);
|
|
86
|
+
}
|
|
87
|
+
return l ? s : void 0;
|
|
88
|
+
}
|
|
89
|
+
case "map": {
|
|
90
|
+
let i = /* @__PURE__ */ new Map();
|
|
91
|
+
for (let [a, o] of t) {
|
|
92
|
+
let t = this.shrink(e.of, o, n, r);
|
|
93
|
+
t !== void 0 && i.set(a, t);
|
|
94
|
+
}
|
|
95
|
+
return i.size ? i : void 0;
|
|
96
|
+
}
|
|
97
|
+
case "array": {
|
|
98
|
+
let i = t.map((t) => t === void 0 ? t : this.shrink(e.of, t, n, r));
|
|
99
|
+
return i.some((e) => e !== void 0) ? i : void 0;
|
|
100
|
+
}
|
|
101
|
+
case "optional": return this.shrink(e.of, t, n, r);
|
|
102
|
+
default: return;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
add(e, t, n) {
|
|
106
|
+
if (n === void 0 || t === void 0) return t;
|
|
107
|
+
if (typeof n == "number") return t + n;
|
|
108
|
+
switch (e.type) {
|
|
109
|
+
case "struct": {
|
|
110
|
+
let r = this.struct(e.name), i = { ...t };
|
|
111
|
+
for (let [e, t] of Object.entries(n)) i[e] = this.add(r[e], i[e], t);
|
|
112
|
+
return i;
|
|
113
|
+
}
|
|
114
|
+
case "map": {
|
|
115
|
+
let r = new Map(t);
|
|
116
|
+
for (let [t, i] of n) r.has(t) && r.set(t, this.add(e.of, r.get(t), i));
|
|
117
|
+
return r;
|
|
118
|
+
}
|
|
119
|
+
case "array": {
|
|
120
|
+
let r = t, i = n;
|
|
121
|
+
return r.length === i.length ? r.map((t, n) => this.add(e.of, t, i[n])) : r;
|
|
122
|
+
}
|
|
123
|
+
case "optional": return this.add(e.of, t, n);
|
|
124
|
+
default: return t;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
correct(e, t) {
|
|
128
|
+
if (this.closed) return;
|
|
129
|
+
let n = {
|
|
130
|
+
type: "struct",
|
|
131
|
+
name: this.stateType
|
|
132
|
+
};
|
|
133
|
+
this.largest = 0;
|
|
134
|
+
let r = this.fold(n, e, t, this.offset);
|
|
135
|
+
this.offset = r === void 0 ? void 0 : this.shrink(n, r, 0, 1);
|
|
136
|
+
}
|
|
137
|
+
state() {
|
|
138
|
+
let e = this.now(), t = Number.isNaN(this.last) ? 0 : Math.max(0, e - this.last), n = {
|
|
139
|
+
type: "struct",
|
|
140
|
+
name: this.stateType
|
|
141
|
+
};
|
|
142
|
+
return this.last = e, this.largest = 0, this.offset !== void 0 && (this.offset = this.shrink(n, this.offset, t, this.keep(0, t))), this.offset === void 0 ? this.client.predicted : this.add(n, this.client.predicted, this.offset);
|
|
143
|
+
}
|
|
144
|
+
reset() {
|
|
145
|
+
this.offset = void 0, this.largest = 0;
|
|
146
|
+
}
|
|
147
|
+
close() {
|
|
148
|
+
this.closed || (this.closed = !0, this.client.oncorrection = this.chained);
|
|
149
|
+
}
|
|
150
|
+
[Symbol.dispose]() {
|
|
151
|
+
this.close();
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
//#endregion
|
|
155
|
+
export { r as CorrectionSmoother };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { MargoError as e } from "@margoengine/math/errors";
|
|
2
|
+
//#region src/transport.ts
|
|
3
|
+
var t = {
|
|
4
|
+
normal: 1e3,
|
|
5
|
+
protocol: 4001,
|
|
6
|
+
rateLimit: 4002,
|
|
7
|
+
mismatch: 4003,
|
|
8
|
+
full: 4004,
|
|
9
|
+
removed: 4005,
|
|
10
|
+
timeout: 4006,
|
|
11
|
+
error: 4007
|
|
12
|
+
}, n = new TextEncoder(), r = new TextDecoder();
|
|
13
|
+
function i(e, t = 123) {
|
|
14
|
+
let i = n.encode(e);
|
|
15
|
+
if (i.length <= t) return e;
|
|
16
|
+
let a = t;
|
|
17
|
+
for (; a > 0 && (i[a] & 192) == 128;) a--;
|
|
18
|
+
return r.decode(i.subarray(0, a));
|
|
19
|
+
}
|
|
20
|
+
async function* a(e, { signal: t } = {}) {
|
|
21
|
+
let n = [], r = null, i = !e.open, a = () => {
|
|
22
|
+
let e = r;
|
|
23
|
+
r = null, e?.();
|
|
24
|
+
};
|
|
25
|
+
e.onmessage = (e, t) => {
|
|
26
|
+
n.push({
|
|
27
|
+
data: e,
|
|
28
|
+
channel: t
|
|
29
|
+
}), a();
|
|
30
|
+
}, e.onclose = () => {
|
|
31
|
+
i = !0, a();
|
|
32
|
+
};
|
|
33
|
+
let o = () => {
|
|
34
|
+
i = !0, a();
|
|
35
|
+
};
|
|
36
|
+
t?.addEventListener("abort", o, { once: !0 });
|
|
37
|
+
try {
|
|
38
|
+
for (;;) {
|
|
39
|
+
for (; n.length;) yield n.shift();
|
|
40
|
+
if (i || t?.aborted) return;
|
|
41
|
+
await new Promise((e) => r = e);
|
|
42
|
+
}
|
|
43
|
+
} finally {
|
|
44
|
+
t?.removeEventListener("abort", o);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
var o = (t, n) => new e(t, n);
|
|
48
|
+
//#endregion
|
|
49
|
+
export { a as i, i as n, o as r, t };
|