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
fix(scene): fade transition propagates load errors and waits for swap
esenginec2c95bbb8e56
diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.tsindex 06ade6aa3..4d30736cb 100644--- a/sdk/src/sceneManager.ts+++ b/sdk/src/sceneManager.ts@@ -65,7 +65,23 @@ export interface TransitionOptions {onComplete?: () => void;}-type TransitionPhase = 'fade-out' | 'fade-in';+/**+ * Fade transition runs in three phases:+ * - fade-out: overlay alpha ramps 0 → 1 over duration/2+ * - loading: overlay stays fully opaque while the old scene unloads and the+ * new one loads. Visual hold absorbs any load latency and prevents a+ * black-screen flash if the swap takes longer than the timer.+ * - fade-in: overlay alpha ramps 1 → 0 over duration/2+ *+ * Only a completed fade-in resolves the caller's promise. Any failure during+ * the `loading` phase rejects it with the original error.+ */+type TransitionPhase = 'fade-out' | 'loading' | 'fade-in';++type SwitchOutcome =+ | { readonly status: 'pending' }+ | { readonly status: 'success' }+ | { readonly status: 'error'; readonly error: unknown };interface TransitionState {phase: TransitionPhase;@@ -76,6 +92,8 @@ interface TransitionState {options: TransitionOptions;resolve: () => void;reject: (reason?: unknown) => void;+ /** Outcome of the in-flight doSwitch() during the `loading` phase. */+ outcome: SwitchOutcome;}const TRANSITION_CALLBACK_ID = '__scene_transition_overlay__';@@ -268,13 +286,24 @@ export class SceneManagerState {options,resolve,reject,+ outcome: { status: 'pending' },};registerDrawCallback(TRANSITION_CALLBACK_ID, () => {if (!this.transition_) return;const halfDuration = this.transition_.duration / 2;- const t = Math.min(this.transition_.elapsed / halfDuration, 1);- const alpha = this.transition_.phase === 'fade-out' ? t : 1 - t;+ let alpha: number;+ switch (this.transition_.phase) {+ case 'fade-out':+ alpha = Math.min(this.transition_.elapsed / halfDuration, 1);+ break;+ case 'loading':+ alpha = 1;+ break;+ case 'fade-in':+ alpha = Math.max(1 - this.transition_.elapsed / halfDuration, 0);+ break;+ }Draw.setLayer(9999);Draw.setDepth(9999);Draw.rect(@@ -292,30 +321,68 @@ export class SceneManagerState {this.transition_.elapsed += dt;const halfDuration = this.transition_.duration / 2;+ // Phase 1 → 2: fade-out reached full opacity. Start the swap, hold+ // the overlay fully opaque while it runs.if (this.transition_.phase === 'fade-out' && this.transition_.elapsed >= halfDuration) {- this.transition_.phase = 'fade-in';+ this.transition_.phase = 'loading';this.transition_.elapsed = 0;- const { targetScene, options } = this.transition_;+ const transition = this.transition_;+ const { targetScene, options } = transition;const oldScene = this.activeScene_;- const doSwitch = async () => {+ // Fire-and-forget; we observe completion via `transition.outcome`.+ // Errors are recorded there rather than rejecting the transition+ // promise directly so the outcome check below owns the cleanup path+ // (avoids racing with a transition_ that may have been cleared).+ void (async () => {try {if (oldScene && oldScene !== targetScene) {await this.unload(oldScene, options);}await this.load(targetScene);+ // Only record success if this transition is still the+ // in-flight one (cancel/replace could have reassigned).+ if (this.transition_ === transition) {+ transition.outcome = { status: 'success' };+ }} catch (err) {log.error('scene', 'Scene transition failed', err);- const { reject: rejectTransition } = this.transition_!;- this.transition_ = null;- unregisterDrawCallback(TRANSITION_CALLBACK_ID);- rejectTransition(err);+ if (this.transition_ === transition) {+ transition.outcome = { status: 'error', error: err };+ } else {+ // Transition was replaced mid-flight; nothing to reject.+ }}- };- doSwitch().catch(() => {});+ })();+ }++ // Phase 2 → 3 or reject: loading phase checks whether the swap has+ // finished this frame. Elapsed is clamped to 0 so the overlay never+ // fades back in prematurely — visual hold until the outcome is known.+ if (this.transition_.phase === 'loading') {+ const outcome = this.transition_.outcome;+ if (outcome.status === 'pending') {+ this.transition_.elapsed = 0;+ return;+ }+ if (outcome.status === 'error') {+ const { reject, options } = this.transition_;+ this.transition_ = null;+ unregisterDrawCallback(TRANSITION_CALLBACK_ID);+ // Still call onComplete? No — onComplete signals success. Keep+ // it scoped to the successful path.+ void options;+ reject(outcome.error);+ return;+ }+ // success → start fade-in+ this.transition_.phase = 'fade-in';+ this.transition_.elapsed = 0;+ return;}+ // Phase 3: fade-in done → resolve caller's promise.if (this.transition_.phase === 'fade-in' && this.transition_.elapsed >= halfDuration) {const { resolve, options } = this.transition_;this.transition_ = null;diff --git a/sdk/tests/scene-transition-errors.test.ts b/sdk/tests/scene-transition-errors.test.tsnew file mode 100644index 000000000..713a40bc9--- /dev/null+++ b/sdk/tests/scene-transition-errors.test.ts@@ -0,0 +1,156 @@+/**+ * @file scene-transition-errors.test.ts+ * @brief Fade transitions propagate load/unload errors to the switchTo+ * promise instead of silently resolving after the visual timer.+ */+import { describe, expect, it, beforeEach, vi } from 'vitest';++vi.mock('../src/scene', () => ({+ loadSceneWithAssets: vi.fn().mockResolvedValue(new Map()),+}));+vi.mock('../src/customDraw', () => ({+ registerDrawCallback: vi.fn(),+ unregisterDrawCallback: vi.fn(),+}));+vi.mock('../src/postprocess', () => ({+ PostProcess: { bind: vi.fn(), unbind: vi.fn() },+ PostProcessStack: vi.fn(),+}));+vi.mock('../src/material', () => ({+ Material: { release: vi.fn(), createShader: vi.fn() },+ defineResource: vi.fn(),+}));+vi.mock('../src/asset', () => ({+ Assets: {+ releaseTexture: vi.fn(),+ releaseFont: vi.fn(),+ releaseMaterial: vi.fn(),+ releaseAll: vi.fn(),+ },+ discoverSceneAssets: vi.fn().mockReturnValue({ textures: [], fonts: [], spines: [], audios: [], unresolved: [] }),+ preloadSceneAssets: vi.fn().mockResolvedValue({ loadedTextures: new Set(), loadedFonts: new Set(), loadedMaterials: new Set(), missing: [] }),+}));++import { SceneManagerState } from '../src/sceneManager';++function waitMicrotask(): Promise<void> {+ return new Promise(r => setTimeout(r, 0));+}++function createMockApp() {+ const entities = new Map<number, Map<symbol, any>>();+ let nextEntity = 1;+ const resources = new Map<any, any>();++ const world = {+ spawn: vi.fn(() => {+ const e = nextEntity++;+ entities.set(e, new Map());+ return e;+ }),+ despawn: vi.fn((e: number) => entities.delete(e)),+ valid: vi.fn((e: number) => entities.has(e)),+ has: vi.fn((e: number, comp: symbol) => entities.get(e)?.has(comp) ?? false),+ get: vi.fn((e: number, comp: symbol) => entities.get(e)?.get(comp)),+ insert: vi.fn((e: number, comp: symbol, data: any) => {+ if (!entities.has(e)) entities.set(e, new Map());+ entities.get(e)!.set(comp, data);+ }),+ set: vi.fn((e: number, comp: symbol, data: any) => {+ if (!entities.has(e)) entities.set(e, new Map());+ entities.get(e)!.set(comp, data);+ }),+ remove: vi.fn((e: number, comp: symbol) => {+ entities.get(e)?.delete(comp);+ }),+ };++ return {+ world,+ hasResource: vi.fn((key: any) => resources.has(key)),+ getResource: vi.fn((key: any) => resources.get(key)),+ addSystemToSchedule: vi.fn(),+ };+}++describe('SceneManager fade transition error handling', () => {+ let app: ReturnType<typeof createMockApp>;+ let manager: SceneManagerState;++ beforeEach(() => {+ app = createMockApp();+ manager = new SceneManagerState(app as any);+ });++ it('rejects switchTo when the new scene fails to load', async () => {+ manager.register({ name: 'start', data: { version: '1.0', name: 'Test', entities: [] } });+ manager.register({+ name: 'boom',+ data: { version: '1.0', name: 'Test', entities: [] },+ setup: () => { throw new Error('setup blew up'); },+ });+ await manager.load('start');++ const promise = manager.switchTo('boom', { transition: 'fade', duration: 0.1 });+ const recorded: unknown[] = [];+ promise.catch(e => { recorded.push(e); });++ // Drive the transition to and through the loading phase.+ manager.updateTransition(0.06); // fade-out half → loading+ await new Promise(r => setTimeout(r, 10)); // let async setup fail+ manager.updateTransition(0.0); // loading sees error → reject++ await waitMicrotask();+ await waitMicrotask();++ expect(recorded).toHaveLength(1);+ expect((recorded[0] as Error).message).toMatch(/setup blew up/);+ // Transition state must be cleared even on failure.+ expect(manager.isTransitioning()).toBe(false);+ });++ it('does not resolve the fade promise while loading is still pending', async () => {+ let finishLoad: (() => void) | null = null;+ let loadStartedResolve!: () => void;+ const loadStarted = new Promise<void>(r => { loadStartedResolve = r; });+ manager.register({+ name: 'slow',+ data: { version: '1.0', name: 'Test', entities: [] },+ setup: () => new Promise<void>(resolveSlow => {+ loadStartedResolve();+ finishLoad = resolveSlow;+ }),+ });+ manager.register({ name: 'start', data: { version: '1.0', name: 'Test', entities: [] } });+ await manager.load('start');++ let resolved = false;+ let rejected = false;+ const promise = manager.switchTo('slow', { transition: 'fade', duration: 0.1 });+ promise.then(() => { resolved = true; }, () => { rejected = true; });++ manager.updateTransition(0.06); // fade-out → loading+ await loadStarted; // ensure setup has begun++ // Even if we drive updateTransition well past the full fade duration,+ // the caller's promise must remain pending until load completes.+ for (let i = 0; i < 5; i++) {+ manager.updateTransition(0.1);+ await waitMicrotask();+ }+ expect(resolved).toBe(false);+ expect(rejected).toBe(false);+ expect(manager.isTransitioning()).toBe(true);++ // Complete the load → loading phase observes success → fade-in begins.+ finishLoad!();+ await waitMicrotask();+ await waitMicrotask();+ manager.updateTransition(0.0); // loading → fade-in+ manager.updateTransition(0.06); // fade-in done+ await promise;++ expect(resolved).toBe(true);+ expect(manager.isTransitioning()).toBe(false);+ });+});diff --git a/sdk/tests/sceneManager.test.ts b/sdk/tests/sceneManager.test.tsindex a42ea0e53..f1f2c0f16 100644--- a/sdk/tests/sceneManager.test.ts+++ b/sdk/tests/sceneManager.test.ts@@ -833,11 +833,14 @@ describe('SceneManager', () => {});await Promise.resolve();- // Complete fade-out (half = 0.5)+ // Complete fade-out (half = 0.5) → enters loading phase.manager.updateTransition(0.6);await new Promise(r => setTimeout(r, 10));- // Complete fade-in (half = 0.5)+ // Flush the loading-phase outcome; sees success → flips to fade-in.+ manager.updateTransition(0.0);++ // Complete fade-in (half = 0.5).manager.updateTransition(0.6);expect(manager.isTransitioning()).toBe(false);