library_godot_display.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055
  1. /*************************************************************************/
  2. /* library_godot_display.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. * Display Server listeners.
  32. * Keeps track of registered event listeners so it can remove them on shutdown.
  33. */
  34. const GodotDisplayListeners = {
  35. $GodotDisplayListeners__deps: ['$GodotOS'],
  36. $GodotDisplayListeners__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayListeners.clear(); resolve(); });',
  37. $GodotDisplayListeners: {
  38. handlers: [],
  39. has: function (target, event, method, capture) {
  40. return GodotDisplayListeners.handlers.findIndex(function (e) {
  41. return e.target === target && e.event === event && e.method === method && e.capture === capture;
  42. }) !== -1;
  43. },
  44. add: function (target, event, method, capture) {
  45. if (GodotDisplayListeners.has(target, event, method, capture)) {
  46. return;
  47. }
  48. function Handler(p_target, p_event, p_method, p_capture) {
  49. this.target = p_target;
  50. this.event = p_event;
  51. this.method = p_method;
  52. this.capture = p_capture;
  53. }
  54. GodotDisplayListeners.handlers.push(new Handler(target, event, method, capture));
  55. target.addEventListener(event, method, capture);
  56. },
  57. clear: function () {
  58. GodotDisplayListeners.handlers.forEach(function (h) {
  59. h.target.removeEventListener(h.event, h.method, h.capture);
  60. });
  61. GodotDisplayListeners.handlers.length = 0;
  62. },
  63. },
  64. };
  65. mergeInto(LibraryManager.library, GodotDisplayListeners);
  66. /*
  67. * Drag and drop handler.
  68. * This is pretty big, but basically detect dropped files on GodotConfig.canvas,
  69. * process them one by one (recursively for directories), and copies them to
  70. * the temporary FS path '/tmp/drop-[random]/' so it can be emitted as a godot
  71. * event (that requires a string array of paths).
  72. *
  73. * NOTE: The temporary files are removed after the callback. This means that
  74. * deferred callbacks won't be able to access the files.
  75. */
  76. const GodotDisplayDragDrop = {
  77. $GodotDisplayDragDrop__deps: ['$FS', '$GodotFS'],
  78. $GodotDisplayDragDrop: {
  79. promises: [],
  80. pending_files: [],
  81. add_entry: function (entry) {
  82. if (entry.isDirectory) {
  83. GodotDisplayDragDrop.add_dir(entry);
  84. } else if (entry.isFile) {
  85. GodotDisplayDragDrop.add_file(entry);
  86. } else {
  87. GodotRuntime.error('Unrecognized entry...', entry);
  88. }
  89. },
  90. add_dir: function (entry) {
  91. GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) {
  92. const reader = entry.createReader();
  93. reader.readEntries(function (entries) {
  94. for (let i = 0; i < entries.length; i++) {
  95. GodotDisplayDragDrop.add_entry(entries[i]);
  96. }
  97. resolve();
  98. });
  99. }));
  100. },
  101. add_file: function (entry) {
  102. GodotDisplayDragDrop.promises.push(new Promise(function (resolve, reject) {
  103. entry.file(function (file) {
  104. const reader = new FileReader();
  105. reader.onload = function () {
  106. const f = {
  107. 'path': file.relativePath || file.webkitRelativePath,
  108. 'name': file.name,
  109. 'type': file.type,
  110. 'size': file.size,
  111. 'data': reader.result,
  112. };
  113. if (!f['path']) {
  114. f['path'] = f['name'];
  115. }
  116. GodotDisplayDragDrop.pending_files.push(f);
  117. resolve();
  118. };
  119. reader.onerror = function () {
  120. GodotRuntime.print('Error reading file');
  121. reject();
  122. };
  123. reader.readAsArrayBuffer(file);
  124. }, function (err) {
  125. GodotRuntime.print('Error!');
  126. reject();
  127. });
  128. }));
  129. },
  130. process: function (resolve, reject) {
  131. if (GodotDisplayDragDrop.promises.length === 0) {
  132. resolve();
  133. return;
  134. }
  135. GodotDisplayDragDrop.promises.pop().then(function () {
  136. setTimeout(function () {
  137. GodotDisplayDragDrop.process(resolve, reject);
  138. }, 0);
  139. });
  140. },
  141. _process_event: function (ev, callback) {
  142. ev.preventDefault();
  143. if (ev.dataTransfer.items) {
  144. // Use DataTransferItemList interface to access the file(s)
  145. for (let i = 0; i < ev.dataTransfer.items.length; i++) {
  146. const item = ev.dataTransfer.items[i];
  147. let entry = null;
  148. if ('getAsEntry' in item) {
  149. entry = item.getAsEntry();
  150. } else if ('webkitGetAsEntry' in item) {
  151. entry = item.webkitGetAsEntry();
  152. }
  153. if (entry) {
  154. GodotDisplayDragDrop.add_entry(entry);
  155. }
  156. }
  157. } else {
  158. GodotRuntime.error('File upload not supported');
  159. }
  160. new Promise(GodotDisplayDragDrop.process).then(function () {
  161. const DROP = `/tmp/drop-${parseInt(Math.random() * (1 << 30), 10)}/`;
  162. const drops = [];
  163. const files = [];
  164. FS.mkdir(DROP);
  165. GodotDisplayDragDrop.pending_files.forEach((elem) => {
  166. const path = elem['path'];
  167. GodotFS.copy_to_fs(DROP + path, elem['data']);
  168. let idx = path.indexOf('/');
  169. if (idx === -1) {
  170. // Root file
  171. drops.push(DROP + path);
  172. } else {
  173. // Subdir
  174. const sub = path.substr(0, idx);
  175. idx = sub.indexOf('/');
  176. if (idx < 0 && drops.indexOf(DROP + sub) === -1) {
  177. drops.push(DROP + sub);
  178. }
  179. }
  180. files.push(DROP + path);
  181. });
  182. GodotDisplayDragDrop.promises = [];
  183. GodotDisplayDragDrop.pending_files = [];
  184. callback(drops);
  185. if (GodotConfig.persistent_drops) {
  186. // Delay removal at exit.
  187. GodotOS.atexit(function (resolve, reject) {
  188. GodotDisplayDragDrop.remove_drop(files, DROP);
  189. resolve();
  190. });
  191. } else {
  192. GodotDisplayDragDrop.remove_drop(files, DROP);
  193. }
  194. });
  195. },
  196. remove_drop: function (files, drop_path) {
  197. const dirs = [drop_path.substr(0, drop_path.length - 1)];
  198. // Remove temporary files
  199. files.forEach(function (file) {
  200. FS.unlink(file);
  201. let dir = file.replace(drop_path, '');
  202. let idx = dir.lastIndexOf('/');
  203. while (idx > 0) {
  204. dir = dir.substr(0, idx);
  205. if (dirs.indexOf(drop_path + dir) === -1) {
  206. dirs.push(drop_path + dir);
  207. }
  208. idx = dir.lastIndexOf('/');
  209. }
  210. });
  211. // Remove dirs.
  212. dirs.sort(function (a, b) {
  213. const al = (a.match(/\//g) || []).length;
  214. const bl = (b.match(/\//g) || []).length;
  215. if (al > bl) {
  216. return -1;
  217. } else if (al < bl) {
  218. return 1;
  219. }
  220. return 0;
  221. }).forEach(function (dir) {
  222. FS.rmdir(dir);
  223. });
  224. },
  225. handler: function (callback) {
  226. return function (ev) {
  227. GodotDisplayDragDrop._process_event(ev, callback);
  228. };
  229. },
  230. },
  231. };
  232. mergeInto(LibraryManager.library, GodotDisplayDragDrop);
  233. const GodotDisplayVK = {
  234. $GodotDisplayVK__deps: ['$GodotRuntime', '$GodotConfig', '$GodotDisplayListeners'],
  235. $GodotDisplayVK__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayVK.clear(); resolve(); });',
  236. $GodotDisplayVK: {
  237. textinput: null,
  238. textarea: null,
  239. available: function () {
  240. return GodotConfig.virtual_keyboard && 'ontouchstart' in window;
  241. },
  242. init: function (input_cb) {
  243. function create(what) {
  244. const elem = document.createElement(what);
  245. elem.style.display = 'none';
  246. elem.style.position = 'absolute';
  247. elem.style.zIndex = '-1';
  248. elem.style.background = 'transparent';
  249. elem.style.padding = '0px';
  250. elem.style.margin = '0px';
  251. elem.style.overflow = 'hidden';
  252. elem.style.width = '0px';
  253. elem.style.height = '0px';
  254. elem.style.border = '0px';
  255. elem.style.outline = 'none';
  256. elem.readonly = true;
  257. elem.disabled = true;
  258. GodotDisplayListeners.add(elem, 'input', function (evt) {
  259. const c_str = GodotRuntime.allocString(elem.value);
  260. input_cb(c_str, elem.selectionEnd);
  261. GodotRuntime.free(c_str);
  262. }, false);
  263. GodotDisplayListeners.add(elem, 'blur', function (evt) {
  264. elem.style.display = 'none';
  265. elem.readonly = true;
  266. elem.disabled = true;
  267. }, false);
  268. GodotConfig.canvas.insertAdjacentElement('beforebegin', elem);
  269. return elem;
  270. }
  271. GodotDisplayVK.textinput = create('input');
  272. GodotDisplayVK.textarea = create('textarea');
  273. GodotDisplayVK.updateSize();
  274. },
  275. show: function (text, multiline, start, end) {
  276. if (!GodotDisplayVK.textinput || !GodotDisplayVK.textarea) {
  277. return;
  278. }
  279. if (GodotDisplayVK.textinput.style.display !== '' || GodotDisplayVK.textarea.style.display !== '') {
  280. GodotDisplayVK.hide();
  281. }
  282. GodotDisplayVK.updateSize();
  283. const elem = multiline ? GodotDisplayVK.textarea : GodotDisplayVK.textinput;
  284. elem.readonly = false;
  285. elem.disabled = false;
  286. elem.value = text;
  287. elem.style.display = 'block';
  288. elem.focus();
  289. elem.setSelectionRange(start, end);
  290. },
  291. hide: function () {
  292. if (!GodotDisplayVK.textinput || !GodotDisplayVK.textarea) {
  293. return;
  294. }
  295. [GodotDisplayVK.textinput, GodotDisplayVK.textarea].forEach(function (elem) {
  296. elem.blur();
  297. elem.style.display = 'none';
  298. elem.value = '';
  299. });
  300. },
  301. updateSize: function () {
  302. if (!GodotDisplayVK.textinput || !GodotDisplayVK.textarea) {
  303. return;
  304. }
  305. const rect = GodotConfig.canvas.getBoundingClientRect();
  306. function update(elem) {
  307. elem.style.left = `${rect.left}px`;
  308. elem.style.top = `${rect.top}px`;
  309. elem.style.width = `${rect.width}px`;
  310. elem.style.height = `${rect.height}px`;
  311. }
  312. update(GodotDisplayVK.textinput);
  313. update(GodotDisplayVK.textarea);
  314. },
  315. clear: function () {
  316. if (GodotDisplayVK.textinput) {
  317. GodotDisplayVK.textinput.remove();
  318. GodotDisplayVK.textinput = null;
  319. }
  320. if (GodotDisplayVK.textarea) {
  321. GodotDisplayVK.textarea.remove();
  322. GodotDisplayVK.textarea = null;
  323. }
  324. },
  325. },
  326. };
  327. mergeInto(LibraryManager.library, GodotDisplayVK);
  328. /*
  329. * Display server cursor helper.
  330. * Keeps track of cursor status and custom shapes.
  331. */
  332. const GodotDisplayCursor = {
  333. $GodotDisplayCursor__deps: ['$GodotOS', '$GodotConfig'],
  334. $GodotDisplayCursor__postset: 'GodotOS.atexit(function(resolve, reject) { GodotDisplayCursor.clear(); resolve(); });',
  335. $GodotDisplayCursor: {
  336. shape: 'auto',
  337. visible: true,
  338. cursors: {},
  339. set_style: function (style) {
  340. GodotConfig.canvas.style.cursor = style;
  341. },
  342. set_shape: function (shape) {
  343. GodotDisplayCursor.shape = shape;
  344. let css = shape;
  345. if (shape in GodotDisplayCursor.cursors) {
  346. const c = GodotDisplayCursor.cursors[shape];
  347. css = `url("${c.url}") ${c.x} ${c.y}, auto`;
  348. }
  349. if (GodotDisplayCursor.visible) {
  350. GodotDisplayCursor.set_style(css);
  351. }
  352. },
  353. clear: function () {
  354. GodotDisplayCursor.set_style('');
  355. GodotDisplayCursor.shape = 'auto';
  356. GodotDisplayCursor.visible = true;
  357. Object.keys(GodotDisplayCursor.cursors).forEach(function (key) {
  358. URL.revokeObjectURL(GodotDisplayCursor.cursors[key]);
  359. delete GodotDisplayCursor.cursors[key];
  360. });
  361. },
  362. lockPointer: function () {
  363. const canvas = GodotConfig.canvas;
  364. if (canvas.requestPointerLock) {
  365. canvas.requestPointerLock();
  366. }
  367. },
  368. releasePointer: function () {
  369. if (document.exitPointerLock) {
  370. document.exitPointerLock();
  371. }
  372. },
  373. isPointerLocked: function () {
  374. return document.pointerLockElement === GodotConfig.canvas;
  375. },
  376. },
  377. };
  378. mergeInto(LibraryManager.library, GodotDisplayCursor);
  379. /*
  380. * Display Gamepad API helper.
  381. */
  382. const GodotDisplayGamepads = {
  383. $GodotDisplayGamepads__deps: ['$GodotRuntime', '$GodotDisplayListeners'],
  384. $GodotDisplayGamepads: {
  385. samples: [],
  386. get_pads: function () {
  387. try {
  388. // Will throw in iframe when permission is denied.
  389. // Will throw/warn in the future for insecure contexts.
  390. // See https://github.com/w3c/gamepad/pull/120
  391. const pads = navigator.getGamepads();
  392. if (pads) {
  393. return pads;
  394. }
  395. return [];
  396. } catch (e) {
  397. return [];
  398. }
  399. },
  400. get_samples: function () {
  401. return GodotDisplayGamepads.samples;
  402. },
  403. get_sample: function (index) {
  404. const samples = GodotDisplayGamepads.samples;
  405. return index < samples.length ? samples[index] : null;
  406. },
  407. sample: function () {
  408. const pads = GodotDisplayGamepads.get_pads();
  409. const samples = [];
  410. for (let i = 0; i < pads.length; i++) {
  411. const pad = pads[i];
  412. if (!pad) {
  413. samples.push(null);
  414. continue;
  415. }
  416. const s = {
  417. standard: pad.mapping === 'standard',
  418. buttons: [],
  419. axes: [],
  420. connected: pad.connected,
  421. };
  422. for (let b = 0; b < pad.buttons.length; b++) {
  423. s.buttons.push(pad.buttons[b].value);
  424. }
  425. for (let a = 0; a < pad.axes.length; a++) {
  426. s.axes.push(pad.axes[a]);
  427. }
  428. samples.push(s);
  429. }
  430. GodotDisplayGamepads.samples = samples;
  431. },
  432. init: function (onchange) {
  433. GodotDisplayListeners.samples = [];
  434. function add(pad) {
  435. const guid = GodotDisplayGamepads.get_guid(pad);
  436. const c_id = GodotRuntime.allocString(pad.id);
  437. const c_guid = GodotRuntime.allocString(guid);
  438. onchange(pad.index, 1, c_id, c_guid);
  439. GodotRuntime.free(c_id);
  440. GodotRuntime.free(c_guid);
  441. }
  442. const pads = GodotDisplayGamepads.get_pads();
  443. for (let i = 0; i < pads.length; i++) {
  444. // Might be reserved space.
  445. if (pads[i]) {
  446. add(pads[i]);
  447. }
  448. }
  449. GodotDisplayListeners.add(window, 'gamepadconnected', function (evt) {
  450. add(evt.gamepad);
  451. }, false);
  452. GodotDisplayListeners.add(window, 'gamepaddisconnected', function (evt) {
  453. onchange(evt.gamepad.index, 0);
  454. }, false);
  455. },
  456. get_guid: function (pad) {
  457. if (pad.mapping) {
  458. return pad.mapping;
  459. }
  460. const ua = navigator.userAgent;
  461. let os = 'Unknown';
  462. if (ua.indexOf('Android') >= 0) {
  463. os = 'Android';
  464. } else if (ua.indexOf('Linux') >= 0) {
  465. os = 'Linux';
  466. } else if (ua.indexOf('iPhone') >= 0) {
  467. os = 'iOS';
  468. } else if (ua.indexOf('Macintosh') >= 0) {
  469. // Updated iPads will fall into this category.
  470. os = 'MacOSX';
  471. } else if (ua.indexOf('Windows') >= 0) {
  472. os = 'Windows';
  473. }
  474. const id = pad.id;
  475. // Chrom* style: NAME (Vendor: xxxx Product: xxxx)
  476. const exp1 = /vendor: ([0-9a-f]{4}) product: ([0-9a-f]{4})/i;
  477. // Firefox/Safari style (safari may remove leading zeores)
  478. const exp2 = /^([0-9a-f]+)-([0-9a-f]+)-/i;
  479. let vendor = '';
  480. let product = '';
  481. if (exp1.test(id)) {
  482. const match = exp1.exec(id);
  483. vendor = match[1].padStart(4, '0');
  484. product = match[2].padStart(4, '0');
  485. } else if (exp2.test(id)) {
  486. const match = exp2.exec(id);
  487. vendor = match[1].padStart(4, '0');
  488. product = match[2].padStart(4, '0');
  489. }
  490. if (!vendor || !product) {
  491. return `${os}Unknown`;
  492. }
  493. return os + vendor + product;
  494. },
  495. },
  496. };
  497. mergeInto(LibraryManager.library, GodotDisplayGamepads);
  498. const GodotDisplayScreen = {
  499. $GodotDisplayScreen__deps: ['$GodotConfig', '$GodotOS', '$GL', 'emscripten_webgl_get_current_context'],
  500. $GodotDisplayScreen: {
  501. desired_size: [0, 0],
  502. hidpi: true,
  503. getPixelRatio: function () {
  504. return GodotDisplayScreen.hidpi ? window.devicePixelRatio || 1 : 1;
  505. },
  506. isFullscreen: function () {
  507. const elem = document.fullscreenElement || document.mozFullscreenElement
  508. || document.webkitFullscreenElement || document.msFullscreenElement;
  509. if (elem) {
  510. return elem === GodotConfig.canvas;
  511. }
  512. // But maybe knowing the element is not supported.
  513. return document.fullscreen || document.mozFullScreen
  514. || document.webkitIsFullscreen;
  515. },
  516. hasFullscreen: function () {
  517. return document.fullscreenEnabled || document.mozFullScreenEnabled
  518. || document.webkitFullscreenEnabled;
  519. },
  520. requestFullscreen: function () {
  521. if (!GodotDisplayScreen.hasFullscreen()) {
  522. return 1;
  523. }
  524. const canvas = GodotConfig.canvas;
  525. try {
  526. const promise = (canvas.requestFullscreen || canvas.msRequestFullscreen
  527. || canvas.mozRequestFullScreen || canvas.mozRequestFullscreen
  528. || canvas.webkitRequestFullscreen
  529. ).call(canvas);
  530. // Some browsers (Safari) return undefined.
  531. // For the standard ones, we need to catch it.
  532. if (promise) {
  533. promise.catch(function () {
  534. // nothing to do.
  535. });
  536. }
  537. } catch (e) {
  538. return 1;
  539. }
  540. return 0;
  541. },
  542. exitFullscreen: function () {
  543. if (!GodotDisplayScreen.isFullscreen()) {
  544. return 0;
  545. }
  546. try {
  547. const promise = document.exitFullscreen();
  548. if (promise) {
  549. promise.catch(function () {
  550. // nothing to do.
  551. });
  552. }
  553. } catch (e) {
  554. return 1;
  555. }
  556. return 0;
  557. },
  558. _updateGL: function () {
  559. const gl_context_handle = _emscripten_webgl_get_current_context(); // eslint-disable-line no-undef
  560. const gl = GL.getContext(gl_context_handle);
  561. if (gl) {
  562. GL.resizeOffscreenFramebuffer(gl);
  563. }
  564. },
  565. updateSize: function () {
  566. const isFullscreen = GodotDisplayScreen.isFullscreen();
  567. const wantsFullWindow = GodotConfig.canvas_resize_policy === 2;
  568. const noResize = GodotConfig.canvas_resize_policy === 0;
  569. const wwidth = GodotDisplayScreen.desired_size[0];
  570. const wheight = GodotDisplayScreen.desired_size[1];
  571. const canvas = GodotConfig.canvas;
  572. let width = wwidth;
  573. let height = wheight;
  574. if (noResize) {
  575. // Don't resize canvas, just update GL if needed.
  576. if (canvas.width !== width || canvas.height !== height) {
  577. GodotDisplayScreen.desired_size = [canvas.width, canvas.height];
  578. GodotDisplayScreen._updateGL();
  579. return 1;
  580. }
  581. return 0;
  582. }
  583. const scale = GodotDisplayScreen.getPixelRatio();
  584. if (isFullscreen || wantsFullWindow) {
  585. // We need to match screen size.
  586. width = window.innerWidth * scale;
  587. height = window.innerHeight * scale;
  588. }
  589. const csw = `${width / scale}px`;
  590. const csh = `${height / scale}px`;
  591. if (canvas.style.width !== csw || canvas.style.height !== csh || canvas.width !== width || canvas.height !== height) {
  592. // Size doesn't match.
  593. // Resize canvas, set correct CSS pixel size, update GL.
  594. canvas.width = width;
  595. canvas.height = height;
  596. canvas.style.width = csw;
  597. canvas.style.height = csh;
  598. GodotDisplayScreen._updateGL();
  599. return 1;
  600. }
  601. return 0;
  602. },
  603. },
  604. };
  605. mergeInto(LibraryManager.library, GodotDisplayScreen);
  606. /**
  607. * Display server interface.
  608. *
  609. * Exposes all the functions needed by DisplayServer implementation.
  610. */
  611. const GodotDisplay = {
  612. $GodotDisplay__deps: ['$GodotConfig', '$GodotRuntime', '$GodotDisplayCursor', '$GodotDisplayListeners', '$GodotDisplayDragDrop', '$GodotDisplayGamepads', '$GodotDisplayScreen', '$GodotDisplayVK'],
  613. $GodotDisplay: {
  614. window_icon: '',
  615. findDPI: function () {
  616. function testDPI(dpi) {
  617. return window.matchMedia(`(max-resolution: ${dpi}dpi)`).matches;
  618. }
  619. function bisect(low, high, func) {
  620. const mid = parseInt(((high - low) / 2) + low, 10);
  621. if (high - low <= 1) {
  622. return func(high) ? high : low;
  623. }
  624. if (func(mid)) {
  625. return bisect(low, mid, func);
  626. }
  627. return bisect(mid, high, func);
  628. }
  629. try {
  630. const dpi = bisect(0, 800, testDPI);
  631. return dpi >= 96 ? dpi : 96;
  632. } catch (e) {
  633. return 96;
  634. }
  635. },
  636. },
  637. godot_js_display_is_swap_ok_cancel__sig: 'i',
  638. godot_js_display_is_swap_ok_cancel: function () {
  639. const win = (['Windows', 'Win64', 'Win32', 'WinCE']);
  640. const plat = navigator.platform || '';
  641. if (win.indexOf(plat) !== -1) {
  642. return 1;
  643. }
  644. return 0;
  645. },
  646. godot_js_display_alert__sig: 'vi',
  647. godot_js_display_alert: function (p_text) {
  648. window.alert(GodotRuntime.parseString(p_text)); // eslint-disable-line no-alert
  649. },
  650. godot_js_display_screen_dpi_get__sig: 'i',
  651. godot_js_display_screen_dpi_get: function () {
  652. return GodotDisplay.findDPI();
  653. },
  654. godot_js_display_pixel_ratio_get__sig: 'f',
  655. godot_js_display_pixel_ratio_get: function () {
  656. return GodotDisplayScreen.getPixelRatio();
  657. },
  658. godot_js_display_fullscreen_request__sig: 'i',
  659. godot_js_display_fullscreen_request: function () {
  660. return GodotDisplayScreen.requestFullscreen();
  661. },
  662. godot_js_display_fullscreen_exit__sig: 'i',
  663. godot_js_display_fullscreen_exit: function () {
  664. return GodotDisplayScreen.exitFullscreen();
  665. },
  666. godot_js_display_desired_size_set__sig: 'vii',
  667. godot_js_display_desired_size_set: function (width, height) {
  668. GodotDisplayScreen.desired_size = [width, height];
  669. GodotDisplayScreen.updateSize();
  670. },
  671. godot_js_display_size_update__sig: 'i',
  672. godot_js_display_size_update: function () {
  673. const updated = GodotDisplayScreen.updateSize();
  674. if (updated) {
  675. GodotDisplayVK.updateSize();
  676. }
  677. return updated;
  678. },
  679. godot_js_display_screen_size_get__sig: 'vii',
  680. godot_js_display_screen_size_get: function (width, height) {
  681. const scale = GodotDisplayScreen.getPixelRatio();
  682. GodotRuntime.setHeapValue(width, window.screen.width * scale, 'i32');
  683. GodotRuntime.setHeapValue(height, window.screen.height * scale, 'i32');
  684. },
  685. godot_js_display_window_size_get: function (p_width, p_height) {
  686. GodotRuntime.setHeapValue(p_width, GodotConfig.canvas.width, 'i32');
  687. GodotRuntime.setHeapValue(p_height, GodotConfig.canvas.height, 'i32');
  688. },
  689. godot_js_display_has_webgl__sig: 'ii',
  690. godot_js_display_has_webgl: function (p_version) {
  691. if (p_version !== 1 && p_version !== 2) {
  692. return false;
  693. }
  694. try {
  695. return !!document.createElement('canvas').getContext(p_version === 2 ? 'webgl2' : 'webgl');
  696. } catch (e) { /* Not available */ }
  697. return false;
  698. },
  699. /*
  700. * Canvas
  701. */
  702. godot_js_display_canvas_focus__sig: 'v',
  703. godot_js_display_canvas_focus: function () {
  704. GodotConfig.canvas.focus();
  705. },
  706. godot_js_display_canvas_is_focused__sig: 'i',
  707. godot_js_display_canvas_is_focused: function () {
  708. return document.activeElement === GodotConfig.canvas;
  709. },
  710. /*
  711. * Touchscreen
  712. */
  713. godot_js_display_touchscreen_is_available__sig: 'i',
  714. godot_js_display_touchscreen_is_available: function () {
  715. return 'ontouchstart' in window;
  716. },
  717. /*
  718. * Clipboard
  719. */
  720. godot_js_display_clipboard_set__sig: 'ii',
  721. godot_js_display_clipboard_set: function (p_text) {
  722. const text = GodotRuntime.parseString(p_text);
  723. if (!navigator.clipboard || !navigator.clipboard.writeText) {
  724. return 1;
  725. }
  726. navigator.clipboard.writeText(text).catch(function (e) {
  727. // Setting OS clipboard is only possible from an input callback.
  728. GodotRuntime.error('Setting OS clipboard is only possible from an input callback for the HTML5 plafrom. Exception:', e);
  729. });
  730. return 0;
  731. },
  732. godot_js_display_clipboard_get__sig: 'ii',
  733. godot_js_display_clipboard_get: function (callback) {
  734. const func = GodotRuntime.get_func(callback);
  735. try {
  736. navigator.clipboard.readText().then(function (result) {
  737. const ptr = GodotRuntime.allocString(result);
  738. func(ptr);
  739. GodotRuntime.free(ptr);
  740. }).catch(function (e) {
  741. // Fail graciously.
  742. });
  743. } catch (e) {
  744. // Fail graciously.
  745. }
  746. },
  747. /*
  748. * Window
  749. */
  750. godot_js_display_window_title_set__sig: 'vi',
  751. godot_js_display_window_title_set: function (p_data) {
  752. document.title = GodotRuntime.parseString(p_data);
  753. },
  754. godot_js_display_window_icon_set__sig: 'vii',
  755. godot_js_display_window_icon_set: function (p_ptr, p_len) {
  756. let link = document.getElementById('-gd-engine-icon');
  757. if (link === null) {
  758. link = document.createElement('link');
  759. link.rel = 'icon';
  760. link.id = '-gd-engine-icon';
  761. document.head.appendChild(link);
  762. }
  763. const old_icon = GodotDisplay.window_icon;
  764. const png = new Blob([GodotRuntime.heapSlice(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
  765. GodotDisplay.window_icon = URL.createObjectURL(png);
  766. link.href = GodotDisplay.window_icon;
  767. if (old_icon) {
  768. URL.revokeObjectURL(old_icon);
  769. }
  770. },
  771. /*
  772. * Cursor
  773. */
  774. godot_js_display_cursor_set_visible__sig: 'vi',
  775. godot_js_display_cursor_set_visible: function (p_visible) {
  776. const visible = p_visible !== 0;
  777. if (visible === GodotDisplayCursor.visible) {
  778. return;
  779. }
  780. GodotDisplayCursor.visible = visible;
  781. if (visible) {
  782. GodotDisplayCursor.set_shape(GodotDisplayCursor.shape);
  783. } else {
  784. GodotDisplayCursor.set_style('none');
  785. }
  786. },
  787. godot_js_display_cursor_is_hidden__sig: 'i',
  788. godot_js_display_cursor_is_hidden: function () {
  789. return !GodotDisplayCursor.visible;
  790. },
  791. godot_js_display_cursor_set_shape__sig: 'vi',
  792. godot_js_display_cursor_set_shape: function (p_string) {
  793. GodotDisplayCursor.set_shape(GodotRuntime.parseString(p_string));
  794. },
  795. godot_js_display_cursor_set_custom_shape__sig: 'viiiii',
  796. godot_js_display_cursor_set_custom_shape: function (p_shape, p_ptr, p_len, p_hotspot_x, p_hotspot_y) {
  797. const shape = GodotRuntime.parseString(p_shape);
  798. const old_shape = GodotDisplayCursor.cursors[shape];
  799. if (p_len > 0) {
  800. const png = new Blob([GodotRuntime.heapSlice(HEAPU8, p_ptr, p_len)], { type: 'image/png' });
  801. const url = URL.createObjectURL(png);
  802. GodotDisplayCursor.cursors[shape] = {
  803. url: url,
  804. x: p_hotspot_x,
  805. y: p_hotspot_y,
  806. };
  807. } else {
  808. delete GodotDisplayCursor.cursors[shape];
  809. }
  810. if (shape === GodotDisplayCursor.shape) {
  811. GodotDisplayCursor.set_shape(GodotDisplayCursor.shape);
  812. }
  813. if (old_shape) {
  814. URL.revokeObjectURL(old_shape.url);
  815. }
  816. },
  817. godot_js_display_cursor_lock_set__sig: 'vi',
  818. godot_js_display_cursor_lock_set: function (p_lock) {
  819. if (p_lock) {
  820. GodotDisplayCursor.lockPointer();
  821. } else {
  822. GodotDisplayCursor.releasePointer();
  823. }
  824. },
  825. godot_js_display_cursor_is_locked__sig: 'i',
  826. godot_js_display_cursor_is_locked: function () {
  827. return GodotDisplayCursor.isPointerLocked() ? 1 : 0;
  828. },
  829. /*
  830. * Listeners
  831. */
  832. godot_js_display_fullscreen_cb__sig: 'vi',
  833. godot_js_display_fullscreen_cb: function (callback) {
  834. const canvas = GodotConfig.canvas;
  835. const func = GodotRuntime.get_func(callback);
  836. function change_cb(evt) {
  837. if (evt.target === canvas) {
  838. func(GodotDisplayScreen.isFullscreen());
  839. }
  840. }
  841. GodotDisplayListeners.add(document, 'fullscreenchange', change_cb, false);
  842. GodotDisplayListeners.add(document, 'mozfullscreenchange', change_cb, false);
  843. GodotDisplayListeners.add(document, 'webkitfullscreenchange', change_cb, false);
  844. },
  845. godot_js_display_window_blur_cb__sig: 'vi',
  846. godot_js_display_window_blur_cb: function (callback) {
  847. const func = GodotRuntime.get_func(callback);
  848. GodotDisplayListeners.add(window, 'blur', function () {
  849. func();
  850. }, false);
  851. },
  852. godot_js_display_notification_cb__sig: 'viiiii',
  853. godot_js_display_notification_cb: function (callback, p_enter, p_exit, p_in, p_out) {
  854. const canvas = GodotConfig.canvas;
  855. const func = GodotRuntime.get_func(callback);
  856. const notif = [p_enter, p_exit, p_in, p_out];
  857. ['mouseover', 'mouseleave', 'focus', 'blur'].forEach(function (evt_name, idx) {
  858. GodotDisplayListeners.add(canvas, evt_name, function () {
  859. func(notif[idx]);
  860. }, true);
  861. });
  862. },
  863. godot_js_display_paste_cb__sig: 'vi',
  864. godot_js_display_paste_cb: function (callback) {
  865. const func = GodotRuntime.get_func(callback);
  866. GodotDisplayListeners.add(window, 'paste', function (evt) {
  867. const text = evt.clipboardData.getData('text');
  868. const ptr = GodotRuntime.allocString(text);
  869. func(ptr);
  870. GodotRuntime.free(ptr);
  871. }, false);
  872. },
  873. godot_js_display_drop_files_cb__sig: 'vi',
  874. godot_js_display_drop_files_cb: function (callback) {
  875. const func = GodotRuntime.get_func(callback);
  876. const dropFiles = function (files) {
  877. const args = files || [];
  878. if (!args.length) {
  879. return;
  880. }
  881. const argc = args.length;
  882. const argv = GodotRuntime.allocStringArray(args);
  883. func(argv, argc);
  884. GodotRuntime.freeStringArray(argv, argc);
  885. };
  886. const canvas = GodotConfig.canvas;
  887. GodotDisplayListeners.add(canvas, 'dragover', function (ev) {
  888. // Prevent default behavior (which would try to open the file(s))
  889. ev.preventDefault();
  890. }, false);
  891. GodotDisplayListeners.add(canvas, 'drop', GodotDisplayDragDrop.handler(dropFiles));
  892. },
  893. godot_js_display_setup_canvas__sig: 'viiii',
  894. godot_js_display_setup_canvas: function (p_width, p_height, p_fullscreen, p_hidpi) {
  895. const canvas = GodotConfig.canvas;
  896. GodotDisplayListeners.add(canvas, 'contextmenu', function (ev) {
  897. ev.preventDefault();
  898. }, false);
  899. GodotDisplayListeners.add(canvas, 'webglcontextlost', function (ev) {
  900. alert('WebGL context lost, please reload the page'); // eslint-disable-line no-alert
  901. ev.preventDefault();
  902. }, false);
  903. GodotDisplayScreen.hidpi = !!p_hidpi;
  904. switch (GodotConfig.canvas_resize_policy) {
  905. case 0: // None
  906. GodotDisplayScreen.desired_size = [canvas.width, canvas.height];
  907. break;
  908. case 1: // Project
  909. GodotDisplayScreen.desired_size = [p_width, p_height];
  910. break;
  911. default: // Full window
  912. // Ensure we display in the right place, the size will be handled by updateSize
  913. canvas.style.position = 'absolute';
  914. canvas.style.top = 0;
  915. canvas.style.left = 0;
  916. break;
  917. }
  918. GodotDisplayScreen.updateSize();
  919. if (p_fullscreen) {
  920. GodotDisplayScreen.requestFullscreen();
  921. }
  922. },
  923. /*
  924. * Virtual Keyboard
  925. */
  926. godot_js_display_vk_show__sig: 'viiii',
  927. godot_js_display_vk_show: function (p_text, p_multiline, p_start, p_end) {
  928. const text = GodotRuntime.parseString(p_text);
  929. const start = p_start > 0 ? p_start : 0;
  930. const end = p_end > 0 ? p_end : start;
  931. GodotDisplayVK.show(text, p_multiline, start, end);
  932. },
  933. godot_js_display_vk_hide__sig: 'v',
  934. godot_js_display_vk_hide: function () {
  935. GodotDisplayVK.hide();
  936. },
  937. godot_js_display_vk_available__sig: 'i',
  938. godot_js_display_vk_available: function () {
  939. return GodotDisplayVK.available();
  940. },
  941. godot_js_display_vk_cb__sig: 'vi',
  942. godot_js_display_vk_cb: function (p_input_cb) {
  943. const input_cb = GodotRuntime.get_func(p_input_cb);
  944. if (GodotDisplayVK.available()) {
  945. GodotDisplayVK.init(input_cb);
  946. }
  947. },
  948. /*
  949. * Gamepads
  950. */
  951. godot_js_display_gamepad_cb__sig: 'vi',
  952. godot_js_display_gamepad_cb: function (change_cb) {
  953. const onchange = GodotRuntime.get_func(change_cb);
  954. GodotDisplayGamepads.init(onchange);
  955. },
  956. godot_js_display_gamepad_sample_count__sig: 'i',
  957. godot_js_display_gamepad_sample_count: function () {
  958. return GodotDisplayGamepads.get_samples().length;
  959. },
  960. godot_js_display_gamepad_sample__sig: 'i',
  961. godot_js_display_gamepad_sample: function () {
  962. GodotDisplayGamepads.sample();
  963. return 0;
  964. },
  965. godot_js_display_gamepad_sample_get__sig: 'iiiiiii',
  966. godot_js_display_gamepad_sample_get: function (p_index, r_btns, r_btns_num, r_axes, r_axes_num, r_standard) {
  967. const sample = GodotDisplayGamepads.get_sample(p_index);
  968. if (!sample || !sample.connected) {
  969. return 1;
  970. }
  971. const btns = sample.buttons;
  972. const btns_len = btns.length < 16 ? btns.length : 16;
  973. for (let i = 0; i < btns_len; i++) {
  974. GodotRuntime.setHeapValue(r_btns + (i << 2), btns[i], 'float');
  975. }
  976. GodotRuntime.setHeapValue(r_btns_num, btns_len, 'i32');
  977. const axes = sample.axes;
  978. const axes_len = axes.length < 10 ? axes.length : 10;
  979. for (let i = 0; i < axes_len; i++) {
  980. GodotRuntime.setHeapValue(r_axes + (i << 2), axes[i], 'float');
  981. }
  982. GodotRuntime.setHeapValue(r_axes_num, axes_len, 'i32');
  983. const is_standard = sample.standard ? 1 : 0;
  984. GodotRuntime.setHeapValue(r_standard, is_standard, 'i32');
  985. return 0;
  986. },
  987. };
  988. autoAddDeps(GodotDisplay, '$GodotDisplay');
  989. mergeInto(LibraryManager.library, GodotDisplay);