Skip to content

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.

feat(play): the editor plays a streamed world the way the package ships it

esengine26ddd3fe6e7e
diff --git a/desktop b/desktop
index 88ad087c2..199adce1b 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 88ad087c2844c7c3ca687e8865338cd7011195fb
+Subproject commit 199adce1bfa0323d8757134ea7e27bc9aee48a98
diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.json
index 49c9156c7..c56ac19dd 100644
--- a/docs/astro/src/data/apiStability.generated.json
+++ b/docs/astro/src/data/apiStability.generated.json
@@ -3,10 +3,10 @@
"counts": {
"public": 113,
"beta": 91,
- "experimental": 1822,
+ "experimental": 1824,
"deprecated": 3
},
- "total": 2026,
+ "total": 2028,
"subsystems": [
{
"id": "ecs",
diff --git a/pipeline/src/world/cookWorld.ts b/pipeline/src/world/cookWorld.ts
index 0a6afb857..643ff25c5 100644
--- a/pipeline/src/world/cookWorld.ts
+++ b/pipeline/src/world/cookWorld.ts
@@ -16,8 +16,10 @@
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import path from 'node:path';
-import type { SceneData, PrefabRoot } from 'esengine';
-import { cutWorld, worldManifestPath, registryEntityFields, WORLD_DIR } from 'esengine/node';
+import type { SceneData } from 'esengine';
+import {
+ cutWorld, resolvePrefabRoots, worldManifestPath, registryEntityFields, WORLD_DIR,
+} from 'esengine/node';
import { readCachedAssetIndex, scanAssetDatabase, type AssetIndex } from '../assets/assetDb';
/** One streamed scene, as `game.config.json` names it. */
@@ -32,33 +34,19 @@ export interface CookWorldsResult {
}
/**
- * Read the prefab an instance names, for the position an instance that does not
- * override it inherits. From the PROJECT rather than the payload: a prefab is
- * content-addressed by then, and where its root sits is the same either way.
+ * Read the prefab document an instance names. From the PROJECT rather than the
+ * payload: a prefab is content-addressed by then, and where its root sits is the
+ * same either way. What the document MEANS is `prefabRootOf`, shared with the
+ * realm that reads the same prefab over http.
*/
-function prefabResolver(root: string, index: AssetIndex): (ref: string) => Promise<PrefabRoot | null> {
+function prefabReader(root: string, index: AssetIndex): (ref: string) => Promise<unknown | null> {
const byUuid = new Map<string, string>();
for (const entry of index.entries) byUuid.set(entry.uuid, entry.path);
- return async (ref: string): Promise<PrefabRoot | null> => {
+ return async (ref: string): Promise<unknown | null> => {
const uuid = ref.startsWith('@uuid:') ? ref.slice('@uuid:'.length) : null;
const relative = uuid !== null ? byUuid.get(uuid) : ref;
if (!relative) return null;
- try {
- const prefab = JSON.parse(await readFile(path.join(root, relative), 'utf8')) as {
- rootEntityId?: string;
- entities?: Array<{
- prefabEntityId?: string;
- components?: Array<{ type: string; data: Record<string, unknown> }>;
- }>;
- };
- const rootId = prefab.rootEntityId ?? '0';
- const rootEntity = (prefab.entities ?? []).find((e) => e.prefabEntityId === rootId);
- const transform = rootEntity?.components?.find((c) => c.type === 'Transform');
- const at = (transform?.data.position ?? {}) as Partial<{ x: number; y: number; z: number }>;
- return { rootId, position: { x: at.x ?? 0, y: at.y ?? 0, z: at.z ?? 0 } };
- } catch {
- return null;
- }
+ return JSON.parse(await readFile(path.join(root, relative), 'utf8')) as unknown;
};
}
@@ -95,7 +83,7 @@ export async function cookWorlds(
const worlds: CookedWorld[] = [];
const warnings: string[] = [];
let index: AssetIndex | null = null;
- let resolve: ((ref: string) => Promise<PrefabRoot | null>) | null = null;
+ let read: ((ref: string) => Promise<unknown | null>) | null = null;
for (const scene of scenes) {
const staged = path.join(payloadDir, scene.path);
@@ -109,24 +97,15 @@ export async function cookWorlds(
// reference check costs a whole engine to load.
if (!text.includes('"StreamedWorld"')) continue;
- if (resolve === null) {
+ if (read === null) {
index = await readCachedAssetIndex(root)
?? (await scanAssetDatabase(root, { write: false, adopt: false })).index;
- resolve = prefabResolver(root, index);
+ read = prefabReader(root, index);
}
- // Prefab roots are read up front: partitioning is synchronous so a cook
- // that had to await inside it could not stay a pure function.
const document = JSON.parse(text) as SceneData;
- const roots = new Map<string, PrefabRoot | null>();
- for (const entry of (document.entities ?? []) as Array<{ prefab?: string }>) {
- if (typeof entry.prefab === 'string' && !roots.has(entry.prefab)) {
- roots.set(entry.prefab, await resolve(entry.prefab));
- }
- }
-
const cut = cutWorld(document, scene.name, {
entityFieldsOf: registryEntityFields(),
- resolvePrefab: (ref) => roots.get(ref) ?? null,
+ resolvePrefab: await resolvePrefabRoots(document, read),
});
if (cut === null) continue;
if (cut.errors.length > 0) {
diff --git a/pipeline/tests/cook-world-prefabs.test.ts b/pipeline/tests/cook-world-prefabs.test.ts
new file mode 100644
index 000000000..7e9eaf92c
--- /dev/null
+++ b/pipeline/tests/cook-world-prefabs.test.ts
@@ -0,0 +1,81 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A prefab instance is placed by the root the cook read off disk.
+ *
+ * An instance that overrides nothing carries no position of its own, so where it
+ * stands is a fact only its asset holds. Reading it is the one half of the cut a
+ * package does not share with an editor Play session — the realm fetches the same
+ * prefab over http — so the reading itself is pinned here, against real files.
+ */
+import { describe, it, expect, afterEach } from 'vitest';
+import { mkdtemp, mkdir, writeFile, rm, readFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { cookWorlds } from '../src/world/cookWorld';
+import type { WorldManifest } from 'esengine';
+
+const SIZE = 1000;
+const UUID = 'aaaabbbb-cccc-dddd-eeee-ffff00001111';
+
+let project = '';
+afterEach(async () => {
+ if (project) await rm(project, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });
+ project = '';
+});
+
+/** A project holding one prefab whose root sits at `at`, and a scene instancing it. */
+async function projectWith(at: [number, number, number], override: number[] | null): Promise<string> {
+ project = await mkdtemp(path.join(tmpdir(), 'cook-world-'));
+ await mkdir(path.join(project, 'assets', 'scenes'), { recursive: true });
+ await mkdir(path.join(project, 'assets', 'prefabs'), { recursive: true });
+ await writeFile(path.join(project, 'assets', 'prefabs', 'Hut.esprefab'), JSON.stringify({
+ rootEntityId: 'r',
+ entities: [{
+ prefabEntityId: 'r', name: 'Hut',
+ components: [{ type: 'Transform', data: { position: { x: at[0], y: at[1], z: at[2] } } }],
+ }],
+ }));
+ await writeFile(path.join(project, 'assets', 'prefabs', 'Hut.esprefab.meta'),
+ JSON.stringify({ uuid: UUID, type: 'prefab' }));
+ await writeFile(path.join(project, 'assets', 'scenes', 'main.esscene'), JSON.stringify({
+ version: 4, name: 'main',
+ entities: [
+ { id: 0, name: 'World', parent: null, children: [], visible: true,
+ components: [{ type: 'StreamedWorld', data: { cellSize: SIZE } }] },
+ {
+ id: 1, name: 'Hut', parent: null, prefab: `@uuid:${UUID}`,
+ overrides: override === null ? [] : [{
+ type: 'property', prefabEntityId: 'r',
+ componentType: 'Transform', propertyName: 'position',
+ value: { x: override[0], y: override[1], z: override[2] },
+ }],
+ },
+ ],
+ }));
+ await writeFile(path.join(project, 'project.esproject'), JSON.stringify({
+ formatVersion: '1', name: 'Cooked', defaultScene: 'assets/scenes/main.esscene',
+ }));
+ return project;
+}
+
+/** Cook the project in place — the payload IS the project here, which is all the cut reads. */
+async function cellsOf(root: string): Promise<string[]> {
+ const result = await cookWorlds(root, root, [{ name: 'main', path: 'assets/scenes/main.esscene' }]);
+ expect(result.worlds).toHaveLength(1);
+ const manifest = JSON.parse(
+ await readFile(path.join(root, result.worlds[0].manifest), 'utf8'),
+ ) as WorldManifest;
+ return manifest.cells.map((c) => c.name);
+}
+
+describe('cooking a world that instances a prefab', () => {
+ it('puts the instance in the cell its asset root falls in', async () => {
+ expect(await cellsOf(await projectWith([1500, 0, 500], null))).toEqual(['main.cell_1_0']);
+ });
+
+ it('and in the cell an override moves it to, not the asset\'s', async () => {
+ expect(await cellsOf(await projectWith([1500, 0, 500], [500, 0, 500])))
+ .toEqual(['main.cell_0_0']);
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 69805f197..76cf3a63f 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 · 1661 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1663 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -7213,6 +7213,7 @@ app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
catalog: Catalog | undefined
+cellDocuments: ReadonlyMap<string, SceneData> | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
module: ESEngineModule | null
@@ -12597,6 +12598,11 @@ PerceptionPlugin
PostProcessPlugin
```
+## prefabRootOf — function @experimental
+```
+(document: unknown): PrefabRoot | null
+```
+
## prefabsPlugin — const @experimental
```
PrefabsPlugin
@@ -12897,6 +12903,11 @@ ReplicationPlugin
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
```
+## resolvePrefabRoots — function @experimental
+```
+(scene: SceneData, read: (ref: string) => Promise<unknown | null>): Promise<(ref: string) => PrefabRoot | null>
+```
+
## resolveRelativePath — function @experimental
```
(basePath: string, relativePath: string): string
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 7810d083b..c35e28b24 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 · 1680 experimental · 3 deprecated
+Symbols: 113 public · 89 beta · 1682 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -7406,6 +7406,7 @@ app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
catalog: Catalog | undefined
+cellDocuments: ReadonlyMap<string, SceneData> | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
module: ESEngineModule | null
@@ -12840,6 +12841,11 @@ PerceptionPlugin
PostProcessPlugin
```
+## prefabRootOf — function @experimental
+```
+(document: unknown): PrefabRoot | null
+```
+
## prefabsPlugin — const @experimental
```
PrefabsPlugin
@@ -13140,6 +13146,11 @@ ReplicationPlugin
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
```
+## resolvePrefabRoots — function @experimental
+```
+(scene: SceneData, read: (ref: string) => Promise<unknown | null>): Promise<(ref: string) => PrefabRoot | null>
+```
+
## resolveRelativePath — function @experimental
```
(basePath: string, relativePath: string): string
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index a848c1f6a..0f94f7719 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 · 1660 experimental · 3 deprecated
+Symbols: 113 public · 86 beta · 1662 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -7208,6 +7208,7 @@ app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
catalog: Catalog | undefined
+cellDocuments: ReadonlyMap<string, SceneData> | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
module: ESEngineModule | null
@@ -12602,6 +12603,11 @@ PerceptionPlugin
PostProcessPlugin
```
+## prefabRootOf — function @experimental
+```
+(document: unknown): PrefabRoot | null
+```
+
## prefabsPlugin — const @experimental
```
PrefabsPlugin
@@ -12902,6 +12908,11 @@ ReplicationPlugin
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
```
+## resolvePrefabRoots — function @experimental
+```
+(scene: SceneData, read: (ref: string) => Promise<unknown | null>): Promise<(ref: string) => PrefabRoot | null>
+```
+
## resolveRelativePath — function @experimental
```
(basePath: string, relativePath: string): string
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index ac5a3edbd..0f5fe65c9 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 · 1682 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1684 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -7454,6 +7454,7 @@ app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
catalog: Catalog | undefined
+cellDocuments: ReadonlyMap<string, SceneData> | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
module: ESEngineModule | null
@@ -12859,6 +12860,11 @@ PerceptionPlugin
PostProcessPlugin
```
+## prefabRootOf — function @experimental
+```
+(document: unknown): PrefabRoot | null
+```
+
## prefabsPlugin — const @experimental
```
PrefabsPlugin
@@ -13159,6 +13165,11 @@ ReplicationPlugin
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
```
+## resolvePrefabRoots — function @experimental
+```
+(scene: SceneData, read: (ref: string) => Promise<unknown | null>): Promise<(ref: string) => PrefabRoot | null>
+```
+
## resolveRelativePath — function @experimental
```
(basePath: string, relativePath: string): string
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 8041d0a6f..b01f89f71 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 · 1672 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1674 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -7215,6 +7215,7 @@ app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
catalog: Catalog | undefined
+cellDocuments: ReadonlyMap<string, SceneData> | undefined
firstScene: string
manifest: AddressableManifest | ManifestModel | null | undefined
module: ESEngineModule | null
@@ -12625,6 +12626,11 @@ PerceptionPlugin
PostProcessPlugin
```
+## prefabRootOf — function @experimental
+```
+(document: unknown): PrefabRoot | null
+```
+
## prefabsPlugin — const @experimental
```
PrefabsPlugin
@@ -12925,6 +12931,11 @@ ReplicationPlugin
(def: AnimatorControllerDef, overrides: ReadonlyMap<string, number | boolean>): Record<string, number | boolean>
```
+## resolvePrefabRoots — function @experimental
+```
+(scene: SceneData, read: (ref: string) => Promise<unknown | null>): Promise<(ref: string) => PrefabRoot | null>
+```
+
## resolveRelativePath — function @experimental
```
(basePath: string, relativePath: string): string
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index ff222dfb4..1806fecad 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -256,6 +256,8 @@ export {
stableEntityId,
partitionWorld,
cutWorld,
+ prefabRootOf,
+ resolvePrefabRoots,
cellDocumentPath,
worldManifestPath,
registryEntityFields,
diff --git a/sdk/src/residency/cutWorld.ts b/sdk/src/residency/cutWorld.ts
index 67e132503..2830c9982 100644
--- a/sdk/src/residency/cutWorld.ts
+++ b/sdk/src/residency/cutWorld.ts
@@ -13,7 +13,7 @@
* impossible, because there is nowhere left to disagree.
*/
-import { partitionWorld, type PartitionOptions } from './partitionWorld';
+import { partitionWorld, type PartitionOptions, type PrefabRoot } from './partitionWorld';
import type { WorldCell, WorldManifest } from './cells';
import type { SceneData } from '../scene/scene';
@@ -92,3 +92,42 @@ export function cutWorld(
warnings: partition.warnings,
};
}
+
+/** The shape of a `.esprefab` this reads — only the root's placement. */
+interface PrefabDocument {
+ rootEntityId?: string;
+ entities?: Array<{
+ prefabEntityId?: string;
+ components?: Array<{ type: string; data: Record<string, unknown> }>;
+ }>;
+}
+
+/** Where a prefab asset's root sits, from its document. Null if it has no root. */
+export function prefabRootOf(document: unknown): PrefabRoot | null {
+ const prefab = document as PrefabDocument | null;
+ if (prefab === null || typeof prefab !== 'object') return null;
+ const rootId = prefab.rootEntityId ?? '0';
+ const root = (prefab.entities ?? []).find((e) => e.prefabEntityId === rootId);
+ if (!root) return null;
+ const at = (root.components?.find((c) => c.type === 'Transform')?.data.position ?? {}) as
+ Partial<{ x: number; y: number; z: number }>;
+ return { rootId, position: { x: at.x ?? 0, y: at.y ?? 0, z: at.z ?? 0 } };
+}
+
+/**
+ * Read every prefab `scene` instances, and answer where each one's root sits.
+ *
+ * A synchronous lookup, resolved up front, because the partition is pure and one
+ * that could await inside it would not be. Both hosts come through here; they
+ * differ only in how the bytes are fetched.
+ */
+export async function resolvePrefabRoots(
+ scene: SceneData, read: (ref: string) => Promise<unknown | null>,
+): Promise<(ref: string) => PrefabRoot | null> {
+ const roots = new Map<string, PrefabRoot | null>();
+ for (const entry of (scene.entities ?? []) as unknown as Array<{ prefab?: string }>) {
+ if (typeof entry.prefab !== 'string' || roots.has(entry.prefab)) continue;
+ roots.set(entry.prefab, prefabRootOf(await read(entry.prefab).catch(() => null)));
+ }
+ return (ref) => roots.get(ref) ?? null;
+}
diff --git a/sdk/src/residency/index.ts b/sdk/src/residency/index.ts
index d96bc3214..f5848f6b3 100644
--- a/sdk/src/residency/index.ts
+++ b/sdk/src/residency/index.ts
@@ -25,6 +25,7 @@ export {
type PartitionOptions, type PartitionedCell, type PrefabRoot, type WorldPartition,
} from './partitionWorld';
export {
- cutWorld, cellDocumentPath, worldManifestPath, WORLD_DIR, type CutWorld,
+ cutWorld, cellDocumentPath, worldManifestPath, WORLD_DIR,
+ prefabRootOf, resolvePrefabRoots, type CutWorld,
} from './cutWorld';
export { registryEntityFields } from './componentRefs';
diff --git a/sdk/src/runtime/playRealmRuntime.ts b/sdk/src/runtime/playRealmRuntime.ts
index 30d2bc10c..527420ecc 100644
--- a/sdk/src/runtime/playRealmRuntime.ts
+++ b/sdk/src/runtime/playRealmRuntime.ts
@@ -20,6 +20,8 @@ import type { ESEngineModule } from '../wasm';
import { Audio } from '../audio/Audio';
import { VideoPlayer } from '../video/VideoAPI';
import { initRuntime } from './runtimeLoader';
+import { cutWorld, resolvePrefabRoots, type CutWorld } from '../residency/cutWorld';
+import { registryEntityFields } from '../residency/componentRefs';
import type { ThemeOverrides } from '../ui';
import type { RuntimeAssetSource } from './runtimeAssets';
import { HttpBackend } from '../asset/Backend';
@@ -176,6 +178,39 @@ function createPlayRealmSource(
};
}
+/**
+ * Cut the snapshot the way a cook would, or answer null when it is not a world.
+ *
+ * Here rather than on disk because the scene an author is playing may never
+ * have been saved. Same `cutWorld`, so the cells and the manifest are what the
+ * package would carry — only the documents stay in memory.
+ */
+export async function cutPlayWorld(
+ scene: SceneData, sceneName: string, resolveRef: (ref: string) => string,
+): Promise<CutWorld | null> {
+ const resolvePrefab = await resolvePrefabRoots(scene, async (ref) => {
+ const response = await fetch(resolveRef(ref));
+ return response.ok ? await response.json() as unknown : null;
+ });
+ const cut = cutWorld(scene, sceneName, {
+ // The realm's registry, which by now holds the project's own components
+ // as well as the engine's — so a cross-cell reference a cook could not
+ // see is found HERE, before it is packaged.
+ entityFieldsOf: registryEntityFields(),
+ resolvePrefab,
+ });
+ if (cut !== null && cut.errors.length > 0) {
+ // Refused, not played whole: a world the editor agreed to run streamed is
+ // one the author will ship, and this same cut fails the build.
+ throw new Error(
+ `scene "${sceneName}" cannot be cut into cells, so it cannot be played `
+ + `as the streamed world it declares:\n`
+ + cut.errors.map((e) => ` ${e}`).join('\n'),
+ );
+ }
+ return cut;
+}
+
/**
* Boot the shipping runtime against a single in-memory scene snapshot. The host
* page has already created `app` (createWebApp) + bound a GL context; here we
@@ -186,6 +221,10 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Prom
const source = createPlayRealmSource(assetManifest, assetBaseUrl, config.assetPathMap, config.manifest);
applyAssetRefResolvers(app, (ref) => resolvePlayAssetRef(ref, assetManifest, assetBaseUrl, config.assetPathMap));
const entryName = config.entrySceneName ?? '__play';
+ const cut = await cutPlayWorld(
+ sceneData, entryName,
+ (ref) => resolvePlayAssetRef(ref, assetManifest, assetBaseUrl, config.assetPathMap),
+ );
await initRuntime({
app,
module,
@@ -195,9 +234,12 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Prom
persistUpdateKey: config.persistUpdateKey,
catalog: config.catalogData ? Catalog.fromJson(config.catalogData) : undefined,
scenes: [
- { name: entryName, data: sceneData },
+ // The persistent world when there is one: what a package boots is the
+ // part residency never removes, and the places arrive as it asks.
+ { name: entryName, data: cut?.persistent ?? sceneData },
...(config.extraScenes ?? []).filter((s) => s.name !== entryName),
],
+ ...(cut ? { worlds: [cut.manifest], cellDocuments: cut.documents } : {}),
firstScene: entryName,
aspectRatio: canvas.width / canvas.height,
physicsEnabled: config.physicsEnabled,
diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.ts
index 1f2ae8381..d667b9944 100644
--- a/sdk/src/runtime/runtimeLoader.ts
+++ b/sdk/src/runtime/runtimeLoader.ts
@@ -746,6 +746,13 @@ export interface RuntimeInitConfig {
* residency brings in, so they are deliberately not in `scenes`.
*/
worlds?: WorldManifest[];
+ /**
+ * Cell name → its document, for a host that already holds them: an editor
+ * Play session cuts the unsaved scene in memory and has nowhere to fetch a
+ * cell FROM. A package leaves this out and every cell arrives by its path;
+ * the manifest is the same either way, cell paths included.
+ */
+ cellDocuments?: ReadonlyMap<string, SceneData>;
firstScene: string;
spineModule?: SpineWasmModule | null;
spineManager?: SpineManager | null;
@@ -867,11 +874,15 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {
// the persistent rows the cook said it names — freshly each time, because
// the entities behind those rows are only the ones alive right now.
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) => {
// 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.
- const config = createRuntimeSceneConfig(cell.name, undefined, sceneOpts, cell.path);
+ const config = createRuntimeSceneConfig(
+ cell.name, documents?.get(cell.name), sceneOpts, cell.path,
+ );
config.externalEntities = () => persistentEntityRows(app, world);
config.onPhase = (phase, ms) => streamer.recordPhase(cell.name, phase, ms);
return config;
diff --git a/sdk/tests/play-world-parity.test.ts b/sdk/tests/play-world-parity.test.ts
new file mode 100644
index 000000000..3d531ca97
--- /dev/null
+++ b/sdk/tests/play-world-parity.test.ts
@@ -0,0 +1,174 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Play cuts the world it was handed, and cuts it the way a package will.
+ *
+ * The deliberate gap this closes was that a package streamed its world and the
+ * editor played the whole thing — so an author could only find out what the
+ * world does after building it. What is pinned here is that Play now boots the
+ * PERSISTENT half, holds the same manifest a cook would write, and refuses the
+ * same worlds a build refuses.
+ */
+import { describe, it, expect, vi, afterEach } from 'vitest';
+
+// The runtime itself is not under test here; what it was HANDED is.
+const initRuntime = vi.hoisted(() => vi.fn());
+vi.mock('../src/runtime/runtimeLoader', () => ({ initRuntime }));
+vi.mock('../src/runtime/packagedRuntime', () => ({ applyAssetRefResolvers: vi.fn() }));
+
+import { cutPlayWorld, initPlayRealmRuntime } from '../src/runtime/playRealmRuntime';
+import type { RuntimeInitConfig } from '../src/runtime/runtimeLoader';
+import { cellDocumentPath } from '../src/residency/cutWorld';
+import { defineComponent } from '../src/ecs/component';
+import type { Entity } from '../src/types';
+import type { SceneData } from '../src/scene/scene';
+
+// A project's own component, which is the case only Play can catch: a cook loads
+// the engine's registry and never sees this one, so the cross-cell reference it
+// holds is refused HERE and nowhere earlier.
+defineComponent<{ watches: Entity }>('Watchtower', { watches: 0 as Entity },
+ { entityFields: ['watches'] });
+
+const SIZE = 1000;
+const PREFAB = '@uuid:aaaabbbb-cccc-dddd-eeee-ffff00001111';
+
+type Component = { type: string; data: Record<string, unknown> };
+
+function entity(
+ id: number, name: string, at: [number, number, number] | null,
+ extra: { parent?: number | null; components?: Component[] } = {},
+): Record<string, unknown> {
+ const components: Component[] = [...(extra.components ?? [])];
+ if (at !== null) {
+ components.unshift({ type: 'Transform', data: { position: { x: at[0], y: at[1], z: at[2] } } });
+ }
+ return { id, name, parent: extra.parent ?? null, children: [], visible: true, components };
+}
+
+const declaration: Component = { type: 'StreamedWorld', data: { cellSize: SIZE } };
+
+function scene(...entities: Array<Record<string, unknown>>): SceneData {
+ return { version: 4, name: 'main', entities } as unknown as SceneData;
+}
+
+/** Nothing in this realm is fetchable unless a case says otherwise. */
+const refuseFetch = (): never => { throw new Error('nothing should have been fetched'); };
+const resolveRef = (ref: string): string => `estella://project/${ref}`;
+
+const names = (document: SceneData): string[] =>
+ (document.entities as unknown as Array<{ name: string }>).map((e) => e.name);
+
+afterEach(() => vi.unstubAllGlobals());
+
+describe('the snapshot Play boots', () => {
+ it('is left whole when the scene never declared itself a world', async () => {
+ vi.stubGlobal('fetch', refuseFetch);
+ expect(await cutPlayWorld(scene(entity(0, 'Ground', [0, 0, 0])), '__play', resolveRef))
+ .toBeNull();
+ });
+
+ it('is the persistent half, with the places in cells that carry their ship paths', async () => {
+ vi.stubGlobal('fetch', refuseFetch);
+ const cut = (await cutPlayWorld(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ entity(1, 'Player', [10, 0, 10], { components: [{ type: 'WorldPersistent', data: {} }] }),
+ entity(2, 'RockA', [500, 0, 500]),
+ entity(3, 'RockB', [1500, 0, 500]),
+ ), 'main', resolveRef))!;
+
+ expect(names(cut.persistent).sort()).toEqual(['Player', 'World']);
+ expect(cut.manifest.cellSize).toBe(SIZE);
+ expect(cut.manifest.cells.map((c) => c.name)).toEqual(['main.cell_0_0', 'main.cell_1_0']);
+ // The path a package would fetch. Play never does, but a manifest that
+ // differed in a field one host ignores is still a different manifest.
+ for (const cell of cut.manifest.cells) {
+ expect(cell.path).toBe(cellDocumentPath(cell.name));
+ }
+ // And every cell the manifest names is actually deliverable from memory.
+ expect([...cut.documents.keys()].sort()).toEqual(cut.manifest.cells.map((c) => c.name).sort());
+ expect(names(cut.documents.get('main.cell_0_0')!)).toEqual(['RockA']);
+ expect(names(cut.documents.get('main.cell_1_0')!)).toEqual(['RockB']);
+ });
+
+ it('places a prefab instance by the root it reads over the realm origin', async () => {
+ const fetched: string[] = [];
+ vi.stubGlobal('fetch', (url: string) => {
+ fetched.push(url);
+ return Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve({
+ rootEntityId: 'r',
+ entities: [{
+ prefabEntityId: 'r',
+ components: [{ type: 'Transform', data: { position: { x: 1500, y: 0, z: 500 } } }],
+ }],
+ }),
+ });
+ });
+ const cut = (await cutPlayWorld(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ { id: 1, name: 'Hut', parent: null, prefab: PREFAB, overrides: [] },
+ ), 'main', resolveRef))!;
+
+ expect(fetched).toEqual([`estella://project/${PREFAB}`]);
+ expect(cut.errors).toEqual([]);
+ expect(cut.manifest.cells.map((c) => c.name)).toEqual(['main.cell_1_0']);
+ });
+
+ it('refuses a world a build would refuse, rather than playing it whole', async () => {
+ vi.stubGlobal('fetch', refuseFetch);
+ await expect(cutPlayWorld(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ entity(1, 'Watcher', [500, 0, 500], {
+ components: [{ type: 'Watchtower', data: { watches: 2 } }],
+ }),
+ entity(2, 'Quarry', [1500, 0, 500]),
+ ), 'main', resolveRef)).rejects.toThrow(/cannot be cut into cells/);
+ });
+});
+
+describe('what Play hands the shipping runtime', () => {
+ /** The realm's boot, reduced to the one argument this is about. */
+ async function boot(data: SceneData): Promise<RuntimeInitConfig> {
+ initRuntime.mockClear();
+ vi.stubGlobal('fetch', refuseFetch);
+ await initPlayRealmRuntime({
+ app: { enableStats: vi.fn(), run: vi.fn() } as never,
+ module: {} as never,
+ canvas: { width: 800, height: 600 } as never,
+ sceneData: data,
+ entrySceneName: 'main',
+ assetManifest: {},
+ });
+ return initRuntime.mock.calls[0][0] as RuntimeInitConfig;
+ }
+
+ it('is the world, its cells and their documents — not the scene played whole', async () => {
+ const config = await boot(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ entity(1, 'Player', [10, 0, 10], { components: [{ type: 'WorldPersistent', data: {} }] }),
+ entity(2, 'RockA', [500, 0, 500]),
+ entity(3, 'RockB', [1500, 0, 500]),
+ ));
+
+ // The entry is the persistent half. Handing over the whole document is
+ // exactly the gap this closes, and it would leave everything else here
+ // true — the streamer would simply publish a second copy of the world.
+ expect(names(config.scenes[0].data!).sort()).toEqual(['Player', 'World']);
+ expect(config.worlds).toHaveLength(1);
+ expect(config.worlds![0].cells.map((c) => c.name))
+ .toEqual(['main.cell_0_0', 'main.cell_1_0']);
+ // Registered by path and delivered from memory: without the documents the
+ // realm would reach for `world/main.cell_0_0.json`, which only a package has.
+ for (const cell of config.worlds![0].cells) {
+ expect(config.cellDocuments?.get(cell.name)).toBeDefined();
+ }
+ });
+
+ it('carries no world at all for a scene that is not one', async () => {
+ const config = await boot(scene(entity(0, 'Ground', [0, 0, 0])));
+ expect(config.worlds).toBeUndefined();
+ expect(config.cellDocuments).toBeUndefined();
+ expect(names(config.scenes[0].data!)).toEqual(['Ground']);
+ });
+});
diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjs
index 0ed2797e7..6f04df6db 100644
--- a/tools/goldenProjects.mjs
+++ b/tools/goldenProjects.mjs
@@ -255,10 +255,9 @@ export const GOLDEN = [
// Walking is what makes a place exist here, so the frame after 60 frames of
// it differs by more than a character moving — a cell came in.
interact: { keys: ['KeyD'], frames: 60 },
- // Cutting the world is a COOK step, so the editor plays the authored scene
- // whole and the two frames hold different amounts of world on purpose. What
- // the package does is held to by tools/verify-world-residency.mjs.
- parityGap: 'the package streams its world and the editor plays it whole; the frames differ by design',
+ // Comparable now that the editor cuts this world the way the package does —
+ // but not the claim: the frame moved only 0.0073 → 0.0008 when Play stopped
+ // loading it whole. verify-world-residency.mjs asks both for their residency.
},
{
id: 'ui-controls',
diff --git a/tools/verify-world-residency.mjs b/tools/verify-world-residency.mjs
index 515cbe909..6874b305a 100644
--- a/tools/verify-world-residency.mjs
+++ b/tools/verify-world-residency.mjs
@@ -26,6 +26,7 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const WORK = path.join(ROOT, '.golden', 'world-residency');
const PROJECT = path.join(ROOT, 'examples', 'world-streaming-3d');
const LAUNCHER = path.join(ROOT, 'tools', 'launchers', 'residency-run.mjs');
+const DESKTOP = path.join(ROOT, 'desktop');
const A = 'main.cell_0_0';
const B = 'main.cell_1_0';
@@ -83,6 +84,54 @@ function claim(ok, text, detail) {
}
const resident = (r, cell) => r.streaming.residentCells.includes(cell);
+const same = (a, b) => JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
+const sortKeys = (o) => Object.fromEntries(Object.entries(o).sort(([a], [b]) => a.localeCompare(b)));
+
+/**
+ * Boot the editor into Play on the same project and read the same report.
+ *
+ * Through the play-frame eval hook, because the realm is an out-of-process
+ * frame. POLLS rather than reading once: a reading taken before residency
+ * settles says "loading", which is neither present nor absent.
+ */
+function playRealmResidency() {
+ const settle = `(async () => {
+ for (let i = 0; i < 900; i++) {
+ const r = window.__estellaPlay?.streaming?.();
+ if (r && r.streamed && r.loadingCells.length === 0
+ && r.unloadingCells.length === 0 && r.residentCells.length > 0) break;
+ await new Promise((done) => setTimeout(done, 16));
+ }
+ return JSON.stringify(window.__estellaPlay?.streaming?.() ?? null);
+ })()`;
+ const r = runElectron(['.'], {
+ via: 'npx',
+ encoding: 'utf8',
+ cwd: DESKTOP,
+ env: {
+ ESTELLA_SHOT: path.join(WORK, 'editor-play.png'),
+ ESTELLA_SHOT_PROJECT: PROJECT,
+ ESTELLA_SHOT_SCENE: 'assets/scenes/main.esscene',
+ ESTELLA_SHOT_PLAY: '1',
+ ESTELLA_SHOT_PLAY_EVAL: settle,
+ ESTELLA_WIN_W: '1500',
+ ESTELLA_WIN_H: '1040',
+ },
+ });
+ const line = (r.stdout || '').split('\n').find((l) => l.includes('[playEval]'));
+ if (!line) {
+ console.error(` the editor printed no play-realm reading — ${(r.stdout || r.stderr || '').trim().slice(-300)}`);
+ return null;
+ }
+ try {
+ // The hook prints a string result as-is, and the eval already stringified
+ // the report — so this is the report's own encoding and nothing else.
+ return JSON.parse(line.slice(line.indexOf('[playEval]') + '[playEval]'.length).trim());
+ } catch {
+ console.error(` the reading did not parse: ${line.slice(0, 300)}`);
+ return null;
+ }
+}
const entities = (r, cell) => r.streaming.cellEntityCounts[cell];
const authored = (r, cell) => r.streaming.authoredCellEntityCounts[cell];
/** An entity handle's slot, so a criterion can say whether one was REUSED. */
@@ -418,6 +467,31 @@ function main() {
'with nothing compiled at first sight either',
`${CELL_COMPILES} peaked at ${quiet.atReveal[CELL_COMPILES] ?? 0}`);
+ // ---- The editor plays the same world, and cuts it the same way --------
+ //
+ // Frames cannot make this claim: the editor's moved 0.0073 → 0.0008 when
+ // Play stopped loading the world whole — inside every parity tolerance.
+ const played = playRealmResidency();
+ if (played === null) {
+ claim(false, 'the editor play realm reported its residency');
+ } else {
+ claim(played.streamed && played.cellCount === initial.streaming.cellCount,
+ 'the editor plays a cut world too, with the cells the package ships',
+ `${played.cellCount} cells, streamed=${played.streamed}`);
+ claim(same(played.residentCells, initial.streaming.residentCells),
+ 'and the same places are resident at boot, because the geometry is the same',
+ `editor ${JSON.stringify([...played.residentCells].sort())} `
+ + `vs package ${JSON.stringify([...initial.streaming.residentCells].sort())}`);
+ claim(JSON.stringify(sortKeys(played.authoredCellEntityCounts))
+ === JSON.stringify(sortKeys(initial.streaming.authoredCellEntityCounts)),
+ 'holding what the cook put in them — one partition, two hosts',
+ JSON.stringify(sortKeys(played.authoredCellEntityCounts)));
+ claim(JSON.stringify(sortKeys(played.cellEntityCounts))
+ === JSON.stringify(sortKeys(initial.streaming.cellEntityCounts)),
+ 'and the live entity counts agree, so both published the same documents',
+ `editor ${JSON.stringify(sortKeys(played.cellEntityCounts))}`);
+ }
+
const failed = results.filter((r) => !r.ok).length;
console.log(`\nworld-residency: ${results.length - failed}/${results.length}`);
process.exit(failed === 0 ? 0 : 1);