@usions/sdk 2.22.0 → 2.24.0

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.
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Usion SDK Netcode — Interest grid (area-of-interest spatial hash).
3
+ *
4
+ * Buckets entities into fixed-size cells so "who is near (x, y)?" costs a few
5
+ * cell lookups instead of an O(N) scan — the building block for world rooms
6
+ * where each client should only receive nearby state (AOI filtering). Pure
7
+ * JS, no DOM/window references: the same helper runs in the browser and in a
8
+ * Node game server producing per-player snapshots.
9
+ *
10
+ * const grid = Usion.netcode.createInterestGrid({ cellSize: 256 });
11
+ * grid.upsert('p1', 120, 40); // insert or move
12
+ * grid.query(0, 0, 300); // → ids within 300 units (circle)
13
+ * const { entered, left, visible } = grid.observe('p1', 120, 40, 500);
14
+ * // entered → spawn for this observer; left → despawn (diffed per observer)
15
+ */
16
+
17
+ /** @typedef {string|number} InterestGridId */
18
+
19
+ /**
20
+ * @param {*} id
21
+ * @param {string} method
22
+ * @returns {InterestGridId}
23
+ */
24
+ function checkId(id, method) {
25
+ const ok = (typeof id === 'string' && id.length > 0)
26
+ || (typeof id === 'number' && isFinite(id));
27
+ if (!ok) {
28
+ throw new Error('interestGrid.' + method + ': id must be a non-empty string or a finite number');
29
+ }
30
+ return id;
31
+ }
32
+
33
+ /**
34
+ * @param {*} value
35
+ * @param {string} name
36
+ * @param {string} method
37
+ * @returns {number}
38
+ */
39
+ function checkFinite(value, name, method) {
40
+ if (typeof value !== 'number' || !isFinite(value)) {
41
+ throw new Error('interestGrid.' + method + ': ' + name + ' must be a finite number');
42
+ }
43
+ return value;
44
+ }
45
+
46
+ /**
47
+ * @param {*} value
48
+ * @param {string} method
49
+ * @returns {number}
50
+ */
51
+ function checkRadius(value, method) {
52
+ checkFinite(value, 'radius', method);
53
+ if (value < 0) throw new Error('interestGrid.' + method + ': radius must be >= 0');
54
+ return value;
55
+ }
56
+
57
+ /**
58
+ * Create an interest grid.
59
+ * @param {{cellSize?: number}} [opts] - cellSize (world units) defaults to 256;
60
+ * pick roughly the typical query radius so lookups touch ~4–9 cells.
61
+ */
62
+ export function createInterestGrid(opts) {
63
+ opts = opts || {};
64
+ const cellSize = opts.cellSize != null ? opts.cellSize : 256;
65
+ if (typeof cellSize !== 'number' || !isFinite(cellSize) || cellSize <= 0) {
66
+ throw new Error('createInterestGrid: cellSize must be a finite number > 0');
67
+ }
68
+
69
+ /** @type {Map<InterestGridId, {x: number, y: number, key: string}>} */
70
+ const entities = new Map();
71
+ /** @type {Map<string, Set<InterestGridId>>} */
72
+ const cells = new Map();
73
+ // Per-observer visible sets. `prev`/`next` are swapped (never reallocated)
74
+ // each observe() call — this runs per tick per observer.
75
+ /** @type {Map<InterestGridId, {prev: Set<InterestGridId>, next: Set<InterestGridId>}>} */
76
+ const observers = new Map();
77
+
78
+ /** @param {string} key @param {InterestGridId} id */
79
+ function addToCell(key, id) {
80
+ let set = cells.get(key);
81
+ if (!set) { set = new Set(); cells.set(key, set); }
82
+ set.add(id);
83
+ }
84
+
85
+ /** @param {string} key @param {InterestGridId} id */
86
+ function removeFromCell(key, id) {
87
+ const set = cells.get(key);
88
+ if (!set) return;
89
+ set.delete(id);
90
+ if (set.size === 0) cells.delete(key);
91
+ }
92
+
93
+ /**
94
+ * Visit every entity within `radius` of (x, y): scan the cells the circle's
95
+ * bounding box overlaps, then apply a true circle test per entity.
96
+ * @param {number} x @param {number} y @param {number} radius
97
+ * @param {(id: InterestGridId) => void} visit
98
+ */
99
+ function forEachInRadius(x, y, radius, visit) {
100
+ const r2 = radius * radius;
101
+ const minCx = Math.floor((x - radius) / cellSize);
102
+ const maxCx = Math.floor((x + radius) / cellSize);
103
+ const minCy = Math.floor((y - radius) / cellSize);
104
+ const maxCy = Math.floor((y + radius) / cellSize);
105
+ for (let cx = minCx; cx <= maxCx; cx++) {
106
+ for (let cy = minCy; cy <= maxCy; cy++) {
107
+ const set = cells.get(cx + ',' + cy);
108
+ if (!set) continue;
109
+ for (const id of set) {
110
+ const ent = entities.get(id);
111
+ if (!ent) continue;
112
+ const dx = ent.x - x;
113
+ const dy = ent.y - y;
114
+ if (dx * dx + dy * dy <= r2) visit(id);
115
+ }
116
+ }
117
+ }
118
+ }
119
+
120
+ return {
121
+ /**
122
+ * Insert an entity or move an existing one.
123
+ * @param {InterestGridId} id @param {number} x @param {number} y
124
+ */
125
+ upsert: function (id, x, y) {
126
+ checkId(id, 'upsert');
127
+ checkFinite(x, 'x', 'upsert');
128
+ checkFinite(y, 'y', 'upsert');
129
+ const key = Math.floor(x / cellSize) + ',' + Math.floor(y / cellSize);
130
+ const ent = entities.get(id);
131
+ if (ent) {
132
+ ent.x = x;
133
+ ent.y = y;
134
+ if (ent.key !== key) {
135
+ removeFromCell(ent.key, id);
136
+ addToCell(key, id);
137
+ ent.key = key;
138
+ }
139
+ return;
140
+ }
141
+ entities.set(id, { x: x, y: y, key: key });
142
+ addToCell(key, id);
143
+ },
144
+
145
+ /**
146
+ * Remove an entity. Unknown ids are a no-op.
147
+ * @param {InterestGridId} id
148
+ */
149
+ remove: function (id) {
150
+ checkId(id, 'remove');
151
+ const ent = entities.get(id);
152
+ if (!ent) return;
153
+ entities.delete(id);
154
+ removeFromCell(ent.key, id);
155
+ },
156
+
157
+ /**
158
+ * All entity ids within `radius` of (x, y) — a circle test, not just
159
+ * cell membership.
160
+ * @param {number} x @param {number} y @param {number} radius
161
+ * @returns {InterestGridId[]}
162
+ */
163
+ query: function (x, y, radius) {
164
+ checkFinite(x, 'x', 'query');
165
+ checkFinite(y, 'y', 'query');
166
+ checkRadius(radius, 'query');
167
+ /** @type {InterestGridId[]} */
168
+ const out = [];
169
+ forEachInRadius(x, y, radius, function (id) { out.push(id); });
170
+ return out;
171
+ },
172
+
173
+ /**
174
+ * Like query(), but diffed against this observer's previous observe():
175
+ * `entered` are ids newly visible, `left` are ids no longer visible,
176
+ * `visible` is the full current set. Drive spawn/despawn messages from
177
+ * entered/left and per-tick snapshots from visible.
178
+ * @param {InterestGridId} observerId @param {number} x @param {number} y @param {number} radius
179
+ * @returns {{entered: InterestGridId[], left: InterestGridId[], visible: InterestGridId[]}}
180
+ */
181
+ observe: function (observerId, x, y, radius) {
182
+ checkId(observerId, 'observe');
183
+ checkFinite(x, 'x', 'observe');
184
+ checkFinite(y, 'y', 'observe');
185
+ checkRadius(radius, 'observe');
186
+ let tracker = observers.get(observerId);
187
+ if (!tracker) {
188
+ tracker = { prev: new Set(), next: new Set() };
189
+ observers.set(observerId, tracker);
190
+ }
191
+ const prev = tracker.prev;
192
+ const next = tracker.next;
193
+ next.clear();
194
+ /** @type {InterestGridId[]} */
195
+ const entered = [];
196
+ /** @type {InterestGridId[]} */
197
+ const left = [];
198
+ /** @type {InterestGridId[]} */
199
+ const visible = [];
200
+ forEachInRadius(x, y, radius, function (id) {
201
+ next.add(id);
202
+ visible.push(id);
203
+ if (!prev.has(id)) entered.push(id);
204
+ });
205
+ for (const id of prev) {
206
+ if (!next.has(id)) left.push(id);
207
+ }
208
+ tracker.prev = next;
209
+ tracker.next = prev; // reused as scratch on the next call
210
+ return { entered: entered, left: left, visible: visible };
211
+ },
212
+
213
+ /**
214
+ * Free an observer's tracking state (call when a player leaves).
215
+ * @param {InterestGridId} observerId
216
+ */
217
+ dropObserver: function (observerId) {
218
+ checkId(observerId, 'dropObserver');
219
+ observers.delete(observerId);
220
+ },
221
+
222
+ /** @returns {number} Number of entities in the grid. */
223
+ size: function () {
224
+ return entities.size;
225
+ },
226
+ };
227
+ }
package/types/index.d.ts CHANGED
@@ -173,6 +173,51 @@ export interface DirectConnectionConfig {
173
173
  apiUrl?: string;
174
174
  token?: string;
175
175
  protocolVersion?: string;
176
+ /**
177
+ * Liveness watchdog tuning, or `false` to disable probing/dead detection.
178
+ * Defaults: probe after 4 s of silence, declare dead after 12 s. (SDK ≥ 2.24)
179
+ */
180
+ liveness?: DirectLivenessOptions | false;
181
+ /**
182
+ * Hold realtime 'input' frames (latest only) while the socket send buffer
183
+ * exceeds this many bytes; drained as the buffer clears. Control frames
184
+ * (join/action/ping/…) always send. 0 or `false` disables. Default 8192.
185
+ * (SDK ≥ 2.24)
186
+ */
187
+ backpressureBytes?: number | false;
188
+ }
189
+
190
+ /** Liveness watchdog options for connectDirect. (SDK ≥ 2.24) */
191
+ export interface DirectLivenessOptions {
192
+ /** Silence before an RTT probe ping, ms (default 4000, clamped ≥ 1000). */
193
+ probeAfterMs?: number;
194
+ /** Silence before the socket is declared dead and re-dialed, ms (default 12000, clamped ≥ probeAfterMs + 2000). */
195
+ deadAfterMs?: number;
196
+ }
197
+
198
+ /** Coarse connection quality. 'dead' = liveness-declared dead or disconnected. */
199
+ export type NetworkQuality = 'good' | 'fair' | 'poor' | 'dead';
200
+
201
+ /** Snapshot returned by game.getNetworkStats(). (SDK ≥ 2.24) */
202
+ export interface NetworkStats {
203
+ transport: 'direct' | 'relay';
204
+ connectionState: GameConnectionState;
205
+ quality: NetworkQuality;
206
+ /** Smoothed round-trip time in ms (EWMA); null until something measured it. */
207
+ rtt: number | null;
208
+ /** Smoothed RTT variation in ms; null until something measured it. */
209
+ jitter: number | null;
210
+ /** ms since the last inbound direct-socket message; null in relay mode. */
211
+ lastInboundAgeMs: number | null;
212
+ /** Direct-socket send-buffer bytes; null when there is no direct socket. */
213
+ bufferedAmount: number | null;
214
+ }
215
+
216
+ /** Payload of game.onNetworkQuality — fired on quality transitions only. */
217
+ export interface NetworkQualityChange {
218
+ quality: NetworkQuality;
219
+ prev: NetworkQuality;
220
+ stats: NetworkStats;
176
221
  }
