@gamepadly/sdk 0.2.0 → 0.4.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 (134) hide show
  1. package/README.md +163 -8
  2. package/dist/audio/index.d.ts +10 -0
  3. package/dist/audio/index.d.ts.map +1 -0
  4. package/dist/audio/index.js +15 -0
  5. package/dist/audio/index.js.map +7 -0
  6. package/dist/audio/routing.d.ts +40 -0
  7. package/dist/audio/routing.d.ts.map +1 -0
  8. package/dist/audio/routing.js +26 -0
  9. package/dist/audio/routing.js.map +7 -0
  10. package/dist/audio/sampleBank.d.ts +29 -0
  11. package/dist/audio/sampleBank.d.ts.map +1 -0
  12. package/dist/audio/sampleBank.js +354 -0
  13. package/dist/audio/sampleBank.js.map +7 -0
  14. package/dist/bridge/index.js +5 -93
  15. package/dist/bridge/index.js.map +3 -3
  16. package/dist/bridge/profiles.js +89 -0
  17. package/dist/bridge/profiles.js.map +7 -0
  18. package/dist/browser.d.ts +6 -2
  19. package/dist/browser.d.ts.map +1 -1
  20. package/dist/browser.js +2577 -53
  21. package/dist/browser.js.map +4 -4
  22. package/dist/browser.min.js +1 -1
  23. package/dist/diagnostics/circularity.d.ts +26 -0
  24. package/dist/diagnostics/circularity.d.ts.map +1 -0
  25. package/dist/diagnostics/circularity.js +56 -0
  26. package/dist/diagnostics/circularity.js.map +7 -0
  27. package/dist/diagnostics/index.d.ts +15 -0
  28. package/dist/diagnostics/index.d.ts.map +1 -0
  29. package/dist/diagnostics/index.js +31 -0
  30. package/dist/diagnostics/index.js.map +7 -0
  31. package/dist/diagnostics/stick.d.ts +73 -0
  32. package/dist/diagnostics/stick.d.ts.map +1 -0
  33. package/dist/diagnostics/stick.js +134 -0
  34. package/dist/diagnostics/stick.js.map +7 -0
  35. package/dist/diagnostics/telemetry.d.ts +65 -0
  36. package/dist/diagnostics/telemetry.d.ts.map +1 -0
  37. package/dist/diagnostics/telemetry.js +98 -0
  38. package/dist/diagnostics/telemetry.js.map +7 -0
  39. package/dist/game/host.d.ts +40 -0
  40. package/dist/game/host.d.ts.map +1 -0
  41. package/dist/game/host.js +214 -0
  42. package/dist/game/host.js.map +7 -0
  43. package/dist/game/index.d.ts +12 -0
  44. package/dist/game/index.d.ts.map +1 -0
  45. package/dist/game/index.js +27 -0
  46. package/dist/game/index.js.map +7 -0
  47. package/dist/game/mock.d.ts +35 -0
  48. package/dist/game/mock.d.ts.map +1 -0
  49. package/dist/game/mock.js +221 -0
  50. package/dist/game/mock.js.map +7 -0
  51. package/dist/game/seats.d.ts +27 -0
  52. package/dist/game/seats.d.ts.map +1 -0
  53. package/dist/game/seats.js +66 -0
  54. package/dist/game/seats.js.map +7 -0
  55. package/dist/game/types.d.ts +90 -0
  56. package/dist/game/types.d.ts.map +1 -0
  57. package/dist/game/types.js +7 -0
  58. package/dist/game/types.js.map +7 -0
  59. package/dist/haptics/presets.js +133 -0
  60. package/dist/haptics/presets.js.map +7 -0
  61. package/dist/haptics/router.d.ts +16 -0
  62. package/dist/haptics/router.d.ts.map +1 -1
  63. package/dist/haptics/router.js +146 -0
  64. package/dist/haptics/router.js.map +7 -0
  65. package/dist/haptics/samples.d.ts +68 -0
  66. package/dist/haptics/samples.d.ts.map +1 -0
  67. package/dist/haptics/samples.js +124 -0
  68. package/dist/haptics/samples.js.map +7 -0
  69. package/dist/haptics/triggerWrites.d.ts +41 -0
  70. package/dist/haptics/triggerWrites.d.ts.map +1 -0
  71. package/dist/haptics/triggerWrites.js +127 -0
  72. package/dist/haptics/triggerWrites.js.map +7 -0
  73. package/dist/hid/index.d.ts +7 -1
  74. package/dist/hid/index.d.ts.map +1 -1
  75. package/dist/{chunks/chunk-75I5NTQZ.js → hid/index.js} +35 -157
  76. package/dist/hid/index.js.map +7 -0
  77. package/dist/hub.d.ts +33 -2
  78. package/dist/hub.d.ts.map +1 -1
  79. package/dist/hub.js +474 -0
  80. package/dist/hub.js.map +7 -0
  81. package/dist/index.d.ts +12 -2
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +45 -793
  84. package/dist/index.js.map +4 -4
  85. package/dist/input/actions.js +244 -0
  86. package/dist/input/actions.js.map +7 -0
  87. package/dist/input/motion.d.ts +70 -0
  88. package/dist/input/motion.d.ts.map +1 -0
  89. package/dist/input/motion.js +175 -0
  90. package/dist/input/motion.js.map +7 -0
  91. package/dist/input/slotSwitcher.d.ts +31 -0
  92. package/dist/input/slotSwitcher.d.ts.map +1 -0
  93. package/dist/input/slotSwitcher.js +118 -0
  94. package/dist/input/slotSwitcher.js.map +7 -0
  95. package/dist/input/touchpad.d.ts +92 -0
  96. package/dist/input/touchpad.d.ts.map +1 -0
  97. package/dist/input/touchpad.js +268 -0
  98. package/dist/input/touchpad.js.map +7 -0
  99. package/dist/lifecycle.d.ts +37 -0
  100. package/dist/lifecycle.d.ts.map +1 -0
  101. package/dist/lifecycle.js +55 -0
  102. package/dist/lifecycle.js.map +7 -0
  103. package/dist/link/connect.d.ts +67 -0
  104. package/dist/link/connect.d.ts.map +1 -0
  105. package/dist/link/connect.js +123 -0
  106. package/dist/link/connect.js.map +7 -0
  107. package/dist/link/engine.d.ts +7 -1
  108. package/dist/link/engine.d.ts.map +1 -1
  109. package/dist/link/engine.js +985 -0
  110. package/dist/link/engine.js.map +7 -0
  111. package/dist/link/index.d.ts +15 -4
  112. package/dist/link/index.d.ts.map +1 -1
  113. package/dist/link/index.js +29 -958
  114. package/dist/link/index.js.map +4 -4
  115. package/dist/loop/index.js +0 -1
  116. package/dist/loop/index.js.map +1 -1
  117. package/dist/mic/blow.d.ts +72 -0
  118. package/dist/mic/blow.d.ts.map +1 -0
  119. package/dist/mic/blow.js +152 -0
  120. package/dist/mic/blow.js.map +7 -0
  121. package/dist/mic/index.d.ts +9 -0
  122. package/dist/mic/index.d.ts.map +1 -0
  123. package/dist/mic/index.js +23 -0
  124. package/dist/mic/index.js.map +7 -0
  125. package/dist/mic/input.d.ts +37 -0
  126. package/dist/mic/input.d.ts.map +1 -0
  127. package/dist/mic/input.js +109 -0
  128. package/dist/mic/input.js.map +7 -0
  129. package/dist/mic/level.d.ts +33 -0
  130. package/dist/mic/level.d.ts.map +1 -0
  131. package/dist/mic/level.js +61 -0
  132. package/dist/mic/level.js.map +7 -0
  133. package/package.json +17 -1
  134. package/dist/chunks/chunk-75I5NTQZ.js.map +0 -7
package/dist/browser.js CHANGED
@@ -310,6 +310,10 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
310
310
  get device() {
311
311
  return this.getActiveHidSession()?.device ?? null;
312
312
  }
313
+ /** WebHID device behind a slot (default: active slot), or null for Gamepad API / unknown slots. */
314
+ getHidDevice(slotId) {
315
+ return this.getHidSessionForSlot(slotId)?.device ?? null;
316
+ }
313
317
  /** Active slot's WebHID transport (or 'disconnected' when active slot is not WebHID). */
314
318
  get transport() {
315
319
  return this.getActiveHidSession()?.transport ?? "disconnected";
@@ -1008,8 +1012,10 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
1008
1012
  }
1009
1013
  /**
1010
1014
  * Disconnects a specific WebHID controller slot, or the active WebHID slot when `slotId` is omitted.
1015
+ * With `forget: true` the browser permission is revoked too (`HIDDevice.forget()`), so the controller
1016
+ * is not silently re-attached by `reconnectAuthorized()` on the next visit.
1011
1017
  */
1012
- async disconnect(slotId) {
1018
+ async disconnect(slotId, options = {}) {
1013
1019
  const targetId = slotId ?? this.activeSlotId ?? Array.from(this.hidSessions.keys())[0];
1014
1020
  if (!targetId) return;
1015
1021
  const session = this.hidSessions.get(targetId);
@@ -1047,6 +1053,11 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
1047
1053
  this.activeSlotId = remaining[0]?.id ?? null;
1048
1054
  }
1049
1055
  this.emit({ type: "disconnected", slotId: targetId });
1056
+ if (options.forget) {
1057
+ const device = session.device;
1058
+ if (typeof device.forget === "function") await device.forget().catch(() => {
1059
+ });
1060
+ }
1050
1061
  }
1051
1062
  async disconnectAll() {
1052
1063
  const ids = Array.from(this.hidSessions.keys());
@@ -1172,7 +1183,7 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
1172
1183
  }
1173
1184
  }
1174
1185
  populateGamepadInput(pad, out) {
1175
- const clamp = (v) => Math.max(-1, Math.min(1, Number.isFinite(v) ? v : 0));
1186
+ const clamp5 = (v) => Math.max(-1, Math.min(1, Number.isFinite(v) ? v : 0));
1176
1187
  const baseId = identifyGamepadFromId(pad.id || "");
1177
1188
  out.connected = true;
1178
1189
  out.source = "gamepad";
@@ -1183,10 +1194,10 @@ var DualSenseControllerManager = class _DualSenseControllerManager {
1183
1194
  transport: "unknown",
1184
1195
  source: "gamepad"
1185
1196
  };
1186
- out.lx = clamp(pad.axes[0] ?? 0);
1187
- out.ly = clamp(pad.axes[1] ?? 0);
1188
- out.rx = clamp(pad.axes[2] ?? 0);
1189
- out.ry = clamp(pad.axes[3] ?? 0);
1197
+ out.lx = clamp5(pad.axes[0] ?? 0);
1198
+ out.ly = clamp5(pad.axes[1] ?? 0);
1199
+ out.rx = clamp5(pad.axes[2] ?? 0);
1200
+ out.ry = clamp5(pad.axes[3] ?? 0);
1190
1201
  out.l2 = Math.max(0, Math.min(1, pad.buttons[6]?.value ?? 0));
1191
1202
  out.r2 = Math.max(0, Math.min(1, pad.buttons[7]?.value ?? 0));
1192
1203
  out.buttons.cross = Boolean(pad.buttons[0]?.pressed);
@@ -2043,6 +2054,127 @@ function routeTactilePreset(ctx, presetId, opts = {}) {
2043
2054
  });
2044
2055
  }
2045
2056
 
2057
+ // src/haptics/samples.ts
2058
+ var NOOP_SAMPLE_HANDLE = {
2059
+ update() {
2060
+ },
2061
+ stop() {
2062
+ },
2063
+ get active() {
2064
+ return false;
2065
+ }
2066
+ };
2067
+ function clamp(v, min, max) {
2068
+ return Math.max(min, Math.min(max, v));
2069
+ }
2070
+ function makeSeededNoise(seed) {
2071
+ let s = seed >>> 0;
2072
+ return () => {
2073
+ s = s * 1664525 + 1013904223 >>> 0;
2074
+ return s / 4294967296 * 2 - 1;
2075
+ };
2076
+ }
2077
+ function createTactileBuffer(preset, sampleRate = 48e3) {
2078
+ const sr = Math.max(8e3, Math.round(sampleRate));
2079
+ const noise = makeSeededNoise(preset.length * 9973 + 1337);
2080
+ const durationSec = {
2081
+ footstep_ice: 0.09,
2082
+ footstep_metal: 0.14,
2083
+ footstep_gravel: 0.11,
2084
+ footstep_water: 0.16,
2085
+ zipper_tick: 0.032,
2086
+ spring_boing: 0.28,
2087
+ engine_hum: 0.5
2088
+ };
2089
+ const len = Math.max(64, Math.round(durationSec[preset] * sr));
2090
+ const spkL = new Float32Array(len);
2091
+ const spkR = new Float32Array(len);
2092
+ const vcmL = new Float32Array(len);
2093
+ const vcmR = new Float32Array(len);
2094
+ let lp = 0;
2095
+ let phaseVcm = 0;
2096
+ let phaseSpk = 0;
2097
+ for (let i = 0; i < len; i++) {
2098
+ const t = i / sr;
2099
+ const u = i / len;
2100
+ const rawN = noise();
2101
+ lp = lp * 0.72 + rawN * 0.28;
2102
+ let spk = 0;
2103
+ let vcm = 0;
2104
+ switch (preset) {
2105
+ case "footstep_ice": {
2106
+ const env = Math.pow(1 - u, 2.2) * Math.min(1, t / 3e-3);
2107
+ phaseVcm += 2 * Math.PI * (240 - u * 90) / sr;
2108
+ phaseSpk += 2 * Math.PI * (2400 - u * 950) / sr;
2109
+ vcm = (Math.sin(phaseVcm) * 0.65 + (rawN - lp) * 0.45) * env;
2110
+ spk = (Math.sin(phaseSpk) * 0.45 + (rawN - lp) * 0.65) * env;
2111
+ break;
2112
+ }
2113
+ case "footstep_metal": {
2114
+ const envVcm = Math.pow(1 - u, 1.8) * Math.min(1, t / 2e-3);
2115
+ const envSpk = Math.pow(1 - u, 1.4) * Math.min(1, t / 2e-3);
2116
+ phaseVcm += 2 * Math.PI * (148 - u * 35) / sr;
2117
+ phaseSpk += 2 * Math.PI * 1380 / sr;
2118
+ vcm = (Math.sin(phaseVcm) * 0.78 + Math.sin(phaseVcm * 2.13) * 0.22) * envVcm;
2119
+ spk = (Math.sin(phaseSpk) * 0.55 + Math.sin(phaseSpk * 1.47) * 0.35 + (rawN - lp) * 0.2) * envSpk;
2120
+ break;
2121
+ }
2122
+ case "footstep_gravel": {
2123
+ const env = Math.pow(1 - u, 1.9) * Math.min(1, t / 4e-3);
2124
+ const grain = 0.55 + 0.45 * Math.sin(2 * Math.PI * 62 * t);
2125
+ phaseVcm += 2 * Math.PI * (118 + lp * 40) / sr;
2126
+ vcm = (Math.sin(phaseVcm) * 0.5 + lp * 0.65) * grain * env;
2127
+ spk = (rawN * 0.72 + lp * 0.28) * grain * env;
2128
+ break;
2129
+ }
2130
+ case "footstep_water": {
2131
+ const env = Math.sin(Math.PI * Math.pow(u, 0.7)) * (1 - u * 0.35);
2132
+ phaseVcm += 2 * Math.PI * (78 - u * 32) / sr;
2133
+ phaseSpk += 2 * Math.PI * (520 + u * 640) / sr;
2134
+ vcm = (Math.sin(phaseVcm) * 0.75 + lp * 0.35) * env;
2135
+ spk = (Math.sin(phaseSpk) * 0.35 + lp * 0.6) * env;
2136
+ break;
2137
+ }
2138
+ case "zipper_tick": {
2139
+ const env = Math.pow(1 - u, 2.8) * Math.min(1, t / 15e-4);
2140
+ phaseVcm += 2 * Math.PI * (260 - u * 110) / sr;
2141
+ phaseSpk += 2 * Math.PI * (2850 - u * 900) / sr;
2142
+ vcm = Math.sin(phaseVcm) * env;
2143
+ spk = (Math.sin(phaseSpk) * 0.7 + (rawN - lp) * 0.3) * env;
2144
+ break;
2145
+ }
2146
+ case "spring_boing": {
2147
+ const env = Math.pow(1 - u, 1.35) * Math.min(1, t / 4e-3);
2148
+ const wobble = Math.sin(2 * Math.PI * 19 * t);
2149
+ phaseVcm += 2 * Math.PI * (68 + u * 115 + wobble * 18) / sr;
2150
+ phaseSpk += 2 * Math.PI * (260 + u * 540 + wobble * 45) / sr;
2151
+ vcm = Math.sin(phaseVcm) * env * 0.92;
2152
+ spk = Math.sin(phaseSpk) * env * 0.78;
2153
+ break;
2154
+ }
2155
+ case "engine_hum": {
2156
+ const fBase = 48;
2157
+ const w1 = Math.sin(2 * Math.PI * fBase * t);
2158
+ const w2 = Math.sin(2 * Math.PI * (fBase * 2) * t) * 0.45;
2159
+ const w3 = Math.sin(2 * Math.PI * (fBase * 3) * t) * 0.22;
2160
+ vcm = (w1 + w2 + w3) * 0.58;
2161
+ spk = (w2 * 0.5 + w3 * 0.5) * 0.35;
2162
+ break;
2163
+ }
2164
+ }
2165
+ const sClamped = clamp(spk, -0.95, 0.95);
2166
+ const vClamped = clamp(vcm, -0.95, 0.95);
2167
+ spkL[i] = sClamped;
2168
+ spkR[i] = sClamped;
2169
+ vcmL[i] = vClamped;
2170
+ vcmR[i] = vClamped;
2171
+ }
2172
+ return {
2173
+ sampleRate: sr,
2174
+ channels: [spkL, spkR, vcmL, vcmR]
2175
+ };
2176
+ }
2177
+
2046
2178
  // src/input/actions.ts
