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 launched scene has its scripts loaded and enabled before its callback, and the scene before it goes; an instance's mounted components land on the prefab it names; Node.forward/up/right/worldMatrix and the rest of Vec2/Vec3/Quat/Color/Vec4/Mat4 a game calls

yhh4ef7c4fd482d
diff --git a/pipeline/src/import/cocos/convert.ts b/pipeline/src/import/cocos/convert.ts
index 024e23d4f..22f5b1bde 100644
--- a/pipeline/src/import/cocos/convert.ts
+++ b/pipeline/src/import/cocos/convert.ts
@@ -117,8 +117,8 @@ function build(node: CocosNode, ctx: ConvertContext, stack: string[]): XNode {
return { addr: node.id, prefix: '', node: { ...node, children: [] }, children: [] };
}
applyOverrides(sub, node.instance.overrides, ctx);
+ applyMounted(sub, node.instance.mounted, ctx);
if (node.instance.mountedChildren) ctx.report.note('instance-mounted-children', `${ctx.where}: ${node.name}`);
- if (node.instance.mountedComponents) ctx.report.note('instance-mounted-components', `${ctx.where}: ${node.name}`);
if (node.instance.removedComponents) ctx.report.note('instance-removed-components', `${ctx.where}: ${node.name}`);
return lift(sub, node.id);
}
@@ -219,6 +219,30 @@ function applyOverrides(tree: XNode, overrides: CocosOverride[], ctx: ConvertCon
}
}
+/**
+ * The components the instance's file mounts on nodes of the prefab it names. The target is addressed as an override's is; a mounted component
+ * with no node to land on is counted, not lost silently.
+ */
+function applyMounted(tree: XNode, mounted: NonNullable<CocosNode['instance']>['mounted'], ctx: ConvertContext): void {
+ if (mounted.length === 0) return;
+ const nodes = new Map<string, XNode>();
+ const index = (x: XNode): void => {
+ nodes.set(x.addr, x);
+ x.children.forEach(index);
+ };
+ index(tree);
+ for (const m of mounted) {
+ const target = nodes.get(m.target.join(SEP));
+ if (!target) {
+ ctx.report.note('mounted-target-missing', `${ctx.where}: ${m.target.join(SEP)}`);
+ continue;
+ }
+ for (const c of m.components) {
+ target.node.components.push(structuredClone(c));
+ }
+ }
+}
+
function setPath(target: Raw, path: string[], value: unknown): void {
let cur = target;
for (let i = 0; i < path.length - 1; i++) {
@@ -353,8 +377,8 @@ function instanceOverrides(node: CocosNode, ctx: ConvertContext): PrefabOverride
if (!pristine) return null;
const patched = structuredClone(pristine);
applyOverrides(patched, inst.overrides, ctx);
+ applyMounted(patched, inst.mounted, ctx);
if (inst.mountedChildren) ctx.report.note('instance-mounted-children', `${ctx.where}: ${node.name}`);
- if (inst.mountedComponents) ctx.report.note('instance-mounted-components', `${ctx.where}: ${node.name}`);
if (inst.removedComponents) ctx.report.note('instance-removed-components', `${ctx.where}: ${node.name}`);
// Converting both sides is for the difference only; the report counts a component where its own prefab is converted.
const quiet: ConvertContext = { ...ctx, report: new ImportReport() };
diff --git a/pipeline/src/import/cocos/document.ts b/pipeline/src/import/cocos/document.ts
index b272a56ac..24631e6a6 100644
--- a/pipeline/src/import/cocos/document.ts
+++ b/pipeline/src/import/cocos/document.ts
@@ -42,6 +42,11 @@ export interface CocosInstanceRef {
mountedChildren: number;
mountedComponents: number;
removedComponents: number;
+ /**
+ * The components the instance's file adds to nodes of the prefab it names (`mountedComponents`): the target is the `localID` path of a
+ * node, crossing the instances inside the prefab as an override's does.
+ */
+ mounted: Array<{ target: string[]; components: CocosComponent[] }>;
}
export interface CocosNode {
@@ -133,6 +138,15 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocum
duplicateIds++;
return `${id}~${n + 1}`;
};
+ const readComponent = (cref: unknown): CocosComponent | null => {
+ const c = at(cref);
+ if (!c || typeof c.__type__ !== 'string') return null;
+ const cinfo = at(c.__prefab);
+ const cid = safeId((cinfo && typeof cinfo.fileId === 'string' && cinfo.fileId) || (typeof c._id === 'string' && c._id) || `#${indexOf(cref)}`);
+ const data: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(c)) if (!BOOKKEEPING.has(k)) data[k] = v;
+ return { type: c.__type__, id: cid, enabled: c._enabled !== false, data };
+ };
const readNode = (ref: unknown): CocosNode | null => {
const idx = indexOf(ref);
const n = at(ref);
@@ -163,13 +177,8 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocum
for (const cref of rawComponents) nodeAt.set(indexOf(cref), node);
for (const cref of Array.isArray(n._components) ? n._components : []) {
- const c = at(cref);
- if (!c || typeof c.__type__ !== 'string') continue;
- const cinfo = at(c.__prefab);
- const cid = safeId((cinfo && typeof cinfo.fileId === 'string' && cinfo.fileId) || (typeof c._id === 'string' && c._id) || `#${indexOf(cref)}`);
- const data: Record<string, unknown> = {};
- for (const [k, v] of Object.entries(c)) if (!BOOKKEEPING.has(k)) data[k] = v;
- node.components.push({ type: c.__type__, id: cid, enabled: c._enabled !== false, data });
+ const comp = readComponent(cref);
+ if (comp) node.components.push(comp);
}
if (instRaw && info) {
@@ -182,7 +191,16 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocum
overrides.push({ target: t.localID.map((x) => safeId(String(x))), path: o.propertyPath.map(String), value: o.value });
}
const count = (v: unknown): number => (Array.isArray(v) ? v.length : 0);
+ const mounted: CocosInstanceRef['mounted'] = [];
+ for (const mref of Array.isArray(instRaw.mountedComponents) ? instRaw.mountedComponents : []) {
+ const m = at(mref);
+ const t = m ? at(m.targetInfo) : null;
+ if (!m || !t || !Array.isArray(t.localID)) continue;
+ const components = (Array.isArray(m.components) ? m.components : []).map(readComponent).filter((c): c is CocosComponent => c !== null);
+ if (components.length > 0) mounted.push({ target: t.localID.map((x) => safeId(String(x))), components });
+ }
node.instance = {
+ mounted,
asset,
overrides,
mountedChildren: count(instRaw.mountedChildren),
@@ -227,6 +245,9 @@ export function parseCocosDocument(file: unknown, fallbackName = ''): CocosDocum
};
const resolveNode = (node: CocosNode): void => {
for (const c of node.components) for (const [k, v] of Object.entries(c.data)) c.data[k] = resolveRefs(v, new Set());
+ for (const m of node.instance?.mounted ?? []) {
+ for (const c of m.components) for (const [k, v] of Object.entries(c.data)) c.data[k] = resolveRefs(v, new Set());
+ }
node.children.forEach(resolveNode);
};
roots.forEach(resolveNode);
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 464d6b99f..c34a1ff4a 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -31,7 +31,7 @@ import { convertPass, isOutlinePass, type PassConversion } from './effectConvert
* importer that made less (or differently), and is brought up to date when it is opened. Raise it when the converted output changes in a
* way an existing project needs to pick up: a new generated file, a field a document or a manifest now carries.
*/
-export const COCOS_IMPORT_REVISION = 11;
+export const COCOS_IMPORT_REVISION = 12;
/** Whether the project at @p projectRoot was written by an importer of this revision. A project that was not converted has nothing to bring up. */
export function cocosImportIsCurrent(projectRoot: string): boolean {
diff --git a/pipeline/tests/cocos-import.test.ts b/pipeline/tests/cocos-import.test.ts
index 4275b7484..8ff8e5f68 100644
--- a/pipeline/tests/cocos-import.test.ts
+++ b/pipeline/tests/cocos-import.test.ts
@@ -67,7 +67,7 @@ const panelPrefab = [
node('Panel', null, [2, 6], [], 10), // 1
{ __type__: 'cc.Node', _objFlags: 0, _parent: { __id__: 1 }, _prefab: { __id__: 3 } }, // 2 (instance A, untouched)
{ __type__: 'cc.PrefabInfo', root: { __id__: 2 }, asset: { __uuid__: ITEM }, fileId: 'itemRoot', instance: { __id__: 4 } }, // 3
- { __type__: 'cc.PrefabInstance', fileId: 'instA', prefabRootNode: { __id__: 1 }, mountedChildren: [], mountedComponents: [], propertyOverrides: [], removedComponents: [] }, // 4
+ { __type__: 'cc.PrefabInstance', fileId: 'instA', prefabRootNode: { __id__: 1 }, mountedChildren: [], mountedComponents: [{ __id__: 18 }], propertyOverrides: [], removedComponents: [] }, // 4
{ __type__: 'cc.Node', _name: 'pad' }, // 5
{ __type__: 'cc.Node', _objFlags: 0, _parent: { __id__: 1 }, _prefab: { __id__: 7 } }, // 6 (instance B)
{ __type__: 'cc.PrefabInfo', root: { __id__: 6 }, asset: { __uuid__: ITEM }, fileId: 'itemRoot', instance: { __id__: 8 } }, // 7
@@ -82,6 +82,11 @@ const panelPrefab = [
{ __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 14 }, propertyPath: ['_color'], value: { __type__: 'cc.Color', r: 0, g: 255, b: 0, a: 255 } }, // 15
{ __type__: 'cc.TargetInfo', localID: ['lab'] }, // 16
{ __type__: 'CCPropertyOverrideInfo', targetInfo: { __id__: 16 }, propertyPath: ['_string'], value: 'changed' }, // 17
+ // instance A carries a component its file mounted on the item's root: a component the item prefab itself does not have
+ { __type__: 'cc.MountedComponentsInfo', targetInfo: { __id__: 19 }, components: [{ __id__: 20 }] }, // 18
+ { __type__: 'cc.TargetInfo', localID: ['itemRoot'] }, // 19
+ { __type__: 'cc.Button', node: { __id__: 2 }, _enabled: true, __prefab: { __id__: 21 }, _interactable: true, _transition: 0 }, // 20
+ { __type__: 'cc.CompPrefabInfo', fileId: 'mountedButton' }, // 21
];
void instOverrides;
@@ -222,6 +227,14 @@ describe('importing a Cocos project', () => {
expect(kinds).toHaveLength(4);
});
+ it("puts a component the instance's file mounted on the prefab it names, as an added component of that instance", () => {
+ const panel = readJson('assets/cocos/ui/panel.esprefab');
+ const a = panel.entities.find((e: any) => e.prefabEntityId === 'instA');
+ const added = a.nestedPrefab.overrides.filter((o: any) => o.type === 'component_added');
+ expect(added.map((o: any) => `${o.prefabEntityId}:${o.componentType}`)).toEqual(['itemRoot:Cocos.Button']);
+ expect(added[0].componentData.data).toMatchObject({ interactable: true });
+ });
+
it('expands, through the engine\'s own flatten, to what the Cocos instance has', () => {
const panel = readJson('assets/cocos/ui/panel.esprefab');
const item = readJson('assets/cocos/ui/item.esprefab');
diff --git a/sdk/src/cocos/director.ts b/sdk/src/cocos/director.ts
index 31c6cd9fb..5ff3995a1 100644
--- a/sdk/src/cocos/director.ts
+++ b/sdk/src/cocos/director.ts
@@ -18,6 +18,7 @@ import { Node, getCurrentWorld } from './node';
import { Scheduler, scheduler } from './scheduler';
import { SceneManager, type SceneManagerState } from '../scene/sceneManager';
import { listScenes } from './assetManager';
+import { syncActivity } from './registry';
import { SceneAsset } from './assets';
/** The root of the running scene: a stand-in for the parent the world's top-level entities do not have. */
@@ -109,8 +110,13 @@ function runScene(name: string, done?: (error: Error | null, scene?: Scene) => v
(async () => {
const manager = sceneManagerOf(world);
await registerScenes(world, manager);
- await manager.load(name);
- return new Scene(world);
+ // The scene before this one goes (what the game kept stays); asked for the scene already running, it starts over, as Cocos does
+ if (manager.getActive() === name) await manager.reload();
+ else await manager.switchTo(name);
+ const scene = new Scene(world);
+ // The scene is launched with its scripts loaded and enabled: a script added to it right after (as the game does) finds them there
+ for (const root of scene.children) syncActivity(world, root._entity);
+ return scene;
})().then(
(scene) => { loadingScene = ''; director.emit(Director.EVENT_AFTER_SCENE_LAUNCH, scene); done?.(null, scene); },
(error: Error) => { loadingScene = ''; log.warn('cocos', `scene "${name}" did not load: ${String(error.message ?? error)}`); done?.(error); },
diff --git a/sdk/src/cocos/host.ts b/sdk/src/cocos/host.ts
index 7a2d80915..6e5c010c0 100644
--- a/sdk/src/cocos/host.ts
+++ b/sdk/src/cocos/host.ts
@@ -144,11 +144,12 @@ function syncSubtree(world: World, root: Entity): void {
const previous = setCurrentWorld(world);
try {
const stack: Entity[] = [root];
+ // As Cocos activates a tree: every component's `onLoad` first, in node order, then every `onEnable`
+ const made: Component[] = [];
while (stack.length > 0) {
const entity = stack.pop()!;
if (!world.valid(entity)) continue;
const active = world.isEntityActive(entity);
- const made: Component[] = [];
for (const type of world.getComponentTypes(entity)) {
if (!type.startsWith(COMPONENT_PREFIX)) continue;
const info = classInfoNamed(type.slice(COMPONENT_PREFIX.length));
@@ -156,19 +157,20 @@ function syncSubtree(world: World, root: Entity): void {
const inst = instancesOn(world, entity)?.get(info.ctor) ?? (active ? instantiate(world, entity, info.ctor) : null);
if (inst) made.push(inst);
}
- for (const inst of made) {
- const on = inst.enabled && active;
- if (on && !inst._enabledApplied) {
- inst._enabledApplied = true;
- call(inst, 'onEnable');
- } else if (!on && inst._enabledApplied) {
- inst._enabledApplied = false;
- call(inst, 'onDisable');
- }
- }
const children = world.tryGet(entity, Children)?.entities;
if (children) for (let i = children.length - 1; i >= 0; i--) stack.push(children[i]!);
}
+ for (const inst of made) {
+ if (!world.valid(inst._entity)) continue;
+ const on = inst.enabled && world.isEntityActive(inst._entity);
+ if (on && !inst._enabledApplied) {
+ inst._enabledApplied = true;
+ call(inst, 'onEnable');
+ } else if (!on && inst._enabledApplied) {
+ inst._enabledApplied = false;
+ call(inst, 'onDisable');
+ }
+ }
} finally {
setCurrentWorld(previous);
}
diff --git a/sdk/src/cocos/mat4.ts b/sdk/src/cocos/mat4.ts
index 309a638a7..00374e23b 100644
--- a/sdk/src/cocos/mat4.ts
+++ b/sdk/src/cocos/mat4.ts
@@ -32,6 +32,9 @@ export class Vec4 {
}
toString(): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)}, ${this.w.toFixed(2)})`; }
+ static copy(out: Vec4, a: Vec4): Vec4 { out.x = a.x; out.y = a.y; out.z = a.z; out.w = a.w; return out; }
+ static toArray<T extends number[]>(out: T, v: Vec4, ofs = 0): T { out[ofs] = v.x; out[ofs + 1] = v.y; out[ofs + 2] = v.z; out[ofs + 3] = v.w; return out; }
+ static fromArray(out: Vec4, arr: ArrayLike<number>, ofs = 0): Vec4 { out.x = arr[ofs]!; out.y = arr[ofs + 1]!; out.z = arr[ofs + 2]!; out.w = arr[ofs + 3]!; return out; }
static add(out: Vec4, a: Vec4, b: Vec4): Vec4 { out.x = a.x + b.x; out.y = a.y + b.y; out.z = a.z + b.z; out.w = a.w + b.w; return out; }
static subtract(out: Vec4, a: Vec4, b: Vec4): Vec4 { out.x = a.x - b.x; out.y = a.y - b.y; out.z = a.z - b.z; out.w = a.w - b.w; return out; }
static lerp(out: Vec4, a: Vec4, b: Vec4, t: number): Vec4 {
@@ -119,6 +122,46 @@ export class Mat4 {
return out;
}
+ static copy(out: Mat4, a: Mat4): Mat4 { return out.load_(a.a_()); }
+ static strictEquals(a: Mat4, b: Mat4): boolean { const A = a.a_(), B = b.a_(); return A.every((v, i) => v === B[i]); }
+ static toArray<T extends number[]>(out: T, m: Mat4, ofs = 0): T { const a = m.a_(); for (let i = 0; i < 16; i++) out[ofs + i] = a[i]!; return out; }
+ static fromArray(out: Mat4, arr: ArrayLike<number>, ofs = 0): Mat4 {
+ const a = new Array<number>(16);
+ for (let i = 0; i < 16; i++) a[i] = arr[ofs + i]!;
+ return out.load_(a);
+ }
+ static getTranslation(out: Vec3, m: Mat4): Vec3 { return m.getTranslation(out); }
+ static getScaling(out: Vec3, m: Mat4): Vec3 { return m.getScale(out); }
+ static getRotation(out: Quat, m: Mat4): Quat { return m.getRotation(out); }
+ /** Rotation, translation and scale composed (the order Cocos's argument list has them in). */
+ static fromRTS(out: Mat4, q: Quat, t: Vec3, s: Vec3): Mat4 { return Mat4.fromTRS(out, t, q, s); }
+ /** Take a matrix apart into its rotation, translation and scale. */
+ static toRTS(m: Mat4, q: Quat, v: Vec3, s: Vec3): void {
+ m.getScale(s);
+ m.getTranslation(v);
+ m.getRotation(q);
+ }
+ /** @p a turned by @p rad about Y (applied after @p a's own transform, as gl-matrix does). */
+ static rotateY(out: Mat4, a: Mat4, rad: number): Mat4 {
+ const s = Math.sin(rad), c = Math.cos(rad);
+ return Mat4.multiply(out, a, new Mat4(c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1));
+ }
+ static rotateX(out: Mat4, a: Mat4, rad: number): Mat4 {
+ const s = Math.sin(rad), c = Math.cos(rad);
+ return Mat4.multiply(out, a, new Mat4(1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1));
+ }
+ static rotateZ(out: Mat4, a: Mat4, rad: number): Mat4 {
+ const s = Math.sin(rad), c = Math.cos(rad);
+ return Mat4.multiply(out, a, new Mat4(c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1));
+ }
+ /** A perspective projection; @p minClipZ is -1 for GL clip space and 0 for the others. */
+ static perspective(out: Mat4, fov: number, aspect: number, near: number, far: number, isFOVY = true, minClipZ = -1, projectionSignY = 1): Mat4 {
+ const f = 1 / Math.tan(fov / 2), nf = 1 / (near - far);
+ const x = isFOVY ? f / aspect : f;
+ const y = (isFOVY ? f : f * aspect) * projectionSignY;
+ return out.load_([x, 0, 0, 0, 0, y, 0, 0, 0, 0, (far - minClipZ * near) * nf, -1, 0, 0, far * near * nf * (1 - minClipZ), 0]);
+ }
+
static multiply(out: Mat4, a: Mat4, b: Mat4): Mat4 {
const A = a.a_(), B = b.a_(), R = new Array<number>(16);
for (let col = 0; col < 4; col++) {
diff --git a/sdk/src/cocos/math.ts b/sdk/src/cocos/math.ts
index 543b3d958..0385f0143 100644
--- a/sdk/src/cocos/math.ts
+++ b/sdk/src/cocos/math.ts
@@ -30,6 +30,9 @@ export class Vec2 {
lengthSqr(): number { return this.x * this.x + this.y * this.y; }
normalize(): this { const l = this.length(); if (l > 0) { this.x /= l; this.y /= l; } return this; }
dot(v: Vec2): number { return this.x * v.x + this.y * v.y; }
+ lerp(to: Vec2, ratio: number): this { this.x += (to.x - this.x) * ratio; this.y += (to.y - this.y) * ratio; return this; }
+ multiply(v: Vec2): this { this.x *= v.x; this.y *= v.y; return this; }
+ angle(v: Vec2): number { return Vec2.angle(this, v); }
equals(v: Vec2, epsilon = 1e-6): boolean { return Math.abs(this.x - v.x) <= epsilon && Math.abs(this.y - v.y) <= epsilon; }
toString(): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)})`; }
@@ -38,6 +41,17 @@ export class Vec2 {
static subtract(out: Vec2, a: Vec2, b: Vec2): Vec2 { out.x = a.x - b.x; out.y = a.y - b.y; return out; }
static multiplyScalar(out: Vec2, a: Vec2, s: number): Vec2 { out.x = a.x * s; out.y = a.y * s; return out; }
static lerp(out: Vec2, a: Vec2, b: Vec2, t: number): Vec2 { out.x = a.x + (b.x - a.x) * t; out.y = a.y + (b.y - a.y) * t; return out; }
+ static set(out: Vec2, x: number, y: number): Vec2 { out.x = x; out.y = y; return out; }
+ static copy(out: Vec2, a: Vec2): Vec2 { out.x = a.x; out.y = a.y; return out; }
+ static len(a: Vec2): number { return Math.hypot(a.x, a.y); }
+ static dot(a: Vec2, b: Vec2): number { return a.x * b.x + a.y * b.y; }
+ static squaredDistance(a: Vec2, b: Vec2): number { return (a.x - b.x) ** 2 + (a.y - b.y) ** 2; }
+ /** The angle between two vectors, in radians; 0 if either has no length. */
+ static angle(a: Vec2, b: Vec2): number {
+ const m = Math.hypot(a.x, a.y) * Math.hypot(b.x, b.y);
+ return m === 0 ? 0 : Math.acos(Math.min(Math.max((a.x * b.x + a.y * b.y) / m, -1), 1));
+ }
+ static normalize(out: Vec2, a: Vec2): Vec2 { out.x = a.x; out.y = a.y; return out.normalize(); }
}
export class Vec3 {
@@ -88,6 +102,16 @@ export class Vec3 {
this.x = y * v.z - z * v.y; this.y = z * v.x - x * v.z; this.z = x * v.y - y * v.x;
return this;
}
+ lerp(to: Vec3, ratio: number): this { this.x += (to.x - this.x) * ratio; this.y += (to.y - this.y) * ratio; this.z += (to.z - this.z) * ratio; return this; }
+ multiply(v: Vec3): this { this.x *= v.x; this.y *= v.y; this.z *= v.z; return this; }
+ divide(v: Vec3): this { this.x /= v.x; this.y /= v.y; this.z /= v.z; return this; }
+ clampf(min: Vec3, max: Vec3): this {
+ this.x = Math.min(Math.max(this.x, min.x), max.x); this.y = Math.min(Math.max(this.y, min.y), max.y); this.z = Math.min(Math.max(this.z, min.z), max.z);
+ return this;
+ }
+ /** The angle to @p v, in radians; 0 if either has no length. */
+ angle(v: Vec3): number { return Vec3.angle(this, v); }
+ strictEquals(v: Vec3): boolean { return this.x === v.x && this.y === v.y && this.z === v.z; }
equals(v: Vec3, epsilon = 1e-6): boolean {
return Math.abs(this.x - v.x) <= epsilon && Math.abs(this.y - v.y) <= epsilon && Math.abs(this.z - v.z) <= epsilon;
}
@@ -103,6 +127,46 @@ export class Vec3 {
out.x = a.x + (b.x - a.x) * t; out.y = a.y + (b.y - a.y) * t; out.z = a.z + (b.z - a.z) * t;
return out;
}
+ static clone(a: Vec3): Vec3 { return new Vec3(a.x, a.y, a.z); }
+ static set(out: Vec3, x: number, y: number, z: number): Vec3 { out.x = x; out.y = y; out.z = z; return out; }
+ static zero(out: Vec3): Vec3 { out.x = 0; out.y = 0; out.z = 0; return out; }
+ static len(a: Vec3): number { return Math.hypot(a.x, a.y, a.z); }
+ static lengthSqr(a: Vec3): number { return a.x * a.x + a.y * a.y + a.z * a.z; }
+ static squaredDistance(a: Vec3, b: Vec3): number { return (a.x - b.x) ** 2 + (a.y - b.y) ** 2 + (a.z - b.z) ** 2; }
+ static dot(a: Vec3, b: Vec3): number { return a.x * b.x + a.y * b.y + a.z * b.z; }
+ static multiply(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = a.x * b.x; out.y = a.y * b.y; out.z = a.z * b.z; return out; }
+ static divide(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = a.x / b.x; out.y = a.y / b.y; out.z = a.z / b.z; return out; }
+ static negate(out: Vec3, a: Vec3): Vec3 { out.x = -a.x; out.y = -a.y; out.z = -a.z; return out; }
+ static inverse(out: Vec3, a: Vec3): Vec3 { out.x = 1 / a.x; out.y = 1 / a.y; out.z = 1 / a.z; return out; }
+ static min(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = Math.min(a.x, b.x); out.y = Math.min(a.y, b.y); out.z = Math.min(a.z, b.z); return out; }
+ static max(out: Vec3, a: Vec3, b: Vec3): Vec3 { out.x = Math.max(a.x, b.x); out.y = Math.max(a.y, b.y); out.z = Math.max(a.z, b.z); return out; }
+ static clampf(out: Vec3, a: Vec3, min: Vec3, max: Vec3): Vec3 {
+ out.x = Math.min(Math.max(a.x, min.x), max.x); out.y = Math.min(Math.max(a.y, min.y), max.y); out.z = Math.min(Math.max(a.z, min.z), max.z);
+ return out;
+ }
+ /** @p a plus @p b scaled by @p scale. */
+ static scaleAndAdd(out: Vec3, a: Vec3, b: Vec3, scale: number): Vec3 {
+ out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; out.z = a.z + b.z * scale;
+ return out;
+ }
+ static cross(out: Vec3, a: Vec3, b: Vec3): Vec3 {
+ const x = a.y * b.z - a.z * b.y, y = a.z * b.x - a.x * b.z, z = a.x * b.y - a.y * b.x;
+ out.x = x; out.y = y; out.z = z;
+ return out;
+ }
+ /** The angle between two vectors, in radians; 0 if either has no length. */
+ static angle(a: Vec3, b: Vec3): number {
+ const m = Math.hypot(a.x, a.y, a.z) * Math.hypot(b.x, b.y, b.z);
+ return m === 0 ? 0 : Math.acos(Math.min(Math.max((a.x * b.x + a.y * b.y + a.z * b.z) / m, -1), 1));
+ }
+ static equals(a: Vec3, b: Vec3, epsilon = 1e-6): boolean {
+ return Math.abs(a.x - b.x) <= epsilon * Math.max(1, Math.abs(a.x), Math.abs(b.x))
+ && Math.abs(a.y - b.y) <= epsilon * Math.max(1, Math.abs(a.y), Math.abs(b.y))
+ && Math.abs(a.z - b.z) <= epsilon * Math.max(1, Math.abs(a.z), Math.abs(b.z));
+ }
+ static strictEquals(a: Vec3, b: Vec3): boolean { return a.x === b.x && a.y === b.y && a.z === b.z; }
+ static toArray<T extends number[]>(out: T, v: Vec3, ofs = 0): T { out[ofs] = v.x; out[ofs + 1] = v.y; out[ofs + 2] = v.z; return out; }
+ static fromArray(out: Vec3, arr: ArrayLike<number>, ofs = 0): Vec3 { out.x = arr[ofs]!; out.y = arr[ofs + 1]!; out.z = arr[ofs + 2]!; return out; }
}
export class Quat {
@@ -175,6 +239,75 @@ export class Quat {
return out;
}
+ static copy(out: Quat, a: Quat): Quat { out.x = a.x; out.y = a.y; out.z = a.z; out.w = a.w; return out; }
+ static set(out: Quat, x: number, y: number, z: number, w: number): Quat { out.x = x; out.y = y; out.z = z; out.w = w; return out; }
+ static dot(a: Quat, b: Quat): number { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; }
+ static normalize(out: Quat, a: Quat): Quat {
+ const len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
+ if (len > 0) {
+ const k = 1 / Math.sqrt(len);
+ out.x = a.x * k; out.y = a.y * k; out.z = a.z * k; out.w = a.w * k;
+ } else {
+ out.x = 0; out.y = 0; out.z = 0; out.w = 0;
+ }
+ return out;
+ }
+ /** The inverse of a rotation (its conjugate over its squared length). */
+ static invert(out: Quat, a: Quat): Quat {
+ const dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w;
+ const inv = dot ? 1 / dot : 0;
+ out.x = -a.x * inv; out.y = -a.y * inv; out.z = -a.z * inv; out.w = a.w * inv;
+ return out;
+ }
+ static conjugate(out: Quat, a: Quat): Quat { out.x = -a.x; out.y = -a.y; out.z = -a.z; out.w = a.w; return out; }
+ static fromAxisAngle(out: Quat, axis: Vec3, rad: number): Quat {
+ const half = rad * 0.5, s = Math.sin(half);
+ out.x = s * axis.x; out.y = s * axis.y; out.z = s * axis.z; out.w = Math.cos(half);
+ return out;
+ }
+ /** The rotation that turns +Z to @p view with @p up (default +Y) kept upright, as Cocos's `lookAt` builds it. */
+ static fromViewUp(out: Quat, view: Vec3, up: Vec3 = Vec3.UP): Quat {
+ if (view.x * view.x + view.y * view.y + view.z * view.z < 1e-12) return Quat.set(out, 0, 0, 0, 1);
+ const right = Vec3.normalize(new Vec3(), Vec3.cross(new Vec3(), up, view));
+ if (right.lengthSqr() < 1e-12) return Quat.set(out, 0, 0, 0, 1);
+ const upper = Vec3.cross(new Vec3(), view, right);
+ // the columns right / upper / view, as a rotation matrix
+ const m00 = right.x, m01 = right.y, m02 = right.z, m03 = upper.x, m04 = upper.y, m05 = upper.z, m06 = view.x, m07 = view.y, m08 = view.z;
+ const trace = m00 + m04 + m08;
+ if (trace > 0) {
+ const k = 0.5 / Math.sqrt(trace + 1);
+ out.w = 0.25 / k; out.x = (m05 - m07) * k; out.y = (m06 - m02) * k; out.z = (m01 - m03) * k;
+ } else if (m00 > m04 && m00 > m08) {
+ const k = 2 * Math.sqrt(1 + m00 - m04 - m08);
+ out.w = (m05 - m07) / k; out.x = 0.25 * k; out.y = (m01 + m03) / k; out.z = (m06 + m02) / k;
+ } else if (m04 > m08) {
+ const k = 2 * Math.sqrt(1 + m04 - m00 - m08);
+ out.w = (m06 - m02) / k; out.x = (m01 + m03) / k; out.y = 0.25 * k; out.z = (m05 + m07) / k;
+ } else {
+ const k = 2 * Math.sqrt(1 + m08 - m00 - m04);
+ out.w = (m01 - m03) / k; out.x = (m06 + m02) / k; out.y = (m05 + m07) / k; out.z = 0.25 * k;
+ }
+ return Quat.normalize(out, out);
+ }
+ /** The shortest rotation from direction @p a to direction @p b (both unit length). */
+ static rotationTo(out: Quat, a: Vec3, b: Vec3): Quat {
+ const dot = a.dot(b);
+ if (dot < -0.999999) {
+ const axis = Vec3.cross(new Vec3(), Vec3.RIGHT, a);
+ if (axis.length() < 1e-6) Vec3.cross(axis, Vec3.UP, a);
+ axis.normalize();
+ return Quat.fromAxisAngle(out, axis, Math.PI);
+ }
+ if (dot > 0.999999) return Quat.set(out, 0, 0, 0, 1);
+ const axis = Vec3.cross(new Vec3(), a, b);
+ return Quat.normalize(out, Quat.set(out, axis.x, axis.y, axis.z, 1 + dot));
+ }
+ static fromArray(out: Quat, arr: ArrayLike<number>, ofs = 0): Quat { out.x = arr[ofs]!; out.y = arr[ofs + 1]!; out.z = arr[ofs + 2]!; out.w = arr[ofs + 3]!; return out; }
+ static toArray<T extends number[]>(out: T, q: Quat, ofs = 0): T { out[ofs] = q.x; out[ofs + 1] = q.y; out[ofs + 2] = q.z; out[ofs + 3] = q.w; return out; }
+ static equals(a: Quat, b: Quat, epsilon = 1e-6): boolean {
+ return Math.abs(a.x - b.x) <= epsilon && Math.abs(a.y - b.y) <= epsilon && Math.abs(a.z - b.z) <= epsilon && Math.abs(a.w - b.w) <= epsilon;
+ }
+
static multiply(out: Quat, a: Quat, b: Quat): Quat {
const x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;
const y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;
@@ -206,6 +339,19 @@ export class Color {
clone(): Color { return new Color(this.r, this.g, this.b, this.a); }
equals(c: Color): boolean { return this.r === c.r && this.g === c.g && this.b === c.b && this.a === c.a; }
+ /** The channels of @p c as 0..1 floats written to @p out at @p ofs. */
+ static toArray<T extends number[]>(out: T, c: Color, ofs = 0): T {
+ out[ofs] = c.r / 255; out[ofs + 1] = c.g / 255; out[ofs + 2] = c.b / 255; out[ofs + 3] = c.a / 255;
+ return out;
+ }
+ static lerp(out: Color, from: Color, to: Color, ratio: number): Color {
+ out.r = from.r + ratio * (to.r - from.r); out.g = from.g + ratio * (to.g - from.g);
+ out.b = from.b + ratio * (to.b - from.b); out.a = from.a + ratio * (to.a - from.a);
+ return out;
+ }
+ static copy(out: Color, a: Color): Color { return out.set(a); }
+ static fromHEX(out: Color, hex: string): Color { return out.fromHEX(hex); }
+
/** From `#rgb`, `#rrggbb` or `#rrggbbaa`. */
fromHEX(hex: string): this {
let h = hex.replace(/^#/, '');
diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.ts
index e98910ab6..8c6dbc228 100644
--- a/sdk/src/cocos/node.ts
+++ b/sdk/src/cocos/node.ts
@@ -16,6 +16,7 @@ import { setEntityActive } from '../ecs/entityUtils';
import type { World } from '../ecs/world';
import { INVALID_ENTITY, type Entity } from '../types';
import { Quat, Vec3 } from './math';
+import { Mat4 } from './mat4';
import {
COMPONENT_PREFIX, classInfoNamed, classInfoOf, ensureInstance, instancesOn, nodeOf, setNodeFactory, syncActivity,
type ComponentCtor,
@@ -302,6 +303,16 @@ export class Node {
get worldPosition(): Vec3 { const p = this.composedTransform_().worldPosition; return new Vec3(p.x, p.y, p.z); }
set worldPosition(v: Vec3) { this.setWorldPosition(v); }
getWorldRotation(out?: Quat): Quat { const q = this.composedTransform_().worldRotation; return (out ?? new Quat()).set(q.x, q.y, q.z, q.w); }
+ /** The node's world transform as a matrix (translation, rotation and scale composed). */
+ get worldMatrix(): Mat4 { return this.getWorldMatrix(); }
+ getWorldMatrix(out: Mat4 = new Mat4()): Mat4 {
+ const t = this.composedTransform_();
+ return Mat4.fromTRS(out, t.worldPosition as Vec3, t.worldRotation as Quat, t.worldScale as Vec3);
+ }
+ /** The world-space directions of this node's axes: forward is -Z, as in Cocos. */
+ get forward(): Vec3 { return Vec3.transformQuat(new Vec3(), new Vec3(0, 0, -1), this.composedTransform_().worldRotation); }
+ get up(): Vec3 { return Vec3.transformQuat(new Vec3(), new Vec3(0, 1, 0), this.composedTransform_().worldRotation); }
+ get right(): Vec3 { return Vec3.transformQuat(new Vec3(), new Vec3(1, 0, 0), this.composedTransform_().worldRotation); }
getWorldPosition(out?: Vec3): Vec3 { const p = this.composedTransform_().worldPosition; return (out ?? new Vec3()).set(p.x, p.y, p.z); }
/** Place this node so its world position is @p x. Under a parent that is rotated or scaled, the local position is solved for. */
diff --git a/sdk/tests/cocos/math.test.ts b/sdk/tests/cocos/math.test.ts
new file mode 100644
index 000000000..f8d3f6e0b
--- /dev/null
+++ b/sdk/tests/cocos/math.test.ts
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The value types a script reaches for, in the forms Cocos has them: what a game's own code calls (`tempVec3.lerp`, `Vec3.scaleAndAdd`,
+ * `Quat.fromViewUp`, `Mat4.fromRTS`, `Color.toArray`) must exist and give the numbers Cocos gives.
+ */
+import { describe, expect, it } from 'vitest';
+import { Color, Mat4, Quat, Vec2, Vec3, Vec4 } from '../../src/cocos';
+
+describe('Vec3', () => {
+ it('lerps itself toward another by a ratio', () => {
+ const v = new Vec3(0, 10, -4).lerp(new Vec3(10, 20, 4), 0.5);
+ expect([v.x, v.y, v.z]).toEqual([5, 15, 0]);
+ });
+
+ it('multiplies, divides and clamps in place', () => {
+ const v = new Vec3(2, 4, 6).multiply(new Vec3(2, 2, 2)).divide(new Vec3(4, 4, 4)).clampf(new Vec3(0, 0, 0), new Vec3(1, 1, 1));
+ expect([v.x, v.y, v.z]).toEqual([1, 1, 1]);
+ });
+
+ it('has the static forms a script writes with an out parameter', () => {
+ const out = new Vec3();
+ expect(Vec3.scaleAndAdd(out, new Vec3(1, 1, 1), new Vec3(0, 2, 0), 3)).toBe(out);
+ expect([out.x, out.y, out.z]).toEqual([1, 7, 1]);
+ expect(Vec3.cross(new Vec3(), Vec3.RIGHT, Vec3.UP).z).toBe(1);
+ expect(Vec3.dot(new Vec3(1, 2, 3), new Vec3(4, 5, 6))).toBe(32);
+ expect(Vec3.squaredDistance(new Vec3(), new Vec3(1, 2, 2))).toBe(9);
+ expect(Vec3.angle(Vec3.RIGHT, Vec3.UP)).toBeCloseTo(Math.PI / 2, 6);
+ expect(Vec3.angle(Vec3.ZERO, Vec3.UP)).toBe(0);
+ expect(Vec3.min(new Vec3(), new Vec3(1, 5, 3), new Vec3(2, 4, 3)).y).toBe(4);
+ expect(Vec3.max(new Vec3(), new Vec3(1, 5, 3), new Vec3(2, 4, 3)).x).toBe(2);
+ expect(Vec3.toArray([], new Vec3(1, 2, 3))).toEqual([1, 2, 3]);
+ expect(Vec3.clone(new Vec3(1, 2, 3)).equals(new Vec3(1, 2, 3))).toBe(true);
+ expect(Vec3.equals(new Vec3(1, 2, 3), new Vec3(1, 2, 3.0000001))).toBe(true);
+ });
+});
+
+describe('Vec2', () => {
+ it('sets, measures and takes the angle between', () => {
+ const v = Vec2.set(new Vec2(), 3, 4);
+ expect(Vec2.len(v)).toBe(5);
+ expect(Vec2.angle(new Vec2(1, 0), new Vec2(0, 1))).toBeCloseTo(Math.PI / 2, 6);
+ expect(new Vec2(0, 0).lerp(new Vec2(10, 20), 0.25).y).toBe(5);
+ });
+});
+
+describe('Quat', () => {
+ it('inverts, conjugates and normalizes as Cocos does', () => {
+ const q = Quat.fromEuler(new Quat(), 10, 20, 30);
+ const inv = Quat.invert(new Quat(), q);
+ const id = Quat.multiply(new Quat(), q, inv);
+ expect(id.w).toBeCloseTo(1, 6);
+ expect(Math.abs(id.x) + Math.abs(id.y) + Math.abs(id.z)).toBeLessThan(1e-6);
+ const c = Quat.conjugate(new Quat(), q);
+ expect([c.x, c.w]).toEqual([-q.x, q.w]);
+ expect(Quat.dot(q, q)).toBeCloseTo(1, 6);
+ expect(Quat.normalize(new Quat(), new Quat(0, 0, 0, 2)).w).toBe(1);
+ });
+
+ it('makes a rotation from an axis and an angle', () => {
+ const q = Quat.fromAxisAngle(new Quat(), Vec3.UP, Math.PI / 2);
+ const v = Vec3.transformQuat(new Vec3(), Vec3.RIGHT, q);
+ expect(v.z).toBeCloseTo(-1, 6);
+ });
+
+ it('turns +z to the view direction with up kept upright (fromViewUp)', () => {
+ const view = new Vec3(1, 0, 0);
+ const q = Quat.fromViewUp(new Quat(), view);
+ const z = Vec3.transformQuat(new Vec3(), new Vec3(0, 0, 1), q);
+ expect(z.x).toBeCloseTo(1, 6);
+ const up = Vec3.transformQuat(new Vec3(), Vec3.UP, q);
+ expect(up.y).toBeCloseTo(1, 6);
+ expect(Quat.fromViewUp(new Quat(), Vec3.ZERO).w).toBe(1);
+ });
+
+ it('is the shortest rotation between two directions (rotationTo)', () => {
+ const q = Quat.rotationTo(new Quat(), Vec3.RIGHT, Vec3.UP);
+ const v = Vec3.transformQuat(new Vec3(), Vec3.RIGHT, q);
+ expect(v.y).toBeCloseTo(1, 6);
+ const opposite = Quat.rotationTo(new Quat(), Vec3.RIGHT, new Vec3(-1, 0, 0));
+ expect(Vec3.transformQuat(new Vec3(), Vec3.RIGHT, opposite).x).toBeCloseTo(-1, 6);
+ expect(Quat.rotationTo(new Quat(), Vec3.UP, Vec3.UP).w).toBe(1);
+ });
+
+ it('reads from and writes to arrays', () => {
+ expect(Quat.toArray([], new Quat(1, 2, 3, 4))).toEqual([1, 2, 3, 4]);
+ expect(Quat.fromArray(new Quat(), [0, 0, 0, 0, 5, 6, 7, 8], 4).w).toBe(8);
+ });
+});
+
+describe('Mat4', () => {
+ it('composes rotation, translation and scale (fromRTS) and takes them apart again (toRTS)', () => {
+ const q = Quat.fromEuler(new Quat(), 0, 90, 0);
+ const m = Mat4.fromRTS(new Mat4(), q, new Vec3(1, 2, 3), new Vec3(2, 2, 2));
+ const rq = new Quat(), rv = new Vec3(), rs = new Vec3();
+ Mat4.toRTS(m, rq, rv, rs);
+ expect([rv.x, rv.y, rv.z]).toEqual([1, 2, 3]);
+ expect(rs.x).toBeCloseTo(2, 6);
+ expect(Math.abs(Quat.dot(q, rq))).toBeCloseTo(1, 6);
+ expect(Mat4.getTranslation(new Vec3(), m).z).toBe(3);
+ });
+
+ it('turns about Y after the matrix it is given (rotateY)', () => {
+ const m = Mat4.rotateY(new Mat4(), new Mat4(), Math.PI / 2);
+ const p = Vec3.transformMat4(new Vec3(), Vec3.RIGHT, m);
+ expect(p.z).toBeCloseTo(-1, 6);
+ });
+
+ it('is a GL perspective projection', () => {
+ const m = Mat4.perspective(new Mat4(), Math.PI / 2, 2, 1, 11);
+ expect(m.m00).toBeCloseTo(0.5, 6);
+ expect(m.m05).toBeCloseTo(1, 6);
+ expect(m.m10).toBeCloseTo(-1.2, 6);
+ expect(m.m11).toBe(-1);
+ expect(m.m14).toBeCloseTo(-2.2, 6);
+ });
+
+ it('copies, compares and moves through arrays', () => {
+ const a = Mat4.fromTranslation(new Mat4(), new Vec3(1, 2, 3));
+ const b = Mat4.copy(new Mat4(), a);
+ expect(Mat4.strictEquals(a, b)).toBe(true);
+ const arr = Mat4.toArray([], a);
+ expect(arr.length).toBe(16);
+ expect(Mat4.fromArray(new Mat4(), arr).m13).toBe(2);
+ });
+});
+
+describe('Vec4 and Color', () => {
+ it('writes a Vec4 into an array', () => {
+ expect(Vec4.toArray([], new Vec4(1, 2, 3, 4))).toEqual([1, 2, 3, 4]);
+ expect(Vec4.copy(new Vec4(), new Vec4(1, 2, 3, 4)).w).toBe(4);
+ });
+
+ it('writes a Color as 0..1 floats, lerps, and reads hex statically', () => {
+ expect(Color.toArray([], new Color(255, 0, 51, 255))).toEqual([1, 0, 0.2, 1]);
+ const mid = Color.lerp(new Color(), new Color(0, 0, 0, 0), new Color(200, 100, 50, 255), 0.5);
+ expect([mid.r, mid.g, mid.b]).toEqual([100, 50, 25]);
+ const c = Color.fromHEX(new Color(), '#ff8000');
+ expect([c.r, c.g, c.b, c.a]).toEqual([255, 128, 0, 255]);
+ });
+});
diff --git a/sdk/tests/cocos/node-wasm.test.ts b/sdk/tests/cocos/node-wasm.test.ts
index 6f788011d..ffb72264f 100644
--- a/sdk/tests/cocos/node-wasm.test.ts
+++ b/sdk/tests/cocos/node-wasm.test.ts
@@ -129,6 +129,27 @@ describe.skipIf(!HAS_WASM)('Node on the engine', () => {
expect(panel.eulerAngles.z).toBeCloseTo(45, 4);
});
+ it('reads the world directions of its axes: forward is -z, turned by the rotation', () => {
+ connect();
+ const { panel } = tree();
+ expect(panel.forward.z).toBeCloseTo(-1, 5);
+ expect(panel.up.y).toBeCloseTo(1, 5);
+ panel.setRotationFromEuler(0, 90, 0);
+ expect(panel.forward.x).toBeCloseTo(-1, 5);
+ expect(panel.right.z).toBeCloseTo(-1, 5);
+ });
+
+ it('gives its world transform as a matrix: the position in the translation column, the scale on the diagonal', () => {
+ connect();
+ const { panel } = tree();
+ panel.setPosition(4, 5, 6);
+ panel.setScale(2, 2, 2);
+ const m = panel.worldMatrix;
+ expect(m.m12).toBeCloseTo(panel.worldPosition.x, 5);
+ expect(m.m13).toBeCloseTo(panel.worldPosition.y, 5);
+ expect(m.m00).toBeCloseTo(panel.worldScale.x, 5);
+ });
+
it('reads a changed position back as a new object, so mutating it does not move the node', () => {
connect();
const { panel } = tree();
diff --git a/sdk/tests/cocos/script-active-wasm.test.ts b/sdk/tests/cocos/script-active-wasm.test.ts
index d9ea9071f..0d38bf177 100644
--- a/sdk/tests/cocos/script-active-wasm.test.ts
+++ b/sdk/tests/cocos/script-active-wasm.test.ts
@@ -11,7 +11,7 @@ import { 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';
-import { resetClassRegistry } from '../../src/cocos/registry';
+import { resetClassRegistry, syncActivity } from '../../src/cocos/registry';
import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';
import { Component, Node, _decorator, setCurrentWorld } from '../../src/cocos';
import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';
@@ -117,4 +117,39 @@ describe.skipIf(!HAS_WASM)('a script that switches nodes on and off', () => {
child.active = false;
expect(calls).toContain('disable');
});
+
+ it('loads every script of a tree before it enables any, in node order, when the tree is activated at once', async () => {
+ setDefaultContext(new AppContext());
+ ensureBuiltinComponentsRegistered();
+ resetClassRegistry();
+ declareBuiltinScripts();
+ const calls: string[] = [];
+
+ @_decorator.ccclass('First')
+ class First extends Component {
+ onLoad() { calls.push('first.load'); }
+ onEnable() { calls.push('first.enable'); }
+ }
+ @_decorator.ccclass('Second')
+ class Second extends Component {
+ onLoad() { calls.push('second.load'); }
+ onEnable() { calls.push('second.enable'); }
+ }
+ void First; void Second;
+
+ registry = new module.Registry();
+ app = App.new();
+ app.connectCpp(registry as never, module);
+ flushPendingRegistrations(app);
+ setCurrentWorld(app.world);
+ const map = loadSceneData(app.world, {
+ version: SCENE_FORMAT_VERSION, name: 'main',
+ entities: [
+ { id: 0, name: 'Root', parent: null, children: [1], visible: true, components: [transform, { type: 'Cocos.First', data: { enabled: true } }] },
+ { id: 1, name: 'Child', parent: 0, children: [], visible: true, components: [transform, { type: 'Cocos.Second', data: { enabled: true } }] },
+ ],
+ } as unknown as SceneData);
+ syncActivity(app.world, map.get(0)!);
+ expect(calls).toEqual(['first.load', 'second.load', 'first.enable', 'second.enable']);
+ });
});