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.

perf(assets): a scan keeps what each document refers to by what the file was, so a second scan of a large project reads nothing it has read; fix(cocos): a component is found by its cc. name and can be named by a script

yhh01932c0b39e3
diff --git a/pipeline/src/assets/assetDb.ts b/pipeline/src/assets/assetDb.ts
index c36430dd6..117aac31d 100644
--- a/pipeline/src/assets/assetDb.ts
+++ b/pipeline/src/assets/assetDb.ts
@@ -16,7 +16,7 @@
* main.ts. The `.meta` files carry the authored `type`, so this needs no
* extension→type table — it reads the type each meta already declares.
*/
-import { readFile, writeFile, mkdir, readdir, stat } from 'node:fs/promises';
+import { readFile, writeFile, mkdir, readdir, stat, rename } from 'node:fs/promises';
import type { Dirent } from 'node:fs';
import { existsSync } from 'node:fs';
import { randomUUID } from 'node:crypto';
@@ -281,6 +281,44 @@ function collectRefs(
}
}
+/**
+ * What a document can refer to by name, before any of it is resolved: its `@uuid:` strings, its bare uuids and the strings that could be file paths.
+ * This is what reading and parsing a document finds; which of them are assets is a question of the rest of the project, asked again on every scan.
+ */
+function collectCandidates(value: unknown, into: Set<string>): void {
+ if (typeof value === 'string') {
+ if (value.startsWith(UUID_PREFIX) || UUID_V4.test(value) || (!value.includes('://') && PATH_LIKE.test(value))) into.add(value);
+ return;
+ }
+ if (Array.isArray(value)) {
+ for (const v of value) collectCandidates(v, into);
+ return;
+ }
+ if (value && typeof value === 'object') for (const v of Object.values(value as Record<string, unknown>)) collectCandidates(v, into);
+}
+
+/** The candidates of each document by what the file was when they were read: a document that is the same size and was changed at the same time is not read again. */
+interface CandidateCache { version: 1; files: Record<string, { size: number; mtimeMs: number; c: string[] }> }
+const CANDIDATE_CACHE_FILE = path.join('.esengine', 'cache', 'ref-candidates.json');
+
+async function readCandidateCache(root: string): Promise<CandidateCache> {
+ try {
+ const parsed = JSON.parse(await readFile(path.join(root, CANDIDATE_CACHE_FILE), 'utf8')) as CandidateCache;
+ if (parsed.version === 1 && parsed.files) return parsed;
+ } catch { /* none yet, or one that cannot be read: the documents are read */ }
+ return { version: 1, files: {} };
+}
+
+async function writeCandidateCache(root: string, cache: CandidateCache): Promise<void> {
+ try {
+ const file = path.join(root, CANDIDATE_CACHE_FILE);
+ await mkdir(path.dirname(file), { recursive: true });
+ const tmp = `${file}.${process.pid}.tmp`;
+ await writeFile(tmp, JSON.stringify(cache), 'utf8');
+ await rename(tmp, file);
+ } catch { /* a cache that cannot be written costs the next scan its reads */ }
+}
+
/**
* Whether a string could name a file: it ends in an extension, written in one case. Almost every string in a document is a name, a type or
* a label (`Transform`, `Cocos.Widget`, `ui_layer`), and each one asked of the path index costs a normalisation and a lookup; in a project of
@@ -340,6 +378,21 @@ async function computeDeps(
|| SKELETAL_ATLAS_TYPES.has(getEditorType(e.path)),
);
type DepResult = { uuid: string; refs: string[] } | { warning: string };
+ const cache = await readCandidateCache(root);
+ let cacheDirty = false;
+ const seenFiles = new Set<string>();
+ const candidatesOf = async (rel: string): Promise<string[]> => {
+ seenFiles.add(rel);
+ const file = path.join(root, rel);
+ const info = await stat(file);
+ const hit = cache.files[rel];
+ if (hit && hit.size === info.size && hit.mtimeMs === info.mtimeMs) return hit.c;
+ const found = new Set<string>();
+ collectCandidates(JSON.parse(await readTextInRoot(file)), found);
+ cache.files[rel] = { size: info.size, mtimeMs: info.mtimeMs, c: [...found] };
+ cacheDirty = true;
+ return cache.files[rel]!.c;
+ };
const depResults = await mapLimit(refEntries, SCAN_IO_CONCURRENCY, async (entry): Promise<DepResult> => {
// A spine `.atlas` is a TEXT manifest (not JSON): its page image names are
// texture deps — the same edge the SpineAssetLoader walks at runtime. Scan it
@@ -364,8 +417,8 @@ async function computeDeps(
if (dep) refs.add(dep.uuid);
}
} else {
- const json = JSON.parse(await readTextInRoot(path.join(root, entry.path)));
- collectRefs(json, refs, (ref) => {
+ const candidates = await candidatesOf(entry.path);
+ const resolvePath = (ref: string): string | null => {
if (ref.includes('://') || !PATH_LIKE.test(ref)) return null;
const direct = byPath.get(normalizeRefPath(ref));
if (direct) return direct.uuid;
@@ -377,7 +430,8 @@ async function computeDeps(
// single-file playable 404'd them.)
const rel = byPath.get(normalizeRefPath(resolveRelativePath(entry.path, ref)));
return rel?.uuid ?? null;
- }, (id) => uuids.has(id));
+ };
+ for (const candidate of candidates) collectRefs(candidate, refs, resolvePath, (id) => uuids.has(id));
}
refs.delete(entry.uuid);
return { uuid: entry.uuid, refs: [...refs].sort() };
@@ -385,6 +439,9 @@ async function computeDeps(
return { warning: `${entry.path}: ${err instanceof Error ? err.message : String(err)}` };
}
});
+ // A full scan forgets the documents that are gone; one of some documents only (`targets`) leaves the rest as they are.
+ if (!targets) for (const rel of Object.keys(cache.files)) if (!seenFiles.has(rel)) { delete cache.files[rel]; cacheDirty = true; }
+ if (cacheDirty) await writeCandidateCache(root, cache);
const deps: Record<string, string[]> = {};
const warnings: string[] = [];
for (const r of depResults) {
diff --git a/pipeline/tests/asset-db.test.ts b/pipeline/tests/asset-db.test.ts
index ecc5c8c2a..697d1d500 100644
--- a/pipeline/tests/asset-db.test.ts
+++ b/pipeline/tests/asset-db.test.ts
@@ -217,3 +217,22 @@ describe('two files that claim the same uuid', () => {
}
});
});
+
+describe('the references of a document, read once', () => {
+ it('are kept by what the file was, so a second scan reads nothing it has read, and still sees a path that came into being since', async () => {
+ const first = await scanAssetDatabase(root, { write: false });
+ expect(existsSync(path.join(root, '.esengine', 'cache', 'ref-candidates.json'))).toBe(true);
+ const again = await scanAssetDatabase(root, { write: false });
+ expect(again.index.deps).toEqual(first.index.deps);
+
+ // a document names a file by path; the file is added AFTER the document was read: its edge appears without the document being read again
+ const SHEET = '55555555-5555-4555-8555-555555555555';
+ const HOLDER = '66666666-6666-4666-8666-666666666666';
+ writeAsset('assets/materials/holder.esmaterial', 'material', HOLDER, JSON.stringify({ shader: 'builtin:sprite', properties: { u_mask: 'assets/textures/late.png' } }));
+ const before = await scanAssetDatabase(root, { write: false });
+ expect(before.index.deps[HOLDER] ?? []).toEqual([]);
+ writeAsset('assets/textures/late.png', 'texture', SHEET, 'LATE');
+ const after = await scanAssetDatabase(root, { write: false });
+ expect(after.index.deps[HOLDER]).toEqual([SHEET]);
+ });
+});
diff --git a/sdk/src/cocos/component.ts b/sdk/src/cocos/component.ts
index bb9212954..10470e384 100644
--- a/sdk/src/cocos/component.ts
+++ b/sdk/src/cocos/component.ts
@@ -61,7 +61,10 @@ export class Component {
/** See {@link Node.toJSON}: a component holds the world too. */
toJSON(): { component: string; entity: number } { return { component: this.constructor.name, entity: this._entity }; }
[Symbol.for('nodejs.util.inspect.custom')](): string { return `${this.constructor.name}(#${this._entity})`; }
- get name(): string { return `${this.node?.name ?? ''}<${this.constructor.name}>`; }
+ /** A script that names its component (`comp.name = 'UILogin'`) is believed; otherwise it is the node's name and the class. */
+ get name(): string { return this.name_ ?? `${this.node?.name ?? ''}<${this.constructor.name}>`; }
+ set name(value: string) { this.name_ = value; }
+ private name_: string | undefined;
/** False once the component or its entity has gone. */
get isValid(): boolean { return !this._destroyed && !!this._world?.valid(this._entity); }
diff --git a/sdk/src/cocos/node.ts b/sdk/src/cocos/node.ts
index 643670d20..00a52c337 100644
--- a/sdk/src/cocos/node.ts
+++ b/sdk/src/cocos/node.ts
@@ -350,7 +350,8 @@ export class Node {
}
private resolveCtor_(type: ComponentCtor | string): ComponentCtor | undefined {
- if (typeof type === 'string') return classInfoNamed(type)?.ctor;
+ // A scene and a script say `'cc.Button'`; the layer declares the class as `Button`.
+ if (typeof type === 'string') return (classInfoNamed(type) ?? classInfoNamed(type.replace(/^cc\./, '')))?.ctor;
return type;
}
diff --git a/sdk/tests/cocos/node-wasm.test.ts b/sdk/tests/cocos/node-wasm.test.ts
index db83d8ca5..6f788011d 100644
--- a/sdk/tests/cocos/node-wasm.test.ts
+++ b/sdk/tests/cocos/node-wasm.test.ts
@@ -13,7 +13,7 @@ import type { ESEngineModule } from '../../src/wasm';
import { World } from '../../src/ecs/world';
import { Transform, ensureBuiltinComponentsRegistered } from '../../src/ecs/component';
import { AppContext, setDefaultContext } from '../../src/ecs/context';
-import { Node, Quat, Vec3, director, find, setCurrentWorld } from '../../src/cocos';
+import { Button, Node, Quat, Vec3, director, find, setCurrentWorld } from '../../src/cocos';
import { HAS_WASM, loadWasmModule } from '../helpers/loadWasm';
describe.skipIf(!HAS_WASM)('Node on the engine', () => {
@@ -79,6 +79,24 @@ describe.skipIf(!HAS_WASM)('Node on the engine', () => {
expect(names(canvas.children)).toEqual(['Extra', 'Panel', 'Label']);
});
+ it('finds a layer component by the name a scene and a script give it, `cc.Button`, as well as `Button`', () => {
+ connect();
+ const { panel } = tree();
+ const button = panel.addComponent(Button)!;
+ expect(panel.getComponent('Button')).toBe(button);
+ expect(panel.getComponent('cc.Button')).toBe(button);
+ expect(panel.getComponent('cc.NoSuchThing')).toBeNull();
+ });
+
+ it('lets a script name its component', () => {
+ connect();
+ const { panel } = tree();
+ const button = panel.addComponent(Button)!;
+ expect(button.name).toBe('Panel<Button>');
+ button.name = 'MyButton';
+ expect(button.name).toBe('MyButton');
+ });
+
it('detaches with removeFromParent, and moves with setParent', () => {
connect();
const { canvas, panel, button, label } = tree();