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: drain streamed worlds before teardown and replacement
yhh6c311327dd44
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 5a51f8de2..275cb0fc2 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -109,6 +109,15 @@ jobs:run: node tools/tests/placement-shadows.e2e.mjs --webgl-only- name: Check composite lifecycle and mixed shadow policies with genuine headless Chromiumrun: node tools/tests/composite-batch.e2e.mjs --webgl-only+ - name: Check 2D and 3D world residency teardown with genuine headless Chromium+ run: node tools/tests/world-residency.e2e.mjs --webgl-only+ - name: Upload world residency observations+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: world-residency-webgl2+ path: output/world-residency/+ retention-days: 3- name: Upload composite batching observationsif: always()uses: actions/upload-artifact@v7@@ -1120,6 +1129,15 @@ jobs:run: node tools/verify-render.mjs --tier pr --backend webgpu --host engine --no-build --budget 45- name: Check composite lifecycle and mixed shadow policies on the second backendrun: node tools/tests/composite-batch.e2e.mjs --webgpu-only+ - name: Check 2D and 3D world residency teardown on the second backend+ run: node tools/tests/world-residency.e2e.mjs --webgpu-only+ - name: Upload second-backend world residency observations+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: world-residency-webgpu+ path: output/world-residency/+ retention-days: 3- name: Upload second-backend composite batching observationsif: always()uses: actions/upload-artifact@v7diff --git a/docs/astro/src/content/docs/world/streaming.mdx b/docs/astro/src/content/docs/world/streaming.mdxindex 9d1f7f6c8..ffd30b47d 100644--- a/docs/astro/src/content/docs/world/streaming.mdx+++ b/docs/astro/src/content/docs/world/streaming.mdx@@ -183,6 +183,18 @@ report.loadCount; // places brought in since bootCounts rather than a picture, because a cell that is not drawn and a cell thatdoes not exist look the same from a camera.+## Clearing or replacing a world++Disable or remove the streaming sources, then await `streamer.clear()`. It releases+prepared assets and waits for pending preparation, publication and unloading to+finish. Registrations remain reusable: a later source update can request the cells again.++Await `streamer.loadManifest(manifest, sceneConfig)` when replacing a world. It drains+the old cells before registering the replacement, including when both manifests reuse+the same cell names. The latest concurrent replacement request wins; an explicit+`clear()` cancels pending replacement requests. Failed teardown rejects the operation+so the replacement cannot take ownership of a name that still has live content.+## What this version does not doCells load asynchronously through the same scene loading a game already uses.diff --git a/docs/astro/src/content/docs/zh-cn/world/streaming.mdx b/docs/astro/src/content/docs/zh-cn/world/streaming.mdxindex 9f8df1c3e..27ab6fecf 100644--- a/docs/astro/src/content/docs/zh-cn/world/streaming.mdx+++ b/docs/astro/src/content/docs/zh-cn/world/streaming.mdx@@ -150,6 +150,15 @@ report.loadCount; // 启动以来带进来过多少个地方给的是计数而不是画面,因为"没有被画出来的格子"和"根本不存在的格子",从相机看是一样的。+## 清空或替换世界++先禁用或移除流送源,再等待 `streamer.clear()`。它会释放已经预加载的资源,并等待尚未完成的准备、发布和卸载结束。+格子的注册信息会保留,后续更新流送源时仍可以重新请求这些格子。++替换世界时,等待 `streamer.loadManifest(manifest, sceneConfig)`。它会先清理旧格子,再注册新清单,+两个清单使用相同格子名称时也遵守这个顺序。并发替换以最后一次请求为准;显式调用 `clear()` 会取消尚未完成的替换请求。+如果卸载失败,操作会拒绝完成,防止新世界接管仍有旧内容存活的名称。+## 这一版不做什么格子通过游戏本来就在用的场景加载路径异步到达。它们有先后(来源正要走进的格子先于只是可能走进的,近的先)diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 170633aa4..df120208a 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -13580,9 +13580,9 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```-clear: () => void+clear: () => Promise<void>delivery: () => Record<string, CellDelivery>-loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => void+loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => Promise<void>manifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => voidrenderReadinessOf: (name: string) => RenderReadinessStamp | nulldiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 166d3c06d..016c15cf4 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -13796,9 +13796,9 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```-clear: () => void+clear: () => Promise<void>delivery: () => Record<string, CellDelivery>-loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => void+loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => Promise<void>manifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => voidrenderReadinessOf: (name: string) => RenderReadinessStamp | nulldiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 7febc6f6d..7e170fd02 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -13575,9 +13575,9 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```-clear: () => void+clear: () => Promise<void>delivery: () => Record<string, CellDelivery>-loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => void+loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => Promise<void>manifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => voidrenderReadinessOf: (name: string) => RenderReadinessStamp | nulldiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex b903c131f..964b54846 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -13877,9 +13877,9 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```-clear: () => void+clear: () => Promise<void>delivery: () => Record<string, CellDelivery>-loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => void+loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => Promise<void>manifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => voidrenderReadinessOf: (name: string) => RenderReadinessStamp | nulldiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 872d89064..712029fad 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -13608,9 +13608,9 @@ unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>## WorldStreamer — class @experimental```-clear: () => void+clear: () => Promise<void>delivery: () => Record<string, CellDelivery>-loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => void+loadManifest: (manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig) => Promise<void>manifest: WorldManifest | nullrecordPhase: (name: string, phase: string, ms: number) => voidrenderReadinessOf: (name: string) => RenderReadinessStamp | nulldiff --git a/sdk/src/residency/WorldStreamer.ts b/sdk/src/residency/WorldStreamer.tsindex 1a81639ff..9dc87aa31 100644--- a/sdk/src/residency/WorldStreamer.ts+++ b/sdk/src/residency/WorldStreamer.ts@@ -168,19 +168,20 @@ export class WorldStreamer {private prefetchHits_ = 0;private prefetchMisses_ = 0;private lastDemandToResident_ = 0;+ private readonly operations_ = new Set<Promise<void>>();+ private clearPromise_: Promise<void> | null = null;+ private clearing_ = false;+ private manifestRequest_ = 0;constructor(host: WorldStreamHost) {this.host_ = host;}- /**- * Adopt a cooked world: its cells become loadable scenes and residency- * answers for them.- *- * Registered here, not beside the game's own scenes: a cell is content- * residency brings in, and `switchTo('cell_3_2')` is a second author.- */- loadManifest(manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig): void {+ /** Adopt a cooked world after the previous world's operations and receipts drain. The latest request wins. */+ async loadManifest(manifest: WorldManifest, sceneConfig?: (cell: WorldCell) => SceneConfig): Promise<void> {+ const request = ++this.manifestRequest_;+ if (this.cells_.size > 0 || this.clearing_) await this.clearCells_();+ if (request !== this.manifestRequest_) return;this.manifest_ = manifest;this.cells_.clear();for (const cell of manifest.cells) {@@ -272,6 +273,7 @@ export class WorldStreamer {* the world the first is standing in.*/update(sources: readonly ResidencySource[]): void {+ if (this.clearing_) return;this.sourceCount_ = sources.length;if (this.cells_.size === 0) return;const resident = new Set<string>();@@ -299,18 +301,52 @@ export class WorldStreamer {for (const name of decision.prefetch) if (!target.has(name)) this.step_(name);for (const name of decision.toUnload) this.step_(name);for (const [name, state] of this.cells_) {- if (state.residency === 'prepared' && !state.desired && !state.speculated) {+ if ((state.residency === 'prepared' || state.residency === 'preparing') && !state.desired && !state.speculated) {this.step_(name);}}}- /** Everything goes; the cells stay registered. For a world being torn down. */- clear(): void {- for (const [name, state] of this.cells_) {+ /** Drain every cell and preparation; registrations remain reusable by a later update. Cancels pending adoption. */+ clear(): Promise<void> {+ this.manifestRequest_++;+ return this.clearCells_();+ }++ private clearCells_(): Promise<void> {+ if (this.clearPromise_) return this.clearPromise_;+ this.clearing_ = true;+ this.sourceCount_ = 0;+ for (const state of this.cells_.values()) {state.desired = false;- if (state.residency === 'resident') this.step_(name);+ state.speculated = false;}+ this.clearPromise_ = (async () => {+ for (const name of this.cells_.keys()) this.step_(name);+ // Publication may finish by starting an unload, so drain the entire chain.+ while (this.operations_.size > 0) await Promise.allSettled([...this.operations_]);+ const remaining = [...this.cells_].filter(([, state]) => state.residency !== 'unloaded');+ if (remaining.length > 0) throw new Error(`World residency could not release: ${remaining.map(([name]) => name).join(', ')}`);+ })().finally(() => {+ this.clearing_ = false;+ this.clearPromise_ = null;+ });+ return this.clearPromise_;+ }++ /** Track host operations through their completion handlers so replacement cannot reuse a live scene name. */+ private run_<T>(action: () => Promise<T>, done: (value: T) => void, failed: (error: unknown) => void): void {+ let result: Promise<T>;+ try { result = Promise.resolve(action()); } catch (error) { result = Promise.reject(error); }+ const operation = result.then(done, failed);+ this.operations_.add(operation);+ void operation.then(+ () => { this.operations_.delete(operation); },+ error => {+ this.operations_.delete(operation);+ log.error('residency', 'cell completion failed', error);+ },+ );}status(): WorldStreamerStatus {@@ -375,12 +411,14 @@ export class WorldStreamer {private step_(name: string): void {const state = this.cells_.get(name);if (!state) return;+ if (state.readinessInFlight) return;if (state.residency === 'preparing') {// Assets are in and only the program obligation is left. Retried// here, because a claim refused once (a device that rebuilt mid-// readying) costs one more attempt rather than the whole preparation.- if (state.assetsReady && !state.readinessInFlight) {- this.settleReadiness_(name, state);+ if (state.assetsReady) {+ if (!state.desired && !state.speculated) this.discardPrepared_(name, state);+ else this.settleReadiness_(name, state);}return;}@@ -393,16 +431,20 @@ export class WorldStreamer {// Speculation is not authority. A cell nobody is near any more goes// back, receipts included, rather than being published because it// happens to be ready.- this.cancelledRefs_ += this.host_.discardPrepared(name);- state.residency = 'unloaded';- state.assetsReady = false;- state.renderReadiness = null;- this.cancelCount_++;+ this.discardPrepared_(name, state);} else if (state.residency === 'resident' && !state.desired) {this.beginUnload_(name, state);}}+ private discardPrepared_(name: string, state: CellState): void {+ this.cancelledRefs_ += this.host_.discardPrepared(name);+ state.residency = 'unloaded';+ state.assetsReady = false;+ state.renderReadiness = null;+ this.cancelCount_++;+ }+private beginPrepare_(name: string, state: CellState): void {state.residency = 'preparing';state.phases = {};@@ -421,12 +463,12 @@ export class WorldStreamer {}state.assetsReady = false;state.renderReadiness = null;- Promise.resolve(this.host_.prepare(name)).then(+ this.run_(() => this.host_.prepare(name),() => {// One obligation of two. `prepared` is not the end of the assets// arriving, it is the end of everything publication requires.state.assetsReady = true;- this.settleReadiness_(name, state);+ this.step_(name);},(err) => {state.residency = 'unloaded';@@ -448,9 +490,10 @@ export class WorldStreamer {if (!ready) { this.markPrepared_(name, state); return; }state.readinessInFlight = true;- this.askReadiness_(name, ready).then(+ this.run_(() => this.askReadiness_(name, ready),(outcome) => {state.readinessInFlight = false;+ if (!state.desired && !state.speculated) { this.discardPrepared_(name, state); return; }// Not applicable is an answer, not a claim: a host with no// renderer has nothing to ready and owes nothing.if (!outcome.applicable) { this.markPrepared_(name, state); return; }@@ -465,6 +508,7 @@ export class WorldStreamer {(err) => {state.readinessInFlight = false;log.error('residency', `cell "${name}" could not ready its programs`, err);+ if (!state.desired && !state.speculated) this.step_(name);},);}@@ -518,9 +562,10 @@ export class WorldStreamer {if (state.readinessInFlight) return;state.readinessInFlight = true;- this.askReadiness_(name, ready).then(+ this.run_(() => this.askReadiness_(name, ready),(outcome) => {state.readinessInFlight = false;+ if (!state.desired) { this.step_(name); return; }if (!outcome.applicable) { this.beginLoad_(name, state); return; }if (!outcome.stamp) {// Publication created a debt of its own — the readying was@@ -541,6 +586,7 @@ export class WorldStreamer {(err) => {state.readinessInFlight = false;log.error('residency', `cell "${name}" could not re-ready its programs`, err);+ if (!state.desired) this.step_(name);},);}@@ -549,7 +595,7 @@ export class WorldStreamer {state.residency = 'publishing';state.publishedAt = performance.now();this.loadCount_++;- Promise.resolve(this.host_.loadAdditive(name)).then(+ this.run_(() => this.host_.loadAdditive(name),() => {const now = performance.now();state.residency = 'resident';@@ -577,12 +623,11 @@ export class WorldStreamer {// `keepPersistent: false` is the contract: a cell's unload takes everything// the cell brought. Scene persistence answers a different question, and// honouring it here leaves exactly what residency exists to remove.- Promise.resolve(this.host_.unload(name, { keepPersistent: false })).then(+ this.run_(() => this.host_.unload(name, { keepPersistent: false }),() => { state.residency = 'unloaded'; this.step_(name); },(err) => {state.residency = this.host_.isLoaded(name) ? 'resident' : 'unloaded';log.error('residency', `cell "${name}" did not unload`, err);- this.step_(name);},);}diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex 543bf2db7..28e71bc83 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -914,7 +914,7 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {const streamer = app.getResource(WorldStreaming);// Read out here: inside the callback `config` is the scene's, not this one's.const documents = config.cellDocuments;- streamer.loadManifest(world, (cell) => {+ await streamer.loadManifest(world, (cell) => {// Set ON the config, not spread into a copy of it: the setup that// loads the cell closes over the object this returns, so a copy// carries the fields somewhere nothing reads them.diff --git a/sdk/tests/world-residency.test.ts b/sdk/tests/world-residency.test.tsindex 95dff434a..bdd9f284f 100644--- a/sdk/tests/world-residency.test.ts+++ b/sdk/tests/world-residency.test.ts@@ -1,9 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team/**- * @file world-residency.test.ts — why a cell exists, and what the streamer does- * about it. The decision is pure and is held to on its own; the streamer- * is held to the moves it issues, against a host that records them.+ * @file world-residency.test.ts+ * @brief Verify residency decisions, asynchronous ownership and world replacement.*/import { describe, it, expect, vi } from 'vitest';import {@@ -160,7 +159,7 @@ function recordingHost(readiness?: () => RenderReadiness) {},loadAdditive(name) {calls.push(`load:${name}`);- const settle = (): void => { loaded.add(name); };+ const settle = (): void => { readied.delete(name); loaded.add(name); };if (!deferred) { settle(); return Promise.resolve({}); }return new Promise((resolve) => pending.push(() => { settle(); resolve({}); }));},@@ -656,6 +655,191 @@ describe('WorldStreamer', () => {});});+describe('world residency teardown and replacement', () => {+ it('releases prepared assets when the world is cleared', async () => {+ const h = recordingHost();+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(3, 0)));+ streamer.update([source(0, 50, 100, 150, 400)]);+ await flush();+ expect(h.readied.size).toBe(1);+ await streamer.clear();+ await flush();+ expect(h.readied.size).toBe(0);+ expect(streamer.status().prefetchCells).toEqual([]);+ expect(streamer.residencyOf('c_3_0')).toBe('unloaded');+ });++ it('discards a preparation that finishes after clearing began', async () => {+ const h = recordingHost(); h.defer(true);+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ const cleared = streamer.clear();+ h.settle(); h.defer(false);+ await cleared; await flush();+ expect(h.readied.size).toBe(0);+ expect(h.loaded.size).toBe(0);+ expect(streamer.residencyOf('c_0_0')).toBe('unloaded');+ });++ it('unloads a resident cell without preparing it again during clear', async () => {+ const h = recordingHost();+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20, 400)]);+ await flush();+ expect(h.loaded.size).toBe(1);+ await streamer.clear(); await flush();+ expect(h.loaded.size).toBe(0);+ expect(h.readied.size).toBe(0);+ expect(streamer.status().prepareCount).toBe(1);+ });++ it('does not publish after demand disappears during the final readiness check', async () => {+ const claim: RenderReadiness = { applicable: true, stamp: { digestLo: 7, digestHi: 0, programEpoch: 3 } };+ const h = recordingHost();+ let checks = 0, finish!: (value: RenderReadiness) => void;+ h.host.readyRenderPrograms = () => ++checks === 1 ? Promise.resolve(claim)+ : new Promise(resolve => { finish = resolve; });+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ await flush();+ expect(checks).toBe(2);+ streamer.update([]);+ finish(claim); await flush(); await flush();+ expect(h.calls.filter(call => call.startsWith('load:'))).toEqual([]);+ expect(h.readied.size).toBe(0);+ expect(streamer.residencyOf('c_0_0')).toBe('unloaded');+ });++ it('releases assets whose render-program readiness never became valid', async () => {+ const h = recordingHost(() => ({ applicable: true, stamp: null }));+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ await flush();+ expect(streamer.residencyOf('c_0_0')).toBe('preparing');+ await streamer.clear(); await flush();+ expect(h.readied.size).toBe(0);+ expect(streamer.residencyOf('c_0_0')).toBe('unloaded');+ });++ it.each(['unclaimed', 'rejected'])('releases %s readiness when the last source leaves', async outcome => {+ const h = recordingHost(() => {+ if (outcome === 'rejected') throw new Error('renderer unavailable');+ return { applicable: true, stamp: null };+ });+ const streamer = new WorldStreamer(h.host);+ await streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ await flush();+ expect(streamer.residencyOf('c_0_0')).toBe('preparing');+ expect(h.readied.size).toBe(1);+ streamer.update([]);+ await flush();+ expect(h.readied.size).toBe(0);+ expect(streamer.residencyOf('c_0_0')).toBe('unloaded');+ expect(h.calls.some(call => call.startsWith('load:'))).toBe(false);+ });++ it('unloads the previous manifest before registering a replacement', async () => {+ const h = recordingHost();+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ await flush();+ await streamer.loadManifest(manifest(cell(5, 0)));+ expect(h.loaded.size).toBe(0);+ expect(h.calls.indexOf('unload:c_0_0:false')).toBeLessThan(h.calls.indexOf('register:c_5_0'));+ expect(h.calls).toContain('unload:c_0_0:false');+ });++ it('returns old preparation receipts before reusing a cell name', async () => {+ const h = recordingHost(); h.defer(true);+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ const replacement = streamer.loadManifest(manifest(cell(0, 0)));+ h.settle(); h.defer(false);+ await replacement; await flush();+ expect(h.readied.size).toBe(0);+ expect(h.calls).toContain('discard:c_0_0');+ expect(h.calls.indexOf('discard:c_0_0')).toBeLessThan(h.calls.lastIndexOf('register:c_0_0'));+ });++ it('waits for in-flight publication and its teardown before clear resolves', async () => {+ const h = recordingHost();+ let publish!: () => void;+ const load = h.host.loadAdditive;+ h.host.loadAdditive = name => new Promise(resolve => { publish = () => { void load(name).then(resolve); }; });+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ await flush();+ expect(streamer.residencyOf('c_0_0')).toBe('publishing');+ let cleared = false;+ const clearing = streamer.clear().then(() => { cleared = true; });+ streamer.update([source(50, 50, 10, 20)]);+ await flush(); expect(cleared).toBe(false);+ publish(); await clearing;+ expect(h.loaded.size).toBe(0);+ expect(h.readied.size).toBe(0);+ expect(streamer.status().loadCount).toBe(1);+ expect(streamer.status().unloadCount).toBe(1);+ streamer.update([source(50, 50, 10, 20)]);+ await flush(); publish(); await flush();+ expect(h.loaded.size).toBe(1);+ });++ it('adopts only the latest manifest requested while old work drains', async () => {+ const h = recordingHost(); h.defer(true);+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ const first = streamer.loadManifest(manifest(cell(3, 0)));+ const last = streamer.loadManifest(manifest(cell(5, 0)));+ h.settle(); h.defer(false);+ await Promise.all([first, last]);+ expect(h.calls).not.toContain('register:c_3_0');+ expect(streamer.manifest?.cells.map(c => c.name)).toEqual(['c_5_0']);+ expect(h.readied.size).toBe(0);+ });++ it('an explicit clear cancels a pending manifest adoption', async () => {+ const h = recordingHost(); h.defer(true);+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ const replacement = streamer.loadManifest(manifest(cell(5, 0)));+ const cleared = streamer.clear();+ h.settle(); h.defer(false);+ await Promise.all([replacement, cleared]);+ expect(h.calls).not.toContain('register:c_5_0');+ expect(h.loaded.size).toBe(0);+ expect(h.readied.size).toBe(0);+ });++ it('reports a failed unload without spinning or adopting a replacement over live content', async () => {+ const h = recordingHost();+ const unload = h.host.unload;+ let attempts = 0;+ h.host.unload = () => { attempts++; throw new Error('teardown unavailable'); };+ const streamer = new WorldStreamer(h.host);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ await flush();+ await expect(streamer.loadManifest(manifest(cell(5, 0)))).rejects.toThrow('c_0_0');+ expect(attempts).toBe(1);+ expect(h.calls).not.toContain('register:c_5_0');+ expect(h.loaded.size).toBe(1);+ h.host.unload = unload;+ await streamer.clear();+ expect(h.loaded.size).toBe(0);+ });+});+describe('a handle that no longer names its entity', () => {it('does not reach the entity holding its slot', () => {// What residency makes ordinary: an event in flight carries a handlediff --git a/tools/lib/streamingDistricts.mjs b/tools/lib/streamingDistricts.mjsnew file mode 100644index 000000000..54197e566--- /dev/null+++ b/tools/lib/streamingDistricts.mjs@@ -0,0 +1,42 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file streamingDistricts.mjs+ * @brief Two textured neighbourhoods exercising the shared XY and XZ residency path.+ */+export function streamingDistricts(plane, tag = 'base') {+ const screen = plane === 'xy';+ const component = (type, data = {}) => ({ type, data });+ const transform = (position, scale, rotation) => component('Transform', { position,+ ...(scale ? { scale } : {}), ...(rotation ? { rotation } : {}) });+ const persistent = (id, name, components) => ({ id, name, parent: null, children: [], visible: true,+ components: [...components, component('WorldPersistent')] });+ const entities = [+ persistent(1, 'World', [component('StreamedWorld', { cellSize: 100, plane: screen ? 1 : 0 })]),+ persistent(2, 'Observer', [transform({ x: 50, y: screen ? 50 : 0, z: screen ? 0 : 50 }),+ component('WorldStreamingSource', { loadRadius: 30, unloadRadius: 80, prefetchRadius: 500 })]),+ persistent(3, 'Camera', [transform(screen ? { x: 200, y: 150, z: 900 } : { x: 200, y: 500, z: 150 }, undefined,+ screen ? undefined : { x: -Math.SQRT1_2, y: 0, z: 0, w: Math.SQRT1_2 }),+ component('Camera', { isActive: true, projectionType: screen ? 1 : 0, fov: 50, orthoSize: 420, nearPlane: 0.1, farPlane: 1500 })]),+ ];+ if (!screen) entities.push(persistent(4, 'Sun', [transform({ x: 0, y: 0, z: 0 }, undefined,+ { x: -0.3826834324, y: 0, z: 0, w: 0.9238795325 }),+ component('Light', { type: 1, intensity: 1.2, color: { r: 1, g: 1, b: 1, a: 1 }, meshShadows: true, shadowExtent: 600 })]));+ for (let cell = 0; cell < 2; cell++) {+ const id = 100 + cell * 100, x = 50 + cell * 300, second = 50 + cell * 200;+ const name = `${tag}-${cell ? 'b' : 'a'}`;+ const root = { id, name: `${name}-district`, parent: null, children: [], visible: true,+ components: [transform({ x, y: screen ? second : 0, z: screen ? 0 : second })] };+ entities.push(root);+ for (let i = 0; i < 16; i++) {+ const child = id + i + 1, u = (i % 4) * 20 - 30, v = Math.floor(i / 4) * 20 - 30;+ root.children.push(child);+ entities.push({ id: child, name: `${name}-part-${i}`, parent: id, children: [], visible: true, components: [+ transform({ x: u, y: screen ? v : 0, z: screen ? 0 : v }, screen ? undefined : { x: 0.14, y: 0.16, z: 0.14 }),+ component(screen ? 'Sprite' : 'MeshRenderer', { texture: `/textures/residency-${name}.png`,+ ...(screen ? { size: { x: 14, y: 14 } } : { mesh: i % 2 ? 'builtin:cube' : 'builtin:cylinder', lit: true, opaque: true }) }),+ ] });+ }+ }+ return { version: 4, name: `Residency ${plane} ${tag}`, entities };+}diff --git a/tools/render-host/host.ts b/tools/render-host/host.tsindex 07c988d17..15f13baee 100644--- a/tools/render-host/host.ts+++ b/tools/render-host/host.ts@@ -23,6 +23,8 @@ import {getContextLossGuardInfo, decodeImagePixels, captureFramePixels, captureFrame, replayDraw, BatchBreak,RenderTexture, Camera, Sprite, Time,Children, MeshRenderer, RuntimeOnly, CompositeBatch, CompositeBatchingRes, StaticBatchingRes,+ HttpBackend, initRuntime, createRuntimeSceneConfig, WorldStreaming, worldResidencyReport,+ cutWorld, registryEntityFields, stableEntityId, persistentEntityRows,planarReflectionStatus,EditorViewLighting, EditorViewShading, EditorView, EditorGrid, installEditorGrid, editorViewHalfHeight, setEditorViewHalfHeight,ProfileRecorder, AnimatorController, Timeline, onDeviceRestored, Schedule, defineSystem,@@ -69,6 +71,7 @@ let canvas: HTMLCanvasElement | null = null;// write down. loadSceneData hands back exactly that mapping.let sceneRaw: SceneData | null = null;let sourceToEntity = new Map<number, number>();+let streamedSource: RuntimeAssetSource | null = null;/** A door this host does not have. Naming it beats a silent no-op that renders a wrong frame. */function editorOnly(door: string): never {@@ -443,6 +446,52 @@ const api = {canvas.height = h;},+ /** Boot the same partition and scene transactions used by cooked games and editor Play. */+ async loadStreamedWorld(scene: SceneData, name: string) {+ if (!app || !module || streamedSource) throw new Error('loadStreamedWorld requires a fresh host');+ const cut = cutWorld(scene, name, { entityFieldsOf: registryEntityFields() });+ if (!cut || cut.errors.length > 0) throw new Error(`Cannot partition world: ${cut?.errors.join('; ')}`);+ streamedSource = {+ backend: new HttpBackend({ baseUrl: '' }),+ decodePixels: async path => {+ const response = await fetch(path);+ if (!response.ok) throw new Error(`Texture fetch failed: ${response.status} ${path}`);+ return decodeImagePixels(await response.blob());+ },+ };+ await initRuntime({ app, module, source: streamedSource, firstScene: name,+ scenes: [{ name, data: cut.persistent }], worlds: [cut.manifest], cellDocuments: cut.documents });+ sourceToEntity = new Map(app.world.getAllEntities().flatMap(entity => {+ const id = stableEntityId(app!, entity);+ return id === undefined ? [] : [[id, entity] as [number, number]];+ }));+ return cut.manifest;+ },++ /** Replace the cell manifest while retaining the persistent scene and its sources. */+ async replaceStreamedWorld(scene: SceneData, name: string) {+ if (!app || !streamedSource) throw new Error('No streamed world is running');+ const streamer = app.getResource(WorldStreaming);+ const cut = cutWorld(scene, name, { entityFieldsOf: registryEntityFields() });+ if (!cut || cut.errors.length > 0 || !streamer.manifest) throw new Error('Cannot partition replacement world');+ cut.manifest.scene = streamer.manifest.scene;+ await streamer.loadManifest(cut.manifest, cell => {+ const config = createRuntimeSceneConfig(cell.name, cut.documents.get(cell.name),+ { app: app!, module, source: streamedSource! }, cell.path);+ config.externalEntities = () => persistentEntityRows(app!, cut.manifest);+ config.onPhase = (phase, ms) => streamer.recordPhase(cell.name, phase, ms);+ return config;+ });+ return cut.manifest;+ },++ clearWorldResidency: () => app!.getResource(WorldStreaming).clear(),++ worldResidencySnapshot() {+ return { ...worldResidencyReport(app!), assets: app!.getResource(Assets).sizes(),+ entities: app!.world.entityCount(), names: app!.world.getAllEntities().map(entity => app!.world.tryGet(entity, Name)?.value) };+ },+/** Advances frames by hand — the per-frame work app.run()'s loop does. */async step(framesIn: number | null = 1, dtIn: number | null = 1 / 60): Promise<{ world: string; frames: number; dt: number }> {// An omitted argument arrives as null across the JSON hop, and a defaultdiff --git a/tools/tests/world-residency.e2e.mjs b/tools/tests/world-residency.e2e.mjsnew file mode 100644index 000000000..a5586739d--- /dev/null+++ b/tools/tests/world-residency.e2e.mjs@@ -0,0 +1,138 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file world-residency.e2e.mjs+ * @brief Verify real XY/XZ scene transactions, repeated residency and cancellation of delayed assets.+ */+import { chromium } from 'playwright';+import { mkdir, writeFile } from 'node:fs/promises';+import { createRequire } from 'node:module';+import { fileURLToPath } from 'node:url';+import path from 'node:path';+import assert from 'node:assert/strict';+import { serveHost } from '../lib/staticServer.mjs';+import { requireCurrentEngine } from '../lib/engineBuild.mjs';+import { streamingDistricts } from '../lib/streamingDistricts.mjs';++const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');+const out = path.join(root, 'output/world-residency');+const { PNG } = createRequire(new URL('../../pipeline/package.json', import.meta.url))('pngjs');+requireCurrentEngine(root, path.join(root, 'build/render-host/wasm'));+await mkdir(out, { recursive: true });+assert.ok(!(process.argv.includes('--webgl-only') && process.argv.includes('--webgpu-only')));+const backends = process.argv.includes('--webgl-only') ? ['webgl2']+ : process.argv.includes('--webgpu-only') ? ['webgpu'] : ['webgl2', 'webgpu'];+const texture = new PNG({ width: 8, height: 8 });+for (let y = 0; y < 8; y++) for (let x = 0; x < 8; x++) {+ const p = (y * 8 + x) * 4, bright = (x + y) % 2 === 0;+ texture.data.set(bright ? [245, 174, 61, 255] : [34, 151, 192, 255], p);+}+const textureBytes = PNG.sync.write(texture);+const server = await serveHost(path.join(root, 'build/render-host'));+const browser = await chromium.launch({ channel: 'chromium', headless: true,+ args: ['--enable-unsafe-webgpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader', '--mute-audio'] });+const report = { status: 'failed', cases: [] };+try {+ for (const backend of backends) for (const plane of ['xy', 'xz']) {+ const page = await browser.newPage({ viewport: { width: 384, height: 256 } });+ const errors = [];+ page.on('pageerror', error => errors.push(String(error)));+ page.on('console', event => { if (event.type() === 'error') errors.push(event.text()); });+ await page.route('**/favicon.ico', route => route.fulfill({ status: 204 }));+ let releaseLate, lateRequested = false;+ const lateGate = new Promise(resolve => { releaseLate = resolve; });+ await page.route('**/textures/residency-*.png', async route => {+ if (route.request().url().endsWith('/residency-late-b.png')) { lateRequested = true; await lateGate; }+ await route.fulfill({ contentType: 'image/png', body: textureBytes });+ });+ await page.goto(`http://127.0.0.1:${server.address().port}/?w=384&h=256&backend=${backend}`);+ await page.evaluate(async () => { await window.__estellaHeadless.ready; });+ const manifest = await page.evaluate(scene => window.__estellaHeadless.api.loadStreamedWorld(scene, 'districts'), streamingDistricts(plane));+ assert.equal(manifest.plane ?? 'xz', plane);+ assert.deepEqual(manifest.cells.map(cell => [cell.x, cell.z]), [[0, 0], [3, 2]]);+ const snapshot = () => page.evaluate(() => window.__estellaHeadless.api.worldResidencySnapshot());+ const baseline = await snapshot();+ const wait = async predicate => {+ let state;+ for (let i = 0; i < 300; i++) {+ await page.evaluate(() => window.__estellaHeadless.api.step(2));+ state = await snapshot();+ if (predicate(state)) return state;+ await new Promise(resolve => setTimeout(resolve, 10));+ }+ throw new Error(`Residency did not settle: ${JSON.stringify(state)}`);+ };+ const settled = state => state.loadingCells.length === 0 && state.unloadingCells.length === 0 && state.assets.pendingLoads === 0;+ const enabled = value => page.evaluate(value => window.__estellaHeadless.api.setField(2, 'WorldStreamingSource', 'enabled', '', value), value);+ const move = far => page.evaluate(({ far, plane }) => window.__estellaHeadless.api.setField(2, 'Transform', 'position', '',+ { x: far ? 350 : 50, y: plane === 'xy' ? (far ? 250 : 50) : 0, z: plane === 'xz' ? (far ? 250 : 50) : 0 }), { far, plane });+ const assertEmpty = state => {+ assert.deepEqual(state.residentCells, []); assert.deepEqual(state.preparedCells, []);+ assert.deepEqual(state.loadingCells, []); assert.deepEqual(state.unloadingCells, []);+ assert.equal(state.entities, baseline.entities);+ assert.equal(state.assets.refRows, baseline.assets.refRows);+ assert.equal(state.assets.trackedRefRows, baseline.assets.trackedRefRows);+ assert.equal(state.assets.pendingLoads, 0);+ };+ await page.evaluate(() => window.__estellaHeadless.api.setRunMode(true));+ const initial = await wait(state => settled(state) && state.residentCells.length === 1 && state.preparedCells.length === 1);+ assert.equal(initial.residentCells[0], 'districts.cell_0_0');+ assert.ok(initial.entities > baseline.entities && initial.assets.refRows > baseline.assets.refRows);+ const raw = await page.evaluate(async () => {+ const { api } = window.__estellaHeadless;+ await api.step(3); await api.waitForShaders(); await api.step(2);+ const p = await api.captureViewportPixels(); return { width: p.width, height: p.height, rgba: Array.from(p.rgba) };+ });+ const shot = new PNG({ width: raw.width, height: raw.height }), pixels = Buffer.from(raw.rgba), stride = raw.width * 4;+ let visible = 0;+ for (let i = 0; i < pixels.length; i += 4) if ([0, 1, 2].some(c => Math.abs(pixels[i + c] - pixels[c]) > 8)) visible++;+ for (let y = 0; y < raw.height; y++) pixels.copy(shot.data, y * stride, (raw.height - y - 1) * stride, (raw.height - y) * stride);+ await writeFile(path.join(out, `${backend}-${plane}-resident.png`), PNG.sync.write(shot));+ assert.ok(visible > 200, `A resident neighbourhood must produce visible pixels: ${visible}`);+ const cycles = [];+ for (let i = 0; i < 6; i++) {+ await move(i % 2 === 0);+ const live = await wait(state => settled(state) && state.residentCells[0] === (i % 2 === 0 ? 'districts.cell_3_2' : 'districts.cell_0_0') && state.preparedCells.length === 1);+ assert.equal(live.entities, initial.entities);+ assert.equal(live.assets.refRows, initial.assets.refRows);+ await enabled(false);+ const began = performance.now();+ await page.evaluate(() => window.__estellaHeadless.api.clearWorldResidency());+ const empty = await snapshot(); assertEmpty(empty);+ cycles.push({ clearMs: performance.now() - began, entities: empty.entities, assetRefRows: empty.assets.refRows });+ await enabled(true);+ }+ await wait(state => settled(state) && state.residentCells.length === 1 && state.preparedCells.length === 1);+ await page.evaluate(scene => window.__estellaHeadless.api.replaceStreamedWorld(scene, 'replacement'), streamingDistricts(plane, 'replacement'));+ const replaced = await snapshot(); assertEmpty(replaced);+ assert.ok(!replaced.names.some(name => name?.startsWith('base-')));+ const residentReplacement = await wait(state => settled(state) && state.residentCells.length === 1 && state.preparedCells.length === 1);+ assert.ok(residentReplacement.names.some(name => name?.startsWith('replacement-')));+ await enabled(false);+ await page.evaluate(scene => window.__estellaHeadless.api.replaceStreamedWorld(scene, 'late'), streamingDistricts(plane, 'late'));+ await move(false); await enabled(true);+ await wait(state => state.residentCells.includes('late.cell_0_0') && state.loadingCells.includes('late.cell_3_2') && lateRequested);+ await page.evaluate(() => {+ const { api } = window.__estellaHeadless;+ api.setField(2, 'WorldStreamingSource', 'enabled', '', false);+ window.__clearDone = false;+ window.__clearResult = api.clearWorldResidency().then(() => { window.__clearDone = true; });+ });+ assert.equal(await page.evaluate(() => window.__clearDone), false);+ releaseLate();+ await page.evaluate(() => window.__clearResult);+ const cancelled = await snapshot(); assertEmpty(cancelled);+ assert.ok(!cancelled.names.some(name => name?.startsWith('late-')));+ assert.deepEqual(errors, []);+ report.cases.push({ backend, plane, persistentEntities: baseline.entities, visiblePixels: visible,+ residentEntities: initial.entities, residentAssetRefRows: initial.assets.refRows, cycles,+ replacementCleared: true, delayedPreparationCancelled: true, finalAssetRefRows: cancelled.assets.refRows });+ console.log(JSON.stringify(report.cases.at(-1)));+ await page.close();+ }+ report.status = 'checks-passed';+} catch (error) { report.error = String(error); throw error; }+finally {+ await writeFile(path.join(out, 'report.json'), JSON.stringify(report, null, 2));+ await browser.close(); await new Promise(resolve => server.close(resolve));+}