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): a converted project starts at the game launch scene and runs its global-defining scripts first, reads the editor built-in assets, and the layer components survive a replay
yhh877fe8d269ec
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3d33c62c0..23b28b32d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,8 @@ published separately; it ships inside the editor.- **Scroll areas can be pulled past an end and spring back.** A scroll area whose movement is Elastic now does what the setting always said: a drag past an end is stiffer the further out it goes, letting go returns the content, and a flick that reaches an end bounces off it. It is opt-in per area (`ScrollMovement.Elastic`; Clamped, the default, behaves as before), and the gesture model (`ScrollMotion`, with `ScrollContainer.dragTo` and `getOverscroll`) is exported for scrolling anything else the same way.- **More easing curves.** Sine, quart, quint, expo and circ (each in, out and in-out), bounce in and in-out, and smoothstep and smootherstep join the quad, cubic, back, elastic and out-bounce curves. They are new `EasingType` members after the existing ones, so a saved tween keeps its curve, and they ease the same in a C++ tween and a script value tween.- **World content has a rectangle: `ContentRect`.** A size and the pivot the entity's transform sits on, which the `Sprite` and `Text` on the entity follow and which a `UIMask` on it clips to — no `UINode` needed, so a clipping region or a scroll viewport can stand in the world. `contentRectContains` tests a world point against it.+- **A converted Cocos project starts as the game does.** The project opens at the Cocos launch scene (not the starter empty scene) and its design size, scripts that only define globals (the game configuration) run before the ones scenes name, and the editor built-in assets a scene names by uuid (the default progress bar images) are read from the Creator install, which took the missing sprite frames of the client from 385 to 15.+- **Cocos layer components survive a replay.** The components the layer declares (Widget, Button, ProgressBar, ScrollView and the rest) are counted among the engine own, so clearing the registry for a replay no longer drops them, and the host walks its script query before running scripts, so a script that switches nodes on in `start` does not meet a walked query.- **A material colour is the renderer tint.** The engine keeps a mesh colour on the renderer, not in a shader parameter, so `mainColor`, `albedo`, `baseColor` and `color` set on a renderer own material instance write its tint and read back from it.- **Mesh renderers and materials in the Cocos layer.** `MeshRenderer` is a view on the engine mesh renderer: `getSharedMaterial`, `getMaterialInstance` (the engine own per-renderer instance, made once), `material`, `setMaterial`, and `Material.setProperty` / `getProperty` writing through to the engine material (colours 0..255 become 0..1). `ModelRenderer` and `UIMeshRenderer` exist, and `cc.geometry` has `AABB`, `Ray`, `Plane` and the box, ray and plane tests.- **More of `cc`.** `js` (class names and lookup, `isChildClassOf`, `mixin`, `addon`, property definers), `ccenum` and `NodePool` (put a node away, get it back, with the handler component told `unuse` and `reuse`) are in the Cocos compatibility layer.diff --git a/pipeline/src/import/cocos/assets.ts b/pipeline/src/import/cocos/assets.tsindex 57a82de98..7d03a702f 100644--- a/pipeline/src/import/cocos/assets.ts+++ b/pipeline/src/import/cocos/assets.ts@@ -8,7 +8,7 @@* sub-asset (`<image uuid>@f9941`) of its image. This reads every meta* once into a lookup. Read-only.*/-import { readdirSync, readFileSync } from 'node:fs';+import { existsSync, readdirSync, readFileSync } from 'node:fs';import path from 'node:path';export interface CocosAssetEntry {@@ -59,10 +59,41 @@ function* walk(dir: string): Generator<string> {const asObj = (v: unknown): Record<string, unknown> => (typeof v === 'object' && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : {});-export function buildCocosAssetIndex(root: string): CocosAssetIndex {+/** Where a project's own copy of the editor's built-in assets lands in the converted project, under the import's folder. */+export const INTERNAL_FOLDER = '__cocos_internal';++/**+ * The editor's built-in assets (`default_ui`, the default particle, the default materials), which a project names by uuid and does not hold: they+ * live in the Creator install. `COCOS_EDITOR_ASSETS` names the folder outright; otherwise the install the project's own version points at, in the+ * place the installer puts it. Null when it is not on this machine, in which case what refers to one is left as a reference that does not resolve.+ */+export function cocosEditorAssets(version: string | undefined): string | null {+ const tail = ['resources', 'resources', '3d', 'engine', 'editor', 'assets'];+ const candidates: string[] = [];+ if (process.env.COCOS_EDITOR_ASSETS) candidates.push(process.env.COCOS_EDITOR_ASSETS);+ if (version) {+ candidates.push(path.join('C:/ProgramData/cocos/editors/Creator', version, ...tail));+ candidates.push(path.join('/Applications/Cocos/Creator', version, 'CocosCreator.app/Contents', 'Resources', ...tail.slice(1)));+ }+ return candidates.find((c) => existsSync(c)) ?? null;+}++export function buildCocosAssetIndex(root: string, internalRoot?: string | null): CocosAssetIndex {const byUuid = new Map<string, CocosAssetEntry>();const bundles: CocosBundleRoot[] = [];- for (const metaFile of walk(root)) {+ scan(root, root, '', byUuid, bundles, true);+ // What the project does not hold itself: its own assets win, so a project that carries a copy of a built-in is read as it is.+ if (internalRoot) {+ const internal = new Map<string, CocosAssetEntry>();+ scan(internalRoot, internalRoot, `${INTERNAL_FOLDER}/`, internal, [], false);+ // Models are left out: the built-in shapes are mapped to the engine's own, by their uuid, and are not meant to be imported as files.+ for (const [uuid, entry] of internal) if (!byUuid.has(uuid) && entry.importer !== 'fbx' && entry.importer !== 'gltf') byUuid.set(uuid, entry);+ }+ return { root, byUuid, bundles };+}++function scan(dir: string, root: string, relPrefix: string, byUuid: Map<string, CocosAssetEntry>, bundles: CocosBundleRoot[], withBundles: boolean): void {+ for (const metaFile of walk(dir)) {let meta: Record<string, unknown>;try {meta = asObj(JSON.parse(readFileSync(metaFile, 'utf8')));@@ -71,6 +102,7 @@ export function buildCocosAssetIndex(root: string): CocosAssetIndex {}const uuid = meta.uuid;if (meta.importer === 'directory') {+ if (!withBundles) continue;const folder = metaFile.slice(0, -'.meta'.length);const rel = path.relative(root, folder).split(path.sep).join('/');const userData = asObj(meta.userData);@@ -83,7 +115,7 @@ export function buildCocosAssetIndex(root: string): CocosAssetIndex {const entry: CocosAssetEntry = {uuid,file,- rel: path.relative(root, file).split(path.sep).join('/'),+ rel: relPrefix + path.relative(root, file).split(path.sep).join('/'),importer: typeof meta.importer === 'string' ? meta.importer : '',userData: asObj(meta.userData),subs: new Map(),@@ -96,5 +128,4 @@ export function buildCocosAssetIndex(root: string): CocosAssetIndex {}byUuid.set(uuid, entry);}- return { root, byUuid, bundles };}diff --git a/pipeline/src/import/cocos/importProject.ts b/pipeline/src/import/cocos/importProject.tsindex 6135c104e..6574897bc 100644--- a/pipeline/src/import/cocos/importProject.ts+++ b/pipeline/src/import/cocos/importProject.ts@@ -13,7 +13,7 @@ import { copyFileSync, existsSync, linkSync, mkdirSync, readdirSync, readFileSynimport path from 'node:path';import { isInsideRoot } from '../../fs/pathSandbox';import { buildScriptIndex } from './scripts';-import { buildCocosAssetIndex, type CocosAssetEntry } from './assets';+import { buildCocosAssetIndex, cocosEditorAssets, type CocosAssetEntry, type CocosAssetIndex } from './assets';import type { AssetHints, SliceBorder } from './components';import { convertPrefab, convertScene, type ConvertContext } from './convert';import { parseCocosDocument, type CocosDocument } from './document';@@ -146,6 +146,58 @@ function writeClassNames(out: string, entry: string, assetsDir: string, scripts:else rmSync(file, { force: true });}+/** The scene a Cocos game starts in: its launch scene when there is one, else a scene named main at the top. */+function startSceneOf(scenes: readonly string[]): string | undefined {+ const find = (re: RegExp): string | undefined => scenes.find((r) => re.test(r));+ return find(/(^|\/)launch\/main\.scene$/) ?? find(/(^|\/)launch\/[^/]+\.scene$/) ?? find(/^main\.scene$/);+}++/**+ * Make the converted project start where the Cocos game does: the starter project opens its own empty scene and an 800x600 design size, so+ * playing it shows nothing of the game. Only a manifest still carrying the starter's values is changed; one the creator edited is theirs.+ */+function wireManifest(out: string, source: string, into: string, scenes: readonly string[]): void {+ const file = path.join(out, 'project.esproject');+ let manifest: { defaultScene?: string; designResolution?: { width?: number; height?: number } };+ try {+ manifest = JSON.parse(readFileSync(file, 'utf8'));+ } catch {+ return;+ }+ let changed = false;+ const start = startSceneOf(scenes);+ if (start && manifest.defaultScene === 'assets/scenes/main.esscene') {+ manifest.defaultScene = `assets/${into}/${start.replace(/\.scene$/, '.esscene')}`;+ changed = true;+ }+ try {+ const settings = JSON.parse(readFileSync(path.join(source, 'settings', 'v2', 'packages', 'project.json'), 'utf8')) as { general?: { designResolution?: { width?: number; height?: number } } };+ const size = settings.general?.designResolution;+ const dr = manifest.designResolution;+ if (size?.width && size.height && (!dr || (dr.width === 800 && dr.height === 600))) {+ manifest.designResolution = { width: size.width, height: size.height };+ changed = true;+ }+ } catch { /* a project with no settings keeps the starter's size */ }+ if (changed) writeOut(file, JSON.stringify(manifest, null, 2) + '\n');+}++/** A top-level assignment to a global: `globalThis.x = …`, `window.x = …` or `window['x'] = …`. */+const GLOBAL_DEFINITION = /^(?:globalThis|window)(?:\.\w+|\[['"]\w+['"]\])\s*=/m;++/** The scripts that define globals at their top level, in path order. */+function globalDefiningScripts(assets: CocosAssetIndex): string[] {+ const found: string[] = [];+ for (const entry of assets.byUuid.values()) {+ if (!/\.(ts|js)$/.test(entry.rel) || entry.rel.endsWith('.d.ts')) continue;+ if (entry.importer !== 'typescript' && entry.importer !== 'javascript') continue;+ try {+ if (GLOBAL_DEFINITION.test(readFileSync(entry.file, 'utf8'))) found.push(entry.rel);+ } catch { /* unreadable: not one */ }+ }+ return found.sort();+}+const GENERATED = 'Generated by import-cocos';/** A default for a field, of the kind its sample is: what the editor shows before anything is typed. */@@ -203,7 +255,8 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impoconst report = new ImportReport();const progress = (stage: CocosImportProgress['stage'], done: number, total: number, item?: string): void => opts.onProgress?.({ stage, done, total, ...(item ? { item } : {}) });progress('index', 0, 1);- const index = buildCocosAssetIndex(assetsDir);+ const version = (() => { try { return (JSON.parse(readFileSync(path.join(source, 'package.json'), 'utf8')) as { creator?: { version?: string } }).creator?.version; } catch { return undefined; } })();+ const index = buildCocosAssetIndex(assetsDir, cocosEditorAssets(version));const outRef = (assetRel: string): string => `assets/${into}/${assetRel}`;const esRel = (assetRel: string, ext: string): string => assetRel.replace(/\.[^./]+$/, ext);@@ -631,7 +684,10 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Impoif (usedScripts.size > 0) {// The scripts stay where they are, unchanged; this file is how the new project's bundle reaches them.const entry = path.join(out, 'src', 'cocos-scripts.ts');- const loads = [...usedScripts].sort().map((rel) => {+ // Cocos runs every script of the project when the game starts, and a game leans on that: a script that only defines globals (the game's+ // configuration, its helpers on `window`) is named by no scene, and what loads next reads them. Those run first.+ const starters = globalDefiningScripts(index).filter((rel) => !usedScripts.has(rel));+ const loads = [...starters, ...[...usedScripts].sort()].map((rel) => {const target = path.join(assetsDir, rel.replace(/\.(ts|js)$/, ''));// On another drive there is no relative path, only the absolute one, which a require takes just as well.const rel2 = path.relative(path.dirname(entry), target).split(path.sep).join('/');@@ -658,6 +714,7 @@ export async function importCocosProject(opts: CocosImportOptions): Promise<Imporeport.note('cocos-scripts-entry', `${path.relative(out, entry).split(path.sep).join('/')}: ${usedScripts.size} script(s)`);if (!opts.dryRun) wireProjectEntries(out, scriptFields);}+ if (!opts.dryRun) wireManifest(out, source, into, scenes);report.textures = textures.size;if (!opts.dryRun) {diff --git a/pipeline/tests/cocos-import-layer.test.ts b/pipeline/tests/cocos-import-layer.test.tsindex 11e0ea90b..8b2010e78 100644--- a/pipeline/tests/cocos-import-layer.test.ts+++ b/pipeline/tests/cocos-import-layer.test.ts@@ -75,6 +75,8 @@ describe('importing for the compatibility layer', () => {put('scripts/Hud.ts.meta', meta(HUD, 'typescript'));put('scripts/Other.ts', "@ccclass\n@menu('x')\n// a comment between\n@executionOrder(-1)\nexport default class Other extends Component {}\n");put('scripts/Other.ts.meta', meta(OTHER, 'typescript'));+ put('scripts/Globals.ts', "// @ts-ignore\nglobalThis.app_config = { area: 2 };\n");+ put('scripts/Globals.ts.meta', meta('99999999-9999-4999-8999-999999999999', 'typescript'));put('resources.meta', { ver: '1.2.0', importer: 'directory', uuid: 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee', userData: { isBundle: true, bundleName: 'resources' } });put('resources/cfg/rules.json', '{"a":1}');put('resources/cfg/rules.json.meta', meta('f1f1f1f1-f1f1-4f1f-8f1f-f1f1f1f1f1f1', 'json'));@@ -89,6 +91,9 @@ describe('importing for the compatibility layer', () => {put('art/plain.json.meta', meta(PLAIN, 'json'));// the starter project's entry, which the import points at the converted scriptsmkdirSync(path.join(root, 'out', 'src'), { recursive: true });+ writeFileSync(path.join(root, 'out', 'project.esproject'), JSON.stringify({ formatVersion: '1', name: 'x', defaultScene: 'assets/scenes/main.esscene', designResolution: { width: 800, height: 600 } }));+ mkdirSync(path.join(root, 'creator', 'settings', 'v2', 'packages'), { recursive: true });+ writeFileSync(path.join(root, 'creator', 'settings', 'v2', 'packages', 'project.json'), JSON.stringify({ general: { designResolution: { width: 1080, height: 1920 } } }));writeFileSync(path.join(root, 'out', 'src', 'main.ts'), "// Game entry.\nimport './components';\n");report = await importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });scenes = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8'));@@ -194,6 +199,19 @@ describe('importing for the compatibility layer', () => {expect(readFileSync(path.join(root, 'creator', 'assets', 'resources', 'ui', 'icon.png'), 'utf8')).toBe('not a png');});+ it('starts the converted project at the scene and design size of the game, not of the starter', () => {+ const manifest = JSON.parse(readFileSync(path.join(root, 'out', 'project.esproject'), 'utf8')) as { defaultScene: string; designResolution: { width: number; height: number } };+ expect(manifest.defaultScene).toBe('assets/cocos/main.esscene');+ expect(manifest.designResolution).toEqual({ width: 1080, height: 1920 });+ });++ it('runs a script that only defines globals before the scripts scenes name', () => {+ const entry = readFileSync(path.join(root, 'out', 'src', 'cocos-scripts.ts'), 'utf8').split('\n');+ const at = (needle: string): number => entry.findIndex((l) => l.startsWith('load(') && l.includes(needle));+ expect(at("scripts/Globals'")).toBeGreaterThan(-1);+ expect(at("scripts/Globals'")).toBeLessThan(at("scripts/Hud'"));+ });+it('counts the components it maps', () => {for (const type of ['cc.Widget', 'cc.Layout', 'cc.Button', 'cc.UITransform']) expect(report.components[type]!.unmapped).toBe(0);});diff --git a/pipeline/tests/cocos-internal-assets.test.ts b/pipeline/tests/cocos-internal-assets.test.tsnew file mode 100644index 000000000..d90d97ab2--- /dev/null+++ b/pipeline/tests/cocos-internal-assets.test.ts@@ -0,0 +1,73 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A scene names the editor's built-in assets (the default progress bar images) by uuid and the project does not hold them: they are+ * read from the Creator install, and come into the converted project like any image.+ */+import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { importCocosProject } from '../src/import/cocos';+import { buildCocosAssetIndex, cocosEditorAssets, INTERNAL_FOLDER } from '../src/import/cocos/assets';++const BAR = '24a704da-2867-446d-8d1a-5e920c75e09d';+const meta = (uuid: string, importer: string, subMetas: object = {}): object => ({ ver: '1', importer, uuid, subMetas, userData: {} });++describe('built-in editor assets', () => {+ let root: string;+ let editor: string;+ const saved = process.env.COCOS_EDITOR_ASSETS;++ beforeAll(async () => {+ root = mkdtempSync(path.join(tmpdir(), 'cocos-internal-'));+ editor = path.join(root, 'editor-assets');+ mkdirSync(path.join(editor, 'default_ui'), { recursive: true });+ writeFileSync(path.join(editor, 'default_ui', 'default_progressbar.png'), 'png');+ writeFileSync(path.join(editor, 'default_ui', 'default_progressbar.png.meta'), JSON.stringify(meta('bbbbbbbb-1111-4111-8111-bbbbbbbbbbbb', 'image', { f9941: { importer: 'sprite-frame', uuid: BAR, name: 'spriteFrame', userData: {} } })));+ process.env.COCOS_EDITOR_ASSETS = editor;++ const dir = path.join(root, 'creator', 'assets');+ mkdirSync(dir, { recursive: true });+ const unit = { __type__: 'cc.Vec3', x: 1, y: 1, z: 1 }, zero = { __type__: 'cc.Vec3', x: 0, y: 0, z: 0 };+ const scene = [+ { __type__: 'cc.SceneAsset', _name: 'main', scene: { __id__: 1 } },+ { __type__: 'cc.Scene', _name: 'main', _children: [{ __id__: 2 }] },+ { __type__: 'cc.Node', _name: 'Bar', _parent: { __id__: 1 }, _children: [], _active: true, _components: [{ __id__: 3 }], _prefab: null, _lpos: zero, _lrot: { __type__: 'cc.Quat', x: 0, y: 0, z: 0, w: 1 }, _lscale: unit, _layer: 1 },+ { __type__: 'cc.Sprite', node: { __id__: 2 }, _enabled: true, _color: { __type__: 'cc.Color', r: 255, g: 255, b: 255, a: 255 }, _spriteFrame: { __uuid__: `${BAR}`, __expectedType__: 'cc.SpriteFrame' }, _type: 1, _sizeMode: 0 },+ ];+ writeFileSync(path.join(dir, 'main.scene'), JSON.stringify(scene));+ writeFileSync(path.join(dir, 'main.scene.meta'), JSON.stringify(meta('dddddddd-dddd-4ddd-8ddd-dddddddddddd', 'scene')));+ writeFileSync(path.join(root, 'creator', 'package.json'), JSON.stringify({ creator: { version: '3.7.3' } }));+ await importCocosProject({ source: path.join(root, 'creator'), out: path.join(root, 'out') });+ });+ afterAll(() => {+ if (saved === undefined) delete process.env.COCOS_EDITOR_ASSETS; else process.env.COCOS_EDITOR_ASSETS = saved;+ rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ });++ it('finds the install folder, and none for a version nobody has', () => {+ expect(cocosEditorAssets('3.7.3')).toBe(editor);+ delete process.env.COCOS_EDITOR_ASSETS;+ expect(cocosEditorAssets('0.0.0-none')).toBeNull();+ process.env.COCOS_EDITOR_ASSETS = editor;+ });++ it('lets the project\'s own assets win over a built-in of the same uuid', () => {+ const own = path.join(root, 'own');+ mkdirSync(own, { recursive: true });+ writeFileSync(path.join(own, 'mine.png.meta'), JSON.stringify(meta('bbbbbbbb-1111-4111-8111-bbbbbbbbbbbb', 'image')));+ writeFileSync(path.join(own, 'mine.png'), 'png');+ const index = buildCocosAssetIndex(own, editor);+ expect(index.byUuid.get('bbbbbbbb-1111-4111-8111-bbbbbbbbbbbb')!.rel).toBe('mine.png');+ expect(index.byUuid.get(BAR)!.rel).toBe(`${INTERNAL_FOLDER}/default_ui/default_progressbar.png`);+ });++ it('brings the image in and points the sprite at it', () => {+ const scene = JSON.parse(readFileSync(path.join(root, 'out', 'assets', 'cocos', 'main.esscene'), 'utf8')) as { entities: Array<{ name: string; components: Array<{ type: string; data: Record<string, unknown> }> }> };+ const sprite = scene.entities.find((e) => e.name === 'Bar')!.components.find((c) => c.type === 'Sprite')!;+ expect(sprite.data.texture).toBe(`assets/cocos/${INTERNAL_FOLDER}/default_ui/default_progressbar.png`);+ expect(sprite.data.enabled).not.toBe(false);+ expect(existsSync(path.join(root, 'out', 'assets', 'cocos', INTERNAL_FOLDER, 'default_ui', 'default_progressbar.png'))).toBe(true);+ });+});diff --git a/sdk/src/cocos/host.ts b/sdk/src/cocos/host.tsindex 1b3dcbd76..da2c5d25e 100644--- a/sdk/src/cocos/host.ts+++ b/sdk/src/cocos/host.ts@@ -193,7 +193,9 @@ export function declareClass(ctor: ComponentCtor, name: string, raw: RawPropertyconst previous = setCurrentWorld(world);try {const seen = new Set<Entity>();- for (const [entity] of q) {+ // The entities first, then the scripts: a script that switches a node on or off adds and removes components, which a query being+ // 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);@@ -218,7 +220,7 @@ export function declareClass(ctor: ComponentCtor, name: string, raw: RawProperty(q, time, world) => {const previous = setCurrentWorld(world);try {- for (const [entity] of q) {+ for (const [entity] of [...q]) {const inst = instancesOn(world, entity)?.get(ctor);if (inst && inst._started && inst.enabled && world.isEntityActive(entity)) call(inst, 'lateUpdate', time.delta);}diff --git a/sdk/src/cocos/index.ts b/sdk/src/cocos/index.tsindex ca0a04f68..6ea35f459 100644--- a/sdk/src/cocos/index.ts+++ b/sdk/src/cocos/index.ts@@ -48,5 +48,7 @@ export * from './env';export { classInfoNamed, classInfoOf, allClassInfos, COMPONENT_PREFIX, resetClassRegistry } from './registry';import { declareBuiltinScripts as declare } from './builtinScripts';-// Declared once, into the context a game runs in, when the layer is imported.-declare();+import { declareAsEngineComponents } from '../ecs/component';+// Declared once, into the context a game runs in, when the layer is imported. They are the engine's components as far as a reload goes: the layer+// does not load again, so what it declared has to be put back with the rest of them.+declareAsEngineComponents(declare);diff --git a/sdk/src/ecs/component.ts b/sdk/src/ecs/component.tsindex 00e03d3af..e5d689863 100644--- a/sdk/src/ecs/component.ts+++ b/sdk/src/ecs/component.ts@@ -493,6 +493,19 @@ export function markEngineComponentBaseline(): void {engineComponentBaseline_ = new Map(userComponents());}+/**+ * Run @p declare, and count what it registers among the engine's own components. A part of the engine that lives in its own module (the Cocos+ * layer) registers components when it loads, after the entry took its baseline; without this a reload that clears the registry would drop them,+ * the module being cached and not loading again. Components the project declares are never added: they come from the project bundle, which a+ * reload does run again. No-op where no baseline was taken (a test that never loaded the SDK entry).+ */+export function declareAsEngineComponents(declare: () => void): void {+ const before = new Set(userComponents().keys());+ declare();+ if (!engineComponentBaseline_) return;+ for (const [name, def] of userComponents()) if (!before.has(name)) engineComponentBaseline_.set(name, def);+}+/** Re-add the engine baseline to a registry (only where missing), so a context* that has never re-run the SDK's module-level registrations still has them.* No-op until {@link markEngineComponentBaseline} has run (e.g. unit tests thatdiff --git a/sdk/tests/cocos/script-active-wasm.test.ts b/sdk/tests/cocos/script-active-wasm.test.tsnew file mode 100644index 000000000..46ee8c8a9--- /dev/null+++ b/sdk/tests/cocos/script-active-wasm.test.ts@@ -0,0 +1,76 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A script may switch nodes on and off from `start`, which the host runs for every script in one pass: the pass must not be a query+ * being walked, because switching a node off adds and removes components, which a walked query refuses.+ */+import { afterEach, beforeAll, describe, expect, it } from 'vitest';+import type { ESEngineModule } from '../../src/wasm';+import { App, flushPendingRegistrations } from '../../src/app/app';+import { ensureBuiltinComponentsRegistered } from '../../src/ecs/component';+import { AppContext, setDefaultContext } from '../../src/ecs/context';+import { loadSceneData, SCENE_FORMAT_VERSION } from '../../src/scene/scene';+import type { SceneData } from '../../src/scene/scene';+import { resetClassRegistry } from '../../src/cocos/registry';+import { declareBuiltinScripts } from '../../src/cocos/builtinScripts';+import { Component, Node, _decorator, setCurrentWorld } from '../../src/cocos';+import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';++const transform = { type: 'Transform', data: { position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 } } };++describe.skipIf(!HAS_WASM)('a script that switches nodes on and off', () => {+ 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;+ });++ it('can switch another node on in start, and the scripts that node carries still start', async () => {+ setDefaultContext(new AppContext());+ ensureBuiltinComponentsRegistered();+ resetClassRegistry();+ declareBuiltinScripts();+ const started: string[] = [];++ @_decorator.ccclass('Switcher')+ class Switcher extends Component {+ @_decorator.property(Node) other: Node | null = null;+ start() {+ started.push('switcher');+ this.other!.active = true; // takes the Disabled tag off, which a walked query refuses+ this.node.active = false;+ }+ }+ @_decorator.ccclass('Bystander')+ class Bystander extends Component {+ start() { started.push('bystander'); }+ }+ void Switcher; void Bystander;++ registry = new module.Registry();+ app = App.new();+ app.connectCpp(registry as never, module);+ flushPendingRegistrations(app);+ setCurrentWorld(app.world);+ const map = loadSceneData(app.world, {+ version: SCENE_FORMAT_VERSION, name: 'main',+ entities: [+ { id: 0, name: 'A', parent: null, children: [], visible: true, components: [transform, { type: 'Cocos.Switcher', data: { enabled: true, other: 1 } }] },+ { id: 1, name: 'B', parent: null, children: [], visible: true, components: [transform, { type: 'Disabled', data: {} }, { type: 'Cocos.Bystander', data: { enabled: true } }] },+ ],+ } as unknown as SceneData);+ for (let i = 0; i < 3; i++) await app.tick(1 / 60);++ expect(started).toContain('switcher');+ expect(Node.for(app.world, map.get(0)!).active).toBe(false);+ expect(Node.for(app.world, map.get(1)!).active).toBe(true);+ expect(started).toContain('bystander');+ });+});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex e6cf6d0d1..9e946494c 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(cocos): a converted project starts at the game launch scene and runs its global-defining scripts first, reads the editor built-in assets, and the layer components survive a replay':+ {"note":"A converted Cocos project starts as the game does."},'feat(cocos): the colour a script sets on a material instance is the renderer tint':{"note":"A material colour is the renderer tint."},'feat(cocos): MeshRenderer, UIMeshRenderer, material properties and cc.geometry in the compatibility layer':