Skip to content

gitflarePublicPartly agent-ready40

orbit-duel

Real-time two-player orbital combat game on Cloudflare Workers and Durable Objects.

Add the Apache-2.0 licence0413e56
JavaScript231 lines10.2 KB
import { encodeJoin, encodeInput, encodeAck, encodePing, applySnapshot, applyUps, parseMessage } from './shared/protocol.js';import { stepShip, stepBullet, DT, WORLD } from './shared/sim.js'; const TICK_MS = 1000 / 30;const H = WORLD / 2;const wrapD = (d) => (d > H ? d - WORLD : d < -H ? d + WORLD : d);const angD = (d) => { while (d > Math.PI) d -= 2 * Math.PI; while (d < -Math.PI) d += 2 * Math.PI; return d; };const wrapP = (v) => ((v % WORLD) + WORLD) % WORLD; export function createNet(code, name, handlers, opts) {  let watching = !!(opts && opts.watch);  let lastAckAt = 0, sentSinceSnap = false;  const net = {    ws: null, id: 0, role: 'player', rtt: 0, connected: false, serverTick: 0, tick: 0,    meta: [0, 0, 0], names: {}, ups: {}, shipIds: [], me: null, bullets: [], lastSeq: 0, seq: 0,    closed: false, retry: 250,  };  const tokenKey = 'od-token-' + code;  const history = new Map();  const pool = [];  const buf = [];  const inputs = [];  const cur = { rotate: 0, thrust: 0, fire: 0 };  const sent = { rotate: 0, thrust: 0, fire: 0 };  let lastSendAt = 0, lastFrame = 0, tickOffset = 0, haveOffset = false;  const corr = { x: 0, y: 0, until: 0 };  const sim = { x: 0, y: 0, vx: 0, vy: 0, angle: 0, hp: 0, flags: 0, kills: 0 };  const meShip = { x: 0, y: 0, vx: 0, vy: 0, angle: 0, hp: 0, flags: 0, kills: 0 };  const meView = { x: 0, y: 0, vx: 0, vy: 0, angle: 0, hp: 0, flags: 0, kills: 0 };  let haveMe = false, serverMe = null, acc = 0, prevX = 0, prevY = 0, prevA = 0;   function addBullet(r) {    const b = pool.pop() || { id: 0, owner: 0, x: 0, y: 0, vx: 0, vy: 0, life: 0 };    b.id = r[0]; b.owner = r[1]; b.x = r[3]; b.y = r[4]; b.vx = r[5]; b.vy = r[6]; b.life = 1.6;    const est = Math.max(net.serverTick, r[2]);    let alive = true;    for (let t = r[2]; t < est && alive; t++) alive = stepBullet(b, DT) !== false;    if (!alive) { pool.push(b); return; }    net.bullets.push(b);  }  function removeBullet(id) {    const a = net.bullets;    for (let i = 0; i < a.length; i++) {      if (a[i].id === id) { pool.push(a[i]); a[i] = a[a.length - 1]; a.pop(); return; }    }  }  function hasBullet(id) {    for (let i = 0; i < net.bullets.length; i++) if (net.bullets[i].id === id) return true;    return false;  }  function resetBullets(recs) {    while (net.bullets.length) pool.push(net.bullets.pop());    if (recs) for (let i = 0; i < recs.length; i++) addBullet(recs[i]);  }   function setSnap(tick, snap, ups, now) {    net.tick = tick; net.serverTick = Math.max(net.serverTick, tick); net.meta = snap.meta; net.ups = ups;    history.set(tick, { snap, ups });    history.delete(tick - 64);    const off = tick * TICK_MS - now;    if (!haveOffset) { tickOffset = off; haveOffset = true; } else tickOffset += (off - tickOffset) * 0.1;    buf.push({ tick, at: now, snap });    if (buf.length > 12) buf.shift();    net.shipIds.length = 0;    for (const id in snap.ships) net.shipIds.push(+id);    const me = net.id && snap.ships[net.id];    if (me && !(me[7] & 1)) serverMe = me; else { serverMe = null; haveMe = false; net.me = null; }  }   function reconcile(now) {    if (!serverMe) return;    const s = serverMe;    sim.x = s[1]; sim.y = s[2]; sim.vx = s[3]; sim.vy = s[4]; sim.angle = s[5]; sim.hp = s[6]; sim.flags = s[7]; sim.kills = s[8];    while (inputs.length && inputs[0].seq <= net.lastSeq) inputs.shift();    for (let i = 0; i < inputs.length; i++) stepShip(sim, inputs[i], DT);    if (!haveMe) {      meShip.x = sim.x; meShip.y = sim.y; meShip.vx = sim.vx; meShip.vy = sim.vy; haveMe = true; net.me = meView; prevX = meShip.x; prevY = meShip.y; prevA = meShip.angle; acc = 0; corr.x = corr.y = 0;    } else {      const dx = wrapD(sim.x - meShip.x), dy = wrapD(sim.y - meShip.y);      if (Math.hypot(dx, dy) > 40) { meShip.x = sim.x; meShip.y = sim.y; corr.x = corr.y = 0; }      else { corr.x = dx; corr.y = dy; corr.until = now + 100; }      meShip.vx = sim.vx; meShip.vy = sim.vy;    }    meShip.angle = sim.angle; meShip.hp = sim.hp; meShip.flags = sim.flags; meShip.kills = sim.kills;    serverMe = null;  }   function open() {    const proto = location.protocol === 'https:' ? 'wss' : 'ws';    const ws = new WebSocket(proto + '://' + location.host + '/ws/' + code);    net.ws = ws;    ws.onopen = () => {      net.connected = true; net.retry = 250;      ws.send(JSON.stringify(encodeJoin(name, watching ? null : sessionStorage.getItem(tokenKey), null, watching)));      handlers.status(true);    };    ws.onmessage = (ev) => {      const m = parseMessage(ev.data);      if (!m) return;      const now = performance.now();      const t = m[0];      if (t === 'w') {        net.id = m[1]; net.role = m[4];        if (m[2]) sessionStorage.setItem(tokenKey, m[2]);        history.clear(); buf.length = 0; inputs.length = 0; haveOffset = false; haveMe = false; net.me = null;        net.serverTick = m[5];        const ex = m[7];        net.names = (ex && ex.names) || {};        resetBullets(m[8]);        const ups = {};        if (ex && ex.ups) for (const k in ex.ups) ups[k] = ex.ups[k];        setSnap(m[5], applySnapshot(null, m[6]), ups, now);        reconcile(now);        handlers.welcome(m);      } else if (t === 's') {        const h = m[2] < 0 ? null : history.get(m[2]);        if (m[2] >= 0 && !h) return;        const next = applySnapshot(h ? h.snap : null, m[4]);        const ups = m[5] !== undefined ? applyUps(h ? h.ups : null, m[5]) : (h ? h.ups : {});        if (m[6]) net.names = m[6];        net.lastSeq = m[3];        if (m[7]) resetBullets(m[7]);        setSnap(m[1], next, ups, now);        reconcile(now);        if (!sentSinceSnap && now - lastAckAt >= 100) { lastAckAt = now; ws.send(JSON.stringify(encodeAck(m[1]))); }        sentSinceSnap = false;      } else if (t === 'o') {        const r = now - m[1];        net.rtt = net.rtt ? net.rtt * 0.8 + r * 0.2 : r;      } else if (t === 'v') {        for (let i = 2; i < m.length; i++) {          const e = m[i];          if (e[0] === 'fire') { if (!hasBullet(e[1])) addBullet([e[1], e[2], e[3], e[4], e[5], e[6], e[7]]); }          else if (e[0] === 'hit' || e[0] === 'expire' || e[0] === 'rm') removeBullet(e[1]);          handlers.events(e);        }      }    };    ws.onclose = () => {      net.connected = false;      handlers.status(false);      if (net.closed) return;      setTimeout(open, net.retry);      net.retry = Math.min(net.retry * 2, 15000);    };  }   net.sendInput = (i) => {    cur.rotate = i.rotate; cur.thrust = i.thrust; cur.fire = i.fire;    if (!net.ws || net.ws.readyState !== 1 || net.role !== 'player') return;    const now = performance.now();    const changed = cur.rotate !== sent.rotate || cur.thrust !== sent.thrust || cur.fire !== sent.fire;    if (now - lastSendAt < 33 || (!changed && now - lastSendAt < 100)) return;    lastSendAt = now; sentSinceSnap = true;    sent.rotate = cur.rotate; sent.thrust = cur.thrust; sent.fire = cur.fire;    const seq = ++net.seq;    inputs.push({ seq, rotate: cur.rotate, thrust: cur.thrust, fire: cur.fire });    if (inputs.length > 90) inputs.shift();    net.ws.send(JSON.stringify(encodeInput(seq, cur.rotate, cur.thrust, cur.fire, net.tick)));  };   net.update = (now) => {    const dt = lastFrame ? Math.min(0.1, (now - lastFrame) / 1000) : 0;    lastFrame = now;    if (net.me && dt > 0) {      acc += dt;      while (acc >= DT) {        prevX = meShip.x; prevY = meShip.y; prevA = meShip.angle;        stepShip(meShip, cur, DT); acc -= DT;      }      if (corr.until > now) {        const k = Math.min(1, (dt * 1000) / Math.max(1, corr.until - now));        meShip.x += corr.x * k; meShip.y += corr.y * k; corr.x -= corr.x * k; corr.y -= corr.y * k;      }    }    if (net.me) {      const k = acc / DT;      let dx = meShip.x - prevX, dy = meShip.y - prevY, da = meShip.angle - prevA;      if (dx > H) dx -= WORLD; else if (dx < -H) dx += WORLD;      if (dy > H) dy -= WORLD; else if (dy < -H) dy += WORLD;      if (da > Math.PI) da -= 2 * Math.PI; else if (da < -Math.PI) da += 2 * Math.PI;      meView.x = wrapP(meShip.x - dx * (1 - k)); meView.y = wrapP(meShip.y - dy * (1 - k));      meView.angle = meShip.angle - da * (1 - k);      meView.vx = meShip.vx; meView.vy = meShip.vy; meView.hp = meShip.hp; meView.flags = meShip.flags; meView.kills = meShip.kills;    }    if (haveOffset) net.serverTick = Math.max(net.tick, (now + tickOffset) / TICK_MS);    const a = net.bullets;    for (let i = a.length - 1; i >= 0; i--) {      if (stepBullet(a[i], dt) === false) { pool.push(a[i]); a[i] = a[a.length - 1]; a.pop(); }    }  };   function fill(out, e) {    out.x = e[1]; out.y = e[2]; out.vx = e[3]; out.vy = e[4]; out.angle = e[5]; out.hp = e[6]; out.flags = e[7]; out.kills = e[8];  }  net.sampleShip = (id, renderTime, out) => {    const n = buf.length;    if (!n) return false;    let ai = -1;    for (let i = n - 1; i >= 0; i--) if (buf[i].at <= renderTime) { ai = i; break; }    if (ai < 0) { const f = buf[0].snap.ships[id]; if (!f) return false; fill(out, f); return true; }    const a = buf[ai], b = ai + 1 < n ? buf[ai + 1] : null;    const ea = a.snap.ships[id];    const eb = b ? b.snap.ships[id] : undefined;    if (!ea) { if (!eb) return false; fill(out, eb); return true; }    if (b && eb) {      const k = Math.min(1, Math.max(0, (renderTime - a.at) / Math.max(1, b.at - a.at)));      out.x = wrapP(ea[1] + wrapD(eb[1] - ea[1]) * k);      out.y = wrapP(ea[2] + wrapD(eb[2] - ea[2]) * k);      out.vx = ea[3] + (eb[3] - ea[3]) * k; out.vy = ea[4] + (eb[4] - ea[4]) * k;      out.angle = ea[5] + angD(eb[5] - ea[5]) * k;      out.hp = eb[6]; out.flags = eb[7]; out.kills = eb[8];      return true;    }    const t = Math.min(0.25, Math.max(0, (renderTime - a.at) / 1000));    fill(out, ea);    out.x = wrapP(ea[1] + ea[3] * t); out.y = wrapP(ea[2] + ea[4] * t);    return true;  };   net.join = (n) => {    if (n) name = n;    watching = false;    if (net.ws && net.ws.readyState === 1) net.ws.send(JSON.stringify(encodeJoin(name, sessionStorage.getItem(tokenKey), null, false)));  };  net.close = () => { net.closed = true; if (net.ws) net.ws.close(); };  setInterval(() => { if (net.ws && net.ws.readyState === 1) net.ws.send(JSON.stringify(encodePing(performance.now()))); }, 1000);  open();  return net;}