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(cocos): the cc compatibility core — Node as a handle on an entity, Component with Cocos's lifecycle on the engine's frame loop, @ccclass/@property as Estella components, and the value types

yhh7717a66c0312
diff --git a/sdk/src/cocos/assets.ts b/sdk/src/cocos/assets.ts
new file mode 100644
index 000000000..2ca80c78c
--- /dev/null
+++ b/sdk/src/cocos/assets.ts
@@ -0,0 +1,32 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/assets.ts
+ * @brief The asset classes a script names in a `@property` type: `SpriteFrame`, `Prefab`, `AudioClip`, ….
+ *
+ * In the engine an asset reference is a project-relative path, so these are markers: the class exists so that
+ * `@property(SpriteFrame)` can say "this field is a sprite frame", and a value held in such a field is the path (loading it is
+ * the asset system's job). They carry no behaviour.
+ */
+
+export class Asset { constructor(public path = '') {} }
+export class ImageAsset extends Asset {}
+export class Texture2D extends Asset {}
+export class SpriteFrame extends Asset {}
+export class SpriteAtlas extends Asset {}
+export class Prefab extends Asset {}
+export class AudioClip extends Asset {}
+export class Material extends Asset {}
+export class JsonAsset extends Asset {}
+export class TextAsset extends Asset {}
+export class BitmapFont extends Asset {}
+export class Font extends Asset {}
+export class AnimationClip extends Asset {}
+export class SceneAsset extends Asset {}
+export class EffectAsset extends Asset {}
+export class Mesh extends Asset {}
+
+/** Whether a `@property` type names an asset class. */
+export function isAssetClass(type: unknown): boolean {
+ return typeof type === 'function' && (type === Asset || type.prototype instanceof Asset);
+}
diff --git a/sdk/src/cocos/builtins.ts b/sdk/src/cocos/builtins.ts
new file mode 100644
index 000000000..f24207240
--- /dev/null
+++ b/sdk/src/cocos/builtins.ts
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/builtins.ts
+ * @brief The Cocos classes the engine already has under another name — `Label`, `Sprite`, `UITransform`, `Button`.
+ *
+ * A script asks `node.getComponent(Label)` and then sets `label.string`. There is no script class behind it: the answer is a
+ * view on an Estella component (`Text`), whose fields it reads and writes under Cocos's names. An adapter says how to find
+ * that view on an entity and how to make one; the classes that use it live beside it and register themselves.
+ */
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import type { Component } from './component';
+
+export interface BuiltinAdapter {
+ /** The view on @p entity's component, or null when it has none. */
+ get(world: World, entity: Entity): Component | null;
+ /** Give @p entity the component (with the engine's defaults) and return the view. */
+ add(world: World, entity: Entity): Component | null;
+}
+
+const adapters = new Map<unknown, BuiltinAdapter>();
+
+/** Register an adapter under its class and the names a script or a scene may use for it (`'cc.Label'`, `'Label'`). */
+export function registerBuiltinComponent(ctor: Function, names: string[], adapter: BuiltinAdapter): void {
+ adapters.set(ctor, adapter);
+ for (const n of names) adapters.set(n, adapter);
+}
+
+export function builtinAdapterFor(type: unknown): BuiltinAdapter | undefined {
+ return adapters.get(type);
+}
+
+/** Test seam. */
+export function resetBuiltinAdapters(): void {
+ adapters.clear();
+}
diff --git a/sdk/src/cocos/component.ts b/sdk/src/cocos/component.ts
new file mode 100644
index 000000000..6effe0320
--- /dev/null
+++ b/sdk/src/cocos/component.ts
@@ -0,0 +1,119 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/component.ts
+ * @brief `Component`, the base class a Cocos script extends.
+ *
+ * The lifecycle methods are not defined here — a subclass declares the ones it wants, and the host calls whichever exist, in
+ * Cocos's order: `onLoad` once when the instance is made, `onEnable` when it becomes active, `start` once before its first
+ * `update`, `update(dt)` and `lateUpdate(dt)` each frame while active, `onDisable` when it stops being active and
+ * `onDestroy` when the component or its entity goes. Declaring them as optional members (rather than empty methods) keeps a
+ * subclass's own `override` honest and lets the host skip the call when nothing is there.
+ */
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import { classInfoOf, type ComponentCtor } from './registry';
+import type { Node } from './node';
+
+/** One `schedule` / `scheduleOnce` registration. */
+interface Timer {
+ callback: (dt: number) => void;
+ /** Seconds between calls. */
+ interval: number;
+ /** Calls after the first; `Infinity` for forever. */
+ repeat: number;
+ /** Seconds until the next call. */
+ remaining: number;
+ /** Seconds since this timer last fired (what `dt` is). */
+ since: number;
+ calls: number;
+}
+
+export class Component {
+ /** The node this component is on. Set before `onLoad`. */
+ node!: Node;
+ /** Whether the component takes part: a disabled one gets no `update`, and `onDisable` has run. */
+ enabled = true;
+
+ /** @internal */ _world!: World;
+ /** @internal */ _entity!: Entity;
+ /** @internal */ _loaded = false;
+ /** @internal */ _started = false;
+ /** @internal */ _enabledApplied = false;
+ /** @internal */ _destroyed = false;
+ /** @internal */ _timers: Timer[] = [];
+
+ onLoad?(): void;
+ onEnable?(): void;
+ start?(): void;
+ update?(dt: number): void;
+ lateUpdate?(dt: number): void;
+ onDisable?(): void;
+ onDestroy?(): void;
+
+ get uuid(): string { return `${this._entity}:${this.constructor.name}`; }
+
+ /** See {@link Node.toJSON}: a component holds the world too. */
+ toJSON(): { component: string; entity: number } { return { component: this.constructor.name, entity: this._entity }; }
+ [Symbol.for('nodejs.util.inspect.custom')](): string { return `${this.constructor.name}(#${this._entity})`; }
+ get name(): string { return `${this.node?.name ?? ''}<${this.constructor.name}>`; }
+
+ /** False once the component or its entity has gone. */
+ get isValid(): boolean { return !this._destroyed && !!this._world?.valid(this._entity); }
+
+ /** Enabled, and so is every node above it. */
+ get enabledInHierarchy(): boolean { return this.enabled && !!this._world?.isEntityActive(this._entity); }
+
+ getComponent<T extends Component>(type: ComponentCtor<T> | string): T | null { return this.node.getComponent(type); }
+ getComponents<T extends Component>(type: ComponentCtor<T> | string): T[] { return this.node.getComponents(type); }
+ getComponentInChildren<T extends Component>(type: ComponentCtor<T> | string): T | null { return this.node.getComponentInChildren(type); }
+ getComponentsInChildren<T extends Component>(type: ComponentCtor<T> | string): T[] { return this.node.getComponentsInChildren(type); }
+ addComponent<T extends Component>(type: ComponentCtor<T> | string): T | null { return this.node.addComponent(type); }
+
+ /**
+ * Call @p callback every @p interval seconds, @p repeat more times after the first call (forever by default), the first
+ * after @p delay seconds. The callback gets the seconds since its last call.
+ */
+ schedule(callback: (dt: number) => void, interval = 0, repeat = Infinity, delay = 0): void {
+ this.unschedule(callback);
+ this._timers.push({ callback, interval, repeat, remaining: delay > 0 ? delay : interval, since: 0, calls: 0 });
+ }
+
+ scheduleOnce(callback: (dt: number) => void, delay = 0): void {
+ this.schedule(callback, 0, 0, delay);
+ }
+
+ unschedule(callback: (dt: number) => void): void {
+ this._timers = this._timers.filter((t) => t.callback !== callback);
+ }
+
+ unscheduleAllCallbacks(): void {
+ this._timers.length = 0;
+ }
+
+ /** Remove this component from its node. `onDestroy` runs on the next frame, as in Cocos. */
+ destroy(): boolean {
+ if (this._destroyed) return false;
+ const info = classInfoOf(this.constructor);
+ if (info && this._world?.valid(this._entity)) this._world.remove(this._entity, info.def);
+ return true;
+ }
+
+ /** @internal Advance this component's timers; called by the host, once a frame, while the component is active. */
+ _tickTimers(dt: number): void {
+ if (this._timers.length === 0) return;
+ // A callback may schedule or unschedule: walk a copy, and skip a timer that was removed meanwhile.
+ for (const timer of [...this._timers]) {
+ if (!this._timers.includes(timer)) continue;
+ timer.since += dt;
+ timer.remaining -= dt;
+ if (timer.remaining > 0) continue;
+ const elapsed = timer.since;
+ timer.since = 0;
+ timer.calls++;
+ timer.remaining = timer.interval > 0 ? timer.remaining + timer.interval : 0;
+ if (timer.calls > timer.repeat) this._timers = this._timers.filter((t) => t !== timer);
+ timer.callback.call(this, elapsed);
+ }
+ }
+}
diff --git a/sdk/src/cocos/decorators.ts b/sdk/src/cocos/decorators.ts
new file mode 100644
index 000000000..9b0458057
--- /dev/null
+++ b/sdk/src/cocos/decorators.ts
@@ -0,0 +1,141 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/decorators.ts
+ * @brief `@ccclass`, `@property` and the rest of Cocos's `_decorator` namespace.
+ *
+ * The scripts are written with TypeScript's legacy (experimental) decorators, which run when the class is defined: each
+ * `@property` records a field on the class, and `@ccclass` — which runs last — declares the class (host.ts). Everything else in
+ * the namespace configures the Cocos editor and is accepted and ignored, because a script that names it must still load.
+ */
+import { Component } from './component';
+import { Color, Vec2, Vec3 } from './math';
+import { Node } from './node';
+import { isAssetClass } from './assets';
+import { declareClass, type RawPropertySpec } from './host';
+import type { PropertyKind } from './registry';
+
+/** The numeric and string marker types Cocos offers for `@property({ type: ... })`. */
+export class CCInteger {}
+export class CCFloat {}
+export class CCString {}
+export class CCBoolean {}
+
+const ENUM_TAG = Symbol('cocos.enum');
+
+/** An enum object, tagged so a `@property({ type: MyEnum })` is known to be a number. TypeScript's own `enum` works unchanged. */
+export function Enum<T extends object>(obj: T): T {
+ Object.defineProperty(obj, ENUM_TAG, { value: true, enumerable: false });
+ return obj;
+}
+
+/** What a `@property` type argument names. Undefined when it is not one this layer recognises, so the field's value decides. */
+function kindOfType(type: unknown): PropertyKind | undefined {
+ if (type === undefined || type === null) return undefined;
+ if (type === Node) return 'node';
+ if (type === Number || type === CCInteger || type === CCFloat) return 'number';
+ if (type === String || type === CCString) return 'string';
+ if (type === Boolean || type === CCBoolean) return 'boolean';
+ if (type === Vec2) return 'vec2';
+ if (type === Vec3) return 'vec3';
+ if (type === Color) return 'color';
+ if (isAssetClass(type)) return 'asset';
+ if (typeof type === 'function' && (type === Component || type.prototype instanceof Component)) return 'component';
+ if (typeof type === 'object' && (type as Record<symbol, unknown>)[ENUM_TAG]) return 'number';
+ // A TypeScript enum that was not wrapped: an object whose values are numbers.
+ if (typeof type === 'object') return 'number';
+ return 'json';
+}
+
+const recorded = new WeakMap<Function, Map<string, RawPropertySpec>>();
+
+function record(ctor: Function, spec: RawPropertySpec): void {
+ let fields = recorded.get(ctor);
+ if (!fields) recorded.set(ctor, (fields = new Map()));
+ fields.set(spec.name, spec);
+}
+
+/** The properties of a class, base classes first, a subclass's declaration of a name replacing its base's. */
+function propertiesOf(ctor: Function): RawPropertySpec[] {
+ const chain: Function[] = [];
+ for (let c: Function | null = ctor; c && c !== Function.prototype; c = Object.getPrototypeOf(c)) chain.unshift(c);
+ const merged = new Map<string, RawPropertySpec>();
+ for (const c of chain) for (const [name, spec] of recorded.get(c) ?? []) merged.set(name, spec);
+ return [...merged.values()];
+}
+
+interface PropertyOptions {
+ type?: unknown;
+ visible?: unknown;
+ displayName?: string;
+ tooltip?: string;
+ [key: string]: unknown;
+}
+
+function specFor(name: string, options: PropertyOptions | unknown[] | Function | undefined): RawPropertySpec {
+ let type: unknown;
+ let array = false;
+ if (Array.isArray(options)) { type = options[0]; array = true; }
+ else if (typeof options === 'function') type = options;
+ else if (options && typeof options === 'object') {
+ const t = (options as PropertyOptions).type;
+ if (Array.isArray(t)) { type = t[0]; array = true; } else type = t;
+ }
+ const kind = kindOfType(type);
+ return { name, ...(kind ? { kind } : {}), ...(type !== undefined ? { type } : {}), ...(array ? { array } : {}) };
+}
+
+/**
+ * `@property`, in every form a script writes it: bare, with a type (`@property(Node)`), with options (`@property({ type: Label })`),
+ * or with a list (`@property([Node])`).
+ */
+export function property(...args: unknown[]): any {
+ // Bare: `@property` is the decorator itself, called with (prototype, key).
+ if (args.length >= 2 && typeof args[1] === 'string' && args[0] && typeof args[0] === 'object') {
+ record((args[0] as object).constructor, specFor(args[1], undefined));
+ return undefined;
+ }
+ const options = args[0] as PropertyOptions | unknown[] | Function | undefined;
+ return (target: object, key: string): void => { record(target.constructor, specFor(key, options)); };
+}
+
+/** `@ccclass('Name')` or bare `@ccclass`: declare the class, under its own name if none is given. */
+export function ccclass(arg?: string | Function): any {
+ const declare = (ctor: Function, name?: string): void => {
+ declareClass(ctor as never, name || ctor.name, propertiesOf(ctor));
+ };
+ if (typeof arg === 'function') { declare(arg); return undefined; }
+ return (ctor: Function): void => declare(ctor, arg);
+}
+
+/** The editor-only decorators: accepted so a script that uses them loads, and otherwise without effect here. */
+function inert(..._args: unknown[]): any {
+ return (..._inner: unknown[]): void => {};
+}
+
+/** A decorator that is applied bare (`@executeInEditMode`) or as a call (`@menu('x')`), and does nothing either way. */
+function inertEither(...args: unknown[]): any {
+ if (args.length >= 1 && typeof args[0] === 'function' && args.length === 1) return undefined;
+ return inert();
+}
+
+export const requireComponent = inert;
+export const executionOrder = inert;
+export const menu = inert;
+export const help = inert;
+export const icon = inert;
+export const inspector = inert;
+export const playOnFocus = inertEither;
+export const executeInEditMode = inertEither;
+export const disallowMultiple = inertEither;
+export const type = (t: unknown) => (target: object, key: string): void => { record(target.constructor, specFor(key, { type: t })); };
+export const integer = (target: object, key: string): void => { record(target.constructor, { name: key, kind: 'number' }); };
+export const float = integer;
+export const string = (target: object, key: string): void => { record(target.constructor, { name: key, kind: 'string' }); };
+export const boolean = (target: object, key: string): void => { record(target.constructor, { name: key, kind: 'boolean' }); };
+
+/** Cocos exposes these under `_decorator`; scripts import the namespace and write `@_decorator.ccclass`, or destructure it. */
+export const _decorator = {
+ ccclass, property, requireComponent, executionOrder, menu, help, icon, inspector, playOnFocus, executeInEditMode, disallowMultiple,
+ type, integer, float, string, boolean,
+};
diff --git a/sdk/src/cocos/director.ts b/sdk/src/cocos/director.ts
new file mode 100644
index 000000000..16761a9ac
--- /dev/null
+++ b/sdk/src/cocos/director.ts
@@ -0,0 +1,123 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/director.ts
+ * @brief The scene-level entry points of Cocos: `director`, `find`, `isValid`.
+ *
+ * Cocos has one active scene with a root; the engine has a world with several root entities. `Scene` is the view a script
+ * expects over that: its children are the world's parentless named entities, so `director.getScene().getChildByName('Canvas')`
+ * and `find('Canvas/Panel')` mean what they say.
+ */
+import { Name, Parent } from '../ecs/component';
+import type { World } from '../ecs/world';
+import { INVALID_ENTITY, type Entity } from '../types';
+import { Node, getCurrentWorld } from './node';
+
+/** The root of the running scene: a stand-in for the parent the world's top-level entities do not have. */
+export class Scene {
+ constructor(private readonly world: World) {}
+
+ get name(): string { return 'Scene'; }
+ get active(): boolean { return true; }
+ get isValid(): boolean { return true; }
+
+ get children(): Node[] {
+ const roots: Entity[] = [];
+ for (const e of this.world.getEntitiesWithComponents([Name])) {
+ const parent = this.world.tryGet(e, Parent)?.entity;
+ if (!parent || parent === INVALID_ENTITY) roots.push(e);
+ }
+ return roots.map((e) => Node.for(this.world, e));
+ }
+ get childrenCount(): number { return this.children.length; }
+
+ getChildByName(name: string): Node | null {
+ return this.children.find((c) => c.name === name) ?? null;
+ }
+
+ /** `Canvas/Panel/Button`: the first segment names a root, the rest descend. */
+ getChildByPath(path: string): Node | null {
+ const [first, ...rest] = path.split('/').filter((s) => s.length > 0);
+ if (first === undefined) return null;
+ const root = this.getChildByName(first);
+ return root ? (rest.length ? root.getChildByPath(rest.join('/')) : root) : null;
+ }
+}
+
+type DirectorListener = { callback: (...args: any[]) => void; target?: unknown };
+
+const directorListeners = new Map<string, DirectorListener[]>();
+
+function requireWorld(what: string): World {
+ const world = getCurrentWorld();
+ if (!world) throw new Error(`cocos compat: ${what} outside a running scene (no world is current)`);
+ return world;
+}
+
+/** The parts of `director` scripts actually call. Scene loading and the persistent-root list are the engine's, and are not simulated. */
+export const director = {
+ getScene(): Scene | null {
+ const world = getCurrentWorld();
+ return world ? new Scene(world) : null;
+ },
+ /** The time of the last frame, in seconds. */
+ getDeltaTime(): number { return lastDelta; },
+ getTotalFrames(): number { return totalFrames; },
+ on(type: string, callback: (...args: any[]) => void, target?: unknown): void {
+ const list = directorListeners.get(type);
+ if (list) list.push({ callback, target }); else directorListeners.set(type, [{ callback, target }]);
+ },
+ once(type: string, callback: (...args: any[]) => void, target?: unknown): void {
+ const wrapper = (...args: any[]): void => { director.off(type, wrapper, target); callback.apply(target, args); };
+ director.on(type, wrapper, target);
+ },
+ off(type: string, callback?: (...args: any[]) => void, target?: unknown): void {
+ const list = directorListeners.get(type);
+ if (!list) return;
+ directorListeners.set(type, list.filter((l) => (callback && l.callback !== callback) || (target !== undefined && l.target !== target)));
+ },
+ emit(type: string, ...args: any[]): void {
+ for (const l of [...(directorListeners.get(type) ?? [])]) l.callback.apply(l.target, args);
+ },
+ /** Kept for scripts that mark a node to survive a scene change: the engine's scene streaming decides that. */
+ addPersistRootNode(_node: Node): void {},
+ removePersistRootNode(_node: Node): void {},
+ isPersistRootNode(_node: Node): boolean { return false; },
+};
+
+let lastDelta = 0;
+let totalFrames = 0;
+/** @internal The host reports each frame, so `director.getDeltaTime()` and the frame events mean something. */
+export function reportFrame(delta: number): void {
+ lastDelta = delta;
+ totalFrames++;
+}
+
+/** `Director`'s event names. */
+export const Director = Object.freeze({
+ EVENT_BEFORE_UPDATE: 'director_before_update',
+ EVENT_AFTER_UPDATE: 'director_after_update',
+ EVENT_BEFORE_SCENE_LOADING: 'director_before_scene_loading',
+ EVENT_AFTER_SCENE_LAUNCH: 'director_after_scene_launch',
+});
+
+/** A node by absolute path from the scene roots: `find('Canvas/Panel')`. A name with no slash searches the roots, then everything. */
+export function find(path: string, referenceNode?: Node): Node | null {
+ if (referenceNode) return referenceNode.getChildByPath(path);
+ const world = requireWorld('find');
+ const scene = new Scene(world);
+ const direct = scene.getChildByPath(path);
+ if (direct || path.includes('/')) return direct;
+ // A bare name: the first node anywhere with it.
+ for (const e of world.getEntitiesWithComponents([Name])) {
+ if (world.tryGet(e, Name)?.value === path) return Node.for(world, e);
+ }
+ return null;
+}
+
+/** Whether a node or component (or anything that says) is still usable. */
+export function isValid(value: unknown, _strict = false): boolean {
+ if (value === null || value === undefined) return false;
+ const v = value as { isValid?: boolean };
+ return typeof v.isValid === 'boolean' ? v.isValid : true;
+}
diff --git a/sdk/src/cocos/host.ts b/sdk/src/cocos/host.ts
new file mode 100644
index 000000000..36478a480
--- /dev/null
+++ b/sdk/src/cocos/host.ts
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/host.ts
+ * @brief Declaring a script class, and running its lifecycle.
+ *
+ * Declaring a class (`@ccclass`) does two things, both through the engine's own mechanisms. It defines an Estella component
+ * carrying the class's `@property` values — the data a scene or prefab stores and the inspector edits — and it registers a
+ * system, the way `defineBehavior` does, that finds the entities carrying that component and drives the instances' lifecycle.
+ * There is no second runtime: the instances are plain objects held in `registry.ts`, and the frame loop is the engine's.
+ *
+ * Lifecycle is presence-diffed against the live query rather than tracked by events, so a component removed or an entity
+ * despawned by a system that ran earlier is still seen, and an entity switched off (which drops out of the query but keeps its
+ * component) is told apart from one that is gone.
+ */
+import { defineComponent } from '../ecs/component';
+import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';
+import { Query, Mut } from '../ecs/query';
+import { Res, Time } from '../ecs/resource';
+import type { World } from '../ecs/world';
+import type { Entity } from '../types';
+import { log } from '../util/logger';
+import { Color, Vec2, Vec3 } from './math';
+import { Node, setCurrentWorld } from './node';
+import {
+ COMPONENT_PREFIX, classInfoOf, dropInstance, instancesOfClass, instancesOn, nodeOf, registerClassInfo, setInstantiator, storeInstance,
+ type ClassInfo, type ComponentCtor, type PropertyKind, type PropertySpec,
+} from './registry';
+
+/** A property as the decorator recorded it: its kind may still be unknown, to be read off the class's own initializer. */
+export interface RawPropertySpec {
+ name: string;
+ kind?: PropertyKind;
+ type?: unknown;
+ array?: boolean;
+}
+
+/** The kind a value implies, for a property that named no type. */
+function inferKind(value: unknown): PropertyKind {
+ if (typeof value === 'number') return 'number';
+ if (typeof value === 'string') return 'string';
+ if (typeof value === 'boolean') return 'boolean';
+ if (value instanceof Vec3) return 'vec3';
+ if (value instanceof Vec2) return 'vec2';
+ if (value instanceof Color) return 'color';
+ if (value instanceof Node) return 'node';
+ return 'json';
+}
+import type { Component } from './component';
+
+/** The value a freshly declared component carries for one property: what the class's own initializer gave, in the form the engine stores. */
+function storedDefault(spec: PropertySpec, value: unknown): unknown {
+ if (spec.array) return Array.isArray(value) && spec.kind !== 'node' && spec.kind !== 'component' ? structuredClone(value) : [];
+ switch (spec.kind) {
+ case 'number': return typeof value === 'number' ? value : 0;
+ case 'string': return typeof value === 'string' ? value : '';
+ case 'boolean': return typeof value === 'boolean' ? value : false;
+ case 'node':
+ case 'component': return 0;
+ case 'asset': return '';
+ case 'vec2': return value instanceof Vec2 ? { x: value.x, y: value.y } : { x: 0, y: 0 };
+ case 'vec3': return value instanceof Vec3 ? { x: value.x, y: value.y, z: value.z } : { x: 0, y: 0, z: 0 };
+ case 'color': return value instanceof Color ? { r: value.r, g: value.g, b: value.b, a: value.a } : { r: 255, g: 255, b: 255, a: 255 };
+ default: return value === undefined ? null : structuredClone(value);
+ }
+}
+
+/** What a stored value becomes on an instance. */
+function liveValue(world: World, spec: PropertySpec, stored: unknown): unknown {
+ const one = (v: unknown): unknown => {
+ switch (spec.kind) {
+ case 'node': return typeof v === 'number' && v > 0 ? nodeOf(world, v as Entity) : null;
+ case 'component': {
+ if (typeof v !== 'number' || v <= 0) return null;
+ const node = nodeOf(world, v as Entity);
+ return typeof spec.type === 'function' ? node.getComponent(spec.type as ComponentCtor) : null;
+ }
+ case 'vec2': return v && typeof v === 'object' ? new Vec2((v as Vec2).x, (v as Vec2).y) : new Vec2();
+ case 'vec3': return v && typeof v === 'object' ? new Vec3((v as Vec3).x, (v as Vec3).y, (v as Vec3).z) : new Vec3();
+ case 'color': return v && typeof v === 'object' ? new Color((v as Color).r, (v as Color).g, (v as Color).b, (v as Color).a) : new Color();
+ default: return v;
+ }
+ };
+ return spec.array && Array.isArray(stored) ? stored.map(one) : one(stored);
+}
+
+function call(inst: Component, hook: 'onLoad' | 'onEnable' | 'start' | 'onDisable' | 'onDestroy'): void;
+function call(inst: Component, hook: 'update' | 'lateUpdate', dt: number): void;
+function call(inst: Component, hook: keyof Component, dt?: number): void {
+ const fn = (inst as unknown as Record<string, ((dt?: number) => void) | undefined>)[hook];
+ if (typeof fn !== 'function') return;
+ try {
+ fn.call(inst, dt);
+ } catch (err) {
+ log.error('cocos', `${inst.name}.${String(hook)} threw`, err);
+ }
+}
+
+function instantiate(world: World, entity: Entity, ctor: ComponentCtor): Component | null {
+ const info = classInfoOf(ctor);
+ if (!info || !world.valid(entity) || !world.has(entity, info.def)) return null;
+ const previous = setCurrentWorld(world);
+ try {
+ const inst = new ctor();
+ inst._world = world;
+ inst._entity = entity;
+ inst.node = nodeOf(world, entity);
+ // Stored before `onLoad`: a `getComponent` inside it must find this instance, not make a second.
+ storeInstance(world, entity, ctor, inst);
+
+ const data = world.get(entity, info.def) as Record<string, unknown>;
+ if (typeof data.enabled === 'boolean') inst.enabled = data.enabled;
+ 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');
+ return inst;
+ } finally {
+ setCurrentWorld(previous);
+ }
+}
+setInstantiator(instantiate);
+
+/** 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): void {
+ const active = inst.enabled && world.isEntityActive(entity);
+ if (active && !inst._enabledApplied) {
+ inst._enabledApplied = true;
+ call(inst, 'onEnable');
+ } else if (!active && inst._enabledApplied) {
+ inst._enabledApplied = false;
+ call(inst, 'onDisable');
+ }
+ if (!active) return;
+ if (!inst._started) {
+ inst._started = true;
+ call(inst, 'start');
+ }
+ try {
+ inst._tickTimers(dt);
+ } catch (err) {
+ log.error('cocos', `${inst.name} timer threw`, err);
+ }
+ call(inst, 'update', dt);
+}
+
+function destroyInstance(world: World, entity: Entity, ctor: Function, inst: Component): void {
+ if (inst._enabledApplied) {
+ inst._enabledApplied = false;
+ call(inst, 'onDisable');
+ }
+ inst._destroyed = true;
+ inst.unscheduleAllCallbacks();
+ call(inst, 'onDestroy');
+ dropInstance(world, entity, ctor);
+}
+
+/**
+ * Declare a script class: define its component, register it, and register the system that drives it.
+ * @param specs The class's `@property` fields, with their kinds settled.
+ */
+export function declareClass(ctor: ComponentCtor, name: string, raw: RawPropertySpec[]): ClassInfo {
+ // 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; }
+
+ const specs: PropertySpec[] = raw.map((r) => ({ ...r, kind: r.kind ?? inferKind(probe?.[r.name]) }));
+ const defaults: Record<string, unknown> = { enabled: true };
+ for (const spec of specs) defaults[spec.name] = storedDefault(spec, probe?.[spec.name]);
+
+ const componentName = COMPONENT_PREFIX + name;
+ const entityFields = specs.filter((s) => s.kind === 'node' || s.kind === 'component').map((s) => s.name);
+ const def = defineComponent(componentName, defaults, entityFields.length ? { entityFields } : undefined);
+ const info: ClassInfo = { ctor, name, componentName, def, props: specs };
+ registerClassInfo(info);
+
+ const hasLate = typeof (ctor.prototype as Component).lateUpdate === 'function';
+
+ const update = defineSystem(
+ [Query(Mut(def)), Res(Time), GetWorld()],
+ (q, time, world) => {
+ const previous = setCurrentWorld(world);
+ try {
+ const seen = new Set<Entity>();
+ for (const [entity] of q) {
+ seen.add(entity);
+ const inst = instancesOn(world, entity)?.get(ctor) ?? instantiate(world, entity, ctor);
+ if (inst) drive(world, entity, inst, time.delta);
+ }
+ // Instances the query did not return are either switched off (still carrying the component) or gone.
+ for (const [entity, inst] of instancesOfClass(world, ctor)) {
+ if (seen.has(entity)) continue;
+ if (world.valid(entity) && world.has(entity, def)) drive(world, entity, inst, time.delta);
+ else destroyInstance(world, entity, ctor, inst);
+ }
+ } finally {
+ setCurrentWorld(previous);
+ }
+ },
+ { name: `Cocos:${name}`, touches: { opaque: true } },
+ );
+ addSystemToSchedule(Schedule.Update, update);
+
+ if (hasLate) {
+ const late = defineSystem(
+ [Query(Mut(def)), Res(Time), GetWorld()],
+ (q, time, world) => {
+ const previous = setCurrentWorld(world);
+ try {
+ for (const [entity] of q) {
+ const inst = instancesOn(world, entity)?.get(ctor);
+ if (inst && inst._started && inst.enabled && world.isEntityActive(entity)) call(inst, 'lateUpdate', time.delta);
+ }
+ } finally {
+ setCurrentWorld(previous);
+ }
+ },
+ { name: `Cocos:${name}:late`, touches: { opaque: true } },
+ );
+ addSystemToSchedule(Schedule.PostUpdate, late);
+ }
+ return info;
+}
+
+export { Node };
diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.ts
new file mode 100644
index 000000000..3412d1309
--- /dev/null
+++ b/sdk/src/cocos/index.ts
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/index.ts
+ * @brief `esengine/cocos`: the Cocos Creator `cc` module, for scripts that were written against it.
+ *
+ * A project that brings Cocos scripts across builds them with `cc` aliased to this entry (the project-script bundler does that
+ * for a project that asks for it), so `import { Component, Node, _decorator } from 'cc'` resolves here. The names exported are
+ * the ones a Cocos script imports; what stands behind them is the engine — a `Node` is an entity, a `Component` subclass is an
+ * Estella component with an instance — and the parts of Cocos that have no counterpart are not simulated (see each file).
+ */
+export { Vec2, Vec3, Quat, Color, Size, Rect, v2, v3, color, size, rect, math, toRadian, toDegree, clamp, clamp01, lerp } from './math';
+export { Component } from './component';
+export { Node, setCurrentWorld, getCurrentWorld } from './node';
+export {
+ _decorator, ccclass, property, requireComponent, executionOrder, menu, help, icon, inspector, playOnFocus, executeInEditMode,
+ disallowMultiple, type, integer, float, string, boolean, CCInteger, CCFloat, CCString, CCBoolean, Enum,
+} from './decorators';
+export { director, Director, Scene, find, isValid, reportFrame } from './director';
+export {
+ Asset, ImageAsset, Texture2D, SpriteFrame, SpriteAtlas, Prefab, AudioClip, Material, JsonAsset, TextAsset, BitmapFont, Font,
+ AnimationClip, SceneAsset, EffectAsset, Mesh,
+} from './assets';
+export { registerBuiltinComponent, type BuiltinAdapter } from './builtins';
+export { classInfoNamed, classInfoOf, allClassInfos, COMPONENT_PREFIX, resetClassRegistry } from './registry';
diff --git a/sdk/src/cocos/math.ts b/sdk/src/cocos/math.ts
new file mode 100644
index 000000000..4831da78e
--- /dev/null
+++ b/sdk/src/cocos/math.ts
@@ -0,0 +1,226 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/math.ts
+ * @brief The value types a Cocos Creator script reaches for: `Vec2`, `Vec3`, `Quat`, `Color`, `Size`, `Rect`, `math`.
+ *
+ * These are classes with public mutable fields, as in Cocos, because that is what the scripts are written against: they
+ * copy them (`v.clone()`), mutate them in place (`v.x += 1`, `v.add(w)`), and pass an `out` parameter to the static forms.
+ * They are not the engine's own `{x, y, z}` plain objects, and nothing here touches the engine: a {@link Node} converts at
+ * its boundary.
+ */
+
+export class Vec2 {
+ static readonly ZERO = Object.freeze(new Vec2(0, 0)) as Vec2;
+ static readonly ONE = Object.freeze(new Vec2(1, 1)) as Vec2;
+ static readonly UP = Object.freeze(new Vec2(0, 1)) as Vec2;
+ static readonly RIGHT = Object.freeze(new Vec2(1, 0)) as Vec2;
+
+ constructor(public x = 0, public y = 0) {}
+
+ set(x: number | Vec2, y?: number): this {
+ if (typeof x === 'object') { this.x = x.x; this.y = x.y; } else { this.x = x; this.y = y ?? 0; }
+ return this;
+ }
+ clone(): Vec2 { return new Vec2(this.x, this.y); }
+ add(v: Vec2): this { this.x += v.x; this.y += v.y; return this; }
+ subtract(v: Vec2): this { this.x -= v.x; this.y -= v.y; return this; }
+ multiplyScalar(s: number): this { this.x *= s; this.y *= s; return this; }
+ length(): number { return Math.hypot(this.x, this.y); }
+ 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; }
+ 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)})`; }
+
+ static distance(a: Vec2, b: Vec2): number { return Math.hypot(a.x - b.x, a.y - b.y); }
+ static add(out: Vec2, a: Vec2, b: Vec2): Vec2 { out.x = a.x + b.x; out.y = a.y + b.y; return out; }
+ 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; }
+}
+
+export class Vec3 {
+ static readonly ZERO = Object.freeze(new Vec3(0, 0, 0)) as Vec3;
+ static readonly ONE = Object.freeze(new Vec3(1, 1, 1)) as Vec3;
+ static readonly UP = Object.freeze(new Vec3(0, 1, 0)) as Vec3;
+ static readonly RIGHT = Object.freeze(new Vec3(1, 0, 0)) as Vec3;
+ static readonly FORWARD = Object.freeze(new Vec3(0, 0, -1)) as Vec3;
+
+ constructor(public x = 0, public y = 0, public z = 0) {}
+
+ set(x: number | Vec3, y?: number, z?: number): this {
+ if (typeof x === 'object') { this.x = x.x; this.y = x.y; this.z = x.z; } else { this.x = x; this.y = y ?? 0; this.z = z ?? 0; }
+ return this;
+ }
+ clone(): Vec3 { return new Vec3(this.x, this.y, this.z); }
+ add(v: Vec3): this { this.x += v.x; this.y += v.y; this.z += v.z; return this; }
+ subtract(v: Vec3): this { this.x -= v.x; this.y -= v.y; this.z -= v.z; return this; }
+ multiplyScalar(s: number): this { this.x *= s; this.y *= s; this.z *= s; return this; }
+ negative(): this { this.x = -this.x; this.y = -this.y; this.z = -this.z; return this; }
+ length(): number { return Math.hypot(this.x, this.y, this.z); }
+ lengthSqr(): number { return this.x * this.x + this.y * this.y + this.z * this.z; }
+ normalize(): this { const l = this.length(); if (l > 0) { this.x /= l; this.y /= l; this.z /= l; } return this; }
+ dot(v: Vec3): number { return this.x * v.x + this.y * v.y + this.z * v.z; }
+ cross(v: Vec3): this {
+ const { x, y, z } = this;
+ 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;
+ }
+ 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;
+ }
+ toString(): string { return `(${this.x.toFixed(2)}, ${this.y.toFixed(2)}, ${this.z.toFixed(2)})`; }
+
+ static distance(a: Vec3, b: Vec3): number { return Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z); }
+ static add(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 subtract(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 multiplyScalar(out: Vec3, a: Vec3, s: number): Vec3 { out.x = a.x * s; out.y = a.y * s; out.z = a.z * s; return out; }
+ static copy(out: Vec3, a: Vec3): Vec3 { out.x = a.x; out.y = a.y; out.z = a.z; return out; }
+ static normalize(out: Vec3, a: Vec3): Vec3 { out.set(a); return out.normalize(); }
+ static lerp(out: Vec3, a: Vec3, b: Vec3, t: number): 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;
+ }
+}
+
+export class Quat {
+ static readonly IDENTITY = Object.freeze(new Quat(0, 0, 0, 1)) as Quat;
+
+ constructor(public x = 0, public y = 0, public z = 0, public w = 1) {}
+
+ set(x: number | Quat, y?: number, z?: number, w?: number): this {
+ if (typeof x === 'object') { this.x = x.x; this.y = x.y; this.z = x.z; this.w = x.w; } else {
+ this.x = x; this.y = y ?? 0; this.z = z ?? 0; this.w = w ?? 1;
+ }
+ return this;
+ }
+ clone(): Quat { return new Quat(this.x, this.y, this.z, this.w); }
+
+ /** The rotation of @p x, @p y, @p z degrees about those axes — Cocos's own formula, so a script's angles mean what they meant there. */
+ static fromEuler(out: Quat, x: number, y: number, z: number): Quat {
+ const hx = (x * Math.PI) / 360, hy = (y * Math.PI) / 360, hz = (z * Math.PI) / 360;
+ const sx = Math.sin(hx), cx = Math.cos(hx), sy = Math.sin(hy), cy = Math.cos(hy), sz = Math.sin(hz), cz = Math.cos(hz);
+ out.x = sx * cy * cz + cx * sy * sz;
+ out.y = cx * sy * cz + sx * cy * sz;
+ out.z = cx * cy * sz - sx * sy * cz;
+ out.w = cx * cy * cz - sx * sy * sz;
+ return out;
+ }
+
+ /** The Euler angles, in degrees, of a rotation: Cocos's `Quat.toEuler`, the inverse of {@link Quat.fromEuler} (x in [-90, 90]). */
+ static toEuler(out: Vec3, q: Quat, outerZ = false): Vec3 {
+ const { x, y, z, w } = q;
+ const deg = (r: number): number => (r * 180) / Math.PI;
+ let bank = 0, heading = 0, attitude = 0;
+ const test = x * y + z * w;
+ if (test > 0.499999) {
+ heading = deg(2 * Math.atan2(x, w));
+ attitude = 90;
+ } else if (test < -0.499999) {
+ heading = -deg(2 * Math.atan2(x, w));
+ attitude = -90;
+ } else {
+ const sqx = x * x, sqy = y * y, sqz = z * z;
+ bank = deg(Math.atan2(2 * x * w - 2 * y * z, 1 - 2 * sqx - 2 * sqz));
+ heading = deg(Math.atan2(2 * y * w - 2 * x * z, 1 - 2 * sqy - 2 * sqz));
+ attitude = deg(Math.asin(2 * test));
+ if (outerZ) {
+ bank = -180 * Math.sign(bank + 1e-6) + bank;
+ heading = -180 * Math.sign(heading + 1e-6) + heading;
+ attitude = 180 * Math.sign(attitude + 1e-6) - attitude;
+ }
+ }
+ out.x = bank; out.y = heading; out.z = attitude;
+ return out;
+ }
+
+ 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;
+ const z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;
+ const w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;
+ out.x = x; out.y = y; out.z = z; out.w = w;
+ return out;
+ }
+}
+
+export class Color {
+ static readonly WHITE = Object.freeze(new Color(255, 255, 255, 255)) as Color;
+ static readonly BLACK = Object.freeze(new Color(0, 0, 0, 255)) as Color;
+ static readonly TRANSPARENT = Object.freeze(new Color(0, 0, 0, 0)) as Color;
+ static readonly GRAY = Object.freeze(new Color(127, 127, 127, 255)) as Color;
+ static readonly RED = Object.freeze(new Color(255, 0, 0, 255)) as Color;
+ static readonly GREEN = Object.freeze(new Color(0, 255, 0, 255)) as Color;
+ static readonly BLUE = Object.freeze(new Color(0, 0, 255, 255)) as Color;
+ static readonly YELLOW = Object.freeze(new Color(255, 235, 4, 255)) as Color;
+
+ constructor(public r = 0, public g = 0, public b = 0, public a = 255) {}
+
+ set(r: number | Color, g?: number, b?: number, a?: number): this {
+ if (typeof r === 'object') { this.r = r.r; this.g = r.g; this.b = r.b; this.a = r.a; } else {
+ this.r = r; this.g = g ?? 0; this.b = b ?? 0; this.a = a ?? 255;
+ }
+ return this;
+ }
+ 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; }
+
+ /** From `#rgb`, `#rrggbb` or `#rrggbbaa`. */
+ fromHEX(hex: string): this {
+ let h = hex.replace(/^#/, '');
+ if (h.length === 3) h = h.split('').map((c) => c + c).join('');
+ this.r = Number.parseInt(h.slice(0, 2), 16) || 0;
+ this.g = Number.parseInt(h.slice(2, 4), 16) || 0;
+ this.b = Number.parseInt(h.slice(4, 6), 16) || 0;
+ this.a = h.length >= 8 ? Number.parseInt(h.slice(6, 8), 16) || 0 : 255;
+ return this;
+ }
+ toHEX(fmt: '#rrggbb' | '#rrggbbaa' = '#rrggbb'): string {
+ const two = (n: number): string => Math.round(Math.max(0, Math.min(255, n))).toString(16).padStart(2, '0');
+ return `#${two(this.r)}${two(this.g)}${two(this.b)}${fmt === '#rrggbbaa' ? two(this.a) : ''}`;
+ }
+}
+
+export class Size {
+ constructor(public width = 0, public height = 0) {}
+ clone(): Size { return new Size(this.width, this.height); }
+ set(w: number | Size, h?: number): this {
+ if (typeof w === 'object') { this.width = w.width; this.height = w.height; } else { this.width = w; this.height = h ?? 0; }
+ return this;
+ }
+}
+
+export class Rect {
+ constructor(public x = 0, public y = 0, public width = 0, public height = 0) {}
+ clone(): Rect { return new Rect(this.x, this.y, this.width, this.height); }
+ contains(p: Vec2): boolean { return p.x >= this.x && p.x <= this.x + this.width && p.y >= this.y && p.y <= this.y + this.height; }
+ get xMax(): number { return this.x + this.width; }
+ get yMax(): number { return this.y + this.height; }
+}
+
+export function v2(x = 0, y = 0): Vec2 { return new Vec2(x, y); }
+export function v3(x = 0, y = 0, z = 0): Vec3 { return new Vec3(x, y, z); }
+export function color(r = 0, g = 0, b = 0, a = 255): Color { return new Color(r, g, b, a); }
+export function size(width = 0, height = 0): Size { return new Size(width, height); }
+export function rect(x = 0, y = 0, width = 0, height = 0): Rect { return new Rect(x, y, width, height); }
+
+/** Cocos's `math` namespace: the scalar helpers its scripts import alongside the value types. */
+export const math = {
+ EPSILON: 1e-6,
+ toRadian: (degrees: number): number => (degrees * Math.PI) / 180,
+ toDegree: (radians: number): number => (radians * 180) / Math.PI,
+ clamp: (v: number, min: number, max: number): number => Math.min(Math.max(v, min), max),
+ clamp01: (v: number): number => Math.min(Math.max(v, 0), 1),
+ lerp: (from: number, to: number, t: number): number => from + (to - from) * t,
+ approx: (a: number, b: number, epsilon = 1e-6): boolean => Math.abs(a - b) <= epsilon,
+ random: (): number => Math.random(),
+ randomRange: (min: number, max: number): number => min + Math.random() * (max - min),
+ randomRangeInt: (min: number, max: number): number => Math.floor(min + Math.random() * (max - min)),
+ pingPong: (t: number, length: number): number => { const k = t % (length * 2); return length - Math.abs(k - length); },
+};
+export const toRadian = math.toRadian;
+export const toDegree = math.toDegree;
+export const clamp = math.clamp;
+export const clamp01 = math.clamp01;
+export const lerp = math.lerp;
diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.ts
new file mode 100644
index 000000000..0145ef0d4
--- /dev/null
+++ b/sdk/src/cocos/node.ts
@@ -0,0 +1,343 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/node.ts
+ * @brief `Node`: a Cocos scene-graph node, as a thin handle on an Estella entity.
+ *
+ * There is one scene graph — the engine's. A `Node` owns nothing: it is `(world, entity)`, cached so the same entity is the
+ * same `Node` (scripts compare nodes with `===`), and every property reads or writes the entity's own components. A node a
+ * script makes with `new Node('name')` is an entity spawned in the world the host is currently running.
+ *
+ * Transform values cross the boundary as Cocos's value classes (`Vec3`, `Quat`) in and out; the engine's components are plain
+ * objects and a copy comes back from a read, so a write is always a `set` of the whole component.
+ */
+import { Children, Disabled, Name, Parent, Transform, type TransformData } from '../ecs/component';
+import { setEntityActive } from '../ecs/entityUtils';
+import type { World } from '../ecs/world';
+import { INVALID_ENTITY, type Entity } from '../types';
+import { Quat, Vec3 } from './math';
+import {
+ classInfoNamed, classInfoOf, ensureInstance, instancesOn, nodeOf, setNodeFactory,
+ type ComponentCtor,
+} from './registry';
+import type { Component } from './component';
+import { builtinAdapterFor } from './builtins';
+import { log } from '../util/logger';
+
+/** The world a `new Node()` spawns into: set by whatever is running script code (the host, a test). */
+let currentWorld: World | null = null;
+/** Make @p world current, and return the one that was, so a caller can put it back. */
+export function setCurrentWorld(world: World | null): World | null { const previous = currentWorld; currentWorld = world; return previous; }
+export function getCurrentWorld(): World | null { return currentWorld; }
+
+const cache = new WeakMap<World, Map<Entity, Node>>();
+
+type Listener = { callback: (...args: any[]) => void; target?: unknown; once: boolean };
+
+export class Node {
+ /** The event names Cocos scripts register for. Only the ones the engine raises are delivered; see the host. */
+ static readonly EventType = Object.freeze({
+ TOUCH_START: 'touch-start', TOUCH_MOVE: 'touch-move', TOUCH_END: 'touch-end', TOUCH_CANCEL: 'touch-cancel',
+ MOUSE_DOWN: 'mouse-down', MOUSE_MOVE: 'mouse-move', MOUSE_UP: 'mouse-up', MOUSE_WHEEL: 'mouse-wheel',
+ MOUSE_ENTER: 'mouse-enter', MOUSE_LEAVE: 'mouse-leave',
+ TRANSFORM_CHANGED: 'transform-changed', SIZE_CHANGED: 'size-changed', ANCHOR_CHANGED: 'anchor-changed',
+ CHILD_ADDED: 'child-added', CHILD_REMOVED: 'child-removed',
+ PARENT_CHANGED: 'parent-changed', ACTIVE_IN_HIERARCHY_CHANGED: 'active-in-hierarchy-changed',
+ SIBLING_ORDER_CHANGED: 'sibling-order-changed', LAYER_CHANGED: 'layer-changed',
+ });
+
+ /** @internal */ readonly _world: World;
+ /** @internal */ readonly _entity: Entity;
+ private listeners_: Map<string, Listener[]> | null = null;
+ /** Cocos's `layer` bitmask: carried, not interpreted. */
+ layer = 1 << 25;
+
+ /** The node for an entity; the same object every time. */
+ static for(world: World, entity: Entity): Node {
+ let perWorld = cache.get(world);
+ if (!perWorld) cache.set(world, (perWorld = new Map()));
+ let node = perWorld.get(entity);
+ if (!node) {
+ node = new Node(undefined, world, entity);
+ perWorld.set(entity, node);
+ }
+ return node;
+ }
+
+ /**
+ * A new, parentless node in the world the running script is in. The `world` and `entity` parameters are how the engine side
+ * builds a handle on one that already exists; a script never passes them.
+ */
+ constructor(name?: string, world?: World, entity?: Entity) {
+ if (world && entity !== undefined) {
+ this._world = world;
+ this._entity = entity;
+ return;
+ }
+ if (!currentWorld) throw new Error('cocos compat: new Node() outside a running scene (no world is current)');
+ this._world = currentWorld;
+ this._entity = currentWorld.spawn(name ?? 'New Node');
+ let perWorld = cache.get(currentWorld);
+ if (!perWorld) cache.set(currentWorld, (perWorld = new Map()));
+ perWorld.set(this._entity, this);
+ }
+
+ // ---- identity --------------------------------------------------------------------------------------------------
+
+ get uuid(): string { return String(this._entity); }
+ get isValid(): boolean { return this._world.valid(this._entity); }
+
+ /**
+ * What a node prints and serializes as. Without it `console.log(node)` and a failed assertion walk `_world` — the whole
+ * engine — and the process runs out of memory before it says anything.
+ */
+ toJSON(): { node: string; entity: number } { return { node: this.name, entity: this._entity }; }
+ [Symbol.for('nodejs.util.inspect.custom')](): string { return `Node(${this.name}#${this._entity})`; }
+
+ get name(): string { return this._world.tryGet(this._entity, Name)?.value ?? ''; }
+ set name(value: string) { this._world.set(this._entity, Name, { value }); }
+
+ // ---- activity --------------------------------------------------------------------------------------------------
+
+ /** This node's own switch. */
+ get active(): boolean { return !this._world.has(this._entity, Disabled); }
+ set active(value: boolean) { setEntityActive(this._world, this._entity, value); }
+
+ /** This node's switch and every ancestor's. */
+ get activeInHierarchy(): boolean { return this._world.isEntityActive(this._entity); }
+
+ // ---- hierarchy -------------------------------------------------------------------------------------------------
+
+ get parent(): Node | null {
+ const p = this._world.tryGet(this._entity, Parent)?.entity;
+ return p && p !== INVALID_ENTITY ? Node.for(this._world, p) : null;
+ }
+ set parent(value: Node | null) { this.setParent(value); }
+
+ get children(): Node[] {
+ const ids = this._world.tryGet(this._entity, Children)?.entities ?? [];
+ return ids.map((id) => Node.for(this._world, id));
+ }
+ get childrenCount(): number { return this._world.tryGet(this._entity, Children)?.entities.length ?? 0; }
+
+ setParent(parent: Node | null, _keepWorldTransform = false): void {
+ if (parent) this._world.setParent(this._entity, parent._entity);
+ else this._world.removeParent(this._entity);
+ }
+
+ addChild(child: Node): void { child.setParent(this); }
+ 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); }
+
+ getChildByName(name: string): Node | null {
+ for (const c of this.children) if (c.name === name) return c;
+ return null;
+ }
+
+ /** `a/b/c`, each segment a child's name; an empty path is this node. */
+ getChildByPath(path: string): Node | null {
+ let node: Node | null = this;
+ for (const segment of path.split('/')) {
+ if (segment === '') continue;
+ node = node.getChildByName(segment);
+ if (!node) return null;
+ }
+ return node;
+ }
+
+ getSiblingIndex(): number {
+ const p = this.parent;
+ return p ? (this._world.tryGet(p._entity, Children)?.entities.indexOf(this._entity) ?? -1) : 0;
+ }
+ setSiblingIndex(_index: number): void {
+ warnOnce('setSiblingIndex', 'Node.setSiblingIndex does not reorder yet: the engine owns the child order');
+ }
+
+ /** Whether @p other is this node or below it. */
+ isChildOf(other: Node): boolean {
+ for (let n: Node | null = this; n; n = n.parent) if (n === other) return true;
+ return false;
+ }
+
+ /** Remove this node and everything under it; its components get `onDestroy` on the next frame. */
+ destroy(): boolean {
+ if (!this.isValid) return false;
+ this._world.despawn(this._entity);
+ return true;
+ }
+ destroyAllChildren(): void { for (const c of this.children) c.destroy(); }
+
+ // ---- transform -------------------------------------------------------------------------------------------------
+
+ private transform_(): TransformData { return this._world.get(this._entity, Transform); }
+ /** The transform with its world fields current: a script that moves a node and reads where it ended up in the same frame must see the move. */
+ private composedTransform_(): TransformData {
+ this._world.ensureTransformsComposed();
+ return this.transform_();
+ }
+ private writeTransform_(patch: Partial<Pick<TransformData, 'position' | 'rotation' | 'scale'>>): void {
+ this._world.set(this._entity, Transform, { ...this.transform_(), ...patch });
+ }
+
+ get position(): Vec3 { const p = this.transform_().position; return new Vec3(p.x, p.y, p.z); }
+ set position(v: Vec3) { this.setPosition(v); }
+
+ /** `setPosition(vec3)` or `setPosition(x, y, z?)`; z is left alone when omitted. */
+ setPosition(x: number | Vec3, y?: number, z?: number): void {
+ const cur = this.transform_().position;
+ const next = typeof x === 'object' ? { x: x.x, y: x.y, z: x.z } : { x, y: y ?? cur.y, z: z ?? cur.z };
+ this.writeTransform_({ position: next });
+ }
+ getPosition(out?: Vec3): Vec3 { const p = this.transform_().position; return (out ?? new Vec3()).set(p.x, p.y, p.z); }
+
+ get scale(): Vec3 { const s = this.transform_().scale; return new Vec3(s.x, s.y, s.z); }
+ set scale(v: Vec3) { this.setScale(v); }
+ setScale(x: number | Vec3, y?: number, z?: number): void {
+ const cur = this.transform_().scale;
+ const next = typeof x === 'object' ? { x: x.x, y: x.y, z: x.z } : { x, y: y ?? cur.y, z: z ?? cur.z };
+ this.writeTransform_({ scale: next });
+ }
+ getScale(out?: Vec3): Vec3 { const s = this.transform_().scale; return (out ?? new Vec3()).set(s.x, s.y, s.z); }
+
+ get rotation(): Quat { const q = this.transform_().rotation; return new Quat(q.x, q.y, q.z, q.w); }
+ set rotation(q: Quat) { this.setRotation(q); }
+ setRotation(x: number | Quat, y?: number, z?: number, w?: number): void {
+ const q = typeof x === 'object' ? x : new Quat(x, y, z, w);
+ this.writeTransform_({ rotation: { x: q.x, y: q.y, z: q.z, w: q.w } });
+ }
+ getRotation(out?: Quat): Quat { const q = this.transform_().rotation; return (out ?? new Quat()).set(q.x, q.y, q.z, q.w); }
+
+ get eulerAngles(): Vec3 { return Quat.toEuler(new Vec3(), this.rotation); }
+ set eulerAngles(v: Vec3) { this.setRotationFromEuler(v.x, v.y, v.z); }
+ setRotationFromEuler(x: number, y: number, z: number): void { this.setRotation(Quat.fromEuler(new Quat(), x, y, z)); }
+
+ /** The rotation about z, in degrees: the one that matters for a 2D node. */
+ get angle(): number { return this.eulerAngles.z; }
+ set angle(degrees: number) { const e = this.eulerAngles; this.setRotationFromEuler(e.x, e.y, degrees); }
+
+ get worldPosition(): Vec3 { const p = this.composedTransform_().worldPosition; return new Vec3(p.x, p.y, p.z); }
+ set worldPosition(v: Vec3) { this.setWorldPosition(v); }
+ 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. */
+ setWorldPosition(x: number | Vec3, y?: number, z?: number): void {
+ const world = typeof x === 'object' ? x : new Vec3(x, y ?? 0, z ?? 0);
+ const parent = this.parent;
+ if (!parent) { this.setPosition(world); return; }
+ const pt = parent.composedTransform_();
+ const dx = world.x - pt.worldPosition.x, dy = world.y - pt.worldPosition.y, dz = world.z - pt.worldPosition.z;
+ // inverse parent rotation, then inverse parent scale
+ const { x: qx, y: qy, z: qz, w: qw } = pt.worldRotation;
+ const ix = -qx, iy = -qy, iz = -qz;
+ const tx = 2 * (iy * dz - iz * dy), ty = 2 * (iz * dx - ix * dz), tz = 2 * (ix * dy - iy * dx);
+ const rx = dx + qw * tx + (iy * tz - iz * ty);
+ const ry = dy + qw * ty + (iz * tx - ix * tz);
+ const rz = dz + qw * tz + (ix * ty - iy * tx);
+ const s = pt.worldScale;
+ this.setPosition(rx / (s.x || 1), ry / (s.y || 1), rz / (s.z || 1));
+ }
+
+ // ---- components ------------------------------------------------------------------------------------------------
+
+ /** The component of a class (or class name) on this node, or null. */
+ getComponent<T extends Component>(type: ComponentCtor<T> | string): T | null {
+ const ctor = this.resolveCtor_(type);
+ if (ctor) {
+ const info = classInfoOf(ctor);
+ if (info) return this._world.has(this._entity, info.def) ? (ensureInstance(this._world, this._entity, ctor) as T | null) : null;
+ }
+ return (builtinAdapterFor(type)?.get(this._world, this._entity) as T | null | undefined) ?? null;
+ }
+
+ getComponents<T extends Component>(type: ComponentCtor<T> | string): T[] {
+ const one = this.getComponent<T>(type);
+ return one ? [one] : [];
+ }
+
+ getComponentInChildren<T extends Component>(type: ComponentCtor<T> | string): T | null {
+ const own = this.getComponent<T>(type);
+ if (own) return own;
+ for (const c of this.children) {
+ const found = c.getComponentInChildren<T>(type);
+ if (found) return found;
+ }
+ return null;
+ }
+
+ getComponentsInChildren<T extends Component>(type: ComponentCtor<T> | string): T[] {
+ const out = this.getComponents<T>(type);
+ for (const c of this.children) out.push(...c.getComponentsInChildren<T>(type));
+ return out;
+ }
+
+ /** Add a component of a class to this node and return it, its `onLoad` already run. */
+ addComponent<T extends Component>(type: ComponentCtor<T> | string): T | null {
+ const ctor = this.resolveCtor_(type);
+ const info = ctor ? classInfoOf(ctor) : undefined;
+ if (ctor && info) {
+ if (!this._world.has(this._entity, info.def)) this._world.insert(this._entity, info.def, structuredClone(info.def._default));
+ return ensureInstance(this._world, this._entity, ctor) as T | null;
+ }
+ const adapter = builtinAdapterFor(type);
+ if (adapter) return adapter.add(this._world, this._entity) as T | null;
+ throw new Error(`cocos compat: addComponent: no component class "${typeof type === 'string' ? type : type?.name}"`);
+ }
+
+ private resolveCtor_(type: ComponentCtor | string): ComponentCtor | undefined {
+ if (typeof type === 'string') return classInfoNamed(type)?.ctor;
+ return type;
+ }
+
+ /** @internal Every live script component on this node. */
+ _allInstances(): Component[] { return [...(instancesOn(this._world, this._entity)?.values() ?? [])]; }
+
+ // ---- events ----------------------------------------------------------------------------------------------------
+
+ on(type: string, callback: (...args: any[]) => void, target?: unknown, _useCapture?: boolean): typeof callback {
+ this.addListener_(type, { callback, target, once: false });
+ return callback;
+ }
+ once(type: string, callback: (...args: any[]) => void, target?: unknown): void {
+ this.addListener_(type, { callback, target, once: true });
+ }
+ off(type: string, callback?: (...args: any[]) => void, target?: unknown): void {
+ const list = this.listeners_?.get(type);
+ if (!list) return;
+ this.listeners_!.set(type, list.filter((l) => (callback && l.callback !== callback) || (target !== undefined && l.target !== target)));
+ }
+ /** Remove every listener that was registered with @p target. */
+ targetOff(target: unknown): void {
+ if (!this.listeners_) return;
+ for (const [type, list] of this.listeners_) this.listeners_.set(type, list.filter((l) => l.target !== target));
+ }
+ hasEventListener(type: string): boolean { return (this.listeners_?.get(type)?.length ?? 0) > 0; }
+ emit(type: string, ...args: any[]): void {
+ const list = this.listeners_?.get(type);
+ if (!list) return;
+ for (const l of [...list]) {
+ if (l.once) this.off(type, l.callback, l.target);
+ l.callback.call(l.target, ...args);
+ }
+ }
+ dispatchEvent(event: { type: string }): void { this.emit(event.type, event); }
+
+ private addListener_(type: string, listener: Listener): void {
+ if (!this.listeners_) this.listeners_ = new Map();
+ const list = this.listeners_.get(type);
+ if (list) list.push(listener); else this.listeners_.set(type, [listener]);
+ }
+}
+
+setNodeFactory((world, entity) => Node.for(world, entity));
+
+
+const warned = new Set<string>();
+function warnOnce(key: string, message: string): void {
+ if (warned.has(key)) return;
+ warned.add(key);
+ log.warn('cocos', message);
+}
+
+/** The node for an entity, for the parts of the layer that hold only an entity id. */
+export function nodeForEntity(world: World, entity: Entity): Node { return nodeOf(world, entity); }
diff --git a/sdk/src/cocos/registry.ts b/sdk/src/cocos/registry.ts
new file mode 100644
index 000000000..696425de9
--- /dev/null
+++ b/sdk/src/cocos/registry.ts
@@ -0,0 +1,143 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/registry.ts
+ * @brief What the compatibility layer knows: the script classes that were declared, and the live instance of each on each entity.
+ *
+ * A Cocos component is a class instance per node; Estella's components are data. The bridge is two-sided: a declared class
+ * becomes an Estella component carrying its `@property` values (so a scene, a prefab and the inspector can hold them, and the
+ * ordinary save/load/undo machinery applies), and the instance lives here, created the first time something asks for it and
+ * dropped when the entity or the component goes.
+ *
+ * This file holds data and the two operations on it that everything else needs. It imports no engine system, so the classes in
+ * `component.ts` and `node.ts` can both depend on it without depending on each other.
+ */
+import type { World } from '../ecs/world';
+import type { ComponentDef } from '../ecs/component';
+import type { Entity } from '../types';
+import type { Component } from './component';
+import type { Node } from './node';
+
+/** A script class, as `new` sees it. */
+export type ComponentCtor<T extends Component = Component> = new (...args: any[]) => T;
+
+/** What a `@property` field holds, which decides how its stored value becomes the instance's value. */
+export type PropertyKind =
+ | 'number' | 'string' | 'boolean'
+ | 'node' // an entity reference, made a Node
+ | 'component' // an entity reference, made the instance of `type` on it
+ | 'asset' // a project-relative path
+ | 'vec2' | 'vec3' | 'color'
+ | 'json'; // anything else: kept as it is
+
+export interface PropertySpec {
+ name: string;
+ kind: PropertyKind;
+ /** The class a `node`/`component`/`asset` property names, when it named one. */
+ type?: unknown;
+ /** For a list of values, the kind of each. */
+ array?: boolean;
+}
+
+export interface ClassInfo {
+ ctor: ComponentCtor;
+ /** The class name as the script wrote it (`@ccclass('Name')` or the class's own name). */
+ name: string;
+ /** The Estella component name a scene stores: the class name under a prefix that keeps it clear of the engine's own. */
+ componentName: string;
+ def: ComponentDef<any>;
+ props: PropertySpec[];
+}
+
+/** Every Estella component name a compat class takes starts with this, so a script class named like an engine component cannot collide. */
+export const COMPONENT_PREFIX = 'Cocos.';
+
+const byCtor = new Map<Function, ClassInfo>();
+const byName = new Map<string, ClassInfo>();
+
+export function registerClassInfo(info: ClassInfo): void {
+ byCtor.set(info.ctor, info);
+ byName.set(info.name, info);
+ byName.set(info.componentName, info);
+}
+
+export function classInfoOf(ctor: Function): ClassInfo | undefined {
+ return byCtor.get(ctor);
+}
+
+/** A class by the name a script or a scene gives it: either the class name or the component name. */
+export function classInfoNamed(name: string): ClassInfo | undefined {
+ return byName.get(name);
+}
+
+export function allClassInfos(): IterableIterator<ClassInfo> {
+ return byCtor.values();
+}
+
+/** Forget every declaration (a test seam: classes are process-wide, as they are in Cocos). */
+export function resetClassRegistry(): void {
+ byCtor.clear();
+ byName.clear();
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+// Live instances.
+// ---------------------------------------------------------------------------------------------------------------------
+
+const instances = new WeakMap<World, Map<Entity, Map<Function, Component>>>();
+
+export function instancesOn(world: World, entity: Entity): Map<Function, Component> | undefined {
+ return instances.get(world)?.get(entity);
+}
+
+/** Every live instance of one class in a world, by entity. */
+export function instancesOfClass(world: World, ctor: Function): Array<[Entity, Component]> {
+ const out: Array<[Entity, Component]> = [];
+ const perEntity = instances.get(world);
+ if (!perEntity) return out;
+ for (const [entity, byClass] of perEntity) {
+ const inst = byClass.get(ctor);
+ if (inst) out.push([entity, inst]);
+ }
+ return out;
+}
+
+export function storeInstance(world: World, entity: Entity, ctor: Function, inst: Component): void {
+ let perEntity = instances.get(world);
+ if (!perEntity) instances.set(world, (perEntity = new Map()));
+ let byClass = perEntity.get(entity);
+ if (!byClass) perEntity.set(entity, (byClass = new Map()));
+ byClass.set(ctor, inst);
+}
+
+export function dropInstance(world: World, entity: Entity, ctor: Function): void {
+ const perEntity = instances.get(world);
+ const byClass = perEntity?.get(entity);
+ if (!byClass) return;
+ byClass.delete(ctor);
+ if (byClass.size === 0) perEntity!.delete(entity);
+}
+
+// ---------------------------------------------------------------------------------------------------------------------
+// The two late-bound pieces. `Node` and `ensureInstance` need each other, and a cycle of imports is worse than a setter.
+// ---------------------------------------------------------------------------------------------------------------------
+
+let nodeFactory: ((world: World, entity: Entity) => Node) | null = null;
+export function setNodeFactory(factory: (world: World, entity: Entity) => Node): void {
+ nodeFactory = factory;
+}
+export function nodeOf(world: World, entity: Entity): Node {
+ if (!nodeFactory) throw new Error('cocos compat: Node was not loaded; import from "esengine/cocos"');
+ return nodeFactory(world, entity);
+}
+
+let instantiator: ((world: World, entity: Entity, ctor: ComponentCtor) => Component | null) | null = null;
+export function setInstantiator(fn: (world: World, entity: Entity, ctor: ComponentCtor) => Component | null): void {
+ instantiator = fn;
+}
+/** The instance of @p ctor on @p entity, made (and its `onLoad` run) if the entity has the component and it has none yet; null if the entity does not have it. */
+export function ensureInstance(world: World, entity: Entity, ctor: ComponentCtor): Component | null {
+ const existing = instancesOn(world, entity)?.get(ctor);
+ if (existing) return existing;
+ return instantiator ? instantiator(world, entity, ctor) : null;
+}
diff --git a/sdk/tests/cocos/lifecycle.test.ts b/sdk/tests/cocos/lifecycle.test.ts
new file mode 100644
index 000000000..7f880ad61
--- /dev/null
+++ b/sdk/tests/cocos/lifecycle.test.ts
@@ -0,0 +1,277 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The Cocos compatibility layer: a script written against `cc` runs on the engine's own frame loop.
+ *
+ * The scripts here use real legacy decorators (this folder's tsconfig turns them on, as a Cocos project's does), and run through
+ * `App` and a `World` exactly as a game's would. What is pinned is what a Cocos script relies on and nothing else could tell it
+ * is wrong: the ORDER of the lifecycle, that `this.node` is the entity's node and the same object each time, that a property's
+ * stored value becomes the instance's value, and that switching a node off is not destroying it.
+ */
+import { beforeEach, describe, expect, it } from 'vitest';
+import { App, flushPendingRegistrations } from '../../src/app/app';
+import { AppContext, setDefaultContext } from '../../src/ecs/context';
+import { getUserComponents } from '../../src/ecs/component';
+import { resetClassRegistry } from '../../src/cocos/registry';
+import { Component, Node, Vec3, _decorator, director, find, isValid } from '../../src/cocos';
+
+const { ccclass, property } = _decorator;
+
+beforeEach(() => {
+ setDefaultContext(new AppContext());
+ resetClassRegistry();
+});
+
+async function boot(): Promise<App> {
+ const app = App.new();
+ flushPendingRegistrations(app);
+ return app;
+}
+
+const comp = (name: string) => getUserComponents().get(`Cocos.${name}`)!;
+
+describe('declaring a script class', () => {
+ it('makes an Estella component of it, carrying its property defaults and the enabled flag', () => {
+ @ccclass('Patrol')
+ class Patrol extends Component {
+ @property speed = 60;
+ @property label = 'hi';
+ @property loop = true;
+ @property(Node) target: Node | null = null;
+ @property tint = new Vec3(1, 2, 3);
+ }
+ void Patrol;
+ const def = comp('Patrol') as unknown as { _default: Record<string, unknown> } | undefined;
+ expect(def).toBeDefined();
+ expect(def!._default).toEqual({ enabled: true, speed: 60, label: 'hi', loop: true, target: 0, tint: { x: 1, y: 2, z: 3 } });
+ });
+
+ it('is named under a prefix, so a class named like an engine component cannot collide with it', () => {
+ @ccclass('Health')
+ class Health extends Component {}
+ void Health;
+ expect(getUserComponents().has('Cocos.Health')).toBe(true);
+ });
+
+ it('takes the class name when @ccclass is given none, and when it is applied bare', () => {
+ @ccclass
+ class Bare extends Component {}
+ @ccclass()
+ class Called extends Component {}
+ void Bare; void Called;
+ expect(getUserComponents().has('Cocos.Bare')).toBe(true);
+ expect(getUserComponents().has('Cocos.Called')).toBe(true);
+ });
+});
+
+describe('the lifecycle', () => {
+ function lifecycle(events: string[]) {
+ @ccclass('Life')
+ class Life extends Component {
+ onLoad() { events.push('onLoad'); }
+ onEnable() { events.push('onEnable'); }
+ start() { events.push('start'); }
+ update(dt: number) { events.push(`update:${dt > 0 ? 'dt' : '0'}`); }
+ lateUpdate() { events.push('lateUpdate'); }
+ onDisable() { events.push('onDisable'); }
+ onDestroy() { events.push('onDestroy'); }
+ }
+ return Life;
+ }
+
+ it('runs in the order Cocos does: onLoad, onEnable, start, then update and lateUpdate each frame', async () => {
+ const events: string[] = [];
+ lifecycle(events);
+ const app = await boot();
+ const e = app.world.spawn('life');
+ app.world.insert(e, comp('Life'), { enabled: true });
+ await app.tick(1 / 60);
+ await app.tick(1 / 60);
+ expect(events).toEqual(['onLoad', 'onEnable', 'start', 'update:dt', 'lateUpdate', 'update:dt', 'lateUpdate']);
+ });
+
+ it('ends with onDisable then onDestroy when the entity is despawned', async () => {
+ const events: string[] = [];
+ lifecycle(events);
+ const app = await boot();
+ const e = app.world.spawn('life');
+ app.world.insert(e, comp('Life'), { enabled: true });
+ await app.tick(1 / 60);
+ events.length = 0;
+ app.world.despawn(e);
+ await app.tick(1 / 60);
+ expect(events).toEqual(['onDisable', 'onDestroy']);
+ });
+
+ it('treats switching a node off as disabling it, not destroying it, and back on as enabling it again', async () => {
+ const events: string[] = [];
+ lifecycle(events);
+ const app = await boot();
+ const e = app.world.spawn('life');
+ app.world.insert(e, comp('Life'), { enabled: true });
+ await app.tick(1 / 60);
+ events.length = 0;
+
+ Node.for(app.world, e).active = false;
+ await app.tick(1 / 60);
+ expect(events).toEqual(['onDisable']); // no update while off, and no onDestroy
+
+ events.length = 0;
+ Node.for(app.world, e).active = true;
+ await app.tick(1 / 60);
+ expect(events).toEqual(['onEnable', 'update:dt', 'lateUpdate']); // start does not run a second time
+ });
+
+ it('does not let one script throwing stop the rest', async () => {
+ const events: string[] = [];
+ @ccclass('Bad')
+ class Bad extends Component { update() { throw new Error('boom'); } }
+ @ccclass('Good')
+ class Good extends Component { update() { events.push('good'); } }
+ void Bad; void Good;
+ const app = await boot();
+ const a = app.world.spawn('a'), b = app.world.spawn('b');
+ app.world.insert(a, comp('Bad'), { enabled: true });
+ app.world.insert(b, comp('Good'), { enabled: true });
+ await app.tick(1 / 60);
+ await app.tick(1 / 60);
+ expect(events).toEqual(['good', 'good']);
+ });
+});
+
+describe('this.node', () => {
+ it('is the entity node, and the same object every time', async () => {
+ let seen: Node | null = null;
+ let again: Node | null = null;
+ @ccclass('Who')
+ class Who extends Component {
+ onLoad() { seen = this.node; again = Node.for(this._world, this._entity); }
+ }
+ void Who;
+ const app = await boot();
+ const e = app.world.spawn('hero');
+ app.world.insert(e, comp('Who'), { enabled: true });
+ await app.tick(1 / 60);
+ expect(seen).not.toBeNull();
+ expect(seen!.name).toBe('hero');
+ expect(seen).toBe(again);
+ });
+
+ it('finds a sibling component through getComponent, the same instance each time', async () => {
+ const found: unknown[] = [];
+ @ccclass('Other')
+ class Other extends Component { @property hp = 5; }
+ @ccclass('Seeker')
+ class Seeker extends Component {
+ start() { found.push(this.getComponent(Other), this.node.getComponent(Other), this.getComponent('Other')); }
+ }
+ void Seeker;
+ const app = await boot();
+ const e = app.world.spawn('both');
+ app.world.insert(e, comp('Other'), { enabled: true, hp: 9 });
+ app.world.insert(e, comp('Seeker'), { enabled: true });
+ await app.tick(1 / 60);
+ expect(found).toHaveLength(3);
+ expect(found[0]).toBeInstanceOf(Other);
+ expect((found[0] as { hp: number }).hp).toBe(9); // the stored value, not the initializer
+ expect(found[1]).toBe(found[0]);
+ expect(found[2]).toBe(found[0]);
+ });
+
+ it('answers null for a component the node does not have', async () => {
+ let got: unknown = 'unset';
+ @ccclass('Lone')
+ class Lone extends Component {
+ @property x = 0;
+ onLoad() { got = this.node.getComponent('Nope'); }
+ }
+ void Lone;
+ const app = await boot();
+ const e = app.world.spawn('x');
+ app.world.insert(e, comp('Lone'), { enabled: true, x: 0 });
+ await app.tick(1 / 60);
+ expect(got).toBeNull();
+ });
+});
+
+describe('properties', () => {
+ it('hand the instance the stored value in the Cocos type: a Vec3 for a vector, a Node for a node reference', async () => {
+ let seen: { speed?: number; dir?: unknown; target?: unknown } = {};
+ @ccclass('Props')
+ class Props extends Component {
+ @property speed = 1;
+ @property dir = new Vec3();
+ @property(Node) target: Node | null = null;
+ onLoad() { seen = { speed: this.speed, dir: this.dir, target: this.target }; }
+ }
+ void Props;
+ const app = await boot();
+ const other = app.world.spawn('other');
+ const e = app.world.spawn('holder');
+ app.world.insert(e, comp('Props'), { enabled: true, speed: 42, dir: { x: 1, y: 2, z: 3 }, target: other });
+ await app.tick(1 / 60);
+ expect(seen.speed).toBe(42);
+ expect(seen.dir).toBeInstanceOf(Vec3);
+ expect((seen.dir as Vec3).y).toBe(2);
+ expect(seen.target).toBeInstanceOf(Node);
+ expect((seen.target as Node).name).toBe('other');
+ });
+
+ it('declare the node-typed ones as entity references, so a scene remaps them on load', () => {
+ @ccclass('Refs')
+ class Refs extends Component {
+ @property(Node) a: Node | null = null;
+ @property([Node]) list: Node[] = [];
+ @property n = 0;
+ }
+ void Refs;
+ const def = comp('Refs') as unknown as { entityFields: string[] };
+ expect([...def.entityFields].sort()).toEqual(['a', 'list']);
+ });
+});
+
+describe('scheduling', () => {
+ it('scheduleOnce fires once after its delay, and schedule repeats at its interval until unscheduled', async () => {
+ const log: string[] = [];
+ @ccclass('Timers')
+ class Timers extends Component {
+ start() {
+ this.scheduleOnce(() => log.push('once'), 0.05);
+ const tick = (): void => { log.push('tick'); if (log.filter((l) => l === 'tick').length === 3) this.unschedule(tick); };
+ this.schedule(tick, 0.02);
+ }
+ }
+ void Timers;
+ const app = await boot();
+ const e = app.world.spawn('t');
+ app.world.insert(e, comp('Timers'), { enabled: true });
+ for (let i = 0; i < 12; i++) await app.tick(0.01);
+ expect(log.filter((l) => l === 'once')).toHaveLength(1);
+ expect(log.filter((l) => l === 'tick')).toHaveLength(3);
+ });
+});
+
+describe('director, find, isValid', () => {
+ // Hierarchy and transforms live in the C++ registry, so what needs a parent is tested against the real engine (node-wasm.test.ts).
+ it('find a root node by name, and report a despawned one as invalid', async () => {
+ let canvas: Node | null = null;
+ @ccclass('Finder')
+ class Finder extends Component {
+ onLoad() {
+ canvas = find('Canvas');
+ expect(director.getScene()!.getChildByName('Canvas')).toBe(canvas);
+ }
+ }
+ void Finder;
+ const app = await boot();
+ const c = app.world.spawn('Canvas');
+ const h = app.world.spawn('host');
+ app.world.insert(h, comp('Finder'), { enabled: true });
+ await app.tick(1 / 60);
+ expect(canvas).toBe(Node.for(app.world, c));
+ expect(isValid(canvas)).toBe(true);
+ app.world.despawn(c);
+ expect(isValid(canvas)).toBe(false);
+ expect(isValid(null)).toBe(false);
+ });
+});
diff --git a/sdk/tests/cocos/node-wasm.test.ts b/sdk/tests/cocos/node-wasm.test.ts
new file mode 100644
index 000000000..8359e5cfb
--- /dev/null
+++ b/sdk/tests/cocos/node-wasm.test.ts
@@ -0,0 +1,191 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file `Node` against the real engine: hierarchy, transform and activity live in the C++ registry, so these run on the built
+ * wasm core and skip where there is none.
+ *
+ * What is pinned is what a Cocos script cannot be told is wrong: that a handle is the entity (`===`), that a position set is a
+ * position got, that `setWorldPosition` under a rotated, scaled parent lands where it was asked to, and that a tree walks the
+ * way `getChildByPath` and `find` say.
+ */
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+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 { Node, Quat, Vec3, director, find, setCurrentWorld } from '../../src/cocos';
+import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';
+
+describe.skipIf(!HAS_WASM)('Node on the engine', () => {
+ // After connect() both are set; the tests read them through these.
+ const W = (): World => world!;
+ let module: ESEngineModule;
+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;
+ let world: World | undefined;
+
+ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });
+
+ function connect(): void {
+ setDefaultContext(new AppContext());
+ registry = new module.Registry();
+ world = new World();
+ world.connectCpp(registry, module);
+ setCurrentWorld(world);
+ }
+ afterEach(() => {
+ setCurrentWorld(null);
+ world?.disconnectCpp();
+ registry?.delete();
+ registry = undefined;
+ world = undefined;
+ });
+
+ /** The names of nodes: comparing Node objects deeply would walk the whole world they hold. */
+ const names = (nodes: Node[]): string[] => nodes.map((n) => n.name);
+
+ /** Canvas > Panel > Button, with Canvas also holding Label. */
+ function tree(): Record<'canvas' | 'panel' | 'button' | 'label', Node> {
+ const mk = (name: string): Node => { const n = new Node(name); W().insert(n._entity, Transform); return n; };
+ const canvas = mk('Canvas'), panel = mk('Panel'), button = mk('Button'), label = mk('Label');
+ canvas.addChild(panel); canvas.addChild(label); panel.addChild(button);
+ return { canvas, panel, button, label };
+ }
+
+ it('walks a hierarchy the way a script reads it', () => {
+ connect();
+ const { canvas, panel, button, label } = tree();
+ expect(button.parent).toBe(panel);
+ expect(panel.parent).toBe(canvas);
+ expect(canvas.parent).toBeNull();
+ expect(names(canvas.children)).toEqual(['Panel', 'Label']);
+ expect(canvas.getChildByName('Panel')).toBe(panel);
+ expect(canvas.getChildByName('Nope')).toBeNull();
+ expect(canvas.getChildByPath('Panel/Button')).toBe(button);
+ expect(button.isChildOf(canvas)).toBe(true);
+ expect(canvas.isChildOf(button)).toBe(false);
+ });
+
+ it('detaches with removeFromParent, and moves with setParent', () => {
+ connect();
+ const { canvas, panel, button, label } = tree();
+ button.removeFromParent();
+ expect(button.parent).toBeNull();
+ expect(panel.children).toHaveLength(0);
+ button.setParent(label);
+ expect(names(label.children)).toEqual(['Button']);
+ expect(names(canvas.children)).toEqual(['Panel', 'Label']);
+ });
+
+ it('holds a position, a scale and a rotation as the values that were set', () => {
+ connect();
+ const { panel } = tree();
+ panel.setPosition(10, 20, 30);
+ expect(panel.position.x).toBe(10);
+ expect(panel.position.y).toBe(20);
+ expect(panel.position.z).toBe(30);
+ panel.setPosition(new Vec3(1, 2, 3));
+ expect(panel.getPosition().equals(new Vec3(1, 2, 3))).toBe(true);
+ // x and y only: z stays
+ panel.setPosition(7, 8);
+ expect(panel.position.z).toBe(3);
+ panel.setScale(2, 3);
+ expect(panel.scale.x).toBe(2);
+ expect(panel.scale.y).toBe(3);
+ panel.setRotationFromEuler(0, 0, 90);
+ expect(panel.angle).toBeCloseTo(90, 4);
+ panel.angle = 45;
+ expect(panel.eulerAngles.z).toBeCloseTo(45, 4);
+ });
+
+ it('reads a changed position back as a new object, so mutating it does not move the node', () => {
+ connect();
+ const { panel } = tree();
+ panel.setPosition(5, 5, 0);
+ const p = panel.position;
+ p.x = 99;
+ expect(panel.position.x).toBe(5);
+ panel.position = p;
+ expect(panel.position.x).toBe(99);
+ });
+
+ it('places a node in world space under a parent that is moved, rotated and scaled', async () => {
+ connect();
+ const { canvas, panel } = tree();
+ canvas.setPosition(100, 50, 0);
+ canvas.setRotationFromEuler(0, 0, 90);
+ canvas.setScale(2, 2, 1);
+ panel.setWorldPosition(new Vec3(100, 150, 0));
+ const got = panel.worldPosition;
+ expect(got.x).toBeCloseTo(100, 3);
+ expect(got.y).toBeCloseTo(150, 3);
+ });
+
+ it('switches off with its subtree and reports it per node', () => {
+ connect();
+ const { canvas, panel, button } = tree();
+ panel.active = false;
+ expect(panel.active).toBe(false);
+ expect(panel.activeInHierarchy).toBe(false);
+ expect(button.active).toBe(true); // its own switch is untouched
+ expect(button.activeInHierarchy).toBe(false); // an ancestor's takes it out
+ expect(canvas.activeInHierarchy).toBe(true);
+ panel.active = true;
+ expect(button.activeInHierarchy).toBe(true);
+ });
+
+ it('destroys a node and reports it invalid', () => {
+ connect();
+ const { panel } = tree();
+ expect(panel.isValid).toBe(true);
+ panel.destroy();
+ expect(panel.isValid).toBe(false);
+ expect(panel.destroy()).toBe(false);
+ });
+
+ it('finds nodes by path from the scene roots, with find and the scene', () => {
+ connect();
+ const { canvas, panel, button } = tree();
+ expect(find('Canvas')).toBe(canvas);
+ expect(find('Canvas/Panel')).toBe(panel);
+ expect(find('Canvas/Panel/Button')).toBe(button);
+ expect(find('Canvas/Nope')).toBeNull();
+ expect(find('Button')).toBe(button); // a bare name searches everything
+ expect(names(director.getScene()!.children)).toEqual(['Canvas']);
+ expect(find('Panel/Button', canvas)).toBe(button); // relative to a node
+ });
+
+ it('delivers an event to its listeners with the target as this, once for once, and not after off', () => {
+ connect();
+ const { panel } = tree();
+ const log: string[] = [];
+ const target = { id: 't' };
+ const handler = function (this: { id: string }, arg: number): void { log.push(`${this.id}:${arg}`); };
+ panel.on('custom', handler, target);
+ panel.once('custom', () => log.push('once'));
+ panel.emit('custom', 1);
+ panel.emit('custom', 2);
+ panel.off('custom', handler, target);
+ panel.emit('custom', 3);
+ expect(log).toEqual(['t:1', 'once', 't:2']);
+ });
+});
+
+describe('Euler angles', () => {
+ it('round-trip through a quaternion, using Cocos own formulas', () => {
+ for (const [x, y, z] of [[0, 0, 90], [0, 0, 45], [30, 0, 0], [0, 60, 0], [20, 40, 70], [0, 0, -135]] as const) {
+ const e = Quat.toEuler(new Vec3(), Quat.fromEuler(new Quat(), x, y, z));
+ const back = Quat.fromEuler(new Quat(), e.x, e.y, e.z);
+ const q = Quat.fromEuler(new Quat(), x, y, z);
+ // the same rotation, whichever of the two equal quaternions (q and -q) came back
+ const dot = Math.abs(q.x * back.x + q.y * back.y + q.z * back.z + q.w * back.w);
+ expect(dot).toBeCloseTo(1, 5);
+ }
+ });
+
+ it('a rotation about z alone reads back as that angle', () => {
+ const e = Quat.toEuler(new Vec3(), Quat.fromEuler(new Quat(), 0, 0, 45));
+ expect(e.z).toBeCloseTo(45, 4);
+ expect(e.x).toBeCloseTo(0, 4);
+ expect(e.y).toBeCloseTo(0, 4);
+ });
+});
diff --git a/sdk/tests/cocos/tsconfig.json b/sdk/tests/cocos/tsconfig.json
new file mode 100644
index 000000000..ea397a74e
--- /dev/null
+++ b/sdk/tests/cocos/tsconfig.json
@@ -0,0 +1,7 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "experimentalDecorators": true,
+ "useDefineForClassFields": false
+ }
+}