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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(net): client prediction + reconciliation — networking graduates from beta
yhh953fe554db86
diff --git a/docs/astro/src/content/docs/guides/networking.mdx b/docs/astro/src/content/docs/guides/networking.mdxindex 08c02bfe1..590c71212 100644--- a/docs/astro/src/content/docs/guides/networking.mdx+++ b/docs/astro/src/content/docs/guides/networking.mdx@@ -144,6 +144,52 @@ server.setInterestPolicy(({ connectionId, world, candidates }) => {- Installing, replacing, or removing the policy mid-session is safe — the nexttick reconciles every connection's ghost set.+### Client prediction — zero-latency input++Without prediction, your own pawn only moves after a full server round trip.+Enable prediction by handing the client the **same input-to-state function the+server's gameplay runs** — one function, both ends, no duplicated movement+rules:++```typescript+// The ONE movement rule, shared by both ends.+function applyMove(world, entity, actions, dt) {+ const move = actions.move;+ if (!move) return;+ const pos = world.tryGet(entity, NetPos);+ pos.x += move.x * SPEED * dt;+ pos.y += move.y * SPEED * dt;+ world.set(entity, NetPos, pos);+}++// SERVER gameplay (FixedUpdate): per-tick input via tickInputOf.+const input = server.tickInputOf(repl.owner);+if (input) applyMove(world, e, input.actions, time.fixedDelta);++// CLIENT: enable prediction; sendInput once per fixed tick.+await clientNet.connect(clientEnd, {+ prediction: { apply: applyMove },+});+clientNet.client.sendInput({ move: { x: 1, y: 0 } }); // pawn moves NOW+```++How it works: `sendInput` applies the command to your owned entities+immediately and keeps it in a pending buffer; the server consumes commands+**exactly one per fixed tick** (`tickInputOf` — use it instead of `inputOf`+for predicted gameplay) and acknowledges the consumed seq; every fixed tick+the client rebuilds each owned entity as *last authoritative state ⊕ replay of+unacknowledged commands*. Server-side corrections (walls, knockback) therefore+always win, and mispredictions can never accumulate — even fields the server+never re-sends snap back. Owned entities bypass snapshot interpolation.++- **Send an input every fixed tick** (an idle `{ move: {x:0,y:0} }` counts) —+ the server repeats the last command when the queue runs dry, so going silent+ means "keep doing that", not "stop".+- **Assign `Replicated.owner` at spawn** — ownership is part of the spawn+ payload.+- `apply` must depend only on world state + actions + dt: it re-runs during+ reconciliation.+## Best practices- **Use `NetChannel`** for anything beyond a trivial socket — routed types and RPCdiff --git a/docs/astro/src/content/docs/zh-cn/guides/networking.mdx b/docs/astro/src/content/docs/zh-cn/guides/networking.mdxindex 9713c55a8..1331e3cb0 100644--- a/docs/astro/src/content/docs/zh-cn/guides/networking.mdx+++ b/docs/astro/src/content/docs/zh-cn/guides/networking.mdx@@ -137,6 +137,44 @@ server.setInterestPolicy(({ connectionId, world, candidates }) => {无位置的实体恒相关;连接尚无带位置的自有实体时 fail-open(看到全部)。- 会话中安装/替换/移除策略都是安全的——下一 tick 会调和每个连接的 ghost 集。+### 客户端预测——零延迟输入++不开预测时,你自己的 pawn 要等一整个来回才动。开启预测的方式是把**服务器玩法+用的同一个"输入→状态"函数**交给客户端——一个函数、两端共用,移动规则没有第二份:++```typescript+// 唯一的移动规则,两端共用。+function applyMove(world, entity, actions, dt) {+ const move = actions.move;+ if (!move) return;+ const pos = world.tryGet(entity, NetPos);+ pos.x += move.x * SPEED * dt;+ pos.y += move.y * SPEED * dt;+ world.set(entity, NetPos, pos);+}++// 服务器玩法(FixedUpdate):用 tickInputOf 取每 tick 的输入。+const input = server.tickInputOf(repl.owner);+if (input) applyMove(world, e, input.actions, time.fixedDelta);++// 客户端:开启预测;每个固定 tick 调一次 sendInput。+await clientNet.connect(clientEnd, {+ prediction: { apply: applyMove },+});+clientNet.client.sendInput({ move: { x: 1, y: 0 } }); // pawn 立刻动+```++工作原理:`sendInput` 立即把指令应用到你拥有的实体并存入待确认缓冲;服务器+**每个固定 tick 恰好消费一条**指令(`tickInputOf`——预测级玩法用它替代+`inputOf`)并确认已消费的 seq;客户端每个固定 tick 把自有实体重建为+*最新权威状态 ⊕ 未确认指令的重放*。因此服务器侧的修正(墙体、击退)永远获胜,+误预测不可能累积——连服务器不再重发的字段也会被拉回。自有实体绕过快照插值。++- **每个固定 tick 都要发一条输入**(空闲时发 `{ move: {x:0,y:0} }` 也算)——+ 队列干涸时服务器会重复上一条指令,沉默意味着"继续保持",不是"停"。+- **`Replicated.owner` 在 spawn 时就要赋好**——归属随 spawn 载荷走。+- `apply` 只能依赖世界状态 + actions + dt:和解时它会被重放。+## 最佳实践- 超出简单套接字的场景**用 `NetChannel`**——按类型路由和 RPC 胜过一个巨大的 `onMessage` switch。diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 34fa2cdf3..5c5826e8f 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 · 48 beta · 1 deprecated+Symbols: 1116 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -772,7 +772,7 @@ p2x: numberp2y: number```-## BinaryHandler — type @beta+## BinaryHandler — type```(payload: Uint8Array) => void```@@ -2558,7 +2558,7 @@ trigger: string | undefined{ enable(): void; disable(): void; check(context: string): number; diagnose(): void; }```-## GameSocket — class @beta+## GameSocket — class```close: (code?: number, reason?: string) => voidconnect: () => void@@ -2572,7 +2572,7 @@ static new (options: GameSocketOptions): GameSocketstatic prototype: GameSocket```-## GameSocketOptions — type @beta+## GameSocketOptions — type```PlatformSocketOptions```@@ -2959,12 +2959,12 @@ enabled: booleanraycastTarget: boolean```-## InterestPolicy — type @beta+## InterestPolicy — type```(view: InterestView) => ReadonlySet<Entity> | 'all'```-## InterestView — interface @beta+## InterestView — interface```candidates: readonly number[]connectionId: number@@ -3392,7 +3392,7 @@ switches: Record<string, boolean> | undefineduniforms: Record<string, UniformValue> | undefined```-## MemoryTransport — class @beta+## MemoryTransport — class```dropPending: () => voidflush: (limit?: number) => void@@ -3426,19 +3426,19 @@ static prototype: Mesh2DPluginResourceDef<Mesh2DAPI>```-## MessageHandler — type @beta+## MessageHandler — type```(payload: T) => void```-## MessagePortLike — interface @beta+## MessagePortLike — interface```close: (() => void) | undefinedonmessage: ((event: { data: unknown; }) => void) | nullpostMessage: (data: unknown) => void```-## MessagePortTransport — class @beta+## MessagePortTransport — class```close: () => voidonMessage: ((data: string | ArrayBuffer) => void) | null@@ -3580,12 +3580,12 @@ overrides: PrefabOverride[]prefabPath: string```-## Net — const @beta+## Net — const```ResourceDef<NetSession>```-## NetChannel — class @beta+## NetChannel — class```dispose: (reason?: string) => voidhandle: <Req = unknown, Res = unknown>(type: string, handler: RequestHandler<Req, Res>) => () => void@@ -3598,22 +3598,22 @@ static new (transport: NetTransport, opts?: NetChannelOptions): NetChannelstatic prototype: NetChannel```-## NetChannelOptions — interface @beta+## NetChannelOptions — interface```requestTimeoutMs: number | undefined```-## NetGhost — const @beta+## NetGhost — const```ComponentDef<{}>```-## NetRoleKind — type @beta+## NetRoleKind — type```'offline' | 'server' | 'client'```-## NetSession — class @beta+## NetSession — class```client: ReplicationClient | nullconnect: (transport: NetTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>@@ -3625,7 +3625,7 @@ static new (app_: App): NetSessionstatic prototype: NetSession```-## NetTransport — interface @beta+## NetTransport — interface```onMessage: ((data: string | ArrayBuffer) => void) | nullsend: (data: string | ArrayBuffer) => void@@ -4333,6 +4333,12 @@ height: numberwidth: number```+## PredictionOptions — interface+```+apply: (world: World, entity: Entity, actions: Record<string, unknown>, dt: number) => void+maxPendingInputs: number | undefined+```+## PrefabComponentData — interface```data: Record<string, unknown>@@ -4552,17 +4558,17 @@ static prototype: QueryInstance<any>]```-## REPLICATION_CHANNEL — const @beta+## REPLICATION_CHANNEL — const```1```-## REPLICATION_PROTOCOL_VERSION — const @beta+## REPLICATION_PROTOCOL_VERSION — const```-1+2```-## RadiusInterestOptions — interface @beta+## RadiusInterestOptions — interface```position: ((world: World, entity: Entity) => { x: number; y: number; } | null) | undefined```@@ -4682,18 +4688,18 @@ UIElement = 7{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; submitAll(registry: { _cpp: CppRegistry; }, skipFlags: number, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }```-## Replicated — const @beta+## Replicated — const```ComponentDef<ReplicatedData>```-## ReplicatedData — interface @beta+## ReplicatedData — interface```netId: numberowner: number```-## ReplicationClient — class @beta+## ReplicationClient — class```applyPending: () => voidconnect: (transport: NetTransport) => Promise<void>@@ -4705,12 +4711,13 @@ ownsEntity: (entity: Entity) => booleansampleInterpolation: (deltaTicks: number) => voidsendInput: (actions: Record<string, unknown>) => voidserverTick: number+setFixedDelta: (dt: number) => voidtable: ReplicationTablestatic new (world: World, options?: ReplicationClientOptions): ReplicationClientstatic prototype: ReplicationClient```-## ReplicationPlugin — class @beta+## ReplicationPlugin — class```build: (app: App) => voidname: string@@ -4718,9 +4725,10 @@ static new (): ReplicationPluginstatic prototype: ReplicationPlugin```-## ReplicationServer — class @beta+## ReplicationServer — class```attachConnection: (transport: NetTransport) => number+beginTick: (fixedDelta: number) => voidclientIds: number[]connectionCount: numberdetachConnection: (id: number) => void@@ -4729,11 +4737,12 @@ netIds: NetIdssample: (tick: number) => voidsetInterestPolicy: (policy: InterestPolicy | null) => voidtable: ReplicationTable+tickInputOf: (connectionId: number) => ReplInputMsg | nullstatic new (world: World): ReplicationServerstatic prototype: ReplicationServer```-## RequestHandler — type @beta+## RequestHandler — type```(payload: Req) => Res | Promise<Res>```@@ -5325,7 +5334,7 @@ value: number | undefinedworld: World```-## SocketReadyState — type @beta+## SocketReadyState — type```PlatformSocketReadyState```@@ -6811,7 +6820,7 @@ y: numberPartial<Record<SideModuleId, EmscriptenFactory>>```-## WeChatSocket — class @beta+## WeChatSocket — class```close: (code?: number, reason?: string) => voidconnect: () => void@@ -7272,7 +7281,7 @@ Plugin<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>```-## createMemoryTransportPair — function @beta+## createMemoryTransportPair — function```(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]```@@ -7292,7 +7301,7 @@ Plugin(opts: SliderOptions): SliderHandle```-## createSocket — function @beta+## createSocket — function```(options: GameSocketOptions): PlatformSocket```@@ -8177,7 +8186,7 @@ PrefabsPlugin(rz: number, rw: number): number```-## radiusInterest — function @beta+## radiusInterest — function```(radius: number, options?: RadiusInterestOptions): InterestPolicy```@@ -8292,7 +8301,7 @@ PrefabsPlugin(def: BtDefinition, id: string, newParentId: string): BtDefinition```-## replicationPlugin — const @beta+## replicationPlugin — const```ReplicationPlugin```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 8981dc4b5..729d3e06e 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 · 50 beta · 1 deprecated+Symbols: 1115 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -767,7 +767,7 @@ p2x: numberp2y: number```-## BinaryHandler — type @beta+## BinaryHandler — type```(payload: Uint8Array) => void```@@ -2553,7 +2553,7 @@ trigger: string | undefined{ enable(): void; disable(): void; check(context: string): number; diagnose(): void; }```-## GameSocket — class @beta+## GameSocket — class```close: (code?: number, reason?: string) => voidconnect: () => void@@ -2567,7 +2567,7 @@ static new (options: GameSocketOptions): GameSocketstatic prototype: GameSocket```-## GameSocketOptions — type @beta+## GameSocketOptions — type```PlatformSocketOptions```@@ -2954,12 +2954,12 @@ enabled: booleanraycastTarget: boolean```-## InterestPolicy — type @beta+## InterestPolicy — type```(view: InterestView) => ReadonlySet<Entity> | 'all'```-## InterestView — interface @beta+## InterestView — interface```candidates: readonly number[]connectionId: number@@ -3387,7 +3387,7 @@ switches: Record<string, boolean> | undefineduniforms: Record<string, UniformValue> | undefined```-## MemoryTransport — class @beta+## MemoryTransport — class```dropPending: () => voidflush: (limit?: number) => void@@ -3421,19 +3421,19 @@ static prototype: Mesh2DPluginResourceDef<Mesh2DAPI>```-## MessageHandler — type @beta+## MessageHandler — type```(payload: T) => void```-## MessagePortLike — interface @beta+## MessagePortLike — interface```close: (() => void) | undefinedonmessage: ((event: { data: unknown; }) => void) | nullpostMessage: (data: unknown) => void```-## MessagePortTransport — class @beta+## MessagePortTransport — class```close: () => voidonMessage: ((data: string | ArrayBuffer) => void) | null@@ -3575,12 +3575,12 @@ overrides: PrefabOverride[]prefabPath: string```-## Net — const @beta+## Net — const```ResourceDef<NetSession>```-## NetChannel — class @beta+## NetChannel — class```dispose: (reason?: string) => voidhandle: <Req = unknown, Res = unknown>(type: string, handler: RequestHandler<Req, Res>) => () => void@@ -3593,22 +3593,22 @@ static new (transport: NetTransport, opts?: NetChannelOptions): NetChannelstatic prototype: NetChannel```-## NetChannelOptions — interface @beta+## NetChannelOptions — interface```requestTimeoutMs: number | undefined```-## NetGhost — const @beta+## NetGhost — const```ComponentDef<{}>```-## NetRoleKind — type @beta+## NetRoleKind — type```'offline' | 'server' | 'client'```-## NetSession — class @beta+## NetSession — class```client: ReplicationClient | nullconnect: (transport: NetTransport, options?: ReplicationClientOptions) => Promise<ReplicationClient>@@ -3620,7 +3620,7 @@ static new (app_: App): NetSessionstatic prototype: NetSession```-## NetTransport — interface @beta+## NetTransport — interface```onMessage: ((data: string | ArrayBuffer) => void) | nullsend: (data: string | ArrayBuffer) => void@@ -4328,6 +4328,12 @@ height: numberwidth: number```+## PredictionOptions — interface+```+apply: (world: World, entity: Entity, actions: Record<string, unknown>, dt: number) => void+maxPendingInputs: number | undefined+```+## PrefabComponentData — interface```data: Record<string, unknown>@@ -4547,17 +4553,17 @@ static prototype: QueryInstance<any>]```-## REPLICATION_CHANNEL — const @beta+## REPLICATION_CHANNEL — const```1```-## REPLICATION_PROTOCOL_VERSION — const @beta+## REPLICATION_PROTOCOL_VERSION — const```-1+2```-## RadiusInterestOptions — interface @beta+## RadiusInterestOptions — interface```position: ((world: World, entity: Entity) => { x: number; y: number; } | null) | undefined```@@ -4677,18 +4683,18 @@ UIElement = 7{ init(width: number, height: number): void; resize(width: number, height: number): void; beginFrame(elapsedSec?: number): void; updateTransforms(registry: { _cpp: CppRegistry; }): void; begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags?: number, clearColor?: { x: number; y: number; z: number; w: number; }, clearRect?: { x: number; y: number; w: number; h: number; }): void; flush(): void; end(): void; submitAll(registry: { _cpp: CppRegistry; }, skipFlags: number, vpX: number, vpY: number, vpW: number, vpH: number): void; setStage(stage: RenderStage): void; createRenderTarget(width: number, height: number, flags?: number): RenderTargetHandle; releaseRenderTarget(handle: RenderTargetHandle): void; getTargetTexture(handle: RenderTargetHandle): number; getTargetDepthTexture(handle: RenderTargetHandle): number; setClearColor(r: number, g: number, b: number, a: number): void; setViewport(x: number, y: number, w: number, h: number): void; setYSortLayers(mask: number): void; setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void; measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number; }; getStats(): RenderStats; captureNextFrame(): void; getCapturedData(): FrameCaptureData | null; hasCapturedData(): boolean; replayToDrawCall(drawCallIndex: number): void; getSnapshotImageData(): Promise<ImageData | null>; }```-## Replicated — const @beta+## Replicated — const```ComponentDef<ReplicatedData>```-## ReplicatedData — interface @beta+## ReplicatedData — interface```netId: numberowner: number```-## ReplicationClient — class @beta+## ReplicationClient — class```applyPending: () => voidconnect: (transport: NetTransport) => Promise<void>@@ -4700,12 +4706,13 @@ ownsEntity: (entity: Entity) => booleansampleInterpolation: (deltaTicks: number) => voidsendInput: (actions: Record<string, unknown>) => voidserverTick: number+setFixedDelta: (dt: number) => voidtable: ReplicationTablestatic new (world: World, options?: ReplicationClientOptions): ReplicationClientstatic prototype: ReplicationClient```-## ReplicationPlugin — class @beta+## ReplicationPlugin — class```build: (app: App) => voidname: string@@ -4713,9 +4720,10 @@ static new (): ReplicationPluginstatic prototype: ReplicationPlugin```-## ReplicationServer — class @beta+## ReplicationServer — class```attachConnection: (transport: NetTransport) => number+beginTick: (fixedDelta: number) => voidclientIds: number[]connectionCount: numberdetachConnection: (id: number) => void@@ -4724,11 +4732,12 @@ netIds: NetIdssample: (tick: number) => voidsetInterestPolicy: (policy: InterestPolicy | null) => voidtable: ReplicationTable+tickInputOf: (connectionId: number) => ReplInputMsg | nullstatic new (world: World): ReplicationServerstatic prototype: ReplicationServer```-## RequestHandler — type @beta+## RequestHandler — type```(payload: Req) => Res | Promise<Res>```@@ -5320,7 +5329,7 @@ value: number | undefinedworld: World```-## SocketReadyState — type @beta+## SocketReadyState — type```PlatformSocketReadyState```@@ -6806,7 +6815,7 @@ y: numberPartial<Record<SideModuleId, EmscriptenFactory>>```-## WeChatSocket — class @beta+## WeChatSocket — class```close: (code?: number, reason?: string) => voidconnect: () => void@@ -7267,7 +7276,7 @@ Plugin<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>```-## createMemoryTransportPair — function @beta+## createMemoryTransportPair — function```(options?: MemoryTransportOptions): [MemoryTransport, MemoryTransport]```@@ -7287,7 +7296,7 @@ Plugin(opts: SliderOptions): SliderHandle```-## createSocket — function @beta+## createSocket — function```(options: GameSocketOptions): PlatformSocket```@@ -8182,7 +8191,7 @@ PrefabsPlugin(rz: number, rw: number): number```-## radiusInterest — function @beta+## radiusInterest — function```(radius: number, options?: RadiusInterestOptions): InterestPolicy```@@ -8297,7 +8306,7 @@ PrefabsPlugin(def: BtDefinition, id: string, newParentId: string): BtDefinition```-## replicationPlugin — const @beta+## replicationPlugin — const```ReplicationPlugin```diff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex f440f8158..5c8242a4e 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -95,6 +95,7 @@ export {radiusInterest,type NetRoleKind, type ReplicatedData,type InterestPolicy, type InterestView, type RadiusInterestOptions,+ type PredictionOptions,} from './net/replication';// =============================================================================diff --git a/sdk/src/net/GameSocket.ts b/sdk/src/net/GameSocket.tsindex 0b881c228..0234b0e56 100644--- a/sdk/src/net/GameSocket.ts+++ b/sdk/src/net/GameSocket.ts@@ -3,8 +3,6 @@/*** @file GameSocket.ts* @brief Raw browser-WebSocket wrapper behind the platform socket seam.- *- * @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.tsindex 380d4124b..1815b2f08 100644--- a/sdk/src/net/MemoryTransport.ts+++ b/sdk/src/net/MemoryTransport.ts@@ -8,8 +8,6 @@* step deterministically. `manualFlush` holds frames until the test* pumps them, which is how delivery order, latency and packet* interleaving are simulated.- *- * @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.tsindex 2e7ca5476..f15455718 100644--- a/sdk/src/net/MessagePortTransport.ts+++ b/sdk/src/net/MessagePortTransport.ts@@ -7,8 +7,6 @@* workers) with no socket. Structured clone carries both wire planes* (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 will reshape this surface.*/import type { NetTransport } from './NetChannel';diff --git a/sdk/src/net/NetChannel.ts b/sdk/src/net/NetChannel.tsindex 48d721c8a..3bfcc5d4b 100644--- a/sdk/src/net/NetChannel.ts+++ b/sdk/src/net/NetChannel.ts@@ -7,8 +7,6 @@* is the single channel that gives them typed events (`on`/`send`) and* 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 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.tsindex 34c655f3e..11c3be162 100644--- a/sdk/src/net/WeChatSocket.ts+++ b/sdk/src/net/WeChatSocket.ts@@ -3,8 +3,6 @@/*** @file WeChatSocket.ts* @brief Raw wx.connectSocket wrapper behind the platform socket seam.- *- * @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.tsindex 596f0732d..8aa2da0e3 100644--- a/sdk/src/net/index.ts+++ b/sdk/src/net/index.ts@@ -3,8 +3,6 @@/*** @file index.ts* @brief Networking barrel: sockets, transports, NetChannel, replication.- *- * @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.tsindex 3f3d9db9d..7d1f431d1 100644--- a/sdk/src/net/replication/NetIds.ts+++ b/sdk/src/net/replication/NetIds.ts@@ -6,8 +6,6 @@* generation|index, recycled on despawn), so the wire never carries* 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 will reshape this surface.*/import type { Entity } from '../../types';diff --git a/sdk/src/net/replication/ReplicationPlugin.ts b/sdk/src/net/replication/ReplicationPlugin.tsindex f8fa04609..5e4fcda38 100644--- a/sdk/src/net/replication/ReplicationPlugin.ts+++ b/sdk/src/net/replication/ReplicationPlugin.ts@@ -8,8 +8,6 @@* FixedPostUpdate samples + broadcasts. Role gating is a resource,* 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 will reshape this surface.*/import type { App, Plugin } from '../../app';import { defineSystem, Schedule } from '../../system';@@ -92,7 +90,8 @@ export class ReplicationPlugin implements Plugin {Schedule.FixedPreUpdate,defineSystem([Res(Time)],- (_time: TimeData) => {+ (time: TimeData) => {+ session.client?.setFixedDelta(time.fixedDelta);session.client?.applyPending();},{ name: 'ReplicationApplySystem' },@@ -100,6 +99,20 @@ export class ReplicationPlugin implements Plugin {{ runIf: () => session.role === 'client' },);+ // Before gameplay: dequeue each connection's input command for this+ // tick (the exactly-once contract behind tickInputOf + prediction).+ app.addSystemToSchedule(+ Schedule.FixedPreUpdate,+ defineSystem(+ [Res(Time)],+ (time: TimeData) => {+ session.server?.beginTick(time.fixedDelta);+ },+ { name: 'ReplicationBeginTickSystem' },+ ),+ { runIf: () => session.role === 'server' },+ );+app.addSystemToSchedule(Schedule.FixedPostUpdate,defineSystem(diff --git a/sdk/src/net/replication/client.ts b/sdk/src/net/replication/client.tsindex bf1db852f..a30f95ace 100644--- a/sdk/src/net/replication/client.ts+++ b/sdk/src/net/replication/client.ts@@ -9,7 +9,17 @@* deterministic point in the frame, not mid-schedule on socket* timing.*- * @beta Pre-1.0 networking: client prediction will reshape this surface.+ * With {@link PredictionOptions} enabled, the entities this connection+ * owns are simulated locally: `sendInput` applies the command to them+ * immediately (zero perceived latency) and keeps it in a pending+ * buffer; authoritative state for owned entities lands in a shadow+ * "authority copy" instead of the live components; each fixed tick the+ * live state is rebuilt as authority ⊕ replay of the unacknowledged+ * commands (one server tick each — the server consumes the input+ * queue at the same cadence, see `tickInputOf`). Mispredictions can+ * therefore never accumulate: every field snaps back to the last+ * authoritative value before the replay. Owned entities bypass+ * snapshot interpolation entirely.*/import type { World } from '../../world';import type { Entity } from '../../types';@@ -20,17 +30,32 @@ import { NetChannel, type NetTransport } from '../NetChannel';import { log } from '../../logger';import {REPLICATION_CHANNEL, REPLICATION_PROTOCOL_VERSION, ReplMsg,- type ReplDespawnBatch, type ReplHelloRequest, type ReplHelloResponse,+ type ReplAckMsg, type ReplDespawnBatch, type ReplHelloRequest, type ReplHelloResponse,type ReplInputMsg, type ReplSpawnBatch, type ReplSpawnEntity,} from './protocol';import {- buildReplicationTable, decodeStateFrame, tableSchemas,+ buildReplicationTable, cloneValue, decodeStateFrame, tableSchemas,type EntityRefMap, type ReplicationTable, type StateFrame,} from './codec';-import { NetGhost, Replicated } from './components';+import { NetGhost, Replicated, type ReplicatedData } from './components';import { NetIds } from './NetIds';import { InterpolationState } from './interpolation';+/**+ * Client-side prediction for owned entities. `apply` is the same input-to-+ * state logic the server's gameplay runs (register one function, use it on+ * both ends — the single source of the movement rules); with it enabled,+ * `sendInput` also applies the command locally and unacknowledged commands+ * replay on top of every authoritative update.+ */+export interface PredictionOptions {+ /** Advance one owned entity by one fixed tick of `actions`. Must depend+ * only on world state + actions + dt (it re-runs during reconciliation). */+ apply: (world: World, entity: Entity, actions: Record<string, unknown>, dt: number) => void;+ /** Cap on unacknowledged commands kept for replay (default 120). */+ maxPendingInputs?: number;+}+export interface ReplicationClientOptions {/*** How many server ticks the presented state trails the newest received@@ -38,6 +63,8 @@ export interface ReplicationClientOptions {* 0 disables buffering (state applies the moment it drains).*/interpolationDelayTicks?: number;+ /** Enable client-side prediction for the entities this connection owns. */+ prediction?: PredictionOptions;}export class ReplicationClient {@@ -52,11 +79,21 @@ export class ReplicationClient {private readonly pendingDespawns_: ReplDespawnBatch[] = [];private readonly interp_: InterpolationState | null;private inputSeq_ = 0;+ private readonly prediction_: PredictionOptions | null;+ /** Sent-but-unacknowledged input commands, oldest first (replay order). */+ private readonly pendingInputs_: ReplInputMsg[] = [];+ private ackedSeq_ = 0;+ /** Last authoritative value of every replicated field of every OWNED+ * entity: netId → componentId → field record. Deltas land here (never in+ * the live components); reconciliation rebuilds live = this ⊕ replay. */+ private readonly authority_ = new Map<number, Map<number, Record<string, unknown>>>();+ private fixedDelta_ = 1 / 60;constructor(world: World, options: ReplicationClientOptions = {}) {this.world_ = world;const delay = options.interpolationDelayTicks ?? 2;this.interp_ = delay > 0 ? new InterpolationState(delay) : null;+ this.prediction_ = options.prediction ?? null;world.onDespawn((e) => this.netIds_.unregisterEntity(e));}@@ -99,6 +136,9 @@ export class ReplicationClient {// step applies them, so ordering stays deterministic either way.channel.on<ReplSpawnBatch>(ReplMsg.spawn, (batch) => this.pendingSpawns_.push(batch));channel.on<ReplDespawnBatch>(ReplMsg.despawn, (batch) => this.pendingDespawns_.push(batch));+ channel.on<ReplAckMsg>(ReplMsg.ack, (ack) => {+ if (ack.seq > this.ackedSeq_) this.ackedSeq_ = ack.seq;+ });channel.onBinary(REPLICATION_CHANNEL, (payload) => {// Copy out: the payload view may alias a transport-owned buffer.this.pendingFrames_.push(payload.slice());@@ -122,6 +162,12 @@ export class ReplicationClient {}this.connectionId_ = res.connectionId;this.serverTick_ = res.tick;+ if (res.fixedDelta > 0) this.fixedDelta_ = res.fixedDelta;+ }++ /** @internal Keep the replay dt in lockstep with the app (plugin-fed). */+ setFixedDelta(dt: number): void {+ if (dt > 0) this.fixedDelta_ = dt;}disconnect(): void {@@ -131,10 +177,21 @@ export class ReplicationClient {}/** Send an input command (typically the InputMap's evaluated action values,- * once per fixed tick). The seq stamp makes stale deliveries harmless. */+ * once per fixed tick — with prediction enabled that cadence is the+ * contract, since the server consumes one command per tick). The seq+ * stamp makes stale deliveries harmless. With prediction the command also+ * applies to the owned entities immediately. */sendInput(actions: Record<string, unknown>): void {if (!this.channel_) return;- this.channel_.send<ReplInputMsg>(ReplMsg.input, { seq: ++this.inputSeq_, actions });+ const msg: ReplInputMsg = { seq: ++this.inputSeq_, actions };+ this.channel_.send<ReplInputMsg>(ReplMsg.input, msg);+ if (!this.prediction_) return;+ this.pendingInputs_.push(msg);+ const cap = this.prediction_.maxPendingInputs ?? 120;+ if (this.pendingInputs_.length > cap) this.pendingInputs_.shift();+ for (const e of this.ownedEntities_()) {+ this.prediction_.apply(this.world_, e, actions, this.fixedDelta_);+ }}/** True when this client's connection owns the entity (Replicated.owner). */@@ -144,7 +201,9 @@ export class ReplicationClient {}/** Apply everything received since the last fixed step. Spawns before- * state (a frame may reference an entity spawned in the same flush). */+ * state (a frame may reference an entity spawned in the same flush).+ * With prediction enabled, ends by reconciling every owned entity:+ * live state ← authority copy ⊕ replay of unacknowledged inputs. */applyPending(): void {while (this.pendingSpawns_.length > 0) {this.applySpawnBatch_(this.pendingSpawns_.shift()!);@@ -155,6 +214,68 @@ export class ReplicationClient {while (this.pendingDespawns_.length > 0) {this.applyDespawnBatch_(this.pendingDespawns_.shift()!);}+ if (this.prediction_) {+ while (this.pendingInputs_.length > 0 && this.pendingInputs_[0].seq <= this.ackedSeq_) {+ this.pendingInputs_.shift();+ }+ this.reconcilePredicted_();+ }+ }++ /** Rebuild every owned entity's live state as authority ⊕ pending replay.+ * Idempotent — running it on a tick with no new data reproduces the same+ * values, so it runs unconditionally each fixed step. */+ private reconcilePredicted_(): void {+ const owned = this.ownedEntities_();+ if (owned.length === 0) return;+ for (const e of owned) {+ const netId = this.netIds_.netIdOf(e);+ if (netId === undefined) continue;+ const perComp = this.authority_.get(netId);+ if (!perComp) continue;+ for (const [componentId, snap] of perComp) {+ const te = this.table.entries[componentId];+ if (!te) continue;+ const existing = this.world_.tryGet(e, te.def) as Record<string, unknown> | null;+ const target = existing ?? {};+ for (const f of te.fields) {+ // Clone: replay mutates live objects in place; the+ // authority copy must never alias them.+ if (f in snap) target[f] = cloneValue(snap[f]);+ }+ if (existing) {+ this.world_.set(e, te.def, target);+ } else {+ this.world_.insert(e, te.def, target);+ }+ }+ }+ // Replay tick-by-tick across all owned entities — the same order the+ // server applies the queue to the connection's entities.+ for (const input of this.pendingInputs_) {+ for (const e of owned) {+ this.prediction_!.apply(this.world_, e, input.actions, this.fixedDelta_);+ }+ }+ }++ private ownedEntities_(): Entity[] {+ const out: Entity[] = [];+ if (this.connectionId_ === 0) return out;+ for (const e of this.world_.getEntitiesWithComponents([Replicated])) {+ const repl = this.world_.tryGet(e, Replicated) as ReplicatedData | null;+ if (repl && repl.owner === this.connectionId_) out.push(e);+ }+ return out;+ }++ /** Whether this netId's state is under local prediction (owned + enabled). */+ private isPredicted_(netId: number): boolean {+ if (!this.prediction_) return false;+ const e = this.netIds_.entityOf(netId);+ if (e === undefined || !this.world_.valid(e)) return false;+ const repl = this.world_.tryGet(e, Replicated) as ReplicatedData | null;+ return repl !== null && repl.owner === this.connectionId_;}private applySpawnBatch_(batch: ReplSpawnBatch): void {@@ -182,6 +303,22 @@ export class ReplicationClient {}this.world_.insert(e, NetGhost, {});this.netIds_.register(spawn.netId, e);+ this.seedAuthority_(spawn.netId, e);+ }++ /** Seed the authority copy for a freshly spawned OWNED entity from its+ * just-loaded state (the spawn payload IS the authoritative baseline). */+ private seedAuthority_(netId: number, e: Entity): void {+ if (!this.isPredicted_(netId)) return;+ const perComp = new Map<number, Record<string, unknown>>();+ 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>;+ const snap: Record<string, unknown> = {};+ for (const f of te.fields) snap[f] = cloneValue(data[f]);+ perComp.set(te.id, snap);+ }+ this.authority_.set(netId, perComp);}private remapEntityRefs_(type: string, data: Record<string, unknown>): Record<string, unknown> {@@ -201,6 +338,7 @@ export class ReplicationClient {const e = this.netIds_.entityOf(netId);this.netIds_.unregister(netId);this.interp_?.drop(netId);+ this.authority_.delete(netId);if (e !== undefined && this.world_.valid(e)) {this.world_.despawn(e);}@@ -210,6 +348,13 @@ export class ReplicationClient {private applyStateFrame_(frame: StateFrame): void {if (frame.tick > this.serverTick_) this.serverTick_ = frame.tick;for (const entry of frame.entries) {+ // Predicted (owned) entities: authoritative values land in the+ // authority copy — never the live components, never interpolation.+ // Reconciliation rebuilds the live state at the end of the flush.+ if (this.isPredicted_(entry.netId)) {+ this.updateAuthority_(entry.netId, entry.componentId, entry.fieldMask, entry.values);+ continue;+ }if (this.interp_) {let v = 0;const te = this.table.entries[entry.componentId];@@ -225,6 +370,27 @@ export class ReplicationClient {}}+ private updateAuthority_(netId: number, componentId: number, fieldMask: number, values: unknown[]): void {+ const te = this.table.entries[componentId];+ if (!te) return;+ let perComp = this.authority_.get(netId);+ if (!perComp) {+ perComp = new Map();+ this.authority_.set(netId, perComp);+ }+ let snap = perComp.get(componentId);+ if (!snap) {+ snap = {};+ perComp.set(componentId, snap);+ }+ let v = 0;+ for (let i = 0; i < te.fields.length; i++) {+ if (fieldMask & (1 << i)) {+ snap[te.fields[i]] = values[v++];+ }+ }+ }+private applyEntryNow_(netId: number, componentId: number, fieldMask: number, values: unknown[]): void {const e = this.netIds_.entityOf(netId);if (e === undefined || !this.world_.valid(e)) return;diff --git a/sdk/src/net/replication/codec.ts b/sdk/src/net/replication/codec.tsindex 15bf91508..f04c4fbc2 100644--- a/sdk/src/net/replication/codec.ts+++ b/sdk/src/net/replication/codec.ts@@ -18,8 +18,6 @@* string → u16 len + utf8, plain object → keys recursively in* declaration order, entity-ref field → u32 netId (remapped at both* ends), anything else → JSON string fallback.- *- * @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';@@ -56,6 +54,19 @@ function buildShape(defaultValue: unknown): FieldShape {}}+/**+ * Deep-clone a replicated field value (plain JSON-shaped data). Shared by the+ * server's shadow snapshots and the client's prediction authority copies —+ * both must never alias live component objects.+ */+export function cloneValue<T>(v: T): T {+ if (v === null || typeof v !== 'object') return v;+ if (Array.isArray(v)) return v.map(cloneValue) as T;+ const out: Record<string, unknown> = {};+ for (const k in v) out[k] = cloneValue((v as Record<string, unknown>)[k]);+ return out as T;+}+// =============================================================================// Replication table// =============================================================================diff --git a/sdk/src/net/replication/components.ts b/sdk/src/net/replication/components.tsindex f7ff355ad..25d6d395c 100644--- a/sdk/src/net/replication/components.ts+++ b/sdk/src/net/replication/components.ts@@ -8,8 +8,6 @@* annotations / metadata), not here. `NetGhost` tags the client-side* proxies so local simulation (physics, AI) can yield to the incoming* authoritative state via Without(NetGhost) queries.- *- * @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.tsindex b47a525d9..03585d73b 100644--- a/sdk/src/net/replication/index.ts+++ b/sdk/src/net/replication/index.ts@@ -11,6 +11,7 @@ export {type ReplSpawnBatch,type ReplDespawnBatch,type ReplInputMsg,+ type ReplAckMsg,} from './protocol';export {buildReplicationTable,@@ -18,6 +19,7 @@ export {diffSchemas,encodeValue,decodeValue,+ cloneValue,decodeStateFrame,ByteWriter,ByteReader,@@ -38,7 +40,7 @@ export {} from './interest';export { NetIds } from './NetIds';export { ReplicationServer } from './server';-export { ReplicationClient, type ReplicationClientOptions } from './client';+export { ReplicationClient, type ReplicationClientOptions, type PredictionOptions } from './client';export { lerpValue, InterpolationState, ComponentBuffer } from './interpolation';export {ReplicationPlugin,diff --git a/sdk/src/net/replication/interest.ts b/sdk/src/net/replication/interest.tsindex c104762a4..d8cdb644c 100644--- a/sdk/src/net/replication/interest.ts+++ b/sdk/src/net/replication/interest.ts@@ -11,8 +11,6 @@* 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';diff --git a/sdk/src/net/replication/interpolation.ts b/sdk/src/net/replication/interpolation.tsindex db14e49d6..3c3da886a 100644--- a/sdk/src/net/replication/interpolation.ts+++ b/sdk/src/net/replication/interpolation.ts@@ -10,8 +10,6 @@* across frame-rate mismatch and delivery jitter. Continuous values* 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 will reshape this surface.*/import type { FieldShape } from './codec';diff --git a/sdk/src/net/replication/protocol.ts b/sdk/src/net/replication/protocol.tsindex d8fd495e5..5c3bdf4ec 100644--- a/sdk/src/net/replication/protocol.ts+++ b/sdk/src/net/replication/protocol.ts@@ -8,12 +8,10 @@* channel {@link REPLICATION_CHANNEL} (see codec.ts for the frame* layout). Version or schema drift refuses the connection at* handshake — never a silently mismatched simulation.- *- * @beta Pre-1.0 networking: client prediction will reshape this surface.*/import type { SceneComponentData } from '../../scene';-export const REPLICATION_PROTOCOL_VERSION = 1;+export const REPLICATION_PROTOCOL_VERSION = 2;/** NetChannel binary channel id the snapshot frames ride on. */export const REPLICATION_CHANNEL = 1;@@ -24,6 +22,7 @@ export const ReplMsg = {spawn: 'repl:spawn',despawn: 'repl:despawn',input: 'repl:input',+ ack: 'repl:ack',} as const;/** One component's replication schema, as exchanged for handshake comparison. */@@ -47,6 +46,8 @@ export interface ReplHelloOk {connectionId: number;/** The server's current fixed tick, so the client can offset its buffers. */tick: number;+ /** The server's fixed timestep in seconds (0 if it hasn't ticked yet) —+ * the dt client prediction replays unacknowledged inputs with. */fixedDelta: number;}@@ -82,10 +83,23 @@ export interface ReplDespawnBatch {* Client → server input command. `actions` is game-defined (typically one* InputMap's evaluated values per fixed tick: booleans, axes, {x,y} pairs);* `seq` is a client-monotonic counter so stale deliveries never overwrite- * newer state. The server keeps the latest per connection and gameplay reads- * it via `ReplicationServer.inputOf(connectionId)`.+ * newer state. The server keeps the latest per connection for gameplay that+ * reads `ReplicationServer.inputOf(connectionId)`, and additionally queues+ * commands for exactly-once per-tick consumption via `tickInputOf` — the+ * contract client prediction replays against.*/export interface ReplInputMsg {seq: number;actions: Record<string, unknown>;}++/**+ * Server → client input acknowledgement: the authoritative state at `tick`+ * incorporates this connection's inputs up to and including `seq`. Client+ * prediction drops acknowledged inputs and replays the rest on top of the+ * authoritative state. Sent only when the acknowledged seq advances.+ */+export interface ReplAckMsg {+ tick: number;+ seq: number;+}diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.tsindex 754030164..ec19d53f9 100644--- a/sdk/src/net/replication/server.ts+++ b/sdk/src/net/replication/server.ts@@ -15,8 +15,6 @@* 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';@@ -27,11 +25,11 @@ import { NetChannel, type NetTransport } from '../NetChannel';import { log } from '../../logger';import {REPLICATION_CHANNEL, REPLICATION_PROTOCOL_VERSION, ReplMsg,- type ReplDespawnBatch, type ReplHelloRequest, type ReplHelloResponse,+ type ReplAckMsg, type ReplDespawnBatch, type ReplHelloRequest, type ReplHelloResponse,type ReplInputMsg, type ReplSpawnBatch, type ReplSpawnEntity,} from './protocol';import {- buildReplicationTable, diffSchemas, tableSchemas, FrameWriter,+ buildReplicationTable, cloneValue, diffSchemas, tableSchemas, FrameWriter,type EntityRefMap, type ReplicationTable, type ReplicationTableEntry,} from './codec';import { Replicated, type ReplicatedData } from './components';@@ -45,10 +43,20 @@ interface Connection {ready: boolean;/** Latest input command from this connection (stale seq never overwrites). */input: ReplInputMsg | null;+ /** Queued input commands, consumed exactly one per fixed tick (beginTick). */+ queue: ReplInputMsg[];+ /** The command this tick's gameplay runs against (repeats on starvation). */+ applied: ReplInputMsg | null;+ /** Highest input seq acknowledged to the client (0 = none yet). */+ ackedSeq: number;/** Entities this connection currently knows (has been sent a spawn for). */interest: Set<Entity>;}+/** Queued-but-unconsumed input cap; beyond it the oldest commands drop (a+ * client flooding faster than the tick rate loses history, not the server). */+const INPUT_QUEUE_CAP = 128;+/** 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. */@@ -60,14 +68,6 @@ interface DirtyEntry {data: Record<string, unknown>;}-function deepClone<T>(v: T): T {- if (v === null || typeof v !== 'object') return v;- if (Array.isArray(v)) return v.map(deepClone) as T;- const out: Record<string, unknown> = {};- for (const k in v) out[k] = deepClone((v as Record<string, unknown>)[k]);- return out as T;-}-function fieldEqual(a: unknown, b: unknown): boolean {if (a === b) return true;if (a === null || b === null || typeof a !== 'object' || typeof b !== 'object') return false;@@ -93,6 +93,7 @@ export class ReplicationServer {private readonly knownNetIds_ = new Map<Entity, number>();private policy_: InterestPolicy | null = null;private tick_ = 0;+ private fixedDelta_ = 0;constructor(world: World) {this.world_ = world;@@ -149,11 +150,19 @@ export class ReplicationServer {attachConnection(transport: NetTransport): number {const id = this.nextConnectionId_++;const channel = new NetChannel(transport);- const conn: Connection = { id, channel, ready: false, input: null, interest: new Set() };+ const conn: Connection = {+ id, channel, ready: false,+ input: null, queue: [], applied: null, ackedSeq: 0,+ interest: new Set(),+ };this.connections_.set(id, conn);channel.on<ReplInputMsg>(ReplMsg.input, (msg) => {if (!conn.input || msg.seq > conn.input.seq) conn.input = msg;+ // The per-tick queue keeps every command in order for exactly-once+ // consumption (tickInputOf) — the contract prediction replays against.+ conn.queue.push(msg);+ if (conn.queue.length > INPUT_QUEUE_CAP) conn.queue.shift();});channel.handle<ReplHelloRequest, ReplHelloResponse>(ReplMsg.hello, (req) => {@@ -170,7 +179,7 @@ export class ReplicationServer {// The initial world spawn goes out on the next microtask — after this// response is on the wire — and flips the connection hot.Promise.resolve().then(() => this.sendInitialState_(conn));- return { ok: true, connectionId: id, tick: this.tick_, fixedDelta: 0 };+ return { ok: true, connectionId: id, tick: this.tick_, fixedDelta: this.fixedDelta_ };});return id;@@ -185,11 +194,37 @@ export class ReplicationServer {/** The latest input command a connection sent (null before the first).* Gameplay reads this in FixedUpdate and applies it to the entities the- * connection owns (Replicated.owner). */+ * connection owns (Replicated.owner). Latest-persists: a held command+ * applies every tick until replaced. */inputOf(connectionId: number): ReplInputMsg | null {return this.connections_.get(connectionId)?.input ?? null;}+ /**+ * The input command dequeued for THIS fixed tick — each command is+ * consumed exactly once, in order, one per tick ({@link beginTick}); when+ * the queue runs dry the last command repeats (network jitter must not+ * stall a held input). This is the accessor prediction-grade gameplay+ * applies in FixedUpdate: the server acknowledges the consumed seq, and+ * the client replays exactly the unacknowledged commands, one tick each.+ */+ tickInputOf(connectionId: number): ReplInputMsg | null {+ return this.connections_.get(connectionId)?.applied ?? null;+ }++ /**+ * Start a fixed tick: dequeue each connection's next input command (the+ * plugin calls this in FixedPreUpdate, before gameplay). `fixedDelta` is+ * remembered for the handshake so clients replay with the server's dt.+ */+ beginTick(fixedDelta: number): void {+ if (fixedDelta > 0) this.fixedDelta_ = fixedDelta;+ for (const conn of this.connections_.values()) {+ const next = conn.queue.shift();+ if (next) conn.applied = next;+ }+ }+/** One replication tick: spawns/despawns on the control plane, dirty* fields as binary delta frames (one shared broadcast without a policy,* one filtered frame per connection with one). Runs in FixedPostUpdate. */@@ -232,6 +267,14 @@ export class ReplicationServer {} else {this.sampleWithInterest_(tick, despawned, dirty);}++ // Acknowledge consumed inputs: this tick's state incorporates each+ // connection's commands through the seq its gameplay ran against.+ for (const conn of this.connections_.values()) {+ if (!conn.ready || !conn.applied || conn.applied.seq <= conn.ackedSeq) continue;+ conn.ackedSeq = conn.applied.seq;+ this.sendTo_(conn, (c) => c.channel.send<ReplAckMsg>(ReplMsg.ack, { tick, seq: conn.ackedSeq }));+ }}/** Fast path (no policy): everything to every ready connection on shared@@ -373,7 +416,7 @@ export class ReplicationServer {if (!this.world_.has(e, te.def)) continue;const data = this.world_.tryGet(e, te.def) as Record<string, unknown>;const snap: Record<string, unknown> = {};- for (const f of te.fields) snap[f] = deepClone(data[f]);+ for (const f of te.fields) snap[f] = cloneValue(data[f]);perComp.set(te.id, snap);}this.shadow_.set(e, perComp);@@ -429,7 +472,7 @@ export class ReplicationServer {const f = te.fields[i];if (!(f in snap) || !fieldEqual(data[f], snap[f])) {mask |= 1 << i;- snap[f] = deepClone(data[f]);+ snap[f] = cloneValue(data[f]);}}if (mask !== 0) {diff --git a/sdk/tests/replication-prediction.test.ts b/sdk/tests/replication-prediction.test.tsnew file mode 100644index 000000000..57beeb925--- /dev/null+++ b/sdk/tests/replication-prediction.test.ts@@ -0,0 +1,233 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * Client-side prediction + reconciliation: owned entities respond to input+ * immediately (before any server round trip), unacknowledged commands replay+ * on top of every authoritative update (authority ⊕ replay), server-side+ * corrections win, and mispredictions can never accumulate because the live+ * state is rebuilt from the authority copy every fixed step. The server's+ * per-tick input queue (tickInputOf) is the exactly-once contract that makes+ * the replay deterministic.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { App } from '../src/app';+import { defineComponent, clearUserComponents } from '../src/component';+import { defineSystem, Schedule, GetWorld } from '../src/system';+import { MemoryTransport } from '../src/net/MemoryTransport';+import { replicationPlugin, Net, Replicated, type ReplicationServer } from '../src/net/replication';+import type { Entity } from '../src/types';+import type { World } from '../src/world';++const STEP = 1 / 60;+const SPEED = 600; // units/second → 10 units per tick++let NetPos: ReturnType<typeof defineComponent<{ x: number; y: number }>>;++beforeEach(() => {+ clearUserComponents();+ NetPos = defineComponent('NetPos', { x: 0, y: 0 }, { replicatedFields: ['x', 'y'] });+});++/** The ONE movement function both ends run — the single source of the rules. */+function applyMove(world: World, entity: Entity, actions: Record<string, unknown>, dt: number): void {+ const move = actions.move as { x: number; y: number } | undefined;+ if (!move) return;+ const pos = world.tryGet(entity, NetPos) as { x: number; y: number } | null;+ if (!pos) return;+ pos.x += move.x * SPEED * dt;+ pos.y += move.y * SPEED * dt;+ world.set(entity, NetPos, pos);+}++function makeApp(): App {+ const app = App.new();+ app.addPlugin(replicationPlugin);+ return app;+}++/** Server gameplay: apply each connection's PER-TICK input to its entities. */+function addServerInputSystem(serverApp: App, server: ReplicationServer): void {+ serverApp.addSystemToSchedule(Schedule.FixedUpdate, defineSystem(+ [GetWorld()],+ (world) => {+ for (const e of world.getEntitiesWithComponents([Replicated])) {+ const repl = world.tryGet(e, Replicated)!;+ if (repl.owner === 0) continue;+ const input = server.tickInputOf(repl.owner);+ if (input) applyMove(world as World, e as Entity, input.actions, STEP);+ }+ },+ { name: 'ApplyPlayerInput' },+ ));+}++async function makePredictedPair(interpolationDelayTicks = 0) {+ const serverApp = makeApp();+ const clientApp = makeApp();+ const server = serverApp.getResource(Net).startServer();+ addServerInputSystem(serverApp, server);+ const [ta, tb] = MemoryTransport.pair();+ const connId = server.attachConnection(ta);+ const client = await clientApp.getResource(Net).connect(tb, {+ interpolationDelayTicks,+ prediction: { apply: applyMove },+ });++ const pawn = serverApp.world.spawn('pawn');+ serverApp.world.insert(pawn, Replicated, { owner: connId });+ serverApp.world.insert(pawn, NetPos, {});+ await serverApp.tick(STEP);+ await clientApp.tick(STEP);+ const ghost = clientApp.world.getEntitiesWithComponents([Replicated])[0];+ expect(client.ownsEntity(ghost)).toBe(true);+ return { serverApp, clientApp, server, client, connId, pawn, ghost };+}++const posX = (app: App, e: Entity): number => (app.world.tryGet(e, NetPos) as { x: number }).x;++describe('client prediction', () => {+ it('an owned entity moves the moment input is sent — no server round trip', async () => {+ const { serverApp, clientApp, pawn, ghost, client } = await makePredictedPair();++ client.sendInput({ move: { x: 1, y: 0 } });+ expect(posX(clientApp, ghost)).toBeCloseTo(10, 5); // immediately+ expect(posX(serverApp, pawn)).toBe(0); // server hasn't ticked++ await serverApp.tick(STEP);+ await clientApp.tick(STEP);+ expect(posX(serverApp, pawn)).toBeCloseTo(10, 5);+ expect(posX(clientApp, ghost)).toBeCloseTo(10, 5); // converged, no rubber-band+ });++ it('prediction stays ahead under latency and converges exactly when acks land', async () => {+ const serverApp = makeApp();+ const clientApp = makeApp();+ const server = serverApp.getResource(Net).startServer();+ addServerInputSystem(serverApp, server);+ const [ta, tb] = MemoryTransport.pair({ manualFlush: true });+ const connId = server.attachConnection(ta);+ const connectP = clientApp.getResource(Net).connect(tb, {+ interpolationDelayTicks: 0,+ prediction: { apply: applyMove },+ });+ for (let i = 0; i < 8; i++) { ta.flush(); tb.flush(); await Promise.resolve(); }+ const client = await connectP;++ const pawn = serverApp.world.spawn('pawn');+ serverApp.world.insert(pawn, Replicated, { owner: connId });+ serverApp.world.insert(pawn, NetPos, {});+ await serverApp.tick(STEP);+ ta.flush(); tb.flush();+ await clientApp.tick(STEP);+ const ghost = clientApp.world.getEntitiesWithComponents([Replicated])[0];++ // Three inputs while the wire is held: the client is 3 ticks ahead.+ for (let i = 0; i < 3; i++) client.sendInput({ move: { x: 1, y: 0 } });+ expect(posX(clientApp, ghost)).toBeCloseTo(30, 5);+ expect(posX(serverApp, pawn)).toBe(0);++ // Release the wire: the server consumes the queue one command per tick.+ ta.flush(); tb.flush();+ for (let i = 0; i < 3; i++) {+ await serverApp.tick(STEP);+ ta.flush(); tb.flush();+ await clientApp.tick(STEP);+ }+ expect(posX(serverApp, pawn)).toBeCloseTo(30, 5);+ expect(posX(clientApp, ghost)).toBeCloseTo(30, 5);+ });++ it('a server-side correction wins over the prediction', async () => {+ const { serverApp, clientApp, ghost, pawn, client } = await makePredictedPair();++ // Server-only rule the client's apply knows nothing about: a wall at x=25.+ serverApp.addSystemToSchedule(Schedule.FixedUpdate, defineSystem(+ [GetWorld()],+ (world) => {+ const pos = world.tryGet(pawn, NetPos) as { x: number; y: number } | null;+ if (pos && pos.x > 25) { pos.x = 25; world.set(pawn, NetPos, pos); }+ },+ { name: 'WallClamp' },+ ));++ for (let i = 0; i < 3; i++) client.sendInput({ move: { x: 1, y: 0 } });+ expect(posX(clientApp, ghost)).toBeCloseTo(30, 5); // optimistic++ for (let i = 0; i < 4; i++) {+ await serverApp.tick(STEP);+ await clientApp.tick(STEP);+ }+ expect(posX(serverApp, pawn)).toBeCloseTo(25, 5);+ expect(posX(clientApp, ghost)).toBeCloseTo(25, 5); // corrected+ });++ it('local tampering cannot drift: live state is rebuilt from authority every step', async () => {+ const { serverApp, clientApp, ghost, client } = await makePredictedPair();++ client.sendInput({ move: { x: 1, y: 0 } });+ await serverApp.tick(STEP);+ await clientApp.tick(STEP);+ expect(posX(clientApp, ghost)).toBeCloseTo(10, 5);++ // A wayward local write to a predicted entity — the server sends no+ // new delta for x (it idles on the next command), yet reconciliation+ // snaps the value back to the authority copy.+ clientApp.world.set(ghost, NetPos, { x: 999, y: 0 });+ client.sendInput({ move: { x: 0, y: 0 } }); // the per-tick idle command+ await serverApp.tick(STEP);+ await clientApp.tick(STEP);+ expect(posX(clientApp, ghost)).toBeCloseTo(10, 5);+ });++ it('non-owned entities are untouched by prediction and still replicate', async () => {+ const { serverApp, clientApp, client, server } = await makePredictedPair();++ const npc = serverApp.world.spawn('npc');+ serverApp.world.insert(npc, Replicated, {});+ serverApp.world.insert(npc, NetPos, { x: 100, y: 0 });+ await serverApp.tick(STEP);+ await clientApp.tick(STEP);+ const npcGhost = clientApp.world.getEntitiesWithComponents([Replicated])+ .find((e) => !client.ownsEntity(e))!;+ expect(posX(clientApp, npcGhost)).toBe(100);++ client.sendInput({ move: { x: 1, y: 0 } });+ expect(posX(clientApp, npcGhost)).toBe(100); // prediction never touches it++ serverApp.world.set(npc, NetPos, { x: 120, y: 0 });+ await serverApp.tick(STEP);+ await clientApp.tick(STEP);+ expect(posX(clientApp, npcGhost)).toBe(120); // normal replication path+ void server;+ });++ it('prediction bypasses snapshot interpolation for owned entities', async () => {+ const { clientApp, ghost, client } = await makePredictedPair(/* interpolationDelayTicks */ 2);+ client.sendInput({ move: { x: 1, y: 0 } });+ // With a 2-tick presentation delay a ghost would lag; the owned pawn moves NOW.+ expect(posX(clientApp, ghost)).toBeCloseTo(10, 5);+ });+});++describe('per-tick input queue (tickInputOf)', () => {+ it('consumes exactly one command per tick, repeats on starvation, and inputOf stays latest', async () => {+ const serverApp = makeApp();+ const clientApp = makeApp();+ const server = serverApp.getResource(Net).startServer();+ const [ta, tb] = MemoryTransport.pair();+ const connId = server.attachConnection(ta);+ const client = await clientApp.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });++ client.sendInput({ n: 1 });+ client.sendInput({ n: 2 });+ expect(server.inputOf(connId)!.seq).toBe(2); // latest-persists, unchanged+ expect(server.tickInputOf(connId)).toBeNull(); // nothing consumed yet++ await serverApp.tick(STEP);+ expect(server.tickInputOf(connId)!.actions).toEqual({ n: 1 });+ await serverApp.tick(STEP);+ expect(server.tickInputOf(connId)!.actions).toEqual({ n: 2 });+ await serverApp.tick(STEP); // queue dry → the held command repeats+ expect(server.tickInputOf(connId)!.actions).toEqual({ n: 2 });+ });+});