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): director has a scheduler and fires its frame events, setSiblingIndex reorders through the engine entity order, loadAny takes a uuid, and an asset counts its holders

yhh606f30656568
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.ts
index 88db524e3..eccca9f42 100644
--- a/pipeline/src/import/cocos/importProject.ts
+++ b/pipeline/src/import/cocos/importProject.ts
@@ -664,7 +664,7 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
// Assets scripts load by path at run time (`resources.load('ui/icon')`) are named by no scene, so nothing above would bring them
// across. They are copied, and listed by bundle in a manifest the runtime layer resolves those paths through.
- const manifest: Record<string, Record<string, { path: string; kind: string }>> = {};
+ const manifest: Record<string, Record<string, { path: string; kind: string; uuid: string }>> = {};
if (index.bundles.length > 0) {
const files = new Set(index.byUuid.values());
for (const bundle of index.bundles) {
@@ -675,17 +675,17 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impo
const ext = /\.([^./]+)$/.exec(entry.rel)?.[1]?.toLowerCase() ?? '';
if (ext === 'prefab') {
const ref = ctx.prefabRef(entry.uuid);
- if (ref) entries[key] = { path: ref, kind: 'prefab' };
+ if (ref) entries[key] = { path: ref, kind: 'prefab', uuid: entry.uuid };
} else if (ext === 'json') {
- entries[key] = { path: ctx.assetRef(entry), kind: 'json' };
+ entries[key] = { path: ctx.assetRef(entry), kind: 'json', uuid: entry.uuid };
} else if (['txt', 'text', 'xml', 'csv', 'atlas'].includes(ext)) {
- entries[key] = { path: ctx.assetRef(entry), kind: 'text' };
+ entries[key] = { path: ctx.assetRef(entry), kind: 'text', uuid: entry.uuid };
} else if (['png', 'jpg', 'jpeg', 'webp'].includes(ext)) {
- entries[key] = { path: ctx.assetRef(entry), kind: 'texture' };
+ entries[key] = { path: ctx.assetRef(entry), kind: 'texture', uuid: entry.uuid };
} else if (['mp3', 'wav', 'ogg', 'm4a'].includes(ext)) {
- entries[key] = { path: ctx.assetRef(entry), kind: 'audio' };
+ entries[key] = { path: ctx.assetRef(entry), kind: 'audio', uuid: entry.uuid };
} else if (ext !== 'meta' && ext !== 'ts' && ext !== 'js' && ext !== 'scene') {
- entries[key] = { path: '', kind: ext || 'other' };
+ entries[key] = { path: '', kind: ext || 'other', uuid: entry.uuid };
}
}
}
diff --git a/pipeline/tests/cocos-import-layer.test.ts b/pipeline/tests/cocos-import-layer.test.ts
index 02701e82c..fca7bd92e 100644
--- a/pipeline/tests/cocos-import-layer.test.ts
+++ b/pipeline/tests/cocos-import-layer.test.ts
@@ -158,10 +158,12 @@ describe('importing for the compatibility layer', () => {
it('lists what scripts load by path in a manifest, by bundle, and copies those files', () => {
const manifest = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'resources.json'), 'utf8'));
- expect(manifest.resources['cfg/rules']).toEqual({ path: 'assets/cocos/resources/cfg/rules.json', kind: 'json' });
- expect(manifest.resources['ui/icon']).toEqual({ path: 'assets/cocos/resources/ui/icon.png', kind: 'texture' });
- expect(manifest.resources['prefab/thing']).toEqual({ path: 'assets/cocos/resources/prefab/thing.esprefab', kind: 'prefab' });
- expect(manifest.hero['skin']).toEqual({ path: 'assets/cocos/hero/skin.json', kind: 'json' });
+ // each entry also names the asset's Cocos uuid, which loadAny({ uuid }) resolves it by
+ expect(typeof manifest.resources['cfg/rules'].uuid).toBe('string');
+ expect(manifest.resources['cfg/rules']).toMatchObject({ path: 'assets/cocos/resources/cfg/rules.json', kind: 'json' });
+ expect(manifest.resources['ui/icon']).toMatchObject({ path: 'assets/cocos/resources/ui/icon.png', kind: 'texture' });
+ expect(manifest.resources['prefab/thing']).toMatchObject({ path: 'assets/cocos/resources/prefab/thing.esprefab', kind: 'prefab' });
+ expect(manifest.hero['skin']).toMatchObject({ path: 'assets/cocos/hero/skin.json', kind: 'json' });
expect(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'resources', 'cfg', 'rules.json'), 'utf8')).toBe('{"a":1}');
});
diff --git a/sdk/src/cocos/assetManager.ts b/sdk/src/cocos/assetManager.ts
index cbef16cb9..25ded5b9e 100644
--- a/sdk/src/cocos/assetManager.ts
+++ b/sdk/src/cocos/assetManager.ts
@@ -26,6 +26,8 @@ export interface ResourceEntry {
path: string;
/** What kind of asset it is: `prefab`, `json`, `text`, or another the layer cannot load. */
kind: string;
+ /** The Cocos uuid of the asset, which `loadAny({ uuid })` names it by. */
+ uuid?: string;
}
export type ResourceManifest = Record<string, Record<string, ResourceEntry>>;
@@ -289,14 +291,17 @@ class AssetManager {
})().then((a) => { loaded.add(url, a); onComplete?.(null, a); }, (e: Error) => { if (onComplete) onComplete(e, null as never); else log.warn('cocos', e.message); });
}
- /** Requests in the shapes a script writes: `{ url }` remote, `{ path, bundle?, type? }` a bundle's asset. A uuid is not resolvable here. */
+ /** Requests in the shapes a script writes: `{ url }` remote, `{ path, bundle?, type? }` a bundle's asset, `{ uuid }` or a bare uuid (by the manifest's listing). */
loadAny(requests: unknown, ...rest: unknown[]): void {
const onComplete = rest.find((a) => typeof a === 'function') as Callback<unknown> | undefined;
const one = (r: any): Promise<Asset> => new Promise((resolve, reject) => {
const done: Callback<Asset> = (e, a) => (e ? reject(e) : resolve(a));
if (r && typeof r === 'object' && typeof r.url === 'string') this.loadRemote(r.url, r, done);
else if (r && typeof r === 'object' && typeof r.path === 'string') (bundles.get(r.bundle ?? 'resources') ?? resources).load(r.path, r.type ?? null, done);
- else reject(new Error('cocos compat: loadAny by uuid is not supported; use a bundle path or a url'));
+ else if (r && typeof r === 'object' && typeof r.uuid === 'string') {
+ this.loadByUuid_(r.uuid, r.type ?? null).then(resolve, reject);
+ } else if (typeof r === 'string') this.loadByUuid_(r, null).then(resolve, reject);
+ else reject(new Error('cocos compat: loadAny takes a uuid, a bundle path or a url'));
});
const list = Array.isArray(requests) ? requests : [requests];
Promise.all(list.map(one)).then(
@@ -305,6 +310,20 @@ class AssetManager {
);
}
+ /** The bundle and key a uuid is listed under in the resource manifest. */
+ private async loadByUuid_(uuid: string, type: AssetCtor | null): Promise<Asset> {
+ const m = await theManifest();
+ for (const [bundle, entries] of Object.entries(m)) {
+ for (const [key, entry] of Object.entries(entries)) {
+ if (entry.uuid !== uuid) continue;
+ return new Promise<Asset>((resolve, reject) => {
+ (bundles.get(bundle) ?? resources).load(key, type, (e: Error | null, a: Asset) => (e ? reject(e) : resolve(a)));
+ });
+ }
+ }
+ throw new Error(`cocos compat: no asset with uuid ${uuid} is listed in the project's bundles`);
+ }
+
releaseAsset(asset: Asset): void { for (const [k, v] of [...loaded.entries()]) if (v === asset) loaded.remove(k); }
releaseAll(): void { loaded.clear(); }
}
diff --git a/sdk/src/cocos/assets.ts b/sdk/src/cocos/assets.ts
index 4f8edbe46..ebdf81bd0 100644
--- a/sdk/src/cocos/assets.ts
+++ b/sdk/src/cocos/assets.ts
@@ -10,7 +10,21 @@
*/
import { Material as EngineMaterial } from '../render/material';
-export class Asset { constructor(public path = '') {} }
+export class Asset {
+ constructor(public path = '') {}
+ /** The Cocos uuid and display name of the asset, where the project's manifest gave one. */
+ uuid = '';
+ name = '';
+ private refCount_ = 0;
+ /** How many holders have asked to keep it. An asset here lives as long as the engine's own resource table holds it, so the count is advice. */
+ get refCount(): number { return this.refCount_; }
+ addRef(): this { this.refCount_++; return this; }
+ decRef(_autoRelease = true): this { if (this.refCount_ > 0) this.refCount_--; return this; }
+ get isDefault(): boolean { return false; }
+ get nativeUrl(): string { return this.path; }
+ get loaded(): boolean { return true; }
+ destroy(): boolean { return true; }
+}
export class ImageAsset extends Asset {}
export class Texture2D extends Asset {}
export class SpriteFrame extends Asset {}
diff --git a/sdk/src/cocos/builtinScripts.ts b/sdk/src/cocos/builtinScripts.ts
index 09a3874e3..05f3fed33 100644
--- a/sdk/src/cocos/builtinScripts.ts
+++ b/sdk/src/cocos/builtinScripts.ts
@@ -14,6 +14,7 @@ import { ContentRect } from '../ui/core/content-rect';
import { declareButton } from './ui/button';
import { declareInputSystem } from './input';
import { declareUiPass } from './ui/pass';
+import { declareDirector } from './director';
import { declareTweenSystem } from './tween';
import { declarePrefabSystem } from './prefabs';
import { declareGameSystem } from './game';
@@ -31,6 +32,7 @@ export function declareBuiltinScripts(): void {
declareButton();
declareInputSystem();
declareUiPass();
+ declareDirector();
declareTweenSystem();
declarePrefabSystem();
declareGameSystem();
diff --git a/sdk/src/cocos/director.ts b/sdk/src/cocos/director.ts
index c92de551f..2c8047257 100644
--- a/sdk/src/cocos/director.ts
+++ b/sdk/src/cocos/director.ts
@@ -11,7 +11,10 @@
import { Name, Parent } from '../ecs/component';
import type { World } from '../ecs/world';
import { INVALID_ENTITY, type Entity } from '../types';
+import { Schedule, defineSystem, addSystemToSchedule } from '../ecs/system';
+import { Res, Time } from '../ecs/resource';
import { Node, getCurrentWorld } from './node';
+import { Scheduler, scheduler } from './scheduler';
/** The root of the running scene: a stand-in for the parent the world's top-level entities do not have. */
export class Scene {
@@ -63,6 +66,9 @@ export const director = {
/** The time of the last frame, in seconds. */
getDeltaTime(): number { return lastDelta; },
getTotalFrames(): number { return totalFrames; },
+ /** The timers kept by target: the ones a game's own timer service runs on. */
+ getScheduler(): Scheduler { return scheduler; },
+ getAnimationManager(): undefined { return undefined; },
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 }]);
@@ -91,6 +97,7 @@ let totalFrames = 0;
export function reportFrame(delta: number): void {
lastDelta = delta;
totalFrames++;
+ scheduler.update(delta);
}
/**
@@ -130,3 +137,26 @@ export function isValid(value: unknown, _strict = false): boolean {
const v = value as { isValid?: boolean };
return typeof v.isValid === 'boolean' ? v.isValid : true;
}
+
+/**
+ * The director's frame, which scripts hook: the delta it reports and the events around the update and the draw. The frame is the
+ * engine's; these systems mark its start (before the scripts run), the end of the update and the end of the frame, in the order Cocos
+ * emits them.
+ */
+export function declareDirector(): void {
+ addSystemToSchedule(Schedule.First, defineSystem(
+ [Res(Time)],
+ (time) => { reportFrame(time.delta); director.emit(Director.EVENT_BEFORE_UPDATE); },
+ { name: 'Cocos:DirectorBegin', touches: { opaque: true } },
+ ));
+ addSystemToSchedule(Schedule.Last, defineSystem(
+ [],
+ () => {
+ director.emit(Director.EVENT_AFTER_UPDATE);
+ director.emit(Director.EVENT_BEFORE_DRAW);
+ director.emit(Director.EVENT_AFTER_DRAW);
+ director.emit(Director.EVENT_END_FRAME);
+ },
+ { name: 'Cocos:DirectorEnd', touches: { opaque: true } },
+ ));
+}
diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.ts
index 24a8657ab..561c5edbc 100644
--- a/sdk/src/cocos/index.ts
+++ b/sdk/src/cocos/index.ts
@@ -21,6 +21,7 @@ export {
disallowMultiple, type, integer, float, string, boolean, CCInteger, CCFloat, CCString, CCBoolean, Enum,
} from './decorators';
export { director, Director, Scene, find, isValid, reportFrame } from './director';
+export { Scheduler } from './scheduler';
export {
Asset, ImageAsset, Texture2D, SpriteFrame, SpriteAtlas, Prefab, AudioClip, Material, JsonAsset, TextAsset, BitmapFont, Font,
AnimationClip, SceneAsset, EffectAsset, Mesh,
diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.ts
index e4fc5b997..643670d20 100644
--- a/sdk/src/cocos/node.ts
+++ b/sdk/src/cocos/node.ts
@@ -22,7 +22,6 @@ import {
} 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;
@@ -196,8 +195,26 @@ export class Node {
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');
+ /**
+ * Move this node among its siblings (-1 is the last place). The engine keeps the child order and the draw order together, in the storage
+ * order of its entities, so the siblings swap their places there and the engine re-establishes both from it: the same operation an
+ * outliner drag is.
+ */
+ setSiblingIndex(index: number): void {
+ const parent = this.parent;
+ if (!parent) return;
+ const siblings = [...(this._world.tryGet(parent._entity, Children)?.entities ?? [])];
+ const from = siblings.indexOf(this._entity);
+ if (from < 0) return;
+ const to = Math.max(0, Math.min(siblings.length - 1, index < 0 ? siblings.length - 1 : index));
+ if (to === from) return;
+ siblings.splice(from, 1);
+ siblings.splice(to, 0, this._entity);
+ const taken = new Set<Entity>(siblings);
+ const order = this._world.getAllEntities();
+ let next = 0;
+ for (let i = 0; i < order.length; i++) if (taken.has(order[i]!)) order[i] = siblings[next++]!;
+ this._world.applyEntityOrder(order);
}
/** Whether @p other is this node or below it. */
@@ -411,12 +428,5 @@ export class Node {
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/scheduler.ts b/sdk/src/cocos/scheduler.ts
new file mode 100644
index 000000000..8b14f75a3
--- /dev/null
+++ b/sdk/src/cocos/scheduler.ts
@@ -0,0 +1,103 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file cocos/scheduler.ts
+ * @brief `director.getScheduler()`: timers kept by target rather than by component.
+ *
+ * A component's own `schedule` stops with the component; the director's scheduler serves anything a script holds, a plain object or a
+ * singleton, and is how a game's timer service ticks. It runs once a frame from the frame the host reports, scaled by `setTimeScale`.
+ */
+
+interface Entry {
+ callback: (dt: number) => void;
+ target: object;
+ interval: number;
+ repeat: number;
+ delay: number;
+ /** Time since the last fire (or since the delay began). */
+ elapsed: number;
+ fired: number;
+ started: boolean;
+ paused: boolean;
+}
+
+export class Scheduler {
+ static readonly ID = 'scheduler';
+ static readonly PRIORITY_SYSTEM = -(2 ** 31);
+ static readonly PRIORITY_NON_SYSTEM = Scheduler.PRIORITY_SYSTEM + 1;
+ static readonly REPEAT_FOREVER = Number.MAX_VALUE - 1;
+ static enableForTarget(_target: unknown): void { /* a target needs no marking here */ }
+
+ private entries_: Entry[] = [];
+ private updates_ = new Map<object, { priority: number; paused: boolean }>();
+ private pausedTargets_ = new Set<object>();
+ private timeScale_ = 1;
+
+ /** Call @p callback on @p target every @p interval seconds (every frame at 0), @p repeat more times after the first, after @p delay. */
+ schedule(callback: (dt: number) => void, target: object, interval = 0, repeat = Scheduler.REPEAT_FOREVER, delay = 0, paused = false): void {
+ if (typeof callback !== 'function') return;
+ this.unschedule(callback, target);
+ this.entries_.push({ callback, target, interval, repeat, delay, elapsed: 0, fired: 0, started: delay <= 0, paused });
+ }
+ scheduleOnce(callback: (dt: number) => void, target: object, delay = 0): void { this.schedule(callback, target, 0, 0, delay); }
+ /** Call `target.update(dt)` every frame, lowest priority first. */
+ scheduleUpdate(target: object, priority = 0, paused = false): void { this.updates_.set(target, { priority, paused }); }
+ unscheduleUpdate(target: object): void { this.updates_.delete(target); }
+ unschedule(callback: (dt: number) => void, target: object): void {
+ this.entries_ = this.entries_.filter((e) => !(e.callback === callback && e.target === target));
+ }
+ unscheduleAllForTarget(target: object): void {
+ this.entries_ = this.entries_.filter((e) => e.target !== target);
+ this.updates_.delete(target);
+ }
+ unscheduleAll(): void { this.entries_ = []; this.updates_.clear(); }
+ unscheduleAllWithMinPriority(minPriority: number): void {
+ if (minPriority <= Scheduler.PRIORITY_SYSTEM) { this.unscheduleAll(); return; }
+ for (const [target, u] of [...this.updates_]) if (u.priority >= minPriority) this.updates_.delete(target);
+ this.entries_ = [];
+ }
+ isScheduled(callback: (dt: number) => void, target: object): boolean {
+ return this.entries_.some((e) => e.callback === callback && e.target === target);
+ }
+ pauseTarget(target: object): void { this.pausedTargets_.add(target); }
+ resumeTarget(target: object): void { this.pausedTargets_.delete(target); }
+ isTargetPaused(target: object): boolean { return this.pausedTargets_.has(target); }
+ setTimeScale(scale: number): void { this.timeScale_ = scale; }
+ getTimeScale(): number { return this.timeScale_; }
+
+ /** @internal Advance by one frame's @p delta seconds. */
+ update(delta: number): void {
+ const dt = delta * this.timeScale_;
+ const updates = [...this.updates_].sort((a, b) => a[1].priority - b[1].priority);
+ for (const [target, u] of updates) {
+ if (u.paused || this.pausedTargets_.has(target) || !this.updates_.has(target)) continue;
+ (target as { update?: (dt: number) => void }).update?.(dt);
+ }
+ // A callback may schedule or unschedule: walk a copy, and skip an entry that was removed meanwhile.
+ for (const e of [...this.entries_]) {
+ if (e.paused || this.pausedTargets_.has(e.target) || !this.entries_.includes(e)) continue;
+ e.elapsed += dt;
+ if (!e.started) {
+ if (e.elapsed < e.delay) continue;
+ e.started = true;
+ e.elapsed -= e.delay;
+ this.fire_(e, e.elapsed);
+ continue;
+ }
+ if (e.interval <= 0) { this.fire_(e, dt); continue; }
+ while (e.elapsed >= e.interval && this.entries_.includes(e)) {
+ e.elapsed -= e.interval;
+ this.fire_(e, e.interval);
+ }
+ }
+ }
+
+ private fire_(e: Entry, dt: number): void {
+ e.fired++;
+ // `repeat` counts the fires after the first, so a once-timer (0) ends with its first
+ if (e.fired > e.repeat) this.entries_ = this.entries_.filter((x) => x !== e);
+ try { e.callback.call(e.target, dt); } catch (err) { console.error('[cocos] a scheduled callback threw', err); }
+ }
+}
+
+export const scheduler = new Scheduler();
diff --git a/sdk/tests/cocos/globals.test.ts b/sdk/tests/cocos/globals.test.ts
index f07fde668..4f382276e 100644
--- a/sdk/tests/cocos/globals.test.ts
+++ b/sdk/tests/cocos/globals.test.ts
@@ -6,7 +6,7 @@
*/
import { beforeEach, describe, expect, it } from 'vitest';
import {
- Game, KeyCode, Layers, Prefab, Size, View, assetManager, game, macro, resources, screen, setResourceManifest, setVisibleSize, sys, view,
+ Game, KeyCode, Scheduler, Asset, director, reportFrame, Layers, Prefab, Size, View, assetManager, game, macro, resources, screen, setResourceManifest, setVisibleSize, sys, view,
providePrefab,
} from '../../src/cocos';
import { keyCodeOf } from '../../src/cocos/inputApi';
@@ -195,3 +195,70 @@ describe('resources and assetManager', () => {
expect(assetManager.cacheManager.cachedFiles.count).toBe(0);
});
});
+
+describe('director', () => {
+ it('hands out a scheduler that runs timers by target, with a delay, an interval and a repeat count', () => {
+ const scheduler = director.getScheduler();
+ const target = {};
+ const calls: number[] = [];
+ scheduler.schedule(function (this: unknown, dt) { expect(this).toBe(target); calls.push(dt); }, target, 0.5, 1, 0.25);
+ reportFrame(0.2); expect(calls).toHaveLength(0); // inside the delay
+ reportFrame(0.1); expect(calls).toHaveLength(1); // the delay ended: the first fire
+ reportFrame(0.5); expect(calls).toHaveLength(2); // one interval later: the one repeat
+ reportFrame(0.5); expect(calls).toHaveLength(2); // and no more
+ expect(scheduler.isScheduled(() => {}, target)).toBe(false);
+ });
+
+ it('stops what was unscheduled, pauses by target, and scales time', () => {
+ const scheduler = new Scheduler();
+ const target = {};
+ let n = 0;
+ const tick = (): void => { n++; };
+ scheduler.schedule(tick, target);
+ scheduler.update(0.1); expect(n).toBe(1);
+ scheduler.pauseTarget(target); scheduler.update(0.1); expect(n).toBe(1);
+ scheduler.resumeTarget(target); scheduler.setTimeScale(0.5);
+ let seen = 0; scheduler.unscheduleAllForTarget(target);
+ scheduler.schedule((dt) => { seen = dt; }, target);
+ scheduler.update(0.2); expect(seen).toBeCloseTo(0.1);
+ scheduler.unscheduleAllForTarget(target); scheduler.update(0.2); expect(n).toBe(1);
+ });
+
+ it('calls update on a scheduled target, lowest priority first', () => {
+ const scheduler = new Scheduler();
+ const order: string[] = [];
+ scheduler.scheduleUpdate({ update: () => order.push('late') }, 5);
+ scheduler.scheduleUpdate({ update: () => order.push('early') }, -5);
+ scheduler.update(0.016);
+ expect(order).toEqual(['early', 'late']);
+ });
+
+ it('reports the frame delta to scripts', () => {
+ reportFrame(0.033);
+ expect(director.getDeltaTime()).toBeCloseTo(0.033);
+ });
+});
+
+describe('Asset', () => {
+ it('keeps a count of its holders', () => {
+ const a = new Asset('x');
+ expect(a.addRef()).toBe(a);
+ a.addRef();
+ expect(a.refCount).toBe(2);
+ a.decRef();
+ expect(a.refCount).toBe(1);
+ a.decRef(); a.decRef();
+ expect(a.refCount).toBe(0);
+ });
+
+ it('is loaded by uuid, from the manifest listing', async () => {
+ setResourceManifest({ resources: { 'prefab/bullet': { path: 'bullet.esprefab', kind: 'prefab', uuid: 'abc-123' } } });
+ providePrefab('bullet.esprefab', { ref: 'bullet.esprefab', scene: { version: 4, name: 'bullet', entities: [] } as never, rootId: 0, missing: [], release() {} });
+ const loaded = await new Promise<{ err: Error | null; result: unknown }>((resolve) =>
+ assetManager.loadAny({ uuid: 'abc-123' }, (err: Error | null, result: unknown) => resolve({ err, result })));
+ expect(loaded.err).toBeNull();
+ expect(loaded.result).toBeInstanceOf(Prefab);
+ const missing = await new Promise<Error | null>((resolve) => assetManager.loadAny('nope', (err: Error | null) => resolve(err)));
+ expect(missing?.message).toMatch(/uuid nope/);
+ });
+});
diff --git a/sdk/tests/cocos/node-wasm.test.ts b/sdk/tests/cocos/node-wasm.test.ts
index 8359e5cfb..db83d8ca5 100644
--- a/sdk/tests/cocos/node-wasm.test.ts
+++ b/sdk/tests/cocos/node-wasm.test.ts
@@ -65,6 +65,20 @@ describe.skipIf(!HAS_WASM)('Node on the engine', () => {
expect(canvas.isChildOf(button)).toBe(false);
});
+ it('moves a node among its siblings, and the child order follows', () => {
+ connect();
+ const { canvas, panel, label } = tree();
+ const extra = new Node('Extra'); W().insert(extra._entity, Transform); canvas.addChild(extra);
+ expect(names(canvas.children)).toEqual(['Panel', 'Label', 'Extra']);
+ extra.setSiblingIndex(0);
+ expect(names(canvas.children)).toEqual(['Extra', 'Panel', 'Label']);
+ expect(extra.getSiblingIndex()).toBe(0);
+ panel.setSiblingIndex(-1);
+ expect(names(canvas.children)).toEqual(['Extra', 'Label', 'Panel']);
+ label.setSiblingIndex(99); // past the end is the end
+ expect(names(canvas.children)).toEqual(['Extra', 'Panel', 'Label']);
+ });
+
it('detaches with removeFromParent, and moves with setParent', () => {
connect();
const { canvas, panel, button, label } = tree();