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(app): App.setRunInBackground keeps the loop going while the page is hidden
yhh12a3517a6075
diff --git a/desktop b/desktopindex 9ee210d7e..b43c06857 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 9ee210d7e7b00284ab7b0e85a53879490265ba71+Subproject commit b43c0685777ead176ed1f4566d74c9bec6bf2db5diff --git a/sdk/src/app/app.ts b/sdk/src/app/app.tsindex eafa36b64..b4d65f01b 100644--- a/sdk/src/app/app.ts+++ b/sdk/src/app/app.ts@@ -175,6 +175,10 @@ export class App {private readonly executionObservers_: Array<(held: boolean) => void> = [];private loopVersion_ = 0;private queuedFrame_: number | null = null;+ /** Whether {@link queuedFrame_} is a timer (hidden + runInBackground) rather than a rAF id. */+ private queuedOnTimer_ = false;+ private runInBackground_ = false;+ private onVisibility_: (() => void) | null = null;private frameInFlight_: Promise<void> | null = null;private frameTiming_: { seq: number; frameMs: number } | null = null;private lastTime_ = 0;@@ -887,6 +891,38 @@ export class App {(globalThis as { es_setTargetFrameRate?: (fps: number) => void }).es_setTargetFrameRate?.(fps > 0 ? fps : 0);}+ /**+ * Keep simulating while the page is hidden — a window behind others, a+ * minimized one, or one never shown (an editor driven by automation).+ *+ * A browser stops `requestAnimationFrame` for a hidden document, so without+ * this the game holds still there: what a shipped game wants, since nobody is+ * watching and the battery is. An editor's Play wants the opposite; Unity+ * calls the same switch `Application.runInBackground`. While hidden the loop+ * runs on a timer at the frame cap (60 fps when uncapped).+ */+ setRunInBackground(on: boolean): void {+ this.runInBackground_ = on;+ if (typeof document === 'undefined') return;+ if (on && !this.onVisibility_) {+ // A rAF queued just before the page hid never fires: move it to the timer.+ this.onVisibility_ = () => {+ if (this.queuedFrame_ === null || this.queuedOnTimer_ || document.visibilityState !== 'hidden') return;+ if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.queuedFrame_);+ this.queuedFrame_ = null;+ this.queueLoopFrame_();+ };+ document.addEventListener('visibilitychange', this.onVisibility_);+ } else if (!on && this.onVisibility_) {+ document.removeEventListener('visibilitychange', this.onVisibility_);+ this.onVisibility_ = null;+ }+ }++ getRunInBackground(): boolean {+ return this.runInBackground_;+ }+getTargetFrameRate(): number {return this.targetFrameInterval_ > 0 ? 1000 / this.targetFrameInterval_ : 0;}@@ -1310,8 +1346,9 @@ export class App {private invalidateLoop_(): void {this.loopVersion_++;- if (this.queuedFrame_ !== null && typeof cancelAnimationFrame === 'function') {- cancelAnimationFrame(this.queuedFrame_);+ if (this.queuedFrame_ !== null) {+ if (this.queuedOnTimer_) clearTimeout(this.queuedFrame_);+ else if (typeof cancelAnimationFrame === 'function') cancelAnimationFrame(this.queuedFrame_);}this.queuedFrame_ = null;}@@ -1320,6 +1357,18 @@ export class App {if (this.isExecutionHeld() || this.queuedFrame_ !== null) return;if (typeof requestAnimationFrame !== 'function') return;const version = this.loopVersion_;+ const hidden = typeof document !== 'undefined' && document.visibilityState === 'hidden';+ if (hidden && this.runInBackground_) {+ // No rAF arrives for a hidden document; a timer at the frame cadence does.+ this.queuedOnTimer_ = true;+ this.queuedFrame_ = setTimeout(() => {+ if (version !== this.loopVersion_) return;+ this.queuedFrame_ = null;+ void this.mainLoop(platformNow(), version);+ }, this.targetFrameInterval_ > 0 ? this.targetFrameInterval_ : 1000 / 60) as unknown as number;+ return;+ }+ this.queuedOnTimer_ = false;this.queuedFrame_ = requestAnimationFrame((time) => {if (version !== this.loopVersion_) return;this.queuedFrame_ = null;@@ -1387,6 +1436,7 @@ export class App {this.executionHolds_.clear();if (this.hasResource(Input)) setInputExecutionHeld(this.getResource(Input), this, false);this.invalidateLoop_();+ this.setRunInBackground(false);this.running_ = false;for (let i = this.installed_plugins_.length - 1; i >= 0; i--) {diff --git a/sdk/tests/app-run-in-background.test.ts b/sdk/tests/app-run-in-background.test.tsnew file mode 100644index 000000000..a005c63bf--- /dev/null+++ b/sdk/tests/app-run-in-background.test.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * A hidden document gets no requestAnimationFrame. A game that asked to run in+ * the background (an editor's Play) keeps ticking on a timer; one that did not+ * holds still, which is what a shipped game wants.+ */+import { describe, it, expect, vi, afterEach } from 'vitest';+import { App } from '../src/app/app';+import { defineSystem } from '../src/ecs/system';+import { setPlatform } from '../src/platform/base';+import type { PlatformAdapter } from '../src/platform/types';++const realRaf = globalThis.requestAnimationFrame;+const realCancel = globalThis.cancelAnimationFrame;+const realDocument = (globalThis as { document?: unknown }).document;++function hiddenPage(): { fire: () => void } {+ const listeners = new Set<() => void>();+ const doc = {+ visibilityState: 'visible' as 'visible' | 'hidden',+ addEventListener: (_t: string, fn: () => void) => listeners.add(fn),+ removeEventListener: (_t: string, fn: () => void) => listeners.delete(fn),+ };+ (globalThis as { document?: unknown }).document = doc;+ return { fire: () => { doc.visibilityState = 'hidden'; for (const fn of listeners) fn(); } };+}++afterEach(() => {+ vi.useRealTimers();+ globalThis.requestAnimationFrame = realRaf;+ globalThis.cancelAnimationFrame = realCancel;+ (globalThis as { document?: unknown }).document = realDocument;+});++describe('App.setRunInBackground', () => {+ for (const on of [true, false]) {+ it(on ? 'keeps ticking while the page is hidden' : 'holds still while the page is hidden, by default', async () => {+ vi.useFakeTimers();+ // rAF never fires: the page is hidden.+ globalThis.requestAnimationFrame = () => 1;+ globalThis.cancelAnimationFrame = () => undefined;+ let now = 1000;+ setPlatform({ now: () => now } as unknown as PlatformAdapter);+ const page = hiddenPage();+ const app = App.new();+ let frames = 0;+ app.addSystem(defineSystem([], () => { frames++; }, { name: 'Count' }));+ if (on) app.setRunInBackground(true);+ await app.run();+ for (let i = 0; i < 50; i++) await Promise.resolve();+ const started = frames;+ page.fire();+ for (let i = 0; i < 10; i++) { now += 17; await vi.advanceTimersByTimeAsync(17); }+ if (on) expect(frames - started).toBeGreaterThanOrEqual(8);+ else expect(frames).toBe(started);+ app.quit();+ });+ }+});