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(engine): prefab runtime loading + extract; scene codec refactor

esengine42e8a9109a0a
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index 9016c01a3..ba6b73abc 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -5,7 +5,10 @@
import type { App, Plugin } from '../app';
import type { SystemDef } from '../system';
-import { Schedule } from '../system';
+import { Schedule, defineSystem } from '../system';
+import { Res, Time, type TimeData } from '../resource';
+import { playModeOnly } from '../env';
+import { followUpdate } from './FollowTarget';
import type { ESEngineModule, CppRegistry } from '../wasm';
import type { World } from '../world';
import type { Entity } from '../types';
@@ -481,6 +484,15 @@ export function cameraPlugin(
},
};
+ // Per-camera follow (Cinemachine vcam Body): damp FollowTarget cameras
+ // toward their target each frame, BEFORE camera collection, so the
+ // director blends already-followed POVs. Play mode only (gameplay).
+ app.addSystemToSchedule(Schedule.Update, defineSystem(
+ [Res(Time)],
+ (time: TimeData) => followUpdate(app.world, time.delta),
+ { name: 'CameraFollowSystem' },
+ ), { runIf: playModeOnly });
+
app.addSystemToSchedule(Schedule.First, uiCameraSyncSystem);
app.addSystemToSchedule(Schedule.Last, renderSystem);
},
diff --git a/sdk/src/camera/FollowTarget.ts b/sdk/src/camera/FollowTarget.ts
new file mode 100644
index 000000000..83444a170
--- /dev/null
+++ b/sdk/src/camera/FollowTarget.ts
@@ -0,0 +1,84 @@
+/**
+ * @file FollowTarget.ts
+ * @brief Per-camera follow behaviour — the procedural half of the camera
+ * modifier layer (Cinemachine's vcam Body). A camera with a FollowTarget
+ * component damps its Transform toward a target each frame, with a dead
+ * zone (the target can roam within it without the camera moving) and
+ * frame-rate-independent damping. State lives in the camera's Transform
+ * (the ECS-native place), so the director simply blends already-followed
+ * POVs. Runs in play mode only.
+ */
+import { defineComponent, Transform } from '../component';
+import type { World } from '../world';
+import type { Entity } from '../types';
+
+export interface FollowTargetData {
+ /** Entity to follow (-1 = none). */
+ target: number;
+ /** World-space offset added to the target position. */
+ offsetX: number;
+ offsetY: number;
+ /** The target may move within this radius (world units) without the camera following. */
+ deadzone: number;
+ /** Damping time-constant in seconds (larger = smoother/slower; 0 = snap). */
+ damping: number;
+}
+
+export const FollowTarget = defineComponent<FollowTargetData>('FollowTarget', {
+ target: -1,
+ offsetX: 0,
+ offsetY: 0,
+ deadzone: 0,
+ damping: 0.25,
+});
+
+/**
+ * One damped follow step. Pure: given the camera position, the desired position
+ * (target + offset), the dead zone, the damping time-constant, and dt, returns
+ * the camera's next position. Moves the camera only by the part of the gap that
+ * exceeds the dead zone, eased by a frame-rate-independent damping factor.
+ */
+export function followStep(
+ camX: number,
+ camY: number,
+ desiredX: number,
+ desiredY: number,
+ deadzone: number,
+ damping: number,
+ dt: number,
+): { x: number; y: number } {
+ const dx = desiredX - camX;
+ const dy = desiredY - camY;
+ const dist = Math.hypot(dx, dy);
+ if (dist === 0 || dist <= deadzone) return { x: camX, y: camY };
+ const beyond = 1 - deadzone / dist; // fraction of the gap past the dead zone
+ const k = damping > 0 ? 1 - Math.exp(-dt / damping) : 1; // frame-rate-independent
+ return { x: camX + dx * beyond * k, y: camY + dy * beyond * k };
+}
+
+/** Advance every FollowTarget camera by one damped step (called by the follow system). */
+export function followUpdate(world: World, dt: number): void {
+ const entities = world.getEntitiesWithComponents([FollowTarget, Transform]);
+ for (const e of entities) {
+ const ft = world.get(e, FollowTarget);
+ const target = ft.target as Entity;
+ if (ft.target < 0 || !world.valid(target) || !world.has(target, Transform)) continue;
+ const camT = world.get(e, Transform);
+ const tgtT = world.get(target, Transform);
+ const next = followStep(
+ camT.position.x,
+ camT.position.y,
+ tgtT.position.x + ft.offsetX,
+ tgtT.position.y + ft.offsetY,
+ ft.deadzone,
+ ft.damping,
+ dt,
+ );
+ if (next.x !== camT.position.x || next.y !== camT.position.y) {
+ world.set(e, Transform, {
+ ...camT,
+ position: { ...camT.position, x: next.x, y: next.y },
+ });
+ }
+ }
+}
diff --git a/sdk/src/component.ts b/sdk/src/component.ts
index 61077a99f..d934d7718 100644
--- a/sdk/src/component.ts
+++ b/sdk/src/component.ts
@@ -122,8 +122,11 @@ function createComponentDef<T extends object>(
};
}
-export function getComponentRegistry(): Map<string, ComponentDef<any>> {
- return getDefaultContext().componentRegistry;
+// User components live in the per-app AppContext registry (reset-able). Builtins
+// are global and live in `builtinRegistry` (declared further below). The public
+// catalogue accessors merge the two — see getComponentRegistry().
+function userComponents(): Map<string, AnyComponentDef> {
+ return getDefaultContext().componentRegistry as Map<string, AnyComponentDef>;
}
export function defineComponent<T extends object>(
@@ -131,56 +134,47 @@ export function defineComponent<T extends object>(
defaults: T,
metadata?: ComponentMetadata,
): ComponentDef<T> {
- const userExisting = getComponentRegistry().get(name);
- if (userExisting) return userExisting as ComponentDef<T>;
+ const existing = userComponents().get(name);
+ if (existing) return existing as ComponentDef<T>;
- const globalExisting = componentRegistry.get(name);
- if (globalExisting) {
+ if (builtinRegistry.has(name)) {
throw new Error(
- `Component name collision: user component "${name}" conflicts with an existing ${globalExisting._builtin ? 'builtin' : 'user'} component of the same name`
+ `Component name collision: user component "${name}" conflicts with an existing builtin component of the same name`
);
}
const def = createComponentDef(name, defaults, metadata);
- getComponentRegistry().set(name, def);
- componentRegistry.set(name, def);
+ userComponents().set(name, def);
registerToEditor(name, defaults as Record<string, unknown>, false);
return def;
}
export function defineTag(name: string): ComponentDef<{}> {
- const userExisting = getComponentRegistry().get(name);
- if (userExisting) return userExisting as ComponentDef<{}>;
+ const existing = userComponents().get(name);
+ if (existing) return existing as ComponentDef<{}>;
- const globalExisting = componentRegistry.get(name);
- if (globalExisting) {
+ if (builtinRegistry.has(name)) {
throw new Error(
- `Component name collision: tag "${name}" conflicts with an existing ${globalExisting._builtin ? 'builtin' : 'user'} component of the same name`
+ `Component name collision: tag "${name}" conflicts with an existing builtin component of the same name`
);
}
const def = createComponentDef(name, {});
- getComponentRegistry().set(name, def);
- componentRegistry.set(name, def);
+ userComponents().set(name, def);
registerToEditor(name, {}, true);
return def;
}
export function getUserComponent(name: string): ComponentDef<any> | undefined {
- return getComponentRegistry().get(name);
+ return userComponents().get(name) as ComponentDef<any> | undefined;
}
export function clearUserComponents(): void {
- const userRegistry = getComponentRegistry();
- for (const name of userRegistry.keys()) {
- componentRegistry.delete(name);
- }
- userRegistry.clear();
+ userComponents().clear();
}
export function unregisterComponent(name: string): void {
- getComponentRegistry().delete(name);
- componentRegistry.delete(name);
+ userComponents().delete(name);
}
function registerToEditor(
@@ -219,18 +213,33 @@ export function isBuiltinComponent(comp: AnyComponentDef): comp is BuiltinCompon
return comp._builtin === true;
}
-const componentRegistry = new Map<string, AnyComponentDef>();
+// Global builtin (C++-backed) component types — defined once at module load and
+// shared across every context. User components are per-AppContext (see above).
+const builtinRegistry = new Map<string, AnyComponentDef>();
export function registerComponent(name: string, def: AnyComponentDef): void {
- componentRegistry.set(name, def);
+ builtinRegistry.set(name, def);
+}
+
+/** Complete catalogue: global builtins + the current context's user components. */
+export function getComponentRegistry(): Map<string, AnyComponentDef> {
+ const all = new Map<string, AnyComponentDef>(builtinRegistry);
+ for (const [name, def] of userComponents()) all.set(name, def);
+ return all;
}
+/** @deprecated Alias of {@link getComponentRegistry}; kept for back-compat. */
export function getAllRegisteredComponents(): Map<string, AnyComponentDef> {
- return componentRegistry;
+ return getComponentRegistry();
+}
+
+/** Just the current context's user/script components (excludes builtins). */
+export function getUserComponents(): Map<string, AnyComponentDef> {
+ return userComponents();
}
export function getComponent(name: string): AnyComponentDef | undefined {
- return componentRegistry.get(name) ?? getUserComponent(name);
+ return builtinRegistry.get(name) ?? userComponents().get(name);
}
function detectColorKeys(defaults: unknown): readonly string[] {
@@ -249,7 +258,7 @@ function detectColorKeys(defaults: unknown): readonly string[] {
}
export function defineBuiltin<T>(name: string, defaults: T, metadata?: ComponentMetadata): BuiltinComponentDef<T> {
- const existing = componentRegistry.get(name);
+ const existing = builtinRegistry.get(name) ?? userComponents().get(name);
if (existing) {
if (existing._builtin) return existing as BuiltinComponentDef<T>;
throw new Error(
@@ -271,7 +280,7 @@ export function defineBuiltin<T>(name: string, defaults: T, metadata?: Component
animatableFields: meta?.animatableFields ?? [],
discoverAssets: metadata?.discoverAssets,
};
- componentRegistry.set(name, def);
+ builtinRegistry.set(name, def);
return def;
}
diff --git a/sdk/src/context.ts b/sdk/src/context.ts
index 8977cbb04..93568302e 100644
--- a/sdk/src/context.ts
+++ b/sdk/src/context.ts
@@ -56,6 +56,17 @@ export class AppContext {
editorBridge: EditorBridge | null = null;
readonly wasmError: WasmErrorState = { handler: null, lastReportTime: 0, suppressedCount: 0 };
+ /**
+ * Run mode. `editorMode` = an editor host is attached (vs a standalone
+ * runtime); `playMode` = within an editor, gameplay is running. Gameplay
+ * systems gate on these via {@link playModeOnly} (`env.ts`). Kept here so
+ * all app-scoped mutable state lives on one context (with componentRegistry
+ * / editorBridge / pendingSystems) rather than in a separate module global,
+ * so isolated Apps get isolated run modes.
+ */
+ editorMode = false;
+ playMode = false;
+
/** @brief Drain all pending systems and clear the queue */
drainPendingSystems(): PendingSystemEntry[] {
const drained = this.pendingSystems.splice(0);
@@ -70,6 +81,8 @@ export class AppContext {
this.wasmError.handler = null;
this.wasmError.lastReportTime = 0;
this.wasmError.suppressedCount = 0;
+ this.editorMode = false;
+ this.playMode = false;
}
}
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index b23f0f82d..80fa34588 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -66,11 +66,15 @@ export {
export {
loadSceneData,
loadSceneWithAssets,
+ resetWorldTo,
loadComponent,
remapEntityFields,
updateCameraAspectRatio,
findEntityByName,
serializeScene,
+ migrateSceneData,
+ SCENE_FORMAT_VERSION,
+ registerSceneComponentCodec,
getComponentAssetFields,
getComponentAssetFieldDescriptors,
getComponentSpineFieldDescriptor,
@@ -78,6 +82,8 @@ export {
type SceneData,
type SceneEntityData,
type SceneComponentData,
+ type SceneMigrationResult,
+ type SceneComponentCodec,
type SceneLoadOptions,
type SceneLoadProgressCallback,
type MissingAssetCallback,
@@ -134,6 +140,12 @@ export {
PREFAB_FORMAT_VERSION,
diffAgainstSource,
validateOverrides,
+ expandInstance,
+ collapseInstance,
+ expandEntry,
+ collapseEntry,
+ rebuildChildren,
+ extractPrefab,
type PrefabEntityId,
type ProcessedEntity,
type FlattenContext,
@@ -143,6 +155,11 @@ export {
type DiffOptions,
type ValidateResult,
type StaleOverride,
+ type AddedEntity,
+ type PrefabInstanceDelta,
+ type PrefabInstanceEntry,
+ type SyncPrefabResolver,
+ type ExtractEntity,
} from './prefab/index';
export { Prefabs, PrefabServer, PrefabsPlugin, prefabsPlugin } from './prefabServer';
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 9321bd3a7..bfa9292bb 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -41,6 +41,8 @@ export { CameraView, CameraViewApi } from './camera/Camera';
export { EditorView, DEFAULT_EDITOR_VIEW } from './camera/EditorView';
export type { EditorViewData } from './camera/EditorView';
export { CameraDirector, setViewTarget, shakeCamera, BlendCurve } from './camera/CameraDirector';
+export { FollowTarget } from './camera/FollowTarget';
+export type { FollowTargetData } from './camera/FollowTarget';
export type { CameraDirectorState } from './camera/CameraDirector';
export type { CameraPOV } from './camera/CameraPlugin';
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index a4aad43ab..e0606b720 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -66,7 +66,9 @@ export {
unregisterComponent,
registerComponent,
getComponent,
+ getComponentRegistry,
getAllRegisteredComponents,
+ getUserComponents,
type ComponentDef,
type BuiltinComponentDef,
type AnyComponentDef,
diff --git a/sdk/src/env.ts b/sdk/src/env.ts
index ace5b727d..79c735345 100644
--- a/sdk/src/env.ts
+++ b/sdk/src/env.ts
@@ -1,26 +1,41 @@
-let editorMode = false;
-let playMode = false;
+/**
+ * @file env.ts
+ * @brief Run-mode accessors (editor vs runtime, edit vs play).
+ *
+ * State lives on {@link AppContext} (see context.ts) so it is app-scoped and
+ * isolates with `setDefaultContext`, rather than as a module global. These
+ * functions are the stable public surface; gameplay systems gate on
+ * {@link playModeOnly}.
+ */
+import { getDefaultContext } from './context';
export function setEditorMode(active: boolean): void {
- editorMode = active;
+ getDefaultContext().editorMode = active;
}
export function isEditor(): boolean {
- return editorMode;
+ return getDefaultContext().editorMode;
}
export function isRuntime(): boolean {
- return !editorMode;
+ return !getDefaultContext().editorMode;
}
export function setPlayMode(active: boolean): void {
- playMode = active;
+ getDefaultContext().playMode = active;
}
export function isPlayMode(): boolean {
- return playMode;
+ return getDefaultContext().playMode;
}
+/**
+ * Run condition for gameplay (simulation-advancing) systems: true outside an
+ * editor, or inside an editor only while play mode is active. In editor edit
+ * mode it returns false, freezing gameplay while render/transform/layout
+ * systems (which do not use this gate) keep ticking.
+ */
export function playModeOnly(): boolean {
- return !editorMode || playMode;
+ const ctx = getDefaultContext();
+ return !ctx.editorMode || ctx.playMode;
}
diff --git a/sdk/src/index.ts b/sdk/src/index.ts
index a94f1c2b9..29d6371d5 100644
--- a/sdk/src/index.ts
+++ b/sdk/src/index.ts
@@ -8,3 +8,9 @@ setPlatform(webAdapter);
export * from './core';
export * from './webAppFactory';
+
+// ABI layout hash of the component schema this SDK bundle was generated from.
+// Exposed so an embedding host (e.g. the editor) can compare it against the
+// wasm build it loads — see desktop EngineGuard. The authoritative, fatal
+// layout check still happens inside the runtime bridge handshake.
+export { ABI_LAYOUT_HASH } from './component.generated';
diff --git a/sdk/src/particle/ParticlePlugin.ts b/sdk/src/particle/ParticlePlugin.ts
index a21a26f68..624663f3e 100644
--- a/sdk/src/particle/ParticlePlugin.ts
+++ b/sdk/src/particle/ParticlePlugin.ts
@@ -2,6 +2,7 @@ import type { App, Plugin } from '../app';
import { defineSystem, Schedule } from '../system';
import { Res } from '../resource';
import { Time, type TimeData } from '../resource';
+import { playModeOnly } from '../env';
import type { ESEngineModule, CppRegistry } from '../wasm';
import { Particle, ParticleAPI } from './ParticleAPI';
@@ -13,13 +14,15 @@ export class ParticlePlugin implements Plugin {
const registry = app.world.getCppRegistry() as CppRegistry;
app.insertResource(Particle, new ParticleAPI(module, registry));
+ // Particle advance is gameplay — frozen in editor edit mode, runs in
+ // play mode / standalone runtime (matches animation/physics/timeline).
app.addSystemToSchedule(Schedule.Update, defineSystem(
[Res(Time), Res(Particle)],
(time: TimeData, particle: ParticleAPI) => {
particle.update(time.delta);
},
{ name: 'ParticleSystem' }
- ));
+ ), { runIf: playModeOnly });
}
}
diff --git a/sdk/src/prefab/index.ts b/sdk/src/prefab/index.ts
index 2e35ad5f2..9ee313bfb 100644
--- a/sdk/src/prefab/index.ts
+++ b/sdk/src/prefab/index.ts
@@ -21,3 +21,19 @@ export { diffAgainstSource } from './diff';
export type { DiffOptions } from './diff';
export { validateOverrides } from './validate';
export type { ValidateResult, StaleOverride } from './validate';
+
+export {
+ expandInstance,
+ collapseInstance,
+ expandEntry,
+ collapseEntry,
+ rebuildChildren,
+ extractPrefab,
+} from './sceneInstance';
+export type {
+ AddedEntity,
+ PrefabInstanceDelta,
+ PrefabInstanceEntry,
+ SyncPrefabResolver,
+ ExtractEntity,
+} from './sceneInstance';
diff --git a/sdk/src/prefab/sceneInstance.ts b/sdk/src/prefab/sceneInstance.ts
new file mode 100644
index 000000000..73c24d91e
--- /dev/null
+++ b/sdk/src/prefab/sceneInstance.ts
@@ -0,0 +1,249 @@
+/**
+ * @file sceneInstance.ts
+ * @brief Prefab instance ⇄ scene-delta boundary (the canonical expand/collapse core)
+ *
+ * A prefab instance is persisted as a DELTA over its prefab asset and lives,
+ * once loaded, as EXPANDED ordinary entities. This module is the lossless
+ * boundary between the two, built on the engine's own prefab data layer
+ * (`flattenPrefab` / `diffAgainstSource`):
+ *
+ * expand: prefab asset + delta → flat instance entities
+ * collapse: flat instance entities → delta
+ *
+ * It is the SINGLE source for that transform — both the runtime scene loader
+ * (`scene.ts` `loadSceneWithAssets`, for `play == ship`) and the editor's
+ * model layer build on it, so the two never diverge.
+ *
+ * A `{prefab, overrides}` pair alone is NOT enough — `PrefabOverride` cannot
+ * express structural edits — so the delta also carries `added` (entities added
+ * under the instance) and `removed` (prefab children deleted in the instance),
+ * sourced from `diffAgainstSource`'s `untracked` / `orphanedSourceIds`. Both
+ * structural buckets reference entities by stable `prefabEntityId`, so the round
+ * trip survives the id reallocation that `flattenPrefab` performs.
+ *
+ * Pure data (no World / wasm) — unit-testable as the data-loss safety net.
+ */
+
+import { flattenPrefab } from './flatten';
+import { diffAgainstSource } from './diff';
+import { cloneComponents } from './clone';
+import { PREFAB_FORMAT_VERSION } from './migrate';
+import type {
+ PrefabData,
+ PrefabEntityData,
+ PrefabOverride,
+ PrefabEntityId,
+ ProcessedEntity,
+ ComponentData,
+} from './types';
+
+/** Sync nested-prefab resolver passed through to `flattenPrefab`. */
+export type SyncPrefabResolver = (path: string) => PrefabData | null;
+
+const NO_NESTED: SyncPrefabResolver = () => null;
+
+/** An entity added under a prefab instance (not part of the prefab asset). */
+export interface AddedEntity {
+ /** Stable instance-local identity (its prefabEntityId — absent from the asset). */
+ prefabEntityId: PrefabEntityId;
+ name: string;
+ components: ComponentData[];
+ visible: boolean;
+ /** Parent by stable id — a prefab entity OR another added entity; null = under the instance root. */
+ parentId: PrefabEntityId | null;
+}
+
+/** The persisted form of a prefab instance: a minimal delta over the asset. */
+export interface PrefabInstanceDelta {
+ /** `@uuid:` ref to the prefab asset. */
+ prefab: string;
+ /** Property / component / name / visibility / metadata edits. */
+ overrides: PrefabOverride[];
+ /** Entities added under the instance (not in the asset). */
+ added: AddedEntity[];
+ /** Prefab children deleted in this instance (by their asset prefabEntityId). */
+ removed: PrefabEntityId[];
+}
+
+/** A prefab instance as it lives in the scene FILE: a delta + where it attaches. */
+export interface PrefabInstanceEntry extends PrefabInstanceDelta {
+ /** The instance root's stable scene source id. */
+ id: number;
+ /** The instance root's scene parent (its attach point), or null = scene root. */
+ parent: number | null;
+}
+
+/**
+ * Expand a prefab asset + instance delta into flat instance entities, allocating
+ * ids via `allocateId`. Reuses `flattenPrefab` (which applies the overrides),
+ * drops `removed` prefab entities, and appends `added` entities re-linked by
+ * their stable parent id. `loadPrefab` resolves nested prefab refs (callers that
+ * know the prefab is flat may omit it).
+ */
+export function expandInstance(
+ prefab: PrefabData,
+ delta: PrefabInstanceDelta,
+ allocateId: () => number,
+ loadPrefab: SyncPrefabResolver = NO_NESTED,
+): { entities: ProcessedEntity[]; rootId: number } {
+ const { entities, rootId } = flattenPrefab(prefab, delta.overrides, {
+ allocateId,
+ loadPrefab,
+ });
+
+ const removed = new Set(delta.removed);
+ const kept = entities.filter((e) => !removed.has(e.prefabEntityId));
+
+ // prefabEntityId → runtime id, for both kept prefab entities and added ones.
+ const idByPrefabId = new Map<PrefabEntityId, number>();
+ for (const e of kept) idByPrefabId.set(e.prefabEntityId, e.id);
+
+ // Allocate added ids first so parent refs resolve regardless of order.
+ const added: ProcessedEntity[] = delta.added.map((a) => {
+ const id = allocateId();
+ idByPrefabId.set(a.prefabEntityId, id);
+ return {
+ id,
+ prefabEntityId: a.prefabEntityId,
+ name: a.name,
+ parent: rootId,
+ children: [],
+ components: a.components,
+ visible: a.visible,
+ };
+ });
+ delta.added.forEach((a, i) => {
+ added[i].parent = a.parentId != null ? (idByPrefabId.get(a.parentId) ?? rootId) : rootId;
+ });
+
+ const all = [...kept, ...added];
+ rebuildChildren(all);
+ return { entities: all, rootId };
+}
+
+/** Rebuild every entity's `children` array from its `parent` link (consistency). */
+export function rebuildChildren(entities: ProcessedEntity[]): void {
+ const byId = new Map(entities.map((e) => [e.id, e]));
+ for (const e of entities) e.children = [];
+ for (const e of entities) {
+ if (e.parent != null) byId.get(e.parent)?.children.push(e.id);
+ }
+}
+
+/**
+ * Collapse expanded instance entities back to a delta. `diffAgainstSource`
+ * yields the override list + the structural buckets (`untracked` → added,
+ * `orphanedSourceIds` → removed), with added parents recorded by stable id.
+ */
+export function collapseInstance(
+ prefab: PrefabData,
+ prefabRef: string,
+ expanded: readonly ProcessedEntity[],
+): PrefabInstanceDelta {
+ const { overrides, untracked, orphanedSourceIds } = diffAgainstSource(prefab, expanded);
+ const byId = new Map(expanded.map((e) => [e.id, e]));
+ const added: AddedEntity[] = untracked.map((u) => ({
+ prefabEntityId: u.prefabEntityId,
+ name: u.name,
+ components: u.components,
+ visible: u.visible,
+ parentId: u.parent != null ? (byId.get(u.parent)?.prefabEntityId ?? null) : null,
+ }));
+ return { prefab: prefabRef, overrides, added, removed: orphanedSourceIds };
+}
+
+// ── Scene-entry boundary ────────────────────────────────────────────────────
+// A prefab instance is ONE entry in the scene file and an expanded subtree in
+// the loaded scene. The instance root keeps a stable scene id across save/load
+// (other entities may parent to it); the internal entities are re-allocated each
+// load.
+
+/**
+ * Expand a scene instance entry into flat entities: flatten the asset + delta,
+ * pin the instance root to the entry's stable `id` (re-allocating only the
+ * internal entities), and attach the root under the entry's scene `parent`.
+ */
+export function expandEntry(
+ prefab: PrefabData,
+ entry: PrefabInstanceEntry,
+ allocateId: () => number,
+ loadPrefab: SyncPrefabResolver = NO_NESTED,
+): { entities: ProcessedEntity[]; rootId: number } {
+ const { entities, rootId } = expandInstance(prefab, entry, allocateId, loadPrefab);
+ // Pin the root to the persisted scene id (external refs target it); internal
+ // entities keep their fresh ids. Remap the root id + any parent pointing at it.
+ for (const e of entities) {
+ if (e.id === rootId) e.id = entry.id;
+ if (e.parent === rootId) e.parent = entry.id;
+ }
+ const root = entities.find((e) => e.id === entry.id);
+ if (root) root.parent = entry.parent; // attach under the scene parent
+ rebuildChildren(entities);
+ return { entities, rootId: entry.id };
+}
+
+/**
+ * Collapse an expanded instance subtree (root `rootId`, attached under
+ * `sceneParent`) back to a scene entry — the inverse of {@link expandEntry}.
+ */
+export function collapseEntry(
+ prefab: PrefabData,
+ prefabRef: string,
+ expanded: readonly ProcessedEntity[],
+ rootId: number,
+ sceneParent: number | null,
+): PrefabInstanceEntry {
+ return { id: rootId, parent: sceneParent, ...collapseInstance(prefab, prefabRef, expanded) };
+}
+
+// ── Authoring: live entities → a new prefab asset ───────────────────────────
+
+/** A scene/model entity subtree, as fed to {@link extractPrefab} (id-keyed). */
+export interface ExtractEntity {
+ id: number;
+ name: string;
+ parent: number | null;
+ children: number[];
+ components: ComponentData[];
+ visible?: boolean;
+}
+
+/**
+ * Build a fresh {@link PrefabData} from a live entity subtree (the inverse of
+ * instantiation — "Create Prefab from selection"). Source ids are remapped to
+ * stable string `prefabEntityId`s (root first → rootEntityId), parent/child
+ * links are remapped within the subtree (the root detaches → parent null), and
+ * components are deep-cloned so the asset owns its own data. Emits the current
+ * prefab format, so no migration runs on load.
+ *
+ * NOTE: component fields that REFERENCE another entity by id are left as-is —
+ * remapping internal entity links to prefab ids is a later refinement; the
+ * common case (no intra-prefab entity refs) round-trips exactly.
+ */
+export function extractPrefab(
+ entities: readonly ExtractEntity[],
+ rootId: number,
+ name: string,
+): PrefabData {
+ // Root first so it gets a deterministic id and reads first in the file.
+ const ordered = [...entities].sort((a, b) => (a.id === rootId ? -1 : b.id === rootId ? 1 : 0));
+ const idMap = new Map<number, string>();
+ ordered.forEach((e, i) => idMap.set(e.id, String(i)));
+ const inSubtree = (sid: number | null): boolean => sid != null && idMap.has(sid);
+
+ const prefabEntities: PrefabEntityData[] = ordered.map((e) => ({
+ prefabEntityId: idMap.get(e.id)!,
+ name: e.name,
+ parent: e.id === rootId ? null : inSubtree(e.parent) ? idMap.get(e.parent!)! : null,
+ children: e.children.filter((c) => idMap.has(c)).map((c) => idMap.get(c)!),
+ components: cloneComponents(e.components),
+ visible: e.visible ?? true,
+ }));
+
+ return {
+ version: PREFAB_FORMAT_VERSION,
+ name,
+ rootEntityId: idMap.get(rootId)!,
+ entities: prefabEntities,
+ };
+}
diff --git a/sdk/src/scene.ts b/sdk/src/scene.ts
index ca579a9d2..18effb36a 100644
--- a/sdk/src/scene.ts
+++ b/sdk/src/scene.ts
@@ -10,7 +10,14 @@ import { discoverSceneAssets } from './asset/discoverAssets';
import { requireResourceManager } from './resourceManager';
import { validateComponentData, formatValidationErrors } from './validation';
import { log } from './logger';
-import { TilemapAPI } from './tilemap/tilemapAPI';
+import {
+ expandEntry,
+ preloadNestedPrefabs,
+ migratePrefabData,
+ type PrefabData,
+ type PrefabInstanceEntry,
+ type ProcessedEntity,
+} from './prefab/index';
// =============================================================================
// Types
@@ -150,15 +157,189 @@ export function remapEntityFields(compData: SceneComponentData, entityMap: Map<n
}
// =============================================================================
-// Scene Migration
+// Component serialization codecs (out-of-band data)
// =============================================================================
-function migrateToUIRenderer(entityData: SceneEntityData): void {
+/**
+ * Hook for a component whose full state does not fit the plain field record —
+ * e.g. TilemapLayer's tile chunks live in a C++ blob. Registered by the owning
+ * plugin (see tilemapPlugin) so the generic (de)serializer carries no
+ * component-specific knowledge.
+ */
+export interface SceneComponentCodec {
+ /** Serialize: write out-of-band state into the plain record. */
+ exportData?(entity: number, data: Record<string, unknown>): void;
+ /**
+ * Out-of-band field keys. Stripped from `data` before validation/insert
+ * (so the component insert doesn't choke on them) and passed to
+ * {@link importData} after insert.
+ */
+ outOfBandFields?: readonly string[];
+ /** Deserialize: reapply out-of-band state after the component is inserted. */
+ importData?(entity: number, outOfBand: Record<string, unknown>): void;
+}
+
+const sceneComponentCodecs = new Map<string, SceneComponentCodec>();
+
+/** Register a custom (de)serializer for a component type. Idempotent. */
+export function registerSceneComponentCodec(type: string, codec: SceneComponentCodec): void {
+ sceneComponentCodecs.set(type, codec);
+}
+
+// =============================================================================
+// Prefab instance entries (REARCH_PREFABS PF1 — runtime play == ship)
+// =============================================================================
+
+// A scene-file entity is either an ordinary entity record or a prefab-instance
+// entry — a minimal delta over a `.esprefab` asset (`{ prefab, overrides, added,
+// removed }`). The runtime expands each instance into ordinary entities via the
+// SAME `flattenPrefab` core the editor uses (`prefab/sceneInstance.ts`), so a
+// saved prefab scene loads identically in the editor and at runtime.
+type SceneEntry = SceneEntityData | PrefabInstanceEntry;
+
+/** True for a prefab-instance entry (carries a `prefab` asset ref). */
+function isPrefabEntry(e: SceneEntry): e is PrefabInstanceEntry {
+ return typeof (e as PrefabInstanceEntry).prefab === 'string';
+}
+
+/** True if any scene entry is a prefab instance (cheap gate before expansion). */
+export function sceneHasPrefabEntries(scene: SceneData): boolean {
+ return (scene.entities as SceneEntry[]).some(isPrefabEntry);
+}
+
+/** Resolves a prefab asset ref to its PrefabData, or null when unresolvable. */
+export type PrefabAssetResolver = (ref: string) => Promise<PrefabData | null>;
+
+const toSceneEntityData = (e: ProcessedEntity): SceneEntityData => ({
+ id: e.id,
+ name: e.name,
+ parent: e.parent,
+ children: e.children,
+ components: e.components,
+ visible: e.visible,
+});
+
+/**
+ * Expand every prefab-instance entry in a scene into ordinary entity records,
+ * leaving non-prefab entities untouched. Each instance is flattened via
+ * `expandEntry` (the shared prefab core) with its nested prefabs preloaded, so
+ * the result is a plain SceneData ready for migration + spawn. Async because
+ * resolving prefab (and nested-prefab) assets is async; an unresolvable prefab
+ * drops that one instance with a warning rather than aborting the whole scene.
+ */
+export async function expandScenePrefabs(
+ scene: SceneData,
+ loadPrefab: PrefabAssetResolver,
+): Promise<SceneData> {
+ const entries = scene.entities as SceneEntry[];
+ // Allocate fresh ids for expanded internals above every id already in the
+ // file, so they never collide with non-prefab entities or instance roots
+ // (which keep their stable scene id across save/load).
+ let nextId = 0;
+ for (const e of entries) nextId = Math.max(nextId, e.id);
+ const allocateId = () => ++nextId;
+
+ const out: SceneEntityData[] = [];
+ for (const entry of entries) {
+ if (!isPrefabEntry(entry)) {
+ out.push(entry);
+ continue;
+ }
+ const raw = await loadPrefab(entry.prefab);
+ if (!raw) {
+ log.warn('scene', `Prefab instance "${entry.prefab}" could not be resolved; instance skipped`);
+ continue;
+ }
+ const prefab = migratePrefabData(raw).data;
+ // Preload nested prefabs into a cache so the sync flatten resolver never
+ // misses — `flattenPrefab` throws on an unresolved nested ref.
+ const cache = new Map<string, PrefabData>();
+ try {
+ await preloadNestedPrefabs(
+ prefab,
+ async (ref) => {
+ const d = await loadPrefab(ref);
+ if (!d) throw new Error(`nested prefab "${ref}" not found`);
+ return migratePrefabData(d).data;
+ },
+ cache,
+ );
+ } catch (e) {
+ log.warn('scene', `Prefab instance "${entry.prefab}" has an unresolved nested prefab; instance skipped (${e})`);
+ continue;
+ }
+ const { entities } = expandEntry(prefab, entry, allocateId, (ref) => cache.get(ref) ?? null);
+ for (const pe of entities) out.push(toSceneEntityData(pe));
+ }
+ return { ...scene, entities: out };
+}
+
+// =============================================================================
+// Scene Migration — versioned, idempotent, non-mutating (mirrors prefab/migrate)
+// =============================================================================
+
+/** Current scene format version. Bump when adding a migration step below. */
+export const SCENE_FORMAT_VERSION = '1.0';
+
+export interface SceneMigrationResult {
+ /** A migrated *copy* — the input is never mutated. */
+ data: SceneData;
+ /** True if any legacy shape was upgraded (callers may prompt a re-save). */
+ migrated: boolean;
+ fromVersion: string;
+ toVersion: string;
+}
+
+const versionNum = (v: string): number => {
+ const n = parseFloat(v);
+ return Number.isFinite(n) ? n : 0;
+};
+
+/**
+ * Upgrade a SceneData to the current format. Total + idempotent: already-current
+ * data returns `migrated: false`; migrations are shape-driven so they no-op on
+ * current scenes. Rejects data newer than this engine. Returns a deep copy, so
+ * loading never mutates the caller's object (snapshots can be reloaded).
+ */
+export function migrateSceneData(raw: SceneData): SceneMigrationResult {
+ if (!raw || typeof raw !== 'object' || !Array.isArray(raw.entities)) {
+ throw new Error('Scene data must have an "entities" array');
+ }
+ const fromVersion = typeof raw.version === 'string' ? raw.version : '1.0';
+ if (versionNum(fromVersion) > versionNum(SCENE_FORMAT_VERSION)) {
+ throw new Error(
+ `Scene format version "${fromVersion}" is newer than this engine supports ` +
+ `("${SCENE_FORMAT_VERSION}"); upgrade the engine to load it.`,
+ );
+ }
+
+ // Scene data is plain JSON — JSON clone is safe on every platform and frees
+ // the migrations/loader below to mutate without touching the caller's input.
+ const data: SceneData = JSON.parse(JSON.stringify(raw)) as SceneData;
+
+ let migrated = false;
+ for (const entity of data.entities) {
+ // Prefab-instance entries carry no `components` to migrate; the async
+ // loader expands them first, so any seen here belong to the sync path
+ // and are left untouched (spawnAndLoadEntities warns + skips them).
+ if (isPrefabEntry(entity)) continue;
+ if (migrateEntityToUIRenderer(entity)) migrated = true;
+ for (const comp of entity.components) {
+ if (normalizeLegacyComponent(comp)) migrated = true;
+ }
+ }
+
+ data.version = SCENE_FORMAT_VERSION;
+ return { data, migrated, fromVersion, toVersion: SCENE_FORMAT_VERSION };
+}
+
+/** Legacy UIRect+Sprite (no UIRenderer) → UIRenderer. Returns true if changed. */
+function migrateEntityToUIRenderer(entityData: SceneEntityData): boolean {
const hasUIRect = entityData.components.some(c => c.type === 'UIRect');
const spriteIdx = entityData.components.findIndex(c => c.type === 'Sprite');
const hasUIRenderer = entityData.components.some(c => c.type === 'UIRenderer');
- if (!hasUIRect || spriteIdx === -1 || hasUIRenderer) return;
+ if (!hasUIRect || spriteIdx === -1 || hasUIRenderer) return false;
const sprite = entityData.components[spriteIdx].data;
const tex = sprite.texture as number | undefined;
@@ -176,6 +357,31 @@ function migrateToUIRenderer(entityData: SceneEntityData): void {
},
});
entityData.components.splice(spriteIdx, 1);
+ return true;
+}
+
+/** Normalize legacy component spellings in place. Returns true if changed. */
+function normalizeLegacyComponent(compData: SceneComponentData): boolean {
+ let changed = false;
+ if (compData.type === 'LocalTransform' || compData.type === 'WorldTransform') {
+ compData.type = 'Transform';
+ changed = true;
+ }
+ if (compData.type === 'UIRect') {
+ const rectData = compData.data as Record<string, unknown>;
+ if (rectData.anchor && !rectData.anchorMin) {
+ rectData.anchorMin = { ...(rectData.anchor as Record<string, unknown>) };
+ rectData.anchorMax = { ...(rectData.anchor as Record<string, unknown>) };
+ delete rectData.anchor;
+ changed = true;
+ }
+ }
+ if (compData.type === 'UIMask') {
+ const maskData = compData.data as Record<string, unknown>;
+ if (maskData.mode === 'scissor') { maskData.mode = 0; changed = true; }
+ else if (maskData.mode === 'stencil') { maskData.mode = 1; changed = true; }
+ }
+ return changed;
}
// =============================================================================
@@ -187,6 +393,13 @@ function spawnAndLoadEntities(world: World, sceneData: SceneData): Map<number, E
for (const entityData of sceneData.entities) {
if (entityData.visible === false) continue;
+ // A prefab-instance entry reaching here means the synchronous path was
+ // used on an unexpanded prefab scene — it has no spawnable components.
+ // Skip it (loadSceneWithAssets is the supported prefab-scene path).
+ if (isPrefabEntry(entityData)) {
+ log.warn('scene', 'Prefab-instance entry skipped in synchronous load; use loadSceneWithAssets to load prefab scenes');
+ continue;
+ }
const entity = world.spawn();
entityMap.set(entityData.id, entity);
world.insert(entity, Name, { value: entityData.name });
@@ -195,7 +408,7 @@ function spawnAndLoadEntities(world: World, sceneData: SceneData): Map<number, E
try {
for (const entityData of sceneData.entities) {
if (entityData.visible === false) continue;
- migrateToUIRenderer(entityData);
+ if (isPrefabEntry(entityData)) continue;
const entity = entityMap.get(entityData.id)!;
for (const compData of entityData.components) {
remapEntityFields(compData, entityMap);
@@ -223,7 +436,25 @@ function spawnAndLoadEntities(world: World, sceneData: SceneData): Map<number, E
}
export function loadSceneData(world: World, sceneData: SceneData): Map<number, Entity> {
- return spawnAndLoadEntities(world, sceneData);
+ const { data } = migrateSceneData(sceneData);
+ return spawnAndLoadEntities(world, data);
+}
+
+/**
+ * Reset the world to a previously-captured scene: despawn every current entity,
+ * then reload `sceneData`. Used for editor play-state isolation (snapshot before
+ * Play via {@link serializeScene}, restore on Stop), level restart, etc. Because
+ * {@link loadSceneData} no longer mutates its input, the same snapshot can be
+ * restored repeatedly. Entity ids change; the returned map is
+ * snapshot-id → new entity for callers that need to remap references/selection.
+ */
+export function resetWorldTo(world: World, sceneData: SceneData): Map<number, Entity> {
+ // getAllEntities returns a fresh array, so despawning as we go is safe; the
+ // valid() guard tolerates despawn cascading to children.
+ for (const entity of world.getAllEntities()) {
+ if (world.valid(entity)) world.despawn(entity);
+ }
+ return loadSceneData(world, sceneData);
}
export async function loadSceneWithAssets(
@@ -231,24 +462,44 @@ export async function loadSceneWithAssets(
sceneData: SceneData,
options?: SceneLoadOptions
): Promise<Map<number, Entity>> {
+ // Expand prefab-instance entries first (via the same flattenPrefab core the
+ // editor uses) so migration + asset resolution + spawn all operate on plain
+ // entities — this is how a saved prefab scene achieves play == ship. The
+ // prefab's own asset refs are resolved by the regular preload below.
+ let scene = sceneData;
+ if (options?.assets && sceneHasPrefabEntries(scene)) {
+ const assets = options.assets;
+ scene = await expandScenePrefabs(scene, async (ref) => {
+ try {
+ const r = await assets.loadPrefab(ref);
+ return (r?.data as PrefabData) ?? null;
+ } catch (e) {
+ log.warn('scene', `Failed to load prefab "${ref}": ${e}`);
+ return null;
+ }
+ });
+ }
+ // Migrate up-front to a private copy; asset resolution + spawn all operate
+ // on it, so the caller's SceneData is never mutated.
+ const { data } = migrateSceneData(scene);
if (options?.assets) {
const assets = options.assets;
- const result = await assets.preloadSceneAssets(sceneData, options.onProgress);
+ const result = await assets.preloadSceneAssets(data, options.onProgress);
if (options.onMissingAssets) {
options.onMissingAssets(result.missing);
}
if (options.abortOnMissingAssets && result.missing.length > 0) {
throw new MissingAssetsError(result.missing);
}
- assets.resolveSceneAssetPaths(sceneData, result);
- applyTextureMetadata(sceneData, result.textureHandles);
+ assets.resolveSceneAssetPaths(data, result);
+ applyTextureMetadata(data, result.textureHandles);
if (options.collectAssets) {
for (const handle of result.materialHandles.values()) {
if (handle) options.collectAssets.materialHandles.add(handle);
}
}
}
- return spawnAndLoadEntities(world, sceneData);
+ return spawnAndLoadEntities(world, data);
}
function applyTextureMetadata(sceneData: SceneData, textureHandles: Map<string, number>): void {
@@ -264,46 +515,38 @@ function applyTextureMetadata(sceneData: SceneData, textureHandles: Map<string,
}
export function loadComponent(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void {
- if (compData.type === 'LocalTransform' || compData.type === 'WorldTransform') {
- compData.type = 'Transform';
+ // Legacy-format normalization happens once up-front in migrateSceneData;
+ // by here compData is already current-shape.
+ const comp = getComponent(compData.type);
+ if (!comp) {
+ const context = entityName ? ` on entity "${entityName}"` : '';
+ log.warn('scene', `Unknown component type: ${compData.type}${context}`);
+ return;
}
- if (compData.type === 'UIRect') {
- const rectData = compData.data as Record<string, unknown>;
- if (rectData.anchor && !rectData.anchorMin) {
- rectData.anchorMin = { ...(rectData.anchor as Record<string, unknown>) };
- rectData.anchorMax = { ...(rectData.anchor as Record<string, unknown>) };
- delete rectData.anchor;
+
+ // Strip out-of-band fields (e.g. TilemapLayer's tile-chunk blob) before
+ // validation/insert so the component insert doesn't choke on them; the
+ // registered codec replays them once the component is in.
+ const codec = sceneComponentCodecs.get(compData.type);
+ let outOfBand: Record<string, unknown> | undefined;
+ if (codec?.outOfBandFields?.length) {
+ for (const field of codec.outOfBandFields) {
+ if (field in compData.data) {
+ (outOfBand ??= {})[field] = compData.data[field];
+ delete compData.data[field];
+ }
}
}
- if (compData.type === 'UIMask') {
- const maskData = compData.data as Record<string, unknown>;
- if (maskData.mode === 'scissor') maskData.mode = 0;
- else if (maskData.mode === 'stencil') maskData.mode = 1;
+
+ const errors = validateComponentData(compData.type, comp._default as Record<string, unknown>, compData.data);
+ if (errors.length > 0) {
+ const context = entityName ? ` (entity "${entityName}")` : '';
+ log.warn('scene', formatValidationErrors(compData.type + context, errors));
}
- const comp = getComponent(compData.type);
- if (comp) {
- // TilemapLayer carries tile chunks out-of-component as a base64 blob
- // alongside the regular field record. Strip it before validation so
- // the insert doesn't choke on the sibling field, then replay the
- // chunks through the C++ import binding once the component is in.
- let tilemapChunks: string | undefined;
- if (compData.type === 'TilemapLayer') {
- const raw = compData.data.chunks;
- if (typeof raw === 'string') tilemapChunks = raw;
- delete compData.data.chunks;
- }
- const errors = validateComponentData(compData.type, comp._default as Record<string, unknown>, compData.data);
- if (errors.length > 0) {
- const context = entityName ? ` (entity "${entityName}")` : '';
- log.warn('scene', formatValidationErrors(compData.type + context, errors));
- }
- world.insert(entity, comp, compData.data);
- if (tilemapChunks !== undefined && tilemapChunks !== '') {
- TilemapAPI.importChunks(entity as unknown as number, tilemapChunks);
- }
- } else {
- const context = entityName ? ` on entity "${entityName}"` : '';
- log.warn('scene', `Unknown component type: ${compData.type}${context}`);
+ world.insert(entity, comp, compData.data);
+
+ if (codec?.importData && outOfBand) {
+ codec.importData(entity as unknown as number, outOfBand);
}
}
@@ -369,10 +612,9 @@ export function serializeScene(world: World, sceneName = 'scene'): SceneData {
const data = world.tryGet(entity, comp);
if (data === null) continue;
const payload = data as Record<string, unknown>;
- if (typeName === 'TilemapLayer') {
- const blob = TilemapAPI.exportChunks(entityNum);
- if (blob) payload.chunks = blob;
- }
+ // Components with out-of-band state (e.g. TilemapLayer chunks) fold
+ // it into the record via their registered codec.
+ sceneComponentCodecs.get(typeName)?.exportData?.(entityNum, payload);
components.push({
type: typeName,
data: payload,
@@ -389,7 +631,7 @@ export function serializeScene(world: World, sceneName = 'scene'): SceneData {
}
return {
- version: '1.0',
+ version: SCENE_FORMAT_VERSION,
name: sceneName,
entities,
};
diff --git a/sdk/src/tilemap/tilemapPlugin.ts b/sdk/src/tilemap/tilemapPlugin.ts
index d9fb719b0..04f015976 100644
--- a/sdk/src/tilemap/tilemapPlugin.ts
+++ b/sdk/src/tilemap/tilemapPlugin.ts
@@ -5,6 +5,7 @@ import { Schedule } from '../system';
import type { SystemDef } from '../system';
import { initTilemapAPI, shutdownTilemapAPI, TilemapAPI } from './tilemapAPI';
import { Tilemap } from './components';
+import { registerSceneComponentCodec } from '../scene';
import { getTilemapSource } from './tilesetCache';
import { getTextureDimensions } from '../resourceManager';
import { Time } from '../resource';
@@ -38,6 +39,23 @@ export class TilemapPlugin implements Plugin {
const module = app.wasmModule as ESEngineModule;
initTilemapAPI(module);
+ // Tile chunks live in a C++ blob, not the component's field record, so
+ // teach the scene (de)serializer to carry them out-of-band instead of
+ // hardcoding TilemapLayer knowledge in scene.ts.
+ registerSceneComponentCodec('TilemapLayer', {
+ exportData: (entity, data) => {
+ const blob = TilemapAPI.exportChunks(entity);
+ if (blob) data.chunks = blob;
+ },
+ outOfBandFields: ['chunks'],
+ importData: (entity, outOfBand) => {
+ const blob = outOfBand.chunks;
+ if (typeof blob === 'string' && blob !== '') {
+ TilemapAPI.importChunks(entity, blob);
+ }
+ },
+ });
+
const world = app.world;
const initializedLayers = this.initializedLayers_;
const animatedLayers = this.animatedLayers_;
diff --git a/sdk/src/timer.ts b/sdk/src/timer.ts
index a8c6039e8..9f3ed98b1 100644
--- a/sdk/src/timer.ts
+++ b/sdk/src/timer.ts
@@ -7,6 +7,7 @@ import { defineResource, Res } from './resource';
import { defineSystem } from './system';
import { Schedule } from './system';
import { Time } from './resource';
+import { playModeOnly } from './env';
import type { Plugin } from './app';
// =============================================================================
@@ -220,6 +221,7 @@ export const timerPlugin: Plugin = {
name: 'Timer',
build(app) {
app.insertResource(TimerRes, new TimerManager());
- app.addSystemToSchedule(Schedule.PreUpdate, timerSystem);
+ // Timers advance game time — frozen in editor edit mode.
+ app.addSystemToSchedule(Schedule.PreUpdate, timerSystem, { runIf: playModeOnly });
},
};
diff --git a/sdk/src/world.ts b/sdk/src/world.ts
index 36d8129a9..e3e671fa7 100644
--- a/sdk/src/world.ts
+++ b/sdk/src/world.ts
@@ -4,7 +4,7 @@
*/
import { Entity, entityGeneration, entityIndex, makeEntity } from './types';
-import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents, getComponentRegistry, Name } from './component';
+import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents, getUserComponents, Name } from './component';
import type { CppRegistry, ESEngineModule } from './wasm';
import { handleWasmError } from './wasmError';
import { BuiltinBridge, convertFromWasm, convertForWasm, type BridgeConnectOptions, type BuiltinMethods } from './ecs/BuiltinBridge';
@@ -576,7 +576,7 @@ export class World {
}
const ids = this.scripts_.getEntityComponentIds(entity);
if (ids) {
- const registry = getComponentRegistry();
+ const registry = getUserComponents();
for (const id of ids) {
for (const [name, def] of registry) {
if (def._id === id) {
diff --git a/sdk/tests/camera-follow.test.ts b/sdk/tests/camera-follow.test.ts
new file mode 100644
index 000000000..af351d28e
--- /dev/null
+++ b/sdk/tests/camera-follow.test.ts
@@ -0,0 +1,34 @@
+/**
+ * @file Camera follow — the damped, dead-zoned follow step (the procedural
+ * per-camera behaviour). Pure math, deterministic.
+ */
+import { describe, it, expect } from 'vitest';
+import { followStep } from '../src/camera/FollowTarget';
+
+describe('followStep', () => {
+ it('snaps to the desired position with no damping and no dead zone', () => {
+ expect(followStep(0, 0, 100, 0, 0, 0, 0.016)).toEqual({ x: 100, y: 0 });
+ });
+
+ it('keeps the target at the dead-zone boundary (snap)', () => {
+ const p = followStep(0, 0, 100, 0, 30, 0, 0.016); // dead zone 30
+ expect(p.x).toBeCloseTo(70); // target now sits 30 units from the camera
+ expect(p.y).toBeCloseTo(0);
+ });
+
+ it('does not move while the target is within the dead zone', () => {
+ expect(followStep(0, 0, 20, 0, 30, 0.25, 0.016)).toEqual({ x: 0, y: 0 });
+ });
+
+ it('damps partially toward the target', () => {
+ const p = followStep(0, 0, 100, 0, 0, 0.25, 0.016);
+ expect(p.x).toBeCloseTo(100 * (1 - Math.exp(-0.016 / 0.25)));
+ });
+
+ it('is frame-rate independent (two dt/2 steps == one dt step)', () => {
+ const a1 = followStep(0, 0, 100, 0, 0, 0.25, 0.016);
+ const a2 = followStep(a1.x, a1.y, 100, 0, 0, 0.25, 0.016);
+ const b = followStep(0, 0, 100, 0, 0, 0.25, 0.032);
+ expect(a2.x).toBeCloseTo(b.x, 5);
+ });
+});
diff --git a/sdk/tests/component.test.ts b/sdk/tests/component.test.ts
index 469a1b555..62fd5cc80 100644
--- a/sdk/tests/component.test.ts
+++ b/sdk/tests/component.test.ts
@@ -5,10 +5,14 @@ import {
defineTag,
getComponent,
getUserComponent,
+ getUserComponents,
+ getComponentRegistry,
+ getAllRegisteredComponents,
getComponentDefaults,
clearUserComponents,
unregisterComponent,
} from '../src/component';
+import { AppContext, getDefaultContext, setDefaultContext } from '../src/context';
describe('Component Registry', () => {
beforeEach(() => {
@@ -226,3 +230,53 @@ describe('Component Registry', () => {
});
});
});
+
+// Two-tier registry invariants: builtins are GLOBAL (one module-level registry),
+// user components are PER-CONTEXT (AppContext) and must not leak across contexts.
+describe('Component registry tiers (builtins global, user per-context)', () => {
+ beforeEach(() => clearUserComponents());
+
+ it('getComponentRegistry merges builtins + the current context user components', () => {
+ const Builtin = defineBuiltin('TierBuiltin', { v: 0 });
+ const User = defineComponent('TierUser', { v: 0 });
+
+ const all = getComponentRegistry();
+ expect(all.get('TierBuiltin')).toBe(Builtin);
+ expect(all.get('TierUser')).toBe(User);
+ // getAllRegisteredComponents is an alias of the complete view.
+ expect(getAllRegisteredComponents().get('TierBuiltin')).toBe(Builtin);
+ // getComponent resolves both tiers.
+ expect(getComponent('TierBuiltin')).toBe(Builtin);
+ expect(getComponent('TierUser')).toBe(User);
+ });
+
+ it('getUserComponents excludes builtins', () => {
+ defineBuiltin('TierBuiltin2', { v: 0 });
+ const User = defineComponent('TierUser2', { v: 0 });
+ const users = getUserComponents();
+ expect(users.get('TierUser2')).toBe(User);
+ expect(users.has('TierBuiltin2')).toBe(false);
+ });
+
+ it('user components do NOT leak across contexts; builtins stay global', () => {
+ const Builtin = defineBuiltin('TierBuiltinGlobal', { v: 0 });
+ defineComponent('TierUserA', { v: 0 });
+ expect(getComponentRegistry().has('TierUserA')).toBe(true);
+
+ const original = getDefaultContext();
+ setDefaultContext(new AppContext());
+ try {
+ // Fresh context: the user component is isolated (no leak)…
+ expect(getComponentRegistry().has('TierUserA')).toBe(false);
+ expect(getUserComponents().has('TierUserA')).toBe(false);
+ // …but the builtin is still globally visible.
+ expect(getComponent('TierBuiltinGlobal')).toBe(Builtin);
+ expect(getComponentRegistry().has('TierBuiltinGlobal')).toBe(true);
+ } finally {
+ setDefaultContext(original);
+ }
+
+ // Restored context still has the original user component.
+ expect(getComponentRegistry().has('TierUserA')).toBe(true);
+ });
+});
diff --git a/sdk/tests/run-mode.test.ts b/sdk/tests/run-mode.test.ts
new file mode 100644
index 000000000..8af350a05
--- /dev/null
+++ b/sdk/tests/run-mode.test.ts
@@ -0,0 +1,83 @@
+/**
+ * @file run-mode.test.ts
+ * @brief Editor/runtime + edit/play run mode (env.ts) gates gameplay systems.
+ *
+ * RC12 §E4: gameplay (simulation-advancing) systems gate on `playModeOnly`,
+ * whose state now lives on AppContext. In editor edit mode they freeze while
+ * edit-safe systems (no gate) keep ticking; in play mode or standalone runtime
+ * they run.
+ */
+import { describe, expect, it, afterEach } from 'vitest';
+import { App } from '../src/app';
+import { Schedule, defineSystem } from '../src/system';
+import { setEditorMode, setPlayMode, isEditor, isPlayMode, isRuntime, playModeOnly } from '../src/env';
+import { getDefaultContext } from '../src/context';
+
+function namedSystem(name: string, trace: string[]) {
+ return defineSystem([], () => { trace.push(name); }, { name });
+}
+
+// Run mode lives on the (process-shared default) AppContext; reset so state
+// never leaks into other test files.
+afterEach(() => {
+ setEditorMode(false);
+ setPlayMode(false);
+});
+
+describe('run mode (env.ts over AppContext)', () => {
+ it('defaults to standalone runtime: not editor, playModeOnly true', () => {
+ expect(isEditor()).toBe(false);
+ expect(isRuntime()).toBe(true);
+ expect(isPlayMode()).toBe(false);
+ expect(playModeOnly()).toBe(true);
+ });
+
+ it('editor edit mode freezes playModeOnly; play mode re-enables it', () => {
+ setEditorMode(true);
+ expect(isEditor()).toBe(true);
+ expect(playModeOnly()).toBe(false); // edit mode → gameplay frozen
+
+ setPlayMode(true);
+ expect(playModeOnly()).toBe(true); // play mode → gameplay runs
+ });
+
+ it('state is backed by AppContext (not a separate module global)', () => {
+ setEditorMode(true);
+ setPlayMode(true);
+ expect(getDefaultContext().editorMode).toBe(true);
+ expect(getDefaultContext().playMode).toBe(true);
+
+ getDefaultContext().reset();
+ expect(isEditor()).toBe(false);
+ expect(isPlayMode()).toBe(false);
+ });
+
+ it('scheduler skips gameplay (playModeOnly) systems in edit mode, keeps edit-safe ticking', async () => {
+ const app = App.new();
+ const trace: string[] = [];
+ app.addSystemToSchedule(Schedule.Update, namedSystem('Gameplay', trace), { runIf: playModeOnly });
+ app.addSystemToSchedule(Schedule.Update, namedSystem('Render', trace)); // edit-safe (no gate)
+
+ // Editor edit mode → only the edit-safe system runs.
+ setEditorMode(true);
+ setPlayMode(false);
+ await app.tick(1 / 60);
+ expect(trace).toEqual(['Render']);
+
+ // Play mode → both run.
+ trace.length = 0;
+ setPlayMode(true);
+ await app.tick(1 / 60);
+ expect(trace.sort()).toEqual(['Gameplay', 'Render']);
+ });
+
+ it('standalone runtime runs gameplay systems regardless of play flag', async () => {
+ const app = App.new();
+ const trace: string[] = [];
+ app.addSystemToSchedule(Schedule.Update, namedSystem('Gameplay', trace), { runIf: playModeOnly });
+
+ // editorMode false (default) → playModeOnly true even with playMode false.
+ await app.tick(1 / 60);
+ expect(trace).toEqual(['Gameplay']);
+ });
+});
diff --git a/sdk/tests/scene-prefab.test.ts b/sdk/tests/scene-prefab.test.ts
new file mode 100644
index 000000000..2fb6c3c69
--- /dev/null
+++ b/sdk/tests/scene-prefab.test.ts
@@ -0,0 +1,288 @@
+/**
+ * @file Runtime prefab-instance scene loading (REARCH_PREFABS PF1 — play == ship).
+ *
+ * A saved scene may carry prefab-instance entries — a minimal delta over a
+ * `.esprefab` asset (`{ prefab, overrides, added, removed }`). The runtime
+ * loader expands them into ordinary entities via the SAME flattenPrefab core
+ * the editor uses, so a prefab scene loads identically in the editor and at
+ * runtime. This pins:
+ * - the delta round-trip `collapse(expand) === delta` (the data-loss net),
+ * - `expandScenePrefabs` (scene → plain scene), and
+ * - `loadSceneWithAssets` actually spawning the expanded instance into a World.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { World } from '../src/world';
+import { createMockModule } from './mocks/wasm';
+import { defineBuiltin } from '../src/component';
+import {
+ loadSceneData,
+ loadSceneWithAssets,
+ expandScenePrefabs,
+ sceneHasPrefabEntries,
+ type SceneData,
+} from '../src/scene';
+import {
+ migratePrefabData,
+ flattenPrefab,
+ expandInstance,
+ collapseInstance,
+ expandEntry,
+ collapseEntry,
+ extractPrefab,
+ type PrefabData,
+ type PrefabInstanceDelta,
+ type PrefabInstanceEntry,
+ type ExtractEntity,
+} from '../src/prefab/index';
+
+defineBuiltin('Transform', {
+ position: { x: 0, y: 0, z: 0 },
+ rotation: { w: 1, x: 0, y: 0, z: 0 },
+ scale: { x: 1, y: 1, z: 1 },
+});
+defineBuiltin('Sprite', {
+ texture: 0,
+ color: { r: 1, g: 1, b: 1, a: 1 },
+});
+
+const REF = '@uuid:turret-0000';
+
+function turretPrefab(): PrefabData {
+ return migratePrefabData({
+ version: '1.0',
+ name: 'Turret',
+ rootEntityId: 'root',
+ entities: [
+ {
+ prefabEntityId: 'root',
+ name: 'Turret',
+ parent: null,
+ children: ['barrel', 'scope'],
+ components: [{ type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } }],
+ visible: true,
+ },
+ {
+ prefabEntityId: 'barrel',
+ name: 'Barrel',
+ parent: 'root',
+ children: [],
+ components: [{ type: 'Sprite', data: { color: { r: 1, g: 1, b: 1, a: 1 } } }],
+ visible: true,
+ },
+ {
+ prefabEntityId: 'scope',
+ name: 'Scope',
+ parent: 'root',
+ children: [],
+ components: [],
+ visible: true,
+ },
+ ],
+ }).data as PrefabData;
+}
+
+/** A minimal Assets stub: no real asset I/O, just a prefab resolver. */
+function mockAssets(prefabs: Record<string, PrefabData | null>) {
+ return {
+ preloadSceneAssets: vi.fn().mockResolvedValue({
+ textureHandles: new Map(),
+ materialHandles: new Map(),
+ fontHandles: new Map(),
+ missing: [],
+ releaseCallbacks: [],
+ }),
+ resolveSceneAssetPaths: vi.fn(),
+ loadPrefab: vi.fn(async (ref: string) => ({ data: prefabs[ref] ?? null })),
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ } as any;
+}
+
+describe('Prefab scene loading (PF1)', () => {
+ // ── The delta round-trip safety net (same invariant the editor pins, now
+ // anchored on the SDK core both sides share). ──
+ it('round-trips overrides + added + removed (collapse∘expand = identity)', () => {
+ const prefab = turretPrefab();
+ const delta: PrefabInstanceDelta = {
+ prefab: REF,
+ overrides: [
+ { prefabEntityId: 'root', type: 'property', componentType: 'Transform', propertyName: 'position', value: { x: 5, y: 0, z: 0 } },
+ { prefabEntityId: 'barrel', type: 'name', value: 'BigBarrel' },
+ { prefabEntityId: 'barrel', type: 'visibility', value: false },
+ ],
+ added: [
+ { prefabEntityId: 'addon1', name: 'Muzzle', components: [{ type: 'Sprite', data: { color: { r: 0, g: 1, b: 0, a: 1 } } }], visible: true, parentId: 'root' },
+ ],
+ removed: ['scope'],
+ };
+
+ let nid = 0;
+ const { entities } = expandInstance(prefab, delta, () => nid++);
+ const back = collapseInstance(prefab, REF, entities);
+
+ expect(back.prefab).toBe(REF);
+ expect(back.removed.sort()).toEqual(['scope']);
+ expect(back.added).toHaveLength(1);
+ expect(back.added[0].prefabEntityId).toBe('addon1');
+ expect(back.added[0].parentId).toBe('root');
+ expect(back.overrides.find((o) => o.type === 'property' && o.prefabEntityId === 'root')?.value).toEqual({ x: 5, y: 0, z: 0 });
+ expect(back.overrides.find((o) => o.type === 'name' && o.prefabEntityId === 'barrel')?.value).toBe('BigBarrel');
+ expect(back.overrides.find((o) => o.type === 'visibility' && o.prefabEntityId === 'barrel')?.value).toBe(false);
+ });
+
+ it('a scene entry round-trips through expandEntry → collapseEntry (root id + parent preserved)', () => {
+ const prefab = turretPrefab();
+ const entry: PrefabInstanceEntry = {
+ id: 100,
+ parent: 7,
+ prefab: REF,
+ overrides: [{ prefabEntityId: 'barrel', type: 'name', value: 'BigBarrel' }],
+ added: [],
+ removed: ['scope'],
+ };
+ let nid = 200;
+ const { entities, rootId } = expandEntry(prefab, entry, () => nid++);
+ const back = collapseEntry(prefab, REF, entities, rootId, entry.parent);
+ expect(back.id).toBe(100);
+ expect(back.parent).toBe(7);
+ expect(back.removed.sort()).toEqual(['scope']);
+ expect(back.overrides.find((o) => o.type === 'name')?.value).toBe('BigBarrel');
+ });
+
+ // ── expandScenePrefabs: scene file (with a prefab entry) → plain scene. ──
+ it('expands a prefab-instance entry into ordinary entities, pinning the root id', async () => {
+ const prefab = turretPrefab();
+ const scene = {
+ version: '1.0',
+ name: 's',
+ entities: [
+ { id: 1, name: 'Ground', parent: null, children: [], components: [], visible: true },
+ { id: 2, prefab: REF, parent: 1, overrides: [{ prefabEntityId: 'root', type: 'property', componentType: 'Transform', propertyName: 'position', value: { x: 5, y: 0, z: 0 } }], added: [], removed: ['scope'] },
+ ],
+ } as unknown as SceneData;
+
+ expect(sceneHasPrefabEntries(scene)).toBe(true);
+ const out = await expandScenePrefabs(scene, async (ref) => (ref === REF ? prefab : null));
+
+ // Ground + (root + barrel); scope removed; no prefab entries remain.
+ expect(out.entities).toHaveLength(3);
+ expect(sceneHasPrefabEntries(out)).toBe(false);
+ const root = out.entities.find((e) => e.id === 2)!; // pinned to the entry id
+ expect(root.name).toBe('Turret');
+ expect(root.parent).toBe(1); // attached under Ground
+ // The position override is baked into the expanded root's Transform.
+ const transform = root.components.find((c) => c.type === 'Transform')!;
+ expect((transform.data.position as { x: number }).x).toBe(5);
+ // No expanded internal id collides with the file ids (1, 2).
+ const barrel = out.entities.find((e) => e.name === 'Barrel')!;
+ expect(barrel.id).toBeGreaterThan(2);
+ expect(barrel.parent).toBe(2);
+ });
+
+ it('drops an instance whose prefab cannot be resolved (no throw)', async () => {
+ const scene = {
+ version: '1.0',
+ name: 's',
+ entities: [
+ { id: 1, name: 'Ground', parent: null, children: [], components: [], visible: true },
+ { id: 2, prefab: '@uuid:missing', parent: null, overrides: [], added: [], removed: [] },
+ ],
+ } as unknown as SceneData;
+ const out = await expandScenePrefabs(scene, async () => null);
+ expect(out.entities.map((e) => e.name)).toEqual(['Ground']);
+ });
+
+ it('passes a scene with no prefab instances through unchanged', async () => {
+ const scene: SceneData = {
+ version: '1.0',
+ name: 's',
+ entities: [{ id: 1, name: 'A', parent: null, children: [], components: [{ type: 'Transform', data: {} }], visible: true }],
+ };
+ expect(sceneHasPrefabEntries(scene)).toBe(false);
+ const out = await expandScenePrefabs(scene, async () => null);
+ expect(out.entities).toHaveLength(1);
+ expect(out.entities[0].name).toBe('A');
+ });
+
+ // ── loadSceneWithAssets: the play == ship path — a prefab scene spawns into
+ // a real World via the same expansion. ──
+ it('loadSceneWithAssets spawns the expanded prefab instance into the World', async () => {
+ createMockModule();
+ const world = new World();
+ const prefab = turretPrefab();
+ const scene = {
+ version: '1.0',
+ name: 's',
+ entities: [
+ { id: 1, name: 'Ground', parent: null, children: [], components: [{ type: 'Transform', data: {} }], visible: true },
+ { id: 2, prefab: REF, parent: null, overrides: [{ prefabEntityId: 'barrel', type: 'name', value: 'BigBarrel' }], added: [], removed: ['scope'] },
+ ],
+ } as unknown as SceneData;
+
+ const assets = mockAssets({ [REF]: prefab });
+ await loadSceneWithAssets(world, scene, { assets });
+
+ expect(assets.loadPrefab).toHaveBeenCalledWith(REF);
+ // Ground + Turret (root) + BigBarrel (barrel); scope removed.
+ expect(world.findEntityByName('Ground')).not.toBeNull();
+ expect(world.findEntityByName('Turret')).not.toBeNull();
+ expect(world.findEntityByName('BigBarrel')).not.toBeNull(); // name override applied
+ expect(world.findEntityByName('Scope')).toBeNull(); // removed
+ });
+
+ // ── extractPrefab: live subtree → a new prefab asset (the authoring path). ──
+ it('extractPrefab builds a PrefabData from a subtree (root first, string ids, detached, deep-cloned)', () => {
+ const subtree: ExtractEntity[] = [
+ { id: 10, name: 'Turret', parent: 5 /* external scene parent */, children: [11, 12], components: [{ type: 'Transform', data: { position: { x: 3, y: 4, z: 0 } } }], visible: true },
+ { id: 11, name: 'Barrel', parent: 10, children: [], components: [{ type: 'Sprite', data: {} }], visible: true },
+ { id: 12, name: 'Scope', parent: 10, children: [], components: [], visible: false },
+ ];
+ const prefab = extractPrefab(subtree, 10, 'Turret');
+
+ expect(prefab.name).toBe('Turret');
+ expect(prefab.rootEntityId).toBe('0');
+ const root = prefab.entities[0];
+ expect(root.prefabEntityId).toBe('0');
+ expect(root.name).toBe('Turret');
+ expect(root.parent).toBeNull(); // detached from the scene parent (5)
+ expect(root.children).toHaveLength(2);
+ const barrel = prefab.entities.find((e) => e.name === 'Barrel')!;
+ expect(barrel.parent).toBe('0'); // remapped within the subtree
+ expect(prefab.entities.find((e) => e.name === 'Scope')!.visible).toBe(false);
+
+ // Components are deep-cloned — mutating the source doesn't leak in.
+ (subtree[0].components[0].data.position as { x: number }).x = 999;
+ expect((root.components[0].data.position as { x: number }).x).toBe(3);
+ });
+
+ it('extract → flatten round-trips: a created prefab instantiates back to the same entities', () => {
+ const subtree: ExtractEntity[] = [
+ { id: 10, name: 'Turret', parent: null, children: [11], components: [{ type: 'Transform', data: { position: { x: 1, y: 2, z: 0 } } }], visible: true },
+ { id: 11, name: 'Barrel', parent: 10, children: [], components: [{ type: 'Sprite', data: {} }], visible: true },
+ ];
+ const prefab = extractPrefab(subtree, 10, 'Turret');
+ let nid = 100;
+ const { entities, rootId } = flattenPrefab(prefab, [], { allocateId: () => nid++, loadPrefab: () => null });
+ expect(entities).toHaveLength(2);
+ expect(entities.find((e) => e.id === rootId)!.name).toBe('Turret');
+ expect(entities.find((e) => e.name === 'Barrel')!.parent).toBe(rootId);
+ });
+
+ it('loadSceneData (sync) skips prefab entries without throwing', () => {
+ createMockModule();
+ const world = new World();
+ const scene = {
+ version: '1.0',
+ name: 's',
+ entities: [
+ { id: 1, name: 'Ground', parent: null, children: [], components: [{ type: 'Transform', data: {} }], visible: true },
+ { id: 2, prefab: REF, parent: null, overrides: [], added: [], removed: [] },
+ ],
+ } as unknown as SceneData;
+
+ const map = expect(() => loadSceneData(world, scene)).not.toThrow();
+ void map;
+ expect(world.findEntityByName('Ground')).not.toBeNull();
+ // The prefab entry is not spawnable synchronously — it is skipped.
+ expect(world.findEntityByName('Turret')).toBeNull();
+ });
+});
diff --git a/sdk/tests/scene.test.ts b/sdk/tests/scene.test.ts
index 0b282fdf1..d7c845abc 100644
--- a/sdk/tests/scene.test.ts
+++ b/sdk/tests/scene.test.ts
@@ -6,10 +6,14 @@ import { INVALID_ENTITY } from '../src/types';
import {
loadSceneData,
loadSceneWithAssets,
+ resetWorldTo,
loadComponent,
remapEntityFields,
findEntityByName,
updateCameraAspectRatio,
+ migrateSceneData,
+ SCENE_FORMAT_VERSION,
+ registerSceneComponentCodec,
getComponentAssetFields,
getComponentAssetFieldDescriptors,
getComponentSpineFieldDescriptor,
@@ -211,86 +215,24 @@ describe('Scene', () => {
expect(transform.position.y).toBe(20);
});
- it('should convert LocalTransform to Transform', () => {
- const entity = world.spawn();
- const compData: SceneComponentData = {
- type: 'LocalTransform',
- data: { position: { x: 5, y: 5, z: 0 } },
- };
- loadComponent(world, entity, compData);
-
- expect(compData.type).toBe('Transform');
- expect(world.has(entity, Transform)).toBe(true);
- });
-
- it('should convert WorldTransform to Transform', () => {
- const entity = world.spawn();
- const compData: SceneComponentData = {
- type: 'WorldTransform',
- data: {},
- };
- loadComponent(world, entity, compData);
-
- expect(compData.type).toBe('Transform');
- });
-
- it('should convert legacy UIRect anchor to anchorMin/anchorMax', () => {
- const entity = world.spawn();
- loadComponent(world, entity, {
- type: 'UIRect',
- data: { anchor: { x: 0.5, y: 0.5 } },
+ it('should carry out-of-band codec fields around insert (strip + replay)', () => {
+ const captured: Record<string, unknown> = {};
+ registerSceneComponentCodec('Sprite', {
+ outOfBandFields: ['_blob'],
+ importData: (_entity, oob) => { captured.blob = oob._blob; },
});
-
- const rect = world.get(entity, UIRect);
- expect(rect.anchorMin).toEqual({ x: 0.5, y: 0.5 });
- expect(rect.anchorMax).toEqual({ x: 0.5, y: 0.5 });
- });
-
- it('should not overwrite existing anchorMin with legacy anchor', () => {
- const compData = {
- type: 'UIRect',
- data: {
- anchor: { x: 0, y: 0 },
- anchorMin: { x: 0.1, y: 0.1 },
- anchorMax: { x: 0.9, y: 0.9 },
- } as Record<string, unknown>,
- };
-
- expect(compData.data.anchorMin).toEqual({ x: 0.1, y: 0.1 });
- expect(compData.data.anchor).toBeDefined();
-
- // When anchorMin exists, anchor field is NOT converted
- // (anchor stays in data, conversion is skipped)
- loadComponent(world, world.spawn(), {
- type: 'UIRect',
- data: { anchorMin: { x: 0.1, y: 0.1 }, anchorMax: { x: 0.9, y: 0.9 } },
- });
-
- const entity = world.getEntitiesWithComponents([UIRect])[0];
- const rect = world.get(entity, UIRect);
- expect(rect.anchorMin).toEqual({ x: 0.1, y: 0.1 });
- });
-
- it('should convert UIMask mode string "scissor" to 0', () => {
- const entity = world.spawn();
- loadComponent(world, entity, {
- type: 'UIMask',
- data: { mode: 'scissor' },
- });
-
- const mask = world.get(entity, UIMask);
- expect(mask.mode).toBe(0);
- });
-
- it('should convert UIMask mode string "stencil" to 1', () => {
const entity = world.spawn();
+ // `_blob` is not a Sprite field; the codec must strip it before
+ // insert (so validation/insert don't choke) and replay it after.
loadComponent(world, entity, {
- type: 'UIMask',
- data: { mode: 'stencil' },
+ type: 'Sprite',
+ data: { texture: 0, _blob: 'XYZ' },
});
- const mask = world.get(entity, UIMask);
- expect(mask.mode).toBe(1);
+ expect(captured.blob).toBe('XYZ');
+ expect(world.has(entity, Sprite)).toBe(true);
+ // Cleanup: unregister so the codec doesn't leak into other tests.
+ registerSceneComponentCodec('Sprite', {});
});
it('should warn for unknown component type', () => {
@@ -325,6 +267,119 @@ describe('Scene', () => {
});
});
+ // =========================================================================
+ // migrateSceneData (versioned, non-mutating)
+ // =========================================================================
+
+ describe('migrateSceneData', () => {
+ const oneCompScene = (comp: SceneComponentData, version = '1.0'): SceneData => ({
+ version,
+ name: 't',
+ entities: [{ id: 0, name: 'E', parent: null, children: [], components: [comp] }],
+ });
+
+ it('converts LocalTransform / WorldTransform to Transform', () => {
+ expect(
+ migrateSceneData(oneCompScene({ type: 'LocalTransform', data: { position: { x: 5, y: 5, z: 0 } } }))
+ .data.entities[0].components[0].type,
+ ).toBe('Transform');
+ expect(
+ migrateSceneData(oneCompScene({ type: 'WorldTransform', data: {} }))
+ .data.entities[0].components[0].type,
+ ).toBe('Transform');
+ });
+
+ it('splits legacy UIRect.anchor into anchorMin/anchorMax', () => {
+ const { data } = migrateSceneData(oneCompScene({ type: 'UIRect', data: { anchor: { x: 0.5, y: 0.5 } } }));
+ const d = data.entities[0].components[0].data;
+ expect(d.anchorMin).toEqual({ x: 0.5, y: 0.5 });
+ expect(d.anchorMax).toEqual({ x: 0.5, y: 0.5 });
+ expect(d.anchor).toBeUndefined();
+ });
+
+ it('does not overwrite an existing anchorMin', () => {
+ const { data } = migrateSceneData(oneCompScene({
+ type: 'UIRect',
+ data: { anchor: { x: 0, y: 0 }, anchorMin: { x: 0.1, y: 0.1 }, anchorMax: { x: 0.9, y: 0.9 } },
+ }));
+ expect(data.entities[0].components[0].data.anchorMin).toEqual({ x: 0.1, y: 0.1 });
+ });
+
+ it('converts UIMask mode strings to ints', () => {
+ expect(migrateSceneData(oneCompScene({ type: 'UIMask', data: { mode: 'scissor' } }))
+ .data.entities[0].components[0].data.mode).toBe(0);
+ expect(migrateSceneData(oneCompScene({ type: 'UIMask', data: { mode: 'stencil' } }))
+ .data.entities[0].components[0].data.mode).toBe(1);
+ });
+
+ it('reports migrated=true for legacy data, false for current', () => {
+ expect(migrateSceneData(oneCompScene({ type: 'LocalTransform', data: {} })).migrated).toBe(true);
+ expect(migrateSceneData(oneCompScene({ type: 'Transform', data: { position: { x: 0, y: 0, z: 0 } } })).migrated).toBe(false);
+ });
+
+ it('stamps the current format version', () => {
+ expect(migrateSceneData(oneCompScene({ type: 'Transform', data: {} }, '0.9')).data.version)
+ .toBe(SCENE_FORMAT_VERSION);
+ });
+
+ it('rejects data newer than the engine supports', () => {
+ expect(() => migrateSceneData({ version: '99.0', name: 't', entities: [] }))
+ .toThrow(/newer than this engine/);
+ });
+
+ it('does not mutate the caller input (snapshots stay reusable)', () => {
+ const input = oneCompScene({ type: 'LocalTransform', data: { position: { x: 5, y: 5, z: 0 } } });
+ migrateSceneData(input);
+ expect(input.entities[0].components[0].type).toBe('LocalTransform');
+ expect(input.version).toBe('1.0');
+ });
+ });
+
+ // =========================================================================
+ // resetWorldTo (play-state restore)
+ // =========================================================================
+
+ describe('resetWorldTo', () => {
+ const snapshot = (): SceneData => ({
+ version: '1.0',
+ name: 'snap',
+ entities: [
+ { id: 0, name: 'A', parent: null, children: [1], components: [{ type: 'Transform', data: { position: { x: 1, y: 2, z: 0 } } }] },
+ { id: 1, name: 'B', parent: 0, children: [], components: [{ type: 'Transform', data: { position: { x: 3, y: 4, z: 0 } } }] },
+ ],
+ });
+
+ it('despawns all entities and reloads the snapshot', () => {
+ const snap = snapshot();
+ loadSceneData(world, snap);
+ expect(world.getAllEntities().length).toBe(2);
+
+ // Mutate the live world (as Play would): add an entity.
+ const extra = world.spawn();
+ world.insert(extra, Transform, { position: { x: 9, y: 9, z: 0 } });
+ expect(world.getAllEntities().length).toBe(3);
+
+ resetWorldTo(world, snap);
+
+ // Extra is gone; A and B are back with their original transforms.
+ const xs = world.getEntitiesWithComponents([Transform])
+ .map(e => world.get(e, Transform).position.x)
+ .sort((a, b) => a - b);
+ expect(xs).toEqual([1, 3]);
+ });
+
+ it('restores repeatedly from the same snapshot (non-mutating)', () => {
+ const snap = snapshot();
+ loadSceneData(world, snap);
+ world.despawn(world.getAllEntities()[0]);
+ resetWorldTo(world, snap);
+ expect(world.getAllEntities().length).toBe(2);
+ world.despawn(world.getAllEntities()[0]);
+ resetWorldTo(world, snap);
+ expect(world.getAllEntities().length).toBe(2);
+ });
+ });
+
// =========================================================================
// loadSceneData (sync)
// =========================================================================
@@ -629,7 +684,7 @@ describe('Scene', () => {
await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
- expect(mockAssets.preloadSceneAssets).toHaveBeenCalledWith(sceneData, undefined);
+ expect(mockAssets.preloadSceneAssets).toHaveBeenCalledTimes(1);
const entity = world.getEntitiesWithComponents([Sprite])[0];
const sprite = world.get(entity, Sprite);
expect(sprite.texture).toBe(42);
@@ -683,7 +738,7 @@ describe('Scene', () => {
await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
- expect(mockAssets.preloadSceneAssets).toHaveBeenCalledWith(sceneData, undefined);
+ expect(mockAssets.preloadSceneAssets).toHaveBeenCalledTimes(1);
});
it('should call preloadSceneAssets for spine assets', async () => {
@@ -708,7 +763,7 @@ describe('Scene', () => {
};
await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
- expect(mockAssets.preloadSceneAssets).toHaveBeenCalledWith(sceneData, undefined);
+ expect(mockAssets.preloadSceneAssets).toHaveBeenCalledTimes(1);
});
it('should handle texture load failure gracefully', async () => {
@@ -861,7 +916,7 @@ describe('Scene', () => {
await loadSceneWithAssets(world, sceneData, { assets: mockAssets });
- expect(mockAssets.preloadSceneAssets).toHaveBeenCalledWith(sceneData, undefined);
+ expect(mockAssets.preloadSceneAssets).toHaveBeenCalledTimes(1);
expect(mockAssets.resolveSceneAssetPaths).toHaveBeenCalled();
});