@n3rdw1z4rd/core 0.18.5 → 0.19.1

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 (109) hide show
  1. package/README.md +72 -10
  2. package/dist/astar.d.ts +44 -0
  3. package/dist/astar.js +118 -0
  4. package/dist/canvas-renderer.d.ts +157 -0
  5. package/dist/canvas-renderer.js +207 -0
  6. package/dist/clock.d.ts +69 -0
  7. package/dist/clock.js +108 -0
  8. package/dist/color-palette.d.ts +25 -0
  9. package/dist/color-palette.js +112 -0
  10. package/dist/color.d.ts +90 -0
  11. package/dist/color.js +224 -0
  12. package/dist/css/main.css +1 -3
  13. package/dist/disposable.d.ts +27 -0
  14. package/dist/disposable.js +32 -0
  15. package/dist/dungeon-generator.d.ts +142 -0
  16. package/dist/dungeon-generator.js +288 -0
  17. package/dist/ecs.d.ts +87 -0
  18. package/dist/ecs.js +101 -0
  19. package/dist/emitter.d.ts +40 -0
  20. package/dist/emitter.js +54 -0
  21. package/dist/event-queue.d.ts +29 -0
  22. package/dist/event-queue.js +40 -0
  23. package/dist/index.cjs +3820 -0
  24. package/dist/index.d.cts +2657 -0
  25. package/dist/index.d.ts +35 -873
  26. package/dist/index.js +34 -3981
  27. package/dist/input/action-map.d.ts +79 -0
  28. package/dist/input/action-map.js +131 -0
  29. package/dist/input/bindings.d.ts +273 -0
  30. package/dist/input/bindings.js +250 -0
  31. package/dist/input/gestures.d.ts +108 -0
  32. package/dist/input/gestures.js +159 -0
  33. package/dist/input/index.d.ts +5 -0
  34. package/dist/input/index.js +5 -0
  35. package/dist/input/input.d.ts +297 -0
  36. package/dist/input/input.js +695 -0
  37. package/dist/log.d.ts +8 -0
  38. package/dist/log.js +9 -0
  39. package/dist/map2d.d.ts +83 -0
  40. package/dist/map2d.js +120 -0
  41. package/dist/map3d-CHDJiq5T.d.cts +236 -0
  42. package/dist/map3d.d.ts +94 -0
  43. package/dist/map3d.js +148 -0
  44. package/dist/math.d.ts +176 -0
  45. package/dist/math.js +206 -0
  46. package/dist/misc.d.ts +46 -0
  47. package/dist/misc.js +71 -0
  48. package/dist/observable.d.ts +43 -0
  49. package/dist/observable.js +53 -0
  50. package/dist/particle-renderer.d.ts +47 -0
  51. package/dist/particle-renderer.js +82 -0
  52. package/dist/particle-system-2d.d.ts +60 -0
  53. package/dist/particle-system-2d.js +147 -0
  54. package/dist/random.d.ts +46 -0
  55. package/dist/random.js +74 -0
  56. package/dist/rectangle.d.ts +44 -0
  57. package/dist/rectangle.js +69 -0
  58. package/dist/rng.d.ts +72 -0
  59. package/dist/rng.js +152 -0
  60. package/dist/signal.d.ts +34 -0
  61. package/dist/signal.js +41 -0
  62. package/dist/spatial-partition-2d.d.ts +42 -0
  63. package/dist/spatial-partition-2d.js +52 -0
  64. package/dist/spatial-partition-3d-Ba-VBveM.cjs +1324 -0
  65. package/dist/spatial-partition-3d.d.ts +44 -0
  66. package/dist/spatial-partition-3d.js +57 -0
  67. package/dist/three/asteroid-mesh.d.ts +41 -0
  68. package/dist/three/asteroid-mesh.js +44 -0
  69. package/dist/three/camera-rig.d.ts +140 -0
  70. package/dist/three/camera-rig.js +197 -0
  71. package/dist/three/cube-sphere-geometry.d.ts +55 -0
  72. package/dist/three/cube-sphere-geometry.js +239 -0
  73. package/dist/three/ecs.d.ts +75 -0
  74. package/dist/three/ecs.js +64 -0
  75. package/dist/three/index.d.ts +12 -0
  76. package/dist/three/index.js +12 -0
  77. package/dist/three/particle-system-3d.d.ts +53 -0
  78. package/dist/three/particle-system-3d.js +224 -0
  79. package/dist/three/renderer.d.ts +38 -0
  80. package/dist/three/renderer.js +57 -0
  81. package/dist/three/starfield.d.ts +23 -0
  82. package/dist/three/starfield.js +64 -0
  83. package/dist/three/texture-atlas.d.ts +76 -0
  84. package/dist/three/texture-atlas.js +84 -0
  85. package/dist/three/texture-utils.d.ts +31 -0
  86. package/dist/three/texture-utils.js +44 -0
  87. package/dist/three/voxel-geometry.d.ts +72 -0
  88. package/dist/three/voxel-geometry.js +231 -0
  89. package/dist/three/voxel-mesh.d.ts +67 -0
  90. package/dist/three/voxel-mesh.js +71 -0
  91. package/dist/three.cjs +1307 -0
  92. package/dist/three.d.cts +655 -0
  93. package/dist/tilemap.d.ts +17 -0
  94. package/dist/tilemap.js +26 -0
  95. package/dist/types.d.ts +34 -0
  96. package/dist/types.js +0 -0
  97. package/dist/vector.d.ts +78 -0
  98. package/dist/vector.js +169 -0
  99. package/dist/webgl-renderer.d.ts +89 -0
  100. package/dist/webgl-renderer.js +140 -0
  101. package/dist/webgl.d.ts +357 -0
  102. package/dist/webgl.js +628 -0
  103. package/dist/worker-interface.d.ts +30 -0
  104. package/dist/worker-interface.js +39 -0
  105. package/package.json +55 -13
  106. package/dist/css/index.ts +0 -1
  107. package/dist/index.css +0 -104
  108. package/dist/index.d.mts +0 -873
  109. package/dist/index.mjs +0 -3977
