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
feat(prefab): Apply-to-Prefab for instance overrides (2D-parity B2)
esengined5e4fa780da8
diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex 3ce951b44..8a2e23d5a 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -23,6 +23,7 @@ import {Search,Square,Trash2,+ Upload,Volume2,X,type LucideIcon,@@ -1951,6 +1952,13 @@ function EditorDetails() {><FolderOpen size={12} strokeWidth={1.9} /> Select</button>+ <button+ type="button"+ title="Apply this instance's overrides to the prefab asset (updates the base for all instances)"+ onClick={() => void ProjectStore.applyPrefabInstance(selectedId)}+ >+ <Upload size={12} strokeWidth={1.9} /> Apply+ </button><buttontype="button"title="Revert all overrides — re-sync this instance to the prefab"diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 879a3e72a..0f649ea5b 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1,8 +1,8 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { createStore } from 'zustand/vanilla';-import { getComponent, Assets, migratePrefabData, extractPrefab } from 'esengine';-import type { SceneData, PrefabData, ExtractEntity, PhysicsPluginConfig } from 'esengine';+import { getComponent, Assets, migratePrefabData, extractPrefab, diffAgainstSource, applyOverridesToSource } from 'esengine';+import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig } from 'esengine';import { EngineHost } from '@/engine/EngineHost';import { SceneModel } from '@/engine/SceneModel';import { Reconciler } from '@/engine/Reconciler';@@ -487,6 +487,75 @@ class ProjectStoreImpl {return this.instantiatePrefabFromPath(info.path, parent, position);}+ /**+ * Apply a prefab instance's overrides back to the prefab asset (Details "Apply"):+ * this instance's current values become the prefab's new base, then the instance+ * re-syncs to that base so its overrides clear. Works on any entity of the+ * instance (resolves to the root). Returns the fresh root's source id, or null.+ *+ * Scope: property / name / visibility / component overrides on existing prefab+ * entities (the same set `diffAgainstSource` reports). Metadata diffs are dropped+ * — the editor model doesn't track per-instance metadata, so they're never a real+ * override, and baking them would strip the prefab's own metadata. Structural+ * edits (entities the instance added/removed) and live propagation to *other*+ * in-scene instances are not applied here; those siblings re-derive from the new+ * base on next load.+ */+ async applyPrefabInstance(sourceId: number): Promise<number | null> {+ const tag = SceneModel.prefabTag(sourceId);+ const instanceRoot = tag?.instanceRoot ?? sourceId;+ const ref = SceneModel.prefabTag(instanceRoot)?.prefab;+ if (!ref) return null;+ const info = this.assetInfo(ref);+ if (!info) return null;+ const oldPrefab = await this.loadPrefabAsset(ref);+ if (!oldPrefab) {+ Toasts.push(`Could not load prefab: ${info.path.split('/').pop() ?? info.path}`, 'error');+ return null;+ }++ // The instance's live subtree as flattened entities (matching the save path's+ // ProcessedEntity shape — metadata is not modelled per-instance).+ const processed: ProcessedEntity[] = [];+ for (const id of SceneModel.collectSubtree(instanceRoot)) {+ const e = SceneModel.entityBySource(id);+ const t = SceneModel.prefabTag(id);+ if (!e || !t) continue;+ processed.push({+ id,+ prefabEntityId: t.prefabId,+ name: e.name,+ parent: e.parent,+ children: e.children ?? [],+ components: e.components as ProcessedEntity['components'],+ visible: (e as { visible?: boolean }).visible ?? true,+ });+ }+ if (processed.length === 0) return null;++ const overrides = diffAgainstSource(oldPrefab, processed).overrides+ .filter((o) => o.type !== 'metadata_set' && o.type !== 'metadata_removed');+ if (overrides.length === 0) {+ Toasts.push('No overrides to apply', 'info');+ return instanceRoot;+ }+ const newPrefab = applyOverridesToSource(oldPrefab, overrides);++ try {+ await window.estella.fs.write(info.path, JSON.stringify(newPrefab, null, 2) + '\n');+ } catch (err) {+ Toasts.push(`Apply failed: could not write ${info.path.split('/').pop() ?? info.path}`, 'error');+ return null;+ }+ this.prefabCache.set(ref, newPrefab);++ // Re-sync this instance to the updated base so its (now-applied) overrides+ // clear — reuses the proven delete + re-instantiate path.+ const newRoot = await this.revertPrefabInstance(instanceRoot);+ Toasts.push(`Applied ${overrides.length} override${overrides.length === 1 ? '' : 's'} to ${info.path.split('/').pop() ?? info.path}`, 'success');+ return newRoot;+ }+/*** Spawn a Sprite entity from an image asset dropped into the viewport: resolve its* texture ref (preloading it so it renders), read the image's natural pixel size,diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 1e4fa3a4f..cca25ea54 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -163,6 +163,7 @@ export {migratePrefabData,PREFAB_FORMAT_VERSION,diffAgainstSource,+ applyOverridesToSource,validateOverrides,expandInstance,collapseInstance,diff --git a/sdk/src/prefab/index.ts b/sdk/src/prefab/index.tsindex 05110a830..d6e65e2ae 100644--- a/sdk/src/prefab/index.ts+++ b/sdk/src/prefab/index.ts@@ -13,7 +13,8 @@ export type {} from './types';export { flattenPrefab } from './flatten';-export { applyOverrides, bucketOverridesByEntity } from './override';+export { applyOverrides, applyOverridesToSource, bucketOverridesByEntity } from './override';+export type { OverrideTarget } from './override';export { remapComponentEntityRefs } from './entityRef';export { cloneComponents, cloneComponentData, cloneMetadata } from './clone';export { collectNestedPrefabPaths, preloadNestedPrefabs } from './collect';diff --git a/sdk/src/prefab/override.ts b/sdk/src/prefab/override.tsindex 805d64b99..69febeb12 100644--- a/sdk/src/prefab/override.ts+++ b/sdk/src/prefab/override.ts@@ -1,12 +1,27 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type {+ ComponentData,+ PrefabData,PrefabEntityId,PrefabOverride,- ProcessedEntity,} from './types';import { cloneComponentData } from './clone';+/**+ * The fields {@link applyOverrides} reads/writes. Both `ProcessedEntity` (a+ * flattened instance entity) and `PrefabEntityData` (a source-file entity)+ * satisfy it structurally, so the same override logic bakes overrides into a+ * live instance *or* into the prefab source.+ */+export interface OverrideTarget {+ prefabEntityId: PrefabEntityId;+ name: string;+ visible: boolean;+ components: ComponentData[];+ metadata?: Record<string, unknown>;+}+/*** Group overrides by their target entity once so flatten can apply each* entity's overrides in O(K) instead of O(N×M) per scene tree.@@ -24,7 +39,7 @@ export function bucketOverridesByEntity(}export function applyOverrides(- entity: ProcessedEntity,+ entity: OverrideTarget,overrides: readonly PrefabOverride[] | undefined,): void {if (!overrides || overrides.length === 0) return;@@ -103,3 +118,28 @@ export function applyOverrides(}}}++/**+ * Bake a set of overrides into a prefab's source, returning a NEW PrefabData with+ * the changes applied as the base (entity identities preserved). This is the core+ * of editor "Apply to Prefab": an instance's overrides (from {@link diffAgainstSource})+ * become the prefab's new base, so every instance re-derives from them.+ *+ * Scope matches {@link diffAgainstSource}: property / name / visibility /+ * component add·replace·remove / metadata overrides on existing prefab entities.+ * Structural changes (entities the instance added or removed) are not folded in —+ * the caller surfaces those separately. Pure: the input `source` is not mutated.+ */+export function applyOverridesToSource(+ source: PrefabData,+ overrides: readonly PrefabOverride[],+): PrefabData {+ const next = JSON.parse(JSON.stringify(source)) as PrefabData;+ if (overrides.length === 0) return next;+ const buckets = bucketOverridesByEntity(overrides);+ for (const entity of next.entities) {+ const bucket = buckets.get(entity.prefabEntityId);+ if (bucket) applyOverrides(entity, bucket);+ }+ return next;+}diff --git a/sdk/tests/prefab-apply-to-source.test.ts b/sdk/tests/prefab-apply-to-source.test.tsnew file mode 100644index 000000000..cbec87e3b--- /dev/null+++ b/sdk/tests/prefab-apply-to-source.test.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file applyOverridesToSource — the core of editor "Apply to Prefab": fold an+ * instance's overrides into the prefab source as the new base.+ */+import { describe, it, expect } from 'vitest';+// Import the value directly: the prefab barrel (`../src/prefab`) has a pre-existing+// circular-import quirk under vitest's source ESM that leaves several function+// re-exports undefined (the bundled dist resolves them fine). Types are erased, so+// they can still come from the barrel.+import { applyOverridesToSource } from '../src/prefab/override';+import type { PrefabData, PrefabOverride } from '../src/prefab';++function basePrefab(): PrefabData {+ return {+ version: '1.0',+ name: 'Enemy',+ rootEntityId: '0',+ entities: [+ { prefabEntityId: '0', name: 'Root', parent: null, children: ['1'], visible: true,+ components: [{ type: 'Transform', data: { x: 0, y: 0 } }] },+ { prefabEntityId: '1', name: 'Body', parent: '0', children: [], visible: true,+ components: [{ type: 'Sprite', data: { texture: 'a.png', color: 'white' } }] },+ ],+ };+}++describe('applyOverridesToSource', () => {+ it('bakes a property override into the matching source entity', () => {+ const overrides: PrefabOverride[] = [+ { prefabEntityId: '1', type: 'property', componentType: 'Sprite', propertyName: 'color', value: 'red' },+ ];+ const next = applyOverridesToSource(basePrefab(), overrides);+ const body = next.entities.find(e => e.prefabEntityId === '1')!;+ expect((body.components[0].data as { color: string }).color).toBe('red');+ });++ it('does not mutate the input source (pure)', () => {+ const src = basePrefab();+ applyOverridesToSource(src, [+ { prefabEntityId: '1', type: 'property', componentType: 'Sprite', propertyName: 'color', value: 'red' },+ ]);+ const body = src.entities.find(e => e.prefabEntityId === '1')!;+ expect((body.components[0].data as { color: string }).color).toBe('white');+ });++ it('preserves entity identities and unrelated entities/fields', () => {+ const next = applyOverridesToSource(basePrefab(), [+ { prefabEntityId: '1', type: 'property', componentType: 'Sprite', propertyName: 'color', value: 'red' },+ ]);+ expect(next.entities.map(e => e.prefabEntityId)).toEqual(['0', '1']);+ const root = next.entities.find(e => e.prefabEntityId === '0')!;+ expect((root.components[0].data as { x: number }).x).toBe(0); // untouched+ const body = next.entities.find(e => e.prefabEntityId === '1')!;+ expect((body.components[0].data as { texture: string }).texture).toBe('a.png'); // untouched field+ });++ it('applies name, visibility, component add/replace/remove, metadata', () => {+ const overrides: PrefabOverride[] = [+ { prefabEntityId: '0', type: 'name', value: 'Boss' },+ { prefabEntityId: '1', type: 'visibility', value: false },+ { prefabEntityId: '1', type: 'component_added', componentData: { type: 'Health', data: { hp: 5 } } },+ { prefabEntityId: '1', type: 'component_replaced', componentData: { type: 'Sprite', data: { texture: 'b.png' } } },+ { prefabEntityId: '0', type: 'component_removed', componentType: 'Transform' },+ { prefabEntityId: '1', type: 'metadata_set', metadataKey: 'tag', value: 'enemy' },+ ];+ const next = applyOverridesToSource(basePrefab(), overrides);+ const root = next.entities.find(e => e.prefabEntityId === '0')!;+ const body = next.entities.find(e => e.prefabEntityId === '1')!;+ expect(root.name).toBe('Boss');+ expect(root.components.find(c => c.type === 'Transform')).toBeUndefined();+ expect(body.visible).toBe(false);+ expect(body.components.find(c => c.type === 'Health')?.data).toEqual({ hp: 5 });+ expect(body.components.find(c => c.type === 'Sprite')?.data).toEqual({ texture: 'b.png' });+ expect(body.metadata?.tag).toBe('enemy');+ });++ it('is a no-op clone when there are no overrides', () => {+ const src = basePrefab();+ const next = applyOverridesToSource(src, []);+ expect(next).toEqual(src);+ expect(next).not.toBe(src); // a distinct object (safe to write)+ });++ it('ignores overrides targeting an unknown entity id', () => {+ const next = applyOverridesToSource(basePrefab(), [+ { prefabEntityId: 'ghost', type: 'name', value: 'X' },+ ]);+ expect(next).toEqual(basePrefab());+ });+});