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(cook): one authored world becomes a persistent scene and its cells

esengine30c1a07b1e77
diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.ts
index 082266a5d..f9a78618a 100644
--- a/pipeline/src/export/exportGame.ts
+++ b/pipeline/src/export/exportGame.ts
@@ -25,6 +25,7 @@ import { writeFile, readFile, mkdir, cp, readdir, rm } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { cookAssets, loadAssetGroups, type CookManifest } from '../assets/cookAssets';
+import { cookWorlds } from '../world/cookWorld';
import { buildAddressableManifest } from '../assets/addressableManifest';
import { activeRemoteRoot } from '../../../sdk/src/asset/assetGroups';
import type { PackagedGameConfig } from 'esengine';
@@ -668,6 +669,12 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
// work on web + desktop too (not just mini-games). Additive: the eager boot
// still reads the flat manifest; this powers on-demand + hot-update delivery.
await writeFile(path.join(payloadDir, 'asset-manifest.json'), await buildAddressableManifest(payloadDir));
+ // A scene that declared itself streamed is cut here, once its assets are staged
+ // and its references are in the form the runtime resolves. The entry scene it
+ // leaves behind is the PERSISTENT world; the places arrive by residency.
+ progress({ phase: 'Cutting worlds' });
+ const world = await cookWorlds(opts.root, payloadDir, scenes);
+ warnings.push(...world.warnings);
// The flat manifest is a build-time intermediate: the addressable one above is
// derived from it, and every runtime now reads only that. Dropping it keeps one
// asset model in the package — the mini-game export has always done this.
@@ -811,6 +818,7 @@ async function produceExport(opts: ExportGameOptions): Promise<ExportGameResult>
...(sideModuleDeclarations(projectModules, platform).length > 0
? { sideModules: sideModuleDeclarations(projectModules, platform) } : {}),
...(aot ? { aot } : {}),
+ ...(world.worlds.length > 0 ? { worlds: world.worlds } : {}),
};
await writeFile(path.join(payloadDir, 'game.config.json'), JSON.stringify(gameConfig, null, 2) + '\n');
diff --git a/pipeline/src/world/componentRefs.ts b/pipeline/src/world/componentRefs.ts
new file mode 100644
index 000000000..de551d0cc
--- /dev/null
+++ b/pipeline/src/world/componentRefs.ts
@@ -0,0 +1,33 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file componentRefs.ts
+ * @brief Which component fields hold entity references, asked of the engine
+ * rather than listed here.
+ *
+ * @details A table would answer for the components someone remembered. The
+ * registry answers for every one the engine has — builtins from the
+ * generated metadata and the TypeScript components alike — which is what
+ * the cross-cell reference check has to be complete over.
+ */
+
+import { getComponentRegistry } from 'esengine/node';
+
+let cached: Map<string, readonly string[]> | null = null;
+
+/**
+ * The entity-valued fields of a component type; empty for most of them.
+ *
+ * A project's OWN components live in its script bundle, not in this registry, so
+ * a reference one holds goes unchecked at cook. The runtime is the backstop: an
+ * id it cannot resolve is cleared, never left pointing at another entity.
+ */
+export function engineEntityFields(componentType: string): readonly string[] {
+ if (cached === null) {
+ cached = new Map();
+ for (const [name, def] of getComponentRegistry()) {
+ if (def.entityFields.length > 0) cached.set(name, def.entityFields);
+ }
+ }
+ return cached.get(componentType) ?? [];
+}
diff --git a/pipeline/src/world/cookWorld.ts b/pipeline/src/world/cookWorld.ts
new file mode 100644
index 000000000..04a97f161
--- /dev/null
+++ b/pipeline/src/world/cookWorld.ts
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cookWorld.ts
+ * @brief Turning a staged scene into a persistent scene plus cell documents.
+ *
+ * @details Runs over the COOKED payload rather than the project: by then every
+ * asset reference is in the form the runtime resolves, so a cell is the
+ * same bytes the whole scene would have been, minus the places that are
+ * somewhere else.
+ */
+
+import { readFile, writeFile, mkdir } from 'node:fs/promises';
+import path from 'node:path';
+import type { SceneData, WorldManifest } from 'esengine';
+import { partitionWorld, type PrefabRoot } from './partitionWorld';
+import { engineEntityFields } from './componentRefs';
+import { readCachedAssetIndex, scanAssetDatabase, type AssetIndex } from '../assets/assetDb';
+
+/** Where cooked world content goes, package-relative. */
+const WORLD_DIR = 'world';
+
+/** One streamed scene, as `game.config.json` names it. */
+export interface CookedWorld {
+ scene: string;
+ manifest: string;
+}
+
+export interface CookWorldsResult {
+ worlds: CookedWorld[];
+ warnings: string[];
+}
+
+/** A file name that survives a scene living in a subdirectory. */
+function fileSafe(name: string): string {
+ return name.replace(/[^A-Za-z0-9_.-]/g, '_');
+}
+
+/**
+ * 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.
+ */
+function prefabResolver(root: string, index: AssetIndex): (ref: string) => Promise<PrefabRoot | 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> => {
+ 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;
+ }
+ };
+}
+
+/**
+ * Cut every staged scene that declares itself streamed.
+ *
+ * Throws on a partition error. A hard reference across a residency boundary is
+ * not a warning: shipping it produces a handle that dangles the first time a
+ * player walks away, which is the failure this whole stage exists to prevent.
+ */
+export async function cookWorlds(
+ root: string, payloadDir: string, scenes: ReadonlyArray<{ name: string; path: string }>,
+): Promise<CookWorldsResult> {
+ const worlds: CookedWorld[] = [];
+ const warnings: string[] = [];
+ let index: AssetIndex | null = null;
+ let resolve: ((ref: string) => Promise<PrefabRoot | null>) | null = null;
+
+ for (const scene of scenes) {
+ const staged = path.join(payloadDir, scene.path);
+ let text: string;
+ try {
+ text = await readFile(staged, 'utf8');
+ } catch {
+ continue; // not staged for this target
+ }
+ // Cheap first: most scenes are not worlds, and the registry behind the
+ // reference check costs a whole engine to load.
+ if (!text.includes('"StreamedWorld"')) continue;
+
+ if (resolve === null) {
+ index = await readCachedAssetIndex(root)
+ ?? (await scanAssetDatabase(root, { write: false, adopt: false })).index;
+ resolve = prefabResolver(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 partition = partitionWorld(document, scene.name, {
+ entityFieldsOf: engineEntityFields,
+ resolvePrefab: (ref) => roots.get(ref) ?? null,
+ });
+ if (partition === null) continue;
+ if (partition.errors.length > 0) {
+ throw new Error(
+ `scene "${scene.name}" cannot be cut into cells:\n`
+ + partition.errors.map((e) => ` ${e}`).join('\n'),
+ );
+ }
+ warnings.push(...partition.warnings.map((w) => `${scene.name}: ${w}`));
+
+ const worldDir = path.join(payloadDir, WORLD_DIR);
+ await mkdir(worldDir, { recursive: true });
+ const manifest: WorldManifest = {
+ version: 1,
+ scene: scene.name,
+ cellSize: partition.cellSize,
+ persistentRefs: partition.persistentRefs,
+ cells: partition.cells.map((cell) => ({
+ name: cell.name,
+ path: `${WORLD_DIR}/${fileSafe(cell.name)}.json`,
+ x: cell.x, z: cell.z,
+ minX: cell.minX, minZ: cell.minZ, maxX: cell.maxX, maxZ: cell.maxZ,
+ entityCount: cell.entityCount,
+ rootCount: cell.rootCount,
+ })),
+ };
+ for (const cell of partition.cells) {
+ await writeFile(
+ path.join(worldDir, `${fileSafe(cell.name)}.json`),
+ JSON.stringify(cell.data) + '\n',
+ );
+ }
+ const manifestPath = `${WORLD_DIR}/${fileSafe(scene.name)}.world.json`;
+ await writeFile(path.join(payloadDir, manifestPath), JSON.stringify(manifest, null, 2) + '\n');
+ // The staged scene becomes the PERSISTENT world. What a package boots is
+ // then the thing residency never removes, and the places arrive later.
+ await writeFile(staged, JSON.stringify(partition.persistent) + '\n');
+ worlds.push({ scene: scene.name, manifest: manifestPath });
+ }
+
+ return { worlds, warnings };
+}
diff --git a/pipeline/src/world/partitionWorld.ts b/pipeline/src/world/partitionWorld.ts
new file mode 100644
index 000000000..8df4f0e97
--- /dev/null
+++ b/pipeline/src/world/partitionWorld.ts
@@ -0,0 +1,425 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file partitionWorld.ts
+ * @brief Cutting one authored world into a persistent scene plus cells.
+ *
+ * @details Spatial partition is COOKED content. A packaged game that walked its
+ * whole world at boot to decide who lives where has already paid for the
+ * world it was trying not to load.
+ *
+ * Only TOP-LEVEL entities are placed. That is what makes a subtree the
+ * residency atom rather than a rule to remember: a door cannot be sorted
+ * away from its house, because the door was never asked. Placing by each
+ * entity's own world position is the version of this that leaves children
+ * behind when their parent unloads, and it takes the hierarchy contract
+ * with it.
+ *
+ * Pure: the caller supplies what only a project can answer — which
+ * fields hold entity references, and where a prefab's root sits.
+ */
+
+import { isPrefabEntry } from 'esengine';
+import type {
+ SceneData, SceneEntityData, SceneComponentData, SceneEntry, PrefabInstanceEntry,
+} from 'esengine';
+
+interface Vec3 { x: number; y: number; z: number }
+
+/** Where a prefab asset's root sits, for an instance that does not override it. */
+export interface PrefabRoot {
+ rootId: string;
+ position: Vec3;
+}
+
+export interface PartitionOptions {
+ /** The entity-valued fields of a component type; empty for most. */
+ entityFieldsOf(componentType: string): readonly string[];
+ /** Resolve a scene's `@uuid:` prefab reference. Absent = instances must override. */
+ resolvePrefab?(ref: string): PrefabRoot | null;
+}
+
+/** One cooked cell: what it covers, and the scene document that fills it. */
+export interface PartitionedCell {
+ name: string;
+ x: number;
+ z: number;
+ minX: number;
+ minZ: number;
+ maxX: number;
+ maxZ: number;
+ entityCount: number;
+ rootCount: number;
+ data: SceneData;
+}
+
+export interface WorldPartition {
+ cellSize: number;
+ /** The entry scene as it now ships: everything residency never removes. */
+ persistent: SceneData;
+ cells: PartitionedCell[];
+ /**
+ * Authored ids a cell references in the persistent world. The runtime needs
+ * exactly these to resolve across the document boundary.
+ */
+ persistentRefs: number[];
+ /** Refuse the build. A dangling hard reference is not a warning. */
+ errors: string[];
+ warnings: string[];
+}
+
+const ORIGIN: Vec3 = { x: 0, y: 0, z: 0 };
+
+/** A scene entry's authored name; a prefab instance carries one the type omits. */
+function nameOf(entry: SceneEntry): string {
+ return (entry as { name?: string }).name ?? '';
+}
+
+function componentsOf(entry: SceneEntry): SceneComponentData[] {
+ return isPrefabEntry(entry) ? [] : (entry as SceneEntityData).components ?? [];
+}
+
+/**
+ * Whether an entry carries a component, counting the one a prefab instance ADDS
+ * — the only way to mark an instance, since its own list is the delta.
+ */
+function hasComponent(entry: SceneEntry, type: string): boolean {
+ if (!isPrefabEntry(entry)) {
+ return componentsOf(entry).some((component) => component.type === type);
+ }
+ return (entry as PrefabInstanceEntry).overrides.some(
+ (override) => override.type === 'component_added' && override.componentType === type,
+ );
+}
+
+function componentData(entry: SceneEntry, type: string): Record<string, unknown> | null {
+ for (const component of componentsOf(entry)) {
+ if (component.type === type) return component.data as Record<string, unknown>;
+ }
+ return null;
+}
+
+function vec3(value: unknown, fallback: Vec3): Vec3 {
+ if (value === null || typeof value !== 'object') return fallback;
+ const v = value as Partial<Vec3>;
+ return {
+ x: typeof v.x === 'number' ? v.x : fallback.x,
+ y: typeof v.y === 'number' ? v.y : fallback.y,
+ z: typeof v.z === 'number' ? v.z : fallback.z,
+ };
+}
+
+/**
+ * The position an entry declares, in its parent's space.
+ *
+ * A prefab instance's is an override over the asset's root, which is why the
+ * asset has to be resolvable: an instance placed at the origin and an instance
+ * that never said where it goes are the same document without it.
+ */
+function localPosition(
+ entry: SceneEntry, options: PartitionOptions, problems: string[],
+): Vec3 {
+ if (!isPrefabEntry(entry)) {
+ const transform = componentData(entry, 'Transform');
+ return transform ? vec3(transform.position, ORIGIN) : ORIGIN;
+ }
+ const instance = entry as PrefabInstanceEntry;
+ const asset = options.resolvePrefab?.(instance.prefab) ?? null;
+ if (asset === null) {
+ problems.push(
+ `entity ${instance.id} ("${nameOf(instance)}") instances a prefab this cook cannot read `
+ + `(${instance.prefab}), so where it stands is unknown`,
+ );
+ return ORIGIN;
+ }
+ for (const override of instance.overrides) {
+ if (override.type !== 'property' || override.prefabEntityId !== asset.rootId) continue;
+ if (override.componentType === 'Transform' && override.propertyName === 'position') {
+ return vec3(override.value, asset.position);
+ }
+ }
+ return asset.position;
+}
+
+/** Rotation and scale, for composing where a CHILD ends up. Identity by default. */
+function localRotation(entry: SceneEntry): [number, number, number, number] {
+ const transform = isPrefabEntry(entry) ? null : componentData(entry, 'Transform');
+ const r = transform?.rotation as Partial<{ x: number; y: number; z: number; w: number }> | undefined;
+ if (!r) return [0, 0, 0, 1];
+ return [r.x ?? 0, r.y ?? 0, r.z ?? 0, r.w ?? 1];
+}
+
+function localScale(entry: SceneEntry): Vec3 {
+ const transform = isPrefabEntry(entry) ? null : componentData(entry, 'Transform');
+ return transform ? vec3(transform.scale, { x: 1, y: 1, z: 1 }) : { x: 1, y: 1, z: 1 };
+}
+
+/** Rotate `v` by the quaternion `q`. */
+function rotate(q: readonly [number, number, number, number], v: Vec3): Vec3 {
+ const [qx, qy, qz, qw] = q;
+ const tx = 2 * (qy * v.z - qz * v.y);
+ const ty = 2 * (qz * v.x - qx * v.z);
+ const tz = 2 * (qx * v.y - qy * v.x);
+ return {
+ x: v.x + qw * tx + (qy * tz - qz * ty),
+ y: v.y + qw * ty + (qz * tx - qx * tz),
+ z: v.z + qw * tz + (qx * ty - qy * tx),
+ };
+}
+
+function multiplyQuat(
+ a: readonly [number, number, number, number], b: readonly [number, number, number, number],
+): [number, number, number, number] {
+ const [ax, ay, az, aw] = a;
+ const [bx, by, bz, bw] = b;
+ return [
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw,
+ aw * bw - ax * bx - ay * by - az * bz,
+ ];
+}
+
+interface Placement {
+ /** Grid coordinate, or null for the persistent world. */
+ cell: { x: number; z: number } | null;
+ root: number;
+}
+
+/**
+ * Cut `scene` into a persistent scene plus cells, or answer null when the scene
+ * never declared itself streamed — which is every scene that came before this
+ * and every small one that should stay whole.
+ */
+export function partitionWorld(
+ scene: SceneData, sceneName: string, options: PartitionOptions,
+): WorldPartition | null {
+ const entries = (scene.entities ?? []) as unknown as SceneEntry[];
+ let cellSize = 0;
+ for (const entry of entries) {
+ if (!hasComponent(entry, 'StreamedWorld')) continue;
+ const declaration = componentData(entry, 'StreamedWorld');
+ if (declaration && declaration.enabled === false) return null;
+ cellSize = typeof declaration?.cellSize === 'number' ? declaration.cellSize : 0;
+ break;
+ }
+ if (cellSize <= 0) {
+ // A declaration with no usable size is a mistake worth naming, but a
+ // scene with no declaration at all is simply not a streamed world.
+ return entries.some((entry) => hasComponent(entry, 'StreamedWorld'))
+ ? {
+ cellSize: 0, persistent: scene, cells: [], persistentRefs: [],
+ errors: [`StreamedWorld in "${sceneName}" declares no positive cellSize`],
+ warnings: [],
+ }
+ : null;
+ }
+
+ const errors: string[] = [];
+ const warnings: string[] = [];
+ const byId = new Map<number, SceneEntry>();
+ for (const entry of entries) byId.set(entry.id, entry);
+
+ const childrenOf = new Map<number, number[]>();
+ const roots: number[] = [];
+ for (const entry of entries) {
+ const parent = entry.parent;
+ if (parent === null || parent === undefined || !byId.has(parent)) {
+ if (parent !== null && parent !== undefined) {
+ warnings.push(`entity ${entry.id} names a parent (${parent}) the scene does not hold`);
+ }
+ roots.push(entry.id);
+ continue;
+ }
+ const siblings = childrenOf.get(parent);
+ if (siblings) siblings.push(entry.id);
+ else childrenOf.set(parent, [entry.id]);
+ }
+
+ // Subtree membership and composed world positions in one walk: the placement
+ // comes from the ROOT, and the positions are what the cell's box has to cover.
+ const placement = new Map<number, Placement>();
+ const worldPosition = new Map<number, Vec3>();
+ const members = new Map<number, number[]>();
+ for (const root of roots) {
+ const entry = byId.get(root)!;
+ const streamed = !hasComponent(entry, 'WorldPersistent')
+ && !hasComponent(entry, 'StreamedWorld')
+ && (isPrefabEntry(entry) || componentData(entry, 'Transform') !== null);
+ const rootPosition = localPosition(entry, options, errors);
+ const cell = streamed
+ ? { x: Math.floor(rootPosition.x / cellSize), z: Math.floor(rootPosition.z / cellSize) }
+ : null;
+
+ const subtree: number[] = [];
+ const stack: Array<{ id: number; position: Vec3; rotation: [number, number, number, number]; scale: Vec3 }> = [
+ { id: root, position: rootPosition, rotation: localRotation(entry), scale: localScale(entry) },
+ ];
+ while (stack.length > 0) {
+ const node = stack.pop()!;
+ subtree.push(node.id);
+ placement.set(node.id, { cell, root });
+ worldPosition.set(node.id, node.position);
+ for (const child of childrenOf.get(node.id) ?? []) {
+ const childEntry = byId.get(child)!;
+ const local = localPosition(childEntry, options, errors);
+ const scaled = { x: local.x * node.scale.x, y: local.y * node.scale.y, z: local.z * node.scale.z };
+ const turned = rotate(node.rotation, scaled);
+ stack.push({
+ id: child,
+ position: { x: node.position.x + turned.x, y: node.position.y + turned.y, z: node.position.z + turned.z },
+ rotation: multiplyQuat(node.rotation, localRotation(childEntry)),
+ scale: {
+ x: node.scale.x * localScale(childEntry).x,
+ y: node.scale.y * localScale(childEntry).y,
+ z: node.scale.z * localScale(childEntry).z,
+ },
+ });
+ }
+ }
+ members.set(root, subtree);
+ }
+
+ for (const entry of entries) {
+ if (roots.includes(entry.id)) continue;
+ if (hasComponent(entry, 'WorldPersistent')) {
+ errors.push(
+ `entity ${entry.id} ("${nameOf(entry)}") carries WorldPersistent but is not top-level — `
+ + 'a subtree is the residency atom, so persistence is its root\'s answer',
+ );
+ }
+ if (hasComponent(entry, 'StreamedWorld')) {
+ errors.push(`entity ${entry.id} ("${nameOf(entry)}") carries StreamedWorld but is not top-level`);
+ }
+ }
+
+ const persistentRefs = new Set<number>();
+ checkReferences(entries, byId, placement, options, persistentRefs, errors);
+
+ // Sorted, so two cooks of one world produce the same manifest.
+ const cellKeys = new Map<string, number[]>();
+ const persistentRoots: number[] = [];
+ for (const root of roots) {
+ const cell = placement.get(root)!.cell;
+ if (cell === null) { persistentRoots.push(root); continue; }
+ const key = `${cell.x}_${cell.z}`;
+ const bucket = cellKeys.get(key);
+ if (bucket) bucket.push(root);
+ else cellKeys.set(key, [root]);
+ }
+
+ const order = new Map<number, number>();
+ entries.forEach((entry, index) => order.set(entry.id, index));
+ const documentOf = (ids: number[], name: string): SceneData => {
+ const kept = new Set(ids);
+ const list = entries.filter((entry) => kept.has(entry.id))
+ .map((entry) => ({ ...entry, parent: byId.has(entry.parent as number) ? entry.parent : null }));
+ return {
+ version: scene.version,
+ name,
+ ...(scene.generator ? { generator: scene.generator } : {}),
+ entities: list as unknown as SceneEntityData[],
+ ...(scene.textureMetadata ? { textureMetadata: scene.textureMetadata } : {}),
+ };
+ };
+
+ const persistentIds: number[] = [];
+ for (const root of persistentRoots) persistentIds.push(...members.get(root)!);
+ persistentIds.sort((a, b) => order.get(a)! - order.get(b)!);
+
+ const cells: PartitionedCell[] = [];
+ const keys = [...cellKeys.keys()].sort((a, b) => {
+ const [ax, az] = a.split('_').map(Number);
+ const [bx, bz] = b.split('_').map(Number);
+ return ax - bx || az - bz;
+ });
+ for (const key of keys) {
+ const [x, z] = key.split('_').map(Number);
+ const ids: number[] = [];
+ for (const root of cellKeys.get(key)!) ids.push(...members.get(root)!);
+ ids.sort((a, b) => order.get(a)! - order.get(b)!);
+ let minX = x * cellSize;
+ let minZ = z * cellSize;
+ let maxX = minX + cellSize;
+ let maxZ = minZ + cellSize;
+ // The grid square unioned with where the content actually is: a prop
+ // hanging over the edge is part of the place the box stands for, and a
+ // box that stops short of it pops the prop in at the boundary.
+ for (const id of ids) {
+ const at = worldPosition.get(id)!;
+ minX = Math.min(minX, at.x); maxX = Math.max(maxX, at.x);
+ minZ = Math.min(minZ, at.z); maxZ = Math.max(maxZ, at.z);
+ }
+ const name = `${sceneName}.cell_${x}_${z}`;
+ cells.push({
+ name, x, z, minX, minZ, maxX, maxZ,
+ entityCount: ids.length,
+ rootCount: cellKeys.get(key)!.length,
+ data: documentOf(ids, name),
+ });
+ }
+
+ return {
+ cellSize,
+ persistent: documentOf(persistentIds, scene.name),
+ cells,
+ persistentRefs: [...persistentRefs].sort((a, b) => a - b),
+ errors,
+ warnings,
+ };
+}
+
+/**
+ * Hard entity references, held to what residency can keep true.
+ *
+ * Same cell is fine, and so is streamed-to-persistent (the persistent world
+ * outlives every cell). The other two directions point at something residency is
+ * entitled to delete, and are refused.
+ */
+function checkReferences(
+ entries: readonly SceneEntry[],
+ byId: ReadonlyMap<number, SceneEntry>,
+ placement: ReadonlyMap<number, Placement>,
+ options: PartitionOptions,
+ persistentRefs: Set<number>,
+ errors: string[],
+): void {
+ const sameCell = (a: Placement, b: Placement): boolean =>
+ a.cell !== null && b.cell !== null && a.cell.x === b.cell.x && a.cell.z === b.cell.z;
+
+ const check = (holder: SceneEntry, componentType: string, field: string, value: unknown): void => {
+ const one = (candidate: unknown): void => {
+ if (typeof candidate !== 'number' || !byId.has(candidate)) return;
+ const from = placement.get(holder.id);
+ const to = placement.get(candidate);
+ if (!from || !to || from.root === to.root || sameCell(from, to)) return;
+ if (from.cell !== null && to.cell === null) { persistentRefs.add(candidate); return; }
+ const where = to.cell === null ? 'the persistent world' : `cell ${to.cell.x},${to.cell.z}`;
+ errors.push(
+ `${componentType}.${field} on entity ${holder.id} ("${nameOf(holder)}") references `
+ + `entity ${candidate} ("${nameOf(byId.get(candidate)!)}") in ${where} — `
+ + 'residency may delete one without the other',
+ );
+ };
+ if (Array.isArray(value)) value.forEach(one);
+ else one(value);
+ };
+
+ for (const entry of entries) {
+ if (!isPrefabEntry(entry)) {
+ for (const component of (entry as SceneEntityData).components ?? []) {
+ for (const field of options.entityFieldsOf(component.type)) {
+ check(entry, component.type, field, (component.data as Record<string, unknown>)[field]);
+ }
+ }
+ continue;
+ }
+ // An instance's references live in its overrides; the asset's own are
+ // internal to the instance and cannot cross a cell.
+ for (const override of (entry as PrefabInstanceEntry).overrides) {
+ if (override.type !== 'property' || !override.componentType || !override.propertyName) continue;
+ if (!options.entityFieldsOf(override.componentType).includes(override.propertyName)) continue;
+ check(entry, override.componentType, override.propertyName, override.value);
+ }
+ }
+}
diff --git a/pipeline/tests/partition-world.test.ts b/pipeline/tests/partition-world.test.ts
new file mode 100644
index 000000000..aff3b2721
--- /dev/null
+++ b/pipeline/tests/partition-world.test.ts
@@ -0,0 +1,178 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What the cook does to one authored world, and what it refuses.
+ *
+ * The two claims that matter most are negative. A subtree cannot be split
+ * across cells no matter where a child ends up in the world, because only
+ * top-level entities are ever placed; and a hard reference that crosses a
+ * residency boundary fails the build rather than shipping a handle that dangles
+ * the first time a player walks away.
+ */
+import { describe, it, expect } from 'vitest';
+import type { SceneData } from 'esengine';
+import { partitionWorld, type PartitionOptions } from '../src/world/partitionWorld';
+
+const SIZE = 1000;
+
+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, enabled: true } };
+
+function scene(...entities: Array<Record<string, unknown>>): SceneData {
+ return { version: 4, name: 'main', entities } as unknown as SceneData;
+}
+
+const options: PartitionOptions = {
+ entityFieldsOf: (type) => (type === 'ThirdPersonCamera' ? ['target'] : []),
+};
+
+const cut = (data: SceneData): ReturnType<typeof partitionWorld> =>
+ partitionWorld(data, 'main', options);
+
+const names = (document: SceneData): string[] =>
+ (document.entities as unknown as Array<{ name: string }>).map((e) => e.name);
+
+describe('partitionWorld', () => {
+ it('leaves a scene that never declared itself streamed alone', () => {
+ expect(cut(scene(entity(0, 'Ground', [0, 0, 0])))).toBeNull();
+ });
+
+ it('places top-level entities by their own position, and keeps the rest persistent', () => {
+ const partition = cut(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]),
+ entity(4, 'Services', null),
+ ))!;
+ expect(partition.cellSize).toBe(SIZE);
+ // A root with no Transform is not anywhere, so it stays with the world.
+ expect(names(partition.persistent).sort()).toEqual(['Player', 'Services', 'World']);
+ expect(partition.cells.map((c) => [c.x, c.z])).toEqual([[0, 0], [1, 0]]);
+ expect(names(partition.cells[0].data)).toEqual(['RockA']);
+ expect(names(partition.cells[1].data)).toEqual(['RockB']);
+ });
+
+ it('keeps a subtree whole even when a child stands in another cell', () => {
+ // The lamp's world position is 1500, which is cell 1 — but residency is a
+ // property of the root, so it goes where the house goes. Split by each
+ // entity's own position, unloading the house would strand the lamp.
+ const partition = cut(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ entity(1, 'House', [500, 0, 500]),
+ entity(2, 'Lamp', [1000, 0, 0], { parent: 1 }),
+ ))!;
+ expect(partition.cells).toHaveLength(1);
+ expect(names(partition.cells[0].data)).toEqual(['House', 'Lamp']);
+ // …and the box grows to cover it, so the cell is asked for from where its
+ // content actually is rather than from the grid square it was cut on.
+ expect(partition.cells[0].maxX).toBe(1500);
+ });
+
+ it('composes a child through its parent\'s rotation and scale', () => {
+ const turned = entity(1, 'Rig', [0, 0, 0]);
+ (turned.components as Component[])[0].data.rotation = { x: 0, y: 0.7071067811865476, z: 0, w: 0.7071067811865476 };
+ (turned.components as Component[])[0].data.scale = { x: 2, y: 1, z: 1 };
+ const partition = cut(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ turned,
+ entity(2, 'Arm', [100, 0, 0], { parent: 1 }),
+ ))!;
+ // Scaled to 200 along local X, then a quarter turn about Y sends it to -Z.
+ expect(partition.cells[0].minZ).toBeCloseTo(-200, 4);
+ });
+
+ it('refuses WorldPersistent on anything but a root', () => {
+ const partition = cut(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ entity(1, 'House', [500, 0, 500]),
+ entity(2, 'Lamp', [0, 0, 0], { parent: 1, components: [{ type: 'WorldPersistent', data: {} }] }),
+ ))!;
+ expect(partition.errors.join('\n')).toContain('not top-level');
+ });
+
+ it('refuses a hard reference from one cell into another', () => {
+ const partition = cut(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ entity(1, 'Watcher', [500, 0, 500], {
+ components: [{ type: 'ThirdPersonCamera', data: { target: 2 } }],
+ }),
+ entity(2, 'Watched', [1500, 0, 500]),
+ ))!;
+ expect(partition.errors.join('\n')).toContain('residency may delete one without the other');
+ });
+
+ it('allows a cell to reference the persistent world, and records which rows', () => {
+ const partition = cut(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ entity(1, 'Player', [10, 0, 10], { components: [{ type: 'WorldPersistent', data: {} }] }),
+ entity(2, 'Turret', [1500, 0, 500], {
+ components: [{ type: 'ThirdPersonCamera', data: { target: 1 } }],
+ }),
+ ))!;
+ expect(partition.errors).toEqual([]);
+ expect(partition.persistentRefs).toEqual([1]);
+ });
+
+ it('refuses a persistent entity holding a reference into a cell', () => {
+ // The dangerous direction: the holder outlives what it points at.
+ const partition = cut(scene(
+ entity(0, 'World', null, { components: [declaration] }),
+ entity(1, 'Camera', [0, 0, 0], {
+ components: [
+ { type: 'WorldPersistent', data: {} },
+ { type: 'ThirdPersonCamera', data: { target: 2 } },
+ ],
+ }),
+ entity(2, 'Prop', [1500, 0, 500]),
+ ))!;
+ expect(partition.errors.join('\n')).toContain('cell 1,0');
+ });
+
+ it('places a prefab instance by its override, and refuses one it cannot read', () => {
+ const instance = {
+ id: 1, name: 'Coin', parent: null, prefab: '@uuid:abc',
+ overrides: [{
+ prefabEntityId: '0', type: 'property', componentType: 'Transform',
+ propertyName: 'position', value: { x: 2500, y: 0, z: 0 },
+ }],
+ added: [], removed: [],
+ };
+ const document = scene(entity(0, 'World', null, { components: [declaration] }), instance);
+ const placed = partitionWorld(document, 'main', {
+ ...options,
+ resolvePrefab: () => ({ rootId: '0', position: { x: 0, y: 0, z: 0 } }),
+ })!;
+ expect(placed.errors).toEqual([]);
+ expect(placed.cells.map((c) => c.x)).toEqual([2]);
+
+ const unread = partitionWorld(document, 'main', options)!;
+ expect(unread.errors.join('\n')).toContain('cannot read');
+ });
+
+ it('names a declaration with no usable cell size instead of shipping it whole', () => {
+ const partition = cut(scene(
+ entity(0, 'World', null, { components: [{ type: 'StreamedWorld', data: { cellSize: 0 } }] }),
+ ))!;
+ expect(partition.errors.join('\n')).toContain('no positive cellSize');
+ });
+
+ it('answers null for a world whose streaming is switched off', () => {
+ expect(cut(scene(
+ entity(0, 'World', null, { components: [{ type: 'StreamedWorld', data: { cellSize: SIZE, enabled: false } }] }),
+ entity(1, 'RockA', [500, 0, 500]),
+ ))).toBeNull();
+ });
+});
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 5d374e56f..51c6f1aab 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 · 1622 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1624 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5512,6 +5512,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
+worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -7301,6 +7302,11 @@ parent: number | null
visible: boolean | undefined
```
+## SceneEntry — type @experimental
+```
+SceneEntityData | PrefabInstanceEntry
+```
+
## SceneLoadCancelled — class @experimental
```
static new (name: string): SceneLoadCancelled
@@ -10057,6 +10063,7 @@ z: number
```
cellSize: number
cells: WorldCell[]
+persistentRefs: number[]
scene: string
version: number
```
@@ -11782,6 +11789,11 @@ InputRouter
(): boolean
```
+## isPrefabEntry — function @experimental
+```
+(e: SceneEntry): e is PrefabInstanceEntry
+```
+
## isRootPlacementChannel — function @experimental
```
(childPath: string, component: string, property: string): boolean
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index bab10841e..b8f00925c 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 · 1641 experimental · 3 deprecated
+Symbols: 113 public · 89 beta · 1643 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
@@ -5695,6 +5695,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
+worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -7494,6 +7495,11 @@ parent: number | null
visible: boolean | undefined
```
+## SceneEntry — type @experimental
+```
+SceneEntityData | PrefabInstanceEntry
+```
+
## SceneLoadCancelled — class @experimental
```
static new (name: string): SceneLoadCancelled
@@ -10250,6 +10256,7 @@ z: number
```
cellSize: number
cells: WorldCell[]
+persistentRefs: number[]
scene: string
version: number
```
@@ -12025,6 +12032,11 @@ InputRouter
(): boolean
```
+## isPrefabEntry — function @experimental
+```
+(e: SceneEntry): e is PrefabInstanceEntry
+```
+
## isRootPlacementChannel — function @experimental
```
(childPath: string, component: string, property: string): boolean
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index c36d071bc..9863bd7d2 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 · 1621 experimental · 3 deprecated
+Symbols: 113 public · 86 beta · 1623 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5507,6 +5507,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
+worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -7296,6 +7297,11 @@ parent: number | null
visible: boolean | undefined
```
+## SceneEntry — type @experimental
+```
+SceneEntityData | PrefabInstanceEntry
+```
+
## SceneLoadCancelled — class @experimental
```
static new (name: string): SceneLoadCancelled
@@ -10052,6 +10058,7 @@ z: number
```
cellSize: number
cells: WorldCell[]
+persistentRefs: number[]
scene: string
version: number
```
@@ -11777,6 +11784,11 @@ InputRouter
(): boolean
```
+## isPrefabEntry — function @experimental
+```
+(e: SceneEntry): e is PrefabInstanceEntry
+```
+
## isRootPlacementChannel — function @experimental
```
(childPath: string, component: string, property: string): boolean
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index ea3dd8f2b..4697306d4 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 · 1643 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1645 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5753,6 +5753,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
+worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -7542,6 +7543,11 @@ parent: number | null
visible: boolean | undefined
```
+## SceneEntry — type @experimental
+```
+SceneEntityData | PrefabInstanceEntry
+```
+
## SceneLoadCancelled — class @experimental
```
static new (name: string): SceneLoadCancelled
@@ -10304,6 +10310,7 @@ z: number
```
cellSize: number
cells: WorldCell[]
+persistentRefs: number[]
scene: string
version: number
```
@@ -12044,6 +12051,11 @@ InputRouter
(): boolean
```
+## isPrefabEntry — function @experimental
+```
+(e: SceneEntry): e is PrefabInstanceEntry
+```
+
## isRootPlacementChannel — function @experimental
```
(childPath: string, component: string, property: string): boolean
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index aa321f20d..fab606363 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 · 1633 experimental · 3 deprecated
+Symbols: 113 public · 84 beta · 1635 experimental · 3 deprecated
## ANCHOR_AXES — const @experimental
```
@@ -5514,6 +5514,7 @@ sideModules: { id: string; file: string; globalName?: string; }[] | undefined
steamAppId: number | undefined
uiTheme: "light" | undefined
uiThemeColors: Record<string, string> | undefined
+worlds: { scene: string; manifest: string; }[] | undefined
ySortLayers: number | undefined
```
@@ -7303,6 +7304,11 @@ parent: number | null
visible: boolean | undefined
```
+## SceneEntry — type @experimental
+```
+SceneEntityData | PrefabInstanceEntry
+```
+
## SceneLoadCancelled — class @experimental
```
static new (name: string): SceneLoadCancelled
@@ -10080,6 +10086,7 @@ z: number
```
cellSize: number
cells: WorldCell[]
+persistentRefs: number[]
scene: string
version: number
```
@@ -11810,6 +11817,11 @@ InputRouter
(): boolean
```
+## isPrefabEntry — function @experimental
+```
+(e: SceneEntry): e is PrefabInstanceEntry
+```
+
## isRootPlacementChannel — function @experimental
```
(childPath: string, component: string, property: string): boolean
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index aabdf0fcb..591a7bd42 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -172,6 +172,10 @@ export {
type SliceBorder,
} from './scene/scene';
+// The scene FILE's own vocabulary: a cook that reads a document has to tell its
+// two kinds of entry apart the same way the loader does.
+export { isPrefabEntry, type SceneEntry } from './scene/sceneEntry';
+
/**
* Structural problems in an authored document, in one vocabulary for scenes and
* prefabs alike — what every gate that reads one judges by.
diff --git a/sdk/src/residency/cells.ts b/sdk/src/residency/cells.ts
index 84d245e3d..b5ccf8da1 100644
--- a/sdk/src/residency/cells.ts
+++ b/sdk/src/residency/cells.ts
@@ -43,6 +43,12 @@ export interface WorldManifest {
scene: string;
/** Edge of one grid square, world units. */
cellSize: number;
+ /**
+ * Authored ids in the persistent world that a cell holds a hard reference to.
+ * Only these are kept resolvable — a table of every row would be a cost the
+ * whole world pays for the handful of references that exist.
+ */
+ persistentRefs: number[];
cells: WorldCell[];
}
diff --git a/sdk/src/runtime/packagedRuntime.ts b/sdk/src/runtime/packagedRuntime.ts
index 03e2f5d5e..497216f11 100644
--- a/sdk/src/runtime/packagedRuntime.ts
+++ b/sdk/src/runtime/packagedRuntime.ts
@@ -40,6 +40,12 @@ export interface PackagedGameConfig {
entryScene: string;
/** Every switchable scene (SceneManager name + cooked path); includes the entry. */
scenes?: Array<{ name: string; path: string }>;
+ /**
+ * Scenes the cook cut into cells, each with the manifest describing them.
+ * Deliberately not in `scenes`: a cell is content residency brings in, not a
+ * place a game switches to.
+ */
+ worlds?: Array<{ scene: string; manifest: string }>;
/**
* The project's own bundled code, as a payload-relative file name. Absent
* means this build has none — which is how a host tells "no project script"
diff --git a/sdk/tests/world-residency.test.ts b/sdk/tests/world-residency.test.ts
index ce911b92b..35f082a7b 100644
--- a/sdk/tests/world-residency.test.ts
+++ b/sdk/tests/world-residency.test.ts
@@ -115,7 +115,7 @@ function recordingHost() {
}
const manifest = (...cells: WorldCell[]): WorldManifest =>
- ({ version: 1, scene: 'main', cellSize: 100, cells });
+ ({ version: 1, scene: 'main', cellSize: 100, persistentRefs: [], cells });
describe('WorldStreamer', () => {
it('registers every cell as a scene the game itself never names', async () => {