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
test(gameplay): drive the character in its own package, and find out realVelocity was lying
esengineb25a31a3c87f
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex d41591b69..71fc54ac9 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -616,6 +616,12 @@ jobs:- name: Launch the golden packages and compare them to the editor (PR tier)run: node tools/verify-golden.mjs --tier pr+ # What the third-person character DOES in that package: the ramp it climbs,+ # the step it crosses, the wall that stops it. A frame that differs says+ # something moved; only the world's own answer says it was allowed to.+ - name: Drive the third-person character in its package+ run: node tools/verify-third-person.mjs+# The same game packaged twice from one tree, compiled and interpreted, and# the two frames held against each other — the only check that sees what a# compiled system does to a PIXEL.diff --git a/examples/third-person-3d/assets/models/locomotion.esanimator.meta b/examples/third-person-3d/assets/models/locomotion.esanimator.metanew file mode 100644index 000000000..75c22741c--- /dev/null+++ b/examples/third-person-3d/assets/models/locomotion.esanimator.meta@@ -0,0 +1,6 @@+{+ "uuid": "17daaa3a-1cb8-4859-a8bc-5fd44fafade2",+ "version": "2.0",+ "type": "animatorcontroller",+ "importer": {}+}diff --git a/examples/third-person-3d/assets/models/skinned-fade.esmesh.meta b/examples/third-person-3d/assets/models/skinned-fade.esmesh.metaindex 90653d470..631d87be1 100644--- a/examples/third-person-3d/assets/models/skinned-fade.esmesh.meta+++ b/examples/third-person-3d/assets/models/skinned-fade.esmesh.meta@@ -1,5 +1,5 @@{- "uuid": "e4adc279-27d8-4383-8b4d-c3b009b67a31",+ "uuid": "93f77f22-75e9-4e77-bb2e-9aa20fa65158","version": "2.0","type": "mesh","importer": {}diff --git a/examples/third-person-3d/assets/models/skinned-fade.gltf.meta b/examples/third-person-3d/assets/models/skinned-fade.gltf.metaindex 14ba40008..d46b74e10 100644--- a/examples/third-person-3d/assets/models/skinned-fade.gltf.meta+++ b/examples/third-person-3d/assets/models/skinned-fade.gltf.meta@@ -1,8 +1,6 @@{- "uuid": "d63c357f-d90b-47f6-a61e-eb42f460f6eb",+ "uuid": "bb661ce9-961b-4c14-84b7-fd36cdf15dd6","version": "2.0","type": "model",- "importer": {- "scale": 1- }+ "importer": {}}diff --git a/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline.meta b/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline.metaindex 2409e6b80..869c0f699 100644--- a/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline.meta+++ b/examples/third-person-3d/assets/models/skinned-fade_Bent.estimeline.meta@@ -1,5 +1,5 @@{- "uuid": "8fb5d824-25b2-4dbd-804d-524a47ae7fc8",+ "uuid": "e8fb9feb-3a9a-452e-9ab3-9e10ed32e456","version": "2.0","type": "animation","importer": {}diff --git a/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline.meta b/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline.metaindex 108bc0efd..01305d34b 100644--- a/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline.meta+++ b/examples/third-person-3d/assets/models/skinned-fade_Flat.estimeline.meta@@ -1,5 +1,5 @@{- "uuid": "3db4d297-f7f4-426a-8c0f-cfe86a022120",+ "uuid": "0e6a79ad-2c01-4179-9672-c254c620f75c","version": "2.0","type": "animation","importer": {}diff --git a/examples/third-person-3d/assets/scenes/main.esscene b/examples/third-person-3d/assets/scenes/main.essceneindex 478a5b83b..9d88210a9 100644--- a/examples/third-person-3d/assets/scenes/main.esscene+++ b/examples/third-person-3d/assets/scenes/main.esscene@@ -51,14 +51,14 @@"type": "Transform","data": {"position": {- "x": 0,+ "x": -200,"y": -20,- "z": 0+ "z": -300},"scale": {- "x": 16.0,+ "x": 30.0,"y": 0.4,- "z": 16.0+ "z": 24.0}}},@@ -72,9 +72,9 @@"type": "BoxCollider3D","data": {"halfExtents": {- "x": 800.0,+ "x": 1500.0,"y": 20.0,- "z": 800.0+ "z": 1200.0},"friction": 0.6}@@ -109,12 +109,12 @@"position": {"x": 420,"y": 120,- "z": 0+ "z": -520},"scale": {- "x": 0.4,+ "x": 3.0,"y": 2.4,- "z": 8.0+ "z": 0.4}}},@@ -128,9 +128,9 @@"type": "BoxCollider3D","data": {"halfExtents": {- "x": 20.0,+ "x": 150.0,"y": 120.0,- "z": 400.0+ "z": 20.0},"friction": 0.6}@@ -163,13 +163,13 @@"type": "Transform","data": {"position": {- "x": -360,- "y": 25,- "z": 0+ "x": -400,+ "y": 15,+ "z": -520},"scale": {"x": 3.0,- "y": 0.5,+ "y": 0.3,"z": 4.0}}@@ -185,7 +185,7 @@"data": {"halfExtents": {"x": 150.0,- "y": 25.0,+ "y": 15.0,"z": 200.0},"friction": 0.6@@ -230,9 +230,9 @@"z": 0},"scale": {- "x": 4.0,+ "x": 3.0,"y": 0.3,- "z": 7.0+ "z": 8.0}}},@@ -246,9 +246,9 @@"type": "BoxCollider3D","data": {"halfExtents": {- "x": 200.0,+ "x": 150.0,"y": 15.0,- "z": 350.0+ "z": 400.0},"friction": 0.6}@@ -470,6 +470,118 @@}}]+ },+ {+ "id": 11,+ "name": "HighStep",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": -800,+ "y": 45,+ "z": -520+ },+ "scale": {+ "x": 3.0,+ "y": 0.9,+ "z": 4.0+ }+ }+ },+ {+ "type": "RigidBody3D",+ "data": {+ "bodyType": 0+ }+ },+ {+ "type": "BoxCollider3D",+ "data": {+ "halfExtents": {+ "x": 150,+ "y": 45,+ "z": 200+ },+ "friction": 0.6+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "lit": true,+ "opaque": true,+ "cullBackfaces": true,+ "color": {+ "r": 0.45,+ "g": 0.28,+ "b": 0.3,+ "a": 1+ }+ }+ }+ ]+ },+ {+ "id": 12,+ "name": "BackWall",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 420,+ "y": 120,+ "z": 400+ },+ "scale": {+ "x": 4.0,+ "y": 2.4,+ "z": 0.4+ }+ }+ },+ {+ "type": "RigidBody3D",+ "data": {+ "bodyType": 0+ }+ },+ {+ "type": "BoxCollider3D",+ "data": {+ "halfExtents": {+ "x": 200,+ "y": 120,+ "z": 20+ },+ "friction": 0.6+ }+ },+ {+ "type": "MeshRenderer",+ "data": {+ "mesh": "builtin:cube",+ "lit": true,+ "opaque": true,+ "cullBackfaces": true,+ "color": {+ "r": 0.4,+ "g": 0.34,+ "b": 0.44,+ "a": 1+ }+ }+ }+ ]}]}\ No newline at end of filediff --git a/examples/third-person-3d/assets/scenes/main.esscene.meta b/examples/third-person-3d/assets/scenes/main.esscene.metanew file mode 100644index 000000000..9eee263b2--- /dev/null+++ b/examples/third-person-3d/assets/scenes/main.esscene.meta@@ -0,0 +1,6 @@+{+ "uuid": "f1231e52-2b20-449f-8f3d-5505b330b105",+ "version": "2.0",+ "type": "scene",+ "importer": {}+}diff --git a/pipeline/src/assets/cookAssets.ts b/pipeline/src/assets/cookAssets.tsindex b6135e871..712ee99c7 100644--- a/pipeline/src/assets/cookAssets.ts+++ b/pipeline/src/assets/cookAssets.ts@@ -219,6 +219,44 @@ function rewriteFontRefs());}+/**+ * An animator controller names the clips its motions play as sibling files, which+ * staging moves out from under it. The controller then loads and every state+ * plays nothing, which reads as a broken graph rather than a missing asset.+ */+function rewriteAnimatorRefs(+ bytes: Uint8Array,+ docPath: string,+ byPath: Map<string, AssetEntry>,+): Uint8Array {+ const json = JSON.parse(Buffer.from(bytes).toString('utf8')) as {+ states?: { motion?: unknown; stateMachine?: { states?: unknown[] } }[];+ };+ // Only a motion whose clip is an ASSET: a sprite clip and a spine animation+ // are names their own runtime holds, and rewriting those would break them.+ const ASSET_KINDS = new Set(['timeline']);+ const walk = (motion: unknown): void => {+ if (!motion || typeof motion !== 'object') return;+ const m = motion as { kind?: string; clip?: string; thresholds?: { motion?: unknown }[] };+ if (m.kind === 'blend1d') {+ for (const stop of m.thresholds ?? []) walk(stop.motion);+ return;+ }+ if (m.kind && ASSET_KINDS.has(m.kind) && typeof m.clip === 'string') {+ m.clip = logicalRef(m.clip, docPath, byPath) as string;+ }+ };+ const states = (list: unknown[] | undefined): void => {+ for (const state of list ?? []) {+ const st = state as { motion?: unknown; stateMachine?: { states?: unknown[] } };+ walk(st.motion);+ states(st.stateMachine?.states);+ }+ };+ states(json.states);+ return new TextEncoder().encode(JSON.stringify(json, null, 2) + '\n');+}+/*** A baked environment names its reflection atlas as a SIBLING file, which staging* moves out from under it — the runtime then asks for `assets/sky_env.png` and gets@@ -636,6 +674,14 @@ export async function cookAssets(warnings.push(`${entry.path}: environment ref rewrite failed — ${err instanceof Error ? err.message : String(err)}`);}}+ // Animator controllers: the clips their motions play → logical project paths.+ if (ext.toLowerCase() === '.esanimator') {+ try {+ data = rewriteAnimatorRefs(data, entry.path, byPath);+ } catch (err) {+ warnings.push(`${entry.path}: animator ref rewrite failed — ${err instanceof Error ? err.message : String(err)}`);+ }+ }// Tilemaps: relative tileset image/source refs → logical project paths, so the// @uuid-loaded map resolves them to the embedded assets (see rewriteTilemapRefs).if (ext.toLowerCase() === '.tmj' || ext.toLowerCase() === '.tmx') {diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.tsindex 19d6c7cac..b53793e27 100644--- a/pipeline/src/runtime/gameHost.ts+++ b/pipeline/src/runtime/gameHost.ts@@ -16,7 +16,8 @@ import {indexPackagedManifest, createPackagedAssetSource, applyAssetRefResolvers, initRuntime,HttpBackend, fetchDecodePixels, registerPackagedSideModules,packagedAppOptions, packagedRuntimeInit, Transform, SceneManager, Nav, UINode,- acquireWebGPUDevice,+ acquireWebGPUDevice, ThirdPersonCamera, CharacterController3D, AnimatorController,+ Animator, TPC_SPEED, TPC_GROUNDED,} from 'esengine';import type { SceneData, AddressableManifest, PackagedGameConfig, RenderSurfaceSource } from 'esengine';import type { ESEngineModule } from 'esengine/wasm';@@ -143,9 +144,9 @@ async function boot(): Promise<void> {probe(names: string[] = []): {scene: string | null;transitioning: boolean;- at: Record<string, { x: number; y: number; w?: number; h?: number }>;+ at: Record<string, { x: number; y: number; z?: number; w?: number; h?: number }>;} {- const at: Record<string, { x: number; y: number; w?: number; h?: number }> = {};+ const at: Record<string, { x: number; y: number; z?: number; w?: number; h?: number }> = {};for (const name of names) {const entity = app.world.findEntityByName(name);if (entity === null || !app.world.has(entity, Transform)) continue;@@ -153,7 +154,9 @@ async function boot(): Promise<void> {// parented (every UI node) the local offset answers a different question.const t = app.world.get(entity, Transform);const p = t.worldPosition ?? t.position;- at[name] = { x: p.x, y: p.y };+ // z as well: a 3D driver asking where something is cannot be answered+ // by the plane, and a character walking a ramp moves in all three.+ at[name] = { x: p.x, y: p.y, z: p.z ?? 0 };// A node's own size, for a claim about a value the game COMPUTED rather// than about where it ended up — a spectrum bar barely moves while its// height carries the whole answer.@@ -169,6 +172,68 @@ async function boot(): Promise<void> {// "the thing I was walking to is gone", which is a lie with a cost.return { scene: scenes?.getActive() ?? null, transitioning: scenes?.isTransitioning() ?? false, at };},+ /**+ * What a third-person character IS: where it stands, what the physics step+ * gave it, what its animator was told. Read-only, off the same components+ * the game runs on — pixels cannot say whether a ramp was climbed, and a+ * unit test answers about the request rather than the result.+ */+ gameplay(playerName: string, cameraName?: string): {+ found: boolean;+ position: { x: number; y: number; z: number } | null;+ realVelocity: { x: number; y: number; z: number } | null;+ askedVelocity: { x: number; y: number; z: number } | null;+ grounded: boolean;+ animator: { speed: number; grounded: boolean; state: string } | null;+ camera: { x: number; y: number; z: number } | null;+ cameraDistance: number | null;+ } {+ const blank = {+ found: false, position: null, realVelocity: null, askedVelocity: null,+ grounded: false, animator: null, camera: null, cameraDistance: null,+ };+ const player = app.world.findEntityByName(playerName);+ if (player === null || !app.world.has(player, Transform)) return blank;++ const t = app.world.get(player, Transform);+ const p = t.worldPosition ?? t.position;+ const position = { x: p.x, y: p.y, z: p.z ?? 0 };++ let realVelocity = null;+ let askedVelocity = null;+ let grounded = false;+ if (app.world.has(player, CharacterController3D)) {+ const c = app.world.get(player, CharacterController3D);+ realVelocity = { x: c.realVelocity.x, y: c.realVelocity.y, z: c.realVelocity.z };+ askedVelocity = { x: c.velocity.x, y: c.velocity.y, z: c.velocity.z };+ grounded = c.isOnFloor;+ }++ let animator = null;+ if (app.hasResource(AnimatorController) && app.world.has(player, Animator)) {+ const ctrl = app.getResource(AnimatorController);+ animator = {+ speed: ctrl.getFloat(player, TPC_SPEED),+ grounded: ctrl.getBool(player, TPC_GROUNDED),+ state: app.world.get(player, Animator).currentState,+ };+ }++ let camera = null;+ let cameraDistance = null;+ const eye = cameraName ? app.world.findEntityByName(cameraName)+ : (app.world.getEntitiesWithComponents([ThirdPersonCamera])[0] ?? null);+ if (eye !== null && eye !== undefined && app.world.has(eye, Transform)) {+ const ct = app.world.get(eye, Transform);+ const cp = ct.worldPosition ?? ct.position;+ camera = { x: cp.x, y: cp.y, z: cp.z ?? 0 };+ cameraDistance = Math.hypot(cp.x - position.x, cp.y - position.y,+ (cp.z ?? 0) - position.z);+ }++ return { found: true, position, realVelocity, askedVelocity, grounded,+ animator, camera, cameraDistance };+ },/*** Advance the world by `frames` steps of exactly `dt`, wall clock ignored.*diff --git a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cppindex b6d68a62d..a16222244 100644--- a/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp+++ b/src/esengine/bindings/modules/physics3d/Physics3DModuleEntry.cpp@@ -532,6 +532,10 @@ void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,vertical += g().system->GetGravity().GetY() * dt;}character.SetLinearVelocity(Vec3(vx, vertical, vz));+ // Where it stood before the sweep. GetLinearVelocity afterwards returns what+ // we PUT there — ExtendedUpdate moves the character without rewriting it — so+ // the only honest answer is the ground it covered over the time it had.+ const RVec3 startedAt = character.GetPosition();CharacterVirtual::ExtendedUpdateSettings settings;settings.mWalkStairsStepUp = Vec3(0, stepUp, 0);settings.mStickToFloorStepDown = Vec3(0, -stepDown, 0);@@ -544,7 +548,12 @@ void physics3d_moveCharacter(uint32_t characterId, float vx, float vy, float vz,const RVec3 position = character.GetPosition();const Vec3 normal = character.GetGroundNormal();- const Vec3 velocity = character.GetLinearVelocity();+ // The velocity it REACHED, not the one it was given: a character shoving a+ // wall keeps the velocity it asked for and covers no ground, and gameplay+ // reading the request back would never know the difference.+ const Vec3 velocity = dt > 0.0f+ ? Vec3((position - startedAt) / dt)+ : Vec3::sZero();g().queryBuffer = {static_cast<float>(position.GetX()), static_cast<float>(position.GetY()),static_cast<float>(position.GetZ()),diff --git a/tools/goldenProjects.mjs b/tools/goldenProjects.mjsindex 8c89d8b62..8a7e5e3cf 100644--- a/tools/goldenProjects.mjs+++ b/tools/goldenProjects.mjs@@ -48,7 +48,7 @@ export const DEFAULT_RESPONDS = 0.15;* {@link KNOWN_GAPS}.*/export const CAPABILITIES = [- 'physics', 'input', 'animation',+ 'physics', 'input', 'animation', 'third-person','ecs', 'particles', 'audio','ui-layout', 'text', 'localization','spine', 'material', 'asset-lifecycle',@@ -79,6 +79,7 @@ export const EVIDENCE = {input: /\b(Input|defineInputMap|isKeyDown|InputState)\b/,animation: /\b(SpriteAnimator|Animator|spriteAnim|Flipbook|TimelinePlayer|AnimClip)\b/,ecs: /\b(defineComponent|defineSystem)\b/,+ 'third-person': /\b(ThirdPersonController|ThirdPersonCamera)\b/,particles: /\bParticleEmitter\b/,// Components OR the resource: audio-demo takes Res(Audio) and never inserts a// component, and a pattern that only knew the components read it as unused.@@ -228,6 +229,16 @@ export const GOLDEN = [// the 3D world draws an empty room rather than a still one.interact: { keys: ['KeyW'], frames: 40 },},+ {+ id: 'third-person-3d',+ certifies: ['third-person'],+ targets: ['web'],+ tier: 'pr',+ // The character walks on the key it declares. What it DOES on the way is+ // verify-third-person's, over this same package: a frame that differs says+ // something moved, not that the world allowed it.+ interact: { keys: ['KeyW'], frames: 60 },+ },{id: 'ui-controls',certifies: ['ui-layout', 'text'],diff --git a/tools/launchers/inputScript.mjs b/tools/launchers/inputScript.mjsindex d48b0e5b1..8f981e249 100644--- a/tools/launchers/inputScript.mjs+++ b/tools/launchers/inputScript.mjs@@ -29,6 +29,10 @@* so standing one up there drives its real polling path rather than poking its* state. Each entry sets axes/buttons over a frame range.*+ * `drags` are real mouse drags — press, move over a frame range, release. What a+ * mouse-look camera reads is the DELTA between two frames, which a single+ * pointer position cannot say.+ ** `touches` are real TouchEvents — what a phone sends and what the web platform* binds; a mouse pointer proves nothing about playing with a thumb. Each presses* at (x, y) and optionally drags to (toX, toY) over its frame range, in@@ -68,6 +72,14 @@ export function inputScript(spec) {key: String(h.key), from: Number(h.from) || 0, to: Number(h.to ?? frames),})),);+ const drags = JSON.stringify(+ (spec.drags ?? []).map((d) => ({+ from: Number(d.from) || 0, to: Number(d.to ?? frames),+ x: Number(d.x) || 0, y: Number(d.y) || 0,+ toX: d.toX === undefined ? Number(d.x) || 0 : Number(d.toX),+ toY: d.toY === undefined ? Number(d.y) || 0 : Number(d.toY),+ })),+ );return `(async () => {const raf = () => new Promise((r) => requestAnimationFrame(r));@@ -137,6 +149,7 @@ export function inputScript(spec) {const taps = ${taps};const holds = ${holds};const touches = ${touches};+ const drags = ${drags};const hiddenSpec = ${hidden};const setHidden = (h) => {Object.defineProperty(document, 'hidden', { value: h, configurable: true });@@ -198,6 +211,13 @@ export function inputScript(spec) {fireTouch('touchend', t.id, at ? at.x : t.toX, at ? at.y : t.toY, live);}}+ for (const d of drags) {+ if (i === d.from) firePointer('down', d.x, d.y);+ else if (i > d.from && i < d.to) {+ const k = (i - d.from) / Math.max(1, d.to - d.from);+ firePointer('move', d.x + (d.toX - d.x) * k, d.y + (d.toY - d.y) * k);+ } else if (i === d.to) firePointer('up', d.toX, d.toY);+ }for (const t of taps) {if (t.at !== i) continue;fireKey('keydown', t.key);@@ -212,7 +232,7 @@ export function inputScript(spec) {for (const k of keys) fireKey('keyup', k);await raf();return keys.length + taps.length + holds.length + touches.length + padSpec.length- + hiddenSpec.length + (pointer ? 1 : 0);+ + hiddenSpec.length + drags.length + (pointer ? 1 : 0);})()`;}diff --git a/tools/launchers/launch-export.mjs b/tools/launchers/launch-export.mjsindex b67443982..9f575e937 100644--- a/tools/launchers/launch-export.mjs+++ b/tools/launchers/launch-export.mjs@@ -28,6 +28,9 @@* CSS variables the web platform reads* --probe a,b,c after settling, print where those named entities are* (opens the package with ?headless)+ * --gameplay p[,c] after settling, print what the third-person character+ * IS: where it stands, what the physics step gave it, and+ * what its animator was told* --log <regex> also print console lines matching this (the engine's own* warnings say why a subsystem sat out; only `[engine]`* lines are forwarded otherwise, which means diagnosing@@ -141,8 +144,9 @@ async function main() {return;}const PROBE = flag('probe', '');+const GAMEPLAY = flag('gameplay', '');const server = await serve(DIR, flag('safe-area', ''));- const base = `http://127.0.0.1:${server.address().port}/${PROBE ? '?headless' : ''}`;+ const base = `http://127.0.0.1:${server.address().port}/${PROBE || GAMEPLAY ? '?headless' : ''}`;const win = new BrowserWindow({// Content size, not window size: with the frame counted in, the surface came@@ -201,6 +205,15 @@ async function main() {console.log(` probe: ${JSON.stringify(seen)}`);}+ if (GAMEPLAY) {+ const [player, camera] = GAMEPLAY.split(',').map((n) => n.trim());+ const seen = await win.webContents.executeJavaScript(+ `window.__estellaCooked?.gameplay(${JSON.stringify(player)}, `+ + `${JSON.stringify(camera ?? null)}) ?? null`,+ ).catch((e) => ({ error: String(e) }));+ console.log(` gameplay: ${JSON.stringify(seen)}`);+ }+const image = await win.webContents.capturePage();if (OUT) await writeFile(OUT, image.toPNG());stop();diff --git a/tools/verify-third-person.mjs b/tools/verify-third-person.mjsnew file mode 100644index 000000000..2d3871e5a--- /dev/null+++ b/tools/verify-third-person.mjs@@ -0,0 +1,191 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file verify-third-person.mjs — what the character DOES, in a packaged game.+ *+ * The gameplay unit criteria hold the ownership: input becomes a request, the+ * character controller answers it, the answer reaches the animator. What they+ * cannot say is whether the answer is right — whether a ramp is climbed, a step+ * is crossed, a wall stops it — because that is Jolt's answer and not the+ * controller's. So this drives the real package: real Physics3D, real+ * CharacterController3D, real Animator over TimelineMotion, real skin.+ *+ * Input goes in as key and mouse events on the page, and the only thing read+ * back is `__estellaCooked.gameplay` — an observation seam, not a second way to+ * play. Lanes run in -Z, so a run strafes to one and then walks it.+ */+import { spawnSync } from 'node:child_process';+import { rmSync, mkdirSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { runElectron } from './lib/electronRun.mjs';++const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');+const WORK = path.join(ROOT, '.golden', 'third-person');+const PROJECT = path.join(ROOT, 'examples', 'third-person-3d');+const LAUNCHER = path.join(ROOT, 'tools', 'launchers', 'launch-export.mjs');++const W = 960, H = 640;+/** Frames of strafe per lane: the character covers moveSpeed/60 a frame. */+const TO_LANE = { wall: 75, step: 75, highStep: 150 };++function packageGame() {+ rmSync(WORK, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 });+ mkdirSync(WORK, { recursive: true });+ const out = path.join(WORK, 'web');+ const r = spawnSync(process.execPath, [+ path.join(ROOT, 'pipeline', 'bin', 'estella.mjs'), 'export', PROJECT,+ '--platform', 'web', '--out', out,+ ], { encoding: 'utf8', cwd: ROOT });+ if (r.status !== 0) {+ console.error('✗ third-person: the package did not build');+ for (const l of `${r.stderr ?? ''}${r.stdout ?? ''}`.split('\n').slice(-8)) {+ if (l.trim()) console.error(` ${l}`);+ }+ process.exit(1);+ }+ return out;+}++/** Drive the package with one gesture and read what the character became. */+function run(dir, input) {+ const r = runElectron([+ LAUNCHER, '--dir', dir, '--w', String(W), '--h', String(H),+ '--settle', '30', '--timeout', '60000',+ '--input', JSON.stringify(input), '--gameplay', 'Player,Camera',+ '--out', path.join(WORK, 'frame.png'),+ ], { encoding: 'utf8', cwd: ROOT });+ const line = (r.stdout || '').split('\n').find((l) => l.includes('gameplay:'));+ if (!line) {+ return { error: `no reading — ${(r.stdout || r.stderr || '').trim().slice(-200)}` };+ }+ try {+ return JSON.parse(line.slice(line.indexOf('{')));+ } catch (e) {+ return { error: `unreadable reading: ${e.message}` };+ }+}++/**+ * Walk a lane: strafe to it over `strafe` frames, then hold forward to the end.+ * Forward is never RELEASED - a wall claim is about the stick still being full,+ * and a reading taken after the key came up says nothing about it.+ */+const walkLane = (strafe, key, forward = 150) => ({+ holds: [+ ...(strafe ? [{ key, from: 0, to: strafe }] : []),+ { key: 'KeyW', from: strafe, to: strafe + forward + 1 },+ ],+ frames: strafe + forward,+});++/** Strafe to a lane and stand there, so the eye is read where the lane put it. */+const standIn = (strafe, key) => ({+ holds: [{ key, from: 0, to: strafe }],+ frames: strafe + 40,+});++const results = [];+function check(what, ok, detail) {+ results.push({ what, ok, detail });+ console.log(`${ok ? '✓' : '✗'} ${what}${detail ? ` — ${detail}` : ''}`);+}++const dir = packageGame();+const START = { y: 60, z: 120 };++// 1. Flat locomotion: still, moving, and still again.+{+ const idle = run(dir, { frames: 40 });+ check('starts idle on the floor',+ idle.animator?.state === 'Idle' && idle.grounded === true+ && (idle.animator?.speed ?? -1) === 0,+ `state ${idle.animator?.state}, speed ${idle.animator?.speed}, grounded ${idle.grounded}`);++ const moving = run(dir, { keys: ['KeyW'], frames: 90 });+ const travelled = START.z - (moving.position?.z ?? START.z);+ check('walking moves the character and the animator follows',+ travelled > 200 && (moving.animator?.speed ?? 0) > 100+ && moving.animator?.state === 'Locomotion',+ `travelled ${travelled.toFixed(0)}, speed ${moving.animator?.speed?.toFixed(0)}, state ${moving.animator?.state}`);++ const released = run(dir, { holds: [{ key: 'KeyW', from: 0, to: 60 }], frames: 160 });+ check('releasing returns it to idle',+ Math.abs(released.realVelocity?.z ?? 99) < 5 && (released.animator?.speed ?? 99) === 0+ && released.animator?.state === 'Idle',+ `realVz ${released.realVelocity?.z?.toFixed(1)}, speed ${released.animator?.speed}, state ${released.animator?.state}`);+}++// 2. A wall: the stick is full and the world gives nothing.+{+ const at = run(dir, walkLane(TO_LANE.wall, 'KeyD'));+ const asked = Math.hypot(at.askedVelocity?.x ?? 0, at.askedVelocity?.z ?? 0);+ const real = Math.hypot(at.realVelocity?.x ?? 0, at.realVelocity?.z ?? 0);+ check('a wall stops it while the stick is still full',+ asked > 100 && real < 20 && (at.position?.z ?? -999) > -520,+ `asked ${asked.toFixed(0)}, real ${real.toFixed(0)}, z ${at.position?.z?.toFixed(0)}`);+ check('and the animator says standing still',+ (at.animator?.speed ?? 99) === 0,+ `speed ${at.animator?.speed}`);+}++// 3. A walkable ramp: it goes UP.+{+ const at = run(dir, { keys: ['KeyW'], frames: 150 });+ const climbed = (at.position?.y ?? 0) - START.y;+ check('a walkable ramp is climbed',+ climbed > 40 && at.grounded === true,+ `climbed ${climbed.toFixed(0)}, grounded ${at.grounded}`);+}++// 4/5. A step it can climb, and one it cannot. The pair is the claim: reaching+// the far side of a low step is also what walking on flat ground looks like.+{+ const low = run(dir, walkLane(TO_LANE.step, 'KeyA'));+ const raised = (low.position?.y ?? 0) - START.y;+ check('a step inside stepHeight is crossed',+ raised > 20 && low.grounded === true,+ `raised ${raised.toFixed(0)}, z ${low.position?.z?.toFixed(0)}`);++ const high = run(dir, walkLane(TO_LANE.highStep, 'KeyA'));+ const lifted = (high.position?.y ?? 0) - START.y;+ check('a step above it is not',+ lifted < 20,+ `lifted ${lifted.toFixed(0)}, z ${high.position?.z?.toFixed(0)}`);+}++// 6. Camera-relative movement, turned by a real mouse drag.+{+ const straight = run(dir, { keys: ['KeyW'], frames: 90 });+ // sensitivity 0.2 deg/px over a 960-wide surface: 450 px is a quarter turn.+ const turned = run(dir, {+ drags: [{ from: 0, to: 20, x: 0.7, y: 0.5, toX: 0.7 - 450 / W, toY: 0.5 }],+ holds: [{ key: 'KeyW', from: 25, to: 115 }],+ frames: 125,+ });+ const straightDz = Math.abs(START.z - (straight.position?.z ?? START.z));+ const straightDx = Math.abs(straight.position?.x ?? 0);+ const turnedDx = Math.abs(turned.position?.x ?? 0);+ const turnedDz = Math.abs(START.z - (turned.position?.z ?? START.z));+ check('forward is along -Z with the camera behind',+ straightDz > 200 && straightDx < 40, `dz ${straightDz.toFixed(0)}, dx ${straightDx.toFixed(0)}`);+ check('turning the camera turns what forward means',+ turnedDx > 150 && turnedDx > turnedDz,+ `dx ${turnedDx.toFixed(0)}, dz ${turnedDz.toFixed(0)}`);+}++// 7. Camera obstruction, against the same wall the character cannot pass.+{+ const open = run(dir, { frames: 40 });+ const against = run(dir, standIn(TO_LANE.wall, 'KeyD'));+ check('the eye sits back when nothing is in the way',+ (open.cameraDistance ?? 0) > 400, `distance ${open.cameraDistance?.toFixed(0)}`);+ check('and pulls in when the wall is behind the character',+ (against.cameraDistance ?? 999) < (open.cameraDistance ?? 0) - 40,+ `distance ${against.cameraDistance?.toFixed(0)} vs ${open.cameraDistance?.toFixed(0)}`);+}++const failed = results.filter((r) => !r.ok);+console.log(`\nverify-third-person: ${results.length - failed.length}/${results.length}`+ + ' behaviour(s) hold up in the packaged game.');+process.exit(failed.length ? 1 : 0);