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(assets): a package carries the assets its scripts name, and says which file it lacks
yhh96bd8c29dd1b
diff --git a/desktop b/desktopindex 01a2c6bbb..1810b2429 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 01a2c6bbb12f80f7c1abf6250b8c985ee717d968+Subproject commit 1810b2429495075ef362039a72f0a1979e07686adiff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.tsindex 5c0ff4986..edd0a6780 100644--- a/pipeline/src/assets/cookAssets.ts+++ b/pipeline/src/assets/cookAssets.ts@@ -52,6 +52,9 @@ import { cookCached } from './cookCache';import { cookTexture, loadTextureEncoder, pngDimensions, COMPRESSED_TARGETS, type BasisEncoderModule } from './textureCook';import { meshTextureRoles } from './textureUsage';import { makeStreamTail, type StreamTail } from './streamTail';+import { matchScriptAssetRefs, scanScriptAssetRefs } from './scriptAssetRefs';+import { readManifest } from '../project/readProject';+import { resolveScripts } from '../project/format';const MANIFEST = 'assets.manifest.json';@@ -142,7 +145,9 @@ export type InclusionReason =/** A locale table — loaded by code, so reachability would cull it. */| 'locale'/** A data asset (`.json`), named by the code that loads it. */- | 'data';+ | 'data'+ /** Named by a string literal in the project's scripts (`via` holds it). */+ | 'script';/** How one asset got in: the reason, and for a dependency the asset that named it. */export interface Inclusion {@@ -476,6 +481,17 @@ function shaderTwinDeriver(): Promise<((source: string) => Promise<string>) | nu* Cook assets reachable from `entryScenes` (project-relative scene paths) into* `outDir` (project-relative or absolute). Returns what was included vs culled.*/+/** The folder the project's startup script lives in — every export target cooks+ * from here, so each one ships what the scripts name without being told. */+async function projectScriptDirs(root: string): Promise<string[]> {+ try {+ const main = resolveScripts(await readManifest(root)).main;+ return main ? [path.posix.dirname(main.split(path.sep).join('/').split('\\').join('/'))] : [];+ } catch {+ return [];+ }+}+export async function cookAssets(root: string,opts: {@@ -496,6 +512,10 @@ export async function cookAssets(/** Stage a small copy of each texture a mesh draws as its surface (streamTail.ts), for texture streaming to fetch first.* Worth it where files are fetched as they are needed (the web); a package downloaded whole only grows. */streamTails?: boolean;+ /** Project-relative folders holding the game's scripts: an asset a literal there+ * names ships even when no scene references it (scriptAssetRefs.ts). Absent:+ * the folder of the project's startup script; `[]` scans nothing. */+ scriptDirs?: string[];},): Promise<CookResult> {const contentAddressed = opts.contentAddressed ?? false;@@ -570,6 +590,22 @@ export async function cookAssets(for (const e of shippable) {if (e.type === 'json') seed(e.uuid, { reason: 'data' });}+ // …and what the scripts name: a path only code holds never reaches a scene,+ // and culling it is a build that works in the editor and 404s on a device.+ const scriptDirs = opts.scriptDirs ?? await projectScriptDirs(root);+ if (scriptDirs.length > 0) {+ const named = matchScriptAssetRefs(await scanScriptAssetRefs(root, scriptDirs), shippable);+ const byFolder = new Map<string, number>();+ for (const { uuid, via } of named) {+ if (reachable.has(uuid)) continue;+ seed(uuid, { reason: 'script', via });+ if (via.endsWith('/')) byFolder.set(via, (byFolder.get(via) ?? 0) + 1);+ }+ for (const [folder, n] of byFolder) {+ warnings.push(`scripts build paths under "${folder}" at run time, so all ${n} asset(s) there ship; `+ + 'name the files whole, or list them as alwaysInclude, to ship only what is used');+ }+ }// …then take the transitive closure over the dependency graph.while (queue.length > 0) {const uuid = queue.shift()!;diff --git a/pipeline/src/assets/scriptAssetRefs.ts b/pipeline/src/assets/scriptAssetRefs.tsnew file mode 100644index 000000000..7dedf61f0--- /dev/null+++ b/pipeline/src/assets/scriptAssetRefs.ts@@ -0,0 +1,95 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file scriptAssetRefs.ts+ * @brief The assets a project's scripts name, so a package carries them.+ *+ * Reachability starts at the scenes, and a scene cannot reference what only code+ * names: `assets.loadTexture('assets/ui/coin.png')`, an `insert(Sprite, { texture: … })`+ * at run time. Culled, such an asset works in the editor, which serves the whole+ * project, and 404s only on a device. The scripts are read here for the string+ * literals they hold, the way a bundler finds a static `import()`:+ *+ * - a literal that IS a shippable asset's path (or an `@uuid:` ref) ships it;+ * - a template literal with a static head ending in `/`+ * (`` `assets/sfx/${name}.wav` ``) ships the folder it names, the way a+ * bundler's context module does — and says so, since a folder is a guess at+ * which of its files the code will ask for.+ *+ * Text, not a parse: a path in a comment ships too, which costs a file; a path+ * the scan missed costs a broken build. Anything else — a path assembled from+ * pieces, a name from data — still needs `alwaysInclude` in asset-groups.json.+ */+import { readdir, readFile } from 'node:fs/promises';+import path from 'node:path';++const SCRIPT_EXT = /\.(ts|tsx|mts|cts|js|mjs|cjs|jsx)$/i;+const SKIP_DIRS = new Set(['node_modules', 'dist', 'build']);+/** Quoted strings and template heads; deliberately loose (see the file comment). */+const LITERAL = /'([^'\\\n]{3,})'|"([^"\\\n]{3,})"|`([^`\\$]*)(\$\{)?/g;+const UUID_REF = /^@uuid:([0-9a-f-]{36})$/i;++export interface ScriptAssetRefs {+ /** Whole literals, normalised as project-relative paths. */+ readonly literals: ReadonlySet<string>;+ /** Static heads of template literals that stop at a folder (`assets/sfx/`). */+ readonly folders: ReadonlySet<string>;+}++const normalise = (s: string): string => s.trim().replace(/\\/g, '/').replace(/^\.?\//, '');++/** Every script under @p dirs (project-relative), read for the literals it holds. */+export async function scanScriptAssetRefs(root: string, dirs: readonly string[]): Promise<ScriptAssetRefs> {+ const literals = new Set<string>();+ const folders = new Set<string>();+ const walk = async (abs: string): Promise<void> => {+ let entries;+ try { entries = await readdir(abs, { withFileTypes: true }); } catch { return; }+ for (const e of entries) {+ if (e.name.startsWith('.') || SKIP_DIRS.has(e.name)) continue;+ const child = path.join(abs, e.name);+ if (e.isDirectory()) { await walk(child); continue; }+ if (!SCRIPT_EXT.test(e.name) || e.name.endsWith('.d.ts')) continue;+ const text = await readFile(child, 'utf8').catch(() => '');+ for (const m of text.matchAll(LITERAL)) {+ const whole = m[1] ?? m[2];+ if (whole !== undefined) { literals.add(normalise(whole)); continue; }+ const head = m[3] ?? '';+ if (m[4] === undefined) literals.add(normalise(head));+ else if (head.endsWith('/') && head.length > 1) folders.add(normalise(head));+ }+ }+ };+ for (const dir of dirs) await walk(path.join(root, dir));+ return { literals, folders };+}++/** Why one asset ships because of the scripts: the literal that named it. */+export interface ScriptMatch {+ uuid: string;+ /** The literal (a path, a ref, or a folder head ending in `/`). */+ via: string;+}++/** The shippable assets @p refs name, each once, with what named it. */+export function matchScriptAssetRefs(+ refs: ScriptAssetRefs,+ shippable: ReadonlyArray<{ uuid: string; path: string }>,+): ScriptMatch[] {+ const out = new Map<string, ScriptMatch>();+ const byUuid = new Map(shippable.map((e) => [e.uuid.toLowerCase(), e]));+ for (const lit of refs.literals) {+ const ref = UUID_REF.exec(lit);+ const hit = ref ? byUuid.get(ref[1].toLowerCase()) : undefined;+ if (hit) out.set(hit.uuid, { uuid: hit.uuid, via: lit });+ }+ for (const e of shippable) {+ if (out.has(e.uuid)) continue;+ const p = normalise(e.path);+ if (refs.literals.has(p)) { out.set(e.uuid, { uuid: e.uuid, via: p }); continue; }+ for (const folder of refs.folders) {+ if (p.startsWith(folder)) { out.set(e.uuid, { uuid: e.uuid, via: folder }); break; }+ }+ }+ return [...out.values()];+}diff --git a/pipeline/tests/script-asset-refs.test.ts b/pipeline/tests/script-asset-refs.test.tsnew file mode 100644index 000000000..1e50c592c--- /dev/null+++ b/pipeline/tests/script-asset-refs.test.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * What a project's scripts name ships, though no scene references it: a whole+ * path or an @uuid ref in a literal, and the folder a template literal builds+ * paths under. Culled, such an asset works in the editor and 404s on a device.+ */+import { describe, it, expect, beforeAll, afterAll } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { cookAssets } from '../src/assets/cookAssets';+import { matchScriptAssetRefs, scanScriptAssetRefs } from '../src/assets/scriptAssetRefs';++let root: string;+const SCENE = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+const COIN = '11111111-1111-4111-8111-111111111111';+const BY_REF = '22222222-2222-4222-8222-222222222222';+const SFX_A = '33333333-3333-4333-8333-333333333333';+const SFX_B = '44444444-4444-4444-8444-444444444444';+const UNUSED = '55555555-5555-4555-8555-555555555555';++function writeAsset(rel: string, type: string, uuid: string, body = 'x'): void {+ const abs = path.join(root, rel);+ mkdirSync(path.dirname(abs), { recursive: true });+ writeFileSync(abs, body);+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));+}++beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-script-refs-'));+ writeFileSync(path.join(root, 'project.esproject'), JSON.stringify({ name: 'p', version: '1.0', scripts: { main: 'src/main.ts' } }));+ writeAsset('assets/scenes/main.esscene', 'scene', SCENE, JSON.stringify({ version: '1.0', name: 'm', entities: [] }));+ writeAsset('assets/ui/coin.png', 'texture', COIN);+ writeAsset('assets/ui/other.png', 'texture', BY_REF);+ writeAsset('assets/sfx/jump.wav', 'audio', SFX_A);+ writeAsset('assets/sfx/land.wav', 'audio', SFX_B);+ writeAsset('assets/ui/unused.png', 'texture', UNUSED);+ mkdirSync(path.join(root, 'src', 'game'), { recursive: true });+ writeFileSync(path.join(root, 'src', 'main.ts'), `import './game/hud';\nexport const coin = './assets/ui/coin.png';\n`);+ writeFileSync(path.join(root, 'src', 'game', 'hud.ts'),+ `const ref = "@uuid:${BY_REF}";\nexport const sfx = (name: string) => \`assets/sfx/\${name}.wav\`;\n`);+});++afterAll(() => { if (root) rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); });++describe('assets the scripts name', () => {+ it('matches whole paths, @uuid refs and template folders', async () => {+ const refs = await scanScriptAssetRefs(root, ['src']);+ const matched = matchScriptAssetRefs(refs, [+ { uuid: COIN, path: 'assets/ui/coin.png' }, { uuid: BY_REF, path: 'assets/ui/other.png' },+ { uuid: SFX_A, path: 'assets/sfx/jump.wav' }, { uuid: UNUSED, path: 'assets/ui/unused.png' },+ ]);+ expect(Object.fromEntries(matched.map((m) => [m.uuid, m.via]))).toEqual({+ [COIN]: 'assets/ui/coin.png', [BY_REF]: `@uuid:${BY_REF}`, [SFX_A]: 'assets/sfx/',+ });+ });++ it('ships them from the project startup folder, says so for a folder, and still culls the rest', async () => {+ const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });+ expect(res.ok).toBe(true);+ expect(res.included.sort()).toEqual([SCENE, COIN, BY_REF, SFX_A, SFX_B].sort());+ expect(res.inclusion['assets/ui/coin.png']).toEqual({ reason: 'script', via: 'assets/ui/coin.png' });+ expect(res.unused).toContain(UNUSED);+ expect(res.warnings.some((w) => w.includes('assets/sfx/') && w.includes('2 asset'))).toBe(true);+ });+});diff --git a/sdk/src/asset/AddressableManifest.ts b/sdk/src/asset/AddressableManifest.tsindex be7ddd1fe..8702f63f5 100644--- a/sdk/src/asset/AddressableManifest.ts+++ b/sdk/src/asset/AddressableManifest.ts@@ -4,6 +4,22 @@ import type { AddressableAssetType } from '../assetTypes';import { indexTextureImportSettings, type ParsedTextureImportSettings } from './textureImportSettings';import type { SpineCullingRect, SpineManifestContract } from './spineImportSettings';import { contentHashOf } from './contentHash';+import { log } from '../util/logger';++const warnedNotPackaged = new Set<string>();++/**+ * A project file the package does not carry, said once and with the reason —+ * otherwise the first anyone hears of it is a 404 from the loader. Only refs+ * that look like files: `builtin:` meshes, URLs and blobs are not the cook's.+ */+function warnNotPackaged(ref: string): void {+ if (warnedNotPackaged.has(ref) || ref.includes(':') || !/\.[a-z0-9]{2,8}$/i.test(ref)) return;+ warnedNotPackaged.add(ref);+ log.warn('asset', `"${ref}" is not in this package. A build ships what its scenes reference, what the `+ + 'scripts name as a whole path in a string literal, and the folders asset-groups.json marks '+ + 'alwaysInclude — name the file whole in code, or mark its folder alwaysInclude.');+}export type { AddressableAssetType };@@ -409,6 +425,7 @@ export class ManifestModel {resolvePath(ref: string): string {const { byKey, byPath } = this.indexes();const entry = byKey.get(ref) ?? byPath.get(ref);+ if (!entry) warnNotPackaged(ref);return entry ? entry.path : ref;}}diff --git a/sdk/tests/manifest-model.test.ts b/sdk/tests/manifest-model.test.tsindex b6a1b53ba..0e16b0c10 100644--- a/sdk/tests/manifest-model.test.ts+++ b/sdk/tests/manifest-model.test.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';import {ManifestModel,normalizeBundleMode,@@ -139,6 +139,20 @@ describe('ManifestModel resolution', () => {// A build path is the name the cook staged the file under. A ref nothing// knows comes back spelled exactly as it was asked for, so the read that// fails names the file the caller actually wanted.+ it('resolvePath: a project file the package lacks is named once, with what ships', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);+ const m = model();+ m.resolvePath('assets/ui/never-packaged.png');+ m.resolvePath('assets/ui/never-packaged.png');+ m.resolvePath('builtin:cube');+ m.resolvePath('images/a.abc123.png'); // a build path: a hit, not a miss+ const said = warn.mock.calls.map((c) => c.join(' ')).filter((t) => t.includes('not in this package'));+ warn.mockRestore();+ expect(said).toHaveLength(1);+ expect(said[0]).toContain('never-packaged.png');+ expect(said[0]).toContain('alwaysInclude');+ });+it('resolvePath: miss returns the ref verbatim', () => {expect(model().resolvePath('assets/hero.esprefab')).toBe('assets/hero.esprefab');});