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): Stop can hand back what you changed while playing
yhh14795823bed1
diff --git a/desktop/src/App.tsx b/desktop/src/App.tsxindex 009fe3d2a..3af2d29d5 100644--- a/desktop/src/App.tsx+++ b/desktop/src/App.tsx@@ -34,6 +34,7 @@ import { uiPreviewAspect } from '@/mode/resolutionPresets';import { EngineHost } from '@/engine/EngineHost';import { PlayRealms } from '@/engine/PlayRealm';import { PlayInspect } from '@/engine/PlayInspect';+import { PlayEdits, offerToKeepPlayEdits } from '@/engine/playEdits';import { TimelinePreview } from '@/engine/TimelinePreview';import { FlipbookViewportPreview } from '@/engine/FlipbookViewportPreview';import { TimelineRecorder } from '@/timeline/TimelineRecorder';@@ -210,6 +211,7 @@ export function App() {return;}const players = useEditorStore.getState().playPlayers;+ PlayEdits.clear(); // a fresh session owes nothingvoid PlayRealms.startSession(payload, players);PlayInspect.start(); // poll the running game for live inspect/debug// 'window' → a Game dock tab; 'viewport' → the Viewport mounts it (PIE).@@ -225,8 +227,13 @@ export function App() {requestAnimationFrame(() => dockApi.maximizePanel('viewport'));}} else {- PlayRealms.stopSession();- PlayInspect.stop();+ // Read what was changed while the realm can still answer, THEN tear it+ // down. The offer is a toast rather than a dialog: Stop must not wait on a+ // person, and a modal in an automated run is a hang.+ void offerToKeepPlayEdits().finally(() => {+ PlayInspect.stop();+ PlayRealms.stopSession();+ });if (autoMaximized.current) {dockApi.exitMaximized();autoMaximized.current = false;diff --git a/desktop/src/engine/SceneCommands.ts b/desktop/src/engine/SceneCommands.tsindex 360cc7952..4d614f918 100644--- a/desktop/src/engine/SceneCommands.ts+++ b/desktop/src/engine/SceneCommands.ts@@ -435,6 +435,17 @@ export class SceneCommandsImpl {this.writeField_(sourceId, compName, key, 'vec2list', verts);}+ /**+ * Write a field's value AS IT ALREADY IS — the door for a value that came from+ * a world rather than from a control, which has no inspector shape to convert+ * from (keeping what a play session left behind).+ */+ setFieldValue(sourceId: EntityId, compName: string, key: string, value: unknown): void {+ const e = this.model.entityBySource(sourceId);+ if (!e) return;+ this.writeResolved_(sourceId, compName, key, clampFieldValue(compName, key, value));+ }+/** The unconditional single-field write (model + undo/gesture bookkeeping). */private writeField_(sourceId: EntityId,@@ -460,6 +471,24 @@ export class SceneCommandsImpl {// Transform.position, so the scene file never stores one.const effective = { ...defaultDataFor(compName), ...cur };const after = clampFieldValue(compName, key, toModelValue(effective, type, key, value));+ this.writeResolved_(sourceId, compName, key, after, k, firstTouch, before);+ }++ /** Everything from the model write on: the gesture ledger, or its own undo step. */+ private writeResolved_(+ sourceId: EntityId,+ compName: string,+ key: string,+ after: unknown,+ editK?: string,+ firstTouchIn?: boolean,+ beforeIn?: unknown,+ ): void {+ const k = editK ?? editKey(sourceId, compName, key);+ const firstTouch = firstTouchIn ?? (!this.gesture || !this.gesture.touched.has(k));+ const before = editK !== undefined+ ? beforeIn+ : (firstTouch ? structuredClone(this.modelFieldValue(sourceId, compName, key)) : undefined);this.model.setField(sourceId, compName, key, after);if (this.gesture) {diff --git a/desktop/src/engine/entityOps.ts b/desktop/src/engine/entityOps.tsindex 191578dc2..3f5681231 100644--- a/desktop/src/engine/entityOps.ts+++ b/desktop/src/engine/entityOps.ts@@ -9,8 +9,9 @@* and how one of the two paths quietly stops being maintained.** So the choice is made once, here: the document sink records undo and reaches- * disk, the live sink posts to the realm and evaporates on Stop. Callers name- * an entity by {@link EntityRef} and say what they want.+ * disk, the live sink posts to the realm and — unless Stop is told to keep it —+ * evaporates. Being the one door is also what lets {@link PlayEdits} know what a+ * person changed, as opposed to what the game did.*/import type { EntityId, FieldWrite, InspectorFieldType } from '@/types';import { useEditorStore } from '@/store/editorStore';@@ -18,6 +19,7 @@ import { SceneCommands, toModelValue } from './SceneCommands';import { PlayInspect } from './PlayInspect';import { PlayRealm } from './PlayRealm';import { srcIdOf, type EntityRef } from './entityRef';+import { PlayEdits } from './playEdits';/** The value vocabulary every inspector control commits in. */type FieldValue = Parameters<FieldWrite>[2];@@ -45,6 +47,7 @@ export const EntityOps = {// model itself; the realm takes a whole component value, so the same merge// happens here against what the realm last reported.PlayInspect.setField(live, comp, key, toModelValue(PlayInspect.componentData(live, comp), type, key, value as never));+ PlayEdits.record(ref, comp, key);return 'live';}const src = srcIdOf(ref);@@ -58,6 +61,7 @@ export const EntityOps = {const live = PlayInspect.liveIdOf(ref);if (live == null) return null;PlayInspect.setVisible(live, visible);+ PlayEdits.recordVisibility(ref);return 'live';}const src = srcIdOf(ref);@@ -78,6 +82,7 @@ export const EntityOps = {const live = PlayInspect.liveIdOf(ref);if (live == null || !point.canvas) return null;PlayRealm.dragTo(live, point.canvas.x, point.canvas.y, axis);+ PlayEdits.record(ref, 'Transform', 'position');return 'live';}const src = srcIdOf(ref);diff --git a/desktop/src/engine/playEdits.ts b/desktop/src/engine/playEdits.tsnew file mode 100644index 000000000..7375a2b2d--- /dev/null+++ b/desktop/src/engine/playEdits.ts@@ -0,0 +1,189 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file playEdits.ts — what a person changed while the game was running.+ *+ * A play session's edits are thrown away at Stop, which is the right default and+ * a famous way to lose an afternoon of tuning. The scene document is never+ * destroyed here, so the work does not have to be: this remembers what was+ * touched and offers it back.+ *+ * It records the WRITES, not a diff of the world. A diff cannot tell a value a+ * person dragged from one a system writes every frame — a bobbing sprite's y+ * changes constantly and nobody asked for it — so the only honest source is the+ * op layer every deliberate edit already passes through.+ *+ * What is recorded is the ADDRESS, not the value: the value is read from the+ * running world at Stop, so keeping an edit keeps what is on screen when you+ * press it rather than an intermediate frame of a drag.+ */+import type { EntityId } from '@/types';+import { PlayRealm } from './PlayRealm';+import { PlayInspect } from './PlayInspect';+import { SceneCommands } from './SceneCommands';+import { SceneModel } from './SceneModel';+import { refKey, srcIdOf, type EntityRef } from './entityRef';+import { Toasts } from '@/store/Toasts';+import { LogStore } from '@/store/LogStore';+import { t } from '@/i18n';++/** One thing a person aimed at: a component field, or the entity's visibility. */+interface Touch {+ ref: EntityRef;+ /** null = the editor's show/hide bit rather than a component field. */+ field: { comp: string; key: string } | null;+}++/** A touched address resolved against the running world — ready to write back. */+export interface PendingEdit {+ /** The document row it lands on. */+ src: EntityId;+ /** "Sprite0 · Transform.position" — what the offer lists. */+ label: string;+ /** The value as the running world holds it, rendered for the log. */+ shown: string;+ apply: () => void;+}++/** What a harvest found, including what it could not offer. */+export interface HarvestResult {+ edits: PendingEdit[];+ /** Edits to entities the game spawned — no document row to keep them on. */+ spawned: number;+}++const addressOf = (t: Touch): string =>+ `${refKey(t.ref)}|${t.field ? `${t.field.comp}.${t.field.key}` : ':visible'}`;++/** A model value as a short human string — the log line, not a round-trip. */+function show(value: unknown): string {+ if (value == null) return String(value);+ if (typeof value === 'number') return String(Math.round(value * 1000) / 1000);+ if (typeof value !== 'object') return String(value);+ const obj = value as Record<string, unknown>;+ const parts = Object.keys(obj)+ .filter((k) => typeof obj[k] === 'number')+ .map((k) => `${k} ${show(obj[k])}`);+ return parts.length ? parts.join(', ') : JSON.stringify(value);+}++class PlayEditsImpl {+ private touched = new Map<string, Touch>();++ /** Forget everything (a fresh play session starts owing nothing). */+ clear(): void {+ this.touched.clear();+ }++ count(): number {+ return this.touched.size;+ }++ /** A component field was written on the running entity. */+ record(ref: EntityRef, comp: string, key: string): void {+ const touch: Touch = { ref, field: { comp, key } };+ this.touched.set(addressOf(touch), touch);+ }++ /** The running entity was shown or hidden. */+ recordVisibility(ref: EntityRef): void {+ const touch: Touch = { ref, field: null };+ this.touched.set(addressOf(touch), touch);+ }++ /**+ * Read the current value of everything touched, while the realm is still up.+ * Call before tearing it down — afterwards there is nothing left to ask.+ */+ async harvest(): Promise<HarvestResult> {+ const touches = [...this.touched.values()];+ if (touches.length === 0) return { edits: [], spawned: 0 };++ const keepable = touches.filter((t) => srcIdOf(t.ref) != null);+ const spawned = touches.length - keepable.length;++ // Resolve identity BEFORE the first await: the mapping belongs to a live+ // session, and the teardown this runs alongside is entitled to drop it.+ const liveOf = new Map(keepable.map((t) => [t, PlayInspect.liveIdOf(t.ref)] as const));+ // One tree sample answers every visibility touch; component data has to be+ // asked for per entity, so ask once per entity rather than once per field.+ const wantsTree = keepable.some((t) => t.field === null);+ const liveIds = [...new Set([...liveOf.values()].filter((id): id is EntityId => id != null))];+ const [tree, ...details] = await Promise.all([+ wantsTree ? PlayRealm.snapshot(null, { tree: true }).then((s) => s?.tree ?? null) : Promise.resolve(null),+ ...liveIds.map((id) => PlayRealm.snapshot(id, { tree: false }).then((s) => s?.selected ?? null)),+ ]);+ const dataOf = new Map(liveIds.map((id, i) => [id, details[i]]));++ const edits: PendingEdit[] = [];+ for (const touch of keepable) {+ const src = srcIdOf(touch.ref)!;+ const live = liveOf.get(touch) ?? null;+ const name = SceneModel.entityBySource(src)?.name ?? `#${src}`;+ if (live == null) continue; // destroyed before Stop — nothing to read++ if (touch.field === null) {+ const row = tree?.entities.find((e) => e.id === live) as { hidden?: boolean } | undefined;+ if (!row) continue;+ const visible = !row.hidden;+ edits.push({+ src,+ label: `${name} · ${visible ? 'visible' : 'hidden'}`,+ shown: String(visible),+ apply: () => SceneCommands.setEntityVisible(src, visible),+ });+ continue;+ }++ const { comp, key } = touch.field;+ const data = dataOf.get(live)?.components.find((c) => c.type === comp)?.data as Record<string, unknown> | undefined;+ if (!data || !(key in data)) continue;+ const value = data[key];+ edits.push({+ src,+ label: `${name} · ${comp}.${key}`,+ shown: show(value),+ apply: () => SceneCommands.setFieldValue(src, comp, key, value),+ });+ }+ return { edits, spawned };+ }++ /** Write every kept edit to the document as ONE undo step. */+ applyAll(edits: readonly PendingEdit[], label: string): void {+ SceneCommands.transact(label, () => {+ for (const edit of edits) edit.apply();+ });+ }+}++export const PlayEdits = new PlayEditsImpl();++/**+ * Offer back whatever the play session changed. A sticky toast, not a dialog:+ * Stop must not wait on an answer, and a modal in an automated run is a hang.+ *+ * Resolves once the running world has been read — the caller tears the realm+ * down after that, not before.+ */+export async function offerToKeepPlayEdits(): Promise<void> {+ if (PlayEdits.count() === 0) return;+ const { edits, spawned } = await PlayEdits.harvest().catch(() => ({ edits: [], spawned: 0 }));+ PlayEdits.clear();+ if (spawned > 0) LogStore.push('info', 'Play', t('play.keep.spawnedDropped', { n: spawned }));+ if (edits.length === 0) return;++ for (const edit of edits) LogStore.push('info', 'Play', `${edit.label} = ${edit.shown}`);+ Toasts.push(+ t('play.keep.offer', { n: edits.length }),+ 'info',+ 0, // sticky: the answer is the user's, and it is not urgent+ {+ label: t('play.keep.action'),+ run: () => {+ PlayEdits.applyAll(edits, t('play.keep.undoLabel'));+ Toasts.push(t('play.keep.kept', { n: edits.length }), 'success');+ },+ },+ );+}diff --git a/desktop/src/i18n/messages/layout.ts b/desktop/src/i18n/messages/layout.tsindex cc9463252..e92662704 100644--- a/desktop/src/i18n/messages/layout.ts+++ b/desktop/src/i18n/messages/layout.ts@@ -98,5 +98,18 @@ export const layoutMessages = defineMessages({// — App shell toasts —'layout.toast.openSceneFirst': { en: 'Open a scene before playing', zh: '请先打开场景再运行' },++ // — Keeping what a play session changed —+ 'play.keep.offer': {+ en: '{n} change(s) made while playing — keep them in the scene?',+ zh: '运行期间改动了 {n} 处 — 保留到场景里吗?',+ },+ 'play.keep.action': { en: 'Keep', zh: '保留' },+ 'play.keep.kept': { en: 'Kept {n} change(s) — undo to revert', zh: '已保留 {n} 处改动 — 撤销可还原' },+ 'play.keep.undoLabel': { en: 'Keep play changes', zh: '保留运行期改动' },+ 'play.keep.spawnedDropped': {+ en: '{n} change(s) were made to entities the game spawned — the scene has no row for them, so they end with the session.',+ zh: '有 {n} 处改动落在游戏自己创建的实体上 — 场景里没有对应的行,它们随会话一起结束。',+ },'layout.toast.noPlayInPrefab': { en: 'Exit Prefab Mode before playing — a prefab has no scene to run.', zh: '请先退出预制体编辑再运行——预制体没有可运行的场景。' },});diff --git a/desktop/tests/play-edits.test.ts b/desktop/tests/play-edits.test.tsnew file mode 100644index 000000000..78ece8a5a--- /dev/null+++ b/desktop/tests/play-edits.test.ts@@ -0,0 +1,156 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file Keeping what a play session changed.+ *+ * The whole idea rests on one distinction: what a PERSON changed, versus what+ * the game did. A diff of the world cannot draw it — a bobbing sprite's y moves+ * every frame and nobody asked for it — so the journal records the addresses the+ * op layer was asked to write, and reads their values back at Stop.+ */+import { describe, it, expect, beforeEach, vi } from 'vitest';++vi.mock('@/engine/SceneCommands', () => ({+ SceneCommands: {+ setField: vi.fn(),+ setFieldValue: vi.fn(),+ setEntityVisible: vi.fn(),+ setEntityXY: vi.fn(),+ transact: vi.fn((_label: string, fn: () => void) => fn()),+ },+ toModelValue: (_cur: unknown, _t: unknown, _k: string, v: unknown) => v,+}));+vi.mock('@/engine/PlayRealm', () => ({+ PlayRealm: { setField: vi.fn(), setVisible: vi.fn(), dragTo: vi.fn(), snapshot: vi.fn() },+}));++import { PlayEdits } from '@/engine/playEdits';+import { EntityOps } from '@/engine/entityOps';+import { SceneCommands } from '@/engine/SceneCommands';+import { PlayRealm } from '@/engine/PlayRealm';+import { PlayInspect } from '@/engine/PlayInspect';+import { SceneModel } from '@/engine/SceneModel';+import { useEditorStore } from '@/store/editorStore';+import { authoredRef, spawnedRef } from '@/engine/entityRef';++const snapshotMock = vi.mocked(PlayRealm.snapshot);++/** Play, with the realm holding runtime 900 for document row 3. */+function playing() {+ useEditorStore.setState({ isPlaying: true });+ vi.spyOn(PlayInspect, 'liveIdOf').mockImplementation((ref) =>+ ref == null ? null : ref.world === 'authored' ? (ref.src === 3 ? 900 : null) : ref.live);+ vi.spyOn(PlayInspect, 'componentData').mockReturnValue({});+ vi.spyOn(SceneModel, 'entityBySource').mockReturnValue({ name: 'Player' } as never);+}++/** The realm's answer: entity 900 sits at x 42, and is hidden. */+function realmHolds(position: { x: number; y: number }, hidden = false) {+ snapshotMock.mockImplementation((sel, opts) =>+ Promise.resolve({+ tree: opts?.tree === false ? null : ({ entities: [{ id: 900, name: 'Player', parent: null, components: [], hidden }] } as never),+ selected: sel == null ? null : ({ id: sel, components: [{ type: 'Transform', data: { position } }] } as never),+ overlay: null,+ }));+}++beforeEach(() => {+ vi.restoreAllMocks();+ vi.clearAllMocks();+ PlayEdits.clear();+ useEditorStore.setState({ isPlaying: false });+});++describe('the journal', () => {+ it('records nothing for an edit made while not playing', () => {+ EntityOps.setField(authoredRef(3), 'Sprite', 'color', 'color', [1, 0, 0, 1]);+ expect(PlayEdits.count()).toBe(0);+ });++ it('records one address per field, however many times it is written', () => {+ playing();+ for (let i = 0; i < 5; i++) {+ EntityOps.moveToPoint(authoredRef(3), { canvas: { x: i / 10, y: 0.5 } });+ }+ // A drag is hundreds of writes and one intent.+ expect(PlayEdits.count()).toBe(1);+ });++ it('separates a field write, a move and a visibility toggle', () => {+ playing();+ EntityOps.setField(authoredRef(3), 'Sprite', 'color', 'color', [1, 0, 0, 1]);+ EntityOps.moveToPoint(authoredRef(3), { canvas: { x: 0.5, y: 0.5 } });+ EntityOps.setVisible(authoredRef(3), false);+ expect(PlayEdits.count()).toBe(3);+ });++ it('keeps nothing on its own — a write that was refused is not an edit', () => {+ playing();+ // Row 4 has no live entity, so the op is refused; it must not be journalled.+ expect(EntityOps.setField(authoredRef(4), 'Sprite', 'color', 'color', [1, 0, 0, 1])).toBeNull();+ expect(PlayEdits.count()).toBe(0);+ });+});++describe('the harvest', () => {+ it('reads the value the running world holds NOW, not the one written', async () => {+ playing();+ realmHolds({ x: 42, y: 7 });+ // The drag asked for a canvas point; what gets kept is where the entity+ // actually ended up, which is the only value anyone was looking at.+ EntityOps.moveToPoint(authoredRef(3), { canvas: { x: 0.9, y: 0.1 } });++ const { edits, spawned } = await PlayEdits.harvest();+ expect(spawned).toBe(0);+ expect(edits).toHaveLength(1);+ expect(edits[0].src).toBe(3);+ expect(edits[0].label).toBe('Player · Transform.position');+ expect(edits[0].shown).toBe('x 42, y 7');++ edits[0].apply();+ expect(SceneCommands.setFieldValue).toHaveBeenCalledWith(3, 'Transform', 'position', { x: 42, y: 7 });+ });++ it('cannot keep an edit to something the game spawned, and says so', async () => {+ playing();+ realmHolds({ x: 1, y: 1 });+ EntityOps.setVisible(spawnedRef(901), false);++ const { edits, spawned } = await PlayEdits.harvest();+ // No document row exists to write it to — counted, not silently dropped.+ expect(edits).toHaveLength(0);+ expect(spawned).toBe(1);+ });++ it('carries a visibility toggle back as the show/hide command', async () => {+ playing();+ realmHolds({ x: 0, y: 0 }, true);+ EntityOps.setVisible(authoredRef(3), false);++ const { edits } = await PlayEdits.harvest();+ expect(edits).toHaveLength(1);+ edits[0].apply();+ expect(SceneCommands.setEntityVisible).toHaveBeenCalledWith(3, false);+ });++ it('applies everything as one undo step', async () => {+ playing();+ realmHolds({ x: 5, y: 5 });+ EntityOps.moveToPoint(authoredRef(3), { canvas: { x: 0.5, y: 0.5 } });+ EntityOps.setVisible(authoredRef(3), false);++ const { edits } = await PlayEdits.harvest();+ PlayEdits.applyAll(edits, 'Keep play changes');+ expect(SceneCommands.transact).toHaveBeenCalledTimes(1);+ expect(SceneCommands.setFieldValue).toHaveBeenCalled();+ expect(SceneCommands.setEntityVisible).toHaveBeenCalled();+ });++ it('has nothing to harvest when nothing was touched', async () => {+ playing();+ const { edits, spawned } = await PlayEdits.harvest();+ expect(edits).toHaveLength(0);+ expect(spawned).toBe(0);+ expect(snapshotMock).not.toHaveBeenCalled(); // no realm round-trip for nothing+ });+});diff --git a/docs/astro/src/content/docs/editor/play.mdx b/docs/astro/src/content/docs/editor/play.mdxindex 6f47b44a3..83e7bdc99 100644--- a/docs/astro/src/content/docs/editor/play.mdx+++ b/docs/astro/src/content/docs/editor/play.mdx@@ -41,6 +41,20 @@ the pointer, where a drag lands — so it is the game's own camera doing the proand a moved entity ends up where the game will draw it. As with any play-time edit, itlasts until Stop.+## Keeping what you changed++Play-time edits end at Stop — that is what makes them safe to make. But the scene+document is never destroyed while the game runs, so the work does not have to be+thrown away: if you changed anything, Stop offers to **keep** it, and the Output Log+lists exactly what that would be. Keeping is one undo step.++What gets kept is the FIELD's value as the running world holds it at Stop, for each+field you touched. So dragging one axis of a position keeps the position — including+an axis a script was driving. The log line shows the value before you decide.++Entities the game spawned cannot be kept: the scene has no row to write them to. Those+are counted in the log rather than silently dropped.+## Autosave & recoveryThe editor periodically snapshots your **unsaved** documents — only when there arediff --git a/docs/astro/src/content/docs/zh-cn/editor/play.mdx b/docs/astro/src/content/docs/zh-cn/editor/play.mdxindex 43fc9c33f..b15115cfe 100644--- a/docs/astro/src/content/docs/zh-cn/editor/play.mdx+++ b/docs/astro/src/content/docs/zh-cn/editor/play.mdx@@ -29,6 +29,17 @@ description: "在隔离 realm 里于编辑器内运行游戏、运行模式选这些问题全部由运行中的世界回答——实体画在哪、指针下是谁、拖拽落到哪——用的是游戏自己的相机做投影,所以移动后的位置就是游戏接下来会画的位置。和任何运行期修改一样,它到停止为止。+## 保留你改过的东西++运行期的改动到停止为止——正因为如此它们才敢随便改。但游戏运行时场景文档从没被销毁,所以这些+工作不必扔掉:只要你改过东西,停止时会问你要不要**保留**,输出日志里列着到底是哪些。保留是+一步撤销。++保留的是你碰过的**那个字段**在停止那一刻的实时值。所以拖了位置的一根轴,保留的是整个位置+——包括某根由脚本驱动的轴。日志会在你决定前把值列出来。++游戏自己创建的实体保留不了:场景里没有对应的行可写。这些会记在日志里,而不是悄悄丢掉。+## 自动保存与恢复编辑器会定期快照你**未保存**的文档——仅在存在未保存改动且没有 Play 会话运行时——所以崩溃或