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): onLoad waits for the node to be active in the hierarchy, a base of the built-in views (UIRenderer) is found through the one the node holds, and Node.insertChild

yhh6ff8195097d6
diff --git a/sdk/src/cocos/builtins.ts b/sdk/src/cocos/builtins.ts
index f24207240..ac02bd658 100644
--- a/sdk/src/cocos/builtins.ts
+++ b/sdk/src/cocos/builtins.ts
@@ -31,6 +31,15 @@ export function builtinAdapterFor(type: unknown): BuiltinAdapter | undefined {
return adapters.get(type);
}
+/** The adapters of the built-in classes that derive from @p base (`UIRenderer` is the base of `Label` and `Sprite`, and has no view of its own). */
+export function builtinAdaptersDerivedFrom(base: Function): BuiltinAdapter[] {
+ const out: BuiltinAdapter[] = [];
+ for (const [key, adapter] of adapters) {
+ if (typeof key === 'function' && key !== base && key.prototype instanceof base) out.push(adapter);
+ }
+ return out;
+}
+
/** Test seam. */
export function resetBuiltinAdapters(): void {
adapters.clear();
diff --git a/sdk/src/cocos/host.ts b/sdk/src/cocos/host.ts
index 6e5c010c0..a9e414339 100644
--- a/sdk/src/cocos/host.ts
+++ b/sdk/src/cocos/host.ts
@@ -124,11 +124,9 @@ function instantiate(world: World, entity: Entity, ctor: ComponentCtor): Compone
for (const spec of info.props) {
if (spec.name in data) (inst as unknown as Record<string, unknown>)[spec.name] = liveValue(world, spec, data[spec.name]);
}
- inst._loaded = true;
- call(inst, 'onLoad');
- // `start` belongs to the start phase, which runs before the frame's updates; what has no `start` has started
- if (typeof (inst as unknown as { start?: unknown }).start === 'function') awaitStart(world, inst);
- else inst._started = true;
+ // A component added to a node that is not active in the hierarchy (a prefab instance not yet given a parent) is there to be read and set, and
+ // loads when the node becomes active, as in Cocos.
+ if (world.isEntityActive(entity)) loadInstance(world, inst);
return inst;
} finally {
setCurrentWorld(previous);
@@ -136,6 +134,15 @@ function instantiate(world: World, entity: Entity, ctor: ComponentCtor): Compone
}
setInstantiator(instantiate);
+/** Run the load part of a component's life: `onLoad` now, `start` in the start phase. */
+function loadInstance(world: World, inst: Component): void {
+ inst._loaded = true;
+ call(inst, 'onLoad');
+ // `start` belongs to the start phase, which runs before the frame's updates; what has no `start` has started
+ if (typeof (inst as unknown as { start?: unknown }).start === 'function') awaitStart(world, inst);
+ else inst._started = true;
+}
+
/**
* Bring the scripts of a node and everything under it to the state its activity says, at once: the classes it carries are made (`onLoad`)
* while it is active, and `onEnable` / `onDisable` run as the switch changed. `start` and `update` stay with the frame.
@@ -155,6 +162,7 @@ function syncSubtree(world: World, root: Entity): void {
const info = classInfoNamed(type.slice(COMPONENT_PREFIX.length));
if (!info) continue;
const inst = instancesOn(world, entity)?.get(info.ctor) ?? (active ? instantiate(world, entity, info.ctor) : null);
+ if (inst && active && !inst._loaded) loadInstance(world, inst);
if (inst) made.push(inst);
}
const children = world.tryGet(entity, Children)?.entities;
@@ -180,6 +188,7 @@ setActivitySync(syncSubtree);
/** Run the per-frame part of one instance: enable/disable as its activity changes, then `start` once, then the timers and `update`. */
function drive(world: World, entity: Entity, inst: Component, dt: number, fresh = false): void {
const active = inst.enabled && world.isEntityActive(entity);
+ if (active && !inst._loaded) loadInstance(world, inst);
if (active && !inst._enabledApplied) {
inst._enabledApplied = true;
call(inst, 'onEnable');
diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.ts
index 663cae112..b811ae5d2 100644
--- a/sdk/src/cocos/node.ts
+++ b/sdk/src/cocos/node.ts
@@ -22,7 +22,7 @@ import {
type ComponentCtor,
} from './registry';
import type { Component } from './component';
-import { builtinAdapterFor } from './builtins';
+import { builtinAdapterFor, builtinAdaptersDerivedFrom } from './builtins';
/** The world a `new Node()` spawns into: set by whatever is running script code (the host, a test). */
let currentWorld: World | null = null;
@@ -194,6 +194,11 @@ export class Node {
}
addChild(child: Node): void { child.setParent(this); }
+ /** Add @p child at place @p index among this node's children (the end when it is past it). */
+ insertChild(child: Node, index: number): void {
+ child.setParent(this);
+ child.setSiblingIndex(index);
+ }
removeChild(child: Node): void { if (child.parent === this) child.setParent(null); }
removeFromParent(): void { this.setParent(null); }
removeAllChildren(): void { for (const c of this.children) c.setParent(null); }
@@ -421,7 +426,20 @@ export class Node {
return this.subclassInstances_(ctor)[0] as T | undefined ?? null;
}
}
- return (builtinAdapterFor(type)?.get(this._world, this._entity) as T | null | undefined) ?? null;
+ const own = builtinAdapterFor(type)?.get(this._world, this._entity) as T | null | undefined;
+ if (own) return own;
+ // the base of built-in views (`UIRenderer`) is found by the one the node holds
+ return (typeof type === 'function' ? this.derivedViews_(type)[0] : undefined) as T | undefined ?? null;
+ }
+
+ /** The views on this node of the built-in classes that derive from @p base. */
+ private derivedViews_(base: Function): Component[] {
+ const out: Component[] = [];
+ for (const adapter of builtinAdaptersDerivedFrom(base)) {
+ const view = adapter.get(this._world, this._entity);
+ if (view) out.push(view);
+ }
+ return out;
}
getComponents<T extends Component>(type: ComponentCtor<T> | string): T[] {
diff --git a/sdk/tests/cocos/node-wasm.test.ts b/sdk/tests/cocos/node-wasm.test.ts
index 898033994..251abbf87 100644
--- a/sdk/tests/cocos/node-wasm.test.ts
+++ b/sdk/tests/cocos/node-wasm.test.ts
@@ -13,7 +13,7 @@ import type { ESEngineModule } from '../../src/wasm';
import { World } from '../../src/ecs/world';
import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
import { AppContext, setDefaultContext } from '../../src/ecs/context';
-import { Button, Node, Quat, Vec3, director, find, setCurrentWorld } from '../../src/cocos';
+import { Button, Label, Node, Quat, UIRenderer, Vec3, director, find, setCurrentWorld } from '../../src/cocos';
import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';
describe.skipIf(!HAS_WASM)('Node on the engine', () => {
@@ -285,3 +285,40 @@ describe.skipIf(!HAS_WASM)('Node world-space setters', () => {
expect(child.worldPosition.z).toBeCloseTo(1, 5);
});
});
+
+describe.skipIf(!HAS_WASM)('Node.insertChild', () => {
+ let module: ESEngineModule;
+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;
+ let world: World | undefined;
+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });
+ afterEach(() => { setCurrentWorld(null); world?.disconnectCpp(); registry?.delete(); registry = undefined; world = undefined; });
+
+ it('puts a child at the place asked among the others', () => {
+ setDefaultContext(new AppContext());
+ registry = new module.Registry(); world = new World(); world.connectCpp(registry, module); setCurrentWorld(world);
+ const mk = (name: string): Node => { const n = new Node(name); world!.insert(n._entity, Transform); return n; };
+ const parent = mk('p'), a = mk('a'), b = mk('b'), c = mk('c');
+ parent.addChild(a); parent.addChild(b);
+ parent.insertChild(c, 1);
+ expect(parent.children.map((n) => n.name)).toEqual(['a', 'c', 'b']);
+ });
+});
+
+describe.skipIf(!HAS_WASM)('a base of the built-in views', () => {
+ let module: ESEngineModule;
+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;
+ let world: World | undefined;
+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });
+ afterEach(() => { setCurrentWorld(null); world?.disconnectCpp(); registry?.delete(); registry = undefined; world = undefined; });
+
+ it('is found as the Label the node holds, and is nothing on a node with no drawn element', () => {
+ setDefaultContext(new AppContext());
+ registry = new module.Registry(); world = new World(); world.connectCpp(registry, module); setCurrentWorld(world);
+ const n = new Node('n'), bare = new Node('bare');
+ world.insert(n._entity, Transform); world.insert(bare._entity, Transform);
+ const label = n.addComponent(Label)!;
+ expect(n.getComponent(UIRenderer)).toBe(label);
+ expect(n.getComponents(UIRenderer)).toEqual([label]);
+ expect(bare.getComponent(UIRenderer)).toBeNull();
+ });
+});
diff --git a/sdk/tests/cocos/script-active-wasm.test.ts b/sdk/tests/cocos/script-active-wasm.test.ts
index 0d38bf177..f020ceb00 100644
--- a/sdk/tests/cocos/script-active-wasm.test.ts
+++ b/sdk/tests/cocos/script-active-wasm.test.ts
@@ -7,7 +7,7 @@
import { afterEach, beforeAll, describe, expect, it } from 'vitest';
import type { ESEngineModule } from '../../src/wasm';
import { App, flushPendingRegistrations } from '../../src/app/app';
-import { ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
+import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
import { AppContext, setDefaultContext } from '../../src/ecs/context';
import { loadSceneData, SCENE_FORMAT_VERSION } from '../../src/scene/scene';
import type { SceneData } from '../../src/scene/scene';
@@ -153,3 +153,37 @@ describe.skipIf(!HAS_WASM)('a script that switches nodes on and off', () => {
expect(calls).toEqual(['first.load', 'second.load', 'first.enable', 'second.enable']);
});
});
+
+describe.skipIf(!HAS_WASM)('a component added to a node that is not active', () => {
+ let module: ESEngineModule;
+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;
+ let app: App | undefined;
+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });
+ afterEach(() => { setCurrentWorld(null); app?.world.disconnectCpp(); registry?.delete(); app = undefined; registry = undefined; });
+
+ it('loads when the node becomes active, not when it is added, so what its creator sets after addComponent is there for onLoad', () => {
+ setDefaultContext(new AppContext());
+ ensureBuiltinComponentsRegistered();
+ resetClassRegistry();
+ declareBuiltinScripts();
+ const seen: Array<string | null> = [];
+ @_decorator.ccclass('NeedsOwner')
+ class NeedsOwner extends Component {
+ owner: string | null = null;
+ onLoad() { seen.push(this.owner); }
+ }
+ registry = new module.Registry();
+ app = App.new();
+ app.connectCpp(registry as never, module);
+ flushPendingRegistrations(app);
+ setCurrentWorld(app.world);
+ const n = new Node('n');
+ app.world.insert(n._entity, Transform);
+ n.active = false;
+ const comp = n.addComponent(NeedsOwner)!;
+ expect(seen).toEqual([]);
+ comp.owner = 'view';
+ n.active = true;
+ expect(seen).toEqual(['view']);
+ });
+});