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.

fix(input): sample named actions independently for fixed steps

yhh16942660c702
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b64c632b5..1de7369b3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,10 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Fixed
+
+- **Named actions reach fixed simulation steps independently of render frames.** Input maps sample before FixedUpdate instead of exposing the previous render frame's actions. Presses and releases survive frames without a fixed step, reach only the first catch-up step, and remain independently visible to Update. Pending flags use constant space per action, host cancellation drops buffered pulses, and current axis values are sampled for each cadence.
+
## [0.87.1] - 2026-10-15
### Fixed
diff --git a/sdk/src/input/actionEdges.ts b/sdk/src/input/actionEdges.ts
index 7288db5a5..f0d0e9ea7 100644
--- a/sdk/src/input/actionEdges.ts
+++ b/sdk/src/input/actionEdges.ts
@@ -7,25 +7,41 @@ export interface ActionEdge {
sequence: number;
}
interface EdgeState {
- readonly owner: object;
+ readonly owner: { fixed: boolean; cancellation: number };
sequence: number;
readonly events: ActionEdge[];
}
const states = new WeakMap<object, EdgeState>();
+function stateFor(input: object): EdgeState {
+ let state = states.get(input);
+ if (!state) {
+ state = { owner: { fixed: false, cancellation: 0 }, sequence: 0, events: [] };
+ states.set(input, state);
+ }
+ return state;
+}
+
/** Ordered physical transitions, shared read-only by all maps until frame cleanup. */
export function recordActionEdge(input: object, source: ActionEdge['source'], code: ActionEdge['code'], down: boolean): void {
- let state = states.get(input);
- if (!state) { state = { owner: {}, sequence: 0, events: [] }; states.set(input, state); }
- state.events.push({ source, code, down, sequence: ++state.sequence });
+ const state = stateFor(input);
+ const event = { source, code, down, sequence: ++state.sequence };
+ state.events.push(event);
}
-export function actionEdges(input: object): Readonly<EdgeState> | undefined { return states.get(input); }
+export function actionEdges(input: object): Readonly<EdgeState> { return stateFor(input); }
+
+export function beginFixedActionEdges(input: object): void { stateFor(input).owner.fixed = true; }
+export function endFixedActionEdges(input: object): void {
+ const state = states.get(input);
+ if (state) { state.owner.fixed = false; }
+}
/** A claimed release cancels that source without manufacturing gameplay edges. */
export function discardActionEdges(input: object, source: ActionEdge['source'], code: ActionEdge['code']): void {
- const events = states.get(input)?.events;
- if (!events) return;
+ const state = states.get(input);
+ if (!state) return;
+ const events = state.events;
let keep = 0;
for (const event of events) if (event.source !== source || event.code !== code) events[keep++] = event;
events.length = keep;
@@ -35,3 +51,8 @@ export function clearActionEdges(input: object): void {
const state = states.get(input);
if (state) state.events.length = 0;
}
+
+export function cancelActionEdges(input: object): void {
+ const state = states.get(input);
+ if (state) { state.events.length = 0; state.owner.cancellation++; }
+}
diff --git a/sdk/src/input/input.ts b/sdk/src/input/input.ts
index 4e1776db0..492dcc97a 100644
--- a/sdk/src/input/input.ts
+++ b/sdk/src/input/input.ts
@@ -9,7 +9,7 @@ import type { GamepadSnapshot, InputEventCallbacks } from '../platform/types';
import { inputRouter } from './inputRouter';
import { cancelPrimaryPointer, takePrimaryPointerCancellation } from './pointerCancellation';
import { recordTouchEnd } from './touchEdges';
-import { recordActionEdge, discardActionEdges, clearActionEdges } from './actionEdges';
+import { recordActionEdge, discardActionEdges, clearActionEdges, beginFixedActionEdges, endFixedActionEdges, cancelActionEdges } from './actionEdges';
import type { Vec2 } from '../types';
/**
@@ -390,6 +390,7 @@ export class InputState {
* mirrors. Called by App before each FixedUpdate step. */
beginFixedStep(): void {
this.fixedContext_ = true;
+ beginFixedActionEdges(this);
}
/** Leave a fixed step: drop the consumed edges (so a later step this frame
@@ -397,6 +398,7 @@ export class InputState {
* on a frame with no fixed step are never cleared here, so they survive to the
* next frame's first step instead of being lost. */
endFixedStep(): void {
+ endFixedActionEdges(this);
this.keysPressedFixed.clear();
this.keysReleasedFixed.clear();
this.mouseButtonsPressedFixed.clear();
@@ -537,6 +539,7 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {
state.touches.clear();
state.cancelVirtualSources();
state.clearFrameState();
+ cancelActionEdges(state);
state.keysPressedFixed.clear();
state.keysReleasedFixed.clear();
state.mouseButtonsPressedFixed.clear();
diff --git a/sdk/src/input/inputMap.ts b/sdk/src/input/inputMap.ts
index cff25739c..fc04f88f6 100644
--- a/sdk/src/input/inputMap.ts
+++ b/sdk/src/input/inputMap.ts
@@ -9,8 +9,8 @@
* 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).
+ * existing resource/system model — evaluation reads the raw `Input` resource
+ * independently for render frames and fixed simulation steps.
*/
import { Schedule, defineSystem, addSystemToSchedule } from '../ecs/system';
import { Res } from '../ecs/resource';
@@ -134,6 +134,8 @@ const DOWN_THRESHOLD = 0.5;
interface ActionState {
tapSequence: number;
+ pendingPressed: boolean;
+ pendingReleased: boolean;
value: number; // button: [0,1]; axis: [-1,1]; axis2d: magnitude [0,1]
vec: Vec2; // axis2d direction; scalar actions put value in x
down: boolean;
@@ -244,40 +246,64 @@ interface PendingListen {
/**
* A live set of named actions, as {@link defineInputMap} answers it. Query it by
- * name from a system; the map recomputes itself once per frame, so every read
- * within a frame sees the same values.
+ * name from a system. Every read within a render frame or fixed simulation step
+ * sees the same values; edges reach each cadence independently, once.
*
* @public
*/
export class InputMap {
private readonly defs_ = new Map<string, ActionDef>();
private readonly state_ = new Map<string, ActionState>();
+ private readonly fixedState_ = new Map<string, ActionState>();
private pendingListen_: PendingListen | null = null;
- private tapOwner_: object | undefined;
+ private tapOwner_: { fixed: boolean; cancellation: number } | undefined;
+ private cancellation_ = 0;
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, tapSequence: 0 });
+ this.state_.set(name, { value: 0, vec: { x: 0, y: 0 }, down: false, pressed: false, released: false, tapSequence: 0, pendingPressed: false, pendingReleased: false });
+ this.fixedState_.set(name, { ...this.state_.get(name)!, vec: { x: 0, y: 0 } });
}
}
- /** @internal Recompute every action from the current raw input. Called once per
- * frame by the registered evaluation system; complete physical taps survive
- * between samples alongside the normal held-state transitions. */
+ /** @internal Recompute the active cadence. Render evaluation also buffers
+ * edges for the next fixed step; complete physical taps survive between
+ * samples alongside the normal held-state transitions. */
evaluate(input: InputState): void {
const edges = actionEdges(input);
- const tapOwner = edges?.owner;
+ const tapOwner = edges.owner;
if (this.tapOwner_ !== tapOwner) {
this.tapOwner_ = tapOwner;
- for (const state of this.state_.values()) state.tapSequence = 0;
+ for (const states of [this.state_, this.fixedState_]) {
+ for (const state of states.values()) state.tapSequence = 0;
+ }
+ for (const state of this.fixedState_.values()) state.pendingPressed = state.pendingReleased = false;
+ }
+ if (this.cancellation_ !== tapOwner.cancellation) {
+ this.cancellation_ = tapOwner.cancellation;
+ for (const state of this.fixedState_.values()) state.pendingPressed = state.pendingReleased = false;
+ }
+ if (tapOwner.fixed) this.evaluateStates_(input, this.fixedState_, false);
+ else {
+ if (this.pendingListen_) this.scanForRebind_(input);
+ this.evaluateStates_(input, this.state_, false);
+ this.evaluateStates_(input, this.fixedState_, true);
}
- if (this.pendingListen_) this.scanForRebind_(input);
+ }
+
+ private evaluateStates_(input: InputState, states: Map<string, ActionState>, buffer: boolean): void {
+ const edges = actionEdges(input);
for (const [name, def] of this.defs_) {
- const st = this.state_.get(name)!;
+ const st = states.get(name)!;
const prevDown = st.down;
- if (def.type === 'axis2d') {
+ if (buffer) {
+ const sampled = this.state_.get(name)!;
+ st.value = sampled.value;
+ st.vec.x = sampled.vec.x;
+ st.vec.y = sampled.vec.y;
+ } else 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);
@@ -302,26 +328,40 @@ export class InputMap {
st.down = Math.abs(st.value) >= DOWN_THRESHOLD;
st.pressed = st.down && !prevDown;
st.released = !st.down && prevDown;
- if (def.type === 'button' && edges?.events.length) {
+ if (def.type === 'button' && edges.events.length) {
const observed = observedButtonEdges(def.bindings, input, edges.events, st.tapSequence, prevDown);
st.pressed ||= !!(observed & 1);
st.released ||= !!(observed & 2);
}
// A held alternative absorbs taps too, so releasing it cannot replay
// an earlier pulse. Each map owns its watermark independently.
- st.tapSequence = edges?.sequence ?? 0;
+ st.tapSequence = edges.sequence;
+ if (buffer) {
+ // Constant space per action even if no simulation step runs for
+ // many render frames. Raw frame events can be cleared normally.
+ st.pendingPressed ||= st.pressed;
+ st.pendingReleased ||= st.released;
+ } else if (states === this.fixedState_) {
+ st.pressed ||= st.pendingPressed;
+ st.released ||= st.pendingReleased;
+ st.pendingPressed = st.pendingReleased = false;
+ }
}
}
+ private readStates_(): Map<string, ActionState> {
+ return this.tapOwner_?.fixed ? this.fixedState_ : this.state_;
+ }
+
// — 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; }
+ down(name: string): boolean { return this.readStates_().get(name)?.down ?? false; }
+ pressed(name: string): boolean { return this.readStates_().get(name)?.pressed ?? false; }
+ released(name: string): boolean { return this.readStates_().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; }
+ value(name: string): number { return this.readStates_().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;
+ const v = this.readStates_().get(name)?.vec;
return v ? { x: v.x, y: v.y } : { x: 0, y: 0 };
}
actions(): string[] { return [...this.defs_.keys()]; }
@@ -420,20 +460,21 @@ export class InputMap {
}
/**
- * Define a named-action input map and register its per-frame evaluation system.
+ * Define a named-action input map and register render/fixed evaluation systems.
* 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 const Game = defineInputMap({ Jump: Button(Key('Space'), GpButton(GamepadButton.South)) });
+ * // In a system: if (Game.pressed('Jump')) jump();
*
* @public
*/
export function defineInputMap(actions: Record<string, ActionDef>): InputMap {
const map = new InputMap(actions);
+ addSystemToSchedule(
+ Schedule.FixedPreUpdate,
+ defineSystem([Res(Input)], (input) => map.evaluate(input), { name: 'InputMapFixedEval' }),
+ );
// PreUpdate: after gamepad poll (First) + always-current event input, before gameplay (Update).
addSystemToSchedule(
Schedule.PreUpdate,
diff --git a/sdk/tests/input-map-fixed-step.test.ts b/sdk/tests/input-map-fixed-step.test.ts
new file mode 100644
index 000000000..7721bbac8
--- /dev/null
+++ b/sdk/tests/input-map-fixed-step.test.ts
@@ -0,0 +1,92 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import { beforeEach, describe, expect, it } from 'vitest';
+import { App } from '../src/app/app';
+import { AppContext, setDefaultContext } from '../src/ecs/context';
+import { Schedule, defineSystem } from '../src/ecs/system';
+import { Input, InputState, inputEventCallbacks } from '../src/input/input';
+import { Button, Key, MouseButton, Axis1D, Virtual, defineInputMap } from '../src/input/inputMap';
+
+let context: AppContext;
+beforeEach(() => { context = new AppContext(); setDefaultContext(context); });
+
+function harness() {
+ const map = defineInputMap({ Jump: Button(Key('Space'), MouseButton(0)), Move: Axis1D(Virtual('move')) });
+ const app = App.new(), input = new InputState();
+ app.insertResource(Input, input);
+ app.addBundleSystems(context.drainPendingSystems() as Parameters<App['addBundleSystems']>[0]);
+ const fixed: boolean[] = [], rendered: boolean[] = [], released: boolean[] = [], held: boolean[] = [], movement: number[] = [];
+ app.addSystemToSchedule(Schedule.FixedUpdate, defineSystem([], () => {
+ fixed.push(map.pressed('Jump')); released.push(map.released('Jump')); held.push(map.down('Jump')); movement.push(map.value('Move'));
+ }));
+ app.addSystemToSchedule(Schedule.Update, defineSystem([], () => { rendered.push(map.pressed('Jump')); }));
+ app.addSystemToSchedule(Schedule.Last, defineSystem([], () => input.clearFrameState()));
+ return { app, input, map, fixed, rendered, released, held, movement };
+}
+
+describe('named actions in fixed timestep', () => {
+ it('delivers current input once on a catch-up frame and independently to Update', async () => {
+ const h = harness();
+ h.input.noteKeyDown('Space');
+ await h.app.tick(2 / 60);
+ expect(h.fixed).toEqual([true, false]);
+ expect(h.rendered).toEqual([true]);
+ await h.app.tick(1 / 60);
+ expect(h.fixed).toEqual([true, false, false]);
+ });
+ it('retains a short tap across render frames with no fixed step', async () => {
+ const h = harness();
+ h.input.noteKeyDown('Space'); h.input.noteKeyUp('Space');
+ await h.app.tick(1 / 120);
+ expect(h.fixed).toEqual([]);
+ expect(h.rendered).toEqual([true]);
+ await h.app.tick(1 / 120);
+ expect(h.fixed).toEqual([true]);
+ expect(h.rendered).toEqual([true, false]);
+ await h.app.tick(1 / 60);
+ expect(h.fixed).toEqual([true, false]);
+ });
+ it('does not repeat a buffered tap on catch-up steps', async () => {
+ const h = harness();
+ h.input.noteKeyDown('Space'); h.input.noteKeyUp('Space');
+ await h.app.tick(1 / 120);
+ await h.app.tick(3 / 120);
+ expect(h.fixed).toEqual([true, false]);
+ expect(h.released).toEqual([true, false]);
+ expect(h.held).toEqual([false, false]);
+ });
+ it('delivers mouse release/repress independently to both cadences', async () => {
+ const h = harness();
+ h.input.noteMouseDown(0); await h.app.tick(1 / 60);
+ h.input.noteMouseUp(0); h.input.noteMouseDown(0); await h.app.tick(2 / 60);
+ expect(h.fixed).toEqual([true, true, false]);
+ expect(h.released).toEqual([false, true, false]);
+ expect(h.rendered).toEqual([true, true]);
+ expect(h.held).toEqual([true, true, true]);
+ });
+ it('cancels a rendered pulse before the next simulation step', async () => {
+ const h = harness();
+ h.input.noteKeyDown('Space'); h.input.noteKeyUp('Space');
+ await h.app.tick(1 / 120);
+ inputEventCallbacks(h.input).onInputCancel!();
+ await h.app.tick(1 / 120);
+ expect(h.fixed).toEqual([false]);
+ expect(h.released).toEqual([false]);
+ });
+ it('samples axes on the current step rather than the previous render frame', async () => {
+ const h = harness();
+ h.input.setVirtual('move', .75); await h.app.tick(2 / 60);
+ h.input.setVirtual('move', -.25); await h.app.tick(1 / 60);
+ expect(h.movement).toEqual([.75, .75, -.25]);
+ expect(h.map.value('Move')).toBe(-.25);
+ });
+ it('retains pending edges while scaled simulation is stopped', async () => {
+ const h = harness();
+ h.input.noteKeyDown('Space'); h.input.noteKeyUp('Space');
+ for (let frame = 0; frame < 200; frame++) await h.app.tick(0);
+ expect(h.fixed).toEqual([]);
+ await h.app.tick(2 / 60);
+ expect(h.fixed).toEqual([true, false]);
+ expect(h.rendered.filter(Boolean)).toHaveLength(1);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index f50582c1e..57cd374c9 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -28,6 +28,8 @@ export const NOTES_FLOOR = 'v0.65.0';
* the reader recognises anyway.
*/
export const NOTED = {
+ 'fix(input): sample named actions independently for fixed steps':
+ { note: 'Named actions reach fixed simulation steps independently of render frames.' },
'test(youtube): acknowledge each hit and retain failure state':
{ internal: 'Headless YouTube acceptance acknowledges each actual training hit and retains live gameplay state and screenshots before closing a failed browser session; missing attacks still fail.' },
'chore(release): prepare 0.87.1':