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(editor): a row the game destroys stays in the tree
yhh9b21e6cab595
diff --git a/desktop/src/i18n/messages/outliner.ts b/desktop/src/i18n/messages/outliner.tsindex d2f3bfcd7..7ebd2a8a0 100644--- a/desktop/src/i18n/messages/outliner.ts+++ b/desktop/src/i18n/messages/outliner.ts@@ -10,6 +10,7 @@ export const outlinerMessages = defineMessages({'out.liveWorld': { en: 'Live — edits end at Stop', zh: '运行中 · 改动在停止时结束' },'out.waitingGame': { en: 'Waiting for the running game…', zh: '正在等待运行中的游戏…' },'out.spawnedTip': { en: 'Spawned by the running game', zh: '由运行中的游戏创建' },+ 'out.goneTip': { en: 'Destroyed — the scene still has it, the running game does not', zh: '已销毁 · 场景里还有它,运行中的游戏里没有了' },// — Header strip (search / sort / create buttons) —// `type:` / `comp:` are literal query tokens (parseQuery grammar) — never translated.diff --git a/desktop/src/outliner/OutlinerRow.tsx b/desktop/src/outliner/OutlinerRow.tsxindex 51dc9b39a..4527e427d 100644--- a/desktop/src/outliner/OutlinerRow.tsx+++ b/desktop/src/outliner/OutlinerRow.tsx@@ -15,6 +15,7 @@ import type React from 'react';import { Fragment, memo } from 'react';import { ChevronRight, Folder, FolderOpen } from 'lucide-react';import { NodeIcon } from '@/components/icons';+import { t } from '@/i18n';import type { ReactNode } from 'react';import type { OutlinerItem } from './OutlinerModel';import type { OutlinerColumn, OutlinerColumnContext } from './columns';@@ -46,6 +47,8 @@ export interface OutlinerRowProps {/** The running game made this entity; no document row corresponds to it, and* it is gone on Stop. */spawned?: boolean;+ /** The document has this entity, the running world no longer does. */+ gone?: boolean;/** Keyboard-focus row (shows a focus ring; distinct from selection). */cursored?: boolean;/** Lowercased substring to highlight in the name (the search bare text). */@@ -113,8 +116,10 @@ function OutlinerRowInner(props: OutlinerRowProps) {`${props.agentTouched ? ' agent-touched' : ''}` +`${props.agentFresh ? ' agent-fresh' : ''}` +`${props.agentPeeked ? ' agent-peek' : ''}` +- `${props.spawned ? ' spawned' : ''}`+ `${props.spawned ? ' spawned' : ''}` ++ `${props.gone ? ' gone' : ''}`}+ title={props.gone ? t('out.goneTip') : undefined}style={{ paddingLeft: depth * 14 }}role="treeitem"aria-selected={selected}diff --git a/desktop/src/outliner/liveTree.ts b/desktop/src/outliner/liveTree.tsnew file mode 100644index 000000000..26d3f7002--- /dev/null+++ b/desktop/src/outliner/liveTree.ts@@ -0,0 +1,77 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file liveTree.ts — the running world's rows, plus the authored ones it no longer has.+ */+import type { SceneData } from 'esengine';+import type { EntityId } from '@/types';+import type { LiveOrigin } from '@/engine/playProtocol';+import { authoredRef, refOfLive, spawnedRef, type EntityRef } from '@/engine/entityRef';++type LiveEntity = SceneData['entities'][number] & LiveOrigin;++export interface LiveTreeView {+ /** The tree to build rows from; null until the realm has reported one. */+ data: SceneData | null;+ /** Who a row is — the one answer for every id in {@link data}. */+ refOf: (id: EntityId) => EntityRef;+ /** Ids of rows the running world does not have (nothing can be written to them). */+ gone: ReadonlySet<EntityId>;+}++// A tombstone still needs an id in the merged tree, and a realm handle must never+// be mistaken for one. Handles are indices, so the negatives are free.+const tombstoneId = (src: EntityId): EntityId => -src - 1;+const srcOfTombstone = (id: EntityId): EntityId => -id - 1;++const NO_IDS: ReadonlySet<EntityId> = new Set();++/**+ * Merge the realm's tree with the scene document: every live entity as reported,+ * plus a tombstone for each authored one the game destroyed, under whichever+ * world owns its parent.+ */+export function mergeLiveTree(live: SceneData | null, doc: SceneData | null): LiveTreeView {+ if (!live) return { data: null, refOf: spawnedRef, gone: NO_IDS };+ const srcToLive = new Map<EntityId, EntityId>();+ const liveToSrc = new Map<EntityId, EntityId>();+ for (const e of live.entities as LiveEntity[]) {+ if (e.src === undefined) continue;+ srcToLive.set(e.src, e.id);+ liveToSrc.set(e.id, e.src);+ }+ const asReported: LiveTreeView = { data: live, refOf: (id) => refOfLive(id, liveToSrc.get(id)), gone: NO_IDS };+ // With nothing of the document running, the realm is showing another world —+ // every authored row would be a tombstone, which is noise, not information.+ if (srcToLive.size === 0) return asReported;+ const docEntities = doc?.entities ?? [];+ const deadSrcs = new Set(docEntities.filter((e) => !srcToLive.has(e.id)).map((e) => e.id));+ if (deadSrcs.size === 0) return asReported;++ const parentOf = (parent: EntityId | null | undefined): EntityId | null =>+ parent == null ? null : srcToLive.get(parent) ?? (deadSrcs.has(parent) ? tombstoneId(parent) : null);+ type Row = SceneData['entities'][number];+ // Placed where the document has it, behind the last authored row still running:+ // the row you were reading must not jump when the game destroys it.+ const lead: Row[] = [];+ const behind = new Map<EntityId, Row[]>();+ let anchor: EntityId | null = null;+ for (const e of docEntities) {+ const alive = srcToLive.get(e.id);+ if (alive !== undefined) { anchor = alive; continue; }+ const tomb = { ...e, id: tombstoneId(e.id), parent: parentOf(e.parent), children: [] };+ if (anchor === null) lead.push(tomb);+ else (behind.get(anchor) ?? behind.set(anchor, []).get(anchor)!).push(tomb);+ }+ const entities: Row[] = [...lead];+ for (const e of live.entities) {+ entities.push(e);+ const tombs = behind.get(e.id);+ if (tombs) entities.push(...tombs);+ }+ return {+ data: { ...live, entities },+ refOf: (id) => (id < 0 ? authoredRef(srcOfTombstone(id)) : refOfLive(id, liveToSrc.get(id))),+ gone: new Set([...deadSrcs].map(tombstoneId)),+ };+}diff --git a/desktop/src/panels/Outliner.tsx b/desktop/src/panels/Outliner.tsxindex 25c05b263..53773322c 100644--- a/desktop/src/panels/Outliner.tsx+++ b/desktop/src/panels/Outliner.tsx@@ -19,6 +19,7 @@ import { contributedContextRows } from '@/plugins/contextMenus';import { VirtualTree } from '@/components/VirtualTree';import { t } from '@/i18n';import { buildOutlinerItems, collectExpandableKeys, entityKey, folderKey, parseQuery, type OutlinerItem, type SortMode } from '@/outliner/OutlinerModel';+import { mergeLiveTree } from '@/outliner/liveTree';import { useOutliner } from '@/outliner/OutlinerController';import { OutlinerRow } from '@/outliner/OutlinerRow';import { useAgent, touchedEntities } from '@/store/AgentStore';@@ -116,22 +117,25 @@ export function Outliner() {() => (engine.status === 'ready' ? (SceneModel.current?.entities.length ?? 0) : 0),[engine.status, structRev],);+ // A destroyed enemy leaves the running world, not the scene you are editing:+ // its row stays, as a tombstone.+ const liveView = useMemo(() => mergeLiveTree(liveTree, SceneModel.current), [liveTree, structRev]);// An authored row keeps the folder it was filed under while the game runs; a// spawned one has no document to be filed in, so it collects under Runtime.const liveFolderOf = (id: EntityId): string => {- const ref = PlayInspect.refOf(id);+ const ref = liveView.refOf(id);return ref.world === 'authored' ? SceneModel.folderOf(ref.src) : RUNTIME_FOLDER;};const items = useMemo(() => {if (live) {- return buildOutlinerItems(liveTree, {+ return buildOutlinerItems(liveView.data, {expanded,query,sort: sortMode,folderOf: liveFolderOf,folders: SceneModel.sceneFolders(),- refOf: (id) => PlayInspect.refOf(id),+ refOf: liveView.refOf,});}return engine.status === 'ready'@@ -146,7 +150,7 @@ export function Outliner() {: [];},// eslint-disable-next-line react-hooks/exhaustive-deps- [live, liveTree, engine.status, structRev, expanded, query, sortMode],+ [live, liveView, engine.status, structRev, expanded, query, sortMode],);// Keyed on the snapshot REFERENCE, which PlayInspect holds stable unless the// tree actually differs — so a steady game rebuilds neither set per sample.@@ -185,7 +189,7 @@ export function Outliner() {() =>live? {- onToggleVisible: (id, visible) => EntityOps.setVisible(PlayInspect.refOf(id), visible),+ onToggleVisible: (id, visible) => EntityOps.setVisible(liveView.refOf(id), visible),canToggleVisible: (id) => hideable.has(id),}: {@@ -193,7 +197,7 @@ export function Outliner() {onToggleLock: (id, locked) => SceneCommands.setEntityLocked(id, locked),isPrefab: (id) => SceneModel.prefabTag(id) != null,},- [live, hideable],+ [live, hideable, liveView],);// A scene swap resets the model ('reset' event). This panel is a persistent dock@@ -401,7 +405,7 @@ export function Outliner() {const expandAll = () =>useOutliner.getState().setExpanded(live- ? collectExpandableKeys(liveTree, { folderOf: liveFolderOf, refOf: (id) => PlayInspect.refOf(id) })+ ? collectExpandableKeys(liveView.data, { folderOf: liveFolderOf, refOf: liveView.refOf }): collectExpandableKeys(SceneModel.current, { folderOf: (id) => SceneModel.folderOf(id), folders: SceneModel.sceneFolders() }),);@@ -699,6 +703,7 @@ export function Outliner() {agentFresh={!live && it.kind === 'entity' && agentFresh.has(it.id)}agentPeeked={!live && it.kind === 'entity' && agentPeeked.includes(it.id)}spawned={it.kind === 'entity' && it.ref.world === 'spawned'}+ gone={live && it.kind === 'entity' && liveView.gone.has(it.id)}renaming={renaming === it.key}dropPos={drop?.key === it.key ? drop.pos : undefined}prefabRole={diff --git a/desktop/src/theme/outliner.css b/desktop/src/theme/outliner.cssindex fac294b24..896177834 100644--- a/desktop/src/theme/outliner.css+++ b/desktop/src/theme/outliner.css@@ -125,3 +125,9 @@/* A row the game made: nothing in the document answers to it, so it reads as aguest — dimmer name, no drag affordance. */.row.spawned .rname { color: var(--text-dim); font-style: italic; }++/* A row the game destroyed. Struck through rather than merely dim, which is what+ a hidden row already reads as. */+.row.gone .rname { color: var(--text-faint); text-decoration: line-through; }+.row.gone .ricon { opacity: 0.4; }+.row.sel.gone .rname { color: rgba(255, 255, 255, 0.7); }diff --git a/desktop/tests/live-tree-identity.test.ts b/desktop/tests/live-tree-identity.test.tsindex 5fa4caaff..1896543ba 100644--- a/desktop/tests/live-tree-identity.test.ts+++ b/desktop/tests/live-tree-identity.test.ts@@ -13,6 +13,7 @@ import { describe, it, expect, beforeEach } from 'vitest';import type { SceneData } from 'esengine';import { authoredRef, spawnedRef, refKey, refOfLive, sameRef, srcIdOf } from '@/engine/entityRef';import { buildOutlinerItems, entityKey } from '@/outliner/OutlinerModel';+import { mergeLiveTree } from '@/outliner/liveTree';import { useSelection } from '@/store/selectionStore';/** A live tree as the realm reports it: realm handles, `src` only where the@@ -31,6 +32,9 @@ const liveTree = (rows: Array<{ id: number; src?: number; parent?: number | null})),}) as unknown as SceneData;+/** The scene document those rows were loaded from: plain ids, no realm handles. */+const sceneDoc = (rows: Array<{ id: number; parent?: number | null }>): SceneData => liveTree(rows);+const srcOfLive = (tree: SceneData) => {const map = new Map<number, number>();for (const e of tree.entities as Array<{ id: number; src?: number }>) {@@ -97,6 +101,74 @@ describe('the tree of a running world', () => {});});+describe('rows the running world no longer has', () => {+ it('keeps a destroyed entity in the tree, on the row it was authored as', () => {+ const live = liveTree([{ id: 900, src: 3 }]); // document row 4 was destroyed+ const view = mergeLiveTree(live, sceneDoc([{ id: 3 }, { id: 4 }]));+ const items = buildOutlinerItems(view.data, { expanded: new Set(), refOf: view.refOf });+ expect(items.map((i) => i.key)).toEqual([entityKey(3), entityKey(4)]);+ expect(items[1].kind === 'entity' && view.gone.has(items[1].id)).toBe(true);+ });++ it('gives a tombstone an id no realm handle can be', () => {+ // Two id spaces in one array: handle 4 (a bullet) and document row 4 (gone)+ // are different entities, and one row must not swallow the other.+ const live = liveTree([{ id: 900, src: 3 }, { id: 4 }]);+ const view = mergeLiveTree(live, sceneDoc([{ id: 3 }, { id: 4 }]));+ const ids = (view.data!.entities as Array<{ id: number }>).map((e) => e.id);+ expect(new Set(ids).size).toBe(ids.length);+ expect(buildOutlinerItems(view.data, { expanded: new Set(), refOf: view.refOf })).toHaveLength(3);+ });++ it('answers for a tombstone as the document row it is', () => {+ const view = mergeLiveTree(liveTree([{ id: 900, src: 3 }]), sceneDoc([{ id: 3 }, { id: 4 }]));+ const [tomb] = [...view.gone];+ // Which is what makes every op resolve it through liveIdOf and find nothing.+ expect(view.refOf(tomb)).toEqual(authoredRef(4));+ });++ it('nests a tombstone under the parent that survived it', () => {+ const view = mergeLiveTree(liveTree([{ id: 900, src: 3 }]), sceneDoc([{ id: 3 }, { id: 4, parent: 3 }]));+ const items = buildOutlinerItems(view.data, { expanded: new Set([entityKey(3)]), refOf: view.refOf });+ expect(items.map((i) => i.key)).toEqual([entityKey(3), entityKey(4)]);+ expect(items[1].parentKey).toBe(entityKey(3));+ });++ it('nests a tombstone under its parent when both are gone', () => {+ const doc = sceneDoc([{ id: 3 }, { id: 4 }, { id: 5, parent: 4 }]);+ const view = mergeLiveTree(liveTree([{ id: 900, src: 3 }]), doc);+ const items = buildOutlinerItems(view.data, { expanded: new Set([entityKey(4)]), refOf: view.refOf });+ expect(items.map((i) => i.key)).toEqual([entityKey(3), entityKey(4), entityKey(5)]);+ expect(items[2].parentKey).toBe(entityKey(4));+ });++ it('leaves a tombstone where the document has it, not at the end', () => {+ const live = liveTree([{ id: 900, src: 3 }, { id: 901, src: 5 }]);+ const view = mergeLiveTree(live, sceneDoc([{ id: 3 }, { id: 4 }, { id: 5 }]));+ const items = buildOutlinerItems(view.data, { expanded: new Set(), refOf: view.refOf });+ expect(items.map((i) => i.key)).toEqual([entityKey(3), entityKey(4), entityKey(5)]);+ });++ it('shows no tombstones while nothing of the document is running', () => {+ // Booting, or a game that moved on to another scene. That is not this scene+ // with holes in it, and a whole document of tombstones says nothing.+ const live = liveTree([{ id: 901 }]);+ const view = mergeLiveTree(live, sceneDoc([{ id: 3 }, { id: 4 }]));+ expect(view.data).toBe(live);+ expect(view.gone.size).toBe(0);+ });++ it('hands back the realm tree itself while every authored row is alive', () => {+ // Reference identity: a steady game must not rebuild the Outliner every sample.+ const live = liveTree([{ id: 900, src: 3 }, { id: 901 }]);+ expect(mergeLiveTree(live, sceneDoc([{ id: 3 }])).data).toBe(live);+ });++ it('has nothing to show before the realm reports a tree', () => {+ expect(mergeLiveTree(null, sceneDoc([{ id: 3 }])).data).toBeNull();+ });+});+describe('one selection', () => {beforeEach(() => useSelection.getState().select(null));