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(asset): WeChat subpackages via folder convention, end-to-end (T1)

yhh82d1af6fbca3
diff --git a/desktop/electron/cookAssets.ts b/desktop/electron/cookAssets.ts
index 2892c3516..446dfaa07 100644
--- a/desktop/electron/cookAssets.ts
+++ b/desktop/electron/cookAssets.ts
@@ -40,6 +40,26 @@ export interface CookManifestEntry extends AssetEntry {
size: number;
/** GPU formats the staged KTX2 can transcode to, when the asset was compressed. */
compressedFormats?: string[];
+ /**
+ * Addressable group this asset belongs to. `'main'` ships in the main package
+ * (loaded eagerly); any other name is a lazy subpackage (folder convention:
+ * `subpackages/<name>/…` → group `<name>`), loaded on demand. The runtime
+ * AssetRegistry ignores this field; the AddressableManifest + WeChat subpackage
+ * layout read it.
+ */
+ group: string;
+}
+
+/**
+ * Folder-convention subpackage detection: an asset under `subpackages/<name>/…`
+ * belongs to lazy group `<name>`. Returns null for main-package assets. The
+ * single source of truth for the grouping — cook (here), export layout, and the
+ * manifest all derive from it.
+ */
+const SUBPACKAGE_RE = /^subpackages\/([^/]+)\//;
+export function subpackageOf(projectRelPath: string): string | null {
+ const m = SUBPACKAGE_RE.exec(projectRelPath.replace(/\\/g, '/'));
+ return m ? m[1] : null;
}
/** Targets the UASTC KTX2 the cook emits can transcode to at runtime. */
@@ -96,6 +116,13 @@ export async function cookAssets(
}
seed(entry.uuid);
}
+ // Force-include lazy-subpackage assets: they're loaded on demand, so the entry
+ // scene never references them — but they (and their deps) must still ship. A
+ // shared dep that lives outside subpackages/ resolves to group 'main' below, so
+ // it lands in the always-present main package, not duplicated per subpackage.
+ for (const e of index.entries) {
+ if (subpackageOf(e.path)) seed(e.uuid);
+ }
// …then take the transitive closure over the dependency graph.
while (queue.length > 0) {
const uuid = queue.shift()!;
@@ -141,8 +168,13 @@ export async function cookAssets(
// — content changes yield a new name, so it is permanently cacheable. Scenes
// keep their logical path: they're loaded by name and the exporters read +
// transform them in place. Refs are by uuid, so renaming leaves is transparent.
+ // Group by folder convention. Lazy-subpackage assets must stay under their
+ // subpackage root (subpackages/<name>/…) so the root maps to a WeChat
+ // subPackage — including the content-addressed layout (root/assets/<hash>).
+ const group = subpackageOf(entry.path) ?? 'main';
const useCA = contentAddressed && entry.type !== 'scene';
- const outRel = useCA ? `assets/${hash}${ext}` : swapExt(entry.path, ext);
+ const caBase = group === 'main' ? 'assets' : `subpackages/${group}/assets`;
+ const outRel = useCA ? `${caBase}/${hash}${ext}` : swapExt(entry.path, ext);
const dst = path.join(absOut, outRel);
if (!staged.has(outRel)) {
await mkdir(path.dirname(dst), { recursive: true });
@@ -156,6 +188,7 @@ export async function cookAssets(
importer: entry.importer,
contentHash: hash,
size: data.byteLength,
+ group,
...(compressedFormats ? { compressedFormats } : {}),
});
} catch (err) {
diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.ts
index 4dc090d30..617b8964a 100644
--- a/desktop/electron/exportWeChat.ts
+++ b/desktop/electron/exportWeChat.ts
@@ -43,7 +43,7 @@ export interface ExportWeChatResult {
}
interface CookManifest {
- entries: { uuid: string; path: string; type: string; contentHash?: string; size?: number }[];
+ entries: { uuid: string; path: string; type: string; contentHash?: string; size?: number; group?: string }[];
}
// Editor asset type → AddressableAssetType (sdk/src/assetTypes.ts). The WeChat
@@ -71,8 +71,22 @@ function stripUuidRefs(v: unknown): unknown {
return v;
}
-function gameJson(orientation: 'portrait' | 'landscape'): string {
- return JSON.stringify({ deviceOrientation: orientation, showStatusBar: false }, null, 2) + '\n';
+function gameJson(
+ orientation: 'portrait' | 'landscape',
+ subPackages: ReadonlyArray<{ name: string; root: string }>,
+): string {
+ const cfg: Record<string, unknown> = { deviceOrientation: orientation, showStatusBar: false };
+ // WeChat 分包: each lazy group is a subpackage rooted at subpackages/<name>/.
+ // The game calls Assets.loadGroup(name) → wx.loadSubpackage at runtime.
+ if (subPackages.length > 0) cfg.subPackages = subPackages.map((s) => ({ name: s.name, root: s.root }));
+ return JSON.stringify(cfg, null, 2) + '\n';
+}
+
+/** Distinct lazy subpackage groups present in the cook, as WeChat subPackage roots. */
+function subPackagesOf(entries: CookManifest['entries']): Array<{ name: string; root: string }> {
+ const names = new Set<string>();
+ for (const e of entries) if (e.group && e.group !== 'main') names.add(e.group);
+ return [...names].map((name) => ({ name, root: `subpackages/${name}` }));
}
function projectConfigJson(title: string, appid: string): string {
@@ -142,15 +156,26 @@ async function scanWeChatSideModules(
async function buildAddressableManifest(absOut: string): Promise<string> {
const cook = JSON.parse(await readFile(path.join(absOut, 'assets.manifest.json'), 'utf8')) as CookManifest;
type Entry = { path: string; type: string; size: number; labels: string[]; contentHash?: string };
- const assets: Record<string, Entry> = {};
+ type Group = { bundleMode: string; labels: string[]; assets: Record<string, Entry> };
+ // One group per cook group: 'main' is local (eager); every other is a lazy
+ // subpackage. bundleMode here is the typed wire value the SDK's normalizeBundleMode
+ // reads ('local' | 'lazy').
+ const groups: Record<string, Group> = {};
for (const e of cook.entries) {
let size = e.size ?? 0;
if (e.size == null) { try { size = (await stat(path.join(absOut, e.path))).size; } catch { /* missing file → 0 */ } }
+ const groupName = e.group ?? 'main';
+ const group = (groups[groupName] ??= {
+ bundleMode: groupName === 'main' ? 'local' : 'lazy', labels: [], assets: {},
+ });
const entry: Entry = { path: e.path, type: addrType(e.type), size, labels: [] };
if (e.contentHash) entry.contentHash = e.contentHash;
- assets[e.uuid.toLowerCase()] = entry;
+ group.assets[e.uuid.toLowerCase()] = entry;
}
- return JSON.stringify({ version: '2.0', groups: { main: { bundleMode: 'local', labels: [], assets } } }, null, 2) + '\n';
+ // Always emit a main group so the runtime's main package exists even if every
+ // asset happened to land in a subpackage.
+ groups.main ??= { bundleMode: 'local', labels: [], assets: {} };
+ return JSON.stringify({ version: '2.0', groups }, null, 2) + '\n';
}
/**
@@ -257,7 +282,7 @@ export async function exportWeChat(opts: {
const engineGlueFile = ['esengine.js', 'esengine.wxgame.js']
.find((f) => existsSync(path.join(opts.wasmDir, f))) ?? 'esengine.js';
await writeFile(path.join(absOut, 'game.js'), gameEntryJs(sideModules, engineGlueFile));
- await writeFile(path.join(absOut, 'game.json'), gameJson(opts.orientation ?? 'portrait'));
+ await writeFile(path.join(absOut, 'game.json'), gameJson(opts.orientation ?? 'portrait', subPackagesOf(cookEntries)));
await writeFile(path.join(absOut, 'project.config.json'), projectConfigJson(title, opts.appid ?? ''));
// 6. The -t wechat engine runtime (WXWebAssembly glue + binary + side modules).
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
index 5c3b8e9be..26783d717 100644
--- a/desktop/tests/export-wechat.test.ts
+++ b/desktop/tests/export-wechat.test.ts
@@ -19,6 +19,7 @@ let root: string;
let out: string;
const TEX = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
const SCN = 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb';
+const SUBTEX = 'cccccccc-cccc-cccc-cccc-cccccccccccc';
const meta = (uuid: string, type: string) => JSON.stringify({ uuid, version: '2.0', type, importer: {} });
beforeAll(() => {
@@ -32,6 +33,11 @@ beforeAll(() => {
JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'Sprite', data: { texture: `@uuid:${TEX}` } }] }] }),
);
writeFileSync(path.join(root, 'scenes', 'main.esscene.meta'), meta(SCN, 'scene'));
+ // A lazy-subpackage asset (folder convention): NOT referenced by the entry
+ // scene, so it exercises force-include + grouping.
+ mkdirSync(path.join(root, 'subpackages', 'level2'), { recursive: true });
+ writeFileSync(path.join(root, 'subpackages', 'level2', 'extra.png'), 'PNG2DATA');
+ writeFileSync(path.join(root, 'subpackages', 'level2', 'extra.png.meta'), meta(SUBTEX, 'texture'));
mkdirSync(path.join(root, 'src'), { recursive: true });
writeFileSync(path.join(root, 'src', 'main.ts'), `import { defineComponent } from 'esengine';\ndefineComponent('SpawnMarker', { rate: 1 });\n`);
// Stub SDK dist (the bundle aliases `esengine` → <sdkDir>/index.wechat.js) + stub -t wechat runtime.
@@ -93,5 +99,13 @@ describe('exportGame (wechat)', () => {
expect(gjson.deviceOrientation).toBe('landscape');
expect(existsSync(path.join(out, 'wasm', 'esengine.js'))).toBe(true);
expect(existsSync(path.join(out, 'wasm', 'esengine.wasm'))).toBe(true);
+
+ // 分包: the subpackages/level2 asset forms a lazy group, registered as a
+ // WeChat subPackage, with its file staged under the subpackage root.
+ expect(manifest.groups.level2.bundleMode).toBe('lazy');
+ expect(manifest.groups.main.bundleMode).toBe('local');
+ expect(manifest.groups.level2.assets[SUBTEX].path).toBe('subpackages/level2/extra.png');
+ expect(gjson.subPackages).toContainEqual({ name: 'level2', root: 'subpackages/level2' });
+ expect(existsSync(path.join(out, 'subpackages', 'level2', 'extra.png'))).toBe(true);
}, 60_000);
});
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 71e53f2c6..235949504 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -3,6 +3,7 @@
import type { Backend } from './Backend';
import { Catalog, type AtlasFrameInfo } from './Catalog';
import { ManifestModel, type AddressableManifest } from './AddressableManifest';
+import { platformLoadSubpackage } from '../platform';
import type {
AssetLoader, LoadContext, TextureResult, SpineResult,
MaterialResult, FontResult, AudioResult, AnimClipResult,
@@ -370,6 +371,12 @@ export class Assets {
return bundle;
}
+ // A lazy group is an on-demand subpackage — download it before loading its
+ // assets (no-op on platforms without a subpackage concept, e.g. web).
+ if (model.bundleMode(groupName) === 'lazy') {
+ await platformLoadSubpackage(groupName);
+ }
+
let loadedCount = 0;
const promises: Promise<void>[] = [];
const track = (p: Promise<void>): Promise<void> =>
diff --git a/sdk/src/platform/base.ts b/sdk/src/platform/base.ts
index d5eb07cd7..5abf40798 100644
--- a/sdk/src/platform/base.ts
+++ b/sdk/src/platform/base.ts
@@ -112,6 +112,14 @@ export function platformCreateAudioBackend(): import('../audio/PlatformAudioBack
return getPlatform().createAudioBackend();
}
+/** Download an on-demand subpackage by name (resolves immediately on platforms
+ * with no subpackage concept, e.g. web). The single channel lazy asset groups
+ * use before loading their assets. */
+export function platformLoadSubpackage(name: string): Promise<void> {
+ const p = getPlatform();
+ return p.loadSubpackage ? p.loadSubpackage(name) : Promise.resolve();
+}
+
export function platformDevicePixelRatio(): number {
if (currentPlatform) {
return currentPlatform.devicePixelRatio();
diff --git a/sdk/src/platform/index.ts b/sdk/src/platform/index.ts
index 0b37df3f1..0cbdac7a3 100644
--- a/sdk/src/platform/index.ts
+++ b/sdk/src/platform/index.ts
@@ -33,6 +33,7 @@ export {
platformCreateImage,
platformNow,
platformCreateAudioBackend,
+ platformLoadSubpackage,
platformDevicePixelRatio,
} from './base';
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index 01d8887b2..120299415 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -119,6 +119,11 @@ export interface PlatformAdapter {
createAudioBackend(): import('../audio/PlatformAudioBackend').PlatformAudioBackend;
+ /** Download an on-demand asset subpackage by name and resolve when its files
+ * are available. WeChat → wx.loadSubpackage; platforms with no subpackage
+ * concept (web) omit it and lazy groups load directly from their URLs. */
+ loadSubpackage?(name: string): Promise<void>;
+
devicePixelRatio(): number;
getStorageItem(key: string): string | null;
diff --git a/sdk/src/platform/wechat/index.ts b/sdk/src/platform/wechat/index.ts
index c59f8af5e..84ae34112 100644
--- a/sdk/src/platform/wechat/index.ts
+++ b/sdk/src/platform/wechat/index.ts
@@ -68,6 +68,18 @@ class WeChatPlatformAdapter implements PlatformAdapter {
return wx.createImage() as unknown as HTMLImageElement;
}
+ /** WeChat 分包: download a subpackage so its files become readable. */
+ loadSubpackage(name: string): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ wx.loadSubpackage({
+ name,
+ success: () => resolve(),
+ fail: (err: unknown) => reject(new Error(`loadSubpackage("${name}") failed: ${JSON.stringify(err)}`)),
+ complete: () => {},
+ });
+ });
+ }
+
createCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas {
const canvas = wx.createCanvas() as unknown as HTMLCanvasElement;
canvas.width = width;
diff --git a/sdk/src/wechatRuntime.ts b/sdk/src/wechatRuntime.ts
index ceab5f876..1925464e2 100644
--- a/sdk/src/wechatRuntime.ts
+++ b/sdk/src/wechatRuntime.ts
@@ -15,6 +15,7 @@ import { applyBuildRuntimeConfig, type RuntimeBuildConfig } from './defaults';
import { platformReadTextFile, platformReadFile, platformInstantiateWasm, platformLoadImagePixels } from './platform';
import { toBuildPath } from './assetTypes';
import { ManifestModel, type AddressableManifest } from './asset/AddressableManifest';
+import { Assets } from './asset/AssetPlugin';
import { createWeChatSideModuleHost, type WeChatSideModuleFactories } from './sideModules';
import type { Vec2 } from './types';
import type { SceneData } from './scene';
@@ -143,6 +144,12 @@ export async function initWeChatRuntime(config: WeChatRuntimeConfig): Promise<vo
applyBuildRuntimeConfig(app, config.runtimeConfig);
}
+ // Hand the manifest to the App's Assets so game code can `Assets.loadGroup(name)`
+ // on demand — a lazy (subpackage) group triggers wx.loadSubpackage first, the
+ // eager 'main' group loads directly. Eager scene assets still load through the
+ // runtime loader below; this enables the on-demand subpackage path.
+ if (app.hasResource(Assets)) app.getResource(Assets).setManifest(manifest);
+
const provider = new WeChatAssetProvider(resolvePath);
const scenes: Array<{ name: string; data: SceneData }> = [];
diff --git a/sdk/tests/asset-group-loading.test.ts b/sdk/tests/asset-group-loading.test.ts
index d0be7e53e..424f16e15 100644
--- a/sdk/tests/asset-group-loading.test.ts
+++ b/sdk/tests/asset-group-loading.test.ts
@@ -5,6 +5,7 @@ import { Assets } from '../src/asset/Assets';
import { Catalog, type CatalogData } from '../src/asset/Catalog';
import type { AddressableManifest } from '../src/asset/AddressableManifest';
import type { Backend } from '../src/asset/Backend';
+import * as platform from '../src/platform';
const mockModule = {
_malloc: vi.fn(() => 0),
@@ -44,6 +45,7 @@ vi.mock('../src/platform', () => ({
},
platformNow: () => 0,
platformDevicePixelRatio: () => 1,
+ platformLoadSubpackage: vi.fn(() => Promise.resolve()),
}));
function createMockBackend(): Backend {
@@ -185,4 +187,24 @@ describe('Assets.loadGroup', () => {
expect(bundle.textures.size).toBe(0);
expect(progressCalls).toContainEqual([0, 0]);
});
+
+ it('downloads a lazy group as a subpackage before loading its assets', async () => {
+ const sub = vi.mocked(platform.platformLoadSubpackage);
+ sub.mockClear();
+ const assets = createAssets();
+ assets.setManifest(createManifest());
+ vi.spyOn(assets, 'loadTexture').mockResolvedValue({ handle: 1, width: 1, height: 1 } as any);
+ await assets.loadGroup('extra'); // createManifest: 'extra' is bundleMode 'lazy'
+ expect(sub).toHaveBeenCalledWith('extra');
+ });
+
+ it('does not download a subpackage for a local (main-package) group', async () => {
+ const sub = vi.mocked(platform.platformLoadSubpackage);
+ sub.mockClear();
+ const assets = createAssets();
+ assets.setManifest(createManifest());
+ vi.spyOn(assets, 'loadTexture').mockResolvedValue({ handle: 1, width: 1, height: 1 } as any);
+ await assets.loadGroup('main'); // bundleMode 'local'
+ expect(sub).not.toHaveBeenCalled();
+ });
});