177
222
 
178
223
  export interface PlayerJoinedData {
@@ -278,6 +323,20 @@ export interface GameInviteResult {
278
323
  invited: string[];
279
324
  }
280
325
 
326
+ /** Options for game.joinWorld(). */
327
+ export interface JoinWorldOptions {
328
+ /** Service to place into (defaults to the current service). */
329
+ serviceId?: string;
330
+ }
331
+
332
+ /** Result of game.joinWorld(). */
333
+ export interface WorldJoinResult {
334
+ /** The world room this player was placed into (also set on game.roomId). */
335
+ roomId: string;
336
+ /** Players in the world at placement time (this player included). */
337
+ playerIds: string[];
338
+ }
339
+
281
340
  /** Unified connection-state machine, identical across all transports. */
282
341
  export type GameConnectionState = 'connected' | 'disconnected' | 'rejoining' | 'reconnected';
283
342
 
@@ -362,6 +421,15 @@ export interface GameModule {
362
421
  // transitions so rejoining clients can restore instantly (the host
363
422
  // need not be the one to call it).
364
423
  join(roomId?: string): Promise<GameJoinResult>;
424
+ /**
425
+ * Place this player into a drop-in/drop-out WORLD room (services tagged
426
+ * `world`). Placement rides the matchmaking channel (works embedded AND
427
+ * standalone): the platform returns the world you're already in, else
428
+ * backfills a world with space, else creates a new one. Sets `game.roomId`,
429
+ * so the usual `connect()`+`join()` / `connectDirect()` flow works
430
+ * unchanged afterwards. Rejects with MATCH_TIMEOUT after 15s. (SDK ≥ 2.23)
431
+ */
432
+ joinWorld(opts?: JoinWorldOptions): Promise<WorldJoinResult>;
365
433
  leave(): void;
366
434
  action(actionType: string, actionData?: Record<string, any>, opts?: GameActionOptions): Promise<ActionResult>;
367
435
  realtime(actionType: string, actionData?: Record<string, any>): void;
@@ -499,6 +567,8 @@ export interface GameModule {
499
567
  createLagCompensator(opts?: LagCompensatorOptions): LagCompensator;
500
568
  /** Deterministic lockstep (inputs-only sim + free replays). */
501
569
  createLockstep(opts: LockstepOptions): Lockstep;
570
+ /** Spatial hash for area-of-interest filtering in world rooms. (SDK ≥ 2.23) */
571
+ createInterestGrid(opts?: InterestGridOptions): InterestGrid;
502
572
  /** Inject latency/jitter/loss locally to test under bad networks (null = off). */
503
573
  simulateNetwork(opts: NetworkSimOptions | null): NetworkSim | void;
504
574
 
@@ -506,6 +576,21 @@ export interface GameModule {
506
576
  ping(): Promise<number | null>;
507
577
  /** Latest smoothed round-trip time in ms (null until first ping). */
508
578
  getRtt(): number | null;
579
+
580
+ // ─── Network resilience (SDK ≥ 2.24) ─────────────────────────
581
+ /**
582
+ * Cheap snapshot of connection health: transport, connection state,
583
+ * quality, smoothed rtt/jitter, age of the last inbound direct frame,
584
+ * and buffered (unsent) bytes. Works in every transport; relay mode
585
+ * reports rtt/jitter null unless game.ping() measured them.
586
+ */
587
+ getNetworkStats(): NetworkStats;
588
+ /**
589
+ * Observe network-quality TRANSITIONS ('good'/'fair'/'poor'/'dead') —
590
+ * fires only when the quality level changes, with { quality, prev, stats }.
591
+ * Drive a connection-quality indicator or degrade send rates from here.
592
+ */
593
+ onNetworkQuality(callback: (change: NetworkQualityChange) => void): UnsubscribeFn;
509
594
  }
510
595
 
511
596
  // ─── Netcode toolkit ──────────────────────────────────────────────
@@ -841,6 +926,43 @@ export class WebTransportConnection {
841
926
  close(): void;
842
927
  }
843
928
 
929
+ // ─── Interest grid (area-of-interest spatial hash, SDK ≥ 2.23) ───
930
+
931
+ export interface InterestGridOptions {
932
+ /** Cell size in world units (default 256); pick ≈ the typical query radius. */
933
+ cellSize?: number;
934
+ }
935
+
936
+ /** Per-observer visibility diff from InterestGrid.observe(). */
937
+ export interface InterestGridObservation {
938
+ /** Ids visible now that were not visible on this observer's previous observe(). */
939
+ entered: Array<string | number>;
940
+ /** Ids visible on the previous observe() that no longer are. */
941
+ left: Array<string | number>;
942
+ /** All ids currently within the radius. */
943
+ visible: Array<string | number>;
944
+ }
945
+
946
+ /**
947
+ * Spatial hash for area-of-interest filtering: O(cells touched) proximity
948
+ * queries plus per-observer enter/leave diffs. Pure JS (browser and Node) —
949
+ * the AOI building block for world-scale rooms.
950
+ */
951
+ export interface InterestGrid {
952
+ /** Insert an entity or move an existing one. */
953
+ upsert(id: string | number, x: number, y: number): void;
954
+ /** Remove an entity (unknown ids are a no-op). */
955
+ remove(id: string | number): void;
956
+ /** Entity ids within `radius` of (x, y) — a true circle test. */
957
+ query(x: number, y: number, radius: number): Array<string | number>;
958
+ /** query() diffed against this observer's previous call. */
959
+ observe(observerId: string | number, x: number, y: number, radius: number): InterestGridObservation;
960
+ /** Free an observer's tracking state (call when a player leaves). */
961
+ dropObserver(observerId: string | number): void;
962
+ /** Number of entities in the grid. */
963
+ size(): number;
964
+ }
965
+
844
966
  export interface NetcodeModule {
845
967
  SnapshotInterpolation: typeof SnapshotInterpolation;
846
968
  Vault: typeof Vault;
@@ -858,6 +980,8 @@ export interface NetcodeModule {
858
980
  quantize<T = any>(value: T, precision?: number): T;
859
981
  encode(value: any): Uint8Array;
860
982
  decode(buf: ArrayBuffer | Uint8Array): any;
983
+ /** Spatial hash for area-of-interest filtering in world rooms. (SDK ≥ 2.23) */
984
+ createInterestGrid(opts?: InterestGridOptions): InterestGrid;
861
985
  }
862
986
 
863
987
  // ─── Results ────────────────────────────────────────────────────
@@ -1155,6 +1279,7 @@ export declare const ERROR_CODES: {
1155
1279
  readonly VALUE_TOO_LARGE: 'VALUE_TOO_LARGE';
1156
1280
  readonly LOBBY_FULL: 'LOBBY_FULL';
1157
1281
  readonly LOBBY_CLOSED: 'LOBBY_CLOSED';
1282
+ readonly WORLD_FULL: 'WORLD_FULL';
1158
1283
  readonly CONFLICT: 'CONFLICT';
1159
1284
  readonly RATE_LIMITED: 'RATE_LIMITED';
1160
1285
  readonly REQUEST_TIMEOUT: 'REQUEST_TIMEOUT';