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
fix(net): a client joining a quiet server is told the world as it is
esengine2199ce8dc37d
diff --git a/sdk/src/net/replication/server.ts b/sdk/src/net/replication/server.tsindex 0e1ddff37..54aed5690 100644--- a/sdk/src/net/replication/server.ts+++ b/sdk/src/net/replication/server.ts@@ -286,32 +286,7 @@ export class ReplicationServer {this.tick_ = tick;if (this.connections_.size === 0) return;- const current = this.world_.getEntitiesWithComponents([Replicated]);- const currentSet = new Set(current);-- const spawnedEntities: Entity[] = [];- for (const e of current) {- if (!this.known_.has(e)) {- this.registerEntity_(e);- spawnedEntities.push(e);- }- }-- // netIds captured before unregistering so per-connection despawns can- // still name entities that vanished this tick.- const despawned: { entity: Entity; netId: number }[] = [];- for (const e of [...this.known_]) {- if (!currentSet.has(e) || !this.world_.valid(e)) {- const netId = this.knownNetIds_.get(e);- if (netId !== undefined) {- despawned.push({ entity: e, netId });- this.netIds_.unregister(netId);- }- this.known_.delete(e);- this.knownNetIds_.delete(e);- this.shadow_.delete(e);- }- }+ const { spawnedEntities, despawned } = this.reconcileRegistry_();// Diff once against the shadow; frames below share the result.const sample = this.collectDirty_();@@ -465,6 +440,53 @@ export class ReplicationServer {return visible;}+ /**+ * Bring the registry level with the world, and say what moved. netIds are+ * captured before unregistering so a per-connection despawn can still name+ * an entity that vanished this tick.+ */+ private reconcileRegistry_(): {+ spawnedEntities: Entity[];+ despawned: { entity: Entity; netId: number }[];+ } {+ const current = this.world_.getEntitiesWithComponents([Replicated]);+ const currentSet = new Set(current);++ const spawnedEntities: Entity[] = [];+ for (const e of current) {+ if (!this.known_.has(e)) {+ this.registerEntity_(e);+ spawnedEntities.push(e);+ }+ }++ const despawned: { entity: Entity; netId: number }[] = [];+ for (const e of [...this.known_]) {+ if (!currentSet.has(e) || !this.world_.valid(e)) {+ const netId = this.knownNetIds_.get(e);+ if (netId !== undefined) {+ despawned.push({ entity: e, netId });+ this.netIds_.unregister(netId);+ }+ this.known_.delete(e);+ this.knownNetIds_.delete(e);+ this.shadow_.delete(e);+ }+ }+ return { spawnedEntities, despawned };+ }++ /**+ * The registry, rebuilt from the world for a client arriving when nothing is+ * ready. `sample` returns early with no connections, so the registry stops+ * following the world — and the initial state is built FROM it. Shadows are+ * re-seeded so the frame after does not re-send what the spawn carried.+ */+ private rebaseRegistry_(): void {+ this.reconcileRegistry_();+ for (const e of this.known_) this.seedShadow_(e);+ }+private registerEntity_(e: Entity): void {const repl = this.world_.tryGet(e, Replicated) as ReplicatedData;if (repl.netId === 0) {@@ -559,6 +581,9 @@ export class ReplicationServer {private sendInitialState_(conn: Connection): void {if (!this.connections_.has(conn.id)) return;+ let anyReady = false;+ for (const c of this.connections_.values()) if (c.ready) { anyReady = true; break; }+ if (!anyReady) this.rebaseRegistry_();// Everything relevant right now, full component payloads (current state// included — no separate baseline frame needed).const candidates = [...this.known_];diff --git a/sdk/tests/replication-zero-clients.test.ts b/sdk/tests/replication-zero-clients.test.tsnew file mode 100644index 000000000..e5b3a6b3e--- /dev/null+++ b/sdk/tests/replication-zero-clients.test.ts@@ -0,0 +1,87 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file What a client joining an already-running server is told.+ *+ * `sample()` returns early with no connections, so the replication registry+ * stops tracking the world while nobody is listening. The next client's initial+ * state is built from that registry — so whatever the world did in between has+ * to be reconciled before the first spawn batch goes out, or the client starts+ * from a world that no longer exists.+ */+import { describe, it, expect, beforeEach } from 'vitest';+import { App } from '../src/app/app';+import { defineComponent, clearUserComponents, Name } from '../src/ecs/component';+import { MemoryTransport } from '../src/net/MemoryTransport';+import { replicationPlugin, Net, Replicated } from '../src/net/replication';+import type { Entity } from '../src/types';++const STEP = 1 / 60;++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; };++function spawnAt(app: App, name: string, x: number): Entity {+ const e = app.world.spawn(name);+ app.world.insert(e, Replicated, { owner: 0 });+ app.world.insert(e, NetPos, { x, y: 0, z: 0 });+ return e;+}++const ghosts = (app: App): string[] =>+ app.world.getEntitiesWithComponents([Replicated])+ .map((e) => (app.world.tryGet(e, Name) as { value: string } | null)?.value ?? '')+ .sort();++const xOf = (app: App, name: string): number | undefined => {+ for (const e of app.world.getEntitiesWithComponents([Replicated])) {+ if ((app.world.tryGet(e, Name) as { value: string } | null)?.value === name) {+ return (app.world.tryGet(e, NetPos) as { x: number } | null)?.x;+ }+ }+ return undefined;+};++describe('a client that joins after the server ran with nobody connected', () => {+ it('is told the world as it is now, not as the last client left it', async () => {+ const serverApp = makeApp();+ const server = serverApp.getResource(Net).startServer();++ const stays = spawnAt(serverApp, 'stays', 10);+ const leaves = spawnAt(serverApp, 'leaves', 20);++ // A connects, sees both, and goes away.+ const appA = makeApp();+ const [sa, ca] = MemoryTransport.pair();+ const connA = server.attachConnection(sa);+ const clientA = await appA.getResource(Net).connect(ca, { interpolationDelayTicks: 0 });+ await serverApp.tick(STEP); await appA.tick(STEP);+ expect(ghosts(appA)).toEqual(['leaves', 'stays']);+ clientA.disconnect();+ server.detachConnection(connA);++ // The world moves on with nobody listening.+ serverApp.world.despawn(leaves);+ const joined = spawnAt(serverApp, 'joined', 30);+ serverApp.world.set(stays, NetPos, { x: 99, y: 0, z: 0 });+ for (let i = 0; i < 4; i++) await serverApp.tick(STEP);++ // B connects. What the INITIAL STATE says, before any later sample can+ // correct it: only the client ticks here, so this is the handshake alone.+ const appB = makeApp();+ const [sb, cb] = MemoryTransport.pair();+ server.attachConnection(sb);+ await appB.getResource(Net).connect(cb, { interpolationDelayTicks: 0 });+ await appB.tick(STEP);++ expect(ghosts(appB)).toEqual(['joined', 'stays']);+ expect(xOf(appB, 'stays')).toBe(99);+ expect(joined).toBeGreaterThan(0);+ });+});