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): visual input-map editor (named actions + bindings)
esengine518a628887e9
diff --git a/desktop/electron/importAssets.ts b/desktop/electron/importAssets.tsindex 69ac65199..de1b3258b 100644--- a/desktop/electron/importAssets.ts+++ b/desktop/electron/importAssets.ts@@ -26,6 +26,7 @@ const EXT_TO_TYPE: Record<string, string> = {'.fnt': 'bitmapFont', '.bmfont': 'bitmapFont', '.ttf': 'font', '.otf': 'font', '.woff': 'font', '.woff2': 'font','.tmx': 'tilemap', '.tmj': 'tilemap','.skel': 'spine', '.atlas': 'spine',+ '.inputmap': 'inputmap',};/** The supported import extensions (no leading dot) — used by the file dialog filter. */diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsxindex dfda936c1..8d8a72592 100644--- a/desktop/src/panels/ContentBrowser.tsx+++ b/desktop/src/panels/ContentBrowser.tsx@@ -410,6 +410,17 @@ export function ContentBrowser() {}};+ const newInputMap = async () => {+ try {+ const path = await ProjectStore.createInputMapFile(cwd);+ refreshFs();+ selectAsset(path); // unified inspector opens the input-map editor+ setRenaming(path);+ } catch (e) {+ Toasts.push(`New input map failed: ${errMsg(e)}`, 'error');+ }+ };+const showInExplorer = async (path: string) => {try {await window.estella.shell.showItem(path);@@ -542,6 +553,7 @@ export function ContentBrowser() {{ label: 'New Folder', icon: <FolderPlus size={14} />, onClick: () => void newFolder() },{ sep: true },{ label: 'New Scene', onClick: () => void newScene() },+ { label: 'New Input Map', onClick: () => void newInputMap() },{ label: 'New Material', onClick: () => void createMaterial(cwd) },{ label: 'New Material Graph', onClick: () => void createMaterialGraph(cwd) },{ sep: true },diff --git a/desktop/src/panels/Details.tsx b/desktop/src/panels/Details.tsxindex c931efbdb..3ce951b44 100644--- a/desktop/src/panels/Details.tsx+++ b/desktop/src/panels/Details.tsx@@ -41,8 +41,9 @@ import { SceneModel } from '@/engine/SceneModel';import { InspectorClipboard } from '@/engine/inspectorClipboard';import { SceneCommands, toModelValue } from '@/engine/SceneCommands';import { PlayInspect } from '@/engine/PlayInspect';-import type { SceneData } from 'esengine';+import type { SceneData, InputMapAsset, ActionType, Binding } from 'esengine';import { modelAddableComponentEntries, subscribeSchemas, getSchemaRevision, prettyLabel, hexToRgba, dynamicEnumOptions } from '@/engine/schema';+import * as imap from '@/project/inputMapDoc';import { ProjectStore } from '@/project/ProjectStore';import { confirmDiscard } from '@/project/discardGuard';import { MaterialDocument } from '@/material/MaterialDocument';@@ -1547,6 +1548,139 @@ function MaterialAssetInspector({ path }: { path: string }) {// Asset view of the unified inspector — shown when an asset (not an entity) is// selected (in the content browser). A material is edited inline (reflection-driven+const BINDING_KINDS: Array<{ kind: Binding['kind']; label: string }> = [+ { kind: 'key', label: 'Key' },+ { kind: 'keys1d', label: 'Keys · 1D axis' },+ { kind: 'keys2d', label: 'Keys · 2D axis' },+ { kind: 'mouse', label: 'Mouse button' },+ { kind: 'gpButton', label: 'Gamepad button' },+ { kind: 'gpAxis', label: 'Gamepad axis' },+ { kind: 'stick', label: 'Gamepad stick' },+];++function defaultBinding(kind: Binding['kind']): Binding {+ switch (kind) {+ case 'keys1d': return { kind: 'keys1d', neg: 'KeyA', pos: 'KeyD' };+ case 'keys2d': return { kind: 'keys2d', up: 'KeyW', down: 'KeyS', left: 'KeyA', right: 'KeyD' };+ case 'mouse': return { kind: 'mouse', button: 0 };+ case 'gpButton': return { kind: 'gpButton', button: 0 };+ case 'gpAxis': return { kind: 'gpAxis', axis: 0 };+ case 'stick': return { kind: 'stick', stick: 'left' };+ default: return { kind: 'key', code: 'Space' };+ }+}++function BindingRow({ binding, onChange, onRemove }: { binding: Binding; onChange: (b: Binding) => void; onRemove: () => void }) {+ const b = binding as Record<string, unknown>;+ const set = (patch: Record<string, unknown>) => onChange({ ...(b as object), ...patch } as unknown as Binding);+ const txt = (k: string, ph: string) => (+ <input className="im-in" value={String(b[k] ?? '')} placeholder={ph} onChange={(e) => set({ [k]: e.target.value })} />+ );+ const num = (k: string) => (+ <input className="im-in num" type="number" value={Number(b[k] ?? 0)} onChange={(e) => set({ [k]: Number(e.target.value) || 0 })} />+ );+ let fields: React.ReactNode = null;+ switch (binding.kind) {+ case 'key': fields = txt('code', 'Code (e.g. Space, KeyW)'); break;+ case 'keys1d': fields = <>{txt('neg', '−')}{txt('pos', '+')}</>; break;+ case 'keys2d': fields = <>{txt('up', 'Up')}{txt('down', 'Down')}{txt('left', 'Left')}{txt('right', 'Right')}</>; break;+ case 'mouse': case 'gpButton': fields = num('button'); break;+ case 'gpAxis': fields = num('axis'); break;+ case 'stick':+ fields = (+ <select className="im-in" value={String(b.stick)} onChange={(e) => set({ stick: e.target.value })}>+ <option value="left">Left</option>+ <option value="right">Right</option>+ </select>+ );+ break;+ }+ return (+ <div className="im-binding">+ <select className="im-in kind" value={binding.kind} onChange={(e) => onChange(defaultBinding(e.target.value as Binding['kind']))}>+ {BINDING_KINDS.map((k) => <option key={k.kind} value={k.kind}>{k.label}</option>)}+ </select>+ {fields}+ <button type="button" className="im-x" onClick={onRemove} title="Remove binding">×</button>+ </div>+ );+}++// The .inputmap editor, embedded in the unified inspector (no separate panel): edits+// the SAME JSON the runtime's loadInputMapAsset reads. Saves on every edit.+function InputMapAssetInspector({ path }: { path: string }) {+ const [map, setMap] = useState<InputMapAsset | null>(null);+ useEffect(() => {+ let alive = true;+ void window.estella.fs+ .read(path)+ .then((t) => {+ if (!alive) return;+ try {+ setMap(JSON.parse(t) as InputMapAsset);+ } catch {+ setMap(imap.blankInputMap());+ }+ })+ .catch(() => alive && setMap(imap.blankInputMap()));+ return () => {+ alive = false;+ };+ }, [path]);++ if (!map) return <div className="insp"><div className="filter-empty">Loading…</div></div>;++ const commit = (next: InputMapAsset) => {+ setMap(next);+ void window.estella.fs.write(path, JSON.stringify(next, null, 2) + '\n');+ };+ const uniqueName = () => {+ let n = 'NewAction';+ for (let i = 2; map.actions[n]; i++) n = `NewAction${i}`;+ return n;+ };+ const actions = Object.entries(map.actions);++ return (+ <div className="insp input-map">+ <div className="im-head">+ <span>Input Actions</span>+ <button type="button" className="im-add" onClick={() => commit(imap.addAction(map, uniqueName()))}>+ Action</button>+ </div>+ {actions.length === 0 && <div className="filter-empty">No actions yet — add one to bind keys / buttons / axes.</div>}+ {actions.map(([name, def]) => (+ <div className="im-action" key={name}>+ <div className="im-action-head">+ <input+ className="im-name"+ key={name}+ defaultValue={name}+ onBlur={(e) => {+ if (e.target.value.trim() && e.target.value !== name) commit(imap.renameAction(map, name, e.target.value));+ }}+ />+ <select className="im-in" value={def.type} onChange={(e) => commit(imap.setActionType(map, name, e.target.value as ActionType))}>+ <option value="button">Button</option>+ <option value="axis">Axis</option>+ <option value="axis2d">Axis 2D</option>+ </select>+ <button type="button" className="im-x" onClick={() => commit(imap.removeAction(map, name))} title="Remove action">×</button>+ </div>+ {def.bindings.map((bnd, i) => (+ <BindingRow+ key={i}+ binding={bnd}+ onChange={(nb) => commit(imap.setBinding(map, name, i, nb))}+ onRemove={() => commit(imap.removeBinding(map, name, i))}+ />+ ))}+ <button type="button" className="im-addb" onClick={() => commit(imap.addBinding(map, name, defaultBinding('key')))}>+ Binding</button>+ </div>+ ))}+ </div>+ );+}+// rows); other assets show their fs metadata + the image/type glyph preview.function AssetInspector({ path }: { path: string }) {const name = baseName(path);@@ -1555,6 +1689,9 @@ function AssetInspector({ path }: { path: string }) {if (isMaterialAsset(path)) {return <MaterialAssetInspector path={path} />;}+ if (type === 'inputmap') {+ return <InputMapAssetInspector path={path} />;+ }return (<div className="insp"><div className="cb-detail-body" style={{ flex: 1, minHeight: 0, overflowY: 'auto' }}>diff --git a/desktop/src/project/ProjectStore.ts b/desktop/src/project/ProjectStore.tsindex 0f2d2144e..879a3e72a 100644--- a/desktop/src/project/ProjectStore.ts+++ b/desktop/src/project/ProjectStore.ts@@ -6,6 +6,7 @@ import type { SceneData, PrefabData, ExtractEntity, PhysicsPluginConfig } from 'import { EngineHost } from '@/engine/EngineHost';import { SceneModel } from '@/engine/SceneModel';import { Reconciler } from '@/engine/Reconciler';+import { blankInputMap } from './inputMapDoc';import { EditorHistory } from '@/engine/EditorHistory';import { expandScenePrefabs, collapseScenePrefabs } from '@/engine/PrefabInstance';import { SceneCommands } from '@/engine/SceneCommands';@@ -355,6 +356,12 @@ class ProjectStoreImpl {return window.estella.project.createAsset(destDir, 'scene.esscene', content, 'scene');}+ /** Create a blank `.inputmap` asset (named input actions) under `destDir`. */+ async createInputMapFile(destDir: string): Promise<string> {+ const content = JSON.stringify(blankInputMap(), null, 2) + '\n';+ return window.estella.project.createAsset(destDir, 'input.inputmap', content, 'inputmap');+ }+/*** Load the project's asset index (the main-process AssetDatabase scan)* into a uuid→path registry, then point the enginediff --git a/desktop/src/project/assetTypes.ts b/desktop/src/project/assetTypes.tsindex e9654ee67..5c03883d2 100644--- a/desktop/src/project/assetTypes.ts+++ b/desktop/src/project/assetTypes.ts@@ -13,7 +13,7 @@*/import {Folder, Film, Image, FileImage, PersonStanding, Music,- Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow,+ Component, Blend, FileCode2, Clapperboard, Grid3x3, File, Workflow, Gamepad2,type LucideIcon,} from 'lucide-react';import type { AssetType } from '@/types';@@ -47,6 +47,7 @@ export const ASSET_TYPES: Record<AssetType, AssetTypeDef> = {animation: { extensions: ['esanim', 'estimeline'], badge: 'ANM', icon: Clapperboard, tint: '#9bb39a' },tileset: { extensions: ['estileset'], badge: 'TST', icon: Grid3x3, tint: '#9b8fc0' },tilemap: { extensions: ['estilemap'], badge: 'TMP', icon: Grid3x3, tint: '#7fa6c4' },+ inputmap: { extensions: ['inputmap'], badge: 'INP', icon: Gamepad2, tint: '#a0b88f' },file: { badge: '', icon: File, tint: 'var(--text-dim)' },};diff --git a/desktop/src/project/inputMapDoc.ts b/desktop/src/project/inputMapDoc.tsnew file mode 100644index 000000000..068a79f14--- /dev/null+++ b/desktop/src/project/inputMapDoc.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file inputMapDoc.ts+ * @brief Pure, immutable edits over an InputMapAsset (the `.inputmap` content: named+ * actions, each a button/axis/axis2d with device-agnostic bindings). The data+ * model is the SDK's (defineInputMap / loadInputMapAsset ship the same JSON),+ * so the editor authors exactly what the runtime loads. Engine/DOM-free → the+ * editing logic unit-tests in isolation; the panel just renders + dispatches.+ */+import type { InputMapAsset, ActionDef, ActionType, Binding } from 'esengine';++export const INPUT_MAP_VERSION = 1;++export const blankInputMap = (): InputMapAsset => ({ version: INPUT_MAP_VERSION, actions: {} });++const withActions = (map: InputMapAsset, actions: Record<string, ActionDef>): InputMapAsset => ({ ...map, actions });++export function addAction(map: InputMapAsset, name: string, type: ActionType = 'button'): InputMapAsset {+ const n = name.trim();+ if (!n || map.actions[n]) return map;+ return withActions(map, { ...map.actions, [n]: { type, bindings: [] } });+}++export function removeAction(map: InputMapAsset, name: string): InputMapAsset {+ if (!map.actions[name]) return map;+ const actions = { ...map.actions };+ delete actions[name];+ return withActions(map, actions);+}++/** Rename an action, preserving its position in the (ordered) action list. */+export function renameAction(map: InputMapAsset, from: string, to: string): InputMapAsset {+ const t = to.trim();+ if (from === t || !map.actions[from] || !t || map.actions[t]) return map;+ const actions: Record<string, ActionDef> = {};+ for (const [k, v] of Object.entries(map.actions)) actions[k === from ? t : k] = v;+ return withActions(map, actions);+}++export function setActionType(map: InputMapAsset, name: string, type: ActionType): InputMapAsset {+ const a = map.actions[name];+ if (!a || a.type === type) return map;+ return withActions(map, { ...map.actions, [name]: { ...a, type, bindings: [...a.bindings] } });+}++export function addBinding(map: InputMapAsset, name: string, binding: Binding): InputMapAsset {+ const a = map.actions[name];+ if (!a) return map;+ return withActions(map, { ...map.actions, [name]: { ...a, bindings: [...a.bindings, binding] } });+}++export function removeBinding(map: InputMapAsset, name: string, index: number): InputMapAsset {+ const a = map.actions[name];+ if (!a || index < 0 || index >= a.bindings.length) return map;+ return withActions(map, { ...map.actions, [name]: { ...a, bindings: a.bindings.filter((_, i) => i !== index) } });+}++export function setBinding(map: InputMapAsset, name: string, index: number, binding: Binding): InputMapAsset {+ const a = map.actions[name];+ if (!a || index < 0 || index >= a.bindings.length) return map;+ return withActions(map, {+ ...map.actions,+ [name]: { ...a, bindings: a.bindings.map((b, i) => (i === index ? binding : b)) },+ });+}diff --git a/desktop/src/theme/inspector.css b/desktop/src/theme/inspector.cssindex 3951a1576..b467b92da 100644--- a/desktop/src/theme/inspector.css+++ b/desktop/src/theme/inspector.css@@ -234,3 +234,19 @@/* Live "Game" inspector banner (UE5 PIE Details) — editing the running game. */.game-live { padding: 6px 12px; font-size: var(--fs-xs); font-weight: 500; color: var(--run-hi); background: rgba(70, 160, 74, 0.12); border-bottom: 1px solid var(--border); flex-shrink: 0; }++/* .inputmap editor (named input actions + bindings), embedded in the inspector. */+.input-map { padding: 8px; display: flex; flex-direction: column; gap: 8px; overflow-y: auto; }+.im-head { display: flex; align-items: center; justify-content: space-between; font-size: var(--fs-sm); color: var(--text-dim); font-weight: 600; }+.im-add, .im-addb { font-size: var(--fs-2xs); color: var(--acc-hi); padding: 2px 8px; border-radius: var(--r-xs); border: 1px solid var(--border); }+.im-add:hover, .im-addb:hover { background: var(--acc-soft); }+.im-action { border: 1px solid var(--border); border-radius: var(--r-sm); padding: 6px; display: flex; flex-direction: column; gap: 4px; background: var(--inset); }+.im-action-head { display: flex; align-items: center; gap: 4px; }+.im-name { flex: 1; min-width: 0; background: var(--void); border: 1px solid var(--border); border-radius: var(--r-xs); padding: 2px 6px; color: var(--text); font-size: var(--fs-sm); font-weight: 600; }+.im-binding { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; }+.im-in { background: var(--void); border: 1px solid var(--border); border-radius: var(--r-xs); padding: 2px 5px; color: var(--text); font-size: var(--fs-xs); min-width: 0; }+.im-in.kind { flex-shrink: 0; }+.im-in.num { width: 54px; }+.im-x { color: var(--text-mute); width: 18px; height: 18px; border-radius: var(--r-xs); flex-shrink: 0; line-height: 1; }+.im-x:hover { color: var(--error); }+.im-addb { align-self: flex-start; }diff --git a/desktop/src/types.ts b/desktop/src/types.tsindex 7490ef2c4..ff5f34133 100644--- a/desktop/src/types.ts+++ b/desktop/src/types.ts@@ -143,6 +143,7 @@ export type AssetType =| 'animation'| 'tileset'| 'tilemap'+ | 'inputmap'| 'file';export interface AssetItem {diff --git a/desktop/tests/input-map-doc.test.ts b/desktop/tests/input-map-doc.test.tsnew file mode 100644index 000000000..686d2a321--- /dev/null+++ b/desktop/tests/input-map-doc.test.ts@@ -0,0 +1,57 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file InputMap document edits — pure, immutable CRUD over actions + bindings,+ * the editable core of the .inputmap asset (same JSON the runtime loads).+ */+import { describe, it, expect } from 'vitest';+import type { Binding } from 'esengine';+import {+ blankInputMap,+ addAction,+ removeAction,+ renameAction,+ setActionType,+ addBinding,+ removeBinding,+ setBinding,+} from '@/project/inputMapDoc';++const key = (code: string): Binding => ({ kind: 'key', code });++describe('inputMapDoc', () => {+ it('addAction adds a button action, is immutable, and dedups / ignores empty', () => {+ const m0 = blankInputMap();+ const m1 = addAction(m0, 'Jump');+ expect(m1.actions.Jump).toEqual({ type: 'button', bindings: [] });+ expect(m0.actions).toEqual({}); // original untouched+ expect(addAction(m1, 'Jump')).toBe(m1); // existing name → same ref (no-op)+ expect(addAction(m1, ' ')).toBe(m1); // empty → no-op+ });++ it('adds / edits / removes bindings', () => {+ let m = addAction(blankInputMap(), 'Jump');+ m = addBinding(m, 'Jump', key('Space'));+ expect(m.actions.Jump.bindings).toEqual([{ kind: 'key', code: 'Space' }]);+ m = setBinding(m, 'Jump', 0, key('KeyW'));+ expect(m.actions.Jump.bindings[0]).toEqual({ kind: 'key', code: 'KeyW' });+ m = removeBinding(m, 'Jump', 0);+ expect(m.actions.Jump.bindings).toEqual([]);+ });++ it('renameAction preserves list position and rejects collisions', () => {+ let m = addAction(addAction(blankInputMap(), 'A'), 'B');+ m = renameAction(m, 'A', 'Fire');+ expect(Object.keys(m.actions)).toEqual(['Fire', 'B']); // position kept+ expect(m.actions.Fire.type).toBe('button');+ expect(renameAction(m, 'Fire', 'B')).toBe(m); // would collide → no-op+ });++ it('setActionType changes the type; removeAction deletes', () => {+ let m = addAction(blankInputMap(), 'Move');+ m = setActionType(m, 'Move', 'axis2d');+ expect(m.actions.Move.type).toBe('axis2d');+ m = removeAction(m, 'Move');+ expect(m.actions.Move).toBeUndefined();+ });+});