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(services): a store overlay covers the game the way an ad does
esenginebd2b753aec44
diff --git a/native/host/bindings/SteamBindings.cpp b/native/host/bindings/SteamBindings.cppindex c4deb213b..fe5f8d65f 100644--- a/native/host/bindings/SteamBindings.cpp+++ b/native/host/bindings/SteamBindings.cpp@@ -16,9 +16,20 @@#include "Bindings.hpp"#include "steam/SteamApi.hpp"+#include <cstdlib>+namespace eshost {namespace {+/** Push the overlay's state into JS, where the services layer pauses the game. */+void deliverSteamOverlay(bool covered) {+ HostState& h = host();+ if (!h.js) return;+ JSValue arg = JS_NewBool(h.js, covered);+ callJs(h, "es_onSteamOverlay", 1, &arg);+ JS_FreeValue(h.js, arg);+}+// es_steam_init(appId) -> bool. Called by the SDK, which is where game.config.json// is read — the host has no JSON parser and no reason to grow one.JSValue js_steam_init(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {@@ -28,6 +39,17 @@ JSValue js_steam_init(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv// do on Windows and silently never resolve on macOS (see SteamApi::init).const std::string dir = host().platform ? host().platform->executableDir() : std::string();const bool ok = steam().init(static_cast<uint32_t>(appId), dir);+ if (ok) {+ // The overlay covers the game without changing anything a host can see —+ // the window keeps its focus and stays visible — so this push is the only+ // way the services layer learns to pause.+ steam().onOverlay([](bool covered) { deliverSteamOverlay(covered); });+ if (const char* self = std::getenv("ESTELLA_STEAM_SELFCHECK"); self && self[0] == '1') {+ steam().traceCallbacks(true);+ steam().activateOverlay();+ ESHOST_LOGI("steam: self-check opened the overlay — expecting callback %d", 331);+ }+ }if (!ok && !steam().lastError().empty()) {// Not an error: no client, signed out, or a build that does not ship to// Steam. It reaches the boot record so "achievements did nothing" has andiff --git a/native/host/steam/SteamApi.cpp b/native/host/steam/SteamApi.cppindex e0255ef54..0435494b7 100644--- a/native/host/steam/SteamApi.cpp+++ b/native/host/steam/SteamApi.cpp@@ -96,12 +96,52 @@ using PfnSetStatInt32 = bool (*)(void* self, const char* name, std::int32_t valuusing PfnGetStatInt32 = bool (*)(void* self, const char* name, std::int32_t* out);using PfnGetSteamID = std::uint64_t (*)(void* self);using PfnGetPersonaName = const char* (*)(void* self);+using PfnActivateGameOverlay = void (*)(void* self, const char* dialog);++/**+ * Manual dispatch — how a binding that carries no Valve header reads callbacks.+ *+ * The header's own mechanism is a C++ class whose vtable Steam writes into, which+ * cannot be declared without the header. Valve added these four for exactly this+ * case, and every non-C++ binding uses them.+ */+using PfnManualDispatchInit = void (*)();+using PfnGetHSteamPipe = std::int32_t (*)();+using PfnManualDispatchRunFrame = void (*)(std::int32_t pipe);+using PfnManualDispatchFreeLastCallback = void (*)(std::int32_t pipe);++/** CallbackMsg_t, field for field — the layout the dispatcher writes into. */+struct CallbackMsg {+ std::int32_t steamUser;+ std::int32_t callback;+ std::uint8_t* param;+ std::int32_t paramSize;+};+using PfnManualDispatchGetNextCallback = bool (*)(std::int32_t pipe, CallbackMsg* out);++/**+ * GameOverlayActivated_t — `k_iSteamFriendsCallbacks (300) + 31`.+ *+ * A number, so getting it wrong is a pause that silently never happens. It is+ * checked by a run rather than by reading: ESTELLA_STEAM_SELFCHECK opens the+ * overlay and reports which ids arrived (see Host.cpp).+ */+constexpr std::int32_t kGameOverlayActivated = 331;++/** Its first byte: non-zero while the overlay covers the game. */+constexpr int kOverlayActiveOffset = 0;/** Steam's error buffer is a fixed 1024 bytes (SteamErrMsg). */constexpr int kErrMsgSize = 1024;struct Fns {PfnRunCallbacks runCallbacks = nullptr;+ PfnManualDispatchInit dispatchInit = nullptr;+ PfnGetHSteamPipe getPipe = nullptr;+ PfnManualDispatchRunFrame dispatchRunFrame = nullptr;+ PfnManualDispatchGetNextCallback dispatchNext = nullptr;+ PfnManualDispatchFreeLastCallback dispatchFree = nullptr;+ PfnActivateGameOverlay activateOverlay = nullptr;PfnSetAchievement setAchievement = nullptr;PfnGetAchievement getAchievement = nullptr;PfnClearAchievement clearAchievement = nullptr;@@ -207,6 +247,24 @@ bool SteamApi::init(std::uint32_t appId, const std::string& directory) {symbol(library_, "SteamAPI_ISteamUser_GetSteamID"));g_fns.getPersonaName = reinterpret_cast<PfnGetPersonaName>(symbol(library_, "SteamAPI_ISteamFriends_GetPersonaName"));+ g_fns.activateOverlay = reinterpret_cast<PfnActivateGameOverlay>(+ symbol(library_, "SteamAPI_ISteamFriends_ActivateGameOverlay"));++ // Manual dispatch, AFTER init and before any other dispatch call — that order+ // is Valve's, and the wrong one leaves a pipe that answers nothing.+ g_fns.dispatchInit = reinterpret_cast<PfnManualDispatchInit>(+ symbol(library_, "SteamAPI_ManualDispatch_Init"));+ g_fns.getPipe = reinterpret_cast<PfnGetHSteamPipe>(symbol(library_, "SteamAPI_GetHSteamPipe"));+ g_fns.dispatchRunFrame = reinterpret_cast<PfnManualDispatchRunFrame>(+ symbol(library_, "SteamAPI_ManualDispatch_RunFrame"));+ g_fns.dispatchNext = reinterpret_cast<PfnManualDispatchGetNextCallback>(+ symbol(library_, "SteamAPI_ManualDispatch_GetNextCallback"));+ g_fns.dispatchFree = reinterpret_cast<PfnManualDispatchFreeLastCallback>(+ symbol(library_, "SteamAPI_ManualDispatch_FreeLastCallback"));+ if (g_fns.dispatchInit && g_fns.getPipe) {+ g_fns.dispatchInit();+ pipe_ = g_fns.getPipe();+ }ESHOST_LOGI("steam: up for app %u (%s, %s, %s)", appId, statsVersion, userVersion, friendsVersion);return true;@@ -263,7 +321,28 @@ bool SteamApi::reset() {}void SteamApi::pump() {- if (g_fns.runCallbacks) g_fns.runCallbacks();+ // Manual dispatch REPLACES RunCallbacks — calling both would run each+ // callback twice, once through a queue the other already drained.+ if (pipe_ == 0 || !g_fns.dispatchRunFrame || !g_fns.dispatchNext || !g_fns.dispatchFree) {+ if (g_fns.runCallbacks) g_fns.runCallbacks();+ return;+ }+ g_fns.dispatchRunFrame(pipe_);+ CallbackMsg msg{};+ while (g_fns.dispatchNext(pipe_, &msg)) {+ if (traceCallbacks_) ESHOST_LOGI("steam: callback %d (%d bytes)", msg.callback, msg.paramSize);+ if (msg.callback == kGameOverlayActivated && msg.param && msg.paramSize > kOverlayActiveOffset) {+ const bool covered = msg.param[kOverlayActiveOffset] != 0;+ if (overlay_) overlay_(covered);+ }+ // Every callback, on every path: the dispatcher hands out ONE at a time+ // and will not advance until the last is released.+ g_fns.dispatchFree(pipe_);+ }+}++void SteamApi::activateOverlay() {+ if (friends_ && g_fns.activateOverlay) g_fns.activateOverlay(friends_, "Friends");}} // namespace eshostdiff --git a/native/host/steam/SteamApi.hpp b/native/host/steam/SteamApi.hppindex cad7532fd..9c3a66655 100644--- a/native/host/steam/SteamApi.hpp+++ b/native/host/steam/SteamApi.hpp@@ -24,7 +24,9 @@#pragma once#include <cstdint>+#include <functional>#include <string>+#include <utility>namespace eshost {@@ -77,6 +79,22 @@ class SteamApi {* the game is alive and the overlay never opens. */void pump();+ /**+ * Told when the overlay starts and stops covering the game.+ *+ * A takeover the game never asked for, and one nothing else can observe:+ * the window keeps its focus and stays visible, so a host watching those+ * would see no change at all while the player is somewhere else entirely.+ */+ void onOverlay(std::function<void(bool)> listener) { overlay_ = std::move(listener); }++ /** Open the overlay. Used by the self-check, which is the only way the+ * callback path above can be verified without a person pressing Shift+Tab. */+ void activateOverlay();++ /** Log every callback the dispatcher hands out — the self-check's eyes. */+ void traceCallbacks(bool on) { traceCallbacks_ = on; }+/** Why {@link init} answered false, for the boot record. Empty on success. */const std::string& lastError() const { return error_; }@@ -84,6 +102,10 @@ class SteamApi {void* library_ = nullptr;void* stats_ = nullptr;void* user_ = nullptr;+ /** The dispatch pipe; 0 until manual dispatch is up. */+ std::int32_t pipe_ = 0;+ std::function<void(bool)> overlay_;+ bool traceCallbacks_ = false;void* friends_ = nullptr;std::string error_;};diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 1772a1ee4..7aa3a1c6e 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1476 stable · 17 beta · 1 deprecated+Symbols: 1478 stable · 17 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -145,18 +145,10 @@ setProvider: (provider: AdProvider | null) => voidshowInterstitial: (adUnitId: string) => Promise<void>showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>showing: boolean-static new (host: AdsHost): AdsAPI+static new (takeover: Takeover): AdsAPIstatic prototype: AdsAPI```-## AdsHost — interface-```-isPaused: () => boolean-resumeAudio: () => void-setPaused: (paused: boolean) => void-suspendAudio: () => void-```-## AiAction — type```(@@ -5146,6 +5138,7 @@ onAppShow: ((callback: () => void) => () => void) | undefinedonContextLost: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedonShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined+onStoreOverlay: ((listener: (covered: boolean) => void) => () => void) | undefinedonUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefinedopenDataCanvas: (() => PlatformCanvas | null) | undefinedopenDataPostMessage: ((message: Record<string, unknown>) => void) | undefined@@ -7207,6 +7200,22 @@ numberRecord<string, string | number>```+## Takeover — interface+```+active: boolean+around: <T>(show: () => Promise<T>) => Promise<T>+begin: () => void+end: () => void+```++## TakeoverHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## TerrainColor — interface```color: string@@ -9290,6 +9299,11 @@ Plugin(options: GameSocketOptions): PlatformSocket```+## createTakeover — function+```+(host: TakeoverHost): Takeover+```+## createTextInput — function```(opts: TextInputOptions): TextInputHandlediff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex cea99268b..54afc1a50 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1495 stable · 22 beta · 1 deprecated+Symbols: 1497 stable · 22 beta · 1 deprecated## ABI_LAYOUT_HASH — const```@@ -145,18 +145,10 @@ setProvider: (provider: AdProvider | null) => voidshowInterstitial: (adUnitId: string) => Promise<void>showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>showing: boolean-static new (host: AdsHost): AdsAPI+static new (takeover: Takeover): AdsAPIstatic prototype: AdsAPI```-## AdsHost — interface-```-isPaused: () => boolean-resumeAudio: () => void-setPaused: (paused: boolean) => void-suspendAudio: () => void-```-## AiAction — type```(@@ -4669,6 +4661,7 @@ onAppHide: (callback: () => void) => () => voidonAppShow: (callback: () => void) => () => voidonContextLost: (callback: () => void) => () => voidonMemoryWarning: (callback: () => void) => () => void+onStoreOverlay: (listener: (covered: boolean) => void) => () => voidonUnhandledError: (callback: (error: unknown) => void) => () => voidpollGamepads: () => GamepadSnapshot[]rasterizeGlyph: ((request: PlatformGlyphRequest) => PlatformGlyph | null) | undefined@@ -5325,6 +5318,7 @@ onAppShow: ((callback: () => void) => () => void) | undefinedonContextLost: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedonShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined+onStoreOverlay: ((listener: (covered: boolean) => void) => () => void) | undefinedonUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefinedopenDataCanvas: (() => PlatformCanvas | null) | undefinedopenDataPostMessage: ((message: Record<string, unknown>) => void) | undefined@@ -7396,6 +7390,22 @@ numberRecord<string, string | number>```+## Takeover — interface+```+active: boolean+around: <T>(show: () => Promise<T>) => Promise<T>+begin: () => void+end: () => void+```++## TakeoverHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## TerrainColor — interface```color: string@@ -9519,6 +9529,11 @@ Plugin(options: GameSocketOptions): PlatformSocket```+## createTakeover — function+```+(host: TakeoverHost): Takeover+```+## createTextInput — function```(opts: TextInputOptions): TextInputHandlediff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 9c301e739..672b69326 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1475 stable · 19 beta · 1 deprecated+Symbols: 1477 stable · 19 beta · 1 deprecated## ANCHOR_AXES — const```@@ -140,18 +140,10 @@ setProvider: (provider: AdProvider | null) => voidshowInterstitial: (adUnitId: string) => Promise<void>showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>showing: boolean-static new (host: AdsHost): AdsAPI+static new (takeover: Takeover): AdsAPIstatic prototype: AdsAPI```-## AdsHost — interface-```-isPaused: () => boolean-resumeAudio: () => void-setPaused: (paused: boolean) => void-suspendAudio: () => void-```-## AiAction — type```(@@ -5141,6 +5133,7 @@ onAppShow: ((callback: () => void) => () => void) | undefinedonContextLost: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedonShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined+onStoreOverlay: ((listener: (covered: boolean) => void) => () => void) | undefinedonUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefinedopenDataCanvas: (() => PlatformCanvas | null) | undefinedopenDataPostMessage: ((message: Record<string, unknown>) => void) | undefined@@ -7202,6 +7195,22 @@ numberRecord<string, string | number>```+## Takeover — interface+```+active: boolean+around: <T>(show: () => Promise<T>) => Promise<T>+begin: () => void+end: () => void+```++## TakeoverHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## TerrainColor — interface```color: string@@ -9285,6 +9294,11 @@ Plugin(options: GameSocketOptions): PlatformSocket```+## createTakeover — function+```+(host: TakeoverHost): Takeover+```+## createTextInput — function```(opts: TextInputOptions): TextInputHandlediff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex ce81a24b7..42e25e40b 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1496 stable · 17 beta · 1 deprecated+Symbols: 1498 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -140,18 +140,10 @@ setProvider: (provider: AdProvider | null) => voidshowInterstitial: (adUnitId: string) => Promise<void>showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>showing: boolean-static new (host: AdsHost): AdsAPI+static new (takeover: Takeover): AdsAPIstatic prototype: AdsAPI```-## AdsHost — interface-```-isPaused: () => boolean-resumeAudio: () => void-setPaused: (paused: boolean) => void-suspendAudio: () => void-```-## AiAction — type```(@@ -5386,6 +5378,7 @@ onAppShow: ((callback: () => void) => () => void) | undefinedonContextLost: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedonShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined+onStoreOverlay: ((listener: (covered: boolean) => void) => () => void) | undefinedonUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefinedopenDataCanvas: (() => PlatformCanvas | null) | undefinedopenDataPostMessage: ((message: Record<string, unknown>) => void) | undefined@@ -7447,6 +7440,22 @@ numberRecord<string, string | number>```+## Takeover — interface+```+active: boolean+around: <T>(show: () => Promise<T>) => Promise<T>+begin: () => void+end: () => void+```++## TakeoverHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## TerrainColor — interface```color: string@@ -9535,6 +9544,11 @@ Plugin(options: GameSocketOptions): PlatformSocket```+## createTakeover — function+```+(host: TakeoverHost): Takeover+```+## createTextInput — function```(opts: TextInputOptions): TextInputHandlediff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 6b4eb9338..f5df7bebc 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 1486 stable · 17 beta · 1 deprecated+Symbols: 1488 stable · 17 beta · 1 deprecated## ANCHOR_AXES — const```@@ -140,18 +140,10 @@ setProvider: (provider: AdProvider | null) => voidshowInterstitial: (adUnitId: string) => Promise<void>showRewarded: (adUnitId: string) => Promise<PlatformRewardedAdResult>showing: boolean-static new (host: AdsHost): AdsAPI+static new (takeover: Takeover): AdsAPIstatic prototype: AdsAPI```-## AdsHost — interface-```-isPaused: () => boolean-resumeAudio: () => void-setPaused: (paused: boolean) => void-suspendAudio: () => void-```-## AiAction — type```(@@ -5148,6 +5140,7 @@ onAppShow: ((callback: () => void) => () => void) | undefinedonContextLost: ((callback: () => void) => () => void) | undefinedonMemoryWarning: ((callback: () => void) => () => void) | undefinedonShareRequest: ((provide: () => PlatformShareOptions) => void) | undefined+onStoreOverlay: ((listener: (covered: boolean) => void) => () => void) | undefinedonUnhandledError: ((callback: (error: unknown) => void) => () => void) | undefinedopenDataCanvas: (() => PlatformCanvas | null) | undefinedopenDataPostMessage: ((message: Record<string, unknown>) => void) | undefined@@ -7209,6 +7202,22 @@ numberRecord<string, string | number>```+## Takeover — interface+```+active: boolean+around: <T>(show: () => Promise<T>) => Promise<T>+begin: () => void+end: () => void+```++## TakeoverHost — interface+```+isPaused: () => boolean+resumeAudio: () => void+setPaused: (paused: boolean) => void+suspendAudio: () => void+```+## TerrainColor — interface```color: string@@ -9312,6 +9321,11 @@ Plugin(options: GameSocketOptions): PlatformSocket```+## createTakeover — function+```+(host: TakeoverHost): Takeover+```+## createTextInput — function```(opts: TextInputOptions): TextInputHandlediff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex b56ccf1d9..50f3f9a3c 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -415,13 +415,13 @@ export {export {Achievements, AchievementsAPI, createLocalAchievements,- Ads, AdsAPI, createMockAdProvider,+ Ads, AdsAPI, createMockAdProvider, createTakeover,Share, ShareAPI,Leaderboard, LeaderboardAPI, createLocalLeaderboard,Identity, IdentityAPI, Payment, PaymentAPI,ServicesPlugin, servicesPlugin,type AchievementProvider,- type AdProvider, type AdsHost, type MockAdProviderOptions, type ShareCard,+ type AdProvider, type MockAdProviderOptions, type ShareCard, type Takeover, type TakeoverHost,type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,type LeaderboardStyle, type LocalLeaderboardOptions, type LoginResult,type PaymentRequest, type PaymentFailure,diff --git a/sdk/src/platform/native/adapter.ts b/sdk/src/platform/native/adapter.tsindex bf93f0cb0..3f5230382 100644--- a/sdk/src/platform/native/adapter.ts+++ b/sdk/src/platform/native/adapter.ts@@ -260,6 +260,15 @@ export class NativePlatformAdapter implements PlatformAdapter {return steam?.available() ? steam.identity() : null;}+ /** The store overlay covering the game, and uncovering it. */+ onStoreOverlay(listener: (covered: boolean) => void): () => void {+ const steam = this.bridge_.steam;+ if (!steam) return () => {};+ let live = true;+ steam.onOverlay((covered) => { if (live) listener(covered); });+ return () => { live = false; };+ }+// createSocket / loadSubpackage are optional and deferred to the shell.}diff --git a/sdk/src/platform/native/bridge.ts b/sdk/src/platform/native/bridge.tsindex 4932c3ecd..e491eaf91 100644--- a/sdk/src/platform/native/bridge.ts+++ b/sdk/src/platform/native/bridge.ts@@ -79,6 +79,10 @@ export interface NativeSteamBridge {getStat(name: string): number;store(): boolean;reset(): boolean;+ /** Called when the store's overlay covers the game, and again when it stops.+ * One subscriber: the host pushes to one entry point, and the services layer+ * is what fans it out. */+ onOverlay(listener: (covered: boolean) => void): void;}/** What the OS editing surface reports back. `state` carries the surface's wholediff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.tsindex fbeaddc96..e1b0a8c14 100644--- a/sdk/src/platform/native/hostBridge.ts+++ b/sdk/src/platform/native/hostBridge.ts@@ -224,6 +224,9 @@ export function createHostBridge(getStat: (n: string) => bindings.es_steam_getStat?.(n) ?? 0,store: () => bindings.es_steam_store?.() ?? false,reset: () => bindings.es_steam_reset?.() ?? false,+ onOverlay: (listener: (covered: boolean) => void) => {+ scope.es_onSteamOverlay = (covered: boolean) => listener(covered);+ },},}: {}),diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex 21e427adf..3d5ba97d5 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -449,6 +449,15 @@ export interface PlatformAdapter {* account id do not survive a double. */steamIdentity?(): { id: string; name: string } | null;+ /**+ * Tell me when the store's overlay covers the game, and when it stops.+ *+ * A takeover the game did not ask for: the player pressed Shift+Tab and can+ * no longer act, so it pauses exactly as a fullscreen ad does. Returns an+ * unsubscribe. Absent where no overlay exists, and nothing is missed there.+ */+ onStoreOverlay?(listener: (covered: boolean) => void): () => void;+/** Create the platform audio backend (WebAudio on web, the mini-game audio API* on WeChat). Optional — a host with no audio device (headless node, the* unshipped native shell) omits it and the audio system falls back to thediff --git a/sdk/src/services/ads.ts b/sdk/src/services/ads.tsindex c7c6451fc..67c92d555 100644--- a/sdk/src/services/ads.ts+++ b/sdk/src/services/ads.ts@@ -16,6 +16,7 @@ import { defineResource } from '../ecs/resource';import { platformCreateRewardedAd, platformCreateInterstitialAd, platformCanCreateAds } from '../platform';import type { PlatformRewardedAd, PlatformInterstitialAd, PlatformRewardedAdResult } from '../platform/types';import { log } from '../util/logger';+import type { Takeover } from './takeover';/*** A drop-in ad source for hosts that have none: the editor's play mode, unit@@ -64,24 +65,18 @@ export function createMockAdProvider(options: MockAdProviderOptions = {}): AdPro};}-/** What the ads service asks of the app around a fullscreen takeover. Injected- * so the service stays a pure orchestration (and the tests stay honest). */-export interface AdsHost {- setPaused(paused: boolean): void;- isPaused(): boolean;- suspendAudio(): void;- resumeAudio(): void;-}-export class AdsAPI {- private readonly host_: AdsHost;+ private readonly takeover_: Takeover;private provider_: AdProvider | null = null;private readonly rewarded_ = new Map<string, PlatformRewardedAd>();private readonly interstitials_ = new Map<string, PlatformInterstitialAd>();private showing_ = false;- constructor(host: AdsHost) {- this.host_ = host;+ /** @param takeover The app-wide pause/silence ceremony. Shared rather than+ * private: a store overlay opening during an ad is one covered game, not two+ * (see services/takeover.ts). */+ constructor(takeover: Takeover) {+ this.takeover_ = takeover;}/** Whether SOME ad source exists here — the platform's or an installed@@ -135,20 +130,14 @@ export class AdsAPI {private static readonly NO_SOURCE ='no ad source on this platform — check Ads.available, or install a provider (the editor installs a mock in play mode)';- /** The pause/suspend ceremony around a fullscreen takeover. A game the- * DEVELOPER already paused stays paused afterwards — the ceremony restores- * the state it found, it does not assert one. */+ /** An ad covers the game exactly as a store overlay does; `showing` stays an+ * ADS question, which is why the flag is still here. */private async withTakeover_<T>(show: () => Promise<T>): Promise<T> {- const wasPaused = this.host_.isPaused();this.showing_ = true;- if (!wasPaused) this.host_.setPaused(true);- this.host_.suspendAudio();try {- return await show();+ return await this.takeover_.around(show);} finally {this.showing_ = false;- this.host_.resumeAudio();- if (!wasPaused) this.host_.setPaused(false);}}diff --git a/sdk/src/services/index.ts b/sdk/src/services/index.tsindex e22da40be..96a5407f4 100644--- a/sdk/src/services/index.ts+++ b/sdk/src/services/index.ts@@ -2,8 +2,9 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamexport {Ads, AdsAPI, createMockAdProvider,- type AdProvider, type AdsHost, type MockAdProviderOptions,+ type AdProvider, type MockAdProviderOptions,} from './ads';+export { createTakeover, type Takeover, type TakeoverHost } from './takeover';export { Share, ShareAPI, type ShareCard } from './share';export {Leaderboard, LeaderboardAPI, createLocalLeaderboard,diff --git a/sdk/src/services/servicesPlugin.ts b/sdk/src/services/servicesPlugin.tsindex 0c54c91b5..cd7f2a05c 100644--- a/sdk/src/services/servicesPlugin.ts+++ b/sdk/src/services/servicesPlugin.ts@@ -24,12 +24,17 @@ import { Leaderboard, LeaderboardAPI } from './leaderboard';import { Achievements, AchievementsAPI } from './achievements';import { Identity, IdentityAPI } from './identity';import { Payment, PaymentAPI } from './payment';+import { createTakeover } from './takeover';+import { getPlatform } from '../platform';export class ServicesPlugin implements Plugin {name = 'Services';build(app: App): void {- app.insertResource(Ads, new AdsAPI({+ // ONE ceremony for everything that covers the game. An ad and a store+ // overlay are the same event to a player, and they can overlap — the+ // overlay closing must not resume a game an ad is still covering.+ const takeover = createTakeover({setPaused: (p) => app.setPaused(p),isPaused: () => app.isPaused(),// Resolved per call: the audio plugin builds in the same pass and@@ -37,7 +42,14 @@ export class ServicesPlugin implements Plugin {// a Null backend behind the same API — suspending silence is free.suspendAudio: () => app.getResource(Audio)?.suspend(),resumeAudio: () => app.getResource(Audio)?.resume(),- }));+ });+ app.insertResource(Ads, new AdsAPI(takeover));+ // A takeover the game never asked for: the player pressed Shift+Tab. The+ // platform seam is absent everywhere but a store's own shell, and where+ // it is absent there is nothing that can cover the game.+ getPlatform().onStoreOverlay?.((covered) => {+ if (covered) takeover.begin(); else takeover.end();+ });app.insertResource(Share, new ShareAPI());app.insertResource(Achievements, new AchievementsAPI());app.insertResource(Identity, new IdentityAPI());diff --git a/sdk/src/services/takeover.ts b/sdk/src/services/takeover.tsnew file mode 100644index 000000000..6f7a39c6b--- /dev/null+++ b/sdk/src/services/takeover.ts@@ -0,0 +1,72 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file takeover.ts+ * @brief Something covered the game: pause it, silence it, and put back+ * exactly what was found.+ *+ * A fullscreen ad and a store overlay are the same event as far as the game is+ * concerned — the player is no longer looking at it and no longer able to act.+ * The ceremony was written inside the ads service, which is where it was needed+ * first; the Steam overlay needs the same one, and a second copy would be a+ * second answer to "what happens when a game is covered".+ *+ * ★ Ref-counted, which a single caller never needed: a player can open the Steam+ * overlay DURING an interstitial ad, and the overlay closing must not resume a+ * game the ad is still covering.+ */++/** What a takeover asks of the app. Injected so this stays pure orchestration —+ * and so a test can drive it without an App. */+export interface TakeoverHost {+ setPaused(paused: boolean): void;+ isPaused(): boolean;+ suspendAudio(): void;+ resumeAudio(): void;+}++export interface Takeover {+ /** Something is now covering the game. */+ begin(): void;+ /** …and is not any more. Unbalanced calls are ignored rather than trusted:+ * a store tells you the overlay closed, and nothing guarantees it told you+ * it opened. */+ end(): void;+ /** Whether anything is covering the game right now. */+ readonly active: boolean;+ /** The common case: cover the game for the length of one promise. */+ around<T>(show: () => Promise<T>): Promise<T>;+}++export function createTakeover(host: TakeoverHost): Takeover {+ let depth = 0;+ /** The state to restore. A game the DEVELOPER already paused stays paused+ * afterwards — this restores what it found, it does not assert a state. */+ let wasPaused = false;++ const takeover: Takeover = {+ begin(): void {+ if (depth++ > 0) return;+ wasPaused = host.isPaused();+ if (!wasPaused) host.setPaused(true);+ host.suspendAudio();+ },+ end(): void {+ if (depth === 0 || --depth > 0) return;+ host.resumeAudio();+ if (!wasPaused) host.setPaused(false);+ },+ get active(): boolean {+ return depth > 0;+ },+ async around<T>(show: () => Promise<T>): Promise<T> {+ takeover.begin();+ try {+ return await show();+ } finally {+ takeover.end();+ }+ },+ };+ return takeover;+}diff --git a/sdk/tests/services-ads.test.ts b/sdk/tests/services-ads.test.tsindex 4ec4e8d76..003f2d967 100644--- a/sdk/tests/services-ads.test.ts+++ b/sdk/tests/services-ads.test.ts@@ -9,10 +9,11 @@* stays paused after it.*/import { describe, it, expect } from 'vitest';-import { AdsAPI, createMockAdProvider, type AdsHost, type AdProvider } from '../src/services/ads';+import { AdsAPI, createMockAdProvider, type AdProvider } from '../src/services/ads';+import { createTakeover, type TakeoverHost } from '../src/services/takeover';import { ShareAPI } from '../src/services/share';-function recordingHost(): AdsHost & { events: string[]; paused: boolean } {+function recordingHost(): TakeoverHost & { events: string[]; paused: boolean } {const h = {events: [] as string[],paused: false,@@ -27,7 +28,7 @@ function recordingHost(): AdsHost & { events: string[]; paused: boolean } {describe('AdsAPI takeover ceremony', () => {it('pauses the clock and suspends audio for exactly the span of the ad', async () => {const host = recordingHost();- const ads = new AdsAPI(host);+ const ads = new AdsAPI(createTakeover(host));ads.setProvider(createMockAdProvider({ durationMs: 1 }));const r = await ads.showRewarded('unit-1');@@ -39,7 +40,7 @@ describe('AdsAPI takeover ceremony', () => {it('restores state when the ad errors (no fill twice)', async () => {const host = recordingHost();- const ads = new AdsAPI(host);+ const ads = new AdsAPI(createTakeover(host));const failing: AdProvider = {createRewardedAd: () => ({preload: () => Promise.reject(new Error('no fill')),@@ -59,7 +60,7 @@ describe('AdsAPI takeover ceremony', () => {it('a game the developer paused stays paused after the ad', async () => {const host = recordingHost();host.paused = true;- const ads = new AdsAPI(host);+ const ads = new AdsAPI(createTakeover(host));ads.setProvider(createMockAdProvider({ durationMs: 1 }));await ads.showRewarded('unit-1');@@ -69,14 +70,14 @@ describe('AdsAPI takeover ceremony', () => {});it('reports an abandoned video as not completed', async () => {- const ads = new AdsAPI(recordingHost());+ const ads = new AdsAPI(createTakeover(recordingHost()));ads.setProvider(createMockAdProvider({ durationMs: 1, completed: false }));const r = await ads.showRewarded('unit-1');expect(r.completed).toBe(false);});it('rejects loud when no ad source exists, and says how to get one', async () => {- const ads = new AdsAPI(recordingHost());+ const ads = new AdsAPI(createTakeover(recordingHost()));expect(ads.available).toBe(false);await expect(ads.showRewarded('unit-1')).rejects.toThrow(/no ad source/);});@@ -90,7 +91,7 @@ describe('AdsAPI takeover ceremony', () => {},createInterstitialAd: () => { throw new Error('unused'); },};- const ads = new AdsAPI(recordingHost());+ const ads = new AdsAPI(createTakeover(recordingHost()));ads.setProvider(counting);await ads.showRewarded('a');await ads.showRewarded('a');diff --git a/sdk/tests/services-takeover.test.ts b/sdk/tests/services-takeover.test.tsnew file mode 100644index 000000000..417d50aa4--- /dev/null+++ b/sdk/tests/services-takeover.test.ts@@ -0,0 +1,81 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file The one ceremony for anything that covers the game.+ *+ * A fullscreen ad and a store overlay are the same event to a player, and they+ * OVERLAP: pressing Shift+Tab during an interstitial is ordinary. The rules that+ * a single caller never needed — ref counting, and restoring the state that was+ * found rather than asserting one — are what this pins.+ */+import { describe, it, expect } from 'vitest';+import { createTakeover, type TakeoverHost } from '../src/services/takeover';++function recordingHost(paused = false): TakeoverHost & { events: string[]; paused: boolean } {+ const h = {+ events: [] as string[],+ paused,+ setPaused(p: boolean) { h.paused = p; h.events.push(p ? 'pause' : 'unpause'); },+ isPaused() { return h.paused; },+ suspendAudio() { h.events.push('audio-off'); },+ resumeAudio() { h.events.push('audio-on'); },+ };+ return h;+}++describe('the takeover ceremony', () => {+ it('pauses and silences for exactly the span it covers', () => {+ const host = recordingHost();+ const takeover = createTakeover(host);+ takeover.begin();+ expect(takeover.active).toBe(true);+ takeover.end();+ expect(host.events).toEqual(['pause', 'audio-off', 'audio-on', 'unpause']);+ expect(takeover.active).toBe(false);+ });++ it('leaves a game the developer paused paused', () => {+ // It restores what it found; asserting a state would un-pause a pause+ // menu the moment an ad closed over it.+ const host = recordingHost(true);+ const takeover = createTakeover(host);+ takeover.begin();+ takeover.end();+ expect(host.paused).toBe(true);+ expect(host.events).toEqual(['audio-off', 'audio-on']);+ });++ it('an overlay opening during an ad does not resume the game when it closes', () => {+ // The reason this is ref-counted: the overlay's `end` arrives while the ad+ // is still on screen, and the game must stay covered until the ad ends.+ const host = recordingHost();+ const takeover = createTakeover(host);+ takeover.begin(); // the ad+ takeover.begin(); // Shift+Tab over it+ takeover.end(); // the overlay closes+ expect(host.paused).toBe(true);+ expect(host.events).toEqual(['pause', 'audio-off']);+ takeover.end(); // the ad ends+ expect(host.paused).toBe(false);+ expect(host.events).toEqual(['pause', 'audio-off', 'audio-on', 'unpause']);+ });++ it('ignores an end nobody began', () => {+ // A store reports that its overlay closed; nothing guarantees it reported+ // that it opened, and an unbalanced end would resume a paused game.+ const host = recordingHost(true);+ const takeover = createTakeover(host);+ takeover.end();+ takeover.end();+ expect(host.events).toEqual([]);+ expect(host.paused).toBe(true);+ });++ it('restores through a rejection, because a covered game must not stay covered', async () => {+ const host = recordingHost();+ const takeover = createTakeover(host);+ await expect(takeover.around(() => Promise.reject(new Error('no fill')))).rejects.toThrow('no fill');+ expect(host.paused).toBe(false);+ expect(takeover.active).toBe(false);+ });+});