2047
2179
  var BUTTON_NAMES = /* @__PURE__ */ new Set([
2048
2180
  "cross",
@@ -2284,6 +2416,739 @@ function createActionTracker(spec) {
2284
2416
  };
2285
2417
  }
2286
2418
 
2419
+ // src/input/motion.ts
2420
+ function clamp2(v, min, max) {
2421
+ return Math.max(min, Math.min(max, v));
2422
+ }
2423
+ function createMotionTracker(options = {}) {
2424
+ const gyroWeight = clamp2(options.gyroWeight ?? 0.94, 0, 0.995);
2425
+ const gyroScale = Math.max(0.5, options.gyroScaleRadPerSec ?? 4.5);
2426
+ const fullTiltRad = Math.max(0.2, options.fullTiltRad ?? Math.PI / 4);
2427
+ const flickThreshold = Math.max(0.15, options.flickThreshold ?? 0.62);
2428
+ const flickCooldownMs = Math.max(80, options.flickCooldownMs ?? 320);
2429
+ const shakeDecay = Math.max(0.2, options.shakeDecay ?? 2.4);
2430
+ const shakeThreshold = clamp2(options.shakeThreshold ?? 0.35, 0.05, 0.95);
2431
+ let initialized = false;
2432
+ let active = false;
2433
+ let rawPitch = 0;
2434
+ let rawRoll = 0;
2435
+ let rawYaw = 0;
2436
+ let zeroPitch = 0;
2437
+ let zeroRoll = 0;
2438
+ let zeroYaw = 0;
2439
+ let gravX = 0;
2440
+ let gravY = 1;
2441
+ let gravZ = 0;
2442
+ let shakeIntensity = 0;
2443
+ let lastFlickAt = -1e9;
2444
+ let lastNowMs = 0;
2445
+ const state = {
2446
+ active: false,
2447
+ pitch: 0,
2448
+ roll: 0,
2449
+ yaw: 0,
2450
+ pitchNorm: 0,
2451
+ rollNorm: 0,
2452
+ angularSpeed: 0,
2453
+ linearAccelDelta: 0,
2454
+ shakeIntensity: 0,
2455
+ shaking: false,
2456
+ justFlicked: false,
2457
+ flickDirection: "none"
2458
+ };
2459
+ function writePose() {
2460
+ const pitch = clamp2(rawPitch - zeroPitch, -Math.PI / 2, Math.PI / 2);
2461
+ const roll = clamp2(rawRoll - zeroRoll, -Math.PI / 2, Math.PI / 2);
2462
+ const yaw = rawYaw - zeroYaw;
2463
+ state.active = active;
2464
+ state.pitch = pitch;
2465
+ state.roll = roll;
2466
+ state.yaw = yaw;
2467
+ state.pitchNorm = clamp2(pitch / fullTiltRad, -1, 1);
2468
+ state.rollNorm = clamp2(roll / fullTiltRad, -1, 1);
2469
+ }
2470
+ return {
2471
+ update(input, dtSec, nowMs = typeof performance !== "undefined" ? performance.now() : Date.now()) {
2472
+ const dt = dtSec !== void 0 ? clamp2(dtSec, 1e-3, 0.1) : lastNowMs > 0 ? clamp2((nowMs - lastNowMs) / 1e3, 1e-3, 0.1) : 1 / 60;
2473
+ lastNowMs = nowMs;
2474
+ const { gx, gy, gz, ax, ay, az } = {
2475
+ gx: input.gyro.x,
2476
+ gy: input.gyro.y,
2477
+ gz: input.gyro.z,
2478
+ ax: input.accel.x,
2479
+ ay: input.accel.y,
2480
+ az: input.accel.z
2481
+ };
2482
+ const accelMag = Math.hypot(ax, ay, az);
2483
+ const angularSpeed = Math.hypot(gx, gy, gz);
2484
+ const hasSignal = input.connected && (accelMag > 0.02 || angularSpeed > 2e-3);
2485
+ if (!hasSignal) {
2486
+ active = false;
2487
+ shakeIntensity = Math.max(0, shakeIntensity - shakeDecay * dt);
2488
+ state.active = false;
2489
+ state.angularSpeed = 0;
2490
+ state.linearAccelDelta = 0;
2491
+ state.shakeIntensity = shakeIntensity;
2492
+ state.shaking = shakeIntensity >= shakeThreshold;
2493
+ state.justFlicked = false;
2494
+ state.flickDirection = "none";
2495
+ return state;
2496
+ }
2497
+ active = true;
2498
+ const accelRoll = Math.atan2(-ax, Math.hypot(ay, az) || 1e-4);
2499
+ const accelPitch = Math.atan2(az, Math.hypot(ax, ay) || 1e-4);
2500
+ if (!initialized) {
2501
+ initialized = true;
2502
+ rawPitch = accelPitch;
2503
+ rawRoll = accelRoll;
2504
+ rawYaw = 0;
2505
+ gravX = ax;
2506
+ gravY = ay;
2507
+ gravZ = az;
2508
+ } else {
2509
+ const alpha = accelMag > 0.45 && accelMag < 1.65 ? gyroWeight : 0.99;
2510
+ rawPitch = alpha * (rawPitch + gx * gyroScale * dt) + (1 - alpha) * accelPitch;
2511
+ rawRoll = alpha * (rawRoll + gz * gyroScale * dt) + (1 - alpha) * accelRoll;
2512
+ const yawRate = Math.abs(gy) > 0.012 ? gy : 0;
2513
+ rawYaw += yawRate * gyroScale * dt;
2514
+ }
2515
+ const gravAlpha = 0.84;
2516
+ gravX = gravAlpha * gravX + (1 - gravAlpha) * ax;
2517
+ gravY = gravAlpha * gravY + (1 - gravAlpha) * ay;
2518
+ gravZ = gravAlpha * gravZ + (1 - gravAlpha) * az;
2519
+ const linX = ax - gravX;
2520
+ const linY = ay - gravY;
2521
+ const linZ = az - gravZ;
2522
+ const linearDelta = Math.hypot(linX, linY, linZ);
2523
+ const rawAgitation = clamp2((linearDelta * 1.15 + angularSpeed * 0.72 - 0.12) * 1.35, 0, 1);
2524
+ if (rawAgitation > shakeIntensity) {
2525
+ shakeIntensity = Math.min(1, shakeIntensity + (rawAgitation - shakeIntensity) * Math.min(1, dt * 16));
2526
+ } else {
2527
+ shakeIntensity = Math.max(0, shakeIntensity - shakeDecay * dt);
2528
+ }
2529
+ const flickImpulse = angularSpeed * 0.85 + linearDelta * 0.55;
2530
+ let justFlicked = false;
2531
+ let flickDirection = "none";
2532
+ if (flickImpulse >= flickThreshold && nowMs - lastFlickAt >= flickCooldownMs) {
2533
+ lastFlickAt = nowMs;
2534
+ justFlicked = true;
2535
+ const absPitch = Math.abs(gx) + Math.abs(linY) * 0.6;
2536
+ const absSide = Math.abs(gy) + Math.abs(gz) * 0.7 + Math.abs(linX) * 0.6;
2537
+ if (absPitch >= absSide) {
2538
+ flickDirection = gx + linY * 0.5 >= 0 ? "up" : "down";
2539
+ } else {
2540
+ flickDirection = gy + gz * 0.5 - linX * 0.4 >= 0 ? "right" : "left";
2541
+ }
2542
+ }
2543
+ writePose();
2544
+ state.angularSpeed = angularSpeed;
2545
+ state.linearAccelDelta = linearDelta;
2546
+ state.shakeIntensity = shakeIntensity;
2547
+ state.shaking = shakeIntensity >= shakeThreshold;
2548
+ state.justFlicked = justFlicked;
2549
+ state.flickDirection = flickDirection;
2550
+ return state;
2551
+ },
2552
+ getState() {
2553
+ return state;
2554
+ },
2555
+ recenter() {
2556
+ zeroPitch = rawPitch;
2557
+ zeroRoll = rawRoll;
2558
+ zeroYaw = rawYaw;
2559
+ writePose();
2560
+ },
2561
+ reset() {
2562
+ initialized = false;
2563
+ active = false;
2564
+ rawPitch = 0;
2565
+ rawRoll = 0;
2566
+ rawYaw = 0;
2567
+ zeroPitch = 0;
2568
+ zeroRoll = 0;
2569
+ zeroYaw = 0;
2570
+ gravX = 0;
2571
+ gravY = 1;
2572
+ gravZ = 0;
2573
+ shakeIntensity = 0;
2574
+ lastFlickAt = -1e9;
2575
+ lastNowMs = 0;
2576
+ state.active = false;
2577
+ state.pitch = 0;
2578
+ state.roll = 0;
2579
+ state.yaw = 0;
2580
+ state.pitchNorm = 0;
2581
+ state.rollNorm = 0;
2582
+ state.angularSpeed = 0;
2583
+ state.linearAccelDelta = 0;
2584
+ state.shakeIntensity = 0;
2585
+ state.shaking = false;
2586
+ state.justFlicked = false;
2587
+ state.flickDirection = "none";
2588
+ }
2589
+ };
2590
+ }
2591
+
2592
+ // src/input/touchpad.ts
2593
+ function clamp3(v, min, max) {
2594
+ return Math.max(min, Math.min(max, v));
2595
+ }
2596
+ function createTouchpadGestures(options = {}) {
2597
+ const tapMaxMs = Math.max(40, options.tapMaxMs ?? 240);
2598
+ const tapMaxMove = Math.max(0.01, options.tapMaxMove ?? 0.06);
2599
+ const doubleTapWindowMs = Math.max(100, options.doubleTapWindowMs ?? 320);
2600
+ const swipeMinSpeed = Math.max(0.2, options.swipeMinSpeed ?? 1.15);
2601
+ const swipeMinDistance = Math.max(0.03, options.swipeMinDistance ?? 0.12);
2602
+ const velAlpha = clamp3(options.velocitySmoothing ?? 0.45, 0.05, 1);
2603
+ let prev1Active = false;
2604
+ let prev1X = 0.5;
2605
+ let prev1Y = 0.5;
2606
+ let start1X = 0.5;
2607
+ let start1Y = 0.5;
2608
+ let start1At = 0;
2609
+ let maxMove1 = 0;
2610
+ let hadSecondDuringTouch = false;
2611
+ let lastTapAt = -1e9;
2612
+ let lastTapX = 0.5;
2613
+ let lastTapY = 0.5;
2614
+ let prev2Active = false;
2615
+ let prev2X = 0.5;
2616
+ let prev2Y = 0.5;
2617
+ let start2At = 0;
2618
+ let maxMove2 = 0;
2619
+ let start2X = 0.5;
2620
+ let start2Y = 0.5;
2621
+ let prevPinchActive = false;
2622
+ let startPinchDist = 0;
2623
+ let prevPinchDist = 0;
2624
+ let prevClicked = false;
2625
+ let lastNowMs = 0;
2626
+ let vx = 0;
2627
+ let vy = 0;
2628
+ const state = {
2629
+ fingerCount: 0,
2630
+ active: false,
2631
+ x: 0.5,
2632
+ y: 0.5,
2633
+ justTouched: false,
2634
+ justReleased: false,
2635
+ dx: 0,
2636
+ dy: 0,
2637
+ totalDx: 0,
2638
+ totalDy: 0,
2639
+ vx: 0,
2640
+ vy: 0,
2641
+ speed: 0,
2642
+ justTapped: false,
2643
+ justDoubleTapped: false,
2644
+ justTwoFingerTapped: false,
2645
+ justSwiped: false,
2646
+ swipeDirection: "none",
2647
+ pinchActive: false,
2648
+ pinchDistance: 0,
2649
+ pinchDelta: 0,
2650
+ pinchScale: 1,
2651
+ secondFinger: {
2652
+ active: false,
2653
+ justTouched: false,
2654
+ justReleased: false,
2655
+ x: 0.5,
2656
+ y: 0.5,
2657
+ dx: 0,
2658
+ dy: 0
2659
+ },
2660
+ clicked: false,
2661
+ justClicked: false
2662
+ };
2663
+ return {
2664
+ update(input, dtSec, nowMs = typeof performance !== "undefined" ? performance.now() : Date.now()) {
2665
+ const dt = dtSec !== void 0 ? clamp3(dtSec, 1e-3, 0.1) : lastNowMs > 0 ? clamp3((nowMs - lastNowMs) / 1e3, 1e-3, 0.1) : 1 / 60;
2666
+ lastNowMs = nowMs;
2667
+ const t1Active = Boolean(input.connected && input.touch.active);
2668
+ const t2Active = Boolean(input.connected && input.touch2.active);
2669
+ const t1X = clamp3(input.touch.x, 0, 1);
2670
+ const t1Y = clamp3(input.touch.y, 0, 1);
2671
+ const t2X = clamp3(input.touch2.x, 0, 1);
2672
+ const t2Y = clamp3(input.touch2.y, 0, 1);
2673
+ const justTouched1 = t1Active && !prev1Active;
2674
+ const justReleased1 = !t1Active && prev1Active;
2675
+ const justTouched2 = t2Active && !prev2Active;
2676
+ const justReleased2 = !t2Active && prev2Active;
2677
+ let dx1 = 0;
2678
+ let dy1 = 0;
2679
+ let justTapped = false;
2680
+ let justDoubleTapped = false;
2681
+ let justTwoFingerTapped = false;
2682
+ let justSwiped = false;
2683
+ let swipeDirection = "none";
2684
+ if (justTouched1) {
2685
+ start1X = t1X;
2686
+ start1Y = t1Y;
2687
+ start1At = nowMs;
2688
+ maxMove1 = 0;
2689
+ hadSecondDuringTouch = t2Active;
2690
+ vx = 0;
2691
+ vy = 0;
2692
+ } else if (t1Active) {
2693
+ dx1 = t1X - prev1X;
2694
+ dy1 = t1Y - prev1Y;
2695
+ if (t2Active) hadSecondDuringTouch = true;
2696
+ const distFromStart = Math.hypot(t1X - start1X, t1Y - start1Y);
2697
+ if (distFromStart > maxMove1) maxMove1 = distFromStart;
2698
+ const instVx = dx1 / dt;
2699
+ const instVy = dy1 / dt;
2700
+ vx = vx * (1 - velAlpha) + instVx * velAlpha;
2701
+ vy = vy * (1 - velAlpha) + instVy * velAlpha;
2702
+ } else if (justReleased1) {
2703
+ const heldMs = nowMs - start1At;
2704
+ const totalDist = Math.hypot(prev1X - start1X, prev1Y - start1Y);
2705
+ const speed = Math.hypot(vx, vy);
2706
+ if (heldMs <= tapMaxMs && maxMove1 <= tapMaxMove && !hadSecondDuringTouch) {
2707
+ justTapped = true;
2708
+ if (nowMs - lastTapAt <= doubleTapWindowMs && Math.hypot(prev1X - lastTapX, prev1Y - lastTapY) <= tapMaxMove * 2.5) {
2709
+ justDoubleTapped = true;
2710
+ lastTapAt = -1e9;
2711
+ } else {
2712
+ lastTapAt = nowMs;
2713
+ lastTapX = prev1X;
2714
+ lastTapY = prev1Y;
2715
+ }
2716
+ } else if (!hadSecondDuringTouch && speed >= swipeMinSpeed && totalDist >= swipeMinDistance) {
2717
+ justSwiped = true;
2718
+ const totalDx = prev1X - start1X;
2719
+ const totalDy = prev1Y - start1Y;
2720
+ if (Math.abs(totalDx) >= Math.abs(totalDy)) {
2721
+ swipeDirection = totalDx >= 0 ? "right" : "left";
2722
+ } else {
2723
+ swipeDirection = totalDy >= 0 ? "down" : "up";
2724
+ }
2725
+ }
2726
+ } else {
2727
+ vx = 0;
2728
+ vy = 0;
2729
+ }
2730
+ let dx2 = 0;
2731
+ let dy2 = 0;
2732
+ if (justTouched2) {
2733
+ start2X = t2X;
2734
+ start2Y = t2Y;
2735
+ start2At = nowMs;
2736
+ maxMove2 = 0;
2737
+ } else if (t2Active) {
2738
+ dx2 = t2X - prev2X;
2739
+ dy2 = t2Y - prev2Y;
2740
+ const d2 = Math.hypot(t2X - start2X, t2Y - start2Y);
2741
+ if (d2 > maxMove2) maxMove2 = d2;
2742
+ }
2743
+ if (justReleased2 && prev1Active && nowMs - start2At <= tapMaxMs && maxMove2 <= tapMaxMove && maxMove1 <= tapMaxMove || justReleased1 && justReleased2 && nowMs - start1At <= tapMaxMs && nowMs - start2At <= tapMaxMs && maxMove1 <= tapMaxMove && maxMove2 <= tapMaxMove) {
2744
+ justTwoFingerTapped = true;
2745
+ }
2746
+ const pinchActive = t1Active && t2Active;
2747
+ let pinchDistance = 0;
2748
+ let pinchDelta = 0;
2749
+ let pinchScale = 1;
2750
+ if (pinchActive) {
2751
+ pinchDistance = Math.hypot(t2X - t1X, t2Y - t1Y);
2752
+ if (!prevPinchActive) {
2753
+ startPinchDist = Math.max(0.02, pinchDistance);
2754
+ prevPinchDist = pinchDistance;
2755
+ pinchDelta = 0;
2756
+ pinchScale = 1;
2757
+ } else {
2758
+ pinchDelta = pinchDistance - prevPinchDist;
2759
+ pinchScale = pinchDistance / Math.max(0.02, startPinchDist);
2760
+ prevPinchDist = pinchDistance;
2761
+ }
2762
+ } else {
2763
+ startPinchDist = 0;
2764
+ prevPinchDist = 0;
2765
+ }
2766
+ const clicked = Boolean(input.connected && input.buttons.touchpadClick);
2767
+ const justClicked = clicked && !prevClicked;
2768
+ prev1Active = t1Active;
2769
+ if (t1Active) {
2770
+ prev1X = t1X;
2771
+ prev1Y = t1Y;
2772
+ }
2773
+ prev2Active = t2Active;
2774
+ if (t2Active) {
2775
+ prev2X = t2X;
2776
+ prev2Y = t2Y;
2777
+ }
2778
+ prevPinchActive = pinchActive;
2779
+ prevClicked = clicked;
2780
+ const fingerCount = t1Active && t2Active ? 2 : t1Active || t2Active ? 1 : 0;
2781
+ state.fingerCount = fingerCount;
2782
+ state.active = t1Active;
2783
+ state.x = t1Active ? t1X : prev1X;
2784
+ state.y = t1Active ? t1Y : prev1Y;
2785
+ state.justTouched = justTouched1;
2786
+ state.justReleased = justReleased1;
2787
+ state.dx = dx1;
2788
+ state.dy = dy1;
2789
+ state.totalDx = t1Active ? t1X - start1X : 0;
2790
+ state.totalDy = t1Active ? t1Y - start1Y : 0;
2791
+ state.vx = t1Active || justReleased1 ? vx : 0;
2792
+ state.vy = t1Active || justReleased1 ? vy : 0;
2793
+ state.speed = Math.hypot(state.vx, state.vy);
2794
+ state.justTapped = justTapped;
2795
+ state.justDoubleTapped = justDoubleTapped;
2796
+ state.justTwoFingerTapped = justTwoFingerTapped;
2797
+ state.justSwiped = justSwiped;
2798
+ state.swipeDirection = swipeDirection;
2799
+ state.pinchActive = pinchActive;
2800
+ state.pinchDistance = pinchDistance;
2801
+ state.pinchDelta = pinchDelta;
2802
+ state.pinchScale = pinchScale;
2803
+ state.secondFinger.active = t2Active;
2804
+ state.secondFinger.justTouched = justTouched2;
2805
+ state.secondFinger.justReleased = justReleased2;
2806
+ state.secondFinger.x = t2Active ? t2X : prev2X;
2807
+ state.secondFinger.y = t2Active ? t2Y : prev2Y;
2808
+ state.secondFinger.dx = dx2;
2809
+ state.secondFinger.dy = dy2;
2810
+ state.clicked = clicked;
2811
+ state.justClicked = justClicked;
2812
+ return state;
2813
+ },
2814
+ getState() {
2815
+ return state;
2816
+ },
2817
+ reset() {
2818
+ prev1Active = false;
2819
+ prev2Active = false;
2820
+ prevPinchActive = false;
2821
+ prevClicked = false;
2822
+ hadSecondDuringTouch = false;
2823
+ lastTapAt = -1e9;
2824
+ lastNowMs = 0;
2825
+ vx = 0;
2826
+ vy = 0;
2827
+ state.fingerCount = 0;
2828
+ state.active = false;
2829
+ state.justTouched = false;
2830
+ state.justReleased = false;
2831
+ state.dx = 0;
2832
+ state.dy = 0;
2833
+ state.totalDx = 0;
2834
+ state.totalDy = 0;
2835
+ state.vx = 0;
2836
+ state.vy = 0;
2837
+ state.speed = 0;
2838
+ state.justTapped = false;
2839
+ state.justDoubleTapped = false;
2840
+ state.justTwoFingerTapped = false;
2841
+ state.justSwiped = false;
2842
+ state.swipeDirection = "none";
2843
+ state.pinchActive = false;
2844
+ state.pinchDistance = 0;
2845
+ state.pinchDelta = 0;
2846
+ state.pinchScale = 1;
2847
+ state.secondFinger.active = false;
2848
+ state.secondFinger.justTouched = false;
2849
+ state.secondFinger.justReleased = false;
2850
+ state.secondFinger.dx = 0;
2851
+ state.secondFinger.dy = 0;
2852
+ state.clicked = false;
2853
+ state.justClicked = false;
2854
+ }
2855
+ };
2856
+ }
2857
+
2858
+ // src/input/slotSwitcher.ts
2859
+ var STICK_DELTA_THRESHOLD = 0.22;
2860
+ var STICK_MIN_MAGNITUDE = 0.25;
2861
+ var TRIGGER_DELTA_THRESHOLD = 0.25;
2862
+ var TRIGGER_MIN_VALUE = 0.25;
2863
+ var SWITCH_COOLDOWN_MS = 280;
2864
+ var SlotAutoSwitcher = class {
2865
+ anchors = /* @__PURE__ */ new Map();
2866
+ cooldownUntil = 0;
2867
+ notifyManualSelect(samples, now) {
2868
+ this.reanchorAll(samples);
2869
+ this.cooldownUntil = now + SWITCH_COOLDOWN_MS;
2870
+ }
2871
+ evaluate(samples, activeSlotId, now) {
2872
+ const liveIds = new Set(samples.map((s) => s.id));
2873
+ for (const id of this.anchors.keys()) {
2874
+ if (!liveIds.has(id)) this.anchors.delete(id);
2875
+ }
2876
+ if (samples.length === 0) {
2877
+ return { switchTo: null, triggeredSlotId: null };
2878
+ }
2879
+ let bestSwitchId = null;
2880
+ let bestSwitchScore = 0;
2881
+ let triggeredSlotId = null;
2882
+ for (const sample of samples) {
2883
+ const prev = this.anchors.get(sample.id);
2884
+ if (!prev) {
2885
+ this.anchors.set(sample.id, toAnchor(sample));
2886
+ continue;
2887
+ }
2888
+ const buttonPressed = sample.lastActivityAt > prev.lastActivityAt;
2889
+ const leftMag = Math.hypot(sample.lx, sample.ly);
2890
+ const leftDelta = Math.hypot(sample.lx - prev.lx, sample.ly - prev.ly);
2891
+ const rightMag = Math.hypot(sample.rx, sample.ry);
2892
+ const rightDelta = Math.hypot(sample.rx - prev.rx, sample.ry - prev.ry);
2893
+ const leftPush = leftMag >= STICK_MIN_MAGNITUDE && leftDelta >= STICK_DELTA_THRESHOLD;
2894
+ const rightPush = rightMag >= STICK_MIN_MAGNITUDE && rightDelta >= STICK_DELTA_THRESHOLD;
2895
+ const l2Push = sample.l2 >= TRIGGER_MIN_VALUE && sample.l2 - prev.l2 >= TRIGGER_DELTA_THRESHOLD;
2896
+ const r2Push = sample.r2 >= TRIGGER_MIN_VALUE && sample.r2 - prev.r2 >= TRIGGER_DELTA_THRESHOLD;
2897
+ const hasIntentionalInput = buttonPressed || leftPush || rightPush || l2Push || r2Push;
2898
+ if (sample.id === activeSlotId || samples.length === 1) {
2899
+ if (hasIntentionalInput) {
2900
+ triggeredSlotId = sample.id;
2901
+ this.anchors.set(sample.id, toAnchor(sample));
2902
+ } else {
2903
+ relaxAnchorTowardCenter(prev, sample, leftMag, rightMag);
2904
+ }
2905
+ continue;
2906
+ }
2907
+ if (now < this.cooldownUntil) {
2908
+ if (!hasIntentionalInput) {
2909
+ relaxAnchorTowardCenter(prev, sample, leftMag, rightMag);
2910
+ }
2911
+ continue;
2912
+ }
2913
+ if (buttonPressed) {
2914
+ const score = 10 + (sample.lastActivityAt - prev.lastActivityAt) * 1e-6;
2915
+ if (score > bestSwitchScore) {
2916
+ bestSwitchScore = score;
2917
+ bestSwitchId = sample.id;
2918
+ }
2919
+ } else if (leftPush || rightPush || l2Push || r2Push) {
2920
+ const score = Math.max(
2921
+ leftPush ? leftDelta : 0,
2922
+ rightPush ? rightDelta : 0,
2923
+ l2Push ? sample.l2 - prev.l2 : 0,
2924
+ r2Push ? sample.r2 - prev.r2 : 0
2925
+ );
2926
+ if (score > bestSwitchScore) {
2927
+ bestSwitchScore = score;
2928
+ bestSwitchId = sample.id;
2929
+ }
2930
+ } else {
2931
+ relaxAnchorTowardCenter(prev, sample, leftMag, rightMag);
2932
+ }
2933
+ }
2934
+ if (bestSwitchId) {
2935
+ this.reanchorAll(samples);
2936
+ this.cooldownUntil = now + SWITCH_COOLDOWN_MS;
2937
+ return { switchTo: bestSwitchId, triggeredSlotId: bestSwitchId };
2938
+ }
2939
+ return { switchTo: null, triggeredSlotId };
2940
+ }
2941
+ detectTargetSlot(samples, activeSlotId, now) {
2942
+ return this.evaluate(samples, activeSlotId, now).switchTo;
2943
+ }
2944
+ reanchorAll(samples) {
2945
+ for (const s of samples) {
2946
+ this.anchors.set(s.id, toAnchor(s));
2947
+ }
2948
+ }
2949
+ };
2950
+ function relaxAnchorTowardCenter(prev, sample, leftMag, rightMag) {
2951
+ if (leftMag < Math.hypot(prev.lx, prev.ly)) {
2952
+ prev.lx = sample.lx;
2953
+ prev.ly = sample.ly;
2954
+ }
2955
+ if (rightMag < Math.hypot(prev.rx, prev.ry)) {
2956
+ prev.rx = sample.rx;
2957
+ prev.ry = sample.ry;
2958
+ }
2959
+ if (sample.l2 < prev.l2) prev.l2 = sample.l2;
2960
+ if (sample.r2 < prev.r2) prev.r2 = sample.r2;
2961
+ }
2962
+ function toAnchor(s) {
2963
+ return {
2964
+ lastActivityAt: s.lastActivityAt,
2965
+ lx: s.lx,
2966
+ ly: s.ly,
2967
+ rx: s.rx,
2968
+ ry: s.ry,
2969
+ l2: s.l2,
2970
+ r2: s.r2
2971
+ };
2972
+ }
2973
+
2974
+ // src/haptics/triggerWrites.ts
2975
+ var TriggerFeedbackController = class {
2976
+ mounted = true;
2977
+ confirmedLeft = "off";
2978
+ confirmedRight = "off";
2979
+ pendingLeftSeq = 0;
2980
+ pendingRightSeq = 0;
2981
+ inFlightNonOff = 0;
2982
+ uncertainTriggerState = false;
2983
+ rumbleActive = false;
2984
+ get leftPreset() {
2985
+ return this.confirmedLeft;
2986
+ }
2987
+ get rightPreset() {
2988
+ return this.confirmedRight;
2989
+ }
2990
+ get hasActiveTrigger() {
2991
+ return this.confirmedLeft !== "off" || this.confirmedRight !== "off" || this.inFlightNonOff > 0 || this.uncertainTriggerState;
2992
+ }
2993
+ get needsCleanup() {
2994
+ return this.hasActiveTrigger || this.rumbleActive;
2995
+ }
2996
+ markMounted() {
2997
+ this.mounted = true;
2998
+ }
2999
+ markRumbleActive() {
3000
+ this.rumbleActive = true;
3001
+ }
3002
+ async applyPreset(hid, target, presetId, spec) {
3003
+ const isOff = presetId === "off";
3004
+ const hadActiveBefore = this.hasActiveTrigger;
3005
+ const hadActiveTargetBefore = this.uncertainTriggerState || (target === "left" ? this.confirmedLeft !== "off" : target === "right" ? this.confirmedRight !== "off" : this.confirmedLeft !== "off" || this.confirmedRight !== "off");
3006
+ const leftSeq = target === "left" || target === "both" ? ++this.pendingLeftSeq : 0;
3007
+ const rightSeq = target === "right" || target === "both" ? ++this.pendingRightSeq : 0;
3008
+ if (!isOff) {
3009
+ this.inFlightNonOff += 1;
3010
+ }
3011
+ let ok = false;
3012
+ let threw = false;
3013
+ try {
3014
+ if (target === "both") {
3015
+ ok = await hid.setTriggers(spec, spec);
3016
+ } else if (target === "left") {
3017
+ ok = await hid.setTriggers(spec, void 0);
3018
+ } else {
3019
+ ok = await hid.setTriggers(void 0, spec);
3020
+ }
3021
+ } catch {
3022
+ ok = false;
3023
+ threw = true;
3024
+ } finally {
3025
+ if (!isOff) {
3026
+ this.inFlightNonOff = Math.max(0, this.inFlightNonOff - 1);
3027
+ }
3028
+ }
3029
+ const leftIsLatest = target === "right" || leftSeq === this.pendingLeftSeq;
3030
+ const rightIsLatest = target === "left" || rightSeq === this.pendingRightSeq;
3031
+ const stale = !(leftIsLatest && rightIsLatest);
3032
+ if (!this.mounted) {
3033
+ if (!isOff && (ok || threw) || isOff && !ok && hadActiveBefore) {
3034
+ void hid.resetTriggers().catch(() => {
3035
+ });
3036
+ }
3037
+ return {
3038
+ ok,
3039
+ stale,
3040
+ unmounted: true,
3041
+ hadActiveBefore,
3042
+ hadActiveTargetBefore,
3043
+ leftPreset: this.confirmedLeft,
3044
+ rightPreset: this.confirmedRight,
3045
+ needsReset: this.needsCleanup
3046
+ };
3047
+ }
3048
+ if (ok) {
3049
+ if (stale) {
3050
+ if (!isOff) {
3051
+ this.uncertainTriggerState = true;
3052
+ }
3053
+ } else {
3054
+ if (target === "left" || target === "both") this.confirmedLeft = presetId;
3055
+ if (target === "right" || target === "both") this.confirmedRight = presetId;
3056
+ if (this.confirmedLeft === "off" && this.confirmedRight === "off" && this.inFlightNonOff === 0) {
3057
+ this.uncertainTriggerState = false;
3058
+ }
3059
+ }
3060
+ } else if (threw && !isOff) {
3061
+ this.uncertainTriggerState = true;
3062
+ }
3063
+ return {
3064
+ ok,
3065
+ stale,
3066
+ unmounted: false,
3067
+ hadActiveBefore,
3068
+ hadActiveTargetBefore,
3069
+ leftPreset: this.confirmedLeft,
3070
+ rightPreset: this.confirmedRight,
3071
+ needsReset: this.needsCleanup
3072
+ };
3073
+ }
3074
+ cleanupOnUnmount(hid) {
3075
+ this.mounted = false;
3076
+ if (!this.needsCleanup) return false;
3077
+ this.confirmedLeft = "off";
3078
+ this.confirmedRight = "off";
3079
+ this.uncertainTriggerState = false;
3080
+ this.rumbleActive = false;
3081
+ void hid.resetTriggers().catch(() => {
3082
+ });
3083
+ return true;
3084
+ }
3085
+ cleanupOnSlotChange(hid) {
3086
+ if (!this.needsCleanup) return false;
3087
+ this.pendingLeftSeq += 1;
3088
+ this.pendingRightSeq += 1;
3089
+ this.confirmedLeft = "off";
3090
+ this.confirmedRight = "off";
3091
+ this.uncertainTriggerState = false;
3092
+ this.rumbleActive = false;
3093
+ void hid.resetTriggers().catch(() => {
3094
+ });
3095
+ return true;
3096
+ }
3097
+ };
3098
+
3099
+ // src/lifecycle.ts
3100
+ function attachControllerLifecycle(hid, options = {}) {
3101
+ const onChange = options.onChange ?? (() => {
3102
+ });
3103
+ const autoHotplug = options.autoHotplug !== false;
3104
+ const autoReset = options.autoEmergencyReset !== false;
3105
+ const getAudio = () => typeof options.audio === "function" ? options.audio() : options.audio ?? null;
3106
+ if (autoHotplug) hid.attachHidHotplug();
3107
+ const unsubStatus = hid.onStatusChange(() => onChange("status"));
3108
+ const onGamepadEvent = () => onChange("gamepad");
3109
+ const onPageExit = () => {
3110
+ hid.emergencyReset();
3111
+ const audio = getAudio();
3112
+ audio?.stopAllContinuous?.();
3113
+ if (options.teardownAudioOnExit) void audio?.teardownDsOutput?.().catch(() => {
3114
+ });
3115
+ };
3116
+ const hasWindow = typeof window !== "undefined";
3117
+ if (hasWindow) {
3118
+ if (autoHotplug) {
3119
+ window.addEventListener("gamepadconnected", onGamepadEvent);
3120
+ window.addEventListener("gamepaddisconnected", onGamepadEvent);
3121
+ }
3122
+ if (autoReset) {
3123
+ window.addEventListener("pagehide", onPageExit);
3124
+ window.addEventListener("beforeunload", onPageExit);
3125
+ }
3126
+ }
3127
+ const pollMs = options.pollMs ?? 250;
3128
+ let poll = pollMs > 0 && typeof setInterval !== "undefined" ? setInterval(() => onChange("poll"), pollMs) : null;
3129
+ let cleaned = false;
3130
+ return () => {
3131
+ if (cleaned) return;
3132
+ cleaned = true;
3133
+ if (poll !== null) {
3134
+ clearInterval(poll);
3135
+ poll = null;
3136
+ }
3137
+ unsubStatus();
3138
+ if (hasWindow) {
3139
+ if (autoHotplug) {
3140
+ window.removeEventListener("gamepadconnected", onGamepadEvent);
3141
+ window.removeEventListener("gamepaddisconnected", onGamepadEvent);
3142
+ }
3143
+ if (autoReset) {
3144
+ window.removeEventListener("pagehide", onPageExit);
3145
+ window.removeEventListener("beforeunload", onPageExit);
3146
+ }
3147
+ }
3148
+ if (autoHotplug && options.detachHotplugOnCleanup !== false) hid.detachHidHotplug();
3149
+ };
3150
+ }
3151
+
2287
3152
  // src/hub.ts
2288
3153
  var NOOP_CONTINUOUS = {
2289
3154
  update() {
@@ -2323,7 +3188,7 @@ function computeCapabilities(hid, audio, slotId, allow4ChAudio) {
2323
3188
  };
2324
3189
  }
2325
3190
  function buildCapabilitySignature(slots, active) {
2326
- const slotSig = slots.map((s) => `${s.id}:${s.source}:${s.identity.model}:${s.identity.transport}`).join(",");
3191
+ const slotSig = slots.map((s) => `${s.id}:${s.source}:${s.identity.model}:${s.identity.displayName}:${s.identity.transport}`).join(",");
2327
3192
  return [
2328
3193
  slotSig,
2329
3194
  active.slotId ?? "",
@@ -2336,18 +3201,22 @@ function buildCapabilitySignature(slots, active) {
2336
3201
  active.hasGyro ? 1 : 0
2337
3202
  ].join("|");
2338
3203
  }
3204
+ function toPcBusSampleOptions(opts) {
3205
+ const route = opts.route ?? "pc";
3206
+ if (route === "pc") return opts;
3207
+ return { ...opts, route: "pc", gain: (opts.gain ?? 0.85) * (route === "speaker" ? 0.45 : 0.5) };
3208
+ }
2339
3209
  function createGamepadly(options = {}) {
2340
3210
  const ownsHid = !options.hid;
2341
3211
  const hid = options.hid ?? new DualSenseControllerManager();
2342
3212
  let audio = options.audio ?? null;
3213
+ const samples = options.samples ?? null;
2343
3214
  let disposed = false;
2344
3215
  const continuousHandles = /* @__PURE__ */ new Set();
3216
+ const sampleHandles = /* @__PURE__ */ new Set();
2345
3217
  const timers = /* @__PURE__ */ new Set();
2346
3218
  const trackers = /* @__PURE__ */ new Set();
2347
3219
  const capListeners = /* @__PURE__ */ new Set();
2348
- if (options.autoHotplug !== false) {
2349
- hid.attachHidHotplug();
2350
- }
2351
3220
  if (options.attachKeyboardFallback && ownsHid) {
2352
3221
  hid.attachKeyboardFallback();
2353
3222
  }
@@ -2370,26 +3239,15 @@ function createGamepadly(options = {}) {
2370
3239
  hid.getConnectedControllers(),
2371
3240
  computeCapabilities(hid, audio, void 0, true)
2372
3241
  );
2373
- const unsubHidStatus = hid.onStatusChange(() => {
2374
- syncCapabilities();
3242
+ const detachLifecycle = attachControllerLifecycle(hid, {
3243
+ autoHotplug: options.autoHotplug,
3244
+ detachHotplugOnCleanup: ownsHid,
3245
+ autoEmergencyReset: options.autoEmergencyReset,
3246
+ teardownAudioOnExit: options.teardownAudioOnExit,
3247
+ audio: () => audio,
3248
+ pollMs: options.capabilityPollMs ?? 250,
3249
+ onChange: syncCapabilities
2375
3250
  });
2376
- const onGamepadEvent = () => syncCapabilities();
2377
- const onPageHide = () => hid.emergencyReset();
2378
- if (typeof window !== "undefined") {
2379
- if (options.autoHotplug !== false) {
2380
- window.addEventListener("gamepadconnected", onGamepadEvent);
2381
- window.addEventListener("gamepaddisconnected", onGamepadEvent);
2382
- }
2383
- if (options.autoEmergencyReset !== false) {
2384
- window.addEventListener("pagehide", onPageHide);
2385
- window.addEventListener("beforeunload", onPageHide);
2386
- }
2387
- }
2388
- let pollInterval = null;
2389
- const pollMs = options.capabilityPollMs ?? 250;
2390
- if (pollMs > 0 && typeof setInterval !== "undefined") {
2391
- pollInterval = setInterval(syncCapabilities, pollMs);
2392
- }
2393
3251
  const createPlayerHandle = (target) => {
2394
3252
  let lastLightbarColor = [23, 23, 23];
2395
3253
  let lastLightbarSentAt = 0;
@@ -2555,6 +3413,62 @@ function createGamepadly(options = {}) {
2555
3413
  },
2556
3414
  playControllerSpeakerTone: (spec) => {
2557
3415
  if (!disposed) audio?.playControllerSpeakerTone(spec);
3416
+ },
3417
+ loadSample: (id, source) => {
3418
+ const sink = samples ?? audio;
3419
+ if (disposed || !sink?.loadSample) return Promise.resolve(false);
3420
+ return sink.loadSample(id, source);
3421
+ },
3422
+ hasSample: (id) => {
3423
+ const sink = samples ?? audio;
3424
+ if (disposed || !sink?.hasSample) return false;
3425
+ return sink.hasSample(id);
3426
+ },
3427
+ unloadSample: (id) => {
3428
+ const sink = samples ?? audio;
3429
+ if (!disposed) sink?.unloadSample?.(id);
3430
+ },
3431
+ playSample: (id, opts = {}) => {
3432
+ if (disposed) return NOOP_SAMPLE_HANDLE;
3433
+ for (const h of sampleHandles) {
3434
+ if (!h.active) sampleHandles.delete(h);
3435
+ }
3436
+ const r = resolveTarget();
3437
+ const route = opts.route ?? "pc";
3438
+ const ownsControllerAudio = Boolean(audio && r.isPrimary && audio.dsMode !== "none");
3439
+ const can4Ch = Boolean(ownsControllerAudio && audio && audio.dsMaxChannelCount >= 4);
3440
+ if ((route === "vcm" || route === "quad") && !can4Ch) {
3441
+ const fb = opts.fallbackHaptic;
3442
+ routeHapticPulse(getRouteCtx(), {
3443
+ pan: opts.pan ?? 0,
3444
+ freqHz: fb?.freqHz ?? 145,
3445
+ durationMs: fb?.durationMs ?? (opts.loop ? 90 : 65),
3446
+ intensity: fb?.intensity ?? Math.min(1, (opts.gain ?? 0.85) * 0.72)
3447
+ });
3448
+ }
3449
+ const sink = samples ?? audio;
3450
+ if (!sink?.playSample) return NOOP_SAMPLE_HANDLE;
3451
+ let sinkOpts = opts;
3452
+ if (route !== "pc" && !ownsControllerAudio) {
3453
+ if (route === "vcm") return NOOP_SAMPLE_HANDLE;
3454
+ sinkOpts = toPcBusSampleOptions(opts);
3455
+ }
3456
+ const rawHandle = sink.playSample(id, sinkOpts);
3457
+ if (!rawHandle.active) return rawHandle;
3458
+ const tracked = {
3459
+ get active() {
3460
+ return !disposed && rawHandle.active;
3461
+ },
3462
+ update: (p) => {
3463
+ if (!disposed) rawHandle.update(p);
3464
+ },
3465
+ stop: (fadeOutMs) => {
3466
+ sampleHandles.delete(tracked);
3467
+ rawHandle.stop(fadeOutMs);
3468
+ }
3469
+ };
3470
+ sampleHandles.add(tracked);
3471
+ return tracked;
2558
3472
  }
2559
3473
  },
2560
3474
  lightbar: {
@@ -2619,6 +3533,10 @@ function createGamepadly(options = {}) {
2619
3533
  syncCapabilities();
2620
3534
  return ok;
2621
3535
  },
3536
+ async disconnectWebHID(slotId, opts) {
3537
+ await hid.disconnect(slotId, opts);
3538
+ syncCapabilities();
3539
+ },
2622
3540
  async reconnectAuthorized() {
2623
3541
  const ok = await hid.reconnectAuthorized();
2624
3542
  syncCapabilities();
@@ -2648,22 +3566,8 @@ function createGamepadly(options = {}) {
2648
3566
  dispose() {
2649
3567
  if (disposed) return;
2650
3568
  disposed = true;
2651
- if (pollInterval !== null) {
2652
- clearInterval(pollInterval);
2653
- pollInterval = null;
2654
- }
2655
- unsubHidStatus();
3569
+ detachLifecycle();
2656
3570
  capListeners.clear();
2657
- if (typeof window !== "undefined") {
2658
- if (options.autoHotplug !== false) {
2659
- window.removeEventListener("gamepadconnected", onGamepadEvent);
2660
- window.removeEventListener("gamepaddisconnected", onGamepadEvent);
2661
- }
2662
- if (options.autoEmergencyReset !== false) {
2663
- window.removeEventListener("pagehide", onPageHide);
2664
- window.removeEventListener("beforeunload", onPageHide);
2665
- }
2666
- }
2667
3571
  for (const t of timers) clearTimeout(t);
2668
3572
  timers.clear();
2669
3573
  for (const tr of trackers) {
@@ -2680,15 +3584,19 @@ function createGamepadly(options = {}) {
2680
3584
  }
2681
3585
  }
2682
3586
  continuousHandles.clear();
3587
+ for (const s of sampleHandles) {
3588
+ try {
3589
+ s.stop();
3590
+ } catch {
3591
+ }
3592
+ }
3593
+ sampleHandles.clear();
2683
3594
  hid.stopGamepadRumble();
2684
3595
  hid.resetTriggers().catch(() => {
2685
3596
  });
2686
3597
  hid.setLightbar(23, 23, 23).catch(() => {
2687
3598
  });
2688
- if (ownsHid) {
2689
- if (options.autoHotplug !== false) hid.detachHidHotplug();
2690
- if (options.attachKeyboardFallback) hid.detachKeyboardFallback();
2691
- }
3599
+ if (ownsHid && options.attachKeyboardFallback) hid.detachKeyboardFallback();
2692
3600
  }
2693
3601
  };
2694
3602
  }
@@ -2743,8 +3651,31 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
2743
3651
  this.dsChGains[1].gain.setTargetAtTime(spk, this.dsCtx.currentTime, 0.015);
2744
3652
  }
2745
3653
  }
2746
- // Track active continuous handles for clean disposal
3654
+ // Track active continuous handles & graph lifecycle subscribers
2747
3655
  activeContinuous = /* @__PURE__ */ new Set();
3656
+ audioGraphListeners = /* @__PURE__ */ new Set();
3657
+ onAudioGraphChange(listener) {
3658
+ this.audioGraphListeners.add(listener);
3659
+ return () => {
3660
+ this.audioGraphListeners.delete(listener);
3661
+ };
3662
+ }
3663
+ getAudioRouting() {
3664
+ return {
3665
+ pcCtx: this.pcCtx,
3666
+ pcMasterGain: this.pcMasterGain,
3667
+ dsCtx: this.dsCtx,
3668
+ dsChGains: this.dsChGains
3669
+ };
3670
+ }
3671
+ emitAudioGraph(event) {
3672
+ for (const fn of this.audioGraphListeners) {
3673
+ try {
3674
+ fn(event);
3675
+ } catch {
3676
+ }
3677
+ }
3678
+ }
2748
3679
  // Companion WebSocket lifecycle & auto-reconnect
2749
3680
  companionToken = "";
2750
3681
  intentionalWsClose = false;
@@ -2943,6 +3874,7 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
2943
3874
  splitter.connect(anR, 1);
2944
3875
  this.pcAnalysers = [anL, anR];
2945
3876
  this.pcNoiseBuffer = this.createNoiseBuffer(ctx);
3877
+ this.emitAudioGraph("pc_ready");
2946
3878
  }
2947
3879
  // =========================================================================
2948
3880
  // OUTPUT B: DUALSENSE 4CH (MODE 1: GAMEPADLY LINK COMPANION WASAPI)
@@ -3149,6 +4081,7 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
3149
4081
  this.dsMerger.connect(ctx.destination);
3150
4082
  }
3151
4083
  this.dsNoiseBuffer = this.createNoiseBuffer(ctx);
4084
+ this.emitAudioGraph("ds_ready");
3152
4085
  }
3153
4086
  async teardownDsOutput() {
3154
4087
  this.intentionalWsClose = true;
@@ -3157,6 +4090,7 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
3157
4090
  this.reconnectTimer = null;
3158
4091
  }
3159
4092
  this.stopAllContinuous();
4093
+ this.emitAudioGraph("ds_teardown");
3160
4094
  if (this.dsWorklet) {
3161
4095
  try {
3162
4096
  this.dsWorklet.port.onmessage = null;
@@ -3648,9 +4582,1559 @@ var ThreeLayerAudioEngine = class _ThreeLayerAudioEngine {
3648
4582
  }
3649
4583
  };
3650
4584
 
3651
- // src/link/index.ts
3652
- function createLinkAudio(options) {
3653
- return new ThreeLayerAudioEngine(options);
4585
+ // src/link/connect.ts
4586
+ var LINK_PROTOCOL_START_URI = "gamepadly-link://start";
4587
+ function shouldAutoLaunchLink() {
4588
+ if (typeof navigator === "undefined") return false;
4589
+ return /Windows/i.test(navigator.userAgent) && !/Firefox\//i.test(navigator.userAgent);
4590
+ }
4591
+ function launchLinkViaProtocol(uri = LINK_PROTOCOL_START_URI) {
4592
+ if (typeof document === "undefined" || !document.body) return;
4593
+ const anchor = document.createElement("a");
4594
+ anchor.href = uri;
4595
+ anchor.style.display = "none";
4596
+ document.body.appendChild(anchor);
4597
+ anchor.click();
4598
+ document.body.removeChild(anchor);
4599
+ }
4600
+ function errorMessage(err) {
4601
+ return err instanceof Error ? err.message : String(err);
4602
+ }
4603
+ async function launchAndWaitForCompanion(audio, uri, force) {
4604
+ let sawBlur = false;
4605
+ let wake = null;
4606
+ const onBlur = () => {
4607
+ sawBlur = true;
4608
+ };
4609
+ const onFocus = () => {
4610
+ const fn = wake;
4611
+ wake = null;
4612
+ fn?.();
4613
+ };
4614
+ const hasWindow = typeof window !== "undefined";
4615
+ if (hasWindow) {
4616
+ window.addEventListener("blur", onBlur);
4617
+ window.addEventListener("focus", onFocus);
4618
+ }
4619
+ let health = { online: false };
4620
+ try {
4621
+ launchLinkViaProtocol(uri);
4622
+ const startMs = Date.now();
4623
+ while (true) {
4624
+ await new Promise((resolve) => {
4625
+ const timer = setTimeout(() => {
4626
+ wake = null;
4627
+ resolve();
4628
+ }, 450);
4629
+ wake = () => {
4630
+ clearTimeout(timer);
4631
+ resolve();
4632
+ };
4633
+ });
4634
+ health = await audio.probeCompanion(700);
4635
+ if (health.online) break;
4636
+ const budgetMs = sawBlur || force ? 12e3 : 3600;
4637
+ if (Date.now() - startMs >= budgetMs) break;
4638
+ }
4639
+ } finally {
4640
+ if (hasWindow) {
4641
+ window.removeEventListener("blur", onBlur);
4642
+ window.removeEventListener("focus", onFocus);
4643
+ }
4644
+ }
4645
+ return health;
4646
+ }
4647
+ async function connectDualSenseViaCompanion(audio, options = {}) {
4648
+ let health = { online: false };
4649
+ let devices = [];
4650
+ try {
4651
+ await audio.initPcOutput().catch(() => {
4652
+ });
4653
+ health = await audio.probeCompanion(900);
4654
+ const autoLaunch = options.autoLaunch ?? shouldAutoLaunchLink();
4655
+ if (!health.online && (options.forceLaunch || autoLaunch)) {
4656
+ options.onLaunchingChange?.(true);
4657
+ try {
4658
+ health = await launchAndWaitForCompanion(
4659
+ audio,
4660
+ options.launchUri ?? LINK_PROTOCOL_START_URI,
4661
+ Boolean(options.forceLaunch)
4662
+ );
4663
+ } finally {
4664
+ options.onLaunchingChange?.(false);
4665
+ }
4666
+ }
4667
+ if (!health.online) return { ok: false, error: "link_not_running", health, devices };
4668
+ devices = await audio.listCompanionDevices().catch(() => []);
4669
+ const target = (options.deviceId ? devices.find((d) => d.id === options.deviceId) : void 0) ?? devices.find((d) => d.isDualSense && d.channels >= 4) ?? devices.find((d) => d.isDualSense);
4670
+ const bind = await audio.connectDualSenseCompanion(
4671
+ target?.id || options.deviceId || "",
4672
+ target?.name || "DualSense WASAPI"
4673
+ );
4674
+ return { ok: true, bind, health, devices };
4675
+ } catch (err) {
4676
+ return { ok: false, error: "failed", message: errorMessage(err), health, devices };
4677
+ }
4678
+ }
4679
+ async function connectDualSenseViaBrowser(audio, options = {}) {
4680
+ try {
4681
+ if (!ThreeLayerAudioEngine.checkBrowserCapabilities().hasSetSinkId) {
4682
+ return { ok: false, error: "no_set_sink_id" };
4683
+ }
4684
+ await audio.initPcOutput().catch(() => {
4685
+ });
4686
+ await audio.unlockBrowserDeviceLabels();
4687
+ const outputs = await audio.listBrowserOutputDevices();
4688
+ const target = (options.deviceId ? outputs.find((o) => o.deviceId === options.deviceId) : void 0) ?? outputs.find(
4689
+ (o) => o.isLikelyDualSense && o.deviceId !== "default" && o.deviceId !== "communications"
4690
+ ) ?? outputs.find((o) => o.isLikelyDualSense);
4691
+ if (!target) return { ok: false, error: "dualsense_audio_not_found" };
4692
+ const bind = await audio.connectDualSenseBrowserSink(target.deviceId, target.label);
4693
+ return { ok: true, bind };
4694
+ } catch (err) {
4695
+ return { ok: false, error: "failed", message: errorMessage(err) };
4696
+ }
4697
+ }
4698
+
4699
+ // src/audio/sampleBank.ts
4700
+ function createSampleBank(provider) {
4701
+ const sampleStore = /* @__PURE__ */ new Map();
4702
+ const activeSamples = /* @__PURE__ */ new Set();
4703
+ let disposed = false;
4704
+ const routing = () => provider.getAudioRouting();
4705
+ function buildAudioBufferFromPcm(ctx, pcm) {
4706
+ const chCount = Math.max(1, Math.min(4, pcm.channels.length));
4707
+ const frameCount = Math.max(1, pcm.channels[0]?.length ?? 1);
4708
+ const buf = ctx.createBuffer(chCount, frameCount, Math.max(8e3, Math.round(pcm.sampleRate)));
4709
+ for (let c = 0; c < chCount; c++) {
4710
+ const dst = buf.getChannelData(c);
4711
+ const src = pcm.channels[c] ?? pcm.channels[0];
4712
+ if (src) {
4713
+ dst.set(src.length === frameCount ? src : src.subarray(0, frameCount));
4714
+ }
4715
+ }
4716
+ return buf;
4717
+ }
4718
+ function decodeSampleForContext(id, target) {
4719
+ if (disposed) return Promise.resolve(null);
4720
+ const entry = sampleStore.get(id);
4721
+ const snap = routing();
4722
+ const ctx = target === "pc" ? snap.pcCtx : snap.dsCtx;
4723
+ if (!entry || !ctx) return Promise.resolve(null);
4724
+ if (target === "pc" && entry.pcCtxRef === ctx && entry.pcBuffer) {
4725
+ return Promise.resolve(entry.pcBuffer);
4726
+ }
4727
+ if (target === "ds" && entry.dsCtxRef === ctx && entry.dsBuffer) {
4728
+ return Promise.resolve(entry.dsBuffer);
4729
+ }
4730
+ if (entry.rawPcm) {
4731
+ const buf = buildAudioBufferFromPcm(ctx, entry.rawPcm);
4732
+ if (target === "pc") {
4733
+ entry.pcCtxRef = ctx;
4734
+ entry.pcBuffer = buf;
4735
+ } else {
4736
+ entry.dsCtxRef = ctx;
4737
+ entry.dsBuffer = buf;
4738
+ }
4739
+ return Promise.resolve(buf);
4740
+ }
4741
+ if (!entry.rawEncoded) return Promise.resolve(null);
4742
+ if (target === "pc" && entry.pcDecoding || target === "ds" && entry.dsDecoding) {
4743
+ return Promise.resolve(null);
4744
+ }
4745
+ if (target === "pc") entry.pcDecoding = true;
4746
+ else entry.dsDecoding = true;
4747
+ const copy = entry.rawEncoded.slice(0);
4748
+ return ctx.decodeAudioData(copy).then((decoded) => {
4749
+ if (disposed || sampleStore.get(id) !== entry) return null;
4750
+ const latest = routing();
4751
+ if (target === "pc" && latest.pcCtx === ctx) {
4752
+ entry.pcCtxRef = ctx;
4753
+ entry.pcBuffer = decoded;
4754
+ } else if (target === "ds" && latest.dsCtx === ctx) {
4755
+ entry.dsCtxRef = ctx;
4756
+ entry.dsBuffer = decoded;
4757
+ }
4758
+ return decoded;
4759
+ }).catch(() => null).finally(() => {
4760
+ if (target === "pc") entry.pcDecoding = false;
4761
+ else entry.dsDecoding = false;
4762
+ });
4763
+ }
4764
+ function warmSamplesForContext(target) {
4765
+ for (const id of sampleStore.keys()) {
4766
+ void decodeSampleForContext(id, target);
4767
+ }
4768
+ }
4769
+ function getSampleBufferSync(id, target) {
4770
+ const entry = sampleStore.get(id);
4771
+ const snap = routing();
4772
+ const ctx = target === "pc" ? snap.pcCtx : snap.dsCtx;
4773
+ if (!entry || !ctx) return null;
4774
+ if (target === "pc") {
4775
+ if (entry.pcCtxRef === ctx && entry.pcBuffer) return entry.pcBuffer;
4776
+ } else {
4777
+ if (entry.dsCtxRef === ctx && entry.dsBuffer) return entry.dsBuffer;
4778
+ }
4779
+ if (entry.rawPcm) {
4780
+ const buf = buildAudioBufferFromPcm(ctx, entry.rawPcm);
4781
+ if (target === "pc") {
4782
+ entry.pcCtxRef = ctx;
4783
+ entry.pcBuffer = buf;
4784
+ } else {
4785
+ entry.dsCtxRef = ctx;
4786
+ entry.dsBuffer = buf;
4787
+ }
4788
+ return buf;
4789
+ }
4790
+ void decodeSampleForContext(id, target);
4791
+ return null;
4792
+ }
4793
+ function stopAll(fadeOutMs = 0) {
4794
+ for (const h of Array.from(activeSamples)) {
4795
+ try {
4796
+ h.stop(fadeOutMs);
4797
+ } catch {
4798
+ }
4799
+ }
4800
+ activeSamples.clear();
4801
+ }
4802
+ const unsubGraph = typeof provider.onAudioGraphChange === "function" ? provider.onAudioGraphChange((ev) => {
4803
+ if (disposed) return;
4804
+ if (ev === "pc_ready") {
4805
+ warmSamplesForContext("pc");
4806
+ } else if (ev === "ds_ready") {
4807
+ warmSamplesForContext("ds");
4808
+ } else if (ev === "ds_teardown") {
4809
+ stopAll(0);
4810
+ for (const entry of sampleStore.values()) {
4811
+ entry.dsCtxRef = null;
4812
+ entry.dsBuffer = null;
4813
+ entry.dsDecoding = false;
4814
+ }
4815
+ }
4816
+ }) : () => {
4817
+ };
4818
+ return {
4819
+ async loadSample(id, source) {
4820
+ if (disposed || !id) return false;
4821
+ try {
4822
+ if (typeof source === "string") {
4823
+ const res = await fetch(source);
4824
+ if (!res.ok) return false;
4825
+ const raw = await res.arrayBuffer();
4826
+ sampleStore.set(id, { rawEncoded: raw });
4827
+ } else if (source instanceof ArrayBuffer) {
4828
+ sampleStore.set(id, { rawEncoded: source.slice(0) });
4829
+ } else if (source && Array.isArray(source.channels) && source.channels.length > 0) {
4830
+ sampleStore.set(id, {
4831
+ rawPcm: {
4832
+ sampleRate: source.sampleRate,
4833
+ channels: source.channels.map((ch) => new Float32Array(ch))
4834
+ }
4835
+ });
4836
+ } else {
4837
+ return false;
4838
+ }
4839
+ const snap = routing();
4840
+ const tasks = [];
4841
+ if (snap.pcCtx) tasks.push(decodeSampleForContext(id, "pc"));
4842
+ if (snap.dsCtx) tasks.push(decodeSampleForContext(id, "ds"));
4843
+ if (tasks.length > 0) await Promise.all(tasks);
4844
+ return true;
4845
+ } catch {
4846
+ return false;
4847
+ }
4848
+ },
4849
+ hasSample(id) {
4850
+ return sampleStore.has(id);
4851
+ },
4852
+ unloadSample(id) {
4853
+ sampleStore.delete(id);
4854
+ },
4855
+ playSample(id, options = {}) {
4856
+ if (disposed) return NOOP_SAMPLE_HANDLE;
4857
+ const route = options.route ?? "pc";
4858
+ const initPan = Math.max(-1, Math.min(1, options.pan ?? 0));
4859
+ const initGain = Math.max(1e-3, Math.min(1.5, options.gain ?? 0.85));
4860
+ const initRate = Math.max(0.25, Math.min(4, options.playbackRate ?? 1));
4861
+ const loop = Boolean(options.loop);
4862
+ const delaySec = Math.max(0, (options.delayMs ?? 0) / 1e3);
4863
+ const snap = routing();
4864
+ const dsReady4Ch = Boolean(snap.dsCtx && snap.dsChGains.length >= 4);
4865
+ const dsReady2Ch = Boolean(snap.dsCtx && snap.dsChGains.length >= 2);
4866
+ let target = "pc";
4867
+ let effectiveRoute = route;
4868
+ let gainScale = 1;
4869
+ if (route === "vcm") {
4870
+ if (!dsReady4Ch) return NOOP_SAMPLE_HANDLE;
4871
+ target = "ds";
4872
+ } else if (route === "speaker") {
4873
+ if (dsReady2Ch) {
4874
+ target = "ds";
4875
+ } else if (snap.pcCtx && snap.pcMasterGain) {
4876
+ target = "pc";
4877
+ effectiveRoute = "pc";
4878
+ gainScale = 0.45;
4879
+ } else {
4880
+ return NOOP_SAMPLE_HANDLE;
4881
+ }
4882
+ } else if (route === "quad") {
4883
+ if (dsReady4Ch) {
4884
+ target = "ds";
4885
+ } else if (snap.pcCtx && snap.pcMasterGain) {
4886
+ target = "pc";
4887
+ effectiveRoute = "pc";
4888
+ gainScale = 0.5;
4889
+ } else {
4890
+ return NOOP_SAMPLE_HANDLE;
4891
+ }
4892
+ } else {
4893
+ if (!snap.pcCtx || !snap.pcMasterGain) return NOOP_SAMPLE_HANDLE;
4894
+ target = "pc";
4895
+ }
4896
+ const ctx = target === "pc" ? snap.pcCtx : snap.dsCtx;
4897
+ const buffer = getSampleBufferSync(id, target);
4898
+ if (!buffer) return NOOP_SAMPLE_HANDLE;
4899
+ const src = ctx.createBufferSource();
4900
+ src.buffer = buffer;
4901
+ src.loop = loop;
4902
+ src.playbackRate.value = initRate;
4903
+ const masterGain = ctx.createGain();
4904
+ masterGain.gain.value = initGain * gainScale;
4905
+ let pcPanner = null;
4906
+ let vcmGainL = null;
4907
+ let vcmGainR = null;
4908
+ const cleanupNodes = [src, masterGain];
4909
+ if (effectiveRoute === "pc") {
4910
+ pcPanner = ctx.createStereoPanner();
4911
+ pcPanner.pan.value = initPan;
4912
+ src.connect(masterGain);
4913
+ masterGain.connect(pcPanner);
4914
+ pcPanner.connect(snap.pcMasterGain);
4915
+ cleanupNodes.push(pcPanner);
4916
+ } else if (effectiveRoute === "speaker") {
4917
+ src.connect(masterGain);
4918
+ masterGain.connect(snap.dsChGains[0]);
4919
+ masterGain.connect(snap.dsChGains[1]);
4920
+ } else if (effectiveRoute === "vcm") {
4921
+ vcmGainL = ctx.createGain();
4922
+ vcmGainR = ctx.createGain();
4923
+ vcmGainL.gain.value = Math.cos((initPan + 1) * Math.PI / 4);
4924
+ vcmGainR.gain.value = Math.sin((initPan + 1) * Math.PI / 4);
4925
+ src.connect(masterGain);
4926
+ masterGain.connect(vcmGainL);
4927
+ masterGain.connect(vcmGainR);
4928
+ vcmGainL.connect(snap.dsChGains[2]);
4929
+ vcmGainR.connect(snap.dsChGains[3]);
4930
+ cleanupNodes.push(vcmGainL, vcmGainR);
4931
+ } else {
4932
+ if (buffer.numberOfChannels >= 4) {
4933
+ const splitter = ctx.createChannelSplitter(4);
4934
+ const spkMono = ctx.createGain();
4935
+ spkMono.gain.value = 0.5;
4936
+ vcmGainL = ctx.createGain();
4937
+ vcmGainR = ctx.createGain();
4938
+ vcmGainL.gain.value = Math.cos((initPan + 1) * Math.PI / 4) * Math.SQRT2;
4939
+ vcmGainR.gain.value = Math.sin((initPan + 1) * Math.PI / 4) * Math.SQRT2;
4940
+ src.connect(masterGain);
4941
+ masterGain.connect(splitter);
4942
+ splitter.connect(spkMono, 0);
4943
+ splitter.connect(spkMono, 1);
4944
+ spkMono.connect(snap.dsChGains[0]);
4945
+ spkMono.connect(snap.dsChGains[1]);
4946
+ splitter.connect(vcmGainL, 2);
4947
+ splitter.connect(vcmGainR, 3);
4948
+ vcmGainL.connect(snap.dsChGains[2]);
4949
+ vcmGainR.connect(snap.dsChGains[3]);
4950
+ cleanupNodes.push(splitter, spkMono, vcmGainL, vcmGainR);
4951
+ } else {
4952
+ const spkAtt = ctx.createGain();
4953
+ spkAtt.gain.value = 0.35;
4954
+ vcmGainL = ctx.createGain();
4955
+ vcmGainR = ctx.createGain();
4956
+ vcmGainL.gain.value = Math.cos((initPan + 1) * Math.PI / 4);
4957
+ vcmGainR.gain.value = Math.sin((initPan + 1) * Math.PI / 4);
4958
+ src.connect(masterGain);
4959
+ masterGain.connect(spkAtt);
4960
+ spkAtt.connect(snap.dsChGains[0]);
4961
+ spkAtt.connect(snap.dsChGains[1]);
4962
+ masterGain.connect(vcmGainL);
4963
+ masterGain.connect(vcmGainR);
4964
+ vcmGainL.connect(snap.dsChGains[2]);
4965
+ vcmGainR.connect(snap.dsChGains[3]);
4966
+ cleanupNodes.push(spkAtt, vcmGainL, vcmGainR);
4967
+ }
4968
+ }
4969
+ let isActive = true;
4970
+ const disposeNodes = () => {
4971
+ if (!isActive) return;
4972
+ isActive = false;
4973
+ activeSamples.delete(handle);
4974
+ for (const n of cleanupNodes) {
4975
+ try {
4976
+ n.disconnect();
4977
+ } catch {
4978
+ }
4979
+ }
4980
+ };
4981
+ const handle = {
4982
+ get active() {
4983
+ return isActive;
4984
+ },
4985
+ update: ({ pan, gain, playbackRate } = {}) => {
4986
+ if (!isActive) return;
4987
+ const now = ctx.currentTime;
4988
+ if (gain !== void 0) {
4989
+ const g = Math.max(1e-4, Math.min(1.5, gain)) * gainScale;
4990
+ masterGain.gain.setTargetAtTime(g, now, 0.02);
4991
+ }
4992
+ if (playbackRate !== void 0) {
4993
+ const r = Math.max(0.25, Math.min(4, playbackRate));
4994
+ src.playbackRate.setTargetAtTime(r, now, 0.025);
4995
+ }
4996
+ if (pan !== void 0) {
4997
+ const p = Math.max(-1, Math.min(1, pan));
4998
+ if (pcPanner) {
4999
+ pcPanner.pan.setTargetAtTime(p, now, 0.02);
5000
+ }
5001
+ if (vcmGainL && vcmGainR) {
5002
+ const mult = effectiveRoute === "quad" && buffer.numberOfChannels >= 4 ? Math.SQRT2 : 1;
5003
+ vcmGainL.gain.setTargetAtTime(Math.cos((p + 1) * Math.PI / 4) * mult, now, 0.02);
5004
+ vcmGainR.gain.setTargetAtTime(Math.sin((p + 1) * Math.PI / 4) * mult, now, 0.02);
5005
+ }
5006
+ }
5007
+ },
5008
+ stop: (fadeOutMs = 0) => {
5009
+ if (!isActive) return;
5010
+ const now = ctx.currentTime;
5011
+ if (fadeOutMs > 4) {
5012
+ const fadeSec = Math.min(2, fadeOutMs / 1e3);
5013
+ try {
5014
+ masterGain.gain.cancelScheduledValues(now);
5015
+ masterGain.gain.setValueAtTime(Math.max(1e-4, masterGain.gain.value), now);
5016
+ masterGain.gain.exponentialRampToValueAtTime(1e-4, now + fadeSec);
5017
+ src.stop(now + fadeSec + 0.015);
5018
+ } catch {
5019
+ disposeNodes();
5020
+ }
5021
+ } else {
5022
+ try {
5023
+ src.stop();
5024
+ } catch {
5025
+ }
5026
+ disposeNodes();
5027
+ }
5028
+ }
5029
+ };
5030
+ src.onended = () => {
5031
+ disposeNodes();
5032
+ };
5033
+ activeSamples.add(handle);
5034
+ src.start(ctx.currentTime + delaySec);
5035
+ return handle;
5036
+ },
5037
+ stopAll,
5038
+ dispose() {
5039
+ if (disposed) return;
5040
+ disposed = true;
5041
+ unsubGraph();
5042
+ stopAll(0);
5043
+ sampleStore.clear();
5044
+ }
5045
+ };
5046
+ }
5047
+
5048
+ // src/link/index.ts
5049
+ function createLinkAudio(options) {
5050
+ const engine = new ThreeLayerAudioEngine(options);
5051
+ const bank = createSampleBank(engine);
5052
+ return Object.assign(engine, {
5053
+ loadSample: bank.loadSample,
5054
+ hasSample: bank.hasSample,
5055
+ unloadSample: bank.unloadSample,
5056
+ playSample: bank.playSample,
5057
+ stopAllSamples: bank.stopAll
5058
+ });
5059
+ }
5060
+
5061
+ // src/audio/routing.ts
5062
+ function createPcAudioRouting(ctx, destination = ctx.destination) {
5063
+ const output = ctx.createGain();
5064
+ output.connect(destination);
5065
+ let disposed = false;
5066
+ return {
5067
+ output,
5068
+ getAudioRouting: () => ({
5069
+ pcCtx: disposed ? null : ctx,
5070
+ pcMasterGain: disposed ? null : output,
5071
+ dsCtx: null,
5072
+ dsChGains: []
5073
+ }),
5074
+ dispose() {
5075
+ if (disposed) return;
5076
+ disposed = true;
5077
+ try {
5078
+ output.disconnect();
5079
+ } catch {
5080
+ }
5081
+ }
5082
+ };
5083
+ }
5084
+
5085
+ // src/mic/input.ts
5086
+ var CONTROLLER_MIC_RE = /wireless controller|dualsense|ps5/i;
5087
+ function isMicInputSupported() {
5088
+ return typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getUserMedia) && typeof window !== "undefined" && Boolean(
5089
+ window.AudioContext || window.webkitAudioContext
5090
+ );
5091
+ }
5092
+ function rawConstraints(deviceId) {
5093
+ return {
5094
+ video: false,
5095
+ audio: {
5096
+ ...deviceId ? { deviceId: { exact: deviceId } } : {},
5097
+ echoCancellation: false,
5098
+ noiseSuppression: false,
5099
+ autoGainControl: false
5100
+ }
5101
+ };
5102
+ }
5103
+ function stopStream(s) {
5104
+ if (!s) return;
5105
+ for (const track of s.getTracks()) {
5106
+ try {
5107
+ track.stop();
5108
+ } catch {
5109
+ }
5110
+ }
5111
+ }
5112
+ async function findControllerMic() {
5113
+ if (!navigator.mediaDevices?.enumerateDevices) return void 0;
5114
+ try {
5115
+ const devices = await navigator.mediaDevices.enumerateDevices();
5116
+ return devices.find((d) => d.kind === "audioinput" && CONTROLLER_MIC_RE.test(d.label || ""));
5117
+ } catch {
5118
+ return void 0;
5119
+ }
5120
+ }
5121
+ async function openMicInput(options = {}) {
5122
+ if (!isMicInputSupported()) return "unsupported";
5123
+ const AudioCtx = window.AudioContext || window.webkitAudioContext;
5124
+ const preferPad = !options.deviceId && options.preferControllerMic !== false;
5125
+ let stream = null;
5126
+ try {
5127
+ const known = preferPad ? await findControllerMic() : void 0;
5128
+ try {
5129
+ stream = await navigator.mediaDevices.getUserMedia(rawConstraints(options.deviceId ?? known?.deviceId));
5130
+ } catch (err) {
5131
+ if (!known) throw err;
5132
+ stream = await navigator.mediaDevices.getUserMedia(rawConstraints());
5133
+ }
5134
+ if (preferPad && !CONTROLLER_MIC_RE.test(stream.getAudioTracks()[0]?.label || "")) {
5135
+ const pad = await findControllerMic();
5136
+ const currentId = stream.getAudioTracks()[0]?.getSettings?.().deviceId;
5137
+ if (pad?.deviceId && pad.deviceId !== currentId) {
5138
+ try {
5139
+ const padStream = await navigator.mediaDevices.getUserMedia(rawConstraints(pad.deviceId));
5140
+ stopStream(stream);
5141
+ stream = padStream;
5142
+ } catch {
5143
+ }
5144
+ }
5145
+ }
5146
+ const ctx = new AudioCtx();
5147
+ if (ctx.state === "suspended") await ctx.resume();
5148
+ const source = ctx.createMediaStreamSource(stream);
5149
+ const analyser = ctx.createAnalyser();
5150
+ analyser.fftSize = options.fftSize ?? 512;
5151
+ analyser.smoothingTimeConstant = options.smoothing ?? 0.55;
5152
+ source.connect(analyser);
5153
+ const label = stream.getAudioTracks()[0]?.label || "";
5154
+ const activeStream = stream;
5155
+ let closed = false;
5156
+ return {
5157
+ ctx,
5158
+ analyser,
5159
+ stream: activeStream,
5160
+ label,
5161
+ usingControllerMic: CONTROLLER_MIC_RE.test(label),
5162
+ close() {
5163
+ if (closed) return;
5164
+ closed = true;
5165
+ try {
5166
+ source.disconnect();
5167
+ } catch {
5168
+ }
5169
+ stopStream(activeStream);
5170
+ ctx.close().catch(() => {
5171
+ });
5172
+ }
5173
+ };
5174
+ } catch {
5175
+ stopStream(stream);
5176
+ return "denied";
5177
+ }
5178
+ }
5179
+ function timeDomainRms(buf) {
5180
+ if (buf.length === 0) return 0;
5181
+ let sumSq = 0;
5182
+ for (let i = 0; i < buf.length; i++) {
5183
+ const v = (buf[i] - 128) / 128;
5184
+ sumSq += v * v;
5185
+ }
5186
+ return Math.sqrt(sumSq / buf.length);
5187
+ }
5188
+
5189
+ // src/mic/blow.ts
5190
+ function clamp4(v, min, max) {
5191
+ return Math.max(min, Math.min(max, v));
5192
+ }
5193
+ function analyzeBlowSpectrum(freqBins, timeDomain, sampleRate, fftSize, opts = {}) {
5194
+ const rmsThreshold = opts.rmsThreshold ?? 0.035;
5195
+ const flatnessThreshold = opts.flatnessThreshold ?? 0.28;
5196
+ let sumSq = 0;
5197
+ for (let i = 0; i < timeDomain.length; i++) {
5198
+ const s = (timeDomain[i] - 128) / 128;
5199
+ sumSq += s * s;
5200
+ }
5201
+ const rms = timeDomain.length > 0 ? Math.sqrt(sumSq / timeDomain.length) : 0;
5202
+ const binHz = sampleRate / Math.max(1, fftSize);
5203
+ const startBin = Math.max(1, Math.floor(80 / binHz));
5204
+ const endBin = Math.min(freqBins.length - 1, Math.ceil(1600 / binHz));
5205
+ const count = Math.max(1, endBin - startBin + 1);
5206
+ let arithSum = 0;
5207
+ let logSum = 0;
5208
+ let activeBins = 0;
5209
+ for (let i = startBin; i <= endBin; i++) {
5210
+ const mag = Math.max(1e-4, freqBins[i] / 255);
5211
+ arithSum += mag;
5212
+ logSum += Math.log(mag);
5213
+ if (freqBins[i] > 18) activeBins++;
5214
+ }
5215
+ const arithMean = arithSum / count;
5216
+ const geomMean = Math.exp(logSum / count);
5217
+ const flatness = arithMean > 1e-4 ? clamp4(geomMean / arithMean, 0, 1) : 0;
5218
+ const bandFill = activeBins / count;
5219
+ if (rms < rmsThreshold) {
5220
+ return { rms, flatness, rawIntensity: 0 };
5221
+ }
5222
+ const levelNorm = clamp4((rms - rmsThreshold) / Math.max(0.05, 0.28 - rmsThreshold), 0, 1);
5223
+ const flatnessFactor = clamp4(
5224
+ (flatness - flatnessThreshold * 0.65) / Math.max(0.15, 0.78 - flatnessThreshold * 0.65),
5225
+ 0,
5226
+ 1
5227
+ );
5228
+ const fillFactor = clamp4(bandFill / 0.45, 0, 1);
5229
+ const rawIntensity = clamp4(levelNorm * (0.25 + 0.75 * flatnessFactor * fillFactor), 0, 1);
5230
+ return { rms, flatness, rawIntensity };
5231
+ }
5232
+ function createMicBlowSensor(options = {}) {
5233
+ const rmsThreshold = clamp4(options.rmsThreshold ?? 0.035, 5e-3, 0.5);
5234
+ const flatnessThreshold = clamp4(options.flatnessThreshold ?? 0.28, 0.05, 0.9);
5235
+ const blowingThreshold = clamp4(options.blowingThreshold ?? 0.22, 0.05, 0.95);
5236
+ const smoothing = clamp4(options.smoothing ?? 0.28, 0.05, 1);
5237
+ const fftSize = options.fftSize ?? 512;
5238
+ let input = null;
5239
+ let analyser = null;
5240
+ let freqBuf = null;
5241
+ let timeBuf = null;
5242
+ let blowingSinceMs = 0;
5243
+ let opSeq = 0;
5244
+ const state = {
5245
+ status: "idle",
5246
+ intensity: 0,
5247
+ blowing: false,
5248
+ sustainedMs: 0,
5249
+ peakIntensity: 0,
5250
+ rms: 0,
5251
+ flatness: 0,
5252
+ deviceLabel: "",
5253
+ usingControllerMic: false
5254
+ };
5255
+ function stop() {
5256
+ opSeq++;
5257
+ input?.close();
5258
+ input = null;
5259
+ analyser = null;
5260
+ freqBuf = null;
5261
+ timeBuf = null;
5262
+ blowingSinceMs = 0;
5263
+ state.status = state.status === "denied" || state.status === "unsupported" ? state.status : "idle";
5264
+ state.intensity = 0;
5265
+ state.blowing = false;
5266
+ state.sustainedMs = 0;
5267
+ state.rms = 0;
5268
+ state.flatness = 0;
5269
+ state.deviceLabel = "";
5270
+ state.usingControllerMic = false;
5271
+ }
5272
+ return {
5273
+ async start() {
5274
+ stop();
5275
+ const mySeq = opSeq;
5276
+ state.peakIntensity = 0;
5277
+ const opened = await openMicInput({
5278
+ preferControllerMic: options.preferControllerMic,
5279
+ deviceId: options.deviceId,
5280
+ fftSize,
5281
+ smoothing: 0.55
5282
+ });
5283
+ if (mySeq !== opSeq) {
5284
+ if (typeof opened !== "string") opened.close();
5285
+ return false;
5286
+ }
5287
+ if (typeof opened === "string") {
5288
+ state.status = opened;
5289
+ return false;
5290
+ }
5291
+ input = opened;
5292
+ analyser = opened.analyser;
5293
+ freqBuf = new Uint8Array(new ArrayBuffer(analyser.frequencyBinCount));
5294
+ timeBuf = new Uint8Array(new ArrayBuffer(analyser.fftSize));
5295
+ state.status = "active";
5296
+ state.deviceLabel = opened.label || "Microphone";
5297
+ state.usingControllerMic = opened.usingControllerMic;
5298
+ return true;
5299
+ },
5300
+ stop,
5301
+ sample(nowMs = typeof performance !== "undefined" ? performance.now() : Date.now()) {
5302
+ if (state.status !== "active" || !input || !analyser || !freqBuf || !timeBuf) {
5303
+ return state;
5304
+ }
5305
+ analyser.getByteFrequencyData(freqBuf);
5306
+ analyser.getByteTimeDomainData(timeBuf);
5307
+ const metrics = analyzeBlowSpectrum(freqBuf, timeBuf, input.ctx.sampleRate, analyser.fftSize, {
5308
+ rmsThreshold,
5309
+ flatnessThreshold
5310
+ });
5311
+ const target = metrics.rawIntensity;
5312
+ state.intensity = state.intensity + (target - state.intensity) * smoothing;
5313
+ if (state.intensity < 5e-3) state.intensity = 0;
5314
+ if (state.intensity > state.peakIntensity) state.peakIntensity = state.intensity;
5315
+ state.rms = metrics.rms;
5316
+ state.flatness = metrics.flatness;
5317
+ const isBlowing = state.intensity >= blowingThreshold;
5318
+ if (isBlowing) {
5319
+ if (!state.blowing) blowingSinceMs = nowMs;
5320
+ state.sustainedMs = Math.max(0, nowMs - blowingSinceMs);
5321
+ } else {
5322
+ blowingSinceMs = 0;
5323
+ state.sustainedMs = 0;
5324
+ }
5325
+ state.blowing = isBlowing;
5326
+ return state;
5327
+ },
5328
+ getState() {
5329
+ return state;
5330
+ },
5331
+ dispose() {
5332
+ stop();
5333
+ }
5334
+ };
5335
+ }
5336
+
5337
+ // src/mic/level.ts
5338
+ function createMicLevelMeter(options = {}) {
5339
+ const gain = options.gain ?? 2.6;
5340
+ let input = null;
5341
+ let buf = null;
5342
+ let opSeq = 0;
5343
+ const state = {
5344
+ status: "idle",
5345
+ level: 0,
5346
+ peak: 0,
5347
+ rms: 0,
5348
+ deviceLabel: "",
5349
+ usingControllerMic: false
5350
+ };
5351
+ const stop = () => {
5352
+ opSeq++;
5353
+ input?.close();
5354
+ input = null;
5355
+ buf = null;
5356
+ if (state.status === "active") state.status = "idle";
5357
+ state.level = 0;
5358
+ state.rms = 0;
5359
+ };
5360
+ return {
5361
+ async start() {
5362
+ stop();
5363
+ const mySeq = opSeq;
5364
+ const opened = await openMicInput({ fftSize: 256, smoothing: 0.65, ...options });
5365
+ if (mySeq !== opSeq) {
5366
+ if (typeof opened !== "string") opened.close();
5367
+ return false;
5368
+ }
5369
+ if (typeof opened === "string") {
5370
+ state.status = opened;
5371
+ return false;
5372
+ }
5373
+ input = opened;
5374
+ buf = new Uint8Array(new ArrayBuffer(opened.analyser.fftSize));
5375
+ state.status = "active";
5376
+ state.peak = 0;
5377
+ state.deviceLabel = opened.label;
5378
+ state.usingControllerMic = opened.usingControllerMic;
5379
+ return true;
5380
+ },
5381
+ sample() {
5382
+ if (!input || !buf) return state;
5383
+ input.analyser.getByteTimeDomainData(buf);
5384
+ state.rms = timeDomainRms(buf);
5385
+ state.level = Math.min(1, state.rms * gain);
5386
+ if (state.level > state.peak) state.peak = state.level;
5387
+ return state;
5388
+ },
5389
+ getState: () => state,
5390
+ stop,
5391
+ dispose: stop
5392
+ };
5393
+ }
5394
+
5395
+ // src/game/types.ts
5396
+ function defineGame(game) {
5397
+ return game;
5398
+ }
5399
+
5400
+ // src/game/host.ts
5401
+ var NOOP_CONTINUOUS_HANDLE = {
5402
+ update() {
5403
+ },
5404
+ stop() {
5405
+ }
5406
+ };
5407
+ function createLocalBestScoreStorage(key) {
5408
+ return {
5409
+ getBestScore: () => {
5410
+ if (typeof localStorage === "undefined") return 0;
5411
+ try {
5412
+ const raw = localStorage.getItem(key);
5413
+ return raw ? Number(raw) || 0 : 0;
5414
+ } catch {
5415
+ return 0;
5416
+ }
5417
+ },
5418
+ saveBestScore: (score) => {
5419
+ if (typeof localStorage === "undefined") return;
5420
+ try {
5421
+ const prev = Number(localStorage.getItem(key) || 0);
5422
+ if (score > prev) localStorage.setItem(key, String(Math.round(score)));
5423
+ } catch {
5424
+ }
5425
+ }
5426
+ };
5427
+ }
5428
+ function createGameHost(opts) {
5429
+ const { gameId, locale, getPlayerSeats } = opts;
5430
+ const hub = createGamepadly(opts.hub);
5431
+ const active = hub.active;
5432
+ const idleKeyboardState = createEmptyInput();
5433
+ idleKeyboardState.source = "keyboard_mouse";
5434
+ idleKeyboardState.deviceName = "Keyboard & Mouse";
5435
+ idleKeyboardState.identity = {
5436
+ brand: "none",
5437
+ model: "none",
5438
+ displayName: "Keyboard & Mouse",
5439
+ rawId: "",
5440
+ transport: "disconnected",
5441
+ source: "keyboard_mouse"
5442
+ };
5443
+ const idleDisconnectedState = createEmptyInput();
5444
+ const sanitizeInput = opts.isolateKeyboardFallback === false ? (st) => st : (st) => st.source === "keyboard_mouse" ? idleKeyboardState : st;
5445
+ const slotHandleCache = /* @__PURE__ */ new Map();
5446
+ const getCachedSlotHandle = (slotId) => {
5447
+ let h = slotHandleCache.get(slotId);
5448
+ if (!h) {
5449
+ h = hub.player(slotId);
5450
+ slotHandleCache.set(slotId, h);
5451
+ }
5452
+ return h;
5453
+ };
5454
+ const unassignedHandle = hub.player("__unassigned_seat__");
5455
+ const createDynamicSeatHandle = (seatIndex) => {
5456
+ const resolveHandle = () => {
5457
+ const seats = getPlayerSeats?.();
5458
+ if (!seats) return hub.player(seatIndex);
5459
+ const slotId = seats[seatIndex] ?? null;
5460
+ return slotId ? getCachedSlotHandle(slotId) : null;
5461
+ };
5462
+ return {
5463
+ getSlotId: () => resolveHandle()?.getSlotId() ?? null,
5464
+ getCapabilities: () => {
5465
+ const h = resolveHandle();
5466
+ if (h) return h.getCapabilities();
5467
+ return { ...unassignedHandle.getCapabilities(), slotId: null };
5468
+ },
5469
+ input: {
5470
+ getState: () => {
5471
+ const h = resolveHandle();
5472
+ return h ? sanitizeInput(h.input.getState()) : idleDisconnectedState;
5473
+ },
5474
+ applyDeadzone
5475
+ },
5476
+ triggers: {
5477
+ reset: () => resolveHandle()?.triggers.reset(),
5478
+ setLeft: (effect) => resolveHandle()?.triggers.setLeft(effect),
5479
+ setRight: (effect) => resolveHandle()?.triggers.setRight(effect),
5480
+ setBoth: (left, right) => resolveHandle()?.triggers.setBoth(left, right),
5481
+ applyPreset: (presetId, side) => resolveHandle()?.triggers.applyPreset(presetId, side),
5482
+ pulseImpulse: (spec) => resolveHandle()?.triggers.pulseImpulse(spec)
5483
+ },
5484
+ haptics: {
5485
+ pulse: (spec) => resolveHandle()?.haptics.pulse(spec),
5486
+ sweep: (spec) => resolveHandle()?.haptics.sweep(spec),
5487
+ rumble: (o) => resolveHandle()?.haptics.rumble(o),
5488
+ hdRumble: (spec) => resolveHandle()?.haptics.hdRumble(spec),
5489
+ hdSequence: (steps) => resolveHandle()?.haptics.hdSequence(steps),
5490
+ playPreset: (presetId, o) => resolveHandle()?.haptics.playPreset(presetId, o),
5491
+ createContinuous: (preset) => resolveHandle()?.haptics.createContinuous(preset) ?? NOOP_CONTINUOUS_HANDLE,
5492
+ playComboPreset: (presetId, pan) => resolveHandle()?.haptics.playComboPreset(presetId, pan),
5493
+ stop: () => resolveHandle()?.haptics.stop()
5494
+ },
5495
+ // PC-bus sounds stay audible for an unassigned seat (they don't belong to a controller);
5496
+ // controller outputs (speaker tone, VCM, haptics, triggers, lightbar) stay inert.
5497
+ audio: {
5498
+ playPcTone: (spec) => (resolveHandle() ?? active).audio.playPcTone(spec),
5499
+ playPcNoise: (o) => (resolveHandle() ?? active).audio.playPcNoise(o),
5500
+ playControllerSpeakerTone: (spec) => resolveHandle()?.audio.playControllerSpeakerTone(spec),
5501
+ loadSample: (id, source) => active.audio.loadSample(id, source),
5502
+ hasSample: (id) => active.audio.hasSample(id),
5503
+ unloadSample: (id) => active.audio.unloadSample(id),
5504
+ playSample: (id, o = {}) => {
5505
+ const h = resolveHandle();
5506
+ if (h) return h.audio.playSample(id, o);
5507
+ if (o.route === "vcm") return NOOP_SAMPLE_HANDLE;
5508
+ return active.audio.playSample(id, toPcBusSampleOptions(o));
5509
+ }
5510
+ },
5511
+ lightbar: {
5512
+ setColor: (r, g, b) => resolveHandle()?.lightbar.setColor(r, g, b),
5513
+ flash: (r, g, b, durationMs) => resolveHandle()?.lightbar.flash(r, g, b, durationMs)
5514
+ },
5515
+ createActions: (spec) => (resolveHandle() ?? active).createActions(spec)
5516
+ };
5517
+ };
5518
+ const capListeners = /* @__PURE__ */ new Set();
5519
+ const micSensors = /* @__PURE__ */ new Set();
5520
+ const sdk = {
5521
+ gameId,
5522
+ locale,
5523
+ showcase: opts.showcase,
5524
+ getCapabilities: () => active.getCapabilities(),
5525
+ onCapabilitiesChange: (listener) => {
5526
+ capListeners.add(listener);
5527
+ const unsubHub = hub.onCapabilitiesChange(listener);
5528
+ return () => {
5529
+ capListeners.delete(listener);
5530
+ unsubHub();
5531
+ };
5532
+ },
5533
+ players: {
5534
+ getSlots: () => hub.getSlots(),
5535
+ get: (indexOrSlotId) => {
5536
+ if (typeof indexOrSlotId === "number" && getPlayerSeats) {
5537
+ return createDynamicSeatHandle(indexOrSlotId);
5538
+ }
5539
+ return typeof indexOrSlotId === "string" ? getCachedSlotHandle(indexOrSlotId) : hub.player(indexOrSlotId);
5540
+ }
5541
+ },
5542
+ input: {
5543
+ getState: () => sanitizeInput(active.input.getState()),
5544
+ applyDeadzone: active.input.applyDeadzone
5545
+ },
5546
+ triggers: active.triggers,
5547
+ haptics: active.haptics,
5548
+ audio: active.audio,
5549
+ lightbar: active.lightbar,
5550
+ createActions: (spec) => active.createActions(spec),
5551
+ createMicBlowSensor: (o) => {
5552
+ const sensor = createMicBlowSensor(o);
5553
+ micSensors.add(sensor);
5554
+ return {
5555
+ start: () => sensor.start(),
5556
+ sample: (nowMs) => sensor.sample(nowMs),
5557
+ getState: () => sensor.getState(),
5558
+ stop: () => sensor.stop(),
5559
+ dispose: () => {
5560
+ micSensors.delete(sensor);
5561
+ sensor.dispose();
5562
+ }
5563
+ };
5564
+ },
5565
+ storage: opts.storage ?? createLocalBestScoreStorage(`${opts.storageKeyPrefix ?? "gamepadly:best:"}${gameId}`)
5566
+ };
5567
+ let disposed = false;
5568
+ return {
5569
+ sdk,
5570
+ hub,
5571
+ notifyPlayerSeatsChanged: () => {
5572
+ if (disposed) return;
5573
+ const event = {
5574
+ slots: hub.getSlots(),
5575
+ active: active.getCapabilities()
5576
+ };
5577
+ for (const fn of capListeners) {
5578
+ try {
5579
+ fn(event);
5580
+ } catch {
5581
+ }
5582
+ }
5583
+ },
5584
+ dispose: () => {
5585
+ if (disposed) return;
5586
+ disposed = true;
5587
+ for (const m of micSensors) {
5588
+ try {
5589
+ m.dispose();
5590
+ } catch {
5591
+ }
5592
+ }
5593
+ micSensors.clear();
5594
+ capListeners.clear();
5595
+ slotHandleCache.clear();
5596
+ hub.dispose();
5597
+ }
5598
+ };
5599
+ }
5600
+
5601
+ // src/game/mock.ts
5602
+ var ALL_CAPABILITIES = [
5603
+ "standard_input",
5604
+ "analog_triggers",
5605
+ "dual_motor_rumble",
5606
+ "impulse_triggers",
5607
+ "hd_rumble",
5608
+ "adaptive_triggers",
5609
+ "audio_haptics",
5610
+ "controller_speaker",
5611
+ "gyro",
5612
+ "accelerometer",
5613
+ "touchpad",
5614
+ "lightbar",
5615
+ "battery"
5616
+ ];
5617
+ var BRAND_PROFILES = {
5618
+ sony: {
5619
+ model: "dualsense",
5620
+ displayName: "DualSense Wireless Controller",
5621
+ tier: "dualsense_full_4ch",
5622
+ caps: [
5623
+ "standard_input",
5624
+ "analog_triggers",
5625
+ "dual_motor_rumble",
5626
+ "adaptive_triggers",
5627
+ "audio_haptics",
5628
+ "controller_speaker",
5629
+ "gyro",
5630
+ "accelerometer",
5631
+ "touchpad",
5632
+ "lightbar",
5633
+ "battery"
5634
+ ]
5635
+ },
5636
+ nintendo: {
5637
+ model: "switch_pro",
5638
+ displayName: "Switch Pro Controller",
5639
+ tier: "switch_pro_hid",
5640
+ caps: ["standard_input", "hd_rumble", "gyro", "accelerometer", "battery"]
5641
+ },
5642
+ xbox: {
5643
+ model: "xbox_series",
5644
+ displayName: "Xbox Wireless Controller",
5645
+ tier: "xbox_impulse",
5646
+ caps: ["standard_input", "analog_triggers", "dual_motor_rumble", "impulse_triggers"]
5647
+ },
5648
+ generic: {
5649
+ model: "generic",
5650
+ displayName: "Standard Gamepad",
5651
+ tier: "standard_gamepad",
5652
+ caps: ["standard_input", "analog_triggers", "dual_motor_rumble"]
5653
+ },
5654
+ none: {
5655
+ model: "none",
5656
+ displayName: "Keyboard & Mouse",
5657
+ tier: "keyboard_mouse",
5658
+ caps: []
5659
+ }
5660
+ };
5661
+ function buildCapabilities(slotId, state, tier, ready) {
5662
+ const matrix = {};
5663
+ for (const id of ALL_CAPABILITIES) {
5664
+ matrix[id] = { inherent: ready.has(id), availability: ready.has(id) ? "ready" : "unsupported" };
5665
+ }
5666
+ const has = (cap) => ready.has(cap);
5667
+ return {
5668
+ slotId,
5669
+ tier,
5670
+ identity: state.identity,
5671
+ matrix,
5672
+ has,
5673
+ hasAdaptiveTriggers: has("adaptive_triggers"),
5674
+ hasImpulseTriggers: has("impulse_triggers"),
5675
+ hasHdRumble: has("hd_rumble"),
5676
+ hasDualRumble: has("dual_motor_rumble"),
5677
+ has4ChHaptics: has("audio_haptics"),
5678
+ hasControllerSpeaker: has("controller_speaker"),
5679
+ hasGyro: has("gyro"),
5680
+ hasTouchpad: has("touchpad")
5681
+ };
5682
+ }
5683
+ var noop = () => {
5684
+ };
5685
+ function createMockPlayerHandle(options = {}, index = 0) {
5686
+ const brand = options.brand ?? "generic";
5687
+ const profile = BRAND_PROFILES[brand];
5688
+ const slotId = options.slotId ?? `gp-${index}`;
5689
+ const connected = brand !== "none";
5690
+ const state = createEmptyInput();
5691
+ state.connected = connected;
5692
+ state.source = connected ? "gamepad" : "keyboard_mouse";
5693
+ state.deviceName = options.displayName ?? profile.displayName;
5694
+ state.identity = {
5695
+ ...state.identity,
5696
+ brand,
5697
+ model: profile.model,
5698
+ displayName: options.displayName ?? profile.displayName,
5699
+ transport: connected ? "usb" : "disconnected",
5700
+ source: connected ? "gamepad" : "keyboard_mouse"
5701
+ };
5702
+ const ready = new Set(profile.caps);
5703
+ return {
5704
+ state,
5705
+ getSlotId: () => connected ? slotId : null,
5706
+ getCapabilities: () => buildCapabilities(connected ? slotId : null, state, profile.tier, ready),
5707
+ input: {
5708
+ getState: () => state,
5709
+ applyDeadzone
5710
+ },
5711
+ triggers: {
5712
+ reset: noop,
5713
+ setLeft: noop,
5714
+ setRight: noop,
5715
+ setBoth: noop,
5716
+ applyPreset: noop,
5717
+ pulseImpulse: noop
5718
+ },
5719
+ haptics: {
5720
+ pulse: noop,
5721
+ sweep: noop,
5722
+ rumble: noop,
5723
+ hdRumble: noop,
5724
+ hdSequence: noop,
5725
+ playPreset: noop,
5726
+ createContinuous: () => ({ update: noop, stop: noop }),
5727
+ playComboPreset: noop,
5728
+ stop: noop
5729
+ },
5730
+ audio: {
5731
+ playPcTone: noop,
5732
+ playPcNoise: noop,
5733
+ playControllerSpeakerTone: noop,
5734
+ loadSample: async () => false,
5735
+ hasSample: () => false,
5736
+ unloadSample: noop,
5737
+ playSample: () => NOOP_SAMPLE_HANDLE
5738
+ },
5739
+ lightbar: {
5740
+ setColor: noop,
5741
+ flash: noop
5742
+ },
5743
+ createActions: (spec) => createActionTracker(spec)
5744
+ };
5745
+ }
5746
+ var IDLE_MIC_STATE = {
5747
+ status: "idle",
5748
+ intensity: 0,
5749
+ blowing: false,
5750
+ sustainedMs: 0,
5751
+ peakIntensity: 0,
5752
+ rms: 0,
5753
+ flatness: 0,
5754
+ deviceLabel: "",
5755
+ usingControllerMic: false
5756
+ };
5757
+ function createIdleMicSensor() {
5758
+ return {
5759
+ start: async () => false,
5760
+ stop: noop,
5761
+ sample: () => ({ ...IDLE_MIC_STATE }),
5762
+ getState: () => ({ ...IDLE_MIC_STATE }),
5763
+ dispose: noop
5764
+ };
5765
+ }
5766
+ function createMockGameSDK(options) {
5767
+ const playerOptions = options.players ?? [{}];
5768
+ const mockPlayers = playerOptions.map((p, i) => createMockPlayerHandle(p, i));
5769
+ const keyboard = createMockPlayerHandle({ brand: "none", slotId: "__keyboard__" });
5770
+ const p1 = mockPlayers[0] ?? keyboard;
5771
+ const slots = mockPlayers.filter((p) => p.state.connected).map((p, i) => ({
5772
+ id: p.getSlotId() ?? `gp-${i}`,
5773
+ playerNumber: i + 1,
5774
+ source: "gamepad",
5775
+ identity: p.state.identity,
5776
+ battery: { percent: 100, charging: false, full: false, known: false },
5777
+ observedReportHz: null,
5778
+ lastActivityAt: 0
5779
+ }));
5780
+ let best = options.bestScore ?? 0;
5781
+ const storage = {
5782
+ getBestScore: () => best,
5783
+ saveBestScore: (score) => {
5784
+ if (score > best) best = Math.round(score);
5785
+ }
5786
+ };
5787
+ return {
5788
+ gameId: options.gameId,
5789
+ locale: options.locale,
5790
+ showcase: options.showcase,
5791
+ mockPlayers,
5792
+ getCapabilities: () => p1.getCapabilities(),
5793
+ onCapabilitiesChange: () => () => {
5794
+ },
5795
+ players: {
5796
+ getSlots: () => slots.map((s) => ({ ...s })),
5797
+ get: (indexOrSlotId) => {
5798
+ if (typeof indexOrSlotId === "number") return mockPlayers[indexOrSlotId] ?? keyboard;
5799
+ return mockPlayers.find((p) => p.getSlotId() === indexOrSlotId) ?? keyboard;
5800
+ }
5801
+ },
5802
+ input: p1.input,
5803
+ triggers: p1.triggers,
5804
+ haptics: p1.haptics,
5805
+ audio: p1.audio,
5806
+ lightbar: p1.lightbar,
5807
+ createActions: (spec) => createActionTracker(spec),
5808
+ createMicBlowSensor: () => createIdleMicSensor(),
5809
+ storage
5810
+ };
5811
+ }
5812
+
5813
+ // src/game/seats.ts
5814
+ function createInitialSeats(slots, maxPlayers) {
5815
+ const count = Math.max(1, maxPlayers);
5816
+ return Array.from({ length: count }, (_, idx) => slots[idx]?.id ?? null);
5817
+ }
5818
+ function reconcileSeats(prevSeats, prevSlots, nextSlots, maxPlayers) {
5819
+ const count = Math.max(1, maxPlayers);
5820
+ if (prevSlots.length === 0) {
5821
+ return createInitialSeats(nextSlots, count);
5822
+ }
5823
+ const nextById = new Map(nextSlots.map((s) => [s.id, s]));
5824
+ const prevById = new Map(prevSlots.map((s) => [s.id, s]));
5825
+ const prevIds = new Set(prevSlots.map((s) => s.id));
5826
+ const seats = Array.from({ length: count }, (_, idx) => prevSeats[idx] ?? null);
5827
+ const usedIds = /* @__PURE__ */ new Set();
5828
+ const vanishedIndices = [];
5829
+ for (let i = 0; i < count; i++) {
5830
+ const id = seats[i];
5831
+ if (!id) continue;
5832
+ if (nextById.has(id) && !usedIds.has(id)) {
5833
+ usedIds.add(id);
5834
+ } else {
5835
+ vanishedIndices.push(i);
5836
+ }
5837
+ }
5838
+ const newCandidates = nextSlots.filter((s) => !prevIds.has(s.id) && !usedIds.has(s.id));
5839
+ for (const seatIdx of vanishedIndices) {
5840
+ const oldId = seats[seatIdx];
5841
+ const oldBrand = oldId ? prevById.get(oldId)?.brand : void 0;
5842
+ const matchIdx = oldBrand ? newCandidates.findIndex((c) => c.brand === oldBrand && !usedIds.has(c.id)) : -1;
5843
+ if (matchIdx >= 0) {
5844
+ const migrated = newCandidates.splice(matchIdx, 1)[0];
5845
+ seats[seatIdx] = migrated.id;
5846
+ usedIds.add(migrated.id);
5847
+ } else {
5848
+ seats[seatIdx] = null;
5849
+ }
5850
+ }
5851
+ for (const candidate of newCandidates) {
5852
+ const emptyIdx = seats.indexOf(null);
5853
+ if (emptyIdx === -1) break;
5854
+ seats[emptyIdx] = candidate.id;
5855
+ usedIds.add(candidate.id);
5856
+ }
5857
+ return seats;
5858
+ }
5859
+ function toggleSeatAssignment(prevSeats, slotId, maxPlayers) {
5860
+ const count = Math.max(1, maxPlayers);
5861
+ const seats = Array.from({ length: count }, (_, idx) => prevSeats[idx] ?? null);
5862
+ const existingIdx = seats.indexOf(slotId);
5863
+ if (existingIdx >= 0) {
5864
+ seats[existingIdx] = null;
5865
+ return seats;
5866
+ }
5867
+ const emptyIdx = seats.indexOf(null);
5868
+ if (emptyIdx >= 0) {
5869
+ seats[emptyIdx] = slotId;
5870
+ return seats;
5871
+ }
5872
+ return [...seats.slice(1), slotId];
5873
+ }
5874
+
5875
+ // src/diagnostics/circularity.ts
5876
+ var CIRCULARITY_SECTORS = 72;
5877
+ var SECTORS = CIRCULARITY_SECTORS;
5878
+ var CIRCULARITY_MIN_RIM_MAGNITUDE = 0.72;
5879
+ var CIRCULARITY_MIN_SECTORS = 12;
5880
+ function createCircularity() {
5881
+ return {
5882
+ sectors: new Float32Array(SECTORS),
5883
+ coveragePct: 0,
5884
+ avgErrorPct: null,
5885
+ maxMag: 0
5886
+ };
5887
+ }
5888
+ function updateCircularity(c, x, y) {
5889
+ const mag = Math.hypot(x, y);
5890
+ if (mag > c.maxMag) c.maxMag = mag;
5891
+ if (mag < CIRCULARITY_MIN_RIM_MAGNITUDE) return;
5892
+ let ang = Math.atan2(y, x);
5893
+ if (ang < 0) ang += Math.PI * 2;
5894
+ const idx = Math.min(SECTORS - 1, Math.floor(ang / (Math.PI * 2) * SECTORS));
5895
+ if (mag > c.sectors[idx]) {
5896
+ c.sectors[idx] = mag;
5897
+ let filled = 0;
5898
+ let errSum = 0;
5899
+ for (let i = 0; i < SECTORS; i++) {
5900
+ if (c.sectors[i] > 0) {
5901
+ filled++;
5902
+ errSum += Math.abs(c.sectors[i] - 1);
5903
+ }
5904
+ }
5905
+ c.coveragePct = Math.round(filled / SECTORS * 100);
5906
+ c.avgErrorPct = filled >= CIRCULARITY_MIN_SECTORS ? Number((errSum / filled * 100).toFixed(1)) : null;
5907
+ }
5908
+ }
5909
+ function buildSectorPath(sectors, cx, cy, radius) {
5910
+ const pts = [];
5911
+ for (let i = 0; i < SECTORS; i++) {
5912
+ const r = sectors[i];
5913
+ if (r <= 0) continue;
5914
+ const ang = (i + 0.5) / SECTORS * Math.PI * 2;
5915
+ const clampedR = Math.min(1.22, r);
5916
+ const px = cx + Math.cos(ang) * radius * clampedR;
5917
+ const py = cy + Math.sin(ang) * radius * clampedR;
5918
+ pts.push(`${pts.length === 0 ? "M" : "L"}${px.toFixed(1)},${py.toFixed(1)}`);
5919
+ }
5920
+ if (pts.length >= 24) pts.push("Z");
5921
+ return pts.join(" ");
5922
+ }
5923
+
5924
+ // src/diagnostics/stick.ts
5925
+ var DEFAULT_DRIFT_THRESHOLDS = Object.freeze({
5926
+ mildOffset: 0.03,
5927
+ driftOffset: 0.08,
5928
+ mildJitter: 0.015,
5929
+ driftJitter: 0.03
5930
+ });
5931
+ function createRestState() {
5932
+ return {
5933
+ inRestSince: null,
5934
+ sessionActive: false,
5935
+ sessionMinX: 0,
5936
+ sessionMaxX: 0,
5937
+ sessionMinY: 0,
5938
+ sessionMaxY: 0,
5939
+ settled: false,
5940
+ peakOffset: 0,
5941
+ peakJitter: 0
5942
+ };
5943
+ }
5944
+ function classifyRestVerdict(settled, peakOffset, peakJitter, thresholds = DEFAULT_DRIFT_THRESHOLDS) {
5945
+ if (!settled) return "waiting";
5946
+ if (peakOffset >= thresholds.driftOffset || peakJitter >= thresholds.driftJitter) return "drift";
5947
+ if (peakOffset >= thresholds.mildOffset || peakJitter >= thresholds.mildJitter) return "mild";
5948
+ return "normal";
5949
+ }
5950
+ var StickDriftTracker = class {
5951
+ left = createRestState();
5952
+ right = createRestState();
5953
+ restMaxMag;
5954
+ settleMs;
5955
+ thresholds;
5956
+ constructor(options = {}) {
5957
+ this.restMaxMag = options.restMaxMagnitude ?? 0.22;
5958
+ this.settleMs = options.settleMs ?? 350;
5959
+ this.thresholds = { ...DEFAULT_DRIFT_THRESHOLDS, ...options.thresholds };
5960
+ }
5961
+ updateAxis(state, x, y, now) {
5962
+ const mag = Math.hypot(x, y);
5963
+ if (mag >= this.restMaxMag) {
5964
+ state.inRestSince = null;
5965
+ state.sessionActive = false;
5966
+ return;
5967
+ }
5968
+ if (state.inRestSince === null) {
5969
+ state.inRestSince = now;
5970
+ state.sessionActive = false;
5971
+ return;
5972
+ }
5973
+ if (now - state.inRestSince < this.settleMs) return;
5974
+ if (!state.sessionActive) {
5975
+ state.sessionActive = true;
5976
+ state.sessionMinX = x;
5977
+ state.sessionMaxX = x;
5978
+ state.sessionMinY = y;
5979
+ state.sessionMaxY = y;
5980
+ } else {
5981
+ if (x < state.sessionMinX) state.sessionMinX = x;
5982
+ if (x > state.sessionMaxX) state.sessionMaxX = x;
5983
+ if (y < state.sessionMinY) state.sessionMinY = y;
5984
+ if (y > state.sessionMaxY) state.sessionMaxY = y;
5985
+ }
5986
+ state.settled = true;
5987
+ if (mag > state.peakOffset) state.peakOffset = mag;
5988
+ const jitter = Math.max(state.sessionMaxX - state.sessionMinX, state.sessionMaxY - state.sessionMinY);
5989
+ if (jitter > state.peakJitter) state.peakJitter = jitter;
5990
+ }
5991
+ update(lx, ly, rx, ry, now) {
5992
+ this.updateAxis(this.left, lx, ly, now);
5993
+ this.updateAxis(this.right, rx, ry, now);
5994
+ }
5995
+ snapshotAxis(state) {
5996
+ const peakOffset = Number(state.peakOffset.toFixed(4));
5997
+ const peakJitter = Number(state.peakJitter.toFixed(4));
5998
+ return {
5999
+ settled: state.settled,
6000
+ peakOffset,
6001
+ peakJitter,
6002
+ verdict: classifyRestVerdict(state.settled, peakOffset, peakJitter, this.thresholds)
6003
+ };
6004
+ }
6005
+ getSnapshot() {
6006
+ return {
6007
+ left: this.snapshotAxis(this.left),
6008
+ right: this.snapshotAxis(this.right)
6009
+ };
6010
+ }
6011
+ reset() {
6012
+ this.left = createRestState();
6013
+ this.right = createRestState();
6014
+ }
6015
+ };
6016
+ var ButtonBounceTracker = class {
6017
+ states = /* @__PURE__ */ new Map();
6018
+ counts = /* @__PURE__ */ new Map();
6019
+ releaseMaxMs;
6020
+ pressIntervalMaxMs;
6021
+ constructor(options = {}) {
6022
+ this.releaseMaxMs = options.releaseMaxMs ?? 55;
6023
+ this.pressIntervalMaxMs = options.pressIntervalMaxMs ?? 90;
6024
+ }
6025
+ update(buttons, now) {
6026
+ for (const [key, pressed] of Object.entries(buttons)) {
6027
+ let timing = this.states.get(key);
6028
+ if (!timing) {
6029
+ timing = { pressed, lastPressAt: pressed ? now : 0, lastReleaseAt: 0 };
6030
+ this.states.set(key, timing);
6031
+ continue;
6032
+ }
6033
+ if (pressed && !timing.pressed) {
6034
+ if (timing.lastReleaseAt > 0 && timing.lastPressAt > 0 && now - timing.lastReleaseAt <= this.releaseMaxMs && now - timing.lastPressAt <= this.pressIntervalMaxMs) {
6035
+ this.counts.set(key, (this.counts.get(key) ?? 0) + 1);
6036
+ }
6037
+ timing.lastPressAt = now;
6038
+ } else if (!pressed && timing.pressed) {
6039
+ timing.lastReleaseAt = now;
6040
+ }
6041
+ timing.pressed = pressed;
6042
+ }
6043
+ }
6044
+ getBouncedButtons() {
6045
+ return Array.from(this.counts.keys());
6046
+ }
6047
+ reset() {
6048
+ this.states.clear();
6049
+ this.counts.clear();
6050
+ }
6051
+ };
6052
+
6053
+ // src/diagnostics/telemetry.ts
6054
+ function createControllerTelemetry(options) {
6055
+ const { source, brandFilter } = options;
6056
+ const setActive = options.setActiveSlot ?? ((id) => void source.setActiveSlot(id));
6057
+ const switcher = new SlotAutoSwitcher();
6058
+ const memory = /* @__PURE__ */ new Map();
6059
+ let latestSamples = [];
6060
+ let activeKey = brandFilter ? `__none_${brandFilter}__` : "__none__";
6061
+ const createDiagnostics = () => ({
6062
+ circularity: { left: createCircularity(), right: createCircularity() },
6063
+ drift: new StickDriftTracker(options.drift),
6064
+ bounce: new ButtonBounceTracker(options.bounce),
6065
+ tested: /* @__PURE__ */ new Set()
6066
+ });
6067
+ const getDiagnostics = (key) => {
6068
+ let d = memory.get(key);
6069
+ if (!d) {
6070
+ d = createDiagnostics();
6071
+ memory.set(key, d);
6072
+ }
6073
+ return d;
6074
+ };
6075
+ return {
6076
+ update(now) {
6077
+ const allSlots = source.getConnectedControllers();
6078
+ const slots = brandFilter ? allSlots.filter((s) => s.identity.brand === brandFilter) : allSlots;
6079
+ const otherSlots = brandFilter ? allSlots.filter((s) => s.identity.brand !== brandFilter) : [];
6080
+ const globalActiveId = source.getActiveSlotId();
6081
+ let activeSlotId = globalActiveId;
6082
+ if (brandFilter) {
6083
+ if (slots.length === 0) {
6084
+ activeSlotId = null;
6085
+ } else if (!globalActiveId || !slots.some((s) => s.id === globalActiveId)) {
6086
+ activeSlotId = slots[0].id;
6087
+ setActive(activeSlotId);
6088
+ }
6089
+ }
6090
+ let triggered = false;
6091
+ if (slots.length > 0) {
6092
+ latestSamples = slots.map((slot) => {
6093
+ const s = source.getInputState(slot.id);
6094
+ return {
6095
+ id: slot.id,
6096
+ lastActivityAt: slot.lastActivityAt,
6097
+ lx: s.lx,
6098
+ ly: s.ly,
6099
+ rx: s.rx,
6100
+ ry: s.ry,
6101
+ l2: s.l2,
6102
+ r2: s.r2
6103
+ };
6104
+ });
6105
+ const { switchTo, triggeredSlotId } = switcher.evaluate(latestSamples, activeSlotId, now);
6106
+ if (switchTo && switchTo !== activeSlotId) {
6107
+ activeSlotId = switchTo;
6108
+ setActive(switchTo);
6109
+ }
6110
+ triggered = triggeredSlotId !== null;
6111
+ } else {
6112
+ latestSamples = [];
6113
+ }
6114
+ const slotKey = activeSlotId ?? (brandFilter ? `__none_${brandFilter}__` : "__none__");
6115
+ activeKey = slotKey;
6116
+ const diagnostics = getDiagnostics(slotKey);
6117
+ const input = activeSlotId ? source.getInputState(activeSlotId) : brandFilter ? createEmptyInput() : source.getInputState();
6118
+ if (input.connected) {
6119
+ updateCircularity(diagnostics.circularity.left, input.lx, input.ly);
6120
+ updateCircularity(diagnostics.circularity.right, input.rx, input.ry);
6121
+ diagnostics.drift.update(input.lx, input.ly, input.rx, input.ry, now);
6122
+ diagnostics.bounce.update(input.buttons, now);
6123
+ for (const [btn, pressed] of Object.entries(input.buttons)) {
6124
+ if (pressed) diagnostics.tested.add(btn);
6125
+ }
6126
+ }
6127
+ return { now, slots, otherSlots, activeSlotId, slotKey, input, triggered, diagnostics };
6128
+ },
6129
+ selectSlot(slotId, now) {
6130
+ switcher.notifyManualSelect(latestSamples, now);
6131
+ setActive(slotId);
6132
+ },
6133
+ resetActive() {
6134
+ memory.set(activeKey, createDiagnostics());
6135
+ },
6136
+ getDiagnostics
6137
+ };
3654
6138
  }
3655
6139
 
3656
6140
  // src/bridge/profiles.ts
@@ -4276,29 +6760,69 @@ function createGameLoop(options) {
4276
6760
  }
4277
6761
  export {
4278
6762
  BUILTIN_BRIDGE_PROFILES,
6763
+ ButtonBounceTracker,
6764
+ CIRCULARITY_MIN_RIM_MAGNITUDE,
6765
+ CIRCULARITY_MIN_SECTORS,
6766
+ CIRCULARITY_SECTORS,
4279
6767
  COMPANION_HTTP_BASE,
4280
6768
  COMPANION_WS_BASE,
6769
+ CONTROLLER_MIC_RE,
4281
6770
  DualSenseControllerManager as ControllerManager,
6771
+ DEFAULT_DRIFT_THRESHOLDS,
4282
6772
  DualSenseControllerManager,
6773
+ LINK_PROTOCOL_START_URI,
6774
+ NOOP_SAMPLE_HANDLE,
6775
+ SlotAutoSwitcher,
6776
+ StickDriftTracker,
4283
6777
  TACTILE_PRESETS,
4284
6778
  TRIGGER_PRESETS,
4285
6779
  ThreeLayerAudioEngine,
6780
+ TriggerFeedbackController,
6781
+ analyzeBlowSpectrum,
4286
6782
  applyDeadzone,
6783
+ attachControllerLifecycle,
6784
+ buildSectorPath,
4287
6785
  buildSwitchHdFromPulse,
6786
+ classifyRestVerdict,
6787
+ connectDualSenseViaBrowser,
6788
+ connectDualSenseViaCompanion,
4288
6789
  crc32WithSeed,
4289
6790
  createActionTracker,
4290
6791
  createCanvasStage,
6792
+ createCircularity,
6793
+ createControllerTelemetry,
4291
6794
  createDisposables,
4292
6795
  createEmptyInput,
6796
+ createGameHost,
4293
6797
  createGameLoop,
4294
6798
  createGamepadly,
6799
+ createInitialSeats,
4295
6800
  createKeyMouseBridge,
4296
6801
  createLinkAudio,
6802
+ createLocalBestScoreStorage,
6803
+ createMicBlowSensor,
6804
+ createMicLevelMeter,
6805
+ createMockGameSDK,
6806
+ createMockPlayerHandle,
6807
+ createMotionTracker,
6808
+ createPcAudioRouting,
6809
+ createSampleBank,
6810
+ createTactileBuffer,
6811
+ createTouchpadGestures,
6812
+ defineGame,
4297
6813
  encodeSwitchHdRumbleSide,
4298
6814
  encodeTriggerEffect,
4299
6815
  identifyGamepadFromId,
6816
+ isMicInputSupported,
6817
+ launchLinkViaProtocol,
6818
+ openMicInput,
6819
+ reconcileSeats,
4300
6820
  routeHapticPulse,
4301
6821
  routeHapticSweep,
4302
- routeTactilePreset
6822
+ routeTactilePreset,
6823
+ shouldAutoLaunchLink,
6824
+ timeDomainRms,
6825
+ toggleSeatAssignment,
6826
+ updateCircularity
4303
6827
  };
4304
6828
  //# sourceMappingURL=browser.js.map