@n3rdw1z4rd/core 0.19.1 → 0.21.0

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