@n3rdw1z4rd/core 0.19.0 → 0.20.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.
package/dist/index.cjs CHANGED
@@ -190,6 +190,13 @@ var CanvasRenderer = class {
190
190
  get height() {
191
191
  return this.canvas.height;
192
192
  }
193
+ /** canvas center in pixels */
194
+ get center() {
195
+ return {
196
+ x: Math.floor(this.width / 2),
197
+ y: Math.floor(this.height / 2)
198
+ };
199
+ }
193
200
  /**
194
201
  * @param canvas defaults to a new canvas element, not attached to the page (append {@link CanvasRenderer.canvas} yourself)
195
202
  */
@@ -1608,7 +1615,7 @@ const AXIS_NAMES = {
1608
1615
  const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
1609
1616
  /**
1610
1617
  * A readable name for a binding, e.g. for "Press Space to jump" prompts. Pass `keyLabels` (from
1611
- * {@link Input.loadKeyboardLayout}) to name keys as printed on the player's keyboard.
1618
+ * {@link InputActionMap.loadKeyboardLayout}) to name keys as printed on the player's keyboard.
1612
1619
  *
1613
1620
  * @category Input
1614
1621
  */
@@ -1643,8 +1650,17 @@ function bindingLabel(binding, keyLabels) {
1643
1650
  */
1644
1651
  const DEFAULT_DEADZONE = .2;
1645
1652
  /**
1646
- * Named actions and the inputs bound to them, like Godot's InputMap. Every {@link Input} has one as
1647
- * {@link Input.actions}; the methods that change it return `this` for chaining.
1653
+ * Repeat timing used by `repeat: true`: first repeat after 400 ms, then every 100 ms.
1654
+ *
1655
+ * @category Input
1656
+ */
1657
+ const DEFAULT_REPEAT = {
1658
+ delay: 400,
1659
+ interval: 100
1660
+ };
1661
+ /**
1662
+ * Named actions and the inputs bound to them, like Godot's InputMap. Every {@link InputActionMap} has one as
1663
+ * {@link InputActionMap.actions}; the methods that change it return `this` for chaining.
1648
1664
  *
1649
1665
  * ```ts
1650
1666
  * input.actions
@@ -1670,14 +1686,20 @@ var ActionMap = class {
1670
1686
  get(name) {
1671
1687
  return this._actions.get(name);
1672
1688
  }
1673
- /** Adds an action, or replaces its bindings (and deadzone, if given) if it exists. */
1689
+ /** Adds an action, or replaces its bindings (and deadzone / repeat, if given) if it exists. */
1674
1690
  add(name, bindings = [], options = {}) {
1675
1691
  const existing = this._actions.get(name);
1676
- this._actions.set(name, {
1692
+ const repeat = options.repeat === void 0 ? existing?.repeat : options.repeat === false ? void 0 : {
1693
+ ...DEFAULT_REPEAT,
1694
+ ...options.repeat === true ? {} : options.repeat
1695
+ };
1696
+ const action = {
1677
1697
  name,
1678
1698
  deadzone: options.deadzone ?? existing?.deadzone ?? .2,
1679
1699
  bindings: [...bindings]
1680
- });
1700
+ };
1701
+ if (repeat) action.repeat = repeat;
1702
+ this._actions.set(name, action);
1681
1703
  return this;
1682
1704
  }
1683
1705
  /** Removes an action, if it exists. */
@@ -1713,24 +1735,35 @@ var ActionMap = class {
1713
1735
  /** A JSON-serializable copy of all actions, for saving rebinds; see {@link ActionMap.load}. */
1714
1736
  toJSON() {
1715
1737
  const json = {};
1716
- for (const action of this._actions.values()) json[action.name] = {
1717
- deadzone: action.deadzone,
1718
- bindings: action.bindings.map((b) => ({ ...b }))
1719
- };
1738
+ for (const action of this._actions.values()) {
1739
+ json[action.name] = {
1740
+ deadzone: action.deadzone,
1741
+ bindings: action.bindings.map((b) => ({ ...b }))
1742
+ };
1743
+ if (action.repeat) json[action.name].repeat = { ...action.repeat };
1744
+ }
1720
1745
  return json;
1721
1746
  }
1722
1747
  /** Replaces all actions with the saved ones (e.g. a player's rebinds). */
1723
1748
  load(json) {
1724
1749
  this.clear();
1725
- for (const [name, action] of Object.entries(json)) this.add(name, action.bindings, { deadzone: action.deadzone });
1750
+ for (const [name, action] of Object.entries(json)) this.add(name, action.bindings, {
1751
+ deadzone: action.deadzone,
1752
+ repeat: action.repeat ?? false
1753
+ });
1726
1754
  return this;
1727
1755
  }
1728
1756
  /**
1729
1757
  * Godot-style `ui_*` actions for menus and dialogs (`ui_accept`, `ui_cancel`, `ui_left`, `ui_right`,
1730
- * `ui_up`, `ui_down`, `ui_page_up`, `ui_page_down`), with a 0.5 deadzone; replaces existing ones.
1758
+ * `ui_up`, `ui_down`, `ui_page_up`, `ui_page_down`), with a 0.5 deadzone; the directions and
1759
+ * page actions auto-repeat ({@link DEFAULT_REPEAT}). Replaces existing ones.
1731
1760
  */
1732
1761
  addDefaults() {
1733
1762
  const ui = { deadzone: .5 };
1763
+ const nav = {
1764
+ deadzone: .5,
1765
+ repeat: true
1766
+ };
1734
1767
  this.add("ui_accept", [
1735
1768
  key("Enter"),
1736
1769
  key("NumpadEnter"),
@@ -1742,24 +1775,24 @@ var ActionMap = class {
1742
1775
  key("ArrowLeft"),
1743
1776
  pad("DpadLeft"),
1744
1777
  padAxis("leftX", -1)
1745
- ], ui);
1778
+ ], nav);
1746
1779
  this.add("ui_right", [
1747
1780
  key("ArrowRight"),
1748
1781
  pad("DpadRight"),
1749
1782
  padAxis("leftX", 1)
1750
- ], ui);
1783
+ ], nav);
1751
1784
  this.add("ui_up", [
1752
1785
  key("ArrowUp"),
1753
1786
  pad("DpadUp"),
1754
1787
  padAxis("leftY", -1)
1755
- ], ui);
1788
+ ], nav);
1756
1789
  this.add("ui_down", [
1757
1790
  key("ArrowDown"),
1758
1791
  pad("DpadDown"),
1759
1792
  padAxis("leftY", 1)
1760
- ], ui);
1761
- this.add("ui_page_up", [key("PageUp"), pad("LB")], ui);
1762
- this.add("ui_page_down", [key("PageDown"), pad("RB")], ui);
1793
+ ], nav);
1794
+ this.add("ui_page_up", [key("PageUp"), pad("LB")], nav);
1795
+ this.add("ui_page_down", [key("PageDown"), pad("RB")], nav);
1763
1796
  return this;