@@ -0,0 +1,695 @@
1
+ import { GAMEPAD_AXES, GAMEPAD_BUTTONS, XR_AXES, XR_BUTTONS, controlId } from "./bindings.js";
2
+ import { ActionMap } from "./action-map.js";
3
+ import { GestureRecognizer } from "./gestures.js";
4
+ import { Observable } from "../observable.js";
5
+ //#region src/input/input.ts
6
+ const ANY = -1;
7
+ const now = () => performance.now();
8
+ const MOUSE_BUTTONS = [
9
+ "left",
10
+ "middle",
11
+ "right",
12
+ "back",
13
+ "forward"
14
+ ];
15
+ const BUTTON_BITS = [
16
+ 1,
17
+ 4,
18
+ 2,
19
+ 8,
20
+ 16
21
+ ];
22
+ const isEditable = (target) => {
23
+ const element = target;
24
+ const tag = element?.tagName;
25
+ return !!element && (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || element.isContentEditable === true);
26
+ };
27
+ /**
28
+ * Game input with a Godot-style action map: bind keys, buttons, sticks, gestures and VR controls
29
+ * to named actions, then query actions instead of devices.
30
+ *
31
+ * const input = new Input(canvas);
32
+ * input.actions.add('jump', [key('Space'), pad('A')]);
33
+ *
34
+ * // every frame, before game logic:
35
+ * input.update();
36
+ * if (input.isActionJustPressed('jump')) player.jump();
37
+ *
38
+ * Call `dispose()` to remove all listeners.
39
+ *
40
+ * @category Input
41
+ */
42
+ var Input = class {
43
+ /** the actions to query; holds the `ui_*` defaults unless {@link InputOptions.defaults} is false */
44
+ actions = new ActionMap();
45
+ /** Thresholds for taps, swipes etc. can be tuned via `gestureRecognizer.thresholds`. */
46
+ gestureRecognizer = new GestureRecognizer();
47
+ /** Two-finger gesture values for the last frame (pinch 1 / pan 0 / rotate 0 when not gesturing). */
48
+ gestures = {
49
+ pinch: 1,
50
+ pan: {
51
+ x: 0,
52
+ y: 0
53
+ },
54
+ rotate: 0
55
+ };
56
+ /** Fingers currently on the target. */
57
+ get touches() {
58
+ return this.gestureRecognizer.touches;
59
+ }
60
+ /** the mouse or pen; not updated by touch */
61
+ pointer = {
62
+ type: "mouse",
63
+ x: 0,
64
+ y: 0,
65
+ ndcX: 0,
66
+ ndcY: 0,
67
+ deltaX: 0,
68
+ deltaY: 0,
69
+ wheelX: 0,
70
+ wheelY: 0,
71
+ pressure: 0,
72
+ tiltX: 0,
73
+ tiltY: 0
74
+ };
75
+ /** notified when {@link Input.lastDevice} changes, e.g. to switch on-screen button prompts */
76
+ onDeviceChange = new Observable();
77
+ /** notified from update() when a gamepad is first seen */
78
+ onGamepadConnected = new Observable();
79
+ /** notified from update() when a gamepad goes away; its held controls are released */
80
+ onGamepadDisconnected = new Observable();
81
+ _gamepads = /* @__PURE__ */ new Map();
82
+ /** Connected gamepads, as found by the last update(). */
83
+ get gamepads() {
84
+ return [...this._gamepads].map(([device, gamepad]) => ({
85
+ device,
86
+ id: gamepad.id,
87
+ standard: gamepad.mapping === "standard"
88
+ }));
89
+ }
90
+ _lastDevice = "keyboard";
91
+ _keyLabels;
92
+ _target;
93
+ _options;
94
+ _listeners = [];
95
+ _controls = /* @__PURE__ */ new Map([[0, /* @__PURE__ */ new Map()]]);
96
+ _actionStates = /* @__PURE__ */ new Map();
97
+ _actionListeners = [];
98
+ _warned = /* @__PURE__ */ new Set();
99
+ _pending = {
100
+ deltaX: 0,
101
+ deltaY: 0,
102
+ wheelX: 0,
103
+ wheelY: 0
104
+ };
105
+ _capture;
106
+ /** The kind of device that produced the most recent input (initially `'keyboard'`). */
107
+ get lastDevice() {
108
+ return this._lastDevice;
109
+ }
110
+ /** Whether the pointer is locked to the target, see {@link Input.lockPointer}. */
111
+ get isPointerLocked() {
112
+ return typeof document !== "undefined" && !!this._target && document.pointerLockElement === this._target;
113
+ }
114
+ /**
115
+ * @param target element that receives pointer, wheel and touch input (usually the canvas)
116
+ */
117
+ constructor(target, options = {}) {
118
+ this._target = target;
119
+ this._options = {
120
+ defaults: options.defaults ?? true,
121
+ preventDefault: options.preventDefault ?? true,
122
+ preventContextMenu: options.preventContextMenu ?? true
123
+ };
124
+ if (this._options.defaults) this.actions.addDefaults();
125
+ const keyboard = options.keyboardTarget ?? (typeof window !== "undefined" ? window : void 0);
126
+ if (keyboard) {
127
+ this._listen(keyboard, "keydown", (e) => this._onKeyDown(e));
128
+ this._listen(keyboard, "keyup", (e) => this._onKeyUp(e));
129
+ this._listen(keyboard, "blur", () => this.releaseAll(0));
130
+ }
131
+ if (typeof document !== "undefined") this._listen(document, "visibilitychange", () => {
132
+ if (document.hidden) this.releaseAll(0);
133
+ });
134
+ if (target) {
135
+ const style = target.style;
136
+ if (this._options.preventDefault && style) style.touchAction = "none";
137
+ this._listen(target, "pointerdown", (e) => this._onPointerDown(e));
138
+ this._listen(target, "pointerup", (e) => this._onPointerUp(e));
139
+ this._listen(target, "pointercancel", (e) => this._onPointerCancel(e));
140
+ this._listen(target, "pointermove", (e) => this._onPointerMove(e));
141
+ this._listen(target, "wheel", (e) => this._onWheel(e), { passive: false });
142
+ this._listen(target, "contextmenu", (e) => {
143
+ if (this._options.preventContextMenu) e.preventDefault();
144
+ });
145
+ }
146
+ }
147
+ /**
148
+ * Call once per frame, before reading input: polls devices and advances "just pressed" /
149
+ * "just released" by one frame. Action callbacks fire from here.
150
+ */
151
+ update() {
152
+ this.pointer.deltaX = this._pending.deltaX;
153
+ this.pointer.deltaY = this._pending.deltaY;
154
+ this.pointer.wheelX = this._pending.wheelX;
155
+ this.pointer.wheelY = this._pending.wheelY;
156
+ this._pending.deltaX = this._pending.deltaY = this._pending.wheelX = this._pending.wheelY = 0;
157
+ this._pollGamepads();
158
+ this._pollXR();
159
+ this._updateGestures();
160
+ const devices = [...this._controls.keys()];
161
+ const fired = [];
162
+ for (const name of this.actions.names) {
163
+ const action = this.actions.get(name);
164
+ let states = this._actionStates.get(name);
165
+ if (!states) this._actionStates.set(name, states = /* @__PURE__ */ new Map());
166
+ let anyRaw = 0;
167
+ for (const device of devices) {
168
+ let raw = 0;
169
+ for (const binding of action.bindings) raw = Math.max(raw, this._bindingValue(binding, device));
170
+ anyRaw = Math.max(anyRaw, raw);
171
+ if (this._advance(states, device, raw, action.deadzone)) fired.push({
172
+ action: name,
173
+ phase: states.get(device).pressed ? "pressed" : "released",
174
+ device
175
+ });
176
+ }
177
+ if (this._advance(states, ANY, anyRaw, action.deadzone)) fired.push({
178
+ action: name,
179
+ phase: states.get(ANY).pressed ? "pressed" : "released",
180
+ device: ANY
181
+ });
182
+ }
183
+ for (const controls of this._controls.values()) for (const state of controls.values()) state.pressed = false;
184
+ for (const { action, phase, device } of fired) for (const listener of [...this._actionListeners]) if (listener.action === action && listener.phase === phase && listener.device === device) listener.callback();
185
+ }
186
+ /** Whether the action is held past its deadzone. Unknown actions return false (and warn once). */
187
+ isActionPressed(action, query) {
188
+ return this._state(action, query)?.pressed ?? false;
189
+ }
190
+ /** Whether the action became pressed in the last update(). */
191
+ isActionJustPressed(action, query) {
192
+ const state = this._state(action, query);
193
+ return !!state && state.pressed && !state.wasPressed;
194
+ }
195
+ /** Whether the action was released in the last update(). */
196
+ isActionJustReleased(action, query) {
197
+ const state = this._state(action, query);
198
+ return !!state && !state.pressed && state.wasPressed;
199
+ }
200
+ /** 0..1, rescaled past the action's deadzone (analog triggers and sticks give values in between). */
201
+ getActionStrength(action, query) {
202
+ return this._state(action, query)?.strength ?? 0;
203
+ }
204
+ /** 0..1 before the deadzone is applied. */
205
+ getActionRawStrength(action, query) {
206
+ return this._state(action, query)?.raw ?? 0;
207
+ }
208
+ /** -1..1: `positive` minus `negative`. */
209
+ getAxis(negative, positive, query) {
210
+ return this.getActionStrength(positive, query) - this.getActionStrength(negative, query);
211
+ }
212
+ /**
213
+ * A 2D direction from four actions, with a circular deadzone and length at most 1 (diagonals
214
+ * aren't faster). Y is positive towards `positiveY`, as in Godot's get_vector("left", "right", "up", "down").
215
+ *
216
+ * @param options.deadzone default: the average of the four actions' deadzones
217
+ * @returns `x` and `y` in -1..1; `{ x: 0, y: 0 }` inside the deadzone
218
+ */
219
+ getVector(negativeX, positiveX, negativeY, positiveY, options = {}) {
220
+ const names = [
221
+ negativeX,
222
+ positiveX,
223
+ negativeY,
224
+ positiveY
225
+ ];
226
+ const raw = names.map((name) => this.getActionRawStrength(name, options));
227
+ const deadzone = options.deadzone ?? names.reduce((sum, name) => sum + (this.actions.get(name)?.deadzone ?? 0), 0) / 4;
228
+ let x = raw[1] - raw[0];
229
+ let y = raw[3] - raw[2];
230
+ const length = Math.hypot(x, y);
231
+ if (length <= deadzone) return {
232
+ x: 0,
233
+ y: 0
234
+ };
235
+ const scale = (Math.min(length, 1) - deadzone) / (1 - deadzone) / length;
236
+ x *= scale;
237
+ y *= scale;
238
+ return {
239
+ x,
240
+ y
241
+ };
242
+ }
243
+ /** Calls `callback` when the action is pressed or released (during update()). Returns an unsubscribe function. */
244
+ onAction(action, phase, callback, query = {}) {
245
+ const listener = {
246
+ action,
247
+ phase,
248
+ device: query.device ?? ANY,
249
+ callback
250
+ };
251
+ this._actionListeners.push(listener);
252
+ return () => {
253
+ const i = this._actionListeners.indexOf(listener);
254
+ if (i >= 0) this._actionListeners.splice(i, 1);
255
+ };
256
+ }
257
+ /** Whether a key (by `KeyboardEvent.code`) is held right now, regardless of actions. */
258
+ isKeyPressed(code) {
259
+ return (this._controls.get(0).get(`key:${code}`)?.value ?? 0) > 0;
260
+ }
261
+ /** Whether a mouse or pen button is held right now, regardless of actions. */
262
+ isMouseButtonPressed(button) {
263
+ return (this._controls.get(0).get(`mouse:${button}`)?.value ?? 0) > 0;
264
+ }
265
+ /**
266
+ * Releases every held key and button, on one device or all. Keyboard, mouse and touch (device 0)
267
+ * are released automatically when the window loses focus, since their release events get lost.
268
+ */
269
+ releaseAll(device) {
270
+ if (device === void 0 || device === 0) this.gestureRecognizer.clear();
271
+ for (const [d, controls] of this._controls) {
272
+ if (device !== void 0 && d !== device) continue;
273
+ for (const state of controls.values()) {
274
+ state.value = 0;
275
+ state.suppressed = false;
276
+ }
277
+ }
278
+ }
279
+ /** Requests pointer lock on the target (browsers only allow it from a user gesture, e.g. a click). */
280
+ lockPointer() {
281
+ this._target?.requestPointerLock?.();
282
+ }
283
+ /** Exits pointer lock if the target holds it. */
284
+ unlockPointer() {
285
+ if (this.isPointerLocked) document.exitPointerLock();
286
+ }
287
+ /**
288
+ * Waits for the player's next input and resolves with a binding for it, for rebinding menus.
289
+ * Resolves `null` if the cancel key is pressed or another capture starts. The captured press
290
+ * doesn't trigger any actions.
291
+ */
292
+ captureBinding(options = {}) {
293
+ this.cancelCapture();
294
+ return new Promise((resolve) => {
295
+ this._capture = {
296
+ options,
297
+ resolve
298
+ };
299
+ });
300
+ }
301
+ /** Ends a pending {@link Input.captureBinding}, resolving it with `null`. */
302
+ cancelCapture() {
303
+ const capture = this._capture;
304
+ this._capture = void 0;
305
+ capture?.resolve(null);
306
+ }
307
+ /**
308
+ * Loads the keyboard layout (where supported, e.g. Chromium) so {@link bindingLabel} names keys
309
+ * as printed on the player's keyboard: KeyW is "Z" on AZERTY.
310
+ */
311
+ async loadKeyboardLayout() {
312
+ const keyboard = globalThis.navigator?.keyboard;
313
+ try {
314
+ this._keyLabels = await keyboard?.getLayoutMap?.();
315
+ } catch {
316
+ this._keyLabels = void 0;
317
+ }
318
+ return this._keyLabels;
319
+ }
320
+ /** The layout loaded by {@link Input.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
321
+ get keyLabels() {
322
+ return this._keyLabels;
323
+ }
324
+ /** Removes all event listeners and action callbacks, cancels any capture and detaches XR. */
325
+ dispose() {
326
+ for (const [target, type, listener, options] of this._listeners) target.removeEventListener(type, listener, options);
327
+ this._listeners.length = 0;
328
+ this._actionListeners.length = 0;
329
+ this.cancelCapture();
330
+ this.detachXR();
331
+ }
332
+ _listen(target, type, listener, options) {
333
+ target.addEventListener(type, listener, options);
334
+ this._listeners.push([
335
+ target,
336
+ type,
337
+ listener,
338
+ options
339
+ ]);
340
+ }
341
+ _state(action, query) {
342
+ if (!this.actions.has(action)) {
343
+ if (!this._warned.has(action)) {
344
+ this._warned.add(action);
345
+ console.warn(`Input: unknown action "${action}"`);
346
+ }
347
+ return;
348
+ }
349
+ return this._actionStates.get(action)?.get(query?.device ?? ANY);
350
+ }
351
+ _advance(states, device, raw, deadzone) {
352
+ let state = states.get(device);
353
+ if (!state) states.set(device, state = {
354
+ raw: 0,
355
+ strength: 0,
356
+ pressed: false,
357
+ wasPressed: false
358
+ });
359
+ state.wasPressed = state.pressed;
360
+ state.raw = raw;
361
+ state.pressed = raw > 0 && raw >= deadzone;
362
+ state.strength = !state.pressed ? 0 : deadzone >= 1 ? 1 : Math.min(1, (raw - deadzone) / (1 - deadzone));
363
+ if (state.pressed && raw >= 1) state.strength = 1;
364
+ return state.pressed !== state.wasPressed;
365
+ }
366
+ _controlValue(device, id) {
367
+ const state = this._controls.get(device)?.get(id);
368
+ if (!state || state.suppressed) return 0;
369
+ return state.pressed && state.value < .5 ? 1 : state.value;
370
+ }
371
+ _bindingValue(binding, device) {
372
+ const value = this._controlValue(device, controlId(binding));
373
+ if (value === 0 || binding.type !== "key" || !binding.modifiers) return value;
374
+ const held = (left, right) => this._controlValue(device, `key:${left}`) > 0 || this._controlValue(device, `key:${right}`) > 0;
375
+ const m = binding.modifiers;
376
+ if (m.shift && !held("ShiftLeft", "ShiftRight")) return 0;
377
+ if (m.ctrl && !held("ControlLeft", "ControlRight")) return 0;
378
+ if (m.alt && !held("AltLeft", "AltRight")) return 0;
379
+ if (m.meta && !held("MetaLeft", "MetaRight")) return 0;
380
+ return value;
381
+ }
382
+ _control(device, binding) {
383
+ let controls = this._controls.get(device);
384
+ if (!controls) this._controls.set(device, controls = /* @__PURE__ */ new Map());
385
+ const id = controlId(binding);
386
+ let state = controls.get(id);
387
+ if (!state) controls.set(id, state = {
388
+ value: 0,
389
+ pressed: false,
390
+ suppressed: false
391
+ });
392
+ return state;
393
+ }
394
+ /** Updates a held control (key, button, axis direction: 0..1); `binding` describes it for captureBinding(). */
395
+ _setControl(device, binding, value) {
396
+ const state = this._control(device, binding);
397
+ const wasDown = state.value >= .5;
398
+ state.value = value;
399
+ if (value >= .5 && !wasDown) {
400
+ if (this._tryCapture(binding)) state.suppressed = true;
401
+ else state.pressed = true;
402
+ }
403
+ if (value === 0) state.suppressed = false;
404
+ }
405
+ /** A one-frame press with no held state: wheel steps, gestures. */
406
+ _pulse(device, binding) {
407
+ const state = this._control(device, binding);
408
+ if (!this._tryCapture(binding)) state.pressed = true;
409
+ }
410
+ _tryCapture(binding) {
411
+ const capture = this._capture;
412
+ if (!capture) return false;
413
+ const types = capture.options.types;
414
+ const cancelKey = capture.options.cancelKey === void 0 ? "Escape" : capture.options.cancelKey;
415
+ const cancelled = binding.type === "key" && binding.code === cancelKey;
416
+ if (!cancelled && types && !types.includes(binding.type)) return false;
417
+ this._capture = void 0;
418
+ capture.resolve(cancelled ? null : binding);
419
+ return true;
420
+ }
421
+ _setLastDevice(type) {
422
+ if (type === this._lastDevice) return;
423
+ this._lastDevice = type;
424
+ this.onDeviceChange.notify(type);
425
+ }
426
+ /**
427
+ * Vibrates a gamepad (where supported). Magnitudes are 0..1; `strong` defaults to 1, `weak` to
428
+ * `strong`, `duration` to 200 ms.
429
+ */
430
+ rumble(device, options = {}) {
431
+ (this._gamepads.get(device)?.vibrationActuator)?.playEffect?.("dual-rumble", {
432
+ startDelay: 0,
433
+ duration: options.duration ?? 200,
434
+ strongMagnitude: options.strong ?? 1,
435
+ weakMagnitude: options.weak ?? options.strong ?? 1
436
+ })?.catch(() => {});
437
+ }
438
+ _pollGamepads() {
439
+ const pads = globalThis.navigator?.getGamepads?.() ?? [];
440
+ const seen = /* @__PURE__ */ new Set();
441
+ for (const gamepad of pads) {
442
+ if (!gamepad || !gamepad.connected) continue;
443
+ const device = gamepad.index + 1;
444
+ const isNew = !this._gamepads.has(device);
445
+ seen.add(device);
446
+ this._gamepads.set(device, gamepad);
447
+ if (isNew) this.onGamepadConnected.notify({
448
+ device,
449
+ id: gamepad.id,
450
+ standard: gamepad.mapping === "standard"
451
+ });
452
+ let active = false;
453
+ for (let i = 0; i < GAMEPAD_BUTTONS.length && i < gamepad.buttons.length; i++) {
454
+ const button = gamepad.buttons[i];
455
+ const value = button.value > 0 ? button.value : button.pressed ? 1 : 0;
456
+ this._setControl(device, {
457
+ type: "pad",
458
+ button: GAMEPAD_BUTTONS[i]
459
+ }, value);
460
+ active ||= value >= .5;
461
+ }
462
+ for (let i = 0; i < GAMEPAD_AXES.length && i < gamepad.axes.length; i++) {
463
+ const value = gamepad.axes[i];
464
+ this._setControl(device, {
465
+ type: "padAxis",
466
+ axis: GAMEPAD_AXES[i],
467
+ direction: 1
468
+ }, Math.max(0, value));
469
+ this._setControl(device, {
470
+ type: "padAxis",
471
+ axis: GAMEPAD_AXES[i],
472
+ direction: -1
473
+ }, Math.max(0, -value));
474
+ active ||= Math.abs(value) >= .5;
475
+ }
476
+ if (active) this._setLastDevice("gamepad");
477
+ }
478
+ for (const [device, gamepad] of this._gamepads) {
479
+ if (seen.has(device)) continue;
480
+ for (const state of this._controls.get(device)?.values() ?? []) state.value = 0;
481
+ this._gamepads.delete(device);
482
+ this.onGamepadDisconnected.notify({
483
+ device,
484
+ id: gamepad.id,
485
+ standard: gamepad.mapping === "standard"
486
+ });
487
+ }
488
+ }
489
+ _updateGestures() {
490
+ const frame = this.gestureRecognizer.update(now());
491
+ this.gestures.pinch = frame.pinch;
492
+ this.gestures.pan = frame.pan;
493
+ this.gestures.rotate = frame.rotate;
494
+ for (const name of frame.gestures) this._pulse(0, {
495
+ type: "gesture",
496
+ gesture: name
497
+ });
498
+ }
499
+ _xrSession;
500
+ _xrEnd;
501
+ _xrHeld = /* @__PURE__ */ new Set();
502
+ /** The session set by {@link Input.attachXR}, until detached or ended. */
503
+ get xrSession() {
504
+ return this._xrSession;
505
+ }
506
+ /**
507
+ * Reads VR controller buttons and sticks from a WebXR session (e.g. `renderer.xr.getSession()`)
508
+ * into the action map. Controller poses stay with three.js (`renderer.xr.getController(i)`).
509
+ * XR controller state only updates during XR frames, so call update() from the XR animation
510
+ * loop (`renderer.setAnimationLoop`). Detaches automatically when the session ends.
511
+ */
512
+ attachXR(session) {
513
+ this.detachXR();
514
+ this._xrSession = session;
515
+ this._xrEnd = () => this.detachXR();
516
+ session.addEventListener("end", this._xrEnd);
517
+ }
518
+ /** Stops reading the XR session and releases its controls. */
519
+ detachXR() {
520
+ if (this._xrSession && this._xrEnd) this._xrSession.removeEventListener("end", this._xrEnd);
521
+ this._xrSession = void 0;
522
+ this._xrEnd = void 0;
523
+ this._releaseXR(/* @__PURE__ */ new Set());
524
+ }
525
+ _pollXR() {
526
+ const session = this._xrSession;
527
+ if (!session) return;
528
+ const held = /* @__PURE__ */ new Set();
529
+ let active = false;
530
+ for (const source of session.inputSources) {
531
+ const hand = source.handedness;
532
+ const gamepad = source.gamepad;
533
+ if (hand !== "left" && hand !== "right" || !gamepad) continue;
534
+ for (let i = 0; i < XR_BUTTONS.length && i < gamepad.buttons.length; i++) {
535
+ const button = gamepad.buttons[i];
536
+ const value = button.value > 0 ? button.value : button.pressed ? 1 : 0;
537
+ const binding = {
538
+ type: "xr",
539
+ hand,
540
+ button: XR_BUTTONS[i]
541
+ };
542
+ this._setControl(0, binding, value);
543
+ held.add(controlId(binding));
544
+ active ||= value >= .5;
545
+ }
546
+ for (let i = 0; i < XR_AXES.length && i < gamepad.axes.length; i++) {
547
+ const value = gamepad.axes[i];
548
+ for (const direction of [1, -1]) {
549
+ const binding = {
550
+ type: "xrAxis",
551
+ hand,
552
+ axis: XR_AXES[i],
553
+ direction
554
+ };
555
+ this._setControl(0, binding, Math.max(0, value * direction));
556
+ held.add(controlId(binding));
557
+ }
558
+ active ||= Math.abs(value) >= .5;
559
+ }
560
+ }
561
+ this._releaseXR(held);
562
+ for (const id of held) this._xrHeld.add(id);
563
+ if (active) this._setLastDevice("xr");
564
+ }
565
+ _releaseXR(keep) {
566
+ const controls = this._controls.get(0);
567
+ for (const id of this._xrHeld) {
568
+ if (keep.has(id)) continue;
569
+ const state = controls.get(id);
570
+ if (state) state.value = 0;
571
+ this._xrHeld.delete(id);
572
+ }
573
+ }
574
+ _isBound(type, predicate) {
575
+ for (const name of this.actions.names) if (this.actions.get(name).bindings.some((b) => b.type === type && predicate(b))) return true;
576
+ return false;
577
+ }
578
+ _onKeyDown(event) {
579
+ if (isEditable(event.target)) return;
580
+ if (this._options.preventDefault && this._isBound("key", (b) => b.type === "key" && b.code === event.code)) event.preventDefault();
581
+ this._setLastDevice("keyboard");
582
+ if (event.repeat) return;
583
+ this._setControl(0, {
584
+ type: "key",
585
+ code: event.code
586
+ }, 1);
587
+ }
588
+ _onKeyUp(event) {
589
+ this._setControl(0, {
590
+ type: "key",
591
+ code: event.code
592
+ }, 0);
593
+ }
594
+ _updatePointer(event) {
595
+ const rect = this._target?.getBoundingClientRect?.();
596
+ const left = rect?.left ?? 0;
597
+ const top = rect?.top ?? 0;
598
+ const width = rect?.width || 1;
599
+ const height = rect?.height || 1;
600
+ this.pointer.type = event.pointerType === "pen" ? "pen" : "mouse";
601
+ this.pointer.x = event.clientX - left;
602
+ this.pointer.y = event.clientY - top;
603
+ this.pointer.ndcX = this.pointer.x / width * 2 - 1;
604
+ this.pointer.ndcY = -(this.pointer.y / height * 2 - 1);
605
+ this.pointer.pressure = event.pressure ?? 0;
606
+ this.pointer.tiltX = event.tiltX ?? 0;
607
+ this.pointer.tiltY = event.tiltY ?? 0;
608
+ }
609
+ _local(event) {
610
+ const rect = this._target?.getBoundingClientRect?.();
611
+ return {
612
+ x: event.clientX - (rect?.left ?? 0),
613
+ y: event.clientY - (rect?.top ?? 0)
614
+ };
615
+ }
616
+ _onPointerDown(event) {
617
+ if (event.pointerType === "touch") {
618
+ const { x, y } = this._local(event);
619
+ this.gestureRecognizer.down(event.pointerId, x, y, now());
620
+ this._setLastDevice("touch");
621
+ this._target?.setPointerCapture?.(event.pointerId);
622
+ return;
623
+ }
624
+ this._updatePointer(event);
625
+ this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
626
+ const button = MOUSE_BUTTONS[event.button];
627
+ if (button) this._setControl(0, {
628
+ type: "mouse",
629
+ button
630
+ }, 1);
631
+ this._target?.setPointerCapture?.(event.pointerId);
632
+ }
633
+ _onPointerUp(event) {
634
+ if (event.pointerType === "touch") {
635
+ const { x, y } = this._local(event);
636
+ this.gestureRecognizer.up(event.pointerId, x, y, now());
637
+ return;
638
+ }
639
+ this._updatePointer(event);
640
+ const button = MOUSE_BUTTONS[event.button];
641
+ if (button) this._setControl(0, {
642
+ type: "mouse",
643
+ button
644
+ }, 0);
645
+ }
646
+ _onPointerCancel(event) {
647
+ if (event.pointerType === "touch") this.gestureRecognizer.cancel(event.pointerId);
648
+ else this._onPointerUp(event);
649
+ }
650
+ _onPointerMove(event) {
651
+ if (event.pointerType === "touch") {
652
+ const { x, y } = this._local(event);
653
+ this.gestureRecognizer.move(event.pointerId, x, y);
654
+ return;
655
+ }
656
+ this._updatePointer(event);
657
+ this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
658
+ this._pending.deltaX += event.movementX ?? 0;
659
+ this._pending.deltaY += event.movementY ?? 0;
660
+ const button = MOUSE_BUTTONS[event.button];
661
+ if (button) {
662
+ const down = ((event.buttons ?? 0) & BUTTON_BITS[event.button]) !== 0;
663
+ this._setControl(0, {
664
+ type: "mouse",
665
+ button
666
+ }, down ? 1 : 0);
667
+ }
668
+ }
669
+ _onWheel(event) {
670
+ const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 800 : 1;
671
+ const dx = event.deltaX * scale;
672
+ const dy = event.deltaY * scale;
673
+ this._pending.wheelX += dx;
674
+ this._pending.wheelY += dy;
675
+ if (this._options.preventDefault && this._isBound("wheel", () => true)) event.preventDefault();
676
+ if (dy < 0) this._pulse(0, {
677
+ type: "wheel",
678
+ direction: "up"
679
+ });
680
+ if (dy > 0) this._pulse(0, {
681
+ type: "wheel",
682
+ direction: "down"
683
+ });
684
+ if (dx < 0) this._pulse(0, {
685
+ type: "wheel",
686
+ direction: "left"
687
+ });
688
+ if (dx > 0) this._pulse(0, {
689
+ type: "wheel",
690
+ direction: "right"
691
+ });
692
+ }
693
+ };
694
+ //#endregion
695
+ export { Input };
package/dist/log.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ //#region src/log.d.ts
2
+ /**
3
+ * `console.debug` with a bold gray `[dev]` prefix; takes the same arguments. Visible only when the
4
+ * console shows verbose/debug messages.
5
+ * @category Utilities
6
+ */
7
+ export declare const log: (...args: any[]) => void;
8
+ //#endregion
package/dist/log.js ADDED
@@ -0,0 +1,9 @@
1
+ //#region src/log.ts
2
+ /**
3
+ * `console.debug` with a bold gray `[dev]` prefix; takes the same arguments. Visible only when the
4
+ * console shows verbose/debug messages.
5
+ * @category Utilities
6
+ */
7
+ const log = console.debug.bind(console, "%c[dev]", "font-weight: bold; color: #888;");
8
+ //#endregion
9
+ export { log };