@forgeax/engine-input 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +312 -0
  3. package/dist/.tsbuildinfo +1 -0
  4. package/dist/__tests__/browser-backend-dual-instance.test.d.ts +2 -0
  5. package/dist/__tests__/browser-backend-dual-instance.test.d.ts.map +1 -0
  6. package/dist/__tests__/browser-backend-focus-loss.test.d.ts +2 -0
  7. package/dist/__tests__/browser-backend-focus-loss.test.d.ts.map +1 -0
  8. package/dist/__tests__/browser-backend-lock-error.test.d.ts +2 -0
  9. package/dist/__tests__/browser-backend-lock-error.test.d.ts.map +1 -0
  10. package/dist/__tests__/browser-backend-lock-gate.test.d.ts +2 -0
  11. package/dist/__tests__/browser-backend-lock-gate.test.d.ts.map +1 -0
  12. package/dist/__tests__/browser-backend-lock-release.test.d.ts +2 -0
  13. package/dist/__tests__/browser-backend-lock-release.test.d.ts.map +1 -0
  14. package/dist/__tests__/browser-backend-lock-state.test.d.ts +2 -0
  15. package/dist/__tests__/browser-backend-lock-state.test.d.ts.map +1 -0
  16. package/dist/__tests__/canvas-input-boundary.test.d.ts +2 -0
  17. package/dist/__tests__/canvas-input-boundary.test.d.ts.map +1 -0
  18. package/dist/__tests__/canvas-input-owner.test-d.d.ts +2 -0
  19. package/dist/__tests__/canvas-input-owner.test-d.d.ts.map +1 -0
  20. package/dist/__tests__/composite-backend.test.d.ts +2 -0
  21. package/dist/__tests__/composite-backend.test.d.ts.map +1 -0
  22. package/dist/__tests__/controller-platform-owner.test-d.d.ts +2 -0
  23. package/dist/__tests__/controller-platform-owner.test-d.d.ts.map +1 -0
  24. package/dist/__tests__/input-snapshot.test-d.d.ts +2 -0
  25. package/dist/__tests__/input-snapshot.test-d.d.ts.map +1 -0
  26. package/dist/__tests__/input-snapshot.test.d.ts +2 -0
  27. package/dist/__tests__/input-snapshot.test.d.ts.map +1 -0
  28. package/dist/__tests__/swipe-direction-owner.test-d.d.ts +2 -0
  29. package/dist/__tests__/swipe-direction-owner.test-d.d.ts.map +1 -0
  30. package/dist/__tests__/ui-input-matrix.test.d.ts +2 -0
  31. package/dist/__tests__/ui-input-matrix.test.d.ts.map +1 -0
  32. package/dist/__tests__/ui-ownership-edge.test.d.ts +2 -0
  33. package/dist/__tests__/ui-ownership-edge.test.d.ts.map +1 -0
  34. package/dist/__tests__/ui-ownership.test.d.ts +2 -0
  35. package/dist/__tests__/ui-ownership.test.d.ts.map +1 -0
  36. package/dist/__tests__/ui-reset-idempotence.test.d.ts +2 -0
  37. package/dist/__tests__/ui-reset-idempotence.test.d.ts.map +1 -0
  38. package/dist/__tests__/ui-reset.test.d.ts +2 -0
  39. package/dist/__tests__/ui-reset.test.d.ts.map +1 -0
  40. package/dist/action-state.d.ts +146 -0
  41. package/dist/action-state.d.ts.map +1 -0
  42. package/dist/browser-backend.d.ts +121 -0
  43. package/dist/browser-backend.d.ts.map +1 -0
  44. package/dist/canvas-input-boundary.d.ts +13 -0
  45. package/dist/canvas-input-boundary.d.ts.map +1 -0
  46. package/dist/composite-backend.d.ts +34 -0
  47. package/dist/composite-backend.d.ts.map +1 -0
  48. package/dist/controller-db-data.d.ts +5 -0
  49. package/dist/controller-db-data.d.ts.map +1 -0
  50. package/dist/controller-db-data.mjs +12 -0
  51. package/dist/controller-db-data.mjs.map +1 -0
  52. package/dist/controller-db.d.ts +70 -0
  53. package/dist/controller-db.d.ts.map +1 -0
  54. package/dist/controller-db.mjs +119 -0
  55. package/dist/controller-db.mjs.map +1 -0
  56. package/dist/frame-start-scan-system.d.ts +37 -0
  57. package/dist/frame-start-scan-system.d.ts.map +1 -0
  58. package/dist/gamepad-frame.d.ts +42 -0
  59. package/dist/gamepad-frame.d.ts.map +1 -0
  60. package/dist/gesture-recognizer.d.ts +145 -0
  61. package/dist/gesture-recognizer.d.ts.map +1 -0
  62. package/dist/index.d.ts +13 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.mjs +1502 -0
  65. package/dist/index.mjs.map +1 -0
  66. package/dist/input-snapshot.d.ts +420 -0
  67. package/dist/input-snapshot.d.ts.map +1 -0
  68. package/dist/plugin-service.d.ts +11 -0
  69. package/dist/plugin-service.d.ts.map +1 -0
  70. package/dist/ui-ownership.d.ts +17 -0
  71. package/dist/ui-ownership.d.ts.map +1 -0
  72. package/dist/virtual-joystick.d.ts +39 -0
  73. package/dist/virtual-joystick.d.ts.map +1 -0
  74. package/package.json +72 -0
  75. package/src/__tests__/browser-backend-dual-instance.test.ts +379 -0
  76. package/src/__tests__/browser-backend-focus-loss.test.ts +239 -0
  77. package/src/__tests__/browser-backend-lock-error.test.ts +425 -0
  78. package/src/__tests__/browser-backend-lock-gate.test.ts +283 -0
  79. package/src/__tests__/browser-backend-lock-release.test.ts +641 -0
  80. package/src/__tests__/browser-backend-lock-state.test.ts +604 -0
  81. package/src/__tests__/canvas-input-boundary.test.ts +65 -0
  82. package/src/__tests__/canvas-input-owner.test-d.ts +39 -0
  83. package/src/__tests__/composite-backend.test.ts +299 -0
  84. package/src/__tests__/controller-platform-owner.test-d.ts +46 -0
  85. package/src/__tests__/input-snapshot.test-d.ts +78 -0
  86. package/src/__tests__/input-snapshot.test.ts +96 -0
  87. package/src/__tests__/swipe-direction-owner.test-d.ts +45 -0
  88. package/src/__tests__/ui-input-matrix.test.ts +31 -0
  89. package/src/__tests__/ui-ownership-edge.test.ts +33 -0
  90. package/src/__tests__/ui-ownership.test.ts +35 -0
  91. package/src/__tests__/ui-reset-idempotence.test.ts +17 -0
  92. package/src/__tests__/ui-reset.test.ts +25 -0
  93. package/src/action-state.ts +380 -0
  94. package/src/browser-backend.ts +884 -0
  95. package/src/canvas-input-boundary.ts +81 -0
  96. package/src/composite-backend.ts +189 -0
  97. package/src/controller-db-data.ts +25 -0
  98. package/src/controller-db.ts +218 -0
  99. package/src/frame-start-scan-system.ts +93 -0
  100. package/src/gamepad-frame.ts +259 -0
  101. package/src/gesture-recognizer.ts +495 -0
  102. package/src/index.ts +101 -0
  103. package/src/input-snapshot.ts +732 -0
  104. package/src/plugin-service.ts +31 -0
  105. package/src/ui-ownership.ts +61 -0
  106. package/src/virtual-joystick.ts +103 -0
  107. package/vendor/gamecontrollerdb.txt +2114 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,312 @@
