@usions/sdk 2.22.0 → 2.24.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/src/browser.js CHANGED
@@ -32,6 +32,7 @@ var Usion = (function () {
32
32
  VALUE_TOO_LARGE: 'VALUE_TOO_LARGE', // Single value over the per-value quota
33
33
  LOBBY_FULL: 'LOBBY_FULL', // Lobby at max_players
34
34
  LOBBY_CLOSED: 'LOBBY_CLOSED', // Lobby exists but is not open
35
+ WORLD_FULL: 'WORLD_FULL', // World room at max_players
35
36
  CONFLICT: 'CONFLICT', // Concurrent-write conflict; retry
36
37
  RATE_LIMITED: 'RATE_LIMITED', // Too many calls; back off (see retryAfter)
37
38
  REQUEST_TIMEOUT: 'REQUEST_TIMEOUT', // Host/parent did not reply in time
@@ -81,6 +82,7 @@ var Usion = (function () {
81
82
  [/value too large/i, ERROR_CODES.VALUE_TOO_LARGE],
82
83
  [/lobby is full/i, ERROR_CODES.LOBBY_FULL],
83
84
  [/lobby is not open/i, ERROR_CODES.LOBBY_CLOSED],
85
+ [/world room is full/i, ERROR_CODES.WORLD_FULL],
84
86
  [/not found|unknown service/i, ERROR_CODES.NOT_FOUND],
85
87
  [/conflict/i, ERROR_CODES.CONFLICT],
86
88
  [/cancelled/i, ERROR_CODES.CANCELLED],
@@ -189,7 +191,7 @@ var Usion = (function () {
189
191
  * Core Usion object with init, _post, _request
190
192
  */
191
193
  const core = {
192
- version: '2.22.0', // injected from package.json at build
194
+ version: '2.24.1', // injected from package.json at build
193
195
  config: {},
194
196
  _initialized: false,
195
197
  _initCallback: null,
@@ -269,8 +271,19 @@ var Usion = (function () {
269
271
 
270
272
  // Handle INIT message
271
273
  if (data.type === 'INIT' && data.config) {
272
- // Prevent double config - only set once
274
+ // Re-INIT = credential/state refresh, not a re-boot. Hosts re-mint the
275
+ // scoped iframe token and re-INIT before it expires (and retry failed
276
+ // mints with backoff) — dropping these left long-lived iframes 401ing
277
+ // forever once their first token raced the mint or hit the 60-min TTL.
278
+ // Merge the refreshed fields; never re-fire the init callback.
273
279
  if (self._initialized) {
280
+ if (data.config.authToken) {
281
+ self.config.authToken = data.config.authToken;
282
+ if (self.user) self.user._token = data.config.authToken;
283
+ }
284
+ if (data.config.balance !== undefined && self.wallet) {
285
+ self.wallet._balance = data.config.balance;
286
+ }
274
287
  return;
275
288
  }
276
289
 
@@ -1464,6 +1477,7 @@ var Usion = (function () {
1464
1477
  return self._connectPromise;
1465
1478
  }
1466
1479
 
1480
+ if (self._resConfigure) self._resConfigure(config); // liveness/backpressure opts → game._res
1467
1481
  self._connecting = true;
1468
1482
  self.directMode = true;
1469
1483
  self._autoReconnect = config.autoReconnect !== undefined
@@ -1574,6 +1588,7 @@ var Usion = (function () {
1574
1588
  self._sendDirect('heartbeat', {});
1575
1589
  }
1576
1590
  }, 25000);
1591
+ if (self._resOnOpen) self._resOnOpen(); // start liveness watchdog + foreground resync
1577
1592
  resolve();
1578
1593
  };
1579
1594
 
@@ -1585,6 +1600,7 @@ var Usion = (function () {
1585
1600
  };
1586
1601
 
1587
1602
  ws.onclose = function(evt) {
1603
+ if (self._resOnClose) self._resOnClose(evt); // capture close code, stop timers
1588
1604
  self.connected = false;
1589
1605
  self._joined = false;
1590
1606
  self._joinPromise = null;
@@ -1600,6 +1616,7 @@ var Usion = (function () {
1600
1616
  };
1601
1617
 
1602
1618
  ws.onmessage = function(evt) {
1619
+ if (self._res) self._res.lastInboundAt = Date.now(); // any bytes = alive
1603
1620
  self._handleDirectMessage(evt && evt.data);
1604
1621
  };
1605
1622
  });
@@ -1620,7 +1637,9 @@ var Usion = (function () {
1620
1637
  if (!self.directMode) { self._reconnecting = false; return; } // disconnected meanwhile
1621
1638
  attempt += 1;
1622
1639
  self._reconnectAttempt = attempt;
1623
- self._fetchDirectAccess({})
1640
+ // Reuse the cached room token while valid (skips the access round trip).
1641
+ var reuse = self._resCanReuseToken && self._resCanReuseToken();
1642
+ (reuse ? Promise.resolve(self.directConfig) : self._fetchDirectAccess({}))
1624
1643
  .then(function(access) { self.directConfig = access; return self._initDirectSocket(access); })
1625
1644
  .then(function() {
1626
1645
  self.connected = true;
@@ -1635,11 +1654,13 @@ var Usion = (function () {
1635
1654
  setTimeout(go, delay);
1636
1655
  });
1637
1656
  };
1638
- setTimeout(go, 500);
1657
+ setTimeout(go, 100); // fast first attempt; exponential backoff after
1639
1658
  };
1640
1659
 
1641
1660
  game._sendDirect = function(type, payload) {
1642
1661
  if (!this.directSocket || this.directSocket.readyState !== WebSocket.OPEN) return;
1662
+ // Backpressure (input frames only): hold latest while the buffer is full.
1663
+ if (type === 'input' && this._resHoldInput && this._resHoldInput(payload)) return;
1643
1664
  this._directSeq = this._directSeq + 1;
1644
1665
  this.directSocket.send(JSON.stringify({
1645
1666
  type: type,
@@ -1681,11 +1702,10 @@ var Usion = (function () {
1681
1702
  return;
1682
1703
  }
1683
1704
  if (data.type === 'pong') {
1684
- // Resolve a pending game.ping() RTT probe, if any.
1685
- if (this._pongWaiters && this._pongWaiters.length) {
1686
- const waiter = this._pongWaiters.shift();
1687
- if (waiter) waiter();
1688
- }
1705
+ // Resolve a pending game.ping() RTT probe, if any; feed the stats EWMA.
1706
+ var waiter = (this._pongWaiters && this._pongWaiters.length) ? this._pongWaiters.shift() : null;
1707
+ if (this._resOnPong) this._resOnPong(waiter);
1708
+ if (waiter) waiter();
1689
1709
  this._dispatch('sync', payload);
1690
1710
  return;
1691
1711
  }
@@ -1699,6 +1719,252 @@ var Usion = (function () {
1699
1719
  };
1700
1720
  }
1701
1721
 
1722
+ /**
1723
+ * Usion SDK Game Resilience (SDK >= 2.24) - direct-mode liveness watchdog,
1724
+ * token-reuse fast reconnect, input backpressure, and network stats/quality.
1725
+ * State lives on game._res; game-direct.js calls the small _res* hooks here.
1726
+ * Relay mode gets getNetworkStats()/onNetworkQuality() too (quality from the
1727
+ * connection-state machine; no relay RTT measurement in this module).
1728
+ */
1729
+
1730
+ /** @typedef {{probeAfterMs: number, deadAfterMs: number}} LivenessCfg */
1731
+
1732
+ /** @param {any} game @param {any} Usion */
1733
+ function applyGameResilience(game, Usion) {
1734
+ var res = {
1735
+ liveness: /** @type {LivenessCfg|null} */ ({ probeAfterMs: 4000, deadAfterMs: 12000 }),
1736
+ backpressureBytes: 8192,
1737
+ lastInboundAt: 0,
1738
+ lastProbeAt: 0,
1739
+ lastCloseCode: /** @type {number|null} */ (null),
1740
+ declaredDead: false,
1741
+ watchdogTimer: /** @type {*} */ (null),
1742
+ drainTimer: /** @type {*} */ (null),
1743
+ pendingInput: /** @type {*} */ (null),
1744
+ visHandler: /** @type {*} */ (null),
1745
+ lastVisResyncAt: 0,
1746
+ wrappedDisconnect: false,
1747
+ rtt: /** @type {number|null} */ (null),
1748
+ jitter: 0,
1749
+ quality: 'dead',
1750
+ };
1751
+ game._res = res;
1752
+
1753
+ /** EWMA (a=0.3) over ping->pong RTT samples. @param {number} sample */
1754
+ function feedRtt(sample) {
1755
+ if (!(sample >= 0)) return;
1756
+ if (res.rtt == null) { res.rtt = sample; res.jitter = 0; return; }
1757
+ res.jitter += 0.3 * (Math.abs(sample - res.rtt) - res.jitter);
1758
+ res.rtt += 0.3 * (sample - res.rtt);
1759
+ }
1760
+
1761
+ function measuredRtt() { // game.ping() samples count too (any transport)
1762
+ if (res.rtt != null) return { rtt: res.rtt, jitter: res.jitter };
1763
+ var m = game._pingMeter;
1764
+ return m && m.rtt != null ? { rtt: m.rtt, jitter: m.jitter } : { rtt: null, jitter: null };
1765
+ }
1766
+
1767
+ function computeQuality() {
1768
+ var state = game.getConnectionState ? game.getConnectionState()
1769
+ : (game.connected ? 'connected' : 'disconnected');
1770
+ if (res.declaredDead || state === 'disconnected') return 'dead';
1771
+ if (game.directMode && (!game.directSocket || game.directSocket.readyState !== 1)) return 'dead';
1772
+ var rtt = measuredRtt().rtt || 0;
1773
+ var age = (game.directMode && res.lastInboundAt) ? Date.now() - res.lastInboundAt : 0;
1774
+ return (rtt < 150 && age < 2000) ? 'good' : (rtt < 400 && age < 5000) ? 'fair' : 'poor';
1775
+ }
1776
+
1777
+ /** Dispatches networkQuality on TRANSITIONS only. */
1778
+ function evaluate() {
1779
+ var q = computeQuality();
1780
+ if (q === res.quality) return;
1781
+ var prev = res.quality;
1782
+ res.quality = q;
1783
+ game._dispatch('networkQuality', { quality: q, prev: prev, stats: game.getNetworkStats() });
1784
+ }
1785
+
1786
+ /** Cheap snapshot of tracked connection-health numbers. */
1787
+ game.getNetworkStats = function () {
1788
+ var direct = !!game.directMode;
1789
+ var s = direct ? game.directSocket : null;
1790
+ var m = measuredRtt();
1791
+ return {
1792
+ transport: direct ? 'direct' : 'relay',
1793
+ connectionState: game.getConnectionState ? game.getConnectionState() : 'disconnected',
1794
+ quality: res.quality,
1795
+ rtt: m.rtt,
1796
+ jitter: m.jitter,
1797
+ lastInboundAgeMs: (direct && res.lastInboundAt) ? Math.max(0, Date.now() - res.lastInboundAt) : null,
1798
+ bufferedAmount: s ? (s.bufferedAmount || 0) : null,
1799
+ };
1800
+ };
1801
+
1802
+ /** Quality transitions ({quality, prev, stats}); returns unsubscribe. @param {Function} callback */
1803
+ game.onNetworkQuality = function (callback) { return game._setHandler('networkQuality', callback); };
1804
+
1805
+ function stopWatchdog() {
1806
+ if (res.watchdogTimer) { clearInterval(res.watchdogTimer); res.watchdogTimer = null; }
1807
+ }
1808
+
1809
+ /** One plain RTT ping ({t}) - never {last_sequence} (that is a resync). */
1810
+ function sendProbe() {
1811
+ var s = game.directSocket;
1812
+ if (!s || s.readyState !== 1) return;
1813
+ var now = Date.now();
1814
+ var w = /** @type {any} */ (function () {}); // stats-only pong waiter
1815
+ w.sentAt = now;
1816
+ w.statsOnly = true;
1817
+ game._pongWaiters.push(w);
1818
+ res.lastProbeAt = now;
1819
+ game._sendDirect('ping', { t: now });
1820
+ }
1821
+
1822
+ function watchdogTick() {
1823
+ var s = game.directSocket;
1824
+ if (!game.directMode || !s || s.readyState !== 1) { stopWatchdog(); return; }
1825
+ if (res.liveness) {
1826
+ var age = Date.now() - res.lastInboundAt;
1827
+ if (age >= res.liveness.deadAfterMs) {
1828
+ // Silent-dead: declare + close; the onclose path then reconnects.
1829
+ res.declaredDead = true;
1830
+ stopWatchdog();
1831
+ Usion.log('Direct socket liveness timeout - declaring dead');
1832
+ evaluate();
1833
+ game._dispatch('disconnect', 'liveness_timeout');
1834
+ try { s.close(); } catch (e) { /* noop */ }
1835
+ return;
1836
+ }
1837
+ if (age >= res.liveness.probeAfterMs
1838
+ && Date.now() - res.lastProbeAt >= res.liveness.probeAfterMs) sendProbe();
1839
+ }
1840
+ evaluate();
1841
+ }
1842
+
1843
+ /** connectDirect(config) options -> clamped _res settings. @param {any} config */
1844
+ game._resConfigure = function (config) {
1845
+ if (config.liveness === false) {
1846
+ res.liveness = null;
1847
+ } else {
1848
+ var lv = (config.liveness && typeof config.liveness === 'object') ? config.liveness : {};
1849
+ var probe = isFinite(lv.probeAfterMs) ? Math.max(1000, lv.probeAfterMs) : 4000;
1850
+ var dead = isFinite(lv.deadAfterMs) ? lv.deadAfterMs : 12000;
1851
+ res.liveness = { probeAfterMs: probe, deadAfterMs: Math.max(dead, probe + 2000) };
1852
+ }
1853
+ if (config.backpressureBytes === false || config.backpressureBytes === 0) res.backpressureBytes = 0;
1854
+ else if (typeof config.backpressureBytes === 'number' && config.backpressureBytes > 0) res.backpressureBytes = config.backpressureBytes;
1855
+ };
1856
+
1857
+ /** Direct socket opened: reset state, start watchdog + foreground resync. */
1858
+ game._resOnOpen = function () {
1859
+ res.declaredDead = false;
1860
+ res.lastCloseCode = null;
1861
+ res.lastInboundAt = Date.now();
1862
+ res.lastProbeAt = 0;
1863
+ stopWatchdog();
1864
+ res.watchdogTimer = setInterval(watchdogTick, 1000);
1865
+ addVisibility();
1866
+ if (!res.wrappedDisconnect) { // clear timers even if onclose never fires
1867
+ res.wrappedDisconnect = true;
1868
+ var orig = game.disconnect;
1869
+ game.disconnect = function () { teardown(); return orig.apply(game, arguments); };
1870
+ }
1871
+ evaluate();
1872
+ };
1873
+
1874
+ /** @param {any} evt CloseEvent - code kept for the token-reuse decision. */
1875
+ game._resOnClose = function (evt) {
1876
+ res.lastCloseCode = (evt && typeof evt.code === 'number') ? evt.code : null;
1877
+ teardown();
1878
+ evaluate();
1879
+ };
1880
+
1881
+ /** Pong: feed the stats EWMA from the matched waiter. @param {any} waiter */
1882
+ game._resOnPong = function (waiter) {
1883
+ if (waiter && typeof waiter.sentAt === 'number') feedRtt(Date.now() - waiter.sentAt);
1884
+ evaluate();
1885
+ };
1886
+
1887
+ /** Reuse the cached room token on reconnect while safely un-expired. */
1888
+ game._resCanReuseToken = function () {
1889
+ if (res.lastCloseCode === 4401) return false; // auth reject -> refetch
1890
+ var cfg = game.directConfig;
1891
+ if (!cfg || !cfg.ws_url || !cfg.access_token) return false;
1892
+ var exp = parseExpiry(cfg.expires_at);
1893
+ return exp != null && exp - Date.now() > 30000;
1894
+ };
1895
+
1896
+ /**
1897
+ * Backpressure for realtime 'input' frames: while the send buffer is above
1898
+ * the threshold hold the LATEST frame only; drain when it clears.
1899
+ * @param {any} payload @returns {boolean} true = held, don't send now
1900
+ */
1901
+ game._resHoldInput = function (payload) {
1902
+ if (!res.backpressureBytes) return false;
1903
+ var s = game.directSocket;
1904
+ if (!s || (res.pendingInput == null && !(s.bufferedAmount > res.backpressureBytes))) return false;
1905
+ res.pendingInput = payload; // latest-only: newer input replaces stale
1906
+ if (!res.drainTimer) res.drainTimer = setTimeout(drainInput, 50);
1907
+ return true;
1908
+ };
1909
+
1910
+ function drainInput() {
1911
+ res.drainTimer = null;
1912
+ var s = game.directSocket;
1913
+ if (!s || s.readyState !== 1) { res.pendingInput = null; return; }
1914
+ if (res.pendingInput == null) return;
1915
+ if (s.bufferedAmount > res.backpressureBytes) { res.drainTimer = setTimeout(drainInput, 50); return; }
1916
+ var p = res.pendingInput;
1917
+ res.pendingInput = null;
1918
+ game._sendDirect('input', p);
1919
+ }
1920
+
1921
+ /** Defensive expires_at parse (ISO or epoch); null = doubt -> refetch. @param {*} v */
1922
+ function parseExpiry(v) {
1923
+ if (typeof v === 'number' && isFinite(v)) return v > 1e12 ? v : v * 1000;
1924
+ if (typeof v === 'string' && v) {
1925
+ var t = Date.parse(/[zZ]|[+-]\d\d:?\d\d$/.test(v) ? v : v + 'Z'); // bare ISO = UTC
1926
+ return isNaN(t) ? null : t;
1927
+ }
1928
+ return null;
1929
+ }
1930
+
1931
+ function teardown() {
1932
+ stopWatchdog();
1933
+ if (res.drainTimer) { clearTimeout(res.drainTimer); res.drainTimer = null; }
1934
+ res.pendingInput = null;
1935
+ removeVisibility();
1936
+ if (game._pongWaiters && game._pongWaiters.length) {
1937
+ game._pongWaiters = game._pongWaiters.filter(function (/** @type {any} */ w) { return !w.statsOnly; });
1938
+ }
1939
+ }
1940
+
1941
+ /** Foreground: probe immediately + throttled requestSync. */
1942
+ function addVisibility() {
1943
+ if (typeof document === 'undefined' || !document.addEventListener || res.visHandler) return;
1944
+ res.visHandler = function () {
1945
+ if (document.visibilityState !== 'visible' || !game.directMode || !game._joined) return;
1946
+ sendProbe();
1947
+ var now = Date.now();
1948
+ if (now - res.lastVisResyncAt >= 2000) {
1949
+ res.lastVisResyncAt = now;
1950
+ try { game.requestSync(game._lastSequence || 0); } catch (e) { /* non-fatal */ }
1951
+ }
1952
+ };
1953
+ document.addEventListener('visibilitychange', res.visHandler);
1954
+ }
1955
+
1956
+ function removeVisibility() {
1957
+ if (res.visHandler && typeof document !== 'undefined' && document.removeEventListener) {
1958
+ document.removeEventListener('visibilitychange', res.visHandler);
1959
+ }
1960
+ res.visHandler = null;
1961
+ }
1962
+
1963
+ // Re-evaluate quality on connection events (covers relay mode too).
1964
+ game.on('disconnect', evaluate);
1965
+ game.on('connectionState', evaluate);
1966
+ }
1967
+
1702
1968
  /**
1703
1969
  * Usion SDK Game Socket — Socket.IO connection management
1704
1970
  */
@@ -2182,6 +2448,30 @@ var Usion = (function () {
2182
2448
  return self._joinPromise;
2183
2449
  };
2184
2450
 
2451
+ /**
2452
+ * Place this player into a drop-in/drop-out WORLD room (SDK ≥ 2.23).
2453
+ *
2454
+ * World rooms (services tagged `world`) run continuously: players enter and
2455
+ * leave at any time instead of playing fixed matches. Placement rides the
2456
+ * matchmaking channel (works embedded AND standalone): the platform returns
2457
+ * the world you're already in, else backfills a world with space, else
2458
+ * creates a new one. On success `game.roomId` is set, so the usual
2459
+ * `connect()`+`join()` (platform relay) or `connectDirect()` (direct/hosted)
2460
+ * flow works unchanged afterwards. Rejects with MATCH_TIMEOUT after 15s.
2461
+ *
2462
+ * @param {object} [opts]
2463
+ * @param {string} [opts.serviceId] - Defaults to the current service.
2464
+ * @returns {Promise<{roomId: string, playerIds: string[]}>}
2465
+ */
2466
+ game.joinWorld = function(opts) {
2467
+ const self = this;
2468
+ opts = opts || {};
2469
+ return Usion.matchmaking._joinWorld(opts.serviceId).then(function(m) {
2470
+ self.roomId = m.roomId;
2471
+ return { roomId: m.roomId, playerIds: m.players || [] };
2472
+ });
2473
+ };
2474
+
2185
2475
  /**
2186
2476
  * Leave the current game room
2187
2477
  */
@@ -4471,6 +4761,234 @@ var Usion = (function () {
4471
4761
  return reader(bytes)();
4472
4762
  }
4473
4763
 
4764
+ /**
4765
+ * Usion SDK Netcode — Interest grid (area-of-interest spatial hash).
4766
+ *
4767
+ * Buckets entities into fixed-size cells so "who is near (x, y)?" costs a few
4768
+ * cell lookups instead of an O(N) scan — the building block for world rooms
4769
+ * where each client should only receive nearby state (AOI filtering). Pure
4770
+ * JS, no DOM/window references: the same helper runs in the browser and in a
4771
+ * Node game server producing per-player snapshots.
4772
+ *
4773
+ * const grid = Usion.netcode.createInterestGrid({ cellSize: 256 });
4774
+ * grid.upsert('p1', 120, 40); // insert or move
4775
+ * grid.query(0, 0, 300); // → ids within 300 units (circle)
4776
+ * const { entered, left, visible } = grid.observe('p1', 120, 40, 500);
4777
+ * // entered → spawn for this observer; left → despawn (diffed per observer)
4778
+ */
4779
+
4780
+ /** @typedef {string|number} InterestGridId */
4781
+
4782
+ /**
4783
+ * @param {*} id
4784
+ * @param {string} method
4785
+ * @returns {InterestGridId}
4786
+ */
4787
+ function checkId(id, method) {
4788
+ const ok = (typeof id === 'string' && id.length > 0)
4789
+ || (typeof id === 'number' && isFinite(id));
4790
+ if (!ok) {
4791
+ throw new Error('interestGrid.' + method + ': id must be a non-empty string or a finite number');
4792
+ }
4793
+ return id;
4794
+ }
4795
+
4796
+ /**
4797
+ * @param {*} value
4798
+ * @param {string} name
4799
+ * @param {string} method
4800
+ * @returns {number}
4801
+ */
4802
+ function checkFinite(value, name, method) {
4803
+ if (typeof value !== 'number' || !isFinite(value)) {
4804
+ throw new Error('interestGrid.' + method + ': ' + name + ' must be a finite number');
4805
+ }
4806
+ return value;
4807
+ }
4808
+
4809
+ /**
4810
+ * @param {*} value
4811
+ * @param {string} method
4812
+ * @returns {number}
4813
+ */
4814
+ function checkRadius(value, method) {
4815
+ checkFinite(value, 'radius', method);
4816
+ if (value < 0) throw new Error('interestGrid.' + method + ': radius must be >= 0');
4817
+ return value;
4818
+ }
4819
+
4820
+ /**
4821
+ * Create an interest grid.
4822
+ * @param {{cellSize?: number}} [opts] - cellSize (world units) defaults to 256;
4823
+ * pick roughly the typical query radius so lookups touch ~4–9 cells.
4824
+ */
4825
+ function createInterestGrid(opts) {
4826
+ opts = opts || {};
4827
+ const cellSize = opts.cellSize != null ? opts.cellSize : 256;
4828
+ if (typeof cellSize !== 'number' || !isFinite(cellSize) || cellSize <= 0) {
4829
+ throw new Error('createInterestGrid: cellSize must be a finite number > 0');
4830
+ }
4831
+
4832
+ /** @type {Map<InterestGridId, {x: number, y: number, key: string}>} */
4833
+ const entities = new Map();
4834
+ /** @type {Map<string, Set<InterestGridId>>} */
4835
+ const cells = new Map();
4836
+ // Per-observer visible sets. `prev`/`next` are swapped (never reallocated)
4837
+ // each observe() call — this runs per tick per observer.
4838
+ /** @type {Map<InterestGridId, {prev: Set<InterestGridId>, next: Set<InterestGridId>}>} */
4839
+ const observers = new Map();
4840
+
4841
+ /** @param {string} key @param {InterestGridId} id */
4842
+ function addToCell(key, id) {
4843
+ let set = cells.get(key);
4844
+ if (!set) { set = new Set(); cells.set(key, set); }
4845
+ set.add(id);
4846
+ }
4847
+
4848
+ /** @param {string} key @param {InterestGridId} id */
4849
+ function removeFromCell(key, id) {
4850
+ const set = cells.get(key);
4851
+ if (!set) return;
4852
+ set.delete(id);
4853
+ if (set.size === 0) cells.delete(key);
4854
+ }
4855
+
4856
+ /**
4857
+ * Visit every entity within `radius` of (x, y): scan the cells the circle's
4858
+ * bounding box overlaps, then apply a true circle test per entity.
4859
+ * @param {number} x @param {number} y @param {number} radius
4860
+ * @param {(id: InterestGridId) => void} visit
4861
+ */
4862
+ function forEachInRadius(x, y, radius, visit) {
4863
+ const r2 = radius * radius;
4864
+ const minCx = Math.floor((x - radius) / cellSize);
4865
+ const maxCx = Math.floor((x + radius) / cellSize);
4866
+ const minCy = Math.floor((y - radius) / cellSize);
4867
+ const maxCy = Math.floor((y + radius) / cellSize);
4868
+ for (let cx = minCx; cx <= maxCx; cx++) {
4869
+ for (let cy = minCy; cy <= maxCy; cy++) {
4870
+ const set = cells.get(cx + ',' + cy);
4871
+ if (!set) continue;
4872
+ for (const id of set) {
4873
+ const ent = entities.get(id);
4874
+ if (!ent) continue;
4875
+ const dx = ent.x - x;
4876
+ const dy = ent.y - y;
4877
+ if (dx * dx + dy * dy <= r2) visit(id);
4878
+ }
4879
+ }
4880
+ }
4881
+ }
4882
+
4883
+ return {
4884
+ /**
4885
+ * Insert an entity or move an existing one.
4886
+ * @param {InterestGridId} id @param {number} x @param {number} y
4887
+ */
4888
+ upsert: function (id, x, y) {
4889
+ checkId(id, 'upsert');
4890
+ checkFinite(x, 'x', 'upsert');
4891
+ checkFinite(y, 'y', 'upsert');
4892
+ const key = Math.floor(x / cellSize) + ',' + Math.floor(y / cellSize);
4893
+ const ent = entities.get(id);
4894
+ if (ent) {
4895
+ ent.x = x;
4896
+ ent.y = y;
4897
+ if (ent.key !== key) {
4898
+ removeFromCell(ent.key, id);
4899
+ addToCell(key, id);
4900
+ ent.key = key;
4901
+ }
4902
+ return;
4903
+ }
4904
+ entities.set(id, { x: x, y: y, key: key });
4905
+ addToCell(key, id);
4906
+ },
4907
+
4908
+ /**
4909
+ * Remove an entity. Unknown ids are a no-op.
4910
+ * @param {InterestGridId} id
4911
+ */
4912
+ remove: function (id) {
4913
+ checkId(id, 'remove');
4914
+ const ent = entities.get(id);
4915
+ if (!ent) return;
4916
+ entities.delete(id);
4917
+ removeFromCell(ent.key, id);
4918
+ },
4919
+
4920
+ /**
4921
+ * All entity ids within `radius` of (x, y) — a circle test, not just
4922
+ * cell membership.
4923
+ * @param {number} x @param {number} y @param {number} radius
4924
+ * @returns {InterestGridId[]}
4925
+ */
4926
+ query: function (x, y, radius) {
4927
+ checkFinite(x, 'x', 'query');
4928
+ checkFinite(y, 'y', 'query');
4929
+ checkRadius(radius, 'query');
4930
+ /** @type {InterestGridId[]} */
4931
+ const out = [];
4932
+ forEachInRadius(x, y, radius, function (id) { out.push(id); });
4933
+ return out;
4934
+ },
4935
+
4936
+ /**
4937
+ * Like query(), but diffed against this observer's previous observe():
4938
+ * `entered` are ids newly visible, `left` are ids no longer visible,
4939
+ * `visible` is the full current set. Drive spawn/despawn messages from
4940
+ * entered/left and per-tick snapshots from visible.
4941
+ * @param {InterestGridId} observerId @param {number} x @param {number} y @param {number} radius
4942
+ * @returns {{entered: InterestGridId[], left: InterestGridId[], visible: InterestGridId[]}}
4943
+ */
4944
+ observe: function (observerId, x, y, radius) {
4945
+ checkId(observerId, 'observe');
4946
+ checkFinite(x, 'x', 'observe');
4947
+ checkFinite(y, 'y', 'observe');
4948
+ checkRadius(radius, 'observe');
4949
+ let tracker = observers.get(observerId);
4950
+ if (!tracker) {
4951
+ tracker = { prev: new Set(), next: new Set() };
4952
+ observers.set(observerId, tracker);
4953
+ }
4954
+ const prev = tracker.prev;
4955
+ const next = tracker.next;
4956
+ next.clear();
4957
+ /** @type {InterestGridId[]} */
4958
+ const entered = [];
4959
+ /** @type {InterestGridId[]} */
4960
+ const left = [];
4961
+ /** @type {InterestGridId[]} */
4962
+ const visible = [];
4963
+ forEachInRadius(x, y, radius, function (id) {
4964
+ next.add(id);
4965
+ visible.push(id);
4966
+ if (!prev.has(id)) entered.push(id);
4967
+ });
4968
+ for (const id of prev) {
4969
+ if (!next.has(id)) left.push(id);
4970
+ }
4971
+ tracker.prev = next;
4972
+ tracker.next = prev; // reused as scratch on the next call
4973
+ return { entered: entered, left: left, visible: visible };
4974
+ },
4975
+
4976
+ /**
4977
+ * Free an observer's tracking state (call when a player leaves).
4978
+ * @param {InterestGridId} observerId
4979
+ */
4980
+ dropObserver: function (observerId) {
4981
+ checkId(observerId, 'dropObserver');
4982
+ observers.delete(observerId);
4983
+ },
4984
+
4985
+ /** @returns {number} Number of entities in the grid. */
4986
+ size: function () {
4987
+ return entities.size;
4988
+ },
4989
+ };
4990
+ }
4991
+
4474
4992
  /**
4475
4993
  * Usion SDK Game Netcode — convenience wiring of the netcode toolkit onto the
4476
4994
  * game module. These helpers ride on the existing realtime/action channels, so
@@ -4489,6 +5007,7 @@ var Usion = (function () {
4489
5007
  game.createPredictor = function (opts) { return new Predictor(opts || {}); };
4490
5008
  game.createLagCompensator = function (opts) { return new LagCompensator(opts || {}); };
4491
5009
  game.createLockstep = function (opts) { return new Lockstep(opts || {}); };
5010
+ game.createInterestGrid = function (opts) { return createInterestGrid(opts || {}); };
4492
5011
 
4493
5012
  // ── Realtime channel router ──────────────────────────────────────────────
4494
5013
  // Multiplexes realtime by action_type so replicate / mesh / mesh-network and
@@ -4774,6 +5293,7 @@ var Usion = (function () {
4774
5293
  const id = self._pingMeter.begin();
4775
5294
  let done = false;
4776
5295
  const finish = function () { if (done) return; done = true; resolve(self._pingMeter.end(id)); };
5296
+ finish.sentAt = Date.now(); // lets the pong pair feed getNetworkStats' EWMA too
4777
5297
  self._pongWaiters.push(finish);
4778
5298
  self._sendDirect('ping', { t: Date.now() });
4779
5299
  setTimeout(function () {
@@ -5112,6 +5632,7 @@ var Usion = (function () {
5112
5632
  room_assigned: 'roomAssigned',
5113
5633
  connection_state: 'connectionState',
5114
5634
  reconnected: 'reconnected',
5635
+ network_quality: 'networkQuality',
5115
5636
  };
5116
5637
 
5117
5638
  function _normalizeEventName(event) {
@@ -5326,6 +5847,8 @@ var Usion = (function () {
5326
5847
 
5327
5848
  // Apply sub-modules
5328
5849
  applyGameDirect(game, Usion);
5850
+ // Direct-mode liveness/backpressure + network stats (hooks into game-direct).
5851
+ applyGameResilience(game, Usion);
5329
5852
  applyGameSocket(game, Usion);
5330
5853
  applyGameProxy(game, Usion);
5331
5854
  applyGameMethods(game, Usion);
@@ -5588,8 +6111,12 @@ var Usion = (function () {
5588
6111
  * Usion.matchmaking.onMatch(({ roomId, players }) => { ... });
5589
6112
  */
5590
6113
 
6114
+ // World placement is a single backend round-trip (no queue wait), so the
6115
+ // bound is fixed rather than caller-supplied like find()'s opts.timeout.
6116
+ const WORLD_JOIN_TIMEOUT_MS = 15000;
6117
+
5591
6118
  function createMatchmakingModule(Usion) {
5592
- let pending = null; // active find() entry: { resolve, reject }
6119
+ let pending = null; // active placement entry: { resolve, reject }
5593
6120
  let onMatchCb = null;
5594
6121
  let bound = false;
5595
6122
 
@@ -5607,6 +6134,69 @@ var Usion = (function () {
5607
6134
  });
5608
6135
  }
5609
6136
 
6137
+ /**
6138
+ * Shared mm-channel placement used by find() (queue matches) and
6139
+ * game.joinWorld() (world backfill): register the resolver, bound the wait,
6140
+ * emit mm:join, and resolve from the immediate-placement ack
6141
+ * ({queued:false, matched:true, room_id, player_ids}) or the mm:matched
6142
+ * push — whichever arrives first.
6143
+ * @param {object} payload - mm:join payload
6144
+ * @param {number} [timeout] - ms until MATCH_TIMEOUT (falsy = wait forever)
6145
+ * @param {string} timeoutMessage
6146
+ */
6147
+ function place(payload, timeout, timeoutMessage) {
6148
+ bind();
6149
+
6150
+ if (pending) {
6151
+ const old = pending; pending = null;
6152
+ old.reject(new UsionError(ERROR_CODES.SUPERSEDED, 'Superseded by a newer find()'));
6153
+ }
6154
+
6155
+ let timer = null;
6156
+ const entry = {};
6157
+ const promise = new Promise(function (resolve, reject) {
6158
+ entry.resolve = function (r) {
6159
+ if (timer) clearTimeout(timer);
6160
+ resolve(r);
6161
+ };
6162
+ entry.reject = function (e) {
6163
+ if (timer) clearTimeout(timer);
6164
+ if (pending === entry) pending = null;
6165
+ reject(e);
6166
+ };
6167
+ });
6168
+
6169
+ // Register BEFORE emitting mm:join: when someone is already waiting in
6170
+ // the queue, mm:matched can arrive ahead of the join ack — registering
6171
+ // afterwards dropped that instant match and left find() hanging forever.
6172
+ pending = entry;
6173
+
6174
+ if (timeout > 0) {
6175
+ timer = setTimeout(function () {
6176
+ timer = null;
6177
+ Usion._backendEmit('mm:cancel', {}).catch(function () { /* best-effort dequeue */ });
6178
+ entry.reject(new UsionError(ERROR_CODES.MATCH_TIMEOUT,
6179
+ timeoutMessage + timeout + 'ms'));
6180
+ }, timeout);
6181
+ }
6182
+
6183
+ Usion._backendEmit('mm:join', payload)
6184
+ .then(function (ack) {
6185
+ // Immediate placement (world rooms): the ack itself carries the room.
6186
+ // The mm:matched push may still follow; pending is already cleared,
6187
+ // so it can't double-resolve.
6188
+ if (ack && ack.matched && ack.room_id && pending === entry) {
6189
+ pending = null;
6190
+ entry.resolve(normalize(ack));
6191
+ }
6192
+ })
6193
+ .catch(function (err) {
6194
+ if (pending === entry) entry.reject(toUsionError(err));
6195
+ });
6196
+
6197
+ return promise;
6198
+ }
6199
+
5610
6200
  return {
5611
6201
  /** Register a handler called whenever a match is found. */
5612
6202
  onMatch: function (cb) { onMatchCb = cb; bind(); },
@@ -5622,47 +6212,17 @@ var Usion = (function () {
5622
6212
  find: function (serviceId, opts) {
5623
6213
  opts = opts || {};
5624
6214
  const sid = serviceId || (Usion.config && Usion.config.serviceId);
5625
- bind();
5626
-
5627
- if (pending) {
5628
- const old = pending; pending = null;
5629
- old.reject(new UsionError(ERROR_CODES.SUPERSEDED, 'Superseded by a newer find()'));
5630
- }
5631
-
5632
- let timer = null;
5633
- const entry = {};
5634
- const promise = new Promise(function (resolve, reject) {
5635
- entry.resolve = function (r) {
5636
- if (timer) clearTimeout(timer);
5637
- resolve(r);
5638
- };
5639
- entry.reject = function (e) {
5640
- if (timer) clearTimeout(timer);
5641
- if (pending === entry) pending = null;
5642
- reject(e);
5643
- };
5644
- });
5645
-
5646
- // Register BEFORE emitting mm:join: when someone is already waiting in
5647
- // the queue, mm:matched can arrive ahead of the join ack — registering
5648
- // afterwards dropped that instant match and left find() hanging forever.
5649
- pending = entry;
5650
-
5651
- if (opts.timeout > 0) {
5652
- timer = setTimeout(function () {
5653
- timer = null;
5654
- Usion._backendEmit('mm:cancel', {}).catch(function () { /* best-effort dequeue */ });
5655
- entry.reject(new UsionError(ERROR_CODES.MATCH_TIMEOUT,
5656
- 'No match within ' + opts.timeout + 'ms'));
5657
- }, opts.timeout);
5658
- }
5659
-
5660
- Usion._backendEmit('mm:join', { service_id: sid, size: opts.size || 2 })
5661
- .catch(function (err) {
5662
- if (pending === entry) entry.reject(toUsionError(err));
5663
- });
6215
+ return place({ service_id: sid, size: opts.size || 2 }, opts.timeout, 'No match within ');
6216
+ },
5664
6217
 
5665
- return promise;
6218
+ /**
6219
+ * @private SDK-internal — use Usion.game.joinWorld(). Immediate placement
6220
+ * into a drop-in/drop-out world room over the same mm channel.
6221
+ * @param {string} [serviceId]
6222
+ */
6223
+ _joinWorld: function (serviceId) {
6224
+ const sid = serviceId || (Usion.config && Usion.config.serviceId);
6225
+ return place({ service_id: sid, mode: 'world' }, WORLD_JOIN_TIMEOUT_MS, 'No world placement within ');
5666
6226
  },
5667
6227
 
5668
6228
  /** Leave the queue / stop waiting. */
@@ -6029,12 +6589,13 @@ var Usion = (function () {
6029
6589
  * MeshNetwork — N-peer full mesh
6030
6590
  * diff / patch / quantize — JSON delta compression (id-keyed arrays)
6031
6591
  * encode / decode — compact binary codec
6592
+ * createInterestGrid — spatial hash for area-of-interest (AOI) filtering
6032
6593
  */
6033
6594
 
6034
6595
  const netcode = {
6035
6596
  SnapshotInterpolation, Vault, Predictor, Coalescer, PingMeter,
6036
6597
  MeshConnection, MeshNetwork, WebTransportConnection, NetworkSim, Lockstep, LagCompensator,
6037
- diff, patch, quantize, encode, decode,
6598
+ diff, patch, quantize, encode, decode, createInterestGrid,
6038
6599
  };
6039
6600
 
6040
6601
  /**