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
fix(spine): single-source atlas pages; cook embeds them, exporter detects versions again
yhhc74b27ba353e
diff --git a/desktop/electron/assetDb.ts b/desktop/electron/assetDb.tsindex b19ba3bcb..f93dacdd2 100644--- a/desktop/electron/assetDb.ts+++ b/desktop/electron/assetDb.ts@@ -22,6 +22,10 @@ import { META_EXT, isContentDir } from './contentPolicy';// The runtime's tileset-path resolver (a dependency-free leaf) — shared so the dep scan// discovers a tilemap's tileset images the same way the loader will later request them.import { resolveRelativePath } from '../../sdk/src/tilemap/tiledPath';+// The spine-atlas page parser (a dependency-free leaf) — shared with the runtime loaders+// so the dep scan discovers an atlas's texture pages the same way they will be requested.+import { parseSpineAtlasPages } from '../../sdk/src/spine/atlasPages';+import { getEditorType } from '../../sdk/src/assetTypes';/** Local, gitignored cache inside the project (next to workspace.json). */const CACHE_DIR = '.esengine/cache';@@ -174,23 +178,36 @@ export async function scanAssetDatabase(const uuids = new Set(entries.map((e) => e.uuid));const deps: Record<string, string[]> = {};for (const entry of entries) {- if (!JSON_REF_TYPES.has(entry.type)) continue;+ // 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+ // apart from the JSON path so the cook embeds those textures (else the atlas+ // ships but its .png is culled and the playable 404s it).+ const isSpineAtlas = getEditorType(entry.path) === 'spine-atlas';+ if (!JSON_REF_TYPES.has(entry.type) && !isSpineAtlas) continue;try {- const json = JSON.parse(await readFile(path.join(root, entry.path), 'utf8'));const refs = new Set<string>();- collectRefs(json, refs, (ref) => {- if (ref.includes('://')) return null;- const direct = byPath.get(normalizeRefPath(ref));- if (direct) return direct.uuid;- // Fall back to a path RELATIVE to the referencing document, resolved the way- // the runtime loads it (collapsing ./ and ../) — so a Tiled tileset image- // "../textures/tileset.png" or a material's sibling "x.esshader" resolves to- // the same asset the loader will request. (The old join left "../" uncollapsed,- // so tilemap tileset images never linked and the cook culled them → the- // single-file playable 404'd them.)- const rel = byPath.get(normalizeRefPath(resolveRelativePath(entry.path, ref)));- return rel?.uuid ?? null;- }, (id) => uuids.has(id));+ if (isSpineAtlas) {+ const content = await readFile(path.join(root, entry.path), 'utf8');+ for (const page of parseSpineAtlasPages(content)) {+ const dep = byPath.get(normalizeRefPath(resolveRelativePath(entry.path, page)));+ if (dep) refs.add(dep.uuid);+ }+ } else {+ const json = JSON.parse(await readFile(path.join(root, entry.path), 'utf8'));+ collectRefs(json, refs, (ref) => {+ if (ref.includes('://')) return null;+ const direct = byPath.get(normalizeRefPath(ref));+ if (direct) return direct.uuid;+ // Fall back to a path RELATIVE to the referencing document, resolved the way+ // the runtime loads it (collapsing ./ and ../) — so a Tiled tileset image+ // "../textures/tileset.png" or a material's sibling "x.esshader" resolves to+ // the same asset the loader will request. (The old join left "../" uncollapsed,+ // so tilemap tileset images never linked and the cook culled them → the+ // single-file playable 404'd them.)+ const rel = byPath.get(normalizeRefPath(resolveRelativePath(entry.path, ref)));+ return rel?.uuid ?? null;+ }, (id) => uuids.has(id));+ }refs.delete(entry.uuid);if (refs.size > 0) deps[entry.uuid] = [...refs].sort();} catch (err) {diff --git a/desktop/electron/exportPlayable.ts b/desktop/electron/exportPlayable.tsindex b7bf7c4b4..1c3826b6b 100644--- a/desktop/electron/exportPlayable.ts+++ b/desktop/electron/exportPlayable.ts@@ -23,7 +23,7 @@ import type { OnExportProgress } from './exportProgress';import { esengineAlias } from './esengineResolve';import {sceneUsesPhysics, detectSpineVersion, detectSpineVersionJson,- spineModuleId, SIDE_MODULE_FILE,+ spineModuleId, SIDE_MODULE_FILE, type SpineVersion,} from './sideModuleScan';export interface ExportPlayableResult {@@ -89,15 +89,21 @@ async function collectSideModules(): Promise<Record<string, { glueBase64: string; wasmBase64: string }>> {const ids = new Set<string>();if (sceneData && sceneUsesPhysics(sceneData as Parameters<typeof sceneUsesPhysics>[0])) ids.add('physics');+ // Spine: the skeleton carries the version. Skeleton + atlas share the authored+ // meta type `spine`, so we discriminate by extension (as the runtime does via+ // the asset-type registry's contentType) — `.skel` is a binary skeleton, `.json`+ // a JSON one; the `.atlas` sibling is not a skeleton and is skipped.for (const e of manifestEntries) {+ if (e.type !== 'spine') continue;+ const ext = path.extname(e.sourcePath ?? e.path).toLowerCase();try {- if (e.type === 'spine-skeleton') {- const v = detectSpineVersion(new Uint8Array(await readFile(path.join(cookDir, e.path))));- if (v) ids.add(spineModuleId(v));- } else if (e.path.toLowerCase().endsWith('.json')) {- const v = detectSpineVersionJson(await readFile(path.join(cookDir, e.path), 'utf8'));- if (v) ids.add(spineModuleId(v));+ let v: SpineVersion | null = null;+ if (ext === '.skel') {+ v = detectSpineVersion(new Uint8Array(await readFile(path.join(cookDir, e.path))));+ } else if (ext === '.json') {+ v = detectSpineVersionJson(await readFile(path.join(cookDir, e.path), 'utf8'));}+ if (v) ids.add(spineModuleId(v));} catch { /* unreadable cook entry — cookAssets already warned; skip */ }}diff --git a/desktop/tests/export-playable.test.ts b/desktop/tests/export-playable.test.tsindex 7eabb5f10..3e5def9d7 100644--- a/desktop/tests/export-playable.test.ts+++ b/desktop/tests/export-playable.test.ts@@ -153,3 +153,79 @@ describe('exportGame (playable) — side-module embedding', () => {}}, 60_000);});++/**+ * Spine: the skeleton + atlas share the authored meta type `spine`, so the exporter+ * must discriminate by extension (`.skel` binary skeleton carries the version) — and+ * the atlas's page image is a dependency the cook has to embed. A playable that lost+ * either shipped a broken spine (module "not embedded" / texture 404) — this is that fix.+ */+describe('exportGame (playable) — spine embedding', () => {+ const SSCN = 'eeeeeeee-eeee-4eee-8eee-eeeeeeeeeeee';+ const SKEL = 'ffffffff-ffff-4fff-8fff-ffffffffffff';+ const ATLAS = '99999999-9999-4999-8999-999999999999';+ const PAGE = '88888888-8888-4888-8888-888888888888';++ // A minimal spine 4.x binary skeleton header: 8 bytes, then a varint length (7)+ // and the version string "4.2.00" — exactly what detectSpineVersion reads.+ const skel = Buffer.concat([Buffer.alloc(8), Buffer.from([7]), Buffer.from('4.2.00')]);+ const atlas = ['hero.png', '\tsize: 64, 64', 'region', '\tbounds: 0, 0, 32, 32', ''].join('\n');++ function setupRoot(withSpineArtifact: boolean): { r: string; o: string } {+ const r = mkdtempSync(path.join(tmpdir(), 'estella-playable-spine-'));+ mkdirSync(path.join(r, 'assets', 'spine'), { recursive: true });+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.png'), 'PNGDATA');+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.png.meta'), meta(PAGE, 'texture'));+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.atlas'), atlas);+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.atlas.meta'), meta(ATLAS, 'spine'));+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.skel'), skel);+ writeFileSync(path.join(r, 'assets', 'spine', 'hero.skel.meta'), meta(SKEL, 'spine'));+ mkdirSync(path.join(r, 'scenes'), { recursive: true });+ writeFileSync(path.join(r, 'scenes', 'main.esscene'),+ JSON.stringify({ version: '1.0', name: 'Main', entities: [{ id: 0, components: [{ type: 'SpineAnimation', data: { skeletonPath: 'assets/spine/hero.skel', atlasPath: 'assets/spine/hero.atlas' } }] }] }));+ writeFileSync(path.join(r, 'scenes', 'main.esscene.meta'), meta(SSCN, 'scene'));+ mkdirSync(path.join(r, '_sdk'), { recursive: true });+ writeFileSync(path.join(r, '_sdk', 'index.js'),+ `export function createWebApp(){return{GL:{registerContext(){}}};}\nexport function setEditorMode(){}\nexport function setPlayMode(){}\nexport function initPlayableRuntime(){return Promise.resolve();}\nexport function createEmbeddedSideModuleHost(){return{acquire(){return Promise.resolve(null);}};}\n`);+ mkdirSync(path.join(r, '_wasm'), { recursive: true });+ writeFileSync(path.join(r, '_wasm', 'esengine.js'), `export default function(){}\n`);+ writeFileSync(path.join(r, '_wasm', 'esengine.wasm'), 'WASMBYTES');+ if (withSpineArtifact) {+ writeFileSync(path.join(r, '_wasm', 'spine42.js'), `export default function(){}/*SPINE_GLUE*/\n`);+ writeFileSync(path.join(r, '_wasm', 'spine42.wasm'), 'SPINE42WASM');+ }+ return { r, o: path.join(r, 'dist') };+ }++ const run = (r: string, o: string) => exportGame({+ root: r, entryScene: 'scenes/main.esscene', gameHostEntry: 'x', playableHostEntry: PLAYABLE_HOST,+ sdkDistDir: path.join(r, '_sdk'), wasmDir: path.join(r, '_wasm'), outDir: o, platform: 'playable',+ });++ it('inlines spine:4.2 (detected from the .skel) and embeds the atlas page texture', async () => {+ const { r, o } = setupRoot(true);+ try {+ const res = await run(r, o);+ expect(res.ok).toBe(true);+ const html = readFileSync(path.join(o, 'index.html'), 'utf8');+ expect(html).toContain('__SIDE_MODULES__');+ expect(html).toContain('"spine:4.2"');+ expect(html).toContain(Buffer.from('SPINE42WASM').toString('base64')); // spine42.wasm inlined+ // The atlas page image is embedded + path-mapped (the dep the cook now follows).+ expect(html).toMatch(/"assets\/spine\/hero\.png":"@uuid:/);+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ }, 60_000);++ it('fails the export when the scene needs spine but spine42.wasm is absent', async () => {+ const { r, o } = setupRoot(false);+ try {+ const res = await run(r, o);+ expect(res.ok).toBe(false);+ expect(res.errors.join('\n')).toMatch(/spine/i);+ } finally {+ rmSync(r, { recursive: true, force: true });+ }+ }, 60_000);+});diff --git a/desktop/tests/spine-cook-deps.test.ts b/desktop/tests/spine-cook-deps.test.tsnew file mode 100644index 000000000..4d934f6af--- /dev/null+++ b/desktop/tests/spine-cook-deps.test.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Regression: a Spine `.atlas` names its page image(s) as texture dependencies.+ * The `.atlas` is a TEXT manifest (not JSON), so the dep scan must parse it and+ * follow atlas → page image — otherwise the cook culls the texture and every+ * ship target (playable/web/…) requests it as an external file and 404s it.+ */+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 { scanAssetDatabase } from '../electron/assetDb';+import { cookAssets } from '../electron/cookAssets';++let root: string;++const PAGE_TEX = '11111111-1111-4111-8111-111111111111';+const ATLAS = '22222222-2222-4222-8222-222222222222';+const SKEL = '33333333-3333-4333-8333-333333333333';+const SCENE = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';++function writeAsset(rel: string, type: string, uuid: string, body: string | Uint8Array = ''): 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: {} }));+}++// A spine atlas: the page image name sits at column 0, its region properties indented.+// The page ref (`hero.png`) is relative to the atlas file (a sibling under assets/spine/).+const atlas = [+ 'hero.png',+ '\tsize: 64, 64',+ '\tfilter: Linear, Linear',+ 'region',+ '\tbounds: 0, 0, 32, 32',+ '',+].join('\n');++// The scene references BOTH the skeleton and the atlas (SpineAnimation fields), the way+// discoverSceneAssets pairs them at runtime — so both are reachable directly.+const scene = JSON.stringify({+ version: '1.0', name: 'm',+ entities: [{+ id: 1, name: 'S', parent: null, children: [], components: [{+ type: 'SpineAnimation',+ data: { skeletonPath: 'assets/spine/hero.skel', atlasPath: 'assets/spine/hero.atlas' },+ }],+ }],+});++beforeAll(() => {+ root = mkdtempSync(path.join(tmpdir(), 'estella-spinecook-'));+ writeAsset('assets/spine/hero.png', 'texture', PAGE_TEX, 'PNG');+ writeAsset('assets/spine/hero.atlas', 'spine', ATLAS, atlas);+ writeAsset('assets/spine/hero.skel', 'spine', SKEL, new Uint8Array([1, 2, 3, 4]));+ writeAsset('assets/scenes/main.esscene', 'scene', SCENE, scene);+});++afterAll(() => {+ if (root) rmSync(root, { recursive: true, force: true });+});++describe('spine atlas page images are cooked dependencies', () => {+ it('links atlas → page image in the dep scan (a .atlas is text, not JSON)', async () => {+ const { index } = await scanAssetDatabase(root, { write: false });+ expect(index.deps[ATLAS]).toContain(PAGE_TEX);+ });++ it('embeds the atlas page texture (reachable through the atlas — not culled)', async () => {+ const res = await cookAssets(root, { entryScenes: ['assets/scenes/main.esscene'], outDir: 'build' });+ expect(res.ok).toBe(true);+ expect(res.included).toEqual(expect.arrayContaining([SCENE, ATLAS, SKEL, PAGE_TEX]));+ expect(res.unused).not.toEqual(expect.arrayContaining([PAGE_TEX]));+ });+});diff --git a/sdk/src/asset/loaders/SpineAssetLoader.ts b/sdk/src/asset/loaders/SpineAssetLoader.tsindex 6c3078823..d4584d95c 100644--- a/sdk/src/asset/loaders/SpineAssetLoader.ts+++ b/sdk/src/asset/loaders/SpineAssetLoader.ts@@ -5,6 +5,7 @@ import { requireResourceManager } from '../../resourceManager';import { getAssetTypeEntry } from '../../assetTypes';import type { ESEngineModule } from '../../wasm';import type { SpineModuleController } from '../../spine/SpineController';+import { parseSpineAtlasPages } from '../../spine/atlasPages';import { log } from '../../logger';export class SpineAssetLoader implements AssetLoader<SpineResult> {@@ -49,7 +50,7 @@ export class SpineAssetLoader implements AssetLoader<SpineResult> {}const atlasContent = await ctx.loadText(ctx.catalog.getBuildPath(atlasPath));- const texNames = parseAtlasTextures(atlasContent);+ const texNames = parseSpineAtlasPages(atlasContent);const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));const rm = requireResourceManager();@@ -150,14 +151,3 @@ function ensureVirtualDir(fs: any, virtualPath: string): void {try { fs.mkdir(currentPath); } catch { /* already exists */ }}}--function parseAtlasTextures(content: string): string[] {- const textures: string[] = [];- for (const line of content.split('\n')) {- const trimmed = line.trim();- if (trimmed && !trimmed.includes(':') && (/\.png$/i.test(trimmed) || /\.jpg$/i.test(trimmed))) {- textures.push(trimmed);- }- }- return textures;-}diff --git a/sdk/src/spine/atlasPages.ts b/sdk/src/spine/atlasPages.tsnew file mode 100644index 000000000..794129290--- /dev/null+++ b/sdk/src/spine/atlasPages.ts@@ -0,0 +1,27 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file atlasPages.ts — the single source of truth for a Spine `.atlas`'s page+ * image names. A spine atlas is a text manifest whose page headers name an+ * image file (`spineboy.png`) at column 0, each followed by indented+ * `key: value` property lines. Those page images are the atlas's texture+ * DEPENDENCIES — resolved relative to the atlas file.+ *+ * Every consumer reads pages through here so the cook's dependency scan+ * (which decides what ships), the runtime {@link SpineAssetLoader}, and the+ * scene loader ({@link loadSpineAssets}) agree by construction — a texture+ * the loader will request is exactly one the cook embedded. Kept a+ * dependency-free leaf so the Node-side cook can import it too.+ */++/** Parse a spine `.atlas`'s page image filenames (relative to the atlas file). */+export function parseSpineAtlasPages(content: string): string[] {+ const pages: string[] = [];+ for (const line of content.split('\n')) {+ const trimmed = line.trim();+ if (trimmed && !trimmed.includes(':') && (/\.png$/i.test(trimmed) || /\.jpg$/i.test(trimmed))) {+ pages.push(trimmed);+ }+ }+ return pages;+}diff --git a/sdk/src/spine/loadSpineScene.ts b/sdk/src/spine/loadSpineScene.tsindex 4233b41b9..3fd97c8b2 100644--- a/sdk/src/spine/loadSpineScene.ts+++ b/sdk/src/spine/loadSpineScene.ts@@ -24,6 +24,7 @@ import { getAssetTypeEntry } from '../assetTypes';import { requireResourceManager } from '../resourceManager';import { log } from '../logger';import { SpineManager, type SpineVersion } from './SpineManager';+import { parseSpineAtlasPages } from './atlasPages';import { createTextureFromPixels, type RuntimeAssetSource } from '../runtimeAssets';/** The opaque C++ registry handle SpineManager.loadEntity expects (app.world.getCppRegistry()). */@@ -36,17 +37,6 @@ interface SpineAssetInfo {textures: Map<string, { glId: number; w: number; h: number }>;}-function parseAtlasTextures(content: string): string[] {- const textures: string[] = [];- for (const line of content.split('\n')) {- const trimmed = line.trim();- if (trimmed && !trimmed.includes(':') && (/\.png$/i.test(trimmed) || /\.jpg$/i.test(trimmed))) {- textures.push(trimmed);- }- }- return textures;-}-/*** Phase 1 — fetch + decode each spine pair's skeleton/atlas/textures and detect* its runtime version. Keyed by `skeletonRef:atlasRef` for {@link applySpineEntities}.@@ -84,7 +74,7 @@ export async function loadSpineAssets(: SpineManager.detectVersion(skelData)): null;- const texNames = parseAtlasTextures(atlasContent);+ const texNames = parseSpineAtlasPages(atlasContent);const atlasDir = atlasPath.substring(0, atlasPath.lastIndexOf('/'));const rm = requireResourceManager();const textures = new Map<string, { glId: number; w: number; h: number }>();