1
+ # @forgeax/engine-input
2
+
3
+ > **Frame-start scanned, frozen `InputSnapshot` Resource for forgeax-engine.** Multi-device surface frozen before user systems run each frame: keyboard (logical key + physical code held/press/release edges) + mouse (position / movementDelta / button held/press/release edges / wheelDelta) + gamepad (7 readpoints: button / buttonValue / justPressed / justReleased / axis / standardMapping / connected) + pointer (per-pointerId position / pressure / delta / phase event queue) + virtualAxis (named joystick readpoint). Higher-level abstractions: **action indirection** (declare once, forget device — `snap.action(name)` / `snap.getAxis` / `snap.getVector`) + **gesture recognizer** (pinch / rotate / swipe / long-press / double-tap — `snap.gesture` + `snap.gestureEvents`). Capability probe (`snap.capabilities`) available at attach time.
4
+
5
+ `inputBackendPlugin(backend)` provides a host-owned backend without taking its
6
+ lifetime. `ownedInputBackendPlugin(backend, dispose)` is the canvas-App form:
7
+ DOM listener release is an effect of the same provider Fiber. World snapshot
8
+ resources and scan systems remain a separate consumer capability.
9
+
10
+ ## 4 步 recipe
11
+
12
+ ```ts
13
+ import { Update, World } from '@forgeax/engine-ecs';
14
+ import {
15
+ attachBrowserInputBackend,
16
+ INPUT_BACKEND_KEY,
17
+ INPUT_MAP_KEY,
18
+ InputFrameStartScan,
19
+ type InputSnapshot,
20
+ } from '@forgeax/engine-input';
21
+
22
+ // 1. attach browser backend (PointerLock + keyboard/mouse listeners) to a canvas
23
+ const detach = attachBrowserInputBackend(canvas);
24
+
25
+ // 2. insert the backend as a Resource + add the frame-start scan system token;
26
+ // it freezes the snapshot into the 'InputSnapshot' Resource before any user
27
+ // system runs (charter P5 split: backend = producer, scan-system + Resource
28
+ // = consumer). Insert the backend BEFORE the system so its ParamValidation
29
+ // finds the resource on the first tick.
30
+ const world = new World();
31
+ world.insertResource(INPUT_BACKEND_KEY, detach.backend);
32
+
33
+ // 2b. (optional) declare an InputMap to enable action readpoints.
34
+ // Duplicate action names → last-wins. Per-action deadzone default: 0.2.
35
+ world.insertResource(INPUT_MAP_KEY, [
36
+ { action: 'jump', bindings: [{ type: 'key', key: ' ' }, { type: 'gamepadButton', button: 0 }] },
37
+ { action: 'moveLeft', bindings: [{ type: 'key', key: 'a' }, { type: 'gamepadAxis', axis: 0, sign: -1 }] },
38
+ { action: 'moveRight', bindings: [{ type: 'key', key: 'd' }, { type: 'gamepadAxis', axis: 0, sign: 1 }] },
39
+ { action: 'moveUp', bindings: [{ type: 'key', key: 'w' }, { type: 'gamepadAxis', axis: 1, sign: -1 }] },
40
+ { action: 'moveDown', bindings: [{ type: 'key', key: 's' }, { type: 'gamepadAxis', axis: 1, sign: 1 }] },
41
+ ]);
42
+
43
+ world.addSystem(Update, InputFrameStartScan);
44
+
45
+ // 3. user system reads the frozen snapshot via the standard Resource API;
46
+ // multi-device surface: keyboard + mouse + gamepad + pointer + virtualAxis
47
+ // + action + gesture
48
+ world.addSystem(Update, {
49
+ name: 'first-person-camera',
50
+ after: ['input-frame-start-scan'],
51
+ queries: [],
52
+ fn: (w) => {
53
+ const snap = w.getResource<InputSnapshot>('InputSnapshot');
54
+ // action: declare once, forget device — same isPressed() for keyboard AND gamepad
55
+ if (snap.action('jump').justPressed()) {/* jump (space or gamepad A) */}
56
+ const move = snap.getVector('moveLeft', 'moveRight', 'moveUp', 'moveDown');
57
+ // move.x / move.y: circular deadzone [−1,1], WASD diagonal magnitude 1
58
+ if (snap.keyboard.down('w')) {/* move forward */}
59
+ const { x, y } = snap.mouse.movementDelta;
60
+ if (snap.mouse.button(0)) {/* primary down */}
61
+ // gamepad: button / buttonValue / justPressed / justReleased / axis
62
+ if (snap.gamepad(0).button(0)) {/* gamepad A pressed */}
63
+ const lx = snap.gamepad(0).axis(0); // left stick X
64
+ // pointer: per-pointerId position + pressure + delta
65
+ const touch = snap.pointer(0);
66
+ if (touch.active) {/* use touch.x, touch.y, touch.pressure */}
67
+ // virtualAxis: named joystick readpoint (zero-vector for unbound)
68
+ const joy = snap.virtualAxis('move');
69
+ // gesture: pinch/rotate continuous values + one-frame lifecycle events
70
+ const gs = snap.gesture.pinchScale;
71
+ const ga = snap.gesture.rotationAngle;
72
+ const gevs = snap.gestureEvents; // GestureEvent[] one-frame lifecycle
73
+ // capability probe (frozen at attach time)
74
+ const hasGamepad = snap.capabilities.gamepad;
75
+ },
76
+ });
77
+
78
+ // 4. on shutdown: detach the listeners so multiple Engine instances do not
79
+ // leak handlers (charter P3 explicit failure: detach is part of the contract)
80
+ detach();
81
+ ```
82
+
83
+ ## 多设备表面(charter F2 minimal surface)
84
+
85
+ ### keyboard (6 read points)
86
+
87
+ | 调用 | 返回 | 语义 |
88
+ |:--|:--|:--|
89
+ | `snap.keyboard.down(key)` | `boolean` | `key` 当前帧首仍处于按下状态(`document.hasFocus()` 失焦时保持上一帧状态) |
90
+ | `snap.keyboard.justPressed(key)` | `boolean` | 上一帧未按、本帧按下(一帧寿命;首帧 held key 视为刚按下) |
91
+ | `snap.keyboard.up(key)` | `boolean` | `key` 上一帧 down、本帧 up 的边沿(一帧内 true,下一帧自动消失) |
92
+ | `snap.keyboard.downCode(code)` | `boolean` | `KeyboardEvent.code` physical code 当前帧按下;例如 `KeyA` 不随键盘布局改变 |
93
+ | `snap.keyboard.justPressedCode(code)` | `boolean` | physical code 上一帧未按、本帧按下(一帧寿命) |
94
+ | `snap.keyboard.upCode(code)` | `boolean` | physical code 上一帧按下、本帧释放(一帧寿命) |
95
+
96
+ ### mouse(5 读点)
97
+
98
+ | 调用 | 返回 | 语义 |
99
+ |:--|:--|:--|
100
+ | `snap.mouse.position` | `{ x: number; y: number } | undefined` | 最新 canvas-pixel 鼠标坐标;悬停时也更新,不需要按键或 pointer capture;尚未收到鼠标事件时为 `undefined` |
101
+ | `snap.mouse.movementDelta` | `{ x: number; y: number }` | PointerLock `movementX/Y` 自上次扫描以来的累加;扫描后 backend 自动清零 |
102
+ | `snap.mouse.pointerLocked` | `boolean` | 合并锁态——W3C `pointerlockchange`(`pointerLockElement === canvas`)OR host `lockProvider.requestLock()` 置位;`required` 字段,非 optional。consumer 写 `if (snap.mouse.pointerLocked)` 判断"仅锁定态消费 look delta"。与 `movementDelta` 同位——两个事实在同一属性路径下(charter F1 单点可索引) |
103
+ | `snap.mouse.button(i)` | `boolean`(`i: 0 \| 1 \| 2`) | 对齐 W3C MouseEvent.button:0=主键 / 1=辅助键 / 2=次键。`i: 3` 触发 TS 编译错误 |
104
+ | `snap.mouse.justPressed(i)` / `justReleased(i)` | `boolean` | 鼠标按钮帧边沿;首帧 held 按钮视为刚按下 |
105
+ | `snap.mouse.wheelDelta` | `number` | 每帧 sign-discrete 滚轮 notches 累加(W3C `WheelEvent.deltaY`:正=下滚/负=上滚);frame-start 冻结后清零。OOS-7:轨迹板高精度滚动未展开(sub-notch 量值保留给未来 `ScrollSnapshot`) |
106
+
107
+ ### gamepad(7 读点)
108
+
109
+ | 调用 | 返回 | 语义 |
110
+ |:--|:--|:--|
111
+ | `snap.gamepad(i).connected` | `boolean` | slot `i` 已连接(index-based,null-padded 自动跳过)。越界 / 断连 → `false` |
112
+ | `snap.gamepad(i).standardMapping` | `boolean` | Standard layout available: **true** when browser reports `mapping==='standard'` **or** the SDL controller DB has normalized a non-standard layout (D-1 redline). `false` = not standard AND DB miss/unavailable — explicitly detectable (AC-10/E-2). When false, all readpoints return empty signals. |
113
+ | `snap.gamepad(i).button(b)` | `boolean`(`b: 0\|1\|...\|16`) | 按钮 `b` 当前帧按下(held)。越界字面量触发 TS 编译错误 |
114
+ | `snap.gamepad(i).buttonValue(b)` | `number` | 按钮 `b` 模拟值(0..1);扳机半程典型 0.5。OOS-4:不施加 gamepad 死区(轴 deadzone 排除) |
115
+ | `snap.gamepad(i).justPressed(b)` | `boolean`(`b: 0\|1\|...\|16`) | 按钮 `b` 边沿——上帧未按、本帧按下(一帧寿命) |
116
+ | `snap.gamepad(i).justReleased(b)` | `boolean`(`b: 0\|1\|...\|16`) | 按钮 `b` 边沿——上帧按、本帧释放(一帧寿命) |
117
+ | `snap.gamepad(i).axis(a)` | `number`(`a: 0\|1\|2\|3`) | 轴 `a` 原始值(-1..1)。越界字面量触发 TS 编译错误。OOS-4:不施加死区——轴 raw 值直读 |
118
+
119
+ ### pointer(per-pointerId reader)
120
+
121
+ | 调用 | 返回 | 语义 |
122
+ |:--|:--|:--|
123
+ | `snap.pointer(id).active` | `boolean` | `pointerId` 当前活跃(触点在 pointerMap 内)。不存在 → `false` + 全字段空信号 |
124
+ | `snap.pointer(id).x` / `.y` | `number` | 当前帧末最后 pointermove 的 canvas-pixel 坐标(DPR 换算:`(clientX-rect.left)*(canvas.width/rect.width)`)。getBoundingClientRect 缺失 → `clientX/Y` 直存(fallback) |
125
+ | `snap.pointer(id).pressure` | `number` | W3C `PointerEvent.pressure`(0..1)。无压感网 → 缺省 0.5 或 0 |
126
+ | `snap.pointer(id).pointerType` | `string` | `'mouse'` / `'pen'` / `'touch'`——W3C `PointerEvent.pointerType` |
127
+ | `snap.pointer(id).delta` | `{ x: number; y: number }` | 跨帧位移(本帧冻结位置 − 上帧冻结位置)。一帧内 N 次 pointermove → delta 为末端 − 上帧末端(AC-09:非 0,避 Bevy #12442 反例) |
128
+ | `snap.pointerEvents` | `readonly PointerPhaseEvent[]` | 本帧相位事件队列(down / move / up / cancel),一帧寿命——sample() 末尾 drain |
129
+
130
+ ### virtualAxis(独立命名空间)
131
+
132
+ | 调用 | 返回 | 语义 |
133
+ |:--|:--|:--|
134
+ | `snap.virtualAxis(name)` | `{ x: number; y: number }` | 名为 `name` 的虚拟摇杆向量:`|vec|<deadzone` → `(0,0)`;`|vec|>radius` → clamp 到模长 1.0;中段 → `clamp(cur−origin, radius)/radius`。不存在 → `(0,0)`(空信号)。fixed 模式 origin=anchor;floating 模式 origin=落点 |
135
+
136
+ ### capabilities(一次性探针)
137
+
138
+ | 调用 | 返回 | 语义 |
139
+ |:--|:--|:--|
140
+ | `snap.capabilities` | `{ gamepad: boolean; pointer: boolean }` | 后端 attach 时冻结的环境探针(`typeof navigator.getGamepads === 'function'` / `typeof PointerEvent !== 'undefined'`)。不须每帧重查 |
141
+
142
+ ### action(声明式设备无关语义层)
143
+
144
+ 4-member `ActionBinding` discriminant union: `'key'` | `'mouseButton'` | `'gamepadButton'` | `'gamepadAxis'`. Declared via `INPUT_MAP_KEY` Resource (`ActionConfig[]`). Per-action deadzone default: **0.2** (Godot prior-art). Aggregation: OR for pressed, MAX for strength/raw. Duplicate action names: last-wins (D-8).
145
+
146
+ | 调用 | 返回 | 语义 |
147
+ |:--|:--|:--|
148
+ | `snap.action(name).isPressed()` | `boolean` | 任意绑定源当前激活(OR 聚合)。未注册 action → `false` |
149
+ | `snap.action(name).justPressed()` | `boolean` | 上帧未按、本帧按下(一帧寿命)。首帧无 prev → justPressed=pressed |
150
+ | `snap.action(name).justReleased()` | `boolean` | 上帧按下、本帧释放(一帧寿命) |
151
+ | `snap.action(name).strength` | `number` | 死区重映射模拟强度 [0, 1]。`\|raw\|<deadzone` → 0;`\|raw\|≥deadzone` → `inverse_lerp(deadzone, 1, \|raw\|)`。数字绑定 → 1.0 |
152
+ | `snap.getAxis(neg, pos)` | `number` | `strength(pos) − strength(neg)`,值域 [-1, 1]。一端/两端未注册 → 该端贡献 0;同 action 双端 → 恒 0 (E-12) |
153
+ | `snap.getVector(nX, pX, nY, pY, opts?)` | `{x: number, y: number}` | 四行动方向合成 2D 向量,单次径向死区(三分支公式,Godot input.cpp F2):`length≤deadzone` → (0,0);`length>1` → 单位圆 clamp;中段 → `vec·inverse_lerp(deadzone, 1, length)/length`。默认 deadzone = 4 个 action 的 per-action deadzone 均值;`opts.deadzone` 覆盖。读 action 的 `raw`(非 `strength`)避免逐轴死区叠加成方形死区。 |
154
+
155
+ WASD 斜向:键盘 a/d/w/s 绑为 `getVector('moveLeft','moveRight','moveUp','moveDown')` → 斜向模长 1(非 √2;AC-06)。
156
+
157
+ ### gesture(触摸手势 recognizer,五类)
158
+
159
+ Five gesture recognizers running in the backend closure (C-3 single legal cross-frame state). All timers advance off injected `now()` (D-3), decoupled from pointer-event frequency. Two output channels (D-4): continuous values via `snap.gesture`, one-frame lifecycle events via `snap.gestureEvents`. No active gesture → identity empty signal (pinchScale=1.0, rotationAngle=0; AC-12).
160
+
161
+ | 调用 | 返回 | 语义 |
162
+ |:--|:--|:--|
163
+ | `snap.gesture.pinchScale` | `number` | 双指捏合缩放比值(累计);无手势 → 1.0。begin 时复位为 1.0,2→1 指抬 end 后冻结,回 2 指 new begin 再复 1.0 (D-11) |
164
+ | `snap.gesture.rotationAngle` | `number` | 双指旋转累计角度(弧度);无手势 → 0。与 pinch 共用同一双指 tracker,同帧 begin/end 成对 |
165
+ | `snap.gestureEvents` | `readonly GestureEvent[]` | 本帧手势生命周期事件队列(一帧寿命,对齐 pointerEvents)。`GestureEvent` 是封闭判别联合:`pinch-begin/end/cancel`、`rotate-begin/end/cancel`、`swipe`(含 direction)、`long-press`、`double-tap`。每个 event 带 `pointerType`(`'mouse' \| 'pen' \| 'touch'`,AC-19 消费路径) |
166
+
167
+ ### 手势阈值默认表
168
+
169
+ | 常量 | 值 | 来源 |
170
+ |:--|:--|:--|
171
+ | 默认 per-action deadzone | `0.2` | Godot prior-art (F2) |
172
+ | `LONG_PRESS_DURATION_MS` | `500` | LayaAir prior-art |
173
+ | `LONG_PRESS_SLOP` | `10`(canvas px) | LayaAir prior-art |
174
+ | `DOUBLE_TAP_INTERVAL_MS` | `350` | LayaAir prior-art |
175
+ | `DOUBLE_TAP_DISTANCE` | `10`(canvas px) | LayaAir prior-art |
176
+ | `SWIPE_VELOCITY_THRESHOLD` | `0.5`(px/ms) | up 前 100ms 位移窗口推速度 |
177
+ | `SWIPE_WINDOW_MS` | `100` | 速度计算滑动窗口 (D-10) |
178
+
179
+ `engine.run()` 启动前调用返回空快照(不抛异常;charter P3 例外:构造阶段无事件源,空快照即"显式无信号")。
180
+
181
+ ## 形态铁律
182
+
183
+ - **Resource 形态唯一入口** — 用户胶水通过 `world.getResource<InputSnapshot>('InputSnapshot')` 消费;不暴露 `world.input` 平行 API(charter P4 一致抽象)
184
+ - **PointerLock 内部消化** — `requestPointerLock` 用户激活、`pointerlockchange` 状态机、`movementX/Y` 单位陷阱、`firstMouse` flag 全部封装在 `browser-backend.ts`;`InputSnapshot` 表面仅暴露 `snap.mouse.pointerLocked`(合并锁态 boolean)与 `snap.mouse.movementDelta`(累加 delta),不暴露 W3C DOM 细节(plan-strategy OOS-1)
185
+ - **帧首扫描后冻结** — `InputFrameStartScan` system token(顶层 `defineSystem`)先于其他用户系统跑(用 `before` 约束),从 `INPUT_BACKEND_KEY` resource 取 backend、扫描累积器后调用 `world.insertResource` 写入冻结快照;当帧内任何系统调 `snap.*` 看到的都是同一份值(architecture-principles #2 Derive)。backend 经 `world.insertResource(INPUT_BACKEND_KEY, backend)` 注入,descriptor 的 `resources:[INPUT_BACKEND_KEY]` 走结构化 ParamValidation(依赖未注入 -> invalid,非裸 throw)
186
+ - **OOS-1 范围外** — PointerLock 进入/退出事件、`unadjustedMovement` 选项、hot-reload 不在本 MVP 内;后续作为独立 feat 拆出
187
+
188
+ ## 错误模型(charter P3 显式失败)
189
+
190
+ | 行为 | 形态 |
191
+ |:--|:--|
192
+ | `engine.run()` 启动前调用 `snap.*` | 返回空快照(`down/up=false` / `movementDelta={x:0,y:0}` / `button=false`);不抛 |
193
+ | `keyboard.down(unknownKey)` | 返回 `false`(不抛;未按下即 down=false) |
194
+ | `mouse.button(3)` | TS 编译错误(字面量类型 `0 \| 1 \| 2` 收紧);运行时表面不暴露 |
195
+ | `snap.gamepad(i)` 越界 / `i` 断连 | `connected=false` + 全读点 `false`/`0`(空信号不抛) |
196
+ | `snap.gamepad(i)` 非标准布局 | `connected=true` + `standardMapping=false` + 全读点空信号(区分断连——显式可检测) |
197
+ | `snap.gamepad(i).standardMapping` 语义 | **true** when browser reports `mapping==='standard'` **or** SDL controller DB has normalized a non-standard layout (D-1 redline). `false` = not standard AND DB miss/unavailable — the downgrade is explicitly detectable (AC-10/E-2) |
198
+ | `snap.action(name)` 未注册 | 返回空信号:`isPressed()=false` / `strength=0` / `justPressed()=false` / `justReleased()=false`(不抛;AC-01/09) |
199
+ | `snap.gesture` 无活跃手势 | `pinchScale=1.0` / `rotationAngle=0`(恒等空信号,不抛;AC-12) |
200
+ | `snap.gestureEvents` 无生命周期事件 | 空数组 `[]`(不抛) |
201
+ | `snap.gamepad(i).button(17)` / `.axis(4)` | TS 编译错误(字面量 union `0\|1\|...\|16` / `0\|1\|2\|3` 收紧) |
202
+ | `typeof navigator.getGamepads !== 'function'` | `snap.capabilities.gamepad=false` + `snap.gamepad(0..N)` 全空信号(不抛) |
203
+ | `snap.pointer(id)` 不存在 | `active=false` + 全字段空信号(不抛) |
204
+ | `snap.virtualAxis(name)` 不存在 | 零向量 `{ x: 0, y: 0 }`(不抛) |
205
+ | pointer 移出 canvas | 越界坐标原样保留不 clamp——`x`/`y` 可为负或超出 canvas 尺寸(文档化行为,charter P3) |
206
+
207
+ ## 边界行为
208
+
209
+ | 场景 | 行为 |
210
+ |:--|:--|
211
+ | 越界坐标 | pointer `x`/`y` 原样保留不 clamp(可为负或超出 canvas 尺寸);charter P3:显式文档化不隐式行为 |
212
+ | `touch-action` | `attach` 时浏览器 backend 内部设置 `canvas.style.touchAction='none'`(existential 探测——fake canvas 无 `.style` 时静默跳过);detach 恢复原值。AI 用户不需手动设 CSS |
213
+ | 失焦(blur / visibilitychange `hidden`) | pointerMap 全清 + 每活跃触点 push cancel 相位事件进入队列;W3C/provider pointer lock 立即释放;gamepad justPressed/justReleased 集合复位,并以一次 focus-reset sample 边界抑制旧 snapshot 的 mouse/action release——下帧不喷幽灵边沿。恢复焦点后下次 `sample()` 自然恢复 |
214
+ | assemble form — action surface | Assemble-form hosts must manually `world.insertResource(INPUT_MAP_KEY, map)` to enable action readpoints (D-7). Canvas-form `createApp` does this automatically. |
215
+ | controller-db 子导出懒加载 | `@forgeax/engine-input/controller-db` is dynamically imported only on first connected non-standard gamepad (D-2). Until then (or on DB miss), non-standard slots maintain the Feat1 empty-signal behavior (`standardMapping=false`). Standard gamepads never trigger the load (C-5). |
216
+ | 手势 cancel on blur | `onBlur` resets all active gesture recognizers: emits cancel events for each active gesture type, resets continuous values to identity, and clears timers (AC-18). Prevent ghost gestures on refocus. |
217
+ | pointer-lock gate = game gate AND host predicate | `onCanvasClick` evaluates `gameGate && (predicate?.() ?? true)`. `gameGate` defaults to `true` and is set via `InputBackend.setPointerLockAllowed()`. `predicate` is `BrowserInputBackendOptions.pointerLockAllowed` (frozen at attach). Both must be true for a click to request lock. |
218
+ | `setPointerLockAllowed(false)` immediate release | When `gameGate` transitions from `true` to `false` and a lock is active, the backend immediately releases: W3C path calls `exitPointerLock()`, provider path calls `exitLock()` + clears `providerLocked`. This solves the "mode switches to top-down while locked" boundary. |
219
+ | lockProvider error → onLockError | W3C `requestPointerLock` promise rejection and provider `requestLock` throw/reject both route through `onLockError({ path, cause })`. Provider failure also rolls back `providerLocked = false`. The callback is wired by `attachInputAuto` into `AppError({ code: 'app-pointer-lock-failed' })` on the app's `onError` fan-out. |
220
+
221
+ ## Pointer-lock contract: PointerLockProvider / lockProvider / setPointerLockAllowed / pointerLocked
222
+
223
+ Four anchors cover the full pointer-lock surface across the input-backend boundary.
224
+
225
+ ### PointerLockProvider (type SSOT)
226
+
227
+ ```ts
228
+ // @forgeax/engine-input — exported from barrel
229
+ interface PointerLockProvider {
230
+ requestLock(): void | Promise<void>; // request pointer capture (W3C replacement)
231
+ exitLock(): void; // release pointer capture
232
+ }
233
+ ```
234
+
235
+ A single object (not two flat callbacks) — structural typing requires both halves, preventing "requestLock-only" half-injected states. The engine never learns *why* locking is (dis)allowed; it delegates to the abstract callback.
236
+
237
+ ### BrowserInputBackendOptions.lockProvider (injection point)
238
+
239
+ ```ts
240
+ // BrowserInputBackendOptions — optional field, parallel to pointerLockAllowed
241
+ interface BrowserInputBackendOptions {
242
+ pointerLockAllowed?: () => boolean;
243
+ lockProvider?: PointerLockProvider; // absent => fall back to W3C requestPointerLock()
244
+ // ... other options
245
+ }
246
+ ```
247
+
248
+ When `lockProvider` is present, `onCanvasClick` calls `requestLock()` instead of `requestPointerLock()`. The provider's `exitLock()` replaces `exitPointerLock()` in release paths (ESC provider branch, blur, detach, `setPointerLockAllowed(false)` immediate release).
249
+
250
+ ### InputBackend.setPointerLockAllowed (command gate)
251
+
252
+ ```ts
253
+ // InputBackend protocol — optional method
254
+ interface InputBackend {
255
+ sample(): InputBackendSample;
256
+ setPointerLockAllowed?(allowed: boolean): void; // game-side gate
257
+ detach(): void;
258
+ }
259
+ ```
260
+
261
+ - `setPointerLockAllowed(true)` — allow pointer-lock on next trusted click
262
+ - `setPointerLockAllowed(false)` — block pointer-lock AND immediately release any active lock (W3C path: `exitPointerLock`; provider path: `exitLock()` + clears `providerLocked`)
263
+ - Default state: `true` (allow lock)
264
+ - Optional — backends without pointer-lock support omit this method
265
+
266
+ This works together with the pre-existing host predicate `pointerLockAllowed?: () => boolean` (evaluated fresh on each click, e.g. "is input focus in the game quadrant?"). Two gates AND-combine: both must be true for lock; neither duplicates the other's information.
267
+
268
+ ### InputBackendSample.pointerLocked (readpoint)
269
+
270
+ ```ts
271
+ // InputBackendSample — required field (not optional)
272
+ interface InputBackendSample {
273
+ // ... movementX/Y, buttons, downKeys, upKeys, etc.
274
+ readonly pointerLocked: boolean; // W3C pointerlockchange OR provider requestLock engage
275
+ }
276
+ ```
277
+
278
+ Frozen into `snap.mouse.pointerLocked` at frame-start. Consumers read `if (snap.mouse.pointerLocked)` to gate look/camera rotation — both facts (`movementDelta` + `pointerLocked`) sit at the same attribute path for single-point indexing (charter F1).
279
+
280
+ ## 相关包
281
+
282
+ - [`@forgeax/engine-ecs`](../ecs) — 提供 `World` + Resource 存储 + Schedule(消费方契约依赖:`world.insertResource('InputSnapshot', frozenSnapshot)`)
283
+ - [`@forgeax/engine-runtime`](../runtime) — 在 `Engine.create({ canvas })` 流水线里调用 `attachBrowserInputBackend(canvas)`、`world.insertResource(INPUT_BACKEND_KEY, backend)` 与 `world.addSystem(Update, InputFrameStartScan)`,对 AI 用户屏蔽组装细节
284
+
285
+ ## Simulation input boundary
286
+
287
+ Use `InputSnapshot` as the frame-start boundary for simulation input. A
288
+ simulation trace stores the normalized value consumed by a fixed tick; it does
289
+ not store DOM events, browser objects, or a render frame.
290
+
291
+ ```ts
292
+ const snapshot = inputBackend.snapshot();
293
+ const sample = { tick: fixedTick + 1, input: snapshot.action('moveForward').isPressed() };
294
+ ```
295
+
296
+ The input package freezes the snapshot. ECS owns `record`, `restore`, `trace`,
297
+ participant registration, comparison tolerance, and closed simulation errors.
298
+ Use the same snapshot source for source and fresh target Worlds. Do not add a
299
+ second input recorder, a replay action, or a browser event queue to Remote.
300
+
301
+ The simulation connector accepts package-produced snapshots from the public
302
+ `snapshotFromSample` / `createInputSnapshot` path. If an `InputSnapshot`
303
+ Resource is replaced by a structurally similar value without package-owned
304
+ provenance, the World update does not throw or publish a partial sample;
305
+ `finish()` returns the existing `simulation-trace-invalid` error with
306
+ `detail.path === 'InputSnapshot.provenance'`. Consumers do not author or copy
307
+ private provenance fields. Dispose the failed controller, provide a corrected
308
+ snapshot source, and install the connector on a fresh target World.
309
+
310
+ If a trace fails, inspect `code`, `expected`, `hint`, and `detail`, repair the
311
+ named input boundary, then create a fresh target. RHI tape replay and game
312
+ replay have different owners and are not input snapshot formats.