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.

fix(cocos): a play session that follows another in the same script runtime gets the layer's systems again and none of what the last one loaded

yhha9daba9401c2
diff --git a/sdk/src/cocos/builtinScripts.ts b/sdk/src/cocos/builtinScripts.ts
index 05f3fed33..5fea050f4 100644
--- a/sdk/src/cocos/builtinScripts.ts
+++ b/sdk/src/cocos/builtinScripts.ts
@@ -18,15 +18,27 @@ import { declareDirector } from './director';
import { declareTweenSystem } from './tween';
import { declarePrefabSystem } from './prefabs';
import { declareGameSystem } from './game';
-import { resetClassRegistry } from './registry';
+import { resetClassRegistry, setBuiltinDeclarer } from './registry';
const declared = new WeakSet<object>();
+/** What the layer queued into a context, and the queue's epoch when it did: queued again for each App that takes the queues after that. */
+const queued = new WeakMap<object, { systems: unknown[]; plugins: unknown[]; epoch: number }>();
+
+function requeue(context: ReturnType<typeof getDefaultContext>): void {
+ const kept = queued.get(context);
+ if (!kept || kept.epoch === context.queueEpoch) return;
+ context.pendingSystems.push(...(kept.systems as never[]));
+ context.pendingPlugins.push(...kept.plugins);
+ kept.epoch = context.queueEpoch;
+}
/** Declare the layer's own classes and systems into the current context, once per context. */
export function declareBuiltinScripts(): void {
const context = getDefaultContext();
- if (declared.has(context)) return;
+ if (declared.has(context)) { requeue(context); return; }
declared.add(context);
+ const systemsBefore = context.pendingSystems.length;
+ const pluginsBefore = context.pendingPlugins.length;
// `UITransform` is a view on the engine's rectangle; a scene that holds one needs it registered even in an app without the UI pipeline.
registerComponent('ContentRect', ContentRect);
declareButton();
@@ -36,8 +48,13 @@ export function declareBuiltinScripts(): void {
declareTweenSystem();
declarePrefabSystem();
declareGameSystem();
+ queued.set(context, {
+ systems: context.pendingSystems.slice(systemsBefore), plugins: context.pendingPlugins.slice(pluginsBefore), epoch: context.queueEpoch,
+ });
}
+setBuiltinDeclarer(declareBuiltinScripts);
+
/** Test seam: forget the registry and declare again into the (possibly new) current context. */
export function redeclareBuiltinScripts(): void {
resetClassRegistry();
diff --git a/sdk/src/cocos/host.ts b/sdk/src/cocos/host.ts
index 8f3c8e964..48746fb9b 100644
--- a/sdk/src/cocos/host.ts
+++ b/sdk/src/cocos/host.ts
@@ -24,7 +24,7 @@ import { log } from '../util/logger';
import { Color, Vec2, Vec3 } from './math';
import { Node, setCurrentWorld } from './node';
import {
- COMPONENT_PREFIX, classInfoNamed, classInfoOf, dropInstance, instancesOfClass, instancesOn, nodeOf, registerClassInfo, setActivitySync, setInstantiator, storeInstance,
+ COMPONENT_PREFIX, classInfoNamed, ensureBuiltinsDeclared, classInfoOf, dropInstance, instancesOfClass, instancesOn, nodeOf, registerClassInfo, setActivitySync, setInstantiator, storeInstance,
type ClassInfo, type ComponentCtor, type PropertyKind, type PropertySpec,
} from './registry';
@@ -211,6 +211,7 @@ function destroyInstance(world: World, entity: Entity, ctor: Function, inst: Com
* @param specs The class's `@property` fields, with their kinds settled.
*/
export function declareClass(ctor: ComponentCtor, name: string, raw: RawPropertySpec[]): ClassInfo {
+ ensureBuiltinsDeclared();
// The class's own initializers say what each property starts as, which is what Cocos reads to fill its inspector.
let probe: Record<string, unknown> | null = null;
try { probe = new ctor() as unknown as Record<string, unknown>; } catch { probe = null; }
diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.ts
index 443a6509f..00dd89cae 100644
--- a/sdk/src/cocos/node.ts
+++ b/sdk/src/cocos/node.ts
@@ -54,7 +54,22 @@ function releaseDetached(world: World, entity: Entity): void {
/** The world a script last ran in: what an `await`, a timer or a callback — which run between frames — still belong to. */
let lastWorld: World | null = null;
-export function setCurrentWorld(world: World | null): World | null { const previous = currentWorld; currentWorld = world; if (world) lastWorld = world; return previous; }
+const worldChangeListeners: Array<() => void> = [];
+/**
+ * Run @p fn when scripts begin to run in another world than the one they last ran in. A play session is a world, and a host may keep the
+ * script runtime (its modules, what they kept) from one session to the next: what was kept of the last world names things that are gone.
+ */
+export function onWorldChanged(fn: () => void): void { worldChangeListeners.push(fn); }
+export function setCurrentWorld(world: World | null): World | null {
+ const previous = currentWorld;
+ currentWorld = world;
+ if (world) {
+ const changed = lastWorld !== null && lastWorld !== world;
+ lastWorld = world;
+ if (changed) for (const fn of worldChangeListeners) fn();
+ }
+ return previous;
+}
/**
* The world being run now; between frames (a continuation after an `await`, a timer), the one scripts last ran in, while it is still running.
* Cocos has one running game, so a node made in a callback belongs to it.
diff --git a/sdk/src/cocos/prefabs.ts b/sdk/src/cocos/prefabs.ts
index 846f7dbcf..f478bb0af 100644
--- a/sdk/src/cocos/prefabs.ts
+++ b/sdk/src/cocos/prefabs.ts
@@ -24,7 +24,7 @@ import { loadSceneData, serializeEntityComponents, SCENE_FORMAT_VERSION, type Sc
import type { World } from '../ecs/world';
import type { Entity } from '../types';
import { log } from '../util/logger';
-import { Node, getCurrentWorld, markDetached } from './node';
+import { Node, getCurrentWorld, markDetached, onWorldChanged } from './node';
import { Prefab, preparedPrefabs } from './assets';
const assetsOf = new WeakMap<World, AssetsClass>();
@@ -48,15 +48,22 @@ export function requestPrepare(path: string): void {
if (path && !preparedPrefabs.has(path) && !inFlight.has(path)) wanted.add(path);
}
+/** Drop what the layer kept of the session that ended, and tell whoever else kept something. */
+function endSession(): void {
+ preparedPrefabs.clear();
+ wanted.clear();
+ inFlight.clear();
+ currentAssets = null;
+ for (const fn of sessionListeners) fn();
+}
+// A script that begins to run in another world is in another session, before any frame has told the loader so: a game asks for what it
+// loaded last time at start-up, and must not be handed that.
+onWorldChanged(endSession);
+
/** What the layer kept is of the session that kept it: when the loader has given everything back since, it is dropped. */
function syncSession(assets: AssetsClass): void {
const epoch = assets.epoch;
- if (currentAssets && (currentAssets !== assets || currentEpoch !== epoch)) {
- preparedPrefabs.clear();
- wanted.clear();
- inFlight.clear();
- for (const fn of sessionListeners) fn();
- }
+ if (currentAssets && (currentAssets !== assets || currentEpoch !== epoch)) endSession();
currentAssets = assets;
currentEpoch = epoch;
}
diff --git a/sdk/src/cocos/registry.ts b/sdk/src/cocos/registry.ts
index 81d37b144..2a56ecc41 100644
--- a/sdk/src/cocos/registry.ts
+++ b/sdk/src/cocos/registry.ts
@@ -135,6 +135,19 @@ let instantiator: ((world: World, entity: Entity, ctor: ComponentCtor) => Compon
export function setInstantiator(fn: (world: World, entity: Entity, ctor: ComponentCtor) => Component | null): void {
instantiator = fn;
}
+let builtinDeclarer: (() => void) | null = null;
+export function setBuiltinDeclarer(fn: () => void): void {
+ builtinDeclarer = fn;
+}
+/**
+ * Make sure the layer's own classes and systems are declared in the context now current. The layer declares them once, when it is first
+ * imported; a host that keeps the script runtime from one play session to the next gives the next session a new context and does not
+ * import the layer again, so a game's own classes, declared as its scripts run, ask for them.
+ */
+export function ensureBuiltinsDeclared(): void {
+ builtinDeclarer?.();
+}
+
let activitySync: ((world: World, entity: Entity) => void) | null = null;
export function setActivitySync(fn: (world: World, entity: Entity) => void): void {
activitySync = fn;
diff --git a/sdk/src/ecs/context.ts b/sdk/src/ecs/context.ts
index 960123bca..06c63002d 100644
--- a/sdk/src/ecs/context.ts
+++ b/sdk/src/ecs/context.ts
@@ -72,9 +72,16 @@ export class AppContext {
editorMode = false;
playMode = false;
+ /**
+ * How many times the queues have been taken or cleared. What was declared into them belongs to the App that took them, so a declaration
+ * made once for the context (a layer that is imported once) has to be queued again for the next App when this has moved.
+ */
+ queueEpoch = 0;
+
/** @brief Drain all pending systems and clear the queue */
drainPendingSystems(): PendingSystemEntry[] {
const drained = this.pendingSystems.splice(0);
+ this.queueEpoch++;
return drained;
}
@@ -85,6 +92,7 @@ export class AppContext {
/** @brief Reset all mutable state for a new session */
reset(): void {
+ this.queueEpoch++;
this.pendingSystems.length = 0;
this.pendingPlugins.length = 0;
this.componentRegistry.clear();
diff --git a/sdk/tests/cocos/globals.test.ts b/sdk/tests/cocos/globals.test.ts
index 8f1bcfeb4..db47f3b3e 100644
--- a/sdk/tests/cocos/globals.test.ts
+++ b/sdk/tests/cocos/globals.test.ts
@@ -6,10 +6,13 @@
*/
import { beforeEach, describe, expect, it } from 'vitest';
import {
- Component, EventHandler, Game, KeyCode, Scheduler, Asset, director, reportFrame, Layers, Prefab, Size, View, assetManager, game, macro, resources, screen, setResourceManifest, setVisibleSize, sys, view,
+ Component, EventHandler, Game, KeyCode, Scheduler, Asset, director, reportFrame, Layers, Prefab, Size, View, assetManager, game, macro, resources, screen, setCurrentWorld, setResourceManifest, setVisibleSize, sys, view,
providePrefab,
} from '../../src/cocos';
import { keyCodeOf } from '../../src/cocos/inputApi';
+import { AppContext, setDefaultContext } from '../../src/ecs/context';
+import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';
+import { resetClassRegistry } from '../../src/cocos/registry';
import { setWindowPixels } from '../../src/cocos/ui/screen';
describe('sys', () => {
@@ -271,6 +274,32 @@ describe('Asset', () => {
});
});
+describe('a session that follows another in the same script runtime', () => {
+ it("queues the layer's own systems again for the App that follows, once", () => {
+ const context = new AppContext();
+ setDefaultContext(context);
+ resetClassRegistry();
+ declareBuiltinScripts();
+ const first = context.drainPendingSystems().length;
+ expect(first).toBeGreaterThan(0);
+ // the next App takes the queues from a context that declared the layer once and does not import it again
+ declareBuiltinScripts();
+ expect(context.pendingSystems.length).toBe(first);
+ declareBuiltinScripts();
+ expect(context.pendingSystems.length).toBe(first);
+ });
+
+ it('is not handed what the last one loaded, from the moment scripts run in its world', () => {
+ const first = {} as never, second = {} as never;
+ setCurrentWorld(first);
+ providePrefab('kept.esprefab', { ref: 'kept.esprefab', scene: { version: 4, name: 'kept', entities: [] } as never, rootId: 0, missing: [], release() {} });
+ expect(new Prefab('kept.esprefab')._prepared).toBeDefined();
+ setCurrentWorld(second);
+ expect(new Prefab('kept.esprefab')._prepared).toBeUndefined();
+ setCurrentWorld(null);
+ });
+});
+
describe('a directory with a file the layer cannot load', () => {
it('loads the rest: a directory of configs holds a readme too', async () => {
setResourceManifest({
diff --git a/sdk/tests/cocos/instantiate-wasm.test.ts b/sdk/tests/cocos/instantiate-wasm.test.ts
index 563f58a61..086bf6f70 100644
--- a/sdk/tests/cocos/instantiate-wasm.test.ts
+++ b/sdk/tests/cocos/instantiate-wasm.test.ts
@@ -114,8 +114,9 @@ describe.skipIf(!HAS_WASM)('instantiate and tween on the engine', () => {
it('keeps a switched-off instance switched off after it is parented', async () => {
connect();
- providePrefab('p.esprefab', bullet());
boot();
+ // provided once the session's world is the current one: a prefab provided before it belongs to the session before
+ providePrefab('p.esprefab', bullet());
const made = instantiate(new Prefab('p.esprefab'));
made.active = false;
expect(made.active).toBe(false);