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)!: a spawn stops being a scene snapshot — protocol v4
esengine6a24fd264a06
diff --git a/bench/spawn-contract/README.md b/bench/spawn-contract/README.mdindex c8cef93fe..0677af178 100644--- a/bench/spawn-contract/README.md+++ b/bench/spawn-contract/README.md@@ -83,6 +83,53 @@ archetype, or declare `Sprite.color` replicated and mean it. Same for`Pawn.player`. That is a migration, and it is the correct one — it turns anaccident the source already documents into a declaration.+## Acted on: protocol v4 splits the spawn into its three contracts++```+ReplSpawnEntity+├─ protocol identity netId, name, parentNetId, owner+├─ ghost construction archetype key -> a registered builder+└─ replication baseline table components, declared fields, refs as netIds+```++`serializeEntityComponents` is out of the networking path. `owner` became+protocol identity rather than a field that happened to ride a component dump —+`Replicated` declares no replicated fields and must not start. The baseline is+built FROM the table rather than filtered against it: filtering afterwards would+already have paid for reading every component the entity has, which is the+expensive half.++The client builds a ghost in the order the contracts stack: spawn bare, tag+`NetGhost`, insert `Replicated` from the spawn, register the netId, run the+archetype, then apply the baseline over it. Construction before baseline is what+makes an entity that left interest and came back arrive at the authority's+current state rather than at a fresh default. A key it cannot resolve is refused+before the entity exists at all — a registered netId over a half-built ghost+would take that entity's deltas for the rest of the session.++The version is bumped because the change is semantic: a v3 endpoint parses a v4+spawn without complaint and builds a different world from it.++ABA-interleaved, three rounds, every pair the same direction:++| | spawn payload | sample total |+|---|---|---|+| anchors | 9,877 → **2,368** (4.2x) | 20,925 → **12,730** (−39%) |+| mixed | 9,968 → **2,586** (4.0x) | 22,317 → **16,554** (−26%) |++That is on `bench/sample-budget`'s world, which carries no `Sprite`. The arena's+pawn does, and its fifteen fields were the largest single component in the+census — a game shaped like it gains more than this.++### The arena migrated with it++`buildPawn` is now one function, registered as the `pawn` archetype and called by+the authority's own spawn, so a pawn has one definition of what it is. `Pawn.player`+stopped transiting and is authority-side bookkeeping again; a client learns the+same fact as `Replicated.owner`, which the spawn carries as identity. Colour is+derived from `owner` by the same rule on both ends instead of arriving inside a+Sprite. `check-arena-server` still passes end to end over a real socket.+## What this does not cover- One project. The arena is the certified multiplayer example and the only gamediff --git a/docs/astro/src/content/docs/scripting/networking.mdx b/docs/astro/src/content/docs/scripting/networking.mdxindex 962f0d4b4..8c1fce806 100644--- a/docs/astro/src/content/docs/scripting/networking.mdx+++ b/docs/astro/src/content/docs/scripting/networking.mdx@@ -109,6 +109,31 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // per-tick input uplincompares is field names *and* their wire shapes, since a field defaulting to`0` on one end and `false` on the other agrees on the name and disagrees onthe byte count.+- **A ghost is built from a declared archetype, not from the server's+ components.** A spawn carries three things and they are different contracts:+ identity (`netId`, `owner`, parent, name), the *construction* key, and a+ baseline of declared replication fields. Nothing else crosses — a component+ with no `replicated` fields never reaches a client, and neither do a+ component's undeclared fields.++ So anything a proxy needs in order to exist has to be said out loud:++ ```typescript+ import { registerReplicationArchetype, Replicated, Sprite } from 'esengine';++ registerReplicationArchetype('pawn', (world, entity) => {+ world.insert(entity, Sprite, { size: { x: 36, y: 36 }, layer: 2 });+ });++ // On the server, name it when the entity starts replicating.+ world.insert(e, Replicated, { owner: connectionId, archetype: 'pawn' });+ ```++ The archetype runs first and the authority's baseline lands on top, so an+ entity that leaves interest and comes back arrives at the *current* state+ rather than at a fresh default. A client that has no builder for the key+ refuses the spawn rather than showing half an entity.+- **Structure replicates, not just values**: adding a replicated component to alive entity sends its full state; removing one removes it from every ghost.Spawn → component add → updates → component remove → despawn all cross thediff --git a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdxindex 7bd979404..2d31a729b 100644--- a/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx+++ b/docs/astro/src/content/docs/zh-cn/scripting/networking.mdx@@ -106,6 +106,28 @@ clientNet.client?.sendInput({ move: { x: 1, y: 0 } }); // 每 tick 输入上- **schema 比的是字节布局,不只是字段名**:握手比对字段名**和**它们的 wireshape。一端默认 `0`、另一端默认 `false` 的字段,名字相同、字节数不同,光看名字发现不了。+- **ghost 由声明的 archetype 构建,不是把服务器的组件倒过去。** 一次 spawn 携带三样+ 东西,而它们是三份不同的契约:身份(`netId`/`owner`/父节点/名字)、**构建**键、以及+ 一份只含已声明复制字段的 baseline。别的都不过线——没有 `replicated` 字段的组件+ 永远到不了客户端,组件里未声明的字段同样到不了。++ 所以「一个代理要存在需要什么」必须说出来:++ ```typescript+ import { registerReplicationArchetype, Replicated, Sprite } from 'esengine';++ registerReplicationArchetype('pawn', (world, entity) => {+ world.insert(entity, Sprite, { size: { x: 36, y: 36 }, layer: 2 });+ });++ // 服务器侧:实体开始复制时给出这个键。+ world.insert(e, Replicated, { owner: connectionId, archetype: 'pawn' });+ ```++ archetype 先跑,权威的 baseline 覆盖在上面——所以离开兴趣圈又回来的实体拿到的是+ **当前**状态,不是一份新的默认值。客户端解析不了这个键时会**拒绝**这次 spawn,+ 而不是显示半个实体。+- **结构本身也会复制,不只是值**:给活着的实体加一个 replicated 组件会发送它的完整状态,移除则会从每个 ghost 上移除。spawn → 组件加入 → 更新 →组件移除 → despawn 全部过线,并按权威端发出的顺序抵达。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 7212ca397..5b1c26294 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 113,"beta": 91,- "experimental": 1722,+ "experimental": 1724,"deprecated": 3},- "total": 1926,+ "total": 1928,"subsystems": [{"id": "ecs",diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 0211055db..3621e6dc8 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -3002,6 +3002,11 @@"key": "owner","type": "number","default": "0"+ },+ {+ "key": "archetype",+ "type": "string",+ "default": "empty"}],"animatable": [diff --git a/examples/multiplayer-arena/src/components.ts b/examples/multiplayer-arena/src/components.tsindex 12f05c0ee..52b3fd895 100644--- a/examples/multiplayer-arena/src/components.ts+++ b/examples/multiplayer-arena/src/components.ts@@ -2,8 +2,10 @@ import { defineComponent } from 'esengine';/*** A player-steered pawn. `player` is the owning connection id (0 = the host- * player). The pawn's pose replicates through Transform's built-in `replicated`- * annotation; `player` rides the spawn payload, so ghosts know who they are.+ * player) and is AUTHORITY-side only: provisioning matches pawns to players+ * with it, and a ghost learns the same fact as `Replicated.owner`, which the+ * spawn carries as protocol identity. `speed` comes from the `pawn` archetype+ * on both ends, which is what lets client prediction run the same rule.*/export const Pawn = defineComponent('Pawn', {player: 0,diff --git a/examples/multiplayer-arena/src/main.ts b/examples/multiplayer-arena/src/main.tsindex 97f4bd674..7ef91f8e0 100644--- a/examples/multiplayer-arena/src/main.ts+++ b/examples/multiplayer-arena/src/main.ts@@ -1,5 +1,5 @@import { addSystemToSchedule, Schedule } from 'esengine';-import { provisionPawnsSystem, movePawnsSystem, sendInputSystem } from './net';+import { provisionPawnsSystem, movePawnsSystem, sendInputSystem, paintPawnsSystem } from './net';// Netcode lives on the fixed timestep (the replication cadence): the authority// provisions + simulates there, the client uplinks input there. All three@@ -8,3 +8,6 @@ import { provisionPawnsSystem, movePawnsSystem, sendInputSystem } from './net';addSystemToSchedule(Schedule.FixedUpdate, provisionPawnsSystem);addSystemToSchedule(Schedule.FixedUpdate, movePawnsSystem);addSystemToSchedule(Schedule.FixedUpdate, sendInputSystem);+// Presentation from ownership, on both ends: the ghost's Sprite comes from the+// archetype, so its colour has to be derived rather than received.+addSystemToSchedule(Schedule.FixedUpdate, paintPawnsSystem);diff --git a/examples/multiplayer-arena/src/net.ts b/examples/multiplayer-arena/src/net.tsindex a02a9d981..4f0bc97de 100644--- a/examples/multiplayer-arena/src/net.ts+++ b/examples/multiplayer-arena/src/net.ts@@ -1,6 +1,7 @@import {defineSystem, Res, GetWorld,Time, Input, Net, Replicated, Transform, Sprite,+ registerReplicationArchetype,type World, type Entity, type InputState,} from 'esengine';import { Pawn } from './components';@@ -61,19 +62,52 @@ function applyMove(world: World, entity: Entity, actions: Record<string, unknownworld.set(entity, Transform, transform);}+/**+ * What a pawn IS, in one place. The authority builds one with it and so does+ * every client, because it is registered as the ghost's construction contract:+ * a spawn carries identity and declared state, never a dump of the server's+ * components, so anything a proxy needs to exist has to be said here.+ */+function buildPawn(world: World, entity: Entity): void {+ world.insert(entity, Sprite, { size: { x: 36, y: 36 }, layer: 2 });+ // `speed` is a property of the archetype; `player` is authority-side+ // bookkeeping that provisioning reads and no client needs — ownership+ // reaches them as `Replicated.owner`.+ world.insert(entity, Pawn, {});+}+registerReplicationArchetype('pawn', buildPawn);+function spawnPawn(world: World, player: number): void {- const slot = PLAYER_COLORS[player % PLAYER_COLORS.length];const e = world.spawn(`Pawn P${player + 1}`);world.insert(e, Transform, { position: { x: -150 + player * 100, y: -180, z: 0 } });- world.insert(e, Sprite, { size: { x: 36, y: 36 }, color: slot, layer: 2 });- world.insert(e, Pawn, { player });+ buildPawn(world, e);+ world.update(e, Pawn, (d) => { (d as { player: number }).player = player; });// Marking it Replicated is ALL it takes: the entity spawns on every client- // (full component payload — sprite color included), its annotated Transform- // pose streams as deltas, and `owner` routes that connection's input to it.- // Owner is assigned AT spawn — ownership rides the spawn payload.- world.insert(e, Replicated, { owner: player });+ // through the `pawn` archetype, its annotated Transform pose streams as+ // deltas, and `owner` — protocol identity, carried by the spawn itself —+ // routes that connection's input to it and colours it at both ends.+ world.insert(e, Replicated, { owner: player, archetype: 'pawn' });}+/**+ * Colour from ownership, on whichever end is looking. The fact a client is given+ * is `owner`; the colour is derived from it by the same rule on both ends, so+ * the Sprite an archetype builds does not have to carry it.+ */+export const paintPawnsSystem = defineSystem(+ [GetWorld()],+ (world) => {+ for (const e of world.getEntitiesWithComponents([Pawn, Sprite, Replicated])) {+ const owner = (world.tryGet(e, Replicated) as { owner: number }).owner;+ const want = PLAYER_COLORS[owner % PLAYER_COLORS.length];+ const sprite = world.tryGet(e, Sprite) as { color: { r: number; g: number; b: number } };+ if (sprite.color.r === want.r && sprite.color.g === want.g && sprite.color.b === want.b) continue;+ world.update(e as Entity, Sprite, (d) => { (d as { color: unknown }).color = { ...want }; });+ }+ },+ { name: 'PaintPawnsSystem' },+);+/*** Authority-side provisioning, both directions: a player owed a pawn gets one,* a pawn whose player left is retired. Stateless — the roster is derived fromdiff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex df5e46ccc..37a664ab1 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: 113 public · 84 beta · 1558 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1560 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -6441,7 +6441,7 @@ ReadonlyMap<string, string>## REPLICATION_PROTOCOL_VERSION — const @experimental```-3+4```## RETIRED_COMPONENT_TYPES — const @experimental@@ -6613,10 +6613,16 @@ ComponentDef<ReplicatedData>## ReplicatedData — interface @experimental```+archetype: stringnetId: numberowner: number```+## ReplicationArchetype — type @experimental+```+(world: World, entity: Entity) => void+```+## ReplicationClient — class @experimental```@internal setFixedDelta: (dt: number) => void@@ -12074,6 +12080,11 @@ PrefabsPlugin(id: string, fn: PreSceneDrawCallback): void```+## registerReplicationArchetype — function @experimental+```+(key: string, build: ReplicationArchetype): void+```+## registerSceneComponentCodec — function @experimental```(type: string, codec: SceneComponentCodec): voiddiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex a4ad8274d..e3343ec24 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 89 beta · 1577 experimental · 3 deprecated+Symbols: 113 public · 89 beta · 1579 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -6629,7 +6629,7 @@ ReadonlyMap<string, string>## REPLICATION_PROTOCOL_VERSION — const @experimental```-3+4```## RESOURCE_BINDINGS — const @experimental@@ -6806,10 +6806,16 @@ ComponentDef<ReplicatedData>## ReplicatedData — interface @experimental```+archetype: stringnetId: numberowner: number```+## ReplicationArchetype — type @experimental+```+(world: World, entity: Entity) => void+```+## ReplicationClient — class @experimental```@internal setFixedDelta: (dt: number) => void@@ -12317,6 +12323,11 @@ PrefabsPlugin(id: string, fn: PreSceneDrawCallback): void```+## registerReplicationArchetype — function @experimental+```+(key: string, build: ReplicationArchetype): void+```+## registerSceneComponentCodec — function @experimental```(type: string, codec: SceneComponentCodec): voiddiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 17c926bcf..b8b022c90 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: 113 public · 86 beta · 1557 experimental · 3 deprecated+Symbols: 113 public · 86 beta · 1559 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -6436,7 +6436,7 @@ ReadonlyMap<string, string>## REPLICATION_PROTOCOL_VERSION — const @experimental```-3+4```## RETIRED_COMPONENT_TYPES — const @experimental@@ -6608,10 +6608,16 @@ ComponentDef<ReplicatedData>## ReplicatedData — interface @experimental```+archetype: stringnetId: numberowner: number```+## ReplicationArchetype — type @experimental+```+(world: World, entity: Entity) => void+```+## ReplicationClient — class @experimental```@internal setFixedDelta: (dt: number) => void@@ -12079,6 +12085,11 @@ PrefabsPlugin(id: string, fn: PreSceneDrawCallback): void```+## registerReplicationArchetype — function @experimental+```+(key: string, build: ReplicationArchetype): void+```+## registerSceneComponentCodec — function @experimental```(type: string, codec: SceneComponentCodec): voiddiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 178dd658d..05d6e9909 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 84 beta · 1579 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1581 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -6682,7 +6682,7 @@ ReadonlyMap<string, string>## REPLICATION_PROTOCOL_VERSION — const @experimental```-3+4```## RETIRED_COMPONENT_TYPES — const @experimental@@ -6854,10 +6854,16 @@ ComponentDef<ReplicatedData>## ReplicatedData — interface @experimental```+archetype: stringnetId: numberowner: number```+## ReplicationArchetype — type @experimental+```+(world: World, entity: Entity) => void+```+## ReplicationClient — class @experimental```@internal setFixedDelta: (dt: number) => void@@ -12336,6 +12342,11 @@ PrefabsPlugin(id: string, fn: PreSceneDrawCallback): void```+## registerReplicationArchetype — function @experimental+```+(key: string, build: ReplicationArchetype): void+```+## registerSceneComponentCodec — function @experimental```(type: string, codec: SceneComponentCodec): voiddiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 270e0b31d..4670fe498 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 113 public · 84 beta · 1569 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1571 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -6443,7 +6443,7 @@ ReadonlyMap<string, string>## REPLICATION_PROTOCOL_VERSION — const @experimental```-3+4```## RETIRED_COMPONENT_TYPES — const @experimental@@ -6615,10 +6615,16 @@ ComponentDef<ReplicatedData>## ReplicatedData — interface @experimental```+archetype: stringnetId: numberowner: number```+## ReplicationArchetype — type @experimental+```+(world: World, entity: Entity) => void+```+## ReplicationClient — class @experimental```@internal setFixedDelta: (dt: number) => void@@ -12102,6 +12108,11 @@ PrefabsPlugin(id: string, fn: PreSceneDrawCallback): void```+## registerReplicationArchetype — function @experimental+```+(key: string, build: ReplicationArchetype): void+```+## registerSceneComponentCodec — function @experimental```(type: string, codec: SceneComponentCodec): voiddiff --git a/sdk/src/core-sys.ts b/sdk/src/core-sys.tsindex 80cd1512c..4f9e756f3 100644--- a/sdk/src/core-sys.ts+++ b/sdk/src/core-sys.ts@@ -100,11 +100,12 @@ export {Replicated, NetGhost, ReplicationServer, ReplicationClient,REPLICATION_PROTOCOL_VERSION, REPLICATION_CHANNEL,radiusInterest, radiusInterestProvider,+ registerReplicationArchetype,type NetRoleKind, type ReplicatedData,type InterestPolicy, type InterestView, type RadiusInterestOptions,type InterestProvider, type PreparedInterest, type InterestPoint,type InterestProviderPrepareView, type InterestProviderQueryView,- type PredictionOptions, type PredictionSmoothing,+ type PredictionOptions, type PredictionSmoothing, type ReplicationArchetype,} from './net/replication';// =============================================================================diff --git a/sdk/src/net/replication/archetype.ts b/sdk/src/net/replication/archetype.tsnew file mode 100644index 000000000..3afb893a3--- /dev/null+++ b/sdk/src/net/replication/archetype.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file archetype.ts+ * @brief What a ghost is built from — the construction half of a spawn.+ *+ * A spawn answers three questions under three contracts: who this+ * entity is on the wire, what the client is DECLARED to know about it,+ * and what it takes for a proxy of it to exist at all. This is the+ * third. The server sends a key, the client runs the builder+ * registered under it, and what the authority happens to have on the+ * entity — an AI blackboard, an unrevealed objective — is not part of+ * the answer.+ */+import type { World } from '../../ecs/world';+import type { Entity } from '../../types';+import { log } from '../../util/logger';++/**+ * Builds the client-side shape of one replicated entity. Runs BEFORE the+ * replication baseline is applied, so anything the authority declares wins over+ * what this sets: a re-spawn after leaving and re-entering interest arrives at+ * the current state, not at a fresh default.+ *+ * @experimental+ */+export type ReplicationArchetype = (world: World, entity: Entity) => void;++const archetypes = new Map<string, ReplicationArchetype>();++/**+ * Declare how a ghost of `key` is built. The server names one per replicated+ * entity through `Replicated.archetype`, and a client that cannot resolve the+ * key refuses the spawn rather than building half of it. Synchronous in this+ * first form: a key resolving to a preloaded prefab is a later question.+ *+ * @experimental+ */+export function registerReplicationArchetype(key: string, build: ReplicationArchetype): void {+ if (key === '') throw new Error('[repl] a replication archetype needs a non-empty key');+ if (archetypes.has(key) && archetypes.get(key) !== build) {+ log.warn('repl', `replication archetype "${key}" re-registered; the later one wins`);+ }+ archetypes.set(key, build);+}++/** @internal What the client runs for a spawn naming `key`. */+export function getReplicationArchetype(key: string): ReplicationArchetype | undefined {+ return archetypes.get(key);+}++/** @internal Drop every registration — a project reload, or one test's keys+ * leaking into the next. */+export function clearReplicationArchetypes(): void {+ archetypes.clear();+}diff --git a/sdk/src/net/replication/client.ts b/sdk/src/net/replication/client.tsindex fdfac7295..d1b091f12 100644--- a/sdk/src/net/replication/client.ts+++ b/sdk/src/net/replication/client.ts@@ -39,6 +39,7 @@ import {type EntityRefMap, type FieldShape, type ReplicationTable, type ReplicationTableEntry, type StateFrame,} from './codec';import { NetGhost, Replicated, type ReplicatedData } from './components';+import { getReplicationArchetype } from './archetype';import { NetIds } from './NetIds';import { InterpolationState } from './interpolation';@@ -425,13 +426,33 @@ export class ReplicationClient {const fresh: { spawn: ReplSpawnEntity; entity: Entity }[] = [];for (const spawn of batch.entities) {if (this.netIds_.entityOf(spawn.netId) !== undefined) continue; // duplicate delivery+ // Refused BEFORE anything exists: a ghost the client cannot build is+ // not a ghost it should half-build, and a registered netId pointing+ // at a stripped entity would take deltas for the rest of the session.+ if (spawn.archetype !== '' && !getReplicationArchetype(spawn.archetype)) {+ log.error('repl', `no replication archetype registered for "${spawn.archetype}"`+ + ` — refusing to construct netId ${spawn.netId}`);+ continue;+ }const e = this.world_.spawn(spawn.name || undefined);this.world_.insert(e, NetGhost, {});+ // Protocol identity, from the spawn rather than from a component the+ // authority happened to be holding.+ this.world_.insert(e, Replicated, {+ netId: spawn.netId, owner: spawn.owner, archetype: spawn.archetype,+ });this.netIds_.register(spawn.netId, e);fresh.push({ spawn, entity: e });}+ // Construction first, then the baseline on top: what the authority+ // declares outranks what the archetype defaults to, so an entity that+ // left interest and came back arrives at the current state.+ for (const { spawn, entity } of fresh) {+ if (spawn.archetype === '') continue;+ getReplicationArchetype(spawn.archetype)!(this.world_, entity);+ }for (const { spawn, entity } of fresh) {- for (const comp of spawn.components) {+ for (const comp of spawn.baseline) {const data = this.remapEntityRefs_(comp.type, comp.data);loadComponent(this.world_, entity, { type: comp.type, data }, spawn.name);}diff --git a/sdk/src/net/replication/components.ts b/sdk/src/net/replication/components.tsindex fde8a1838..471b2b2ec 100644--- a/sdk/src/net/replication/components.ts+++ b/sdk/src/net/replication/components.ts@@ -16,11 +16,19 @@ export interface ReplicatedData {netId: number;/** Owning connection id (0 = the server) — input/authority routing (N4). */owner: number;+ /**+ * Which {@link registerReplicationArchetype} builder gives this entity's+ * ghosts their shape. Empty means a bare ghost carrying only the replication+ * baseline. Never replicated as a FIELD — it rides the spawn as protocol+ * metadata, like `netId` and `owner`.+ */+ archetype: string;}export const Replicated = defineComponent<ReplicatedData>('Replicated', {netId: 0,owner: 0,+ archetype: '',});/** Client-side proxy of a server entity: state arrives over the wire. */@@ -33,6 +41,6 @@ export const NetGhost = defineTag('NetGhost');* calls this, so any app built after a reset still serializes these.*/export function ensureReplicationComponentsRegistered(): void {- defineComponent<ReplicatedData>('Replicated', { netId: 0, owner: 0 });+ defineComponent<ReplicatedData>('Replicated', { netId: 0, owner: 0, archetype: '' });defineTag('NetGhost');}diff --git a/sdk/src/net/replication/index.ts b/sdk/src/net/replication/index.tsindex 20164e53e..83e35b69d 100644--- a/sdk/src/net/replication/index.ts+++ b/sdk/src/net/replication/index.ts@@ -46,6 +46,9 @@ export {type RadiusInterestOptions,type InterestPoint,} from './interest';+export {+ registerReplicationArchetype, clearReplicationArchetypes, type ReplicationArchetype,+} from './archetype';export { NetIds } from './NetIds';export { ReplicationServer } from './server';export {diff --git a/sdk/src/net/replication/protocol.ts b/sdk/src/net/replication/protocol.tsindex 6e9933120..2ab4ff1fa 100644--- a/sdk/src/net/replication/protocol.ts+++ b/sdk/src/net/replication/protocol.ts@@ -11,7 +11,13 @@*/import type { SceneComponentData } from '../../scene/scene';-export const REPLICATION_PROTOCOL_VERSION = 3;+/**+ * 4: a spawn stopped being a scene snapshot. It now carries protocol identity,+ * a ghost-construction key, and a baseline of DECLARED replication fields only —+ * a v3 endpoint would read the same JSON and build a different world, which is+ * exactly what a version is for.+ */+export const REPLICATION_PROTOCOL_VERSION = 4;/** NetChannel binary channel id the snapshot frames ride on. */export const REPLICATION_CHANNEL = 1;@@ -65,15 +71,24 @@ export interface ReplHelloError {export type ReplHelloResponse = ReplHelloOk | ReplHelloError;-/** One replicated entity's spawn payload. Component data is the scene- * serialization shape (loadComponent applies it, out-of-band codecs and- * validation included); entity-ref fields arrive rewritten to netIds. */+/**+ * One replicated entity's spawn, in the three contracts it is actually made of.+ * Identity is protocol, not state; construction is declared, not inferred from+ * what the authority holds; and the baseline carries replication-table+ * components with their DECLARED fields and nothing else.+ */export interface ReplSpawnEntity {netId: number;name: string;/** netId of the replicated parent, or 0 for a root. */parentNetId: number;- components: SceneComponentData[];+ /** Owning connection id. Protocol identity like `netId` — it is not a+ * replicated field and must not become one. */+ owner: number;+ /** Which registered archetype builds this ghost; '' for a bare one. */+ archetype: string;+ /** Table components only, declared fields only; entity refs as netIds. */+ baseline: SceneComponentData[];}export interface ReplSpawnBatch {diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.tsindex 4bad2887f..00447e31c 100644--- a/sdk/src/net/replication/server.ts+++ b/sdk/src/net/replication/server.ts@@ -20,7 +20,7 @@ import type { World } from '../../ecs/world';import type { Entity } from '../../types';import { Name, Parent, getComponent, type AnyComponentDef } from '../../ecs/component';import { ABI_LAYOUT_HASH } from '../../ecs/component.generated';-import { serializeEntityComponents, type SceneComponentData } from '../../scene/scene';+import type { SceneComponentData } from '../../scene/scene';import { NetChannel, type ReliableOrderedTransport } from '../NetChannel';import { log } from '../../util/logger';import {@@ -1155,18 +1155,35 @@ export class ReplicationServer {this.shadow_.set(e, perComp);}+ /**+ * The three contracts a spawn is made of. The baseline is built FROM the+ * table rather than filtered against it: the expensive half of a scene+ * serialization is reading every component the entity has, and none of that+ * work is wanted here.+ */private spawnPayload_(e: Entity, netId: number): ReplSpawnEntity {- const components = serializeEntityComponents(this.world_, e).map((c) => this.rewriteEntityRefs_(c));- // Name/Parent are structural components serializeEntityComponents skips- // (scene records carry them beside the component list; so does this).+ const baseline: SceneComponentData[] = [];+ for (const te of this.table.entries) {+ if (!this.world_.has(e, te.def)) continue;+ const live = this.world_.tryGet(e, te.def) as Record<string, unknown> | null;+ if (!live) continue;+ const data: Record<string, unknown> = {};+ for (const f of te.fields) data[f] = cloneValue(live[f]);+ baseline.push(this.rewriteEntityRefs_({ type: te.name, data }));+ }+ // Name/Parent are structural; scene records carry them beside the+ // component list, and so does this.const nameComp = this.world_.tryGet(e, Name) as { value: string } | null;const parentComp = this.world_.tryGet(e, Parent) as { entity: number } | null;const parentNetId = parentComp ? (this.netIds_.netIdOf(parentComp.entity as Entity) ?? 0) : 0;+ const repl = this.world_.tryGet(e, Replicated) as ReplicatedData | null;return {netId,name: nameComp?.value ?? '',parentNetId,- components,+ owner: repl?.owner ?? 0,+ archetype: repl?.archetype ?? '',+ baseline,};}diff --git a/sdk/tests/replication-spawn-contract.test.ts b/sdk/tests/replication-spawn-contract.test.tsindex b64dd0383..392bafc12 100644--- a/sdk/tests/replication-spawn-contract.test.ts+++ b/sdk/tests/replication-spawn-contract.test.ts@@ -25,7 +25,10 @@ import { describe, it, expect, afterEach, beforeAll, beforeEach } from 'vitest';import { App } from '../src/app/app';import { clearUserComponents, defineComponent, Name, Transform, Sprite } from '../src/ecs/component';import { MemoryTransport } from '../src/net/MemoryTransport';-import { replicationPlugin, Net, Replicated } from '../src/net/replication';+import {+ replicationPlugin, Net, Replicated,+ registerReplicationArchetype, clearReplicationArchetypes, radiusInterest,+} from '../src/net/replication';import type { Entity } from '../src/types';import type { CppRegistry, ESEngineModule } from '../src/wasm';import { loadWasmModule, HAS_WASM } from './helpers/loadWasm';@@ -38,6 +41,8 @@ const ARCHETYPE_LAYER = 7;const AUTHORITY_LAYER = 3;let ServerSecret: ReturnType<typeof defineComponent<{ plan: string }>>;+/** A replicated entity reference, so the baseline has netIds to remap. */+let Link: ReturnType<typeof defineComponent<{ target: number }>>;/** Two fields, one declared: the same hole a component at a time. */let PartlyShared: ReturnType<typeof defineComponent<{ shown: number; hidden: number }>>;@@ -47,7 +52,15 @@ describe.skipIf(!HAS_WASM)('a spawn carries three contracts, not one', () => {const opened: App[] = [];beforeEach(() => {clearUserComponents();+ clearReplicationArchetypes();ServerSecret = defineComponent('ServerSecret', { plan: '' });+ Link = defineComponent('SpawnLink', { target: 0 },+ { replicatedFields: ['target'], entityFields: ['target'] });+ // The construction contract, and deliberately NOT what the authority+ // holds: "the ghost has a Sprite" must not be satisfiable by a copy.+ registerReplicationArchetype('pawn', (world, entity) => {+ world.insert(entity, Sprite, { layer: ARCHETYPE_LAYER });+ });PartlyShared = defineComponent('PartlyShared', { shown: 0, hidden: 0 },{ replicatedFields: ['shown'] });});@@ -73,7 +86,7 @@ describe.skipIf(!HAS_WASM)('a spawn carries three contracts, not one', () => {serverApp.world.insert(pawn, Sprite, { layer: AUTHORITY_LAYER });serverApp.world.insert(pawn, PartlyShared, { shown: 5, hidden: 9 });serverApp.world.insert(pawn, ServerSecret, { plan: 'flank at 30s' });- serverApp.world.insert(pawn, Replicated, { owner: connId });+ serverApp.world.insert(pawn, Replicated, { owner: connId, archetype: 'pawn' });for (let i = 0; i < 6; i++) { await serverApp.tick(STEP); await clientApp.tick(STEP); }const ghost = clientApp.world.getEntitiesWithComponents([Replicated])@@ -82,6 +95,26 @@ describe.skipIf(!HAS_WASM)('a spawn carries three contracts, not one', () => {return { serverApp, clientApp, server, connId, pawn, ghost: ghost! };}+ /** Server + client with no entity yet — for the cases that build their own. */+ async function serverWith() {+ const serverApp = App.new();+ serverApp.connectCpp(new module.Registry() as unknown as CppRegistry, module, { strict: false });+ serverApp.addPlugin(replicationPlugin);+ opened.push(serverApp);+ const server = serverApp.getResource(Net).startServer();+ const clientApp = App.new();+ clientApp.connectCpp(new module.Registry() as unknown as CppRegistry, module, { strict: false });+ clientApp.addPlugin(replicationPlugin);+ opened.push(clientApp);+ const [ta, tb] = MemoryTransport.pair();+ const connId = server.attachConnection(ta);+ await clientApp.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });+ const step = async (n = 1) => {+ for (let i = 0; i < n; i++) { await serverApp.tick(STEP); await clientApp.tick(STEP); }+ };+ return { serverApp, clientApp, server, connId, step };+ }+it('gives the ghost the replication baseline', async () => {const h = await arena();const t = h.clientApp.world.tryGet(h.ghost, Transform) as { position: { x: number } } | null;@@ -95,14 +128,15 @@ describe.skipIf(!HAS_WASM)('a spawn carries three contracts, not one', () => {expect(h.clientApp.getResource(Net).client?.ownsEntity(h.ghost)).toBe(true);});- it.fails('does not hand the client a component that declares nothing', async () => {+ it('does not hand the client a component that declares nothing', async () => {// ServerSecret has no `replicatedFields`, and the public contract says- // that means never replicated. The scene projection sends it anyway.+ // that means never replicated. Until protocol v4 the scene projection+ // sent it anyway.const h = await arena();expect(h.clientApp.world.has(h.ghost, ServerSecret)).toBe(false);});- it.fails('does not hand the client the fields a component did not declare', async () => {+ it('does not hand the client the fields a component did not declare', async () => {const h = await arena();const p = h.clientApp.world.tryGet(h.ghost, PartlyShared) as{ shown: number; hidden: number } | null;@@ -110,10 +144,84 @@ describe.skipIf(!HAS_WASM)('a spawn carries three contracts, not one', () => {expect(p?.hidden, 'undeclared field arrived from the authority').toBe(0);});- it.fails('builds the ghost from a construction contract, not the authority dump', async () => {- // Sprite is not in the table, and a ghost still needs one. Where it comes- // from is the whole question: an explicit archetype, or whatever the- // server happened to be holding.+ it('refuses a spawn whose construction key it cannot resolve', async () => {+ const h = await serverWith();+ const orphan = h.serverApp.world.spawn('orphan');+ h.serverApp.world.insert(orphan, Transform, { position: { x: 4, y: 0, z: 0 } });+ h.serverApp.world.insert(orphan, Replicated, { owner: -1, archetype: 'never-registered' });+ await h.step(4);++ // No ghost at all rather than a stripped one: a registered netId over an+ // entity nobody can build would take this entity's deltas for the rest+ // of the session.+ expect(h.clientApp.world.getEntitiesWithComponents([Replicated])).toHaveLength(0);+ });++ it('remaps an entity reference in the baseline, itself and a later sibling', async () => {+ const h = await serverWith();+ // Both spawn in one batch, and `first` points at a netId that is only+ // registered while the batch is still being read.+ const first = h.serverApp.world.spawn('first');+ const second = h.serverApp.world.spawn('second');+ h.serverApp.world.insert(first, Link, { target: second as unknown as number });+ h.serverApp.world.insert(second, Link, { target: second as unknown as number });+ h.serverApp.world.insert(first, Replicated, { owner: -1 });+ h.serverApp.world.insert(second, Replicated, { owner: -1 });+ await h.step(4);++ const named = (n: string) => h.clientApp.world.getEntitiesWithComponents([Replicated])+ .find((e) => (h.clientApp.world.tryGet(e, Name) as { value: string } | null)?.value === n);+ const gFirst = named('first');+ const gSecond = named('second');+ expect(gFirst).toBeDefined();+ expect(gSecond).toBeDefined();+ expect((h.clientApp.world.tryGet(gFirst!, Link) as { target: number }).target).toBe(gSecond);+ expect((h.clientApp.world.tryGet(gSecond!, Link) as { target: number }).target).toBe(gSecond);+ });++ it('re-enters interest at the authority state, not at the archetype default', async () => {+ const h = await serverWith();+ registerReplicationArchetype('drifter', (world, entity) => {+ world.insert(entity, Transform, { position: { x: -999, y: 0, z: 0 } });+ world.insert(entity, Sprite, { layer: ARCHETYPE_LAYER });+ });+ const anchor = h.serverApp.world.spawn('anchor');+ h.serverApp.world.insert(anchor, Transform, { position: { x: 0, y: 0, z: 0 } });+ h.serverApp.world.insert(anchor, Replicated, { owner: h.connId });+ const drifter = h.serverApp.world.spawn('drifter');+ h.serverApp.world.insert(drifter, Transform, { position: { x: 5, y: 0, z: 0 } });+ h.serverApp.world.insert(drifter, Replicated, { owner: -1, archetype: 'drifter' });+ h.server.setInterestPolicy(radiusInterest(20));+ await h.step(4);++ const seen = () => h.clientApp.world.getEntitiesWithComponents([Replicated])+ .find((e) => (h.clientApp.world.tryGet(e, Name) as { value: string } | null)?.value === 'drifter');+ expect(seen()).toBeDefined();++ const serverApp = h.serverApp;+ // `pose`, not `t`: the silent-writes census tracks bindings by name, and+ // this block also holds a `t` read out of the client world.+ const move = (x: number) => {+ serverApp.world.update(drifter, Transform, (pose) => {+ const p = (pose as { position: { x: number } }).position;+ p.x = x;+ });+ };+ move(900);+ await h.step(4);+ expect(seen(), 'it never left interest, so re-entry proves nothing').toBeUndefined();++ move(7);+ await h.step(4);+ const back = seen();+ expect(back).toBeDefined();+ const t = h.clientApp.world.tryGet(back!, Transform) as { position: { x: number } };+ expect(t.position.x, 'the archetype default outranked the authority').toBe(7);+ });++ it('builds the ghost from a construction contract, not the authority dump', async () => {+ // Sprite is not in the table and a ghost still needs one. Where it comes+ // from is the whole question, and the answer is the declared archetype.const h = await arena();const s = h.clientApp.world.tryGet(h.ghost, Sprite) as { layer: number } | null;expect(s, 'the ghost has no Sprite at all').not.toBeNull();diff --git a/sdk/tests/replication.test.ts b/sdk/tests/replication.test.tsindex 5f1c9cda0..806b654cc 100644--- a/sdk/tests/replication.test.ts+++ b/sdk/tests/replication.test.ts@@ -110,6 +110,24 @@ describe('replication handshake', () => {if (!res.ok) expect(res.error).toMatch(/protocol/);});+ it('refuses the version before this one, whose spawn meant something else', async () => {+ // Semantic, not structural: the older endpoint parses this spawn without+ // complaint and builds a different world from it. The handshake is the+ // only place that difference is visible.+ const serverApp = makeApp();+ const server = serverApp.getResource(Net).startServer();+ const [ta, tb] = MemoryTransport.pair();+ server.attachConnection(ta);+ const raw = new NetChannel(tb);+ const res = await raw.request<ReplHelloResponse>(ReplMsg.hello, {+ protocolVersion: REPLICATION_PROTOCOL_VERSION - 1,+ abiHash: ABI_LAYOUT_HASH,+ components: [],+ });+ expect(res.ok).toBe(false);+ if (!res.ok) expect(res.error).toMatch(/protocol/);+ });+it('refuses an ABI hash mismatch', async () => {const serverApp = makeApp();const server = serverApp.getResource(Net).startServer();@@ -202,9 +220,10 @@ describe('spawn / state / despawn replication', () => {const pos = clientApp.world.tryGet(ghost, NetPos)!;expect(pos.x).toBe(10);expect(pos.y).toBe(20);- // Spawn carries the full component payload — including non-replicated- // fields (spawn is scene-shaped); only per-tick deltas are filtered.- expect(pos.secret).toBe(42);+ // The spawn baseline carries DECLARED fields and nothing else, so an+ // undeclared one stays at the client's own default however the authority+ // set it. Before protocol v4 the payload was scene-shaped and this was 42.+ expect(pos.secret).toBe(0);const repl = clientApp.world.tryGet(ghost, Replicated)!;expect(repl.netId).toBeGreaterThan(0);expect(client.netIds.entityOf(repl.netId)).toBe(ghost);@@ -240,8 +259,9 @@ describe('spawn / state / despawn replication', () => {const gpos = clientApp.world.tryGet(ghost, NetPos)!;expect(gpos.x).toBe(100);expect(gpos.y).toBe(2);- // secret keeps its spawn-time value: never re-sent per tick.- expect(gpos.secret).toBe(3);+ // secret is undeclared: it did not ride the spawn baseline and no delta+ // carries it either, so the ghost holds its own default throughout.+ expect(gpos.secret).toBe(0);});it('a quiet server sends no state frames', async () => {