Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(net): interest management — per-connection relevance filtering

yhh4cbea8166789
diff --git a/docs/astro/src/content/docs/guides/networking.mdx b/docs/astro/src/content/docs/guides/networking.mdx
index dff883c89..08c02bfe1 100644
--- a/docs/astro/src/content/docs/guides/networking.mdx
+++ b/docs/astro/src/content/docs/guides/networking.mdx
@@ -115,6 +115,35 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // per-tick input uplin
See the **Multiplayer Arena** example for the full pattern in ~100 lines.
+### Interest management — who sees what
+
+By default every client receives every replicated entity. For bigger worlds,
+install an **interest policy** on the server: each connection then only
+receives the entities relevant to it — entering entities arrive as full
+spawns, leaving ones despawn their client ghost, and delta frames carry only
+what's inside.
+
+```typescript
+import { radiusInterest } from 'esengine';
+
+// Each client sees entities within 800 units of any entity it owns.
+server.setInterestPolicy(radiusInterest(800));
+
+// Or any custom rule — return the relevant subset (or 'all'):
+server.setInterestPolicy(({ connectionId, world, candidates }) => {
+ const visible = new Set(candidates.filter((e) => isRelevantTo(world, e, connectionId)));
+ return visible;
+});
+```
+
+- **Owned entities are never culled** — a policy can't hide a client's own pawn.
+- **Re-entering is seamless**: the respawn carries the entity's *current* state.
+- `radiusInterest` reads `Transform.position` by default (override with
+ `{ position }`); placeless entities are always relevant, and it fails open
+ while a connection owns no positioned entity yet.
+- Installing, replacing, or removing the policy mid-session is safe — the next
+ tick reconciles every connection's ghost set.
+
## Best practices
- **Use `NetChannel`** for anything beyond a trivial socket — routed types and RPC
diff --git a/docs/astro/src/content/docs/zh-cn/guides/networking.mdx b/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
index 564ee2e0b..9713c55a8 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
@@ -112,6 +112,31 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // 每 tick 输入上
完整范式见 **Multiplayer Arena** 示例(约 100 行)。
+### 兴趣管理——谁看见什么
+
+默认每个客户端接收全部复制实体。世界大了以后,在服务器上装一个**兴趣策略**:
+每个连接只接收与它相关的实体——进入兴趣的实体以全量 spawn 到达,离开的实体
+在客户端 despawn 其 ghost,delta 帧只携带兴趣内的内容。
+
+```typescript
+import { radiusInterest } from 'esengine';
+
+// 每个客户端看到它拥有的实体周围 800 单位内的实体。
+server.setInterestPolicy(radiusInterest(800));
+
+// 或任意自定义规则——返回相关子集(或 'all'):
+server.setInterestPolicy(({ connectionId, world, candidates }) => {
+ const visible = new Set(candidates.filter((e) => isRelevantTo(world, e, connectionId)));
+ return visible;
+});
+```
+
+- **自有实体永不被剔除**——策略藏不掉客户端自己的 pawn。
+- **重进无缝**:重新 spawn 携带实体的*当前*状态。
+- `radiusInterest` 默认读 `Transform.position`(可用 `{ position }` 覆盖);
+ 无位置的实体恒相关;连接尚无带位置的自有实体时 fail-open(看到全部)。
+- 会话中安装/替换/移除策略都是安全的——下一 tick 会调和每个连接的 ghost 集。
+
## 最佳实践
- 超出简单套接字的场景**用 `NetChannel`**——按类型路由和 RPC 胜过一个巨大的 `onMessage` switch。
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index fb7b9d9d1..34fa2cdf3 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1084 stable · 44 beta · 1 deprecated
+Symbols: 1084 stable · 48 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -2959,6 +2959,18 @@ enabled: boolean
raycastTarget: boolean
```
+## InterestPolicy — type @beta
+```
+(view: InterestView) => ReadonlySet<Entity> | 'all'
+```
+
+## InterestView — interface @beta
+```
+candidates: readonly number[]
+connectionId: number
+world: World
+```
+
## InterpType — type
```
(typeof InterpType)[keyof typeof InterpType]
@@ -4550,6 +4562,11 @@ static prototype: QueryInstance<any>
1
```
+## RadiusInterestOptions — interface @beta
+```
+position: ((world: World, entity: Entity) => { x: number; y: number; } | null) | undefined
+```
+
## ReadonlySignal — interface
```
get: () => T
@@ -4710,6 +4727,7 @@ detachConnection: (id: number) => void
inputOf: (connectionId: number) => ReplInputMsg | null
netIds: NetIds
sample: (tick: number) => void
+setInterestPolicy: (policy: InterestPolicy | null) => void
table: ReplicationTable
static new (world: World): ReplicationServer
static prototype: ReplicationServer
@@ -8159,6 +8177,11 @@ PrefabsPlugin
(rz: number, rw: number): number
```
+## radiusInterest — function @beta
+```
+(radius: number, options?: RadiusInterestOptions): InterestPolicy
+```
+
## readPtrField — function
```
(f32: Float32Array, u32: Uint32Array, u8: Uint8Array, ptr: number, field: PtrFieldDesc): unknown
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index d28721533..8981dc4b5 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -1,7 +1,7 @@
# API surface — esengine/index.node
<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->
-Symbols: 1083 stable · 46 beta · 1 deprecated
+Symbols: 1083 stable · 50 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -2954,6 +2954,18 @@ enabled: boolean
raycastTarget: boolean
```
+## InterestPolicy — type @beta
+```
+(view: InterestView) => ReadonlySet<Entity> | 'all'
+```
+
+## InterestView — interface @beta
+```
+candidates: readonly number[]
+connectionId: number
+world: World
+```
+
## InterpType — type
```
(typeof InterpType)[keyof typeof InterpType]
@@ -4545,6 +4557,11 @@ static prototype: QueryInstance<any>
1
```
+## RadiusInterestOptions — interface @beta
+```
+position: ((world: World, entity: Entity) => { x: number; y: number; } | null) | undefined
+```
+
## ReadonlySignal — interface
```
get: () => T
@@ -4705,6 +4722,7 @@ detachConnection: (id: number) => void
inputOf: (connectionId: number) => ReplInputMsg | null
netIds: NetIds
sample: (tick: number) => void
+setInterestPolicy: (policy: InterestPolicy | null) => void
table: ReplicationTable
static new (world: World): ReplicationServer
static prototype: ReplicationServer
@@ -8164,6 +8182,11 @@ PrefabsPlugin
(rz: number, rw: number): number
```
+## radiusInterest — function @beta
+```
+(radius: number, options?: RadiusInterestOptions): InterestPolicy
+```
+
## readPtrField — function
```
(f32: Float32Array, u32: Uint32Array, u8: Uint8Array, ptr: number, field: PtrFieldDesc): unknown
diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.ts
index c8bee8b64..f440f8158 100644
--- a/sdk/src/core-sys.ts
+++ b/sdk/src/core-sys.ts
@@ -92,7 +92,9 @@ export {
replicationPlugin, ReplicationPlugin, Net, NetSession,
Replicated, NetGhost, ReplicationServer, ReplicationClient,
REPLICATION_PROTOCOL_VERSION, REPLICATION_CHANNEL,
+ radiusInterest,
type NetRoleKind, type ReplicatedData,
+ type InterestPolicy, type InterestView, type RadiusInterestOptions,
} from './net/replication';
// =============================================================================
diff --git a/sdk/src/net/GameSocket.ts b/sdk/src/net/GameSocket.ts
index df22f46fd..0b881c228 100644
--- a/sdk/src/net/GameSocket.ts
+++ b/sdk/src/net/GameSocket.ts
@@ -4,7 +4,7 @@
* @file GameSocket.ts
* @brief Raw browser-WebSocket wrapper behind the platform socket seam.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { PlatformSocket, PlatformSocketOptions, PlatformSocketReadyState } from '../platform/types';
diff --git a/sdk/src/net/MemoryTransport.ts b/sdk/src/net/MemoryTransport.ts
index ba34803b4..380d4124b 100644
--- a/sdk/src/net/MemoryTransport.ts
+++ b/sdk/src/net/MemoryTransport.ts
@@ -9,7 +9,7 @@
* pumps them, which is how delivery order, latency and packet
* interleaving are simulated.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { NetTransport } from './NetChannel';
diff --git a/sdk/src/net/MessagePortTransport.ts b/sdk/src/net/MessagePortTransport.ts
index 2b68ab6df..2e7ca5476 100644
--- a/sdk/src/net/MessagePortTransport.ts
+++ b/sdk/src/net/MessagePortTransport.ts
@@ -8,7 +8,7 @@
* (JSON strings and ArrayBuffer frames) natively, and a port queues
* messages until the other end attaches, so wiring order is free.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { NetTransport } from './NetChannel';
diff --git a/sdk/src/net/NetChannel.ts b/sdk/src/net/NetChannel.ts
index 8f066dc45..48d721c8a 100644
--- a/sdk/src/net/NetChannel.ts
+++ b/sdk/src/net/NetChannel.ts
@@ -8,7 +8,7 @@
* RPC (`handle`/`request`) with a small JSON envelope. Transport-
* agnostic — anything that can `send` and surface `onMessage` works.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
/** The minimal socket surface NetChannel drives (GameSocket / WeChatSocket fit). */
diff --git a/sdk/src/net/WeChatSocket.ts b/sdk/src/net/WeChatSocket.ts
index 0fac4c17d..34c655f3e 100644
--- a/sdk/src/net/WeChatSocket.ts
+++ b/sdk/src/net/WeChatSocket.ts
@@ -4,7 +4,7 @@
* @file WeChatSocket.ts
* @brief Raw wx.connectSocket wrapper behind the platform socket seam.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { PlatformSocket } from '../platform/types';
import type { GameSocketOptions, SocketReadyState } from './GameSocket';
diff --git a/sdk/src/net/index.ts b/sdk/src/net/index.ts
index 287edbb9a..596f0732d 100644
--- a/sdk/src/net/index.ts
+++ b/sdk/src/net/index.ts
@@ -4,7 +4,7 @@
* @file index.ts
* @brief Networking barrel: sockets, transports, NetChannel, replication.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
export { GameSocket, type GameSocketOptions, type SocketReadyState } from './GameSocket';
export { WeChatSocket } from './WeChatSocket';
diff --git a/sdk/src/net/replication/NetIds.ts b/sdk/src/net/replication/NetIds.ts
index e45024363..3f3d9db9d 100644
--- a/sdk/src/net/replication/NetIds.ts
+++ b/sdk/src/net/replication/NetIds.ts
@@ -7,7 +7,7 @@
* them — a server-allocated NetId is the one cross-machine identity,
* and each endpoint keeps this bidirectional table.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { Entity } from '../../types';
diff --git a/sdk/src/net/replication/ReplicationPlugin.ts b/sdk/src/net/replication/ReplicationPlugin.ts
index 399ac410d..f8fa04609 100644
--- a/sdk/src/net/replication/ReplicationPlugin.ts
+++ b/sdk/src/net/replication/ReplicationPlugin.ts
@@ -9,7 +9,7 @@
* not an environment flag: everything no-ops while NetRole stays
* 'offline', so the plugin is safe to install unconditionally.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { App, Plugin } from '../../app';
import { defineSystem, Schedule } from '../../system';
diff --git a/sdk/src/net/replication/client.ts b/sdk/src/net/replication/client.ts
index 16443d2e9..bf1db852f 100644
--- a/sdk/src/net/replication/client.ts
+++ b/sdk/src/net/replication/client.ts
@@ -9,7 +9,7 @@
* deterministic point in the frame, not mid-schedule on socket
* timing.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { World } from '../../world';
import type { Entity } from '../../types';
diff --git a/sdk/src/net/replication/codec.ts b/sdk/src/net/replication/codec.ts
index 09734f309..15bf91508 100644
--- a/sdk/src/net/replication/codec.ts
+++ b/sdk/src/net/replication/codec.ts
@@ -19,7 +19,7 @@
* declaration order, entity-ref field → u32 netId (remapped at both
* ends), anything else → JSON string fallback.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import { getComponentRegistry, type AnyComponentDef } from '../../component';
import { REPLICATION_PROTOCOL_VERSION, type ReplComponentSchema } from './protocol';
diff --git a/sdk/src/net/replication/components.ts b/sdk/src/net/replication/components.ts
index bf4857776..f7ff355ad 100644
--- a/sdk/src/net/replication/components.ts
+++ b/sdk/src/net/replication/components.ts
@@ -9,7 +9,7 @@
* proxies so local simulation (physics, AI) can yield to the incoming
* authoritative state via Without(NetGhost) queries.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import { defineComponent, defineTag } from '../../component';
diff --git a/sdk/src/net/replication/index.ts b/sdk/src/net/replication/index.ts
index adbd7006d..b47a525d9 100644
--- a/sdk/src/net/replication/index.ts
+++ b/sdk/src/net/replication/index.ts
@@ -30,6 +30,12 @@ export {
type StateFrame,
} from './codec';
export { Replicated, NetGhost, type ReplicatedData } from './components';
+export {
+ radiusInterest,
+ type InterestPolicy,
+ type InterestView,
+ type RadiusInterestOptions,
+} from './interest';
export { NetIds } from './NetIds';
export { ReplicationServer } from './server';
export { ReplicationClient, type ReplicationClientOptions } from './client';
diff --git a/sdk/src/net/replication/interest.ts b/sdk/src/net/replication/interest.ts
new file mode 100644
index 000000000..c104762a4
--- /dev/null
+++ b/sdk/src/net/replication/interest.ts
@@ -0,0 +1,93 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file interest.ts
+ * @brief Interest management — per-connection relevance filtering.
+ *
+ * A policy decides which replicated entities a connection receives. The server
+ * evaluates it once per ready connection per sample tick; entities entering a
+ * connection's interest are spawned to it (full current state), entities
+ * leaving are despawned (the client drops the ghost), and delta frames carry
+ * only entities inside it. Two invariants live in the server, not here: a
+ * connection always sees the entities it owns, and with no policy installed
+ * every connection sees everything (the pre-interest broadcast behavior).
+ *
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
+ */
+import type { World } from '../../world';
+import type { Entity } from '../../types';
+import { getComponent } from '../../component';
+import { Replicated, type ReplicatedData } from './components';
+
+/** What a policy sees when the server asks it for one connection's interest. */
+export interface InterestView {
+ /** The connection being evaluated. */
+ connectionId: number;
+ world: World;
+ /** Every currently replicated entity — the set to filter. */
+ candidates: readonly Entity[];
+}
+
+/**
+ * Returns the entities relevant to the connection, or `'all'` for no
+ * filtering. Runs on the server once per ready connection per sample tick, so
+ * keep it cheap — return a subset of `candidates`, don't run queries of your
+ * own.
+ */
+export type InterestPolicy = (view: InterestView) => ReadonlySet<Entity> | 'all';
+
+export interface RadiusInterestOptions {
+ /**
+ * How to read an entity's 2D position. Defaults to the `Transform`
+ * component's world-space `position`. Return null for "this entity has no
+ * place" — such entities are always relevant (they can't be culled by
+ * distance).
+ */
+ position?: (world: World, entity: Entity) => { x: number; y: number } | null;
+}
+
+/**
+ * The built-in spatial policy: a connection sees the entities within `radius`
+ * of any entity it owns (its pawn/s). Placeless entities (no position) are
+ * always relevant. Fail-open: while a connection owns no positioned entity
+ * (e.g. before gameplay provisions its pawn) it sees everything.
+ */
+export function radiusInterest(radius: number, options: RadiusInterestOptions = {}): InterestPolicy {
+ const r2 = radius * radius;
+ const positionOf = options.position ?? defaultPosition;
+ return ({ connectionId, world, candidates }) => {
+ const anchors: { x: number; y: number }[] = [];
+ for (const e of candidates) {
+ const repl = world.tryGet(e, Replicated) as ReplicatedData | null;
+ if (repl?.owner !== connectionId) continue;
+ const p = positionOf(world, e);
+ if (p) anchors.push(p);
+ }
+ if (anchors.length === 0) return 'all';
+
+ const visible = new Set<Entity>();
+ for (const e of candidates) {
+ const p = positionOf(world, e);
+ if (!p) {
+ visible.add(e);
+ continue;
+ }
+ for (const a of anchors) {
+ const dx = p.x - a.x;
+ const dy = p.y - a.y;
+ if (dx * dx + dy * dy <= r2) {
+ visible.add(e);
+ break;
+ }
+ }
+ }
+ return visible;
+ };
+}
+
+function defaultPosition(world: World, entity: Entity): { x: number; y: number } | null {
+ const Transform = getComponent('Transform');
+ if (!Transform || !world.has(entity, Transform)) return null;
+ const t = world.tryGet(entity, Transform) as { position?: { x: number; y: number } } | null;
+ return t?.position ? { x: t.position.x, y: t.position.y } : null;
+}
diff --git a/sdk/src/net/replication/interpolation.ts b/sdk/src/net/replication/interpolation.ts
index 52f06d035..db14e49d6 100644
--- a/sdk/src/net/replication/interpolation.ts
+++ b/sdk/src/net/replication/interpolation.ts
@@ -11,7 +11,7 @@
* lerp (f32 scalars, f32 leaves of vectors, quats via nlerp);
* discrete values hold until their sample time passes.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { FieldShape } from './codec';
diff --git a/sdk/src/net/replication/protocol.ts b/sdk/src/net/replication/protocol.ts
index 6a320d468..d8fd495e5 100644
--- a/sdk/src/net/replication/protocol.ts
+++ b/sdk/src/net/replication/protocol.ts
@@ -9,7 +9,7 @@
* layout). Version or schema drift refuses the connection at
* handshake — never a silently mismatched simulation.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { SceneComponentData } from '../../scene';
diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.ts
index ed44a5171..754030164 100644
--- a/sdk/src/net/replication/server.ts
+++ b/sdk/src/net/replication/server.ts
@@ -5,11 +5,18 @@
* @brief The authoritative endpoint. Owns connections (one NetChannel per
* transport), answers the handshake, and each fixed tick: replicates
* spawns/despawns of `Replicated` entities on the JSON control plane
- * and diffs replicated fields against a shadow copy to broadcast a
- * binary delta frame. WebSocket transports are reliable+ordered, so
+ * and diffs replicated fields against a shadow copy into binary delta
+ * frames. WebSocket transports are reliable+ordered, so
* delta-since-last-send needs no ack protocol.
*
- * @beta Pre-1.0 networking: client prediction and interest management will reshape this surface.
+ * With an {@link InterestPolicy} installed, spawns/despawns/deltas are
+ * filtered per connection: the shadow diff still runs once, but each
+ * connection only receives the entities the policy deems relevant,
+ * entering entities arrive as full spawns and leaving ones as
+ * despawns. Without a policy every ready connection sees everything
+ * on a single broadcast frame (the fast path).
+ *
+ * @beta Pre-1.0 networking: client prediction will reshape this surface.
*/
import type { World } from '../../world';
import type { Entity } from '../../types';
@@ -25,10 +32,11 @@ import {
} from './protocol';
import {
buildReplicationTable, diffSchemas, tableSchemas, FrameWriter,
- type EntityRefMap, type ReplicationTable,
+ type EntityRefMap, type ReplicationTable, type ReplicationTableEntry,
} from './codec';
import { Replicated, type ReplicatedData } from './components';
import { NetIds } from './NetIds';
+import type { InterestPolicy } from './interest';
interface Connection {
id: number;
@@ -37,6 +45,19 @@ interface Connection {
ready: boolean;
/** Latest input command from this connection (stale seq never overwrites). */
input: ReplInputMsg | null;
+ /** Entities this connection currently knows (has been sent a spawn for). */
+ interest: Set<Entity>;
+}
+
+/** One dirty component on one entity this tick — diffed once, written into
+ * whichever frames (shared or per-connection) need it. `data` is the live
+ * component record; it is read before the next simulation step mutates it. */
+interface DirtyEntry {
+ entity: Entity;
+ netId: number;
+ te: ReplicationTableEntry;
+ mask: number;
+ data: Record<string, unknown>;
}
function deepClone<T>(v: T): T {
@@ -70,6 +91,7 @@ export class ReplicationServer {
/** known entity → netId, owned by sampling. Survives the onDespawn hook
* clearing netIds_, so a despawn can still broadcast its id. */
private readonly knownNetIds_ = new Map<Entity, number>();
+ private policy_: InterestPolicy | null = null;
private tick_ = 0;
constructor(world: World) {
@@ -110,11 +132,24 @@ export class ReplicationServer {
};
}
+ /**
+ * Install (or replace / remove) the interest policy. With a policy, each
+ * ready connection only receives the entities the policy deems relevant to
+ * it; an entity entering a connection's interest arrives as a full spawn,
+ * one leaving despawns its client ghost. Entities a connection owns are
+ * always relevant to it regardless of the policy. Safe to change
+ * mid-session: the next sample tick reconciles every connection's ghost
+ * set against the new policy.
+ */
+ setInterestPolicy(policy: InterestPolicy | null): void {
+ this.policy_ = policy;
+ }
+
/** Accept a transport (server-side end of one client link). */
attachConnection(transport: NetTransport): number {
const id = this.nextConnectionId_++;
const channel = new NetChannel(transport);
- const conn: Connection = { id, channel, ready: false, input: null };
+ const conn: Connection = { id, channel, ready: false, input: null, interest: new Set() };
this.connections_.set(id, conn);
channel.on<ReplInputMsg>(ReplMsg.input, (msg) => {
@@ -156,7 +191,8 @@ export class ReplicationServer {
}
/** One replication tick: spawns/despawns on the control plane, dirty
- * fields as one binary delta frame. Runs in FixedPostUpdate. */
+ * fields as binary delta frames (one shared broadcast without a policy,
+ * one filtered frame per connection with one). Runs in FixedPostUpdate. */
sample(tick: number): void {
this.tick_ = tick;
if (this.connections_.size === 0) return;
@@ -164,19 +200,22 @@ export class ReplicationServer {
const current = this.world_.getEntitiesWithComponents([Replicated]);
const currentSet = new Set(current);
- const spawned: ReplSpawnEntity[] = [];
+ const spawnedEntities: Entity[] = [];
for (const e of current) {
if (!this.known_.has(e)) {
- spawned.push(this.registerEntity_(e));
+ this.registerEntity_(e);
+ spawnedEntities.push(e);
}
}
- const despawnedIds: number[] = [];
+ // netIds captured before unregistering so per-connection despawns can
+ // still name entities that vanished this tick.
+ const despawned: { entity: Entity; netId: number }[] = [];
for (const e of [...this.known_]) {
if (!currentSet.has(e) || !this.world_.valid(e)) {
const netId = this.knownNetIds_.get(e);
if (netId !== undefined) {
- despawnedIds.push(netId);
+ despawned.push({ entity: e, netId });
this.netIds_.unregister(netId);
}
this.known_.delete(e);
@@ -185,24 +224,138 @@ export class ReplicationServer {
}
}
- if (spawned.length > 0) {
- this.broadcast_((c) => c.channel.send<ReplSpawnBatch>(ReplMsg.spawn, { tick, entities: spawned }));
+ // Diff once against the shadow; frames below share the result.
+ const dirty = this.collectDirty_();
+
+ if (!this.policy_) {
+ this.sampleBroadcast_(tick, spawnedEntities, despawned, dirty);
+ } else {
+ this.sampleWithInterest_(tick, despawned, dirty);
}
- if (despawnedIds.length > 0) {
- this.broadcast_((c) => c.channel.send<ReplDespawnBatch>(ReplMsg.despawn, { tick, netIds: despawnedIds }));
+ }
+
+ /** Fast path (no policy): everything to every ready connection on shared
+ * payloads. Interest bookkeeping stays exact so a policy can be installed
+ * (or removed) mid-session and the next tick reconciles cleanly. */
+ private sampleBroadcast_(
+ tick: number,
+ spawnedEntities: Entity[],
+ despawned: { entity: Entity; netId: number }[],
+ dirty: DirtyEntry[],
+ ): void {
+ if (spawnedEntities.length > 0) {
+ const entities = spawnedEntities.map((e) => this.spawnPayload_(e, this.knownNetIds_.get(e)!));
+ this.broadcast_((c) => c.channel.send<ReplSpawnBatch>(ReplMsg.spawn, { tick, entities }));
+ }
+ if (despawned.length > 0) {
+ const netIds = despawned.map((d) => d.netId);
+ this.broadcast_((c) => c.channel.send<ReplDespawnBatch>(ReplMsg.despawn, { tick, netIds }));
}
- const frame = new FrameWriter(tick);
- for (const e of this.known_) {
- this.diffEntity_(e, frame);
+ for (const conn of this.connections_.values()) {
+ if (!conn.ready) continue;
+ for (const e of spawnedEntities) conn.interest.add(e);
+ for (const d of despawned) conn.interest.delete(d.entity);
+ // A policy removed mid-session may have left this connection blind
+ // to entities it never entered — catch it up (interest ⊆ known, so
+ // equal sizes ⇒ equal sets and this costs one comparison).
+ if (conn.interest.size !== this.known_.size) {
+ const missing: ReplSpawnEntity[] = [];
+ for (const e of this.known_) {
+ if (conn.interest.has(e)) continue;
+ conn.interest.add(e);
+ missing.push(this.spawnPayload_(e, this.knownNetIds_.get(e)!));
+ }
+ if (missing.length > 0) {
+ this.sendTo_(conn, (c) => c.channel.send<ReplSpawnBatch>(ReplMsg.spawn, { tick, entities: missing }));
+ }
+ }
}
- if (frame.entryCount > 0) {
+
+ if (dirty.length > 0) {
+ const frame = new FrameWriter(tick);
+ for (const d of dirty) frame.entry(d.netId, d.te, d.mask, d.data, this.refs_);
const payload = frame.finish();
this.broadcast_((c) => c.channel.sendBinary(REPLICATION_CHANNEL, payload));
}
}
- private registerEntity_(e: Entity): ReplSpawnEntity {
+ /** Interest path: evaluate the policy per ready connection; spawn entering
+ * entities (full current state), despawn leaving ones, and write that
+ * connection's delta frame from the shared dirty list. */
+ private sampleWithInterest_(
+ tick: number,
+ despawned: { entity: Entity; netId: number }[],
+ dirty: DirtyEntry[],
+ ): void {
+ const despawnedNetIds = new Map(despawned.map((d) => [d.entity, d.netId]));
+ const candidates = [...this.known_];
+ // Spawn payloads serialize once per entity per tick, however many
+ // connections it enters.
+ const payloads = new Map<Entity, ReplSpawnEntity>();
+ const payloadOf = (e: Entity): ReplSpawnEntity => {
+ let p = payloads.get(e);
+ if (!p) {
+ p = this.spawnPayload_(e, this.knownNetIds_.get(e)!);
+ payloads.set(e, p);
+ }
+ return p;
+ };
+
+ for (const conn of this.connections_.values()) {
+ if (!conn.ready) continue;
+ const visible = this.visibleFor_(conn.id, candidates);
+
+ const enters: Entity[] = [];
+ for (const e of visible) {
+ if (!conn.interest.has(e)) enters.push(e);
+ }
+ const leaveIds: number[] = [];
+ for (const e of conn.interest) {
+ if (visible.has(e)) continue;
+ const netId = this.knownNetIds_.get(e) ?? despawnedNetIds.get(e);
+ if (netId !== undefined) leaveIds.push(netId);
+ }
+ conn.interest = visible;
+
+ this.sendTo_(conn, (c) => {
+ if (enters.length > 0) {
+ c.channel.send<ReplSpawnBatch>(ReplMsg.spawn, { tick, entities: enters.map(payloadOf) });
+ }
+ if (leaveIds.length > 0) {
+ c.channel.send<ReplDespawnBatch>(ReplMsg.despawn, { tick, netIds: leaveIds });
+ }
+ // Entities that just entered skip the delta — their spawn
+ // payload already carries this tick's state.
+ let frame: FrameWriter | null = null;
+ const entered = new Set(enters);
+ for (const d of dirty) {
+ if (!visible.has(d.entity) || entered.has(d.entity)) continue;
+ frame ??= new FrameWriter(tick);
+ frame.entry(d.netId, d.te, d.mask, d.data, this.refs_);
+ }
+ if (frame && frame.entryCount > 0) {
+ c.channel.sendBinary(REPLICATION_CHANNEL, frame.finish());
+ }
+ });
+ }
+ }
+
+ /** The policy's answer for one connection, with the server's invariant
+ * applied on top: a connection always sees the entities it owns (input
+ * routing and prediction anchor on them, so a policy cannot cull them). */
+ private visibleFor_(connectionId: number, candidates: readonly Entity[]): Set<Entity> {
+ const result = this.policy_!({ connectionId, world: this.world_, candidates });
+ const visible = result === 'all' ? new Set(candidates) : new Set(result);
+ for (const e of candidates) {
+ if (visible.has(e)) continue;
+ const repl = this.world_.tryGet(e, Replicated) as ReplicatedData | null;
+ if (repl && repl.owner === connectionId) visible.add(e);
+ }
+ return visible;
+ }
+
+ private registerEntity_(e: Entity): void {
const repl = this.world_.tryGet(e, Replicated) as ReplicatedData;
if (repl.netId === 0) {
repl.netId = this.netIds_.allocate();
@@ -212,7 +365,6 @@ export class ReplicationServer {
this.known_.add(e);
this.knownNetIds_.set(e, repl.netId);
this.seedShadow_(e);
- return this.spawnPayload_(e, repl.netId);
}
private seedShadow_(e: Entity): void {
@@ -254,57 +406,70 @@ export class ReplicationServer {
return { type: c.type, data };
}
- private diffEntity_(e: Entity, frame: FrameWriter): void {
- const perComp = this.shadow_.get(e);
- if (!perComp) return;
- const netId = this.netIds_.netIdOf(e);
- if (netId === undefined) return;
- for (const te of this.table.entries) {
- if (!this.world_.has(e, te.def)) continue;
- const data = this.world_.tryGet(e, te.def) as Record<string, unknown>;
- let snap = perComp.get(te.id);
- if (!snap) {
- // Component added after spawn: replicate all fields.
- snap = {};
- perComp.set(te.id, snap);
- }
- let mask = 0;
- for (let i = 0; i < te.fields.length; i++) {
- const f = te.fields[i];
- if (!(f in snap) || !fieldEqual(data[f], snap[f])) {
- mask |= 1 << i;
- snap[f] = deepClone(data[f]);
+ /** Diff every known entity against its shadow (updating the shadow), and
+ * return this tick's dirty component entries. */
+ private collectDirty_(): DirtyEntry[] {
+ const out: DirtyEntry[] = [];
+ for (const e of this.known_) {
+ const perComp = this.shadow_.get(e);
+ if (!perComp) continue;
+ const netId = this.knownNetIds_.get(e);
+ if (netId === undefined) continue;
+ for (const te of this.table.entries) {
+ if (!this.world_.has(e, te.def)) continue;
+ const data = this.world_.tryGet(e, te.def) as Record<string, unknown>;
+ let snap = perComp.get(te.id);
+ if (!snap) {
+ // Component added after spawn: replicate all fields.
+ snap = {};
+ perComp.set(te.id, snap);
+ }
+ let mask = 0;
+ for (let i = 0; i < te.fields.length; i++) {
+ const f = te.fields[i];
+ if (!(f in snap) || !fieldEqual(data[f], snap[f])) {
+ mask |= 1 << i;
+ snap[f] = deepClone(data[f]);
+ }
+ }
+ if (mask !== 0) {
+ out.push({ entity: e, netId, te, mask, data });
}
- }
- if (mask !== 0) {
- frame.entry(netId, te, mask, data, this.refs_);
}
}
+ return out;
}
private sendInitialState_(conn: Connection): void {
if (!this.connections_.has(conn.id)) return;
- // Everything known right now, full component payloads (current state
+ // Everything relevant right now, full component payloads (current state
// included — no separate baseline frame needed).
+ const candidates = [...this.known_];
+ const visible = this.policy_ ? this.visibleFor_(conn.id, candidates) : new Set(candidates);
const entities: ReplSpawnEntity[] = [];
- for (const e of this.known_) {
- const netId = this.netIds_.netIdOf(e);
+ for (const e of visible) {
+ const netId = this.knownNetIds_.get(e);
if (netId !== undefined) entities.push(this.spawnPayload_(e, netId));
}
if (entities.length > 0) {
conn.channel.send<ReplSpawnBatch>(ReplMsg.spawn, { tick: this.tick_, entities });
}
+ conn.interest = visible;
conn.ready = true;
}
private broadcast_(fn: (conn: Connection) => void): void {
for (const conn of this.connections_.values()) {
if (!conn.ready) continue;
- try {
- fn(conn);
- } catch (err) {
- log.warn('repl', `broadcast to connection ${conn.id} failed`, err);
- }
+ this.sendTo_(conn, fn);
+ }
+ }
+
+ private sendTo_(conn: Connection, fn: (conn: Connection) => void): void {
+ try {
+ fn(conn);
+ } catch (err) {
+ log.warn('repl', `send to connection ${conn.id} failed`, err);
}
}
}
diff --git a/sdk/tests/replication-interest.test.ts b/sdk/tests/replication-interest.test.ts
new file mode 100644
index 000000000..31b0bf367
--- /dev/null
+++ b/sdk/tests/replication-interest.test.ts
@@ -0,0 +1,230 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Interest management: with a policy installed the server filters
+ * spawns/despawns/deltas per connection — ghosts exist only while relevant,
+ * leaving despawns them, re-entering respawns them with current state, owned
+ * entities can never be culled, and the no-policy broadcast path is unchanged
+ * (including installing/removing a policy mid-session).
+ */
+import { describe, it, expect, beforeEach } from 'vitest';
+import { App } from '../src/app';
+import { defineComponent, clearUserComponents, Name } from '../src/component';
+import { MemoryTransport } from '../src/net/MemoryTransport';
+import {
+ replicationPlugin, Net, Replicated, radiusInterest,
+ type InterestPolicy,
+} from '../src/net/replication';
+import type { Entity } from '../src/types';
+import type { World } from '../src/world';
+
+const STEP = 1 / 60;
+
+let NetPos: ReturnType<typeof defineComponent<{ x: number; y: number }>>;
+
+beforeEach(() => {
+ clearUserComponents();
+ NetPos = defineComponent('NetPos', { x: 0, y: 0 }, {
+ replicatedFields: ['x', 'y'],
+ });
+});
+
+function makeApp(): App {
+ const app = App.new();
+ app.addPlugin(replicationPlugin);
+ return app;
+}
+
+const posOf = (world: World, e: Entity): { x: number; y: number } | null => {
+ const p = world.tryGet(e, NetPos) as { x: number; y: number } | null;
+ return p ? { x: p.x, y: p.y } : null;
+};
+
+async function makePair(policy?: InterestPolicy) {
+ const serverApp = makeApp();
+ const clientApp = makeApp();
+ const server = serverApp.getResource(Net).startServer();
+ if (policy) server.setInterestPolicy(policy);
+ const [ta, tb] = MemoryTransport.pair();
+ const connId = server.attachConnection(ta);
+ const client = await clientApp.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });
+ return { serverApp, clientApp, server, client, connId };
+}
+
+function spawnAt(app: App, name: string, x: number, y: number, owner = 0): Entity {
+ const e = app.world.spawn(name);
+ app.world.insert(e, Replicated, { owner });
+ app.world.insert(e, NetPos, { x, y });
+ return e;
+}
+
+function ghostNames(app: App): string[] {
+ return app.world.getEntitiesWithComponents([Replicated])
+ .map((e) => (app.world.tryGet(e, Name) as { value: string } | null)?.value ?? '')
+ .sort();
+}
+
+async function step(serverApp: App, clientApp: App, n = 1): Promise<void> {
+ for (let i = 0; i < n; i++) {
+ await serverApp.tick(STEP);
+ await clientApp.tick(STEP);
+ }
+}
+
+describe('interest management (radius policy)', () => {
+ it('spawns only relevant ghosts, despawns on leave, respawns with current state on re-enter', async () => {
+ const { serverApp, clientApp, server, client, connId } = await makePair();
+ server.setInterestPolicy(radiusInterest(100, { position: posOf }));
+
+ spawnAt(serverApp, 'pawn', 0, 0, connId);
+ const near = spawnAt(serverApp, 'near', 50, 0);
+ const far = spawnAt(serverApp, 'far', 500, 0);
+ await step(serverApp, clientApp);
+
+ expect(ghostNames(clientApp)).toEqual(['near', 'pawn']);
+
+ // `near` wanders out of range → its ghost despawns.
+ serverApp.world.set(near, NetPos, { x: 400, y: 0 });
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['pawn']);
+
+ // `far` wanders in — while out of interest it also changed y; the
+ // respawn must carry CURRENT state, not the state at first spawn.
+ serverApp.world.set(far, NetPos, { x: 80, y: 33 });
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['far', 'pawn']);
+ const farGhost = client.netIds.entityOf(
+ (serverApp.world.tryGet(far, Replicated) as { netId: number }).netId,
+ )!;
+ const farPos = clientApp.world.tryGet(farGhost, NetPos) as { x: number; y: number };
+ expect(farPos).toMatchObject({ x: 80, y: 33 });
+ });
+
+ it('deltas for out-of-interest entities never reach the client', async () => {
+ const { serverApp, clientApp, server, client, connId } = await makePair();
+ server.setInterestPolicy(radiusInterest(100, { position: posOf }));
+
+ spawnAt(serverApp, 'pawn', 0, 0, connId);
+ const far = spawnAt(serverApp, 'far', 500, 0);
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['pawn']);
+
+ // Move the far entity (still out of range): no ghost may appear and
+ // the client's netId table must not learn it.
+ serverApp.world.set(far, NetPos, { x: 510, y: 5 });
+ await step(serverApp, clientApp, 2);
+ expect(ghostNames(clientApp)).toEqual(['pawn']);
+ const farNetId = (serverApp.world.tryGet(far, Replicated) as { netId: number }).netId;
+ expect(client.netIds.entityOf(farNetId)).toBeUndefined();
+ });
+
+ it('a policy can never cull entities the connection owns', async () => {
+ const { serverApp, clientApp, server, connId } = await makePair();
+ // A hostile policy that claims nothing is relevant.
+ server.setInterestPolicy(() => new Set<Entity>());
+
+ spawnAt(serverApp, 'pawn', 12345, 0, connId);
+ spawnAt(serverApp, 'scenery', 0, 0);
+ await step(serverApp, clientApp);
+
+ expect(ghostNames(clientApp)).toEqual(['pawn']);
+ });
+
+ it('a server-despawned entity inside interest despawns the ghost', async () => {
+ const { serverApp, clientApp, server, connId } = await makePair();
+ server.setInterestPolicy(radiusInterest(100, { position: posOf }));
+
+ spawnAt(serverApp, 'pawn', 0, 0, connId);
+ const near = spawnAt(serverApp, 'near', 10, 0);
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['near', 'pawn']);
+
+ serverApp.world.despawn(near);
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['pawn']);
+ });
+
+ it('the initial state for a late joiner is policy-filtered', async () => {
+ const serverApp = makeApp();
+ const server = serverApp.getResource(Net).startServer();
+ server.setInterestPolicy(radiusInterest(100, { position: posOf }));
+
+ const laterApp = makeApp();
+ const [tc, td] = MemoryTransport.pair();
+ const connId = server.attachConnection(tc);
+ spawnAt(serverApp, 'pawn', 0, 0, connId);
+ spawnAt(serverApp, 'near', 20, 0);
+ spawnAt(serverApp, 'far', 900, 0);
+ await serverApp.tick(STEP); // entities become known before the join completes
+
+ await laterApp.getResource(Net).connect(td, { interpolationDelayTicks: 0 });
+ await step(serverApp, laterApp);
+ expect(ghostNames(laterApp)).toEqual(['near', 'pawn']);
+ });
+
+ it('radius policy fails open while the connection owns no positioned entity', async () => {
+ const { serverApp, clientApp, server } = await makePair();
+ server.setInterestPolicy(radiusInterest(100, { position: posOf }));
+
+ spawnAt(serverApp, 'a', 0, 0);
+ spawnAt(serverApp, 'b', 9999, 0);
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['a', 'b']);
+ });
+});
+
+describe('interest management (mid-session transitions)', () => {
+ it('installing a policy mid-session despawns now-irrelevant ghosts', async () => {
+ const { serverApp, clientApp, server, connId } = await makePair();
+
+ spawnAt(serverApp, 'pawn', 0, 0, connId);
+ spawnAt(serverApp, 'far', 800, 0);
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['far', 'pawn']); // broadcast path
+
+ server.setInterestPolicy(radiusInterest(100, { position: posOf }));
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['pawn']);
+ });
+
+ it('removing the policy catches connections up on everything they missed', async () => {
+ const { serverApp, clientApp, server, connId } = await makePair();
+ server.setInterestPolicy(radiusInterest(100, { position: posOf }));
+
+ spawnAt(serverApp, 'pawn', 0, 0, connId);
+ spawnAt(serverApp, 'far', 800, 0);
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['pawn']);
+
+ server.setInterestPolicy(null);
+ await step(serverApp, clientApp);
+ expect(ghostNames(clientApp)).toEqual(['far', 'pawn']);
+ });
+
+ it('two connections receive different worlds under the same policy', async () => {
+ const serverApp = makeApp();
+ const server = serverApp.getResource(Net).startServer();
+ server.setInterestPolicy(radiusInterest(100, { position: posOf }));
+
+ const appA = makeApp();
+ const appB = makeApp();
+ const [ta, tb] = MemoryTransport.pair();
+ const [tc, td] = MemoryTransport.pair();
+ const connA = server.attachConnection(ta);
+ const connB = server.attachConnection(tc);
+ await appA.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });
+ await appB.getResource(Net).connect(td, { interpolationDelayTicks: 0 });
+
+ spawnAt(serverApp, 'pawnA', 0, 0, connA);
+ spawnAt(serverApp, 'pawnB', 1000, 0, connB);
+ spawnAt(serverApp, 'nearA', 30, 0);
+ spawnAt(serverApp, 'nearB', 1030, 0);
+
+ await serverApp.tick(STEP);
+ await appA.tick(STEP);
+ await appB.tick(STEP);
+
+ expect(ghostNames(appA)).toEqual(['nearA', 'pawnA']);
+ expect(ghostNames(appB)).toEqual(['nearB', 'pawnB']);
+ });
+});