winzik/engine/web/jumphp-gamepad.js
David Nurdin a74fe529a5 Web APIs: WebGL, page lifecycle, phone features, async HTTP, PWA, gamepads
- JsBridge both ways, synchronous with the frames (emscripten pre/postMainLoop);
  hide/close delivered at once between frames (jumphp_events)
- JumPHP\Gl\WebGl: 3D layer composed with the SDL picture (key colour / alpha),
  post-processing shaders, Mat4 (also software 3D on desktop)
- JumPHP\Device\Lifecycle (hide/show/blur/focus/online/offline/resize/close,
  pause_scene, mute when hidden) and Device (vibrate, wake lock, orientation,
  fullscreen, clipboard, tilt/motion, battery)
- JumPHP\Http: async requests (fetch / curl_multi / non-blocking sockets)
- JumPHP\Device\Pwa + sw.js: installable, offline, updates (game.yaml pwa)
- Gamepad: standard button names everywhere (pad0:a, pad0:start...), axes,
  hot-plug, rumble; Gamepad API in the browser
- games/hello-webgl example, docs/api-web.md, AGENTS.md

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-28 09:58:52 +01:00

33 lines
1.3 KiB
JavaScript

// Gamepads for PHP (JumPHP\Input\Gamepad): before each PHP frame, the state of navigator.getGamepads()
// goes to PHP (JsBridge 'gamepad': {pads: [{i, id, std, b: [values], a: [values]}]}) when it changed.
// "standard" mapping pads (nearly all) have W3C button numbers: PHP names them (a, b, start, lt...).
// PHP -> page: {do: 'rumble', pad, strong, weak, ms} (Chromium: vibrationActuator).
export function install(api) {
if (!navigator.getGamepads) return {};
let last = '';
const round = (v) => Math.round(v * 1000) / 1000;
api.beforeFrame(() => {
const pads = [];
for (const gp of navigator.getGamepads()) {
if (!gp || !gp.connected) continue;
pads.push({
i: gp.index, id: gp.id, std: gp.mapping === 'standard',
b: gp.buttons.map((b) => round(b.value || (b.pressed ? 1 : 0))),
a: gp.axes.map(round),
});
}
const json = JSON.stringify(pads);
if (json === last) return;
last = json;
api.send('gamepad', { pads }, 'gamepad');
});
api.on('gamepad', (msg) => {
if (msg.do !== 'rumble') return;
const gp = navigator.getGamepads()[msg.pad];
const actuator = gp && gp.vibrationActuator;
if (actuator && actuator.playEffect) {
actuator.playEffect('dual-rumble', { duration: msg.ms, strongMagnitude: msg.strong, weakMagnitude: msg.weak }).catch(() => {});
}
});
return {};
}