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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(cocos): instantiate (prepared prefab or node copy, held out of the scene until parented) and tween (to/by/set/delay/call/then/union/sequence/parallel/repeat, easing, Tween.stopAll*); the importer numbers scene entities from 1 so a reference to the first one is not read as none
yhhca89d70e856f
diff --git a/pipeline/src/import/cocos/convert.ts b/pipeline/src/import/cocos/convert.tsindex ea5419ec1..530fe0e6b 100644--- a/pipeline/src/import/cocos/convert.ts+++ b/pipeline/src/import/cocos/convert.ts@@ -362,7 +362,8 @@ export function convertPrefab(doc: CocosDocument, ctx: ConvertContext): PrefabFiexport function convertScene(doc: CocosDocument, ctx: ConvertContext): SceneFile {const entities: (SceneEntity | SceneInstanceEntry)[] = [];ctx.report.documents.converted++;- let next = 0;+ // From 1: 0 is the engine's "no entity", and a reference to an entity numbered 0 would read as none.+ let next = 1;// Ids are given before any node is converted, so a reference to a node that comes later in the file has something to point at.const ids = new Map<string, number>();const assign = (n: CocosNode): void => {diff --git a/pipeline/tests/cocos-import.test.ts b/pipeline/tests/cocos-import.test.tsindex 6bd0389cd..b24a0070c 100644--- a/pipeline/tests/cocos-import.test.ts+++ b/pipeline/tests/cocos-import.test.ts@@ -237,7 +237,7 @@ describe('importing a Cocos project', () => {it('turns a scene\'s prefab instance into an entry with the overrides it applied', () => {const scene = readJson('assets/cocos/main.esscene');const entry = scene.entities.find((e: any) => typeof e.prefab === 'string');- expect(entry).toMatchObject({ prefab: 'assets/cocos/ui/panel.esprefab', parent: 0, added: [], removed: [] });+ expect(entry).toMatchObject({ prefab: 'assets/cocos/ui/panel.esprefab', parent: 1, added: [], removed: [] });// 'instB/itemRoot' addresses the engine's composed id for the nested root: slot / local idexpect(entry.overrides).toEqual([expect.objectContaining({ prefabEntityId: 'instB/itemRoot', type: 'property', componentType: 'Transform', propertyName: 'position', value: { x: 9, y: 9, z: 0 } }),diff --git a/sdk/src/cocos/assets.ts b/sdk/src/cocos/assets.tsindex 2ca80c78c..d5282b878 100644--- a/sdk/src/cocos/assets.ts+++ b/sdk/src/cocos/assets.ts@@ -14,7 +14,19 @@ 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 {}+/** Prepared prefabs by path: shared by every `Prefab` handle that names the path. */+export const preparedPrefabs = new Map<string, unknown>();++/**+ * A prefab a script holds. `instantiate` is synchronous in Cocos, which is only possible because the prefab was loaded first; here+ * that is the prepared form (see prefabs.ts), made once per path as soon as a script holds the handle.+ */+export class Prefab extends Asset {+ /** The engine's prepared prefab, once it has loaded. @internal */+ get _prepared(): unknown { return preparedPrefabs.get(this.path); }+ /** Why preparing failed, when it did. @internal */+ _failed = '';+}export class AudioClip extends Asset {}export class Material extends Asset {}export class JsonAsset extends Asset {}diff --git a/sdk/src/cocos/builtinScripts.ts b/sdk/src/cocos/builtinScripts.tsindex a581e93ad..da30433b4 100644--- a/sdk/src/cocos/builtinScripts.ts+++ b/sdk/src/cocos/builtinScripts.ts@@ -13,6 +13,8 @@ import { declareButton } from './ui/button';import { declareInputSystem } from './input';import { declareUiPass } from './ui/pass';import { uiTransformDef } from './ui/uiTransform';+import { declareTweenSystem } from './tween';+import { declarePrefabSystem } from './prefabs';import { resetClassRegistry } from './registry';const declared = new WeakSet<object>();@@ -27,6 +29,8 @@ export function declareBuiltinScripts(): void {// A scene holds `Cocos.UITransform` before any script asks for one, so the component has to exist when it loads.uiTransformDef();declareUiPass();+ declareTweenSystem();+ declarePrefabSystem();}/** Test seam: forget the registry and declare again into the (possibly new) current context. */diff --git a/sdk/src/cocos/easing.ts b/sdk/src/cocos/easing.tsnew file mode 100644index 000000000..dee3f080f--- /dev/null+++ b/sdk/src/cocos/easing.ts@@ -0,0 +1,109 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cocos/easing.ts+ * @brief The easing curves a tween names: `'sineOut'`, `'backInOut'`, … and the functions behind them.+ *+ * Each curve takes progress 0..1 and returns eased progress. The families are the standard ones (Penner's), with the+ * parameters Cocos uses where a curve has any (elastic's amplitude and period, back's overshoot).+ */+export type EasingFunction = (k: number) => number;++const PI = Math.PI;++const quadIn: EasingFunction = (k) => k * k;+const quadOut: EasingFunction = (k) => k * (2 - k);+const quadInOut: EasingFunction = (k) => ((k *= 2) < 1 ? 0.5 * k * k : -0.5 * (--k * (k - 2) - 1));+const cubicIn: EasingFunction = (k) => k * k * k;+const cubicOut: EasingFunction = (k) => --k * k * k + 1;+const cubicInOut: EasingFunction = (k) => ((k *= 2) < 1 ? 0.5 * k * k * k : 0.5 * ((k -= 2) * k * k + 2));+const quartIn: EasingFunction = (k) => k * k * k * k;+const quartOut: EasingFunction = (k) => 1 - --k * k * k * k;+const quartInOut: EasingFunction = (k) => ((k *= 2) < 1 ? 0.5 * k * k * k * k : -0.5 * ((k -= 2) * k * k * k - 2));+const quintIn: EasingFunction = (k) => k * k * k * k * k;+const quintOut: EasingFunction = (k) => --k * k * k * k * k + 1;+const quintInOut: EasingFunction = (k) => ((k *= 2) < 1 ? 0.5 * k * k * k * k * k : 0.5 * ((k -= 2) * k * k * k * k + 2));+const sineIn: EasingFunction = (k) => (k === 1 ? 1 : 1 - Math.cos((k * PI) / 2));+const sineOut: EasingFunction = (k) => Math.sin((k * PI) / 2);+const sineInOut: EasingFunction = (k) => 0.5 * (1 - Math.cos(PI * k));+const expoIn: EasingFunction = (k) => (k === 0 ? 0 : 1024 ** (k - 1));+const expoOut: EasingFunction = (k) => (k === 1 ? 1 : 1 - 2 ** (-10 * k));+const expoInOut: EasingFunction = (k) => {+ if (k === 0) return 0;+ if (k === 1) return 1;+ if ((k *= 2) < 1) return 0.5 * 1024 ** (k - 1);+ return 0.5 * (-(2 ** (-10 * (k - 1))) + 2);+};+const circIn: EasingFunction = (k) => 1 - Math.sqrt(1 - k * k);+const circOut: EasingFunction = (k) => Math.sqrt(1 - --k * k);+const circInOut: EasingFunction = (k) => ((k *= 2) < 1 ? -0.5 * (Math.sqrt(1 - k * k) - 1) : 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1));++const elasticIn: EasingFunction = (k) => {+ if (k === 0) return 0;+ if (k === 1) return 1;+ const a = 0.1, p = 0.4;+ const s = p / 4;+ return -(1 * 2 ** (10 * (k -= 1)) * Math.sin(((k - s) * 2 * PI) / p)) * (a / a);+};+const elasticOut: EasingFunction = (k) => {+ if (k === 0) return 0;+ if (k === 1) return 1;+ const p = 0.4;+ const s = p / 4;+ return 2 ** (-10 * k) * Math.sin(((k - s) * 2 * PI) / p) + 1;+};+const elasticInOut: EasingFunction = (k) => {+ if (k === 0) return 0;+ if (k === 1) return 1;+ const p = 0.4 * 1.5;+ const s = p / 4;+ if ((k *= 2) < 1) return -0.5 * 2 ** (10 * (k -= 1)) * Math.sin(((k - s) * 2 * PI) / p);+ return 2 ** (-10 * (k -= 1)) * Math.sin(((k - s) * 2 * PI) / p) * 0.5 + 1;+};++const S = 1.70158;+const backIn: EasingFunction = (k) => (k === 1 ? 1 : k * k * ((S + 1) * k - S));+const backOut: EasingFunction = (k) => (k === 0 ? 0 : --k * k * ((S + 1) * k + S) + 1);+const backInOut: EasingFunction = (k) => {+ const s = S * 1.525;+ if ((k *= 2) < 1) return 0.5 * (k * k * ((s + 1) * k - s));+ return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);+};++const bounceOut: EasingFunction = (k) => {+ if (k < 1 / 2.75) return 7.5625 * k * k;+ if (k < 2 / 2.75) return 7.5625 * (k -= 1.5 / 2.75) * k + 0.75;+ if (k < 2.5 / 2.75) return 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375;+ return 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375;+};+const bounceIn: EasingFunction = (k) => 1 - bounceOut(1 - k);+const bounceInOut: EasingFunction = (k) => (k < 0.5 ? bounceIn(k * 2) * 0.5 : bounceOut(k * 2 - 1) * 0.5 + 0.5);++/** The curve that runs the "out" half first, then the "in" half. */+const outIn = (out: EasingFunction, inn: EasingFunction): EasingFunction => (k) => (k < 0.5 ? 0.5 * out(2 * k) : 0.5 * inn(2 * k - 1) + 0.5);++export const easing = {+ linear: ((k) => k) as EasingFunction,+ smooth: ((k) => (k <= 0 ? 0 : k >= 1 ? 1 : k * k * (3 - 2 * k))) as EasingFunction,+ fade: ((k) => (k <= 0 ? 0 : k >= 1 ? 1 : k * k * k * (k * (k * 6 - 15) + 10))) as EasingFunction,+ constant: ((k) => (k >= 1 ? 1 : 0)) as EasingFunction,+ quadIn, quadOut, quadInOut, quadOutIn: outIn(quadOut, quadIn),+ cubicIn, cubicOut, cubicInOut, cubicOutIn: outIn(cubicOut, cubicIn),+ quartIn, quartOut, quartInOut, quartOutIn: outIn(quartOut, quartIn),+ quintIn, quintOut, quintInOut, quintOutIn: outIn(quintOut, quintIn),+ sineIn, sineOut, sineInOut, sineOutIn: outIn(sineOut, sineIn),+ expoIn, expoOut, expoInOut, expoOutIn: outIn(expoOut, expoIn),+ circIn, circOut, circInOut, circOutIn: outIn(circOut, circIn),+ elasticIn, elasticOut, elasticInOut, elasticOutIn: outIn(elasticOut, elasticIn),+ backIn, backOut, backInOut, backOutIn: outIn(backOut, backIn),+ bounceIn, bounceOut, bounceInOut, bounceOutIn: outIn(bounceOut, bounceIn),+} as const;++export type EasingName = keyof typeof easing;++/** A curve by name or function; an unknown name is linear, as a mistyped name is in Cocos. */+export function resolveEasing(e: EasingName | EasingFunction | string | undefined): EasingFunction {+ if (typeof e === 'function') return e;+ if (typeof e === 'string' && e in easing) return easing[e as EasingName];+ return easing.linear;+}diff --git a/sdk/src/cocos/host.ts b/sdk/src/cocos/host.tsindex 36478a480..1b3dcbd76 100644--- a/sdk/src/cocos/host.ts+++ b/sdk/src/cocos/host.ts@@ -47,6 +47,8 @@ function inferKind(value: unknown): PropertyKind {return 'json';}import type { Component } from './component';+import { Prefab, type Asset } from './assets';+import { requestPrepare } from './prefabs';/** 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 {@@ -65,6 +67,13 @@ function storedDefault(spec: PropertySpec, value: unknown): unknown {}}+/** An asset path as the asset class the script named; a prefab starts loading the moment a script holds it. */+function asAsset(type: Function, path: string): unknown {+ const asset = new (type as new (path: string) => Asset)(path);+ if (asset instanceof Prefab) requestPrepare(path);+ return asset;+}+/** What a stored value becomes on an instance. */function liveValue(world: World, spec: PropertySpec, stored: unknown): unknown {const one = (v: unknown): unknown => {@@ -78,6 +87,7 @@ function liveValue(world: World, spec: PropertySpec, stored: unknown): unknown {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();+ case 'asset': return typeof v === 'string' && v !== '' && typeof spec.type === 'function' ? asAsset(spec.type, v) : v;default: return v;}};diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.tsindex 305c378fb..71a18ad00 100644--- a/sdk/src/cocos/index.ts+++ b/sdk/src/cocos/index.ts@@ -27,6 +27,8 @@ export {export { registerBuiltinComponent, type BuiltinAdapter } from './builtins';export { UITransform, Label, LabelOutline, LabelShadow, Sprite, UIOpacity, Button, EventHandler, Widget, Layout, getVisibleSize, setVisibleSize } from './ui';export { Touch, EventTouch, pumpTouches } from './input';+export { tween, Tween, tweenUtil, easing, updateTweens } from './tween';+export { instantiate, loadPrefab, providePrefab } from './prefabs';export { declareBuiltinScripts, redeclareBuiltinScripts } from './builtinScripts';/** `cc/env` is the same module here: its flags are named exports beside the rest. */export * from './env';diff --git a/sdk/src/cocos/math.ts b/sdk/src/cocos/math.tsindex 4831da78e..763a9d408 100644--- a/sdk/src/cocos/math.ts+++ b/sdk/src/cocos/math.ts@@ -98,6 +98,25 @@ export class Quat {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. */+ /** Spherical interpolation from @p a to @p b, written to @p out. */+ static slerp(out: Quat, a: Quat, b: Quat, t: number): Quat {+ let cosom = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;+ let bx = b.x, by = b.y, bz = b.z, bw = b.w;+ if (cosom < 0) { cosom = -cosom; bx = -bx; by = -by; bz = -bz; bw = -bw; }+ let scale0 = 1 - t, scale1 = t;+ if (1 - cosom > 1e-6) {+ const omega = Math.acos(cosom);+ const sinom = Math.sin(omega);+ scale0 = Math.sin((1 - t) * omega) / sinom;+ scale1 = Math.sin(t * omega) / sinom;+ }+ out.x = scale0 * a.x + scale1 * bx;+ out.y = scale0 * a.y + scale1 * by;+ out.z = scale0 * a.z + scale1 * bz;+ out.w = scale0 * a.w + scale1 * bw;+ return out;+ }+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);diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.tsindex 02d5e66db..a470643be 100644--- a/sdk/src/cocos/node.ts+++ b/sdk/src/cocos/node.ts@@ -27,6 +27,32 @@ 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. */+// A node made by `instantiate` is not in the scene until it is given a parent. The entity exists in the world from the start, so it+// is held switched off, and `active` keeps answering what the node itself was made as; the first `addChild` lets it in.+const detached = new WeakMap<World, Map<Entity, boolean>>();++/** Hold a freshly instantiated root out of the scene until it has a parent. @internal */+export function markDetached(world: World, entity: Entity): void {+ let perWorld = detached.get(world);+ if (!perWorld) detached.set(world, (perWorld = new Map()));+ perWorld.set(entity, !world.has(entity, Disabled));+ setEntityActive(world, entity, false);+}+function detachedActive(world: World, entity: Entity): boolean | undefined { return detached.get(world)?.get(entity); }+function setDetachedActive(world: World, entity: Entity, value: boolean): boolean {+ const perWorld = detached.get(world);+ if (!perWorld?.has(entity)) return false;+ perWorld.set(entity, value);+ return true;+}+function releaseDetached(world: World, entity: Entity): void {+ const perWorld = detached.get(world);+ const wasActive = perWorld?.get(entity);+ if (wasActive === undefined) return;+ perWorld!.delete(entity);+ setEntityActive(world, entity, wasActive);+}+export function setCurrentWorld(world: World | null): World | null { const previous = currentWorld; currentWorld = world; return previous; }export function getCurrentWorld(): World | null { return currentWorld; }@@ -106,8 +132,11 @@ export class Node {// ---- 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); }+ get active(): boolean { return detachedActive(this._world, this._entity) ?? !this._world.has(this._entity, Disabled); }+ set active(value: boolean) {+ if (setDetachedActive(this._world, this._entity, value)) return;+ setEntityActive(this._world, this._entity, value);+ }/** This node's switch and every ancestor's. */get activeInHierarchy(): boolean { return this._world.isEntityActive(this._entity); }@@ -127,8 +156,10 @@ export class Node {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);+ if (parent) {+ this._world.setParent(this._entity, parent._entity);+ releaseDetached(this._world, this._entity);+ } else this._world.removeParent(this._entity);}addChild(child: Node): void { child.setParent(this); }diff --git a/sdk/src/cocos/prefabs.ts b/sdk/src/cocos/prefabs.tsnew file mode 100644index 000000000..392bf5f94--- /dev/null+++ b/sdk/src/cocos/prefabs.ts@@ -0,0 +1,149 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cocos/prefabs.ts+ * @brief `instantiate(prefab)` and `instantiate(node)`.+ *+ * Cocos's `instantiate` answers a node at once, because its prefabs are loaded before a script can hold them. The engine's+ * prefab spawn is asynchronous for the same reason the other way round: loading is what it does. The bridge is the engine's+ * *prepared prefab* (prefab/preparedPrefab.ts) — load once, with every asset the prefab names, then spawn synchronously any+ * number of times. A script that holds a `Prefab` (a `@property(Prefab)` field) causes that preparation to start, so by the time+ * a click handler runs it is ready; an `instantiate` before then says so rather than returning something half made.+ *+ * What comes back is out of the scene until it is given a parent, as in Cocos: the entity is made, held switched off, and let in+ * by the first `addChild` (see `markDetached` in node.ts).+ */+import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';+import { Res } from '../ecs/resource';+import { Assets } from '../asset/AssetPlugin';+import type { Assets as AssetsClass } from '../asset/Assets';+import { preparePrefab, spawnPrepared, type PreparedPrefab } from '../prefab/preparedPrefab';+import { getComponent } from '../ecs/component';+import { Children, Name, Parent } from '../ecs/component';+import { loadSceneData, serializeEntityComponents, SCENE_FORMAT_VERSION, type SceneData } from '../scene/scene';+import type { World } from '../ecs/world';+import type { Entity } from '../types';+import { log } from '../util/logger';+import { Node, getCurrentWorld, markDetached } from './node';+import { Prefab, preparedPrefabs } from './assets';++const assetsOf = new WeakMap<World, AssetsClass>();+const wanted = new Set<string>();+const inFlight = new Set<string>();++/** Start preparing the prefab at @p path, once the engine's asset loader is there to do it. */+export function requestPrepare(path: string): void {+ if (path && !preparedPrefabs.has(path) && !inFlight.has(path)) wanted.add(path);+}++/** Hand the layer a prefab already prepared (a host that loaded it its own way, or a test). */+export function providePrefab(path: string, prepared: PreparedPrefab): void {+ preparedPrefabs.set(path, prepared);+}++/** Prepare a prefab and answer when it is ready to `instantiate`. */+export function loadPrefab(path: string, world: World | null = getCurrentWorld()): Promise<Prefab> {+ const assets = world ? assetsOf.get(world) : undefined;+ if (preparedPrefabs.has(path)) return Promise.resolve(new Prefab(path));+ if (!assets) return Promise.reject(new Error(`cocos compat: cannot load prefab "${path}": the engine's asset loader is not running`));+ return preparePrefab(assets, path).then((p) => { preparedPrefabs.set(path, p); return new Prefab(path); });+}++function drain(assets: AssetsClass): void {+ for (const path of wanted) {+ wanted.delete(path);+ inFlight.add(path);+ preparePrefab(assets, path)+ .then((p) => { preparedPrefabs.set(path, p); })+ .catch((err) => { log.warn('cocos', `prefab "${path}" could not be prepared: ${String(err)}`); })+ .finally(() => { inFlight.delete(path); });+ }+}++/** The system that learns where the asset loader is and starts the preparations scripts asked for. */+export function declarePrefabSystem(): void {+ const system = defineSystem(+ [Res(Assets), GetWorld()],+ (assets, world) => {+ if (!assets) return;+ assetsOf.set(world, assets as AssetsClass);+ if (wanted.size > 0) drain(assets as AssetsClass);+ },+ { name: 'Cocos:Prefabs', touches: { opaque: true } },+ );+ addSystemToSchedule(Schedule.First, system);+}++// ---------------------------------------------------------------------------------------------------------------------+// instantiate+// ---------------------------------------------------------------------------------------------------------------------++function subtreeOf(world: World, root: Entity): Entity[] {+ const out: Entity[] = [];+ const visit = (e: Entity): void => {+ out.push(e);+ for (const c of world.tryGet(e, Children)?.entities ?? []) visit(c);+ };+ visit(root);+ return out;+}++/** A copy of a node and everything under it, as a new parentless node. References to nodes outside the subtree are kept. */+function cloneNode(src: Node): Node {+ const world = src._world;+ const ids = subtreeOf(world, src._entity);+ const inside = new Set<number>(ids as unknown as number[]);+ const external = new Map<number, Entity>();+ const entities = ids.map((entity) => {+ const components = serializeEntityComponents(world, entity);+ for (const c of components) {+ const def = getComponent(c.type);+ for (const field of def?.entityFields ?? []) {+ const value = (c.data as Record<string, unknown>)[field];+ for (const ref of Array.isArray(value) ? value : [value]) {+ if (typeof ref === 'number' && ref > 0 && !inside.has(ref) && world.valid(ref as Entity)) external.set(ref, ref as Entity);+ }+ }+ }+ const parent = entity === src._entity ? null : (world.tryGet(entity, Parent)?.entity ?? null);+ return {+ id: entity as unknown as number,+ name: world.tryGet(entity, Name)?.value ?? '',+ parent: parent as unknown as number | null,+ children: (world.tryGet(entity, Children)?.entities ?? []) as unknown as number[],+ components,+ visible: true,+ };+ });+ const scene = { version: SCENE_FORMAT_VERSION, name: src.name, entities } as unknown as SceneData;+ const map = loadSceneData(world, scene, external);+ return Node.for(world, map.get(src._entity as unknown as number)!);+}++/**+ * A new node from a prefab or a copy of an existing node.+ *+ * @throws when given a prefab that has not finished loading: unlike Cocos, which has loaded it by the time a script holds it, the+ * engine loads on demand, and returning an empty node would hide that.+ */+export function instantiate<T extends Node | Prefab>(original: T): Node;+export function instantiate(original: Node | Prefab | null | undefined): Node {+ if (original instanceof Node) {+ const copy = cloneNode(original);+ markDetached(original._world, copy._entity);+ return copy;+ }+ if (original instanceof Prefab) {+ const prepared = original._prepared as PreparedPrefab | undefined;+ if (!prepared) {+ requestPrepare(original.path);+ throw new Error(`cocos compat: instantiate: prefab "${original.path}" is not loaded yet — hold it in a @property(Prefab) field so it loads with the scene, or await loadPrefab(path) first`);+ }+ const world = getCurrentWorld();+ if (!world) throw new Error('cocos compat: instantiate outside a running scene (no world is current)');+ const { root } = spawnPrepared(world, prepared);+ markDetached(world, root);+ return Node.for(world, root);+ }+ throw new Error('cocos compat: instantiate takes a Prefab or a Node');+}diff --git a/sdk/src/cocos/tween.ts b/sdk/src/cocos/tween.tsnew file mode 100644index 000000000..0590488ed--- /dev/null+++ b/sdk/src/cocos/tween.ts@@ -0,0 +1,366 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file cocos/tween.ts+ * @brief `tween(target).to(...).by(...).delay(...).call(...)`: Cocos's chainable property animation.+ *+ * A tween is a recipe — a list of steps — and `start()` turns it into a running tree of actions that the frame loop advances by+ * the frame's delta. The shapes Cocos scripts use are all here: `to` / `by` / `set` / `delay` / `call`, `then`, `union`,+ * `sequence` / `parallel`, `repeat` / `repeatForever`, easing by name or function, `progress` and the `onStart` / `onUpdate` /+ * `onComplete` hooks, and `Tween.stopAll*`.+ *+ * What it animates is whatever the target's properties are: numbers lerp, and the value types (`Vec2`, `Vec3`, `Quat`, `Color`)+ * lerp per component and are assigned back as new values, so a `Node` accessor like `position` sees every change. A tween on a+ * `Node` stops when the node is destroyed and waits while it is inactive, which is what Cocos's action manager does.+ */+import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';+import { Res, Time } from '../ecs/resource';+import { log } from '../util/logger';+import { easing, resolveEasing, type EasingFunction, type EasingName } from './easing';+import { Node } from './node';+import { Quat } from './math';++type Props = Record<string, unknown>;++export interface TweenOptions<T = unknown> {+ easing?: EasingName | EasingFunction | string;+ /** Replace the interpolation: given a start, an end, the current value and the eased ratio, return the next value. */+ progress?: (start: number, end: number, current: number, ratio: number) => number;+ onStart?: (target?: T) => void;+ onUpdate?: (target: T, ratio: number) => void;+ onComplete?: (target?: T) => void;+}++// ---------------------------------------------------------------------------------------------------------------------+// Values.+// ---------------------------------------------------------------------------------------------------------------------++const isObject = (v: unknown): v is Record<string, number> => typeof v === 'object' && v !== null;++/** A copy that is safe to hold while the target's own value changes underneath. */+function snapshot(v: unknown): unknown {+ if (!isObject(v)) return v;+ const clone = (v as { clone?: () => unknown }).clone;+ if (typeof clone === 'function') return clone.call(v);+ return { ...v };+}++const FIELDS = ['x', 'y', 'z', 'w', 'r', 'g', 'b', 'a', 'width', 'height'];++function addValues(a: unknown, b: unknown): unknown {+ if (typeof a === 'number' && typeof b === 'number') return a + b;+ if (isObject(a) && isObject(b)) {+ const out = snapshot(a) as Record<string, number>;+ for (const f of FIELDS) if (typeof a[f] === 'number' && typeof b[f] === 'number') out[f] = a[f]! + b[f]!;+ return out;+ }+ return b;+}++function interpolate(start: unknown, end: unknown, current: unknown, ratio: number, progress?: TweenOptions['progress']): unknown {+ if (typeof start === 'number' && typeof end === 'number') {+ return progress ? progress(start, end, typeof current === 'number' ? current : start, ratio) : start + (end - start) * ratio;+ }+ if (isObject(start) && isObject(end)) {+ if (start instanceof Quat && end instanceof Quat) return Quat.slerp(new Quat(), start, end, ratio);+ const out = (isObject(current) ? snapshot(current) : snapshot(start)) as Record<string, number>;+ for (const f of FIELDS) {+ const s = start[f], e = end[f];+ if (typeof s === 'number' && typeof e === 'number') out[f] = progress ? progress(s, e, out[f] ?? s, ratio) : s + (e - s) * ratio;+ }+ return out;+ }+ return ratio >= 1 ? end : start;+}++// ---------------------------------------------------------------------------------------------------------------------+// Actions: what a running tween is made of. `step(dt)` returns the time left over when it finished, or -1 while it runs.+// ---------------------------------------------------------------------------------------------------------------------++interface Action { step(dt: number): number }++type Factory = (target: unknown) => Action;++class Sequence implements Action {+ private i = 0;+ constructor(private readonly actions: Action[]) {}+ step(dt: number): number {+ let left = dt;+ while (this.i < this.actions.length) {+ const rest = this.actions[this.i]!.step(left);+ if (rest < 0) return -1;+ left = rest;+ this.i++;+ }+ return left;+ }+}++class Parallel implements Action {+ private readonly done: number[];+ constructor(private readonly actions: Action[]) { this.done = actions.map(() => -1); }+ step(dt: number): number {+ let finished = true;+ for (let i = 0; i < this.actions.length; i++) {+ if (this.done[i]! >= 0) continue;+ this.done[i] = this.actions[i]!.step(dt);+ if (this.done[i]! < 0) finished = false;+ }+ return finished ? Math.min(...this.done) : -1;+ }+}++class Repeat implements Action {+ private n = 0;+ private current: Action;+ constructor(private readonly make: () => Action, private readonly times: number) { this.current = make(); }+ step(dt: number): number {+ let left = dt;+ for (let guard = 0; guard < 10_000; guard++) {+ const rest = this.current.step(left);+ if (rest < 0) return -1;+ left = rest;+ if (++this.n >= this.times) return left;+ this.current = this.make();+ // an iteration that takes no time must not spin+ if (left <= 0 && this.times === Infinity) return -1;+ }+ return -1;+ }+}++/** Frames add up in floating point: ten steps of 0.1 are 0.9999999999999999, and a tween must not wait an extra frame for that. */+const EPS = 1e-9;++class Delay implements Action {+ private t = 0;+ constructor(private readonly duration: number) {}+ step(dt: number): number {+ this.t += dt;+ return this.t >= this.duration - EPS ? Math.max(0, this.t - this.duration) : -1;+ }+}++class Instant implements Action {+ constructor(private readonly run: () => void) {}+ step(dt: number): number { this.run(); return dt; }+}++class Interval implements Action {+ private t = 0;+ private from: Props | null = null;+ private to: Props = {};+ private started = false;+ constructor(+ private readonly target: Record<string, unknown>,+ private readonly duration: number,+ private readonly props: Props,+ private readonly relative: boolean,+ private readonly opts: TweenOptions,+ ) {}++ private begin(): void {+ this.started = true;+ this.from = {};+ for (const key of Object.keys(this.props)) {+ const raw = this.props[key];+ const value = isObject(raw) && 'value' in raw && !('x' in raw) ? (raw as { value: unknown }).value : raw;+ this.from[key] = snapshot(this.target[key]);+ this.to[key] = this.relative ? addValues(this.target[key], value) : value;+ }+ this.opts.onStart?.(this.target);+ }++ step(dt: number): number {+ if (!this.started) this.begin();+ this.t += dt;+ const k = this.duration <= 0 || this.t >= this.duration - EPS ? 1 : this.t / this.duration;+ const eased = resolveEasing(this.opts.easing)(k);+ for (const key of Object.keys(this.props)) {+ const raw = this.props[key];+ const own = isObject(raw) && 'value' in raw && !('x' in raw) ? (raw as { easing?: TweenOptions['easing']; progress?: TweenOptions['progress'] }) : null;+ const ratio = own?.easing ? resolveEasing(own.easing)(k) : eased;+ this.target[key] = interpolate(this.from![key], this.to[key], this.target[key], ratio, own?.progress ?? this.opts.progress);+ }+ this.opts.onUpdate?.(this.target, k);+ if (k < 1) return -1;+ this.opts.onComplete?.(this.target);+ return Math.max(0, this.t - this.duration);+ }+}++// ---------------------------------------------------------------------------------------------------------------------+// The tween.+// ---------------------------------------------------------------------------------------------------------------------++interface Running {+ tween: Tween<unknown>;+ root: Action;+ paused: boolean;+}+const running = new Set<Running>();+let nextId = 1;++export class Tween<T = unknown> {+ /** @internal */ _steps: Factory[] = [];+ /** @internal */ _target: unknown;+ private tag_ = -1;+ private run_: Running | null = null;+ readonly id = nextId++;++ constructor(target?: T) { this._target = target; }++ get tag(): number { return this.tag_; }+ set tag(v: number) { this.tag_ = v; }++ /** The object being animated. */+ getTarget(): T { return this._target as T; }++ target(t: unknown): Tween<T> { this._target = t; return this; }++ to<P extends Props>(duration: number, props: P, opts?: TweenOptions<T>): Tween<T> {+ this._steps.push((t) => new Interval(t as Record<string, unknown>, duration, props, false, (opts ?? {}) as TweenOptions));+ return this;+ }++ by<P extends Props>(duration: number, props: P, opts?: TweenOptions<T>): Tween<T> {+ this._steps.push((t) => new Interval(t as Record<string, unknown>, duration, props, true, (opts ?? {}) as TweenOptions));+ return this;+ }++ set<P extends Props>(props: P): Tween<T> {+ this._steps.push((t) => new Instant(() => { for (const [k, v] of Object.entries(props)) (t as Record<string, unknown>)[k] = snapshot(v); }));+ return this;+ }++ delay(duration: number): Tween<T> {+ this._steps.push(() => new Delay(duration));+ return this;+ }++ call(callback: (target?: T) => void): Tween<T> {+ this._steps.push((t) => new Instant(() => callback(t as T)));+ return this;+ }++ /** Run another tween's steps here, on this tween's target. */+ then(other: Tween<unknown>): Tween<T> {+ const steps = other._steps.slice();+ this._steps.push((t) => new Sequence(steps.map((f) => f(t))));+ return this;+ }++ /** Fold everything so far into one step, so a following `repeat` repeats all of it. */+ union(): Tween<T> {+ const steps = this._steps;+ this._steps = [(t) => new Sequence(steps.map((f) => f(t)))];+ return this;+ }++ sequence(...tweens: Tween<unknown>[]): Tween<T> {+ const parts = tweens.map((x) => x._steps.slice());+ this._steps.push((t) => new Sequence(parts.flatMap((steps) => steps.map((f) => f(t)))));+ return this;+ }++ parallel(...tweens: Tween<unknown>[]): Tween<T> {+ const parts = tweens.map((x) => x._steps.slice());+ this._steps.push((t) => new Parallel(parts.map((steps) => new Sequence(steps.map((f) => f(t))))));+ return this;+ }++ /** Repeat @p embed, or everything so far when none is given. */+ repeat(times: number, embed?: Tween<unknown>): Tween<T> {+ return this.repeat_(times, embed);+ }+ repeatForever(embed?: Tween<unknown>): Tween<T> {+ return this.repeat_(Infinity, embed);+ }+ private repeat_(times: number, embed?: Tween<unknown>): Tween<T> {+ const steps = embed ? embed._steps.slice() : this._steps;+ const make = (t: unknown) => (): Action => new Sequence(steps.map((f) => f(t)));+ const factory: Factory = (t) => new Repeat(make(t), times);+ if (embed) this._steps.push(factory); else this._steps = [factory];+ return this;+ }++ /** A copy with the same recipe, optionally on another target. */+ clone(target?: unknown): Tween<T> {+ const copy = new Tween<T>((target ?? this._target) as T);+ copy._steps = this._steps.slice();+ copy.tag_ = this.tag_;+ return copy;+ }++ // ---- Node conveniences, as Cocos has them --------------------------------------------------------------------------+ hide(): Tween<T> { return this.call((t) => { if (t instanceof Node) t.active = false; }); }+ show(): Tween<T> { return this.call((t) => { if (t instanceof Node) t.active = true; }); }+ removeSelf(): Tween<T> { return this.call((t) => { if (t instanceof Node) t.removeFromParent(); }); }+ destroySelf(): Tween<T> { return this.call((t) => { if (t instanceof Node) t.destroy(); }); }++ // ---- running -------------------------------------------------------------------------------------------------------++ start(): Tween<T> {+ this.stop();+ const target = this._target ?? {};+ const run: Running = { tween: this as Tween<unknown>, root: new Sequence(this._steps.map((f) => f(target))), paused: false };+ this.run_ = run;+ running.add(run);+ return this;+ }++ stop(): Tween<T> {+ if (this.run_) { running.delete(this.run_); this.run_ = null; }+ return this;+ }++ pause(): Tween<T> { if (this.run_) this.run_.paused = true; return this; }+ resume(): Tween<T> { if (this.run_) this.run_.paused = false; return this; }++ get isRunning(): boolean { return this.run_ !== null; }++ static stopAll(): void { for (const r of [...running]) r.tween.stop(); }+ static stopAllByTag(tag: number, target?: unknown): void {+ for (const r of [...running]) if (r.tween.tag === tag && (target === undefined || r.tween._target === target)) r.tween.stop();+ }+ static stopAllByTarget(target: unknown): void {+ for (const r of [...running]) if (r.tween._target === target) r.tween.stop();+ }+}++/** Start building a tween on @p target. */+export function tween<T>(target?: T): Tween<T> { return new Tween<T>(target); }+export const tweenUtil = tween;++/** Advance every running tween by @p dt seconds. Exported for a host with its own loop, and for tests. */+export function updateTweens(dt: number): void {+ for (const run of [...running]) {+ if (!running.has(run) || run.paused) continue;+ const target = run.tween._target;+ if (target instanceof Node) {+ if (!target.isValid) { run.tween.stop(); continue; }+ if (!target.activeInHierarchy) continue;+ }+ let rest: number;+ try {+ rest = run.root.step(dt);+ } catch (err) {+ log.error('cocos', 'a tween threw and was stopped', err);+ run.tween.stop();+ continue;+ }+ if (rest >= 0) run.tween.stop();+ }+}++/** Register the system that advances tweens with the frame loop. */+export function declareTweenSystem(): void {+ const system = defineSystem(+ [Res(Time), GetWorld()],+ (time) => { updateTweens(time.delta); },+ { name: 'Cocos:Tween', touches: { opaque: true } },+ );+ addSystemToSchedule(Schedule.Update, system);+}++export { easing };diff --git a/sdk/tests/cocos/instantiate-wasm.test.ts b/sdk/tests/cocos/instantiate-wasm.test.tsnew file mode 100644index 000000000..563f58a61--- /dev/null+++ b/sdk/tests/cocos/instantiate-wasm.test.ts@@ -0,0 +1,218 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file `instantiate` and `tween` on nodes, against the real engine.+ *+ * A prefab is given in its prepared form (what the engine's loader makes), so what is exercised is the layer's side: that a held+ * `Prefab` is a handle on a path, that instantiating spawns a whole subtree whose scripts then run, that the result is outside the+ * scene until it has a parent, and that a copied node is independent of its original but keeps references to nodes outside it.+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import type { ESEngineModule } from '../../src/wasm';+import { App, flushPendingRegistrations } from '../../src/app/app';+import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';+import { AppContext, setDefaultContext } from '../../src/ecs/context';+import { loadSceneData, SCENE_FORMAT_VERSION } from '../../src/scene/scene';+import type { SceneData } from '../../src/scene/scene';+import type { PreparedPrefab } from '../../src/prefab/preparedPrefab';+import { resetClassRegistry } from '../../src/cocos/registry';+import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';+import { Component, Node, Prefab, Vec3, _decorator, instantiate, providePrefab, setCurrentWorld, tween } from '../../src/cocos';+import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';++const transform = (x = 0, y = 0) => ({ type: 'Transform', data: { position: { x, y, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } });++describe.skipIf(!HAS_WASM)('instantiate and tween on the engine', () => {+ let module: ESEngineModule;+ let registry: InstanceType<ESEngineModule['Registry']> | undefined;+ let app: App | undefined;++ beforeAll(async () => { ensureBuiltinComponentsRegistered(); module = await loadWasmModule(); });+ afterEach(() => {+ setCurrentWorld(null);+ app?.world.disconnectCpp();+ registry?.delete();+ app = undefined;+ registry = undefined;+ });++ function connect(): void {+ setDefaultContext(new AppContext());+ ensureBuiltinComponentsRegistered();+ resetClassRegistry();+ declareBuiltinScripts();+ }+ function boot(): void {+ registry = new module.Registry();+ app = App.new();+ app.connectCpp(registry as never, module);+ flushPendingRegistrations(app);+ setCurrentWorld(app.world);+ }+ const frame = async (n = 2): Promise<void> => { for (let i = 0; i < n; i++) await app!.tick(1 / 60); };++ /** A prefab of a root with one child, the root carrying the script. */+ function bullet(): PreparedPrefab {+ const scene = {+ version: SCENE_FORMAT_VERSION, name: 'bullet',+ entities: [+ { id: 0, name: 'Bullet', parent: null, children: [1], visible: true, components: [transform(5, 6), { type: 'Cocos.Bullet', data: { enabled: true, damage: 7 } }] },+ { id: 1, name: 'Trail', parent: 0, children: [], visible: true, components: [transform(1, 0)] },+ ],+ } as unknown as SceneData;+ return { ref: 'bullet.esprefab', scene, rootId: 0, missing: [], release() {} };+ }++ it('holds a prefab property as a handle on its path, and spawns the prepared prefab whole', async () => {+ connect();+ const started: number[] = [];+ @_decorator.ccclass('Bullet')+ class Bullet extends Component {+ @_decorator.property damage = 1;+ start() { started.push(this.damage); }+ }+ @_decorator.ccclass('Gun')+ class Gun extends Component {+ @_decorator.property(Prefab) round: Prefab | null = null;+ }+ void Bullet;+ providePrefab('bullet.esprefab', bullet());+ boot();++ const map = loadSceneData(app!.world, {+ version: SCENE_FORMAT_VERSION, name: 'main',+ entities: [{ id: 0, name: 'Gun', parent: null, children: [], visible: true, components: [transform(), { type: 'Cocos.Gun', data: { enabled: true, round: 'bullet.esprefab' } }] }],+ } as unknown as SceneData);+ await frame();+ const gun = Node.for(app!.world, map.get(0)!);+ const script = gun.getComponent(Gun)!;+ expect(script.round).toBeInstanceOf(Prefab);+ expect(script.round!.path).toBe('bullet.esprefab');++ const made = instantiate(script.round!);+ expect(made.name).toBe('Bullet');+ expect(made.children.map((c) => c.name)).toEqual(['Trail']);+ expect([made.position.x, made.position.y]).toEqual([5, 6]);++ // out of the scene until it has a parent: nothing runs, but the node itself says it is active+ expect(made.active).toBe(true);+ expect(made.activeInHierarchy).toBe(false);+ await frame();+ expect(started).toEqual([]);++ gun.addChild(made);+ expect(made.activeInHierarchy).toBe(true);+ await frame();+ expect(started).toEqual([7]);+ });++ it('says what is wrong when the prefab has not loaded, rather than answering half a node', () => {+ connect();+ boot();+ expect(() => instantiate(new Prefab('never-loaded.esprefab'))).toThrow(/not loaded yet/);+ });++ it('keeps a switched-off instance switched off after it is parented', async () => {+ connect();+ providePrefab('p.esprefab', bullet());+ boot();+ const made = instantiate(new Prefab('p.esprefab'));+ made.active = false;+ expect(made.active).toBe(false);+ const parent = new Node('holder');+ app!.world.insert(parent._entity, Transform);+ parent.addChild(made);+ expect(made.active).toBe(false);+ expect(made.activeInHierarchy).toBe(false);+ });++ it('copies a node with its children and scripts, independent of the original', async () => {+ connect();+ const ticks: string[] = [];+ @_decorator.ccclass('Counter')+ class Counter extends Component {+ @_decorator.property n = 0;+ update() { this.n++; ticks.push(this.node.name); }+ }+ void Counter;+ boot();+ 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.Counter', data: { enabled: true, n: 10 } }] },+ { id: 1, name: 'Child', parent: 0, children: [], visible: true, components: [transform(3, 0)] },+ ],+ } as unknown as SceneData);+ const original = Node.for(app!.world, map.get(0)!);+ const copy = instantiate(original);+ expect(copy).not.toBe(original);+ expect(copy.children.map((c) => c.name)).toEqual(['Child']);+ expect(copy.children[0]).not.toBe(original.children[0]);+ original.setPosition(100, 0, 0);+ expect(copy.position.x).toBe(0);++ const holder = new Node('holder');+ app!.world.insert(holder._entity, Transform);+ holder.addChild(copy);+ await frame(1);+ expect(ticks.filter((n) => n === 'Root')).toHaveLength(2); // the original's and the copy's+ });++ it('keeps a copy\'s reference to a node outside it pointed at that node', async () => {+ connect();+ @_decorator.ccclass('Follower')+ class Follower extends Component {+ @_decorator.property(Node) leader: Node | null = null;+ }+ boot();+ const map = loadSceneData(app!.world, {+ version: SCENE_FORMAT_VERSION, name: 'main',+ entities: [+ { id: 1, name: 'Leader', parent: null, children: [], visible: true, components: [transform()] },+ { id: 2, name: 'Fan', parent: null, children: [], visible: true, components: [transform(), { type: 'Cocos.Follower', data: { enabled: true, leader: 1 } }] },+ ],+ } as unknown as SceneData);+ await frame();+ const leader = Node.for(app!.world, map.get(1)!);+ const copy = instantiate(Node.for(app!.world, map.get(2)!));+ const holder = new Node('holder');+ app!.world.insert(holder._entity, Transform);+ holder.addChild(copy);+ await frame();+ // `===`, not toBe: a failing toBe walks both nodes' worlds to print a diff, and the wasm heap is in there+ expect(copy.getComponent(Follower)!.leader === leader).toBe(true);+ });++ it('tweens a node\'s position by its accessor, and stops when the node is destroyed', async () => {+ connect();+ boot();+ const n = new Node('mover');+ app!.world.insert(n._entity, Transform);+ tween(n).to(0.5, { position: new Vec3(60, 0, 0) }).start();+ await frame(15); // 0.25s at 60 fps+ expect(n.position.x).toBeCloseTo(30, 0);+ await frame(30);+ expect(n.position.x).toBe(60);++ const doomed = new Node('doomed');+ app!.world.insert(doomed._entity, Transform);+ const t = tween(doomed).to(10, { position: new Vec3(1, 0, 0) }).start();+ doomed.destroy();+ await frame(2);+ expect(t.isRunning).toBe(false);+ });++ it('waits while the node is switched off', async () => {+ connect();+ boot();+ const n = new Node('sleeper');+ app!.world.insert(n._entity, Transform);+ tween(n).to(1, { position: new Vec3(10, 0, 0) }).start();+ n.active = false;+ await frame(30);+ expect(n.position.x).toBe(0);+ n.active = true;+ await frame(70);+ expect(n.position.x).toBe(10);+ });+});diff --git a/sdk/tests/cocos/tween.test.ts b/sdk/tests/cocos/tween.test.tsnew file mode 100644index 000000000..376b75be9--- /dev/null+++ b/sdk/tests/cocos/tween.test.ts@@ -0,0 +1,191 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file `tween`: the chain a Cocos script writes, advanced by hand.+ *+ * Pure objects as targets, so the arithmetic is what is under test: `to` goes to a value and `by` goes by it, an easing reshapes+ * progress, a chain runs its steps in order and hands the time left over from one to the next, `repeat` and `union` mean what Cocos+ * means by them, and the value types are interpolated per component.+ */+import { afterEach, describe, expect, it } from 'vitest';+import { Color, Vec3, Tween, easing, tween, updateTweens } from '../../src/cocos';++afterEach(() => Tween.stopAll());++/** Run for @p seconds in @p frames equal steps. */+function run(seconds: number, frames = 10): void { for (let i = 0; i < frames; i++) updateTweens(seconds / frames); }++describe('tween steps', () => {+ it('goes to a value over its duration, and stops there', () => {+ const o = { x: 0 };+ tween(o).to(1, { x: 10 }).start();+ run(0.5, 5);+ expect(o.x).toBeCloseTo(5, 5);+ run(1, 10);+ expect(o.x).toBe(10);+ });++ it('goes by a value from wherever the target is when the step begins', () => {+ const o = { x: 3 };+ tween(o).by(1, { x: 4 }).by(1, { x: 4 }).start();+ run(2, 20);+ expect(o.x).toBe(11);+ });++ it('runs steps in order and carries the leftover time of one into the next', () => {+ const o = { x: 0, y: 0 };+ tween(o).to(1, { x: 1 }).to(1, { y: 1 }).start();+ updateTweens(1.5); // one step's worth and half of the next in a single frame+ expect(o.x).toBe(1);+ expect(o.y).toBeCloseTo(0.5, 5);+ });++ it('sets at once, waits, and calls back with the target', () => {+ const o = { x: 0 };+ const log: string[] = [];+ tween(o).set({ x: 5 }).call((t) => log.push(`call:${(t as typeof o).x}`)).delay(1).call(() => log.push('after')).start();+ updateTweens(0.1);+ expect(log).toEqual(['call:5']);+ updateTweens(1);+ expect(log).toEqual(['call:5', 'after']);+ });++ it('applies an easing by name or by function', () => {+ const a = { x: 0 }, b = { x: 0 };+ tween(a).to(1, { x: 100 }, { easing: 'quadIn' }).start();+ tween(b).to(1, { x: 100 }, { easing: (k) => k * k * k }).start();+ updateTweens(0.5);+ expect(a.x).toBeCloseTo(25, 5);+ expect(b.x).toBeCloseTo(12.5, 5);+ });++ it('has curves that begin at 0 and end at 1', () => {+ for (const [name, fn] of Object.entries(easing)) {+ expect(fn(0), `${name}(0)`).toBeCloseTo(0, 6);+ expect(fn(1), `${name}(1)`).toBeCloseTo(1, 6);+ }+ });++ it('reports its progress through onUpdate, and start and completion once each', () => {+ const o = { x: 0 };+ const seen: number[] = [];+ let started = 0, completed = 0;+ tween(o).to(1, { x: 1 }, { onStart: () => started++, onUpdate: (_t, r) => seen.push(r), onComplete: () => completed++ }).start();+ run(1, 4);+ expect(seen).toEqual([0.25, 0.5, 0.75, 1]);+ expect([started, completed]).toEqual([1, 1]);+ });+});++describe('tween composition', () => {+ it('repeats a sub-tween a number of times', () => {+ const o = { n: 0 };+ tween(o).repeat(3, tween(o).by(0.1, { n: 1 })).start();+ run(1, 20);+ expect(o.n).toBe(3);+ });++ it('repeats everything so far when no tween is given, and forever until stopped', () => {+ const o = { x: 0 };+ const t = tween(o).by(0.5, { x: 1 }).delay(0.5).repeatForever().start();+ run(5, 50);+ expect(o.x).toBe(5);+ expect(t.isRunning).toBe(true);+ t.stop();+ run(2, 20);+ expect(o.x).toBe(5);+ });++ it('unions what came before so a repeat covers all of it', () => {+ const o = { x: 0, y: 0 };+ tween(o).by(0.1, { x: 1 }).by(0.1, { y: 1 }).union().repeat(2).start();+ run(1, 20);+ expect([o.x, o.y]).toEqual([2, 2]);+ });++ it('runs tweens in parallel, finishing when the longest does', () => {+ const o = { x: 0, y: 0 };+ let done = false;+ tween(o).parallel(tween(o).to(1, { x: 1 }), tween(o).to(2, { y: 1 })).call(() => { done = true; }).start();+ run(1, 10);+ expect(o.x).toBe(1);+ expect(o.y).toBeCloseTo(0.5, 6);+ expect(done).toBe(false);+ run(1, 10);+ expect([o.x, o.y, done]).toEqual([1, 1, true]);+ });++ it('runs tweens in sequence, and another tween\'s steps with then', () => {+ const o = { x: 0 };+ tween(o).sequence(tween(o).to(1, { x: 1 }), tween(o).to(1, { x: 3 })).then(tween(o).to(1, { x: 0 })).start();+ run(1, 10);+ expect(o.x).toBe(1);+ run(1, 10);+ expect(o.x).toBe(3);+ run(1, 10);+ expect(o.x).toBe(0);+ });++ it('stops by target and by tag, and not the others', () => {+ const a = { x: 0 }, b = { x: 0 }, c = { x: 0 };+ tween(a).to(1, { x: 1 }).start();+ const tb = tween(b).to(1, { x: 1 }); tb.tag = 7; tb.start();+ tween(c).to(1, { x: 1 }).start();+ Tween.stopAllByTarget(a);+ Tween.stopAllByTag(7);+ run(1, 10);+ expect([a.x, b.x, c.x]).toEqual([0, 0, 1]);+ });++ it('restarts from the beginning when started again', () => {+ const o = { x: 0 };+ const t = tween(o).to(1, { x: 10 }).start();+ run(0.5, 5);+ t.start();+ expect(t.isRunning).toBe(true);+ run(0.5, 5);+ // the second run began its own clock, from the value it found (5): half of the way from there to 10+ expect(o.x).toBeCloseTo(7.5, 5);+ });++ it('can be paused and resumed', () => {+ const o = { x: 0 };+ const t = tween(o).to(1, { x: 1 }).start();+ run(0.5, 5);+ t.pause();+ run(5, 50);+ expect(o.x).toBeCloseTo(0.5, 5);+ t.resume();+ run(0.5, 5);+ expect(o.x).toBe(1);+ });++ it('keeps one throwing callback from stopping the others', () => {+ const a = { x: 0 }, b = { x: 0 };+ tween(a).call(() => { throw new Error('boom'); }).start();+ tween(b).to(1, { x: 1 }).start();+ run(1, 10);+ expect(b.x).toBe(1);+ });+});++describe('tween values', () => {+ it('interpolates vectors and colours per component, and assigns a new value back', () => {+ const o = { position: new Vec3(0, 0, 0), color: new Color(0, 0, 0, 255) };+ const before = o.position;+ tween(o).to(1, { position: new Vec3(10, 20, 30), color: new Color(200, 100, 0, 255) }).start();+ run(0.5, 5);+ expect([o.position.x, o.position.y, o.position.z]).toEqual([5, 10, 15]);+ expect(o.position).not.toBe(before); // an accessor on a Node sees every write+ expect([o.color.r, o.color.g]).toEqual([100, 50]);+ });++ it('lets the target\'s own start value be anything the property returns, without changing it as it moves', () => {+ const start = new Vec3(1, 1, 1);+ const o = { position: start };+ tween(o).by(1, { position: new Vec3(1, 1, 1) }).start();+ run(1, 10);+ expect(start.x).toBe(1);+ expect(o.position.x).toBe(2);+ });+});