library_godot_input.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*************************************************************************/
  2. /* library_godot_input.js */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  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. GodotEventListeners.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. add(evt.gamepad);
  102. }, false);
  103. GodotEventListeners.add(window, 'gamepaddisconnected', function (evt) {
  104. onchange(evt.gamepad.index, 0);
  105. }, false);
  106. },
  107. get_guid: function (pad) {
  108. if (pad.mapping) {
  109. return pad.mapping;
  110. }
  111. const ua = navigator.userAgent;
  112. let os = 'Unknown';
  113. if (ua.indexOf('Android') >= 0) {
  114. os = 'Android';
  115. } else if (ua.indexOf('Linux') >= 0) {
  116. os = 'Linux';
  117. } else if (ua.indexOf('iPhone') >= 0) {
  118. os = 'iOS';
  119. } else if (ua.indexOf('Macintosh') >= 0) {
  120. // Updated iPads will fall into this category.
  121. os = 'MacOSX';
  122. } else if (ua.indexOf('Windows') >= 0) {
  123. os = 'Windows';
  124. }
  125. const id = pad.id;
  126. // Chrom* style: NAME (Vendor: xxxx Product: xxxx)
  127. const exp1 = /vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i;
  128. // Firefox/Safari style (safari may remove leading zeores)
  129. const exp2 = /^([0-9a-f]+)-([0-9a-f]+)-/i;
  130. let vendor = '';
  131. let product = '';
  132. if (exp1.test(id)) {
  133. const match = exp1.exec(id);
  134. vendor = match[1].padStart(4, '0');
  135. product = match[2].padStart(4, '0');
  136. } else if (exp2.test(id)) {
  137. const match = exp2.exec(id);
  138. vendor = match[1].padStart(4, '0');
  139. product = match[2].padStart(4, '0');
  140. }
  141. if (!vendor || !product) {
  142. return `${os}Unknown`;
  143. }
  144. return os + vendor + product;
  145. },
  146. },
  147. };
  148. mergeInto(LibraryManager.library, GodotInputGamepads);
  149. /*
  150. * Drag and drop helper.
  151. * This is pretty big, but basically detect dropped files on GodotConfig.canvas,
  152. * process them one by one (recursively for directories), and copies them to
  153. * the temporary FS path '/tmp/drop-[random]/' so it can be emitted as a godot
  154. * event (that requires a string array of paths).
  155. *
  156. * NOTE: The temporary files are removed after the callback. This means that
  157. * deferred callbacks won't be able to access the files.
  158. */
  159. const GodotInputDragDrop = {
  160. $GodotInputDragDrop__deps: ['$FS', '$GodotFS'],
  161. $GodotInputDragDrop: {
  162. promises: [],
  163. pending_files: [],
  164. add_entry: function (entry) {
  165. if (entry.isDirectory) {
  166. GodotInputDragDrop.add_dir(entry);
  167. } else if (entry.isFile) {
  168. GodotInputDragDrop.add_file(entry);
  169. } else {
  170. GodotRuntime.error('Unrecognized entry...', entry);
  171. }
  172. },
  173. add_dir: function (entry) {
  174. GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) {
  175. const reader = entry.createReader();
  176. reader.readEntries(function (entries) {
  177. for (let i = 0; i < entries.length; i++) {
  178. GodotInputDragDrop.add_entry(entries[i]);
  179. }
  180. resolve();
  181. });
  182. }));
  183. },
  184. add_file: function (entry) {
  185. GodotInputDragDrop.promises.push(new Promise(function (resolve, reject) {
  186. entry.file(function (file) {
  187. const reader = new FileReader();
  188. reader.onload = function () {
  189. const f = {
  190. 'path': file.relativePath || file.webkitRelativePath,
  191. 'name': file.name,
  192. 'type': file.type,
  193. 'size': file.size,
  194. 'data': reader.result,
  195. };
  196. if (!f['path']) {
  197. f['path'] = f['name'];
  198. }
  199. GodotInputDragDrop.pending_files.push(f);
  200. resolve();
  201. };
  202. reader.onerror = function () {
  203. GodotRuntime.print('Error reading file');
  204. reject();
  205. };
  206. reader.readAsArrayBuffer(file);
  207. }, function (err) {
  208. GodotRuntime.print('Error!');
  209. reject();
  210. });
  211. }));
  212. },
  213. process: function (resolve, reject) {
  214. if (GodotInputDragDrop.promises.length === 0) {
  215. resolve();
  216. return;
  217. }
  218. GodotInputDragDrop.promises.pop().then(function () {
  219. setTimeout(function () {
  220. GodotInputDragDrop.process(resolve, reject);
  221. }, 0);
  222. });
  223. },
  224. _process_event: function (ev, callback) {
  225. ev.preventDefault();
  226. if (ev.dataTransfer.items) {
  227. // Use DataTransferItemList interface to access the file(s)
  228. for (let i = 0; i < ev.dataTransfer.items.length; i++) {
  229. const item = ev.dataTransfer.items[i];
  230. let entry = null;
  231. if ('getAsEntry' in item) {
  232. entry = item.getAsEntry();
  233. } else if ('webkitGetAsEntry' in item) {
  234. entry = item.webkitGetAsEntry();
  235. }
  236. if (entry) {
  237. GodotInputDragDrop.add_entry(entry);
  238. }
  239. }
  240. } else {
  241. GodotRuntime.error('File upload not supported');
  242. }
  243. new Promise(GodotInputDragDrop.process).then(function () {
  244. const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`;
  245. const drops = [];
  246. const files = [];
  247. FS.mkdir(DROP);
  248. GodotInputDragDrop.pending_files.forEach((elem) => {
  249. const path = elem['path'];
  250. GodotFS.copy_to_fs(DROP + path, elem['data']);
  251. let idx = path.indexOf('/');
  252. if (idx === -1) {
  253. // Root file
  254. drops.push(DROP + path);
  255. } else {
  256. // Subdir
  257. const sub = path.substr(0, idx);
  258. idx = sub.indexOf('/');
  259. if (idx < 0 && drops.indexOf(DROP + sub) === -1) {
  260. drops.push(DROP + sub);
  261. }
  262. }
  263. files.push(DROP + path);
  264. });
  265. GodotInputDragDrop.promises = [];
  266. GodotInputDragDrop.pending_files = [];
  267. callback(drops);
  268. if (GodotConfig.persistent_drops) {
  269. // Delay removal at exit.
  270. GodotOS.atexit(function (resolve, reject) {
  271. GodotInputDragDrop.remove_drop(files, DROP);
  272. resolve();
  273. });
  274. } else {
  275. GodotInputDragDrop.remove_drop(files, DROP);
  276. }
  277. });
  278. },
  279. remove_drop: function (files, drop_path) {
  280. const dirs = [drop_path.substr(0, drop_path.length - 1)];
  281. // Remove temporary files
  282. files.forEach(function (file) {
  283. FS.unlink(file);
  284. let dir = file.replace(drop_path, '');
  285. let idx = dir.lastIndexOf('/');
  286. while (idx > 0) {
  287. dir = dir.substr(0, idx);
  288. if (dirs.indexOf(drop_path + dir) === -1) {
  289. dirs.push(drop_path + dir);
  290. }
  291. idx = dir.lastIndexOf('/');
  292. }
  293. });
  294. // Remove dirs.
  295. dirs.sort(function (a, b) {
  296. const al = (a.match(/\//g) || []).length;
  297. const bl = (b.match(/\//g) || []).length;
  298. if (al > bl) {
  299. return -1;
  300. } else if (al < bl) {
  301. return 1;
  302. }
  303. return 0;
  304. }).forEach(function (dir) {
  305. FS.rmdir(dir);
  306. });
  307. },
  308. handler: function (callback) {
  309. return function (ev) {
  310. GodotInputDragDrop._process_event(ev, callback);
  311. };
  312. },
  313. },
  314. };
  315. mergeInto(LibraryManager.library, GodotInputDragDrop);
  316. /*
  317. * Godot exposed input functions.
  318. */
  319. const GodotInput = {
  320. $GodotInput__deps: ['$GodotRuntime', '$GodotConfig', '$GodotEventListeners', '$GodotInputGamepads', '$GodotInputDragDrop'],
  321. $GodotInput: {
  322. getModifiers: function (evt) {
  323. return (evt.shiftKey + 0) + ((evt.altKey + 0) << 1) + ((evt.ctrlKey + 0) << 2) + ((evt.metaKey + 0) << 3);
  324. },
  325. computePosition: function (evt, rect) {
  326. const canvas = GodotConfig.canvas;
  327. const rw = canvas.width / rect.width;
  328. const rh = canvas.height / rect.height;
  329. const x = (evt.clientX - rect.x) * rw;
  330. const y = (evt.clientY - rect.y) * rh;
  331. return [x, y];
  332. },
  333. },
  334. /*
  335. * Mouse API
  336. */
  337. godot_js_input_mouse_move_cb__sig: 'vi',
  338. godot_js_input_mouse_move_cb: function (callback) {
  339. const func = GodotRuntime.get_func(callback);
  340. const canvas = GodotConfig.canvas;
  341. function move_cb(evt) {
  342. const rect = canvas.getBoundingClientRect();
  343. const pos = GodotInput.computePosition(evt, rect);
  344. // Scale movement
  345. const rw = canvas.width / rect.width;
  346. const rh = canvas.height / rect.height;
  347. const rel_pos_x = evt.movementX * rw;
  348. const rel_pos_y = evt.movementY * rh;
  349. const modifiers = GodotInput.getModifiers(evt);
  350. func(pos[0], pos[1], rel_pos_x, rel_pos_y, modifiers);
  351. }
  352. GodotEventListeners.add(window, 'mousemove', move_cb, false);
  353. },
  354. godot_js_input_mouse_wheel_cb__sig: 'vi',
  355. godot_js_input_mouse_wheel_cb: function (callback) {
  356. const func = GodotRuntime.get_func(callback);
  357. function wheel_cb(evt) {
  358. if (func(evt['deltaX'] || 0, evt['deltaY'] || 0)) {
  359. evt.preventDefault();
  360. }
  361. }
  362. GodotEventListeners.add(GodotConfig.canvas, 'wheel', wheel_cb, false);
  363. },
  364. godot_js_input_mouse_button_cb__sig: 'vi',
  365. godot_js_input_mouse_button_cb: function (callback) {
  366. const func = GodotRuntime.get_func(callback);
  367. const canvas = GodotConfig.canvas;
  368. function button_cb(p_pressed, evt) {
  369. const rect = canvas.getBoundingClientRect();
  370. const pos = GodotInput.computePosition(evt, rect);
  371. const modifiers = GodotInput.getModifiers(evt);
  372. if (func(p_pressed, evt.button, pos[0], pos[1], modifiers)) {
  373. evt.preventDefault();
  374. }
  375. }
  376. GodotEventListeners.add(canvas, 'mousedown', button_cb.bind(null, 1), false);
  377. GodotEventListeners.add(window, 'mouseup', button_cb.bind(null, 0), false);
  378. },
  379. /*
  380. * Touch API
  381. */
  382. godot_js_input_touch_cb__sig: 'viii',
  383. godot_js_input_touch_cb: function (callback, ids, coords) {
  384. const func = GodotRuntime.get_func(callback);
  385. const canvas = GodotConfig.canvas;
  386. function touch_cb(type, evt) {
  387. const rect = canvas.getBoundingClientRect();
  388. const touches = evt.changedTouches;
  389. for (let i = 0; i < touches.length; i++) {
  390. const touch = touches[i];
  391. const pos = GodotInput.computePosition(touch, rect);
  392. GodotRuntime.setHeapValue(coords + (i * 2), pos[0], 'double');
  393. GodotRuntime.setHeapValue(coords + (i * 2 + 8), pos[1], 'double');
  394. GodotRuntime.setHeapValue(ids + i, touch.identifier, 'i32');
  395. }
  396. func(type, touches.length);
  397. if (evt.cancelable) {
  398. evt.preventDefault();
  399. }
  400. }
  401. GodotEventListeners.add(canvas, 'touchstart', touch_cb.bind(null, 0), false);
  402. GodotEventListeners.add(canvas, 'touchend', touch_cb.bind(null, 1), false);
  403. GodotEventListeners.add(canvas, 'touchcancel', touch_cb.bind(null, 1), false);
  404. GodotEventListeners.add(canvas, 'touchmove', touch_cb.bind(null, 2), false);
  405. },
  406. /*
  407. * Key API
  408. */
  409. godot_js_input_key_cb__sig: 'viii',
  410. godot_js_input_key_cb: function (callback, code, key) {
  411. const func = GodotRuntime.get_func(callback);
  412. function key_cb(pressed, evt) {
  413. const modifiers = GodotInput.getModifiers(evt);
  414. GodotRuntime.stringToHeap(evt.code, code, 32);
  415. GodotRuntime.stringToHeap(evt.key, key, 32);
  416. func(pressed, evt.repeat, modifiers);
  417. evt.preventDefault();
  418. }
  419. GodotEventListeners.add(GodotConfig.canvas, 'keydown', key_cb.bind(null, 1), false);
  420. GodotEventListeners.add(GodotConfig.canvas, 'keyup', key_cb.bind(null, 0), false);
  421. },
  422. /*
  423. * Gamepad API
  424. */
  425. godot_js_input_gamepad_cb__sig: 'vi',
  426. godot_js_input_gamepad_cb: function (change_cb) {
  427. const onchange = GodotRuntime.get_func(change_cb);
  428. GodotInputGamepads.init(onchange);
  429. },
  430. godot_js_input_gamepad_sample_count__sig: 'i',
  431. godot_js_input_gamepad_sample_count: function () {
  432. return GodotInputGamepads.get_samples().length;
  433. },
  434. godot_js_input_gamepad_sample__sig: 'i',
  435. godot_js_input_gamepad_sample: function () {
  436. GodotInputGamepads.sample();
  437. return 0;
  438. },
  439. godot_js_input_gamepad_sample_get__sig: 'iiiiiii',
  440. godot_js_input_gamepad_sample_get: function (p_index, r_btns, r_btns_num, r_axes, r_axes_num, r_standard) {
  441. const sample = GodotInputGamepads.get_sample(p_index);
  442. if (!sample || !sample.connected) {
  443. return 1;
  444. }
  445. const btns = sample.buttons;
  446. const btns_len = btns.length < 16 ? btns.length : 16;
  447. for (let i = 0; i < btns_len; i++) {
  448. GodotRuntime.setHeapValue(r_btns + (i << 2), btns[i], 'float');
  449. }
  450. GodotRuntime.setHeapValue(r_btns_num, btns_len, 'i32');
  451. const axes = sample.axes;
  452. const axes_len = axes.length < 10 ? axes.length : 10;
  453. for (let i = 0; i < axes_len; i++) {
  454. GodotRuntime.setHeapValue(r_axes + (i << 2), axes[i], 'float');
  455. }
  456. GodotRuntime.setHeapValue(r_axes_num, axes_len, 'i32');
  457. const is_standard = sample.standard ? 1 : 0;
  458. GodotRuntime.setHeapValue(r_standard, is_standard, 'i32');
  459. return 0;
  460. },
  461. /*
  462. * Drag/Drop API
  463. */
  464. godot_js_input_drop_files_cb__sig: 'vi',
  465. godot_js_input_drop_files_cb: function (callback) {
  466. const func = GodotRuntime.get_func(callback);
  467. const dropFiles = function (files) {
  468. const args = files || [];
  469. if (!args.length) {
  470. return;
  471. }
  472. const argc = args.length;
  473. const argv = GodotRuntime.allocStringArray(args);
  474. func(argv, argc);
  475. GodotRuntime.freeStringArray(argv, argc);
  476. };
  477. const canvas = GodotConfig.canvas;
  478. GodotEventListeners.add(canvas, 'dragover', function (ev) {
  479. // Prevent default behavior (which would try to open the file(s))
  480. ev.preventDefault();
  481. }, false);
  482. GodotEventListeners.add(canvas, 'drop', GodotInputDragDrop.handler(dropFiles));
  483. },
  484. /* Paste API */
  485. godot_js_input_paste_cb__sig: 'vi',
  486. godot_js_input_paste_cb: function (callback) {
  487. const func = GodotRuntime.get_func(callback);
  488. GodotEventListeners.add(window, 'paste', function (evt) {
  489. const text = evt.clipboardData.getData('text');
  490. const ptr = GodotRuntime.allocString(text);
  491. func(ptr);
  492. GodotRuntime.free(ptr);
  493. }, false);
  494. },
  495. };
  496. autoAddDeps(GodotInput, '$GodotInput');
  497. mergeInto(LibraryManager.library, GodotInput);