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(input): interactive rebinding + binding persistence on InputMap
esenginedf3cbb0c45fe
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.tsindex b99362e7c..7905ce499 100644--- a/sdk/src/core-runtime.ts+++ b/sdk/src/core-runtime.ts@@ -200,6 +200,7 @@ export {type Binding,type ActionDef,type ActionType,+ type ListenOptions,} from './inputMap';// =============================================================================diff --git a/sdk/src/inputMap.ts b/sdk/src/inputMap.tsindex ac6a3cf8b..c8530d5ee 100644--- a/sdk/src/inputMap.ts+++ b/sdk/src/inputMap.ts@@ -14,7 +14,8 @@*/import { Schedule, defineSystem, addSystemToSchedule } from './system';import { Res } from './resource';-import { Input, InputState, GamepadAxis } from './input';+import { Input, InputState, GamepadAxis, GamepadButton } from './input';+import { Storage } from './storage';// =============================================================================// Binding model (plain, serializable — also the rebind / persistence format)@@ -105,9 +106,23 @@ const clamp = (v: number, lo: number, hi: number): number => (v < lo ? lo : v >// InputMap// =============================================================================+/** Which device families an interactive rebind listens to. Mouse is OFF by+ * default (so the click that started the rebind isn't captured). */+export interface ListenOptions {+ keyboard?: boolean;+ mouse?: boolean;+ gamepad?: boolean;+}++interface PendingListen {+ resolve: (binding: Binding | null) => void;+ opts: ListenOptions;+}+export class InputMap {private readonly defs_ = new Map<string, ActionDef>();private readonly state_ = new Map<string, ActionState>();+ private pendingListen_: PendingListen | null = null;constructor(actions: Record<string, ActionDef>) {for (const [name, def] of Object.entries(actions)) {@@ -119,6 +134,7 @@ export class InputMap {/** Recompute every action from the current raw input. Called once per frame by* the registered evaluation system; edges (pressed/released) diff vs last frame. */evaluate(input: InputState): void {+ if (this.pendingListen_) this.scanForRebind_(input);for (const [name, def] of this.defs_) {const st = this.state_.get(name)!;const prevDown = st.down;@@ -179,6 +195,67 @@ export class InputMap {if (this.defs_.has(name) && Array.isArray(bindings)) this.setBindings(name, bindings);}}++ // — Persistence (platform Storage) —+ /** Save current bindings under `key`. */+ save(key: string): void { Storage.setJSON(key, this.toJSON()); }+ /** Apply bindings previously {@link save}d under `key`; returns true if found. */+ load(key: string): boolean {+ const data = Storage.getJSON<Record<string, Binding[]>>(key);+ if (!data) return false;+ this.loadJSON(data);+ return true;+ }++ // — Interactive rebinding ("press any input") —+ /** Resolve with the next physical input the user presses (or null if cancelled /+ * superseded by another listen). Drives a rebind UI — the evaluation system+ * feeds it each frame, so the map must be installed and the app running. */+ listenForBinding(opts?: ListenOptions): Promise<Binding | null> {+ this.cancelListen();+ return new Promise((resolve) => { this.pendingListen_ = { resolve, opts: opts ?? {} }; });+ }+ /** Capture the next input and (re)bind it to `name` (replaces, or appends when `append`). */+ async rebind(name: string, opts?: ListenOptions & { append?: boolean }): Promise<Binding | null> {+ const b = await this.listenForBinding(opts);+ if (b) this.setBindings(name, opts?.append ? [...this.getBindings(name), b] : [b]);+ return b;+ }+ /** Cancel a pending {@link listenForBinding} (resolves it with null). */+ cancelListen(): void {+ const p = this.pendingListen_;+ if (p) { this.pendingListen_ = null; p.resolve(null); }+ }+ isListening(): boolean { return this.pendingListen_ !== null; }++ private scanForRebind_(input: InputState): void {+ const found = this.scanBinding_(input, this.pendingListen_!.opts);+ if (found) {+ const p = this.pendingListen_!;+ this.pendingListen_ = null;+ p.resolve(found);+ }+ }++ /** First newly-pressed input this frame, as a Binding (keyboard + gamepad by+ * default; mouse opt-in). Axis sources aren't captured — rebinding targets+ * discrete inputs. */+ private scanBinding_(input: InputState, opts: ListenOptions): Binding | null {+ if (opts.keyboard !== false) {+ for (const code of input.keysPressed) return Key(code);+ }+ if (opts.mouse) {+ for (const button of input.mouseButtonsPressed) return MouseButton(button);+ }+ if (opts.gamepad !== false) {+ for (const pad of input.getGamepads()) {+ for (let b = 0; b <= GamepadButton.Guide; b++) {+ if (input.isGamepadButtonPressed(b, pad)) return GpButton(b, pad);+ }+ }+ }+ return null;+ }}/**diff --git a/sdk/tests/input-map-rebind.test.ts b/sdk/tests/input-map-rebind.test.tsnew file mode 100644index 000000000..a17564034--- /dev/null+++ b/sdk/tests/input-map-rebind.test.ts@@ -0,0 +1,99 @@+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import { describe, it, expect, beforeAll } from 'vitest';+import { InputState, GamepadButton } from '../src/input';+import { InputMap, Button, Key } from '../src/inputMap';+import type { GamepadSnapshot, PlatformAdapter } from '../src/platform/types';+import { setPlatform } from '../src/platform/base';++// save/load goes through the platform Storage; unit tests don't boot a real+// platform (that happens when importing "esengine"), so install an in-memory one.+beforeAll(() => {+ const mem = new Map<string, string>();+ setPlatform({+ getStorageItem: (k: string) => mem.get(k) ?? null,+ setStorageItem: (k: string, v: string) => { mem.set(k, v); },+ removeStorageItem: (k: string) => { mem.delete(k); },+ } as unknown as PlatformAdapter);+});++function padButtons(...pressed: number[]): GamepadSnapshot {+ const buttons = new Array(17).fill(0);+ for (const b of pressed) buttons[b] = 1;+ return { index: 0, connected: true, buttons, axes: new Array(4).fill(0), mapping: 'standard' };+}++describe('InputMap interactive rebind', () => {+ it('listenForBinding resolves on the next key press', async () => {+ const map = new InputMap({ Jump: Button(Key('Space')) });+ const input = new InputState();+ const p = map.listenForBinding();+ expect(map.isListening()).toBe(true);++ input.keysPressed.add('KeyJ');+ map.evaluate(input);++ expect(await p).toEqual({ kind: 'key', code: 'KeyJ' });+ expect(map.isListening()).toBe(false);+ });++ it('rebind captures and replaces the action binding', async () => {+ const map = new InputMap({ Jump: Button(Key('Space')) });+ const input = new InputState();+ const p = map.rebind('Jump');+ input.keysPressed.add('KeyK');+ map.evaluate(input);+ await p;++ expect(map.getBindings('Jump')).toEqual([{ kind: 'key', code: 'KeyK' }]);++ const i2 = new InputState();+ i2.keysDown.add('KeyK');+ map.evaluate(i2);+ expect(map.down('Jump')).toBe(true); // new binding live+ });++ it('captures a gamepad button when keyboard yields nothing', async () => {+ const map = new InputMap({ Fire: Button(Key('Space')) });+ const input = new InputState();+ const p = map.listenForBinding();+ input.updateGamepads([padButtons(GamepadButton.East)]); // pressed edge (prev was empty)+ map.evaluate(input);+ expect(await p).toEqual({ kind: 'gpButton', button: GamepadButton.East, pad: 0 });+ });++ it('cancelListen resolves null and a new listen supersedes the old', async () => {+ const map = new InputMap({ Jump: Button(Key('Space')) });+ const first = map.listenForBinding();+ const second = map.listenForBinding(); // supersedes first → first resolves null+ expect(await first).toBeNull();+ map.cancelListen();+ expect(await second).toBeNull();+ expect(map.isListening()).toBe(false);+ });++ it('ignores mouse unless opted in', async () => {+ const map = new InputMap({ X: Button(Key('Space')) });+ const input = new InputState();+ const p = map.listenForBinding(); // mouse off by default+ input.mouseButtonsPressed.add(0);+ map.evaluate(input);+ expect(map.isListening()).toBe(true); // not captured++ input.keysPressed.add('KeyM');+ map.evaluate(input);+ expect(await p).toEqual({ kind: 'key', code: 'KeyM' });+ });++ it('persists bindings through save / load', () => {+ const a = new InputMap({ Jump: Button(Key('Space')) });+ a.setBindings('Jump', [Key('KeyP')]);+ a.save('test-inputmap-persist');++ const b = new InputMap({ Jump: Button(Key('Space')) });+ expect(b.load('test-inputmap-persist')).toBe(true);+ expect(b.getBindings('Jump')).toEqual([{ kind: 'key', code: 'KeyP' }]);++ expect(new InputMap({ Jump: Button(Key('Space')) }).load('test-inputmap-absent-key')).toBe(false);+ });+});