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): Create Variant from an instance + unified variant/nested resolution (P2 UX)
yhhcdb08b0ecbf4
diff --git a/desktop/src/engine/PrefabInstance.ts b/desktop/src/engine/PrefabInstance.tsindex da0b55828..0156654a6 100644--- a/desktop/src/engine/PrefabInstance.ts+++ b/desktop/src/engine/PrefabInstance.ts@@ -49,6 +49,33 @@ export interface InstanceTag {type LoadPrefab = (ref: string) => Promise<PrefabData | null>;+/**+ * A LOCAL prefab snapshot for one whole-scene expand/collapse pass: `warm(ref)`+ * loads a prefab plus its transitive variant bases / nested refs into an owned+ * map; `resolve(ref)` reads that map SYNChronously (what flattenPrefab needs for+ * variant / nested expansion). The map is local — NOT the shared ProjectStore+ * cache — so a concurrent asset revalidation that clears that cache mid-pass+ * can't pull a variant's base out from under an in-flight flatten.+ */+function prefabSnapshot(loadPrefab: LoadPrefab): {+ warm: (ref: string) => Promise<void>;+ resolve: (ref: string) => PrefabData | null;+} {+ const map = new Map<string, PrefabData>();+ const warm = async (ref: string): Promise<void> => {+ if (map.has(ref)) return;+ const p = await loadPrefab(ref);+ if (!p) return;+ map.set(ref, p);+ if (p.basePrefab) await warm(p.basePrefab);+ for (const e of p.entities) {+ const nested = e.nestedPrefab?.prefabPath;+ if (nested) await warm(nested);+ }+ };+ return { warm, resolve: (ref) => map.get(ref) ?? null };+}+/** A prefab-instance entry as it appears in a scene file (carries a `prefab` ref). */function isPrefabEntry(e: unknown): e is PrefabInstanceEntry {return !!e && typeof e === 'object' && typeof (e as { prefab?: unknown }).prefab === 'string';@@ -77,6 +104,7 @@ export async function expandScenePrefabs(loadPrefab: LoadPrefab,allocateId: () => number,): Promise<{ scene: SceneData; tags: Array<{ id: number; tag: InstanceTag }> }> {+ const snap = prefabSnapshot(loadPrefab);const out: SceneEntity[] = [];const tags: Array<{ id: number; tag: InstanceTag }> = [];for (const raw of scene.entities as unknown[]) {@@ -84,9 +112,11 @@ export async function expandScenePrefabs(out.push(raw as SceneEntity);continue;}- const prefab = await loadPrefab(raw.prefab);+ await snap.warm(raw.prefab); // load the instance prefab + all its deps into the local snapshot+ const prefab = snap.resolve(raw.prefab);if (!prefab) continue; // unresolved prefab — skip (caller warns)- const { entities, rootId } = expandEntry(prefab, raw, allocateId);+ // expandEntry resolves variant bases / nested refs SYNChronously from the snapshot.+ const { entities, rootId } = expandEntry(prefab, raw, allocateId, snap.resolve);for (const pe of entities) {const se = toSceneEntity(pe);// The instance entry carries the outliner folder of its root (editor-only,@@ -115,6 +145,7 @@ export async function collapseScenePrefabs(tagOf: (id: number) => InstanceTag | undefined,loadPrefab: LoadPrefab,): Promise<SceneEntity[]> {+ const snap = prefabSnapshot(loadPrefab);const groups = new Map<number, SceneEntity[]>();const out: SceneEntity[] = [];for (const e of entities) {@@ -130,13 +161,16 @@ export async function collapseScenePrefabs(for (const [rootId, group] of groups) {const rootTag = tagOf(rootId);const root = group.find((e) => e.id === rootId);- const prefab = rootTag?.prefab ? await loadPrefab(rootTag.prefab) : null;+ if (rootTag?.prefab) await snap.warm(rootTag.prefab);+ const prefab = rootTag?.prefab ? snap.resolve(rootTag.prefab) : null;if (!rootTag?.prefab || !prefab || !root) {out.push(...group); // not a resolvable instance — keep raw (lossless)continue;}const processed = group.map((e) => toProcessed(e, tagOf(e.id)!.prefabId));- const entry = collapseEntry(prefab, rootTag.prefab, processed, rootId, root.parent ?? null) as unknown as SceneEntity;+ // collapseEntry re-flattens the prefab for its baseline; the resolver expands+ // a variant base / nested refs so a variant instance round-trips on save.+ const entry = collapseEntry(prefab, rootTag.prefab, processed, rootId, root.parent ?? null, snap.resolve) as unknown as SceneEntity;// Carry the instance root's outliner folder onto the collapsed entry (lossless).const folder = (root as { folder?: string }).folder;if (folder) (entry as { folder?: string }).folder = folder;diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex a41282e4b..178c6d548 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team-import type { SceneData, PrefabData, ControllerState, UIControllerData, GearBinding, GearTween, UIGearData } from 'esengine';+import type { SceneData, PrefabData, ControllerState, UIControllerData, GearBinding, GearTween, UIGearData, SyncPrefabResolver } from 'esengine';import { TilemapAPI, TilemapLiveSync, UIPositionType, DimensionUnit, AnchorAxis, writeFieldPath, type AnchorPreset } from 'esengine';import type { EntityId, InspectorFieldType, InspectorFieldValue } from '@/types';import { EditorHistory, EditorHistoryImpl } from './EditorHistory';@@ -172,6 +172,17 @@ export class SceneCommandsImpl {private readonly history: EditorHistoryImpl,) {}+ /** Resolves a prefab ref → PrefabData SYNChronously for variant / nested+ * expansion when instantiating (ProjectStore installs a warm-cache reader).+ * Default no-op = flat prefabs only, matching the pre-plumbing behaviour. */+ private prefabResolver: SyncPrefabResolver = () => null;++ /** Install the synchronous prefab resolver used by {@link create} so an+ * instantiated variant / nested prefab resolves its base like the load path. */+ setPrefabResolver(fn: SyncPrefabResolver): void {+ this.prefabResolver = fn;+ }+/** Register a field-edit hook; returns the unsubscribe. */addEditHook(fn: EditHook): () => void {this.editHooks.add(fn);@@ -753,6 +764,7 @@ export class SceneCommandsImpl {prefab,{ prefab: ref, overrides: [], added: [], removed: [] },() => this.model.allocateSourceId(),+ this.prefabResolver,);const root = entities.find((e) => e.id === rootId);if (!root) return null;diff --git a/desktop/src/i18n/messages/outliner.ts b/desktop/src/i18n/messages/outliner.tsindex 786816003..4a3110c1c 100644--- a/desktop/src/i18n/messages/outliner.ts+++ b/desktop/src/i18n/messages/outliner.ts@@ -51,6 +51,7 @@ export const outlinerMessages = defineMessages({'out.prefabSelectSource': { en: 'Select Prefab Source', zh: '选中预制体源' },'out.prefabApply': { en: 'Apply to Prefab', zh: '应用到预制体' },'out.prefabRevert': { en: 'Revert to Prefab', zh: '还原为预制体' },+ 'out.prefabCreateVariant': { en: 'Create Variant', zh: '创建变体' },'out.prefabUnpack': { en: 'Unpack Prefab', zh: '解包预制体' },'out.hide': { en: 'Hide', zh: '隐藏' },'out.show': { en: 'Show', zh: '显示' },diff --git a/desktop/src/i18n/messages/project.ts b/desktop/src/i18n/messages/project.tsindex 23aaeb634..e5fbb7290 100644--- a/desktop/src/i18n/messages/project.ts+++ b/desktop/src/i18n/messages/project.ts@@ -130,6 +130,8 @@ export const projectMessages = defineMessages({'proj.resaveFailed': { en: 'Re-saved {upgraded}, {failed} failed', zh: '已重新保存 {upgraded} 个,{failed} 个失败' },'proj.prefabCreateFailed': { en: 'Failed to create prefab: {name}', zh: '创建预制体失败:{name}' },'proj.prefabCreated': { en: 'Created prefab: {name}', zh: '已创建预制体:{name}' },+ 'proj.variantCreated': { en: 'Created variant {name}', zh: '已创建变体 {name}' },+ 'proj.variantNoRemove': { en: "Variant can't remove base entities — {count} removal(s) dropped", zh: '变体无法删除基础实体——已忽略 {count} 处删除' },'proj.saveSortingLayersFailed': { en: 'Failed to save sorting layers', zh: '保存排序层失败' },'proj.saveDesignResolutionFailed': { en: 'Failed to save design resolution', zh: '保存设计分辨率失败' },'proj.savePackagingFailed': { en: 'Failed to save packaging settings', zh: '保存打包设置失败' },diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex 8b8abcfc8..aa67f10ba 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -104,6 +104,7 @@ function prefabInstanceItems(id: number): MenuItem[] {},{ label: t('out.prefabApply'), onClick: () => void ProjectStore.applyPrefabInstance(id) },{ label: t('out.prefabRevert'), onClick: () => void ProjectStore.revertPrefabInstance(id) },+ { label: t('out.prefabCreateVariant'), onClick: () => void ProjectStore.createVariantFromInstance(id) },{ label: t('out.prefabUnpack'), onClick: () => SceneCommands.unpackPrefabInstance(id) },];}diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex b7200b2ba..f7b278b8e 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { createStore } from 'zustand/vanilla';-import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides } from 'esengine';+import { getComponent, getEditorType, Assets, migratePrefabData, extractPrefab, flattenPrefab, collectExternalEntityRefs, collapseInstance, applyDeltaToSource, buildVariant, setTextureParams, TextureFilter, TextureWrap, Renderer, RETIRED_COMPONENT_TYPES, parseThemeOverrides } from 'esengine';import { readTextureImportSettings } from './assetImporter';import type { SceneData, PrefabData, ExtractEntity, ProcessedEntity, PhysicsPluginConfig, AudioProjectConfig, AssetsData, ThemeOverrides } from 'esengine';import { EngineHost } from '@/engine/EngineHost';@@ -265,6 +265,9 @@ class ProjectStoreImpl {// Diagnostics ask the registry whether a model-healthy asset ref actually// names a real, loadable asset (dead refs draw white boxes in silence).setAssetRefProblemResolver((ref) => this.assetRefProblem(ref));+ // Instantiating a variant / nested prefab resolves its base through the same+ // warm-cache reader the scene-load path uses (one resolution truth).+ SceneCommands.setPrefabResolver(this.prefabResolverSync);}/** Read accessor so existing `this.state` reads stay unchanged after the move. */@@ -904,7 +907,9 @@ class ProjectStoreImpl {}/** Load a `.esprefab` asset (PrefabData) by ref, cached. The scene load-expand- * / save-collapse path resolves prefab instances through this. */+ * / save-collapse path resolves prefab instances through this. Warms the+ * prefab's base (variant) + nested refs into the cache too, so the SYNChronous+ * flatten resolver ({@link prefabResolverSync}) can resolve them. */private async loadPrefabAsset(ref: string): Promise<PrefabData | null> {if (!ref.startsWith(UUID_PREFIX)) return null;const cached = this.prefabCache.get(ref);@@ -913,7 +918,10 @@ class ProjectStoreImpl {if (!path) return null;try {const prefab = migratePrefabData(JSON.parse(await window.estella.fs.read(path))).data as PrefabData;+ // Cache BEFORE warming deps so a variant/nested ref CYCLE terminates (the+ // second visit hits the cache and returns instead of re-fetching forever).this.prefabCache.set(ref, prefab);+ await this.warmPrefabDeps(prefab);return prefab;} catch (err) {console.warn('[project] prefab load failed', path, err);@@ -921,6 +929,23 @@ class ProjectStoreImpl {}}+ /** Recursively load a prefab's base (variant `basePrefab`) + every entity's+ * `nestedPrefab` ref into the cache. flattenPrefab resolves those SYNChronously+ * during expansion, so they must already be resident. */+ private async warmPrefabDeps(prefab: PrefabData): Promise<void> {+ if (prefab.basePrefab) await this.loadPrefabAsset(prefab.basePrefab);+ for (const e of prefab.entities) {+ const nested = e.nestedPrefab?.prefabPath;+ if (nested) await this.loadPrefabAsset(nested);+ }+ }++ /** Synchronous prefab resolver for flattenPrefab's variant / nested expansion —+ * a cache read (the async {@link loadPrefabAsset} pre-warms every dependency).+ * Installed on the scene-load + instantiate paths so a variant / nested+ * instance resolves its base the same way in both. */+ private prefabResolverSync = (ref: string): PrefabData | null => this.prefabCache.get(ref) ?? null;+/*** Instantiate a `.esprefab` (by project-relative path) into the open scene* under `parent`, optionally placed at `position` (world coords). Selects the@@ -1070,7 +1095,7 @@ class ProjectStoreImpl {if (processed.length === 0) return null;// The full delta against the asset: property overrides + structural edits.- const delta = collapseInstance(oldPrefab, ref, processed);+ const delta = collapseInstance(oldPrefab, ref, processed, this.prefabResolverSync);const overrides = delta.overrides.filter((o) => o.type !== 'metadata_set' && o.type !== 'metadata_removed');const { added, removed } = delta;@@ -1119,6 +1144,83 @@ class ProjectStoreImpl {return newRoot;}+ /**+ * Create a prefab VARIANT from a prefab instance (Outliner "Create Variant" —+ * Unity's "Create Prefab Variant"): write a new `.esprefab` that inherits the+ * instance's prefab and bakes the instance's current overrides + added entities+ * as the variant's own authored state, then re-link the scene instance to the+ * new variant (so its edits now live in the variant, tracked against the base).+ * Works on any entity of the instance. Returns the re-linked root's source id.+ *+ * Removals aren't representable in a variant (it extends its base — see+ * {@link buildVariant}); if the instance deleted base entities, those drops are+ * reported and skipped. Structural/undo caveats match Apply/Revert (the written+ * asset persists; the re-link is two undo steps).+ */+ async createVariantFromInstance(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 base = await this.loadPrefabAsset(ref);+ if (!base) {+ Toasts.push(t('proj.prefabLoadFailed', { name: info.path.split('/').pop() ?? info.path }), 'error');+ return null;+ }++ // The instance's live subtree → its delta vs the current prefab (same shape+ // Apply uses). Metadata diffs aren't real overrides (not modelled per-instance).+ const processed: ProcessedEntity[] = [];+ for (const id of SceneModel.collectSubtree(instanceRoot)) {+ const e = SceneModel.entityBySource(id);+ const et = SceneModel.prefabTag(id);+ if (!e || !et) continue;+ processed.push({+ id,+ prefabEntityId: et.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 delta = collapseInstance(base, ref, processed, this.prefabResolverSync);+ const overrides = delta.overrides.filter((o) => o.type !== 'metadata_set' && o.type !== 'metadata_removed');+ if (delta.removed.length > 0) {+ Toasts.push(t('proj.variantNoRemove', { count: delta.removed.length }), 'warn');+ }++ // Write the variant beside its base, name derived from the base file.+ const baseLeaf = (info.path.split('/').pop() ?? base.name).replace(/\.esprefab$/i, '');+ const variantName = `${baseLeaf} Variant`;+ const dir = info.path.includes('/') ? info.path.slice(0, info.path.lastIndexOf('/')) : '';+ const variant = buildVariant(base, ref, variantName, { overrides, added: delta.added });+ let newPath: string;+ try {+ newPath = await window.estella.project.createAsset(dir, `${variantName}.esprefab`, JSON.stringify(variant, null, 2) + '\n', 'prefab');+ } catch (err) {+ Toasts.push(t('proj.prefabCreateFailed', { name: variantName }), 'error');+ return null;+ }+ await this.refreshAssets(); // register the new asset so instantiate can resolve it++ // Re-link the scene instance to the variant, preserving its placement (the+ // proven delete + re-instantiate path — the variant flattens to the same tree).+ const root = SceneModel.entityBySource(instanceRoot);+ const parent = root?.parent ?? null;+ const tf = root?.components.find((c) => c.type === 'Transform')?.data as { position?: { x: number; y: number } } | undefined;+ const position = tf?.position ? { x: tf.position.x, y: tf.position.y } : undefined;+ SceneCommands.deleteEntity(instanceRoot);+ const newRoot = await this.instantiatePrefabFromPath(newPath, parent, position);+ Toasts.push(t('proj.variantCreated', { name: variantName }), '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/etc/index.api.md b/sdk/etc/index.api.mdindex 670cadd9d..0b3bcb9d0 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1291 stable · 17 beta · 0 deprecated+Symbols: 1292 stable · 17 beta · 0 deprecated## ABI_LAYOUT_HASH — const```@@ -7990,6 +7990,11 @@ BtPlugin(init?: UIVisualInit): UIVisualData```+## buildVariant — function+```+(base: PrefabData, baseRef: string, name: string, delta: { overrides: readonly PrefabOverride[]; added: readonly AddedEntity[]; }): PrefabData+```+## buildWangIndices — function```(asset: TilesetAsset): WangIndicesdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 608c85f86..e4eea7e35 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1290 stable · 19 beta · 0 deprecated+Symbols: 1291 stable · 19 beta · 0 deprecated## ANCHOR_AXES — const```@@ -7985,6 +7985,11 @@ BtPlugin(init?: UIVisualInit): UIVisualData```+## buildVariant — function+```+(base: PrefabData, baseRef: string, name: string, delta: { overrides: readonly PrefabOverride[]; added: readonly AddedEntity[]; }): PrefabData+```+## buildWangIndices — function```(asset: TilesetAsset): WangIndicesdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 07f81c4a6..49dd06a96 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1301 stable · 17 beta · 0 deprecated+Symbols: 1302 stable · 17 beta · 0 deprecated## ANCHOR_AXES — const```@@ -8009,6 +8009,11 @@ BtPlugin(init?: UIVisualInit): UIVisualData```+## buildVariant — function+```+(base: PrefabData, baseRef: string, name: string, delta: { overrides: readonly PrefabOverride[]; added: readonly AddedEntity[]; }): PrefabData+```+## buildWangIndices — function```(asset: TilesetAsset): WangIndicesdiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 62707194e..e07015aad 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -183,6 +183,7 @@ export {rebuildChildren,extractPrefab,applyDeltaToSource,+ buildVariant,collectExternalEntityRefs,type PrefabEntityId,type ProcessedEntity,diff --git a/sdk/src/prefab/index.ts b/sdk/src/prefab/index.tsindex 13605d2f4..e3c8fe19b 100644--- a/sdk/src/prefab/index.ts+++ b/sdk/src/prefab/index.ts@@ -39,6 +39,7 @@ export {rebuildChildren,extractPrefab,applyDeltaToSource,+ buildVariant,collectExternalEntityRefs,} from './sceneInstance';export type {diff --git a/sdk/src/prefab/sceneInstance.ts b/sdk/src/prefab/sceneInstance.tsindex 01722ba4a..f7a5df64c 100644--- a/sdk/src/prefab/sceneInstance.ts+++ b/sdk/src/prefab/sceneInstance.ts@@ -346,6 +346,48 @@ export function applyDeltaToSource(source: PrefabData, delta: SourceDelta): Prefreturn next;}+/**+ * Build a prefab VARIANT that inherits `baseRef` and bakes an instance delta as+ * the variant's own authored state — the authoring inverse of instantiating a+ * variant, and the sibling of {@link applyDeltaToSource} (which bakes INTO the+ * base instead of layering a new variant on top). Property / component / name /+ * visibility overrides become the variant's `overrides`; entities the instance+ * ADDED become variant `entities` (appended onto the base by+ * `mergeVariantEntities`, which links them into their parent's children on+ * flatten). The variant's rootEntityId mirrors the base — variants EXTEND their+ * base, they never relocate the root.+ *+ * A variant cannot DELETE a base entity (merge only replaces / appends), so+ * `delta.removed` is not representable and is ignored here; a caller that must+ * surface dropped removals should inspect it first. Pure: neither `base` nor+ * `delta` is mutated.+ */+export function buildVariant(+ base: PrefabData,+ baseRef: string,+ name: string,+ delta: { overrides: readonly PrefabOverride[]; added: readonly AddedEntity[] },+): PrefabData {+ const entities: PrefabEntityData[] = delta.added.map((a) => ({+ prefabEntityId: a.prefabEntityId,+ name: a.name,+ // Additions attach to a base entity (or another addition); parentId=null+ // means "under the instance root", which for a variant is the base root.+ parent: a.parentId ?? base.rootEntityId,+ children: [],+ components: cloneComponents([...a.components]),+ visible: a.visible,+ }));+ return {+ version: base.version,+ name,+ rootEntityId: base.rootEntityId,+ basePrefab: baseRef,+ entities,+ ...(delta.overrides.length ? { overrides: delta.overrides.map((o) => ({ ...o })) } : {}),+ };+}+// ── Authoring: live entities → a new prefab asset ───────────────────────────/** A scene/model entity subtree, as fed to {@link extractPrefab} (id-keyed). */diff --git a/sdk/tests/prefab-apply-to-source.test.ts b/sdk/tests/prefab-apply-to-source.test.tsindex 2c10142e3..323415b9f 100644--- a/sdk/tests/prefab-apply-to-source.test.ts+++ b/sdk/tests/prefab-apply-to-source.test.ts@@ -10,7 +10,8 @@ import { describe, it, expect } from 'vitest';// 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 { applyDeltaToSource } from '../src/prefab/sceneInstance';+import { applyDeltaToSource, buildVariant } from '../src/prefab/sceneInstance';+import { flattenPrefab } from '../src/prefab/flatten';import type { AddedEntity } from '../src/prefab/sceneInstance';import type { PrefabData, PrefabOverride } from '../src/prefab';@@ -174,3 +175,70 @@ describe('applyDeltaToSource (structural Apply)', () => {expect(src.entities[0].children).toEqual(['1']);});});++// ── buildVariant: an instance delta → a base-tracked variant PrefabData ──────++describe('buildVariant', () => {+ const BASE_REF = '@uuid:base';+ /** Flatten a variant, resolving its base ref through a fixed loader. */+ function flatten(variant: PrefabData, base: PrefabData) {+ let n = 0;+ return flattenPrefab(variant, [], {+ allocateId: () => n++,+ loadPrefab: (ref) => (ref === BASE_REF ? base : null),+ }).entities;+ }++ it('inherits the base + mirrors its rootEntityId, carrying overrides', () => {+ const base = basePrefab();+ const overrides: PrefabOverride[] = [+ { prefabEntityId: '1', type: 'property', componentType: 'Sprite', propertyName: 'color', value: 'red' },+ ];+ const v = buildVariant(base, BASE_REF, 'Enemy Variant', { overrides, added: [] });+ expect(v.basePrefab).toBe(BASE_REF);+ expect(v.rootEntityId).toBe(base.rootEntityId);+ expect(v.name).toBe('Enemy Variant');+ expect(v.overrides).toEqual(overrides);+ expect(v.entities).toEqual([]);+ // The base is untouched (pure).+ expect(base.entities[1].components[0].data).toEqual({ texture: 'a.png', color: 'white' });+ });++ it('flattens to the base with the variant overrides applied', () => {+ const base = basePrefab();+ const v = buildVariant(base, BASE_REF, 'V', {+ overrides: [{ prefabEntityId: '1', type: 'property', componentType: 'Sprite', propertyName: 'color', value: 'red' }],+ added: [],+ });+ const flat = flatten(v, base);+ const body = flat.find((e) => e.name === 'Body')!;+ expect((body.components.find((c) => c.type === 'Sprite')!.data as { color: string }).color).toBe('red');+ });++ it('appends added entities as variant entities, linked under their parent', () => {+ const base = basePrefab();+ const added: AddedEntity[] = [+ { prefabEntityId: 'x', name: 'Extra', components: [{ type: 'Marker', data: {} }], visible: true, parentId: '0' },+ ];+ const v = buildVariant(base, BASE_REF, 'V', { overrides: [], added });+ expect(v.entities).toEqual([+ { prefabEntityId: 'x', name: 'Extra', parent: '0', children: [], components: [{ type: 'Marker', data: {} }], visible: true },+ ]);+ // The addition survives flatten and attaches under the (runtime) root.+ const flat = flatten(v, base);+ const root = flat.find((e) => e.parent === null)!;+ const extra = flat.find((e) => e.name === 'Extra')!;+ expect(extra).toBeDefined();+ expect(extra.parent).toBe(root.id);+ });++ it('maps a null parentId to the base root, and drops the overrides key when empty', () => {+ const base = basePrefab();+ const v = buildVariant(base, BASE_REF, 'V', {+ overrides: [],+ added: [{ prefabEntityId: 'y', name: 'Loose', components: [], visible: true, parentId: null }],+ });+ expect(v.entities[0].parent).toBe(base.rootEntityId);+ expect('overrides' in v).toBe(false);+ });+});