Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(sdk): achievements as an engine service, with the ids declared

esengine8784d28293d4
diff --git a/desktop/src/engine/playProtocol.ts b/desktop/src/engine/playProtocol.ts
index 9e4bb9458..f553e983b 100644
--- a/desktop/src/engine/playProtocol.ts
+++ b/desktop/src/engine/playProtocol.ts
@@ -81,6 +81,10 @@ export interface PlayPayload {
/** Project camera fit (design resolution + scale mode) — letterboxes the realm's
* main camera without a UI Canvas; absent = no fit (raw orthoSize). */
screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
+ /** The project's declared achievement ids — Play checks an unlock against the
+ * same set a shipped build does, so a typo is caught here rather than by a
+ * player whose achievement never fires. */
+ achievements?: string[];
/** Multiplayer preview role; absent = a plain single-player session. */
net?: PlayNetConfig;
/**
diff --git a/desktop/src/playHost.ts b/desktop/src/playHost.ts
index b4efcfeeb..303591ef2 100644
--- a/desktop/src/playHost.ts
+++ b/desktop/src/playHost.ts
@@ -309,6 +309,9 @@ async function buildAppAndRun(msg: InitMessage): Promise<void> {
audioConfig: msg.audioConfig,
uiTheme: msg.uiTheme,
uiThemeOverrides: msg.uiThemeOverrides,
+ // The declared achievement ids, so a typo'd unlock is refused HERE — a store
+ // would accept it and do nothing, and only a player would ever find out.
+ achievements: msg.achievements,
enableStats: true, // editor profiler: per-phase / per-system frame timing
});
// Realm-local debug handle for automation/diagnostics (mirrors the headless
diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.ts
index cf56ea668..1a5cc9035 100644
--- a/desktop/src/project/ProjectStore.ts
+++ b/desktop/src/project/ProjectStore.ts
@@ -1537,6 +1537,7 @@ class ProjectStoreImpl {
depthLayers?: number;
colorSpace?: 'gamma' | 'linear';
screenFit?: { designWidth: number; designHeight: number; scaleMode: number; matchWidthOrHeight: number };
+ achievements?: string[];
} | null {
const sceneData = SceneModel.serialize();
if (!sceneData) return null;
diff --git a/desktop/src/project/format.ts b/desktop/src/project/format.ts
index 84e75e67b..dc7704c07 100644
--- a/desktop/src/project/format.ts
+++ b/desktop/src/project/format.ts
@@ -298,6 +298,14 @@ export interface ProjectPackaging {
* mark, so a packaged game never ships with the platform's placeholder.
*/
icon?: string;
+ /**
+ * The achievements this game has, by id.
+ *
+ * Platform-NEUTRAL rather than under a store, because every store has this same
+ * list under a different name. Declaring them lets the runtime refuse an unlock
+ * a store would accept and silently drop.
+ */
+ achievements?: string[];
/** Per-platform packaging config: each target's slice of the app identity, plus
* whatever only it has (a WeChat appid, an Android versionCode). */
platforms?: {
@@ -576,6 +584,15 @@ export function parseManifest(raw: unknown): ProjectManifest {
}
if (Object.keys(budgets).length > 0) pkg.sizeBudget = budgets;
}
+ // Deduplicated and trimmed: a store keys achievements by this string, so a
+ // stray blank or a repeat is a row that can never match one.
+ if (Array.isArray(p.achievements)) {
+ const ids = [...new Set(p.achievements
+ .filter((id): id is string => typeof id === 'string')
+ .map((id) => id.trim())
+ .filter(Boolean))];
+ if (ids.length > 0) pkg.achievements = ids;
+ }
if (p.platforms && typeof p.platforms === 'object') {
const pl = p.platforms as Record<string, unknown>;
const platforms: NonNullable<ProjectPackaging['platforms']> = {};
diff --git a/desktop/src/project/runtimeConfig.ts b/desktop/src/project/runtimeConfig.ts
index 4e53b4074..23d186330 100644
--- a/desktop/src/project/runtimeConfig.ts
+++ b/desktop/src/project/runtimeConfig.ts
@@ -45,6 +45,9 @@ export interface RuntimeScreenFit {
* field that makes the rehearsal lie.
*/
export interface RuntimeProjectConfig {
+ /** The achievement ids the project declares — the set the runtime refuses an
+ * unlock outside of. Empty ⇒ nothing is checked. */
+ achievements: string[];
/** Install physics even when the static scene shows no bodies (runtime-spawned). */
physicsEnabled: boolean;
/** World solver + collision matrix (Project Settings → Physics). */
@@ -115,10 +118,11 @@ function physicsConfigOf(features: ProjectManifest['features']): PhysicsPluginCo
* processes have — the editor's live project state satisfies it structurally.
*/
export function runtimeConfigOf(
- manifest: Pick<ProjectManifest, 'designResolution' | 'features'>,
+ manifest: Pick<ProjectManifest, 'designResolution' | 'features' | 'packaging'>,
): RuntimeProjectConfig {
const f = manifest.features;
return {
+ achievements: manifest.packaging?.achievements ?? [],
physicsEnabled: f?.physics?.enabled ?? false,
physicsConfig: physicsConfigOf(f),
audioConfig: f?.audio ?? {},
@@ -135,7 +139,7 @@ export function runtimeConfigOf(
export type PackagedRuntimeFields = Pick<
PackagedGameConfig,
'ySortLayers' | 'depthLayers' | 'colorSpace' | 'screenFit' | 'uiTheme' | 'uiThemeColors'
- | 'physicsEnabled' | 'physicsConfig' | 'audioConfig'
+ | 'physicsEnabled' | 'physicsConfig' | 'audioConfig' | 'achievements'
>;
/**
@@ -162,6 +166,7 @@ export function packagedRuntimeFields(rc: RuntimeProjectConfig): PackagedRuntime
...(rc.physicsEnabled ? { physicsEnabled: true } : {}),
...(isDefaultPhysics(rc.physicsConfig) ? {} : { physicsConfig: rc.physicsConfig }),
...(rc.audioConfig.buses?.length ? { audioConfig: rc.audioConfig } : {}),
+ ...(rc.achievements.length ? { achievements: rc.achievements } : {}),
};
}
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 6ba5c853d..0223f9d8c 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: 1472 stable · 17 beta · 1 deprecated
+Symbols: 1476 stable · 17 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -23,6 +23,37 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## AchievementProvider — interface
+```
+getStat: (name: string) => number
+platformBacked: boolean
+reset: () => Promise<void>
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+```
+
+## Achievements — const
+```
+ResourceDef<AchievementsAPI>
+```
+
+## AchievementsAPI — class
+```
+available: boolean
+getStat: (name: string) => number
+reset: () => Promise<void>
+setKnown: (ids: readonly string[] | null) => void
+setProvider: (provider: AchievementProvider | null) => void
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+static new (): AchievementsAPI
+static prototype: AchievementsAPI
+```
+
## ActionDef — interface
```
bindings: Binding[]
@@ -4678,6 +4709,7 @@ decodePixels: ((path: string, flip: boolean) => Promise<{ width: number; height:
## PackagedGameConfig — interface
```
+achievements: string[] | undefined
audioConfig: AudioProjectConfig | undefined
colorSpace: "gamma" | "linear" | undefined
depthLayers: number | undefined
@@ -5251,6 +5283,7 @@ volume: number | undefined
## PlayRealmRuntimeConfig — interface
```
+achievements: string[] | undefined
app: App
assetBaseUrl: string | undefined
assetManifest: Record<string, string>
@@ -6045,6 +6078,7 @@ textureCacheBudget: number | undefined
## RuntimeInitConfig — interface
```
+achievements: string[] | undefined
app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
@@ -9202,6 +9236,11 @@ Plugin
<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>
```
+## createLocalAchievements — function
+```
+(): AchievementProvider
+```
+
## createLocalLeaderboard — function
```
(options?: LocalLeaderboardOptions): LeaderboardProvider
@@ -10229,7 +10268,7 @@ NavPlugin
## packagedRuntimeInit — function
```
-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }
+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }
```
## paramDefaultValue — function
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index b26cc23dc..02988d726 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: 1491 stable · 22 beta · 1 deprecated
+Symbols: 1495 stable · 22 beta · 1 deprecated
## ABI_LAYOUT_HASH — const
```
@@ -23,6 +23,37 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## AchievementProvider — interface
+```
+getStat: (name: string) => number
+platformBacked: boolean
+reset: () => Promise<void>
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+```
+
+## Achievements — const
+```
+ResourceDef<AchievementsAPI>
+```
+
+## AchievementsAPI — class
+```
+available: boolean
+getStat: (name: string) => number
+reset: () => Promise<void>
+setKnown: (ids: readonly string[] | null) => void
+setProvider: (provider: AchievementProvider | null) => void
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+static new (): AchievementsAPI
+static prototype: AchievementsAPI
+```
+
## ActionDef — interface
```
bindings: Binding[]
@@ -4845,6 +4876,7 @@ decodePixels: ((path: string, flip: boolean) => Promise<{ width: number; height:
## PackagedGameConfig — interface
```
+achievements: string[] | undefined
audioConfig: AudioProjectConfig | undefined
colorSpace: "gamma" | "linear" | undefined
depthLayers: number | undefined
@@ -5418,6 +5450,7 @@ volume: number | undefined
## PlayRealmRuntimeConfig — interface
```
+achievements: string[] | undefined
app: App
assetBaseUrl: string | undefined
assetManifest: Record<string, string>
@@ -6222,6 +6255,7 @@ textureCacheBudget: number | undefined
## RuntimeInitConfig — interface
```
+achievements: string[] | undefined
app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
@@ -9399,6 +9433,11 @@ Plugin
<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>
```
+## createLocalAchievements — function
+```
+(): AchievementProvider
+```
+
## createLocalLeaderboard — function
```
(options?: LocalLeaderboardOptions): LeaderboardProvider
@@ -10456,7 +10495,7 @@ NavPlugin
## packagedRuntimeInit — function
```
-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }
+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }
```
## paramDefaultValue — function
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 152fc272d..77924aaa7 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: 1471 stable · 19 beta · 1 deprecated
+Symbols: 1475 stable · 19 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -18,6 +18,37 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## AchievementProvider — interface
+```
+getStat: (name: string) => number
+platformBacked: boolean
+reset: () => Promise<void>
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+```
+
+## Achievements — const
+```
+ResourceDef<AchievementsAPI>
+```
+
+## AchievementsAPI — class
+```
+available: boolean
+getStat: (name: string) => number
+reset: () => Promise<void>
+setKnown: (ids: readonly string[] | null) => void
+setProvider: (provider: AchievementProvider | null) => void
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+static new (): AchievementsAPI
+static prototype: AchievementsAPI
+```
+
## ActionDef — interface
```
bindings: Binding[]
@@ -4673,6 +4704,7 @@ decodePixels: ((path: string, flip: boolean) => Promise<{ width: number; height:
## PackagedGameConfig — interface
```
+achievements: string[] | undefined
audioConfig: AudioProjectConfig | undefined
colorSpace: "gamma" | "linear" | undefined
depthLayers: number | undefined
@@ -5246,6 +5278,7 @@ volume: number | undefined
## PlayRealmRuntimeConfig — interface
```
+achievements: string[] | undefined
app: App
assetBaseUrl: string | undefined
assetManifest: Record<string, string>
@@ -6040,6 +6073,7 @@ textureCacheBudget: number | undefined
## RuntimeInitConfig — interface
```
+achievements: string[] | undefined
app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
@@ -9197,6 +9231,11 @@ Plugin
<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>
```
+## createLocalAchievements — function
+```
+(): AchievementProvider
+```
+
## createLocalLeaderboard — function
```
(options?: LocalLeaderboardOptions): LeaderboardProvider
@@ -10234,7 +10273,7 @@ NodePlatformAdapter
## packagedRuntimeInit — function
```
-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }
+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }
```
## paramDefaultValue — function
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index c15eb18c4..4eb4c4b75 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: 1492 stable · 17 beta · 1 deprecated
+Symbols: 1496 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -18,6 +18,37 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## AchievementProvider — interface
+```
+getStat: (name: string) => number
+platformBacked: boolean
+reset: () => Promise<void>
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+```
+
+## Achievements — const
+```
+ResourceDef<AchievementsAPI>
+```
+
+## AchievementsAPI — class
+```
+available: boolean
+getStat: (name: string) => number
+reset: () => Promise<void>
+setKnown: (ids: readonly string[] | null) => void
+setProvider: (provider: AchievementProvider | null) => void
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+static new (): AchievementsAPI
+static prototype: AchievementsAPI
+```
+
## ActionDef — interface
```
bindings: Binding[]
@@ -4918,6 +4949,7 @@ decodePixels: ((path: string, flip: boolean) => Promise<{ width: number; height:
## PackagedGameConfig — interface
```
+achievements: string[] | undefined
audioConfig: AudioProjectConfig | undefined
colorSpace: "gamma" | "linear" | undefined
depthLayers: number | undefined
@@ -5491,6 +5523,7 @@ volume: number | undefined
## PlayRealmRuntimeConfig — interface
```
+achievements: string[] | undefined
app: App
assetBaseUrl: string | undefined
assetManifest: Record<string, string>
@@ -6285,6 +6318,7 @@ textureCacheBudget: number | undefined
## RuntimeInitConfig — interface
```
+achievements: string[] | undefined
app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
@@ -9442,6 +9476,11 @@ Plugin
<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>
```
+## createLocalAchievements — function
+```
+(): AchievementProvider
+```
+
## createLocalLeaderboard — function
```
(options?: LocalLeaderboardOptions): LeaderboardProvider
@@ -10484,7 +10523,7 @@ NavPlugin
## packagedRuntimeInit — function
```
-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }
+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }
```
## paramDefaultValue — function
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 66efe1122..c2db64eb5 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: 1482 stable · 17 beta · 1 deprecated
+Symbols: 1486 stable · 17 beta · 1 deprecated
## ANCHOR_AXES — const
```
@@ -18,6 +18,37 @@ readonly AnchorAxis[]
readonly ["local", "subpackage", "remote"]
```
+## AchievementProvider — interface
+```
+getStat: (name: string) => number
+platformBacked: boolean
+reset: () => Promise<void>
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+```
+
+## Achievements — const
+```
+ResourceDef<AchievementsAPI>
+```
+
+## AchievementsAPI — class
+```
+available: boolean
+getStat: (name: string) => number
+reset: () => Promise<void>
+setKnown: (ids: readonly string[] | null) => void
+setProvider: (provider: AchievementProvider | null) => void
+setStat: (name: string, value: number) => void
+store: () => Promise<void>
+unlock: (id: string) => Promise<void>
+unlocked: (id: string) => boolean
+static new (): AchievementsAPI
+static prototype: AchievementsAPI
+```
+
## ActionDef — interface
```
bindings: Binding[]
@@ -4680,6 +4711,7 @@ decodePixels: ((path: string, flip: boolean) => Promise<{ width: number; height:
## PackagedGameConfig — interface
```
+achievements: string[] | undefined
audioConfig: AudioProjectConfig | undefined
colorSpace: "gamma" | "linear" | undefined
depthLayers: number | undefined
@@ -5253,6 +5285,7 @@ volume: number | undefined
## PlayRealmRuntimeConfig — interface
```
+achievements: string[] | undefined
app: App
assetBaseUrl: string | undefined
assetManifest: Record<string, string>
@@ -6047,6 +6080,7 @@ textureCacheBudget: number | undefined
## RuntimeInitConfig — interface
```
+achievements: string[] | undefined
app: App
aspectRatio: number | undefined
audioConfig: AudioProjectConfig | undefined
@@ -9224,6 +9258,11 @@ Plugin
<T>(opts: CreateListViewOptions<T>): ListViewHandle<T>
```
+## createLocalAchievements — function
+```
+(): AchievementProvider
+```
+
## createLocalLeaderboard — function
```
(options?: LocalLeaderboardOptions): LeaderboardProvider
@@ -10256,7 +10295,7 @@ NavPlugin
## packagedRuntimeInit — function
```
-(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; }
+(config: Pick<PackagedGameConfig, "physicsEnabled" | "physicsConfig" | "audioConfig" | "uiTheme" | "uiThemeColors" | "achievements">): { physicsEnabled?: boolean; physicsConfig?: PhysicsPluginConfig; audioConfig?: AudioProjectConfig; uiTheme?: "light"; uiThemeOverrides?: ThemeOverrides; achievements?: string[]; }
```
## paramDefaultValue — function
diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.ts
index 3247a1fb2..b56ccf1d9 100644
--- a/sdk/src/core-content.ts
+++ b/sdk/src/core-content.ts
@@ -410,15 +410,17 @@ export {
} from './audio';
// =============================================================================
-// Platform services (ads, share)
+// Platform services (ads, share, achievements)
// =============================================================================
export {
+ Achievements, AchievementsAPI, createLocalAchievements,
Ads, AdsAPI, createMockAdProvider,
Share, ShareAPI,
Leaderboard, LeaderboardAPI, createLocalLeaderboard,
Identity, IdentityAPI, Payment, PaymentAPI,
ServicesPlugin, servicesPlugin,
+ type AchievementProvider,
type AdProvider, type AdsHost, type MockAdProviderOptions, type ShareCard,
type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,
type LeaderboardStyle, type LocalLeaderboardOptions, type LoginResult,
diff --git a/sdk/src/runtime/packagedRuntime.ts b/sdk/src/runtime/packagedRuntime.ts
index 33ee4e7d8..2e10f4267 100644
--- a/sdk/src/runtime/packagedRuntime.ts
+++ b/sdk/src/runtime/packagedRuntime.ts
@@ -51,6 +51,9 @@ export interface PackagedGameConfig {
uiTheme?: 'light';
/** Project theme color overrides (role → #rrggbbaa hex). */
uiThemeColors?: Record<string, string>;
+ /** 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[];
/**
* Install physics even when the shipped scene shows no bodies — a project
* that spawns them from script (Project Settings → Physics → Enabled).
@@ -153,13 +156,15 @@ export function packagedAppOptions(
*/
export function packagedRuntimeInit(
config: Pick<PackagedGameConfig,
- 'physicsEnabled' | 'physicsConfig' | 'audioConfig' | 'uiTheme' | 'uiThemeColors'>,
+ 'physicsEnabled' | 'physicsConfig' | 'audioConfig' | 'uiTheme' | 'uiThemeColors'
+ | 'achievements'>,
): {
physicsEnabled?: boolean;
physicsConfig?: PhysicsPluginConfig;
audioConfig?: AudioProjectConfig;
uiTheme?: 'light';
uiThemeOverrides?: ThemeOverrides;
+ achievements?: string[];
} {
return {
physicsEnabled: config.physicsEnabled,
@@ -167,6 +172,7 @@ export function packagedRuntimeInit(
audioConfig: config.audioConfig,
uiTheme: config.uiTheme,
uiThemeOverrides: parseThemeOverrides(config.uiThemeColors),
+ achievements: config.achievements,
};
}
diff --git a/sdk/src/runtime/playRealmRuntime.ts b/sdk/src/runtime/playRealmRuntime.ts
index 027def245..45369050b 100644
--- a/sdk/src/runtime/playRealmRuntime.ts
+++ b/sdk/src/runtime/playRealmRuntime.ts
@@ -85,6 +85,9 @@ export interface PlayRealmRuntimeConfig {
uiThemeOverrides?: ThemeOverrides;
/** Project-declared mixer state (bus volumes / effects / duck rules). */
audioConfig?: AudioProjectConfig;
+ /** The project's declared achievement ids — Play checks an unlock against the
+ * same set a shipped build does, so a typo is found here. */
+ achievements?: string[];
/** Turn on per-phase / per-system frame timing (editor profiler; off in shipped games). */
enableStats?: boolean;
}
@@ -191,6 +194,7 @@ export async function initPlayRealmRuntime(config: PlayRealmRuntimeConfig): Prom
uiTheme: config.uiTheme,
uiThemeOverrides: config.uiThemeOverrides,
audioConfig: config.audioConfig,
+ achievements: config.achievements,
// Physics (and spine) are acquired from app.sideModules — the fetch host
// createWebApp built from this realm's wasmBaseUrl.
});
diff --git a/sdk/src/runtime/runtimeLoader.ts b/sdk/src/runtime/runtimeLoader.ts
index b71e0a33f..cbbad1ae3 100644
--- a/sdk/src/runtime/runtimeLoader.ts
+++ b/sdk/src/runtime/runtimeLoader.ts
@@ -27,6 +27,7 @@ import { SceneManager, type SceneConfig } from '../scene/sceneManager';
import { DEFAULT_GRAVITY, DEFAULT_FIXED_TIMESTEP } from '../defaults';
import { SpriteAnimation } from '../animation/SpriteAnimator';
import { Audio } from '../audio/Audio';
+import { Achievements } from '../services/achievements';
import { VideoPlayer } from '../video/VideoAPI';
import { Localization, matchLocale } from '../i18n/Localization';
import { LocalizationPlugin } from '../i18n/LocalizationPlugin';
@@ -513,6 +514,9 @@ export interface RuntimeInitConfig {
uiTheme?: 'dark' | 'light';
/** Project-declared theme token overrides; see {@link LoadRuntimeSceneOptions.uiThemeOverrides}. */
uiThemeOverrides?: ThemeOverrides;
+ /** 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[];
aspectRatio?: number;
}
@@ -539,6 +543,10 @@ export async function initRuntime(config: RuntimeInitConfig): Promise<void> {
applyAudioProjectConfig(app.getResource(Audio), config.audioConfig);
}
+ // 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);
+
const sceneOpts: Omit<LoadRuntimeSceneOptions, 'sceneData' | 'sceneName'> = {
app: config.app,
module: config.module,
diff --git a/sdk/src/services/achievements.ts b/sdk/src/services/achievements.ts
new file mode 100644
index 000000000..734d7e735
--- /dev/null
+++ b/sdk/src/services/achievements.ts
@@ -0,0 +1,156 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file achievements.ts
+ * @brief Achievements and stats as an engine service — one API, whichever
+ * store the game is in.
+ *
+ * A store's achievement service is a NOTIFICATION on top of state the game
+ * already owns: "the player has done this". So unlike ads, this always works —
+ * without a platform behind it the unlock is recorded locally, which is the same
+ * data a game's own achievements screen reads. {@link available} says whether a
+ * STORE will also hear about it, which is what a UI reads to decide between
+ * letting the platform draw its toast and drawing its own.
+ *
+ * ★ Unknown ids are the failure this file is shaped around. On a store, unlocking
+ * an id the backend does not have does nothing at all and reports nothing — the
+ * achievement simply never fires, and it is a player who finds out. So the game's
+ * ids are declared (Project Settings → Packaging → Achievements), and an unlock
+ * outside that set is an error the moment it happens.
+ */
+import { defineResource } from '../ecs/resource';
+import { Storage } from '../util/storage';
+import { log } from '../util/logger';
+
+/**
+ * What a platform answers. The same shape as {@link AdProvider} and
+ * {@link LeaderboardProvider}: the engine orchestrates, the provider does the
+ * platform's half, and the editor installs one to rehearse without a store.
+ */
+export interface AchievementProvider {
+ /** Whether a real store is behind this, rather than a local stand-in. Decides
+ * {@link AchievementsAPI.available}. */
+ readonly platformBacked: boolean;
+ unlock(id: string): Promise<void>;
+ unlocked(id: string): boolean;
+ setStat(name: string, value: number): void;
+ getStat(name: string): number;
+ /** Push everything set since the last call. Stores batch; a local provider
+ * has already persisted and answers immediately. */
+ store(): Promise<void>;
+ /** Clear every achievement and stat. A development affordance — no shipped
+ * game calls it, and stores treat it as a test-only operation. */
+ reset(): Promise<void>;
+}
+
+const STORAGE_KEY = 'achievements';
+
+interface LocalState {
+ unlocked: string[];
+ stats: Record<string, number>;
+}
+
+/**
+ * The stand-in every platform without a store gets, and what Play rehearses on.
+ *
+ * It persists — an achievement that forgets itself on restart rehearses nothing —
+ * through {@link Storage}, which on desktop is the directory a store's cloud save
+ * syncs.
+ */
+export function createLocalAchievements(): AchievementProvider {
+ const read = (): LocalState => {
+ const raw = Storage.getJSON<LocalState>(STORAGE_KEY);
+ return { unlocked: raw?.unlocked ?? [], stats: raw?.stats ?? {} };
+ };
+ let state = read();
+ const flush = () => Storage.setJSON(STORAGE_KEY, state);
+
+ return {
+ platformBacked: false,
+ unlock: (id) => {
+ if (!state.unlocked.includes(id)) {
+ state.unlocked.push(id);
+ flush();
+ }
+ return Promise.resolve();
+ },
+ unlocked: (id) => state.unlocked.includes(id),
+ setStat: (name, value) => { state.stats[name] = value; flush(); },
+ getStat: (name) => state.stats[name] ?? 0,
+ store: () => Promise.resolve(),
+ reset: () => {
+ state = { unlocked: [], stats: {} };
+ flush();
+ return Promise.resolve();
+ },
+ };
+}
+
+export class AchievementsAPI {
+ private provider_: AchievementProvider = createLocalAchievements();
+ private known_: readonly string[] | null = null;
+
+ /** Whether a STORE is behind this. False still records unlocks — it means the
+ * platform will not draw its own notification, so a game that wants one
+ * should draw it. */
+ get available(): boolean {
+ return this.provider_.platformBacked;
+ }
+
+ /** The ids this game declares, from the project's packaging settings. Absent
+ * ⇒ nothing is checked, which is what an older project gets. */
+ setKnown(ids: readonly string[] | null): void {
+ this.known_ = ids && ids.length > 0 ? [...ids] : null;
+ }
+
+ /** Install (or restore the local default with null) the provider that answers
+ * for this platform. */
+ setProvider(provider: AchievementProvider | null): void {
+ this.provider_ = provider ?? createLocalAchievements();
+ }
+
+ /**
+ * Unlock @p id. Idempotent: re-unlocking is what a game does every time it
+ * re-checks a condition, and no store treats it as an event.
+ *
+ * An id outside the declared set is REFUSED, not forwarded — a store would
+ * accept it and do nothing.
+ */
+ async unlock(id: string): Promise<void> {
+ if (!this.check_(id)) return;
+ await this.provider_.unlock(id);
+ }
+
+ /** Whether @p id is unlocked, as the platform currently reports it. */
+ unlocked(id: string): boolean {
+ return this.provider_.unlocked(id);
+ }
+
+ /** Set a stat a store may track (and may unlock an achievement from). */
+ setStat(name: string, value: number): void {
+ this.provider_.setStat(name, value);
+ }
+
+ getStat(name: string): number {
+ return this.provider_.getStat(name);
+ }
+
+ /** Push what has been set. Cheap to call often; stores batch behind it. */
+ store(): Promise<void> {
+ return this.provider_.store();
+ }
+
+ /** Development only: clear everything. */
+ reset(): Promise<void> {
+ return this.provider_.reset();
+ }
+
+ private check_(id: string): boolean {
+ if (!this.known_ || this.known_.includes(id)) return true;
+ log.error('achievements', `"${id}" is not one of this project's achievements `
+ + `(${this.known_.join(', ')}) — a store would accept it and do nothing.`);
+ return false;
+ }
+}
+
+export const Achievements = defineResource<AchievementsAPI>(null!, 'Achievements');
diff --git a/sdk/src/services/index.ts b/sdk/src/services/index.ts
index 010e30cb6..e22da40be 100644
--- a/sdk/src/services/index.ts
+++ b/sdk/src/services/index.ts
@@ -10,6 +10,9 @@ export {
type LeaderboardOptions, type LeaderboardProvider, type LeaderboardScope,
type LeaderboardStyle, type LocalLeaderboardOptions,
} from './leaderboard';
+export {
+ Achievements, AchievementsAPI, createLocalAchievements, type AchievementProvider,
+} from './achievements';
export { Identity, IdentityAPI, type LoginResult } from './identity';
export { Payment, PaymentAPI, type PaymentRequest, type PaymentFailure } from './payment';
export { ServicesPlugin, servicesPlugin } from './servicesPlugin';
diff --git a/sdk/src/services/servicesPlugin.ts b/sdk/src/services/servicesPlugin.ts
index ac23535fc..0c54c91b5 100644
--- a/sdk/src/services/servicesPlugin.ts
+++ b/sdk/src/services/servicesPlugin.ts
@@ -21,6 +21,7 @@ import { Schedule, defineSystem } from '../ecs/system';
import { Ads, AdsAPI } from './ads';
import { Share, ShareAPI } from './share';
import { Leaderboard, LeaderboardAPI } from './leaderboard';
+import { Achievements, AchievementsAPI } from './achievements';
import { Identity, IdentityAPI } from './identity';
import { Payment, PaymentAPI } from './payment';
@@ -38,6 +39,7 @@ export class ServicesPlugin implements Plugin {
resumeAudio: () => app.getResource(Audio)?.resume(),
}));
app.insertResource(Share, new ShareAPI());
+ app.insertResource(Achievements, new AchievementsAPI());
app.insertResource(Identity, new IdentityAPI());
app.insertResource(Payment, new PaymentAPI());
// Resolved per call rather than captured: the module is attached by
diff --git a/sdk/tests/achievements.test.ts b/sdk/tests/achievements.test.ts
new file mode 100644
index 000000000..4ffd2c516
--- /dev/null
+++ b/sdk/tests/achievements.test.ts
@@ -0,0 +1,142 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The achievements service.
+ *
+ * The one that matters is the unknown-id guard. On a store, unlocking an id the
+ * backend does not have does nothing and reports nothing — it is a player who
+ * finds out, months later, that an achievement never fires. Everything else here
+ * is the ordinary contract: unlocks are idempotent, they survive a restart, and
+ * a platform behind them changes `available` and nothing else.
+ */
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { AchievementsAPI, createLocalAchievements, type AchievementProvider } from '../src/services/achievements';
+import { Storage } from '../src/util/storage';
+import { log } from '../src/util/logger';
+import { setPlatform } from '../src/platform/base';
+import { webAdapter } from '../src/platform/web';
+
+// The local provider persists through Storage, which is the platform's — so the
+// tests run against a real one rather than a stub, and what they exercise is what
+// a game gets.
+beforeEach(() => {
+ setPlatform(webAdapter);
+ Storage.remove('achievements');
+});
+
+describe('the unknown-id guard', () => {
+ it('refuses an id the project did not declare, loudly', async () => {
+ const errors = vi.spyOn(log, 'error').mockImplementation(() => {});
+ const api = new AchievementsAPI();
+ api.setKnown(['FIRST_BLOOD', 'MARATHON']);
+
+ await api.unlock('FIRST_BLODO');
+ expect(api.unlocked('FIRST_BLODO')).toBe(false);
+ expect(errors).toHaveBeenCalledTimes(1);
+ // The message names what IS declared, because the mistake is nearly always
+ // a typo and the fix is right there.
+ expect(String(errors.mock.calls[0]?.[1])).toContain('FIRST_BLOOD');
+ errors.mockRestore();
+ });
+
+ it('checks nothing when the project declared nothing', async () => {
+ const api = new AchievementsAPI();
+ await api.unlock('ANYTHING');
+ expect(api.unlocked('ANYTHING')).toBe(true);
+ });
+
+ it('stops checking again when the declaration is cleared', async () => {
+ const api = new AchievementsAPI();
+ api.setKnown(['A']);
+ api.setKnown(null);
+ await api.unlock('B');
+ expect(api.unlocked('B')).toBe(true);
+ });
+});
+
+describe('the local provider', () => {
+ it('records an unlock and survives a restart', async () => {
+ const api = new AchievementsAPI();
+ await api.unlock('FIRST_BLOOD');
+ expect(api.unlocked('FIRST_BLOOD')).toBe(true);
+
+ // A second API over the same storage is what a restart looks like.
+ expect(new AchievementsAPI().unlocked('FIRST_BLOOD')).toBe(true);
+ });
+
+ it('is idempotent — re-unlocking is what a game does every frame it re-checks', async () => {
+ const api = new AchievementsAPI();
+ await api.unlock('A');
+ await api.unlock('A');
+ expect(Storage.getJSON<{ unlocked: string[] }>('achievements')?.unlocked).toEqual(['A']);
+ });
+
+ it('keeps stats and clears everything on reset', async () => {
+ const api = new AchievementsAPI();
+ api.setStat('kills', 41);
+ api.setStat('kills', 42);
+ expect(api.getStat('kills')).toBe(42);
+ expect(api.getStat('never-set')).toBe(0);
+
+ await api.unlock('A');
+ await api.reset();
+ expect(api.unlocked('A')).toBe(false);
+ expect(api.getStat('kills')).toBe(0);
+ });
+
+ it('reports no store behind it — a game draws its own notification', () => {
+ expect(new AchievementsAPI().available).toBe(false);
+ expect(createLocalAchievements().platformBacked).toBe(false);
+ });
+});
+
+describe('a platform provider', () => {
+ const provider = (): AchievementProvider & { calls: string[] } => {
+ const calls: string[] = [];
+ const unlocked = new Set<string>();
+ return {
+ calls,
+ platformBacked: true,
+ unlock: async (id) => { calls.push(`unlock ${id}`); unlocked.add(id); },
+ unlocked: (id) => unlocked.has(id),
+ setStat: (n, v) => { calls.push(`stat ${n}=${v}`); },
+ getStat: () => 0,
+ store: async () => { calls.push('store'); },
+ reset: async () => { calls.push('reset'); },
+ };
+ };
+
+ it('answers instead of the local one, and says a store is there', async () => {
+ const api = new AchievementsAPI();
+ const p = provider();
+ api.setProvider(p);
+ expect(api.available).toBe(true);
+
+ await api.unlock('A');
+ api.setStat('kills', 7);
+ await api.store();
+ expect(p.calls).toEqual(['unlock A', 'stat kills=7', 'store']);
+ // Nothing reached local storage: the platform owns the state now.
+ expect(Storage.getJSON('achievements')).toBeUndefined();
+ });
+
+ it('still refuses an undeclared id before the platform ever sees it', async () => {
+ const errors = vi.spyOn(log, 'error').mockImplementation(() => {});
+ const api = new AchievementsAPI();
+ const p = provider();
+ api.setProvider(p);
+ api.setKnown(['A']);
+ await api.unlock('B');
+ expect(p.calls).toEqual([]);
+ errors.mockRestore();
+ });
+
+ it('falls back to the local provider when cleared', async () => {
+ const api = new AchievementsAPI();
+ api.setProvider(provider());
+ api.setProvider(null);
+ expect(api.available).toBe(false);
+ await api.unlock('A');
+ expect(api.unlocked('A')).toBe(true);
+ });
+});
diff --git a/tools/check-project-settings.mjs b/tools/check-project-settings.mjs
index ff345ed09..18f6a7321 100644
--- a/tools/check-project-settings.mjs
+++ b/tools/check-project-settings.mjs
@@ -41,6 +41,10 @@ const STORE = 'desktop/src/project/ProjectStore.ts';
* printed by `--list` so the gaps stay visible rather than becoming folklore.
*/
const DECLARED_GAPS = {
+ achievements: {
+ 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',
+ },
physicsEnabled: {
editor: 'edit mode does not simulate — bodies are authored, not stepped',
},
@@ -62,6 +66,7 @@ const DECLARED_GAPS = {
/** The feature branch in the manifest parser each field is read from. */
const PARSE_KEY = {
+ achievements: 'p.achievements',
physicsEnabled: 'p.enabled',
physicsConfig: 'physics',
audioConfig: 'parseAudioProjectConfig',