@vgai/engine 0.5.4 → 0.5.6

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 (448) hide show
  1. package/dist/adapter/adapter-surface.d.ts +30 -0
  2. package/dist/adapter/adapter-surface.d.ts.map +1 -0
  3. package/dist/adapter/adapter-surface.js +18 -0
  4. package/dist/adapter/authoring.d.ts +597 -0
  5. package/dist/adapter/authoring.d.ts.map +1 -0
  6. package/dist/adapter/authoring.js +22 -0
  7. package/dist/adapter/colyseus-networking-adapter.d.ts +77 -0
  8. package/dist/adapter/colyseus-networking-adapter.d.ts.map +1 -0
  9. package/dist/adapter/colyseus-networking-adapter.js +76 -0
  10. package/dist/adapter/first-party-systems.d.ts +23 -0
  11. package/dist/adapter/first-party-systems.d.ts.map +1 -0
  12. package/dist/adapter/first-party-systems.js +196 -0
  13. package/dist/adapter/host-context.d.ts +194 -0
  14. package/dist/adapter/host-context.d.ts.map +1 -0
  15. package/dist/adapter/host-context.js +80 -0
  16. package/dist/adapter/index.d.ts +33 -0
  17. package/dist/adapter/index.d.ts.map +1 -0
  18. package/dist/adapter/index.js +25 -0
  19. package/dist/adapter/ingest/game-contract.d.ts +53 -0
  20. package/dist/adapter/ingest/game-contract.d.ts.map +1 -0
  21. package/dist/adapter/ingest/game-contract.js +30 -0
  22. package/dist/adapter/ingest/scene-capture.d.ts +121 -0
  23. package/dist/adapter/ingest/scene-capture.d.ts.map +1 -0
  24. package/dist/adapter/ingest/scene-capture.js +270 -0
  25. package/dist/adapter/ingest/structural-ids.d.ts +64 -0
  26. package/dist/adapter/ingest/structural-ids.d.ts.map +1 -0
  27. package/dist/adapter/ingest/structural-ids.js +110 -0
  28. package/dist/adapter/ingest/upstream-pin.d.ts +44 -0
  29. package/dist/adapter/ingest/upstream-pin.d.ts.map +1 -0
  30. package/dist/adapter/ingest/upstream-pin.js +47 -0
  31. package/dist/adapter/loop-gate-report.d.ts +34 -0
  32. package/dist/adapter/loop-gate-report.d.ts.map +1 -0
  33. package/dist/adapter/loop-gate-report.js +37 -0
  34. package/dist/adapter/rapier-physics-adapter.d.ts +69 -0
  35. package/dist/adapter/rapier-physics-adapter.d.ts.map +1 -0
  36. package/dist/adapter/rapier-physics-adapter.js +135 -0
  37. package/dist/adapter/root-adapter.d.ts +195 -0
  38. package/dist/adapter/root-adapter.d.ts.map +1 -0
  39. package/dist/adapter/root-adapter.js +25 -0
  40. package/dist/adapter/setup-three-root-adapter.d.ts +87 -0
  41. package/dist/adapter/setup-three-root-adapter.d.ts.map +1 -0
  42. package/dist/adapter/setup-three-root-adapter.js +791 -0
  43. package/dist/adapter/system-adapter.d.ts +453 -0
  44. package/dist/adapter/system-adapter.d.ts.map +1 -0
  45. package/dist/adapter/system-adapter.js +13 -0
  46. package/dist/adapter/transform.d.ts +18 -0
  47. package/dist/adapter/transform.d.ts.map +1 -0
  48. package/dist/adapter/transform.js +1 -0
  49. package/dist/ai/navigation.d.ts +78 -0
  50. package/dist/ai/navigation.d.ts.map +1 -0
  51. package/dist/ai/navigation.js +152 -0
  52. package/dist/animation/anim-graph-types.d.ts +25 -0
  53. package/dist/animation/anim-graph-types.d.ts.map +1 -0
  54. package/dist/animation/anim-graph-types.js +1 -0
  55. package/dist/animation/animation-clock.d.ts +213 -0
  56. package/dist/animation/animation-clock.d.ts.map +1 -0
  57. package/dist/animation/animation-clock.js +301 -0
  58. package/dist/animation/blend-node.d.ts +22 -0
  59. package/dist/animation/blend-node.d.ts.map +1 -0
  60. package/dist/animation/blend-node.js +97 -0
  61. package/dist/animation/camera-ownership.d.ts +249 -0
  62. package/dist/animation/camera-ownership.d.ts.map +1 -0
  63. package/dist/animation/camera-ownership.js +169 -0
  64. package/dist/animation/cinematic-cues.d.ts +200 -0
  65. package/dist/animation/cinematic-cues.d.ts.map +1 -0
  66. package/dist/animation/cinematic-cues.js +213 -0
  67. package/dist/animation/clip-map.d.ts +12 -0
  68. package/dist/animation/clip-map.d.ts.map +1 -0
  69. package/dist/animation/clip-map.js +31 -0
  70. package/dist/animation/cubic-spline-interpolant.d.ts +54 -0
  71. package/dist/animation/cubic-spline-interpolant.d.ts.map +1 -0
  72. package/dist/animation/cubic-spline-interpolant.js +111 -0
  73. package/dist/animation/theatre-clock-binding.d.ts +89 -0
  74. package/dist/animation/theatre-clock-binding.d.ts.map +1 -0
  75. package/dist/animation/theatre-clock-binding.js +29 -0
  76. package/dist/animation/theatre-director.d.ts +277 -0
  77. package/dist/animation/theatre-director.d.ts.map +1 -0
  78. package/dist/animation/theatre-director.js +248 -0
  79. package/dist/animation/theatre-object-binding.d.ts +305 -0
  80. package/dist/animation/theatre-object-binding.d.ts.map +1 -0
  81. package/dist/animation/theatre-object-binding.js +351 -0
  82. package/dist/animation/xstate-animation-binding.d.ts +119 -0
  83. package/dist/animation/xstate-animation-binding.d.ts.map +1 -0
  84. package/dist/animation/xstate-animation-binding.js +349 -0
  85. package/dist/animation/xstate-animation-meta.d.ts +266 -0
  86. package/dist/animation/xstate-animation-meta.d.ts.map +1 -0
  87. package/dist/animation/xstate-animation-meta.js +252 -0
  88. package/dist/asset-formats/camera.d.ts +15 -0
  89. package/dist/asset-formats/camera.d.ts.map +1 -0
  90. package/dist/asset-formats/camera.js +15 -0
  91. package/dist/asset-formats/collider.d.ts +21 -0
  92. package/dist/asset-formats/collider.d.ts.map +1 -0
  93. package/dist/asset-formats/collider.js +53 -0
  94. package/dist/asset-formats/index.d.ts +46 -0
  95. package/dist/asset-formats/index.d.ts.map +1 -0
  96. package/dist/asset-formats/index.js +36 -0
  97. package/dist/asset-formats/instances.d.ts +17 -0
  98. package/dist/asset-formats/instances.d.ts.map +1 -0
  99. package/dist/asset-formats/instances.js +31 -0
  100. package/dist/asset-formats/light.d.ts +21 -0
  101. package/dist/asset-formats/light.d.ts.map +1 -0
  102. package/dist/asset-formats/light.js +35 -0
  103. package/dist/asset-formats/material.d.ts +129 -0
  104. package/dist/asset-formats/material.d.ts.map +1 -0
  105. package/dist/asset-formats/material.js +88 -0
  106. package/dist/asset-formats/mesh.d.ts +22 -0
  107. package/dist/asset-formats/mesh.d.ts.map +1 -0
  108. package/dist/asset-formats/mesh.js +64 -0
  109. package/dist/asset-formats/parse.d.ts +20 -0
  110. package/dist/asset-formats/parse.d.ts.map +1 -0
  111. package/dist/asset-formats/parse.js +34 -0
  112. package/dist/asset-formats/particles.d.ts +1390 -0
  113. package/dist/asset-formats/particles.d.ts.map +1 -0
  114. package/dist/asset-formats/particles.js +319 -0
  115. package/dist/asset-formats/render-env.d.ts +387 -0
  116. package/dist/asset-formats/render-env.d.ts.map +1 -0
  117. package/dist/asset-formats/render-env.js +300 -0
  118. package/dist/asset-formats/tuples.d.ts +12 -0
  119. package/dist/asset-formats/tuples.d.ts.map +1 -0
  120. package/dist/asset-formats/tuples.js +14 -0
  121. package/dist/asset-loaders.d.ts +97 -0
  122. package/dist/asset-loaders.d.ts.map +1 -0
  123. package/dist/asset-loaders.js +209 -0
  124. package/dist/asset-parse-error.d.ts +24 -0
  125. package/dist/asset-parse-error.d.ts.map +1 -0
  126. package/dist/asset-parse-error.js +29 -0
  127. package/dist/asset-registry.d.ts +38 -0
  128. package/dist/asset-registry.d.ts.map +1 -0
  129. package/dist/asset-registry.js +66 -0
  130. package/dist/assets.d.ts +26 -0
  131. package/dist/assets.d.ts.map +1 -0
  132. package/dist/assets.js +55 -0
  133. package/dist/audio/wav-encode.d.ts +38 -0
  134. package/dist/audio/wav-encode.d.ts.map +1 -0
  135. package/dist/audio/wav-encode.js +97 -0
  136. package/dist/canvas-react/engine-bridge.d.ts +45 -0
  137. package/dist/canvas-react/engine-bridge.d.ts.map +1 -0
  138. package/dist/canvas-react/engine-bridge.js +45 -0
  139. package/dist/canvas-react/index.d.ts +42 -0
  140. package/dist/canvas-react/index.d.ts.map +1 -0
  141. package/dist/canvas-react/index.js +41 -0
  142. package/dist/canvas-react/pixi-primitive.d.ts +85 -0
  143. package/dist/canvas-react/pixi-primitive.d.ts.map +1 -0
  144. package/dist/canvas-react/pixi-primitive.js +181 -0
  145. package/dist/canvas-react/pixi-react-adapter.d.ts +71 -0
  146. package/dist/canvas-react/pixi-react-adapter.d.ts.map +1 -0
  147. package/dist/canvas-react/pixi-react-adapter.js +229 -0
  148. package/dist/canvas-react/pixi-react-root-factory.d.ts +56 -0
  149. package/dist/canvas-react/pixi-react-root-factory.d.ts.map +1 -0
  150. package/dist/canvas-react/pixi-react-root-factory.js +73 -0
  151. package/dist/canvas-react/world-context.d.ts +88 -0
  152. package/dist/canvas-react/world-context.d.ts.map +1 -0
  153. package/dist/canvas-react/world-context.js +212 -0
  154. package/dist/config.d.ts +9 -0
  155. package/dist/config.d.ts.map +1 -0
  156. package/dist/config.js +8 -0
  157. package/dist/core/frame-pacing.d.ts +90 -0
  158. package/dist/core/frame-pacing.d.ts.map +1 -0
  159. package/dist/core/frame-pacing.js +89 -0
  160. package/dist/core/game-loop.d.ts +62 -0
  161. package/dist/core/game-loop.d.ts.map +1 -0
  162. package/dist/core/game-loop.js +189 -0
  163. package/dist/core/seeded-random.d.ts +69 -0
  164. package/dist/core/seeded-random.d.ts.map +1 -0
  165. package/dist/core/seeded-random.js +121 -0
  166. package/dist/core/sim-clock.d.ts +199 -0
  167. package/dist/core/sim-clock.d.ts.map +1 -0
  168. package/dist/core/sim-clock.js +291 -0
  169. package/dist/core/system-runner.d.ts +96 -0
  170. package/dist/core/system-runner.d.ts.map +1 -0
  171. package/dist/core/system-runner.js +253 -0
  172. package/dist/core/types.d.ts +111 -0
  173. package/dist/core/types.d.ts.map +1 -0
  174. package/dist/core/types.js +25 -0
  175. package/dist/data/data-asset.d.ts +101 -0
  176. package/dist/data/data-asset.d.ts.map +1 -0
  177. package/dist/data/data-asset.js +122 -0
  178. package/dist/data/data-check-core.d.ts +109 -0
  179. package/dist/data/data-check-core.d.ts.map +1 -0
  180. package/dist/data/data-check-core.js +177 -0
  181. package/dist/data/data-ref.d.ts +79 -0
  182. package/dist/data/data-ref.d.ts.map +1 -0
  183. package/dist/data/data-ref.js +130 -0
  184. package/dist/data/vite-plugin-data.d.ts +79 -0
  185. package/dist/data/vite-plugin-data.d.ts.map +1 -0
  186. package/dist/data/vite-plugin-data.js +217 -0
  187. package/dist/defaults.d.ts +233 -0
  188. package/dist/defaults.d.ts.map +1 -0
  189. package/dist/defaults.js +137 -0
  190. package/dist/dev/chrome-trace.d.ts +45 -0
  191. package/dist/dev/chrome-trace.d.ts.map +1 -0
  192. package/dist/dev/chrome-trace.js +114 -0
  193. package/dist/dev/console-bridge.d.ts +22 -0
  194. package/dist/dev/console-bridge.d.ts.map +1 -0
  195. package/dist/dev/console-bridge.js +71 -0
  196. package/dist/dev/debug-draw.d.ts +24 -0
  197. package/dist/dev/debug-draw.d.ts.map +1 -0
  198. package/dist/dev/debug-draw.js +73 -0
  199. package/dist/dev/instruments.d.ts +133 -0
  200. package/dist/dev/instruments.d.ts.map +1 -0
  201. package/dist/dev/instruments.js +231 -0
  202. package/dist/dev/logger.d.ts +30 -0
  203. package/dist/dev/logger.d.ts.map +1 -0
  204. package/dist/dev/logger.js +90 -0
  205. package/dist/dev/performance-profiler.d.ts +111 -0
  206. package/dist/dev/performance-profiler.d.ts.map +1 -0
  207. package/dist/dev/performance-profiler.js +215 -0
  208. package/dist/dev/render-debug-adapter.d.ts +57 -0
  209. package/dist/dev/render-debug-adapter.d.ts.map +1 -0
  210. package/dist/dev/render-debug-adapter.js +141 -0
  211. package/dist/dev/render-memory.d.ts +53 -0
  212. package/dist/dev/render-memory.d.ts.map +1 -0
  213. package/dist/dev/render-memory.js +190 -0
  214. package/dist/dev/webgl-frame-capture.d.ts +134 -0
  215. package/dist/dev/webgl-frame-capture.d.ts.map +1 -0
  216. package/dist/dev/webgl-frame-capture.js +270 -0
  217. package/dist/dev/webgl-gpu-timer.d.ts +8 -0
  218. package/dist/dev/webgl-gpu-timer.d.ts.map +1 -0
  219. package/dist/dev/webgl-gpu-timer.js +52 -0
  220. package/dist/ecs/scene-index.d.ts +179 -0
  221. package/dist/ecs/scene-index.d.ts.map +1 -0
  222. package/dist/ecs/scene-index.js +331 -0
  223. package/dist/ecs/scene-query.d.ts +6 -0
  224. package/dist/ecs/scene-query.d.ts.map +1 -0
  225. package/dist/ecs/scene-query.js +40 -0
  226. package/dist/ecs/user-data.d.ts +193 -0
  227. package/dist/ecs/user-data.d.ts.map +1 -0
  228. package/dist/ecs/user-data.js +145 -0
  229. package/dist/index.d.ts +35 -0
  230. package/dist/index.d.ts.map +1 -0
  231. package/dist/index.js +29 -0
  232. package/dist/input/input-manager.d.ts +944 -0
  233. package/dist/input/input-manager.d.ts.map +1 -0
  234. package/dist/input/input-manager.js +2209 -0
  235. package/dist/input/input-types.d.ts +174 -0
  236. package/dist/input/input-types.d.ts.map +1 -0
  237. package/dist/input/input-types.js +1 -0
  238. package/dist/input/prompt-labels.d.ts +21 -0
  239. package/dist/input/prompt-labels.d.ts.map +1 -0
  240. package/dist/input/prompt-labels.js +121 -0
  241. package/dist/input/rebind-controller.d.ts +59 -0
  242. package/dist/input/rebind-controller.d.ts.map +1 -0
  243. package/dist/input/rebind-controller.js +85 -0
  244. package/dist/input/schema.d.ts +16 -0
  245. package/dist/input/schema.d.ts.map +1 -0
  246. package/dist/input/schema.js +228 -0
  247. package/dist/loader.d.ts +76 -0
  248. package/dist/loader.d.ts.map +1 -0
  249. package/dist/loader.js +114 -0
  250. package/dist/manifest/editor-port.d.ts +53 -0
  251. package/dist/manifest/editor-port.d.ts.map +1 -0
  252. package/dist/manifest/editor-port.js +67 -0
  253. package/dist/manifest/filename.d.ts +14 -0
  254. package/dist/manifest/filename.d.ts.map +1 -0
  255. package/dist/manifest/filename.js +43 -0
  256. package/dist/manifest/index.d.ts +6 -0
  257. package/dist/manifest/index.d.ts.map +1 -0
  258. package/dist/manifest/index.js +9 -0
  259. package/dist/manifest/load-file.d.ts +7 -0
  260. package/dist/manifest/load-file.d.ts.map +1 -0
  261. package/dist/manifest/load-file.js +23 -0
  262. package/dist/manifest/load.d.ts +161 -0
  263. package/dist/manifest/load.d.ts.map +1 -0
  264. package/dist/manifest/load.js +269 -0
  265. package/dist/manifest/locate.d.ts +24 -0
  266. package/dist/manifest/locate.d.ts.map +1 -0
  267. package/dist/manifest/locate.js +48 -0
  268. package/dist/manifest/schema.d.ts +293 -0
  269. package/dist/manifest/schema.d.ts.map +1 -0
  270. package/dist/manifest/schema.js +633 -0
  271. package/dist/physics/collider-dimensions.d.ts +63 -0
  272. package/dist/physics/collider-dimensions.d.ts.map +1 -0
  273. package/dist/physics/collider-dimensions.js +98 -0
  274. package/dist/physics/collision-system.d.ts +41 -0
  275. package/dist/physics/collision-system.d.ts.map +1 -0
  276. package/dist/physics/collision-system.js +64 -0
  277. package/dist/physics/physics-registry.d.ts +45 -0
  278. package/dist/physics/physics-registry.d.ts.map +1 -0
  279. package/dist/physics/physics-registry.js +65 -0
  280. package/dist/physics/transform-writer.d.ts +16 -0
  281. package/dist/physics/transform-writer.d.ts.map +1 -0
  282. package/dist/physics/transform-writer.js +38 -0
  283. package/dist/pixi/authoring.d.ts +93 -0
  284. package/dist/pixi/authoring.d.ts.map +1 -0
  285. package/dist/pixi/authoring.js +207 -0
  286. package/dist/pixi/index.d.ts +16 -0
  287. package/dist/pixi/index.d.ts.map +1 -0
  288. package/dist/pixi/index.js +15 -0
  289. package/dist/pixi/ingest-iframe.d.ts +82 -0
  290. package/dist/pixi/ingest-iframe.d.ts.map +1 -0
  291. package/dist/pixi/ingest-iframe.js +166 -0
  292. package/dist/pixi/ingest.d.ts +97 -0
  293. package/dist/pixi/ingest.d.ts.map +1 -0
  294. package/dist/pixi/ingest.js +40 -0
  295. package/dist/pixi/physics-registry.d.ts +24 -0
  296. package/dist/pixi/physics-registry.d.ts.map +1 -0
  297. package/dist/pixi/physics-registry.js +38 -0
  298. package/dist/pixi/scene-capture.d.ts +43 -0
  299. package/dist/pixi/scene-capture.d.ts.map +1 -0
  300. package/dist/pixi/scene-capture.js +92 -0
  301. package/dist/pixi/system-adapters.d.ts +16 -0
  302. package/dist/pixi/system-adapters.d.ts.map +1 -0
  303. package/dist/pixi/system-adapters.js +37 -0
  304. package/dist/react/unmanaged-root-detector.d.ts +18 -0
  305. package/dist/react/unmanaged-root-detector.d.ts.map +1 -0
  306. package/dist/react/unmanaged-root-detector.js +70 -0
  307. package/dist/react/use-data.d.ts +60 -0
  308. package/dist/react/use-data.d.ts.map +1 -0
  309. package/dist/react/use-data.js +101 -0
  310. package/dist/react/use-selection.d.ts +54 -0
  311. package/dist/react/use-selection.d.ts.map +1 -0
  312. package/dist/react/use-selection.js +71 -0
  313. package/dist/react/world-state.d.ts +154 -0
  314. package/dist/react/world-state.d.ts.map +1 -0
  315. package/dist/react/world-state.js +220 -0
  316. package/dist/render/auto-batcher.d.ts +34 -0
  317. package/dist/render/auto-batcher.d.ts.map +1 -0
  318. package/dist/render/auto-batcher.js +140 -0
  319. package/dist/render/instance-mesh.d.ts +5 -0
  320. package/dist/render/instance-mesh.d.ts.map +1 -0
  321. package/dist/render/instance-mesh.js +19 -0
  322. package/dist/render/light-camera-factory.d.ts +24 -0
  323. package/dist/render/light-camera-factory.d.ts.map +1 -0
  324. package/dist/render/light-camera-factory.js +71 -0
  325. package/dist/render/lod.d.ts +13 -0
  326. package/dist/render/lod.d.ts.map +1 -0
  327. package/dist/render/lod.js +16 -0
  328. package/dist/render/material-factory.d.ts +15 -0
  329. package/dist/render/material-factory.d.ts.map +1 -0
  330. package/dist/render/material-factory.js +186 -0
  331. package/dist/render/mesh-shadow.d.ts +11 -0
  332. package/dist/render/mesh-shadow.d.ts.map +1 -0
  333. package/dist/render/mesh-shadow.js +19 -0
  334. package/dist/render/particles-factory.d.ts +99 -0
  335. package/dist/render/particles-factory.d.ts.map +1 -0
  336. package/dist/render/particles-factory.js +361 -0
  337. package/dist/render/render-batch-system.d.ts +33 -0
  338. package/dist/render/render-batch-system.d.ts.map +1 -0
  339. package/dist/render/render-batch-system.js +223 -0
  340. package/dist/render/render-features.d.ts +47 -0
  341. package/dist/render/render-features.d.ts.map +1 -0
  342. package/dist/render/render-features.js +105 -0
  343. package/dist/render/render-settings.d.ts +35 -0
  344. package/dist/render/render-settings.d.ts.map +1 -0
  345. package/dist/render/render-settings.js +51 -0
  346. package/dist/render/spark-renderer-lifecycle.d.ts +18 -0
  347. package/dist/render/spark-renderer-lifecycle.d.ts.map +1 -0
  348. package/dist/render/spark-renderer-lifecycle.js +57 -0
  349. package/dist/render/viewport-shading.d.ts +17 -0
  350. package/dist/render/viewport-shading.d.ts.map +1 -0
  351. package/dist/render/viewport-shading.js +87 -0
  352. package/dist/runtime/create-runtime.d.ts +259 -0
  353. package/dist/runtime/create-runtime.d.ts.map +1 -0
  354. package/dist/runtime/create-runtime.js +666 -0
  355. package/dist/runtime/debug-bridge.d.ts +288 -0
  356. package/dist/runtime/debug-bridge.d.ts.map +1 -0
  357. package/dist/runtime/debug-bridge.js +277 -0
  358. package/dist/runtime/debug-registry.d.ts +287 -0
  359. package/dist/runtime/debug-registry.d.ts.map +1 -0
  360. package/dist/runtime/debug-registry.js +528 -0
  361. package/dist/runtime/dev-layers.d.ts +34 -0
  362. package/dist/runtime/dev-layers.d.ts.map +1 -0
  363. package/dist/runtime/dev-layers.js +40 -0
  364. package/dist/runtime/frame-selector-cache.d.ts +41 -0
  365. package/dist/runtime/frame-selector-cache.d.ts.map +1 -0
  366. package/dist/runtime/frame-selector-cache.js +65 -0
  367. package/dist/runtime/game.d.ts +576 -0
  368. package/dist/runtime/game.d.ts.map +1 -0
  369. package/dist/runtime/game.js +1003 -0
  370. package/dist/runtime/gameplay-rng-trap.d.ts +47 -0
  371. package/dist/runtime/gameplay-rng-trap.d.ts.map +1 -0
  372. package/dist/runtime/gameplay-rng-trap.js +95 -0
  373. package/dist/runtime/input-router.d.ts +78 -0
  374. package/dist/runtime/input-router.d.ts.map +1 -0
  375. package/dist/runtime/input-router.js +171 -0
  376. package/dist/runtime/mount-game.d.ts +126 -0
  377. package/dist/runtime/mount-game.d.ts.map +1 -0
  378. package/dist/runtime/mount-game.js +159 -0
  379. package/dist/runtime/mount-manifest.d.ts +174 -0
  380. package/dist/runtime/mount-manifest.d.ts.map +1 -0
  381. package/dist/runtime/mount-manifest.js +304 -0
  382. package/dist/runtime/presentation.d.ts +85 -0
  383. package/dist/runtime/presentation.d.ts.map +1 -0
  384. package/dist/runtime/presentation.js +92 -0
  385. package/dist/runtime/render-audio-control.d.ts +126 -0
  386. package/dist/runtime/render-audio-control.d.ts.map +1 -0
  387. package/dist/runtime/render-audio-control.js +116 -0
  388. package/dist/runtime/render-control.d.ts +347 -0
  389. package/dist/runtime/render-control.d.ts.map +1 -0
  390. package/dist/runtime/render-control.js +317 -0
  391. package/dist/runtime/render-seed.d.ts +56 -0
  392. package/dist/runtime/render-seed.d.ts.map +1 -0
  393. package/dist/runtime/render-seed.js +73 -0
  394. package/dist/runtime/state-bridge.d.ts +60 -0
  395. package/dist/runtime/state-bridge.d.ts.map +1 -0
  396. package/dist/runtime/state-bridge.js +62 -0
  397. package/dist/runtime/types.d.ts +285 -0
  398. package/dist/runtime/types.d.ts.map +1 -0
  399. package/dist/runtime/types.js +1 -0
  400. package/dist/runtime/unexported-game-trap.d.ts +36 -0
  401. package/dist/runtime/unexported-game-trap.d.ts.map +1 -0
  402. package/dist/runtime/unexported-game-trap.js +80 -0
  403. package/dist/setup/setup-audio.d.ts +20 -0
  404. package/dist/setup/setup-audio.d.ts.map +1 -0
  405. package/dist/setup/setup-audio.js +41 -0
  406. package/dist/setup/setup-particles.d.ts +17 -0
  407. package/dist/setup/setup-particles.d.ts.map +1 -0
  408. package/dist/setup/setup-particles.js +16 -0
  409. package/dist/setup/setup-physics.d.ts +25 -0
  410. package/dist/setup/setup-physics.d.ts.map +1 -0
  411. package/dist/setup/setup-physics.js +51 -0
  412. package/dist/setup/setup-renderer.d.ts +82 -0
  413. package/dist/setup/setup-renderer.d.ts.map +1 -0
  414. package/dist/setup/setup-renderer.js +381 -0
  415. package/dist/world3d-react/engine-bridge.d.ts +47 -0
  416. package/dist/world3d-react/engine-bridge.d.ts.map +1 -0
  417. package/dist/world3d-react/engine-bridge.js +48 -0
  418. package/dist/world3d-react/index.d.ts +47 -0
  419. package/dist/world3d-react/index.d.ts.map +1 -0
  420. package/dist/world3d-react/index.js +46 -0
  421. package/dist/world3d-react/r3f-adapter.d.ts +51 -0
  422. package/dist/world3d-react/r3f-adapter.d.ts.map +1 -0
  423. package/dist/world3d-react/r3f-adapter.js +368 -0
  424. package/dist/world3d-react/r3f-root-factory.d.ts +62 -0
  425. package/dist/world3d-react/r3f-root-factory.d.ts.map +1 -0
  426. package/dist/world3d-react/r3f-root-factory.js +79 -0
  427. package/dist/world3d-react/rapier-physics-bridge.d.ts +76 -0
  428. package/dist/world3d-react/rapier-physics-bridge.d.ts.map +1 -0
  429. package/dist/world3d-react/rapier-physics-bridge.js +120 -0
  430. package/dist/world3d-react/renderer-config.d.ts +58 -0
  431. package/dist/world3d-react/renderer-config.d.ts.map +1 -0
  432. package/dist/world3d-react/renderer-config.js +96 -0
  433. package/dist/world3d-react/world-context.d.ts +123 -0
  434. package/dist/world3d-react/world-context.d.ts.map +1 -0
  435. package/dist/world3d-react/world-context.js +204 -0
  436. package/dist-config/config.js +303 -0
  437. package/dist-config/config.js.map +7 -0
  438. package/package.json +14 -3
  439. package/src/adapter/rapier-physics-adapter.ts +77 -34
  440. package/src/config.ts +8 -0
  441. package/src/core/frame-pacing.ts +26 -0
  442. package/src/core/game-loop.ts +4 -3
  443. package/src/dev/instruments.ts +302 -0
  444. package/src/runtime/mount-game.ts +6 -0
  445. package/src/runtime/unexported-game-trap.ts +82 -0
  446. package/src/setup/setup-renderer.ts +2 -0
  447. package/src/world3d-react/index.ts +9 -0
  448. package/src/world3d-react/rapier-physics-bridge.tsx +137 -0
