fix(net): interpolate between snapshots to absorb jitter (P1-6)
netfight eased to the newest snapshot with no buffer, so a jittery client's robot stalled then jumped. Render ~120 ms in the past between the two bracketing snapshots instead. Dev params ?netlag/?interp/ ?netprobe reproduce it; unit test for the interp math + a Playwright lag test (tests/e2e/netlag.spec.js).
This commit is contained in:
100
game/netfight.js
100
game/netfight.js
@@ -1,26 +1,62 @@
|
||||
/* Robot Clash - client side of a server-run live fight. No simulation here: the server steps RC.Combat;
|
||||
this sends the local input and shows the server's snapshots (already mapped to "robot 0 = me").
|
||||
|
||||
const nf = RC.NetFight({ net, seat, stats }) stats = RC.NetStats() (optional, F3 overlay)
|
||||
nf.frame(s, input, dt) send input (on change, max 30/s, at least every 0.25 s), ease the local state toward
|
||||
the newest snapshot, return the events of snapshots not seen yet
|
||||
nf.oppAway true while the opponent is disconnected (server tells us)
|
||||
nf.silentFor seconds since the last snapshot (connection trouble)
|
||||
nf.stop() */
|
||||
Entity interpolation: snapshots (20 Hz) are buffered and rendered ~INTERP_DELAY ms in the past, between the two
|
||||
snapshots bracketing the render time. This absorbs jitter (uneven arrival) so the robot does not jump - the old
|
||||
"ease to the newest snapshot" had no buffer and jumped whenever a snapshot arrived late.
|
||||
|
||||
const nf = RC.NetFight({ net, seat, stats, interp, lag })
|
||||
interp interpolation delay in ms (default 100); lag = { base, jit, seed } delays incoming snapshots (dev only)
|
||||
nf.frame(s, input, dt) send input, show the interpolated world, return not-yet-seen events
|
||||
nf.oppAway / nf.silentFor / nf.stop()
|
||||
Pure, Node-testable: RC.NetFight.pickFrames(buf, renderTime), RC.NetFight.lerpRobot(da, db, k) */
|
||||
(function (root) {
|
||||
'use strict';
|
||||
const RC = (root.RC = root.RC || {});
|
||||
const SEND_MIN = 1 / 30, SEND_KEEP = 0.25;
|
||||
const SEND_MIN = 1 / 30, SEND_KEEP = 0.25, INTERP_DEFAULT = 120, BUF_MAX = 30;
|
||||
const EASE = ['x', 'z', 'y'], ANG = ['a', 'turretA'];
|
||||
const wrap = a => { while (a > Math.PI) a -= 2 * Math.PI; while (a < -Math.PI) a += 2 * Math.PI; return a; };
|
||||
const mul = s => { let a = (s >>> 0) || 1; return () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; };
|
||||
|
||||
// buf = [{ at, tick, snap }] sorted by at/tick ascending. Pick the snapshot reached by renderTime (a) and the
|
||||
// next one (b), with the fraction between them. Past the newest -> hold the newest (a === b, frac 1).
|
||||
function pickFrames(buf, renderTime) {
|
||||
if (!buf.length) return null;
|
||||
let a = buf[0], b = null;
|
||||
for (let i = 0; i < buf.length; i++) { if (buf[i].at <= renderTime) a = buf[i]; else { b = buf[i]; break; } }
|
||||
const span = b ? (b.at - a.at) : 0;
|
||||
const frac = b && span > 0 ? Math.min(1, Math.max(0, (renderTime - a.at) / span)) : (b ? 0 : 1);
|
||||
return { a, b: b || a, frac };
|
||||
}
|
||||
// blend two robot snapshots: positions/angles interpolate, discrete fields come from the reached snapshot (da)
|
||||
function lerpRobot(da, db, k) {
|
||||
const r = {};
|
||||
for (const f of (RC.Proto ? RC.Proto.RF : Object.keys(da))) if (da[f] !== undefined && !EASE.includes(f) && !ANG.includes(f)) r[f] = da[f];
|
||||
for (const f of EASE) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + (db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
|
||||
for (const f of ANG) { if (typeof da[f] === 'number' && typeof db[f] === 'number') r[f] = da[f] + wrap(db[f] - da[f]) * k; else if (typeof da[f] === 'number') r[f] = da[f]; }
|
||||
r.lost = Object.assign({}, da.lost); r.lostW = (da.lostW || []).slice(); r.W = (da.W || []).map(w => Object.assign({}, w));
|
||||
return r;
|
||||
}
|
||||
RC.NetFight = (opt) => {
|
||||
const sock = opt.net.socket, seat = opt.seat;
|
||||
let latest = null, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
|
||||
const stats = opt.stats || null; // RC.NetStats for the F3 overlay (optional)
|
||||
const DELAY = opt.interp > 0 ? opt.interp : INTERP_DEFAULT;
|
||||
const lag = opt.lag && opt.lag.base >= 0 ? opt.lag : null, rng = lag ? mul(lag.seed || 1) : null;
|
||||
const stats = opt.stats || null;
|
||||
const buf = []; // in-order snapshot buffer
|
||||
let newest = null, lastTick = -1, seenTick = -1, seq = 0, sendT = 0, keepT = 0, prev = null, lastSnap = Date.now();
|
||||
|
||||
function accept(m) { // a snapshot arrived (possibly delayed by the dev lag injector)
|
||||
const snap = RC.Proto.toLocal(seat, m);
|
||||
lastSnap = Date.now(); newest = snap;
|
||||
if (stats) stats.snap(snap, m._bytes, performance.now());
|
||||
if (m.tick <= lastTick) return; // out of order (rare) -> drop, keep the buffer monotonic
|
||||
lastTick = m.tick;
|
||||
buf.push({ at: Date.now(), tick: m.tick, snap });
|
||||
while (buf.length > BUF_MAX) buf.shift();
|
||||
}
|
||||
const off = sock.on('snap', m => {
|
||||
latest = RC.Proto.toLocal(seat, m); lastSnap = Date.now();
|
||||
if (stats) stats.snap(latest, m._bytes, performance.now());
|
||||
if (!lag) return accept(m);
|
||||
setTimeout(() => accept(m), Math.max(0, lag.base + (rng() * 2 - 1) * lag.jit));
|
||||
});
|
||||
|
||||
const changed = i => !prev || i.throttle !== prev.throttle || i.turn !== prev.turn || i.fire !== prev.fire || i.fire2 !== prev.fire2 || i.fire3 !== prev.fire3;
|
||||
@@ -31,38 +67,36 @@
|
||||
if (sock.send(Object.assign({ t: 'input', seq: ++seq }, i))) { prev = i; sendT = SEND_MIN; keepT = SEND_KEEP; if (stats) stats.inputSent(seq, performance.now()); }
|
||||
}
|
||||
|
||||
function applyRobot(r, d, k) {
|
||||
for (const f of EASE) if (typeof d[f] === 'number') r[f] += (d[f] - r[f]) * k;
|
||||
for (const f of ANG) if (typeof d[f] === 'number') r[f] += wrap(d[f] - r[f]) * k;
|
||||
for (const f of RC.Proto.RF) if (!EASE.includes(f) && !ANG.includes(f) && d[f] !== undefined) r[f] = d[f];
|
||||
if (d.lost) r.lost = Object.assign(r.lost || {}, d.lost);
|
||||
if (d.lostW) r.lostW = d.lostW.slice();
|
||||
if (d.W && r.W) d.W.forEach((w, i) => { if (r.W[i]) Object.assign(r.W[i], w); });
|
||||
}
|
||||
const applyRobot = (r, d) => { Object.assign(r, d); };
|
||||
const syncList = (dst, src, def) => { dst.length = src.length; for (let i = 0; i < src.length; i++) dst[i] = Object.assign(dst[i] || Object.assign({}, def), src[i]); };
|
||||
|
||||
function frame(s, inp, dt) {
|
||||
sendInput(inp, dt);
|
||||
if (!latest) return [];
|
||||
const n = latest, k = Math.min(1, dt * 14);
|
||||
s.t = n.time; s.left = n.left; s.pitOpen = n.pitOpen; s.pitAlarm = n.pitAlarm; s.endIn = n.endIn;
|
||||
s.press.st = n.press.st; s.press.y = n.press.y;
|
||||
Object.assign(s.crane, n.crane);
|
||||
syncList(s.rockets, n.rockets, { sp: 6, t: 3 });
|
||||
syncList(s.mines, n.mines, { r: 0.85 });
|
||||
applyRobot(s.robots[0], n.robots[0], k);
|
||||
applyRobot(s.robots[1], n.robots[1], k);
|
||||
if (n.result) s.result = n.result;
|
||||
if (n.tick === seenTick) return [];
|
||||
seenTick = n.tick;
|
||||
return n.ev || [];
|
||||
if (!buf.length) return [];
|
||||
const renderTime = Date.now() - DELAY;
|
||||
const fr = pickFrames(buf, renderTime), na = fr.a.snap, nb = fr.b.snap, k = fr.frac;
|
||||
s.t = na.time; s.left = na.left; s.pitOpen = na.pitOpen; s.pitAlarm = na.pitAlarm; s.endIn = na.endIn;
|
||||
s.press.st = na.press.st; s.press.y = na.press.y;
|
||||
Object.assign(s.crane, na.crane);
|
||||
syncList(s.rockets, na.rockets, { sp: 6, t: 3 });
|
||||
syncList(s.mines, na.mines, { r: 0.85 });
|
||||
applyRobot(s.robots[0], lerpRobot(na.robots[0], nb.robots[0], k));
|
||||
applyRobot(s.robots[1], lerpRobot(na.robots[1], nb.robots[1], k));
|
||||
if (na.result) s.result = na.result;
|
||||
while (buf.length > 2 && buf[1].at <= renderTime) buf.shift(); // keep one snapshot older than renderTime
|
||||
if (fr.a.tick === seenTick) return [];
|
||||
seenTick = fr.a.tick;
|
||||
return na.ev || [];
|
||||
}
|
||||
|
||||
return {
|
||||
frame,
|
||||
get oppAway() { return !!(latest && latest.away && latest.away[1]); },
|
||||
get oppAway() { return !!(newest && newest.away && newest.away[1]); },
|
||||
get silentFor() { return (Date.now() - lastSnap) / 1000; },
|
||||
stop() { off(); },
|
||||
};
|
||||
};
|
||||
RC.NetFight.pickFrames = pickFrames;
|
||||
RC.NetFight.lerpRobot = lerpRobot;
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = RC;
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
|
||||
Reference in New Issue
Block a user