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(poki): add authored training gameplay flow
yhh07e9974c2301
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex c1595bad6..0da65ba95 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -63,6 +63,11 @@ jobs:node pipeline/bin/estella.mjs export examples/playable-ad --profile "$playable_network" --wasm build/wasm/web --out "output/playable-ci-export-$playable_network" --json "output/playable-ci-export-$playable_network.json" || exit 1node tools/verify-playable.mjs "output/playable-ci-export-$playable_network/index.html" --report "output/playable-ci-export-$playable_network.json" --scenario examples/playable-ad/playable-check.json --out "output/playable-ci-check-$playable_network" --store-url https://example.com/store || exit 1done+ - name: Check authored Poki gameplay and the standalone example in SDK mocks+ run: |+ node pipeline/bin/estella.mjs export examples/mobile-controls --profile poki --wasm build/wasm/web --out output/poki-training-ci-export --json output/poki-training-ci-export.json+ node pipeline/bin/estella.mjs export examples/mobile-controls --platform web --wasm build/wasm/web --out output/poki-training-ci-standalone --json output/poki-training-ci-standalone.json+ node tools/tests/poki-training.e2e.mjs --dir output/poki-training-ci-export --standalone output/poki-training-ci-standalone --out output/poki-training-ci-check- name: Upload hash-bound local observations and screenshotsif: always()uses: actions/upload-artifact@v7@@ -70,6 +75,13 @@ jobs:name: playable-local-mock-checkspath: output/playable-ci-*retention-days: 3+ - name: Upload Poki training local observations and screenshots+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: poki-training-local-mock-checks+ path: output/poki-training-ci-*+ retention-days: 3# The engine binaries, and nothing else: every gate below waits on this job, so# a step here that no downstream job reads is a delay on all of them.diff --git a/desktop b/desktopindex 8820a435b..bd736d65a 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 8820a435b7b61c4a8dd5ea48bd8c71525fa0eaa1+Subproject commit bd736d65abe057e8fd1a5e0a3295899194e06acfdiff --git a/docs/astro/src/content/docs/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/publishing/ads-sharing.mdxindex 8baf779d4..92e71f638 100644--- a/docs/astro/src/content/docs/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/publishing/ads-sharing.mdx@@ -333,3 +333,14 @@ and successful ad behavior, and audio/input restoration require testing in the[Poki Inspector](https://developers.poki.com/guide/sdk-html5). A Web export is notplatform approval. The channel page permits HTTPS resources/frames for theSDK-managed ads; standalone retains its same-origin policy.+++The Mobile Controls example includes a `poki` export profile. Its three-hit+training round reports actual START, PAUSE, completion and REPLAY transitions,+with opt-in rewarded credits and explicit commercial opportunities. Initial+loading, device-control buttons and returning from the background do not start+gameplay. Export with `estella export examples/mobile-controls --profile poki`.+The existing standalone profile keeps its original controls. The room requires+landscape orientation and shows a rotate hint in portrait. CI checks these flows+in headless Chromium using SDK mocks and that commit's Web runtime; official+Inspector and physical-device approval remain separate.diff --git a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdxindex 398bb7289..28f8a52d7 100644--- a/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx+++ b/docs/astro/src/content/docs/zh-cn/publishing/ads-sharing.mdx@@ -296,3 +296,12 @@ Play 模式里没有本地替身,理由和登录那节一样——一次不扣恢复仍需在 [Poki Inspector](https://developers.poki.com/guide/sdk-html5)验证,成功导出不代表平台验收。渠道页面为 SDK 管理的广告允许 HTTPS资源和 iframe;独立发行继续使用同源资源策略。+++Mobile Controls 示例提供 `poki` 导出配置:三次命中的训练回合按实际开始、+暂停、完成与重玩上报事件;奖励广告由玩家主动选择,商业广告在继续游戏+或重玩前请求。初始加载、设备控制按钮和从后台返回都不触发 gameplay 开始。+运行 `estella export examples/mobile-controls --profile poki` 即可导出。+默认独立发行继续使用原有操作。该训练房要求横屏,竖屏显示旋转提示。+CI 使用真正无头 Chromium、SDK 模拟和同提交 Web WASM 检查这些流程;+官方 Inspector 与物理设备验收仍需单独完成。diff --git a/examples/mobile-controls/README.md b/examples/mobile-controls/README.mdindex a0f47471d..7da7f3fa9 100644--- a/examples/mobile-controls/README.md+++ b/examples/mobile-controls/README.md@@ -41,3 +41,27 @@ The browser/mini-game contract host verifies export, rendering and input wiring.It cannot certify WeChat base-library behavior, Safari permission prompts on aphone, native sensor axes, vibration hardware, or real background/foregroundbehavior. Those remain separate device acceptance checks.+++## Poki Web training profile++Export the same room with `node pipeline/bin/estella.mjs export+examples/mobile-controls --profile poki`. START begins a three-hit round; PAUSE+stops gameplay, RESUME gives Poki a commercial opportunity, and the third hit+ends the round. REPLAY resets the player and monster after a commercial break.+WATCH AD +1 is an explicit opt-in for one training credit. A skipped or failed+video grants no credit. Credits persist across rounds for this page session;+this example does not implement cloud storage.++Only the Poki export adds these controls. The HTML channel marker preserves this+flow even if the SDK script fails: training still works, ads remain unavailable.+Gameplay notifications use the official SDK directly; loading notifications+remain the export host's responsibility. Device permission/fullscreen buttons+never start gameplay. Hidden gameplay stops once; returning requires RESUME.+An ad that closes while hidden preserves the paused state instead of sending a+new gameplay-start event. Menu or finished-state rewards do not report gameplay.++The profile uses the same CC0 room, authored joystick and character textures.+Its local headless scenario is SDK wiring evidence, not Poki Inspector approval+or physical-device acceptance. Test with the official+[Poki Inspector](https://developers.poki.com/guide/sdk-html5) before submission.diff --git a/examples/mobile-controls/project.esproject b/examples/mobile-controls/project.esprojectindex eb04c4c5c..9696cd31b 100644--- a/examples/mobile-controls/project.esproject+++ b/examples/mobile-controls/project.esproject@@ -9,5 +9,17 @@"width": 800,"height": 450},- "spineVersion": "none"+ "spineVersion": "none",+ "packaging": {+ "profiles": {+ "poki": {+ "platform": "web",+ "platforms": {+ "web": {+ "channel": "poki"+ }+ }+ }+ }+ }}diff --git a/examples/mobile-controls/src/main.ts b/examples/mobile-controls/src/main.tsindex bc5c9abea..ddc101c9f 100644--- a/examples/mobile-controls/src/main.ts+++ b/examples/mobile-controls/src/main.ts@@ -2,8 +2,10 @@ import {addStartupSystem, addSystemToSchedule, defineSystem, Schedule, Res, GetWorld,Input, InputMap, Axis2D, Button, Keys2D, Key, Virtual, Time, Transform, Sprite,UIEvents, Text, Name, UINode, UIPositionType, spawnUIEntity, createButton, px, Device,- type Entity, type DeviceResult,+ Ads, type World, type Entity, type DeviceResult,} from 'esengine';+import { setupPokiTraining } from './pokiTrainingUI';+import type { TrainingSession } from './pokiTraining';const controls = new InputMap({ Move: Axis2D(Keys2D('KeyW', 'KeyS', 'KeyA', 'KeyD'), Virtual('move')),Fire: Button(Key('Space'), Virtual('fire')) });@@ -12,13 +14,23 @@ let motion = false;let motionData = 'off';let status: Entity | null = null;let message = 'Drag the left stick and hold Fire. WASD / Space also work.';+let trainer: TrainingSession | null = null;let hits = 0;let hitFlash = 0;let recoil = 0;let misses = 0;const report = (name: string) => (result: DeviceResult) => { message = `${name}: ${result.status}${result.reason ? ` (${result.reason})` : ''}`; };-addStartupSystem(defineSystem([Res(UIEvents), GetWorld()], (events, world) => {+const refreshStatus = (world: World): void => {+ if (status === null || !world.valid(status)) return;+ const caps = Device.capabilities();+ const content = trainer+ ? `${trainer.phase.toUpperCase()} / ${trainer.message}\nRound: ${trainer.hits} / 3 hits / Credits: ${trainer.credits} / Motion: ${motion ? motionData : 'off'} / ${message}`+ : `${message}\nHits: ${hits} / Sensor data: ${motion ? motionData : 'off'} / Vibration API: ${caps.vibration ? 'available' : 'unavailable'}`;+ if (world.get(status, Text).content !== content) world.insert(status, Text, { ...world.get(status, Text), content });+};++addStartupSystem(defineSystem([Res(UIEvents), Res(Ads), GetWorld()], (events, ads, world) => {const canvas = world.findEntityByName('Canvas'); if (canvas === null) return;spawnUIEntity({ world, parent: canvas,node: { position: UIPositionType.Absolute, insetLeft: px(30), insetTop: px(6), width: px(740), height: px(22), pointerEvents: 1 },@@ -60,10 +72,25 @@ addStartupSystem(defineSystem([Res(UIEvents), GetWorld()], (events, world) => {visual: { color: { r: 0.075, g: 0.09, b: 0.14, a: 0.95 } },text: { content: 'Approach the monster, then attack.\nWASD / stick to move / Space / Fire to attack', fontSize: 13 } });world.insert(hint, UINode, { ...world.get(hint, UINode), pointerEvents: 1 });+ const player = world.findEntityByName('Player'); const target = world.findEntityByName('Target');+ if (player !== null && target !== null) {+ const playerStart = { ...world.get(player, Transform).position };+ const targetStart = { ...world.get(target, Transform).position };+ trainer = setupPokiTraining(world, events, canvas, ads, () => {+ hits = 0; misses = 0; hitFlash = 0; recoil = 0;+ for (const [entity, position] of [[player, playerStart], [target, targetStart]] as const) {+ const transform = world.get(entity, Transform); transform.position = { ...position };+ transform.scale = { x: 1, y: 1, z: 1 }; world.insert(entity, Transform, transform);+ world.insert(entity, Sprite, { ...world.get(entity, Sprite), color: { r: 1, g: 1, b: 1, a: 1 } });+ }+ }, () => refreshStatus(world));+ refreshStatus(world);+ }}, { name: 'MobileControlsSetup' }));addSystemToSchedule(Schedule.Update, defineSystem([Res(Input), Res(Time), GetWorld()], (input, time, world) => {controls.evaluate(input);+ if (trainer && trainer.phase !== 'playing') { refreshStatus(world); return; }const player = world.findEntityByName('Player'); const target = world.findEntityByName('Target');if (player === null || target === null) return;const axis = controls.axis2d('Move'); const transform = world.get(player, Transform);@@ -85,7 +112,7 @@ addSystemToSchedule(Schedule.Update, defineSystem([Res(Input), Res(Time), GetWorif (controls.pressed('Fire')) {recoil = 0.12;if (Math.hypot(destination.x - transform.position.x, destination.y - transform.position.y) < 85) {- hits++; hitFlash = 0.3; message = `Hit! Training score: ${hits}`; void Device.vibrate({ duration: 'short', intensity: 'heavy' }).then(report('Hit vibration'));+ hits++; trainer?.hit(); hitFlash = 0.3; message = `Hit! Training score: ${hits}`; void Device.vibrate({ duration: 'short', intensity: 'heavy' }).then(report('Hit vibration'));if (hits % 3 === 0) {targetTransform.position = { ...destination,x: destination.x > 0 ? -180 : 180, y: hits % 2 === 0 ? -40 : 40 };@@ -93,9 +120,5 @@ addSystemToSchedule(Schedule.Update, defineSystem([Res(Input), Res(Time), GetWor}} else { misses++; message = `Out of reach - move closer to the monster. Misses: ${misses}`; }}- if (status !== null && world.valid(status)) {- const caps = Device.capabilities();- const content = `${message}\nHits: ${hits} / Sensor data: ${motion ? motionData : 'off'} / Vibration API: ${caps.vibration ? 'available' : 'unavailable'}`;- if (world.get(status, Text).content !== content) world.insert(status, Text, { ...world.get(status, Text), content });- }+ refreshStatus(world);}, { name: 'MobileControlsUpdate' }));diff --git a/examples/mobile-controls/src/pokiTraining.ts b/examples/mobile-controls/src/pokiTraining.tsnew file mode 100644index 000000000..0615ec11b--- /dev/null+++ b/examples/mobile-controls/src/pokiTraining.ts@@ -0,0 +1,85 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** Authored training state: platform events follow actual game transitions. */+export type TrainingPhase = 'menu' | 'playing' | 'paused' | 'finished' | 'ad';+export interface TrainingAds {+ readonly available: boolean;+ showRewarded(id: string): Promise<{ completed: boolean }>;+ showInterstitial(id: string): Promise<void>;+}+export interface TrainingHooks {+ gameplayStart(): void;+ gameplayStop(): void;+ reset(): void;+ changed(): void;+}+export class TrainingSession {+ phase: TrainingPhase = 'menu';+ credits = 0;+ hits = 0;+ message = 'Press START to begin a three-hit training round.';+ private hidden = false;+ private disposed = false;+ constructor(private readonly ads: TrainingAds, private readonly hooks: TrainingHooks) {}++ async begin(): Promise<void> {+ if (this.disposed || this.hidden || this.phase === 'playing' || this.phase === 'ad') return;+ const previous = this.phase;+ if (previous !== 'menu' && this.ads.available) {+ this.phase = 'ad'; this.message = 'Commercial break. Training is paused.'; this.hooks.changed();+ try { await this.ads.showInterstitial('poki'); }+ catch { this.message = 'No commercial available. Continue training.'; }+ }+ if (this.disposed) return;+ if (previous === 'finished') { this.hits = 0; this.hooks.reset(); }+ if (this.hidden) {+ this.phase = 'paused'; this.message = 'Game hidden. Press RESUME when you return.';+ } else {+ this.phase = 'playing'; this.message = 'Approach the monster and land three hits.';+ this.hooks.gameplayStart();+ }+ this.hooks.changed();+ }+ pause(): void {+ if (this.disposed || this.phase !== 'playing') return;+ this.phase = 'paused'; this.message = 'Paused. Press RESUME to continue.';+ this.hooks.gameplayStop(); this.hooks.changed();+ }+ hit(): void {+ if (this.disposed || this.phase !== 'playing') return;+ if (++this.hits >= 3) {+ this.phase = 'finished'; this.message = 'Training complete! Press REPLAY for a new round.';+ this.hooks.gameplayStop();+ }+ this.hooks.changed();+ }+ async reward(): Promise<void> {+ if (this.disposed || !this.ads.available || this.phase === 'ad' || this.hidden) return;+ const previous = this.phase;+ if (previous === 'playing') this.hooks.gameplayStop();+ this.phase = 'ad'; this.message = 'Rewarded break. Watch to earn one training credit.'; this.hooks.changed();+ try {+ const result = await this.ads.showRewarded('poki');+ if (this.disposed) return;+ if (result.completed) { this.credits++; this.message = 'Reward earned: +1 training credit.'; }+ else this.message = 'Video not completed. No reward granted.';+ } catch {+ if (this.disposed) return;+ this.message = 'No rewarded ad available. No reward granted.';+ }+ this.phase = previous === 'playing' && this.hidden ? 'paused' : previous;+ if (this.phase === 'playing') this.hooks.gameplayStart();+ this.hooks.changed();+ }+ visibility(hidden: boolean): void {+ if (this.disposed) return;+ this.hidden = hidden;+ if (hidden) this.pause();+ }+ dispose(): void {+ if (this.disposed) return;+ this.disposed = true;+ if (this.phase === 'playing') this.hooks.gameplayStop();+ this.phase = 'paused';+ }+}diff --git a/examples/mobile-controls/src/pokiTrainingUI.ts b/examples/mobile-controls/src/pokiTrainingUI.tsnew file mode 100644index 000000000..e668ee122--- /dev/null+++ b/examples/mobile-controls/src/pokiTrainingUI.ts@@ -0,0 +1,60 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { createButton, spawnUIEntity, Text, Name, UIPositionType, px, type AdsAPI } from 'esengine';+import { TrainingSession } from './pokiTraining';++type ButtonOptions = Parameters<typeof createButton>[0];+interface PokiGameplay { gameplayStart(): void; gameplayStop(): void }++export function setupPokiTraining(+ world: ButtonOptions['world'], events: ButtonOptions['events'], parent: NonNullable<ButtonOptions['parent']>,+ ads: AdsAPI, reset: () => void, refresh: () => void,+): TrainingSession | null {+ if (typeof document === 'undefined' || document.documentElement?.dataset?.webChannel !== 'poki') return null;+ const notify = (event: keyof PokiGameplay): void => {+ const sdk = (globalThis as unknown as { PokiSDK?: PokiGameplay }).PokiSDK;+ try { sdk?.[event](); }+ catch (error) { console.warn('[training] Poki gameplay event failed', event, error); }+ };+ const controls: Array<{ button: ReturnType<typeof createButton>; label: ReturnType<typeof spawnUIEntity> }> = [];+ const update = (): void => {+ if (controls.length !== 3 || !world.valid(parent) || world.isDestructionPending(parent)) return;+ const phase = session.phase;+ const labels = [phase === 'menu' ? 'START' : phase === 'finished' ? 'REPLAY' : 'RESUME', 'PAUSE', ads.available ? 'WATCH AD +1' : 'ADS UNAVAILABLE'];+ controls.forEach(({ button, label }, index) => {+ button.setDisabled(index === 0 ? phase === 'playing' || phase === 'ad'+ : index === 1 ? phase !== 'playing' : !ads.available || phase === 'ad');+ world.insert(label, Text, { ...world.get(label, Text), content: labels[index] });+ });+ refresh();+ };+ const session = new TrainingSession(ads, {+ gameplayStart: () => notify('gameplayStart'), gameplayStop: () => notify('gameplayStop'), reset, changed: update,+ });+ const actions = [() => { void session.begin(); }, () => session.pause(), () => { void session.reward(); }];+ for (let index = 0; index < 3; index++) {+ const button = createButton({ world, events, parent, userGesture: true,+ node: { position: UIPositionType.Absolute, insetLeft: px(232 + index * 118), insetTop: px(346), width: px(112), height: px(36) },+ onClick: actions[index],+ });+ world.insert(button.entity, Name, { value: ['TrainingStart', 'TrainingPause', 'TrainingReward'][index] });+ const label = spawnUIEntity({ world, parent: button.entity, node: { fill: true }, text: { content: '', fontSize: 13 } });+ controls.push({ button, label });+ }+ const onVisibility = () => session.visibility(document.hidden);+ const onHide = () => session.visibility(true);+ document.addEventListener('visibilitychange', onVisibility);+ window.addEventListener('pagehide', onHide);+ window.addEventListener('pageshow', onVisibility);+ const offDespawn = world.onDespawn(entity => {+ if (entity !== parent) return;+ document.removeEventListener('visibilitychange', onVisibility);+ window.removeEventListener('pagehide', onHide);+ window.removeEventListener('pageshow', onVisibility);+ offDespawn(); session.dispose();+ controls.forEach(({ button }) => button.dispose());+ });+ session.visibility(document.hidden);+ update();+ return session;+}diff --git a/pipeline/src/export/exportGame.ts b/pipeline/src/export/exportGame.tsindex d2c5c2aa6..7b227da68 100644--- a/pipeline/src/export/exportGame.ts+++ b/pipeline/src/export/exportGame.ts@@ -353,7 +353,7 @@ function indexHtml(? `default-src 'self' data: blob: https:; script-src 'self' 'unsafe-eval' blob: https: ${inlineScripts}; style-src 'self' 'unsafe-inline' https:; img-src 'self' data: blob: https:; connect-src 'self' data: blob: https:${connect}; frame-src https:; media-src 'self' data: blob: https:; worker-src 'self' blob:;`: `default-src 'self'; script-src 'self' 'unsafe-eval' blob: ${inlineScripts}; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self' data: blob:${connect}; worker-src 'self' blob:;`;return `<!doctype html>-<html lang="en">+<html lang="en" data-web-channel="${webChannel === 'poki' ? 'poki' : 'standalone'}"><head><meta charset="UTF-8" /><metadiff --git a/pipeline/tests/export-splash.test.ts b/pipeline/tests/export-splash.test.tsindex ef33aca36..59ee3ce46 100644--- a/pipeline/tests/export-splash.test.ts+++ b/pipeline/tests/export-splash.test.ts@@ -136,11 +136,13 @@ describe('Poki host page', () => {expect(html.indexOf(script)).toBeGreaterThan(html.indexOf('<head>'));expect(html.indexOf(script)).toBeLessThan(html.indexOf('</head>'));expect(html.indexOf(script)).toBeLessThan(html.indexOf('src="./game.js"'));+ expect(html).toContain('data-web-channel="poki"');expect(html).toContain('frame-src https:');expect(html).toContain("script-src 'self' 'unsafe-eval' blob: https:");});it('keeps standalone exports free of SDK injection and broad HTTPS policy', async () => {const { html } = await page();+ expect(html).toContain('data-web-channel="standalone"');expect(html).not.toContain('poki-sdk');expect(html).not.toContain('frame-src https:');expect(html).toContain("default-src 'self';");diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 83fdecba5..cbfdc252e 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,12 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'fix(audio): preserve latest Web device suspension intent':+ { note: 'Web audio preserves the latest device pause intent.' },+ 'feat(poki): add authored training gameplay flow':+ { note: 'Poki training reports authored gameplay and ad outcomes.' },+ 'feat(editor): point Poki settings to the training example':+ { note: 'Poki training reports authored gameplay and ad outcomes.' },'feat(web): connect Poki channel exports to ads services':{ note: 'Web exports can select the Poki channel.' },'feat(editor): expose Poki Web distribution channel':diff --git a/tools/tests/poki-training.e2e.mjs b/tools/tests/poki-training.e2e.mjsnew file mode 100644index 000000000..9fb41a3a5--- /dev/null+++ b/tools/tests/poki-training.e2e.mjs@@ -0,0 +1,222 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/** Shipped training example with explicit local SDK mocks; no visible browser. */+import fs from 'node:fs';+import path from 'node:path';+import http from 'node:http';+import crypto from 'node:crypto';+import assert from 'node:assert/strict';+import { chromium } from 'playwright';++const args = process.argv.slice(2);+const flag = name => { const at = args.indexOf(name); return at >= 0 ? args[at + 1] : undefined; };+if (!flag('--dir') || !flag('--standalone')) throw new Error('Expected --dir <Poki export> --standalone <ordinary Web export>');+const out = path.resolve(flag('--out') ?? 'output/poki-training-check');+fs.mkdirSync(out, { recursive: true });+const roots = { poki: fs.realpathSync(flag('--dir')), standalone: fs.realpathSync(flag('--standalone')) };+const sha = file => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');+const filesOf = (root, under = '') => fs.readdirSync(path.join(root, under), { withFileTypes: true }).flatMap(entry => {+ const file = under ? `${under}/${entry.name}` : entry.name;+ if (entry.isDirectory()) return filesOf(root, file);+ if (!entry.isFile()) throw new Error(`Unsupported export entry: ${file}`);+ return [file];+});+const identities = Object.fromEntries(Object.entries(roots).map(([name, root]) => [name,+ Object.fromEntries(filesOf(root).map(file => [file, sha(path.join(root, file))])),+]));+const mime = { '.html': 'text/html', '.js': 'text/javascript', '.mjs': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.webp': 'image/webp' };+const server = http.createServer((req, res) => {+ try {+ const parts = decodeURIComponent(new URL(req.url, 'http://localhost').pathname).split('/');+ const root = roots[parts[1]];+ if (!root) throw new Error('Unknown export');+ const file = fs.realpathSync(path.resolve(root, parts.slice(2).join('/') || 'index.html'));+ if (!file.startsWith(root + path.sep) || !fs.statSync(file).isFile()) throw new Error('Outside export');+ res.setHeader('Content-Type', mime[path.extname(file)] ?? 'application/octet-stream');+ res.end(fs.readFileSync(file));+ } catch { res.writeHead(404); res.end(); }+});+await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+const origin = `http://127.0.0.1:${server.address().port}`;+const browser = await chromium.launch({ headless: true, args: ['--enable-unsafe-swiftshader', '--use-angle=swiftshader', '--mute-audio'] });+const cases = [];+const result = { mode: 'local-mock', headless: true, status: 'failed', identities,+ verifierSha256: sha(new URL(import.meta.url)), cases,+ pending: ['Official SDK and Poki Inspector acceptance', 'Physical devices and real background transitions', 'Audible quality', 'Other channels and cloud saves'] };+const position = page => page.evaluate(() => window.__estellaCooked.probe(['Player']).at.Player);+const status = page => page.evaluate(() => window.__estellaCooked.probe(['DeviceStatus']).at.DeviceStatus?.text ?? '');++try {+ for (const viewport of [{ width: 800, height: 450 }, { width: 360, height: 640 }]) {+ for (const mode of ['normal', 'init-failed', 'sdk-missing', 'standalone']) {+ const context = await browser.newContext({ viewport });+ const page = await context.newPage();+ const observation = { viewport, mode, status: 'failed', errors: [], unexpectedRequests: [], events: [], screenshots: [] };+ cases.push(observation);+ page.on('pageerror', error => observation.errors.push(String(error)));+ await page.addInitScript(() => {+ window.__audioContexts = [];+ window.__audioOperations = [];+ const Original = window.AudioContext;+ if (Original) window.AudioContext = class extends Original {+ constructor(...args) { super(...args); window.__audioContexts.push(this); }+ resume() {+ window.__audioOperations.push({ kind: 'resume', state: this.state, stack: new Error().stack });+ return super.resume();+ }+ suspend() {+ window.__audioOperations.push({ kind: 'suspend', state: this.state, stack: new Error().stack });+ return super.suspend();+ }+ };+ });+ await context.route('**/*', async route => {+ const url = route.request().url();+ if (url.startsWith(origin + '/')) return route.continue();+ if (url === 'https://game-cdn.poki.com/scripts/v2/poki-sdk.js' && mode !== 'standalone') {+ return route.fulfill({ contentType: 'text/javascript', body: mode === 'sdk-missing' ? '' : `+ window.__events=[];+ const record=event=>__events.push({event,active:navigator.userActivation.isActive});+ window.PokiSDK={+ init(){record('init');return ${mode === 'init-failed' ? 'Promise.reject(new Error("blocked"))' : 'Promise.resolve()'}},+ gameLoadingFinished(){record('loaded')},gameplayStart(){record('start')},gameplayStop(){record('stop')},+ rewardedBreak(){record('rewarded');return new Promise((resolve,reject)=>{window.__close=value=>value==='error'?reject(new Error('no fill')):resolve(value)})},+ commercialBreak(){record('commercial');return new Promise((resolve,reject)=>{window.__close=value=>value==='error'?reject(new Error('no fill')):resolve()})}+ };` });+ }+ observation.unexpectedRequests.push(url); return route.abort();+ });+ try {+ await page.goto(`${origin}/${mode === 'standalone' ? 'standalone' : 'poki'}/?headless`);+ await page.waitForFunction(() => window.__estellaCooked?.probe(['DeviceStatus', 'Player']).at.DeviceStatus?.text, {}, { timeout: 30000 });+ if (mode !== 'sdk-missing' && mode !== 'standalone') {+ await page.waitForFunction(() => window.__events?.some(e => e.event === 'loaded'));+ }+ let surface = viewport;+ const click = async name => {+ observation.lastClick = name;+ const box = await page.evaluate(n => window.__estellaCooked.probe([n]).at[n], name);+ assert(box, `Missing button ${name}`);+ const scale = Math.min(surface.width / 800, surface.height / 450);+ await page.mouse.click(surface.width / 2 + box.x * scale, surface.height / 2 - box.y * scale);+ await page.waitForTimeout(100);+ };+ const phase = expected => page.waitForFunction(prefix => window.__estellaCooked.probe(['DeviceStatus']).at.DeviceStatus.text.startsWith(prefix), expected.toUpperCase(), { timeout: 5000 });+ const snapshot = async label => {+ const file = `${mode}-${viewport.width}x${viewport.height}-${label}.png`;+ await page.screenshot({ path: path.join(out, file) });+ observation.screenshots.push({ file, sha256: sha(path.join(out, file)) });+ };+ const expected = mode === 'sdk-missing' || mode === 'standalone' ? [] : ['init', 'loaded'];+ const trace = async () => assert.deepEqual(await page.evaluate(() => (window.__events ?? []).map(e => e.event)), expected);+ if (viewport.height > viewport.width) {+ assert.equal(await page.evaluate(() => getComputedStyle(document.getElementById('rotate-hint')).display), 'flex');+ assert.equal(await page.evaluate(() => getComputedStyle(document.getElementById('canvas')).display), 'none');+ await snapshot('rotate-hint'); await trace();+ surface = { width: viewport.height, height: viewport.width };+ observation.rotatedViewport = surface;+ await page.setViewportSize(surface);+ await page.waitForFunction(() => getComputedStyle(document.getElementById('canvas')).display !== 'none');+ await page.waitForTimeout(100); await trace();+ }+ if (mode === 'standalone') {+ assert.equal(await page.evaluate(() => !!window.__estellaCooked.probe(['TrainingStart']).at.TrainingStart), false);+ const before = await position(page);+ await page.keyboard.down('KeyD'); await page.waitForTimeout(180); await page.keyboard.up('KeyD');+ assert.notDeepEqual(await position(page), before, 'Standalone controls retain their original behavior');+ await snapshot('playing');+ } else {+ await phase('menu'); await trace();+ const before = await position(page);+ await page.keyboard.down('KeyD'); await page.waitForTimeout(150); await page.keyboard.up('KeyD');+ assert.deepEqual(await position(page), before, 'Menu input must not move the player');+ await click('Keep awake'); await trace();+ await snapshot('menu'); await click('TrainingStart'); await phase('playing');+ if (mode !== 'sdk-missing') expected.push('start'); await trace();+ if (mode !== 'normal') {+ await click('TrainingReward'); await trace(); assert.match(await status(page), /Credits: 0/);+ await click('TrainingPause'); await phase('paused');+ if (mode !== 'sdk-missing') expected.push('stop'); await trace();+ await click('TrainingStart'); await phase('playing');+ if (mode !== 'sdk-missing') expected.push('start'); await trace();+ } else {+ assert.equal((await page.evaluate(() => __events.find(e => e.event === 'start'))).active, true);+ await page.waitForFunction(() => __audioContexts.length > 0 && __audioContexts.every(c => c.state === 'running'));+ await click('TrainingStart'); await trace();+ await click('TrainingPause'); expected.push('stop'); await phase('paused'); await trace();+ const frozen = await position(page);+ await page.keyboard.down('KeyD'); await page.waitForTimeout(150); await page.keyboard.up('KeyD'); assert.deepEqual(await position(page), frozen);+ await click('TrainingStart'); expected.push('commercial'); await phase('ad'); await trace();+ assert.equal((await page.evaluate(() => __events.find(e => e.event === 'commercial'))).active, true);+ await click('TrainingReward'); await click('TrainingStart'); await trace();+ await page.waitForFunction(() => __audioContexts.every(c => c.state === 'suspended'));+ await page.evaluate(() => __close(true)); expected.push('start'); await phase('playing'); await trace();+ for (const [outcome, credits] of [[false, 0], [true, 1], ['error', 1]]) {+ await click('TrainingReward'); expected.push('stop', 'rewarded'); await phase('ad'); await trace();+ const at = await position(page);+ await page.keyboard.down('KeyD'); await page.waitForTimeout(150); await page.keyboard.up('KeyD'); assert.deepEqual(await position(page), at);+ await page.waitForFunction(() => __audioContexts.every(c => c.state === 'suspended'));+ await page.evaluate(value => __close(value), outcome); expected.push('start'); await phase('playing'); await trace();+ await page.waitForFunction(() => __audioContexts.every(c => c.state === 'running'));+ assert.match(await status(page), new RegExp(`Credits: ${credits}`));+ }+ const at = await page.evaluate(() => window.__estellaCooked.probe(['Player', 'Target']).at);+ const vertical = at.Target.y > at.Player.y ? 'KeyW' : 'KeyS';+ if (Math.abs(at.Target.y - at.Player.y) > 15) {+ await page.keyboard.down(vertical);+ await page.waitForFunction(() => { const p=__estellaCooked.probe(['Player','Target']).at;return Math.abs(p.Player.y-p.Target.y)<15; }, {}, { timeout: 5000 });+ await page.keyboard.up(vertical);+ }+ const current = await page.evaluate(() => window.__estellaCooked.probe(['Player', 'Target']).at);+ const horizontal = current.Target.x > current.Player.x ? 'KeyD' : 'KeyA';+ await page.keyboard.down(horizontal);+ await page.waitForFunction(() => { const p=__estellaCooked.probe(['Player','Target']).at;return Math.hypot(p.Player.x-p.Target.x,p.Player.y-p.Target.y)<60; }, {}, { timeout: 6000 });+ await page.keyboard.up(horizontal);+ for (let hit=0;hit<3;hit++) { await page.keyboard.press('Space', { delay: 80 }); await page.waitForTimeout(80); }+ expected.push('stop'); await phase('finished'); await trace(); assert.match(await status(page), /Round: 3 \/ 3 hits/);+ await snapshot('finished');+ await click('TrainingReward'); expected.push('rewarded'); await phase('ad'); await trace();+ await page.evaluate(() => __close(true)); await phase('finished'); await trace(); assert.match(await status(page), /Credits: 2/);+ await click('TrainingStart'); expected.push('commercial'); await phase('ad'); await trace();+ await page.evaluate(() => __close('error')); expected.push('start'); await phase('playing'); await trace(); assert.match(await status(page), /Round: 0 \/ 3 hits/);+ // This checks the authored guard, not physical device backgrounding.+ await page.evaluate(() => { Object.defineProperty(document, 'hidden', { configurable: true, value: true }); document.dispatchEvent(new Event('visibilitychange')); });+ expected.push('stop'); await phase('paused'); await trace();+ await page.evaluate(() => { Object.defineProperty(document, 'hidden', { configurable: true, value: false }); document.dispatchEvent(new Event('visibilitychange')); });+ await trace(); await phase('paused'); await snapshot('paused');+ }+ }+ if (mode !== 'standalone') {+ const wasPlaying = (await status(page)).startsWith('PLAYING');+ await page.evaluate(() => window.dispatchEvent(new Event('pagehide')));+ if (wasPlaying && mode !== 'sdk-missing') expected.push('stop');+ await phase('paused'); await trace();+ await page.evaluate(() => window.dispatchEvent(new Event('pageshow')));+ await phase('paused'); await trace();+ }+ await trace(); observation.events = await page.evaluate(() => window.__events ?? []);+ observation.audioOperations = await page.evaluate(() => __audioOperations.map(({ kind, state }) => ({ kind, state })));+ assert.deepEqual(observation.errors, []); assert.deepEqual(observation.unexpectedRequests, []);+ observation.status = 'passed';+ } catch (error) {+ observation.failure = String(error);+ observation.diagnostics = await page.evaluate(() => ({+ events: window.__events ?? [], audioStates: (window.__audioContexts ?? []).map(c => c.state),+ audioOperations: window.__audioOperations ?? [],+ status: window.__estellaCooked?.probe(['DeviceStatus']).at.DeviceStatus?.text,+ }));+ throw error;+ }+ finally { await context.close(); }+ }+ }+ for (const [name, root] of Object.entries(roots)) {+ assert.deepEqual(filesOf(root).sort(), Object.keys(identities[name]).sort(), 'Export file set changed during verification');+ for (const [file, hash] of Object.entries(identities[name])) assert.equal(sha(path.join(root, file)), hash, 'Export changed during verification');+ }+ result.status = 'checks-passed';+ console.log(`Poki training: ${cases.length} headless cases passed (SDK mocks; official/device acceptance pending)`);+} finally {+ fs.writeFileSync(path.join(out, 'runtime-check.json'), JSON.stringify(result, null, 2));+ await browser.close(); await new Promise(resolve => server.close(resolve));+}diff --git a/tools/tests/poki-training.test.ts b/tools/tests/poki-training.test.tsnew file mode 100644index 000000000..31311ec4b--- /dev/null+++ b/tools/tests/poki-training.test.ts@@ -0,0 +1,108 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect } from 'vitest';+import { TrainingSession, type TrainingAds } from '../../examples/mobile-controls/src/pokiTraining';++function harness() {+ const events: string[] = [];+ const ads: TrainingAds = { available: true,+ showRewarded: async () => { events.push('rewarded'); return { completed: true }; },+ showInterstitial: async () => { events.push('commercial'); },+ };+ const session = new TrainingSession(ads, {+ gameplayStart: () => events.push('start'), gameplayStop: () => events.push('stop'),+ reset: () => events.push('reset'), changed: () => {},+ });+ return { session, ads, events };+}++describe('authored Poki training flow', () => {+ it('menu hits and construction emit no gameplay; first intent starts once', async () => {+ const { session, events } = harness(); session.hit(); session.hit();+ expect(session.hits).toBe(0); expect(events).toEqual([]);+ await session.begin(); await session.begin();+ expect(events).toEqual(['start']);+ });+ it('pause is idempotent and resume signals a commercial before gameplay', async () => {+ const { session, events } = harness(); await session.begin(); session.pause(); session.pause(); session.hit();+ expect(session.hits).toBe(0); await session.begin();+ expect(events).toEqual(['start', 'stop', 'commercial', 'start']);+ });+ it('three actual hits finish once and explicit replay resets after the break', async () => {+ const { session, events } = harness(); await session.begin();+ session.hit(); session.hit(); session.hit(); session.hit();+ expect(session.phase).toBe('finished'); expect(session.hits).toBe(3);+ await session.begin(); expect(session.hits).toBe(0);+ expect(events).toEqual(['start', 'stop', 'commercial', 'reset', 'start']);+ });+ for (const outcome of ['success', 'abandoned', 'error'] as const) {+ it(`restores playing after a ${outcome} rewarded break; rewards only completion`, async () => {+ const { session, ads, events } = harness();+ ads.showRewarded = async () => { events.push('rewarded'); if (outcome === 'error') throw new Error('no fill'); return { completed: outcome === 'success' }; };+ await session.begin(); await session.reward();+ expect(session.phase).toBe('playing'); expect(session.credits).toBe(outcome === 'success' ? 1 : 0);+ expect(events).toEqual(['start', 'stop', 'rewarded', 'start']);+ });+ }+ it('a menu reward emits no gameplay start/stop', async () => {+ const { session, events } = harness(); await session.reward();+ expect(events).toEqual(['rewarded']); expect(session.phase).toBe('menu'); expect(session.credits).toBe(1);+ });+ it('paused/finished rewards preserve their game state', async () => {+ const { session, events } = harness(); await session.begin(); session.pause(); await session.reward();+ expect(session.phase).toBe('paused'); expect(events).toEqual(['start', 'stop', 'rewarded']);+ await session.begin(); session.hit(); session.hit(); session.hit(); const before = events.length;+ await session.reward(); expect(session.phase).toBe('finished'); expect(events.slice(before)).toEqual(['rewarded']);+ });+ it('ignores overlapping actions and hits while an ad is pending', async () => {+ const { session, ads, events } = harness(); let close!: (result: { completed: boolean }) => void;+ ads.showRewarded = () => { events.push('rewarded'); return new Promise(resolve => { close = resolve; }); };+ await session.begin(); const pending = session.reward();+ await session.reward(); await session.begin(); session.pause(); session.hit();+ expect(session.phase).toBe('ad'); expect(events).toEqual(['start', 'stop', 'rewarded']); expect(session.hits).toBe(0);+ close({ completed: true }); await pending; expect(events).toEqual(['start', 'stop', 'rewarded', 'start']);+ });+ it('hidden gameplay stops once and foreground requires a new resume intent', async () => {+ const { session, events } = harness(); await session.begin(); session.visibility(true); session.visibility(true);+ await session.begin(); expect(events).toEqual(['start', 'stop']);+ session.visibility(false); expect(session.phase).toBe('paused'); expect(events).toEqual(['start', 'stop']);+ await session.begin(); expect(events).toEqual(['start', 'stop', 'commercial', 'start']);+ });+ it('a rewarded completion in the background grants the reward without restarting gameplay', async () => {+ const { session, ads, events } = harness(); let close!: (result: { completed: boolean }) => void;+ ads.showRewarded = () => { events.push('rewarded'); return new Promise(resolve => { close = resolve; }); };+ await session.begin(); const pending = session.reward(); session.visibility(true); close({ completed: true }); await pending;+ expect(session.credits).toBe(1); expect(session.phase).toBe('paused'); expect(events).toEqual(['start', 'stop', 'rewarded']);+ });+ it('a commercial completion in the background waits for player intent', async () => {+ const { session, ads, events } = harness(); let close!: () => void;+ ads.showInterstitial = () => { events.push('commercial'); return new Promise(resolve => { close = resolve; }); };+ await session.begin(); session.pause(); const pending = session.begin(); session.visibility(true); close(); await pending;+ expect(session.phase).toBe('paused'); expect(events).toEqual(['start', 'stop', 'commercial']);+ });+ it('missing ads never prevent gameplay and never grant a reward', async () => {+ const { session, ads, events } = harness(); Object.defineProperty(ads, 'available', { value: false });+ await session.begin(); session.pause(); await session.begin(); await session.reward();+ expect(session.phase).toBe('playing'); expect(session.credits).toBe(0); expect(events).toEqual(['start', 'stop', 'start']);+ });+ it('commercial rejection resumes gameplay without leaving an ad phase', async () => {+ const { session, ads, events } = harness(); ads.showInterstitial = async () => { events.push('commercial'); throw new Error('no fill'); };+ await session.begin(); session.pause(); await session.begin();+ expect(session.phase).toBe('playing'); expect(events).toEqual(['start', 'stop', 'commercial', 'start']);+ });+});+++describe('Poki training scene lifetime', () => {+ it('scene cleanup stops playing once and rejects later actions', async () => {+ const { session, events } = harness(); await session.begin();+ session.dispose(); session.dispose(); await session.begin(); await session.reward(); session.hit();+ expect(events).toEqual(['start', 'stop']); expect(session.credits).toBe(0);+ });+ it('a reward finishing after scene cleanup cannot restart gameplay or mutate credits', async () => {+ const { session, ads, events } = harness(); let close!: (result: { completed: boolean }) => void;+ ads.showRewarded = () => { events.push('rewarded'); return new Promise(resolve => { close = resolve; }); };+ await session.begin(); const pending = session.reward(); session.dispose(); close({ completed: true }); await pending;+ expect(events).toEqual(['start', 'stop', 'rewarded']); expect(session.credits).toBe(0);+ });+});