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): a finger is a pointer of its own, on the host and in the UI

esenginee76ad34f7845
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index 4845daa68..4d13cc355 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -32,6 +32,7 @@ env:
test_clip_depth test_sort_key test_sprite_mask_range test_shadow_atlas test_particle_shapes test_lod_selection test_hdr_format
test_text_edit test_render_graph test_device_loss test_physics_interpolation
test_bitmap_font test_texture_cache test_mesh_recovery test_aot_host test_aot_conformance
+ test_touch_stream
test_frame_lifecycle
jobs:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fec24cd9e..f649549ae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,25 @@ published separately; it ships inside the editor.
### Fixed
+- **Multi-touch: two on-screen buttons can be held at once.** On a packaged Android
+ or iOS game, pressing a second button let go of the first — "the last press cancels
+ the others" (#56). Two layers were single-finger.
+
+ The hosts collapsed every finger onto one id: Android read pointer index 0 whatever
+ the event was about, and iOS set `multipleTouchEnabled = NO` and dispatched
+ `anyObject`. Both now feed one id per finger, alive from its start to its end, over
+ the contract in `native/host/platform/touch_stream.hpp` that a test holds off-device.
+
+ Above them the UI hit-test read the synthesized mouse, so only the primary finger
+ could press anything. It now tracks one pointer per finger: each holds and releases
+ its own control, a control two fingers hold stays pressed until the last lifts, and
+ a finger that slides off before letting go releases without clicking. Gestures —
+ drag, scroll, sliders — stay on the primary pointer.
+
+ `InputState.touchesEnded` is a `Map<number, TouchPoint>` rather than a `Set<number>`
+ (`@beta`): a release is hit-tested where the finger lifted, and the live `touches`
+ no longer hold it.
+
- **A WeChat 分包 is a directory the package carries.** A folder marked *subpackage*
in the editor staged its assets where they were authored (`assets/level2/`), while
`game.json` declared the root `subpackages/level2` — a directory that was never
diff --git a/examples/input-actions/src/systems/gestures.ts b/examples/input-actions/src/systems/gestures.ts
index 0613e2d25..765e428e2 100644
--- a/examples/input-actions/src/systems/gestures.ts
+++ b/examples/input-actions/src/systems/gestures.ts
@@ -69,8 +69,7 @@ function moveTouch(id: number, x: number, y: number): void {
}
function endTouch(id: number): void {
- padInput.touches.delete(id);
- padInput.touchesEnded.add(id);
+ padInput.endTouch(id);
}
export const gestureSystem = defineSystem(
@@ -90,7 +89,7 @@ export const gestureSystem = defineSystem(
const live = input.touches.get(id);
if (live) moveTouch(id, live.x, live.y);
}
- for (const id of input.touchesEnded) {
+ for (const id of input.touchesEnded.keys()) {
if (padTouchIds.delete(id)) endTouch(id);
}
diff --git a/native/host/platform/android.cpp b/native/host/platform/android.cpp
index a729c6e19..0776382dc 100644
--- a/native/host/platform/android.cpp
+++ b/native/host/platform/android.cpp
@@ -32,6 +32,7 @@
#include "Host.hpp"
#include "media/glyph_raster.hpp" // GLYPH_BOLD / GLYPH_ITALIC, for the font match
+#include "platform/touch_stream.hpp"
#define LOG_TAG "EstellaSDK"
@@ -432,21 +433,35 @@ void attachTextEditor(ANativeActivity* activity) {
__android_log_print(ANDROID_LOG_INFO, LOG_TAG, "text editor: soft keyboard up (IME)");
}
+// The decoder's own copies of the MotionEvent constants, held against the NDK's
+// so a test that cannot include <android/input.h> is still testing this ABI.
+static_assert(eshost::input::kMotionActionMask == AMOTION_EVENT_ACTION_MASK);
+static_assert(eshost::input::kMotionPointerIndexMask == AMOTION_EVENT_ACTION_POINTER_INDEX_MASK);
+static_assert(eshost::input::kMotionPointerIndexShift == AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
+static_assert(eshost::input::kMotionActionDown == AMOTION_EVENT_ACTION_DOWN);
+static_assert(eshost::input::kMotionActionUp == AMOTION_EVENT_ACTION_UP);
+static_assert(eshost::input::kMotionActionMove == AMOTION_EVENT_ACTION_MOVE);
+static_assert(eshost::input::kMotionActionCancel == AMOTION_EVENT_ACTION_CANCEL);
+static_assert(eshost::input::kMotionActionPointerDown == AMOTION_EVENT_ACTION_POINTER_DOWN);
+static_assert(eshost::input::kMotionActionPointerUp == AMOTION_EVENT_ACTION_POINTER_UP);
+
+// One finger is one id, for the whole gesture: Android's own pointer id is that
+// identity, and the coordinates come from the pointer the action names — reading
+// index 0 reports every finger at the first one's position.
int32_t onInput(android_app*, AInputEvent* ev) {
if (!eshost::booted() || AInputEvent_getType(ev) != AINPUT_EVENT_TYPE_MOTION) return 0;
- const int32_t action = AMotionEvent_getAction(ev) & AMOTION_EVENT_ACTION_MASK;
- const float x = AMotionEvent_getX(ev, 0);
- const float y = AMotionEvent_getY(ev, 0);
- int type;
- switch (action) {
- case AMOTION_EVENT_ACTION_DOWN:
- case AMOTION_EVENT_ACTION_POINTER_DOWN: type = 0; break;
- case AMOTION_EVENT_ACTION_MOVE: type = 1; break;
- case AMOTION_EVENT_ACTION_UP:
- case AMOTION_EVENT_ACTION_POINTER_UP: type = 2; break;
- default: type = 3; break;
- }
- eshost::touch(type, 0, x, y);
+ const eshost::input::MotionAction act = eshost::input::decodeMotion(AMotionEvent_getAction(ev));
+ if (!act.handled) return 0;
+ const size_t count = AMotionEvent_getPointerCount(ev);
+ const auto send = [&](size_t index) {
+ eshost::touch(act.phase, AMotionEvent_getPointerId(ev, index),
+ AMotionEvent_getX(ev, index), AMotionEvent_getY(ev, index));
+ };
+ if (act.allPointers) {
+ for (size_t i = 0; i < count; ++i) send(i);
+ } else if (static_cast<size_t>(act.index) < count) {
+ send(static_cast<size_t>(act.index));
+ }
return 1;
}
diff --git a/native/host/platform/ios.mm b/native/host/platform/ios.mm
index 73b0fa99b..f428f8bd9 100644
--- a/native/host/platform/ios.mm
+++ b/native/host/platform/ios.mm
@@ -25,6 +25,7 @@
#include "Host.hpp"
#include "platform/apple_common.hpp" // Core Text + NSURLSession, shared with macOS
+#include "platform/touch_stream.hpp"
using esengine::u32;
using esengine::u8;
@@ -183,6 +184,7 @@ IOSPlatform g_platform;
@implementation EstellaViewController {
CADisplayLink* _displayLink;
+ eshost::input::TouchIdTable _touchIds;
BOOL _booted;
UITextView* _editor;
BOOL _multiline;
@@ -191,7 +193,7 @@ IOSPlatform g_platform;
- (void)loadView {
self.view = [[EstellaMetalView alloc] initWithFrame:UIScreen.mainScreen.bounds];
- self.view.multipleTouchEnabled = NO; // the host feeds one touch id, as Android does
+ self.view.multipleTouchEnabled = YES; // one id per finger — see touch_stream.hpp
}
- (void)viewDidLoad {
@@ -248,26 +250,33 @@ IOSPlatform g_platform;
}
// UIKit touches are in points, top-left origin; the host contract is surface
-// pixels with the same origin (as on the web), so scale them here.
-- (void)dispatchTouches:(NSSet<UITouch*>*)touches type:(int)type {
- UITouch* t = touches.anyObject;
- if (!t) return;
- const CGPoint p = [t locationInView:self.view];
+// pixels with the same origin (as on the web), so scale them here. Every touch
+// in the set is dispatched under its OWN id: UIKit identifies a finger by the
+// UITouch object, which the table turns into the small stable id the engine
+// tracks a finger by.
+- (void)dispatchTouches:(NSSet<UITouch*>*)touches phase:(eshost::input::Phase)phase {
const CGFloat scale = self.view.contentScaleFactor;
- eshost::touch(type, 0, (float)(p.x * scale), (float)(p.y * scale));
+ const bool ending = phase == eshost::input::kTouchEnd || phase == eshost::input::kTouchCancel;
+ for (UITouch* t in touches) {
+ const void* key = (__bridge const void*)t;
+ const int touchId = ending ? _touchIds.release(key) : _touchIds.acquire(key);
+ if (touchId < 0) continue; // an end for a finger we never started, or past kMaxTouches
+ const CGPoint p = [t locationInView:self.view];
+ eshost::touch(phase, touchId, (float)(p.x * scale), (float)(p.y * scale));
+ }
}
- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
- [self dispatchTouches:touches type:0];
+ [self dispatchTouches:touches phase:eshost::input::kTouchStart];
}
- (void)touchesMoved:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
- [self dispatchTouches:touches type:1];
+ [self dispatchTouches:touches phase:eshost::input::kTouchMove];
}
- (void)touchesEnded:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
- [self dispatchTouches:touches type:2];
+ [self dispatchTouches:touches phase:eshost::input::kTouchEnd];
}
- (void)touchesCancelled:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
- [self dispatchTouches:touches type:3];
+ [self dispatchTouches:touches phase:eshost::input::kTouchCancel];
}
- (BOOL)prefersStatusBarHidden { return YES; }
diff --git a/native/host/platform/touch_stream.hpp b/native/host/platform/touch_stream.hpp
new file mode 100644
index 000000000..3a2804246
--- /dev/null
+++ b/native/host/platform/touch_stream.hpp
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file touch_stream.hpp
+ * @brief The touch stream every native platform feeds `eshost::touch` with.
+ *
+ * One finger is one id, alive from its start to its end or cancel, and
+ * two fingers down at once are two live ids. The engine, the web
+ * adapter and the mini-game adapter have always worked that way; a
+ * host that collapses every finger onto id 0 makes the second press
+ * release the first, so two on-screen buttons can never be held
+ * together.
+ *
+ * Platform-free on purpose: UIKit identifies a finger by the UITouch
+ * pointer and Android numbers its own, so what they share is the
+ * contract, and this is where it is stated and tested.
+ */
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+
+namespace eshost::input {
+
+/** Touch phases, valued as the `type` argument `eshost::touch` takes. */
+enum Phase : int {
+ kTouchStart = 0,
+ kTouchMove = 1,
+ kTouchEnd = 2,
+ kTouchCancel = 3,
+};
+
+/** How many fingers a host tracks at once. Ten is every finger a person has;
+ * past that the extra touch is dropped rather than aliased onto a live id. */
+inline constexpr int kMaxTouches = 10;
+
+/**
+ * Stable engine ids for a host that identifies a finger by a pointer (UIKit's
+ * UITouch*). Ids are the smallest free slot, so an ordinary two-finger gesture
+ * is 0 and 1, and a released id is reused only after its finger has ended.
+ *
+ * The pointer is a key, never dereferenced: it is only compared.
+ */
+class TouchIdTable {
+public:
+ /** This key's id, allocating one on first sight. -1 when full. */
+ int acquire(const void* key) {
+ const int existing = find(key);
+ if (existing >= 0) return existing;
+ for (int i = 0; i < kMaxTouches; ++i) {
+ if (keys_[i] == nullptr) {
+ keys_[i] = key;
+ return i;
+ }
+ }
+ return -1;
+ }
+
+ /** This key's id, or -1 when it holds none. */
+ int find(const void* key) const {
+ for (int i = 0; i < kMaxTouches; ++i) {
+ if (keys_[i] == key) return i;
+ }
+ return -1;
+ }
+
+ /** Free this key's id and answer it, or -1 when it held none. */
+ int release(const void* key) {
+ const int id = find(key);
+ if (id >= 0) keys_[id] = nullptr;
+ return id;
+ }
+
+ /** Drop every id — a host tearing its surface down owes no ends. */
+ void clear() {
+ for (int i = 0; i < kMaxTouches; ++i) keys_[i] = nullptr;
+ }
+
+ int live() const {
+ int n = 0;
+ for (int i = 0; i < kMaxTouches; ++i) {
+ if (keys_[i] != nullptr) ++n;
+ }
+ return n;
+ }
+
+private:
+ const void* keys_[kMaxTouches] = {};
+};
+
+// Android MotionEvent action constants. Fixed by the platform ABI; android.cpp
+// static_asserts these against the NDK's own so the two cannot drift.
+inline constexpr int32_t kMotionActionMask = 0xff;
+inline constexpr int32_t kMotionPointerIndexMask = 0xff00;
+inline constexpr int32_t kMotionPointerIndexShift = 8;
+inline constexpr int32_t kMotionActionDown = 0;
+inline constexpr int32_t kMotionActionUp = 1;
+inline constexpr int32_t kMotionActionMove = 2;
+inline constexpr int32_t kMotionActionCancel = 3;
+inline constexpr int32_t kMotionActionPointerDown = 5;
+inline constexpr int32_t kMotionActionPointerUp = 6;
+
+/** What one MotionEvent is about. `index` is the pointer it names, or every
+ * pointer in the event when `allPointers`; `handled` is false for an action
+ * that is not a touch at all (hover, scroll, outside). */
+struct MotionAction {
+ bool handled = false;
+ Phase phase = kTouchCancel;
+ bool allPointers = false;
+ int index = 0;
+};
+
+/**
+ * Decode a RAW `AMotionEvent_getAction` value — raw because the pointer a
+ * POINTER_DOWN/UP names is packed into the same word as the action, and reading
+ * only the masked action is exactly how a host ends up reporting every finger as
+ * the first one.
+ */
+inline MotionAction decodeMotion(int32_t action) {
+ MotionAction out;
+ const int32_t masked = action & kMotionActionMask;
+ const int index = static_cast<int>((action & kMotionPointerIndexMask) >> kMotionPointerIndexShift);
+ switch (masked) {
+ case kMotionActionDown: return { true, kTouchStart, false, 0 };
+ case kMotionActionPointerDown: return { true, kTouchStart, false, index };
+ case kMotionActionMove: return { true, kTouchMove, true, 0 };
+ case kMotionActionUp: return { true, kTouchEnd, false, 0 };
+ case kMotionActionPointerUp: return { true, kTouchEnd, false, index };
+ case kMotionActionCancel: return { true, kTouchCancel, true, 0 };
+ default: return out;
+ }
+}
+
+} // namespace eshost::input
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index eb8b6f902..334a6ae85 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -4185,6 +4185,7 @@ beginFixedStep: () => void
clearFrameState: () => void
clearVirtual: () => void
endFixedStep: () => void
+endTouch: (id: number) => void
gamepadButtonThreshold: number
gamepadDeadzone: number
gamepads: Map<number, PadState>
@@ -4196,6 +4197,8 @@ getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
getTouchCount: () => number
getTouches: () => TouchPoint[]
+getTouchesEnded: () => TouchPoint[]
+getTouchesStarted: () => TouchPoint[]
getVirtual: (id: string) => Vec2
injectGamepad: (snapshot: GamepadSnapshot) => void
isGamepadButtonDown: (button: number, pad?: number) => boolean
@@ -4233,7 +4236,7 @@ scrollDeltaY: number
setVirtual: (id: string, x: number, y?: number) => void
touchAvailable: boolean
touches: Map<number, TouchPoint>
-touchesEnded: Set<number>
+touchesEnded: Map<number, TouchPoint>
touchesStarted: Map<number, TouchPoint>
updateGamepads: (snapshots: GamepadSnapshot[]) => void
static new (): InputState
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 3247f1c21..5cfac2901 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -4193,6 +4193,7 @@ beginFixedStep: () => void
clearFrameState: () => void
clearVirtual: () => void
endFixedStep: () => void
+endTouch: (id: number) => void
gamepadButtonThreshold: number
gamepadDeadzone: number
gamepads: Map<number, PadState>
@@ -4204,6 +4205,8 @@ getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
getTouchCount: () => number
getTouches: () => TouchPoint[]
+getTouchesEnded: () => TouchPoint[]
+getTouchesStarted: () => TouchPoint[]
getVirtual: (id: string) => Vec2
injectGamepad: (snapshot: GamepadSnapshot) => void
isGamepadButtonDown: (button: number, pad?: number) => boolean
@@ -4241,7 +4244,7 @@ scrollDeltaY: number
setVirtual: (id: string, x: number, y?: number) => void
touchAvailable: boolean
touches: Map<number, TouchPoint>
-touchesEnded: Set<number>
+touchesEnded: Map<number, TouchPoint>
touchesStarted: Map<number, TouchPoint>
updateGamepads: (snapshots: GamepadSnapshot[]) => void
static new (): InputState
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 90a627e7b..fae8666fe 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -4180,6 +4180,7 @@ beginFixedStep: () => void
clearFrameState: () => void
clearVirtual: () => void
endFixedStep: () => void
+endTouch: (id: number) => void
gamepadButtonThreshold: number
gamepadDeadzone: number
gamepads: Map<number, PadState>
@@ -4191,6 +4192,8 @@ getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
getTouchCount: () => number
getTouches: () => TouchPoint[]
+getTouchesEnded: () => TouchPoint[]
+getTouchesStarted: () => TouchPoint[]
getVirtual: (id: string) => Vec2
injectGamepad: (snapshot: GamepadSnapshot) => void
isGamepadButtonDown: (button: number, pad?: number) => boolean
@@ -4228,7 +4231,7 @@ scrollDeltaY: number
setVirtual: (id: string, x: number, y?: number) => void
touchAvailable: boolean
touches: Map<number, TouchPoint>
-touchesEnded: Set<number>
+touchesEnded: Map<number, TouchPoint>
touchesStarted: Map<number, TouchPoint>
updateGamepads: (snapshots: GamepadSnapshot[]) => void
static new (): InputState
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 7da4c36f0..1a5966d29 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -4180,6 +4180,7 @@ beginFixedStep: () => void
clearFrameState: () => void
clearVirtual: () => void
endFixedStep: () => void
+endTouch: (id: number) => void
gamepadButtonThreshold: number
gamepadDeadzone: number
gamepads: Map<number, PadState>
@@ -4191,6 +4192,8 @@ getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
getTouchCount: () => number
getTouches: () => TouchPoint[]
+getTouchesEnded: () => TouchPoint[]
+getTouchesStarted: () => TouchPoint[]
getVirtual: (id: string) => Vec2
injectGamepad: (snapshot: GamepadSnapshot) => void
isGamepadButtonDown: (button: number, pad?: number) => boolean
@@ -4228,7 +4231,7 @@ scrollDeltaY: number
setVirtual: (id: string, x: number, y?: number) => void
touchAvailable: boolean
touches: Map<number, TouchPoint>
-touchesEnded: Set<number>
+touchesEnded: Map<number, TouchPoint>
touchesStarted: Map<number, TouchPoint>
updateGamepads: (snapshots: GamepadSnapshot[]) => void
static new (): InputState
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index 39a182e46..84750d916 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -4187,6 +4187,7 @@ beginFixedStep: () => void
clearFrameState: () => void
clearVirtual: () => void
endFixedStep: () => void
+endTouch: (id: number) => void
gamepadButtonThreshold: number
gamepadDeadzone: number
gamepads: Map<number, PadState>
@@ -4198,6 +4199,8 @@ getScrollDelta: () => { x: number; y: number; }
getTouch: (id: number) => TouchPoint | null
getTouchCount: () => number
getTouches: () => TouchPoint[]
+getTouchesEnded: () => TouchPoint[]
+getTouchesStarted: () => TouchPoint[]
getVirtual: (id: string) => Vec2
injectGamepad: (snapshot: GamepadSnapshot) => void
isGamepadButtonDown: (button: number, pad?: number) => boolean
@@ -4235,7 +4238,7 @@ scrollDeltaY: number
setVirtual: (id: string, x: number, y?: number) => void
touchAvailable: boolean
touches: Map<number, TouchPoint>
-touchesEnded: Set<number>
+touchesEnded: Map<number, TouchPoint>
touchesStarted: Map<number, TouchPoint>
updateGamepads: (snapshots: GamepadSnapshot[]) => void
static new (): InputState
diff --git a/sdk/src/input/gesture.ts b/sdk/src/input/gesture.ts
index 5d4c16b4d..ea2be6217 100644
--- a/sdk/src/input/gesture.ts
+++ b/sdk/src/input/gesture.ts
@@ -87,7 +87,7 @@ export class GestureDetector {
}
private processEnds_(): void {
- for (const id of this.input_.touchesEnded) {
+ for (const id of this.input_.touchesEnded.keys()) {
const track = this.tracks_.get(id);
if (!track) continue;
diff --git a/sdk/src/input/input.ts b/sdk/src/input/input.ts
index 49b07c471..505ff32b6 100644
--- a/sdk/src/input/input.ts
+++ b/sdk/src/input/input.ts
@@ -91,7 +91,9 @@ export class InputState {
touches = new Map<number, TouchPoint>();
touchesStarted = new Map<number, TouchPoint>();
- touchesEnded = new Set<number>();
+ /** Fingers lifted this frame, at the position they lifted AT — a release is
+ * hit-tested where it happened, and the live `touches` no longer hold it. */
+ touchesEnded = new Map<number, TouchPoint>();
// — Fixed-timestep edge mirrors —
// The render edges above are cleared once per rendered frame (Schedule.Last),
@@ -188,6 +190,24 @@ export class InputState {
return this.touches.has(id);
}
+ /** Fingers that went down this frame. */
+ getTouchesStarted(): TouchPoint[] {
+ return [...this.touchesStarted.values()];
+ }
+
+ /** Fingers that came up this frame, at the position they came up at. */
+ getTouchesEnded(): TouchPoint[] {
+ return [...this.touchesEnded.values()];
+ }
+
+ /** Retire a live touch, keeping where it was — the write door `onTouchEnd`
+ * and `onTouchCancel` share, so the two cannot record an end differently. */
+ endTouch(id: number): void {
+ const point = this.touches.get(id);
+ this.touches.delete(id);
+ this.touchesEnded.set(id, point ?? { id, x: 0, y: 0 });
+ }
+
// — Virtual (an on-screen control, or anything else that decides to be input) —
/**
* Named 2D values a game writes itself — an on-screen control, the only
@@ -426,13 +446,11 @@ export function inputEventCallbacks(state: InputState): InputEventCallbacks {
},
onTouchEnd(id) {
if (inputRouter.dispatchTouchEnd(id)) return;
- state.touches.delete(id);
- state.touchesEnded.add(id);
+ state.endTouch(id);
},
onTouchCancel(id) {
if (inputRouter.dispatchTouchCancel(id)) return;
- state.touches.delete(id);
- state.touchesEnded.add(id);
+ state.endTouch(id);
},
};
}
diff --git a/sdk/src/ui/input/interaction.ts b/sdk/src/ui/input/interaction.ts
index 8922cced9..87cdb9ad8 100644
--- a/sdk/src/ui/input/interaction.ts
+++ b/sdk/src/ui/input/interaction.ts
@@ -24,6 +24,7 @@ import { ensureComponent, walkParentChain } from '../util/helpers';
import type { CppRegistry } from '../../wasm';
import { engineApi } from '../../ecs/bridge/engineApi';
import { UILayoutGeneration } from '../layout/ui-layout-generation';
+import { UiPointerBook, uiPointersOf, type UiPointerSample } from './pointerBook';
import { SystemLabel, PluginName } from '../../ecs/systemLabels';
import type { UILayoutGenerationData } from '../layout/ui-layout-generation';
@@ -60,12 +61,12 @@ export class UIInteractionPlugin implements Plugin {
// included) — shared with every other producer, not owned by the UI.
const events = ensureEntityEvents(app);
- let hoveredEntity: Entity | null = null;
- let pressedEntity: Entity | null = null;
- let lastPointerX = NaN;
- let lastPointerY = NaN;
- let lastWorldPointerX = NaN;
- let lastWorldPointerY = NaN;
+ // The press policy lives in UiPointerBook; this system is its projection
+ // onto the world — a raycast per pointer, and the writes its verdicts
+ // imply. Gestures (drag, scroll, slider) stay on the primary pointer.
+ const book = new UiPointerBook();
+ /** Where each pointer last hit, so a settled pointer skips the raycast. */
+ const lastHit = new Map<number, { x: number; y: number; entity: Entity | null }>();
let lastLayoutGen = -1;
app.addSystemToSchedule(Schedule.PreUpdate, defineSystem(
@@ -90,101 +91,97 @@ export class UIInteractionPlugin implements Plugin {
if (!camera.valid && !overlay.active) { input.pointerOverUI = false; return; }
const dpr = platformDevicePixelRatio();
- const mouseGLX = input.mouseX * dpr;
const surfaceH = overlay.active ? overlay.surfaceH : camera.screenH;
- const mouseGLY = surfaceH - input.mouseY * dpr;
-
- // The pointer, once per domain. Neither is derived from the
- // other: each is the inverse of the projection that domain is
- // drawn with, which is what keeps a click where the pixel is.
- const worldMouse = camera.valid
- ? screenToUiWorld(camera, mouseGLX, mouseGLY)
- : { x: 0, y: 0 };
- camera.worldMouseX = worldMouse.x;
- camera.worldMouseY = worldMouse.y;
-
- const layoutMouse = overlay.active
- ? screenToUiLayout(overlay, mouseGLX, mouseGLY)
- : worldMouse;
- overlay.pointerX = layoutMouse.x;
- overlay.pointerY = layoutMouse.y;
-
- const mouseDown = input.isMouseButtonDown(0);
- const mousePressed = input.isMouseButtonPressed(0);
- const mouseReleased = input.isMouseButtonReleased(0);
-
- const pointerMoved = layoutMouse.x !== lastPointerX || layoutMouse.y !== lastPointerY
- || worldMouse.x !== lastWorldPointerX
- || worldMouse.y !== lastWorldPointerY;
+ const pointers = uiPointersOf(input);
const layoutChanged = layoutGen.generation !== lastLayoutGen;
- const hasMouseEvent = mousePressed || mouseReleased;
- const needsHitTest = pointerMoved || layoutChanged || hasMouseEvent;
-
- lastPointerX = layoutMouse.x;
- lastPointerY = layoutMouse.y;
- lastWorldPointerX = worldMouse.x;
- lastWorldPointerY = worldMouse.y;
lastLayoutGen = layoutGen.generation;
- let hitEntity: Entity | null = hoveredEntity;
- if (needsHitTest) {
- // With no camera there is no world ray: inverting a projection
- // never written yields NaN, which answers "no" by accident.
- // The screen's ray stands in — nothing is in the world.
- const screenRay = overlay.active
- ? uiLayoutRay(overlay, mouseGLX, mouseGLY) : undefined;
- const worldRay = camera.valid
- ? uiPointerRay(camera, mouseGLX, mouseGLY)
- : screenRay!;
- hitEntity = uiHitTestWorld(world, worldRay, screenRay);
- }
-
- if (hoveredEntity !== null && !world.valid(hoveredEntity)) {
- hoveredEntity = null;
- }
-
- // Gameplay reads this (Update) to skip input the UI claimed.
- input.pointerOverUI = hitEntity !== null;
-
- if (hoveredEntity !== hitEntity) {
- if (hoveredEntity !== null && world.valid(hoveredEntity) && world.has(hoveredEntity, UIInteraction)) {
- const prev = world.get(hoveredEntity, UIInteraction) as UIInteractionData;
- prev.hovered = false;
- world.insert(hoveredEntity, UIInteraction, prev);
- events.emit(hoveredEntity, UIEventType.HoverExit);
+ // The single-pointer resources every other consumer reads are the
+ // PRIMARY pointer's: the mouse, or the oldest finger on the glass.
+ let primaryWritten = false;
+ let overUI = false;
+
+ const hit = (pointer: UiPointerSample): Entity | null => {
+ const glX = pointer.x * dpr;
+ const glY = surfaceH - pointer.y * dpr;
+ // The pointer, once per domain. Neither is derived from the
+ // other: each is the inverse of the projection that domain is
+ // drawn with, which is what keeps a click where the pixel is.
+ const worldPointer = camera.valid ? screenToUiWorld(camera, glX, glY) : { x: 0, y: 0 };
+ const layoutPointer = overlay.active ? screenToUiLayout(overlay, glX, glY) : worldPointer;
+ if (!primaryWritten) {
+ primaryWritten = true;
+ camera.worldMouseX = worldPointer.x;
+ camera.worldMouseY = worldPointer.y;
+ overlay.pointerX = layoutPointer.x;
+ overlay.pointerY = layoutPointer.y;
+ }
+ const cached = lastHit.get(pointer.id);
+ const edge = pointer.pressed || pointer.released;
+ const settled = cached !== undefined
+ && cached.x === layoutPointer.x && cached.y === layoutPointer.y;
+ let entity: Entity | null;
+ if (settled && !layoutChanged && !edge) {
+ entity = cached.entity !== null && world.valid(cached.entity) ? cached.entity : null;
+ } else {
+ // With no camera there is no world ray: inverting a projection
+ // never written yields NaN, which answers "no" by accident.
+ // The screen's ray stands in — nothing is in the world.
+ const screenRay = overlay.active ? uiLayoutRay(overlay, glX, glY) : undefined;
+ const worldRay = camera.valid ? uiPointerRay(camera, glX, glY) : screenRay!;
+ entity = uiHitTestWorld(world, worldRay, screenRay);
+ lastHit.set(pointer.id, { x: layoutPointer.x, y: layoutPointer.y, entity });
}
- if (hitEntity !== null) {
- ensureComponent(world, hitEntity, UIInteraction);
- const curr = world.get(hitEntity, UIInteraction) as UIInteractionData;
- curr.hovered = true;
- world.insert(hitEntity, UIInteraction, curr);
- events.emit(hitEntity, UIEventType.HoverEnter);
+ if (entity !== null) overUI = true;
+ return entity;
+ };
+
+ const wasPressed = new Set(book.pressed);
+ for (const event of book.step(pointers, hit, (e) => world.valid(e))) {
+ switch (event.kind) {
+ case 'hoverEnter':
+ ensureComponent(world, event.entity, UIInteraction);
+ events.emit(event.entity, UIEventType.HoverEnter);
+ break;
+ case 'hoverExit':
+ events.emit(event.entity, UIEventType.HoverExit);
+ break;
+ case 'press':
+ ensureComponent(world, event.entity, UIInteraction);
+ emitWithBubbling(world, events, event.entity, UIEventType.Press);
+ break;
+ case 'release':
+ emitWithBubbling(world, events, event.entity, UIEventType.Release);
+ break;
+ case 'click':
+ emitWithBubbling(world, events, event.entity, UIEventType.Click);
+ break;
}
- hoveredEntity = hitEntity;
}
- if (mousePressed && hitEntity !== null) {
- const interaction = world.get(hitEntity, UIInteraction) as UIInteractionData;
- interaction.pressed = true;
- interaction.justPressed = true;
- world.insert(hitEntity, UIInteraction, interaction);
- pressedEntity = hitEntity;
- emitWithBubbling(world, events, hitEntity, UIEventType.Press);
+ // `hovered` and `pressed` are facts about the ENTITY: true while
+ // any pointer is over or holding it, false once none is.
+ const hovered = book.hovered;
+ const pressed = book.pressed;
+ const touched = new Set<Entity>([...interactionEntities, ...hovered, ...pressed, ...wasPressed]);
+ for (const entity of touched) {
+ if (!world.valid(entity) || !world.has(entity, UIInteraction)) continue;
+ const data = world.get(entity, UIInteraction) as UIInteractionData;
+ const isHovered = hovered.has(entity);
+ const isPressed = pressed.has(entity);
+ const justPressed = data.justPressed || (isPressed && !wasPressed.has(entity));
+ const justReleased = data.justReleased || (!isPressed && wasPressed.has(entity));
+ if (data.hovered === isHovered && data.pressed === isPressed
+ && data.justPressed === justPressed && data.justReleased === justReleased) continue;
+ data.hovered = isHovered;
+ data.pressed = isPressed;
+ data.justPressed = justPressed;
+ data.justReleased = justReleased;
+ world.insert(entity, UIInteraction, data);
}
- if (mouseReleased && pressedEntity !== null) {
- if (world.valid(pressedEntity) && world.has(pressedEntity, UIInteraction)) {
- const interaction = world.get(pressedEntity, UIInteraction) as UIInteractionData;
- interaction.pressed = false;
- interaction.justReleased = true;
- world.insert(pressedEntity, UIInteraction, interaction);
- emitWithBubbling(world, events, pressedEntity, UIEventType.Release);
- if (pressedEntity === hoveredEntity) {
- emitWithBubbling(world, events, pressedEntity, UIEventType.Click);
- }
- }
- pressedEntity = null;
- }
+ // Gameplay reads this (Update) to skip input the UI claimed.
+ input.pointerOverUI = overUI;
},
{ name: 'UIInteractionSystem' }
), { runAfter: [SystemLabel.UILayout], runIf: playModeOnly });
diff --git a/sdk/src/ui/input/pointerBook.ts b/sdk/src/ui/input/pointerBook.ts
new file mode 100644
index 000000000..d3146277b
--- /dev/null
+++ b/sdk/src/ui/input/pointerBook.ts
@@ -0,0 +1,167 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file pointerBook.ts
+ * @brief Which pointer is over what, and which pointer is holding what.
+ *
+ * A finger is a pointer of its own, so two on-screen buttons can be
+ * held at once. Folding every finger onto the synthesized mouse made
+ * the SECOND finger's release let go of the FIRST one's button, which
+ * is what a player feels as "the last press cancels the others".
+ *
+ * The policy lives here, apart from the raycast and the ECS writes it
+ * drives, so it can be exercised without a world: what a press over
+ * nothing means, when a release is a click, and when an entity stops
+ * being pressed while another finger still holds it.
+ */
+import type { Entity } from '../../types';
+import type { InputState } from '../../input/input';
+
+/** One pointer this frame. `hovers` is false for a finger that is not down: a
+ * finger is over a control only while it touches the glass. */
+export interface UiPointerSample {
+ id: number;
+ x: number;
+ y: number;
+ down: boolean;
+ pressed: boolean;
+ released: boolean;
+ hovers: boolean;
+}
+
+export type UiPointerEventKind = 'hoverEnter' | 'hoverExit' | 'press' | 'release' | 'click';
+
+export interface UiPointerEvent {
+ kind: UiPointerEventKind;
+ entity: Entity;
+ /** The pointer it happened under — a click carries which finger made it. */
+ pointer: number;
+}
+
+/** The pointer id the mouse (and the touch host's synthesized button) uses. No
+ * touch can collide with it: platform touch ids are non-negative. */
+export const MOUSE_POINTER = -1;
+
+/**
+ * This frame's pointers. A touch host synthesizes mouse button 0 from the FIRST
+ * finger, so while any finger is on the glass the fingers ARE the pointers —
+ * counting both presses every control twice. A finger that lifted this frame is
+ * still a pointer, carrying where it lifted: that is where its release lands.
+ */
+export function uiPointersOf(input: InputState): UiPointerSample[] {
+ const pointers: UiPointerSample[] = [];
+ if (input.touches.size > 0 || input.touchesEnded.size > 0) {
+ for (const t of input.touches.values()) {
+ pointers.push({
+ id: t.id, x: t.x, y: t.y, down: true,
+ pressed: input.touchesStarted.has(t.id), released: false, hovers: true,
+ });
+ }
+ for (const t of input.touchesEnded.values()) {
+ pointers.push({
+ id: t.id, x: t.x, y: t.y, down: false, pressed: false, released: true, hovers: false,
+ });
+ }
+ return pointers;
+ }
+ pointers.push({
+ id: MOUSE_POINTER, x: input.mouseX, y: input.mouseY,
+ down: input.isMouseButtonDown(0),
+ pressed: input.isMouseButtonPressed(0),
+ released: input.isMouseButtonReleased(0),
+ hovers: true,
+ });
+ return pointers;
+}
+
+export class UiPointerBook {
+ private hoveredBy_ = new Map<number, Entity>();
+ private pressedBy_ = new Map<number, Entity>();
+
+ /** Entities at least one pointer is over. */
+ get hovered(): ReadonlySet<Entity> {
+ return new Set(this.hoveredBy_.values());
+ }
+
+ /** Entities at least one pointer is holding down. */
+ get pressed(): ReadonlySet<Entity> {
+ return new Set(this.pressedBy_.values());
+ }
+
+ /** What this pointer is holding, if anything. */
+ pressedByPointer(pointer: number): Entity | null {
+ return this.pressedBy_.get(pointer) ?? null;
+ }
+
+ /**
+ * Fold this frame's pointers in and answer what happened, in the order it
+ * happened. `hit` is the entity under a pointer (null for none) and `alive`
+ * says whether an entity the book remembers still exists — a control
+ * despawned mid-press owes no events but must not stay held.
+ */
+ step(
+ pointers: readonly UiPointerSample[],
+ hit: (pointer: UiPointerSample) => Entity | null,
+ alive: (entity: Entity) => boolean,
+ ): UiPointerEvent[] {
+ const out: UiPointerEvent[] = [];
+ const live = new Set<number>();
+
+ for (const p of pointers) {
+ live.add(p.id);
+ const under = hit(p);
+
+ const was = this.hoveredBy_.get(p.id) ?? null;
+ const now = p.hovers ? under : null;
+ if (was !== now) {
+ if (was !== null && alive(was)) out.push({ kind: 'hoverExit', entity: was, pointer: p.id });
+ if (now !== null) out.push({ kind: 'hoverEnter', entity: now, pointer: p.id });
+ if (now === null) this.hoveredBy_.delete(p.id);
+ else this.hoveredBy_.set(p.id, now);
+ }
+
+ if (p.pressed && under !== null) {
+ this.pressedBy_.set(p.id, under);
+ out.push({ kind: 'press', entity: under, pointer: p.id });
+ }
+
+ // A pointer that is no longer down releases what it took, whether or
+ // not this is the frame it lifted on.
+ if (!p.down && this.pressedBy_.has(p.id)) {
+ const held = this.pressedBy_.get(p.id)!;
+ this.pressedBy_.delete(p.id);
+ if (alive(held)) {
+ out.push({ kind: 'release', entity: held, pointer: p.id });
+ // A click is a release over the control this pointer took —
+ // sliding off and letting go is a release and nothing more.
+ if (held === under) out.push({ kind: 'click', entity: held, pointer: p.id });
+ }
+ }
+ }
+
+ // A pointer that vanished without lifting — a cancelled gesture, a mouse
+ // that left the window — still owes its exit and its release.
+ for (const [id, entity] of [...this.hoveredBy_]) {
+ if (live.has(id)) continue;
+ this.hoveredBy_.delete(id);
+ if (alive(entity)) out.push({ kind: 'hoverExit', entity, pointer: id });
+ }
+ for (const [id, entity] of [...this.pressedBy_]) {
+ if (live.has(id)) continue;
+ this.pressedBy_.delete(id);
+ if (alive(entity)) out.push({ kind: 'release', entity, pointer: id });
+ }
+
+ // A control that died under a pointer stops being held, silently.
+ for (const [id, entity] of [...this.hoveredBy_]) if (!alive(entity)) this.hoveredBy_.delete(id);
+ for (const [id, entity] of [...this.pressedBy_]) if (!alive(entity)) this.pressedBy_.delete(id);
+
+ return out;
+ }
+
+ /** Forget every pointer — a realm tearing its UI down owes no events. */
+ clear(): void {
+ this.hoveredBy_.clear();
+ this.pressedBy_.clear();
+ }
+}
diff --git a/sdk/tests/gesture.test.ts b/sdk/tests/gesture.test.ts
index e7756a385..78e966143 100644
--- a/sdk/tests/gesture.test.ts
+++ b/sdk/tests/gesture.test.ts
@@ -24,7 +24,7 @@ describe('GestureDetector', () => {
input.clearFrameState();
input.touches.delete(0);
- input.touchesEnded.add(0);
+ input.touchesEnded.set(0, { id: 0, x: 0, y: 0 });
gesture.update(0.016);
expect(onTap).toHaveBeenCalledWith(100, 100);
@@ -45,7 +45,7 @@ describe('GestureDetector', () => {
input.clearFrameState();
input.touches.delete(0);
- input.touchesEnded.add(0);
+ input.touchesEnded.set(0, { id: 0, x: 0, y: 0 });
gesture.update(0.016);
expect(onTap).not.toHaveBeenCalled();
@@ -67,7 +67,7 @@ describe('GestureDetector', () => {
input.clearFrameState();
input.touches.delete(0);
- input.touchesEnded.add(0);
+ input.touchesEnded.set(0, { id: 0, x: 0, y: 0 });
gesture.update(0.016);
expect(onSwipe).toHaveBeenCalledWith('right', expect.any(Number));
diff --git a/sdk/tests/input-multitouch.test.ts b/sdk/tests/input-multitouch.test.ts
index 92597d40b..fdd4cf5ea 100644
--- a/sdk/tests/input-multitouch.test.ts
+++ b/sdk/tests/input-multitouch.test.ts
@@ -51,7 +51,7 @@ describe('InputState multi-touch', () => {
input.touches.set(1, { id: 1, x: 30, y: 40 });
input.touches.delete(0);
- input.touchesEnded.add(0);
+ input.touchesEnded.set(0, { id: 0, x: 0, y: 0 });
expect(input.getTouchCount()).toBe(1);
expect(input.isTouchActive(0)).toBe(false);
@@ -60,7 +60,7 @@ describe('InputState multi-touch', () => {
it('should clear per-frame touch state', () => {
input.touchesStarted.set(0, { id: 0, x: 10, y: 20 });
- input.touchesEnded.add(1);
+ input.touchesEnded.set(1, { id: 1, x: 0, y: 0 });
input.touches.set(0, { id: 0, x: 10, y: 20 });
input.clearFrameState();
diff --git a/sdk/tests/ui-multi-pointer.test.ts b/sdk/tests/ui-multi-pointer.test.ts
new file mode 100644
index 000000000..ceaed11e6
--- /dev/null
+++ b/sdk/tests/ui-multi-pointer.test.ts
@@ -0,0 +1,134 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file ui-multi-pointer.test.ts
+ * @brief Two on-screen buttons, held at once: each finger is a pointer of its
+ * own, one letting go never releases another's control, and a control
+ * two fingers hold stays pressed until the last one lifts.
+ */
+import { describe, it, expect } from 'vitest';
+import { UiPointerBook, uiPointersOf, MOUSE_POINTER, type UiPointerSample } from '../src/ui/input/pointerBook';
+import { InputState } from '../src/input/input';
+import type { Entity } from '../src/types';
+
+const BUTTON_A = 1 as Entity;
+const BUTTON_B = 2 as Entity;
+
+/** A screen with one control per x: x<100 is A, x<200 is B, past that nothing. */
+const screen = (p: UiPointerSample): Entity | null =>
+ (p.x < 100 ? BUTTON_A : p.x < 200 ? BUTTON_B : null);
+
+const finger = (id: number, x: number, over: Partial<UiPointerSample> = {}): UiPointerSample => ({
+ id, x, y: 0, down: true, pressed: false, released: false, hovers: true, ...over,
+});
+
+const kinds = (events: ReturnType<UiPointerBook['step']>, entity: Entity): string[] =>
+ events.filter((e) => e.entity === entity).map((e) => e.kind);
+
+describe('two fingers, two buttons', () => {
+ it('holds both, and one letting go does not release the other', () => {
+ const book = new UiPointerBook();
+ const alive = () => true;
+
+ book.step([finger(0, 10, { pressed: true })], screen, alive);
+ expect([...book.pressed]).toEqual([BUTTON_A]);
+
+ const second = book.step([finger(0, 10), finger(1, 150, { pressed: true })], screen, alive);
+ expect(kinds(second, BUTTON_B)).toContain('press');
+ expect(kinds(second, BUTTON_A)).not.toContain('release');
+ expect([...book.pressed].sort()).toEqual([BUTTON_A, BUTTON_B]);
+
+ // B lifts. A is still down and must stay pressed — the whole bug.
+ const lift = book.step(
+ [finger(0, 10), finger(1, 150, { down: false, released: true, hovers: false })],
+ screen, alive,
+ );
+ expect(kinds(lift, BUTTON_B)).toEqual(['hoverExit', 'release', 'click']);
+ expect(kinds(lift, BUTTON_A)).toEqual([]);
+ expect([...book.pressed]).toEqual([BUTTON_A]);
+
+ const last = book.step([finger(0, 10, { down: false, released: true, hovers: false })], screen, alive);
+ expect(kinds(last, BUTTON_A)).toEqual(['hoverExit', 'release', 'click']);
+ expect([...book.pressed]).toEqual([]);
+ });
+
+ it('a control two fingers hold stays pressed until the last one lets go', () => {
+ const book = new UiPointerBook();
+ const alive = () => true;
+ book.step([finger(0, 10, { pressed: true }), finger(1, 20, { pressed: true })], screen, alive);
+ expect([...book.pressed]).toEqual([BUTTON_A]);
+
+ book.step([finger(0, 10), finger(1, 20, { down: false, released: true, hovers: false })], screen, alive);
+ expect([...book.pressed]).toEqual([BUTTON_A]);
+
+ book.step([finger(0, 10, { down: false, released: true, hovers: false })], screen, alive);
+ expect([...book.pressed]).toEqual([]);
+ });
+
+ it('sliding off before letting go is a release, not a click', () => {
+ const book = new UiPointerBook();
+ const alive = () => true;
+ book.step([finger(0, 10, { pressed: true })], screen, alive);
+ const off = book.step([finger(0, 150, { down: false, released: true, hovers: false })], screen, alive);
+ expect(kinds(off, BUTTON_A)).toEqual(['hoverExit', 'release']);
+ });
+
+ it('a finger that vanishes without lifting still releases what it held', () => {
+ const book = new UiPointerBook();
+ const alive = () => true;
+ book.step([finger(0, 10, { pressed: true })], screen, alive);
+ const gone = book.step([], screen, alive);
+ expect(kinds(gone, BUTTON_A)).toEqual(['hoverExit', 'release']);
+ expect([...book.pressed]).toEqual([]);
+ });
+
+ it('a control despawned under a finger is dropped without events', () => {
+ const book = new UiPointerBook();
+ book.step([finger(0, 10, { pressed: true })], screen, () => true);
+ const dead = book.step([finger(0, 10, { down: false, released: true, hovers: false })], screen, () => false);
+ expect(dead).toEqual([]);
+ expect([...book.pressed]).toEqual([]);
+ });
+
+ it('a finger hovers only while it is down', () => {
+ const book = new UiPointerBook();
+ const alive = () => true;
+ const down = book.step([finger(0, 10, { pressed: true })], screen, alive);
+ expect(kinds(down, BUTTON_A)).toEqual(['hoverEnter', 'press']);
+ const up = book.step([finger(0, 10, { down: false, released: true, hovers: false })], screen, alive);
+ expect(kinds(up, BUTTON_A)).toEqual(['hoverExit', 'release', 'click']);
+ });
+});
+
+describe('the pointer set a frame of input makes', () => {
+ it('is the mouse when nothing is touching the glass', () => {
+ const input = new InputState();
+ input.mouseX = 42;
+ input.noteMouseDown(0);
+ const [p] = uiPointersOf(input);
+ expect(p.id).toBe(MOUSE_POINTER);
+ expect(p.pressed).toBe(true);
+ expect(p.down).toBe(true);
+ });
+
+ it('is the fingers while any is down — never both, or one finger presses twice', () => {
+ const input = new InputState();
+ // What a touch host does: the primary finger also synthesizes button 0.
+ input.touches.set(0, { id: 0, x: 10, y: 5 });
+ input.touchesStarted.set(0, { id: 0, x: 10, y: 5 });
+ input.noteMouseDown(0);
+ const pointers = uiPointersOf(input);
+ expect(pointers).toHaveLength(1);
+ expect(pointers[0].id).toBe(0);
+ expect(pointers[0].pressed).toBe(true);
+ });
+
+ it('keeps a lifted finger for the frame it lifted on, where it lifted', () => {
+ const input = new InputState();
+ input.touches.set(3, { id: 3, x: 70, y: 90 });
+ input.endTouch(3);
+ const pointers = uiPointersOf(input);
+ expect(pointers).toHaveLength(1);
+ expect(pointers[0]).toMatchObject({ id: 3, x: 70, y: 90, down: false, released: true, hovers: false });
+ });
+});
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 6812a16f6..f7b1a96e2 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -24,6 +24,15 @@ add_executable(test_particle
target_link_libraries(test_particle PRIVATE esengine)
add_test(NAME test_particle COMMAND test_particle)
+# The native touch stream: header-only, so it builds without an NDK or an SDK and
+# the ONE contract both mobile hosts feed is tested off-device (see
+# native/host/platform/touch_stream.hpp).
+add_executable(test_touch_stream
+ input/test_touch_stream.cpp
+)
+target_include_directories(test_touch_stream PRIVATE ${CMAKE_SOURCE_DIR}/native/host)
+add_test(NAME test_touch_stream COMMAND test_touch_stream)
+
# Tilemap system tests
add_executable(test_tilemap
tilemap/test_tilemap.cpp
diff --git a/tests/input/test_touch_stream.cpp b/tests/input/test_touch_stream.cpp
new file mode 100644
index 000000000..74369d09d
--- /dev/null
+++ b/tests/input/test_touch_stream.cpp
@@ -0,0 +1,95 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file The native touch stream: one id per finger, alive from its start to its
+ * end. Both mobile hosts collapsed every finger onto id 0, so a second
+ * button press released the first — two buttons could never be held at
+ * once. The decoding is here rather than in the platform files because
+ * neither of those can be built off-device.
+ */
+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
+#include "doctest.h"
+
+#include "platform/touch_stream.hpp"
+
+using namespace eshost::input;
+
+/** A raw MotionEvent action word: the pointer a POINTER_DOWN/UP names is packed
+ * in beside the action, which is what makes reading the masked action alone a
+ * report about the wrong finger. */
+static int32_t rawAction(int32_t action, int pointerIndex) {
+ return action | (pointerIndex << kMotionPointerIndexShift);
+}
+
+TEST_CASE("a MotionEvent names the pointer it is about") {
+ SUBCASE("the first finger down") {
+ const MotionAction a = decodeMotion(kMotionActionDown);
+ CHECK(a.handled);
+ CHECK(a.phase == kTouchStart);
+ CHECK_FALSE(a.allPointers);
+ CHECK(a.index == 0);
+ }
+ SUBCASE("a second finger down names its own index") {
+ const MotionAction a = decodeMotion(rawAction(kMotionActionPointerDown, 1));
+ CHECK(a.handled);
+ CHECK(a.phase == kTouchStart);
+ CHECK(a.index == 1);
+ }
+ SUBCASE("a second finger up names its own index") {
+ const MotionAction a = decodeMotion(rawAction(kMotionActionPointerUp, 2));
+ CHECK(a.handled);
+ CHECK(a.phase == kTouchEnd);
+ CHECK(a.index == 2);
+ }
+ SUBCASE("a move is about every finger on the screen") {
+ const MotionAction a = decodeMotion(kMotionActionMove);
+ CHECK(a.phase == kTouchMove);
+ CHECK(a.allPointers);
+ }
+ SUBCASE("a cancel releases every finger") {
+ const MotionAction a = decodeMotion(kMotionActionCancel);
+ CHECK(a.phase == kTouchCancel);
+ CHECK(a.allPointers);
+ }
+ SUBCASE("anything else is not a touch") {
+ CHECK_FALSE(decodeMotion(7 /* HOVER_MOVE */).handled);
+ CHECK_FALSE(decodeMotion(4 /* OUTSIDE */).handled);
+ }
+}
+
+TEST_CASE("a pointer-identified finger keeps one id for its whole life") {
+ TouchIdTable ids;
+ int a = 1, b = 2, c = 3;
+
+ const int first = ids.acquire(&a);
+ const int second = ids.acquire(&b);
+ CHECK(first == 0);
+ CHECK(second == 1);
+ CHECK(first != second);
+ // Moving is not a new finger.
+ CHECK(ids.acquire(&a) == first);
+ CHECK(ids.live() == 2);
+
+ // Ending the SECOND must not disturb the first — the bug this file exists for.
+ CHECK(ids.release(&b) == second);
+ CHECK(ids.find(&a) == first);
+ CHECK(ids.live() == 1);
+
+ // A freed id is reused, and only after its finger ended.
+ CHECK(ids.acquire(&c) == second);
+ CHECK(ids.release(&c) == second);
+
+ // An end for a finger that never started is not an end for someone else's.
+ CHECK(ids.release(&c) == -1);
+
+ ids.clear();
+ CHECK(ids.live() == 0);
+}
+
+TEST_CASE("a full table drops the extra finger rather than aliasing a live one") {
+ TouchIdTable ids;
+ int keys[kMaxTouches + 1] = {};
+ for (int i = 0; i < kMaxTouches; ++i) CHECK(ids.acquire(&keys[i]) == i);
+ CHECK(ids.acquire(&keys[kMaxTouches]) == -1);
+ CHECK(ids.live() == kMaxTouches);
+}