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(native): Steam behind the achievements service, loaded not linked
esengine4a4cc85e0899
diff --git a/build-tools/cli.js b/build-tools/cli.jsindex 455b79d86..4d5a6ea52 100644--- a/build-tools/cli.js+++ b/build-tools/cli.js@@ -167,6 +167,7 @@ program.option('--dawn-build <dir>', 'Dawn build dir for this target (default: <dawn>/out-<target>, built if absent)').option('--quickjs <dir>', 'QuickJS-ng source dir (default: the pinned checkout; or ESTELLA_QUICKJS_DIR)').option('--sdl <dir>', 'Desktop: SDL3 source dir or install prefix (default: the pinned checkout; or ESTELLA_SDL_DIR)')+ .option('--steam-sdk <dir>', 'Desktop template: a Steamworks SDK on this machine; its redistributable rides along so games get achievements with no setup').option('--macos-archs <archs>', 'Desktop: CMAKE_OSX_ARCHITECTURES (arm64, or "arm64;x86_64" for a universal build)').option('--macos-min <version>', 'Desktop: macOS deployment target').option('--abi <abi>', 'Android ABI', 'arm64-v8a')@@ -203,6 +204,7 @@ programdawnBuild: options.dawnBuild,quickjs: options.quickjs,sdl: options.sdl,+ steamSdk: options.steamSdk,macosArchs: options.macosArchs,macosMin: options.macosMin,abi: options.abi,diff --git a/build-tools/tasks/native.js b/build-tools/tasks/native.jsindex 16130a882..d1c80e776 100644--- a/build-tools/tasks/native.js+++ b/build-tools/tasks/native.js@@ -394,7 +394,9 @@ async function buildDesktopHost(options) {// Same rule as the other two: the compiled half is project-independent, so it// is packed as the template every package is assembled from.if (options.template !== false) {- await emitNativeTemplate({ platform: target, root: rootDir, zipTo: options.templateOut });+ await emitNativeTemplate({+ platform: target, root: rootDir, zipTo: options.templateOut, steamSdk: options.steamSdk,+ });}logger.info(`Run an export with: ${path.relative(rootDir, exe)} <exported-project-dir>`);return exe;@@ -838,7 +840,10 @@ export async function buildNative(options = {}) {if (isDesktopTarget(target)) {if (options.package) return packageDesktopApp(options);if (options.templateOnly) {- return emitNativeTemplate({ platform: target, root: config.paths.root, zipTo: options.templateOut });+ return emitNativeTemplate({+ platform: target, root: config.paths.root, zipTo: options.templateOut,+ steamSdk: options.steamSdk,+ });}return buildDesktopHost(options);}diff --git a/build-tools/tasks/nativeTemplateEmit.js b/build-tools/tasks/nativeTemplateEmit.jsindex a3f2b26fd..ed285a57c 100644--- a/build-tools/tasks/nativeTemplateEmit.js+++ b/build-tools/tasks/nativeTemplateEmit.js@@ -141,6 +141,9 @@ export async function emitNativeTemplate(options) {const ctx = {root,+ // A Steamworks SDK on THIS machine. The redistributable is copied from it+ // into the template; nothing about it is committed.+ steamSdk: options.steamSdk,dawnLibrary: options.dawnLibrary,libcxxShared: (abi) => (platform === 'android' && options.ndk && ABI_TRIPLE[abi]? ndkLibcxxShared(options.ndk, ABI_TRIPLE[abi]) : null),diff --git a/build-tools/utils/desktopApp.js b/build-tools/utils/desktopApp.jsindex 80f60e09b..1dd6d6bad 100644--- a/build-tools/utils/desktopApp.js+++ b/build-tools/utils/desktopApp.js@@ -100,10 +100,11 @@ export async function assembleDesktopApp(options) {await cp(sources.bytecode, path.join(content, path.basename(sources.bytecode)));}- // Whatever else the runtime needs beside the executable. On Windows that is- // the HLSL compiler Dawn loads before it can create a device at all.- if (platform === 'windows' && existsSync(sources.d3dCompiler)) {- await cp(sources.d3dCompiler, path.join(root, path.basename(sources.d3dCompiler)));+ // What the runtime needs beside the executable: Dawn's HLSL compiler (Windows)+ // and Steam's redistributable, which the host dlopens if present. Copied rather+ // than required — a template without one still produces a game.+ for (const dll of [sources.d3dCompiler, sources.steamRedist]) {+ if (dll && existsSync(dll)) await cp(dll, path.join(root, path.basename(dll)));}const iconPng = options.iconPng && existsSync(options.iconPng) ? options.iconPng : sources.icon;diff --git a/build-tools/utils/nativeTemplate.d.ts b/build-tools/utils/nativeTemplate.d.tsindex 8871b2d3d..c613e593c 100644--- a/build-tools/utils/nativeTemplate.d.ts+++ b/build-tools/utils/nativeTemplate.d.ts@@ -122,6 +122,10 @@ export function desktopTemplateSources(dir: string, platform?: NativePlatform):infoPlistIn: string;icon: string;bytecode: string;+ /** Windows only. */+ d3dCompiler: string;+ /** Steam's redistributable, when the template was emitted with an SDK. */+ steamRedist: string;};export function iosTemplateSources(dir: string): {diff --git a/build-tools/utils/nativeTemplate.js b/build-tools/utils/nativeTemplate.jsindex 40db80775..c5b2897de 100644--- a/build-tools/utils/nativeTemplate.js+++ b/build-tools/utils/nativeTemplate.js@@ -47,6 +47,21 @@ export const DEFAULT_ICON = 'icon.png';*/export const D3D_COMPILER = 'd3dcompiler_47.dll';+/** Steam's redistributable, per platform — the filename the host dlopens. */+export const STEAM_REDIST = {+ windows: 'steam_api64.dll',+ macos: 'libsteam_api.dylib',+ linux: 'libsteam_api.so',+};++/** The redistributable inside a Steamworks SDK checkout, or null. */+function steamRedist(sdkDir, platform) {+ if (!sdkDir) return null;+ const sub = { windows: 'win64', macos: 'osx', linux: 'linux64' }[platform];+ const file = path.join(sdkDir, 'redistributable_bin', sub, STEAM_REDIST[platform]);+ return existsSync(file) ? file : null;+}+/** Where the Windows SDK keeps the redistributable D3D compiler, newest first. */function windowsSdkD3DRedist() {const root = 'C:/Program Files (x86)/Windows Kits/10/Redist/D3D/x64';@@ -143,6 +158,13 @@ export function templateLayout(platform, options = {}) {rel: D3D_COMPILER, releaseRequired: true, optional: true,from: () => windowsSdkD3DRedist(),}] : []),+ // Steam's redistributable, from an SDK on the BUILD machine+ // (`--steam-sdk <dir>`) and never from this repository. Optional — a+ // template without it still packages every game.+ {+ rel: STEAM_REDIST[platform], optional: true,+ from: (ctx) => steamRedist(ctx.steamSdk, platform),+ },{ rel: DEFAULT_ICON, from: (ctx) => path.join(ctx.root, 'native', 'icon.png') },];}@@ -458,5 +480,7 @@ export function desktopTemplateSources(dir, platform = 'macos') {bytecode: path.join(dir, BYTECODE_FILE),/** Windows only; absent elsewhere. */d3dCompiler: path.join(dir, D3D_COMPILER),+ /** Steam's redistributable, when the template was emitted with an SDK. */+ steamRedist: path.join(dir, STEAM_REDIST[platform] ?? STEAM_REDIST.macos),};}diff --git a/desktop/src/project/runtimeConfig.ts b/desktop/src/project/runtimeConfig.tsindex 23d186330..668a96c24 100644--- a/desktop/src/project/runtimeConfig.ts+++ b/desktop/src/project/runtimeConfig.ts@@ -48,6 +48,9 @@ export interface RuntimeProjectConfig {/** The achievement ids the project declares — the set the runtime refuses an* unlock outside of. Empty ⇒ nothing is checked. */achievements: string[];+ /** The Steam application id, when the desktop build ships to Steam. 0 ⇒ it does+ * not, and no runtime tries to bring a client up. */+ steamAppId: number;/** Install physics even when the static scene shows no bodies (runtime-spawned). */physicsEnabled: boolean;/** World solver + collision matrix (Project Settings → Physics). */@@ -123,6 +126,11 @@ export function runtimeConfigOf(const f = manifest.features;return {achievements: manifest.packaging?.achievements ?? [],+ // Only when the channel is actually Steam: an app id left behind by a project+ // that has since gone back to a standalone build must not make the runtime+ // hunt for a client.+ steamAppId: manifest.packaging?.platforms?.desktop?.channel === 'steam'+ ? (manifest.packaging?.platforms?.desktop?.steam?.appId ?? 0) : 0,physicsEnabled: f?.physics?.enabled ?? false,physicsConfig: physicsConfigOf(f),audioConfig: f?.audio ?? {},@@ -139,7 +147,7 @@ export function runtimeConfigOf(export type PackagedRuntimeFields = Pick<PackagedGameConfig,'ySortLayers' | 'depthLayers' | 'colorSpace' | 'screenFit' | 'uiTheme' | 'uiThemeColors'- | 'physicsEnabled' | 'physicsConfig' | 'audioConfig' | 'achievements'+ | 'physicsEnabled' | 'physicsConfig' | 'audioConfig' | 'achievements' | 'steamAppId'>;/**@@ -167,6 +175,7 @@ export function packagedRuntimeFields(rc: RuntimeProjectConfig): PackagedRuntime...(isDefaultPhysics(rc.physicsConfig) ? {} : { physicsConfig: rc.physicsConfig }),...(rc.audioConfig.buses?.length ? { audioConfig: rc.audioConfig } : {}),...(rc.achievements.length ? { achievements: rc.achievements } : {}),+ ...(rc.steamAppId > 0 ? { steamAppId: rc.steamAppId } : {}),};}diff --git a/native/CMakeLists.txt b/native/CMakeLists.txtindex f6821d9bb..58ba579e3 100644--- a/native/CMakeLists.txt+++ b/native/CMakeLists.txt@@ -298,6 +298,8 @@ if(ESTELLA_QUICKJS_DIR)host/bindings/AssetBindings.cpphost/bindings/AudioBindings.cpphost/bindings/InputBindings.cpp+ $<$<BOOL:${ESTELLA_DESKTOP}>:host/steam/SteamApi.cpp>+ $<$<BOOL:${ESTELLA_DESKTOP}>:host/bindings/SteamBindings.cpp>host/bindings/NetBindings.cpphost/bindings/TextEditorBindings.cpphost/media/native_audio.cpp@@ -349,6 +351,7 @@ if(ESTELLA_QUICKJS_DIR)add_executable(estella_js_host ${HOST_SOURCES} host/platform/desktop.cpp${DESKTOP_OS_SOURCES})set_target_properties(estella_js_host PROPERTIES OUTPUT_NAME estella_desktop)+ target_compile_definitions(estella_js_host PRIVATE ESTELLA_DESKTOP)target_link_libraries(estella_js_host esengine estella_physics estella_video estella_spineestella_dragonbones qjs SDL3::SDL3)if(ESTELLA_WINDOWS)diff --git a/native/host/Bindings.hpp b/native/host/Bindings.hppindex 6b299d73e..98af3b25b 100644--- a/native/host/Bindings.hpp+++ b/native/host/Bindings.hpp@@ -52,6 +52,10 @@ void registerAudioBindings(HostState& h, JSValue global);* pushed; see InputBindings.cpp. */void registerInputBindings(HostState& h, JSValue global);+/** es_steam_* — the store's half of achievements. Desktop only: bound where a+ * Steam client can exist, and answering `available: false` where one cannot. */+void registerSteamBindings(HostState& h, JSValue global);+/** es_fetch over the platform's native networking. */void registerNetBindings(HostState& h, JSValue global);diff --git a/native/host/Host.cpp b/native/host/Host.cppindex 43115df97..08082eb48 100644--- a/native/host/Host.cpp+++ b/native/host/Host.cpp@@ -22,6 +22,9 @@#include "esengine/bindings/ActiveContext.hpp" // g_activeContext — the context the generated bindings act on#include "Shot.hpp"+#if defined(ESTELLA_DESKTOP)+#include "steam/SteamApi.hpp"+#endif#include "esengine/core/Log.hpp"#include "esengine/core/World.hpp"#include "esengine/ecs/TransformSystem.hpp"@@ -335,6 +338,11 @@ void frame() {// cameras and drove RenderFrame through the es_renderer_* bindings. What is// left here is what only a host can do: flip the swapchain.if (!jsOwnsFrame(h)) fallbackFrame(h);+#if defined(ESTELLA_DESKTOP)+ // Steam's callbacks, once per frame: without them the client never learns the+ // game is alive and the overlay never opens.+ steam().pump();+#endifh.gfx->present();if (shotAfterPresent(*h.gfx)) h.quitRequested = true;if (++h.frame % 120 == 0) ESHOST_LOGI("real-SDK frame %llu", (unsigned long long)h.frame);diff --git a/native/host/Runtime.cpp b/native/host/Runtime.cppindex 20614dec8..70e6df741 100644--- a/native/host/Runtime.cpp+++ b/native/host/Runtime.cpp@@ -420,6 +420,9 @@ void initRuntime(HostState& h) {registerAssetBindings(h, global);registerAudioBindings(h, global);registerInputBindings(h, global);+#if defined(ESTELLA_DESKTOP)+ registerSteamBindings(h, global);+#endifregisterNetBindings(h, global);registerTextEditorBindings(h, global);diff --git a/native/host/bindings/SteamBindings.cpp b/native/host/bindings/SteamBindings.cppnew file mode 100644index 000000000..c10f6336b--- /dev/null+++ b/native/host/bindings/SteamBindings.cpp@@ -0,0 +1,104 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file SteamBindings.cpp+ * @brief `es_steam_*` — the store's half of the achievements service.+ * @details Bound only where a Steam client can exist (desktop). The SDK installs+ * its Steam provider when `es_steam_available()` says yes, and keeps the+ * local one otherwise, so a game's code is the same either way.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "Bindings.hpp"+#include "steam/SteamApi.hpp"++namespace eshost {+namespace {++// 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) {+ int32_t appId = 0;+ if (argc < 1 || JS_ToInt32(ctx, &appId, argv[0]) < 0 || appId <= 0) return JS_NewBool(ctx, false);+ const bool ok = steam().init(static_cast<uint32_t>(appId));+ 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 an+ // answer that is not a guess.+ ESHOST_LOGI("steam: unavailable — %s", steam().lastError().c_str());+ }+ return JS_NewBool(ctx, ok);+}++JSValue js_steam_available(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ return JS_NewBool(ctx, steam().available());+}++// es_steam_identity() -> { id, name }: the signed-in account. The id is a STRING+// because a 64-bit account id does not survive a double.+JSValue js_steam_identity(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ JSValue o = JS_NewObject(ctx);+ JS_SetPropertyStr(ctx, o, "id", JS_NewString(ctx, steam().steamId().c_str()));+ JS_SetPropertyStr(ctx, o, "name", JS_NewString(ctx, steam().personaName().c_str()));+ return o;+}++const char* argString(JSContext* ctx, JSValueConst v, std::string& keep) {+ const char* s = JS_ToCString(ctx, v);+ keep = s ? s : "";+ if (s) JS_FreeCString(ctx, s);+ return keep.c_str();+}++JSValue js_steam_unlock(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ std::string id;+ if (argc < 1) return JS_NewBool(ctx, false);+ return JS_NewBool(ctx, steam().unlock(argString(ctx, argv[0], id)));+}++JSValue js_steam_unlocked(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ std::string id;+ if (argc < 1) return JS_NewBool(ctx, false);+ return JS_NewBool(ctx, steam().unlocked(argString(ctx, argv[0], id)));+}++JSValue js_steam_setStat(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ std::string name;+ int32_t value = 0;+ if (argc < 2 || JS_ToInt32(ctx, &value, argv[1]) < 0) return JS_NewBool(ctx, false);+ return JS_NewBool(ctx, steam().setStat(argString(ctx, argv[0], name), value));+}++JSValue js_steam_getStat(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv) {+ std::string name;+ if (argc < 1) return JS_NewInt32(ctx, 0);+ return JS_NewInt32(ctx, steam().stat(argString(ctx, argv[0], name)));+}++JSValue js_steam_store(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ return JS_NewBool(ctx, steam().store());+}++JSValue js_steam_reset(JSContext* ctx, JSValueConst, int, JSValueConst*) {+ return JS_NewBool(ctx, steam().reset());+}++} // namespace++void registerSteamBindings(HostState& h, JSValue global) {+ bindGlobal(h, global, "es_steam_init", js_steam_init, 1);+ bindGlobal(h, global, "es_steam_available", js_steam_available, 0);+ bindGlobal(h, global, "es_steam_identity", js_steam_identity, 0);+ bindGlobal(h, global, "es_steam_unlock", js_steam_unlock, 1);+ bindGlobal(h, global, "es_steam_unlocked", js_steam_unlocked, 1);+ bindGlobal(h, global, "es_steam_setStat", js_steam_setStat, 2);+ bindGlobal(h, global, "es_steam_getStat", js_steam_getStat, 1);+ bindGlobal(h, global, "es_steam_store", js_steam_store, 0);+ bindGlobal(h, global, "es_steam_reset", js_steam_reset, 0);+}++} // namespace eshostdiff --git a/native/host/steam/SteamApi.cpp b/native/host/steam/SteamApi.cppnew file mode 100644index 000000000..4435faa1e--- /dev/null+++ b/native/host/steam/SteamApi.cpp@@ -0,0 +1,262 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file SteamApi.cpp+ * @brief The dynamic load and the flat-API calls. See the header for why this+ * is loaded rather than linked.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#include "steam/SteamApi.hpp"++#include <cstdio>+#include <cstring>++#include "Runtime.hpp" // ESHOST_LOGI / ESHOST_LOGE++#if defined(_WIN32)+#include <windows.h>+#else+#include <dlfcn.h>+#endif++namespace eshost {+namespace {++/** The library's name, per platform — the redistributable's own filename. */+#if defined(_WIN32)+constexpr const char* kSteamLibrary = "steam_api64.dll";+#elif defined(__APPLE__)+constexpr const char* kSteamLibrary = "libsteam_api.dylib";+#else+constexpr const char* kSteamLibrary = "libsteam_api.so";+#endif++/**+ * The accessor names to try, newest first.+ *+ * ★ The accessor carries the INTERFACE VERSION in its name, so one hard-coded+ * name means a newer redistributable silently has no achievements. A window is+ * tried, and none resolving is reported rather than vanishing.+ */+constexpr const char* kUserStatsAccessors[] = {+ "SteamAPI_SteamUserStats_v014", "SteamAPI_SteamUserStats_v013",+ "SteamAPI_SteamUserStats_v012", "SteamAPI_SteamUserStats_v011",+};+constexpr const char* kUserAccessors[] = {+ "SteamAPI_SteamUser_v024", "SteamAPI_SteamUser_v023", "SteamAPI_SteamUser_v022",+};+constexpr const char* kFriendsAccessors[] = {+ "SteamAPI_SteamFriends_v018", "SteamAPI_SteamFriends_v017", "SteamAPI_SteamFriends_v016",+};++void* openLibrary(const char* name) {+#if defined(_WIN32)+ return reinterpret_cast<void*>(LoadLibraryA(name));+#else+ return dlopen(name, RTLD_LAZY | RTLD_LOCAL);+#endif+}++void closeLibrary(void* handle) {+ if (!handle) return;+#if defined(_WIN32)+ FreeLibrary(reinterpret_cast<HMODULE>(handle));+#else+ dlclose(handle);+#endif+}++void* symbol(void* handle, const char* name) {+ if (!handle) return nullptr;+#if defined(_WIN32)+ return reinterpret_cast<void*>(GetProcAddress(reinterpret_cast<HMODULE>(handle), name));+#else+ return dlsym(handle, name);+#endif+}++/** The subset of the flat API this host calls, declared here because the point is+ * to carry no Valve header. Signatures transcribed from steam_api_flat.h. */+using PfnInitFlat = int (*)(char* outErrMsg); // ESteamAPIInitResult; 0 == OK+using PfnShutdown = void (*)();+using PfnRunCallbacks = void (*)();+using PfnRestartAppIfNecessary = bool (*)(std::uint32_t appId);+using PfnAccessor = void* (*)();+using PfnSetAchievement = bool (*)(void* self, const char* name);+using PfnGetAchievement = bool (*)(void* self, const char* name, bool* achieved);+using PfnClearAchievement = bool (*)(void* self, const char* name);+using PfnStoreStats = bool (*)(void* self);+using PfnResetAllStats = bool (*)(void* self, bool alsoAchievements);+using PfnSetStatInt32 = bool (*)(void* self, const char* name, std::int32_t value);+using PfnGetStatInt32 = bool (*)(void* self, const char* name, std::int32_t* out);+using PfnGetSteamID = std::uint64_t (*)(void* self);+using PfnGetPersonaName = const char* (*)(void* self);++/** Steam's error buffer is a fixed 1024 bytes (SteamErrMsg). */+constexpr int kErrMsgSize = 1024;++struct Fns {+ PfnRunCallbacks runCallbacks = nullptr;+ PfnSetAchievement setAchievement = nullptr;+ PfnGetAchievement getAchievement = nullptr;+ PfnClearAchievement clearAchievement = nullptr;+ PfnStoreStats storeStats = nullptr;+ PfnResetAllStats resetAllStats = nullptr;+ PfnSetStatInt32 setStat = nullptr;+ PfnGetStatInt32 getStat = nullptr;+ PfnGetSteamID getSteamID = nullptr;+ PfnGetPersonaName getPersonaName = nullptr;+ PfnShutdown shutdown = nullptr;+};+Fns g_fns;++/** Resolve the first accessor that exists, and say which. */+void* resolveInterface(void* lib, const char* const* names, int count, const char** chosen) {+ for (int i = 0; i < count; ++i) {+ if (auto fn = reinterpret_cast<PfnAccessor>(symbol(lib, names[i]))) {+ *chosen = names[i];+ return fn();+ }+ }+ return nullptr;+}++} // namespace++SteamApi& steam() {+ static SteamApi instance;+ return instance;+}++bool SteamApi::init(std::uint32_t appId) {+ if (library_) return available();+ error_.clear();++ library_ = openLibrary(kSteamLibrary);+ if (!library_) {+ // Ordinary: a build that does not ship to Steam has no reason to carry it.+ error_ = std::string(kSteamLibrary) + " is not beside the executable";+ return false;+ }++ auto initFlat = reinterpret_cast<PfnInitFlat>(symbol(library_, "SteamAPI_InitFlat"));+ g_fns.shutdown = reinterpret_cast<PfnShutdown>(symbol(library_, "SteamAPI_Shutdown"));+ g_fns.runCallbacks = reinterpret_cast<PfnRunCallbacks>(symbol(library_, "SteamAPI_RunCallbacks"));+ if (!initFlat) {+ error_ = "SteamAPI_InitFlat is missing — the library is not a Steamworks redistributable";+ closeLibrary(library_);+ library_ = nullptr;+ return false;+ }++ char message[kErrMsgSize] = {};+ const int result = initFlat(message);+ if (result != 0) {+ // No client running, not signed in, or the app is not owned. None of these+ // is a defect, and each has to reach the boot record in Steam's own words.+ error_ = message[0] ? message : "SteamAPI_InitFlat failed";+ closeLibrary(library_);+ library_ = nullptr;+ return false;+ }++ const char* statsVersion = "";+ const char* userVersion = "";+ const char* friendsVersion = "";+ stats_ = resolveInterface(library_, kUserStatsAccessors,+ (int)(sizeof(kUserStatsAccessors) / sizeof(char*)), &statsVersion);+ user_ = resolveInterface(library_, kUserAccessors,+ (int)(sizeof(kUserAccessors) / sizeof(char*)), &userVersion);+ friends_ = resolveInterface(library_, kFriendsAccessors,+ (int)(sizeof(kFriendsAccessors) / sizeof(char*)), &friendsVersion);+ if (!stats_) {+ error_ = "no ISteamUserStats accessor resolved — this redistributable is newer than the "+ "versions this host knows (see kUserStatsAccessors)";+ ESHOST_LOGE("steam: %s", error_.c_str());+ shutdown();+ return false;+ }++ g_fns.setAchievement = reinterpret_cast<PfnSetAchievement>(+ symbol(library_, "SteamAPI_ISteamUserStats_SetAchievement"));+ g_fns.getAchievement = reinterpret_cast<PfnGetAchievement>(+ symbol(library_, "SteamAPI_ISteamUserStats_GetAchievement"));+ g_fns.clearAchievement = reinterpret_cast<PfnClearAchievement>(+ symbol(library_, "SteamAPI_ISteamUserStats_ClearAchievement"));+ g_fns.storeStats = reinterpret_cast<PfnStoreStats>(+ symbol(library_, "SteamAPI_ISteamUserStats_StoreStats"));+ g_fns.resetAllStats = reinterpret_cast<PfnResetAllStats>(+ symbol(library_, "SteamAPI_ISteamUserStats_ResetAllStats"));+ g_fns.setStat = reinterpret_cast<PfnSetStatInt32>(+ symbol(library_, "SteamAPI_ISteamUserStats_SetStatInt32"));+ g_fns.getStat = reinterpret_cast<PfnGetStatInt32>(+ symbol(library_, "SteamAPI_ISteamUserStats_GetStatInt32"));+ g_fns.getSteamID = reinterpret_cast<PfnGetSteamID>(+ symbol(library_, "SteamAPI_ISteamUser_GetSteamID"));+ g_fns.getPersonaName = reinterpret_cast<PfnGetPersonaName>(+ symbol(library_, "SteamAPI_ISteamFriends_GetPersonaName"));++ ESHOST_LOGI("steam: up for app %u (%s, %s, %s)", appId, statsVersion, userVersion, friendsVersion);+ return true;+}++void SteamApi::shutdown() {+ if (g_fns.shutdown) g_fns.shutdown();+ closeLibrary(library_);+ library_ = nullptr;+ stats_ = user_ = friends_ = nullptr;+ g_fns = Fns{};+}++std::string SteamApi::steamId() const {+ if (!user_ || !g_fns.getSteamID) return {};+ char buf[32];+ std::snprintf(buf, sizeof(buf), "%llu",+ static_cast<unsigned long long>(g_fns.getSteamID(user_)));+ return buf;+}++std::string SteamApi::personaName() const {+ if (!friends_ || !g_fns.getPersonaName) return {};+ const char* name = g_fns.getPersonaName(friends_);+ return name ? name : "";+}++bool SteamApi::unlock(const char* id) {+ return stats_ && g_fns.setAchievement && g_fns.setAchievement(stats_, id);+}++bool SteamApi::unlocked(const char* id) const {+ bool achieved = false;+ if (stats_ && g_fns.getAchievement) g_fns.getAchievement(stats_, id, &achieved);+ return achieved;+}++bool SteamApi::setStat(const char* name, std::int32_t value) {+ return stats_ && g_fns.setStat && g_fns.setStat(stats_, name, value);+}++std::int32_t SteamApi::stat(const char* name) const {+ std::int32_t value = 0;+ if (stats_ && g_fns.getStat) g_fns.getStat(stats_, name, &value);+ return value;+}++bool SteamApi::store() {+ return stats_ && g_fns.storeStats && g_fns.storeStats(stats_);+}++bool SteamApi::reset() {+ return stats_ && g_fns.resetAllStats && g_fns.resetAllStats(stats_, true);+}++void SteamApi::pump() {+ if (g_fns.runCallbacks) g_fns.runCallbacks();+}++} // namespace eshostdiff --git a/native/host/steam/SteamApi.hpp b/native/host/steam/SteamApi.hppnew file mode 100644index 000000000..cad0839e3--- /dev/null+++ b/native/host/steam/SteamApi.hpp@@ -0,0 +1,88 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file SteamApi.hpp+ * @brief Steam, reached by loading its library at run time and resolving the+ * flat C API — so this binary contains no Valve code and no Valve header.+ * @details The engine ships as ONE prebuilt runtime template that every desktop+ * game is assembled around. Linking steam_api would put Valve code in+ * that template, and every user of the engine — including everyone who+ * never ships to Steam — would inherit its licensing. Unreal can link it+ * because its users compile the engine; we cannot, because ours do not.+ *+ * So: the declarations below are OURS, written from the flat API's+ * signatures, and the library is opened only if it is beside the+ * executable. Absent, {@link SteamApi::available} is false and the game+ * runs exactly as it does off Steam.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++#include <cstdint>+#include <string>++namespace eshost {++/**+ * The Steam client, or nothing.+ *+ * One instance, brought up during boot and shut down with the host. Every call is+ * safe when Steam is absent: it answers as though nothing is unlocked and nothing+ * is signed in, which is what a game off Steam sees.+ */+class SteamApi {+ public:+ /**+ * Load the library beside the executable and initialise.+ *+ * @param appId The Steam application id, for the ownership check.+ * @returns false when there is no library, no running client, or no session —+ * all of which are ordinary, and none of which is an error.+ */+ bool init(std::uint32_t appId);+ void shutdown();++ /** Whether a Steam session is behind this. Everything below is a no-op+ * otherwise, so nothing has to branch on it except a UI deciding whose+ * notification to draw. */+ bool available() const { return stats_ != nullptr; }++ /** The signed-in account, as a decimal string — 64 bits does not survive a+ * double, and this crosses into JS. Empty when signed out. */+ std::string steamId() const;+ /** The account's display name, for a "signed in as" line. */+ std::string personaName() const;++ bool unlock(const char* id);+ bool unlocked(const char* id) const;+ bool setStat(const char* name, std::int32_t value);+ std::int32_t stat(const char* name) const;+ /** Push everything set since the last call; Steam batches behind this. */+ bool store();+ /** Clear every achievement and stat. Development only. */+ bool reset();++ /** Run Steam's callbacks, once per frame. Without it the client never learns+ * the game is alive and the overlay never opens. */+ void pump();++ /** Why {@link init} answered false, for the boot record. Empty on success. */+ const std::string& lastError() const { return error_; }++ private:+ void* library_ = nullptr;+ void* stats_ = nullptr;+ void* user_ = nullptr;+ void* friends_ = nullptr;+ std::string error_;+};++/** The process's Steam client. */+SteamApi& steam();++} // namespace eshostdiff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 0223f9d8c..1772a1ee4 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -4720,6 +4720,7 @@ physicsEnabled: boolean | undefinedscenes: { name: string; path: string; }[] | undefinedscreenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefinedsideModules: { id: string; file: string; globalName?: string; }[] | undefined+steamAppId: number | undefineduiTheme: "light" | undefineduiThemeColors: Record<string, string> | undefinedySortLayers: number | undefined@@ -5159,6 +5160,8 @@ requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefined+steamAchievements: ((appId: number) => AchievementProvider | null) | undefined+steamIdentity: (() => { id: string; name: string; } | null) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6095,6 +6098,7 @@ scenes: { name: string; data?: SceneData; path?: string; }[]source: RuntimeAssetSourcespineManager: SpineManager | null | undefinedspineModule: SpineWasmModule | null | undefined+steamAppId: number | undefineduiTheme: "dark" | "light" | undefineduiThemeOverrides: ThemeOverrides | undefined```@@ -10268,7 +10272,7 @@ NavPlugin## packagedRuntimeInit — function```-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; }```## paramDefaultValue — functiondiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 02988d726..cea99268b 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -4546,6 +4546,7 @@ readFile: (path: string) => Promise<ArrayBuffer>registerInput: (listener: NativeInputListener) => () => voidremoveStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+steam: NativeSteamBridge | undefinedstorageKeys: () => string[]textEditor: NativeTextEditorBridge | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined@@ -4608,6 +4609,15 @@ es_readCacheFile: ((key: string) => ArrayBuffer | null) | undefinedes_readDataFile: ((key: string) => ArrayBuffer | null) | undefinedes_removeStorageItem: ((key: string) => void) | undefinedes_setStorageItem: ((key: string, value: string) => void) | undefined+es_steam_available: (() => boolean) | undefined+es_steam_getStat: ((name: string) => number) | undefined+es_steam_identity: (() => { id: string; name: string; }) | undefined+es_steam_init: ((appId: number) => boolean) | undefined+es_steam_reset: (() => boolean) | undefined+es_steam_setStat: ((name: string, value: number) => boolean) | undefined+es_steam_store: (() => boolean) | undefined+es_steam_unlock: ((id: string) => boolean) | undefined+es_steam_unlocked: ((id: string) => boolean) | undefinedes_storageKeys: (() => string[]) | undefinedes_textEditor_blur: (() => void) | undefinedes_textEditor_focus: ((value: string, selectionStart: number, selectionEnd: number, multiline: boolean, maxLength: number, password: boolean) => void) | undefined@@ -4667,6 +4677,8 @@ readFile: (path: string) => Promise<ArrayBuffer>readTextFile: (path: string) => Promise<string>removeStorageItem: (key: string) => voidsetStorageItem: (key: string, value: string) => void+steamAchievements: (appId: number) => AchievementProvider | null+steamIdentity: () => { id: string; name: string; } | nullunbindInputEvents: () => voidwriteCacheFile: (key: string, bytes: ArrayBuffer) => Promise<void>static new (bridge_: NativeBridge): NativePlatformAdapter@@ -4887,6 +4899,7 @@ physicsEnabled: boolean | undefinedscenes: { name: string; path: string; }[] | undefinedscreenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefinedsideModules: { id: string; file: string; globalName?: string; }[] | undefined+steamAppId: number | undefineduiTheme: "light" | undefineduiThemeColors: Record<string, string> | undefinedySortLayers: number | undefined@@ -5326,6 +5339,8 @@ requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefined+steamAchievements: ((appId: number) => AchievementProvider | null) | undefined+steamIdentity: (() => { id: string; name: string; } | null) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6272,6 +6287,7 @@ scenes: { name: string; data?: SceneData; path?: string; }[]source: RuntimeAssetSourcespineManager: SpineManager | null | undefinedspineModule: SpineWasmModule | null | undefined+steamAppId: number | undefineduiTheme: "dark" | "light" | undefineduiThemeOverrides: ThemeOverrides | undefined```@@ -10495,7 +10511,7 @@ NavPlugin## packagedRuntimeInit — function```-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; }```## paramDefaultValue — functiondiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex 77924aaa7..9c301e739 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -4715,6 +4715,7 @@ physicsEnabled: boolean | undefinedscenes: { name: string; path: string; }[] | undefinedscreenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefinedsideModules: { id: string; file: string; globalName?: string; }[] | undefined+steamAppId: number | undefineduiTheme: "light" | undefineduiThemeColors: Record<string, string> | undefinedySortLayers: number | undefined@@ -5154,6 +5155,8 @@ requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefined+steamAchievements: ((appId: number) => AchievementProvider | null) | undefined+steamIdentity: (() => { id: string; name: string; } | null) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6090,6 +6093,7 @@ scenes: { name: string; data?: SceneData; path?: string; }[]source: RuntimeAssetSourcespineManager: SpineManager | null | undefinedspineModule: SpineWasmModule | null | undefined+steamAppId: number | undefineduiTheme: "dark" | "light" | undefineduiThemeOverrides: ThemeOverrides | undefined```@@ -10273,7 +10277,7 @@ NodePlatformAdapter## packagedRuntimeInit — function```-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; }```## paramDefaultValue — functiondiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 4eb4c4b75..ce81a24b7 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -4960,6 +4960,7 @@ physicsEnabled: boolean | undefinedscenes: { name: string; path: string; }[] | undefinedscreenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefinedsideModules: { id: string; file: string; globalName?: string; }[] | undefined+steamAppId: number | undefineduiTheme: "light" | undefineduiThemeColors: Record<string, string> | undefinedySortLayers: number | undefined@@ -5399,6 +5400,8 @@ requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefined+steamAchievements: ((appId: number) => AchievementProvider | null) | undefined+steamIdentity: (() => { id: string; name: string; } | null) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6335,6 +6338,7 @@ scenes: { name: string; data?: SceneData; path?: string; }[]source: RuntimeAssetSourcespineManager: SpineManager | null | undefinedspineModule: SpineWasmModule | null | undefined+steamAppId: number | undefineduiTheme: "dark" | "light" | undefineduiThemeOverrides: ThemeOverrides | undefined```@@ -10523,7 +10527,7 @@ NavPlugin## packagedRuntimeInit — function```-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; }```## paramDefaultValue — functiondiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex c2db64eb5..6b4eb9338 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -4722,6 +4722,7 @@ physicsEnabled: boolean | undefinedscenes: { name: string; path: string; }[] | undefinedscreenFit: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number; } | undefinedsideModules: { id: string; file: string; globalName?: string; }[] | undefined+steamAppId: number | undefineduiTheme: "light" | undefineduiThemeColors: Record<string, string> | undefinedySortLayers: number | undefined@@ -5161,6 +5162,8 @@ requestPayment: ((request: PlatformPaymentRequest) => Promise<void>) | undefinedsetCloudKeyValues: ((entries: Readonly<Record<string, string>>) => boolean) | undefinedsetStorageItem: (key: string, value: string) => voidshare: ((options: PlatformShareOptions) => void) | undefined+steamAchievements: ((appId: number) => AchievementProvider | null) | undefined+steamIdentity: (() => { id: string; name: string; } | null) | undefinedunbindInputEvents: (() => void) | undefinedwriteCacheFile: ((key: string, bytes: ArrayBuffer) => Promise<void>) | undefined```@@ -6097,6 +6100,7 @@ scenes: { name: string; data?: SceneData; path?: string; }[]source: RuntimeAssetSourcespineManager: SpineManager | null | undefinedspineModule: SpineWasmModule | null | undefined+steamAppId: number | undefineduiTheme: "dark" | "light" | undefineduiThemeOverrides: ThemeOverrides | undefined```@@ -10295,7 +10299,7 @@ NavPlugin## packagedRuntimeInit — function```-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements" | "steamAppId">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; steamAppId?: number; }```## paramDefaultValue — functiondiff --git a/sdk/src/platform/native/adapter.ts b/sdk/src/platform/native/adapter.tsindex c922d262e..bf93f0cb0 100644--- a/sdk/src/platform/native/adapter.ts+++ b/sdk/src/platform/native/adapter.ts@@ -35,6 +35,8 @@ import { setPlatform } from '../base';import { createPrimaryPointer } from '../primaryPointer';import { NativeAudioBackend } from '../../audio/NativeAudioBackend';import { createNativeTextEditor } from './textEditor';+import { createSteamAchievements } from './steamAchievements';+import type { AchievementProvider } from '../../services/achievements';import type { NativeBridge, NativeInputListener } from './bridge';export class NativePlatformAdapter implements PlatformAdapter {@@ -238,6 +240,26 @@ export class NativePlatformAdapter implements PlatformAdapter {return this.bridge_.pollGamepads?.() ?? [];}+ /**+ * Bring Steam up for @p appId and hand back its achievements provider, or null.+ *+ * Null is the ordinary answer: no client running, signed out, a build that+ * ships nowhere near Steam, or a platform that has none. The service keeps its+ * local provider and the game behaves the same.+ */+ steamAchievements(appId: number): AchievementProvider | null {+ const steam = this.bridge_.steam;+ if (!steam || !steam.init(appId) || !steam.available()) return null;+ return createSteamAchievements(steam);+ }++ /** The signed-in Steam account, or null. `id` is a string: 64 bits of account+ * id do not survive a double. */+ steamIdentity(): { id: string; name: string } | null {+ const steam = this.bridge_.steam;+ return steam?.available() ? steam.identity() : null;+ }+// 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 31273a200..4932c3ecd 100644--- a/sdk/src/platform/native/bridge.ts+++ b/sdk/src/platform/native/bridge.ts@@ -62,6 +62,25 @@ export interface NativeInputListener {onKeyUp(code: string): void;}+/**+ * The store's half of achievements, as the desktop host exposes it.+ *+ * `init` is separate from the rest because the app id lives in game.config.json,+ * which the SDK reads — the host has no JSON parser and no reason to grow one.+ */+export interface NativeSteamBridge {+ init(appId: number): boolean;+ available(): boolean;+ /** `{ id, name }`; the id is a STRING because 64 bits do not survive a double. */+ identity(): { id: string; name: string };+ unlock(id: string): boolean;+ unlocked(id: string): boolean;+ setStat(name: string, value: number): boolean;+ getStat(name: string): number;+ store(): boolean;+ reset(): boolean;+}+/** What the OS editing surface reports back. `state` carries the surface's whole* value + selection (it is the owner while focused); `composing` is absent on a* host that cannot tell whether an IME preedit is in flight. */@@ -185,6 +204,10 @@ export interface NativeBridge {* a shell with no pads to report (a phone). */pollGamepads?(): GamepadSnapshot[];+ /** The Steam client, on a shell that can have one (desktop). Absent everywhere+ * else, and present-but-unavailable when no client is running. */+ steam?: NativeSteamBridge;+devicePixelRatio(): number;/** High-resolution clock. Optional — falls back to `Date.now()`. */now?(): number;diff --git a/sdk/src/platform/native/hostBridge.ts b/sdk/src/platform/native/hostBridge.tsindex c229ffeda..fbeaddc96 100644--- a/sdk/src/platform/native/hostBridge.ts+++ b/sdk/src/platform/native/hostBridge.ts@@ -67,6 +67,17 @@ export interface NativeHostBindings {* browser without navigator.getGamepads() gives it. */es_pollGamepads?(): { index: number; connected: boolean; buttons: number[]; axes: number[] }[];+ /** The Steam client. Bound only where one can exist (desktop). */+ es_steam_init?(appId: number): boolean;+ es_steam_available?(): boolean;+ es_steam_identity?(): { id: string; name: string };+ es_steam_unlock?(id: string): boolean;+ es_steam_unlocked?(id: string): boolean;+ es_steam_setStat?(name: string, value: number): boolean;+ es_steam_getStat?(name: string): number;+ es_steam_store?(): boolean;+ es_steam_reset?(): boolean;+/** Perform an HTTP request off the main thread (native TLS stack), calling* back with the reply. Optional — a host without it stays offline (remote* asset groups and hot-update do not resolve). */@@ -199,6 +210,23 @@ export function createHostBridge(return () => { listener = null; };},devicePixelRatio: () => bindings.es_devicePixelRatio?.() ?? 1,+ // All-or-nothing: the host binds the whole surface or none of it, so one+ // probe decides rather than nine optional calls at every site.+ ...(bindings.es_steam_init+ ? {+ steam: {+ init: (appId: number) => bindings.es_steam_init!(appId),+ available: () => bindings.es_steam_available?.() ?? false,+ identity: () => bindings.es_steam_identity?.() ?? { id: '', name: '' },+ unlock: (id: string) => bindings.es_steam_unlock?.(id) ?? false,+ unlocked: (id: string) => bindings.es_steam_unlocked?.(id) ?? false,+ setStat: (n: string, v: number) => bindings.es_steam_setStat?.(n, v) ?? false,+ getStat: (n: string) => bindings.es_steam_getStat?.(n) ?? 0,+ store: () => bindings.es_steam_store?.() ?? false,+ reset: () => bindings.es_steam_reset?.() ?? false,+ },+ }+ : {}),...(bindings.es_pollGamepads// 'standard' is asserted HERE rather than by the host: the layout is// this bridge's contract with the SDK, and a host that filled thediff --git a/sdk/src/platform/native/steamAchievements.ts b/sdk/src/platform/native/steamAchievements.tsnew file mode 100644index 000000000..4158521e6--- /dev/null+++ b/sdk/src/platform/native/steamAchievements.ts@@ -0,0 +1,30 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file steamAchievements.ts+ * @brief Steam behind the achievements service — one provider, not a second API.+ *+ * A game calls `Achievements.unlock('X')` and this forwards it. What changes when+ * Steam is there is `available`, which is what a UI reads to decide between the+ * platform's own notification and drawing its own.+ */+import type { AchievementProvider } from '../../services/achievements';+import type { NativeSteamBridge } from './bridge';++/**+ * Wrap a live Steam client as an {@link AchievementProvider}.+ *+ * `store()` is what actually reaches Steam's servers; unlock and setStat are+ * local to the client until then. The service calls it, so no game has to know.+ */+export function createSteamAchievements(steam: NativeSteamBridge): AchievementProvider {+ return {+ platformBacked: true,+ unlock: (id) => { steam.unlock(id); return Promise.resolve(); },+ unlocked: (id) => steam.unlocked(id),+ setStat: (name, value) => { steam.setStat(name, value); },+ getStat: (name) => steam.getStat(name),+ store: () => { steam.store(); return Promise.resolve(); },+ reset: () => { steam.reset(); return Promise.resolve(); },+ };+}diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.tsindex b8501fe6e..21e427adf 100644--- a/sdk/src/platform/types.ts+++ b/sdk/src/platform/types.ts@@ -5,6 +5,8 @@* @brief Platform adapter interface definitions*/+import type { AchievementProvider } from '../services/achievements';+// =============================================================================// Response Types// =============================================================================@@ -434,6 +436,19 @@ export interface PlatformAdapter {* gamepad polling entirely. */pollGamepads?(): GamepadSnapshot[];+ /**+ * Bring a store's achievement service up for @p appId, or null.+ *+ * A platform with no store omits it; a desktop build with no client running+ * answers null. The service then keeps its local provider, so a game's code+ * never branches on any of this.+ */+ steamAchievements?(appId: number): AchievementProvider | null;++ /** The signed-in store account, or null. `id` is a STRING — 64 bits of+ * account id do not survive a double. */+ steamIdentity?(): { id: string; name: string } | null;+/** 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/runtime/packagedRuntime.ts b/sdk/src/runtime/packagedRuntime.tsindex 2e10f4267..d68569866 100644--- a/sdk/src/runtime/packagedRuntime.ts+++ b/sdk/src/runtime/packagedRuntime.ts@@ -54,6 +54,9 @@ export interface PackagedGameConfig {/** The achievement ids this game declares. The runtime refuses an unlock* outside the set, because a store accepts an unknown id and does nothing. */achievements?: string[];+ /** The Steam application id, when this build ships to Steam. Its presence is+ * what makes the runtime try to bring a Steam client up at all. */+ steamAppId?: number;/*** Install physics even when the shipped scene shows no bodies — a project* that spawns them from script (Project Settings → Physics → Enabled).@@ -157,7 +160,7 @@ export function packagedAppOptions(export function packagedRuntimeInit(config: Pick<PackagedGameConfig,'physicsEnabled' | 'physicsConfig' | 'audioConfig' | 'uiTheme' | 'uiThemeColors'- | 'achievements'>,+ | 'achievements' | 'steamAppId'>,): {physicsEnabled?: boolean;physicsConfig?: PhysicsPluginConfig;@@ -165,6 +168,7 @@ export function packagedRuntimeInit(uiTheme?: 'light';uiThemeOverrides?: ThemeOverrides;achievements?: string[];+ steamAppId?: number;} {return {physicsEnabled: config.physicsEnabled,@@ -173,6 +177,7 @@ export function packagedRuntimeInit(uiTheme: config.uiTheme,uiThemeOverrides: parseThemeOverrides(config.uiThemeColors),achievements: config.achievements,+ steamAppId: config.steamAppId,};}diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.tsindex cbbad1ae3..89a360f3d 100644--- a/sdk/src/runtime/runtimeLoader.ts+++ b/sdk/src/runtime/runtimeLoader.ts@@ -28,6 +28,7 @@ import { DEFAULT_GRAVITY, DEFAULT_FIXED_TIMESTEP } from '../defaults';import { SpriteAnimation } from '../animation/SpriteAnimator';import { Audio } from '../audio/Audio';import { Achievements } from '../services/achievements';+import { getPlatform } from '../platform/base';import { VideoPlayer } from '../video/VideoAPI';import { Localization, matchLocale } from '../i18n/Localization';import { LocalizationPlugin } from '../i18n/LocalizationPlugin';@@ -517,6 +518,9 @@ export interface RuntimeInitConfig {/** The achievement ids the project declares — the set an unlock is checked* against, since a store would take an unknown one and do nothing. */achievements?: string[];+ /** The Steam application id; present ⇒ try to bring a Steam client up and let+ * it answer for achievements. Absent or unavailable keeps the local one. */+ steamAppId?: number;aspectRatio?: number;}@@ -546,6 +550,12 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {// The declared achievement ids, so an unlock outside the set is refused here// rather than accepted by a store and silently dropped.app.getResource(Achievements)?.setKnown(config.achievements ?? null);+ // A store, if there is one behind this build. Everything about the game's code+ // is the same either way — what changes is whether Steam also hears.+ if (config.steamAppId) {+ const provider = getPlatform().steamAchievements?.(config.steamAppId);+ if (provider) app.getResource(Achievements)?.setProvider(provider);+ }const sceneOpts: Omit<LoadRuntimeSceneOptions, 'sceneData' | 'sceneName'> = {app: config.app,diff --git a/tools/check-project-settings.mjs b/tools/check-project-settings.mjsindex 18f6a7321..b2ba61a66 100644--- a/tools/check-project-settings.mjs+++ b/tools/check-project-settings.mjs@@ -45,6 +45,12 @@ const DECLARED_GAPS = {editor: 'nothing unlocks one while a scene is being authored — edit mode runs no '+ 'gameplay, so the set is checked in Play and in a shipped build',},+ steamAppId: {+ editor: 'edit mode is not a shipped game — a Steam client is brought up by the '+ + 'runtime, and Play rehearses that with the local provider',+ play: 'Play is not launched by Steam, so a client would refuse the ownership '+ + 'check; the local provider is what a rehearsal can honestly use',+ },physicsEnabled: {editor: 'edit mode does not simulate — bodies are authored, not stepped',},@@ -67,6 +73,7 @@ const DECLARED_GAPS = {/** The feature branch in the manifest parser each field is read from. */const PARSE_KEY = {achievements: 'p.achievements',+ steamAppId: 'dt.steam',physicsEnabled: 'p.enabled',physicsConfig: 'physics',audioConfig: 'parseAudioProjectConfig',