library_godot_input.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. /**************************************************************************/
  2. /* library_godot_input.js */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. /*
  31. * Gamepad API helper.
  32. */
  33. const GodotInputGamepads = {
  34. $GodotInputGamepads__deps: ['$GodotRuntime', '$GodotEventListeners'],
  35. $GodotInputGamepads: {
  36. samples: [],
  37. get_pads: function () {
  38. try {
  39. // Will throw in iframe when permission is denied.
  40. // Will throw/warn in the future for insecure contexts.
  41. // See https://github.com/w3c/gamepad/pull/120
  42. const pads = navigator.getGamepads();
  43. if (pads) {
  44. return pads;
  45. }
  46. return [];
  47. } catch (e) {
  48. return [];
  49. }
  50. },
  51. get_samples: function () {
  52. return GodotInputGamepads.samples;
  53. },
  54. get_sample: function (index) {
  55. const samples = GodotInputGamepads.samples;
  56. return index < samples.length ? samples[index] : null;
  57. },
  58. sample: function () {
  59. const pads = GodotInputGamepads.get_pads();
  60. const samples = [];
  61. for (let i = 0; i < pads.length; i++) {
  62. const pad = pads[i];
  63. if (!pad) {
  64. samples.push(null);
  65. continue;
  66. }
  67. const s = {
  68. standard: pad.mapping === 'standard',
  69. buttons: [],
  70. axes: [],
  71. connected: pad.connected,
  72. };
  73. for (let b = 0; b < pad.buttons.length; b++) {
  74. s.buttons.push(pad.buttons[b].value);
  75. }
  76. for (let a = 0; a < pad.axes.length; a++) {
  77. s.axes.push(pad.axes[a]);
  78. }
  79. samples.push(s);
  80. }
  81. GodotInputGamepads.samples = samples;
  82. },
  83. init: function (onchange) {
  84. GodotInputGamepads.samples = [];
  85. function add(pad) {
  86. const guid = GodotInputGamepads.get_guid(pad);
  87. const c_id = GodotRuntime.allocString(pad.id);
  88. const c_guid = GodotRuntime.allocString(guid);
  89. onchange(pad.index, 1, c_id, c_guid);
  90. GodotRuntime.free(c_id);
  91. GodotRuntime.free(c_guid);
  92. }
  93. const pads = GodotInputGamepads.get_pads();
  94. for (let i = 0; i < pads.length; i++) {
  95. // Might be reserved space.
  96. if (pads[i]) {
  97. add(pads[i]);
  98. }
  99. }
  100. GodotEventListeners.add(window, 'gamepadconnected', function (evt) {
  101. if (evt.gamepad) {
  102. add(evt.gamepad);
  103. }
  104. }, false);
  105. GodotEventListeners.add(window, 'gamepaddisconnected', function (evt) {
  106. if (evt.gamepad) {
  107. onchange(evt.gamepad.index, 0);
  108. }
  109. }, false);
  110. },
  111. get_guid: function (pad) {
  112. if (pad.mapping) {
  113. return pad.mapping;
  114. }
  115. const ua = navigator.userAgent;
  116. let os = 'Unknown';
  117. if (ua.indexOf('Android') >= 0) {
  118. os = 'Android';
  119. } else if (ua.indexOf('Linux') >= 0) {
  120. os = 'Linux';
  121. } else if (ua.indexOf('iPhone') >= 0) {
  122. os = 'iOS';
  123. } else if (ua.indexOf('Macintosh') >= 0) {
  124. // Updated iPads will fall into this category.
  125. os = 'MacOSX';
  126. } else if (ua.indexOf('Windows') >= 0) {
  127. os = 'Windows';
  128. }
  129. const id = pad.id;
  130. // Chrom* style: NAME (Vendor: xxxx Product: xxxx)
  131. const exp1 = /vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i;
  132. // Firefox/Safari style (safari may remove leading zeores)
  133. const exp2 = /^([0-9a-f]+)-([0-9a-f]+)-/i;
  134. let vendor = '';
  135. let product = '';
  136. if (exp1.test(id)) {
  137. const match = exp1.exec(id);
  138. vendor = match[1].padStart(4, '0');
  139. product = match[2].padStart(4, '0');
  140. } else if (exp2.test(id)) {
  141. const match = exp2.exec(id);
  142. vendor = match[1].padStart(4, '0');
  143. product = match[2].padStart(4, '0');
  144. }
  145. if (!vendor || !product) {
  146. return `${os}Unknown`;
  147. }
  148. return os + vendor + product;
  149. },
  150. },
  151. };
  152. mergeInto(LibraryManager.library, GodotInputGamepads);
  153. /*
  154. * Drag and drop helper.
  155. * This is pretty big, but basically detect dropped files on GodotConfig.canvas,
  156. * process them one by one (recursively for directories), and copies them to
  157. * the temporary FS path '/tmp/drop-[random]/' so it can be emitted as a godot
  158. * event (that requires a string array of paths).
  159. *
  160. * NOTE: The temporary files are removed after the callback. This means that
  161. * deferred callbacks won't be able to access the files.
  162. */
  163. const GodotInputDragDrop = {
  164. $GodotInputDragDrop__deps: ['$FS', '$GodotFS'],
  165. $GodotInputDragDrop: {
  166. promises: [],
  167. pending_files: [],
  168. add_entry: function (entry) {
  169. if (entry.isDirectory) {
  170. GodotInputDragDrop.add_dir(entry);
  171. } else if (entry.isFile) {
  172. GodotInputDragDrop.add_file(entry);
  173. } else {
  174. GodotRuntime.error('Unrecognized entry...', entry);
  175. }
  176. },
  177. add_dir: function (entry) {
  178. GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) {
  179. const reader = entry.createReader();
  180. reader.readEntries(function (entries) {
  181. for (let i = 0; i < entries.length; i++) {
  182. GodotInputDragDrop.add_entry(entries[i]);
  183. }
  184. resolve();
  185. });
  186. }));
  187. },
  188. add_file: function (entry) {
  189. GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) {
  190. entry.file(function (file) {
  191. const reader = new FileReader();
  192. reader.onload = function () {
  193. const f = {
  194. 'path': file.relativePath || file.webkitRelativePath,
  195. 'name': file.name,
  196. 'type': file.type,
  197. 'size': file.size,
  198. 'data': reader.result,
  199. };
  200. if (!f['path']) {
  201. f['path'] = f['name'];
  202. }
  203. GodotInputDragDrop.pending_files.push(f);
  204. resolve();
  205. };
  206. reader.onerror = function () {
  207. GodotRuntime.print('Error reading file');
  208. reject();
  209. };
  210. reader.readAsArrayBuffer(file);
  211. }, function (err) {
  212. GodotRuntime.print('Error!');
  213. reject();
  214. });
  215. }));
  216. },
  217. process: function (resolve, reject) {
  218. if (GodotInputDragDrop.promises.length === 0) {
  219. resolve();
  220. return;
  221. }
  222. GodotInputDragDrop.promises.pop().then(function () {
  223. setTimeout(function () {
  224. GodotInputDragDrop.process(resolve, reject);
  225. }, 0);
  226. });
  227. },
  228. _process_event: function (ev, callback) {
  229. ev.preventDefault();
  230. if (ev.dataTransfer.items) {
  231. // Use DataTransferItemList interface to access the file(s)
  232. for (let i = 0; i < ev.dataTransfer.items.length; i++) {
  233. const item = ev.dataTransfer.items[i];
  234. let entry = null;
  235. if ('getAsEntry' in item) {
  236. entry = item.getAsEntry();
  237. } else if ('webkitGetAsEntry' in item) {
  238. entry = item.webkitGetAsEntry();
  239. }
  240. if (entry) {
  241. GodotInputDragDrop.add_entry(entry);
  242. }
  243. }
  244. } else {
  245. GodotRuntime.error('File upload not supported');
  246. }
  247. new Promise(GodotInputDragDrop.process).then(function () {
  248. const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`;
  249. const drops = [];
  250. const files = [];
  251. FS.mkdir(DROP.slice(0, -1)); // Without trailing slash
  252. GodotInputDragDrop.pending_files.forEach((elem) => {
  253. const path = elem['path'];
  254. GodotFS.copy_to_fs(DROP + path, elem['data']);
  255. let idx = path.indexOf('/');
  256. if (idx === -1) {
  257. // Root file
  258. drops.push(DROP + path);
  259. } else {
  260. // Subdir
  261. const sub = path.substr(0, idx);
  262. idx = sub.indexOf('/');
  263. if (idx < 0 && drops.indexOf(DROP + sub) === -1) {
  264. drops.push(DROP + sub);
  265. }
  266. }
  267. files.push(DROP + path);
  268. });
  269. GodotInputDragDrop.promises = [];
  270. GodotInputDragDrop.pending_files = [];
  271. callback(drops);
  272. if (GodotConfig.persistent_drops) {
  273. // Delay removal at exit.
  274. GodotOS.atexit(function (resolve, reject) {
  275. GodotInputDragDrop.remove_drop(files, DROP);
  276. resolve();
  277. });
  278. } else {
  279. GodotInputDragDrop.remove_drop(files, DROP);
  280. }
  281. });
  282. },
  283. remove_drop: function (files, drop_path) {
  284. const dirs = [drop_path.substr(0, drop_path.length - 1)];
  285. // Remove temporary files
  286. files.forEach(function (file) {
  287. FS.unlink(file);
  288. let dir = file.replace(drop_path, '');
  289. let idx = dir.lastIndexOf('/');
  290. while (idx > 0) {
  291. dir = dir.substr(0, idx);
  292. if (dirs.indexOf(drop_path + dir) === -1) {
  293. dirs.push(drop_path + dir);
  294. }
  295. idx = dir.lastIndexOf('/');
  296. }
  297. });
  298. // Remove dirs.
  299. dirs.sort(function (a, b) {
  300. const al = (a.match(/\//g) || []).length;
  301. const bl = (b.match(/\//g) || []).length;
  302. if (al > bl) {
  303. return -1;
  304. } else if (al < bl) {
  305. return 1;
  306. }
  307. return 0;
  308. }).forEach(function (dir) {
  309. FS.rmdir(dir);
  310. });
  311. },
  312. handler: function (callback) {
  313. return function (ev) {
  314. GodotInputDragDrop._process_event(ev, callback);
  315. };
  316. },
  317. },
  318. };
  319. mergeInto(LibraryManager.library, GodotInputDragDrop);
  320. /*
  321. * Godot exposed input functions.
  322. */
  323. const GodotInput = {
  324. $GodotInput__deps: ['$GodotRuntime', '$GodotConfig', '$GodotEventListeners', '$GodotInputGamepads', '$GodotInputDragDrop'],
  325. $GodotInput: {
  326. getModifiers: function (evt) {
  327. return (evt.shiftKey + 0) + ((evt.altKey + 0) << 1) + ((evt.ctrlKey + 0) << 2) + ((evt.metaKey + 0) << 3);
  328. },
  329. computePosition: function (evt, rect) {
  330. const canvas = GodotConfig.canvas;
  331. const rw = canvas.width / rect.width;
  332. const rh = canvas.height / rect.height;
  333. const x = (evt.clientX - rect.x) * rw;
  334. const y = (evt.clientY - rect.y) * rh;
  335. return [x, y];
  336. },
  337. },
  338. /*
  339. * Mouse API
  340. */
  341. godot_js_input_mouse_move_cb__sig: 'vi',
  342. godot_js_input_mouse_move_cb: function (callback) {
  343. const func = GodotRuntime.get_func(callback);
  344. const canvas = GodotConfig.canvas;
  345. function move_cb(evt) {
  346. const rect = canvas.getBoundingClientRect();
  347. const pos = GodotInput.computePosition(evt, rect);
  348. // Scale movement
  349. const rw = canvas.width / rect.width;
  350. const rh = canvas.height / rect.height;
  351. const rel_pos_x = evt.movementX * rw;
  352. const rel_pos_y = evt.movementY * rh;
  353. const modifiers = GodotInput.getModifiers(evt);
  354. func(pos[0], pos[1], rel_pos_x, rel_pos_y, modifiers);
  355. }
  356. GodotEventListeners.add(window, 'mousemove', move_cb, false);
  357. },
  358. godot_js_input_mouse_wheel_cb__sig: 'vi',
  359. godot_js_input_mouse_wheel_cb: function (callback) {
  360. const func = GodotRuntime.get_func(callback);
  361. function wheel_cb(evt) {
  362. if (func(evt['deltaX'] || 0, evt['deltaY'] || 0)) {
  363. evt.preventDefault();
  364. }
  365. }
  366. GodotEventListeners.add(GodotConfig.canvas, 'wheel', wheel_cb, false);
  367. },
  368. godot_js_input_mouse_button_cb__sig: 'vi',
  369. godot_js_input_mouse_button_cb: function (callback) {
  370. const func = GodotRuntime.get_func(callback);
  371. const canvas = GodotConfig.canvas;
  372. function button_cb(p_pressed, evt) {
  373. const rect = canvas.getBoundingClientRect();
  374. const pos = GodotInput.computePosition(evt, rect);
  375. const modifiers = GodotInput.getModifiers(evt);
  376. // Since the event is consumed, focus manually.
  377. // NOTE: The iframe container may not have focus yet, so focus even when already active.
  378. if (p_pressed) {
  379. GodotConfig.canvas.focus();
  380. }
  381. if (func(p_pressed, evt.button, pos[0], pos[1], modifiers)) {
  382. evt.preventDefault();
  383. }
  384. }
  385. GodotEventListeners.add(canvas, 'mousedown', button_cb.bind(null, 1), false);
  386. GodotEventListeners.add(window, 'mouseup', button_cb.bind(null, 0), false);
  387. },
  388. /*
  389. * Touch API
  390. */
  391. godot_js_input_touch_cb__sig: 'viii',
  392. godot_js_input_touch_cb: function (callback, ids, coords) {
  393. const func = GodotRuntime.get_func(callback);
  394. const canvas = GodotConfig.canvas;
  395. function touch_cb(type, evt) {
  396. // Since the event is consumed, focus manually.
  397. // NOTE: The iframe container may not have focus yet, so focus even when already active.
  398. if (type === 0) {
  399. GodotConfig.canvas.focus();
  400. }
  401. const rect = canvas.getBoundingClientRect();
  402. const touches = evt.changedTouches;
  403. for (let i = 0; i < touches.length; i++) {
  404. const touch = touches[i];
  405. const pos = GodotInput.computePosition(touch, rect);
  406. GodotRuntime.setHeapValue(coords + (i * 2) * 8, pos[0], 'double');
  407. GodotRuntime.setHeapValue(coords + (i * 2 + 1) * 8, pos[1], 'double');
  408. GodotRuntime.setHeapValue(ids + i * 4, touch.identifier, 'i32');
  409. }
  410. func(type, touches.length);
  411. if (evt.cancelable) {
  412. evt.preventDefault();
  413. }
  414. }
  415. GodotEventListeners.add(canvas, 'touchstart', touch_cb.bind(null, 0), false);
  416. GodotEventListeners.add(canvas, 'touchend', touch_cb.bind(null, 1), false);
  417. GodotEventListeners.add(canvas, 'touchcancel', touch_cb.bind(null, 1), false);
  418. GodotEventListeners.add(canvas, 'touchmove', touch_cb.bind(null, 2), false);
  419. },
  420. /*
  421. * Key API
  422. */
  423. godot_js_input_key_cb__sig: 'viii',
  424. godot_js_input_key_cb: function (callback, code, key) {
  425. const func = GodotRuntime.get_func(callback);
  426. function key_cb(pressed, evt) {
  427. const modifiers = GodotInput.getModifiers(evt);
  428. GodotRuntime.stringToHeap(evt.code, code, 32);
  429. GodotRuntime.stringToHeap(evt.key, key, 32);
  430. func(pressed, evt.repeat, modifiers);
  431. evt.preventDefault();
  432. }
  433. GodotEventListeners.add(GodotConfig.canvas, 'keydown', key_cb.bind(null, 1), false);
  434. GodotEventListeners.add(GodotConfig.canvas, 'keyup', key_cb.bind(null, 0), false);
  435. },
  436. /*
  437. * Gamepad API
  438. */
  439. godot_js_input_gamepad_cb__sig: 'vi',
  440. godot_js_input_gamepad_cb: function (change_cb) {
  441. const onchange = GodotRuntime.get_func(change_cb);
  442. GodotInputGamepads.init(onchange);
  443. },
  444. godot_js_input_gamepad_sample_count__sig: 'i',
  445. godot_js_input_gamepad_sample_count: function () {
  446. return GodotInputGamepads.get_samples().length;
  447. },
  448. godot_js_input_gamepad_sample__sig: 'i',
  449. godot_js_input_gamepad_sample: function () {
  450. GodotInputGamepads.sample();
  451. return 0;
  452. },
  453. godot_js_input_gamepad_sample_get__sig: 'iiiiiii',
  454. godot_js_input_gamepad_sample_get: function (p_index, r_btns, r_btns_num, r_axes, r_axes_num, r_standard) {
  455. const sample = GodotInputGamepads.get_sample(p_index);
  456. if (!sample || !sample.connected) {
  457. return 1;
  458. }
  459. const btns = sample.buttons;
  460. const btns_len = btns.length < 16 ? btns.length : 16;
  461. for (let i = 0; i < btns_len; i++) {
  462. GodotRuntime.setHeapValue(r_btns + (i << 2), btns[i], 'float');
  463. }
  464. GodotRuntime.setHeapValue(r_btns_num, btns_len, 'i32');
  465. const axes = sample.axes;
  466. const axes_len = axes.length < 10 ? axes.length : 10;
  467. for (let i = 0; i < axes_len; i++) {
  468. GodotRuntime.setHeapValue(r_axes + (i << 2), axes[i], 'float');
  469. }
  470. GodotRuntime.setHeapValue(r_axes_num, axes_len, 'i32');
  471. const is_standard = sample.standard ? 1 : 0;
  472. GodotRuntime.setHeapValue(r_standard, is_standard, 'i32');
  473. return 0;
  474. },
  475. /*
  476. * Drag/Drop API
  477. */
  478. godot_js_input_drop_files_cb__sig: 'vi',
  479. godot_js_input_drop_files_cb: function (callback) {
  480. const func = GodotRuntime.get_func(callback);
  481. const dropFiles = function (files) {
  482. const args = files || [];
  483. if (!args.length) {
  484. return;
  485. }
  486. const argc = args.length;
  487. const argv = GodotRuntime.allocStringArray(args);
  488. func(argv, argc);
  489. GodotRuntime.freeStringArray(argv, argc);
  490. };
  491. const canvas = GodotConfig.canvas;
  492. GodotEventListeners.add(canvas, 'dragover', function (ev) {
  493. // Prevent default behavior (which would try to open the file(s))
  494. ev.preventDefault();
  495. }, false);
  496. GodotEventListeners.add(canvas, 'drop', GodotInputDragDrop.handler(dropFiles));
  497. },
  498. /* Paste API */
  499. godot_js_input_paste_cb__sig: 'vi',
  500. godot_js_input_paste_cb: function (callback) {
  501. const func = GodotRuntime.get_func(callback);
  502. GodotEventListeners.add(window, 'paste', function (evt) {
  503. const text = evt.clipboardData.getData('text');
  504. const ptr = GodotRuntime.allocString(text);
  505. func(ptr);
  506. GodotRuntime.free(ptr);
  507. }, false);
  508. },
  509. godot_js_input_vibrate_handheld__sig: 'vi',
  510. godot_js_input_vibrate_handheld: function (p_duration_ms) {
  511. if (typeof navigator.vibrate !== 'function') {
  512. GodotRuntime.print('This browser does not support vibration.');
  513. } else {
  514. navigator.vibrate(p_duration_ms);
  515. }
  516. },
  517. };
  518. autoAddDeps(GodotInput, '$GodotInput');
  519. mergeInto(LibraryManager.library, GodotInput);