Skip to content

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.

A tween starts where it says it starts, and the editor stops lying about the game

yhh7419de91cc68
diff --git a/desktop/electron/main.ts b/desktop/electron/main.ts
index 77f035ef0..5368bb665 100644
--- a/desktop/electron/main.ts
+++ b/desktop/electron/main.ts
@@ -73,6 +73,18 @@ import type { WorkspaceState } from '../src/project/format';
// switch the headless verify harness sets.
app.commandLine.appendSwitch('enable-unsafe-webgpu');
+// The window sets `backgroundThrottling: false`, but that only reaches ITS renderer —
+// and the game does not run there. The play realm is a cross-origin (estella://) frame,
+// so it lives in its own renderer process, which Chromium still backgrounds when the
+// window loses focus: rAF drops to about 1 Hz and the running game freezes. Nothing in
+// an editor should stop simulating because you alt-tabbed to read something, and it is
+// worse than a slowdown for anything driving the editor from outside — a probe reads
+// the frozen state and reports a broken feature. These are process-wide, so they cover
+// the realm's renderer too.
+app.commandLine.appendSwitch('disable-background-timer-throttling');
+app.commandLine.appendSwitch('disable-renderer-backgrounding');
+app.commandLine.appendSwitch('disable-backgrounding-occluded-windows');
+
// Two privileged custom schemes (must be declared before app ready):
// • estella:// serves files from the open project root (sandboxed) — lets the
// engine fetch project assets (textures via Assets.loadTexture → fetch).
diff --git a/desktop/scripts/editor-mcp-tools.mjs b/desktop/scripts/editor-mcp-tools.mjs
index 1bb0d6094..d997e21be 100644
--- a/desktop/scripts/editor-mcp-tools.mjs
+++ b/desktop/scripts/editor-mcp-tools.mjs
@@ -232,15 +232,21 @@ export const TOOLS = [
{ name: 'create_scene_file', write: true,
description: 'Create a blank scene FILE under a project-relative directory (does not switch to it); returns its path, immediately referenceable (the registry refresh happens before this resolves). '
+ '`name` names it (the `.esscene` extension is added if absent); without one it is `scene.esscene`, which collides the moment you make a second.',
- schema: obj({ destDir: { type: 'string' }, name: { type: 'string' } }, ['destDir']),
- js: (i) => `window.__estellaEditor.createSceneFile(${JSON.stringify(i.destDir)}, ${JSON.stringify(i.name ?? null)})
+ schema: obj({
+ destDir: { type: 'string' }, name: { type: 'string' },
+ overwrite: { type: 'boolean', description: 'a NAMED scene that already exists is emptied and reused (its uuid is kept, so refs survive) instead of the call being refused' },
+ }, ['destDir']),
+ js: (i) => `window.__estellaEditor.createSceneFile(${JSON.stringify(i.destDir)}, ${JSON.stringify(i.name ?? null)}, ${JSON.stringify({ overwrite: i.overwrite === true })})
.then((p) => window.__estellaEditor.refreshAssets().then(() => p))` },
{ name: 'create_prefab_from_entity', write: true,
description: 'Extract an entity and its subtree into a `.esprefab` asset under assets/prefabs/ (the Outliner\'s Create Prefab), named after the entity; returns its `@uuid:` ref. '
+ 'This is what makes a subtree REUSABLE: afterwards `list_entity_templates` offers it as `prefab:<path>`, and creating with that template makes a real INSTANCE — the scene stores a delta, not a copy, so editing the prefab updates every instance. '
+ 'Without it a driver can build the same panel chrome into twenty scenes but never share it. Refs pointing OUT of the subtree cannot live in a standalone prefab and are cleared.',
- schema: obj({ entity: { type: 'number' } }, ['entity']),
- js: (i) => `window.__estellaEditor.createPrefabFromEntity(${Number(i.entity)})
+ schema: obj({
+ entity: { type: 'number' },
+ replace: { type: 'boolean', description: 'overwrite the asset this name already maps to, KEEPING its uuid — what re-extracting a prefab means. Without it the name is deduped to "<name>-1.esprefab" and every existing instance keeps pointing at the stale asset.' },
+ }, ['entity']),
+ js: (i) => `window.__estellaEditor.createPrefabFromEntity(${Number(i.entity)}, ${JSON.stringify({ replace: i.replace === true })})
.then((ref) => { if (!ref) throw new Error('could not create a prefab from entity ${Number(i.entity)} — it may not exist'); return ref; })` },
{ name: 'create_asset', write: true,
description: 'Create a text asset file under a project-relative directory with the given content. `type` is the meta vocabulary: scene, prefab, shader, material, animclip (.esanim), animation (.estimeline), tileset, statemachine (.esfsm), behaviortree (.esbt), locale, inputmap, tilemap (.tmj). A bare baseName gets the type\'s canonical extension appended. Returns the project-relative path, immediately referenceable (the registry refresh happens before this resolves).',
@@ -278,6 +284,10 @@ export const TOOLS = [
.then((text) => window.__estellaEditor.applyOps(JSON.parse(text), ${JSON.stringify(i.label ?? null)}))`
: null),
method: 'applyOps', args: (i) => [i.ops, i.label], root: 'editor' },
+ { name: 'refresh_assets', write: true,
+ description: 'Re-scan the project into the asset registry. The editor watches the filesystem, but a batch written from outside (a converter copying twenty sprites in) can outrun the watcher — and until the scan lands those files have no `.meta`, so `set_import_settings` and any @uuid ref to them fail. Cheap and idempotent; call it after writing assets by hand.',
+ schema: obj({}),
+ js: () => 'window.__estellaEditor.refreshAssets().then(() => true)' },
{ name: 'list_assets',
description: 'Search the open project\'s asset registry. `match` is a case-insensitive SUBSTRING of the project-relative path (not a glob); `type` filters by asset type (texture, scene, prefab, audio, font, material, shader...). '
+ 'Returns { total, assets: [{ ref, path, name, type }] } — `total` is the full match count, `assets` is capped by `limit` (default 200). The `ref` is the stable @uuid: form to write into asset fields.',
@@ -328,7 +338,9 @@ export const TOOLS = [
description: 'Toggle play mode in the editor (check get_play_state first; play runs the game in an isolated realm and never dirties the edit scene).',
schema: obj({}), method: 'play', args: () => [], root: 'editor' },
{ name: 'get_play_state',
- description: 'The play realm state: { playing, ready, error }.',
+ description: 'The play realm state: { playing, ready, error, fps, frameCount }. '
+ + 'CHECK `fps` BEFORE CONCLUDING ANYTHING FROM A PROBE: the realm runs in an out-of-process iframe whose rAF Chromium throttles to ~1/s while the editor window is unfocused, '
+ + 'so a game that looks frozen (an animation that never advances, a tween stuck at its start) is usually a background window, not a bug. `fps` is null until the first heartbeat (~0.5s after Play).',
schema: obj({}), method: 'playState', args: () => [], root: 'editor' },
{ name: 'screenshot',
description: 'Capture the composited editor window as a PNG (includes the play realm iframe — use this to SEE gameplay; capture_viewport only sees the edit viewport).',
diff --git a/desktop/src/engine/PlayRealm.ts b/desktop/src/engine/PlayRealm.ts
index d4aed3997..d8000b88a 100644
--- a/desktop/src/engine/PlayRealm.ts
+++ b/desktop/src/engine/PlayRealm.ts
@@ -47,6 +47,13 @@ export interface PlayRealmSnapshot {
playing: boolean;
ready: boolean;
error: string | null;
+ /** Frames per second the realm is ACTUALLY running, from its own heartbeat. An
+ * unfocused window has the realm's rAF throttled to about 1 — which looks exactly
+ * like a frozen game to anything driving the editor from outside. `null` until the
+ * first heartbeat arrives. */
+ fps: number | null;
+ /** The realm's engine frame counter at that heartbeat. */
+ frameCount: number;
}
export class PlayRealmInstance {
@@ -59,7 +66,9 @@ export class PlayRealmInstance {
// (single-player primary only; multiplayer + play-in-window cold-boot as before).
private warm = false;
private warmedResolve: (() => void) | null = null;
- private readonly store = createStore<PlayRealmSnapshot>(() => ({ playing: false, ready: false, error: null }));
+ private readonly store = createStore<PlayRealmSnapshot>(() => ({
+ playing: false, ready: false, error: null, fps: null, frameCount: 0,
+ }));
constructor(readonly id: number) {}
@@ -186,7 +195,7 @@ export class PlayRealmInstance {
if (this.warm && this.id === 0) {
if (this.iframe) this.iframe.style.visibility = 'hidden';
this.setPaused(true); // freeze the world so a hidden realm doesn't keep simulating
- this.set({ playing: false, ready: false, error: null });
+ this.set({ playing: false, ready: false, error: null, fps: null, frameCount: 0 });
return;
}
if (this.iframe) {
@@ -194,7 +203,7 @@ export class PlayRealmInstance {
this.iframe.src = 'about:blank';
}
this.warm = false;
- this.set({ playing: false, ready: false, error: null });
+ this.set({ playing: false, ready: false, error: null, fps: null, frameCount: 0 });
}
/** Drop the staged realm but keep the iframe + listener (reusable): cold
@@ -330,6 +339,9 @@ export class PlayRealmInstance {
else this.post({ type: 'estella:play:warm' });
break;
}
+ case 'estella:play:frames':
+ this.set({ fps: data.fps ?? 0, frameCount: data.frameCount ?? 0 });
+ break;
case 'estella:play:log':
// The running game's console/wasm output, forwarded from the realm iframe so
// it lands in the editor's Output Log (it runs in a separate JS realm, so the
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index cde9f05d2..a9e7e2541 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -136,4 +136,8 @@ export type PlayInbound =
| { type: 'estella:play:ready'; phases?: Record<string, number> }
| { type: 'estella:play:error'; message: string }
| { type: 'estella:play:log'; level: PlayLogLevel; line: string }
+ // How fast the realm is actually running. "Playing" and "running frames" are not the
+ // same thing — an unfocused window has its realm's rAF throttled to about 1 Hz — and
+ // a driver reading a frozen game needs to be able to tell those apart.
+ | { type: 'estella:play:frames'; frameCount: number; fps: number }
| { type: 'estella:play:reply'; reqId: number; data: unknown };
diff --git a/desktop/src/main.tsx b/desktop/src/main.tsx
index 74c730fba..6f74646c9 100644
--- a/desktop/src/main.tsx
+++ b/desktop/src/main.tsx
@@ -216,8 +216,8 @@ if (new URLSearchParams(location.search).has('automation')) {
/** Patch the project's physics feature (Project Settings → Physics). */
setPhysics: (patch: Record<string, unknown>) => ProjectStore.setPhysics(patch),
/** Create a blank scene FILE under `destDir` (Content Browser "New Scene"). */
- createSceneFile: (destDir: string, name?: string | null) =>
- ProjectStore.createSceneFile(destDir, name ?? undefined),
+ createSceneFile: (destDir: string, name?: string | null, opts?: { overwrite?: boolean }) =>
+ ProjectStore.createSceneFile(destDir, name ?? undefined, opts),
/**
* Extract an entity's subtree into a `.esprefab` asset (the Outliner's Create
* Prefab), returning its `@uuid:` ref.
@@ -228,7 +228,8 @@ if (new URLSearchParams(location.search).has('automation')) {
* data and asset refs are serialized by the code that owns that format rather
* than by a caller guessing at it.
*/
- createPrefabFromEntity: (id: number) => ProjectStore.createPrefabFromEntity(id),
+ createPrefabFromEntity: (id: number, opts?: { replace?: boolean }) =>
+ ProjectStore.createPrefabFromEntity(id, opts),
/** The Create-popover catalog: every ready-made entity the editor can spawn —
* including the open project's own components and prefabs, so automation sees
* the same list a person does. */
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index f8855c0ef..db295a479 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -185,6 +185,37 @@ function jsonMap(json: string | undefined): Record<string, number> {
* initRendererWithContext early-returns once the renderer is live, so the GL +
* EstellaContext are reused, not rebuilt — only the App + a fresh ECS Registry
* are new. */
+/**
+ * Tell the editor how fast the realm is actually running.
+ *
+ * "Playing" is not the same as "running frames": this realm is an out-of-process
+ * iframe, so Chromium throttles its rAF to about once a second whenever the window is
+ * not focused — and a driver that cannot see that reads the frozen result as a broken
+ * feature. The engine's own frame counter is read on a timer (timers survive that
+ * throttling), so the cost is one message every half second and nothing per frame.
+ */
+function startFrameHeartbeat(): void {
+ if (heartbeat != null) return;
+ let lastFrames = 0;
+ let lastAt = performance.now();
+ heartbeat = setInterval(() => {
+ const time = app?.getResourceByName('Time') as { frameCount?: number } | undefined;
+ const frames = time?.frameCount ?? 0;
+ const now = performance.now();
+ const seconds = (now - lastAt) / 1000;
+ post({
+ type: 'estella:play:frames',
+ frameCount: frames,
+ fps: seconds > 0 ? Math.round(((frames - lastFrames) / seconds) * 10) / 10 : 0,
+ });
+ lastFrames = frames;
+ lastAt = now;
+ }, HEARTBEAT_MS) as unknown as number;
+}
+
+const HEARTBEAT_MS = 500;
+let heartbeat: number | null = null;
+
async function buildAppAndRun(msg: InitMessage): Promise<void> {
const module = engineModule!;
app = createWebApp(module, {
@@ -232,6 +263,7 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
// main-process frame eval, and the eval needs SOMETHING to query. getComponent
// lets a probe read component data by name (world.get needs the def).
(window as unknown as { __estellaPlay?: unknown }).__estellaPlay = { app, getComponent };
+ startFrameHeartbeat();
// Surface a failed handshake as a boot error rather than a silent
// half-session (the app keeps running; the role reverted to offline).
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index 9d4527a70..626694fa0 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -668,13 +668,27 @@ class ProjectStoreImpl {
* Browser's "New Scene" — writes it to disk WITHOUT switching the editor to it
* (unlike {@link newScene}). Returns its project-relative path.
*/
- async createSceneFile(destDir: string, name?: string): Promise<string> {
+ async createSceneFile(destDir: string, name?: string, opts?: { overwrite?: boolean }): Promise<string> {
const content = JSON.stringify(this.blankScene(), null, 2) + '\n';
// A bare name takes the extension, so a caller naming scenes in bulk does not
// have to know it. Nameless keeps the Content Browser's "New Scene" default.
const base = name?.trim()
? (name.trim().endsWith('.esscene') ? name.trim() : `${name.trim()}.esscene`)
: 'scene.esscene';
+ // Creating over a name that is taken DEDUPES ("main 2.esscene"), which is right for
+ // the Content Browser's New Scene and wrong for anything driving the editor by name:
+ // a re-run gets a second scene nobody opens while the game keeps the first. So a
+ // named collision is answered here — emptied on request (the uuid is kept, so refs
+ // to the scene survive), and otherwise refused with the flag that would allow it.
+ const rel = `${destDir.replace(/\/$/, '')}/${base}`;
+ if (name?.trim() && this.pathToUuid.has(rel)) {
+ if (!opts?.overwrite) {
+ throw new Error(`"${rel}" already exists — pass overwrite to empty it, or use another name`);
+ }
+ await window.estella.fs.write(rel, content);
+ await this.refreshAssets();
+ return rel;
+ }
return window.estella.project.createAsset(destDir, base, content, 'scene');
}
@@ -905,7 +919,17 @@ class ProjectStoreImpl {
path: string,
patch: Record<string, unknown>,
): Promise<Record<string, unknown>> {
- const meta = JSON.parse(await window.estella.fs.read(path + '.meta'));
+ // The `.meta` is written by the import scan, so a file that has only just been
+ // copied into the project may not have one yet — the watcher is fast but a batch
+ // (a panel's worth of sprites) outruns it. Scanning once and retrying turns "the
+ // importer settings for the fifth of twenty sprites failed" into a non-event.
+ let raw = await window.estella.fs.readOptional(path + '.meta');
+ if (raw === null) {
+ await this.refreshAssets();
+ raw = await window.estella.fs.readOptional(path + '.meta');
+ }
+ if (raw === null) throw new Error(`no import settings for "${path}" — the file is not in the project`);
+ const meta = JSON.parse(raw);
let importer = (meta.importer as Record<string, unknown>) ?? {};
for (const [key, value] of Object.entries(patch)) {
importer = applyImporterEdit(importer, key, value as never);
@@ -1445,7 +1469,7 @@ class ProjectStoreImpl {
* DB so the prefab is immediately draggable. Non-destructive: the source
* entities are left as-is. Returns the new prefab's `@uuid:` ref, or null.
*/
- async createPrefabFromEntity(rootSourceId: number): Promise<string | null> {
+ async createPrefabFromEntity(rootSourceId: number, opts?: { replace?: boolean }): Promise<string | null> {
const root = SceneModel.entityBySource(rootSourceId);
if (!root) return null;
const entities = SceneModel.collectSubtree(rootSourceId)
@@ -1471,9 +1495,16 @@ class ProjectStoreImpl {
// A filesystem-safe leaf, deduped against existing assets.
const base = name.replace(/[^A-Za-z0-9_-]+/g, '_') || 'Prefab';
let rel = `assets/prefabs/${base}.esprefab`;
- for (let n = 1; this.pathToUuid.has(rel); n++) rel = `assets/prefabs/${base}-${n}.esprefab`;
+ // `replace` is what re-extracting a prefab means: same asset, new contents. Deduping
+ // instead would write `<name>-1.esprefab` and leave every instance in the project
+ // pointing at the stale one — a silent no-op for the caller who asked for an update.
+ // The uuid is KEPT for the same reason: refs are by uuid, and a new one orphans them.
+ const existingUuid = opts?.replace ? this.pathToUuid.get(rel) : undefined;
+ if (!existingUuid) {
+ for (let n = 1; this.pathToUuid.has(rel); n++) rel = `assets/prefabs/${base}-${n}.esprefab`;
+ }
- const uuid = crypto.randomUUID();
+ const uuid = existingUuid ?? crypto.randomUUID();
try {
await window.estella.fs.write(rel, JSON.stringify(prefab, null, 2) + '\n');
await window.estella.fs.write(
diff --git a/desktop/tests/editor-mcp-tools.test.ts b/desktop/tests/editor-mcp-tools.test.ts
index 306554ef2..09ddaf8e5 100644
--- a/desktop/tests/editor-mcp-tools.test.ts
+++ b/desktop/tests/editor-mcp-tools.test.ts
@@ -264,3 +264,35 @@ describe('the prefab-mode doors', () => {
expect(res.content[0].text).toMatch(/not part of a prefab instance/);
});
});
+
+describe('re-running an authoring step is not a new asset', () => {
+ it('create_scene_file passes the overwrite decision down, defaulting to refusing', async () => {
+ const driver = Object.assign(vi.fn(async () => '"assets/scenes/shop.esscene"'), {
+ js: vi.fn(async () => '"assets/scenes/shop.esscene"'),
+ });
+ const tool = TOOLS.find((t: { name: string }) => t.name === 'create_scene_file');
+
+ await runTool(tool, driver, { destDir: 'assets/scenes', name: 'shop' });
+ expect(driver.js.mock.calls[0][0]).toContain('{"overwrite":false}');
+
+ await runTool(tool, driver, { destDir: 'assets/scenes', name: 'shop', overwrite: true });
+ expect(driver.js.mock.calls[1][0]).toContain('{"overwrite":true}');
+ });
+
+ it('create_prefab_from_entity can replace the asset it already named', async () => {
+ const driver = Object.assign(vi.fn(async () => '"@uuid:x"'), { js: vi.fn(async () => '"@uuid:x"') });
+ const tool = TOOLS.find((t: { name: string }) => t.name === 'create_prefab_from_entity');
+
+ await runTool(tool, driver, { entity: 7, replace: true });
+ expect(driver.js.mock.calls[0][0]).toContain('createPrefabFromEntity(7, {"replace":true})');
+ });
+
+ it('refresh_assets is a plain renderer call — the scan a batch import needs', async () => {
+ const driver = Object.assign(vi.fn(async () => 'true'), { js: vi.fn(async () => 'true') });
+ const tool = TOOLS.find((t: { name: string }) => t.name === 'refresh_assets');
+ expect(tool).toBeTruthy();
+
+ await runTool(tool, driver, {});
+ expect(driver.js.mock.calls[0][0]).toContain('refreshAssets()');
+ });
+});
diff --git a/src/esengine/animation/TweenSystem.cpp b/src/esengine/animation/TweenSystem.cpp
index 84f73760e..360647866 100644
--- a/src/esengine/animation/TweenSystem.cpp
+++ b/src/esengine/animation/TweenSystem.cpp
@@ -34,6 +34,13 @@ void TweenSystem::update(ecs::Registry& registry, f32 deltaTime) {
if (tween.delay > 0.0f) {
tween.delay -= deltaTime;
if (tween.delay > 0.0f) {
+ // HOLD the start value while waiting, rather than leaving the target
+ // wherever it was. `from` is what the caller said the tween starts at,
+ // and a delay is "start later", not "start elsewhere" — without this a
+ // staggered entrance sits in its final place and only then jumps out to
+ // animate in. It also keeps UI layout off the animated axis for the
+ // whole wait, since the override flag is set by the write.
+ applyValue(registry, tween, tween.from_value);
continue;
}
deltaTime = -tween.delay;
@@ -98,6 +105,11 @@ Entity TweenSystem::createTween(ecs::Registry& registry, Entity targetEntity,
tween.duration = duration;
tween.easing = easing;
tween.state = TweenState::Running;
+ // Take the start value NOW, not on the next update: a tween created after this
+ // frame's tween pass would otherwise leave one frame showing the target where it
+ // was — and for an entrance, where it was IS where the tween is taking it, so the
+ // motion appears to play, stop, and play again.
+ applyValue(registry, tween, from);
return tweenEntity;
}