1764
1797
  }
1765
1798
  };
@@ -1778,7 +1811,7 @@ const DEFAULT_THRESHOLDS = {
1778
1811
  /**
1779
1812
  * Turns touch points into gestures: tap, double tap, long press, swipes (one finger) and
1780
1813
  * pinch / pan / rotate (two fingers). Feed it with down / move / up, call update() once per frame.
1781
- * Times are in ms and positions in pixels, from any consistent clock and origin. {@link Input} drives
1814
+ * Times are in ms and positions in pixels, from any consistent clock and origin. {@link InputActionMap} drives
1782
1815
  * one for you; use this class directly only for custom touch handling.
1783
1816
  *
1784
1817
  * Tap, double tap and swipe are reported when the finger lifts, long press while it is still held;
@@ -1789,7 +1822,8 @@ const DEFAULT_THRESHOLDS = {
1789
1822
  * el.addEventListener('pointerdown', e => recognizer.down(e.pointerId, e.offsetX, e.offsetY, performance.now()));
1790
1823
  * // ... move / up / cancel likewise
1791
1824
  *
1792
- * const { gestures, pinch } = recognizer.update(performance.now());
1825
+ * const { gestures, events, pinch } = recognizer.update(performance.now());
1826
+ * const tap = events.find(e => e.gesture === 'tap'); // { gesture, x, y }
1793
1827
  * ```
1794
1828
  *
1795
1829
  * @category Input
@@ -1853,17 +1887,32 @@ var GestureRecognizer = class {
1853
1887
  const dy = y - touch.startY;
1854
1888
  const distance = Math.hypot(dx, dy);
1855
1889
  if (duration <= t.tapMaxDuration && touch.maxMovement <= t.tapMaxMovement) {
1856
- this._pending.push("tap");
1890
+ this._pending.push({
1891
+ gesture: "tap",
1892
+ x,
1893
+ y
1894
+ });
1857
1895
  const last = this._lastTap;
1858
1896
  if (last && time - last.time <= t.doubleTapMaxDelay && Math.hypot(x - last.x, y - last.y) <= t.doubleTapMaxDistance) {
1859
- this._pending.push("doubleTap");
1897
+ this._pending.push({
1898
+ gesture: "doubleTap",
1899
+ x,
1900
+ y
1901
+ });
1860
1902
  this._lastTap = void 0;
1861
1903
  } else this._lastTap = {
1862
1904
  x,
1863
1905
  y,
1864
1906
  time
1865
1907
  };
1866
- } else if (distance >= t.swipeMinDistance && duration <= t.swipeMaxDuration) this._pending.push(Math.abs(dx) >= Math.abs(dy) ? dx > 0 ? "swipeRight" : "swipeLeft" : dy > 0 ? "swipeDown" : "swipeUp");
1908
+ } else if (distance >= t.swipeMinDistance && duration <= t.swipeMaxDuration) {
1909
+ const gesture = Math.abs(dx) >= Math.abs(dy) ? dx > 0 ? "swipeRight" : "swipeLeft" : dy > 0 ? "swipeDown" : "swipeUp";
1910
+ this._pending.push({
1911
+ gesture,
1912
+ x: touch.startX,
1913
+ y: touch.startY
1914
+ });
1915
+ }
1867
1916
  }
1868
1917
  /** Forgets a finger without recognizing anything (e.g. on `pointercancel`). */
1869
1918
  cancel(id) {
@@ -1880,6 +1929,7 @@ var GestureRecognizer = class {
1880
1929
  update(time) {
1881
1930
  const frame = {
1882
1931
  gestures: [],
1932
+ events: [],
1883
1933
  pinch: 1,
1884
1934
  pan: {
1885
1935
  x: 0,
@@ -1889,7 +1939,11 @@ var GestureRecognizer = class {
1889
1939
  };
1890
1940
  for (const touch of this._touches.values()) if (!touch.multi && !touch.longPressed && touch.maxMovement <= this.thresholds.tapMaxMovement && time - touch.startTime >= this.thresholds.longPressDuration) {
1891
1941
  touch.longPressed = true;
1892
- this._pending.push("longPress");
1942
+ this._pending.push({
1943
+ gesture: "longPress",
1944
+ x: touch.x,
1945
+ y: touch.y
1946
+ });
1893
1947
  }
1894
1948
  const [a, b] = [...this._touches.values()];
1895
1949
  if (a && b) {
@@ -1905,7 +1959,11 @@ var GestureRecognizer = class {
1905
1959
  y: cy - pair.cy
1906
1960
  };
1907
1961
  frame.rotate = Math.atan2(Math.sin(angle - pair.angle), Math.cos(angle - pair.angle));
1908
- if (Math.abs(frame.pinch - 1) >= this.thresholds.pinchMinChange) this._pending.push(frame.pinch > 1 ? "pinchOut" : "pinchIn");
1962
+ if (Math.abs(frame.pinch - 1) >= this.thresholds.pinchMinChange) this._pending.push({
1963
+ gesture: frame.pinch > 1 ? "pinchOut" : "pinchIn",
1964
+ x: cx,
1965
+ y: cy
1966
+ });
1909
1967
  }
1910
1968
  this._pair = {
1911
1969
  a: a.id,
@@ -1916,12 +1974,253 @@ var GestureRecognizer = class {
1916
1974
  cy
1917
1975
  };
1918
1976
  } else this._pair = void 0;
1919
- frame.gestures = this._pending;
1977
+ frame.events = this._pending;
1978
+ frame.gestures = frame.events.map((e) => e.gesture);
1920
1979
  this._pending = [];
1921
1980
  return frame;
1922
1981
  }
1923
1982
  };
1924
1983
  //#endregion
1984
+ //#region src/input/input.ts
1985
+ const BUTTON_BITS = [
1986
+ 1,
1987
+ 4,
1988
+ 2,
1989
+ 8,
1990
+ 16
1991
+ ];
1992
+ /**
1993
+ * Event-based input for keyboard, mouse, pen and touch: subscribe with `on()` and query state
1994
+ * at any time; no frame loop needed. One shared instance, {@link Input.instance}.
1995
+ *
1996
+ * Events (listeners get the DOM event):
1997
+ * - keys, by lowercased `KeyboardEvent.code`: `key_down`, `key_up`, `key_repeat`, `key_pressed`
1998
+ * (released within `inputThreshold` ms), and per key `keyw_down`, `keyw_up`, `keyw_pressed`, ...
1999
+ * - buttons (mouse buttons; the primary finger or pen is button 0): `button_down`, `button_up`,
2000
+ * `button_clicked`, and per button `button0_down`, `button0_up`, `button0_clicked`, ...
2001
+ * No click after a drag.
2002
+ * - pointer: `pointer_move`; `drag_start`, `drag`, `drag_end` (moved `dragThreshold` px with a
2003
+ * button down); `mouse_wheel`; `contextmenu` (see `disableContextMenu()`)
2004
+ * - every finger: `touch_down`, `touch_move`, `touch_up`, `touch_cancel`
2005
+ * - `blur`: the window lost focus or the tab was hidden; every key and button is released
2006
+ *
2007
+ * ```ts
2008
+ * const input = Input.instance;
2009
+ * input.target = canvas;
2010
+ *
2011
+ * input.on('keyw_down', 'arrowup_down', () => move(0, -1));
2012
+ * input.on('button0_clicked', () => select(input.pointerPosition));
2013
+ * input.on('pointer_move', () => {
2014
+ * if (input.isButtonDown(0)) pan(input.pointerDelta.x, input.pointerDelta.y);
2015
+ * });
2016
+ * ```
2017
+ *
2018
+ * @category Input
2019
+ */
2020
+ var Input = class Input extends Emitter {
2021
+ static _instance;
2022
+ /** the shared instance, created on first use */
2023
+ static get instance() {
2024
+ if (!Input._instance) Input._instance = new Input();
2025
+ return Input._instance;
2026
+ }
2027
+ _state = {};
2028
+ _windowListeners = [];
2029
+ _targetListeners = [];
2030
+ _target = window;
2031
+ _contextMenuDisabled = false;
2032
+ _dragStart;
2033
+ _dragging = false;
2034
+ /** pixels from the target's top-left */
2035
+ pointerPosition = new Vector();
2036
+ /** -1..1 across the target, y up */
2037
+ pointerPositionNdc = new Vector();
2038
+ /** pixels moved by the last pointer event (mouse, pen and touch alike) */
2039
+ pointerDelta = new Vector();
2040
+ /** ms; a key or button released within this is also `_pressed` / `_clicked` */
2041
+ inputThreshold = 200;
2042
+ /** px; moving further than this with a button down starts a drag */
2043
+ dragThreshold = 5;
2044
+ /**
2045
+ * Where pointer, wheel and context-menu events are read and positions are measured, default
2046
+ * `window`; usually the canvas. Keys are always read from `window`.
2047
+ */
2048
+ get target() {
2049
+ return this._target;
2050
+ }
2051
+ /** moves the pointer, wheel and context-menu listeners to `target` */
2052
+ set target(target) {
2053
+ this._targetListeners.forEach(([type, listener]) => this._target.removeEventListener(type, listener));
2054
+ this._targetListeners = [];
2055
+ this._target = target;
2056
+ this._listenToTarget();
2057
+ }
2058
+ /** a drag is in progress */
2059
+ get isDragging() {
2060
+ return this._dragging;
2061
+ }
2062
+ constructor() {
2063
+ super();
2064
+ this._listen(this._windowListeners, window, "keydown", this._onKeyDown);
2065
+ this._listen(this._windowListeners, window, "keyup", this._onKeyUp);
2066
+ this._listen(this._windowListeners, window, "blur", this._onBlur);
2067
+ if (typeof document !== "undefined") this._listen(this._windowListeners, document, "visibilitychange", () => {
2068
+ if (document.hidden) this._onBlur(new Event("blur"));
2069
+ });
2070
+ this._listenToTarget();
2071
+ }
2072
+ /** Stops the right-click menu on the target; `contextmenu` is still emitted. */
2073
+ disableContextMenu() {
2074
+ if (this._contextMenuDisabled) return;
2075
+ this._contextMenuDisabled = true;
2076
+ this._listen(this._targetListeners, this._target, "contextmenu", this._onContextMenu);
2077
+ }
2078
+ /** Removes every DOM listener; the next {@link Input.instance} is a new one. */
2079
+ dispose() {
2080
+ this._windowListeners.forEach(([type, listener]) => {
2081
+ window.removeEventListener(type, listener);
2082
+ if (typeof document !== "undefined") document.removeEventListener(type, listener);
2083
+ });
2084
+ this._targetListeners.forEach(([type, listener]) => this._target.removeEventListener(type, listener));
2085
+ this._windowListeners = [];
2086
+ this._targetListeners = [];
2087
+ Input._instance = void 0;
2088
+ }
2089
+ _listenToTarget() {
2090
+ const listeners = this._targetListeners;
2091
+ this._listen(listeners, this._target, "pointerdown", this._onPointerDown);
2092
+ this._listen(listeners, this._target, "pointerup", this._onPointerUp);
2093
+ this._listen(listeners, this._target, "pointercancel", this._onPointerUp);
2094
+ this._listen(listeners, this._target, "pointermove", this._onPointerMove);
2095
+ this._listen(listeners, this._target, "wheel", this._onWheel, { passive: false });
2096
+ if (this._contextMenuDisabled) this._listen(listeners, this._target, "contextmenu", this._onContextMenu);
2097
+ const style = this._target.style;
2098
+ if (style) style.touchAction = "none";
2099
+ }
2100
+ _listen(listeners, target, type, handler, options) {
2101
+ const listener = handler.bind(this);
2102
+ target.addEventListener(type, listener, options);
2103
+ listeners.push([type, listener]);
2104
+ }
2105
+ _down(id, group, name, ev) {
2106
+ if (this._state[id]?.state) return;
2107
+ this._state[id] = {
2108
+ state: 1,
2109
+ timeStamp: ev.timeStamp
2110
+ };
2111
+ this.emit(`${group}_down`, ev);
2112
+ this.emit(`${name}_down`, ev);
2113
+ }
2114
+ _up(id, group, name, quick, ev) {
2115
+ const down = this._state[id];
2116
+ if (!down?.state) return;
2117
+ this._state[id] = {
2118
+ state: 0,
2119
+ timeStamp: ev.timeStamp
2120
+ };
2121
+ this.emit(`${group}_up`, ev);
2122
+ this.emit(`${name}_up`, ev);
2123
+ if (!this._dragging && ev.timeStamp - down.timeStamp <= this.inputThreshold) {
2124
+ this.emit(`${group}_${quick}`, ev);
2125
+ this.emit(`${name}_${quick}`, ev);
2126
+ }
2127
+ }
2128
+ _anyButtonDown() {
2129
+ return BUTTON_BITS.some((_, button) => this.isButtonDown(button));
2130
+ }
2131
+ _updatePointer(ev) {
2132
+ const rect = this._target.getBoundingClientRect?.() ?? {
2133
+ left: 0,
2134
+ top: 0,
2135
+ width: window.innerWidth,
2136
+ height: window.innerHeight
2137
+ };
2138
+ const x = ev.clientX - rect.left;
2139
+ const y = ev.clientY - rect.top;
2140
+ if (ev.pointerType === "touch") this.pointerDelta.set(x - this.pointerPosition.x, y - this.pointerPosition.y);
2141
+ else this.pointerDelta.set(ev.movementX ?? 0, ev.movementY ?? 0);
2142
+ this.pointerPosition.set(x, y);
2143
+ this.pointerPositionNdc.set(x / (rect.width || 1) * 2 - 1, -(y / (rect.height || 1)) * 2 + 1);
2144
+ }
2145
+ _onContextMenu(ev) {
2146
+ ev.preventDefault();
2147
+ this.emit("contextmenu", ev);
2148
+ }
2149
+ _onKeyDown(ev) {
2150
+ if (ev.repeat) this.emit("key_repeat", ev);
2151
+ else this._down(ev.code, "key", ev.code.toLowerCase(), ev);
2152
+ }
2153
+ _onKeyUp(ev) {
2154
+ this._up(ev.code, "key", ev.code.toLowerCase(), "pressed", ev);
2155
+ }
2156
+ _onPointerDown(ev) {
2157
+ if (ev.pointerType === "touch") this.emit("touch_down", ev);
2158
+ if (!ev.isPrimary) return;
2159
+ this._target.setPointerCapture?.(ev.pointerId);
2160
+ this._updatePointer(ev);
2161
+ this.pointerDelta.set(0, 0);
2162
+ if (!this._anyButtonDown()) {
2163
+ this._dragStart = this.pointerPosition.clone();
2164
+ this._dragging = false;
2165
+ }
2166
+ this._down(`button${ev.button}`, "button", `button${ev.button}`, ev);
2167
+ }
2168
+ _onPointerUp(ev) {
2169
+ if (ev.pointerType === "touch") this.emit(ev.type === "pointercancel" ? "touch_cancel" : "touch_up", ev);
2170
+ if (!ev.isPrimary) return;
2171
+ this._updatePointer(ev);
2172
+ this._up(`button${ev.button}`, "button", `button${ev.button}`, "clicked", ev);
2173
+ if (!this._anyButtonDown()) this._endDrag(ev);
2174
+ }
2175
+ _onPointerMove(ev) {
2176
+ if (ev.pointerType === "touch") this.emit("touch_move", ev);
2177
+ if (!ev.isPrimary) return;
2178
+ this._updatePointer(ev);
2179
+ if (ev.pointerType === "mouse" && ev.button >= 0) {
2180
+ const id = `button${ev.button}`;
2181
+ if (ev.buttons & BUTTON_BITS[ev.button]) this._down(id, "button", id, ev);
2182
+ else this._up(id, "button", id, "clicked", ev);
2183
+ }
2184
+ if (this._dragStart && this._anyButtonDown()) {
2185
+ if (!this._dragging && this.pointerPosition.distanceTo(this._dragStart) > this.dragThreshold) {
2186
+ this._dragging = true;
2187
+ this.emit("drag_start", ev);
2188
+ }
2189
+ if (this._dragging) this.emit("drag", ev);
2190
+ }
2191
+ this.emit("pointer_move", ev);
2192
+ }
2193
+ _endDrag(ev) {
2194
+ if (this._dragging) this.emit("drag_end", ev);
2195
+ this._dragStart = void 0;
2196
+ this._dragging = false;
2197
+ }
2198
+ _onWheel(ev) {
2199
+ this.emit("mouse_wheel", ev);
2200
+ }
2201
+ _onBlur(ev) {
2202
+ Object.values(this._state).forEach((s) => s.state = 0);
2203
+ this._endDrag(ev);
2204
+ this.emit("blur", ev);
2205
+ }
2206
+ /** Whether a key (by `KeyboardEvent.code`, e.g. 'KeyW') is down. */
2207
+ isKeyDown(keyCode) {
2208
+ return this._state[keyCode]?.state === 1;
2209
+ }
2210
+ /** 1 if the key is down, else 0. */
2211
+ getKeyState(keyCode) {
2212
+ return this._state[keyCode]?.state ?? 0;
2213
+ }
2214
+ /** Whether a button (`PointerEvent.button`: 0 left / primary finger, 1 middle, 2 right, ...) is down. */
2215
+ isButtonDown(buttonNumber) {
2216
+ return this._state[`button${buttonNumber}`]?.state === 1;
2217
+ }
2218
+ /** 1 if the button is down, else 0. */
2219
+ getButtonState(buttonNumber) {
2220
+ return this._state[`button${buttonNumber}`]?.state ?? 0;
2221
+ }
2222
+ };
2223
+ //#endregion
1925
2224
  //#region src/observable.ts
1926
2225
  /**
1927
2226
  * A set of observers notified with a value (plus optional extra arguments). Observers are
@@ -1974,7 +2273,7 @@ var Observable = class {
1974
2273
  }
1975
2274
  };
1976
2275
  //#endregion
1977
- //#region src/input/input.ts
2276
+ //#region src/input/input-action-map.ts
1978
2277
  const ANY = -1;
1979
2278
  const now = () => performance.now();
1980
2279
  const MOUSE_BUTTONS = [
@@ -1984,40 +2283,41 @@ const MOUSE_BUTTONS = [
1984
2283
  "back",
1985
2284
  "forward"
1986
2285
  ];
1987
- const BUTTON_BITS = [
1988
- 1,
1989
- 4,
1990
- 2,
1991
- 8,
1992
- 16
1993
- ];
1994
2286
  const isEditable = (target) => {
1995
2287
  const element = target;
1996
2288
  const tag = element?.tagName;
1997
2289
  return !!element && (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || element.isContentEditable === true);
1998
2290
  };
1999
2291
  /**
2000
- * Game input with a Godot-style action map: bind keys, buttons, sticks, gestures and VR controls
2001
- * to named actions, then query actions instead of devices.
2292
+ * Game input with a Godot-style action map, built on {@link Input}'s events: bind keys, buttons,
2293
+ * sticks, gestures and VR controls to named actions, then query actions instead of devices once
2294
+ * per frame. Gamepads and VR controllers are polled by `update()`.
2295
+ *
2296
+ * Input.instance.target = canvas;
2002
2297
  *
2003
- * const input = new Input(canvas);
2004
- * input.actions.add('jump', [key('Space'), pad('A')]);
2298
+ * const controls = new InputActionMap();
2299
+ * controls.actions.add('jump', [key('Space'), pad('A')]);
2005
2300
  *
2006
2301
  * // every frame, before game logic:
2007
- * input.update();
2008
- * if (input.isActionJustPressed('jump')) player.jump();
2302
+ * controls.update();
2303
+ * if (controls.isActionJustPressed('jump')) player.jump();
2009
2304
  *
2010
- * Call `dispose()` to remove all listeners.
2305
+ * Call `dispose()` to stop listening.
2011
2306
  *
2012
2307
  * @category Input
2013
2308
  */
2014
- var Input = class {
2015
- /** the actions to query; holds the `ui_*` defaults unless {@link InputOptions.defaults} is false */
2309
+ var InputActionMap = class {
2310
+ /** the actions to query; holds the `ui_*` defaults unless {@link InputActionMapOptions.defaults} is false */
2016
2311
  actions = new ActionMap();
2017
2312
  /** Thresholds for taps, swipes etc. can be tuned via `gestureRecognizer.thresholds`. */
2018
2313
  gestureRecognizer = new GestureRecognizer();
2019
- /** Two-finger gesture values for the last frame (pinch 1 / pan 0 / rotate 0 when not gesturing). */
2314
+ /**
2315
+ * Touch gestures from the last frame: `events` (each recognized gesture and where it happened,
2316
+ * e.g. the tap that triggered an action) and the two-finger values (pinch 1 / pan 0 / rotate 0
2317
+ * when not gesturing).
2318
+ */
2020
2319
  gestures = {
2320
+ events: [],
2021
2321
  pinch: 1,
2022
2322
  pan: {
2023
2323
  x: 0,
@@ -2025,6 +2325,8 @@ var Input = class {
2025
2325
  },
2026
2326
  rotate: 0
2027
2327
  };
2328
+ /** the {@link Input} events are read from */
2329
+ input;
2028
2330
  /** Fingers currently on the target. */
2029
2331
  get touches() {
2030
2332
  return this.gestureRecognizer.touches;
@@ -2044,7 +2346,7 @@ var Input = class {
2044
2346
  tiltX: 0,
2045
2347
  tiltY: 0
2046
2348
  };
2047
- /** notified when {@link Input.lastDevice} changes, e.g. to switch on-screen button prompts */
2349
+ /** notified when {@link InputActionMap.lastDevice} changes, e.g. to switch on-screen button prompts */
2048
2350
  onDeviceChange = new Observable();
2049
2351
  /** notified from update() when a gamepad is first seen */
2050
2352
  onGamepadConnected = new Observable();
@@ -2061,7 +2363,6 @@ var Input = class {
2061
2363
  }
2062
2364
  _lastDevice = "keyboard";
2063
2365
  _keyLabels;
2064
- _target;
2065
2366
  _options;
2066
2367
  _listeners = [];
2067
2368
  _controls = /* @__PURE__ */ new Map([[0, /* @__PURE__ */ new Map()]]);
@@ -2079,48 +2380,40 @@ var Input = class {
2079
2380
  get lastDevice() {
2080
2381
  return this._lastDevice;
2081
2382
  }
2082
- /** Whether the pointer is locked to the target, see {@link Input.lockPointer}. */
2383
+ /** Whether the pointer is locked to the target, see {@link InputActionMap.lockPointer}. */
2083
2384
  get isPointerLocked() {
2084
- return typeof document !== "undefined" && !!this._target && document.pointerLockElement === this._target;
2385
+ return typeof document !== "undefined" && document.pointerLockElement === this.input.target;
2085
2386
  }
2086
- /**
2087
- * @param target element that receives pointer, wheel and touch input (usually the canvas)
2088
- */
2089
- constructor(target, options = {}) {
2090
- this._target = target;
2387
+ constructor(options = {}) {
2388
+ this.input = options.input ?? Input.instance;
2091
2389
  this._options = {
2092
2390
  defaults: options.defaults ?? true,
2093
2391
  preventDefault: options.preventDefault ?? true,
2094
2392
  preventContextMenu: options.preventContextMenu ?? true
2095
2393
  };
2096
2394
  if (this._options.defaults) this.actions.addDefaults();
2097
- const keyboard = options.keyboardTarget ?? (typeof window !== "undefined" ? window : void 0);
2098
- if (keyboard) {
2099
- this._listen(keyboard, "keydown", (e) => this._onKeyDown(e));
2100
- this._listen(keyboard, "keyup", (e) => this._onKeyUp(e));
2101
- this._listen(keyboard, "blur", () => this.releaseAll(0));
2102
- }
2103
- if (typeof document !== "undefined") this._listen(document, "visibilitychange", () => {
2104
- if (document.hidden) this.releaseAll(0);
2105
- });
2106
- if (target) {
2107
- const style = target.style;
2108
- if (this._options.preventDefault && style) style.touchAction = "none";
2109
- this._listen(target, "pointerdown", (e) => this._onPointerDown(e));
2110
- this._listen(target, "pointerup", (e) => this._onPointerUp(e));
2111
- this._listen(target, "pointercancel", (e) => this._onPointerCancel(e));
2112
- this._listen(target, "pointermove", (e) => this._onPointerMove(e));
2113
- this._listen(target, "wheel", (e) => this._onWheel(e), { passive: false });
2114
- this._listen(target, "contextmenu", (e) => {
2115
- if (this._options.preventContextMenu) e.preventDefault();
2116
- });
2117
- }
2395
+ if (this._options.preventContextMenu) this.input.disableContextMenu();
2396
+ this._listen("key_down", (e) => this._onKeyDown(e));
2397
+ this._listen("key_repeat", (e) => this._onKeyDown(e));
2398
+ this._listen("key_up", (e) => this._onKeyUp(e));
2399
+ this._listen("button_down", (e) => this._onButton(e, 1));
2400
+ this._listen("button_up", (e) => this._onButton(e, 0));
2401
+ this._listen("pointer_move", (e) => this._onPointerMove(e));
2402
+ this._listen("touch_down", (e) => this._onTouchDown(e));
2403
+ this._listen("touch_move", (e) => this._onTouchMove(e));
2404
+ this._listen("touch_up", (e) => this._onTouchUp(e));
2405
+ this._listen("touch_cancel", (e) => this.gestureRecognizer.cancel(e.pointerId));
2406
+ this._listen("mouse_wheel", (e) => this._onWheel(e));
2407
+ this._listen("blur", () => this.releaseAll(0));
2118
2408
  }
2119
2409
  /**
2120
2410
  * Call once per frame, before reading input: polls devices and advances "just pressed" /
2121
2411
  * "just released" by one frame. Action callbacks fire from here.
2412
+ *
2413
+ * @param time current time in ms (e.g. the `requestAnimationFrame` timestamp), used for
2414
+ * gesture timing and auto-repeat; default `performance.now()`
2122
2415
  */
2123
- update() {
2416
+ update(time = now()) {
2124
2417
  this.pointer.deltaX = this._pending.deltaX;
2125
2418
  this.pointer.deltaY = this._pending.deltaY;
2126
2419
  this.pointer.wheelX = this._pending.wheelX;
@@ -2128,7 +2421,7 @@ var Input = class {
2128
2421
  this._pending.deltaX = this._pending.deltaY = this._pending.wheelX = this._pending.wheelY = 0;
2129
2422
  this._pollGamepads();
2130
2423
  this._pollXR();
2131
- this._updateGestures();
2424
+ this._updateGestures(time);
2132
2425
  const devices = [...this._controls.keys()];
2133
2426
  const fired = [];
2134
2427
  for (const name of this.actions.names) {
@@ -2140,29 +2433,43 @@ var Input = class {
2140
2433
  let raw = 0;
2141
2434
  for (const binding of action.bindings) raw = Math.max(raw, this._bindingValue(binding, device));
2142
2435
  anyRaw = Math.max(anyRaw, raw);
2143
- if (this._advance(states, device, raw, action.deadzone)) fired.push({
2436
+ const phase = this._advance(states, device, raw, action, time);
2437
+ if (phase) fired.push({
2144
2438
  action: name,
2145
- phase: states.get(device).pressed ? "pressed" : "released",
2146
- device
2439
+ phase,
2440
+ device,
2441
+ repeat: states.get(device).repeated
2147
2442
  });
2148
2443
  }
2149
- if (this._advance(states, ANY, anyRaw, action.deadzone)) fired.push({
2444
+ const phase = this._advance(states, ANY, anyRaw, action, time);
2445
+ if (phase) fired.push({
2150
2446
  action: name,
2151
- phase: states.get(ANY).pressed ? "pressed" : "released",
2152
- device: ANY
2447
+ phase,
2448
+ device: ANY,
2449
+ repeat: states.get(ANY).repeated
2153
2450
  });
2154
2451
  }
2155
2452
  for (const controls of this._controls.values()) for (const state of controls.values()) state.pressed = false;
2156
- 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();
2453
+ 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({
2454
+ action,
2455
+ repeat
2456
+ });
2157
2457
  }
2158
2458
  /** Whether the action is held past its deadzone. Unknown actions return false (and warn once). */
2159
2459
  isActionPressed(action, query) {
2160
2460
  return this._state(action, query)?.pressed ?? false;
2161
2461
  }
2162
- /** Whether the action became pressed in the last update(). */
2462
+ /**
2463
+ * Whether the action became pressed in the last update(), or auto-repeated while held if the
2464
+ * action has {@link Action.repeat} (e.g. to keep walking while a direction is held).
2465
+ */
2163
2466
  isActionJustPressed(action, query) {
2164
2467
  const state = this._state(action, query);
2165
- return !!state && state.pressed && !state.wasPressed;
2468
+ return !!state && state.pressed && (!state.wasPressed || state.repeated);
2469
+ }
2470
+ /** Whether the last update()'s press of the action was an auto-repeat rather than a new press. */
2471
+ isActionRepeated(action, query) {
2472
+ return this._state(action, query)?.repeated ?? false;
2166
2473
  }
2167
2474
  /** Whether the action was released in the last update(). */
2168
2475
  isActionJustReleased(action, query) {
@@ -2212,7 +2519,11 @@ var Input = class {
2212
2519
  y
2213
2520
  };
2214
2521
  }
2215
- /** Calls `callback` when the action is pressed or released (during update()). Returns an unsubscribe function. */
2522
+ /**
2523
+ * Calls `callback` when the action is pressed or released (during update()). With
2524
+ * {@link Action.repeat}, `'pressed'` also fires on each auto-repeat, with `event.repeat` set.
2525
+ * Returns an unsubscribe function.
2526
+ */
2216
2527
  onAction(action, phase, callback, query = {}) {
2217
2528
  const listener = {
2218
2529
  action,
@@ -2250,7 +2561,7 @@ var Input = class {
2250
2561
  }
2251
2562
  /** Requests pointer lock on the target (browsers only allow it from a user gesture, e.g. a click). */
2252
2563
  lockPointer() {
2253
- this._target?.requestPointerLock?.();
2564
+ this.input.target.requestPointerLock?.();
2254
2565
  }
2255
2566
  /** Exits pointer lock if the target holds it. */
2256
2567
  unlockPointer() {
@@ -2270,7 +2581,7 @@ var Input = class {
2270
2581
  };
2271
2582
  });
2272
2583
  }
2273
- /** Ends a pending {@link Input.captureBinding}, resolving it with `null`. */
2584
+ /** Ends a pending {@link InputActionMap.captureBinding}, resolving it with `null`. */
2274
2585
  cancelCapture() {
2275
2586
  const capture = this._capture;
2276
2587
  this._capture = void 0;
@@ -2289,51 +2600,59 @@ var Input = class {
2289
2600
  }
2290
2601
  return this._keyLabels;
2291
2602
  }
2292
- /** The layout loaded by {@link Input.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
2603
+ /** The layout loaded by {@link InputActionMap.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
2293
2604
  get keyLabels() {
2294
2605
  return this._keyLabels;
2295
2606
  }
2296
2607
  /** Removes all event listeners and action callbacks, cancels any capture and detaches XR. */
2297
2608
  dispose() {
2298
- for (const [target, type, listener, options] of this._listeners) target.removeEventListener(type, listener, options);
2609
+ for (const [type, listener] of this._listeners) this.input.off(type, listener);
2299
2610
  this._listeners.length = 0;
2300
2611
  this._actionListeners.length = 0;
2301
2612
  this.cancelCapture();
2302
2613
  this.detachXR();
2303
2614
  }
2304
- _listen(target, type, listener, options) {
2305
- target.addEventListener(type, listener, options);
2306
- this._listeners.push([
2307
- target,
2308
- type,
2309
- listener,
2310
- options
2311
- ]);
2615
+ _listen(type, listener) {
2616
+ this.input.on(type, listener);
2617
+ this._listeners.push([type, listener]);
2312
2618
  }
2313
2619
  _state(action, query) {
2314
2620
  if (!this.actions.has(action)) {
2315
2621
  if (!this._warned.has(action)) {
2316
2622
  this._warned.add(action);
2317
- console.warn(`Input: unknown action "${action}"`);
2623
+ console.warn(`InputActionMap: unknown action "${action}"`);
2318
2624
  }
2319
2625
  return;
2320
2626
  }
2321
2627
  return this._actionStates.get(action)?.get(query?.device ?? ANY);
2322
2628
  }
2323
- _advance(states, device, raw, deadzone) {
2629
+ _advance(states, device, raw, action, time) {
2630
+ const deadzone = action.deadzone;
2324
2631
  let state = states.get(device);
2325
2632
  if (!state) states.set(device, state = {
2326
2633
  raw: 0,
2327
2634
  strength: 0,
2328
2635
  pressed: false,
2329
- wasPressed: false
2636
+ wasPressed: false,
2637
+ repeated: false,
2638
+ nextRepeat: 0
2330
2639
  });
2331
2640
  state.wasPressed = state.pressed;
2641
+ state.repeated = false;
2332
2642
  state.raw = raw;
2333
2643
  state.pressed = raw > 0 && raw >= deadzone;
2334
2644
  state.strength = !state.pressed ? 0 : deadzone >= 1 ? 1 : Math.min(1, (raw - deadzone) / (1 - deadzone));
2335
2645
  if (state.pressed && raw >= 1) state.strength = 1;
2336
- return state.pressed !== state.wasPressed;
2646
+ if (state.pressed !== state.wasPressed) {
2647
+ if (state.pressed && action.repeat) state.nextRepeat = time + action.repeat.delay;
2648
+ return state.pressed ? "pressed" : "released";
2649
+ }
2650
+ if (state.pressed && action.repeat && time >= state.nextRepeat) {
2651
+ const next = state.nextRepeat + action.repeat.interval;
2652
+ state.repeated = true;
2653
+ state.nextRepeat = next > time ? next : time + action.repeat.interval;
2654
+ return "pressed";
2655
+ }
2337
2656
  }
2338
2657
  _controlValue(device, id) {
2339
2658
  const state = this._controls.get(device)?.get(id);
@@ -2458,8 +2777,9 @@ var Input = class {
2458
2777
  });
2459
2778
  }
2460
2779
  }
2461
- _updateGestures() {
2462
- const frame = this.gestureRecognizer.update(now());
2780
+ _updateGestures(time) {
2781
+ const frame = this.gestureRecognizer.update(time);
2782
+ this.gestures.events = frame.events;
2463
2783
  this.gestures.pinch = frame.pinch;
2464
2784
  this.gestures.pan = frame.pan;
2465
2785
  this.gestures.rotate = frame.rotate;
@@ -2471,7 +2791,7 @@ var Input = class {
2471
2791
  _xrSession;
2472
2792
  _xrEnd;
2473
2793
  _xrHeld = /* @__PURE__ */ new Set();
2474
- /** The session set by {@link Input.attachXR}, until detached or ended. */
2794
+ /** The session set by {@link InputActionMap.attachXR}, until detached or ended. */
2475
2795
  get xrSession() {
2476
2796
  return this._xrSession;
2477
2797
  }
@@ -2564,79 +2884,51 @@ var Input = class {
2564
2884
  }, 0);
2565
2885
  }
2566
2886
  _updatePointer(event) {
2567
- const rect = this._target?.getBoundingClientRect?.();
2568
- const left = rect?.left ?? 0;
2569
- const top = rect?.top ?? 0;
2570
- const width = rect?.width || 1;
2571
- const height = rect?.height || 1;
2572
2887
  this.pointer.type = event.pointerType === "pen" ? "pen" : "mouse";
2573
- this.pointer.x = event.clientX - left;
2574
- this.pointer.y = event.clientY - top;
2575
- this.pointer.ndcX = this.pointer.x / width * 2 - 1;
2576
- this.pointer.ndcY = -(this.pointer.y / height * 2 - 1);
2888
+ this.pointer.x = this.input.pointerPosition.x;
2889
+ this.pointer.y = this.input.pointerPosition.y;
2890
+ this.pointer.ndcX = this.input.pointerPositionNdc.x;
2891
+ this.pointer.ndcY = this.input.pointerPositionNdc.y;
2577
2892
  this.pointer.pressure = event.pressure ?? 0;
2578
2893
  this.pointer.tiltX = event.tiltX ?? 0;
2579
2894
  this.pointer.tiltY = event.tiltY ?? 0;
2580
2895
  }
2581
2896
  _local(event) {
2582
- const rect = this._target?.getBoundingClientRect?.();
2897
+ const rect = this.input.target.getBoundingClientRect?.();
2583
2898
  return {
2584
2899
  x: event.clientX - (rect?.left ?? 0),
2585
2900
  y: event.clientY - (rect?.top ?? 0)
2586
2901
  };
2587
2902
  }
2588
- _onPointerDown(event) {
2589
- if (event.pointerType === "touch") {
2590
- const { x, y } = this._local(event);
2591
- this.gestureRecognizer.down(event.pointerId, x, y, now());
2592
- this._setLastDevice("touch");
2593
- this._target?.setPointerCapture?.(event.pointerId);
2594
- return;
2595
- }
2903
+ _onButton(event, value) {
2904
+ if (event.pointerType === "touch") return;
2596
2905
  this._updatePointer(event);
2597
2906
  this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
2598
2907
  const button = MOUSE_BUTTONS[event.button];
2599
2908
  if (button) this._setControl(0, {
2600
2909
  type: "mouse",
2601
2910
  button
2602
- }, 1);
2603
- this._target?.setPointerCapture?.(event.pointerId);
2604
- }
2605
- _onPointerUp(event) {
2606
- if (event.pointerType === "touch") {
2607
- const { x, y } = this._local(event);
2608
- this.gestureRecognizer.up(event.pointerId, x, y, now());
2609
- return;
2610
- }
2611
- this._updatePointer(event);
2612
- const button = MOUSE_BUTTONS[event.button];
2613
- if (button) this._setControl(0, {
2614
- type: "mouse",
2615
- button
2616
- }, 0);
2617
- }
2618
- _onPointerCancel(event) {
2619
- if (event.pointerType === "touch") this.gestureRecognizer.cancel(event.pointerId);
2620
- else this._onPointerUp(event);
2911
+ }, value);
2621
2912
  }
2622
2913
  _onPointerMove(event) {
2623
- if (event.pointerType === "touch") {
2624
- const { x, y } = this._local(event);
2625
- this.gestureRecognizer.move(event.pointerId, x, y);
2626
- return;
2627
- }
2914
+ if (event.pointerType === "touch") return;
2628
2915
  this._updatePointer(event);
2629
2916
  this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
2630
2917
  this._pending.deltaX += event.movementX ?? 0;
2631
2918
  this._pending.deltaY += event.movementY ?? 0;
2632
- const button = MOUSE_BUTTONS[event.button];
2633
- if (button) {
2634
- const down = ((event.buttons ?? 0) & BUTTON_BITS[event.button]) !== 0;
2635
- this._setControl(0, {
2636
- type: "mouse",
2637
- button
2638
- }, down ? 1 : 0);
2639
- }
2919
+ }
2920
+ _onTouchDown(event) {
2921
+ const { x, y } = this._local(event);
2922
+ this.gestureRecognizer.down(event.pointerId, x, y, now());
2923
+ this._setLastDevice("touch");
2924
+ }
2925
+ _onTouchMove(event) {
2926
+ const { x, y } = this._local(event);
2927
+ this.gestureRecognizer.move(event.pointerId, x, y);
2928
+ }
2929
+ _onTouchUp(event) {
2930
+ const { x, y } = this._local(event);
2931
+ this.gestureRecognizer.up(event.pointerId, x, y, now());
2640
2932
  }
2641
2933
  _onWheel(event) {
2642
2934
  const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 800 : 1;
@@ -3701,6 +3993,7 @@ exports.DEFAULT_FONT_SIZE = DEFAULT_FONT_SIZE;
3701
3993
  exports.DEFAULT_MAP_2D_VALUE = DEFAULT_MAP_2D_VALUE;
3702
3994
  exports.DEFAULT_MAP_3D_VALUE = require_spatial_partition_3d.DEFAULT_MAP_3D_VALUE;
3703
3995
  exports.DEFAULT_PIXEL_SIZE = DEFAULT_PIXEL_SIZE;
3996
+ exports.DEFAULT_REPEAT = DEFAULT_REPEAT;
3704
3997
  exports.DEFAULT_TEXTALIGN = DEFAULT_TEXTALIGN;
3705
3998
  exports.DEFAULT_TEXTBASELINE = DEFAULT_TEXTBASELINE;
3706
3999
  exports.DEG2RAD = require_spatial_partition_3d.DEG2RAD;
@@ -3726,6 +4019,7 @@ exports.GetProgramLocations = GetProgramLocations;
3726
4019
  exports.GetUrlParams = GetUrlParams;
3727
4020
  exports.HALF_PI = require_spatial_partition_3d.HALF_PI;
3728
4021
  exports.Input = Input;
4022
+ exports.InputActionMap = InputActionMap;
3729
4023
  exports.LN10 = require_spatial_partition_3d.LN10;
3730
4024
  exports.LN2 = require_spatial_partition_3d.LN2;
3731
4025
  exports.LOG10E = require_spatial_partition_3d.LOG10E;