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.

docs(networking): state replication joins the guide (en + zh-cn)

esengineff7f527b4bea
diff --git a/docs/astro/src/content/docs/guides/networking.mdx b/docs/astro/src/content/docs/guides/networking.mdx
index f8d0163e8..dd4140df2 100644
--- a/docs/astro/src/content/docs/guides/networking.mdx
+++ b/docs/astro/src/content/docs/guides/networking.mdx
@@ -66,6 +66,54 @@ const stats = await channel.request<{ hp: number }>('getStats', { id: 'p1' }, 50
| `request(type, payload, timeoutMs?)` | Send an RPC; resolves with the reply. |
| `dispose(reason?)` | Tear down the channel and reject pending requests. |
+## State replication — multiplayer entities
+
+On top of the transport, Estella ships a **server-authoritative replication
+layer**: mark an entity `Replicated` on the server and it spawns on every
+client, its declared fields stream as binary deltas, and remote pawns render
+with snapshot interpolation. One declaration drives the wire format — no
+hand-written sync code.
+
+```typescript
+import { defineComponent, Net, Replicated, Transform } from 'esengine';
+
+// Which fields replicate is declared on the component (builtins like
+// Transform annotate `replicated` in C++; user components declare it here).
+const Health = defineComponent('Health', { hp: 100, regen: 1 }, {
+ replicatedFields: ['hp'],
+});
+
+// SERVER (the authority): spawn a replicated entity, owned by a connection.
+const net = app.getResource(Net);
+const server = net.startServer();
+// accept connections however your host likes:
+server.attachConnection(transport); // any NetTransport works
+
+const e = app.world.spawn('player');
+app.world.insert(e, Transform, { position: { x: 0, y: 0, z: 0 } });
+app.world.insert(e, Health, {});
+app.world.insert(e, Replicated, { owner: connectionId });
+
+// CLIENT: connect and everything arrives — ghosts spawn, state streams.
+await app.getResource(Net).connect(transport);
+net.client?.sendInput({ move: { x: 1, y: 0 } }); // per-tick input uplink
+
+// SERVER gameplay reads each connection's latest input:
+const input = server.inputOf(connectionId);
+```
+
+- **Authority**: only the server simulates; clients see replicated, interpolated
+ state (`NetGhost` tags the proxies). The handshake refuses a protocol/ABI/schema
+ mismatch fail-loud, so drifted builds never desync silently.
+- **Ownership**: `Replicated.owner` routes a connection's `sendInput` commands to
+ its entities; `client.ownsEntity(e)` answers "is this ghost mine".
+- **Editor preview**: pick **2–4 Players** in the Play-mode dropdown — a listen
+ server plus client views run side by side, zero networking setup.
+- **Dedicated servers**: the same gameplay code runs headless under Node —
+ `import { loadEsengineModule, createHeadlessApp, runHeadless } from 'esengine/node'`.
+
+See the **Multiplayer Arena** example for the full pattern in ~100 lines.
+
## Best practices
- **Use `NetChannel`** for anything beyond a trivial socket — routed types and RPC
@@ -73,11 +121,13 @@ const stats = await channel.request<{ hp: number }>('getStats', { id: 'p1' }, 50
- **Set an RPC timeout** so a lost reply rejects instead of hanging forever.
- **Push received state into components** via `Commands` so gameplay stays in ECS.
- **Queue-before-open is automatic** — you can `send` right after `connect()`.
+- **Gate authority in systems** — check `Net.role` so the same code runs as
+ server, client, or offline single-player.
<Aside type="note">
- Networking is plain classes, not an ECS resource — create the socket/channel
- wherever it fits your app, and drive gameplay from its callbacks. Entity sync /
- rollback is a larger layer you build on top of `NetChannel`.
+ The transport is plain classes (create the socket/channel wherever it fits);
+ the replication layer is ECS-native — a `Net` resource plus systems on the
+ fixed timestep, installed by default and idle until you start a session.
</Aside>
## See also
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 682535792..36cda01a1 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/networking.mdx
@@ -65,16 +65,63 @@ const stats = await channel.request<{ hp: number }>('getStats', { id: 'p1' }, 50
| `request(type, payload, timeoutMs?)` | 发送一个 RPC;以回复 resolve。 |
| `dispose(reason?)` | 拆除通道并 reject 挂起的请求。 |
+## 状态复制——多人实体同步
+
+在传输层之上,Estella 内置**服务器权威的复制层**:在服务器上给实体挂上
+`Replicated`,它就会在每个客户端生成,声明过的字段以二进制增量流式同步,
+远端角色带快照插值渲染。一处声明驱动整个线格式——无需手写同步代码。
+
+```typescript
+import { defineComponent, Net, Replicated, Transform } from 'esengine';
+
+// 哪些字段复制在组件上声明(内置组件如 Transform 在 C++ 侧
+// 用 `replicated` 注解;用户组件在这里声明)。
+const Health = defineComponent('Health', { hp: 100, regen: 1 }, {
+ replicatedFields: ['hp'],
+});
+
+// 服务器(权威端):生成一个复制实体,归某个连接所有。
+const net = app.getResource(Net);
+const server = net.startServer();
+server.attachConnection(transport); // 任何 NetTransport 都行
+
+const e = app.world.spawn('player');
+app.world.insert(e, Transform, { position: { x: 0, y: 0, z: 0 } });
+app.world.insert(e, Health, {});
+app.world.insert(e, Replicated, { owner: connectionId });
+
+// 客户端:连上即得——ghost 自动生成,状态持续流入。
+await app.getResource(Net).connect(transport);
+net.client?.sendInput({ move: { x: 1, y: 0 } }); // 每 tick 输入上行
+
+// 服务器玩法读取各连接的最新输入:
+const input = server.inputOf(connectionId);
+```
+
+- **权威**:只有服务器做模拟;客户端看到的是复制且插值后的状态(`NetGhost`
+ 标记代理实体)。握手会对协议/ABI/schema 不匹配直接拒连,漂移的构建永远
+ 不会静默失步。
+- **归属**:`Replicated.owner` 把某连接的 `sendInput` 命令路由到它的实体;
+ `client.ownsEntity(e)` 回答"这个 ghost 是不是我的"。
+- **编辑器预览**:在 Play 模式下拉里选 **2–4 Players**——listen server 和
+ 客户端视图并排运行,零联网配置。
+- **专用服务器**:同一份玩法代码可在 Node 下无头运行——
+ `import { loadEsengineModule, createHeadlessApp, runHeadless } from 'esengine/node'`。
+
+完整范式见 **Multiplayer Arena** 示例(约 100 行)。
+
## 最佳实践
- 超出简单套接字的场景**用 `NetChannel`**——按类型路由和 RPC 胜过一个巨大的 `onMessage` switch。
- **设置 RPC 超时**,让丢失的回复 reject 而不是永远挂起。
- **把收到的状态推入组件**(用 `Commands`),让玩法留在 ECS。
- **连接前排队是自动的**——`connect()` 之后就能立即 `send`。
+- **在系统里做权威门控**——检查 `Net.role`,同一份代码即可作为服务器、
+ 客户端或离线单机运行。
<Aside type="note">
- 联网是普通类,而非 ECS 资源——在适合你应用的地方创建套接字/通道,并从它的回调驱动玩法。
- 实体同步 / 回滚是你在 `NetChannel` 之上构建的更大一层。
+ 传输层是普通类(在适合你应用的地方创建套接字/通道);复制层则是 ECS
+ 原生的——一个 `Net` 资源加固定时间步上的系统,默认安装,不开会话时零开销。
</Aside>
## 参见
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 67d99d1cc..67e4e7783 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -102,6 +102,9 @@ importers:
'@rollup/plugin-typescript':
specifier: ^11.1.5
+ '@types/node':
+ specifier: ^25.9.3
+ version: 25.9.3
'@types/ws':
specifier: ^8.18.1
version: 8.18.1
@@ -2933,18 +2936,6 @@ packages:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
- resolution: {integrity: sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==}
- engines: {node: '>=10.0.0'}
- peerDependencies:
- bufferutil: ^4.0.1
- utf-8-validate: '>=5.0.2'
- peerDependenciesMeta:
- bufferutil:
- optional: true
- utf-8-validate:
- optional: true
-
resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==}
engines: {node: '>=10.0.0'}
@@ -4751,7 +4742,7 @@ snapshots:
whatwg-encoding: 3.1.1
whatwg-mimetype: 4.0.0
whatwg-url: 14.2.0
- ws: 8.19.0
+ ws: 8.21.0
xml-name-validator: 5.0.0
transitivePeerDependencies:
- bufferutil
@@ -5791,9 +5782,6 @@ snapshots:
- optional: true
-
diff --git a/sdk/package.json b/sdk/package.json
index 83b1ca184..4af4a5e59 100644
--- a/sdk/package.json
+++ b/sdk/package.json
@@ -67,6 +67,7 @@
"devDependencies": {
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.5",
+ "@types/node": "^25.9.3",
"@types/ws": "^8.18.1",
"@vitest/coverage-v8": "^2.1.9",
"@vitest/ui": "^2.1.0",
diff --git a/sdk/tsconfig.json b/sdk/tsconfig.json
index 77de54c45..aa19d65d6 100644
--- a/sdk/tsconfig.json
+++ b/sdk/tsconfig.json
@@ -3,6 +3,7 @@
"target": "ES2020",
"module": "ESNext",
"lib": ["ES2020", "DOM"],
+ "types": ["node"],
"declaration": true,
"strict": true,
"noImplicitAny": true,