@vibe-engine/net 0.1.1 → 0.1.2
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/dist/client.d.ts +5 -0
- package/dist/client.js +74 -2
- package/dist/components.d.ts +9 -0
- package/dist/components.js +11 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/protocol.d.ts +2 -0
- package/dist/server.js +3 -2
- package/package.json +3 -3
package/dist/client.d.ts
CHANGED
|
@@ -18,6 +18,11 @@ export interface NetClientOptions {
|
|
|
18
18
|
};
|
|
19
19
|
/** Ticks de input que o cliente tenta manter na fila do servidor. Padrão 2. */
|
|
20
20
|
targetBuffer?: number;
|
|
21
|
+
/**
|
|
22
|
+
* Ticks no passado em que as entidades dos outros jogadores (`NetOwner`) são desenhadas, deslizando
|
|
23
|
+
* entre snapshots reais. Padrão 6 (100 ms a 60 Hz, dois intervalos de snapshot). 0 desliga.
|
|
24
|
+
*/
|
|
25
|
+
interpolationTicks?: number;
|
|
21
26
|
/** Relógio em ms para o ping e os intervalos entre snapshots (padrão `performance.now`; testes passam o relógio virtual). */
|
|
22
27
|
now?: () => number;
|
|
23
28
|
}
|
package/dist/client.js
CHANGED
|
@@ -55,11 +55,78 @@ export function createNetClient(world, link, opts = {}) {
|
|
|
55
55
|
const values = world.input.sampled(player);
|
|
56
56
|
history.set(tick, values);
|
|
57
57
|
const hits = claims.get(tick);
|
|
58
|
-
link.send({ t: 'input', tick, values, snap: snapAck, ...(hits?.length ? { hits } : {}) });
|
|
58
|
+
link.send({ t: 'input', tick, values, snap: snapAck, ...(hits?.length ? { hits, ...(renderTick >= 0 && delay ? { view: Math.floor(renderTick) } : {}) } : {}) });
|
|
59
|
+
};
|
|
60
|
+
// Interpolação das entidades dos outros jogadores: a posição desenhada é a do servidor no tick
|
|
61
|
+
// `renderTick` (entre dois snapshots), aplicada como deslocamento visual sobre a simulação prevista.
|
|
62
|
+
// Assim a mira (raycast/overlap com `by`) e os rótulos usam o que a tela mostra, sem tocar no estado.
|
|
63
|
+
const delay = opts.interpolationTicks ?? 6;
|
|
64
|
+
let renderTick = -1;
|
|
65
|
+
const statePositions = new Map();
|
|
66
|
+
const posOf = (tick) => {
|
|
67
|
+
let m = statePositions.get(tick);
|
|
68
|
+
if (m)
|
|
69
|
+
return m;
|
|
70
|
+
m = new Map();
|
|
71
|
+
for (const [id, e] of states.get(tick)?.entities ?? []) {
|
|
72
|
+
const owner = e.components.NetOwner?.player;
|
|
73
|
+
if (!owner)
|
|
74
|
+
continue;
|
|
75
|
+
const t2 = e.components.Transform2D;
|
|
76
|
+
const t3 = e.components.Transform3D?.position;
|
|
77
|
+
if (t2)
|
|
78
|
+
m.set(id, { x: t2.x, y: t2.y, z: 0, owner });
|
|
79
|
+
else if (t3)
|
|
80
|
+
m.set(id, { ...t3, owner });
|
|
81
|
+
}
|
|
82
|
+
statePositions.set(tick, m);
|
|
83
|
+
return m;
|
|
84
|
+
};
|
|
85
|
+
const interpolated = new Set();
|
|
86
|
+
const interpolate = () => {
|
|
87
|
+
interpolated.clear();
|
|
88
|
+
if (!delay || !player)
|
|
89
|
+
return;
|
|
90
|
+
const ticks = [...states.keys()].sort((a, b) => a - b);
|
|
91
|
+
const newest = ticks.at(-1);
|
|
92
|
+
if (newest === undefined)
|
|
93
|
+
return;
|
|
94
|
+
const target = newest - delay;
|
|
95
|
+
// O relógio de desenho anda 1 tick por tick; se escorregar muito (pico, aba dormindo), volta ao alvo.
|
|
96
|
+
renderTick = renderTick < 0 || Math.abs(renderTick + 1 - target) > delay ? target : Math.min(renderTick + 1, newest);
|
|
97
|
+
let a = ticks[0], b;
|
|
98
|
+
for (const t of ticks) {
|
|
99
|
+
if (t <= renderTick)
|
|
100
|
+
a = t;
|
|
101
|
+
else {
|
|
102
|
+
b = t;
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (a > renderTick)
|
|
107
|
+
return;
|
|
108
|
+
const pa = posOf(a), pb = b !== undefined ? posOf(b) : null;
|
|
109
|
+
const k = b !== undefined ? (renderTick - a) / (b - a) : 0;
|
|
110
|
+
const now = positions(world);
|
|
111
|
+
for (const [id, p] of pa) {
|
|
112
|
+
if (p.owner === player)
|
|
113
|
+
continue;
|
|
114
|
+
const cur = now.get(id);
|
|
115
|
+
if (!cur)
|
|
116
|
+
continue;
|
|
117
|
+
const q = pb?.get(id);
|
|
118
|
+
// Teletransporte (respawn) entre os dois snapshots: não desliza pelo mapa, pula para o novo.
|
|
119
|
+
const far = q ? Math.hypot(q.x - p.x, q.y - p.y, q.z - p.z) > (cur.m ? 2 : 48) : false;
|
|
120
|
+
const at = !q ? p : far ? (k < 0.5 ? p : q) : { x: p.x + (q.x - p.x) * k, y: p.y + (q.y - p.y) * k, z: p.z + (q.z - p.z) * k };
|
|
121
|
+
world.visualOffsets.set(id, { x: at.x - cur.x, y: at.y - cur.y, z: at.z - cur.z });
|
|
122
|
+
interpolated.add(id);
|
|
123
|
+
}
|
|
59
124
|
};
|
|
60
125
|
// Posições antes e depois da reconciliação: a diferença vira deslocamento visual que some em ~0,1 s.
|
|
61
126
|
const smooth = (before) => {
|
|
62
127
|
for (const [id, now] of positions(world)) {
|
|
128
|
+
if (interpolated.has(id))
|
|
129
|
+
continue; // desenhada pela interpolação, não pela correção
|
|
63
130
|
const was = before.get(id);
|
|
64
131
|
if (!was)
|
|
65
132
|
continue;
|
|
@@ -147,8 +214,10 @@ export function createNetClient(world, link, opts = {}) {
|
|
|
147
214
|
states.set(m.tick, state);
|
|
148
215
|
snapAck = Math.max(snapAck, m.tick);
|
|
149
216
|
for (const t of states.keys())
|
|
150
|
-
if (t < m.tick - 180)
|
|
217
|
+
if (t < m.tick - 180) {
|
|
151
218
|
states.delete(t);
|
|
219
|
+
statePositions.delete(t);
|
|
220
|
+
}
|
|
152
221
|
if (!latest || m.tick > latest.tick) {
|
|
153
222
|
latest = { tick: m.tick, ack: m.ack, buffer: m.buffer, state };
|
|
154
223
|
stats.snapshots++;
|
|
@@ -222,12 +291,15 @@ export function createNetClient(world, link, opts = {}) {
|
|
|
222
291
|
stepOnce();
|
|
223
292
|
// Correção visual some em ~0,3 s (×0,88 por tick a 60 Hz; 0,82 deixava o inimigo dando trancos ao virar), com ou sem tela: a mira (raycast com `by`) usa a posição da tela.
|
|
224
293
|
for (const [id, o] of world.visualOffsets) {
|
|
294
|
+
if (interpolated.has(id))
|
|
295
|
+
continue;
|
|
225
296
|
o.x *= SMOOTH;
|
|
226
297
|
o.y *= SMOOTH;
|
|
227
298
|
o.z *= SMOOTH;
|
|
228
299
|
if (Math.abs(o.x) + Math.abs(o.y) + Math.abs(o.z) < 0.01)
|
|
229
300
|
world.visualOffsets.delete(id);
|
|
230
301
|
}
|
|
302
|
+
interpolate();
|
|
231
303
|
},
|
|
232
304
|
input: {
|
|
233
305
|
set: (action, value) => { if (player)
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* De quem é a entidade (o lutador, a arma, as balas de um jogador). No cliente desse jogador
|
|
3
|
+
* ela é prevista (resposta na hora); nos outros clientes ela é desenhada interpolada entre
|
|
4
|
+
* posições reais do servidor, ~100 ms no passado: o inimigo desliza em vez de ser corrigido
|
|
5
|
+
* a cada mudança de direção. Sem `NetOwner`, a entidade segue a simulação prevista.
|
|
6
|
+
*/
|
|
7
|
+
export declare const NetOwner: import("@vibe-engine/core").ComponentDef<import("@vibe-engine/core").InferFields<{
|
|
8
|
+
player: import("@vibe-engine/core").Field<string>;
|
|
9
|
+
}>>;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Componentes de rede que o jogo põe nas entidades (código shared). */
|
|
2
|
+
import { defineComponent, t } from '@vibe-engine/core';
|
|
3
|
+
/**
|
|
4
|
+
* De quem é a entidade (o lutador, a arma, as balas de um jogador). No cliente desse jogador
|
|
5
|
+
* ela é prevista (resposta na hora); nos outros clientes ela é desenhada interpolada entre
|
|
6
|
+
* posições reais do servidor, ~100 ms no passado: o inimigo desliza em vez de ser corrigido
|
|
7
|
+
* a cada mudança de direção. Sem `NetOwner`, a entidade segue a simulação prevista.
|
|
8
|
+
*/
|
|
9
|
+
export const NetOwner = defineComponent('NetOwner', {
|
|
10
|
+
player: t.string({ doc: 'id do jogador na rede (p1, p2...)' }),
|
|
11
|
+
});
|
package/dist/index.d.ts
CHANGED
|
@@ -13,3 +13,4 @@ export { defineRoom, MAX_PROFILE_BYTES, NetListRooms, NetJoinRoom, NetRoomsListe
|
|
|
13
13
|
export { createRoomHub, type RoomHub, type RoomHubOptions } from './hub.ts';
|
|
14
14
|
export { createRoomClient, type RoomClient, type RoomClientOptions, type RoomSession } from './room-client.ts';
|
|
15
15
|
export { netDebugLines } from './debug.ts';
|
|
16
|
+
export { NetOwner } from './components.ts';
|
package/dist/index.js
CHANGED
|
@@ -13,3 +13,4 @@ export { defineRoom, MAX_PROFILE_BYTES, NetListRooms, NetJoinRoom, NetRoomsListe
|
|
|
13
13
|
export { createRoomHub } from './hub.js';
|
|
14
14
|
export { createRoomClient } from './room-client.js';
|
|
15
15
|
export { netDebugLines } from './debug.js';
|
|
16
|
+
export { NetOwner } from './components.js';
|
package/dist/protocol.d.ts
CHANGED
|
@@ -38,12 +38,14 @@ export type ClientMessage =
|
|
|
38
38
|
/** Input amostrado de um tick do cliente (o cliente roda à frente do servidor). */
|
|
39
39
|
/** `snap`: último snapshot que o cliente tem inteiro (base para a diferença; -1 = mande o estado completo). */
|
|
40
40
|
/** `hits`: o que o jogador viu acertar neste tick (uma lista por consulta com `by`, em ordem) — lag compensation. */
|
|
41
|
+
/** `view`: tick do servidor em que os outros jogadores estavam desenhados (interpolação): a lag compensation aceita acertos desde ali. */
|
|
41
42
|
| {
|
|
42
43
|
t: 'input';
|
|
43
44
|
tick: number;
|
|
44
45
|
values: Record<string, InputValue>;
|
|
45
46
|
snap?: number;
|
|
46
47
|
hits?: HitClaim[][];
|
|
48
|
+
view?: number;
|
|
47
49
|
}
|
|
48
50
|
/** Medida de ping: o servidor devolve o mesmo `id` na hora. */
|
|
49
51
|
| {
|
package/dist/server.js
CHANGED
|
@@ -124,7 +124,7 @@ export function createNetServer(world, opts = {}) {
|
|
|
124
124
|
send(c, { t: 'pong', id: m.id, late: c.late });
|
|
125
125
|
}
|
|
126
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 } : {}) });
|
|
127
|
+
c.queue.push({ tick: m.tick, values: m.values, snap: typeof m.snap === 'number' ? m.snap : -1, ...(Number.isInteger(m.view) ? { view: m.view } : {}), ...(validHits(m.hits) ? { hits: m.hits } : {}) });
|
|
128
128
|
if (typeof m.snap === 'number')
|
|
129
129
|
c.snap = m.snap;
|
|
130
130
|
c.latest = Math.max(c.latest, m.tick);
|
|
@@ -154,7 +154,8 @@ export function createNetServer(world, opts = {}) {
|
|
|
154
154
|
}
|
|
155
155
|
c.ack = Math.max(c.ack, due.at(-1).tick);
|
|
156
156
|
c.claims = due.flatMap((q) => q.hits ?? []);
|
|
157
|
-
|
|
157
|
+
// O que o jogador via: o snapshot mais novo que tinha, ou o tick em que desenhava os outros (interpolação, no passado).
|
|
158
|
+
const snaps = due.map((q) => (q.view !== undefined && q.view >= 0 ? Math.min(q.view, q.snap >= 0 ? q.snap : q.view) : q.snap)).filter((x) => x >= 0);
|
|
158
159
|
c.view = { from: snaps.length ? Math.min(...snaps) : due.at(-1).tick, to: due.at(-1).tick };
|
|
159
160
|
}
|
|
160
161
|
return {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibe-engine/net",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "vibe-engine multiplayer: authoritative server, prediction and reconciliation, rooms and lobby",
|
|
5
5
|
"license": "MIT OR Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -32,12 +32,12 @@
|
|
|
32
32
|
}
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@vibe-engine/core": "0.1.
|
|
35
|
+
"@vibe-engine/core": "0.1.2",
|
|
36
36
|
"ws": "8.23.1"
|
|
37
37
|
},
|
|
38
38
|
"devDependencies": {
|
|
39
39
|
"@types/ws": "8.18.2",
|
|
40
|
-
"@vibe-engine/2d": "0.1.
|
|
40
|
+
"@vibe-engine/2d": "0.1.2"
|
|
41
41
|
},
|
|
42
42
|
"files": [
|
|
43
43
|
"dist",
|