@@ -0,0 +1,2209 @@
1
+ import { AssetParseError } from '../asset-parse-error';
2
+ import { resolveUrl } from '../loader';
3
+ import { bindingDeviceFamily, gamepadAxisLabel, gamepadAxisPairLabel, keyLabel, mouseButtonLabel, STANDARD_GAMEPAD_BUTTON_LABELS, } from './prompt-labels';
4
+ import { InputMapFileSchema } from './schema';
5
+ /**
6
+ * True when a text-entry element is focused, so game input shouldn't also fire
7
+ * (e.g. typing into an editor inspector field / renaming an entity). Cheap guard
8
+ * that holds even when the game viewport is the active tab.
9
+ */
10
+ function isTextEntryFocused() {
11
+ const el = typeof document !== 'undefined' ? document.activeElement : null;
12
+ if (!el)
13
+ return false;
14
+ const tag = el.tagName;
15
+ return (tag === 'INPUT' ||
16
+ tag === 'TEXTAREA' ||
17
+ tag === 'SELECT' ||
18
+ el.isContentEditable === true);
19
+ }
20
+ /**
21
+ * Thrown by `InputManager.setVirtualAction`/`tapVirtualAction` (Task 1.4)
22
+ * for an action name that was never `registerAction`/`loadMap`-ed. Carries a
23
+ * machine-readable `code` and `data.registered` (every declared action name)
24
+ * rather than requiring a caller to parse the message.
25
+ */
26
+ export class InputActionError extends Error {
27
+ code = 'INPUT_ACTION_NOT_FOUND';
28
+ data;
29
+ constructor(action, method, registered) {
30
+ super(`InputManager.${method}: unknown action "${action}". Registered actions: ` +
31
+ (registered.length ? registered.join(', ') : '(none)'));
32
+ this.name = 'InputActionError';
33
+ this.data = { registered };
34
+ }
35
+ }
36
+ /**
37
+ * Thrown by `InputManager.scheduleActionAtTick` (D15/T-D15.5) when the
38
+ * named `tick` has already elapsed — scheduling only ever applies to the
39
+ * CURRENT or a future tick, never one already serviced by `poll()`.
40
+ * Carries `data.currentTick` — the NEXT tick `poll()` will service (not
41
+ * the tick that just elapsed) — so a caller can retry by scheduling for
42
+ * `data.currentTick` or later.
43
+ */
44
+ export class InputTickError extends Error {
45
+ code = 'TICK_ALREADY_PASSED';
46
+ data;
47
+ constructor(tick, currentTick) {
48
+ super(`InputManager.scheduleActionAtTick: tick ${tick} has already passed (next tick to be ` +
49
+ `serviced: ${currentTick}) — scheduling only applies to the current or a future tick`);
50
+ this.name = 'InputTickError';
51
+ this.data = { currentTick };
52
+ }
53
+ }
54
+ /** Shallow equality for a resolved action value (boolean/number/Vector2) —
55
+ * D15/T-D15.5's recording tap uses this to emit DELTAS only (the trace
56
+ * format's "deltas only" line), never a full snapshot every tick. `prev`
57
+ * is `undefined` for an action never recorded before (always "changed"). */
58
+ function actionValuesEqual(prev, next) {
59
+ if (prev === undefined)
60
+ return false;
61
+ if (typeof prev !== typeof next)
62
+ return false;
63
+ if (typeof prev === 'object' && typeof next === 'object') {
64
+ return prev.x === next.x && prev.y === next.y;
65
+ }
66
+ return prev === next;
67
+ }
68
+ /** Cap on {@link InputManager}'s post-gate input-trace ring (D15/T-D15.5) —
69
+ * mirrors `debug-registry.ts`'s own `RING_CAP` precedent for the debug event
70
+ * ring: bounds memory for a recording session a caller forgot to stop. */
71
+ const INPUT_TRACE_CAP = 2000;
72
+ /**
73
+ * Maps raw keyboard/mouse/gamepad events → named actions.
74
+ *
75
+ * Usage:
76
+ * const input = new InputManager();
77
+ * await input.loadMap('inputmaps/default.inputmap.json');
78
+ * // In game loop:
79
+ * input.poll(); // call at start of frame
80
+ * if (input.isPressed('jump')) { ... }
81
+ * if (input.isJustPressed('attack')) { ... }
82
+ * input.endFrame(); // call at end of frame
83
+ *
84
+ * F1 (spec §12 "Define Typed Action Values") — typed action values:
85
+ *
86
+ * Every action DECLARES a value shape (`InputAction.valueType`, defaulted to
87
+ * `'digital'` — see `input-types.ts`'s `ActionValueType`). Each shape has its
88
+ * own typed getter, none of which return `any`:
89
+ *
90
+ * - `'digital'` — `isPressed`/`isJustPressed`/`isJustReleased` -> `boolean`
91
+ * - `'scalar'` — `getScalar` -> `number`
92
+ * - `'vector2'` — `getVector2` -> `Vector2` ({x,y})
93
+ * - `'pointerDelta'` — `getPointerDelta` -> `Vector2`
94
+ * - `'pointerPosition'` — `getPointerPosition` -> `Vector2`
95
+ *
96
+ * Reading an action through the WRONG getter (e.g. `getScalar` on a
97
+ * `'digital'` action) throws — that's the type-safety enforcement point,
98
+ * since actions are declared in data (JSON), not TS types, so there's no
99
+ * compiler backstop otherwise. `readAction(name, expectedType)` is a generic
100
+ * entry point over the same getters, typed via `ActionValueOf<T>`.
101
+ *
102
+ * Each typed getter has a `*Source` sibling (e.g. `getScalarSource`) that
103
+ * returns `ActionValueSource | null` — which binding (and, for gamepad
104
+ * bindings, which connected gamepad, or for injected test bindings, which
105
+ * named source) produced the current value. That's the "device/source
106
+ * metadata" AC.
107
+ *
108
+ * Deadzone + normalization:
109
+ * - scalar: below `deadzone` magnitude -> 0; at/above it, rescaled from 0
110
+ * (at the deadzone edge) to ±1 (at |raw| = 1), sign preserved
111
+ * (`rescaleScalar`).
112
+ * - vector2: below `deadzone` magnitude -> {0,0}; at/above it, direction is
113
+ * preserved and magnitude is rescaled the same way, then the result is
114
+ * clamped to the unit circle — magnitude never exceeds 1 even for a raw
115
+ * diagonal input like {1,1} (`rescaleVector2`).
116
+ *
117
+ * Simultaneous-binding combine rules (documented here, spec §12 F1
118
+ * "simultaneous bindings combine predictably"):
119
+ * - digital: OR — any one satisfied binding makes the action pressed
120
+ * (pre-existing behavior, unchanged).
121
+ * - scalar: max-magnitude across contributing bindings' (deadzone-applied)
122
+ * values, sign preserved; ties keep the first-listed binding
123
+ * (deterministic given binding array order).
124
+ * - vector2: sum contributing (deadzone-applied) {x,y} values component-
125
+ * wise, then clamp the sum to the unit circle (never renormalized UP —
126
+ * only ever scaled down if the sum exceeds magnitude 1).
127
+ * - pointerDelta: sum contributing deltas (matches the existing
128
+ * mouseDeltaX/Y + lookStick accumulation precedent below).
129
+ * - pointerPosition: last-write-wins — the contributing source most
130
+ * recently updated (by injection call order) wins; position isn't
131
+ * additive so summing would be meaningless.
132
+ *
133
+ * Synthetic input injection (test hook, also the shape of F2's "injected
134
+ * test input" backend): `injectAxis`/`injectVector2`/`injectPointerDelta`/
135
+ * `injectPointerPosition` push a raw value into a named source, read back by
136
+ * binding an action to `{ type: 'test_axis' | 'test_vector2' |
137
+ * 'test_pointer_delta' | 'test_pointer_position', sourceId }` — the exact
138
+ * same aggregation path (deadzone/normalize/combine) real device bindings
139
+ * use.
140
+ *
141
+ * F2 (spec §12 "Complete Device Backends") completes the real-device side of
142
+ * that same typed-value path:
143
+ *
144
+ * - `mouse_move` — un-rejected (schema.ts). Feeds `getPointerDelta` (raw
145
+ * accumulated `mouseDeltaX/Y`, no deadzone) and `getVector2` (the same
146
+ * delta, deadzone-rescaled + unit-circle-clamped).
147
+ * - `gamepad_axis_pair` — un-rejected (schema.ts). Feeds `getVector2` with
148
+ * the coupled `(xAxis, yAxis)` reading, deadzone-rescaled like a real
149
+ * stick (default deadzone 0.15, matching `gamepad_axis`).
150
+ * - `touch_button`/`touch_stick` — new binding kinds for touch/virtual
151
+ * controls. `setTouchButton(sourceId, pressed)` feeds a digital action
152
+ * (edge-tracked like `mouse_button`); `setTouchStick(sourceId, value)`
153
+ * feeds a vector2 action (deadzone-rescaled like a gamepad stick). These
154
+ * are the injectable entry points a real on-screen touch UI's own
155
+ * touchstart/touchmove/touchend handlers would call — that DOM wiring is
156
+ * a thin adapter at the edge (browser-verified separately, e.g. F4/e2e);
157
+ * the mapping logic here is unit-tested headlessly with no DOM.
158
+ * - Focus gating — `blur`/`focus` on `window` (guarded, real DOM only) now
159
+ * drop input the same way `setEnabled(false)` does (flushing held
160
+ * key/mouse/touch-button state) without touching the `enabled` flag the
161
+ * editor drives — see `focused`/`inputActive` below. This is what stops
162
+ * a stuck key/button when the user alt-tabs away mid-press.
163
+ * - Pointer lock — `pointerlockchange` on `document` (guarded) tracks
164
+ * `isPointerLocked()`; losing lock flushes mouse-button state (a click
165
+ * held at the moment lock exits must not stick).
166
+ * - Gamepad device identity — `getGamepadInfo(index)` exposes `{index, id,
167
+ * mapping, connected}`; `ActionValueSource.gamepadId` (in addition to the
168
+ * pre-existing `gamepadIndex`) is populated for every
169
+ * gamepad_button/gamepad_axis/gamepad_axis_pair source.
170
+ * - Disconnection/reconnection needs no new tracking: `poll()` already
171
+ * re-reads `navigator.getGamepads()` every frame and every read (digital
172
+ * edges, scalar/vector2 contributions) already skips a `null` gamepad
173
+ * entry, so a disconnected gamepad's bound actions go neutral (and a
174
+ * previously-held button correctly fires `isJustReleased`) with no
175
+ * special-cased code — see the state-transition tests.
176
+ *
177
+ * F3 (spec §12 "Add Rebinding and Prompts") completes the input system with
178
+ * rebinding, structural conflict detection, and device-prompt resolution:
179
+ *
180
+ * - Listing/mutating: `getBindings`/`setBindings`/`addBinding`/
181
+ * `removeBinding`/`replaceBinding` — the same `this.actions` map F1/F2
182
+ * already read, now with a public read + mutation surface (there was
183
+ * previously none — every existing call site either loaded a map once or
184
+ * read through the typed getters).
185
+ * - Reset-to-defaults: `registerAction`/`loadMap`/`loadMapObject` snapshot
186
+ * each action's bindings into `defaultBindings` (a deep clone) at
187
+ * registration/load time; `resetBindings`/`resetAllBindings` restore from
188
+ * that snapshot. Later rebinding calls do NOT touch the snapshot, so
189
+ * "reset" always means "back to what was authored/loaded", not "back to
190
+ * the last reset".
191
+ * - Persist: `toInputMapFile()` serializes the live action set back into
192
+ * the exact `.inputmap.json` shape (`InputMapFile`) `loadMap` reads;
193
+ * `loadMapObject(data)` is `loadMap`'s synchronous, no-`fetch` sibling —
194
+ * both funnel through the same `InputMapFileSchema`-validated
195
+ * `applyParsedMap`. This is the round-trip seam: serialize, write/hand to
196
+ * something else, reload, and rebound actions survive. It complements —
197
+ * doesn't replace — the SDK's `project.inputMap.read/validate/update`
198
+ * operations (B2, `packages/vgai-sdk/src/project/input-map-operations.ts`):
199
+ * those are FILE-level (a CLI/agent editing the `.inputmap.json` on disk,
200
+ * no running game involved); this is RUNTIME-level (a live game rebinding
201
+ * while playing). Both validate through the identical
202
+ * `InputMapFileSchema`, so a file B2 wrote loads here unchanged, and a
203
+ * map this class serializes is a valid document for B2 to read back.
204
+ * - Conflicts: `findConflicts(proposed, excludeActionName?)` scans every
205
+ * OTHER registered action's bindings for one that's structurally
206
+ * equivalent to `proposed` (see the private `bindingsCollide` — same
207
+ * physical input identity: same key code, same mouse button, the same
208
+ * gamepad button/axis/axis-pair, the same touch `sourceId`, etc.) and
209
+ * returns the (possibly empty) list as plain `BindingConflict` data —
210
+ * never throws. A rebinding UI calls this BEFORE calling
211
+ * `addBinding`/`replaceBinding`/`setBindings` and decides what to do with
212
+ * a non-empty result (block, warn, let the user steal the binding by
213
+ * removing it from the other action first).
214
+ * - Prompts: `getPrompt(actionName, device?, gamepadIndex?)` resolves a
215
+ * `BindingPrompt` (display label + icon name) for whichever of the
216
+ * action's bindings belongs to the requested `PromptDevice` family
217
+ * (keyboard/mouse/gamepad/touch — `bindingDeviceFamily` in
218
+ * `prompt-labels.ts`), using `getGamepadInfo` to prefer the standard
219
+ * mapping's canonical glyph names (`'A'`, `'LB'`, ...) for gamepad
220
+ * buttons and falling back to a raw index label (or a "disconnected"
221
+ * label) when the pad isn't in standard mapping or isn't connected.
222
+ * `device` is optional (F4 below) — omit it to resolve against
223
+ * `getLastActiveDevice()` instead.
224
+ *
225
+ * F4 (spec §12 "Schema and Examples") closes F3's one open gap — a
226
+ * current-ACTIVE-device tracker, so a prompt UI can switch its displayed
227
+ * label as the player switches controllers instead of the caller having to
228
+ * track that itself:
229
+ *
230
+ * - `getLastActiveDevice()` returns the `PromptDevice` family of whichever
231
+ * input arrived most recently — keyboard on `keydown`, mouse on
232
+ * `mousedown`/a real `mousemove`, gamepad on a button press or a stick
233
+ * pushed meaningfully off-center (checked in `poll()`), touch on
234
+ * `setTouchButton(_, true)` or `setTouchStick` pushed meaningfully
235
+ * off-center. `null` before any input has arrived.
236
+ * - `getPrompt(actionName)` (device omitted) resolves against it directly,
237
+ * falling back to `'keyboard'` before any input has arrived — a HUD can
238
+ * call it every frame with no extra bookkeeping and the label switches on
239
+ * its own.
240
+ */
241
+ export class InputManager {
242
+ actions = new Map();
243
+ // F1 — each registered/loaded action's declared value shape (defaults to
244
+ // 'digital' — see registerAction/loadMap). Kept as a sibling map rather than
245
+ // folded into `actions` so the pre-F1 `Map<string, InputBinding[]>` shape
246
+ // (and every existing direct read of it, e.g. in tests) stays unchanged.
247
+ actionValueTypes = new Map();
248
+ // F3 — a deep-cloned snapshot of each action's bindings AT REGISTRATION/LOAD
249
+ // TIME (registerAction/loadMap/loadMapObject), restored by
250
+ // resetBindings/resetAllBindings. Later rebinding calls (setBindings/
251
+ // addBinding/removeBinding/replaceBinding) deliberately do not touch this —
252
+ // "reset" always means "back to the originally authored/loaded defaults".
253
+ defaultBindings = new Map();
254
+ // F3 — the `version` field of the last `loadMap`/`loadMapObject`-ed
255
+ // document, carried forward by `toInputMapFile()` so a round-trip
256
+ // (serialize -> reload) preserves it. Defaults to 1 for a manager built
257
+ // purely via `registerAction` (no file was ever loaded).
258
+ loadedMapVersion = 1;
259
+ keysDown = new Set();
260
+ keysJustDown = new Set();
261
+ keysJustUp = new Set();
262
+ mouseButtons = new Set();
263
+ mouseButtonsJustDown = new Set();
264
+ mouseButtonsJustUp = new Set();
265
+ mouseDeltaX = 0;
266
+ mouseDeltaY = 0;
267
+ gamepads = [];
268
+ // Gamepad button edge tracking (P1.6c). Keys are `${gamepadIndex}:${buttonIndex}`.
269
+ // `Prev` is last frame's pressed set; `Down` is this frame's; the just-down/up
270
+ // sets are the per-frame diff computed in poll() and cleared in endFrame().
271
+ gamepadButtonsDown = new Set();
272
+ gamepadButtonsPrev = new Set();
273
+ gamepadButtonsJustDown = new Set();
274
+ gamepadButtonsJustUp = new Set();
275
+ // Gamepad axis edge tracking: raw per-(gamepad,axis) values, this frame vs
276
+ // last frame, so `gamepad_axis` bindings can compute a thresholded
277
+ // (direction + deadzone) boolean for THIS frame and compare it against the
278
+ // same threshold applied to last frame's raw value — giving real
279
+ // isJustPressed/isJustReleased edges for an otherwise-continuous input.
280
+ // Keys are `${gamepadIndex}:${axisIndex}`; `Prev` is carried forward in
281
+ // endFrame(), mirroring the button edge-tracking above.
282
+ gamepadAxesCurrent = new Map();
283
+ gamepadAxesPrev = new Map();
284
+ lookStickX = 0;
285
+ lookStickY = 0;
286
+ // F1 — injected-test-input raw value stores, keyed by caller-chosen
287
+ // `sourceId` (see the class doc comment's "Synthetic input injection"
288
+ // section). Axis/Vector2/pointer-position are LEVEL values (persist across
289
+ // frames until changed, mirroring a real analog stick/gamepad axis —
290
+ // there's no hardware poll to naturally refresh them each frame); pointer
291
+ // delta is a per-frame accumulator (cleared in endFrame(), mirroring
292
+ // mouseDeltaX/Y above).
293
+ testAxisValues = new Map();
294
+ testVector2Values = new Map();
295
+ testPointerDeltaAccum = new Map();
296
+ testPointerPositionValues = new Map();
297
+ // Monotonic counter stamped onto each injectPointerPosition call so the
298
+ // pointerPosition combine rule (last-write-wins) can tell which of several
299
+ // contributing sources was written most recently within/across frames.
300
+ pointerPositionSeq = 0;
301
+ // F2 — touch/virtual-control state, keyed by caller-chosen `sourceId` (the
302
+ // touch UI's own zone/knob id — see setTouchButton/setTouchStick). Buttons
303
+ // mirror the mouse-button edge-tracking shape (Down/JustDown/JustUp sets);
304
+ // sticks are LEVEL values like a gamepad axis (persist until changed).
305
+ touchButtonsDown = new Set();
306
+ touchButtonsJustDown = new Set();
307
+ touchButtonsJustUp = new Set();
308
+ touchStickValues = new Map();
309
+ // F4 (spec §12 "Schema and Examples" — the F3 prompt-switching gap) — which
310
+ // device family most recently produced REAL input, so a prompt UI can
311
+ // switch its displayed label ('Space' -> 'A' -> a touch control's name) as
312
+ // the player switches controllers, without the caller having to guess or
313
+ // track this itself. Updated at the same points raw input arrives: keydown
314
+ // (`'keyboard'`), mousedown/mousemove (`'mouse'`), a gamepad button press or
315
+ // a stick pushed meaningfully past rest (`'gamepad'`, both detected in
316
+ // `poll()` — a raw resting stick reports small non-zero noise on some
317
+ // pads, so this deliberately checks a coarse magnitude, not "any non-zero
318
+ // axis"), and a touch button press / stick pushed past rest
319
+ // (`'touch'` — `setTouchButton`/`setTouchStick`). `null` until the very
320
+ // first input of any kind arrives. See `getLastActiveDevice`/`getPrompt`.
321
+ lastActiveDevice = null;
322
+ /** Coarse "is this stick meaningfully off-center" check shared by the
323
+ * gamepad and touch-stick active-device heuristics above — deliberately a
324
+ * higher bar than a binding's own (often much smaller) configured
325
+ * deadzone, since this is "did the player just grab this control", not
326
+ * "does this binding's value count as non-zero". */
327
+ static isStickActive(v) {
328
+ return Math.hypot(v.x, v.y) > 0.3;
329
+ }
330
+ // Task 1.4 — action-level virtual input
331
+ // for a synthetic player, promoted from hollowstone's `VirtualInput`. Held
332
+ // digitals OR into isPressed alongside binding contributions (like
333
+ // touchButtonsDown above); tap queues, then is promoted to "active" for
334
+ // exactly one poll()/endFrame() bracket (see poll()/endFrame() below,
335
+ // mirroring hollowstone's queued/beginFrame contract); scalar/vector2 are
336
+ // level values feeding the same max-magnitude/sum combine every real
337
+ // binding uses (collectScalarContributions/collectVector2Contributions).
338
+ virtualDigitalHeld = new Set();
339
+ virtualDigitalTapQueued = new Set();
340
+ virtualDigitalTapActive = new Set();
341
+ /** pulse-runner friction #4 — the release-edge mirror of
342
+ * `virtualDigitalTapActive`: a direct `setVirtualAction(action, false)` (or
343
+ * `clearVirtualActions()`) on an action that WAS held writes here so
344
+ * `isJustReleased` fires exactly once, mirroring real `onKeyUp`'s
345
+ * immediate `keysJustUp` write (no queue/promotion needed — unlike the
346
+ * press edge, nothing in `poll()` reassigns this set out from under a
347
+ * write that lands before `poll()` runs). Cleared every `endFrame()`,
348
+ * same bracket as every other just-* edge set. */
349
+ virtualDigitalJustReleased = new Set();
350
+ virtualScalarValues = new Map();
351
+ virtualVector2Values = new Map();
352
+ // D15/T-D15.5 — tick-indexed input scheduling + post-gate recording.
353
+ //
354
+ // `currentTick` is a FALLBACK, self-incrementing counter, used only when a
355
+ // caller never tells `poll()` which tick it's servicing (every existing
356
+ // bare/headless caller — tests, a mount with no `Game` shell behind it —
357
+ // keeps this exact pre-existing behavior, zero regression). The REAL
358
+ // per-world wiring (`setup-three-root-adapter.ts`) instead passes the
359
+ // shared `Game`-level tick counter into every `poll(tick)` call — this is
360
+ // deliberate: an InputManager-local counter drifts from the actual game
361
+ // tick for a paused/frozen world (its `poll()` isn't called every game
362
+ // tick, so a local increment-per-call counter undercounts) — see the
363
+ // `lastServicedTick` gap-handling below, which structurally can't drift
364
+ // because it's driven by whatever tick value the CALLER (ultimately the
365
+ // shared `Game` tick) actually supplies.
366
+ currentTick = 0;
367
+ /** The last tick value `poll()` actually serviced, or `-1` before the
368
+ * first call. Used to detect a GAP (this world's input phase didn't run
369
+ * for one or more intervening ticks — e.g. frozen/paused while other
370
+ * roots kept advancing the shared game tick) so any schedule entries
371
+ * inside that gap can be dropped (with an observable event) instead of
372
+ * silently rotting in {@link scheduledActions} forever. */
373
+ lastServicedTick = -1;
374
+ /** Pending `scheduleActionAtTick` actuations, grouped by their exact target
375
+ * tick. Applied (and removed) at the START of that tick's `poll()` — see
376
+ * `applyScheduledActionsForTick`. A tick whose input phase is skipped
377
+ * entirely (this world paused/frozen, or a gap between two serviced
378
+ * ticks) never reaches it — its scheduled entries are dropped, each
379
+ * emitting one `'input.schedule.dropped'` debug event (`{tick, action}`)
380
+ * via {@link setDebugEmit}'s sink if one is wired — NOT retried on a
381
+ * later tick (mirrors `clearVirtualActions`-on-gate-close: no stuck
382
+ * actuation ever silently fires late). */
383
+ scheduledActions = new Map();
384
+ /** Optional sink for the `'input.schedule.dropped'` debug event (`{tick,
385
+ * action}`) emitted whenever a scheduled entry is discarded because its
386
+ * target tick's input phase never ran. Wired by whoever constructs this
387
+ * `InputManager` with access to a `DebugRegistry`
388
+ * (`setup-three-root-adapter.ts`, the same seed spot as
389
+ * `setVirtualInputTarget`/`setInputActionsSource`) — `null` (the
390
+ * default) for a bare/headless `InputManager`, in which case a drop
391
+ * stays silent (matching pre-D15/T-D15.5 behavior). */
392
+ debugEmit = null;
393
+ /** D15/T-D15.5 recording toggle — see {@link startInputRecording}. */
394
+ inputRecording = false;
395
+ /** The post-gate action-delta trace (§2.c's format sketch) — capped so an
396
+ * accidentally-long recording session can't grow this unboundedly. */
397
+ inputTrace = [];
398
+ /** Last value recorded per action, so `recordPostGateTick` only ever
399
+ * appends a DELTA (the format sketch's "deltas only" line), not a full
400
+ * snapshot every tick. Cleared on `startInputRecording()`. */
401
+ lastTraceSnapshot = new Map();
402
+ disposed = false;
403
+ /**
404
+ * When false, all raw input is ignored and held/transient state is cleared.
405
+ * The editor host drives this (T6.3, `packages/editor/src/play-mode.ts`) so
406
+ * the running game only receives input while its viewport is the active,
407
+ * focused surface — keystrokes typed into the editor (Scene tab, inspector
408
+ * fields) must not leak into the game. A standalone game leaves this true
409
+ * for its whole lifetime.
410
+ */
411
+ enabled = true;
412
+ /**
413
+ * F2 — real window focus, distinct from `enabled` (which is the editor's
414
+ * explicit play-mode gate). `false` while the tab/window is blurred (real
415
+ * `blur`/`focus` events — see the constructor). Held keyboard/mouse/touch
416
+ * state is flushed on blur so a key/button held at alt-tab time doesn't
417
+ * stick (the browser stops delivering keyup/mouseup while blurred).
418
+ */
419
+ focused = true;
420
+ /** Both gates a standalone game must pass for input to be live (spec §12
421
+ * F2 "focus gating"): the editor's explicit `enabled` flag AND real
422
+ * window focus. Used everywhere `enabled` alone used to be checked. */
423
+ get inputActive() {
424
+ return this.enabled && this.focused;
425
+ }
426
+ /** #144 — the gate MACHINE input passes (virtual actions and
427
+ * tick-scheduled actuations): the editor's explicit `enabled` flag ONLY.
428
+ * Window focus deliberately does not participate: a synthetic player
429
+ * drives the shared editor tab precisely while the human's focus is
430
+ * elsewhere (their terminal, another window) — the first live in-editor
431
+ * E2E run froze mid-suite the moment the owner started typing to their
432
+ * agent, which is the bug this gate split fixes. Real-device input keeps
433
+ * the stricter `inputActive` (enabled AND focused) gate above. */
434
+ get machineInputActive() {
435
+ return this.enabled;
436
+ }
437
+ /** F2 — real pointer-lock state (`document.pointerLockElement`), tracked via
438
+ * `pointerlockchange` (see the constructor). */
439
+ pointerLocked = false;
440
+ /** Element currently wired for click-to-pointer-lock, and its listener. */
441
+ pointerLockElement = null;
442
+ onPointerLockClick = () => {
443
+ this.pointerLockElement?.requestPointerLock();
444
+ };
445
+ onPointerLockChange = () => {
446
+ const doc = typeof document !== 'undefined' ? document : null;
447
+ const wasLocked = this.pointerLocked;
448
+ this.pointerLocked =
449
+ !!this.pointerLockElement && doc?.pointerLockElement === this.pointerLockElement;
450
+ // Losing lock mid-click must not leave a mouse button stuck down — the
451
+ // browser may not deliver a mouseup when lock exits (e.g. Escape).
452
+ if (wasLocked && !this.pointerLocked) {
453
+ this.mouseButtons.clear();
454
+ this.mouseButtonsJustDown.clear();
455
+ this.mouseButtonsJustUp.clear();
456
+ }
457
+ };
458
+ onKeyDown = (e) => {
459
+ // Ignore game input while suspended, unfocused, or while the user is typing
460
+ // into a text field (e.g. renaming an entity / editing an inspector value
461
+ // in the editor).
462
+ if (!this.inputActive || isTextEntryFocused())
463
+ return;
464
+ this.lastActiveDevice = 'keyboard';
465
+ if (!this.keysDown.has(e.code)) {
466
+ this.keysJustDown.add(e.code);
467
+ }
468
+ this.keysDown.add(e.code);
469
+ };
470
+ onKeyUp = (e) => {
471
+ if (!this.inputActive)
472
+ return;
473
+ this.keysDown.delete(e.code);
474
+ this.keysJustUp.add(e.code);
475
+ };
476
+ onMouseDown = (e) => {
477
+ if (!this.inputActive)
478
+ return;
479
+ this.lastActiveDevice = 'mouse';
480
+ this.mouseButtons.add(e.button);
481
+ this.mouseButtonsJustDown.add(e.button);
482
+ };
483
+ onMouseUp = (e) => {
484
+ if (!this.inputActive)
485
+ return;
486
+ this.mouseButtons.delete(e.button);
487
+ this.mouseButtonsJustUp.add(e.button);
488
+ };
489
+ onMouseMove = (e) => {
490
+ if (!this.inputActive)
491
+ return;
492
+ if (e.movementX !== 0 || e.movementY !== 0)
493
+ this.lastActiveDevice = 'mouse';
494
+ this.mouseDeltaX += e.movementX;
495
+ this.mouseDeltaY += e.movementY;
496
+ };
497
+ /** F2 — real window blur: drop focus and flush held REAL-device state
498
+ * (the browser stops delivering keyup/mouseup while blurred, so a key
499
+ * held at alt-tab time would stick). #144: virtual-action state is
500
+ * deliberately NOT flushed here — a bot's held action survives the human
501
+ * looking away (see `machineInputActive`); only `setEnabled(false)`
502
+ * clears it. */
503
+ onWindowBlur = () => {
504
+ this.focused = false;
505
+ this.flushRealHeldState();
506
+ };
507
+ /** F2 — real window focus regain. No flush needed (there's nothing held to
508
+ * flush — a fresh keydown/mousedown is required to register pressed
509
+ * again, exactly like re-enabling via `setEnabled(true)`). */
510
+ onWindowFocus = () => {
511
+ this.focused = true;
512
+ };
513
+ /** Clear held/transient REAL-device state (keyboard/mouse/touch-button) —
514
+ * shared by `setEnabled(false)` (via `flushHeldState`) and real blur
515
+ * (`onWindowBlur`), so a key/button physically held when input is
516
+ * suspended doesn't linger. Level values (gamepad axes, touch sticks,
517
+ * injected test axes) are deliberately NOT flushed here — they are gated
518
+ * at READ time instead (see `inputActive` checks in `poll()`/the
519
+ * `collect*Contributions` methods), matching the pre-existing
520
+ * gamepad-axis convention. */
521
+ flushRealHeldState() {
522
+ this.keysDown.clear();
523
+ this.keysJustDown.clear();
524
+ this.keysJustUp.clear();
525
+ this.mouseButtons.clear();
526
+ this.mouseButtonsJustDown.clear();
527
+ this.mouseButtonsJustUp.clear();
528
+ this.mouseDeltaX = 0;
529
+ this.mouseDeltaY = 0;
530
+ this.touchButtonsDown.clear();
531
+ this.touchButtonsJustDown.clear();
532
+ this.touchButtonsJustUp.clear();
533
+ }
534
+ /** The full flush `setEnabled(false)` performs: real-device state AND
535
+ * virtual-action state. Task 1.4's rule ("a bot's held action must not
536
+ * survive input being suspended") now applies only to the editor's
537
+ * explicit gate — #144 moved real window blur onto `flushRealHeldState`
538
+ * alone, so machine input survives the human's focus leaving the tab.
539
+ * No release edge is manufactured here (`manufactureReleaseEdge: false`,
540
+ * the default) — this is a SUSPEND, not a deliberate release, and mirrors
541
+ * `flushRealHeldState`'s own silence (a key physically held at
542
+ * suspend/blur time is wiped with no `keysJustUp`, "flush held state,
543
+ * don't corrupt history", see `poll()`'s doc comment). */
544
+ flushHeldState() {
545
+ this.flushRealHeldState();
546
+ this.clearVirtualActionState();
547
+ }
548
+ /** Shared by the public `clearVirtualActions()` and `flushHeldState()`
549
+ * above — clears every virtual-action store (held digitals, queued/active
550
+ * taps, scalar/vector2 values, the release-edge set itself).
551
+ *
552
+ * `manufactureReleaseEdge` (default `false`): when `true` — only
553
+ * `clearVirtualActions()`'s own deliberate "let go" passes this — every
554
+ * currently-held digital in `virtualDigitalHeld` first gets an
555
+ * `isJustReleased` edge written to `virtualDigitalJustReleased`, mirroring
556
+ * a real key-up (`onKeyUp` → `keysJustUp`). `flushHeldState()` (the
557
+ * editor-gate suspend path) deliberately passes `false` — see its own doc
558
+ * comment for why a suspend must stay silent. */
559
+ clearVirtualActionState(options) {
560
+ if (options?.manufactureReleaseEdge) {
561
+ for (const action of this.virtualDigitalHeld) {
562
+ this.virtualDigitalJustReleased.add(action);
563
+ }
564
+ }
565
+ this.virtualDigitalHeld.clear();
566
+ this.virtualDigitalTapQueued.clear();
567
+ this.virtualDigitalTapActive.clear();
568
+ this.virtualScalarValues.clear();
569
+ this.virtualVector2Values.clear();
570
+ }
571
+ constructor() {
572
+ if (typeof window !== 'undefined') {
573
+ window.addEventListener('keydown', this.onKeyDown);
574
+ window.addEventListener('keyup', this.onKeyUp);
575
+ window.addEventListener('mousedown', this.onMouseDown);
576
+ window.addEventListener('mouseup', this.onMouseUp);
577
+ window.addEventListener('mousemove', this.onMouseMove);
578
+ window.addEventListener('blur', this.onWindowBlur);
579
+ window.addEventListener('focus', this.onWindowFocus);
580
+ }
581
+ // `document` isn't touched by any pre-F2 code path (the headless vitest
582
+ // env stubs `window` only) — guard the same way `isTextEntryFocused` does
583
+ // so tests that don't need pointer-lock coverage need no `document` stub.
584
+ if (typeof document !== 'undefined' && typeof document.addEventListener === 'function') {
585
+ document.addEventListener('pointerlockchange', this.onPointerLockChange);
586
+ }
587
+ }
588
+ /**
589
+ * Load action map from a .inputmap.json file. Validated via
590
+ * `InputMapFileSchema` (T4.6) — a malformed input map throws a
591
+ * `AssetParseError` naming the file, not a deep TypeError once the bad
592
+ * data reaches `isPressed`/`isJustPressed`/`isJustReleased`.
593
+ */
594
+ async loadMap(url) {
595
+ let data;
596
+ try {
597
+ const res = await fetch(resolveUrl(url));
598
+ if (!res.ok) {
599
+ throw new Error(`HTTP ${res.status} ${res.statusText}`);
600
+ }
601
+ const json = await res.json();
602
+ const result = InputMapFileSchema.safeParse(json);
603
+ if (!result.success)
604
+ throw new AssetParseError(result.error.issues, url);
605
+ data = result.data;
606
+ }
607
+ catch (err) {
608
+ const message = `InputManager.loadMap: failed to load input map "${url}": ${err instanceof Error ? err.message : String(err)}`;
609
+ console.error(message);
610
+ throw err instanceof AssetParseError ? err : new Error(message);
611
+ }
612
+ this.applyParsedMap(data);
613
+ }
614
+ /**
615
+ * F3 — `loadMap`'s synchronous, no-`fetch` sibling: apply an already-in-
616
+ * memory (or freshly-deserialized) input-map DOCUMENT, validated through
617
+ * the identical `InputMapFileSchema` (throws `AssetParseError` naming no
618
+ * file, matching `loadMap`'s error shape minus the URL). This is the other
619
+ * half of the F3 persist round-trip: `toInputMapFile()` serializes,
620
+ * `loadMapObject` re-applies — no network/file I/O required, so it's also
621
+ * how a headless test proves a rebind survives a save/reload cycle.
622
+ */
623
+ loadMapObject(data) {
624
+ const result = InputMapFileSchema.safeParse(data);
625
+ if (!result.success)
626
+ throw new AssetParseError(result.error.issues);
627
+ this.applyParsedMap(result.data);
628
+ return result.data;
629
+ }
630
+ /** Shared apply step for `loadMap`/`loadMapObject`: copy each action's
631
+ * bindings + declared valueType into the live maps, and snapshot the
632
+ * bindings as that action's F3 reset-to-defaults baseline. */
633
+ applyParsedMap(data) {
634
+ this.loadedMapVersion = data.version;
635
+ for (const [name, action] of Object.entries(data.actions)) {
636
+ this.actions.set(name, action.bindings);
637
+ // `InputActionSchema.valueType` has a Zod `.default('digital')`, so a
638
+ // successfully-parsed action always carries one even when the source
639
+ // JSON omitted it.
640
+ this.actionValueTypes.set(name, action.valueType ?? 'digital');
641
+ this.defaultBindings.set(name, structuredClone(action.bindings));
642
+ }
643
+ }
644
+ /** Register an action programmatically. `valueType` declares the action's
645
+ * value shape (F1) — defaults to `'digital'`, matching every call site
646
+ * written before F1. F3 — also snapshots `bindings` as this action's
647
+ * reset-to-defaults baseline (see `resetBindings`). */
648
+ registerAction(name, bindings, valueType = 'digital') {
649
+ this.actions.set(name, bindings);
650
+ this.actionValueTypes.set(name, valueType);
651
+ this.defaultBindings.set(name, structuredClone(bindings));
652
+ }
653
+ /** The declared value type for a registered/loaded action (F1) — `'digital'`
654
+ * for an action that never specified one (including an unregistered/typo'd
655
+ * name — harmless, since every typed getter already treats an unknown
656
+ * action as inert). */
657
+ getActionValueType(actionName) {
658
+ return this.actionValueTypes.get(actionName) ?? 'digital';
659
+ }
660
+ /** Enforces the F1 type-safety AC: reading an action through a typed getter
661
+ * whose value type doesn't match the action's DECLARED `valueType` throws,
662
+ * naming both. Unknown actions (never registered/loaded) are exempt — they
663
+ * already read as inert/zeroed by every getter, matching pre-F1 behavior
664
+ * for a typo'd action name. */
665
+ assertValueType(actionName, expected, method) {
666
+ const actual = this.actionValueTypes.get(actionName);
667
+ if (actual !== undefined && actual !== expected) {
668
+ throw new Error(`InputManager.${method}: action "${actionName}" is declared valueType '${actual}', not ` +
669
+ `'${expected}'. Typed reads must match an action's declared valueType (F1, spec §12) — ` +
670
+ `use the getter for '${actual}' instead.`);
671
+ }
672
+ }
673
+ /** The names of all registered actions (r3f `world-context` enumerates these
674
+ * for its input-binding projection). */
675
+ actionNames() {
676
+ return [...this.actions.keys()];
677
+ }
678
+ /**
679
+ * Poll gamepads and virtual look stick (call at start of frame).
680
+ *
681
+ * `tick` (D15/T-D15.3/.5) — the GAME tick this call services. Pass the
682
+ * live, shared `Game` tick counter here (`setup-three-root-adapter.ts` does,
683
+ * via `DebugRegistry.getGameTick()`) so `scheduleActionAtTick`'s numbering
684
+ * never drifts from the actual game tick — the bug an earlier revision of
685
+ * this feature had: an InputManager-LOCAL counter, incremented once per
686
+ * `poll()` call, undercounts for a paused/frozen world (its `poll()` isn't
687
+ * called every game tick while frozen), so a schedule set against "tick
688
+ * 500" could fire at the wrong wall-tick once the world resumed. Omit it
689
+ * (every existing bare/headless caller does) to fall back to the
690
+ * self-incrementing `currentTick` counter — unchanged pre-D15 behavior.
691
+ */
692
+ poll(tick) {
693
+ const servicedTick = tick !== undefined ? tick : this.currentTick;
694
+ // D15/T-D15.5 — a GAP: one or more ticks strictly between the last tick
695
+ // this InputManager serviced and this one never ran its input phase at
696
+ // all (this world was paused/frozen and skipped straight from tick A to
697
+ // a later tick B > A+1 once stepped/resumed again — the frozen-world
698
+ // scenario objection above). Any entries scheduled for a tick inside
699
+ // that gap can never be honored — drop them (each emitting one
700
+ // `'input.schedule.dropped'` event) rather than leaving them to rot in
701
+ // `scheduledActions` forever. Guarded on `size > 0` so the overwhelmingly
702
+ // common case (nothing ever scheduled) costs nothing, even across a
703
+ // very large gap.
704
+ if (this.scheduledActions.size > 0) {
705
+ // Iterate the (tiny) schedule map, never the gap's tick RANGE — a
706
+ // world resuming after a very long freeze (or one mounting late into
707
+ // a game already millions of ticks in) must not pay O(gap) here.
708
+ // Sorted so drop events still arrive in tick order.
709
+ const gapped = [...this.scheduledActions.keys()]
710
+ .filter((t) => t > this.lastServicedTick && t < servicedTick)
711
+ .sort((a, b) => a - b);
712
+ for (const t of gapped) {
713
+ const skipped = this.scheduledActions.get(t);
714
+ this.scheduledActions.delete(t);
715
+ for (const entry of skipped) {
716
+ this.debugEmit?.('input.schedule.dropped', { tick: t, action: entry.action });
717
+ }
718
+ }
719
+ }
720
+ this.lastServicedTick = servicedTick;
721
+ this.currentTick = servicedTick + 1;
722
+ if (!this.enabled) {
723
+ // Input suspended by the editor's explicit gate (play stopped /
724
+ // game-tab-inactive). #144: this branch no longer covers real window
725
+ // blur — an enabled-but-blurred tick falls through so MACHINE input
726
+ // (virtual actions, scheduled actuations) keeps flowing while the
727
+ // human's focus is elsewhere; real devices are gated further down.
728
+ // Unlike keyboard/mouse, gamepad state isn't DOM-event-driven —
729
+ // `isPressed`/`isJustPressed`/`isJustReleased` read `this.gamepads`
730
+ // (and the edge-tracked sets) directly, not a live poll of `navigator`.
731
+ // So gate the READ here: leave `this.gamepads` empty so every
732
+ // gamepad-bound check sees no gamepads and reports false. Deliberately
733
+ // leave the edge-tracking sets
734
+ // (gamepadButtons{Prev,Down,JustDown,JustUp}, gamepadAxes{Current,Prev})
735
+ // untouched — they freeze at their last real values while disabled and
736
+ // resume diffing against genuinely-last-observed hardware state once
737
+ // re-enabled, so there's no phantom edge on re-enable (mirrors the
738
+ // "flush held state, don't corrupt history" intent of setEnabled below).
739
+ // D15/T-D15.5: a tick serviced while gated drops its OWN scheduled
740
+ // entries too (never applied, never retried later) — same honesty line
741
+ // `setVirtualAction`'s own gate already draws — each emitting the same
742
+ // `'input.schedule.dropped'` event the gap-handling above does.
743
+ const gatedDrop = this.scheduledActions.get(servicedTick);
744
+ if (gatedDrop) {
745
+ this.scheduledActions.delete(servicedTick);
746
+ for (const entry of gatedDrop) {
747
+ this.debugEmit?.('input.schedule.dropped', { tick: servicedTick, action: entry.action });
748
+ }
749
+ }
750
+ this.gamepads = [];
751
+ return;
752
+ }
753
+ // Task 1.4 — promote queued tapVirtualAction() calls to this frame's
754
+ // "active" just-pressed set (hollowstone's queued/beginFrame contract,
755
+ // ported onto this engine's existing fixed-step poll()/endFrame()
756
+ // bracket instead of a bespoke beginFrame() — poll() already runs at the
757
+ // start of the fixed step). Cleared in endFrame() below.
758
+ this.virtualDigitalTapActive = this.virtualDigitalTapQueued;
759
+ this.virtualDigitalTapQueued = new Set();
760
+ // D15/T-D15.5 — apply any actuation scheduled for exactly this tick
761
+ // (spec §2.c: "applied at the START of the target tick's input phase",
762
+ // before any gameplay phase reads input — this still runs before every
763
+ // OTHER phase this tick, `input` being the first system phase). Placed
764
+ // AFTER the tap-queue promotion immediately above (not before) so a
765
+ // scheduled digital `true` can add itself to `virtualDigitalTapActive`
766
+ // (see `applyScheduledActionsForTick`) without that promotion's
767
+ // reassignment wiping it out.
768
+ this.applyScheduledActionsForTick(servicedTick);
769
+ if (!this.focused) {
770
+ // #144 — enabled but blurred: everything ABOVE this line is machine
771
+ // input (tap promotion, scheduled actuations) and stays live; real
772
+ // devices below gate exactly as the old combined branch did (no
773
+ // gamepads presented, edge sets frozen at their last real values).
774
+ // The post-gate trace still records — "what the sim actually
775
+ // consumed" includes machine input delivered while blurred.
776
+ this.gamepads = [];
777
+ this.recordPostGateTick(servicedTick);
778
+ return;
779
+ }
780
+ this.gamepads =
781
+ typeof navigator !== 'undefined' && navigator.getGamepads ? [...navigator.getGamepads()] : [];
782
+ // Gamepad button edge detection: diff this frame's pressed set against the
783
+ // previous frame's so isJustPressed/isJustReleased work for gamepads too.
784
+ const current = new Set();
785
+ for (let i = 0; i < this.gamepads.length; i++) {
786
+ const gp = this.gamepads[i];
787
+ if (!gp)
788
+ continue;
789
+ for (let b = 0; b < gp.buttons.length; b++) {
790
+ if (gp.buttons[b]?.pressed)
791
+ current.add(`${i}:${b}`);
792
+ }
793
+ }
794
+ for (const key of current) {
795
+ if (!this.gamepadButtonsPrev.has(key))
796
+ this.gamepadButtonsJustDown.add(key);
797
+ }
798
+ for (const key of this.gamepadButtonsPrev) {
799
+ if (!current.has(key))
800
+ this.gamepadButtonsJustUp.add(key);
801
+ }
802
+ this.gamepadButtonsDown = current;
803
+ // F4 — a button press is unambiguous real gamepad input.
804
+ if (current.size > 0)
805
+ this.lastActiveDevice = 'gamepad';
806
+ // Snapshot this frame's raw axis values per (gamepad, axis) — independent
807
+ // of any binding's direction/deadzone, mirroring the button snapshot
808
+ // above. isPressed/isJustPressed/isJustReleased apply a binding's own
809
+ // threshold to these raw values (current vs. `gamepadAxesPrev`) on read.
810
+ const currentAxes = new Map();
811
+ for (let i = 0; i < this.gamepads.length; i++) {
812
+ const gp = this.gamepads[i];
813
+ if (!gp)
814
+ continue;
815
+ for (let a = 0; a < gp.axes.length; a++) {
816
+ const value = gp.axes[a] ?? 0;
817
+ currentAxes.set(`${i}:${a}`, value);
818
+ // F4 — a stick pushed meaningfully off-center is also unambiguous
819
+ // real gamepad input (see `isStickActive`'s doc comment).
820
+ if (Math.abs(value) > 0.3)
821
+ this.lastActiveDevice = 'gamepad';
822
+ }
823
+ }
824
+ this.gamepadAxesCurrent = currentAxes;
825
+ // Inject look stick as continuous mouse delta (position → rate-of-rotation)
826
+ if (this.lookStickX !== 0 || this.lookStickY !== 0) {
827
+ const scale = 8;
828
+ this.mouseDeltaX += this.lookStickX * scale;
829
+ this.mouseDeltaY += this.lookStickY * scale;
830
+ }
831
+ // D15/T-D15.5 — tap the POST-GATE resolved values for this tick LAST
832
+ // (every binding/virtual/scheduled contribution above has already been
833
+ // folded in): "what the sim actually consumed", the honesty line the
834
+ // design doc draws for record-now/replay-in-SP5 (§2.c).
835
+ this.recordPostGateTick(servicedTick);
836
+ }
837
+ /**
838
+ * D15/T-D15.5 — apply every actuation `scheduleActionAtTick` queued for
839
+ * exactly `tick`, then forget them (a tick is serviced at most once).
840
+ *
841
+ * Digital `true` gets SPECIAL handling (the objection-1 fix): it promotes
842
+ * the action into this tick's `virtualDigitalTapActive` set directly — the
843
+ * same one-tick "active" pulse `tapVirtualAction` uses — so `isJustPressed`
844
+ * reads true for EXACTLY this tick (false on the next, per `endFrame()`'s
845
+ * clear) while `isPressed` keeps reading true afterward (still held) until
846
+ * a later scheduled/explicit `false` releases it. This direct write is
847
+ * safe here (unlike `applyVirtualActionValue`'s equivalent direct-path
848
+ * case — see its doc comment) specifically because this method only ever
849
+ * runs from inside `poll()`, AFTER `poll()`'s own tap-queue-promotion
850
+ * reassignment of `virtualDigitalTapActive` has already happened for this
851
+ * tick (see `poll()`'s own comment on why it's placed after) — so there's
852
+ * no risk of this write being silently wiped by that reassignment.
853
+ *
854
+ * pulse-runner friction #4: a prior revision of this comment
855
+ * used to say `setVirtualAction`'s plain write "never produces a
856
+ * just-pressed edge at all" and that the edge fix landed ONLY here, for
857
+ * this scheduled path — true at the time, and exactly the gap a blind
858
+ * dogfood run (pulse-runner) hit through the direct `setVirtualAction`/
859
+ * `holdFor` path. `applyVirtualActionValue` now manufactures the same kind
860
+ * of edge for THAT path too (queued instead of written directly, for the
861
+ * timing reason above) — this is no longer the only path that does.
862
+ *
863
+ * A digital `false` here simply releases the hold — no edge is
864
+ * manufactured for it at a SCHEDULED tick (no caller needs a virtual
865
+ * `isJustReleased` fired at an exact future tick today); the direct
866
+ * `setVirtualAction(action, false)`/`clearVirtualActions()` paths DO
867
+ * manufacture one now (see `applyVirtualActionValue`/
868
+ * `clearVirtualActionState`). Scalar/vector2 values apply directly,
869
+ * unchanged.
870
+ */
871
+ applyScheduledActionsForTick(tick) {
872
+ const pending = this.scheduledActions.get(tick);
873
+ if (!pending)
874
+ return;
875
+ this.scheduledActions.delete(tick);
876
+ for (const entry of pending) {
877
+ if (typeof entry.value === 'boolean') {
878
+ if (entry.value) {
879
+ this.virtualDigitalHeld.add(entry.action);
880
+ this.virtualDigitalTapActive.add(entry.action);
881
+ }
882
+ else {
883
+ this.virtualDigitalHeld.delete(entry.action);
884
+ }
885
+ }
886
+ else {
887
+ this.applyVirtualActionValue(entry.action, entry.value);
888
+ }
889
+ }
890
+ }
891
+ /** D15/T-D15.5 — append this tick's action-value DELTA to the recording
892
+ * ring, iff a recording is active. Reads every declared digital/scalar/
893
+ * vector2 action through the exact same typed getters gameplay code would
894
+ * (`readAction`), so the trace reflects what a component reading these
895
+ * actions THIS tick actually sees post-gate — never a raw/ungated value.
896
+ * `pointerDelta`/`pointerPosition` actions are skipped (a different,
897
+ * frame-accumulated shape, and not part of the virtual-action/schedule
898
+ * surface this trace exists to prove).
899
+ *
900
+ * Two replay-affecting caveats a future SP5 consumer must know:
901
+ * 1. A gated stretch never calls this at all (`poll()`'s gated branch
902
+ * returns before reaching it) — no entries are recorded for ticks
903
+ * input was suspended. Any change only OBSERVABLE once re-enabled (a
904
+ * delta against `lastTraceSnapshot`) lands as a delta AT the re-enable
905
+ * tick, not at whatever tick it actually happened.
906
+ * 2. This ring is capped (`INPUT_TRACE_CAP`) and evicts via `shift()` once
907
+ * it fills — dropping the OLDEST entry. Because entries are DELTAS,
908
+ * evicting the earliest entries drops the base state later deltas were
909
+ * relative to — this ring is not safe to replay from its start once it
910
+ * has ever been capped. */
911
+ recordPostGateTick(tick) {
912
+ if (!this.inputRecording)
913
+ return;
914
+ const deltas = {};
915
+ let changed = false;
916
+ for (const name of this.actionNames()) {
917
+ const type = this.getActionValueType(name);
918
+ if (type !== 'digital' && type !== 'scalar' && type !== 'vector2')
919
+ continue;
920
+ const value = this.readAction(name, type);
921
+ const prev = this.lastTraceSnapshot.get(name);
922
+ if (actionValuesEqual(prev, value))
923
+ continue;
924
+ deltas[name] = value;
925
+ this.lastTraceSnapshot.set(name, value);
926
+ changed = true;
927
+ }
928
+ if (!changed)
929
+ return;
930
+ this.inputTrace.push({ tick, actions: deltas });
931
+ if (this.inputTrace.length > INPUT_TRACE_CAP)
932
+ this.inputTrace.shift();
933
+ }
934
+ /** Has a `gamepad_axis` binding's raw value crossed its direction+deadzone
935
+ * threshold (positive: `value > deadzone`; negative: `value < -deadzone`)? */
936
+ static axisThresholdMet(value, direction, deadzone) {
937
+ return direction === 'positive' ? value > deadzone : value < -deadzone;
938
+ }
939
+ /** Is an action currently held down? */
940
+ isPressed(actionName) {
941
+ this.assertValueType(actionName, 'digital', 'isPressed');
942
+ // Task 1.4 — a held virtual action, or a tap promoted to this frame's
943
+ // "active" set, ORs into isPressed alongside binding contributions.
944
+ if (this.virtualDigitalHeld.has(actionName) || this.virtualDigitalTapActive.has(actionName)) {
945
+ return true;
946
+ }
947
+ const bindings = this.actions.get(actionName);
948
+ if (!bindings)
949
+ return false;
950
+ for (const binding of bindings) {
951
+ switch (binding.type) {
952
+ case 'key':
953
+ if (this.keysDown.has(binding.code))
954
+ return true;
955
+ break;
956
+ case 'mouse_button':
957
+ if (this.mouseButtons.has(binding.button))
958
+ return true;
959
+ break;
960
+ case 'gamepad_button':
961
+ for (const gp of this.gamepads) {
962
+ if (gp?.buttons[binding.button]?.pressed)
963
+ return true;
964
+ }
965
+ break;
966
+ case 'gamepad_axis': {
967
+ const dz = binding.deadzone ?? 0.15;
968
+ for (const gp of this.gamepads) {
969
+ if (!gp)
970
+ continue;
971
+ const val = gp.axes[binding.axis] ?? 0;
972
+ if (InputManager.axisThresholdMet(val, binding.direction, dz))
973
+ return true;
974
+ }
975
+ break;
976
+ }
977
+ case 'touch_button':
978
+ if (this.touchButtonsDown.has(binding.sourceId))
979
+ return true;
980
+ break;
981
+ }
982
+ }
983
+ return false;
984
+ }
985
+ /** Was an action pressed this frame (not held from previous)? */
986
+ isJustPressed(actionName) {
987
+ this.assertValueType(actionName, 'digital', 'isJustPressed');
988
+ // Task 1.4 — a tapVirtualAction() queued on a prior frame reads
989
+ // just-pressed for exactly the one poll()/endFrame() bracket it was
990
+ // promoted into (see poll()/endFrame() below).
991
+ if (this.virtualDigitalTapActive.has(actionName))
992
+ return true;
993
+ const bindings = this.actions.get(actionName);
994
+ if (!bindings)
995
+ return false;
996
+ for (const binding of bindings) {
997
+ switch (binding.type) {
998
+ case 'key':
999
+ if (this.keysJustDown.has(binding.code))
1000
+ return true;
1001
+ break;
1002
+ case 'mouse_button':
1003
+ if (this.mouseButtonsJustDown.has(binding.button))
1004
+ return true;
1005
+ break;
1006
+ case 'gamepad_button':
1007
+ // Edge-tracked in poll(): true only on the first frame the button
1008
+ // transitions from up→down (across any connected gamepad).
1009
+ for (let i = 0; i < this.gamepads.length; i++) {
1010
+ if (this.gamepadButtonsJustDown.has(`${i}:${binding.button}`))
1011
+ return true;
1012
+ }
1013
+ break;
1014
+ case 'gamepad_axis': {
1015
+ // Edge-tracked via raw axis snapshots (poll()): true only on the
1016
+ // first frame the thresholded (direction+deadzone) boolean flips
1017
+ // from off→on (across any connected gamepad).
1018
+ const dz = binding.deadzone ?? 0.15;
1019
+ for (let i = 0; i < this.gamepads.length; i++) {
1020
+ const key = `${i}:${binding.axis}`;
1021
+ const now = this.gamepadAxesCurrent.get(key) ?? 0;
1022
+ const prev = this.gamepadAxesPrev.get(key) ?? 0;
1023
+ const nowOn = InputManager.axisThresholdMet(now, binding.direction, dz);
1024
+ const prevOn = InputManager.axisThresholdMet(prev, binding.direction, dz);
1025
+ if (nowOn && !prevOn)
1026
+ return true;
1027
+ }
1028
+ break;
1029
+ }
1030
+ case 'touch_button':
1031
+ if (this.touchButtonsJustDown.has(binding.sourceId))
1032
+ return true;
1033
+ break;
1034
+ }
1035
+ }
1036
+ return false;
1037
+ }
1038
+ /** Was an action released this frame (held last frame, up now)? */
1039
+ isJustReleased(actionName) {
1040
+ this.assertValueType(actionName, 'digital', 'isJustReleased');
1041
+ // pulse-runner friction #4 — mirrors isJustPressed's virtual check above:
1042
+ // a direct setVirtualAction(action, false) or clearVirtualActions() on a
1043
+ // held action manufactures exactly one just-released edge here, matching
1044
+ // a real key-up's keysJustUp.
1045
+ if (this.virtualDigitalJustReleased.has(actionName))
1046
+ return true;
1047
+ const bindings = this.actions.get(actionName);
1048
+ if (!bindings)
1049
+ return false;
1050
+ for (const binding of bindings) {
1051
+ switch (binding.type) {
1052
+ case 'key':
1053
+ if (this.keysJustUp.has(binding.code))
1054
+ return true;
1055
+ break;
1056
+ case 'mouse_button':
1057
+ if (this.mouseButtonsJustUp.has(binding.button))
1058
+ return true;
1059
+ break;
1060
+ case 'gamepad_button':
1061
+ for (let i = 0; i < this.gamepads.length; i++) {
1062
+ if (this.gamepadButtonsJustUp.has(`${i}:${binding.button}`))
1063
+ return true;
1064
+ }
1065
+ break;
1066
+ case 'gamepad_axis': {
1067
+ // The mirror of isJustPressed: true only on the first frame the
1068
+ // thresholded boolean flips from on→off.
1069
+ const dz = binding.deadzone ?? 0.15;
1070
+ for (let i = 0; i < this.gamepads.length; i++) {
1071
+ const key = `${i}:${binding.axis}`;
1072
+ const now = this.gamepadAxesCurrent.get(key) ?? 0;
1073
+ const prev = this.gamepadAxesPrev.get(key) ?? 0;
1074
+ const nowOn = InputManager.axisThresholdMet(now, binding.direction, dz);
1075
+ const prevOn = InputManager.axisThresholdMet(prev, binding.direction, dz);
1076
+ if (!nowOn && prevOn)
1077
+ return true;
1078
+ }
1079
+ break;
1080
+ }
1081
+ case 'touch_button':
1082
+ if (this.touchButtonsJustUp.has(binding.sourceId))
1083
+ return true;
1084
+ break;
1085
+ }
1086
+ }
1087
+ return false;
1088
+ }
1089
+ /** Device/source metadata (F1 AC) for a digital action: which binding is
1090
+ * CURRENTLY satisfying `isPressed`, or `null` if none is (including an
1091
+ * unknown action). First-satisfied-binding-wins, mirroring isPressed's own
1092
+ * iteration order. */
1093
+ getDigitalSource(actionName) {
1094
+ this.assertValueType(actionName, 'digital', 'getDigitalSource');
1095
+ // #144 — mirror isPressed's own pre-gate virtual check: a machine-held
1096
+ // action reports its source even while the window is blurred.
1097
+ if (this.machineInputActive &&
1098
+ (this.virtualDigitalHeld.has(actionName) || this.virtualDigitalTapActive.has(actionName))) {
1099
+ return { bindingType: 'virtual' };
1100
+ }
1101
+ if (!this.inputActive)
1102
+ return null;
1103
+ const bindings = this.actions.get(actionName);
1104
+ if (!bindings)
1105
+ return null;
1106
+ for (const binding of bindings) {
1107
+ switch (binding.type) {
1108
+ case 'key':
1109
+ if (this.keysDown.has(binding.code))
1110
+ return { bindingType: 'key' };
1111
+ break;
1112
+ case 'mouse_button':
1113
+ if (this.mouseButtons.has(binding.button))
1114
+ return { bindingType: 'mouse_button' };
1115
+ break;
1116
+ case 'gamepad_button':
1117
+ for (let i = 0; i < this.gamepads.length; i++) {
1118
+ const gp = this.gamepads[i];
1119
+ if (gp?.buttons[binding.button]?.pressed) {
1120
+ return { bindingType: 'gamepad_button', gamepadIndex: i, gamepadId: gp.id };
1121
+ }
1122
+ }
1123
+ break;
1124
+ case 'gamepad_axis': {
1125
+ const dz = binding.deadzone ?? 0.15;
1126
+ for (let i = 0; i < this.gamepads.length; i++) {
1127
+ const gp = this.gamepads[i];
1128
+ if (!gp)
1129
+ continue;
1130
+ const val = gp.axes[binding.axis] ?? 0;
1131
+ if (InputManager.axisThresholdMet(val, binding.direction, dz)) {
1132
+ return { bindingType: 'gamepad_axis', gamepadIndex: i, gamepadId: gp.id };
1133
+ }
1134
+ }
1135
+ break;
1136
+ }
1137
+ case 'touch_button':
1138
+ if (this.touchButtonsDown.has(binding.sourceId)) {
1139
+ return { bindingType: 'touch_button', sourceId: binding.sourceId };
1140
+ }
1141
+ break;
1142
+ }
1143
+ }
1144
+ return null;
1145
+ }
1146
+ // ==========================================================================
1147
+ // F1 — typed scalar/vector2/pointer reads. See the class doc comment above
1148
+ // for the deadzone/normalize/combine rules these implement.
1149
+ // ==========================================================================
1150
+ /** 1D deadzone rescale: magnitudes below `deadzone` become 0; magnitudes
1151
+ * at/above it rescale from 0 (at the deadzone edge) to ±1 (at |raw| = 1),
1152
+ * sign preserved. `raw` is clamped to [-1, 1] first so an out-of-range
1153
+ * input can't overshoot past ±1 the other end. */
1154
+ static rescaleScalar(raw, deadzone) {
1155
+ const clamped = Math.max(-1, Math.min(1, raw));
1156
+ const mag = Math.abs(clamped);
1157
+ if (mag < deadzone)
1158
+ return 0;
1159
+ const rescaled = deadzone >= 1 ? 0 : (mag - deadzone) / (1 - deadzone);
1160
+ return Math.sign(clamped) * Math.min(1, rescaled);
1161
+ }
1162
+ /** Radial deadzone + unit-circle normalization for a Vector2: magnitude
1163
+ * below `deadzone` snaps to {0,0}; at/above it, direction is preserved and
1164
+ * magnitude is rescaled the same way `rescaleScalar` rescales a 1D
1165
+ * magnitude (never renormalized UP past 1 — only ever scaled down). */
1166
+ static rescaleVector2(raw, deadzone) {
1167
+ const mag = Math.hypot(raw.x, raw.y);
1168
+ if (mag === 0 || mag < deadzone)
1169
+ return { x: 0, y: 0 };
1170
+ const rescaledMag = Math.min(1, deadzone >= 1 ? 0 : (mag - deadzone) / (1 - deadzone));
1171
+ const scale = rescaledMag / mag;
1172
+ return { x: raw.x * scale, y: raw.y * scale };
1173
+ }
1174
+ /** Clamp a Vector2's magnitude to at most 1 (unit circle), preserving
1175
+ * direction — the second half of the vector2 "sum-then-clamp" combine
1176
+ * rule (a diagonal sum like {0.8, 0.8} has magnitude > 1). */
1177
+ static clampVector2(v) {
1178
+ const mag = Math.hypot(v.x, v.y);
1179
+ if (mag <= 1 || mag === 0)
1180
+ return v;
1181
+ return { x: v.x / mag, y: v.y / mag };
1182
+ }
1183
+ /** Every `scalar`-relevant binding's (deadzone-applied) contribution for
1184
+ * `actionName`, one entry per binding that can produce a scalar value —
1185
+ * `gamepad_axis` (real device, already implemented pre-F1 for digital
1186
+ * thresholding — F1 additionally reads its raw signed value for scalar
1187
+ * actions, ignoring the binding's `direction` field, which is a digital-
1188
+ * only hint) and `test_axis` (F1's injected-test-input source). `mouse_move`
1189
+ * deliberately does NOT feed scalar (spec §12 F2 — no natural single-axis
1190
+ * selector field is defined for it; it feeds pointerDelta/vector2 only —
1191
+ * see `collectPointerDeltaContributions`/`collectVector2Contributions`). */
1192
+ collectScalarContributions(actionName) {
1193
+ const out = [];
1194
+ // Task 1.4 — a virtual scalar value joins the same max-magnitude combine
1195
+ // real bindings do (computeScalar below). #144: it passes the MACHINE
1196
+ // gate (enabled only), so a bot's held value reads through while the
1197
+ // window is blurred; real bindings below keep the full focus gate.
1198
+ const virtual = this.virtualScalarValues.get(actionName);
1199
+ if (virtual !== undefined && this.machineInputActive) {
1200
+ out.push({ value: virtual, source: { bindingType: 'virtual' } });
1201
+ }
1202
+ if (!this.inputActive)
1203
+ return out;
1204
+ const bindings = this.actions.get(actionName);
1205
+ if (!bindings)
1206
+ return out;
1207
+ for (const binding of bindings) {
1208
+ if (binding.type === 'gamepad_axis') {
1209
+ const dz = binding.deadzone ?? 0.15;
1210
+ for (let i = 0; i < this.gamepads.length; i++) {
1211
+ const gp = this.gamepads[i];
1212
+ if (!gp)
1213
+ continue;
1214
+ const raw = gp.axes[binding.axis] ?? 0;
1215
+ out.push({
1216
+ value: InputManager.rescaleScalar(raw, dz),
1217
+ source: { bindingType: 'gamepad_axis', gamepadIndex: i, gamepadId: gp.id },
1218
+ });
1219
+ }
1220
+ }
1221
+ else if (binding.type === 'test_axis') {
1222
+ const raw = this.testAxisValues.get(binding.sourceId) ?? 0;
1223
+ out.push({
1224
+ value: InputManager.rescaleScalar(raw, binding.deadzone ?? 0),
1225
+ source: { bindingType: 'test_axis', sourceId: binding.sourceId },
1226
+ });
1227
+ }
1228
+ }
1229
+ return out;
1230
+ }
1231
+ computeScalar(actionName) {
1232
+ this.assertValueType(actionName, 'scalar', 'getScalar');
1233
+ let best = null;
1234
+ for (const c of this.collectScalarContributions(actionName)) {
1235
+ if (!best || Math.abs(c.value) > Math.abs(best.value))
1236
+ best = c;
1237
+ }
1238
+ if (!best || best.value === 0)
1239
+ return { value: 0, source: null };
1240
+ return best;
1241
+ }
1242
+ /** Read a `'scalar'`-valueType action's current value: max-magnitude across
1243
+ * contributing (deadzone-applied) bindings, sign preserved (combine rule —
1244
+ * see the class doc comment). Throws if the action is declared a
1245
+ * different valueType. */
1246
+ getScalar(actionName) {
1247
+ return this.computeScalar(actionName).value;
1248
+ }
1249
+ /** Device/source metadata for {@link getScalar} — which binding is
1250
+ * currently driving the combined value, or `null` if every contribution is
1251
+ * zero (including an unknown action). */
1252
+ getScalarSource(actionName) {
1253
+ return this.computeScalar(actionName).source;
1254
+ }
1255
+ /** `gamepad_axis_pair` contribution(s) for {@link collectVector2Contributions} — one entry
1256
+ * per connected gamepad, deadzone-rescaled (default 0.15, matching `gamepad_axis`). Broken
1257
+ * out to a helper so the per-gamepad loop doesn't add to the main dispatcher's complexity. */
1258
+ contributeGamepadAxisPair(binding) {
1259
+ const dz = binding.deadzone ?? 0.15;
1260
+ const out = [];
1261
+ for (let i = 0; i < this.gamepads.length; i++) {
1262
+ const gp = this.gamepads[i];
1263
+ if (!gp)
1264
+ continue;
1265
+ const raw = { x: gp.axes[binding.xAxis] ?? 0, y: gp.axes[binding.yAxis] ?? 0 };
1266
+ out.push({
1267
+ value: InputManager.rescaleVector2(raw, dz),
1268
+ source: { bindingType: 'gamepad_axis_pair', gamepadIndex: i, gamepadId: gp.id },
1269
+ });
1270
+ }
1271
+ return out;
1272
+ }
1273
+ /** Every `vector2`-relevant binding's (deadzone-applied) contribution:
1274
+ * `test_vector2` (F1's injected-test-input source), plus F2's real-device
1275
+ * cases — `gamepad_axis_pair` (see {@link contributeGamepadAxisPair}), `mouse_move` (the
1276
+ * accumulated mouse delta, deadzone default 0 — raw pixel deltas have no natural "at rest"
1277
+ * jitter floor the way an analog stick does), and `touch_stick` (a virtual on-screen stick,
1278
+ * deadzone default 0). */
1279
+ collectVector2Contributions(actionName) {
1280
+ const out = [];
1281
+ // Task 1.4 — a virtual vector2 value joins the same sum-then-clamp
1282
+ // combine real bindings do (computeVector2 below). #144: machine gate
1283
+ // only, same as the scalar collector above.
1284
+ const virtual = this.virtualVector2Values.get(actionName);
1285
+ if (virtual !== undefined && this.machineInputActive) {
1286
+ out.push({ value: virtual, source: { bindingType: 'virtual' } });
1287
+ }
1288
+ if (!this.inputActive)
1289
+ return out;
1290
+ const bindings = this.actions.get(actionName);
1291
+ if (!bindings)
1292
+ return out;
1293
+ for (const binding of bindings) {
1294
+ switch (binding.type) {
1295
+ case 'test_vector2': {
1296
+ const raw = this.testVector2Values.get(binding.sourceId) ?? { x: 0, y: 0 };
1297
+ out.push({
1298
+ value: InputManager.rescaleVector2(raw, binding.deadzone ?? 0),
1299
+ source: { bindingType: 'test_vector2', sourceId: binding.sourceId },
1300
+ });
1301
+ break;
1302
+ }
1303
+ case 'gamepad_axis_pair':
1304
+ out.push(...this.contributeGamepadAxisPair(binding));
1305
+ break;
1306
+ case 'mouse_move': {
1307
+ const raw = { x: this.mouseDeltaX, y: this.mouseDeltaY };
1308
+ out.push({
1309
+ value: InputManager.rescaleVector2(raw, binding.deadzone ?? 0),
1310
+ source: { bindingType: 'mouse_move' },
1311
+ });
1312
+ break;
1313
+ }
1314
+ case 'touch_stick': {
1315
+ const raw = this.touchStickValues.get(binding.sourceId) ?? { x: 0, y: 0 };
1316
+ out.push({
1317
+ value: InputManager.rescaleVector2(raw, binding.deadzone ?? 0),
1318
+ source: { bindingType: 'touch_stick', sourceId: binding.sourceId },
1319
+ });
1320
+ break;
1321
+ }
1322
+ }
1323
+ }
1324
+ return out;
1325
+ }
1326
+ computeVector2(actionName) {
1327
+ this.assertValueType(actionName, 'vector2', 'getVector2');
1328
+ let sum = { x: 0, y: 0 };
1329
+ let bestSource = null;
1330
+ let bestMag = 0;
1331
+ for (const c of this.collectVector2Contributions(actionName)) {
1332
+ sum = { x: sum.x + c.value.x, y: sum.y + c.value.y };
1333
+ const mag = Math.hypot(c.value.x, c.value.y);
1334
+ if (mag > bestMag) {
1335
+ bestMag = mag;
1336
+ bestSource = c.source;
1337
+ }
1338
+ }
1339
+ const clamped = InputManager.clampVector2(sum);
1340
+ if (clamped.x === 0 && clamped.y === 0)
1341
+ return { value: clamped, source: null };
1342
+ return { value: clamped, source: bestSource };
1343
+ }
1344
+ /** Read a `'vector2'`-valueType action's current value: sum contributing
1345
+ * (deadzone-applied) {x,y} values component-wise, then clamp to the unit
1346
+ * circle (combine rule — see the class doc comment). Throws if the action
1347
+ * is declared a different valueType. */
1348
+ getVector2(actionName) {
1349
+ return this.computeVector2(actionName).value;
1350
+ }
1351
+ /** Device/source metadata for {@link getVector2} — the contributing binding
1352
+ * with the largest (pre-combine) magnitude, or `null` if the combined
1353
+ * value is {0,0} (including an unknown action). */
1354
+ getVector2Source(actionName) {
1355
+ return this.computeVector2(actionName).source;
1356
+ }
1357
+ /** Every `pointerDelta`-relevant binding's contribution: `test_pointer_delta`
1358
+ * (F1's injected-test-input source) and — F2 — `mouse_move`, reading the
1359
+ * real accumulated `mouseDeltaX/Y` (the same accumulator `onMouseMove`
1360
+ * fills and `getMouseDelta()` reads). No deadzone for either (deltas are
1361
+ * not deadzoned). */
1362
+ collectPointerDeltaContributions(actionName) {
1363
+ if (!this.inputActive)
1364
+ return [];
1365
+ const bindings = this.actions.get(actionName);
1366
+ if (!bindings)
1367
+ return [];
1368
+ const out = [];
1369
+ for (const binding of bindings) {
1370
+ if (binding.type === 'test_pointer_delta') {
1371
+ const value = this.testPointerDeltaAccum.get(binding.sourceId) ?? { x: 0, y: 0 };
1372
+ out.push({
1373
+ value,
1374
+ source: { bindingType: 'test_pointer_delta', sourceId: binding.sourceId },
1375
+ });
1376
+ }
1377
+ else if (binding.type === 'mouse_move') {
1378
+ out.push({
1379
+ value: { x: this.mouseDeltaX, y: this.mouseDeltaY },
1380
+ source: { bindingType: 'mouse_move' },
1381
+ });
1382
+ }
1383
+ }
1384
+ return out;
1385
+ }
1386
+ computePointerDelta(actionName) {
1387
+ this.assertValueType(actionName, 'pointerDelta', 'getPointerDelta');
1388
+ let sum = { x: 0, y: 0 };
1389
+ let bestSource = null;
1390
+ let bestMag = 0;
1391
+ for (const c of this.collectPointerDeltaContributions(actionName)) {
1392
+ sum = { x: sum.x + c.value.x, y: sum.y + c.value.y };
1393
+ const mag = Math.hypot(c.value.x, c.value.y);
1394
+ if (mag > bestMag) {
1395
+ bestMag = mag;
1396
+ bestSource = c.source;
1397
+ }
1398
+ }
1399
+ if (sum.x === 0 && sum.y === 0)
1400
+ return { value: sum, source: null };
1401
+ return { value: sum, source: bestSource };
1402
+ }
1403
+ /** Read a `'pointerDelta'`-valueType action's this-frame movement: sum of
1404
+ * contributing bindings' deltas (combine rule — see the class doc
1405
+ * comment). Throws if the action is declared a different valueType. */
1406
+ getPointerDelta(actionName) {
1407
+ return this.computePointerDelta(actionName).value;
1408
+ }
1409
+ /** Device/source metadata for {@link getPointerDelta}. */
1410
+ getPointerDeltaSource(actionName) {
1411
+ return this.computePointerDelta(actionName).source;
1412
+ }
1413
+ /** Every `pointerPosition`-relevant binding's contribution, each tagged
1414
+ * with the injection-order sequence number used to break ties (last-
1415
+ * write-wins) — today only `test_pointer_position` (F1's injected-test-
1416
+ * input source). */
1417
+ collectPointerPositionContributions(actionName) {
1418
+ if (!this.inputActive)
1419
+ return [];
1420
+ const bindings = this.actions.get(actionName);
1421
+ if (!bindings)
1422
+ return [];
1423
+ const out = [];
1424
+ for (const binding of bindings) {
1425
+ if (binding.type === 'test_pointer_position') {
1426
+ const entry = this.testPointerPositionValues.get(binding.sourceId);
1427
+ if (entry) {
1428
+ out.push({
1429
+ value: entry.value,
1430
+ seq: entry.seq,
1431
+ source: { bindingType: 'test_pointer_position', sourceId: binding.sourceId },
1432
+ });
1433
+ }
1434
+ }
1435
+ }
1436
+ return out;
1437
+ }
1438
+ computePointerPosition(actionName) {
1439
+ this.assertValueType(actionName, 'pointerPosition', 'getPointerPosition');
1440
+ const contributions = this.collectPointerPositionContributions(actionName);
1441
+ if (contributions.length === 0)
1442
+ return { value: { x: 0, y: 0 }, source: null };
1443
+ let best = contributions[0];
1444
+ for (const c of contributions) {
1445
+ if (c.seq > best.seq)
1446
+ best = c;
1447
+ }
1448
+ return { value: best.value, source: best.source };
1449
+ }
1450
+ /** Read a `'pointerPosition'`-valueType action's current absolute position:
1451
+ * last-write-wins across contributing bindings (combine rule — see the
1452
+ * class doc comment; position isn't additive, so it is never summed).
1453
+ * Throws if the action is declared a different valueType. */
1454
+ getPointerPosition(actionName) {
1455
+ return this.computePointerPosition(actionName).value;
1456
+ }
1457
+ /** Device/source metadata for {@link getPointerPosition} — the most
1458
+ * recently-written contributing source. */
1459
+ getPointerPositionSource(actionName) {
1460
+ return this.computePointerPosition(actionName).source;
1461
+ }
1462
+ /** Generic typed read (F1): dispatches to the matching typed getter based
1463
+ * on `expectedType`, returning `ActionValueOf<T>` — a caller with a
1464
+ * statically-known action-value-type map gets a fully-inferred, non-`any`
1465
+ * return type. Throws the same mismatch error as the dedicated getters if
1466
+ * the action's declared valueType disagrees with `expectedType`. */
1467
+ readAction(actionName, expectedType) {
1468
+ switch (expectedType) {
1469
+ case 'digital':
1470
+ return this.isPressed(actionName);
1471
+ case 'scalar':
1472
+ return this.getScalar(actionName);
1473
+ case 'vector2':
1474
+ return this.getVector2(actionName);
1475
+ case 'pointerDelta':
1476
+ return this.getPointerDelta(actionName);
1477
+ case 'pointerPosition':
1478
+ return this.getPointerPosition(actionName);
1479
+ default:
1480
+ throw new Error(`InputManager.readAction: unknown value type "${expectedType}"`);
1481
+ }
1482
+ }
1483
+ /** Inject a synthetic scalar value for a named test source (F1's injected-
1484
+ * test-input hook — also the shape of F2's "injected test input" backend).
1485
+ * Bind an action to `{ type: 'test_axis', sourceId }` (`valueType:
1486
+ * 'scalar'`) to read it back via {@link getScalar}. The value PERSISTS
1487
+ * across frames (like a real analog stick held in position) until changed
1488
+ * or cleared via {@link clearAxis}. */
1489
+ injectAxis(sourceId, value) {
1490
+ this.testAxisValues.set(sourceId, value);
1491
+ }
1492
+ /** Clear an injected scalar source (e.g. simulating an at-rest/disconnected
1493
+ * device). */
1494
+ clearAxis(sourceId) {
1495
+ this.testAxisValues.delete(sourceId);
1496
+ }
1497
+ /** Inject a synthetic {x,y} value for a named test source. Bind an action
1498
+ * to `{ type: 'test_vector2', sourceId }` (`valueType: 'vector2'`) to read
1499
+ * it back via {@link getVector2}. Persists across frames until changed or
1500
+ * cleared via {@link clearVector2}. */
1501
+ injectVector2(sourceId, value) {
1502
+ this.testVector2Values.set(sourceId, value);
1503
+ }
1504
+ /** Clear an injected Vector2 source. */
1505
+ clearVector2(sourceId) {
1506
+ this.testVector2Values.delete(sourceId);
1507
+ }
1508
+ /** Accumulate a synthetic pointer delta for a named test source — mirrors
1509
+ * real mouse-move delta accumulation (`onMouseMove` above): multiple calls
1510
+ * within the same frame sum, and the accumulator is cleared in
1511
+ * {@link endFrame}. Bind an action to `{ type: 'test_pointer_delta',
1512
+ * sourceId }` (`valueType: 'pointerDelta'`) to read it back via
1513
+ * {@link getPointerDelta}. */
1514
+ injectPointerDelta(sourceId, delta) {
1515
+ const prev = this.testPointerDeltaAccum.get(sourceId) ?? { x: 0, y: 0 };
1516
+ this.testPointerDeltaAccum.set(sourceId, { x: prev.x + delta.x, y: prev.y + delta.y });
1517
+ }
1518
+ /** Set a synthetic absolute pointer position for a named test source.
1519
+ * Persists (last-write-wins across contributing sources on read — see the
1520
+ * pointerPosition combine rule) until changed. Bind an action to `{ type:
1521
+ * 'test_pointer_position', sourceId }` (`valueType: 'pointerPosition'`) to
1522
+ * read it back via {@link getPointerPosition}. */
1523
+ injectPointerPosition(sourceId, value) {
1524
+ this.testPointerPositionValues.set(sourceId, { value, seq: ++this.pointerPositionSeq });
1525
+ }
1526
+ /** Whether input capture is currently enabled (see {@link setEnabled}). */
1527
+ isEnabled() {
1528
+ return this.enabled;
1529
+ }
1530
+ /**
1531
+ * Enable/disable input capture. The editor host disables the running game's
1532
+ * input while its viewport isn't focused so keystrokes don't leak in from
1533
+ * the editor. Disabling clears all held/transient keyboard/mouse/touch-button
1534
+ * state (via {@link flushHeldState}) so nothing sticks (e.g. a held movement
1535
+ * key when you switch back to the Scene tab mid-flight) — gamepad state
1536
+ * doesn't need clearing here since `poll()` itself stops reading it while
1537
+ * disabled (see poll()'s doc comment).
1538
+ */
1539
+ setEnabled(enabled) {
1540
+ if (this.enabled === enabled)
1541
+ return;
1542
+ this.enabled = enabled;
1543
+ if (!enabled)
1544
+ this.flushHeldState();
1545
+ }
1546
+ /** Whether the window/tab is currently focused (F2, spec §12 "focus
1547
+ * gating") — `false` while blurred (real `blur`/`focus` events; see the
1548
+ * constructor). Distinct from {@link isEnabled}, which is the editor's
1549
+ * explicit play-mode gate. */
1550
+ isFocused() {
1551
+ return this.focused;
1552
+ }
1553
+ /** Whether the pointer is currently locked to {@link requestPointerLock}'s
1554
+ * element (F2, spec §12 "pointer lock") — tracked via the real
1555
+ * `pointerlockchange` event. */
1556
+ isPointerLocked() {
1557
+ return this.pointerLocked;
1558
+ }
1559
+ /** Device identity for a connected gamepad slot (F2, spec §12 "expose
1560
+ * device identity" + "prefer the standard mapping"), or `null` if nothing
1561
+ * is connected at `index` (including while input is disabled/unfocused,
1562
+ * since `poll()` empties `this.gamepads` then). `mapping` is the Gamepad
1563
+ * API's own `'standard'`/`''` value — bindings author button/axis indices
1564
+ * assuming the W3C Standard Gamepad layout, so a non-`'standard'` mapping
1565
+ * means those indices may not correspond as documented. */
1566
+ getGamepadInfo(index) {
1567
+ const gp = this.gamepads[index];
1568
+ if (!gp)
1569
+ return null;
1570
+ return { index, id: gp.id, mapping: gp.mapping, connected: gp.connected };
1571
+ }
1572
+ /** Get mouse movement delta this frame */
1573
+ getMouseDelta() {
1574
+ return { x: this.mouseDeltaX, y: this.mouseDeltaY };
1575
+ }
1576
+ /**
1577
+ * F4 (spec §12 "Schema and Examples" — the F3 prompt-switching gap): which
1578
+ * device family most recently produced real input, or `null` before any
1579
+ * input has arrived. A prompt UI polls this (or lets {@link getPrompt}
1580
+ * consult it automatically by omitting `device`) to switch its displayed
1581
+ * label as the player switches controllers — e.g. showing `'Space'` while
1582
+ * they're on keyboard, then `'A'` the moment they touch a gamepad.
1583
+ */
1584
+ getLastActiveDevice() {
1585
+ return this.lastActiveDevice;
1586
+ }
1587
+ // ==========================================================================
1588
+ // F3 — rebinding: list/replace/add/remove/reset/persist. See the class doc
1589
+ // comment above for the full design note.
1590
+ // ==========================================================================
1591
+ /** The current bindings for `actionName` (F3 AC "listed") — a defensive
1592
+ * deep clone, so mutating the returned array/objects never affects the
1593
+ * live binding list. `[]` for an unknown/never-registered action. */
1594
+ getBindings(actionName) {
1595
+ const bindings = this.actions.get(actionName);
1596
+ return bindings ? structuredClone(bindings) : [];
1597
+ }
1598
+ /** Wholesale-replace `actionName`'s bindings array (F3 AC "replaced"). Does
1599
+ * NOT touch the reset-to-defaults snapshot — see `resetBindings`. A no-op
1600
+ * target for an action that was never registered is allowed (it simply
1601
+ * registers one with `valueType: 'digital'`, matching `registerAction`'s
1602
+ * own default) since a rebinding UI operates on actions it already knows
1603
+ * about, but shouldn't have to special-case "brand new action" separately. */
1604
+ setBindings(actionName, bindings) {
1605
+ if (!this.actionValueTypes.has(actionName))
1606
+ this.actionValueTypes.set(actionName, 'digital');
1607
+ this.actions.set(actionName, structuredClone(bindings));
1608
+ }
1609
+ /** Append one binding to `actionName` (F3 AC "added"). */
1610
+ addBinding(actionName, binding) {
1611
+ const bindings = this.actions.get(actionName) ?? [];
1612
+ this.actions.set(actionName, [...bindings, structuredClone(binding)]);
1613
+ if (!this.actionValueTypes.has(actionName))
1614
+ this.actionValueTypes.set(actionName, 'digital');
1615
+ }
1616
+ /** Remove the binding at `index` from `actionName` (F3 AC "removed"). A
1617
+ * no-op if the action is unknown or `index` is out of range (rather than
1618
+ * throwing) — mirrors every other getter's "unknown action is inert"
1619
+ * convention, so a UI doesn't need a separate existence check first. */
1620
+ removeBinding(actionName, index) {
1621
+ const bindings = this.actions.get(actionName);
1622
+ if (!bindings || index < 0 || index >= bindings.length)
1623
+ return;
1624
+ this.actions.set(actionName, [...bindings.slice(0, index), ...bindings.slice(index + 1)]);
1625
+ }
1626
+ /** Replace a single binding slot at `index` on `actionName` — the shape a
1627
+ * rebinding UI actually wants ("rebind THIS control"), built on
1628
+ * `getBindings`/`setBindings`. A no-op if the action is unknown or `index`
1629
+ * is out of range. */
1630
+ replaceBinding(actionName, index, binding) {
1631
+ const bindings = this.actions.get(actionName);
1632
+ if (!bindings || index < 0 || index >= bindings.length)
1633
+ return;
1634
+ const next = bindings.slice();
1635
+ next[index] = structuredClone(binding);
1636
+ this.actions.set(actionName, next);
1637
+ }
1638
+ /** Restore `actionName`'s bindings to the snapshot taken at
1639
+ * `registerAction`/`loadMap`/`loadMapObject` time (F3 AC "reset"). A no-op
1640
+ * for an action with no snapshot (never registered/loaded — there is no
1641
+ * "default" to reset to). */
1642
+ resetBindings(actionName) {
1643
+ const defaults = this.defaultBindings.get(actionName);
1644
+ if (!defaults)
1645
+ return;
1646
+ this.actions.set(actionName, structuredClone(defaults));
1647
+ }
1648
+ /** Reset every action that has a snapshot back to its registered/loaded
1649
+ * defaults. Convenience batch form of `resetBindings`. */
1650
+ resetAllBindings() {
1651
+ for (const actionName of this.defaultBindings.keys())
1652
+ this.resetBindings(actionName);
1653
+ }
1654
+ /**
1655
+ * Whether `a` and `b` are the SAME physical input (F3's structural-conflict
1656
+ * identity check — see `findConflicts`). Deliberately narrower than deep
1657
+ * equality: `deadzone` never participates (two bindings on the same key
1658
+ * with different deadzones are still the same physical control), and a
1659
+ * `gamepad_axis`'s `direction` DOES participate — opposite directions of one
1660
+ * physical axis (e.g. "accelerate" on positive, "brake" on negative) are a
1661
+ * legitimate, non-conflicting pair, not a collision.
1662
+ */
1663
+ static bindingsCollide(a, b) {
1664
+ if (a.type !== b.type)
1665
+ return false;
1666
+ switch (a.type) {
1667
+ case 'key':
1668
+ return a.code === b.code;
1669
+ case 'mouse_button':
1670
+ return a.button === b.button;
1671
+ case 'mouse_move':
1672
+ return true; // there is only one physical mouse-move source
1673
+ case 'gamepad_button':
1674
+ return a.button === b.button;
1675
+ case 'gamepad_axis': {
1676
+ const other = b;
1677
+ return a.axis === other.axis && a.direction === other.direction;
1678
+ }
1679
+ case 'gamepad_axis_pair': {
1680
+ const other = b;
1681
+ return a.xAxis === other.xAxis && a.yAxis === other.yAxis;
1682
+ }
1683
+ case 'touch_button':
1684
+ case 'touch_stick':
1685
+ case 'test_axis':
1686
+ case 'test_vector2':
1687
+ case 'test_pointer_delta':
1688
+ case 'test_pointer_position':
1689
+ return a.sourceId === b.sourceId;
1690
+ default:
1691
+ return false;
1692
+ }
1693
+ }
1694
+ /**
1695
+ * Every EXISTING binding, on every OTHER registered action, that is
1696
+ * structurally the same physical input as `proposed` (F3 AC "conflicts are
1697
+ * detected and returned structurally") — never throws, always a plain
1698
+ * (possibly empty) array a rebinding UI inspects before committing a
1699
+ * rebind. `excludeActionName` is normally the action being rebound itself
1700
+ * (so an action isn't reported as conflicting with its own current
1701
+ * binding when re-proposing an unchanged value).
1702
+ */
1703
+ findConflicts(proposed, excludeActionName) {
1704
+ const conflicts = [];
1705
+ for (const [actionName, bindings] of this.actions) {
1706
+ if (actionName === excludeActionName)
1707
+ continue;
1708
+ bindings.forEach((binding, bindingIndex) => {
1709
+ if (InputManager.bindingsCollide(proposed, binding)) {
1710
+ conflicts.push({ actionName, bindingIndex, binding: structuredClone(binding) });
1711
+ }
1712
+ });
1713
+ }
1714
+ return conflicts;
1715
+ }
1716
+ /**
1717
+ * Serialize every registered/loaded action back into the `.inputmap.json`
1718
+ * document shape (F3 AC "persisted") — the exact `InputMapFile` shape
1719
+ * `loadMap`/`loadMapObject` read, so `manager.loadMapObject(manager.toInputMapFile())`
1720
+ * on a fresh instance reproduces the same live bindings. `version` is
1721
+ * carried forward from the last loaded map when known, else `1` (a
1722
+ * manager built purely via `registerAction` calls, never `loadMap`, has no
1723
+ * file-format version to preserve).
1724
+ */
1725
+ toInputMapFile() {
1726
+ const actions = {};
1727
+ for (const [name, bindings] of this.actions) {
1728
+ actions[name] = {
1729
+ valueType: this.actionValueTypes.get(name) ?? 'digital',
1730
+ bindings: structuredClone(bindings),
1731
+ };
1732
+ }
1733
+ return { version: this.loadedMapVersion, actions };
1734
+ }
1735
+ /**
1736
+ * Resolve a display prompt (F3 AC: labels/icons like `'Space'`, `'A'`, or a
1737
+ * touch control's name) for whichever of `actionName`'s bindings belongs to
1738
+ * the requested `device` family. `null` when the action has no binding for
1739
+ * that device (including an unknown action). `gamepadIndex` (default 0)
1740
+ * selects which connected pad's `mapping`/connected state to consult for a
1741
+ * `gamepad_*` binding — see `getGamepadInfo`.
1742
+ *
1743
+ * F4 — `device` is now OPTIONAL: omit it (or pass `undefined`) to resolve
1744
+ * against {@link getLastActiveDevice} instead (falling back to `'keyboard'`
1745
+ * before any input has arrived), so a prompt UI that wants "show whatever
1746
+ * the player is actually holding right now" doesn't have to track the
1747
+ * active device itself — it can just call `getPrompt(actionName)` every
1748
+ * frame and the label switches on its own as the player changes controllers.
1749
+ * Passing an explicit `device` (as every pre-F4 caller does) is unaffected.
1750
+ */
1751
+ getPrompt(actionName, device, gamepadIndex = 0) {
1752
+ const resolvedDevice = device ?? this.lastActiveDevice ?? 'keyboard';
1753
+ const bindings = this.actions.get(actionName);
1754
+ if (!bindings)
1755
+ return null;
1756
+ const binding = bindings.find((b) => bindingDeviceFamily(b.type) === resolvedDevice);
1757
+ if (!binding)
1758
+ return null;
1759
+ switch (binding.type) {
1760
+ case 'key':
1761
+ return {
1762
+ device: 'keyboard',
1763
+ bindingType: 'key',
1764
+ label: keyLabel(binding.code),
1765
+ icon: keyLabel(binding.code),
1766
+ };
1767
+ case 'mouse_button':
1768
+ return {
1769
+ device: 'mouse',
1770
+ bindingType: 'mouse_button',
1771
+ label: mouseButtonLabel(binding.button),
1772
+ icon: 'mouse',
1773
+ };
1774
+ case 'mouse_move':
1775
+ return { device: 'mouse', bindingType: 'mouse_move', label: 'Mouse', icon: 'mouse' };
1776
+ case 'gamepad_button': {
1777
+ const info = this.getGamepadInfo(gamepadIndex);
1778
+ if (!info?.connected) {
1779
+ return {
1780
+ device: 'gamepad',
1781
+ bindingType: 'gamepad_button',
1782
+ label: 'Gamepad Disconnected',
1783
+ icon: 'gamepad-off',
1784
+ };
1785
+ }
1786
+ const label = info.mapping === 'standard'
1787
+ ? (STANDARD_GAMEPAD_BUTTON_LABELS[binding.button] ?? `Button ${binding.button}`)
1788
+ : `Button ${binding.button}`;
1789
+ return { device: 'gamepad', bindingType: 'gamepad_button', label, icon: label };
1790
+ }
1791
+ case 'gamepad_axis': {
1792
+ const info = this.getGamepadInfo(gamepadIndex);
1793
+ if (!info?.connected) {
1794
+ return {
1795
+ device: 'gamepad',
1796
+ bindingType: 'gamepad_axis',
1797
+ label: 'Gamepad Disconnected',
1798
+ icon: 'gamepad-off',
1799
+ };
1800
+ }
1801
+ return {
1802
+ device: 'gamepad',
1803
+ bindingType: 'gamepad_axis',
1804
+ label: gamepadAxisLabel(binding.axis),
1805
+ icon: 'gamepad-stick',
1806
+ };
1807
+ }
1808
+ case 'gamepad_axis_pair': {
1809
+ const info = this.getGamepadInfo(gamepadIndex);
1810
+ if (!info?.connected) {
1811
+ return {
1812
+ device: 'gamepad',
1813
+ bindingType: 'gamepad_axis_pair',
1814
+ label: 'Gamepad Disconnected',
1815
+ icon: 'gamepad-off',
1816
+ };
1817
+ }
1818
+ return {
1819
+ device: 'gamepad',
1820
+ bindingType: 'gamepad_axis_pair',
1821
+ label: gamepadAxisPairLabel(binding.xAxis, binding.yAxis),
1822
+ icon: 'gamepad-stick',
1823
+ };
1824
+ }
1825
+ case 'touch_button':
1826
+ return {
1827
+ device: 'touch',
1828
+ bindingType: 'touch_button',
1829
+ label: binding.sourceId,
1830
+ icon: 'touch',
1831
+ };
1832
+ case 'touch_stick':
1833
+ return {
1834
+ device: 'touch',
1835
+ bindingType: 'touch_stick',
1836
+ label: binding.sourceId,
1837
+ icon: 'touch',
1838
+ };
1839
+ default:
1840
+ return null;
1841
+ }
1842
+ }
1843
+ /** Call at end of frame to clear per-frame state */
1844
+ endFrame() {
1845
+ this.keysJustDown.clear();
1846
+ this.keysJustUp.clear();
1847
+ this.mouseButtonsJustDown.clear();
1848
+ this.mouseButtonsJustUp.clear();
1849
+ // Carry this frame's gamepad pressed set forward as next frame's baseline,
1850
+ // then clear the per-frame edge sets.
1851
+ this.gamepadButtonsPrev = this.gamepadButtonsDown;
1852
+ this.gamepadButtonsJustDown.clear();
1853
+ this.gamepadButtonsJustUp.clear();
1854
+ // Carry this frame's raw axis snapshot forward as next frame's baseline
1855
+ // for gamepad_axis edge detection (isJustPressed/isJustReleased).
1856
+ this.gamepadAxesPrev = this.gamepadAxesCurrent;
1857
+ this.mouseDeltaX = 0;
1858
+ this.mouseDeltaY = 0;
1859
+ // F1 — pointerDelta is a per-frame accumulator, same shape as
1860
+ // mouseDeltaX/Y above; axis/vector2/pointerPosition are level values and
1861
+ // deliberately NOT reset here (they persist until changed/cleared).
1862
+ this.testPointerDeltaAccum.clear();
1863
+ // F2 — touch-button edges, same shape as the mouse-button edges above.
1864
+ this.touchButtonsJustDown.clear();
1865
+ this.touchButtonsJustUp.clear();
1866
+ // Task 1.4 — a promoted tap is just-pressed for exactly one poll()/
1867
+ // endFrame() bracket.
1868
+ this.virtualDigitalTapActive.clear();
1869
+ // Mirrors the line above for the release edge a direct
1870
+ // `setVirtualAction(action, false)`/`clearVirtualActions()` manufactures
1871
+ // (see `virtualDigitalJustReleased`'s doc comment) — just-released for
1872
+ // exactly one poll()/endFrame() bracket too.
1873
+ this.virtualDigitalJustReleased.clear();
1874
+ }
1875
+ /** Inject synthetic key state from touch controls */
1876
+ setVirtualKey(code, pressed) {
1877
+ if (pressed) {
1878
+ if (!this.keysDown.has(code))
1879
+ this.keysJustDown.add(code);
1880
+ this.keysDown.add(code);
1881
+ }
1882
+ else {
1883
+ if (this.keysDown.has(code))
1884
+ this.keysJustUp.add(code);
1885
+ this.keysDown.delete(code);
1886
+ }
1887
+ }
1888
+ /** Set virtual look stick position (-1..1). Injected as mouse delta during poll(). */
1889
+ setLookStick(x, y) {
1890
+ this.lookStickX = x;
1891
+ this.lookStickY = y;
1892
+ }
1893
+ /** Inject synthetic mouse delta (e.g. from touch controls) */
1894
+ addMouseDelta(dx, dy) {
1895
+ this.mouseDeltaX += dx;
1896
+ this.mouseDeltaY += dy;
1897
+ }
1898
+ /**
1899
+ * F2 (spec §12 "Complete Device Backends") — the touch/virtual-control
1900
+ * digital backend. Set a named virtual button's (`sourceId` — a zone/knob
1901
+ * id the touch UI chooses) pressed state; edge-tracked exactly like a real
1902
+ * mouse button (`onMouseDown`/`onMouseUp` above) so `isJustPressed`/
1903
+ * `isJustReleased` work for `{ type: 'touch_button', sourceId }` bindings.
1904
+ * This is the injectable entry point a real on-screen button's own
1905
+ * touchstart/touchend handler would call — that DOM wiring is a thin
1906
+ * adapter at the edge (browser-verified separately); this method is the
1907
+ * MAPPING logic, unit-tested headlessly with no DOM.
1908
+ */
1909
+ setTouchButton(sourceId, pressed) {
1910
+ if (!this.inputActive)
1911
+ return;
1912
+ if (pressed) {
1913
+ if (!this.touchButtonsDown.has(sourceId))
1914
+ this.touchButtonsJustDown.add(sourceId);
1915
+ this.touchButtonsDown.add(sourceId);
1916
+ this.lastActiveDevice = 'touch'; // F4
1917
+ }
1918
+ else {
1919
+ if (this.touchButtonsDown.has(sourceId))
1920
+ this.touchButtonsJustUp.add(sourceId);
1921
+ this.touchButtonsDown.delete(sourceId);
1922
+ }
1923
+ }
1924
+ /**
1925
+ * F2 — the touch/virtual-control analog backend. Set a named virtual
1926
+ * stick's (`sourceId`) raw `{x,y}` position (e.g. -1..1 per axis, like a
1927
+ * gamepad stick); read back via `getVector2` on a `{ type: 'touch_stick',
1928
+ * sourceId }` binding, deadzone-rescaled the same way a gamepad stick is.
1929
+ * Persists across frames (a level value, like a real analog stick held in
1930
+ * position) until changed or cleared via {@link clearTouchStick}.
1931
+ */
1932
+ setTouchStick(sourceId, value) {
1933
+ this.touchStickValues.set(sourceId, value);
1934
+ // F4 — mirrors the gamepad-axis heuristic in poll() (see `isStickActive`).
1935
+ if (InputManager.isStickActive(value))
1936
+ this.lastActiveDevice = 'touch';
1937
+ }
1938
+ /** Clear a virtual stick's value (e.g. simulating the touch point lifting —
1939
+ * the knob returns to center). */
1940
+ clearTouchStick(sourceId) {
1941
+ this.touchStickValues.delete(sourceId);
1942
+ }
1943
+ // ==========================================================================
1944
+ // Task 1.4 — action-level virtual input for a synthetic player. Promoted from
1945
+ // hollowstone's proven `VirtualInput` (`bot/virtual-input.ts`): a bot drives
1946
+ // NAMED ACTIONS (not raw devices), and its contributions join action
1947
+ // resolution at exactly the same points binding contributions do (see
1948
+ // isPressed/isJustPressed and collectScalarContributions/
1949
+ // collectVector2Contributions above). #144 split the gates: virtual input
1950
+ // passes `machineInputActive` (the editor's `enabled` flag only), while
1951
+ // human input keeps the full `inputActive` (enabled AND focused) gate — a
1952
+ // synthetic player must keep playing the shared editor tab while the
1953
+ // human's focus is elsewhere. Unlike every typed getter above (which
1954
+ // treats an unknown action as inert), these THROW on an unknown name — a
1955
+ // synthetic-player caller needs a loud signal that the action it's driving
1956
+ // doesn't exist, not a silently-ignored actuation.
1957
+ // ==========================================================================
1958
+ /** Existence check shared by `setVirtualAction`/`tapVirtualAction` — throws
1959
+ * `InputActionError` (`code: 'INPUT_ACTION_NOT_FOUND'`, `data.registered`
1960
+ * = every declared action name) for a name that was never
1961
+ * `registerAction`/`loadMap`-ed. */
1962
+ assertActionExists(actionName, method) {
1963
+ if (!this.actionValueTypes.has(actionName)) {
1964
+ throw new InputActionError(actionName, method, this.actionNames());
1965
+ }
1966
+ }
1967
+ /** Which declared `ActionValueType` a `setVirtualAction` value shape
1968
+ * corresponds to — the type-safety check mirrors every typed getter's
1969
+ * `assertValueType` (F1). `pointerDelta`/`pointerPosition` actions aren't
1970
+ * drivable through `setVirtualAction` (no boolean/number/Vector2 call
1971
+ * shape maps to them) — use `injectPointerDelta`/`injectPointerPosition`. */
1972
+ static virtualValueCategory(value) {
1973
+ if (typeof value === 'boolean')
1974
+ return 'digital';
1975
+ if (typeof value === 'number')
1976
+ return 'scalar';
1977
+ return 'vector2';
1978
+ }
1979
+ /**
1980
+ * Set a virtual value for `action`, OR'd/summed into the same action reads
1981
+ * humans drive (see the section doc comment above). A `boolean` holds a
1982
+ * digital action pressed until set `false`/cleared; a `number` or `{x,y}`
1983
+ * is a level value combined via the action's own scalar max-magnitude /
1984
+ * vector2 sum-then-clamp rule.
1985
+ *
1986
+ * A digital `false`→`true` transition manufactures a genuine `isJustPressed`
1987
+ * edge, exactly one real key-down does (pulse-runner friction #4 —
1988
+ * previously this write-half only ever held the action pressed with NO
1989
+ * edge at all; every edge-triggered ability driven through this direct
1990
+ * path was unprovable). Re-setting `true` while already held (auto-repeat)
1991
+ * does NOT re-fire it — see {@link applyVirtualActionValue}. The mirror
1992
+ * `true`→`false` transition manufactures an `isJustReleased` edge the same
1993
+ * way a real key-up does.
1994
+ *
1995
+ * Throws `InputActionError` for an unregistered `action`, and the same
1996
+ * valueType-mismatch error every typed getter throws (`assertValueType`)
1997
+ * when `value`'s shape doesn't match the action's declared `valueType`.
1998
+ *
1999
+ * Gated (`setEnabled(false)` — play stopped or editor-gated; #144: window
2000
+ * focus no longer gates machine input): writes NOTHING — matching
2001
+ * `setTouchButton`'s write-gate precedent above — and returns
2002
+ * `{delivered: false, reason}` rather than a silent no-op, so a probe/bot
2003
+ * never mistakes a swallowed actuation for a delivered one.
2004
+ */
2005
+ setVirtualAction(action, value) {
2006
+ this.assertActionExists(action, 'setVirtualAction');
2007
+ const expected = InputManager.virtualValueCategory(value);
2008
+ this.assertValueType(action, expected, 'setVirtualAction');
2009
+ if (!this.machineInputActive) {
2010
+ return { delivered: false, reason: 'input-gated (input disabled by the editor)' };
2011
+ }
2012
+ this.applyVirtualActionValue(action, value);
2013
+ return { delivered: true };
2014
+ }
2015
+ /**
2016
+ * The write half of {@link setVirtualAction} — extracted so D15/T-D15.5's
2017
+ * `scheduleActionAtTick` can apply a non-boolean (scalar/vector2) queued
2018
+ * actuation through the exact same code path (no gate check here: the two
2019
+ * callers gate differently — `setVirtualAction` above checks
2020
+ * `inputActive` before calling this; `applyScheduledActionsForTick` is
2021
+ * only ever reached from inside `poll()` AFTER its own gate check has
2022
+ * already returned early on a gated tick). `applyScheduledActionsForTick`
2023
+ * still handles digital `true` itself rather than calling here (its
2024
+ * one-tick edge must land EXACTLY at the scheduled tick — see its own doc
2025
+ * comment) — this method's digital branch is `setVirtualAction`'s direct
2026
+ * path, called at an arbitrary point relative to the poll()/endFrame()
2027
+ * bracket.
2028
+ *
2029
+ * pulse-runner friction #4 — the digital branch used to be a bare held-flag
2030
+ * write with no manufactured edge at all (the comment that used to sit
2031
+ * here read: "A digital value is handled by `applyScheduledActionsForTick`
2032
+ * itself (it needs the extra just-pressed edge a plain held-value write
2033
+ * doesn't produce)" — i.e. the edge fix shipped ONLY for the scheduled
2034
+ * path, never for this one, which is exactly the gap a blind dogfood run
2035
+ * hit: `setVirtualAction('jump', true)` held the action down but
2036
+ * `isJustPressed('jump')` never fired). Fixed here by reusing
2037
+ * `tapVirtualAction`'s exact one-tick-pulse queue mechanism for this
2038
+ * DIRECT case, specifically because this method's caller can land at any
2039
+ * point relative to `poll()`: writing `virtualDigitalTapActive` directly
2040
+ * here (as the scheduled path safely does, from inside `poll()` itself)
2041
+ * would risk being silently wiped by `poll()`'s own unconditional
2042
+ * `virtualDigitalTapActive = virtualDigitalTapQueued` reassignment,
2043
+ * depending on timing. Queueing side-steps that hazard by construction —
2044
+ * the same reason `tapVirtualAction` queues instead of writing directly. A
2045
+ * redundant `true` while already held (`virtualDigitalHeld` already has
2046
+ * `action`) does not queue again, matching a real key's auto-repeat never
2047
+ * re-firing `isJustPressed`. The `false` branch mirrors real `onKeyUp`
2048
+ * instead (immediate write, no queue needed — nothing in `poll()`
2049
+ * reassigns `virtualDigitalJustReleased`), and only fires when the action
2050
+ * was actually held (no released→released re-fire).
2051
+ */
2052
+ applyVirtualActionValue(action, value) {
2053
+ switch (InputManager.virtualValueCategory(value)) {
2054
+ case 'digital':
2055
+ if (value) {
2056
+ if (!this.virtualDigitalHeld.has(action))
2057
+ this.virtualDigitalTapQueued.add(action);
2058
+ this.virtualDigitalHeld.add(action);
2059
+ }
2060
+ else {
2061
+ if (this.virtualDigitalHeld.has(action))
2062
+ this.virtualDigitalJustReleased.add(action);
2063
+ this.virtualDigitalHeld.delete(action);
2064
+ }
2065
+ break;
2066
+ case 'scalar':
2067
+ this.virtualScalarValues.set(action, value);
2068
+ break;
2069
+ default:
2070
+ this.virtualVector2Values.set(action, value);
2071
+ break;
2072
+ }
2073
+ }
2074
+ /**
2075
+ * One-frame press of a `'digital'` action (Task 1.4): queues `action` so it
2076
+ * reads `isJustPressed`/`isPressed` true for EXACTLY the next `poll()`'s
2077
+ * frame — promoted to the "active" set at the top of `poll()`, cleared in
2078
+ * `endFrame()` alongside every other just-pressed edge set (see both
2079
+ * above). Hollowstone's `queued`/`beginFrame` tap contract, ported onto
2080
+ * this engine's existing fixed-step `poll()`/`endFrame()` bracket instead
2081
+ * of a bespoke `beginFrame()` hook.
2082
+ *
2083
+ * Throws the same errors as {@link setVirtualAction} (unknown action;
2084
+ * non-digital valueType). A gated tap does NOT queue — it must not fire on
2085
+ * a later frame once input becomes active again — and returns
2086
+ * `{delivered: false, reason}`.
2087
+ */
2088
+ tapVirtualAction(action) {
2089
+ this.assertActionExists(action, 'tapVirtualAction');
2090
+ this.assertValueType(action, 'digital', 'tapVirtualAction');
2091
+ if (!this.machineInputActive) {
2092
+ return { delivered: false, reason: 'input-gated (input disabled by the editor)' };
2093
+ }
2094
+ this.virtualDigitalTapQueued.add(action);
2095
+ return { delivered: true };
2096
+ }
2097
+ /** Clear all virtual-action state — held digitals, queued/active taps, and
2098
+ * scalar/vector2 values. `flushHeldState()` (the same flush
2099
+ * `setEnabled(false)`/real blur apply to held keys/mouse/touch buttons)
2100
+ * shares the underlying wipe, so a bot's held action never survives input
2101
+ * being suspended — but only THIS public entry point (a deliberate "let
2102
+ * go", the mirror of `setVirtualAction(action, false)` below) manufactures
2103
+ * an `isJustReleased` edge for whatever was held; the suspend path stays
2104
+ * silent (see `flushHeldState`'s own doc comment). */
2105
+ clearVirtualActions() {
2106
+ this.clearVirtualActionState({ manufactureReleaseEdge: true });
2107
+ }
2108
+ /**
2109
+ * D15/T-D15.5 — schedule a virtual actuation for exactly `tick`: applied
2110
+ * at the START of that tick's `poll()` (composing with `runTicks` — a
2111
+ * schedule for tick 500 fires exactly once the sim has been driven through
2112
+ * tick 500, regardless of burst size). A digital `true` produces a genuine
2113
+ * `isJustPressed` edge exactly at the target tick (not merely a held value
2114
+ * — see `applyScheduledActionsForTick`).
2115
+ *
2116
+ * Throws `InputActionError` for an unregistered `action` and the same
2117
+ * valueType-mismatch error every typed getter throws (`assertValueType`) —
2118
+ * both checked EAGERLY, at schedule time, not deferred to the target tick.
2119
+ * Throws `InputTickError` (`code: 'TICK_ALREADY_PASSED'`) when `tick` is
2120
+ * strictly less than the tick `poll()` will service NEXT — scheduling only
2121
+ * ever reaches the current or a future tick. A tick whose input phase
2122
+ * never runs (this world paused/frozen at that point, or a multi-tick gap
2123
+ * — see `poll()`) drops its scheduled entries rather than replaying them
2124
+ * late — each drop emits one `'input.schedule.dropped'` debug event
2125
+ * (`{tick, action}`) via {@link setDebugEmit}'s sink, if one is wired.
2126
+ */
2127
+ scheduleActionAtTick(tick, action, value) {
2128
+ this.assertActionExists(action, 'scheduleActionAtTick');
2129
+ const expected = InputManager.virtualValueCategory(value);
2130
+ this.assertValueType(action, expected, 'scheduleActionAtTick');
2131
+ if (tick < this.currentTick) {
2132
+ throw new InputTickError(tick, this.currentTick);
2133
+ }
2134
+ const pending = this.scheduledActions.get(tick);
2135
+ if (pending)
2136
+ pending.push({ action, value });
2137
+ else
2138
+ this.scheduledActions.set(tick, [{ action, value }]);
2139
+ }
2140
+ /** Wire (or clear, via `null`) the sink `poll()` calls with
2141
+ * `'input.schedule.dropped'` (`{tick, action}`) whenever it discards a
2142
+ * scheduled entry for a tick whose input phase never ran. Called once by
2143
+ * whoever constructs this `InputManager` with a `DebugRegistry` behind it
2144
+ * (`setup-three-root-adapter.ts`), the same seed spot as
2145
+ * `setVirtualInputTarget`/`setInputActionsSource` — never called directly
2146
+ * by gameplay code. */
2147
+ setDebugEmit(fn) {
2148
+ this.debugEmit = fn;
2149
+ }
2150
+ /** D15/T-D15.5 — start (or restart) recording the post-gate action-delta
2151
+ * trace: clears any prior trace/snapshot, so a fresh recording session
2152
+ * never carries over stale deltas from an earlier one. */
2153
+ startInputRecording() {
2154
+ this.inputRecording = true;
2155
+ this.inputTrace = [];
2156
+ this.lastTraceSnapshot.clear();
2157
+ }
2158
+ /** D15/T-D15.5 — stop recording (the trace accumulated so far stays
2159
+ * readable via {@link getInputTrace} until the next `startInputRecording`
2160
+ * clears it). Idempotent. */
2161
+ stopInputRecording() {
2162
+ this.inputRecording = false;
2163
+ }
2164
+ /** D15/T-D15.5 — whether a recording is currently active. */
2165
+ isInputRecording() {
2166
+ return this.inputRecording;
2167
+ }
2168
+ /** D15/T-D15.5 — the recorded trace so far (a defensive copy), versioned
2169
+ * per the design doc's format sketch (§2.c). SP5 (out of scope here) is
2170
+ * the eventual consumer that replays this; this module only ever
2171
+ * RECORDS. */
2172
+ getInputTrace() {
2173
+ return { version: 1, ticks: this.inputTrace.slice() };
2174
+ }
2175
+ /** Request pointer lock for FPS-style mouse control */
2176
+ requestPointerLock(element) {
2177
+ // Idempotent: never stack duplicate click listeners. Rewire if the element
2178
+ // changed, and track it so dispose() can remove the listener.
2179
+ if (this.pointerLockElement === element)
2180
+ return;
2181
+ if (this.pointerLockElement) {
2182
+ this.pointerLockElement.removeEventListener('click', this.onPointerLockClick);
2183
+ }
2184
+ this.pointerLockElement = element;
2185
+ element.addEventListener('click', this.onPointerLockClick);
2186
+ }
2187
+ /** Clean up event listeners */
2188
+ dispose() {
2189
+ if (this.disposed)
2190
+ return;
2191
+ this.disposed = true;
2192
+ if (typeof window !== 'undefined') {
2193
+ window.removeEventListener('keydown', this.onKeyDown);
2194
+ window.removeEventListener('keyup', this.onKeyUp);
2195
+ window.removeEventListener('mousedown', this.onMouseDown);
2196
+ window.removeEventListener('mouseup', this.onMouseUp);
2197
+ window.removeEventListener('mousemove', this.onMouseMove);
2198
+ window.removeEventListener('blur', this.onWindowBlur);
2199
+ window.removeEventListener('focus', this.onWindowFocus);
2200
+ }
2201
+ if (typeof document !== 'undefined' && typeof document.removeEventListener === 'function') {
2202
+ document.removeEventListener('pointerlockchange', this.onPointerLockChange);
2203
+ }
2204
+ if (this.pointerLockElement) {
2205
+ this.pointerLockElement.removeEventListener('click', this.onPointerLockClick);
2206
+ this.pointerLockElement = null;
2207
+ }
2208
+ }
2209
+ }