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(examples): cover the four zero-example engine pillars
esengine02a8ec433c82
diff --git a/examples/README.md b/examples/README.mdindex 813766746..8d4e7a7a5 100644--- a/examples/README.md+++ b/examples/README.md@@ -15,12 +15,15 @@ for your own game.| **hello-world** | Basics | A minimal project — rotating, color-pulsing sprites. || **ecs-basics** | ECS | Spawn, move, bounce and expire entities: the core ECS loop. || **event-system** | ECS | Decoupled gameplay with typed events — collect, score, react. |+| **scene-flow** | Basics | Runtime scene flow — menu → level 1 → level 2 through `SceneManager` fade transitions, over a persistent shell scene. |+| **save-load** | Basics | Versioned persistence — `SaveManager` save/load with a live v1→v2 migration, plus raw `Storage` preferences. || **sprite-rendering** | Rendering | Draw sprites with rotation, tint and flipping. || **sprite-animation** | Animation | Frame animation via `.esanim` clips with an idle/walk switcher. || **spine-demo** | Animation | A Spine skeleton cycling idle/walk/run/jump/shoot (1-5 to switch). || **tween-animation** | Animation | Ease positions, scales and colors over time. || **cutscene** | Animation | A code-free cutscene: an FSM state plays a timeline via the built-in `timeline.play` / `timeline.finished` names, then hands over to gameplay (R to replay). || **input-demo** | Input | Keyboard, mouse and pointer input with a motion trail. |+| **input-actions** | Input | Named, rebindable actions (`defineInputMap`) across keyboard + gamepad, plus swipe/pinch gestures with a mouse bridge. || **audio-demo** | Audio | One-shot SFX and a beat visualizer driven by playback. || **collision-layers** | Physics | Layer-based collision filtering between groups of bodies. || **physics-playground** | Physics | Drop balls and crates into a rigid-body sandbox. |@@ -35,7 +38,10 @@ for your own game.| **ui-interaction** | UI | Dragging, focus and pointer interaction. || **ui-layout** | UI | Flexbox-style responsive UI layout. || **ui-list** | UI | A virtualized list and grid — `createListView`, live data, `scrollToIndex`. |+| **ui-controller** | UI | Shared UI controllers + declarative per-page gears: a tab bar, an `$interaction` button, and a tweened popup. |+| **chat** | UI | A chat log — virtualized ListView + TextInput composer with two-way binding. || **enemy-ai** | AI | A state machine drives enemies to patrol, sense the player, and chase via A* navigation. |+| **camera-follow** | Gameplay | The camera director — `FollowTarget` damping + dead zone, `shakeCamera` impacts, `setViewTarget` blends to an overview camera. || **multiplayer-arena** | Networking | Server-authoritative multiplayer with client prediction: each player steers a replicated pawn, own-pawn input applies instantly ('2 Players' in the Play dropdown runs listen server + client). || **platformer** | Game | A tiny platformer — run, jump and collect coins. || **video-puzzle** | Game | A tile-swap puzzle whose tiles are live regions of ONE playing video — texture-handle sharing + per-piece `uvOffset`/`uvScale`. |diff --git a/examples/camera-follow/.gitignore b/examples/camera-follow/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/camera-follow/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/camera-follow/README.md b/examples/camera-follow/README.mdnew file mode 100644index 000000000..41f263572--- /dev/null+++ b/examples/camera-follow/README.md@@ -0,0 +1,117 @@+# Camera Follow++A tour of the **camera director** — the runtime that decides what the camera+shows and how it gets there: damped target following, transient screen shake,+and smooth blends between cameras.++Move the player square with **WASD** / arrow keys across a large scrolling+world. The camera trails it with a dead zone and damping. Then:++| Key | Action |+|---|---|+| **WASD / arrows** | Move the player. |+| **Space** | `shakeCamera` — a decaying impact shake. |+| **1** | `setViewTarget` back to the **follow camera** (1.2 s EaseInOut blend). |+| **2** | `setViewTarget` to the fixed **overview camera** framing the whole world. |++## What it shows++- **`FollowTarget`** — add this component to a camera and point it at an entity;+ the built-in follow system damps the camera's Transform toward the target every+ frame (play mode only). The damping is frame-rate independent, and the dead+ zone lets the target roam a small radius without dragging the view.+- **`shakeCamera(app, opts)`** — pushes a decaying, noise-driven perturbation+ onto the **rendered** view only. The camera's Transform is never touched, so+ the view always recovers and the scene stays clean. Shakes stack.+- **`setViewTarget(app, entity, opts)`** — hands the view to another camera+ entity, optionally **blending** position, zoom, and rotation over `time`+ seconds with a `BlendCurve` easing instead of cutting. The target camera does+ not need `isActive` — the director overrides the active-camera pick.+- **Follow + blend compose**: while blended to the overview, the follow camera+ keeps tracking the player, so pressing **1** blends back to wherever the+ player is *now*.++All three run through the engine's built-in `CameraPlugin` — no camera systems+in project code. The project only spawns the world, moves the player, and issues+director requests from input.++## API reference++### `FollowTarget` component++```typescript+cmds.entity(cameraEntity).insert(FollowTarget, {+ target: playerEntity,+ deadzone: 48,+ damping: 0.25,+});+```++| Property | Type | Default | Description |+|---|---|---|---|+| `target` | Entity | `-1` | Entity to follow (`-1` = none). |+| `offsetX` | number | `0` | World-space X offset added to the target position. |+| `offsetY` | number | `0` | World-space Y offset added to the target position. |+| `deadzone` | number | `0` | Radius (world units) the target may roam before the camera moves. |+| `damping` | number | `0.25` | Smoothing time-constant in seconds (larger = smoother/slower; `0` = snap). |++### `shakeCamera(app, opts?)`++```typescript+shakeCamera(app, { amplitude: 16, rotation: 0.02, frequency: 24, duration: 0.5 });+```++| Option | Default | Description |+|---|---|---|+| `amplitude` | `12` | Peak positional offset (world units). |+| `rotation` | `0` | Peak rotational shake (radians). |+| `frequency` | `22` | Oscillations per second. |+| `duration` | `0.4` | Seconds to decay to zero. |++### `setViewTarget(app, entity, opts?)`++```typescript+setViewTarget(app, overviewCamera, { time: 1.2, curve: BlendCurve.EaseInOut });+```++| Option | Default | Description |+|---|---|---|+| `time` | `0` | Blend duration in seconds; `<= 0` (or no prior view) is an instant cut. |+| `curve` | `BlendCurve.EaseInOut` | Easing: `Linear`, `EaseIn`, `EaseOut`, `EaseInOut`. |++Position, zoom (`orthoSize`), and rotation interpolate (rotation takes the short+way around); discrete fields (projection, viewport) snap at the blend midpoint.++### Calling the director from a system++`setViewTarget`/`shakeCamera` accept either the App (host code) or the+`CameraDirector` resource state itself — inside a system, pass what+`Res(CameraDirector)` gives you, as `src/systems/director.ts` does. In a+self-hosted runtime where you created the App yourself, pass the App directly.++## Files++- `src/systems/setup.ts` — spawns the world (ground-dot grid, landmarks, border),+ the player, the inactive overview camera, and inserts `FollowTarget` on the+ scene's active camera.+- `src/systems/move.ts` — WASD/arrow movement, clamped to the world bounds.+- `src/systems/director.ts` — Space/1/2 → `shakeCamera` / `setViewTarget`.+- `src/components.ts` — the project's `Player` component and `OverviewCam` tag.+- `src/config.ts` — world size, follow/shake/blend tuning, landmark layout.+- `assets/scenes/main.esscene` — the active gameplay camera + UI canvas; the+ rest of the world is spawned from code.++## 中文摘要++本示例演示**相机导演**的三个核心 API:++- **`FollowTarget` 组件**——挂在相机上并指向玩家实体,内置系统每帧以+ 帧率无关的阻尼把相机拉向目标;`deadzone` 内的小幅移动不会带动相机。+- **`shakeCamera`**——按 **空格** 触发衰减震屏,只作用于渲染视图、+ 不改相机 Transform,因此画面必然复原。+- **`setViewTarget`**——按 **1 / 2** 在跟随相机与固定全景相机之间以+ 1.2 秒 EaseInOut 曲线平滑混合(位置、缩放、旋转插值)。++用 **WASD / 方向键** 移动白色方块即可观察相机跟随;各选项的默认值见上方+英文表格。三个能力全部由引擎内置 `CameraPlugin` 驱动,项目代码只负责+生成世界、移动玩家、响应按键。diff --git a/examples/camera-follow/assets/scenes/main.esscene b/examples/camera-follow/assets/scenes/main.esscenenew file mode 100644index 000000000..222633051--- /dev/null+++ b/examples/camera-follow/assets/scenes/main.esscene@@ -0,0 +1,57 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 10+ }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 360,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "UICanvas",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Canvas",+ "data": {+ "designResolution": {+ "x": 1280,+ "y": 720+ },+ "scaleMode": 2+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/camera-follow/assets/scenes/main.esscene.meta b/examples/camera-follow/assets/scenes/main.esscene.metanew file mode 100644index 000000000..1b3d9e3ab--- /dev/null+++ b/examples/camera-follow/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "703485f1-fb5b-40c6-be6d-949a486918af",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/camera-follow/project.esproject b/examples/camera-follow/project.esprojectnew file mode 100644index 000000000..a140ec2ad--- /dev/null+++ b/examples/camera-follow/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Camera Follow",+ "description": "The camera director: FollowTarget damping + dead zone, shakeCamera impacts, and setViewTarget blending to an overview camera.",+ "tag": "Gameplay",+ "version": "1.0.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 1280,+ "height": 720+ },+ "spineVersion": "none"+}diff --git a/examples/camera-follow/src/components.ts b/examples/camera-follow/src/components.tsnew file mode 100644index 000000000..1dedca12e--- /dev/null+++ b/examples/camera-follow/src/components.ts@@ -0,0 +1,14 @@+import { defineComponent, defineTag } from 'esengine';++// The project's declaration entry (src/components.ts): user component/tag+// definitions only — no systems. The editor extracts schemas from here so the+// inspector knows their fields without running project code. (Camera and+// FollowTarget are engine built-ins, so they aren't declared here.)++/** Marks the WASD-controlled player square and carries its move speed. */+export const Player = defineComponent('Player', {+ speed: 420,+});++/** Marks the fixed wide-angle camera that key 2 blends the view to. */+export const OverviewCam = defineTag('OverviewCam');diff --git a/examples/camera-follow/src/config.ts b/examples/camera-follow/src/config.tsnew file mode 100644index 000000000..de87532cd--- /dev/null+++ b/examples/camera-follow/src/config.ts@@ -0,0 +1,44 @@+/** Half-extents of the roamable world (world units). */+export const WORLD_HALF_W = 1600;+export const WORLD_HALF_H = 1000;++/** Spacing of the dim ground-dot grid that makes camera motion visible. */+export const GRID_STEP = 200;++export const PLAYER_SIZE = 48;++/** FollowTarget tuning for the gameplay camera (see the README table). */+export const FOLLOW = {+ deadzone: 48,+ damping: 0.25,+};++/** The overview camera's ortho half-height — wide enough to frame the world. */+export const OVERVIEW_ORTHO = 1050;++/** setViewTarget blend duration (seconds) for the 1/2 camera hand-offs. */+export const BLEND_TIME = 1.2;++/** shakeCamera options for the Space impact (see the README table). */+export const SHAKE = {+ amplitude: 16,+ rotation: 0.02,+ frequency: 24,+ duration: 0.5,+};++/** Landmark blocks scattered across the world so scrolling reads at a glance. */+export const LANDMARKS: Array<{+ x: number; y: number; w: number; h: number;+ color: { r: number; g: number; b: number; a: number };+}> = [+ { x: -1200, y: 700, w: 180, h: 180, color: { r: 0.95, g: 0.45, b: 0.35, a: 1 } },+ { x: 1250, y: 640, w: 140, h: 260, color: { r: 0.4, g: 0.75, b: 1, a: 1 } },+ { x: -600, y: -750, w: 240, h: 120, color: { r: 0.55, g: 0.9, b: 0.45, a: 1 } },+ { x: 900, y: -680, w: 160, h: 160, color: { r: 0.95, g: 0.8, b: 0.35, a: 1 } },+ { x: -1350, y: -200, w: 120, h: 300, color: { r: 0.8, g: 0.55, b: 1, a: 1 } },+ { x: 1400, y: -100, w: 120, h: 220, color: { r: 0.4, g: 0.95, b: 0.85, a: 1 } },+ { x: 300, y: 850, w: 200, h: 100, color: { r: 1, g: 0.6, b: 0.8, a: 1 } },+ { x: -300, y: 250, w: 100, h: 100, color: { r: 1, g: 0.75, b: 0.45, a: 1 } },+ { x: 550, y: -250, w: 130, h: 130, color: { r: 0.6, g: 0.7, b: 1, a: 1 } },+];diff --git a/examples/camera-follow/src/main.ts b/examples/camera-follow/src/main.tsnew file mode 100644index 000000000..50d79fee3--- /dev/null+++ b/examples/camera-follow/src/main.ts@@ -0,0 +1,22 @@+// Camera Follow — a tour of the camera director:+//+// • FollowTarget — the scene camera damps toward the WASD player with a+// dead zone, so small moves don't drag the view (Cinemachine-style Body).+// • shakeCamera — Space triggers a decaying render-only shake that never+// dirties the camera's Transform.+// • setViewTarget — keys 1/2 blend the view between the follow camera and a+// fixed wide-angle overview camera over 1.2 s with an EaseInOut curve.+//+// The follow, shake, and blend systems are all engine built-ins (CameraPlugin);+// project code only spawns the world, moves the player, and issues director+// requests from input.+import { addStartupSystem, addSystemToSchedule, Schedule } from 'esengine';++import './components';+import { setupSystem } from './systems/setup';+import { playerMoveSystem } from './systems/move';+import { cameraDirectorSystem } from './systems/director';++addStartupSystem(setupSystem);+addSystemToSchedule(Schedule.Update, playerMoveSystem);+addSystemToSchedule(Schedule.Update, cameraDirectorSystem);diff --git a/examples/camera-follow/src/systems/director.ts b/examples/camera-follow/src/systems/director.tsnew file mode 100644index 000000000..72ecdc889--- /dev/null+++ b/examples/camera-follow/src/systems/director.ts@@ -0,0 +1,30 @@+import {+ defineSystem, Query, Res, Input, Camera,+ CameraDirector, FollowTarget, setViewTarget, shakeCamera, BlendCurve,+} from 'esengine';+import { OverviewCam } from '../components';+import { BLEND_TIME, SHAKE } from '../config';++// Space → shakeCamera: a decaying perturbation on the rendered view only (the+// camera Transform is untouched, so the view always recovers).+// 1 / 2 → setViewTarget: hand the view to the follow camera / the overview+// camera, easing position + zoom over BLEND_TIME seconds.+export const cameraDirectorSystem = defineSystem(+ [Res(Input), Res(CameraDirector), Query(Camera, FollowTarget), Query(Camera, OverviewCam)],+ (input, director, followCams, overviewCams) => {+ if (input.isKeyPressed('Space')) {+ shakeCamera(director, SHAKE);+ }+ if (input.isKeyPressed('Digit1')) {+ for (const [entity] of followCams) {+ setViewTarget(director, entity, { time: BLEND_TIME, curve: BlendCurve.EaseInOut });+ }+ }+ if (input.isKeyPressed('Digit2')) {+ for (const [entity] of overviewCams) {+ setViewTarget(director, entity, { time: BLEND_TIME, curve: BlendCurve.EaseInOut });+ }+ }+ },+ { name: 'CameraDirectorControls' },+);diff --git a/examples/camera-follow/src/systems/move.ts b/examples/camera-follow/src/systems/move.tsnew file mode 100644index 000000000..63f3de773--- /dev/null+++ b/examples/camera-follow/src/systems/move.ts@@ -0,0 +1,27 @@+import {+ defineSystem, Query, Mut, Res, Time, Input, Transform,+} from 'esengine';+import { Player } from '../components';+import { WORLD_HALF_W, WORLD_HALF_H } from '../config';++const clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);++export const playerMoveSystem = defineSystem(+ [Query(Mut(Transform), Player), Res(Input), Res(Time)],+ (query, input, time) => {+ for (const [, transform, player] of query) {+ let dx = 0;+ let dy = 0;+ if (input.isKeyDown('KeyW') || input.isKeyDown('ArrowUp')) dy += 1;+ if (input.isKeyDown('KeyS') || input.isKeyDown('ArrowDown')) dy -= 1;+ if (input.isKeyDown('KeyA') || input.isKeyDown('ArrowLeft')) dx -= 1;+ if (input.isKeyDown('KeyD') || input.isKeyDown('ArrowRight')) dx += 1;+ if (dx === 0 && dy === 0) continue;+ const len = Math.sqrt(dx * dx + dy * dy);+ const p = transform.position;+ p.x = clamp(p.x + (dx / len) * player.speed * time.delta, -WORLD_HALF_W, WORLD_HALF_W);+ p.y = clamp(p.y + (dy / len) * player.speed * time.delta, -WORLD_HALF_H, WORLD_HALF_H);+ }+ },+ { name: 'PlayerMoveSystem' },+);diff --git a/examples/camera-follow/src/systems/setup.ts b/examples/camera-follow/src/systems/setup.tsnew file mode 100644index 000000000..cc816264f--- /dev/null+++ b/examples/camera-follow/src/systems/setup.ts@@ -0,0 +1,94 @@+import {+ defineSystem, Query, Commands, Transform, Sprite, Camera, ProjectionType,+ FollowTarget,+} from 'esengine';+import { Player, OverviewCam } from '../components';+import {+ WORLD_HALF_W, WORLD_HALF_H, GRID_STEP, PLAYER_SIZE, FOLLOW, OVERVIEW_ORTHO,+ LANDMARKS,+} from '../config';++// Builds the whole world from code (a large scatter of primitives is simpler to+// spawn than to author): ground-dot grid, landmark blocks, border frame, the+// player, and the fixed overview camera. Then wires the scene's gameplay camera+// to the player by inserting a FollowTarget on it — from that point on the+// built-in follow system damps the camera toward the player every frame.+export const setupSystem = defineSystem(+ [Query(Camera), Commands()],+ (cameras, cmds) => {+ // Dim ground dots every GRID_STEP so camera motion is visible everywhere.+ for (let x = -WORLD_HALF_W; x <= WORLD_HALF_W; x += GRID_STEP) {+ for (let y = -WORLD_HALF_H; y <= WORLD_HALF_H; y += GRID_STEP) {+ cmds.spawn()+ .insert(Transform, { position: { x, y, z: 0 } })+ .insert(Sprite, {+ size: { x: 14, y: 14 },+ color: { r: 0.22, g: 0.24, b: 0.28, a: 1 },+ layer: 0,+ });+ }+ }++ for (const mark of LANDMARKS) {+ cmds.spawn()+ .insert(Transform, { position: { x: mark.x, y: mark.y, z: 0 } })+ .insert(Sprite, {+ size: { x: mark.w, y: mark.h },+ color: mark.color,+ layer: 1,+ });+ }++ // Border frame marking the edge of the roamable world.+ const frames = [+ { x: 0, y: WORLD_HALF_H, w: WORLD_HALF_W * 2, h: 8 },+ { x: 0, y: -WORLD_HALF_H, w: WORLD_HALF_W * 2, h: 8 },+ { x: -WORLD_HALF_W, y: 0, w: 8, h: WORLD_HALF_H * 2 },+ { x: WORLD_HALF_W, y: 0, w: 8, h: WORLD_HALF_H * 2 },+ ];+ for (const f of frames) {+ cmds.spawn()+ .insert(Transform, { position: { x: f.x, y: f.y, z: 0 } })+ .insert(Sprite, {+ size: { x: f.w, y: f.h },+ color: { r: 0.45, g: 0.5, b: 0.6, a: 1 },+ layer: 1,+ });+ }++ const player = cmds.spawn('Player')+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })+ .insert(Sprite, {+ size: { x: PLAYER_SIZE, y: PLAYER_SIZE },+ color: { r: 1, g: 1, b: 1, a: 1 },+ layer: 2,+ })+ .insert(Player)+ .id();++ // A fixed wide-angle camera framing the whole world. It is NOT active —+ // it only renders when setViewTarget hands the view to it (key 2).+ cmds.spawn('OverviewCamera')+ .insert(Transform, { position: { x: 0, y: 0, z: 10 } })+ .insert(Camera, {+ projectionType: ProjectionType.Orthographic,+ orthoSize: OVERVIEW_ORTHO,+ isActive: false,+ priority: 0,+ })+ .insert(OverviewCam);++ // The scene's active camera becomes the follow camera. The query snapshot+ // predates the overview spawn, but filter on isActive anyway so the+ // FollowTarget can never land on the overview camera.+ for (const [entity, cam] of cameras) {+ if (!cam.isActive) continue;+ cmds.entity(entity).insert(FollowTarget, {+ target: player,+ deadzone: FOLLOW.deadzone,+ damping: FOLLOW.damping,+ });+ }+ },+ { name: 'SetupSystem' },+);diff --git a/examples/camera-follow/tsconfig.json b/examples/camera-follow/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/camera-follow/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}diff --git a/examples/input-actions/.gitignore b/examples/input-actions/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/input-actions/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/input-actions/README.md b/examples/input-actions/README.mdnew file mode 100644index 000000000..b5b9800ea--- /dev/null+++ b/examples/input-actions/README.md@@ -0,0 +1,118 @@+# Input Actions++The **modern input stack**: a ship driven by **named actions** (`defineInputMap`)+instead of hard-coded keys, with keyboard **and** gamepad bindings, live+**rebinding** persisted via `Storage`, and a **gesture pad** (swipe / pinch via+`GestureDetector`). For the *raw* `Input` resource (per-key queries, mouse+position, trails) see [`input-demo`](../input-demo) — this example is the layer+you should normally build gameplay on.++- **Move** — WASD, arrow keys, or the gamepad left stick (all three bound to one+ `Move` action; the HUD shows the live axis value).+- **Fire** — Space or gamepad South (A / Cross). Firing flashes the ship and+ spawns bullet squares.+- **Rebind fire** — click the button, then press any key or gamepad button; the+ new binding is saved and survives a restart. **Reset** restores the defaults.+- **Gesture pad** (bottom strip) — swipe steps the ship, pinch scales it. On+ desktop: **drag = swipe**, **Shift-drag = pinch** (see below).++## InputMap in five lines++```ts+export const Actions = defineInputMap({+ Move: Axis2D(Keys2D('KeyW','KeyS','KeyA','KeyD'), Stick('left')),+ Fire: Button(Key('Space'), GpButton(GamepadButton.South)),+});+// anywhere: Actions.pressed('Fire') Actions.axis2d('Move')+```++`defineInputMap` registers one `PreUpdate` evaluation system that reads the raw+`Input` resource; gameplay systems just query the returned map by action name.++### Binding syntax++Every binding is **plain serializable data** (that's also the rebind/persistence+format). Constructors:++| Constructor | Data | Feeds |+| --- | --- | --- |+| `Key('Space')` | `{kind:'key', code}` (DOM `KeyboardEvent.code`) | button / axis |+| `MouseButton(0)` | `{kind:'mouse', button}` | button |+| `GpButton(GamepadButton.South, pad?)` | `{kind:'gpButton', button, pad}` — analog value for triggers | button / axis |+| `GpAxis(GamepadAxis.LeftX, pad?, scale?)` | `{kind:'gpAxis', axis, pad, scale}` | axis |+| `Keys1D('KeyQ','KeyE')` | neg/pos keys → signed −1…+1 | axis |+| `Keys2D(up,down,left,right)` | four keys → 2D vector (up = +y) | axis2d |+| `Stick('left'│'right', pad?)` | gamepad stick → 2D vector (Y inverted so up = +y) | axis2d |++Actions wrap bindings with a type: `Button(...)` (value 0–1, has+`pressed`/`released` edges), `Axis1D(...)` (−1…+1), `Axis2D(...)` (normalized+vector via `.axis2d(name)`, magnitude via `.value(name)`). Multiple bindings on+one action **sum** (then clamp/normalize), which is why WASD + arrows + stick+coexist on `Move`. An action reads as `down` at magnitude ≥ 0.5.++### Rebind flow (`src/systems/hud.ts`)++```ts+const binding = await Actions.rebind('Fire', { keyboard: true, gamepad: true });+if (binding) Actions.save(BINDINGS_KEY); // persists via Storage+```++- `rebind(name, opts)` = `listenForBinding(opts)` + `setBindings(name, [b])`;+ pass `append: true` to add instead of replace.+- `ListenOptions` picks device families: `keyboard` and `gamepad` default **on**,+ `mouse` defaults **off** — so the click that opened the rebind UI is not+ captured. Axis sources are never captured; rebinding targets discrete inputs.+- The listener resolves on the **next pressed input** (any key, including+ Escape). To cancel, call `cancelListen()` — here, clicking the button again+ while `isListening()` does that (the promise resolves `null`).+- Persistence: `Actions.save(key)` / `Actions.load(key)` store `toJSON()`+ (bindings only) in `Storage`. `load` ignores action names the map doesn't+ declare, so stale saves can't resurrect removed actions. For data-driven maps+ there is also `toAsset()` / `loadInputMapAsset()` (full `.inputmap` JSON,+ including action types).++## Gestures (`src/systems/gestures.ts`)++`GestureDetector` wraps an `InputState` and fires callbacks from its **touch**+data. Call `detector.update(dt)` once per frame. Events and fields:++| Event | Fields | Fires when |+| --- | --- | --- |+| `onTap` | `(x, y)` — touch **start** position, screen px | released within 0.3 s and < 10 px of travel |+| `onSwipe` | `(direction, speed)` — `'left'│'right'│'up'│'down'`, px/s | travel ≥ 50 px at ≥ 200 px/s (dominant axis wins) |+| `onPinch` | `(scale, centerX, centerY)` — **per-frame** distance ratio (>1 spread, <1 pinch-in) and midpoint | exactly two active touches; multiply into your own accumulated scale |+| `onLongPress` | `(x, y)` | single touch held ≥ 0.5 s with < 10 px of travel |++Note `direction` is in **screen** coordinates (y grows downward): a swipe toward+the top of the screen reports `'up'`, and this demo maps it to +y in the world.++### What sources does it support?++**Touch only.** The detector reads `Input.touches` / `touchesStarted` /+`touchesEnded`, which the platform layer fills from real touch events (web+`touchstart`…, WeChat `onTouchStart`…). Mouse input does **not** reach it, so+this example bridges the mouse itself: `gestureSystem` owns a private+`InputState` fed from two sources — real touches whose start point is inside the+pad (bottom quarter of the screen), and **synthetic touches from mouse drags**+(left-drag = one finger; Shift-drag = a second finger mirrored across the press+point, driving the detector's genuine two-finger pinch path). The detector never+knows the difference — which is also a demonstration that it works on any+`InputState`-shaped touch source you construct.++Two practical details the bridge shows: gating by pad area must happen at the+*source* (swipe callbacks carry no position), and releasing a pinch often also+classifies as a swipe, so the pinch flag suppresses swipes for the rest of that+gesture.++## Files++- `src/actions.ts` — the `InputMap` (Move/Fire), defaults, `Storage` key, and+ binding pretty-printers for the HUD.+- `src/systems/ship.ts` — gameplay reads *only* named actions (`axis2d('Move')`,+ `pressed('Fire')`) + applies gesture steps/scale; bullets fade and despawn.+- `src/systems/gestures.ts` — the `GestureDetector`, pad gating, and the+ mouse→touch bridge.+- `src/systems/hud.ts` — binding labels, the Rebind/Reset buttons+ (`createButton`), rebind status.+- `assets/scenes/main.esscene` — camera, ship, HUD panel, gesture pad (UI built+ from scene-authored flex containers; buttons are added at runtime).diff --git a/examples/input-actions/assets/scenes/main.esscene b/examples/input-actions/assets/scenes/main.esscenenew file mode 100644index 000000000..9bc9e4901--- /dev/null+++ b/examples/input-actions/assets/scenes/main.esscene@@ -0,0 +1,266 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Ship",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": -30, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 44, "y": 44 }, "color": { "r": 0.35, "g": 0.85, "b": 1, "a": 1 }, "layer": 2 } },+ { "type": "ShipControl", "data": { "speed": 260 } }+ ],+ "visible": true+ },+ {+ "id": 2,+ "name": "Canvas",+ "parent": null,+ "children": [3, 10],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "Canvas", "data": { "designResolution": { "x": 800, "y": 600 }, "scaleMode": 2 } },+ { "type": "UINode", "data": {} }+ ],+ "visible": true+ },+ {+ "id": 3,+ "name": "HudPanel",+ "parent": 2,+ "children": [4, 5, 6, 7, 9],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": {+ "position": 1,+ "width": { "value": 400, "unit": 0 },+ "height": { "value": 196, "unit": 0 },+ "insetLeft": { "value": 16, "unit": 0 },+ "insetTop": { "value": 16, "unit": 0 }+ }+ },+ {+ "type": "FlexContainer",+ "data": {+ "direction": 1,+ "justifyContent": 0,+ "alignItems": 3,+ "gap": { "x": 0, "y": 8 },+ "padding": { "left": 16, "top": 14, "right": 16, "bottom": 14 }+ }+ },+ { "type": "UIVisual", "data": { "visualType": 1, "color": { "r": 0.1, "g": 0.1, "b": 0.13, "a": 0.85 }, "enabled": true } }+ ],+ "visible": true+ },+ {+ "id": 4,+ "name": "Title",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 26, "unit": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "Input Actions",+ "fontSize": 18,+ "bold": true,+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 5,+ "name": "MoveLabel",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 20, "unit": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "Move",+ "fontSize": 13,+ "color": { "r": 0.85, "g": 0.85, "b": 0.9, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 6,+ "name": "FireLabel",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 20, "unit": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "Fire",+ "fontSize": 13,+ "color": { "r": 0.85, "g": 0.85, "b": 0.9, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 7,+ "name": "RebindRow",+ "parent": 3,+ "children": [8],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 34, "unit": 0 } } },+ {+ "type": "FlexContainer",+ "data": { "direction": 0, "justifyContent": 0, "alignItems": 1, "gap": { "x": 10, "y": 0 } }+ }+ ],+ "visible": true+ },+ {+ "id": 8,+ "name": "RebindHint",+ "parent": 7,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "flexGrow": 1, "alignSelf": 4 } },+ {+ "type": "Text",+ "data": {+ "content": "",+ "fontSize": 12,+ "color": { "r": 0.6, "g": 0.65, "b": 0.7, "a": 1 },+ "align": 2,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 9,+ "name": "StatusLabel",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 20, "unit": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "Bindings persist via Storage.",+ "fontSize": 12,+ "color": { "r": 1, "g": 0.85, "b": 0.4, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 10,+ "name": "GesturePad",+ "parent": 2,+ "children": [11, 12],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": {+ "position": 1,+ "insetLeft": { "value": 0, "unit": 0 },+ "insetRight": { "value": 0, "unit": 0 },+ "insetBottom": { "value": 0, "unit": 0 },+ "height": { "value": 25, "unit": 1 }+ }+ },+ {+ "type": "FlexContainer",+ "data": {+ "direction": 1,+ "justifyContent": 1,+ "alignItems": 1,+ "gap": { "x": 0, "y": 6 }+ }+ },+ { "type": "UIVisual", "data": { "visualType": 1, "color": { "r": 0.12, "g": 0.14, "b": 0.2, "a": 0.55 }, "enabled": true } }+ ],+ "visible": true+ },+ {+ "id": 11,+ "name": "GestureHint",+ "parent": 10,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 20, "unit": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "Gesture pad - touch: swipe / pinch - mouse: drag = swipe, Shift-drag = pinch",+ "fontSize": 13,+ "color": { "r": 0.75, "g": 0.8, "b": 0.9, "a": 1 },+ "align": 1,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 12,+ "name": "GestureStatus",+ "parent": 10,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ { "type": "UINode", "data": { "height": { "value": 20, "unit": 0 } } },+ {+ "type": "Text",+ "data": {+ "content": "-",+ "fontSize": 13,+ "bold": true,+ "color": { "r": 0.5, "g": 0.9, "b": 1, "a": 1 },+ "align": 1,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/input-actions/assets/scenes/main.esscene.meta b/examples/input-actions/assets/scenes/main.esscene.metanew file mode 100644index 000000000..d4d418788--- /dev/null+++ b/examples/input-actions/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "6463d6d2-968a-4aa6-a67e-22a65a4e157e",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/input-actions/project.esproject b/examples/input-actions/project.esprojectnew file mode 100644index 000000000..32b380d26--- /dev/null+++ b/examples/input-actions/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Input Actions",+ "description": "Named actions (InputMap) with keyboard + gamepad bindings, live rebinding, and swipe/pinch gestures.",+ "tag": "Input",+ "version": "0.1.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 800,+ "height": 600+ },+ "spineVersion": "none"+}diff --git a/examples/input-actions/src/actions.ts b/examples/input-actions/src/actions.tsnew file mode 100644index 000000000..559d97ecb--- /dev/null+++ b/examples/input-actions/src/actions.ts@@ -0,0 +1,47 @@+// The input map: gameplay code queries named actions ("Move", "Fire") instead+// of physical keys, so keyboard, gamepad and rebound inputs all flow through+// one place. defineInputMap registers the per-frame evaluation system itself.+import {+ defineInputMap, Axis2D, Button, Keys2D, Stick, Key, GpButton, GamepadButton,+} from 'esengine';+import type { Binding } from 'esengine';++export const DEFAULT_FIRE: Binding[] = [Key('Space'), GpButton(GamepadButton.South)];++export const Actions = defineInputMap({+ Move: Axis2D(+ Keys2D('KeyW', 'KeyS', 'KeyA', 'KeyD'),+ Keys2D('ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'),+ Stick('left'),+ ),+ Fire: Button(...DEFAULT_FIRE),+});++/** Storage key for user rebinds (Actions.save / Actions.load). */+export const BINDINGS_KEY = 'input-actions.bindings';++function keyName(code: string): string {+ if (code.startsWith('Key')) return code.slice(3);+ if (code.startsWith('Digit')) return code.slice(5);+ return code;+}++export function formatBinding(b: Binding): string {+ switch (b.kind) {+ case 'key': return keyName(b.code);+ case 'mouse': return `Mouse ${b.button}`;+ case 'gpButton': return `Pad ${GamepadButton[b.button] ?? b.button}`;+ case 'gpAxis': return `Pad axis ${b.axis}`;+ case 'keys1d': return `${keyName(b.neg)}/${keyName(b.pos)}`;+ case 'keys2d': {+ const codes = [b.up, b.down, b.left, b.right];+ if (codes.every((c) => c.startsWith('Arrow'))) return 'Arrows';+ return [b.up, b.left, b.down, b.right].map(keyName).join('');+ }+ case 'stick': return b.stick === 'left' ? 'Left stick' : 'Right stick';+ }+}++export function formatBindings(action: string): string {+ return Actions.getBindings(action).map(formatBinding).join(' / ');+}diff --git a/examples/input-actions/src/components.ts b/examples/input-actions/src/components.tsnew file mode 100644index 000000000..af598a9da--- /dev/null+++ b/examples/input-actions/src/components.ts@@ -0,0 +1,11 @@+import { defineComponent } from 'esengine';++export const ShipControl = defineComponent('ShipControl', {+ speed: 260,+ flash: 0,+});++export const Bullet = defineComponent('Bullet', {+ lifetime: 0.7,+ speed: 480,+});diff --git a/examples/input-actions/src/main.ts b/examples/input-actions/src/main.tsnew file mode 100644index 000000000..1c1b8394f--- /dev/null+++ b/examples/input-actions/src/main.ts@@ -0,0 +1,15 @@+// Input Actions — named actions (InputMap) + gestures (GestureDetector).+// The map itself lives in actions.ts; importing it registers the evaluation+// system. See input-demo for the raw Input resource this builds on.+import { addSystemToSchedule, Schedule } from 'esengine';++import './components';+import './actions';+import { shipSystem, bulletSystem } from './systems/ship';+import { gestureSystem } from './systems/gestures';+import { hudSystem } from './systems/hud';++addSystemToSchedule(Schedule.Update, gestureSystem);+addSystemToSchedule(Schedule.Update, shipSystem);+addSystemToSchedule(Schedule.Update, bulletSystem);+addSystemToSchedule(Schedule.Update, hudSystem);diff --git a/examples/input-actions/src/state.ts b/examples/input-actions/src/state.tsnew file mode 100644index 000000000..31354f2bf--- /dev/null+++ b/examples/input-actions/src/state.ts@@ -0,0 +1,11 @@+// Gesture handlers write here; the ship and HUD systems read it. Keeps the+// GestureDetector callbacks decoupled from the ECS world.+export const gestureState = {+ /** Pending swipe displacement in world units; consumed by the ship system. */+ stepX: 0,+ stepY: 0,+ /** Ship scale, driven by pinch. */+ scale: 1,+ /** Last recognized gesture, for the pad HUD. */+ last: '-',+};diff --git a/examples/input-actions/src/systems/gestures.ts b/examples/input-actions/src/systems/gestures.tsnew file mode 100644index 000000000..0613e2d25--- /dev/null+++ b/examples/input-actions/src/systems/gestures.ts@@ -0,0 +1,121 @@+// GestureDetector consumes TOUCH points only (Input.touches / touchesStarted /+// touchesEnded) — mouse input never reaches it by itself. This system funnels+// two sources into a dedicated InputState that only the detector reads:+// a) real touches that started inside the gesture pad (mobile), and+// b) synthetic touches bridged from mouse drags (desktop): a left-drag is a+// one-finger gesture; a Shift-drag adds a second touch mirrored across the+// press point, which drives the detector's real two-finger pinch path.+import {+ defineSystem, Res, Time, Input, InputState, UICameraInfo, GestureDetector,+} from 'esengine';+import type { UICameraData } from 'esengine';+import { gestureState } from '../state';++/** The pad is the bottom quarter of the screen (matches the GesturePad UINode). */+const PAD_FRACTION = 0.25;+const SWIPE_STEP = 90;+const MOUSE_TOUCH = -1;+const MIRROR_TOUCH = -2;++const padInput = new InputState();+const detector = new GestureDetector(padInput);+const padTouchIds = new Set<number>();+let mouseMode: 'none' | 'swipe' | 'pinch' = 'none';+let anchorX = 0;+let anchorY = 0;+// Lifting the fingers off a pinch often travels far enough to classify as a+// swipe too; suppress swipes for the remainder of a gesture that pinched.+let pinchedThisGesture = false;++const clamp = (v: number, lo: number, hi: number): number => (v < lo ? lo : v > hi ? hi : v);++detector.onSwipe = (direction, speed) => {+ if (pinchedThisGesture) return;+ // Touch y grows downward, so a screen-up swipe moves the ship toward +y.+ if (direction === 'left') gestureState.stepX -= SWIPE_STEP;+ else if (direction === 'right') gestureState.stepX += SWIPE_STEP;+ else if (direction === 'up') gestureState.stepY += SWIPE_STEP;+ else gestureState.stepY -= SWIPE_STEP;+ gestureState.last = `Swipe ${direction} (${Math.round(speed)} px/s)`;+};++detector.onPinch = (scale, _centerX, _centerY) => {+ pinchedThisGesture = true;+ gestureState.scale = clamp(gestureState.scale * scale, 0.5, 2.5);+ gestureState.last = `Pinch — ship scale x${gestureState.scale.toFixed(2)}`;+};++detector.onTap = (x, y) => {+ gestureState.last = `Tap (${Math.round(x)}, ${Math.round(y)})`;+};++detector.onLongPress = () => {+ gestureState.last = 'Long press';+};++function inPad(y: number, cam: UICameraData): boolean {+ return cam.valid && cam.screenH > 0 && y >= cam.screenH * (1 - PAD_FRACTION);+}++function startTouch(id: number, x: number, y: number): void {+ const p = { id, x, y };+ padInput.touches.set(id, p);+ padInput.touchesStarted.set(id, p);+}++function moveTouch(id: number, x: number, y: number): void {+ const p = padInput.touches.get(id);+ if (p) { p.x = x; p.y = y; }+}++function endTouch(id: number): void {+ padInput.touches.delete(id);+ padInput.touchesEnded.add(id);+}++export const gestureSystem = defineSystem(+ [Res(Input), Res(UICameraInfo), Res(Time)],+ (input, cam: UICameraData, time) => {+ padInput.touchesStarted.clear();+ padInput.touchesEnded.clear();+ if (padInput.touches.size === 0) pinchedThisGesture = false;++ // a) Real touches: forward the ones that started inside the pad.+ for (const [id, t] of input.touchesStarted) {+ if (!inPad(t.y, cam)) continue;+ padTouchIds.add(id);+ startTouch(id, t.x, t.y);+ }+ for (const id of padTouchIds) {+ const live = input.touches.get(id);+ if (live) moveTouch(id, live.x, live.y);+ }+ for (const id of input.touchesEnded) {+ if (padTouchIds.delete(id)) endTouch(id);+ }++ // b) Mouse bridge.+ const mx = input.mouseX;+ const my = input.mouseY;+ if (mouseMode === 'none') {+ if (input.isMouseButtonPressed(0) && inPad(my, cam) && !input.isPointerOverUI()) {+ const shift = input.isKeyDown('ShiftLeft') || input.isKeyDown('ShiftRight');+ mouseMode = shift ? 'pinch' : 'swipe';+ anchorX = mx;+ anchorY = my;+ startTouch(MOUSE_TOUCH, mx, my);+ if (mouseMode === 'pinch') startTouch(MIRROR_TOUCH, mx, my);+ }+ } else if (input.isMouseButtonDown(0)) {+ moveTouch(MOUSE_TOUCH, mx, my);+ if (mouseMode === 'pinch') moveTouch(MIRROR_TOUCH, 2 * anchorX - mx, 2 * anchorY - my);+ } else {+ endTouch(MOUSE_TOUCH);+ if (mouseMode === 'pinch') endTouch(MIRROR_TOUCH);+ mouseMode = 'none';+ }++ detector.update(time.delta);+ },+ { name: 'GestureSystem' }+);diff --git a/examples/input-actions/src/systems/hud.ts b/examples/input-actions/src/systems/hud.tsnew file mode 100644index 000000000..b94df4394--- /dev/null+++ b/examples/input-actions/src/systems/hud.ts@@ -0,0 +1,95 @@+import {+ defineSystem, Res, GetWorld,+ UIEvents, Text,+ createButton, themeColors, px,+} from 'esengine';+import type {+ Entity, World, Color, ThemeColors, UIEventQueue, TextData,+} from 'esengine';+import { Actions, BINDINGS_KEY, DEFAULT_FIRE, formatBinding, formatBindings } from '../actions';+import { gestureState } from '../state';++let built = false;+let status = '';+const lastText = new Map<Entity, string>();++function setText(world: World, entity: Entity | null, content: string): void {+ if (entity === null || !world.valid(entity) || !world.has(entity, Text)) return;+ if (lastText.get(entity) === content) return;+ lastText.set(entity, content);+ const t = world.get(entity, Text) as TextData;+ t.content = content;+ world.insert(entity, Text, t);+}++function controlStates(c: ThemeColors): Record<string, { color: Color }> {+ return { normal: { color: c.control }, hover: { color: c.controlHover }, pressed: { color: c.controlActive } };+}++function startRebind(): void {+ if (Actions.isListening()) {+ Actions.cancelListen();+ return;+ }+ status = 'Press any key or gamepad button... (click again to cancel)';+ void Actions.rebind('Fire', { keyboard: true, gamepad: true }).then((binding) => {+ if (binding) {+ Actions.save(BINDINGS_KEY);+ status = `Fire is now ${formatBinding(binding)} (saved)`;+ } else {+ status = 'Rebind cancelled.';+ }+ });+}++function resetBindings(): void {+ Actions.cancelListen();+ Actions.setBindings('Fire', DEFAULT_FIRE);+ Actions.save(BINDINGS_KEY);+ status = 'Fire reset to defaults.';+}++function build(world: World, events: UIEventQueue): boolean {+ const row = world.findEntityByName('RebindRow');+ if (row === null) return false;++ status = Actions.load(BINDINGS_KEY)+ ? 'Loaded saved bindings from Storage.'+ : 'Defaults active. Rebind persists via Storage.';++ const c = themeColors();+ createButton({+ world, events, parent: row,+ node: { width: px(120), height: px(28) },+ states: { normal: { color: c.primary }, hover: { color: c.primaryHover }, pressed: { color: c.primaryActive } },+ text: { content: 'Rebind fire', color: c.onPrimary, fontSize: 13 },+ onClick: startRebind,+ });+ createButton({+ world, events, parent: row,+ node: { width: px(80), height: px(28) },+ states: controlStates(c),+ text: { content: 'Reset', color: c.onPrimary, fontSize: 13 },+ onClick: resetBindings,+ });+ return true;+}++export const hudSystem = defineSystem(+ [Res(UIEvents), GetWorld()],+ (events: UIEventQueue, world: World) => {+ if (!built) {+ built = build(world, events);+ if (!built) return;+ }++ const move = Actions.axis2d('Move');+ setText(world, world.findEntityByName('MoveLabel'),+ `Move ${formatBindings('Move')} (${move.x.toFixed(2)}, ${move.y.toFixed(2)})`);+ setText(world, world.findEntityByName('FireLabel'),+ `Fire ${formatBindings('Fire')}${Actions.down('Fire') ? ' [FIRING]' : ''}`);+ setText(world, world.findEntityByName('StatusLabel'), status);+ setText(world, world.findEntityByName('GestureStatus'), gestureState.last);+ },+ { name: 'HudSystem' }+);diff --git a/examples/input-actions/src/systems/ship.ts b/examples/input-actions/src/systems/ship.tsnew file mode 100644index 000000000..13029536e--- /dev/null+++ b/examples/input-actions/src/systems/ship.ts@@ -0,0 +1,69 @@+import {+ defineSystem, Query, Mut, Res, Time, Commands,+ Transform, Sprite,+} from 'esengine';+import { ShipControl, Bullet } from '../components';+import { Actions } from '../actions';+import { gestureState } from '../state';++const HALF_W = 370;+const HALF_H = 260;++const clamp = (v: number, lo: number, hi: number): number => (v < lo ? lo : v > hi ? hi : v);++export const shipSystem = defineSystem(+ [Query(Mut(Transform), Mut(Sprite), Mut(ShipControl)), Res(Time), Commands()],+ (query, time, cmds) => {+ for (const [_entity, transform, sprite, ship] of query) {+ const move = Actions.axis2d('Move');+ let x = transform.position.x + move.x * ship.speed * time.delta;+ let y = transform.position.y + move.y * ship.speed * time.delta;++ // Swipe steps accumulated by the gesture handlers.+ x += gestureState.stepX;+ y += gestureState.stepY;+ gestureState.stepX = 0;+ gestureState.stepY = 0;++ transform.position.x = clamp(x, -HALF_W, HALF_W);+ transform.position.y = clamp(y, -HALF_H, HALF_H);+ transform.scale = { x: gestureState.scale, y: gestureState.scale, z: 1 };++ if (Actions.pressed('Fire')) {+ ship.flash = 1;+ cmds.spawn()+ .insert(Transform, {+ position: { x: transform.position.x, y: transform.position.y + 28, z: 0 },+ })+ .insert(Sprite, {+ size: { x: 8, y: 18 },+ color: { r: 1, g: 0.9, b: 0.4, a: 1 },+ layer: 1,+ })+ .insert(Bullet, {});+ }++ ship.flash = Math.max(0, ship.flash - time.delta * 5);+ sprite.color = {+ r: 0.35 + 0.65 * ship.flash,+ g: 0.85 + 0.15 * ship.flash,+ b: 1,+ a: 1,+ };+ }+ },+ { name: 'ShipSystem' }+);++export const bulletSystem = defineSystem(+ [Query(Mut(Transform), Mut(Sprite), Mut(Bullet)), Res(Time), Commands()],+ (query, time, cmds) => {+ for (const [entity, transform, sprite, bullet] of query) {+ bullet.lifetime -= time.delta;+ transform.position.y += bullet.speed * time.delta;+ sprite.color.a = Math.max(0, bullet.lifetime / 0.7);+ if (bullet.lifetime <= 0) cmds.despawn(entity);+ }+ },+ { name: 'BulletSystem' }+);diff --git a/examples/input-actions/tsconfig.json b/examples/input-actions/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/input-actions/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}diff --git a/examples/save-load/.gitignore b/examples/save-load/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/save-load/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/save-load/README.md b/examples/save-load/README.mdnew file mode 100644index 000000000..49bdc71e3--- /dev/null+++ b/examples/save-load/README.md@@ -0,0 +1,114 @@+# Save & Load++A tiny collect-the-coins game whose whole point is persistence: `SaveManager`+gives you named save slots with **schema versioning + migration on load**, and+raw `Storage` handles the lightweight key/value cases (preferences) that don't+deserve an envelope.++## Controls++| Input | Action |+| ------------------- | ----------------------------------------------- |+| Arrows / WASD | Move the player square |+| **Save** | Write score + position + collected coins (v2) |+| **Load** | Read the slot back, migrating old saves forward |+| **Clear** | Delete the slot |+| **Save as v1** | Write the slot as an *old build* would have |+| **Toggle** | Flip the player color — a raw `Storage` pref |++Collect some coins, **Save**, collect more (or reload the page), then **Load**:+score, player position and the collected-coin set all snap back. Coins are a+pure projection of the collected set (`coins.ts`), so load/clear never need a+special respawn path — the sync system reconciles the world from state.++## SaveManager, option by option++```ts+export const saves = new SaveManager({+ version: SAVE_VERSION, // current schema version stamped into every save+ migrations, // { 1: v1→v2, 2: v2→v3, … } chain, keyed by source version+ keyPrefix: 'save-load:', // slot "demo" → storage key "save-load:demo"+});+```++- **`version`** (required) — the schema version of what `save()` writes *today*.+ Every save is stored as an envelope `{ version, data, savedAt }`, so a load+ always knows which shape it is looking at.+- **`migrations`** — a record where `migrations[n]` upgrades data from version+ `n` to `n + 1`. On `load()`, an older save is run forward step by step+ (`migrateSaveData`) until it reaches `version`. A missing step, or a save+ *newer* than the current build, throws instead of silently corrupting.+- **`storage`** — the backend, defaulting to the engine's `Storage` (which maps+ to `localStorage` on web, the platform store elsewhere). Inject a stub in+ tests.+- **`now`** — clock for the `savedAt` stamp, defaulting to `Date.now`. Inject+ for deterministic tests.+- **`keyPrefix`** — namespace for slot keys (default `save:`). This example uses+ `save-load:` so its slots can't collide with another project's.++The instance methods used here: `save(slot, data)`, `load<T>(slot)` (returns+`null` for an empty/unreadable slot), `remove(slot)`, `savedAt(slot)`; `has()`+also exists.++## The migration story++Shipped games evolve their save shape. Without versioning, the first update+that renames a field bricks every existing save. So:++- **v1** of this game stored `{ points, playerX, playerY }` — flat fields, and+ it didn't track which coins were collected at all.+- **v2** (current) stores `{ score, player: { x, y }, collected: number[] }`.++`save.ts` registers one migration:++```ts+const migrations: Record<number, SaveMigration> = {+ 1: (raw) => {+ const d = raw as SaveDataV1;+ return { score: d.points, player: { x: d.playerX, y: d.playerY }, collected: [] };+ },+};+```++Nothing calls this directly. `load()` reads the envelope, sees `version: 1 <+SAVE_VERSION`, and applies `migrations[1]` (then `[2]`, `[3]`, … if the gap+were wider) before handing the data back — the game only ever sees the current+shape. Note the v1 migration has to *invent* a value for `collected` (empty):+choosing sensible defaults for data old saves never had is the essence of+writing a migration.++**Try it live:** press **Save as v1** (it writes a genuine v1 envelope straight+through `Storage`, exactly as an old build would have), then **Load** — the+status line reports `Loaded v1 save — migrated to v2`.++## Raw Storage for preferences++The player-color toggle skips SaveManager entirely:++```ts+Storage.getBoolean('save-load:pref:alt-color', false);+Storage.setBoolean('save-load:pref:alt-color', value);+```++`Storage` is typed key/value (`getString`/`getNumber`/`getBoolean`/`getJSON` ++setters, `has`, `remove`) — right for a single preference read at startup,+where an envelope and migrations would be ceremony. Rule of thumb: gameplay+state that will outlive schema changes → `SaveManager`; independent scalar+settings → `Storage`.++## Files++```+assets/+ scenes/main.esscene # camera, player square, HUD panel (labels + empty button rows)+src/+ main.ts # registers the systems+ components.ts # Player, Coin+ state.ts # module game state + coin spots+ save.ts # schema (v1/v2), migration, SaveManager, color pref+ systems/+ move.ts # arrow-key movement, clamped to the play area+ coins.ts # coins as a projection of state; pickup; pulse+ build.ts # buttons → SaveManager calls; applies the color pref+ hud.ts # score/status labels track game state+```diff --git a/examples/save-load/assets/scenes/main.esscene b/examples/save-load/assets/scenes/main.esscenenew file mode 100644index 000000000..9eb9294e4--- /dev/null+++ b/examples/save-load/assets/scenes/main.esscene@@ -0,0 +1,208 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": { "x": 0, "y": 0, "z": 10 }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 300,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Player",+ "parent": null,+ "children": [],+ "components": [+ { "type": "Transform", "data": { "position": { "x": 0, "y": -60, "z": 0 } } },+ { "type": "Sprite", "data": { "size": { "x": 40, "y": 40 }, "color": { "r": 0.28, "g": 0.54, "b": 0.92, "a": 1 } } },+ { "type": "Player", "data": {} }+ ],+ "visible": true+ },+ {+ "id": 2,+ "name": "Canvas",+ "parent": null,+ "children": [3],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "Canvas",+ "data": {+ "designResolution": { "x": 800, "y": 600 },+ "scaleMode": 2+ }+ },+ { "type": "UINode", "data": {} }+ ],+ "visible": true+ },+ {+ "id": 3,+ "name": "Panel",+ "parent": 2,+ "children": [4, 5, 6, 7],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": {+ "position": 1,+ "width": { "value": 480, "unit": 0 },+ "height": { "value": 178, "unit": 0 },+ "insetLeft": { "value": 50, "unit": 1 },+ "insetTop": { "value": 16, "unit": 0 },+ "marginLeft": { "value": -240, "unit": 0 }+ }+ },+ {+ "type": "FlexContainer",+ "data": {+ "direction": 1,+ "justifyContent": 0,+ "alignItems": 3,+ "gap": { "x": 0, "y": 10 },+ "padding": { "left": 16, "top": 16, "right": 16, "bottom": 16 }+ }+ },+ {+ "type": "UIVisual",+ "data": {+ "visualType": 1,+ "color": { "r": 0.16, "g": 0.16, "b": 0.18, "a": 0.92 },+ "enabled": true+ }+ }+ ],+ "visible": true+ },+ {+ "id": 4,+ "name": "ScoreLabel",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 26, "unit": 0 } }+ },+ {+ "type": "Text",+ "data": {+ "content": "Score: 0",+ "fontSize": 18,+ "bold": true,+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 5,+ "name": "StatusLabel",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 18, "unit": 0 } }+ },+ {+ "type": "Text",+ "data": {+ "content": "Move with the arrow keys, collect coins, then Save.",+ "fontSize": 12,+ "color": { "r": 0.72, "g": 0.75, "b": 0.8, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ },+ {+ "id": 6,+ "name": "SaveRow",+ "parent": 3,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 36, "unit": 0 } }+ },+ {+ "type": "FlexContainer",+ "data": { "direction": 0, "justifyContent": 0, "alignItems": 1, "gap": { "x": 10, "y": 0 } }+ }+ ],+ "visible": true+ },+ {+ "id": 7,+ "name": "PrefRow",+ "parent": 3,+ "children": [8],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "height": { "value": 36, "unit": 0 } }+ },+ {+ "type": "FlexContainer",+ "data": { "direction": 0, "justifyContent": 3, "alignItems": 1 }+ }+ ],+ "visible": true+ },+ {+ "id": 8,+ "name": "PrefLabel",+ "parent": 7,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": { "flexGrow": 1, "alignSelf": 4 }+ },+ {+ "type": "Text",+ "data": {+ "content": "Player color (raw Storage pref)",+ "fontSize": 13,+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },+ "align": 0,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/save-load/assets/scenes/main.esscene.meta b/examples/save-load/assets/scenes/main.esscene.metanew file mode 100644index 000000000..d2387c54f--- /dev/null+++ b/examples/save-load/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "11310188-689f-443a-94ae-eed1cf1fabd5",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/save-load/project.esproject b/examples/save-load/project.esprojectnew file mode 100644index 000000000..4755250dc--- /dev/null+++ b/examples/save-load/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Save & Load",+ "description": "Versioned save slots with migration (SaveManager) plus raw Storage prefs.",+ "tag": "Basics",+ "version": "1.0.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 800,+ "height": 600+ },+ "spineVersion": "none"+}diff --git a/examples/save-load/src/components.ts b/examples/save-load/src/components.tsnew file mode 100644index 000000000..004a54391--- /dev/null+++ b/examples/save-load/src/components.ts@@ -0,0 +1,10 @@+import { defineComponent } from 'esengine';++export const Player = defineComponent('Player', {+ speed: 260,+});++export const Coin = defineComponent('Coin', {+ index: 0,+ phase: 0,+});diff --git a/examples/save-load/src/main.ts b/examples/save-load/src/main.tsnew file mode 100644index 000000000..9d021da79--- /dev/null+++ b/examples/save-load/src/main.ts@@ -0,0 +1,16 @@+// Save & Load — SaveManager (versioned slots + migration on load) over the+// Storage API, plus raw Storage for a lightweight preference.+import { addStartupSystem, addSystemToSchedule, Schedule } from 'esengine';++import './components';+import { buildSystem } from './systems/build';+import { moveSystem } from './systems/move';+import { coinSyncSystem, coinCollectSystem, coinPulseSystem } from './systems/coins';+import { hudSystem } from './systems/hud';++addStartupSystem(buildSystem);+addSystemToSchedule(Schedule.Update, moveSystem);+addSystemToSchedule(Schedule.Update, coinCollectSystem);+addSystemToSchedule(Schedule.Update, coinSyncSystem);+addSystemToSchedule(Schedule.Update, coinPulseSystem);+addSystemToSchedule(Schedule.Update, hudSystem);diff --git a/examples/save-load/src/save.ts b/examples/save-load/src/save.tsnew file mode 100644index 000000000..e8360594f--- /dev/null+++ b/examples/save-load/src/save.ts@@ -0,0 +1,67 @@+// Save schema + SaveManager wiring. The schema is versioned: bumping+// SAVE_VERSION requires a migration step from the previous version, so saves+// written by older builds keep loading.+import { SaveManager, Storage } from 'esengine';+import type { SaveEnvelope, SaveMigration } from 'esengine';++export const SAVE_VERSION = 2;+export const SLOT = 'demo';+const KEY_PREFIX = 'save-load:';++/** The shape a v1 build wrote: flat fields, no collected-coin tracking. */+export interface SaveDataV1 {+ points: number;+ playerX: number;+ playerY: number;+}++/** Current (v2) shape. */+export interface SaveData {+ score: number;+ player: { x: number; y: number };+ collected: number[];+}++const migrations: Record<number, SaveMigration> = {+ 1: (raw) => {+ const d = raw as SaveDataV1;+ const migrated: SaveData = {+ score: d.points,+ player: { x: d.playerX, y: d.playerY },+ collected: [],+ };+ return migrated;+ },+};++export const saves = new SaveManager({+ version: SAVE_VERSION,+ migrations,+ keyPrefix: KEY_PREFIX,+});++/** Peek at the stored envelope (version / savedAt) without migrating it. */+export function peekEnvelope(): SaveEnvelope<unknown> | undefined {+ return Storage.getJSON<SaveEnvelope<unknown>>(KEY_PREFIX + SLOT);+}++/** Write the slot exactly as an old v1 build would have, to exercise migration. */+export function writeLegacyV1Save(data: SaveDataV1): void {+ Storage.setJSON<SaveEnvelope<SaveDataV1>>(KEY_PREFIX + SLOT, {+ version: 1,+ data,+ savedAt: Date.now(),+ });+}++// A lightweight preference goes through raw Storage — no envelope, no+// versioning, just a typed key/value.+const PREF_ALT_COLOR = 'save-load:pref:alt-color';++export function loadAltColorPref(): boolean {+ return Storage.getBoolean(PREF_ALT_COLOR, false) ?? false;+}++export function saveAltColorPref(value: boolean): void {+ Storage.setBoolean(PREF_ALT_COLOR, value);+}diff --git a/examples/save-load/src/state.ts b/examples/save-load/src/state.tsnew file mode 100644index 000000000..57b0a5ead--- /dev/null+++ b/examples/save-load/src/state.ts@@ -0,0 +1,16 @@+export const COIN_SPOTS: ReadonlyArray<{ x: number; y: number }> = [+ { x: -320, y: 40 },+ { x: -160, y: -120 },+ { x: 0, y: 60 },+ { x: 160, y: -120 },+ { x: 320, y: 40 },+ { x: 0, y: -220 },+];++export const game = {+ score: 0,+ collected: new Set<number>(),+ altColor: false,+ status: 'Move with the arrow keys, collect coins, then Save.',+ built: false,+};diff --git a/examples/save-load/src/systems/build.ts b/examples/save-load/src/systems/build.tsnew file mode 100644index 000000000..2eafddcc4--- /dev/null+++ b/examples/save-load/src/systems/build.ts@@ -0,0 +1,132 @@+// Builds the Save / Load / Clear / Save-as-v1 buttons into the scene-authored+// rows and wires them to the SaveManager. Also applies the raw-Storage color+// preference at startup.+import {+ defineSystem, Res, GetWorld,+ UIEvents, Transform, Sprite,+ createButton, themeColors, px,+} from 'esengine';+import type {+ Entity, World, Color, ThemeColors, UIEventQueue, SpriteData,+} from 'esengine';++import { game } from '../state';+import {+ SAVE_VERSION, SLOT, saves, peekEnvelope, writeLegacyV1Save,+ loadAltColorPref, saveAltColorPref,+} from '../save';+import type { SaveData } from '../save';++const PLAYER_BLUE: Color = { r: 0.28, g: 0.54, b: 0.92, a: 1 };+const PLAYER_ORANGE: Color = { r: 0.95, g: 0.56, b: 0.2, a: 1 };+const BTN_H = 32;++export const buildSystem = defineSystem(+ [Res(UIEvents), GetWorld()],+ (events: UIEventQueue, world: World) => {+ if (game.built) return;++ const saveRow = world.findEntityByName('SaveRow');+ const prefRow = world.findEntityByName('PrefRow');+ if (saveRow === null || prefRow === null) return;+ game.built = true;++ game.altColor = loadAltColorPref();+ applyPlayerColor(world);++ const c = themeColors();++ button(world, events, saveRow, c, true, 'Save', 96, () => doSave(world));+ button(world, events, saveRow, c, false, 'Load', 96, () => doLoad(world));+ button(world, events, saveRow, c, false, 'Clear', 96, () => {+ saves.remove(SLOT);+ game.status = 'Save cleared.';+ });+ button(world, events, saveRow, c, false, 'Save as v1', 118, () => doLegacySave(world));++ button(world, events, prefRow, c, false, 'Toggle', 96, () => {+ game.altColor = !game.altColor;+ saveAltColorPref(game.altColor);+ applyPlayerColor(world);+ game.status = `Color preference stored: ${game.altColor ? 'orange' : 'blue'}.`;+ });+ },+ { name: 'BuildSystem' },+);++function doSave(world: World): void {+ const pos = playerPosition(world);+ if (pos === null) return;+ const data: SaveData = {+ score: game.score,+ player: pos,+ collected: [...game.collected],+ };+ saves.save(SLOT, data);+ const at = saves.savedAt(SLOT);+ game.status = `Saved v${SAVE_VERSION} at ${new Date(at ?? Date.now()).toLocaleTimeString()}.`;+}++function doLoad(world: World): void {+ const envelope = peekEnvelope();+ const data = saves.load<SaveData>(SLOT);+ if (data === null || envelope === undefined) {+ game.status = 'No save found.';+ return;+ }++ game.score = data.score;+ game.collected = new Set(data.collected);+ setPlayerPosition(world, data.player);++ game.status = envelope.version < SAVE_VERSION+ ? `Loaded v${envelope.version} save — migrated to v${SAVE_VERSION}.`+ : `Loaded v${envelope.version} save.`;+}++function doLegacySave(world: World): void {+ const pos = playerPosition(world);+ if (pos === null) return;+ writeLegacyV1Save({ points: game.score, playerX: pos.x, playerY: pos.y });+ game.status = 'Wrote a legacy v1 save — press Load to migrate it.';+}++function playerPosition(world: World): { x: number; y: number } | null {+ const player = world.findEntityByName('Player');+ if (player === null || !world.has(player, Transform)) return null;+ const t = world.get(player, Transform);+ return { x: t.position.x, y: t.position.y };+}++function setPlayerPosition(world: World, pos: { x: number; y: number }): void {+ const player = world.findEntityByName('Player');+ if (player === null || !world.has(player, Transform)) return;+ const t = world.get(player, Transform);+ t.position.x = pos.x;+ t.position.y = pos.y;+ world.insert(player, Transform, t);+}++function applyPlayerColor(world: World): void {+ const player = world.findEntityByName('Player');+ if (player === null || !world.has(player, Sprite)) return;+ const s = world.get(player, Sprite) as SpriteData;+ s.color = { ...(game.altColor ? PLAYER_ORANGE : PLAYER_BLUE) };+ world.insert(player, Sprite, s);+}++function button(+ world: World, events: UIEventQueue, parent: Entity, c: ThemeColors,+ primary: boolean, label: string, width: number, onClick: () => void,+): void {+ const states = primary+ ? { normal: { color: c.primary }, hover: { color: c.primaryHover }, pressed: { color: c.primaryActive } }+ : { normal: { color: c.control }, hover: { color: c.controlHover }, pressed: { color: c.controlActive } };+ createButton({+ world, events, parent,+ node: { width: px(width), height: px(BTN_H) },+ states,+ text: { content: label, color: c.onPrimary, fontSize: 14 },+ onClick,+ });+}diff --git a/examples/save-load/src/systems/coins.ts b/examples/save-load/src/systems/coins.tsnew file mode 100644index 000000000..a90cedf27--- /dev/null+++ b/examples/save-load/src/systems/coins.ts@@ -0,0 +1,70 @@+import {+ defineSystem, Query, Mut, Res, Commands,+ Transform, Sprite, Time,+} from 'esengine';+import { Coin, Player } from '../components';+import { game, COIN_SPOTS } from '../state';++const COIN_SIZE = 24;+const PICKUP_DIST = 34;+const COIN_POINTS = 10;++// Coin entities are a pure projection of `game.collected`: spots not yet+// collected get an entity, collected ones lose theirs. Load/Clear only mutate+// the state and this system reconciles the world — no special respawn paths.+export const coinSyncSystem = defineSystem(+ [Query(Coin), Commands()],+ (coins, cmds) => {+ const present = new Set<number>();+ for (const [entity, coin] of coins) {+ if (game.collected.has(coin.index)) cmds.despawn(entity);+ else present.add(coin.index);+ }++ COIN_SPOTS.forEach((spot, index) => {+ if (game.collected.has(index) || present.has(index)) return;+ cmds.spawn()+ .insert(Transform, { position: { x: spot.x, y: spot.y, z: 0 } })+ .insert(Sprite, {+ size: { x: COIN_SIZE, y: COIN_SIZE },+ color: { r: 0.98, g: 0.8, b: 0.2, a: 1 },+ })+ .insert(Coin, { index, phase: index * 0.7 });+ });+ },+ { name: 'CoinSyncSystem' }+);++export const coinCollectSystem = defineSystem(+ [Query(Transform, Player), Query(Transform, Coin)],+ (players, coins) => {+ for (const [_player, playerTf] of players) {+ for (const [_coin, coinTf, coin] of coins) {+ if (game.collected.has(coin.index)) continue;+ const dx = playerTf.position.x - coinTf.position.x;+ const dy = playerTf.position.y - coinTf.position.y;+ if (dx * dx + dy * dy > PICKUP_DIST * PICKUP_DIST) continue;++ game.collected.add(coin.index);+ game.score += COIN_POINTS;+ game.status = game.collected.size === COIN_SPOTS.length+ ? 'All coins collected — Save, then Clear or reload to compare.'+ : `Collected ${game.collected.size}/${COIN_SPOTS.length} coins.`;+ }+ }+ },+ { name: 'CoinCollectSystem' }+);++export const coinPulseSystem = defineSystem(+ [Query(Mut(Transform), Mut(Coin)), Res(Time)],+ (coins, time) => {+ for (const [_entity, transform, coin] of coins) {+ coin.phase += time.delta * 4;+ const s = 1 + 0.12 * Math.sin(coin.phase);+ transform.scale.x = s;+ transform.scale.y = s;+ }+ },+ { name: 'CoinPulseSystem' }+);diff --git a/examples/save-load/src/systems/hud.ts b/examples/save-load/src/systems/hud.tsnew file mode 100644index 000000000..8381eff5d--- /dev/null+++ b/examples/save-load/src/systems/hud.ts@@ -0,0 +1,27 @@+import { defineSystem, GetWorld, Text } from 'esengine';+import type { World, Entity, TextData } from 'esengine';+import { game } from '../state';++let lastScore = '';+let lastStatus = '';++export const hudSystem = defineSystem(+ [GetWorld()],+ (world: World) => {+ const score = `Score: ${game.score}`;+ if (score !== lastScore && setLabel(world, 'ScoreLabel', score)) lastScore = score;+ if (game.status !== lastStatus && setLabel(world, 'StatusLabel', game.status)) {+ lastStatus = game.status;+ }+ },+ { name: 'HudSystem' }+);++function setLabel(world: World, name: string, content: string): boolean {+ const entity: Entity | null = world.findEntityByName(name);+ if (entity === null || !world.has(entity, Text)) return false;+ const t = world.get(entity, Text) as TextData;+ t.content = content;+ world.insert(entity, Text, t);+ return true;+}diff --git a/examples/save-load/src/systems/move.ts b/examples/save-load/src/systems/move.tsnew file mode 100644index 000000000..bb21d923d--- /dev/null+++ b/examples/save-load/src/systems/move.ts@@ -0,0 +1,37 @@+import {+ defineSystem, Query, Mut, Res,+ Transform, Input, Time,+} from 'esengine';+import { Player } from '../components';++const X_BOUND = 380;+const Y_MIN = -280;+const Y_MAX = 60;++export const moveSystem = defineSystem(+ [Res(Input), Res(Time), Query(Mut(Transform), Player)],+ (input, time, query) => {+ for (const [_entity, transform, player] of query) {+ let dx = 0;+ let dy = 0;++ if (input.isKeyDown('ArrowLeft') || input.isKeyDown('KeyA')) dx -= 1;+ if (input.isKeyDown('ArrowRight') || input.isKeyDown('KeyD')) dx += 1;+ if (input.isKeyDown('ArrowUp') || input.isKeyDown('KeyW')) dy += 1;+ if (input.isKeyDown('ArrowDown') || input.isKeyDown('KeyS')) dy -= 1;++ if (dx !== 0 && dy !== 0) {+ const inv = 1 / Math.SQRT2;+ dx *= inv;+ dy *= inv;+ }++ transform.position.x += dx * player.speed * time.delta;+ transform.position.y += dy * player.speed * time.delta;++ transform.position.x = Math.max(-X_BOUND, Math.min(X_BOUND, transform.position.x));+ transform.position.y = Math.max(Y_MIN, Math.min(Y_MAX, transform.position.y));+ }+ },+ { name: 'MoveSystem' }+);diff --git a/examples/save-load/tsconfig.json b/examples/save-load/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/save-load/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}diff --git a/examples/scene-flow/.gitignore b/examples/scene-flow/.gitignorenew file mode 100644index 000000000..359472ac2--- /dev/null+++ b/examples/scene-flow/.gitignore@@ -0,0 +1,7 @@+node_modules/+dist/+.vscode/+.idea/+.DS_Store+Thumbs.db+.esengine/cache/diff --git a/examples/scene-flow/README.md b/examples/scene-flow/README.mdnew file mode 100644index 000000000..444d86077--- /dev/null+++ b/examples/scene-flow/README.md@@ -0,0 +1,110 @@+# Scene Flow++Runtime multi-scene flow: a **menu**, **level 1** and **level 2** cycling+through `SceneManager` with a fade on every hop. Every other example lives in a+single scene; this one is about the machinery that takes a shipped game from+its title screen into (and between) levels.++Press Play: the menu appears over the shell backdrop. **Start** fades to+level 1 (black, 0.6 s), **Next level** fades to level 2 (white, 0.9 s),+**Back to menu** fades home (deep blue, 1.2 s). The footer at the bottom never+flinches — it belongs to the shell scene that survives every swap.++## How the scenes are addressed++The three flow scenes are **code-built `SceneConfig`s registered on+`SceneManager`**, not extra `.esscene` files. That is a deliberate choice:++- In the editor's Play realm only the **entry** `.esscene` is registered with+ the SceneManager (as the running snapshot). Sibling scene files are not+ switch targets there, so a `.esscene`-addressed flow could not be verified by+ pressing Play.+- In an **exported build** every cooked scene *is* registered by name (see+ `game.config.json` → `scenes`), and `switchTo('name')` lazily fetches it —+ that path exists, but it only kicks in after an export.+- Code-registered scenes behave identically in every realm — editor Play,+ exported web build, WeChat — and entities spawned through the scene's+ `SceneContext` are tracked, so unloading a scene despawns everything it+ created (whole widget subtrees included) with zero cleanup code.++The authored `main.esscene` stays loaded for the entire session as a+**persistent shell**: camera, backdrop, the UI `Canvas` and the footer label.+Flow scenes parent their UI under that Canvas and are swapped in and out above+it.++## Registration and the first load++```ts+export const registerScenesSystem = defineSystem(+ [Res(SceneManager), Res(UIEvents), GetWorld()],+ (scenes, events, world) => {+ scenes.register(menuScene(world, events, scenes)); // SceneConfig { name, setup, systems? }+ scenes.register(level1Scene(world, events, scenes));+ scenes.register(level2Scene(world, events, scenes));+ void scenes.load(SCENES.menu);+ },+ { name: 'RegisterScenesSystem' },+);+```++A `SceneConfig` names the scene and provides either `data`/`path` (serialized+scene JSON) or a `setup(ctx)` callback that builds entities in code. `ctx` is+the scene's `SceneContext`: `ctx.spawn()` creates an entity **owned by the+scene** — SceneManager despawns it (and its subtree) when the scene unloads.+`SceneConfig.systems` registers scene-scoped systems: here `bobSystem` is+installed when a level loads, only runs while that scene's status is+`running`, and is removed on unload — it never appears in `main.ts`.++## `load` vs `transitionTo` / `switchTo`++- **`load(name)`** brings a scene in and makes it active **without unloading+ anything**. The startup system uses it for the first hop so the shell scene+ stays resident underneath. (`loadAdditive` is the variant that keeps the+ current scene active too.)+- **`switchTo(name, options)`** unloads the currently active scene, then loads+ the target — optionally through a fade. This is what every button here calls.+- **`transitionTo(host, name, config)`** is the convenience wrapper over+ `switchTo`. It accepts either the `App` (host/embedding code — the thing+ that called `createWebApp`) or the SceneManager resource state, so systems+ can call it with what `Res(SceneManager)` gives them:++```ts+// host code, with an App in hand:+await transitionTo(app, 'level-1', { type: 'fade', duration: 0.6, color: { r: 0, g: 0, b: 0, a: 1 } });++// inside a system (this example's goTo helper) — identical semantics:+void transitionTo(scenes, 'level-1', { type: 'fade', duration: 0.6, color: { r: 0, g: 0, b: 0, a: 1 } });+```++A switch requested while a transition is already in flight is ignored (with a+console warning), so mashing a button during a fade is harmless.++## TransitionConfig++| Field | Type | Meaning |+| ---------- | -------- | ------------------------------------------------------------------------------------------------ |+| `type` | `'fade'` | Transition kind. Fade is the built-in: overlay ramps to opaque, scenes swap, overlay ramps clear. |+| `duration` | `number` | Total seconds — half fading out, half fading in. The opaque hold stretches if the load is slower. |+| `color` | `Color?` | Overlay color. Defaults to black (`RuntimeConfig.sceneTransitionColor`). |++The three hops each use a different config (`src/flow.ts`) so all the options+are visible in one run: `0.6 s` black, `0.9 s` white, `1.2 s` deep blue.++## Files++```+assets/+ scenes/main.esscene # persistent shell: camera, backdrop, Canvas, footer+src/+ main.ts # registers the startup system+ components.ts # Bobber (platform motion)+ flow.ts # scene names, one TransitionConfig per hop, goTo helper+ scenes/+ build.ts # ctx-tracked UI root under the shell Canvas; platform/heading builders+ menu.ts # title + Start button+ level1.ts # green/blue platforms + Next level button+ level2.ts # orange/purple platforms + Back to menu button+ systems/+ register.ts # startup: register all scenes, load the menu+ bob.ts # scene-scoped platform bobbing (SceneConfig.systems)+```diff --git a/examples/scene-flow/assets/scenes/main.esscene b/examples/scene-flow/assets/scenes/main.esscenenew file mode 100644index 000000000..7e04e6fd8--- /dev/null+++ b/examples/scene-flow/assets/scenes/main.esscene@@ -0,0 +1,106 @@+{+ "version": "1.0",+ "name": "Main",+ "entities": [+ {+ "id": 0,+ "name": "Camera",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": { "x": 0, "y": 0, "z": 10 }+ }+ },+ {+ "type": "Camera",+ "data": {+ "projectionType": 1,+ "orthoSize": 300,+ "isActive": true,+ "priority": 0+ }+ }+ ],+ "visible": true+ },+ {+ "id": 1,+ "name": "Backdrop",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": { "position": { "x": 0, "y": 0, "z": -5 } }+ },+ {+ "type": "Sprite",+ "data": {+ "size": { "x": 820, "y": 620 },+ "color": { "r": 0.07, "g": 0.08, "b": 0.1, "a": 1 }+ }+ }+ ],+ "visible": true+ },+ {+ "id": 2,+ "name": "Canvas",+ "parent": null,+ "children": [+ 3+ ],+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Canvas",+ "data": {+ "designResolution": { "x": 800, "y": 600 },+ "scaleMode": 2+ }+ },+ {+ "type": "UINode",+ "data": {}+ }+ ],+ "visible": true+ },+ {+ "id": 3,+ "name": "ShellFooter",+ "parent": 2,+ "children": [],+ "components": [+ { "type": "Transform", "data": {} },+ {+ "type": "UINode",+ "data": {+ "position": 1,+ "insetLeft": { "value": 0, "unit": 0 },+ "insetRight": { "value": 0, "unit": 0 },+ "insetBottom": { "value": 10, "unit": 0 },+ "height": { "value": 16, "unit": 0 }+ }+ },+ {+ "type": "Text",+ "data": {+ "content": "Shell scene — camera, backdrop and this footer persist across every scene swap",+ "fontSize": 11,+ "color": { "r": 0.55, "g": 0.58, "b": 0.64, "a": 1 },+ "align": 1,+ "verticalAlign": 1+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/examples/scene-flow/assets/scenes/main.esscene.meta b/examples/scene-flow/assets/scenes/main.esscene.metanew file mode 100644index 000000000..739fb8187--- /dev/null+++ b/examples/scene-flow/assets/scenes/main.esscene.meta@@ -0,0 +1,8 @@+{+ "uuid": "54f1c9a2-b767-4df8-85f6-71ae7af1619a",+ "version": "2.0",+ "type": "scene",+ "importer": {+ "autoMigrate": true+ }+}diff --git a/examples/scene-flow/project.esproject b/examples/scene-flow/project.esprojectnew file mode 100644index 000000000..235922617--- /dev/null+++ b/examples/scene-flow/project.esproject@@ -0,0 +1,13 @@+{+ "formatVersion": "1",+ "name": "Scene Flow",+ "description": "Menu → Level 1 → Level 2: runtime scene switching through SceneManager with fade transitions.",+ "tag": "Basics",+ "version": "1.0.0",+ "defaultScene": "assets/scenes/main.esscene",+ "designResolution": {+ "width": 800,+ "height": 600+ },+ "spineVersion": "none"+}diff --git a/examples/scene-flow/src/components.ts b/examples/scene-flow/src/components.tsnew file mode 100644index 000000000..03436b0d4--- /dev/null+++ b/examples/scene-flow/src/components.ts@@ -0,0 +1,8 @@+import { defineComponent } from 'esengine';++export const Bobber = defineComponent('Bobber', {+ baseY: 0,+ amplitude: 8,+ speed: 1.6,+ phase: 0,+});diff --git a/examples/scene-flow/src/flow.ts b/examples/scene-flow/src/flow.tsnew file mode 100644index 000000000..dc5e15c06--- /dev/null+++ b/examples/scene-flow/src/flow.ts@@ -0,0 +1,36 @@+import { transitionTo, type SceneManagerState, type TransitionConfig } from 'esengine';++export const SCENES = {+ menu: 'menu',+ level1: 'level-1',+ level2: 'level-2',+} as const;++// One TransitionConfig per hop, so each demonstrates a different duration/color.+export const FADE_TO_LEVEL_1: TransitionConfig = {+ type: 'fade',+ duration: 0.6,+ color: { r: 0, g: 0, b: 0, a: 1 },+};++export const FADE_TO_LEVEL_2: TransitionConfig = {+ type: 'fade',+ duration: 0.9,+ color: { r: 1, g: 1, b: 1, a: 1 },+};++export const FADE_TO_MENU: TransitionConfig = {+ type: 'fade',+ duration: 1.2,+ color: { r: 0.05, g: 0.07, b: 0.16, a: 1 },+};++/**+ * `transitionTo` accepts the App (host code) or the SceneManager resource state+ * (systems — `Res(SceneManager)`), which is what the button systems hold here.+ * A switch already in flight is ignored by the manager, so double-clicks during+ * a fade are safe.+ */+export function goTo(scenes: SceneManagerState, target: string, fade: TransitionConfig): void {+ void transitionTo(scenes, target, fade);+}diff --git a/examples/scene-flow/src/main.ts b/examples/scene-flow/src/main.tsnew file mode 100644index 000000000..9144f935e--- /dev/null+++ b/examples/scene-flow/src/main.ts@@ -0,0 +1,8 @@+// Scene Flow — runtime multi-scene flow: SceneManager registration, load vs+// switchTo, and fade transitions (menu → level 1 → level 2 → menu).+import { addStartupSystem } from 'esengine';++import './components';+import { registerScenesSystem } from './systems/register';++addStartupSystem(registerScenesSystem);diff --git a/examples/scene-flow/src/scenes/build.ts b/examples/scene-flow/src/scenes/build.tsnew file mode 100644index 000000000..fd0640c95--- /dev/null+++ b/examples/scene-flow/src/scenes/build.ts@@ -0,0 +1,57 @@+// Scene-owned entity builders. Everything a scene creates hangs off entities+// from ctx.spawn(), so SceneManager despawns it all (subtrees included) when+// the scene unloads — no per-scene cleanup code.+import {+ Transform, Sprite, UINode,+ buildUINode, spawnUIEntity, px,+ UIPositionType, TextAlign,+ themeColors,+} from 'esengine';+import type { Color, Entity, SceneContext, ThemeColors, World } from 'esengine';++import { Bobber } from '../components';++/**+ * Scene-owned UI root stretched over the shell's Canvas. Widget factories+ * (createButton, spawnUIEntity) spawn untracked entities, so they must parent+ * under this tracked root — unloading the scene then tears the subtree down.+ */+export function sceneUiRoot(ctx: SceneContext, world: World): Entity {+ const root = ctx.spawn();+ world.insert(root, Transform, {});+ world.insert(root, UINode, buildUINode({ fill: true }));+ const canvas = world.findEntityByName('Canvas');+ if (canvas !== null) world.setParent(root, canvas);+ return root;+}++export function heading(world: World, parent: Entity, content: string): void {+ const c = themeColors();+ spawnUIEntity({+ world, parent,+ node: {+ position: UIPositionType.Absolute,+ insetLeft: px(24), insetTop: px(20),+ width: px(300), height: px(30),+ },+ text: { content, fontSize: 22, bold: true, color: c.text, align: TextAlign.Left },+ });+}++export function platform(+ ctx: SceneContext, world: World,+ x: number, y: number, width: number, color: Color, phase: number,+): void {+ const e = ctx.spawn();+ world.insert(e, Transform, { position: { x, y, z: 0 } });+ world.insert(e, Sprite, { size: { x: width, y: 24 }, color });+ world.insert(e, Bobber, { baseY: y, phase });+}++export function buttonStates(c: ThemeColors): Record<string, { color: Color }> {+ return {+ normal: { color: c.primary },+ hover: { color: c.primaryHover },+ pressed: { color: c.primaryActive },+ };+}diff --git a/examples/scene-flow/src/scenes/level1.ts b/examples/scene-flow/src/scenes/level1.tsnew file mode 100644index 000000000..7910c14db--- /dev/null+++ b/examples/scene-flow/src/scenes/level1.ts@@ -0,0 +1,37 @@+import { createButton, themeColors, px, Schedule, UIPositionType } from 'esengine';+import type { SceneConfig, SceneManagerState, UIEventQueue, World } from 'esengine';++import { SCENES, FADE_TO_LEVEL_2, goTo } from '../flow';+import { bobSystem } from '../systems/bob';+import { sceneUiRoot, heading, platform, buttonStates } from './build';++export function level1Scene(+ world: World, events: UIEventQueue, scenes: SceneManagerState,+): SceneConfig {+ return {+ name: SCENES.level1,+ // Scene-scoped: installed on load, gated to this scene, removed on unload.+ systems: [{ schedule: Schedule.Update, system: bobSystem }],+ setup(ctx) {+ platform(ctx, world, -220, -120, 200, { r: 0.28, g: 0.72, b: 0.42, a: 1 }, 0.0);+ platform(ctx, world, 0, -40, 160, { r: 0.24, g: 0.58, b: 0.86, a: 1 }, 1.1);+ platform(ctx, world, 210, 40, 180, { r: 0.28, g: 0.72, b: 0.42, a: 1 }, 2.2);+ platform(ctx, world, -60, 130, 140, { r: 0.24, g: 0.58, b: 0.86, a: 1 }, 3.3);++ const c = themeColors();+ const root = sceneUiRoot(ctx, world);+ heading(world, root, 'Level 1');+ createButton({+ world, events, parent: root,+ node: {+ position: UIPositionType.Absolute,+ width: px(160), height: px(42),+ insetRight: px(24), insetBottom: px(40),+ },+ states: buttonStates(c),+ text: { content: 'Next level', fontSize: 15, color: c.onPrimary },+ onClick: () => goTo(scenes, SCENES.level2, FADE_TO_LEVEL_2),+ });+ },+ };+}diff --git a/examples/scene-flow/src/scenes/level2.ts b/examples/scene-flow/src/scenes/level2.tsnew file mode 100644index 000000000..ad6f52568--- /dev/null+++ b/examples/scene-flow/src/scenes/level2.ts@@ -0,0 +1,37 @@+import { createButton, themeColors, px, Schedule, UIPositionType } from 'esengine';+import type { SceneConfig, SceneManagerState, UIEventQueue, World } from 'esengine';++import { SCENES, FADE_TO_MENU, goTo } from '../flow';+import { bobSystem } from '../systems/bob';+import { sceneUiRoot, heading, platform, buttonStates } from './build';++export function level2Scene(+ world: World, events: UIEventQueue, scenes: SceneManagerState,+): SceneConfig {+ return {+ name: SCENES.level2,+ systems: [{ schedule: Schedule.Update, system: bobSystem }],+ setup(ctx) {+ platform(ctx, world, -240, 60, 150, { r: 0.85, g: 0.45, b: 0.25, a: 1 }, 0.0);+ platform(ctx, world, -80, -90, 190, { r: 0.68, g: 0.36, b: 0.85, a: 1 }, 0.9);+ platform(ctx, world, 120, 20, 130, { r: 0.85, g: 0.45, b: 0.25, a: 1 }, 1.8);+ platform(ctx, world, 250, -140, 170, { r: 0.68, g: 0.36, b: 0.85, a: 1 }, 2.7);+ platform(ctx, world, 40, 160, 150, { r: 0.86, g: 0.68, b: 0.28, a: 1 }, 3.6);++ const c = themeColors();+ const root = sceneUiRoot(ctx, world);+ heading(world, root, 'Level 2');+ createButton({+ world, events, parent: root,+ node: {+ position: UIPositionType.Absolute,+ width: px(180), height: px(42),+ insetRight: px(24), insetBottom: px(40),+ },+ states: buttonStates(c),+ text: { content: 'Back to menu', fontSize: 15, color: c.onPrimary },+ onClick: () => goTo(scenes, SCENES.menu, FADE_TO_MENU),+ });+ },+ };+}diff --git a/examples/scene-flow/src/scenes/menu.ts b/examples/scene-flow/src/scenes/menu.tsnew file mode 100644index 000000000..73abb480a--- /dev/null+++ b/examples/scene-flow/src/scenes/menu.ts@@ -0,0 +1,55 @@+import {+ createButton, spawnUIEntity, themeColors, px, percent, UIPositionType,+} from 'esengine';+import type { SceneConfig, SceneManagerState, UIEventQueue, World } from 'esengine';++import { SCENES, FADE_TO_LEVEL_1, goTo } from '../flow';+import { sceneUiRoot, buttonStates } from './build';++export function menuScene(+ world: World, events: UIEventQueue, scenes: SceneManagerState,+): SceneConfig {+ return {+ name: SCENES.menu,+ setup(ctx) {+ const c = themeColors();+ const root = sceneUiRoot(ctx, world);++ spawnUIEntity({+ world, parent: root,+ node: {+ position: UIPositionType.Absolute,+ insetLeft: px(0), insetRight: px(0),+ insetTop: percent(26), height: px(44),+ },+ text: { content: 'SCENE FLOW', fontSize: 36, bold: true, color: c.text },+ });+ spawnUIEntity({+ world, parent: root,+ node: {+ position: UIPositionType.Absolute,+ insetLeft: px(0), insetRight: px(0),+ insetTop: percent(26), marginTop: px(52), height: px(20),+ },+ text: {+ content: 'SceneManager + fade transitions',+ fontSize: 13,+ color: { ...c.text, a: 0.6 },+ },+ });++ createButton({+ world, events, parent: root,+ node: {+ position: UIPositionType.Absolute,+ width: px(180), height: px(46),+ insetLeft: percent(50), marginLeft: px(-90),+ insetTop: percent(55),+ },+ states: buttonStates(c),+ text: { content: 'Start', fontSize: 16, color: c.onPrimary },+ onClick: () => goTo(scenes, SCENES.level1, FADE_TO_LEVEL_1),+ });+ },+ };+}diff --git a/examples/scene-flow/src/systems/bob.ts b/examples/scene-flow/src/systems/bob.tsnew file mode 100644index 000000000..64514bcc1--- /dev/null+++ b/examples/scene-flow/src/systems/bob.ts@@ -0,0 +1,16 @@+import { defineSystem, Query, Mut, Res, Time, Transform } from 'esengine';+import { Bobber } from '../components';++// Registered through SceneConfig.systems, not main.ts: SceneManager installs it+// when a level loads, gates it to that scene's 'running' status, and removes it+// again on unload.+export const bobSystem = defineSystem(+ [Query(Mut(Transform), Bobber), Res(Time)],+ (query, time) => {+ for (const [_entity, transform, bob] of query) {+ transform.position.y =+ bob.baseY + Math.sin(time.elapsed * bob.speed + bob.phase) * bob.amplitude;+ }+ },+ { name: 'BobSystem' },+);diff --git a/examples/scene-flow/src/systems/register.ts b/examples/scene-flow/src/systems/register.tsnew file mode 100644index 000000000..20d8168ef--- /dev/null+++ b/examples/scene-flow/src/systems/register.ts@@ -0,0 +1,25 @@+import { defineSystem, Res, GetWorld, SceneManager, UIEvents } from 'esengine';+import type { SceneManagerState, UIEventQueue, World } from 'esengine';++import { SCENES } from '../flow';+import { menuScene } from '../scenes/menu';+import { level1Scene } from '../scenes/level1';+import { level2Scene } from '../scenes/level2';++// Registers every scene the game can switch to, then loads the menu. The+// authored .esscene stays loaded underneath as a persistent shell (camera,+// backdrop, Canvas) — plain load() makes 'menu' the active scene without+// unloading it; from then on every hop is a switchTo with a fade.+export const registerScenesSystem = defineSystem(+ [Res(SceneManager), Res(UIEvents), GetWorld()],+ (scenes: SceneManagerState, events: UIEventQueue, world: World) => {+ if (scenes.isLoaded(SCENES.menu)) return;++ scenes.register(menuScene(world, events, scenes));+ scenes.register(level1Scene(world, events, scenes));+ scenes.register(level2Scene(world, events, scenes));++ void scenes.load(SCENES.menu);+ },+ { name: 'RegisterScenesSystem' },+);diff --git a/examples/scene-flow/tsconfig.json b/examples/scene-flow/tsconfig.jsonnew file mode 100644index 000000000..0a8528b29--- /dev/null+++ b/examples/scene-flow/tsconfig.json@@ -0,0 +1,22 @@+{+ "compilerOptions": {+ "target": "ES2020",+ "module": "ESNext",+ "moduleResolution": "bundler",+ "strict": true,+ "esModuleInterop": true,+ "skipLibCheck": true,+ "forceConsistentCasingInFileNames": true,+ "declaration": false,+ "outDir": "./dist",+ "rootDir": ".",+ "baseUrl": ".",+ "paths": {+ "esengine": ["./.esengine/sdk/index.d.ts"],+ "esengine/wasm": ["./.esengine/sdk/wasm.d.ts"],+ "@esengine/editor": ["./.esengine/editor/index.d.ts"]+ }+ },+ "include": ["src/**/*"],+ "exclude": ["node_modules"]+}