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): director.loadScene runs a project scene through the engine's scene manager (scenes are in the manifest, persistent roots are SceneOwner.persistent); components start in one phase before the frame's updates; Camera.screenPointToRay
yhhe235876f52fc
diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsindex 4cf1c4918..464d6b99f 100644--- a/pipeline/src/import/cocos/importProject.ts+++ b/pipeline/src/import/cocos/importProject.ts@@ -31,7 +31,7 @@ import { convertPass, isOutlinePass, type PassConversion } from './effectConvert* importer that made less (or differently), and is brought up to date when it is opened. Raise it when the converted output changes in a* way an existing project needs to pick up: a new generated file, a field a document or a manifest now carries.*/-export const COCOS_IMPORT_REVISION = 10;+export const COCOS_IMPORT_REVISION = 11;/** Whether the project at @p projectRoot was written by an importer of this revision. A project that was not converted has nothing to bring up. */export function cocosImportIsCurrent(projectRoot: string): boolean {@@ -921,7 +921,10 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impoentries[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', uuid: entry.uuid };- } else if (ext !== 'meta' && ext !== 'ts' && ext !== 'js' && ext !== 'scene') {+ } else if (ext === 'scene') {+ // a scene is run by its name (`director.loadScene('scene_level_003')`), which is the file's, wherever its bundle puts it+ entries[key] = { path: outRef(esRel(entry.rel, '.esscene')), kind: 'scene', uuid: entry.uuid };+ } else if (ext !== 'meta' && ext !== 'ts' && ext !== 'js') {entries[key] = { path: '', kind: ext || 'other', uuid: entry.uuid };}}diff --git a/sdk/src/cocos/assetManager.ts b/sdk/src/cocos/assetManager.tsindex f261bc198..38fc631a5 100644--- a/sdk/src/cocos/assetManager.ts+++ b/sdk/src/cocos/assetManager.ts@@ -17,7 +17,7 @@*/import { platformFetch } from '../platform';import { log } from '../util/logger';-import { Asset, AudioClip, ImageAsset, JsonAsset, Material, Prefab, SpriteFrame, TextAsset, Texture2D } from './assets';+import { Asset, AudioClip, ImageAsset, JsonAsset, Material, Prefab, SceneAsset, SpriteFrame, TextAsset, Texture2D } from './assets';import { getCurrentWorld } from './node';import { assetsFor, loadPrefab, onNewSession } from './prefabs';@@ -160,6 +160,20 @@ async function loadEntry(entry: ResourceEntry, asked: AssetCtor | null): Promisethrow new UnsupportedAssetKind(`cocos compat: loading "${entry.path}" (${entry.kind}${type ? `, as ${type.name}` : ''}) is not supported by the compatibility layer yet; prefabs, JSON, text, images and audio are`);}+/** The scenes of the project, by the name a script runs them by: the file's name, without its folders or extension. */+export async function listScenes(): Promise<Array<{ name: string; path: string }>> {+ const manifest = await theManifest();+ const out = new Map<string, string>();+ for (const bundle of Object.values(manifest)) {+ for (const [key, entry] of Object.entries(bundle)) {+ if (entry.kind !== 'scene' || !entry.path) continue;+ const name = key.slice(key.lastIndexOf('/') + 1);+ if (!out.has(name)) out.set(name, entry.path);+ }+ }+ return [...out].map(([name, path]) => ({ name, path }));+}+export class Bundle {readonly base = '';constructor(readonly name: string, private readonly entries_: () => Promise<Record<string, ResourceEntry>>) {}@@ -228,6 +242,20 @@ export class Bundle {);}+ /** A scene of the bundle as an asset: what `director.runScene` takes. The scene's content is the engine's scene manager's to load. */+ loadScene(name: string, ...rest: unknown[]): void {+ const fns = rest.filter((a): a is (...args: unknown[]) => void => typeof a === 'function');+ const done = fns[fns.length - 1] as ((error: Error | null, asset?: SceneAsset) => void) | undefined;+ listScenes().then((scenes) => {+ if (!scenes.some((s) => s.name === name)) throw new Error(`cocos compat: bundle "${this.name}" has no scene "${name}"`);+ const asset = new SceneAsset(name);+ asset.name = name;+ return asset;+ }).then((asset) => done?.(null, asset), (error: Error) => done?.(error));+ }+ /** Preparing a scene is finding it, here: the scene manager readies what it loads when it loads it. */+ preloadScene(name: string, ...rest: unknown[]): void { this.loadScene(name, ...rest); }+/** Preparing is loading, here. */preload(...args: unknown[]): void { this.load(...args); }preloadDir(...args: unknown[]): void { this.loadDir(...args); }diff --git a/sdk/src/cocos/builtinScripts.ts b/sdk/src/cocos/builtinScripts.tsindex 5fea050f4..d4e135459 100644--- a/sdk/src/cocos/builtinScripts.ts+++ b/sdk/src/cocos/builtinScripts.ts@@ -18,6 +18,7 @@ import { declareDirector } from './director';import { declareTweenSystem } from './tween';import { declarePrefabSystem } from './prefabs';import { declareGameSystem } from './game';+import { declareStartPhase } from './host';import { resetClassRegistry, setBuiltinDeclarer } from './registry';const declared = new WeakSet<object>();@@ -48,6 +49,7 @@ export function declareBuiltinScripts(): void {declareTweenSystem();declarePrefabSystem();declareGameSystem();+ declareStartPhase();queued.set(context, {systems: context.pendingSystems.slice(systemsBefore), plugins: context.pendingPlugins.slice(pluginsBefore), epoch: context.queueEpoch,});diff --git a/sdk/src/cocos/director.ts b/sdk/src/cocos/director.tsindex 2c8047257..31c6cd9fb 100644--- a/sdk/src/cocos/director.ts+++ b/sdk/src/cocos/director.ts@@ -8,20 +8,28 @@* 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 { Children, Name, Parent, SceneOwner } from '../ecs/component';+import { log } from '../util/logger';import type { World } from '../ecs/world';import { INVALID_ENTITY, type Entity } from '../types';-import { Schedule, defineSystem, addSystemToSchedule } from '../ecs/system';+import { Schedule, defineSystem, addSystemToSchedule, GetWorld } from '../ecs/system';import { Res, Time } from '../ecs/resource';import { Node, getCurrentWorld } from './node';import { Scheduler, scheduler } from './scheduler';+import { SceneManager, type SceneManagerState } from '../scene/sceneManager';+import { listScenes } from './assetManager';+import { SceneAsset } from './assets';/** The root of the running scene: a stand-in for the parent the world's top-level entities do not have. */export class Scene {constructor(private readonly world: World) {}- get name(): string { return 'Scene'; }+ private name_ = 'Scene';+ get name(): string { return this.name_; }+ set name(value: string) { this.name_ = value; }get active(): boolean { return true; }+ /** A scene is a root, not a node: it holds no components. */+ getComponent(_type?: unknown): null { return null; }get isValid(): boolean { return true; }get children(): Node[] {@@ -30,6 +38,9 @@ export class Scene {const parent = this.world.tryGet(e, Parent)?.entity;if (!parent || parent === INVALID_ENTITY) roots.push(e);}+ // A node kept across scenes is moved under the new scene after the scene's own, so the new scene's come first+ const kept = (e: Entity): boolean => this.world.tryGet(e, SceneOwner)?.persistent === true;+ roots.sort((a, b) => Number(kept(a)) - Number(kept(b)));return roots.map((e) => Node.for(this.world, e));}get childrenCount(): number { return this.children.length; }@@ -57,8 +68,81 @@ function requireWorld(what: string): World {return world;}-/** The parts of `director` scripts actually call. Scene loading and the persistent-root list are the engine's, and are not simulated. */+/** The engine's scene manager of each world, learned from the frame loop (see {@link declareDirector}). */+const sceneManagers = new WeakMap<World, SceneManagerState>();+const registeredScenes = new WeakMap<World, Set<string>>();+let loadingScene = '';++/** What a scene's nodes keep across a scene change: the engine's `SceneOwner.persistent`, set on the node and what is under it. */+function setPersistent(node: Node, persistent: boolean): void {+ const world = node._world;+ const visit = (e: Entity): void => {+ const owner = world.tryGet(e, SceneOwner);+ if (owner && owner.persistent !== persistent) world.set(e, SceneOwner, { ...owner, persistent });+ for (const child of world.tryGet(e, Children)?.entities ?? []) visit(child);+ };+ visit(node._entity);+}++/** Give the scene manager every scene of the project by name, once. */+async function registerScenes(world: World, manager: SceneManagerState): Promise<void> {+ let done = registeredScenes.get(world);+ if (!done) registeredScenes.set(world, (done = new Set()));+ for (const scene of await listScenes()) {+ if (done.has(scene.name)) continue;+ done.add(scene.name);+ manager.register({ name: scene.name, path: scene.path });+ }+}++function sceneManagerOf(world: World): SceneManagerState {+ const manager = sceneManagers.get(world);+ if (!manager) throw new Error('cocos compat: the engine\'s scene manager is not running');+ return manager;+}++/** Run @p name as the scene: the one before it goes, what the game marked persistent stays, and @p done hears how it went. */+function runScene(name: string, done?: (error: Error | null, scene?: Scene) => void): void {+ const world = requireWorld('director.loadScene');+ loadingScene = name;+ director.emit(Director.EVENT_BEFORE_SCENE_LOADING, name);+ (async () => {+ const manager = sceneManagerOf(world);+ await registerScenes(world, manager);+ await manager.load(name);+ return new Scene(world);+ })().then(+ (scene) => { loadingScene = ''; director.emit(Director.EVENT_AFTER_SCENE_LAUNCH, scene); done?.(null, scene); },+ (error: Error) => { loadingScene = ''; log.warn('cocos', `scene "${name}" did not load: ${String(error.message ?? error)}`); done?.(error); },+ );+}++/** The parts of `director` scripts actually call. */export const director = {+ /** The name of the scene being loaded, or empty: a game reads it to refuse a second load while one is under way. */+ get _loadingScene(): string { return loadingScene; },+ /** Run a scene by its name. `onLaunched(error, scene)` hears the result. */+ loadScene(name: string, onLaunched?: (error: Error | null, scene?: Scene) => void): boolean {+ runScene(name, onLaunched);+ return true;+ },+ /** Run a scene a bundle's `loadScene` gave. */+ runScene(scene: SceneAsset | string, _onBeforeLoad?: () => void, onLaunched?: (error: Error | null, scene?: Scene) => void): void {+ runScene(typeof scene === 'string' ? scene : scene.name, onLaunched);+ },+ /** Ready a scene so running it is quick. */+ preloadScene(name: string, onProgress?: unknown, onLoaded?: (error: Error | null, scene?: SceneAsset) => void): void {+ const done = (typeof onProgress === 'function' && onLoaded === undefined ? onProgress : onLoaded) as ((error: Error | null, scene?: SceneAsset) => void) | undefined;+ const world = requireWorld('director.preloadScene');+ (async () => {+ const manager = sceneManagerOf(world);+ await registerScenes(world, manager);+ await manager.prepare(name);+ const asset = new SceneAsset(name);+ asset.name = name;+ return asset;+ })().then((asset) => done?.(null, asset), (error: Error) => done?.(error));+ },getScene(): Scene | null {const world = getCurrentWorld();return world ? new Scene(world) : null;@@ -85,10 +169,10 @@ export const director = {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; },+ /** Keep a node (and what is under it) through scene changes. */+ addPersistRootNode(node: Node): void { setPersistent(node, true); },+ removePersistRootNode(node: Node): void { setPersistent(node, false); },+ isPersistRootNode(node: Node): boolean { return node._world.tryGet(node._entity, SceneOwner)?.persistent === true; },};let lastDelta = 0;@@ -144,6 +228,11 @@ export function isValid(value: unknown, _strict = false): boolean {* emits them.*/export function declareDirector(): void {+ addSystemToSchedule(Schedule.First, defineSystem(+ [Res(SceneManager), GetWorld()],+ (manager, world) => { if (manager) sceneManagers.set(world, manager as SceneManagerState); },+ { name: 'Cocos:SceneManager', touches: { opaque: true } },+ ));addSystemToSchedule(Schedule.First, defineSystem([Res(Time)],(time) => { reportFrame(time.delta); director.emit(Director.EVENT_BEFORE_UPDATE); },diff --git a/sdk/src/cocos/host.ts b/sdk/src/cocos/host.tsindex 48746fb9b..7a2d80915 100644--- a/sdk/src/cocos/host.ts+++ b/sdk/src/cocos/host.ts@@ -24,7 +24,7 @@ import { log } from '../util/logger';import { Color, Vec2, Vec3 } from './math';import { Node, setCurrentWorld } from './node';import {- COMPONENT_PREFIX, classInfoNamed, ensureBuiltinsDeclared, classInfoOf, dropInstance, instancesOfClass, instancesOn, nodeOf, registerClassInfo, setActivitySync, setInstantiator, storeInstance,+ COMPONENT_PREFIX, classInfoNamed, ensureBuiltinsDeclared, classInfoOf, dropInstance, instancesOfClass, instancesOn, nodeOf, registerClassInfo, setActivitySync, setInstantiator, storeInstance, awaitStart, pendingStarts,type ClassInfo, type ComponentCtor, type PropertyKind, type PropertySpec,} from './registry';@@ -126,6 +126,9 @@ function instantiate(world: World, entity: Entity, ctor: ComponentCtor): Compone}inst._loaded = true;call(inst, 'onLoad');+ // `start` belongs to the start phase, which runs before the frame's updates; what has no `start` has started+ if (typeof (inst as unknown as { start?: unknown }).start === 'function') awaitStart(world, inst);+ else inst._started = true;return inst;} finally {setCurrentWorld(previous);@@ -173,7 +176,7 @@ function syncSubtree(world: World, root: Entity): void {setActivitySync(syncSubtree);/** Run the per-frame part of one instance: enable/disable as its activity changes, then `start` once, then the timers and `update`. */-function drive(world: World, entity: Entity, inst: Component, dt: number): void {+function drive(world: World, entity: Entity, inst: Component, dt: number, fresh = false): void {const active = inst.enabled && world.isEntityActive(entity);if (active && !inst._enabledApplied) {inst._enabledApplied = true;@@ -184,6 +187,10 @@ function drive(world: World, entity: Entity, inst: Component, dt: number): void}if (!active) return;if (!inst._started) {+ // A component made by this very pass has no earlier life to be ordered against: it starts here, as one that existed when the frame began.+ // Any other waits for the start phase, which gives every enabled component its `start` ahead of the frame's updates.+ if (!fresh) return;+ pendingStarts(world)?.delete(inst);inst._started = true;call(inst, 'start');}@@ -206,6 +213,39 @@ function destroyInstance(world: World, entity: Entity, ctor: Function, inst: ComdropInstance(world, entity, ctor);}+/**+ * The start phase of a frame. Cocos calls `start` on every component enabled since the last frame before it calls any `update`, so a script+ * that sets another component up in its `start` is read by that component's `update` of the same frame, whichever of them was declared first.+ */+export function declareStartPhase(): void {+ addSystemToSchedule(Schedule.PreUpdate, defineSystem(+ [GetWorld()],+ (world) => {+ const waiting = pendingStarts(world);+ if (!waiting || waiting.size === 0) return;+ const previous = setCurrentWorld(world);+ try {+ // `start` may enable more components; those wait for the next phase+ for (const inst of [...waiting]) {+ if (inst._destroyed) { waiting.delete(inst); continue; }+ if (!world.valid(inst._entity) || !inst.enabled || !world.isEntityActive(inst._entity)) continue;+ // enabled by the time the frame begins, whether or not its class has had a pass yet+ if (!inst._enabledApplied) {+ inst._enabledApplied = true;+ call(inst, 'onEnable');+ }+ waiting.delete(inst);+ inst._started = true;+ call(inst, 'start');+ }+ } finally {+ setCurrentWorld(previous);+ }+ },+ { name: 'Cocos:Start', touches: { opaque: true } },+ ));+}+/*** 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.@@ -238,8 +278,9 @@ export function declareClass(ctor: ComponentCtor, name: string, raw: RawProperty// walked does not allow.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);+ const existing = instancesOn(world, entity)?.get(ctor);+ const inst = existing ?? instantiate(world, entity, ctor);+ if (inst) drive(world, entity, inst, time.delta, !existing);}// Instances the query did not return are either switched off (still carrying the component) or gone.for (const [entity, inst] of instancesOfClass(world, ctor)) {diff --git a/sdk/src/cocos/math.ts b/sdk/src/cocos/math.tsindex 0dedcb7a2..543b3d958 100644--- a/sdk/src/cocos/math.ts+++ b/sdk/src/cocos/math.ts@@ -54,6 +54,17 @@ export class Vec3 {return this;}clone(): Vec3 { return new Vec3(this.x, this.y, this.z); }+ /** A vector turned by a unit quaternion. */+ static transformQuat(out: Vec3, a: Vec3, q: { x: number; y: number; z: number; w: number }): Vec3 {+ const ix = q.w * a.x + q.y * a.z - q.z * a.y;+ const iy = q.w * a.y + q.z * a.x - q.x * a.z;+ const iz = q.w * a.z + q.x * a.y - q.y * a.x;+ const iw = -q.x * a.x - q.y * a.y - q.z * a.z;+ out.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;+ out.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;+ out.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;+ return out;+ }/** A point through a matrix (w = 1), with the perspective divide. */static transformMat4(out: Vec3, a: Vec3, m: { m00: number; m01: number; m02: number; m03: number; m04: number; m05: number; m06: number; m07: number; m08: number; m09: number; m10: number; m11: number; m12: number; m13: number; m14: number; m15: number }): Vec3 {const x = a.x, y = a.y, z = a.z;diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.tsindex 94914d7b2..e98910ab6 100644--- a/sdk/src/cocos/node.ts+++ b/sdk/src/cocos/node.ts@@ -301,6 +301,7 @@ export class Node {get worldRotation(): Quat { const q = this.composedTransform_().worldRotation; return new Quat(q.x, q.y, q.z, q.w); }get worldPosition(): Vec3 { const p = this.composedTransform_().worldPosition; return new Vec3(p.x, p.y, p.z); }set worldPosition(v: Vec3) { this.setWorldPosition(v); }+ getWorldRotation(out?: Quat): Quat { const q = this.composedTransform_().worldRotation; return (out ?? new Quat()).set(q.x, q.y, q.z, q.w); }getWorldPosition(out?: Vec3): Vec3 { const p = this.composedTransform_().worldPosition; return (out ?? new Vec3()).set(p.x, p.y, p.z); }/** Place this node so its world position is @p x. Under a parent that is rotated or scaled, the local position is solved for. */diff --git a/sdk/src/cocos/registry.ts b/sdk/src/cocos/registry.tsindex 2a56ecc41..b2b999f1e 100644--- a/sdk/src/cocos/registry.ts+++ b/sdk/src/cocos/registry.ts@@ -110,6 +110,16 @@ export function storeInstance(world: World, entity: Entity, ctor: Function, instbyClass.set(ctor, inst);}+/** The instances waiting for their `start`, by world, in the order they were made. */+const awaitingStart = new WeakMap<World, Set<Component>>();+/** An instance with a `start` waits for the start phase, which runs before any `update` of the frame. */+export function awaitStart(world: World, inst: Component): void {+ let set = awaitingStart.get(world);+ if (!set) awaitingStart.set(world, (set = new Set()));+ set.add(inst);+}+export function pendingStarts(world: World): Set<Component> | undefined { return awaitingStart.get(world); }+export function dropInstance(world: World, entity: Entity, ctor: Function): void {const perEntity = instances.get(world);const byClass = perEntity?.get(entity);diff --git a/sdk/src/cocos/ui/camera.ts b/sdk/src/cocos/ui/camera.tsindex b0b2565e1..0bc136b01 100644--- a/sdk/src/cocos/ui/camera.ts+++ b/sdk/src/cocos/ui/camera.ts@@ -18,12 +18,13 @@ import type { Entity } from '../../types';import { isProjectable, projectWorldPoint } from '../../ui/util/math';import { screenToUiWorld } from '../../ui/util/ui-pick';import { Color, Rect, Vec3 } from '../math';+import { Ray } from '../geometry';import { Component } from '../component';import { registerBuiltinComponent } from '../builtins';import type { Node } from '../node';import { viewAdapter } from './view';import { UITransform } from './uiTransform';-import { uiCameraData } from './screen';+import { getWindowPixels, uiCameraData } from './screen';const ProjectionType = Object.freeze({ ORTHO: 0, PERSPECTIVE: 1 });const FOVAxis = Object.freeze({ VERTICAL: 0, HORIZONTAL: 1 });@@ -89,6 +90,36 @@ export class Camera extends Component {return out.set(w.x, w.y, 0);}+ /**+ * The ray from the camera through a screen point (pixels of the drawing surface, origin bottom-left): from the camera's own pose and lens,+ * so a perspective camera's rays fan out from its position and an orthographic one's run parallel.+ */+ screenPointToRay(x: number, y: number, out: Ray = new Ray()): Ray {+ const surface = getWindowPixels();+ const width = surface.width > 0 ? surface.width : 1;+ const height = surface.height > 0 ? surface.height : 1;+ const lens = this.data_();+ const nx = (x / width) * 2 - 1;+ const ny = (y / height) * 2 - 1;+ const aspect = width / height;+ const rotation = this.node.getWorldRotation();+ const position = this.node.getWorldPosition();+ const turn = (v: Vec3): Vec3 => Vec3.transformQuat(new Vec3(), v, rotation);+ if (lens.projectionType === ENGINE_ORTHO) {+ const half = lens.orthoSize;+ const origin = turn(new Vec3(nx * half * aspect, ny * half, 0));+ const dir = turn(new Vec3(0, 0, -1));+ out.o.set(position.x + origin.x, position.y + origin.y, position.z + origin.z);+ out.d.set(dir.x, dir.y, dir.z);+ return out;+ }+ const reach = Math.tan((lens.fov * Math.PI) / 360);+ const dir = turn(new Vec3(nx * reach * aspect, ny * reach, -1)).normalize();+ out.o.set(position.x, position.y, position.z);+ out.d.set(dir.x, dir.y, dir.z);+ return out;+ }+/** The screen point (surface pixels, origin bottom-left) a world point lands on. */worldToScreen(worldPos: Vec3, out: Vec3 = new Vec3()): Vec3 {const cam = uiCameraData();diff --git a/sdk/tests/cocos/lifecycle.test.ts b/sdk/tests/cocos/lifecycle.test.tsindex 7f880ad61..8b1aba321 100644--- a/sdk/tests/cocos/lifecycle.test.ts+++ b/sdk/tests/cocos/lifecycle.test.ts@@ -11,9 +11,9 @@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 { SceneOwner, getUserComponents } from '../../src/ecs/component';import { resetClassRegistry } from '../../src/cocos/registry';-import { Component, Node, Vec3, _decorator, director, find, isValid } from '../../src/cocos';+import { Component, Node, Vec3, _decorator, director, find, isValid, setCurrentWorld } from '../../src/cocos';const { ccclass, property } = _decorator;@@ -275,3 +275,61 @@ describe('director, find, isValid', () => {expect(isValid(null)).toBe(false);});});++describe('the start phase', () => {+ it("gives every enabled component its start before any update of the frame, whichever was declared first", async () => {+ const seen: unknown[] = [];++ @ccclass('Bar')+ class Bar extends Component {+ state = '';+ percent: number | undefined;+ update(dt: number) { if (this.state === 'start') this.percent = dt; }+ }++ @ccclass('Screen')+ class Screen extends Component {+ bar: Bar | null = null;+ start() { this.bar!.state = 'start'; }+ update() { seen.push(this.bar!.percent); }+ }+ void Screen;++ const app = await boot();+ const world = app.world;+ const barEntity = world.spawn('bar');+ world.insert(barEntity, comp('Bar'), { enabled: true });+ const screenEntity = world.spawn('screen');+ world.insert(screenEntity, comp('Screen'), { enabled: true });+ // both exist before the frame, as a view and its child do when a script has been asking for them+ const bar = Node.for(world, barEntity).getComponent(Bar)!;+ const screen = Node.for(world, screenEntity).getComponent(Screen)!;+ screen.bar = bar;+ await app.tick(1 / 60);+ // Bar is declared before Screen, so its update runs first in the frame: it must already see what Screen's start set+ expect(seen).toEqual([1 / 60]);+ });+});++describe('keeping a node through scene changes', () => {+ it("marks the node persistent, and lists the new scene's own roots before the kept ones", async () => {+ const app = await boot();+ const world = app.world;+ const kept = world.spawn('ui_layer');+ world.insert(kept, SceneOwner, { scene: 'main', persistent: false });+ const own = world.spawn('ui_layer');+ world.insert(own, SceneOwner, { scene: 'level', persistent: false });++ setCurrentWorld(world);+ director.addPersistRootNode(Node.for(world, kept));+ expect(world.get(kept, SceneOwner).persistent).toBe(true);+ expect(world.get(own, SceneOwner).persistent).toBe(false);+ expect(director.isPersistRootNode(Node.for(world, kept))).toBe(true);++ // the new scene's own root answers a lookup by name, as in Cocos, where the kept nodes are put under the scene after it+ const scene = director.getScene()!;+ expect(scene.getChildByName('ui_layer')!._entity).toBe(own);+ director.removePersistRootNode(Node.for(world, kept));+ setCurrentWorld(null);+ });+});diff --git a/sdk/tests/cocos/misc.test.ts b/sdk/tests/cocos/misc.test.tsindex 422584ac5..d0d6b13cd 100644--- a/sdk/tests/cocos/misc.test.ts+++ b/sdk/tests/cocos/misc.test.ts@@ -3,7 +3,7 @@import { describe, expect, it } from 'vitest';import { NodePool, ccenum, js, profiler } from '../../src/cocos/misc';import type { Node } from '../../src/cocos/node';-import { Graphics, Label, Sprite, UIRenderer } from '../../src/cocos';+import { Graphics, Label, Quat, Sprite, UIRenderer, Vec3 } from '../../src/cocos';/** The parts of a node a pool touches. */function fakeNode(handler?: { unuse(): void; reuse(args: unknown[]): void }) {@@ -92,3 +92,15 @@ describe('UIRenderer', () => {expect(() => { probe.markForUpdateRenderData(); probe.markForUpdateRenderData(false); probe.setVertsDirty(); }).not.toThrow();});});++describe('Vec3.transformQuat', () => {+ it('keeps a vector under the identity and turns it by a quarter about Y', () => {+ const forward = new Vec3(0, 0, -1);+ expect(Vec3.transformQuat(new Vec3(), forward, new Quat(0, 0, 0, 1))).toMatchObject({ x: 0, y: 0, z: -1 });+ const s = Math.SQRT1_2;+ const turned = Vec3.transformQuat(new Vec3(), forward, new Quat(0, s, 0, s));+ expect(turned.x).toBeCloseTo(-1, 6);+ expect(turned.y).toBeCloseTo(0, 6);+ expect(turned.z).toBeCloseTo(0, 6);+ });+});