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(dragonbones): release atlas pages with their skeleton owners
yhh06c768857e79
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 67334765c..f328486ae 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@ published separately; it ships inside the editor.### Fixed+- **DragonBones atlas textures follow skeleton ownership.** Scene loading reuses a resident atlas page and transfers its reference to the skeleton that uses it. The last armature removal and manager disposal release the page; rejected armatures release otherwise unbound skeletons and uploads. Repeated editor scene switching no longer adds a new atlas texture on every load, while paused poses and device recovery continue drawing correctly.+- **Late scene-load errors roll back the new entities.** A failing final spawn-phase observer or asset-reference publication step now despawns the entities created by that load and releases their owned resources before returning the original error. Existing unrelated entities remain intact and a later load can retry normally.- **Prepared prefab spawns reject failed parent attachments.** The synchronous spawn path rolls back its new hierarchy and entity-owned resources when its parent no longer accepts the root, matching asynchronous instantiation. Preparation resources remain available for later valid spawns, and live parents, position overrides and explicit unparented copies remain supported.diff --git a/sdk/etc/dragonbones.api.md b/sdk/etc/dragonbones.api.mdindex 852ebe973..eeaf799b3 100644--- a/sdk/etc/dragonbones.api.md+++ b/sdk/etc/dragonbones.api.md@@ -35,6 +35,7 @@ skeletonScale: number | undefined## DragonBonesManager — class @experimental```+@internal discardUnboundSkeleton: (assetKey: string) => voidaddEntity: (entity: Entity, skeletonHandle: number, options: DragonBonesEntityOptions) => booleanboundEntities: () => Iterable<Entity>controller: DragonBonesModuleControllerdiff --git a/sdk/src/dragonbones/DragonBonesManager.ts b/sdk/src/dragonbones/DragonBonesManager.tsindex d66181094..d7a5647b7 100644--- a/sdk/src/dragonbones/DragonBonesManager.ts+++ b/sdk/src/dragonbones/DragonBonesManager.ts@@ -20,6 +20,7 @@ import { submitEntityMeshes, type SkeletalMaterialOf, type SkeletalSubmitCore }import type { SkeletalBounds } from '../skeletal/types';import { DragonBonesModuleController } from './DragonBonesController';import { log } from '../util/logger';+import { releaseAtlasOwner, releaseAllAtlasOwners } from './atlasOwnership';/** How one entity's armature is posed and drawn. */interface EntityInfo {@@ -97,6 +98,15 @@ export class DragonBonesManager {return this.controller_.getArmatures(skeletonHandle);}+ /** @internal Retire a scene load that produced no armature instances. */+ discardUnboundSkeleton(assetKey: string): void {+ const shared = this.skeletons_.get(assetKey);+ if (!shared || shared.refcount !== 0) return;+ this.controller_.unloadSkeleton(shared.handle);+ this.skeletons_.delete(assetKey);+ releaseAtlasOwner(this, shared.handle);+ }+// — Entities —————————————————————————————————————————————————————————————/** Replace an armature only after its new instance and ownership are valid. */@@ -259,6 +269,7 @@ export class DragonBonesManager {this.controller_.unloadSkeleton(shared.handle);}for (const handle of this.unkeyedSkeletons_.keys()) this.controller_.unloadSkeleton(handle);+ releaseAllAtlasOwners(this);this.entities_.clear();this.disabled_.clear();this.skeletons_.clear();@@ -272,6 +283,7 @@ export class DragonBonesManager {if (refs > 0) this.unkeyedSkeletons_.set(info.skeletonHandle, refs);else {this.controller_.unloadSkeleton(info.skeletonHandle);+ releaseAtlasOwner(this, info.skeletonHandle);this.unkeyedSkeletons_.delete(info.skeletonHandle);}return;@@ -280,6 +292,7 @@ export class DragonBonesManager {if (!shared) return;if (--shared.refcount <= 0) {this.controller_.unloadSkeleton(shared.handle);+ releaseAtlasOwner(this, shared.handle);this.skeletons_.delete(info.assetKey);}}diff --git a/sdk/src/dragonbones/atlasOwnership.ts b/sdk/src/dragonbones/atlasOwnership.tsnew file mode 100644index 000000000..d7d6f99b3--- /dev/null+++ b/sdk/src/dragonbones/atlasOwnership.ts@@ -0,0 +1,33 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+const pending = new WeakMap<object, () => void>();+const bound = new WeakMap<object, Map<number, () => void>>();++export function ownAtlas(info: object, release: () => void): void { pending.set(info, release); }+export function bindAtlasOwner(info: object, manager: object, handle: number): void {+ const release = pending.get(info);+ if (!release) return;+ pending.delete(info);+ let owners = bound.get(manager);+ if (!owners) bound.set(manager, owners = new Map());+ const previous = owners.get(handle);+ owners.set(handle, release);+ previous?.();+}+export function releaseAtlasOwner(manager: object, handle: number): void {+ const owners = bound.get(manager), release = owners?.get(handle);+ owners?.delete(handle);+ release?.();+}+export function releaseAllAtlasOwners(manager: object): void {+ const owners = bound.get(manager);+ bound.delete(manager);+ if (owners) for (const release of owners.values()) release();+}+export function releaseUnusedAtlases(infos: Iterable<object>): void {+ for (const info of infos) {+ const release = pending.get(info);+ pending.delete(info);+ release?.();+ }+}diff --git a/sdk/src/dragonbones/loadDragonBonesScene.ts b/sdk/src/dragonbones/loadDragonBonesScene.tsindex 7304cf569..2c4c27bb6 100644--- a/sdk/src/dragonbones/loadDragonBonesScene.ts+++ b/sdk/src/dragonbones/loadDragonBonesScene.ts@@ -31,6 +31,7 @@ import { log } from '../util/logger';import { createAtlasPageTexture, type RuntimeAssetSource } from '../runtime/runtimeAssets';import type { BasisTranscoder } from '../asset/compressed';import type { DragonBonesManager } from './DragonBonesManager';+import { ownAtlas, bindAtlasOwner, releaseUnusedAtlases } from './atlasOwnership';/** Lazily yields the realm's Basis transcoder, or null where a cook cannot have* produced a compressed page (editor, uncooked dev). Same seam as Spine's. */@@ -113,12 +114,14 @@ export async function loadDragonBonesAssets(? new Uint8Array(await source.backend.fetchBinary(skelPath)): await source.backend.fetchText(skelPath);- assetInfo.set(cacheKey, {+ const page = await uploadAtlasImage_(module, source, pair.atlas, atlasJson, resolveRef, transcoderProvider);+ const info = {skeletonData,atlasJson,- textureId: await uploadAtlasImage_(- module, source, pair.atlas, atlasJson, resolveRef, transcoderProvider),- });+ textureId: page.textureId,+ };+ if (page.release) ownAtlas(info, page.release);+ assetInfo.set(cacheKey, info);} catch (err) {log.warn('runtime',`Failed to load DragonBones asset: skeleton=${pair.skeleton} atlas=${pair.atlas}`, err);@@ -127,7 +130,7 @@ export async function loadDragonBonesAssets(return assetInfo;}-/** Decode and upload the one page a `_tex.json` names; -1 if there is none to load. */+/** Acquire the page a `_tex.json` names; its release follows the skeleton's lifetime. */async function uploadAtlasImage_(module: ESEngineModule | null,source: RuntimeAssetSource,@@ -135,11 +138,11 @@ async function uploadAtlasImage_(atlasJson: string,resolveRef: (ref: string) => string,transcoderProvider?: TranscoderProvider,-): Promise<number> {+): Promise<{ textureId: number; release?: () => void }> {const imageName = atlasImageName(atlasJson);if (!imageName) {log.warn('runtime', `DragonBones atlas names no image: ${atlasRef}`);- return -1;+ return { textureId: -1 };}// The image is named relative to where the atlas was AUTHORED, not to where a@@ -151,6 +154,9 @@ async function uploadAtlasImage_(const imagePath = slash >= 0 ? `${atlasLogical.substring(0, slash)}/${imageName}` : imageName;try {+ const rm = requireResourceManager();+ const existing = typeof rm.acquireTextureByPath === 'function' ? rm.acquireTextureByPath(imagePath) : 0;+ if (existing) return { textureId: rm.getTextureGLId(existing), release: () => rm.releaseTexture(existing) };const staged = resolveRef(imagePath);const page = await createAtlasPageTexture(staged,@@ -158,12 +164,11 @@ async function uploadAtlasImage_((p) => source.decodePixels(p, false),transcoderProvider, module,);- const rm = requireResourceManager();rm.registerTextureWithPath(page.handle, imagePath);- return rm.getTextureGLId(page.handle);+ return { textureId: rm.getTextureGLId(page.handle), release: () => rm.releaseTexture(page.handle) };} catch (err) {log.warn('runtime', `Failed to load DragonBones atlas image: ${imagePath}`, err);- return -1;+ return { textureId: -1 };}}@@ -180,67 +185,71 @@ export function applyDragonBonesEntities(opts: {}): void {const { manager, sceneData, entityMap, assetInfo } = opts;if (assetInfo.size === 0) return;+ const touched = new Set<string>();+ try {+ for (const sceneEntity of sceneData.entities) {+ // Prefab instances carry no inline components; the loader expands them+ // before this runs.+ if (!Array.isArray(sceneEntity.components)) continue;- for (const sceneEntity of sceneData.entities) {- // Prefab instances carry no inline components; the loader expands them- // before this runs.- if (!Array.isArray(sceneEntity.components)) continue;-- for (const comp of sceneEntity.components) {- const desc = getComponentSkeletalFieldDescriptor(comp.type);- if (!desc || desc.runtime !== 'dragonbones' || !comp.data) continue;+ for (const comp of sceneEntity.components) {+ const desc = getComponentSkeletalFieldDescriptor(comp.type);+ if (!desc || desc.runtime !== 'dragonbones' || !comp.data) continue;- const data = comp.data as Record<string, unknown>;- const skeletonRef = data[desc.skeletonField];- const atlasRef = data[desc.atlasField];- if (typeof skeletonRef !== 'string' || typeof atlasRef !== 'string') continue;- if (!skeletonRef || !atlasRef) continue;+ const data = comp.data as Record<string, unknown>;+ const skeletonRef = data[desc.skeletonField];+ const atlasRef = data[desc.atlasField];+ if (typeof skeletonRef !== 'string' || typeof atlasRef !== 'string') continue;+ if (!skeletonRef || !atlasRef) continue;- const assetKey = `${skeletonRef}:${atlasRef}`;- const info = assetInfo.get(assetKey);- if (!info) continue;+ const assetKey = `${skeletonRef}:${atlasRef}`;+ const info = assetInfo.get(assetKey);+ if (!info) continue;- const entity = entityMap.get(sceneEntity.id);- if (entity === undefined) continue;+ const entity = entityMap.get(sceneEntity.id);+ if (entity === undefined) continue;- const handle = manager.loadSkeleton(info.skeletonData, info.atlasJson, assetKey);- if (handle < 0) continue;- if (info.textureId >= 0) manager.setAtlasTexture(handle, info.textureId);+ const handle = manager.loadSkeleton(info.skeletonData, info.atlasJson, assetKey);+ if (handle < 0) continue;+ touched.add(assetKey);+ if (info.textureId >= 0) manager.setAtlasTexture(handle, info.textureId);+ bindAtlasOwner(info, manager, handle);- // No armature named means the first one the file holds: a file usually- // ships one, and refusing to draw because a field is blank would make- // the common case need a value the user cannot guess without opening- // the file.- const named = typeof data.armature === 'string' ? data.armature : '';- const armature = named || manager.getArmatures(handle)[0];- if (!armature) {- log.warn('runtime', `DragonBones file holds no armature: ${skeletonRef}`);- continue;- }+ // An unspecified armature selects the file's first armature.+ const named = typeof data.armature === 'string' ? data.armature : '';+ const armature = named || manager.getArmatures(handle)[0];+ if (!armature) {+ log.warn('runtime', `DragonBones file holds no armature: ${skeletonRef}`);+ continue;+ }- const props = dragonBonesEntityProps(data);- const added = manager.addEntity(entity, handle, {- armature,- assetKey,- skeletonScale: props.skeletonScale,- flipX: props.flipX,- flipY: props.flipY,- layer: props.layer,- });- if (!added) continue;+ const props = dragonBonesEntityProps(data);+ const added = manager.addEntity(entity, handle, {+ armature,+ assetKey,+ skeletonScale: props.skeletonScale,+ flipX: props.flipX,+ flipY: props.flipY,+ layer: props.layer,+ });+ if (!added) continue;- manager.setEntityProps(entity, props);+ manager.setEntityProps(entity, props);- const animation = typeof data.animation === 'string' ? data.animation : '';- if (animation) {- const fade = typeof data.fadeInTime === 'number' ? data.fadeInTime : 0;- const loop = data.loop !== false;- // fadeInTime is what this component has instead of Spine's mix- // table, so an authored fade belongs to the FIRST play too.- if (fade > 0) manager.fadeIn(entity, animation, fade, loop);- else manager.play(entity, animation, loop);+ const animation = typeof data.animation === 'string' ? data.animation : '';+ if (animation) {+ const fade = typeof data.fadeInTime === 'number' ? data.fadeInTime : 0;+ const loop = data.loop !== false;+ // fadeInTime is what this component has instead of Spine's mix+ // table, so an authored fade belongs to the FIRST play too.+ if (fade > 0) manager.fadeIn(entity, animation, fade, loop);+ else manager.play(entity, animation, loop);+ }}}+ } finally {+ for (const key of touched) manager.discardUnboundSkeleton(key);+ releaseUnusedAtlases(assetInfo.values());}}diff --git a/sdk/tests/dragonbones-manager.integration.test.ts b/sdk/tests/dragonbones-manager.integration.test.tsindex b02ccbeba..48d211a0b 100644--- a/sdk/tests/dragonbones-manager.integration.test.ts+++ b/sdk/tests/dragonbones-manager.integration.test.ts@@ -6,7 +6,7 @@// stops doing — and every one of those fails quietly: a leak shows up as memory,// a double free as a crash three frames later, a missed disable as a thing that// keeps animating. So they are asserted, not eyeballed.-import { describe, it, expect, beforeAll } from 'vitest';+import { describe, it, expect, beforeAll, vi } from 'vitest';import { existsSync, readFileSync } from 'node:fs';import { resolve } from 'node:path';import { WASM_DIR, hasSideModule } from './helpers/loadWasm';@@ -14,6 +14,7 @@ import { DragonBonesManager } from '../src/dragonbones/DragonBonesManager';import { DragonBonesModuleController } from '../src/dragonbones/DragonBonesController';import { wrapDragonBonesModule, type DragonBonesWasmModule } from '../src/dragonbones/DragonBonesModuleLoader';import type { Entity } from '../src/types';+import { ownAtlas, bindAtlasOwner } from '../src/dragonbones/atlasOwnership';const DB_JS = resolve(WASM_DIR, 'dragonbones.js');const DB_WASM = resolve(WASM_DIR, 'dragonbones.wasm');@@ -40,6 +41,31 @@ describe.skipIf(!HAS_ASSETS)('DragonBonesManager', () => {const load = (m: DragonBonesManager, key?: string): number =>m.loadSkeleton(new Uint8Array(readFileSync(SKE)), readFileSync(TEX, 'utf8'), key);+ it('releases a shared atlas only after its last instance is removed', () => {+ const m = fresh(), handle = load(m, 'shared-atlas'), info = {}, release = vi.fn();+ ownAtlas(info, release); bindAtlasOwner(info, m, handle);+ expect(m.addEntity(e(101), handle, { armature: 'Dragon', assetKey: 'shared-atlas' })).toBe(true);+ expect(m.addEntity(e(102), handle, { armature: 'Dragon', assetKey: 'shared-atlas' })).toBe(true);+ m.removeEntity(e(101)); expect(release).not.toHaveBeenCalled();+ m.removeEntity(e(102)); expect(release).toHaveBeenCalledOnce();+ m.dispose(); expect(release).toHaveBeenCalledOnce();+ });+ it('replacement releases the old atlas and disposal releases the current one once', () => {+ const m = fresh(), handle = load(m, 'replace-atlas'), old = vi.fn(), next = vi.fn();+ const first = {}, second = {};+ ownAtlas(first, old); bindAtlasOwner(first, m, handle);+ ownAtlas(second, next); bindAtlasOwner(second, m, handle);+ expect(old).toHaveBeenCalledOnce(); expect(next).not.toHaveBeenCalled();+ m.dispose(); m.dispose(); expect(next).toHaveBeenCalledOnce();+ });+ it('a refused armature releases its otherwise unbound skeleton and atlas', () => {+ const m = fresh(), handle = load(m, 'refused'), info = {}, release = vi.fn();+ ownAtlas(info, release); bindAtlasOwner(info, m, handle);+ expect(m.addEntity(e(103), handle, { armature: 'missing', assetKey: 'refused' })).toBe(false);+ m.discardUnboundSkeleton('refused'); expect(release).toHaveBeenCalledOnce();+ m.dispose(); expect(release).toHaveBeenCalledOnce();+ });+it('parses a keyed file once, however many entities want it', () => {manager = fresh();const first = load(manager, 'dragonboy');diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex bc9f43e7e..a4d891704 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(dragonbones): release atlas pages with their skeleton owners':+ { note: 'DragonBones atlas textures follow skeleton ownership.' },'fix(scene): roll back entities after publication failures':{ note: 'Late scene-load errors roll back the new entities.' },'fix(prefab): roll back prepared spawns on parent rejection':