Skip to content

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

feat(input): gamepad support + named-action input map (defineInputMap)

esengine812998e667aa
diff --git a/sdk/src/core-runtime.ts b/sdk/src/core-runtime.ts
index 9f8c805fe..b99362e7c 100644
--- a/sdk/src/core-runtime.ts
+++ b/sdk/src/core-runtime.ts
@@ -164,9 +164,13 @@ export {
InputState,
InputPlugin,
inputPlugin,
+ GamepadButton,
+ GamepadAxis,
type TouchPoint,
} from './input';
+export type { GamepadSnapshot } from './platform/types';
+
export {
InputRouter,
inputRouter,
@@ -176,6 +180,28 @@ export {
export { GestureDetector, type SwipeDirection } from './gesture';
+// =============================================================================
+// Input Map (named actions — UE Enhanced Input / Unity Input System analog)
+// =============================================================================
+
+export {
+ defineInputMap,
+ InputMap,
+ Key,
+ MouseButton,
+ GpButton,
+ GpAxis,
+ Keys1D,
+ Keys2D,
+ Stick,
+ Button,
+ Axis1D,
+ Axis2D,
+ type Binding,
+ type ActionDef,
+ type ActionType,
+} from './inputMap';
+
// =============================================================================
// Query
// =============================================================================
diff --git a/sdk/src/input.ts b/sdk/src/input.ts
index 558434e6d..f0c0fd804 100644
--- a/sdk/src/input.ts
+++ b/sdk/src/input.ts
@@ -4,6 +4,7 @@ import { defineResource } from './resource';
import { defineSystem, Schedule } from './system';
import type { App, Plugin } from './app';
import { getPlatform } from './platform';
+import type { GamepadSnapshot } from './platform/types';
import { inputRouter } from './inputRouter';
export interface TouchPoint {
@@ -12,6 +13,47 @@ export interface TouchPoint {
y: number;
}
+/**
+ * Standard-mapping gamepad buttons (W3C "standard gamepad"). Positional names
+ * (SDL / Steam Input convention) avoid device assumptions; Xbox / PlayStation
+ * face labels are noted for reference.
+ */
+export enum GamepadButton {
+ South = 0, // A (Xbox) · Cross (PS)
+ East = 1, // B · Circle
+ West = 2, // X · Square
+ North = 3, // Y · Triangle
+ LeftBumper = 4, // LB · L1
+ RightBumper = 5, // RB · R1
+ LeftTrigger = 6, // LT · L2 (analog)
+ RightTrigger = 7, // RT · R2 (analog)
+ Back = 8, // View · Select / Share
+ Start = 9, // Menu · Options
+ LeftStick = 10, // L3 (stick click)
+ RightStick = 11, // R3
+ DpadUp = 12,
+ DpadDown = 13,
+ DpadLeft = 14,
+ DpadRight = 15,
+ Guide = 16, // Xbox · PS · Home
+}
+
+/** Standard-mapping gamepad axes (signed, [-1,1]). */
+export enum GamepadAxis {
+ LeftX = 0,
+ LeftY = 1,
+ RightX = 2,
+ RightY = 3,
+}
+
+/** @internal Per-gamepad runtime state — current + previous frame, for edges. */
+interface PadState {
+ connected: boolean;
+ buttons: number[];
+ prevButtons: number[];
+ axes: number[];
+}
+
export class InputState {
keysDown = new Set<string>();
keysPressed = new Set<string>();
@@ -76,6 +118,79 @@ export class InputState {
return this.touches.has(id);
}
+ // — Gamepad (polled each frame; edges via current/prev diff, not events) —
+ /** Per-index pad state; an index persists across disconnect so a reconnect resumes. */
+ gamepads = new Map<number, PadState>();
+ /** Analog buttons (e.g. triggers) count as "down" at/above this value. */
+ gamepadButtonThreshold = 0.5;
+ /** Axis magnitudes below this read as 0 (rest-position stick jitter). */
+ gamepadDeadzone = 0.15;
+
+ /** Indices of currently-connected gamepads. */
+ getGamepads(): number[] {
+ const out: number[] = [];
+ for (const [i, p] of this.gamepads) if (p.connected) out.push(i);
+ return out;
+ }
+
+ isGamepadConnected(pad = 0): boolean {
+ return this.gamepads.get(pad)?.connected ?? false;
+ }
+
+ isGamepadButtonDown(button: number, pad = 0): boolean {
+ const p = this.connectedPad_(pad);
+ return !!p && (p.buttons[button] ?? 0) >= this.gamepadButtonThreshold;
+ }
+
+ isGamepadButtonPressed(button: number, pad = 0): boolean {
+ const p = this.connectedPad_(pad);
+ if (!p) return false;
+ const t = this.gamepadButtonThreshold;
+ return (p.buttons[button] ?? 0) >= t && (p.prevButtons[button] ?? 0) < t;
+ }
+
+ isGamepadButtonReleased(button: number, pad = 0): boolean {
+ const p = this.connectedPad_(pad);
+ if (!p) return false;
+ const t = this.gamepadButtonThreshold;
+ return (p.buttons[button] ?? 0) < t && (p.prevButtons[button] ?? 0) >= t;
+ }
+
+ /** Raw analog value of a button in [0,1] (triggers; 0/1 for digital buttons). */
+ getGamepadButtonValue(button: number, pad = 0): number {
+ return this.connectedPad_(pad)?.buttons[button] ?? 0;
+ }
+
+ /** Signed axis value in [-1,1], with the deadzone applied. */
+ getGamepadAxis(axis: number, pad = 0): number {
+ const p = this.connectedPad_(pad);
+ if (!p) return 0;
+ const v = p.axes[axis] ?? 0;
+ return Math.abs(v) < this.gamepadDeadzone ? 0 : v;
+ }
+
+ private connectedPad_(pad: number): PadState | undefined {
+ const p = this.gamepads.get(pad);
+ return p?.connected ? p : undefined;
+ }
+
+ /** Ingest this frame's snapshots: shift current→prev (edge detection) then
+ * store new values. Pads absent from `snapshots` are marked disconnected. */
+ updateGamepads(snapshots: GamepadSnapshot[]): void {
+ for (const p of this.gamepads.values()) p.connected = false;
+ for (const snap of snapshots) {
+ let p = this.gamepads.get(snap.index);
+ if (!p) {
+ p = { connected: true, buttons: [], prevButtons: [], axes: [] };
+ this.gamepads.set(snap.index, p);
+ }
+ p.prevButtons = p.buttons;
+ p.buttons = snap.buttons;
+ p.axes = snap.axes;
+ p.connected = snap.connected;
+ }
+ }
+
clearFrameState(): void {
this.keysPressed.clear();
this.keysReleased.clear();
@@ -170,6 +285,17 @@ export class InputPlugin implements Plugin {
},
}, this.target_ ?? undefined);
+ // Gamepads are polled (no DOM events). Web supplies pollGamepads; platforms
+ // without it (WeChat, headless) skip gamepad input. Runs in First so the
+ // freshest pad state is up before any gameplay / action-map system reads it.
+ const platform = getPlatform();
+ if (platform.pollGamepads) {
+ const poll = platform.pollGamepads.bind(platform);
+ app.addSystemToSchedule(Schedule.First, defineSystem([], () => {
+ state.updateGamepads(poll());
+ }, { name: 'GamepadPollSystem' }));
+ }
+
app.addSystemToSchedule(Schedule.Last, defineSystem([], () => {
state.clearFrameState();
}, { name: 'InputClearSystem' }));
diff --git a/sdk/src/inputMap.ts b/sdk/src/inputMap.ts
new file mode 100644
index 000000000..ac6a3cf8b
--- /dev/null
+++ b/sdk/src/inputMap.ts
@@ -0,0 +1,203 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file inputMap.ts
+ * @brief defineInputMap — named input actions over raw input (UE5 Enhanced
+ * Input / Unity Input System analog).
+ *
+ * Decouples gameplay from physical keys: declare named actions ("Jump", "Move")
+ * with one or more device-agnostic bindings (keyboard / mouse / gamepad, plus
+ * composites), then query them by name. The binding model is plain serializable
+ * data (the rebinding + persistence format), and the whole thing rides the
+ * existing resource/system model — a `defineInputMap` registers ONE evaluation
+ * system that reads the raw `Input` resource each frame (REARCH_INPUT.md §2.2).
+ */
+import { Schedule, defineSystem, addSystemToSchedule } from './system';
+import { Res } from './resource';
+import { Input, InputState, GamepadAxis } from './input';
+
+// =============================================================================
+// Binding model (plain, serializable — also the rebind / persistence format)
+// =============================================================================
+
+export type Binding =
+ | { kind: 'key'; code: string }
+ | { kind: 'mouse'; button: number }
+ | { kind: 'gpButton'; button: number; pad?: number }
+ | { kind: 'gpAxis'; axis: number; pad?: number; scale?: number }
+ | { kind: 'keys1d'; neg: string; pos: string }
+ | { kind: 'keys2d'; up: string; down: string; left: string; right: string }
+ | { kind: 'stick'; stick: 'left' | 'right'; pad?: number };
+
+export type ActionType = 'button' | 'axis' | 'axis2d';
+
+export interface ActionDef {
+ type: ActionType;
+ bindings: Binding[];
+}
+
+// — Binding constructors (Capitalized, matching the engine DSL: Query/Mut/With) —
+export const Key = (code: string): Binding => ({ kind: 'key', code });
+export const MouseButton = (button: number): Binding => ({ kind: 'mouse', button });
+export const GpButton = (button: number, pad?: number): Binding => ({ kind: 'gpButton', button, pad });
+export const GpAxis = (axis: number, pad?: number, scale?: number): Binding => ({ kind: 'gpAxis', axis, pad, scale });
+/** Two keys → a signed 1D axis (neg = -1, pos = +1). */
+export const Keys1D = (neg: string, pos: string): Binding => ({ kind: 'keys1d', neg, pos });
+/** Four keys → a 2D axis (up = +y, right = +x). */
+export const Keys2D = (up: string, down: string, left: string, right: string): Binding =>
+ ({ kind: 'keys2d', up, down, left, right });
+/** A gamepad stick → a 2D axis (up = +y; the raw Y axis is inverted to match Keys2D). */
+export const Stick = (stick: 'left' | 'right', pad?: number): Binding => ({ kind: 'stick', stick, pad });
+
+// — Action constructors —
+export const Button = (...bindings: Binding[]): ActionDef => ({ type: 'button', bindings });
+export const Axis1D = (...bindings: Binding[]): ActionDef => ({ type: 'axis', bindings });
+export const Axis2D = (...bindings: Binding[]): ActionDef => ({ type: 'axis2d', bindings });
+
+// =============================================================================
+// Evaluation
+// =============================================================================
+
+/** An action reads as "down" once its magnitude reaches this (digital + analog). */
+const DOWN_THRESHOLD = 0.5;
+
+interface Vec2 { x: number; y: number; }
+
+interface ActionState {
+ value: number; // button: [0,1]; axis: [-1,1]; axis2d: magnitude [0,1]
+ vec: Vec2; // axis2d direction; scalar actions put value in x
+ down: boolean;
+ pressed: boolean;
+ released: boolean;
+}
+
+function evalScalar(b: Binding, input: InputState): number {
+ switch (b.kind) {
+ case 'key': return input.isKeyDown(b.code) ? 1 : 0;
+ case 'mouse': return input.isMouseButtonDown(b.button) ? 1 : 0;
+ case 'gpButton': return input.getGamepadButtonValue(b.button, b.pad ?? 0);
+ case 'keys1d': return (input.isKeyDown(b.pos) ? 1 : 0) - (input.isKeyDown(b.neg) ? 1 : 0);
+ case 'gpAxis': return input.getGamepadAxis(b.axis, b.pad ?? 0) * (b.scale ?? 1);
+ default: return 0; // keys2d / stick are 2D sources — no scalar contribution
+ }
+}
+
+function evalVec(b: Binding, input: InputState): Vec2 {
+ switch (b.kind) {
+ case 'keys2d': return {
+ x: (input.isKeyDown(b.right) ? 1 : 0) - (input.isKeyDown(b.left) ? 1 : 0),
+ y: (input.isKeyDown(b.up) ? 1 : 0) - (input.isKeyDown(b.down) ? 1 : 0),
+ };
+ case 'stick': {
+ const pad = b.pad ?? 0;
+ const xAxis = b.stick === 'left' ? GamepadAxis.LeftX : GamepadAxis.RightX;
+ const yAxis = b.stick === 'left' ? GamepadAxis.LeftY : GamepadAxis.RightY;
+ // Gamepad Y is +down; invert so up = +y (matches Keys2D).
+ return { x: input.getGamepadAxis(xAxis, pad), y: -input.getGamepadAxis(yAxis, pad) };
+ }
+ default: return { x: 0, y: 0 };
+ }
+}
+
+const clamp = (v: number, lo: number, hi: number): number => (v < lo ? lo : v > hi ? hi : v);
+
+// =============================================================================
+// InputMap
+// =============================================================================
+
+export class InputMap {
+ private readonly defs_ = new Map<string, ActionDef>();
+ private readonly state_ = new Map<string, ActionState>();
+
+ constructor(actions: Record<string, ActionDef>) {
+ for (const [name, def] of Object.entries(actions)) {
+ this.defs_.set(name, def);
+ this.state_.set(name, { value: 0, vec: { x: 0, y: 0 }, down: false, pressed: false, released: false });
+ }
+ }
+
+ /** 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 {
+ for (const [name, def] of this.defs_) {
+ const st = this.state_.get(name)!;
+ const prevDown = st.down;
+
+ if (def.type === 'axis2d') {
+ let x = 0, y = 0;
+ for (const b of def.bindings) { const v = evalVec(b, input); x += v.x; y += v.y; }
+ const mag = Math.hypot(x, y);
+ if (mag > 1) { x /= mag; y /= mag; }
+ st.vec.x = x;
+ st.vec.y = y;
+ st.value = Math.min(1, mag);
+ } else {
+ let v = 0;
+ for (const b of def.bindings) v += evalScalar(b, input);
+ v = def.type === 'button' ? clamp(v, 0, 1) : clamp(v, -1, 1);
+ st.value = v;
+ st.vec.x = v;
+ st.vec.y = 0;
+ }
+
+ st.down = Math.abs(st.value) >= DOWN_THRESHOLD;
+ st.pressed = st.down && !prevDown;
+ st.released = !st.down && prevDown;
+ }
+ }
+
+ // — Query —
+ down(name: string): boolean { return this.state_.get(name)?.down ?? false; }
+ pressed(name: string): boolean { return this.state_.get(name)?.pressed ?? false; }
+ released(name: string): boolean { return this.state_.get(name)?.released ?? false; }
+ /** Scalar value: button [0,1], axis [-1,1], axis2d the magnitude [0,1]. */
+ value(name: string): number { return this.state_.get(name)?.value ?? 0; }
+ /** 2D value (axis2d); scalar actions return {value, 0}. A fresh object each call. */
+ axis2d(name: string): Vec2 {
+ const v = this.state_.get(name)?.vec;
+ return v ? { x: v.x, y: v.y } : { x: 0, y: 0 };
+ }
+ actions(): string[] { return [...this.defs_.keys()]; }
+
+ // — Rebinding + persistence (the binding model is the serialization format) —
+ getBindings(name: string): Binding[] { return this.defs_.get(name)?.bindings.map((b) => ({ ...b })) ?? []; }
+ /** Replace an action's bindings (no-op for an unknown action). */
+ setBindings(name: string, bindings: Binding[]): void {
+ const def = this.defs_.get(name);
+ if (def) def.bindings = bindings.map((b) => ({ ...b }));
+ }
+ /** Serialize current bindings (persist via Storage). */
+ toJSON(): Record<string, Binding[]> {
+ const out: Record<string, Binding[]> = {};
+ for (const [name, def] of this.defs_) out[name] = def.bindings.map((b) => ({ ...b }));
+ return out;
+ }
+ /** Override bindings for actions that EXIST in this map (unknown names ignored,
+ * so stale saved data for a removed action never resurrects it). */
+ loadJSON(data: Record<string, Binding[]>): void {
+ for (const [name, bindings] of Object.entries(data)) {
+ if (this.defs_.has(name) && Array.isArray(bindings)) this.setBindings(name, bindings);
+ }
+ }
+}
+
+/**
+ * Define a named-action input map and register its per-frame evaluation system.
+ * Returns the live map — import it and query by name from any system.
+ *
+ * @example
+ * export const Game = defineInputMap({
+ * Move: Axis2D(Keys2D('KeyW','KeyS','KeyA','KeyD'), Stick('left')),
+ * Jump: Button(Key('Space'), GpButton(GamepadButton.South)),
+ * });
+ * // in a system: if (Game.pressed('Jump')) ...; const dir = Game.axis2d('Move');
+ */
+export function defineInputMap(actions: Record<string, ActionDef>): InputMap {
+ const map = new InputMap(actions);
+ // PreUpdate: after gamepad poll (First) + always-current event input, before gameplay (Update).
+ addSystemToSchedule(
+ Schedule.PreUpdate,
+ defineSystem([Res(Input)], (input) => map.evaluate(input), { name: 'InputMapEval' }),
+ );
+ return map;
+}
diff --git a/sdk/src/platform/types.ts b/sdk/src/platform/types.ts
index 4df2e5b1e..4fb2b8fac 100644
--- a/sdk/src/platform/types.ts
+++ b/sdk/src/platform/types.ts
@@ -57,6 +57,21 @@ export interface InputEventCallbacks {
onTouchCancel?(id: number): void;
}
+/**
+ * A per-frame snapshot of one gamepad. With `mapping === 'standard'` the button
+ * and axis indices follow the W3C "standard gamepad" layout (see GamepadButton /
+ * GamepadAxis in input.ts). `buttons[i]` is analog in [0,1] (1 = fully pressed);
+ * `axes[i]` is signed in [-1,1]. Gamepads are POLLED (no DOM events), so the
+ * platform produces these each frame rather than via InputEventCallbacks.
+ */
+export interface GamepadSnapshot {
+ index: number;
+ connected: boolean;
+ buttons: number[];
+ axes: number[];
+ mapping: string;
+}
+
// =============================================================================
// Image Types
// =============================================================================
@@ -97,6 +112,11 @@ export interface PlatformAdapter {
bindInputEvents(callbacks: InputEventCallbacks, target?: unknown): void;
+ /** Poll connected gamepads for this frame. Optional — platforms without
+ * gamepad support (WeChat, headless) omit it and the input plugin skips
+ * gamepad polling entirely. */
+ pollGamepads?(): GamepadSnapshot[];
+
createAudioBackend(): import('../audio/PlatformAudioBackend').PlatformAudioBackend;
devicePixelRatio(): number;
diff --git a/sdk/src/platform/web.ts b/sdk/src/platform/web.ts
index f7d45a0dc..d6ced49b2 100644
--- a/sdk/src/platform/web.ts
+++ b/sdk/src/platform/web.ts
@@ -11,6 +11,7 @@ import type {
PlatformResponse,
WasmInstantiateResult,
InputEventCallbacks,
+ GamepadSnapshot,
ImageLoadResult,
} from './types';
import { WebAudioBackend } from '../audio/WebAudioBackend';
@@ -251,6 +252,23 @@ class WebPlatformAdapter implements PlatformAdapter {
}
}
+ pollGamepads(): GamepadSnapshot[] {
+ const nav = typeof navigator !== 'undefined' ? navigator : undefined;
+ if (!nav || typeof nav.getGamepads !== 'function') return [];
+ const out: GamepadSnapshot[] = [];
+ for (const gp of nav.getGamepads()) {
+ if (!gp) continue; // navigator.getGamepads() is a sparse array (null slots)
+ out.push({
+ index: gp.index,
+ connected: gp.connected,
+ buttons: gp.buttons.map((b) => b.value),
+ axes: gp.axes.slice(),
+ mapping: gp.mapping,
+ });
+ }
+ return out;
+ }
+
createAudioBackend(): PlatformAudioBackend {
return new WebAudioBackend();
}
diff --git a/sdk/tests/input-gamepad.test.ts b/sdk/tests/input-gamepad.test.ts
new file mode 100644
index 000000000..b9805a53e
--- /dev/null
+++ b/sdk/tests/input-gamepad.test.ts
@@ -0,0 +1,82 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { InputState, GamepadButton, GamepadAxis } from '../src/input';
+import type { GamepadSnapshot } from '../src/platform/types';
+
+/** Build a standard-layout snapshot (17 buttons / 4 axes) with specific overrides. */
+function pad(o: {
+ index?: number;
+ connected?: boolean;
+ buttons?: Record<number, number>;
+ axes?: Record<number, number>;
+} = {}): GamepadSnapshot {
+ const buttons = new Array(17).fill(0);
+ const axes = new Array(4).fill(0);
+ for (const [k, v] of Object.entries(o.buttons ?? {})) buttons[+k] = v;
+ for (const [k, v] of Object.entries(o.axes ?? {})) axes[+k] = v;
+ return { index: o.index ?? 0, connected: o.connected ?? true, buttons, axes, mapping: 'standard' };
+}
+
+describe('InputState gamepad', () => {
+ it('reports connected pads and button-down state', () => {
+ const s = new InputState();
+ expect(s.getGamepads()).toEqual([]);
+ s.updateGamepads([pad({ buttons: { [GamepadButton.South]: 1 } })]);
+ expect(s.getGamepads()).toEqual([0]);
+ expect(s.isGamepadConnected(0)).toBe(true);
+ expect(s.isGamepadButtonDown(GamepadButton.South)).toBe(true);
+ expect(s.isGamepadButtonDown(GamepadButton.East)).toBe(false);
+ });
+
+ it('detects pressed/released edges across frames', () => {
+ const s = new InputState();
+ s.updateGamepads([pad({})]); // up
+ expect(s.isGamepadButtonPressed(GamepadButton.South)).toBe(false);
+ s.updateGamepads([pad({ buttons: { [GamepadButton.South]: 1 } })]); // down
+ expect(s.isGamepadButtonPressed(GamepadButton.South)).toBe(true);
+ expect(s.isGamepadButtonDown(GamepadButton.South)).toBe(true);
+ s.updateGamepads([pad({ buttons: { [GamepadButton.South]: 1 } })]); // held
+ expect(s.isGamepadButtonPressed(GamepadButton.South)).toBe(false);
+ s.updateGamepads([pad({})]); // up
+ expect(s.isGamepadButtonReleased(GamepadButton.South)).toBe(true);
+ });
+
+ it('treats analog triggers via threshold and exposes the raw value', () => {
+ const s = new InputState();
+ s.updateGamepads([pad({ buttons: { [GamepadButton.RightTrigger]: 0.3 } })]);
+ expect(s.isGamepadButtonDown(GamepadButton.RightTrigger)).toBe(false); // below 0.5
+ expect(s.getGamepadButtonValue(GamepadButton.RightTrigger)).toBeCloseTo(0.3);
+ s.updateGamepads([pad({ buttons: { [GamepadButton.RightTrigger]: 0.8 } })]);
+ expect(s.isGamepadButtonDown(GamepadButton.RightTrigger)).toBe(true);
+ });
+
+ it('applies a deadzone to axes', () => {
+ const s = new InputState();
+ s.updateGamepads([pad({ axes: { [GamepadAxis.LeftX]: 0.1, [GamepadAxis.LeftY]: 0.6 } })]);
+ expect(s.getGamepadAxis(GamepadAxis.LeftX)).toBe(0); // inside deadzone
+ expect(s.getGamepadAxis(GamepadAxis.LeftY)).toBeCloseTo(0.6);
+ });
+
+ it('marks pads disconnected when absent from a poll', () => {
+ const s = new InputState();
+ s.updateGamepads([pad({})]);
+ expect(s.isGamepadConnected(0)).toBe(true);
+ s.updateGamepads([]); // nothing polled this frame
+ expect(s.isGamepadConnected(0)).toBe(false);
+ expect(s.getGamepads()).toEqual([]);
+ expect(s.isGamepadButtonDown(GamepadButton.South)).toBe(false);
+ });
+
+ it('supports multiple pads by index', () => {
+ const s = new InputState();
+ s.updateGamepads([
+ pad({ index: 0, buttons: { [GamepadButton.South]: 1 } }),
+ pad({ index: 1, buttons: { [GamepadButton.North]: 1 } }),
+ ]);
+ expect(s.getGamepads()).toEqual([0, 1]);
+ expect(s.isGamepadButtonDown(GamepadButton.South, 0)).toBe(true);
+ expect(s.isGamepadButtonDown(GamepadButton.South, 1)).toBe(false);
+ expect(s.isGamepadButtonDown(GamepadButton.North, 1)).toBe(true);
+ });
+});
diff --git a/sdk/tests/input-map.test.ts b/sdk/tests/input-map.test.ts
new file mode 100644
index 000000000..fcb697f81
--- /dev/null
+++ b/sdk/tests/input-map.test.ts
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { describe, it, expect } from 'vitest';
+import { InputState, GamepadButton, GamepadAxis } from '../src/input';
+import {
+ InputMap, Button, Axis1D, Axis2D,
+ Key, MouseButton, GpButton, Keys1D, Keys2D, Stick,
+} from '../src/inputMap';
+import type { GamepadSnapshot } from '../src/platform/types';
+
+function pad(o: { buttons?: Record<number, number>; axes?: Record<number, number> } = {}): GamepadSnapshot {
+ const buttons = new Array(17).fill(0), axes = new Array(4).fill(0);
+ for (const [k, v] of Object.entries(o.buttons ?? {})) buttons[+k] = v;
+ for (const [k, v] of Object.entries(o.axes ?? {})) axes[+k] = v;
+ return { index: 0, connected: true, buttons, axes, mapping: 'standard' };
+}
+
+describe('InputMap', () => {
+ it('evaluates a button action from key OR gamepad', () => {
+ const map = new InputMap({ Jump: Button(Key('Space'), GpButton(GamepadButton.South)) });
+ const input = new InputState();
+ map.evaluate(input);
+ expect(map.down('Jump')).toBe(false);
+
+ input.keysDown.add('Space');
+ map.evaluate(input);
+ expect(map.down('Jump')).toBe(true);
+ expect(map.pressed('Jump')).toBe(true);
+
+ input.keysDown.delete('Space');
+ input.updateGamepads([pad({ buttons: { [GamepadButton.South]: 1 } })]);
+ map.evaluate(input);
+ expect(map.down('Jump')).toBe(true); // still down via gamepad
+ expect(map.pressed('Jump')).toBe(false); // was already down last frame
+ });
+
+ it('detects pressed / released edges', () => {
+ const map = new InputMap({ Fire: Button(MouseButton(0)) });
+ const input = new InputState();
+ map.evaluate(input);
+ input.mouseButtons.add(0);
+ map.evaluate(input);
+ expect(map.pressed('Fire')).toBe(true);
+ map.evaluate(input);
+ expect(map.pressed('Fire')).toBe(false); // held
+ input.mouseButtons.delete(0);
+ map.evaluate(input);
+ expect(map.released('Fire')).toBe(true);
+ });
+
+ it('composes a 1D axis from two keys', () => {
+ const map = new InputMap({ Throttle: Axis1D(Keys1D('KeyS', 'KeyW')) });
+ const input = new InputState();
+ input.keysDown.add('KeyW');
+ map.evaluate(input);
+ expect(map.value('Throttle')).toBe(1);
+ input.keysDown.add('KeyS'); // both → cancel
+ map.evaluate(input);
+ expect(map.value('Throttle')).toBe(0);
+ input.keysDown.delete('KeyW');
+ map.evaluate(input);
+ expect(map.value('Throttle')).toBe(-1);
+ });
+
+ it('composes a 2D axis from WASD, up = +y, normalized', () => {
+ const map = new InputMap({ Move: Axis2D(Keys2D('KeyW', 'KeyS', 'KeyA', 'KeyD')) });
+ const input = new InputState();
+ input.keysDown.add('KeyW');
+ input.keysDown.add('KeyD');
+ map.evaluate(input);
+ const v = map.axis2d('Move');
+ expect(v.x).toBeCloseTo(Math.SQRT1_2);
+ expect(v.y).toBeCloseTo(Math.SQRT1_2);
+ expect(map.value('Move')).toBeCloseTo(1);
+ });
+
+ it('reads a stick into axis2d with Y inverted and deadzone applied', () => {
+ const map = new InputMap({ Move: Axis2D(Stick('left')) });
+ const input = new InputState();
+ input.updateGamepads([pad({ axes: { [GamepadAxis.LeftX]: 0.05, [GamepadAxis.LeftY]: -0.9 } })]);
+ map.evaluate(input);
+ const v = map.axis2d('Move');
+ expect(v.x).toBe(0); // 0.05 inside deadzone
+ expect(v.y).toBeCloseTo(0.9); // stick up (raw Y -0.9) → +y
+ });
+
+ it('combines keyboard and stick on one axis2d (clamped to unit)', () => {
+ const map = new InputMap({ Move: Axis2D(Keys2D('KeyW', 'KeyS', 'KeyA', 'KeyD'), Stick('left')) });
+ const input = new InputState();
+ input.keysDown.add('KeyD'); // +x = 1
+ input.updateGamepads([pad({ axes: { [GamepadAxis.LeftX]: 1 } })]); // +x = 1
+ map.evaluate(input);
+ const v = map.axis2d('Move');
+ expect(v.x).toBeCloseTo(1); // 2 clamped to unit length
+ expect(v.y).toBe(0);
+ });
+
+ it('rebinds and round-trips through JSON', () => {
+ const map = new InputMap({ Jump: Button(Key('Space')) });
+ const input = new InputState();
+ input.keysDown.add('KeyZ');
+ map.evaluate(input);
+ expect(map.down('Jump')).toBe(false);
+
+ map.setBindings('Jump', [Key('KeyZ')]);
+ map.evaluate(input);
+ expect(map.down('Jump')).toBe(true);
+
+ const saved = JSON.parse(JSON.stringify(map.toJSON()));
+ const map2 = new InputMap({ Jump: Button(Key('Space')) });
+ map2.loadJSON(saved);
+ map2.evaluate(input);
+ expect(map2.down('Jump')).toBe(true); // rebind persisted
+
+ map2.loadJSON({ Ghost: [Key('KeyQ')] }); // unknown action ignored
+ expect(map2.actions()).toEqual(['Jump']);
+ });
+});