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
perf(net): ownership is looked up, not searched for
esengine272dbb9ed710
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 7123fa913..63015a999 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -4008,6 +4008,7 @@ raycastTarget: boolean```candidates: readonly number[]connectionId: number+owned: readonly number[] | undefinedworld: World```@@ -6534,6 +6535,7 @@ static prototype: ReplicationPlugin## ReplicationServer — class @experimental```@internal fullScans: number+@internal ownerScanVisits: numberattachConnection: (transport: ReliableOrderedTransport) => numberbeginTick: (fixedDelta: number) => voidclientIds: number[]@@ -9497,6 +9499,7 @@ tabIndex: number | undefined@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -9506,6 +9509,7 @@ tabIndex: number | undefined@internal disconnectCpp: () => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void+@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal getCppRegistry: () => CppRegistry | null@@ -9516,6 +9520,7 @@ tabIndex: number | undefined@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@internal getWorldVersion: () => number+@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@@ -9529,6 +9534,7 @@ tabIndex: number | undefined@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -9543,6 +9549,7 @@ tabIndex: number | undefined@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 8cdcafc01..35f7cfe9d 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -4016,6 +4016,7 @@ raycastTarget: boolean```candidates: readonly number[]connectionId: number+owned: readonly number[] | undefinedworld: World```@@ -6727,6 +6728,7 @@ static prototype: ReplicationPlugin## ReplicationServer — class @experimental```@internal fullScans: number+@internal ownerScanVisits: numberattachConnection: (transport: ReliableOrderedTransport) => numberbeginTick: (fixedDelta: number) => voidclientIds: number[]@@ -9690,6 +9692,7 @@ tabIndex: number | undefined@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -9699,6 +9702,7 @@ tabIndex: number | undefined@internal disconnectCpp: () => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void+@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal getCppRegistry: () => CppRegistry | null@@ -9709,6 +9713,7 @@ tabIndex: number | undefined@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@internal getWorldVersion: () => number+@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@@ -9722,6 +9727,7 @@ tabIndex: number | undefined@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -9736,6 +9742,7 @@ tabIndex: number | undefined@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 83ba211d9..1b2bdef01 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4003,6 +4003,7 @@ raycastTarget: boolean```candidates: readonly number[]connectionId: number+owned: readonly number[] | undefinedworld: World```@@ -6529,6 +6530,7 @@ static prototype: ReplicationPlugin## ReplicationServer — class @experimental```@internal fullScans: number+@internal ownerScanVisits: numberattachConnection: (transport: ReliableOrderedTransport) => numberbeginTick: (fixedDelta: number) => voidclientIds: number[]@@ -9492,6 +9494,7 @@ tabIndex: number | undefined@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -9501,6 +9504,7 @@ tabIndex: number | undefined@internal disconnectCpp: () => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void+@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal getCppRegistry: () => CppRegistry | null@@ -9511,6 +9515,7 @@ tabIndex: number | undefined@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@internal getWorldVersion: () => number+@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@@ -9524,6 +9529,7 @@ tabIndex: number | undefined@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -9538,6 +9544,7 @@ tabIndex: number | undefined@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex ae3a41c95..ac1ea3dec 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -4003,6 +4003,7 @@ raycastTarget: boolean```candidates: readonly number[]connectionId: number+owned: readonly number[] | undefinedworld: World```@@ -6775,6 +6776,7 @@ static prototype: ReplicationPlugin## ReplicationServer — class @experimental```@internal fullScans: number+@internal ownerScanVisits: numberattachConnection: (transport: ReliableOrderedTransport) => numberbeginTick: (fixedDelta: number) => voidclientIds: number[]@@ -9744,6 +9746,7 @@ tabIndex: number | undefined@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -9753,6 +9756,7 @@ tabIndex: number | undefined@internal disconnectCpp: () => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void+@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal getCppRegistry: () => CppRegistry | null@@ -9763,6 +9767,7 @@ tabIndex: number | undefined@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@internal getWorldVersion: () => number+@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@@ -9776,6 +9781,7 @@ tabIndex: number | undefined@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -9790,6 +9796,7 @@ tabIndex: number | undefined@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 09794b7b5..6032df9c2 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4010,6 +4010,7 @@ raycastTarget: boolean```candidates: readonly number[]connectionId: number+owned: readonly number[] | undefinedworld: World```@@ -6536,6 +6537,7 @@ static prototype: ReplicationPlugin## ReplicationServer — class @experimental```@internal fullScans: number+@internal ownerScanVisits: numberattachConnection: (transport: ReliableOrderedTransport) => numberbeginTick: (fixedDelta: number) => voidclientIds: number[]@@ -9520,6 +9522,7 @@ tabIndex: number | undefined@internal advanceRemovedReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal advanceTick: () => void@internal advanceTopologyReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void+@internal advanceWriteReader: (component: AnyComponentDef, readerId: number, lastRunTick: number) => void@internal anyChangedSince: (component: AnyComponentDef, sinceTick: number) => boolean@internal applyEntityOrder: (entities: readonly Entity[]) => void@internal beginIteration: () => void@@ -9529,6 +9532,7 @@ tabIndex: number | undefined@internal disconnectCpp: () => void@internal disposeRemovedReader: (component: AnyComponentDef, readerId: number) => void@internal disposeTopologyReader: (component: AnyComponentDef, readerId: number) => void+@internal disposeWriteReader: (component: AnyComponentDef, readerId: number) => void@internal enableChangeTracking: (component: AnyComponentDef) => void@internal endIteration: () => void@internal getCppRegistry: () => CppRegistry | null@@ -9539,6 +9543,7 @@ tabIndex: number | undefined@internal getWasmModule: () => ESEngineModule | null@internal getWorldTick: () => number@internal getWorldVersion: () => number+@internal getWrittenEntitiesSince: (component: AnyComponentDef, sinceTick: number) => Entity[]@internal hasCpp: boolean@internal isAddedSince: (entity: Entity, component: AnyComponentDef, sinceTick: number) => boolean@internal isChangeTracked: (component: AnyComponentDef) => boolean@@ -9552,6 +9557,7 @@ tabIndex: number | undefined@internal registerRemovedReader: (component: AnyComponentDef) => number@internal registerRemovedReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal registerTopologyReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number+@internal registerWriteReaderFrom: (component: AnyComponentDef, retainFromTick: number) => number@internal removedReaderCount: (component: AnyComponentDef) => number@internal resetIterationDepth: () => void@internal resetQueryCacheStats: () => void@@ -9566,6 +9572,7 @@ tabIndex: number | undefined@internal suspendIteration: () => number@internal topologyReaderCount: (component: AnyComponentDef) => number@internal useScriptPoolMemory: (memory: PoolMemory) => void+@internal writeReaderCount: (component: AnyComponentDef) => numberdespawn: (entity: Entity) => voidentityCount: () => numberfindEntityByName: (name: string) => Entity | nulldiff --git a/sdk/src/ecs/ChangeTracker.ts b/sdk/src/ecs/ChangeTracker.tsindex 05bec25fb..3315bb84d 100644--- a/sdk/src/ecs/ChangeTracker.ts+++ b/sdk/src/ecs/ChangeTracker.ts@@ -100,6 +100,13 @@ export class ChangeTracker {private readonly removals_ = new ReaderOwnedJournal();/** Membership moves, independent of ordinary change tracking. */private readonly topology_ = new ReaderOwnedJournal();+ /**+ * Components WRITTEN, for a consumer that needs to enumerate them sparsely.+ * `isChangedSince` answers about one entity at a time; finding which entities+ * changed through it means walking the per-entity map, which is the O(E) a+ * candidate consumer is trying to avoid.+ */+ private readonly writes_ = new ReaderOwnedJournal();private trackedComponents_ = new Set<symbol>();// The most recent worldTick at which ANY entity changed each component — an// O(1) "did anything change since tick T" gate (vs scanning the per-entity map).@@ -170,6 +177,31 @@ export class ChangeTracker {return this.topology_.readerCount(component._id);}+ /** Entities whose `component` was written after `sinceTick`. Says nothing+ * about WHICH field, or whether the value actually differs. */+ getWrittenEntitiesSince(component: AnyComponentDef, sinceTick: number): Entity[] {+ return this.writes_.since(component._id, sinceTick);+ }++ registerWriteReaderFrom(component: AnyComponentDef, retainFromTick: number): number {+ const id = this.nextReaderId_++;+ this.writes_.register(component._id, id, retainFromTick);+ return id;+ }++ advanceWriteReader(component: AnyComponentDef, readerId: number, lastRunTick: number): void {+ this.writes_.advance(component._id, readerId, lastRunTick);+ }++ disposeWriteReader(component: AnyComponentDef, readerId: number): void {+ this.writes_.dispose(component._id, readerId);+ }++ /** @internal How many readers hold `component`'s write journal. */+ writeReaderCount(component: AnyComponentDef): number {+ return this.writes_.readerCount(component._id);+ }+/*** Take out a claim on `component`'s removal history. History begins HERE:* a new reader does not inherit rows another reader happened to leave, so@@ -238,6 +270,12 @@ export class ChangeTracker {}recordChanged(component: AnyComponentDef, entity: Entity): void {+ // Before the tracking gate, like the other two journals: a consumer that+ // enumerates writes should not have to enrol the component in `Changed`+ // tracking, whose per-entity map it cannot enumerate cheaply anyway.+ if (this.writes_.hasReaders(component._id)) {+ this.writes_.record(component._id, entity, this.worldTick_);+ }if (!this.trackedComponents_.has(component._id)) return;let map = this.componentChangedTicks_.get(component._id);if (!map) {diff --git a/sdk/src/ecs/world.ts b/sdk/src/ecs/world.tsindex 2d49a3cd6..aa61baf4f 100644--- a/sdk/src/ecs/world.ts+++ b/sdk/src/ecs/world.ts@@ -1249,6 +1249,32 @@ export class World {return this.changes_.topologyReaderCount(component);}+ /** @internal A claim on `component`'s WRITE journal — which entities had it+ * written, enumerable sparsely, unlike the per-entity changed map. */+ registerWriteReaderFrom(component: AnyComponentDef, retainFromTick: number): number {+ return this.changes_.registerWriteReaderFrom(component, retainFromTick);+ }++ /** @internal Entities whose `component` was written after `sinceTick`. */+ getWrittenEntitiesSince(component: AnyComponentDef, sinceTick: number): Entity[] {+ return this.changes_.getWrittenEntitiesSince(component, sinceTick);+ }++ /** @internal That reader is done with everything up to `lastRunTick`. */+ advanceWriteReader(component: AnyComponentDef, readerId: number, lastRunTick: number): void {+ this.changes_.advanceWriteReader(component, readerId, lastRunTick);+ }++ /** @internal The reader is gone; its share of the watermark goes with it. */+ disposeWriteReader(component: AnyComponentDef, readerId: number): void {+ this.changes_.disposeWriteReader(component, readerId);+ }++ /** @internal How many readers hold `component`'s write journal. */+ writeReaderCount(component: AnyComponentDef): number {+ return this.changes_.writeReaderCount(component);+ }+/** @internal Mark component as changed without writing data (for in-place Mut query) */markChanged(entity: Entity, component: AnyComponentDef): void {this.changes_.recordChanged(component, entity);diff --git a/sdk/src/net/replication/interest.ts b/sdk/src/net/replication/interest.tsindex 254ed2dd1..005facb53 100644--- a/sdk/src/net/replication/interest.ts+++ b/sdk/src/net/replication/interest.ts@@ -24,6 +24,10 @@ export interface InterestView {world: World;/** Every currently replicated entity — the set to filter. */candidates: readonly Entity[];+ /** The entities this connection owns, when the host keeps an index of them.+ * A policy that needs its own anchors should prefer this over reading+ * `Replicated.owner` off every candidate; absent, fall back to that. */+ owned?: readonly Entity[];}/**@@ -60,11 +64,16 @@ export interface RadiusInterestOptions {export function radiusInterest(radius: number, options: RadiusInterestOptions = {}): InterestPolicy {const r2 = radius * radius;const positionOf = options.position ?? defaultPosition;- return ({ connectionId, world, candidates }) => {+ return ({ connectionId, world, candidates, owned }) => {const anchors: InterestPoint[] = [];- for (const e of candidates) {- const repl = world.tryGet(e, Replicated) as ReplicatedData | null;- if (repl?.owner !== connectionId) continue;+ // The host's own index when it offers one: finding this connection's+ // entities by reading `owner` off every candidate is O(population) per+ // connection, and the answer is already known.+ for (const e of owned ?? candidates) {+ if (!owned) {+ const repl = world.tryGet(e, Replicated) as ReplicatedData | null;+ if (repl?.owner !== connectionId) continue;+ }const p = positionOf(world, e);if (p) anchors.push(p);}diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.tsindex e94d8eb75..2446b3b80 100644--- a/sdk/src/net/replication/server.ts+++ b/sdk/src/net/replication/server.ts@@ -147,8 +147,22 @@ export class ReplicationServer {*/private registryFloor_: number;private readonly registryReader_: number;+ /**+ * Who owns what, so neither the anchor lookup nor the server's forced-owner+ * pass has to read every candidate to find out. Installed with the first+ * interest policy — a broadcast server never pays for it — and kept for the+ * server's life, since a policy can be swapped mid-session.+ */+ private ownedByConnection_: Map<number, Set<Entity>> | null = null;+ /** The index's own record of who owned each entity: a write says the NEW+ * owner, and the old one is needed to take the entity off its set. */+ private readonly ownerOfEntity_ = new Map<Entity, number>();+ private ownerFloor_ = -1;+ private ownerReader_: number | null = null;/** @internal Full-world reconciliations run — a steady-state sample must do none. */fullScans = 0;+ /** @internal Candidates read to answer "who owns this" — zero once indexed. */+ ownerScanVisits = 0;constructor(world: World) {this.world_ = world;@@ -218,6 +232,10 @@ export class ReplicationServer {for (const o of this.observations_) this.world_.disposeRemovedReader(o.def, o.readerId);this.observations_.length = 0;this.world_.disposeTopologyReader(Replicated, this.registryReader_);+ if (this.ownerReader_ !== null) {+ this.world_.disposeWriteReader(Replicated, this.ownerReader_);+ this.ownerReader_ = null;+ }this.offDespawn_();}@@ -256,9 +274,62 @@ export class ReplicationServer {* set against the new policy.*/setInterestPolicy(policy: InterestPolicy | null): void {+ if (policy && !this.ownedByConnection_) this.installOwnerIndex_();this.policy_ = policy;}+ /** Claim the write journal, then seed from what is already known — in that+ * order, so nothing written between the two is missed. */+ private installOwnerIndex_(): void {+ this.ownerFloor_ = this.world_.getWorldTick() - 1;+ this.ownerReader_ = this.world_.registerWriteReaderFrom(Replicated, this.ownerFloor_ + 1);+ this.ownedByConnection_ = new Map();+ for (const e of this.known_) this.indexOwner_(e);+ }++ /** Put `e` under its current owner, taking it off the previous one's set. */+ private indexOwner_(e: Entity): void {+ const index = this.ownedByConnection_;+ if (!index) return;+ const repl = this.world_.tryGet(e, Replicated) as ReplicatedData | null;+ const now = repl ? repl.owner : undefined;+ const before = this.ownerOfEntity_.get(e);+ if (before === now) return;+ if (before !== undefined) this.ownedByConnection_?.get(before)?.delete(e);+ if (now === undefined) { this.ownerOfEntity_.delete(e); return; }+ let set = index.get(now);+ if (!set) { set = new Set(); index.set(now, set); }+ set.add(e);+ this.ownerOfEntity_.set(e, now);+ }++ /** Drop `e` from the index entirely — it has left replication. */+ private unindexOwner_(e: Entity): void {+ const before = this.ownerOfEntity_.get(e);+ if (before === undefined) return;+ this.ownedByConnection_?.get(before)?.delete(e);+ this.ownerOfEntity_.delete(e);+ }++ /**+ * Refresh the index from the entities whose `Replicated` was written. Write+ * history SELECTS candidates; the index's own record against the current+ * world DECIDES — a write that did not move ownership costs one comparison.+ */+ private refreshOwnerIndex_(): void {+ if (this.ownerReader_ === null) return;+ for (const e of this.world_.getWrittenEntitiesSince(Replicated, this.ownerFloor_)) {+ if (this.known_.has(e)) this.indexOwner_(e);+ }+ }++ private advanceOwnerFloor_(): void {+ if (this.ownerReader_ === null) return;+ const nextFloor = this.world_.getWorldTick() - 1;+ this.world_.advanceWriteReader(Replicated, this.ownerReader_, nextFloor);+ this.ownerFloor_ = nextFloor;+ }+/** Accept a transport (server-side end of one client link). */attachConnection(transport: ReliableOrderedTransport): number {const id = this.nextConnectionId_++;@@ -367,11 +438,16 @@ export class ReplicationServer {// floor pins history for as long as the server runs empty.this.advanceObservationFloor_();this.advanceRegistryFloor_();+ this.advanceOwnerFloor_();return;}const { spawnedEntities, despawned } = this.reconcileRegistryIncremental_();+ // Before anything reads ownership: an owner that changed this frame must+ // place the view THIS sample, not the next one.+ this.refreshOwnerIndex_();+// Diff once against the shadow; frames below share the result.const sample = this.collectDirty_();@@ -392,6 +468,7 @@ export class ReplicationServer {// Last: the windows are given up only once their rows are on the wire.this.advanceObservationFloor_();this.advanceRegistryFloor_();+ this.advanceOwnerFloor_();}/** Fast path (no policy): everything to every ready connection on shared@@ -518,9 +595,21 @@ export class ReplicationServer {* applied on top: a connection always sees the entities it owns (input* routing and prediction anchor on them, so a policy cannot cull them). */private visibleFor_(connectionId: number, candidates: readonly Entity[]): Set<Entity> {- const result = this.policy_!({ connectionId, world: this.world_, candidates });+ const owned = this.ownedByConnection_?.get(connectionId);+ const result = this.policy_!({+ connectionId, world: this.world_, candidates,+ owned: owned ? [...owned] : undefined,+ });const visible = result === 'all' ? new Set(candidates) : new Set(result);+ // The server's invariant, not the policy's: an entity a connection owns+ // is always visible to it. From the index when there is one — reading it+ // off every candidate is the same question asked a second time.+ if (owned) {+ for (const e of owned) visible.add(e);+ return visible;+ }for (const e of candidates) {+ this.ownerScanVisits++;if (visible.has(e)) continue;const repl = this.world_.tryGet(e, Replicated) as ReplicatedData | null;if (repl && repl.owner === connectionId) visible.add(e);@@ -546,10 +635,12 @@ export class ReplicationServer {for (const e of current) {if (!this.known_.has(e)) {this.registerEntity_(e);+ this.indexOwner_(e);spawnedEntities.push(e);continue;}this.restoreNetId_(e);+ this.indexOwner_(e);}const despawned: { entity: Entity; netId: number }[] = [];@@ -588,8 +679,10 @@ export class ReplicationServer {const isLive = this.world_.valid(e) && this.world_.has(e, Replicated);if (!isKnown && isLive) {this.registerEntity_(e);+ this.indexOwner_(e);spawnedEntities.push(e);} else if (isKnown && !isLive) {+ this.unindexOwner_(e);const netId = this.knownNetIds_.get(e);if (netId !== undefined) {despawned.push({ entity: e, netId });@@ -617,6 +710,8 @@ export class ReplicationServer {// The shadow is now the world, so both windows start here too.this.advanceObservationFloor_();this.advanceRegistryFloor_();+ this.refreshOwnerIndex_();+ this.advanceOwnerFloor_();}/**diff --git a/sdk/tests/replication-owner-transfer.test.ts b/sdk/tests/replication-owner-transfer.test.tsnew file mode 100644index 000000000..b021e52a0--- /dev/null+++ b/sdk/tests/replication-owner-transfer.test.ts@@ -0,0 +1,184 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Ownership decides two different things, and both have to keep up.+ *+ * `Replicated.owner` places a connection's VIEW — `radiusInterest` reads the+ * entities a connection owns to find its anchors — and it separately forces+ * those entities to stay visible whatever a policy says. A lookup that goes+ * stale on a transfer can satisfy the second and quietly fail the first, so the+ * fixture watches an entity that is only visible THROUGH the moved anchor.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { App } from '../src/app/app';+import { clearUserComponents, defineComponent, Name } from '../src/ecs/component';+import { MemoryTransport } from '../src/net/MemoryTransport';+import { replicationPlugin, Net, Replicated, radiusInterest } from '../src/net/replication';+import type { Entity } from '../src/types';+import type { World } from '../src/ecs/world';++const STEP = 1 / 60;+/** Sim ticks between replication samples: 60Hz simulation, 20Hz replication. */+const SAMPLE_FRAMES = 3;++let NetPos: ReturnType<typeof defineComponent<{ x: number; y: number; z: number }>>;++beforeEach(() => {+ clearUserComponents();+ NetPos = defineComponent('NetPos', { x: 0, y: 0, z: 0 }, { replicatedFields: ['x', 'y', 'z'] });+});++const makeApp = (): App => { const a = App.new(); a.addPlugin(replicationPlugin); return a; };+const posOf = (world: World, e: Entity): { x: number; y: number; z: number } | null => {+ const p = world.tryGet(e, NetPos) as { x: number; y: number; z: number } | null;+ return p ? { x: p.x, y: p.y, z: p.z } : null;+};++const ghosts = (app: App): string[] =>+ app.world.getEntitiesWithComponents([Replicated])+ .map((e) => (app.world.tryGet(e, Name) as { value: string } | null)?.value ?? '')+ .sort();++describe('the ownership a policy is handed', () => {+ it('already reflects a transfer made before this sample', async () => {+ const serverApp = makeApp();+ const server = serverApp.getResource(Net).startServer();+ const world = serverApp.world;++ const ids: number[] = [];+ const clientApps: App[] = [];+ for (let i = 0; i < 2; i++) {+ const app = makeApp();+ const [ta, tb] = MemoryTransport.pair();+ ids.push(server.attachConnection(ta));+ await app.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });+ clientApps.push(app);+ }++ // Watching what the server hands the policy removes the wire from the+ // question: this is about WHEN the index is refreshed within a sample,+ // and a client's copy arrives a frame later either way.+ const seen: { conn: number; owned: number[] }[] = [];+ server.setInterestPolicy(({ connectionId, owned, candidates }) => {+ seen.push({ conn: connectionId, owned: owned ? [...(owned as number[])] : [] });+ return new Set(candidates);+ });++ const e = world.spawn('pawn');+ world.insert(e, Replicated, { owner: ids[0] });+ world.insert(e, NetPos, { x: 0, y: 0, z: 0 });+ const step = async (n = 1) => {+ for (let i = 0; i < n; i++) {+ await serverApp.tick(STEP);+ for (const a of clientApps) await a.tick(STEP);+ }+ };+ await step(4);+ expect(seen.some((r) => r.conn === ids[0] && r.owned.includes(e as number))).toBe(true);++ world.update(e, Replicated, (r) => { (r as { owner: number }).owner = ids[1] as number; });+ seen.length = 0;+ await step(SAMPLE_FRAMES);++ // The FIRST evaluation after the transfer, not eventually.+ const firstForNewOwner = seen.find((r) => r.conn === ids[1]);+ expect(firstForNewOwner?.owned).toContain(e as number);+ const firstForOldOwner = seen.find((r) => r.conn === ids[0]);+ expect(firstForOldOwner?.owned).not.toContain(e as number);+ });+});++describe('what the ownership pass costs', () => {+ it('reads no candidates once the index is installed', async () => {+ const serverApp = makeApp();+ const server = serverApp.getResource(Net).startServer();+ const world = serverApp.world;+ const clientApp = makeApp();+ const [ta, tb] = MemoryTransport.pair();+ const id = server.attachConnection(ta);+ await clientApp.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });+ server.setInterestPolicy(radiusInterest(20, { position: posOf }));++ for (let i = 0; i < 200; i++) {+ const e = world.spawn(`e${i}`);+ world.insert(e, Replicated, { owner: i === 0 ? id : -1 });+ world.insert(e, NetPos, { x: i * 10, y: 0, z: 0 });+ }+ await serverApp.tick(STEP); await clientApp.tick(STEP);++ // The forced-owner pass answered from the index reads nothing; answering+ // it off the candidate list is the second O(population) walk per+ // connection this exists to remove.+ const before = server.ownerScanVisits;+ for (let i = 0; i < 6; i++) { await serverApp.tick(STEP); await clientApp.tick(STEP); }+ expect(server.ownerScanVisits).toBe(before);+ });+});++describe('an anchor changing hands', () => {+ it('moves the view with it, not just the entity itself', async () => {+ const serverApp = makeApp();+ const server = serverApp.getResource(Net).startServer();+ const world = serverApp.world;++ const clients: { app: App; id: number }[] = [];+ for (let i = 0; i < 2; i++) {+ const app = makeApp();+ const [ta, tb] = MemoryTransport.pair();+ const id = server.attachConnection(ta);+ await app.getResource(Net).connect(tb, { interpolationDelayTicks: 0 });+ clients.push({ app, id });+ }+ const [c0, c1] = clients;+ server.setInterestPolicy(radiusInterest(20, { position: posOf }));++ const place = (name: string, x: number, owner: number): Entity => {+ const e = world.spawn(name);+ world.insert(e, Replicated, { owner });+ world.insert(e, NetPos, { x, y: 0, z: 0 });+ return e;+ };+ // c0 holds the anchor that will move, AND a second one far away — without+ // it, losing its last positioned anchor makes radiusInterest fail open to+ // 'all' and the target would never leave, for the wrong reason.+ const moving = place('moving', 0, c0.id);+ place('c0-far', 1000, c0.id);+ place('c1-own', 500, c1.id);+ const target = place('target', 5, -1);++ const step = async (n = 1) => {+ for (let i = 0; i < n; i++) {+ await serverApp.tick(STEP);+ for (const c of clients) await c.app.tick(STEP);+ }+ };+ await step(2);++ expect(ghosts(c0.app)).toContain('target');+ expect(ghosts(c1.app)).not.toContain('target');+ // The prerequisite the whole case rests on: c0 keeps a positioned anchor+ // after the transfer, so a `leave` means the view moved, not that the+ // policy gave up.+ expect(ghosts(c0.app)).toContain('c0-far');++ world.update(moving, Replicated, (r) => { (r as { owner: number }).owner = c1.id; });++ // Counted, not slept through: ownership must place the view on the FIRST+ // sample after the transfer. Refreshing the index later in the sample+ // than the interest evaluation still converges — one sample late.+ let frames = 0;+ while (ghosts(c0.app).includes('target') && frames < 12) {+ await step();+ frames++;+ }+ expect(frames).toBeLessThanOrEqual(SAMPLE_FRAMES + 1);++ // The anchor left c0, so what only it could see leaves too.+ expect(ghosts(c0.app)).not.toContain('target');+ expect(ghosts(c0.app)).toContain('c0-far');+ // And c1 gets both the anchor it now owns and what stands beside it.+ expect(ghosts(c1.app)).toContain('moving');+ expect(ghosts(c1.app)).toContain('target');+ expect(target).toBeGreaterThan(0);+ });+});