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(residency): a world states where it is cut, and who needs it present
esengine27a731c4971a
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 21d640a62..5d374e56f 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 · 1602 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1622 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1961,6 +1961,11 @@ x: numbery: number```+## CellResidency — type @experimental+```+'unloaded' | 'loading' | 'resident' | 'unloading'+```+## Census — interface @experimental```atMs: number@@ -6917,6 +6922,21 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>static prototype: ResMutInstance<any>```+## ResidencyDecision — interface @experimental+```+target: string[]+toLoad: string[]+toUnload: string[]+```++## ResidencySource — interface @experimental+```+loadRadius: number+unloadRadius: number+x: number+z: number+```+## ResolvedAssetGroup — interface @experimental```alwaysInclude: boolean@@ -8104,6 +8124,17 @@ toDeactivate: string[]'unload' | 'sleep'```+## StreamedWorld — const @experimental+```+ComponentDef<StreamedWorldData>+```++## StreamedWorldData — interface @experimental+```+cellSize: number+enabled: boolean+```+## SubEmitterTrigger — enum @beta```Birth = 1@@ -10008,6 +10039,33 @@ static prototype: World0 | 1 | 2```+## WorldCell — interface @experimental+```+entityCount: number+maxX: number+maxZ: number+minX: number+minZ: number+name: string+path: string+rootCount: number+x: number+z: number+```++## WorldManifest — interface @experimental+```+cellSize: number+cells: WorldCell[]+scene: string+version: number+```++## WorldPersistent — const @experimental+```+ComponentDef<{}>+```+## WorldRay — interface @experimental```dir: Vec3@@ -10022,6 +10080,73 @@ right: numbertop: number```+## WorldResidencyReport — interface @experimental+```+assetRefsByCell: Record<string, number>+authoredCellEntityCounts: Record<string, number>+cellCount: number+cellEntityCounts: Record<string, number>+cellRenderCounts: Record<string, number>+desiredCells: string[]+loadCount: number+loadingCells: string[]+persistentEntities: number+residentCells: string[]+sourceCount: number+streamed: boolean+unloadCount: number+unloadingCells: string[]+```++## WorldStreamHost — interface @experimental+```+isLoaded: (name: string) => boolean+loadAdditive: (name: string) => Promise<unknown>+register: (config: { name: string; path: string; }) => void+unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>+```++## WorldStreamer — class @experimental+```+clear: () => void+loadManifest: (manifest: WorldManifest) => void+manifest: WorldManifest | null+residencyOf: (name: string) => CellResidency+status: () => WorldStreamerStatus+update: (sources: readonly ResidencySource[]) => void+static new (host: WorldStreamHost): WorldStreamer+static prototype: WorldStreamer+```++## WorldStreamerStatus — interface @experimental+```+cellCount: number+desiredCells: string[]+loadCount: number+loadingCells: string[]+residentCells: string[]+sourceCount: number+unloadCount: number+unloadingCells: string[]+```++## WorldStreaming — const @experimental+```+ResourceDef<WorldStreamer>+```++## WorldStreamingSource — const @experimental+```+ComponentDef<WorldStreamingSourceData>+```++## WorldStreamingSourceData — interface @experimental+```+enabled: boolean+loadRadius: number+unloadRadius: number+```+## WorldTransform — const @experimental @deprecated```BuiltinComponentDef<TransformData>@@ -10872,6 +10997,11 @@ PluralSelector(input: { x: number; y: number; }, basis: MoveBasis): Vec3```+## desiredResidency — function @experimental+```+(cells: readonly WorldCell[], sources: readonly ResidencySource[], resident: ReadonlySet<string>): ResidencyDecision+```+## detectAnchor — function @experimental```(node: UINodeData): AnchorPreset | null@@ -10907,6 +11037,11 @@ DiagnosticsPlugin(sceneData: SceneData, refResolver?: RefResolver): SceneAssetRefs```+## distanceToCell — function @experimental+```+(cell: WorldCell, x: number, z: number): number+```+## dragPlugin — const @experimental```DragPlugin@@ -13242,6 +13377,21 @@ VideoPlugin(axis: WorldAxis): Vec3```+## worldResidencyPlugin — const @experimental+```+Plugin+```++## worldResidencyReport — function @experimental+```+(app: App): WorldResidencyReport+```++## worldResidencySystem — const @experimental+```+SystemDef+```+## wrapSceneSystem — function @experimental```(app: App, sceneName: string, system: SystemDef): SystemDefdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex f02be4675..bab10841e 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 · 1621 experimental · 3 deprecated+Symbols: 113 public · 89 beta · 1641 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -1961,6 +1961,11 @@ x: numbery: number```+## CellResidency — type @experimental+```+'unloaded' | 'loading' | 'resident' | 'unloading'+```+## Census — interface @experimental```atMs: number@@ -7110,6 +7115,21 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>static prototype: ResMutInstance<any>```+## ResidencyDecision — interface @experimental+```+target: string[]+toLoad: string[]+toUnload: string[]+```++## ResidencySource — interface @experimental+```+loadRadius: number+unloadRadius: number+x: number+z: number+```+## ResolvedAssetGroup — interface @experimental```alwaysInclude: boolean@@ -8297,6 +8317,17 @@ toDeactivate: string[]'unload' | 'sleep'```+## StreamedWorld — const @experimental+```+ComponentDef<StreamedWorldData>+```++## StreamedWorldData — interface @experimental+```+cellSize: number+enabled: boolean+```+## SubEmitterTrigger — enum @beta```Birth = 1@@ -10201,6 +10232,33 @@ static prototype: World0 | 1 | 2```+## WorldCell — interface @experimental+```+entityCount: number+maxX: number+maxZ: number+minX: number+minZ: number+name: string+path: string+rootCount: number+x: number+z: number+```++## WorldManifest — interface @experimental+```+cellSize: number+cells: WorldCell[]+scene: string+version: number+```++## WorldPersistent — const @experimental+```+ComponentDef<{}>+```+## WorldRay — interface @experimental```dir: Vec3@@ -10215,6 +10273,73 @@ right: numbertop: number```+## WorldResidencyReport — interface @experimental+```+assetRefsByCell: Record<string, number>+authoredCellEntityCounts: Record<string, number>+cellCount: number+cellEntityCounts: Record<string, number>+cellRenderCounts: Record<string, number>+desiredCells: string[]+loadCount: number+loadingCells: string[]+persistentEntities: number+residentCells: string[]+sourceCount: number+streamed: boolean+unloadCount: number+unloadingCells: string[]+```++## WorldStreamHost — interface @experimental+```+isLoaded: (name: string) => boolean+loadAdditive: (name: string) => Promise<unknown>+register: (config: { name: string; path: string; }) => void+unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>+```++## WorldStreamer — class @experimental+```+clear: () => void+loadManifest: (manifest: WorldManifest) => void+manifest: WorldManifest | null+residencyOf: (name: string) => CellResidency+status: () => WorldStreamerStatus+update: (sources: readonly ResidencySource[]) => void+static new (host: WorldStreamHost): WorldStreamer+static prototype: WorldStreamer+```++## WorldStreamerStatus — interface @experimental+```+cellCount: number+desiredCells: string[]+loadCount: number+loadingCells: string[]+residentCells: string[]+sourceCount: number+unloadCount: number+unloadingCells: string[]+```++## WorldStreaming — const @experimental+```+ResourceDef<WorldStreamer>+```++## WorldStreamingSource — const @experimental+```+ComponentDef<WorldStreamingSourceData>+```++## WorldStreamingSourceData — interface @experimental+```+enabled: boolean+loadRadius: number+unloadRadius: number+```+## WorldTransform — const @experimental @deprecated```BuiltinComponentDef<TransformData>@@ -11105,6 +11230,11 @@ PluralSelector(input: { x: number; y: number; }, basis: MoveBasis): Vec3```+## desiredResidency — function @experimental+```+(cells: readonly WorldCell[], sources: readonly ResidencySource[], resident: ReadonlySet<string>): ResidencyDecision+```+## detectAnchor — function @experimental```(node: UINodeData): AnchorPreset | null@@ -11140,6 +11270,11 @@ DiagnosticsPlugin(sceneData: SceneData, refResolver?: RefResolver): SceneAssetRefs```+## distanceToCell — function @experimental+```+(cell: WorldCell, x: number, z: number): number+```+## dragPlugin — const @experimental```DragPlugin@@ -13485,6 +13620,21 @@ VideoPlugin(axis: WorldAxis): Vec3```+## worldResidencyPlugin — const @experimental+```+Plugin+```++## worldResidencyReport — function @experimental+```+(app: App): WorldResidencyReport+```++## worldResidencySystem — const @experimental+```+SystemDef+```+## wrapSceneSystem — function @experimental```(app: App, sceneName: string, system: SystemDef): SystemDefdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 6acc8fb93..c36d071bc 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 · 1601 experimental · 3 deprecated+Symbols: 113 public · 86 beta · 1621 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1956,6 +1956,11 @@ x: numbery: number```+## CellResidency — type @experimental+```+'unloaded' | 'loading' | 'resident' | 'unloading'+```+## Census — interface @experimental```atMs: number@@ -6912,6 +6917,21 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>static prototype: ResMutInstance<any>```+## ResidencyDecision — interface @experimental+```+target: string[]+toLoad: string[]+toUnload: string[]+```++## ResidencySource — interface @experimental+```+loadRadius: number+unloadRadius: number+x: number+z: number+```+## ResolvedAssetGroup — interface @experimental```alwaysInclude: boolean@@ -8099,6 +8119,17 @@ toDeactivate: string[]'unload' | 'sleep'```+## StreamedWorld — const @experimental+```+ComponentDef<StreamedWorldData>+```++## StreamedWorldData — interface @experimental+```+cellSize: number+enabled: boolean+```+## SubEmitterTrigger — enum @beta```Birth = 1@@ -10003,6 +10034,33 @@ static prototype: World0 | 1 | 2```+## WorldCell — interface @experimental+```+entityCount: number+maxX: number+maxZ: number+minX: number+minZ: number+name: string+path: string+rootCount: number+x: number+z: number+```++## WorldManifest — interface @experimental+```+cellSize: number+cells: WorldCell[]+scene: string+version: number+```++## WorldPersistent — const @experimental+```+ComponentDef<{}>+```+## WorldRay — interface @experimental```dir: Vec3@@ -10017,6 +10075,73 @@ right: numbertop: number```+## WorldResidencyReport — interface @experimental+```+assetRefsByCell: Record<string, number>+authoredCellEntityCounts: Record<string, number>+cellCount: number+cellEntityCounts: Record<string, number>+cellRenderCounts: Record<string, number>+desiredCells: string[]+loadCount: number+loadingCells: string[]+persistentEntities: number+residentCells: string[]+sourceCount: number+streamed: boolean+unloadCount: number+unloadingCells: string[]+```++## WorldStreamHost — interface @experimental+```+isLoaded: (name: string) => boolean+loadAdditive: (name: string) => Promise<unknown>+register: (config: { name: string; path: string; }) => void+unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>+```++## WorldStreamer — class @experimental+```+clear: () => void+loadManifest: (manifest: WorldManifest) => void+manifest: WorldManifest | null+residencyOf: (name: string) => CellResidency+status: () => WorldStreamerStatus+update: (sources: readonly ResidencySource[]) => void+static new (host: WorldStreamHost): WorldStreamer+static prototype: WorldStreamer+```++## WorldStreamerStatus — interface @experimental+```+cellCount: number+desiredCells: string[]+loadCount: number+loadingCells: string[]+residentCells: string[]+sourceCount: number+unloadCount: number+unloadingCells: string[]+```++## WorldStreaming — const @experimental+```+ResourceDef<WorldStreamer>+```++## WorldStreamingSource — const @experimental+```+ComponentDef<WorldStreamingSourceData>+```++## WorldStreamingSourceData — interface @experimental+```+enabled: boolean+loadRadius: number+unloadRadius: number+```+## WorldTransform — const @experimental @deprecated```BuiltinComponentDef<TransformData>@@ -10867,6 +10992,11 @@ PluralSelector(input: { x: number; y: number; }, basis: MoveBasis): Vec3```+## desiredResidency — function @experimental+```+(cells: readonly WorldCell[], sources: readonly ResidencySource[], resident: ReadonlySet<string>): ResidencyDecision+```+## detectAnchor — function @experimental```(node: UINodeData): AnchorPreset | null@@ -10902,6 +11032,11 @@ DiagnosticsPlugin(sceneData: SceneData, refResolver?: RefResolver): SceneAssetRefs```+## distanceToCell — function @experimental+```+(cell: WorldCell, x: number, z: number): number+```+## dragPlugin — const @experimental```DragPlugin@@ -13247,6 +13382,21 @@ VideoPlugin(axis: WorldAxis): Vec3```+## worldResidencyPlugin — const @experimental+```+Plugin+```++## worldResidencyReport — function @experimental+```+(app: App): WorldResidencyReport+```++## worldResidencySystem — const @experimental+```+SystemDef+```+## wrapSceneSystem — function @experimental```(app: App, sceneName: string, system: SystemDef): SystemDefdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex f1fcdef5d..ea3dd8f2b 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 · 1623 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1643 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1956,6 +1956,11 @@ x: numbery: number```+## CellResidency — type @experimental+```+'unloaded' | 'loading' | 'resident' | 'unloading'+```+## Census — interface @experimental```atMs: number@@ -7158,6 +7163,21 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>static prototype: ResMutInstance<any>```+## ResidencyDecision — interface @experimental+```+target: string[]+toLoad: string[]+toUnload: string[]+```++## ResidencySource — interface @experimental+```+loadRadius: number+unloadRadius: number+x: number+z: number+```+## ResolvedAssetGroup — interface @experimental```alwaysInclude: boolean@@ -8345,6 +8365,17 @@ toDeactivate: string[]'unload' | 'sleep'```+## StreamedWorld — const @experimental+```+ComponentDef<StreamedWorldData>+```++## StreamedWorldData — interface @experimental+```+cellSize: number+enabled: boolean+```+## SubEmitterTrigger — enum @beta```Birth = 1@@ -10255,6 +10286,33 @@ static prototype: World0 | 1 | 2```+## WorldCell — interface @experimental+```+entityCount: number+maxX: number+maxZ: number+minX: number+minZ: number+name: string+path: string+rootCount: number+x: number+z: number+```++## WorldManifest — interface @experimental+```+cellSize: number+cells: WorldCell[]+scene: string+version: number+```++## WorldPersistent — const @experimental+```+ComponentDef<{}>+```+## WorldRay — interface @experimental```dir: Vec3@@ -10269,6 +10327,73 @@ right: numbertop: number```+## WorldResidencyReport — interface @experimental+```+assetRefsByCell: Record<string, number>+authoredCellEntityCounts: Record<string, number>+cellCount: number+cellEntityCounts: Record<string, number>+cellRenderCounts: Record<string, number>+desiredCells: string[]+loadCount: number+loadingCells: string[]+persistentEntities: number+residentCells: string[]+sourceCount: number+streamed: boolean+unloadCount: number+unloadingCells: string[]+```++## WorldStreamHost — interface @experimental+```+isLoaded: (name: string) => boolean+loadAdditive: (name: string) => Promise<unknown>+register: (config: { name: string; path: string; }) => void+unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>+```++## WorldStreamer — class @experimental+```+clear: () => void+loadManifest: (manifest: WorldManifest) => void+manifest: WorldManifest | null+residencyOf: (name: string) => CellResidency+status: () => WorldStreamerStatus+update: (sources: readonly ResidencySource[]) => void+static new (host: WorldStreamHost): WorldStreamer+static prototype: WorldStreamer+```++## WorldStreamerStatus — interface @experimental+```+cellCount: number+desiredCells: string[]+loadCount: number+loadingCells: string[]+residentCells: string[]+sourceCount: number+unloadCount: number+unloadingCells: string[]+```++## WorldStreaming — const @experimental+```+ResourceDef<WorldStreamer>+```++## WorldStreamingSource — const @experimental+```+ComponentDef<WorldStreamingSourceData>+```++## WorldStreamingSourceData — interface @experimental+```+enabled: boolean+loadRadius: number+unloadRadius: number+```+## WorldTransform — const @experimental @deprecated```BuiltinComponentDef<TransformData>@@ -11124,6 +11249,11 @@ PluralSelector(input: { x: number; y: number; }, basis: MoveBasis): Vec3```+## desiredResidency — function @experimental+```+(cells: readonly WorldCell[], sources: readonly ResidencySource[], resident: ReadonlySet<string>): ResidencyDecision+```+## detectAnchor — function @experimental```(node: UINodeData): AnchorPreset | null@@ -11159,6 +11289,11 @@ DiagnosticsPlugin(sceneData: SceneData, refResolver?: RefResolver): SceneAssetRefs```+## distanceToCell — function @experimental+```+(cell: WorldCell, x: number, z: number): number+```+## dragPlugin — const @experimental```DragPlugin@@ -13504,6 +13639,21 @@ VideoPlugin(axis: WorldAxis): Vec3```+## worldResidencyPlugin — const @experimental+```+Plugin+```++## worldResidencyReport — function @experimental+```+(app: App): WorldResidencyReport+```++## worldResidencySystem — const @experimental+```+SystemDef+```+## wrapSceneSystem — function @experimental```(app: App, sceneName: string, system: SystemDef): SystemDefdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 551e888de..aa321f20d 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 · 1613 experimental · 3 deprecated+Symbols: 113 public · 84 beta · 1633 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -1956,6 +1956,11 @@ x: numbery: number```+## CellResidency — type @experimental+```+'unloaded' | 'loading' | 'resident' | 'unloading'+```+## Census — interface @experimental```atMs: number@@ -6919,6 +6924,21 @@ static new <T>(value: T, setter: (v: T) => void): ResMutInstance<T>static prototype: ResMutInstance<any>```+## ResidencyDecision — interface @experimental+```+target: string[]+toLoad: string[]+toUnload: string[]+```++## ResidencySource — interface @experimental+```+loadRadius: number+unloadRadius: number+x: number+z: number+```+## ResolvedAssetGroup — interface @experimental```alwaysInclude: boolean@@ -8106,6 +8126,17 @@ toDeactivate: string[]'unload' | 'sleep'```+## StreamedWorld — const @experimental+```+ComponentDef<StreamedWorldData>+```++## StreamedWorldData — interface @experimental+```+cellSize: number+enabled: boolean+```+## SubEmitterTrigger — enum @beta```Birth = 1@@ -10031,6 +10062,33 @@ static prototype: World0 | 1 | 2```+## WorldCell — interface @experimental+```+entityCount: number+maxX: number+maxZ: number+minX: number+minZ: number+name: string+path: string+rootCount: number+x: number+z: number+```++## WorldManifest — interface @experimental+```+cellSize: number+cells: WorldCell[]+scene: string+version: number+```++## WorldPersistent — const @experimental+```+ComponentDef<{}>+```+## WorldRay — interface @experimental```dir: Vec3@@ -10045,6 +10103,73 @@ right: numbertop: number```+## WorldResidencyReport — interface @experimental+```+assetRefsByCell: Record<string, number>+authoredCellEntityCounts: Record<string, number>+cellCount: number+cellEntityCounts: Record<string, number>+cellRenderCounts: Record<string, number>+desiredCells: string[]+loadCount: number+loadingCells: string[]+persistentEntities: number+residentCells: string[]+sourceCount: number+streamed: boolean+unloadCount: number+unloadingCells: string[]+```++## WorldStreamHost — interface @experimental+```+isLoaded: (name: string) => boolean+loadAdditive: (name: string) => Promise<unknown>+register: (config: { name: string; path: string; }) => void+unload: (name: string, options?: { keepPersistent?: boolean; }) => Promise<void>+```++## WorldStreamer — class @experimental+```+clear: () => void+loadManifest: (manifest: WorldManifest) => void+manifest: WorldManifest | null+residencyOf: (name: string) => CellResidency+status: () => WorldStreamerStatus+update: (sources: readonly ResidencySource[]) => void+static new (host: WorldStreamHost): WorldStreamer+static prototype: WorldStreamer+```++## WorldStreamerStatus — interface @experimental+```+cellCount: number+desiredCells: string[]+loadCount: number+loadingCells: string[]+residentCells: string[]+sourceCount: number+unloadCount: number+unloadingCells: string[]+```++## WorldStreaming — const @experimental+```+ResourceDef<WorldStreamer>+```++## WorldStreamingSource — const @experimental+```+ComponentDef<WorldStreamingSourceData>+```++## WorldStreamingSourceData — interface @experimental+```+enabled: boolean+loadRadius: number+unloadRadius: number+```+## WorldTransform — const @experimental @deprecated```BuiltinComponentDef<TransformData>@@ -10895,6 +11020,11 @@ PluralSelector(input: { x: number; y: number; }, basis: MoveBasis): Vec3```+## desiredResidency — function @experimental+```+(cells: readonly WorldCell[], sources: readonly ResidencySource[], resident: ReadonlySet<string>): ResidencyDecision+```+## detectAnchor — function @experimental```(node: UINodeData): AnchorPreset | null@@ -10930,6 +11060,11 @@ DiagnosticsPlugin(sceneData: SceneData, refResolver?: RefResolver): SceneAssetRefs```+## distanceToCell — function @experimental+```+(cell: WorldCell, x: number, z: number): number+```+## dragPlugin — const @experimental```DragPlugin@@ -13275,6 +13410,21 @@ MiniGameProfile(axis: WorldAxis): Vec3```+## worldResidencyPlugin — const @experimental+```+Plugin+```++## worldResidencyReport — function @experimental+```+(app: App): WorldResidencyReport+```++## worldResidencySystem — const @experimental+```+SystemDef+```+## wrapSceneSystem — function @experimental```(app: App, sceneName: string, system: SystemDef): SystemDefdiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 2b2ec5f9a..aabdf0fcb 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -222,6 +222,33 @@ export {export { sceneManagerPlugin } from './scene/scenePlugin';+// =============================================================================+// World Residency+// =============================================================================++export {+ StreamedWorld,+ WorldPersistent,+ WorldStreamingSource,+ WorldStreamer,+ WorldStreaming,+ desiredResidency,+ distanceToCell,+ worldResidencyPlugin,+ worldResidencySystem,+ worldResidencyReport,+ type StreamedWorldData,+ type WorldStreamingSourceData,+ type WorldCell,+ type WorldManifest,+ type ResidencySource,+ type ResidencyDecision,+ type CellResidency,+ type WorldStreamHost,+ type WorldStreamerStatus,+ type WorldResidencyReport,+} from './residency/index';+export {SceneOrigins,enableSceneOrigins,diff --git a/sdk/src/residency/WorldStreamer.ts b/sdk/src/residency/WorldStreamer.tsnew file mode 100644index 000000000..d46c614e4--- /dev/null+++ b/sdk/src/residency/WorldStreamer.ts@@ -0,0 +1,198 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file WorldStreamer.ts+ * @brief The one thing that decides which cells of a cooked world exist.+ *+ * @details Residency has a single author. Renderers do not load places, AI does+ * not unload them, and an entity never decides it is far enough away to+ * delete itself — every one of those is a second author, and two authors+ * of existence is how a world ends up holding entities nobody can name.+ *+ * A cell is an additively-loaded scene, so bringing one in and taking it+ * out is the scene lifecycle transaction that already exists: one+ * teardown protocol, idempotent, with the cell's asset receipts owned by+ * the cell's own scope. Unloading is a real destroy — not a visibility+ * flag — which is the whole reason a cell is a scene rather than a list+ * of things to hide.+ */++import { desiredResidency, type ResidencySource, type WorldCell, type WorldManifest } from './cells';+import { defineResource } from '../ecs/resource';+import { log } from '../util/logger';++/** Where a cell is in its lifetime. @experimental */+export type CellResidency = 'unloaded' | 'loading' | 'resident' | 'unloading';++/**+ * The slice of `SceneManager` the streamer drives. `SceneManagerState` satisfies+ * it structurally; a criterion injects a recording stub.+ *+ * @experimental+ */+export interface WorldStreamHost {+ register(config: { name: string; path: string }): void;+ loadAdditive(name: string): Promise<unknown>;+ unload(name: string, options?: { keepPersistent?: boolean }): Promise<void>;+ isLoaded(name: string): boolean;+}++/** What the streamer is doing, for a report. @experimental */+export interface WorldStreamerStatus {+ cellCount: number;+ sourceCount: number;+ /** Cells that should exist right now, load radius unioned with the kept band. */+ desiredCells: string[];+ residentCells: string[];+ loadingCells: string[];+ unloadingCells: string[];+ /** Cells brought in since boot, and cells taken out. Churn is the difference. */+ loadCount: number;+ unloadCount: number;+}++interface CellState {+ cell: WorldCell;+ residency: CellResidency;+ /** What the last reconciliation asked for; the async completions re-read it. */+ desired: boolean;+}++export class WorldStreamer {+ private readonly host_: WorldStreamHost;+ private manifest_: WorldManifest | null = null;+ /** In manifest order, so every list this produces is stable. */+ private readonly cells_ = new Map<string, CellState>();+ private sourceCount_ = 0;+ private loadCount_ = 0;+ private unloadCount_ = 0;++ constructor(host: WorldStreamHost) {+ this.host_ = host;+ }++ /**+ * Adopt a cooked world: its cells become loadable scenes and residency starts+ * answering for them.+ *+ * Registered here rather than 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): void {+ this.manifest_ = manifest;+ this.cells_.clear();+ for (const cell of manifest.cells) {+ this.host_.register({ name: cell.name, path: cell.path });+ this.cells_.set(cell.name, { cell, residency: 'unloaded', desired: false });+ }+ }++ get manifest(): WorldManifest | null {+ return this.manifest_;+ }++ residencyOf(name: string): CellResidency {+ return this.cells_.get(name)?.residency ?? 'unloaded';+ }++ /**+ * Reconcile residency against where the sources are.+ *+ * The sources arrive as a list and are unioned, never folded: a fold gives+ * the last one written the whole answer, and then a second camera deletes+ * the world the first is standing in.+ */+ update(sources: readonly ResidencySource[]): void {+ this.sourceCount_ = sources.length;+ if (this.cells_.size === 0) return;+ const resident = new Set<string>();+ for (const [name, state] of this.cells_) {+ // Loading counts as resident so the decision does not ask twice, and+ // unloading does not, so a source that came back re-issues the load.+ if (state.residency === 'resident' || state.residency === 'loading') resident.add(name);+ }+ const cells: WorldCell[] = [];+ for (const state of this.cells_.values()) cells.push(state.cell);+ const decision = desiredResidency(cells, sources, resident);++ const target = new Set(decision.target);+ for (const [name, state] of this.cells_) state.desired = target.has(name);+ for (const name of decision.toLoad) this.step_(name);+ for (const name of decision.toUnload) this.step_(name);+ }++ /** Everything goes; the cells stay registered. For a world being torn down. */+ clear(): void {+ for (const [name, state] of this.cells_) {+ state.desired = false;+ if (state.residency === 'resident') this.step_(name);+ }+ }++ status(): WorldStreamerStatus {+ const desiredCells: string[] = [];+ const residentCells: string[] = [];+ const loadingCells: string[] = [];+ const unloadingCells: string[] = [];+ for (const [name, state] of this.cells_) {+ if (state.desired) desiredCells.push(name);+ if (state.residency === 'resident') residentCells.push(name);+ else if (state.residency === 'loading') loadingCells.push(name);+ else if (state.residency === 'unloading') unloadingCells.push(name);+ }+ return {+ cellCount: this.cells_.size,+ sourceCount: this.sourceCount_,+ desiredCells, residentCells, loadingCells, unloadingCells,+ loadCount: this.loadCount_, unloadCount: this.unloadCount_,+ };+ }++ /**+ * Move one cell toward what it should be, or leave it alone while an earlier+ * move is still in flight. Re-entered when that move finishes, which is what+ * lets a source that turned around re-issue the opposite one — without this,+ * a cell whose load was overtaken stays resident forever.+ */+ private step_(name: string): void {+ const state = this.cells_.get(name);+ if (!state) return;+ if (state.residency === 'loading' || state.residency === 'unloading') return;+ if (state.desired && state.residency === 'unloaded') this.beginLoad_(name, state);+ else if (!state.desired && state.residency === 'resident') this.beginUnload_(name, state);+ }++ private beginLoad_(name: string, state: CellState): void {+ state.residency = 'loading';+ this.loadCount_++;+ Promise.resolve(this.host_.loadAdditive(name)).then(+ () => { state.residency = 'resident'; this.step_(name); },+ (err) => {+ // A cell that failed to come up owns nothing (the scene load is a+ // transaction), so it goes back to being absent and may be asked+ // for again rather than being stuck half-present.+ state.residency = 'unloaded';+ log.error('residency', `cell "${name}" did not load`, err);+ },+ );+ }++ private beginUnload_(name: string, state: CellState): void {+ state.residency = 'unloading';+ this.unloadCount_++;+ // `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(+ () => { 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);+ },+ );+ }+}++/** The world's residency authority. @experimental */+export const WorldStreaming = defineResource<WorldStreamer>(null!, 'WorldStreaming');diff --git a/sdk/src/residency/cells.ts b/sdk/src/residency/cells.tsnew file mode 100644index 000000000..84d245e3d--- /dev/null+++ b/sdk/src/residency/cells.ts@@ -0,0 +1,113 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cells.ts+ * @brief What a cooked world IS, and the one function that decides which of its+ * cells should exist right now.+ *+ * @details Separated from the streamer on purpose: residency is a decision about+ * geometry and radii, and everything expensive — loading, spawning,+ * releasing — is what happens AFTER it. Pure here means the union rule+ * and the hysteresis band can be held to by a criterion that never+ * builds a world.+ */++/** One cooked cell: an additive scene, and the ground it covers. @experimental */+export interface WorldCell {+ /** Registered scene name — what `SceneManager` is asked to bring up. */+ name: string;+ /** Where its document ships, package-relative. */+ path: string;+ /** Grid coordinate on the XZ plane. */+ x: number;+ z: number;+ /**+ * The ground it covers, world units. The grid square UNIONED with where its+ * content actually is: a cell is asked for by distance to this box, and a+ * prop hanging over the edge is part of the place the box stands for.+ */+ minX: number;+ minZ: number;+ maxX: number;+ maxZ: number;+ /** Authored entities inside, for a report that can be checked against the world. */+ entityCount: number;+ /** Top-level authored entities inside — each one a residency atom. */+ rootCount: number;+}++/** A cooked world: the persistent scene's cells. @experimental */+export interface WorldManifest {+ version: number;+ /** Registered name of the persistent scene these cells belong to. */+ scene: string;+ /** Edge of one grid square, world units. */+ cellSize: number;+ cells: WorldCell[];+}++/** One source's ask, as the streamer samples it. @experimental */+export interface ResidencySource {+ x: number;+ z: number;+ loadRadius: number;+ unloadRadius: number;+}++/** What residency should be, and the two moves that get there. @experimental */+export interface ResidencyDecision {+ /** Every cell that should exist after this tick, in manifest order. */+ target: string[];+ toLoad: string[];+ toUnload: string[];+}++/**+ * Ground-plane distance from a point to a cell's box; zero inside it.+ *+ * To the BOX rather than to the cell's centre, because a centre answers the same+ * for a source standing on a diagonal corner as for one a whole cell away, and+ * that is where holes open in a world laid out on a grid.+ */+export function distanceToCell(cell: WorldCell, x: number, z: number): number {+ const dx = Math.max(cell.minX - x, 0, x - cell.maxX);+ const dz = Math.max(cell.minZ - z, 0, z - cell.maxZ);+ return Math.hypot(dx, dz);+}++/**+ * Which cells should exist, given where the sources are and what is resident.+ *+ * A UNION, never a fold: a fold lets the last source win, and a second camera+ * then deletes the world the first is standing in. The band is the other half —+ * in at `loadRadius`, out past `unloadRadius`, so a boundary is not a treadmill.+ */+export function desiredResidency(+ cells: readonly WorldCell[],+ sources: readonly ResidencySource[],+ resident: ReadonlySet<string>,+): ResidencyDecision {+ const target: string[] = [];+ const toLoad: string[] = [];+ const toUnload: string[] = [];+ for (const cell of cells) {+ let wanted = false;+ let kept = false;+ for (const source of sources) {+ const distance = distanceToCell(cell, source.x, source.z);+ if (distance <= source.loadRadius) { wanted = true; break; }+ // An authored band that is not a band is not one the streamer invents:+ // the wider of the two is the only reading under which a resident cell+ // cannot be dropped by the same distance that just asked for it.+ if (distance <= Math.max(source.loadRadius, source.unloadRadius)) kept = true;+ }+ const isResident = resident.has(cell.name);+ if (wanted || (kept && isResident)) {+ target.push(cell.name);+ if (!isResident) toLoad.push(cell.name);+ } else if (isResident) {+ toUnload.push(cell.name);+ }+ }+ return { target, toLoad, toUnload };+}diff --git a/sdk/src/residency/components.ts b/sdk/src/residency/components.tsnew file mode 100644index 000000000..39f91af5b--- /dev/null+++ b/sdk/src/residency/components.ts@@ -0,0 +1,89 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file components.ts+ * @brief What a project AUTHORS about residency: that a world is streamed, what+ * stays out of the streaming, and who asks for content to be present.+ *+ * @details Three declarations and no policy. The grid is read by the cook, which+ * is what turns one authored world into a persistent scene plus cells;+ * the source is read by the streamer, which is the only thing that+ * decides what exists. Neither is a place to put "load this now" — a+ * game that could say that has an answer the engine can never make+ * asynchronous.+ */++import { defineComponent, defineTag, type ComponentDef } from '../ecs/component';++/** The fields of the `StreamedWorld` component. @experimental */+export interface StreamedWorldData {+ /**+ * Edge of one square cell in world units, on the XZ plane. Y does not+ * partition: a cell is a vertical column, so a tower's floors are one place.+ */+ cellSize: number;+ enabled: boolean;+}++/**+ * Declares the scene carrying it a streamed world, and how the cook cuts it.+ *+ * Its entity is persistent by construction — it is what says the world streams.+ * Without this component a scene loads whole, which is what a small one should.+ *+ * @experimental+ */+export const StreamedWorld: ComponentDef<StreamedWorldData> = defineComponent<StreamedWorldData>(+ 'StreamedWorld',+ { cellSize: 1000, enabled: true },+ {+ fields: {+ cellSize: { min: 1, unit: 'wu', tooltip: 'Edge of one cell on the XZ plane.' },+ },+ },+);++/**+ * Keeps the entity's whole subtree out of the partition — the player, the camera,+ * the sun, the services that outlive any place.+ *+ * NOT scene persistence (`setPersistent`, which is about surviving a scene+ * SWITCH): this decides which cooked scene an entity is written into.+ *+ * @experimental+ */+export const WorldPersistent: ComponentDef<{}> = defineTag('WorldPersistent');++/** The fields of the `WorldStreamingSource` component. @experimental */+export interface WorldStreamingSourceData {+ /** Cells whose nearest edge is within this distance are asked for. */+ loadRadius: number;+ /**+ * A resident cell is only given up once its nearest edge passes this. Must+ * exceed `loadRadius`: the gap between the two is the band that stops a+ * source standing on a boundary from loading and unloading every frame.+ */+ unloadRadius: number;+ enabled: boolean;+}++/**+ * "Keep the world near me present." Add it beside a `Transform`.+ *+ * A source states a need, never a decision: several may exist and their asks are+ * UNIONED, which is what makes split screen, a spectator, a cinematic camera and+ * an editor preview the same kind of thing.+ *+ * @experimental+ */+export const WorldStreamingSource: ComponentDef<WorldStreamingSourceData> =+ defineComponent<WorldStreamingSourceData>(+ 'WorldStreamingSource',+ { loadRadius: 2000, unloadRadius: 3000, enabled: true },+ {+ fields: {+ loadRadius: { min: 0, unit: 'wu', tooltip: 'Cells this close are brought in.' },+ unloadRadius: { min: 0, unit: 'wu', tooltip: 'Resident cells are kept until past this.' },+ },+ },+ );diff --git a/sdk/src/residency/index.ts b/sdk/src/residency/index.tsnew file mode 100644index 000000000..f84ffaa4d--- /dev/null+++ b/sdk/src/residency/index.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file index.ts+ * @brief World residency: what exists, and why it exists right now.+ */++export {+ StreamedWorld, WorldPersistent, WorldStreamingSource,+ type StreamedWorldData, type WorldStreamingSourceData,+} from './components';+export {+ desiredResidency, distanceToCell,+ type WorldCell, type WorldManifest, type ResidencySource, type ResidencyDecision,+} from './cells';+export {+ WorldStreamer, WorldStreaming,+ type CellResidency, type WorldStreamHost, type WorldStreamerStatus,+} from './WorldStreamer';+export { worldResidencyPlugin, worldResidencySystem } from './residencyPlugin';+export { worldResidencyReport, type WorldResidencyReport } from './report';diff --git a/sdk/src/residency/report.ts b/sdk/src/residency/report.tsnew file mode 100644index 000000000..61bf419cd--- /dev/null+++ b/sdk/src/residency/report.ts@@ -0,0 +1,100 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file report.ts+ * @brief What residency did, as numbers something outside the frame can check.+ *+ * @details A picture cannot answer this. "The far cell is not drawn" and "the far+ * cell does not exist" look identical from a camera, and the difference+ * between them is the whole feature — so what is published is the count+ * of things that ARE, per cell, beside what the cook said the cell holds.+ *+ * Read-only, and residency-owned facts only: how many bodies physics+ * still has is physics' answer, and a residency report that reached for+ * it would be the second author this design exists to avoid.+ */++import type { App } from '../app/app';+import { SceneManager } from '../scene/sceneManager';+import { WorldStreaming } from './WorldStreamer';+import { renderableComponents } from '../ecs/component';++/** @experimental */+export interface WorldResidencyReport {+ /** False when this build has no cooked world; every other field is empty. */+ streamed: boolean;+ cellCount: number;+ sourceCount: number;+ desiredCells: string[];+ residentCells: string[];+ loadingCells: string[];+ unloadingCells: string[];+ loadCount: number;+ unloadCount: number;+ /** Live entities each resident cell owns. Absent from the map = not resident. */+ cellEntityCounts: Record<string, number>;+ /** Of those, how many draw anything. */+ cellRenderCounts: Record<string, number>;+ /** Acquisitions each resident cell still owes. Zero after it unloads. */+ assetRefsByCell: Record<string, number>;+ /** What the cook put in each cell — the number a live count is checked against. */+ authoredCellEntityCounts: Record<string, number>;+ /** Live entities the persistent world owns; residency never touches these. */+ persistentEntities: number;+}++const EMPTY: WorldResidencyReport = {+ streamed: false, cellCount: 0, sourceCount: 0,+ desiredCells: [], residentCells: [], loadingCells: [], unloadingCells: [],+ loadCount: 0, unloadCount: 0,+ cellEntityCounts: {}, cellRenderCounts: {}, assetRefsByCell: {},+ authoredCellEntityCounts: {}, persistentEntities: 0,+};++/**+ * Residency as it stands this instant.+ *+ * @experimental+ */+export function worldResidencyReport(app: App): WorldResidencyReport {+ if (!app.hasResource(WorldStreaming) || !app.hasResource(SceneManager)) return { ...EMPTY };+ const streamer = app.getResource(WorldStreaming);+ const manifest = streamer.manifest;+ if (manifest === null) return { ...EMPTY };+ const scenes = app.getResource(SceneManager);+ const status = streamer.status();++ const cellEntityCounts: Record<string, number> = {};+ const cellRenderCounts: Record<string, number> = {};+ const assetRefsByCell: Record<string, number> = {};+ const authoredCellEntityCounts: Record<string, number> = {};+ const drawing = renderableComponents();+ for (const cell of manifest.cells) {+ authoredCellEntityCounts[cell.name] = cell.entityCount;+ const context = scenes.getScene(cell.name);+ // A cell nothing brought in has no row at all, which is the difference+ // between "not here" and "here and empty" that a zero would hide.+ if (context === null) continue;+ let drawn = 0;+ for (const entity of context.entities) {+ if (drawing.some((component) => app.world.has(entity, component))) drawn++;+ }+ cellEntityCounts[cell.name] = context.entities.size;+ cellRenderCounts[cell.name] = drawn;+ assetRefsByCell[cell.name] = scenes.assetScopeFor(cell.name)?.size ?? 0;+ }++ return {+ streamed: true,+ cellCount: status.cellCount,+ sourceCount: status.sourceCount,+ desiredCells: status.desiredCells,+ residentCells: status.residentCells,+ loadingCells: status.loadingCells,+ unloadingCells: status.unloadingCells,+ loadCount: status.loadCount,+ unloadCount: status.unloadCount,+ cellEntityCounts, cellRenderCounts, assetRefsByCell, authoredCellEntityCounts,+ persistentEntities: scenes.getScene(manifest.scene)?.entities.size ?? 0,+ };+}diff --git a/sdk/src/residency/residencyPlugin.ts b/sdk/src/residency/residencyPlugin.tsnew file mode 100644index 000000000..46d9f8193--- /dev/null+++ b/sdk/src/residency/residencyPlugin.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file residencyPlugin.ts+ * @brief Where residency runs: after everything that MOVES a source, and off+ * the sources' composed world positions.+ */++import type { App, Plugin } from '../app/app';+import { SceneManager } from '../scene/sceneManager';+import { WorldStreaming, WorldStreamer } from './WorldStreamer';+import type { ResidencySource } from './cells';+import { WorldStreamingSource, type WorldStreamingSourceData } from './components';+import { defineSystem, Schedule, GetWorld } from '../ecs/system';+import { Res } from '../ecs/resource';+import { Transform, type TransformData } from '../ecs/component';+import { playModeOnly } from '../ecs/env';+import type { World } from '../ecs/world';++/**+ * Sample every enabled source and hand the whole list to the streamer.+ *+ * A list, not a focus: the streamer unions them. Exported because this is the+ * only place a `Transform` becomes a residency ask, which is what the criterion+ * for "a second source cannot delete the first one's world" has to reach.+ */+export const worldResidencySystem = defineSystem(+ [Res(WorldStreaming), GetWorld()],+ (streamer: WorldStreamer, world: World) => {+ if (streamer.manifest === null) return;+ // A source parented to a rig has no position of its own, and the ask is+ // about where it IS. Composition is a no-op unless something invalidated it.+ world.ensureTransformsComposed();+ const sources: ResidencySource[] = [];+ for (const entity of world.getEntitiesWithComponents([WorldStreamingSource, Transform])) {+ const source = world.get(entity, WorldStreamingSource) as WorldStreamingSourceData;+ if (!source.enabled) continue;+ const transform = world.get(entity, Transform) as TransformData;+ const at = transform.worldPosition ?? transform.position;+ sources.push({+ x: at.x,+ z: at.z ?? 0,+ loadRadius: source.loadRadius,+ unloadRadius: source.unloadRadius,+ });+ }+ streamer.update(sources);+ },+ {+ name: 'WorldResidencySystem',+ touches: { reads: ['Transform', 'WorldStreamingSource'] },+ },+);++/**+ * Residency, over the scene manager's primitives.+ *+ * `PostUpdate`: a source's ask is about where it ended this frame, and reading it+ * before movement asks for the world it was in last frame — which at a boundary+ * is the wrong side of it.+ */+export const worldResidencyPlugin: Plugin = {+ name: 'worldResidency',+ profileDomain: 'scene',+ // Residency IS the scene manager's primitives, driven by geometry. Declared+ // so an assembly that wires them in the wrong order fails at build rather+ // than handing the streamer an undefined host.+ dependencies: [SceneManager],+ build(app: App): void {+ app.insertResource(WorldStreaming, new WorldStreamer(app.getResource(SceneManager)));+ app.addSystemToSchedule(Schedule.PostUpdate, worldResidencySystem, { runIf: playModeOnly });+ },+};diff --git a/sdk/src/scene/scenePlugin.ts b/sdk/src/scene/scenePlugin.tsindex 374e8ee44..f41768e44 100644--- a/sdk/src/scene/scenePlugin.ts+++ b/sdk/src/scene/scenePlugin.ts@@ -8,6 +8,7 @@import type { App, Plugin } from '../app/app';import { SceneManager, SceneManagerState } from './sceneManager';import { SceneStreaming, SceneStreamingController } from './sceneStreaming';+import { worldResidencyPlugin } from '../residency/residencyPlugin';import { defineSystem, Schedule, GetWorld } from '../ecs/system';import { Res, ResMut, Time } from '../ecs/resource';import { Transform, type TransformData } from '../ecs/component';@@ -51,6 +52,10 @@ export const sceneManagerPlugin: Plugin = {const state = new SceneManagerState(app);app.insertResource(SceneManager, state);app.insertResource(SceneStreaming, new SceneStreamingController(state));+ // Residency rides with scenes rather than being wired at each of the three+ // app assemblies: a cell IS an additive scene, so an assembly that can load+ // one can stream one, and a fourth place to remember is a place to forget.+ app.addPlugin(worldResidencyPlugin);const initSystem: SystemDef = {_id: Symbol('SceneInitSystem'),diff --git a/sdk/tests/world-residency.test.ts b/sdk/tests/world-residency.test.tsnew file mode 100644index 000000000..ce911b92b--- /dev/null+++ b/sdk/tests/world-residency.test.ts@@ -0,0 +1,195 @@+// 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.+ */+import { describe, it, expect } from 'vitest';+import {+ desiredResidency, distanceToCell, type WorldCell, type ResidencySource,+} from '../src/residency/cells';+import { WorldStreamer, type WorldStreamHost } from '../src/residency/WorldStreamer';+import type { WorldManifest } from '../src/residency/cells';++const flush = async () => { await Promise.resolve(); await Promise.resolve(); await Promise.resolve(); };++/** A cell covering one grid square of `size` at grid coordinate (x, z). */+function cell(x: number, z: number, size = 100): WorldCell {+ return {+ name: `c_${x}_${z}`, path: `world/c_${x}_${z}.json`, x, z,+ minX: x * size, minZ: z * size, maxX: (x + 1) * size, maxZ: (z + 1) * size,+ entityCount: 1, rootCount: 1,+ };+}++const source = (x: number, z: number, load: number, unload: number): ResidencySource =>+ ({ x, z, loadRadius: load, unloadRadius: unload });++describe('desiredResidency', () => {+ it('asks for the cell a source stands in', () => {+ const d = desiredResidency([cell(0, 0)], [source(50, 50, 10, 20)], new Set());+ expect(d.toLoad).toEqual(['c_0_0']);+ expect(d.target).toEqual(['c_0_0']);+ });++ it('measures to the cell box, so a diagonal neighbour is not a hole', () => {+ // The corner of c_1_1 is at (100,100); a source at (95,95) is 0 away from+ // c_0_0 and 7.07 from c_1_1's corner. Measured to the CENTRES it would be+ // 70.7 and 70.7 — the same for a cell it is inside and one it is not.+ const cells = [cell(0, 0), cell(1, 1)];+ expect(distanceToCell(cells[1], 95, 95)).toBeCloseTo(Math.hypot(5, 5), 6);+ expect(desiredResidency(cells, [source(95, 95, 10, 20)], new Set()).target)+ .toEqual(['c_0_0', 'c_1_1']);+ });++ it('keeps a resident cell inside the band, and drops it past unloadRadius', () => {+ const c = cell(0, 0);+ // 15 past the edge: beyond loadRadius 10, inside unloadRadius 20.+ const inside = desiredResidency([c], [source(115, 50, 10, 20)], new Set(['c_0_0']));+ expect(inside.toUnload).toEqual([]);+ expect(inside.target).toEqual(['c_0_0']);+ // A cell that is NOT resident is not brought in by the band — otherwise+ // the band is just a wider load radius.+ expect(desiredResidency([c], [source(115, 50, 10, 20)], new Set()).target).toEqual([]);+ expect(desiredResidency([c], [source(125, 50, 10, 20)], new Set(['c_0_0'])).toUnload)+ .toEqual(['c_0_0']);+ });++ it('unions the sources — a second one does not overwrite the first', () => {+ const cells = [cell(0, 0), cell(5, 0)];+ const far = source(550, 50, 10, 20);+ const near = source(50, 50, 10, 20);+ // Whichever order they arrive in, both cells are wanted. A fold would+ // answer with whichever was written last.+ expect(desiredResidency(cells, [near, far], new Set()).target).toEqual(['c_0_0', 'c_5_0']);+ expect(desiredResidency(cells, [far, near], new Set()).target).toEqual(['c_0_0', 'c_5_0']);+ });++ it('keeps a cell one source still needs when another has left it', () => {+ const cells = [cell(0, 0)];+ const resident = new Set(['c_0_0']);+ const left = source(9999, 9999, 10, 20);+ const stayed = source(50, 50, 10, 20);+ expect(desiredResidency(cells, [left, stayed], resident).toUnload).toEqual([]);+ // Either order: whichever is written last must not be the whole answer.+ expect(desiredResidency(cells, [stayed, left], resident).toUnload).toEqual([]);+ // …and gives it up only when NO source needs it.+ expect(desiredResidency(cells, [left], resident).toUnload).toEqual(['c_0_0']);+ });++ it('partitions on XZ only — a source overhead still holds the ground', () => {+ // Y is not in the sample at all: a cell is a vertical column, so a source+ // on a tower's roof keeps the floors below it resident.+ const d = desiredResidency([cell(0, 0)], [source(50, 50, 10, 20)], new Set());+ expect(d.target).toEqual(['c_0_0']);+ });+});++function recordingHost() {+ const loaded = new Set<string>();+ const calls: string[] = [];+ const pending: Array<() => void> = [];+ let deferred = false;+ const host: WorldStreamHost = {+ register(config) { calls.push(`register:${config.name}`); },+ loadAdditive(name) {+ calls.push(`load:${name}`);+ const settle = (): void => { loaded.add(name); };+ if (!deferred) { settle(); return Promise.resolve({}); }+ return new Promise((resolve) => pending.push(() => { settle(); resolve({}); }));+ },+ unload(name, options) {+ calls.push(`unload:${name}:${options?.keepPersistent}`);+ const settle = (): void => { loaded.delete(name); };+ if (!deferred) { settle(); return Promise.resolve(); }+ return new Promise((resolve) => pending.push(() => { settle(); resolve(); }));+ },+ isLoaded: (name) => loaded.has(name),+ };+ return {+ host, loaded, calls,+ defer(on: boolean) { deferred = on; },+ settle() { const queued = pending.splice(0); for (const run of queued) run(); },+ };+}++const manifest = (...cells: WorldCell[]): WorldManifest =>+ ({ version: 1, scene: 'main', cellSize: 100, cells });++describe('WorldStreamer', () => {+ it('registers every cell as a scene the game itself never names', async () => {+ const { host, calls } = recordingHost();+ new WorldStreamer(host).loadManifest(manifest(cell(0, 0), cell(1, 0)));+ expect(calls).toEqual(['register:c_0_0', 'register:c_1_0']);+ });++ it('brings a cell in, and takes it out taking everything with it', async () => {+ const { host, calls, loaded } = recordingHost();+ const streamer = new WorldStreamer(host);+ streamer.loadManifest(manifest(cell(0, 0)));++ streamer.update([source(50, 50, 10, 20)]);+ await flush();+ expect(loaded.has('c_0_0')).toBe(true);+ expect(streamer.residencyOf('c_0_0')).toBe('resident');++ streamer.update([source(9999, 9999, 10, 20)]);+ await flush();+ expect(loaded.has('c_0_0')).toBe(false);+ // keepPersistent false: a cell's unload takes what the cell brought, or+ // residency leaves behind exactly what it exists to remove.+ expect(calls).toContain('unload:c_0_0:false');+ });++ it('does not churn a cell a source is breathing across the boundary of', async () => {+ const { host } = recordingHost();+ const streamer = new WorldStreamer(host);+ streamer.loadManifest(manifest(cell(0, 0)));+ // Inside the band the whole time: in at 5 past the edge, back out to 15.+ for (let i = 0; i < 20; i++) {+ streamer.update([source(i % 2 === 0 ? 105 : 115, 50, 10, 20)]);+ await flush();+ }+ const status = streamer.status();+ expect(status.loadCount).toBe(1);+ expect(status.unloadCount).toBe(0);+ expect(status.residentCells).toEqual(['c_0_0']);+ });++ it('asks once while a load is in flight, and finishes what the source undid', async () => {+ const { host, calls, settle, defer } = recordingHost();+ defer(true);+ const streamer = new WorldStreamer(host);+ streamer.loadManifest(manifest(cell(0, 0)));++ streamer.update([source(50, 50, 10, 20)]);+ streamer.update([source(50, 50, 10, 20)]);+ expect(calls.filter((c) => c === 'load:c_0_0')).toHaveLength(1);++ // The source leaves while the load is still in flight. The unload cannot+ // be issued yet — but it must not be forgotten, or the cell stays resident+ // with nothing asking for it.+ streamer.update([source(9999, 9999, 10, 20)]);+ expect(calls.filter((c) => c.startsWith('unload:'))).toHaveLength(0);+ settle();+ await flush();+ settle();+ await flush();+ expect(streamer.residencyOf('c_0_0')).toBe('unloaded');+ });++ it('counts a cell that failed to load as absent, so it can be asked for again', async () => {+ const failing: WorldStreamHost = {+ register() {},+ loadAdditive: () => Promise.reject(new Error('no')),+ unload: () => Promise.resolve(),+ isLoaded: () => false,+ };+ const streamer = new WorldStreamer(failing);+ streamer.loadManifest(manifest(cell(0, 0)));+ streamer.update([source(50, 50, 10, 20)]);+ await flush();+ expect(streamer.residencyOf('c_0_0')).toBe('unloaded');+ });+});