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.

fix(wechat): stage KTX2 as .ktx2.bin — WeChat's package suffix whitelist has no ktx2

yhhf9aaa4dd040d
diff --git a/desktop/electron/exportWeChat.ts b/desktop/electron/exportWeChat.ts
index 099c311cd..f776b05a0 100644
--- a/desktop/electron/exportWeChat.ts
+++ b/desktop/electron/exportWeChat.ts
@@ -22,7 +22,7 @@
* Pure Node (esbuild + fs) — IPC wiring is in main.ts.
*/
import { loadEsbuild } from './esbuildRuntime';
-import { writeFile, mkdir, cp, readFile, stat, rm } from 'node:fs/promises';
+import { writeFile, mkdir, cp, readFile, rename, stat, rm } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import path from 'node:path';
import { cookAssets } from './cookAssets';
@@ -158,9 +158,10 @@ async function scanWeChatSideModules(
// meta type `spine`, so discriminate by extension — `.skel` is a binary
// skeleton, `.json` a JSON one; the `.atlas` sibling is not a skeleton.
for (const e of cookEntries) {
- // Any staged KTX2 texture (compressTextures cook, or an authored .ktx2)
- // needs the Basis transcoder at runtime.
- if (e.path.toLowerCase().endsWith('.ktx2')) ids.add('basis');
+ // Any staged KTX2 texture (compressTextures cook, or an authored .ktx2 —
+ // staged as .ktx2.bin for the WeChat suffix whitelist) needs the Basis
+ // transcoder at runtime. Mirrors sdk isKtx2Path.
+ if (/\.ktx2(\.bin)?$/.test(e.path.toLowerCase())) ids.add('basis');
if (e.type !== 'spine') continue;
const ext = path.extname(e.sourcePath ?? e.path).toLowerCase();
try {
@@ -287,6 +288,24 @@ export async function exportWeChat(opts: {
const cook = await cookAssets(opts.root, { entryScenes: [opts.entryScene], outDir: absOut, contentAddressed: opts.contentAddressed, compressTextures: opts.compressTextures, atlasTextures: opts.atlasTextures });
warnings.push(...cook.warnings);
+ // 1a. WeChat's code-package suffix whitelist has no `ktx2` — the packer
+ // drops such files and fs reads are denied regardless of packOptions.
+ // Re-stage KTX2 containers under the whitelisted `.bin` with a
+ // truth-keeping compound suffix; the runtime's KTX2 detection
+ // (isKtx2Path) accepts both spellings.
+ const flatManifestPath = path.join(absOut, 'assets.manifest.json');
+ try {
+ const flat = JSON.parse(await readFile(flatManifestPath, 'utf8')) as CookManifest;
+ let renamed = 0;
+ for (const e of flat.entries) {
+ if (!e.path.toLowerCase().endsWith('.ktx2')) continue;
+ await rename(path.join(absOut, e.path), path.join(absOut, `${e.path}.bin`));
+ e.path = `${e.path}.bin`;
+ renamed++;
+ }
+ if (renamed > 0) await writeFile(flatManifestPath, JSON.stringify(flat, null, 2));
+ } catch { /* no cook manifest — surfaces in step 2 */ }
+
// 1b. Scan the scene for the optional modules it needs (physics/spine), so the
// generated entry requires exactly those — the export-time half of the
// runtime's self-gating. Read the cook manifest + scene once and reuse below.
diff --git a/desktop/tests/export-wechat.test.ts b/desktop/tests/export-wechat.test.ts
index 47eda3547..e54806cfb 100644
--- a/desktop/tests/export-wechat.test.ts
+++ b/desktop/tests/export-wechat.test.ts
@@ -245,10 +245,17 @@ describe('exportGame (wechat)', () => {
expect(res.ok).toBe(true);
expect(readFileSync(path.join(outKtx, 'game.js'), 'utf8')).toContain("\"basis\": asFactory(require('./wasm/basis.js'))");
expect(existsSync(path.join(outKtx, 'wasm', 'basis.wasm'))).toBe(true);
- // WeChat denies fs reads of unlisted custom extensions — the staged .ktx2
- // must ride into packOptions.include.
+ // WeChat's code-package suffix whitelist has no `ktx2` — the container is
+ // re-staged as .ktx2.bin (whitelisted), and the manifest tracks the rename
+ // while the logical identity stays on the source path.
+ expect(existsSync(path.join(outKtx, 'assets', 'pre.ktx2.bin'))).toBe(true);
+ expect(existsSync(path.join(outKtx, 'assets', 'pre.ktx2'))).toBe(false);
+ const manifest = JSON.parse(readFileSync(path.join(outKtx, 'asset-manifest.json'), 'utf8'));
+ const ktxAsset = manifest.groups.main.assets['ffffffff-ffff-ffff-ffff-ffffffffffff'];
+ expect(ktxAsset.path).toBe('assets/pre.ktx2.bin');
const pcfg = JSON.parse(readFileSync(path.join(outKtx, 'project.config.json'), 'utf8'));
- expect(pcfg.packOptions.include).toContainEqual({ type: 'suffix', value: '.ktx2' });
+ expect(pcfg.packOptions.include).toContainEqual({ type: 'suffix', value: '.bin' });
+ expect(pcfg.packOptions.include).not.toContainEqual({ type: 'suffix', value: '.ktx2' });
}, 60_000);
it('a .ktx2 texture without a wechat basis build fails the export', async () => {
diff --git a/sdk/src/asset/compressed.ts b/sdk/src/asset/compressed.ts
index ff610be04..4c4dc1c90 100644
--- a/sdk/src/asset/compressed.ts
+++ b/sdk/src/asset/compressed.ts
@@ -44,6 +44,15 @@ export function isKtx2(bytes: Uint8Array): boolean {
return true;
}
+/** True if `path` names a KTX2 container: its own extension, or the
+ * `.ktx2.bin` spelling the WeChat export stages (WeChat's code-package
+ * suffix whitelist has no `ktx2`; `bin` is whitelisted, and the compound
+ * suffix keeps the container's identity in the name). */
+export function isKtx2Path(path: string): boolean {
+ const p = path.toLowerCase();
+ return p.endsWith('.ktx2') || p.endsWith('.ktx2.bin');
+}
+
// =============================================================================
// Transcoder seam
// =============================================================================
diff --git a/sdk/src/asset/loaders/TextureLoader.ts b/sdk/src/asset/loaders/TextureLoader.ts
index e6eaa3948..481d531ff 100644
--- a/sdk/src/asset/loaders/TextureLoader.ts
+++ b/sdk/src/asset/loaders/TextureLoader.ts
@@ -6,7 +6,7 @@ import { decodeImageBitmap } from '../imageDecode';
import { requireResourceManager } from '../../resourceManager';
import type { ESEngineModule } from '../../wasm';
import { withMalloc } from '../../wasmScratch';
-import { isKtx2, loadCompressedTexture, type BasisTranscoder } from '../compressed';
+import { isKtx2, isKtx2Path, loadCompressedTexture, type BasisTranscoder } from '../compressed';
import { glWrapMode } from '../glTexParams';
import { createTextureFromPixels, type TextureParams } from '../../runtimeAssets';
@@ -156,7 +156,7 @@ export class TextureLoader implements AssetLoader<TextureResult> {
private async decodeAndUpload_(
path: string, ctx: LoadContext, flip: boolean, settings?: TextureImportSettings,
): Promise<TextureResult> {
- if (path.toLowerCase().endsWith('.ktx2')) {
+ if (isKtx2Path(path)) {
return this.loadCompressed(path, ctx, settings);
}
// A platform pixel decoder (runtime scene loader) pre-decodes to RGBA and
diff --git a/sdk/src/spine/loadSpineScene.ts b/sdk/src/spine/loadSpineScene.ts
index 952556db6..44fc95515 100644
--- a/sdk/src/spine/loadSpineScene.ts
+++ b/sdk/src/spine/loadSpineScene.ts
@@ -26,7 +26,7 @@ import { log } from '../logger';
import { SpineManager, type SpineVersion } from './SpineManager';
import { parseSpineAtlasPages } from './atlasPages';
import { createTextureFromPixels, type RuntimeAssetSource } from '../runtimeAssets';
-import type { BasisTranscoder } from '../asset/compressed';
+import { isKtx2Path, type BasisTranscoder } from '../asset/compressed';
/** Lazily yields the realm's Basis transcoder (KTX2 atlas pages), or null where
* compressed textures can't occur (editor, uncooked dev). Same seam as the
@@ -95,7 +95,7 @@ export async function loadSpineAssets(
// manifest/catalog like every other fetch.
const staged = resolveRef(texPath);
let result: { width: number; height: number; pixels: Uint8Array };
- if (staged.toLowerCase().endsWith('.ktx2')) {
+ if (isKtx2Path(staged)) {
const transcoder = await transcoderProvider?.();
if (!transcoder) throw new Error('KTX2 atlas page but no Basis transcoder in this realm');
const rgba = transcoder.transcodeToRgba(new Uint8Array(await source.backend.fetchBinary(staged)));
diff --git a/sdk/tests/spine-atlas-page-resolve.test.ts b/sdk/tests/spine-atlas-page-resolve.test.ts
index 77432c187..e5505cf6d 100644
--- a/sdk/tests/spine-atlas-page-resolve.test.ts
+++ b/sdk/tests/spine-atlas-page-resolve.test.ts
@@ -68,6 +68,17 @@ describe('loadSpineAssets resolves atlas page paths through the manifest', () =>
expect(tex).toEqual({ glId: 7, w: 2, h: 2 });
});
+ it('recognizes the WeChat .ktx2.bin staging spelling as KTX2', async () => {
+ const source = makeSource({ 'assets/spine/spineboy.png': 'assets/spine/spineboy.ktx2.bin' });
+ const transcoder: BasisTranscoder = {
+ transcode: vi.fn(() => null),
+ transcodeToRgba: vi.fn(() => ({ width: 2, height: 2, data: new Uint8Array(16) })),
+ };
+ await loadSpineAssets({} as never, source, null, PAIR, async () => transcoder);
+ expect(source.decodePixels).not.toHaveBeenCalled();
+ expect(transcoder.transcodeToRgba).toHaveBeenCalledTimes(1);
+ });
+
it('decodes a content-addressed page from its STAGED path', async () => {
const source = makeSource({ 'assets/spine/spineboy.png': 'assets/1234abcd.png' });
await loadSpineAssets({} as never, source, null, PAIR);