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(prefab): roll back prepared spawns on parent rejection
yhh2065c0c1cb08
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ec5e2ba66..62141d5fc 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,8 @@ published separately; it ships inside the editor.### Fixed+- **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.+- **Standalone scene and prefab spawns release their resources.** Loads without a scene collector transfer acquired resources to the entities that reference them, then release the preload receipts. Destroying or rolling back a spawned hierarchy retires those acquisitions. Prefab document reads also use scoped receipts, including nested sources, so repeated spawns no longer accumulate unowned references.- **Prefab spawns roll back when their parent disappears.** Runtime instantiation checks that its requested parent accepts the root after asynchronous loading. A rejected attachment despawns the newly created hierarchy and rejects the spawn instead of leaving an unparented instance behind; live parents and the explicit no-parent sentinel remain supported.diff --git a/sdk/src/prefab/preparedPrefab.ts b/sdk/src/prefab/preparedPrefab.tsindex feb0ef37d..69df30f60 100644--- a/sdk/src/prefab/preparedPrefab.ts+++ b/sdk/src/prefab/preparedPrefab.ts@@ -116,6 +116,7 @@ export async function preparePrefabFromSource(}export interface SpawnPreparedOptions {+ /** A rejected parent attachment rolls back the spawned hierarchy. */parent?: Entity;/** Where the root lands. Absent leaves the prefab's own transform. */position?: { x: number; y: number; z?: number };@@ -139,7 +140,9 @@ export function spawnPrepared(ownership?.attach(world, entities);prepared.trackSpawnReferences?.(entities);const root = entities.get(prepared.rootId)!;- if (options?.parent !== undefined) world.setParent(root, options.parent);+ if (options?.parent !== undefined && !world.trySetParent(root, options.parent)) {+ throw new Error(`Prepared prefab "${prepared.scene.name}" could not attach to parent ${options.parent}`);+ }if (options?.position) {// Transform is C++-backed, so the read is a copy: change it and hand it back.const transform = world.get(root, Transform);diff --git a/sdk/tests/prepared-parent-resource-wasm.test.ts b/sdk/tests/prepared-parent-resource-wasm.test.tsnew file mode 100644index 000000000..efe63c4c2--- /dev/null+++ b/sdk/tests/prepared-parent-resource-wasm.test.ts@@ -0,0 +1,50 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { beforeAll, describe, expect, it, vi } from 'vitest';+import { Assets } from '../src/asset/Assets';+import type { Backend } from '../src/asset/Backend';+import { World } from '../src/ecs/world';+import { spawnPrepared } from '../src/prefab/preparedPrefab';+import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';+import type { ESEngineModule } from '../src/wasm';++vi.mock('../src/wasm/resourceManager', () => ({+ requireResourceManager: () => ({ releaseTexture: vi.fn(), invalidateTexturePath: () => false }),+ getResourceManager: () => null, evictTextureDimensions: vi.fn(),+}));++describe.skipIf(!HAS_WASM)('prepared parent rejection releases real asset leases', () => {+ let engine: ESEngineModule;+ beforeAll(async () => { engine = await loadWasmModule(); });+ it('preserves preparation ownership while releasing every failed spawned copy', async () => {+ const registry = new engine.Registry(), world = new World(); world.connectCpp(registry, engine);+ const unloaded = vi.fn();+ const prefab = { version: '2', name: 'owned', rootEntityId: 'root', entities: [+ { prefabEntityId: 'root', name: 'root', parent: null, children: [], visible: true,+ components: [{ type: 'MeshRenderer', data: { mesh: 'mesh.esmesh' } }] },+ ] };+ const assets = Assets.create({ module: engine, backend: {+ fetchBinary: async () => new ArrayBuffer(8), fetchText: async () => JSON.stringify(prefab),+ resolveUrl: (path: string) => `http://test/${path}`,+ } as Backend });+ assets.register<{ handle: number }>({ type: 'mesh', load: async () => ({ handle: 1 }), unload: unloaded } as never);+ try {+ const prepared = await assets.preparePrefab('root.esprefab');+ const before = assets.sizes().refRows;+ for (let i = 0; i < 20; i++) {+ const parent = world.spawn(); world.despawn(parent);+ expect(() => spawnPrepared(world, prepared, { parent })).toThrow(/parent/);+ expect(world.getAllEntities()).toHaveLength(0);+ expect(assets.sizes().refRows).toBe(before);+ }+ expect(unloaded).not.toHaveBeenCalled();+ const live = spawnPrepared(world, prepared);+ expect(assets.sizes().refRows).toBeGreaterThan(before);+ world.despawn(live.root);+ expect(assets.sizes().refRows).toBe(before);+ prepared.release();+ expect(assets.sizes()).toMatchObject({ refRows: 0, registrySlots: 0, trackedRefRows: 0 });+ expect(unloaded).toHaveBeenCalledOnce();+ } finally { assets.releaseAll(); for (const entity of world.getAllEntities()) world.despawn(entity); registry.delete(); }+ });+});diff --git a/sdk/tests/prepared-prefab.test.ts b/sdk/tests/prepared-prefab.test.tsindex 13b12f6d6..f12cd83af 100644--- a/sdk/tests/prepared-prefab.test.ts+++ b/sdk/tests/prepared-prefab.test.ts@@ -8,6 +8,7 @@ import { instantiatePrefab, type PrefabData } from '../src/prefab';import type { Assets } from '../src/asset/Assets';import { HAS_WASM, loadWasmModule } from './helpers/loadWasm';import type { ESEngineModule, CppRegistry } from '../src/wasm';+import { INVALID_ENTITY } from '../src/types';const leaf = (name: string): PrefabData => ({ version: '2', name, rootEntityId: 'root', entities: [{ prefabEntityId: 'root', name, parent: null, children: [], visible: true,@@ -89,4 +90,31 @@ describe.skipIf(!HAS_WASM)('prepared prefabs use the same dependency graph as asawait expect(preparePrefab(assets, 'root')).rejects.toThrow(/Circular reference/);expect(load.mock.calls.length).toBeLessThanOrEqual(2);});+ it('rolls back a prepared hierarchy when its parent no longer exists', async () => {+ const source = leaf('root'); source.entities[0].children = ['child'];+ source.entities.push({ ...leaf('child').entities[0], prefabEntityId: 'child', parent: 'root' });+ const { assets } = assetsFor({ root: source });+ const prepared = await preparePrefab(assets, 'root');+ const w = world();+ try {+ const parent = w.spawn(); w.despawn(parent);+ expect(() => spawnPrepared(w, prepared, { parent })).toThrow(/parent/);+ expect(w.getAllEntities()).toHaveLength(0);+ } finally { for (const e of w.getAllEntities()) if (w.valid(e)) w.despawn(e); prepared.release(); }+ });+ it('supports live parents, position overrides and an explicit unparented spawn', async () => {+ const { assets } = assetsFor({ root: leaf('root') });+ const prepared = await preparePrefab(assets, 'root'), w = world();+ try {+ const parent = w.spawn();+ const child = spawnPrepared(w, prepared, { parent, position: { x: 90, y: 80 } });+ expect(w.get(child.root, Parent).entity).toBe(parent);+ expect(w.get(child.root, Transform).position).toEqual({ x: 90, y: 80, z: 0 });+ const standalone = spawnPrepared(w, prepared, { parent: INVALID_ENTITY });+ expect(w.has(standalone.root, Parent)).toBe(false);+ w.despawn(parent);+ expect(w.valid(child.root)).toBe(false);+ expect(w.valid(standalone.root)).toBe(true);+ } finally { for (const e of w.getAllEntities()) if (w.valid(e)) w.despawn(e); prepared.release(); }+ });});diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex d1ebe768c..f5efb08b1 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(prefab): roll back prepared spawns on parent rejection':+ { note: 'Prepared prefab spawns reject failed parent attachments.' },'fix(asset): transfer standalone spawn resources to entity owners':{ note: 'Standalone scene and prefab spawns release their resources.' },'fix(prefab): roll back spawns when parent attachment fails':