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(scene): a run can start over, and a scene owns what was spawned into it

esengine45b71af60f15
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 13b5d488a..a9eebc4e4 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5583,8 +5583,8 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
-static new (world: World, getAssets: () => AssetsClass): PrefabServer
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -6348,6 +6348,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneCon
loadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>
pause: (name: string) => void
register: (config: SceneConfig) => void
+reload: (options?: TransitionOptions) => Promise<void>
reset: () => void
resume: (name: string) => void
setInitial: (name: string) => void
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 1f5b56406..decc71795 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5766,8 +5766,8 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
-static new (world: World, getAssets: () => AssetsClass): PrefabServer
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -6541,6 +6541,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneCon
loadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>
pause: (name: string) => void
register: (config: SceneConfig) => void
+reload: (options?: TransitionOptions) => Promise<void>
reset: () => void
resume: (name: string) => void
setInitial: (name: string) => void
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 7e5d50dc8..c3db4bb09 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -5578,8 +5578,8 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
-static new (world: World, getAssets: () => AssetsClass): PrefabServer
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -6343,6 +6343,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneCon
loadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>
pause: (name: string) => void
register: (config: SceneConfig) => void
+reload: (options?: TransitionOptions) => Promise<void>
reset: () => void
resume: (name: string) => void
setInitial: (name: string) => void
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 6ffa5239c..7c1b1244b 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -5823,8 +5823,8 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
-static new (world: World, getAssets: () => AssetsClass): PrefabServer
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -6588,6 +6588,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneCon
loadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>
pause: (name: string) => void
register: (config: SceneConfig) => void
+reload: (options?: TransitionOptions) => Promise<void>
reset: () => void
resume: (name: string) => void
setInitial: (name: string) => void
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index eaeffcd0d..47a4a1162 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -5585,8 +5585,8 @@ value: unknown
## PrefabServer — class
```
-instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; }) => Promise<InstantiatePrefabResult>
-static new (world: World, getAssets: () => AssetsClass): PrefabServer
+instantiate: (pathOrAddress: string, options?: { baseUrl?: string; parent?: Entity; overrides?: SpawnOverride[]; scene?: boolean; }) => Promise<InstantiatePrefabResult>
+static new (world: World, getAssets: () => AssetsClass, getScenes?: () => SceneManagerState | null): PrefabServer
static prototype: PrefabServer
```
@@ -6350,6 +6350,7 @@ load: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneCon
loadAdditive: (name: string, onProgress?: SceneLoadProgressCallback) => Promise<SceneContext>
pause: (name: string) => void
register: (config: SceneConfig) => void
+reload: (options?: TransitionOptions) => Promise<void>
reset: () => void
resume: (name: string) => void
setInitial: (name: string) => void
diff --git a/sdk/src/prefab/prefabServer.ts b/sdk/src/prefab/prefabServer.ts
index c59c27b90..8ac33c543 100644
--- a/sdk/src/prefab/prefabServer.ts
+++ b/sdk/src/prefab/prefabServer.ts
@@ -5,6 +5,7 @@ import type { World } from '../ecs/world';
import type { Entity } from '../types';
import type { Assets as AssetsClass } from '../asset/Assets';
import { Assets } from '../asset/AssetPlugin';
+import { SceneManager, type SceneManagerState } from '../scene/sceneManager';
import { defineResource } from '../ecs/resource';
import {
instantiatePrefab,
@@ -22,29 +23,57 @@ export type SpawnOverride = Omit<PrefabOverride, 'prefabEntityId'> & { prefabEnt
export class PrefabServer {
private readonly world_: World;
private readonly getAssets_: () => AssetsClass;
+ private readonly getScenes_: () => SceneManagerState | null;
// Resolved per call, not captured: the play/cooked runtime replaces the
// Assets resource after plugin build (ensureRuntimeAssets), and a captured
// instance would silently bypass its resolveRef/manifest channel.
- constructor(world: World, getAssets: () => AssetsClass) {
+ constructor(
+ world: World,
+ getAssets: () => AssetsClass,
+ getScenes: () => SceneManagerState | null = () => null,
+ ) {
this.world_ = world;
this.getAssets_ = getAssets;
+ this.getScenes_ = getScenes;
}
+ /**
+ * Spawn a prefab into the world. What it spawns belongs to the scene that
+ * was live when it landed, exactly like an entity that scene authored —
+ * ownerless, a bullet or a called minion leaks into the next room. Pass
+ * `scene: false` for something meant to outlive the area it came from.
+ */
async instantiate(pathOrAddress: string, options?: {
baseUrl?: string;
parent?: Entity;
overrides?: SpawnOverride[];
+ scene?: boolean;
}): Promise<InstantiatePrefabResult> {
const assets = this.getAssets_();
const prefabResult = await assets.loadPrefab(pathOrAddress);
const prefab = prefabResult.data as PrefabData;
- return instantiatePrefab(this.world_, prefab, {
+ const result = await instantiatePrefab(this.world_, prefab, {
assets,
assetBaseUrl: options?.baseUrl,
parent: options?.parent,
overrides: resolveSpawnOverrides(prefab, pathOrAddress, options?.overrides),
});
+ if (options?.scene !== false) this.adoptIntoActiveScene_(result);
+ return result;
+ }
+
+ /**
+ * The load is asynchronous, so the scene that asked may already be gone by
+ * the time the entities exist — adopting into whatever is active now is the
+ * only owner that is real, and a switch that already happened takes it.
+ */
+ private adoptIntoActiveScene_(result: InstantiatePrefabResult): void {
+ const scenes = this.getScenes_();
+ const active = scenes?.getActive();
+ const ctx = active ? scenes?.getScene(active) : null;
+ if (!ctx) return;
+ for (const entity of result.entities.values()) ctx.adopt(entity);
}
}
@@ -94,7 +123,11 @@ export class PrefabsPlugin implements Plugin {
dependencies = [Assets];
build(app: App): void {
- app.insertResource(Prefabs, new PrefabServer(app.world, () => app.getResource(Assets)));
+ app.insertResource(Prefabs, new PrefabServer(
+ app.world,
+ () => app.getResource(Assets),
+ () => (app.hasResource(SceneManager) ? app.getResource(SceneManager) : null),
+ ));
}
}
diff --git a/sdk/src/scene/sceneManager.ts b/sdk/src/scene/sceneManager.ts
index 12877be49..2aed1b0b3 100644
--- a/sdk/src/scene/sceneManager.ts
+++ b/sdk/src/scene/sceneManager.ts
@@ -249,6 +249,29 @@ export class SceneManagerState {
}
async switchTo(name: string, options?: TransitionOptions): Promise<void> {
+ return this.switchTo_(name, options, false);
+ }
+
+ /**
+ * Start the active scene over: retire it and bring it back up, entities and
+ * all. `switchTo` cannot express this — asked for the scene already running
+ * it does nothing, which is the right answer for a gate and the wrong one
+ * for every death, retry and restart there is.
+ */
+ async reload(options?: TransitionOptions): Promise<void> {
+ const name = this.activeScene_;
+ if (!name) {
+ log.warn('scene', 'reload() with no active scene');
+ return;
+ }
+ return this.switchTo_(name, options, true);
+ }
+
+ private async switchTo_(
+ name: string,
+ options: TransitionOptions | undefined,
+ reload: boolean,
+ ): Promise<void> {
if (this.transitionController_.isTransitioning() || this.switching_) {
log.warn('scene', `Scene switch already in progress, ignoring switchTo("${name}")`);
return;
@@ -259,7 +282,7 @@ export class SceneManagerState {
this.switching_ = true;
try {
if ((options?.transition ?? 'none') !== 'fade') {
- await this.swapTo_(name, options);
+ await this.swapTo_(name, options, reload);
return;
}
await this.transitionController_.start(
@@ -269,7 +292,7 @@ export class SceneManagerState {
onStart: options?.onStart,
onComplete: options?.onComplete,
},
- () => this.swapTo_(name, options),
+ () => this.swapTo_(name, options, reload),
);
} finally {
this.switching_ = false;
@@ -277,11 +300,15 @@ export class SceneManagerState {
}
/** The swap itself: retire whatever is active, bring `name` up. */
- private async swapTo_(name: string, options?: TransitionOptions): Promise<void> {
+ private async swapTo_(
+ name: string,
+ options?: TransitionOptions,
+ reload = false,
+ ): Promise<void> {
// Read at swap time, not at switchTo time: a fade puts half a second
// between the two, and the scene to retire is the one active NOW.
const outgoing = this.activeScene_;
- if (outgoing && outgoing !== name) {
+ if (outgoing && (reload || outgoing !== name)) {
await this.unload(outgoing, options);
}
await this.load(name);
diff --git a/sdk/tests/prefab-spawn-ownership.test.ts b/sdk/tests/prefab-spawn-ownership.test.ts
new file mode 100644
index 000000000..8cd861ee4
--- /dev/null
+++ b/sdk/tests/prefab-spawn-ownership.test.ts
@@ -0,0 +1,64 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file What a runtime spawn belongs to.
+ *
+ * An entity a scene authored is retired with that scene. One spawned into it
+ * from a prefab — a bullet, a called minion, a dropped pickup — had no owner at
+ * all, so it survived every switch and piled up in whatever room came next. It
+ * now belongs to the scene that was live when it landed.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import type { PrefabData } from '../src/prefab';
+import type { Entity } from '../src/types';
+
+const SPAWNED = [11, 12] as Entity[];
+vi.mock('../src/prefab', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('../src/prefab')>()),
+ instantiatePrefab: async () => ({ root: SPAWNED[0], entities: new Map([[0, SPAWNED[0]], [1, SPAWNED[1]]]) }),
+}));
+
+const { PrefabServer } = await import('../src/prefab/prefabServer');
+
+const PREFAB: PrefabData = {
+ version: '2',
+ name: 'Wisp',
+ rootEntityId: 'root',
+ entities: [
+ { prefabEntityId: 'root', name: 'Wisp', parent: null, children: [], components: {}, visible: true },
+ ],
+} as unknown as PrefabData;
+
+function scenes(active: string | null): { manager: unknown; adopted: Entity[] } {
+ const adopted: Entity[] = [];
+ const ctx = { adopt: (e: Entity) => { adopted.push(e); } };
+ return {
+ manager: {
+ getActive: () => active,
+ getScene: (name: string) => (name === active ? ctx : null),
+ },
+ adopted,
+ };
+}
+
+const spawn = async (active: string | null, opts?: { scene?: boolean }): Promise<Entity[]> => {
+ const { manager, adopted } = scenes(active);
+ const assets = { loadPrefab: async () => ({ data: PREFAB }) };
+ const server = new PrefabServer({} as never, () => assets as never, () => manager as never);
+ await server.instantiate('assets/prefabs/Wisp.esprefab', opts);
+ return adopted;
+};
+
+describe('PrefabServer.instantiate ownership', () => {
+ it('hands every spawned entity to the live scene', async () => {
+ expect(await spawn('spire')).toEqual(SPAWNED);
+ });
+
+ it('leaves the spawn ownerless when asked', async () => {
+ expect(await spawn('spire', { scene: false })).toEqual([]);
+ });
+
+ it('spawns fine with no scene running at all', async () => {
+ expect(await spawn(null)).toEqual([]);
+ });
+});
diff --git a/sdk/tests/scene-switch-parity.test.ts b/sdk/tests/scene-switch-parity.test.ts
index 1776b9c0b..558aa2cc4 100644
--- a/sdk/tests/scene-switch-parity.test.ts
+++ b/sdk/tests/scene-switch-parity.test.ts
@@ -76,9 +76,8 @@ describe.each(MODES)('switchTo ($name)', (mode) => {
}
});
- /** Drive the switch to completion — a fade only advances on updateTransition. */
- async function switchAndSettle(to: string): Promise<void> {
- const done = manager.switchTo(to, mode.options);
+ /** Drive one to completion — a fade only advances on updateTransition. */
+ async function settle(done: Promise<void>): Promise<void> {
for (let i = 0; i < 60 && manager.isTransitioning(); i++) {
manager.updateTransition(0.05);
await Promise.resolve();
@@ -91,6 +90,8 @@ describe.each(MODES)('switchTo ($name)', (mode) => {
}
}
+ const switchAndSettle = (to: string): Promise<void> => settle(manager.switchTo(to, mode.options));
+
it('brings the target up as the active scene', async () => {
await switchAndSettle('alpha');
expect(manager.isActive('alpha'), 'the target never became active').toBe(true);
@@ -123,4 +124,20 @@ describe.each(MODES)('switchTo ($name)', (mode) => {
expect(manager.isActive('alpha')).toBe(true);
expect(app.live.size, 'the active scene was torn down and rebuilt').toBe(before);
});
+
+ // Which is exactly why reload exists: a death, a retry and a restart all
+ // want the scene they are already in, built again from its data.
+ it('reload starts the active scene over', async () => {
+ await switchAndSettle('alpha');
+ const before = [...app.live];
+ await settle(manager.reload(mode.options));
+ expect(manager.isActive('alpha')).toBe(true);
+ expect(app.live.size, 'the rebuilt scene has the wrong population').toBe(before.length);
+ expect([...app.live], 'the entities were kept, so nothing was rebuilt').not.toEqual(before);
+ });
+
+ it('reload with nothing active does nothing', async () => {
+ await settle(manager.reload(mode.options));
+ expect(app.live.size).toBe(0);
+ });
});