@vibe-engine/net 0.0.0-stage → 0.1.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/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +22 -0
- package/README.md +10 -2
- package/dist/client.d.ts +60 -0
- package/dist/client.js +248 -0
- package/dist/debug.d.ts +3 -0
- package/dist/debug.js +13 -0
- package/dist/delta.d.ts +40 -0
- package/dist/delta.js +124 -0
- package/dist/events.d.ts +17 -0
- package/dist/events.js +9 -0
- package/dist/hub.d.ts +29 -0
- package/dist/hub.js +130 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +15 -0
- package/dist/loopback.d.ts +21 -0
- package/dist/loopback.js +45 -0
- package/dist/node.server.d.ts +30 -0
- package/dist/node.server.js +146 -0
- package/dist/positions.d.ts +9 -0
- package/dist/positions.js +18 -0
- package/dist/protocol.d.ts +116 -0
- package/dist/protocol.js +6 -0
- package/dist/room-client.d.ts +60 -0
- package/dist/room-client.js +153 -0
- package/dist/room.d.ts +89 -0
- package/dist/room.js +58 -0
- package/dist/server.d.ts +52 -0
- package/dist/server.js +232 -0
- package/dist/websocket.d.ts +5 -0
- package/dist/websocket.js +27 -0
- package/package.json +48 -3
package/dist/server.js
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { diffState } from './delta.js';
|
|
2
|
+
import { positions } from './positions.js';
|
|
3
|
+
/** Quantos ticks de snapshots o servidor guarda como base de diferença (~2 s a 60 Hz). */
|
|
4
|
+
const HISTORY_TICKS = 120;
|
|
5
|
+
import { PROTOCOL, prefixed } from './protocol.js';
|
|
6
|
+
import { NetPlayerAway, NetPlayerBack, NetPlayerJoined, NetPlayerLeft } from './events.js';
|
|
7
|
+
/** Limites do que o servidor aceita de um cliente por tick (entrada não confiável). */
|
|
8
|
+
const MAX_HIT_QUERIES = 16;
|
|
9
|
+
const MAX_HITS_PER_QUERY = 32;
|
|
10
|
+
const finite = (v) => typeof v === 'number' && Number.isFinite(v);
|
|
11
|
+
function validHits(v) {
|
|
12
|
+
return Array.isArray(v) && v.length <= MAX_HIT_QUERIES && v.every((q) => Array.isArray(q) && q.length <= MAX_HITS_PER_QUERY
|
|
13
|
+
&& q.every((h) => h && typeof h.entity === 'string' && h.at && finite(h.at.x) && finite(h.at.y) && finite(h.at.z)));
|
|
14
|
+
}
|
|
15
|
+
/** Menor distância de `p` à linha que passa pelas posições, em ordem. */
|
|
16
|
+
function distanceToPath(p, path) {
|
|
17
|
+
let best = Infinity;
|
|
18
|
+
for (let i = 0; i < path.length; i++) {
|
|
19
|
+
const a = path[i], b = path[i + 1] ?? a;
|
|
20
|
+
const ab = { x: b.x - a.x, y: b.y - a.y, z: b.z - a.z };
|
|
21
|
+
const l2 = ab.x * ab.x + ab.y * ab.y + ab.z * ab.z;
|
|
22
|
+
const t = l2 ? Math.max(0, Math.min(1, ((p.x - a.x) * ab.x + (p.y - a.y) * ab.y + (p.z - a.z) * ab.z) / l2)) : 0;
|
|
23
|
+
best = Math.min(best, Math.hypot(p.x - (a.x + ab.x * t), p.y - (a.y + ab.y * t), p.z - (a.z + ab.z * t)));
|
|
24
|
+
}
|
|
25
|
+
return best;
|
|
26
|
+
}
|
|
27
|
+
export function createNetServer(world, opts = {}) {
|
|
28
|
+
const every = opts.snapshotEvery ?? 3;
|
|
29
|
+
const conns = [];
|
|
30
|
+
const stats = { lateInputs: 0, snapshots: 0, full: 0, deltas: 0, hitsAccepted: 0, hitsRejected: 0 };
|
|
31
|
+
const lag = opts.lagCompensation === false ? null : { maxTicks: opts.lagCompensation?.maxTicks ?? 30, px: opts.lagCompensation?.tolerance?.px ?? 32, m: opts.lagCompensation?.tolerance?.m ?? 1 };
|
|
32
|
+
const trail = new Map(); // tick → posições (o caminho real de cada alvo)
|
|
33
|
+
if (lag) {
|
|
34
|
+
trail.set(world.frame, positions(world));
|
|
35
|
+
world.hitAuthority = {
|
|
36
|
+
resolve(w, by, query) {
|
|
37
|
+
const c = conns.find((x) => x.player === by);
|
|
38
|
+
const claim = c?.claims.shift();
|
|
39
|
+
if (!c || !claim)
|
|
40
|
+
return query(new Map());
|
|
41
|
+
const overrides = new Map();
|
|
42
|
+
const from = Math.max(c.view.from - 1, w.frame - lag.maxTicks);
|
|
43
|
+
const to = Math.min(c.view.to + 1, w.frame);
|
|
44
|
+
for (const h of claim) {
|
|
45
|
+
const path = [];
|
|
46
|
+
for (let f = from; f <= to; f++) {
|
|
47
|
+
const p = trail.get(f)?.get(h.entity);
|
|
48
|
+
if (p)
|
|
49
|
+
path.push(p);
|
|
50
|
+
}
|
|
51
|
+
if (path.length && distanceToPath(h.at, path) <= (path[0].m ? lag.m : lag.px)) {
|
|
52
|
+
overrides.set(h.entity, h.at);
|
|
53
|
+
stats.hitsAccepted++;
|
|
54
|
+
}
|
|
55
|
+
else
|
|
56
|
+
stats.hitsRejected++;
|
|
57
|
+
}
|
|
58
|
+
return query(overrides);
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const history = new Map();
|
|
63
|
+
let next = 1;
|
|
64
|
+
let lastSnapshot = 0;
|
|
65
|
+
const tokens = new Map(); // jogador → token
|
|
66
|
+
const profiles = new Map(); // jogador → perfil (vale na volta com o token)
|
|
67
|
+
const away = new Map(); // jogador → tick em que perde a vaga
|
|
68
|
+
const grace = opts.reconnectGraceTicks ?? 600;
|
|
69
|
+
const token = () => globalThis.crypto.randomUUID();
|
|
70
|
+
const send = (c, m) => c.link.send(m);
|
|
71
|
+
function read(c) {
|
|
72
|
+
for (const raw of c.link.receive()) {
|
|
73
|
+
const m = raw;
|
|
74
|
+
if (m.t === 'hello') {
|
|
75
|
+
if (c.player)
|
|
76
|
+
continue;
|
|
77
|
+
if (m.protocol !== PROTOCOL || (opts.version && m.version !== opts.version)) {
|
|
78
|
+
send(c, { t: 'reject', code: 'version-mismatch', message: `server runs version ${opts.version ?? '?'} (protocol ${PROTOCOL}), client sent ${m.version} (protocol ${m.protocol}); reload the page to update` });
|
|
79
|
+
c.link.close();
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const back = m.token ? [...tokens].find(([p, tk]) => tk === m.token && away.has(p))?.[0] : undefined;
|
|
83
|
+
if (back) {
|
|
84
|
+
// Voltou a tempo: mesmo id, mesmo lutador, mesmo placar.
|
|
85
|
+
away.delete(back);
|
|
86
|
+
c.player = back;
|
|
87
|
+
send(c, { t: 'welcome', player: back, tick: world.frame, tickRate: world.tickRate, token: tokens.get(back), rejoined: true });
|
|
88
|
+
world.inject(NetPlayerBack, { player: back, profile: profiles.get(back) ?? {} });
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (m.token) {
|
|
92
|
+
// Token de uma vaga que já expirou: volta para o lobby (a conexão continua) em vez de virar outro jogador.
|
|
93
|
+
send(c, { t: 'reject', code: 'rejoin-expired', message: 'your seat in this room expired; pick a room again' });
|
|
94
|
+
conns.splice(conns.indexOf(c), 1);
|
|
95
|
+
const rest = c.link.receive();
|
|
96
|
+
if (opts.onRelease)
|
|
97
|
+
opts.onRelease(rest.length ? prefixed(c.link, rest) : c.link);
|
|
98
|
+
else
|
|
99
|
+
c.link.close();
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
if (conns.filter((x) => x.player).length + away.size >= (opts.maxPlayers ?? 8)) {
|
|
103
|
+
send(c, { t: 'reject', code: 'room-full', message: `room is full (${opts.maxPlayers ?? 8} players)` });
|
|
104
|
+
c.link.close();
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
c.player = `p${next++}`;
|
|
108
|
+
tokens.set(c.player, token());
|
|
109
|
+
profiles.set(c.player, c.profile);
|
|
110
|
+
send(c, { t: 'welcome', player: c.player, tick: world.frame, tickRate: world.tickRate, token: tokens.get(c.player), rejoined: false });
|
|
111
|
+
world.inject(NetPlayerJoined, { player: c.player, profile: c.profile });
|
|
112
|
+
}
|
|
113
|
+
else if (m.t === 'leave' && c.player) {
|
|
114
|
+
// Saiu de propósito: vaga liberada na hora; a conexão volta para o lobby.
|
|
115
|
+
world.inject(NetPlayerLeft, { player: c.player });
|
|
116
|
+
tokens.delete(c.player);
|
|
117
|
+
profiles.delete(c.player);
|
|
118
|
+
conns.splice(conns.indexOf(c), 1);
|
|
119
|
+
const rest = c.link.receive();
|
|
120
|
+
opts.onRelease?.(rest.length ? prefixed(c.link, rest) : c.link);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
else if (m.t === 'ping' && typeof m.id === 'number') {
|
|
124
|
+
send(c, { t: 'pong', id: m.id, late: c.late });
|
|
125
|
+
}
|
|
126
|
+
else if (m.t === 'input' && c.player && Number.isInteger(m.tick)) {
|
|
127
|
+
c.queue.push({ tick: m.tick, values: m.values, snap: typeof m.snap === 'number' ? m.snap : -1, ...(validHits(m.hits) ? { hits: m.hits } : {}) });
|
|
128
|
+
if (typeof m.snap === 'number')
|
|
129
|
+
c.snap = m.snap;
|
|
130
|
+
c.latest = Math.max(c.latest, m.tick);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** Inputs com tick ≤ agora: o último valor vence; botão apertado em algum deles vira `press` (não perde o tiro). */
|
|
135
|
+
function apply(c) {
|
|
136
|
+
const due = c.queue.filter((q) => q.tick <= world.frame).sort((a, b) => a.tick - b.tick);
|
|
137
|
+
if (!due.length)
|
|
138
|
+
return;
|
|
139
|
+
c.queue = c.queue.filter((q) => q.tick > world.frame);
|
|
140
|
+
if (due.length > 1 || due[0].tick < world.frame) {
|
|
141
|
+
const late = due.filter((q) => q.tick < world.frame).length;
|
|
142
|
+
stats.lateInputs += late;
|
|
143
|
+
c.late += late;
|
|
144
|
+
}
|
|
145
|
+
const last = due.at(-1).values;
|
|
146
|
+
for (const [action, value] of Object.entries(last)) {
|
|
147
|
+
try {
|
|
148
|
+
if (value === false && due.some((q) => q.values[action] === true))
|
|
149
|
+
world.input.press(action, c.player);
|
|
150
|
+
else
|
|
151
|
+
world.input.set(action, value, c.player); // o buffer valida e recorta: cliente não manda valor impossível
|
|
152
|
+
}
|
|
153
|
+
catch { /* ação desconhecida ou valor inválido: ignora a ação, não derruba a sala */ }
|
|
154
|
+
}
|
|
155
|
+
c.ack = Math.max(c.ack, due.at(-1).tick);
|
|
156
|
+
c.claims = due.flatMap((q) => q.hits ?? []);
|
|
157
|
+
const snaps = due.map((q) => q.snap).filter((x) => x >= 0);
|
|
158
|
+
c.view = { from: snaps.length ? Math.min(...snaps) : due.at(-1).tick, to: due.at(-1).tick };
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
connect(link, profile = {}) {
|
|
162
|
+
conns.push({ link, player: null, profile, queue: [], ack: -1, latest: -1, snap: -1, late: 0, claims: [], view: { from: 0, to: 0 } });
|
|
163
|
+
},
|
|
164
|
+
tick() {
|
|
165
|
+
for (const c of [...conns]) {
|
|
166
|
+
if (c.link.closed) {
|
|
167
|
+
conns.splice(conns.indexOf(c), 1);
|
|
168
|
+
if (c.player) {
|
|
169
|
+
// Caiu: fica na sala parado (input zerado) esperando voltar com o token.
|
|
170
|
+
away.set(c.player, world.frame + grace);
|
|
171
|
+
world.input.restoreLive({ values: {}, taps: [] }, c.player);
|
|
172
|
+
world.inject(NetPlayerAway, { player: c.player });
|
|
173
|
+
}
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
read(c);
|
|
177
|
+
}
|
|
178
|
+
for (const [p, until] of [...away])
|
|
179
|
+
if (world.frame >= until) {
|
|
180
|
+
away.delete(p);
|
|
181
|
+
tokens.delete(p);
|
|
182
|
+
profiles.delete(p);
|
|
183
|
+
world.inject(NetPlayerLeft, { player: p });
|
|
184
|
+
}
|
|
185
|
+
for (const c of conns)
|
|
186
|
+
if (c.player)
|
|
187
|
+
apply(c);
|
|
188
|
+
world.step(1);
|
|
189
|
+
for (const c of conns)
|
|
190
|
+
c.claims = []; // o que não foi usado neste tick não vale para o próximo
|
|
191
|
+
if (lag) {
|
|
192
|
+
trail.set(world.frame, positions(world));
|
|
193
|
+
for (const f of trail.keys())
|
|
194
|
+
if (f < world.frame - lag.maxTicks - 2)
|
|
195
|
+
trail.delete(f);
|
|
196
|
+
}
|
|
197
|
+
if (world.frame % every === 0) {
|
|
198
|
+
const state = world.netState();
|
|
199
|
+
// Eventos do intervalo (menos os internos da física e dos resources): o cliente toca o som do tiro dos outros.
|
|
200
|
+
const events = world.observe({ entityIds: [], sinceFrame: lastSnapshot }).events
|
|
201
|
+
.filter((e) => !e.name.startsWith('physics.') && e.name !== 'resource.op')
|
|
202
|
+
.map(({ frame, name, payload }) => ({ frame, name, payload }));
|
|
203
|
+
lastSnapshot = world.frame;
|
|
204
|
+
stats.snapshots++;
|
|
205
|
+
history.set(world.frame, state);
|
|
206
|
+
for (const t of history.keys())
|
|
207
|
+
if (t < world.frame - HISTORY_TICKS)
|
|
208
|
+
history.delete(t);
|
|
209
|
+
// Diferença contra o último snapshot que cada cliente confirmou (calculada uma vez por base); sem base, o estado completo.
|
|
210
|
+
const deltas = new Map();
|
|
211
|
+
for (const c of conns) {
|
|
212
|
+
if (!c.player)
|
|
213
|
+
continue;
|
|
214
|
+
const base = history.get(c.snap);
|
|
215
|
+
const head = { t: 'snapshot', tick: world.frame, ack: c.ack, buffer: c.latest - world.frame, events };
|
|
216
|
+
if (!base || c.snap >= world.frame) {
|
|
217
|
+
send(c, { ...head, state });
|
|
218
|
+
stats.full++;
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
if (!deltas.has(c.snap))
|
|
222
|
+
deltas.set(c.snap, diffState(c.snap, base, state));
|
|
223
|
+
send(c, { ...head, delta: deltas.get(c.snap) });
|
|
224
|
+
stats.deltas++;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
get players() { return [...conns.filter((c) => c.player).map((c) => c.player), ...away.keys()]; },
|
|
229
|
+
get away() { return [...away.keys()]; },
|
|
230
|
+
stats,
|
|
231
|
+
};
|
|
232
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export function connectWebSocket(url, opts = {}) {
|
|
2
|
+
return new Promise((resolve, reject) => {
|
|
3
|
+
const ws = new WebSocket(url);
|
|
4
|
+
const inbox = [];
|
|
5
|
+
let closed = false;
|
|
6
|
+
const timer = setTimeout(() => { ws.close(); reject(new Error(`net: could not connect to ${url} in ${opts.timeoutMs ?? 5000} ms (is the server running? vibe dev starts it for projects with net in vibe.config.ts)`)); }, opts.timeoutMs ?? 5000);
|
|
7
|
+
ws.addEventListener('message', (e) => { try {
|
|
8
|
+
inbox.push(JSON.parse(String(e.data)));
|
|
9
|
+
}
|
|
10
|
+
catch { /* mensagem inválida: ignora */ } });
|
|
11
|
+
ws.addEventListener('close', () => { closed = true; });
|
|
12
|
+
ws.addEventListener('error', () => { if (ws.readyState !== WebSocket.OPEN) {
|
|
13
|
+
clearTimeout(timer);
|
|
14
|
+
reject(new Error(`net: could not connect to ${url}`));
|
|
15
|
+
} });
|
|
16
|
+
ws.addEventListener('open', () => {
|
|
17
|
+
clearTimeout(timer);
|
|
18
|
+
resolve({
|
|
19
|
+
send: (m) => { if (ws.readyState === WebSocket.OPEN)
|
|
20
|
+
ws.send(JSON.stringify(m)); },
|
|
21
|
+
receive: () => inbox.splice(0),
|
|
22
|
+
close: () => { closed = true; ws.close(); },
|
|
23
|
+
get closed() { return closed; },
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibe-engine/net",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "vibe-engine multiplayer: authoritative server, prediction and reconciliation, rooms and lobby",
|
|
5
|
+
"license": "MIT OR Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/sergiobanhos/vibe-engine.git",
|
|
9
|
+
"directory": "packages/net"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/sergiobanhos/vibe-engine#readme",
|
|
12
|
+
"keywords": [
|
|
13
|
+
"game-engine",
|
|
14
|
+
"ecs",
|
|
15
|
+
"typescript",
|
|
16
|
+
"headless",
|
|
17
|
+
"ai-native",
|
|
18
|
+
"vibe-engine"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=24"
|
|
22
|
+
},
|
|
23
|
+
"type": "module",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./node": {
|
|
30
|
+
"types": "./dist/node.server.d.ts",
|
|
31
|
+
"default": "./dist/node.server.js"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@vibe-engine/core": "0.1.1",
|
|
36
|
+
"ws": "8.23.1"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@types/ws": "8.18.2",
|
|
40
|
+
"@vibe-engine/2d": "0.1.1"
|
|
41
|
+
},
|
|
42
|
+
"files": [
|
|
43
|
+
"dist",
|
|
44
|
+
"LICENSE-MIT",
|
|
45
|
+
"LICENSE-APACHE",
|
|
46
|
+
"README.md"
|
|
47
|
+
],
|
|
48
|
+
"publishConfig": {
|
|
49
|
+
"access": "public"
|
|
50
|
+
}
|
|
6
51
|
}
|