os_javascript.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. /*************************************************************************/
  2. /* os_javascript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 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. #include "os_javascript.h"
  31. #include "gles2/rasterizer_gles2.h"
  32. #include "gles3/rasterizer_gles3.h"
  33. #include "io/file_access_buffered_fa.h"
  34. #include "main/main.h"
  35. #include "servers/visual/visual_server_raster.h"
  36. #include "unix/dir_access_unix.h"
  37. #include "unix/file_access_unix.h"
  38. #include <emscripten.h>
  39. #include <stdlib.h>
  40. #include "dom_keys.inc"
  41. #define DOM_BUTTON_LEFT 0
  42. #define DOM_BUTTON_MIDDLE 1
  43. #define DOM_BUTTON_RIGHT 2
  44. #define DOM_BUTTON_XBUTTON1 3
  45. #define DOM_BUTTON_XBUTTON2 4
  46. // Window (canvas)
  47. static void focus_canvas() {
  48. /* clang-format off */
  49. EM_ASM(
  50. Module.canvas.focus();
  51. );
  52. /* clang-format on */
  53. }
  54. static bool is_canvas_focused() {
  55. /* clang-format off */
  56. return EM_ASM_INT_V(
  57. return document.activeElement == Module.canvas;
  58. );
  59. /* clang-format on */
  60. }
  61. static bool cursor_inside_canvas = true;
  62. EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  63. OS_JavaScript *os = get_singleton();
  64. // Empty ID is canvas.
  65. String target_id = String::utf8(p_event->id);
  66. if (target_id.empty() || target_id == "canvas") {
  67. // This event property is the only reliable data on
  68. // browser fullscreen state.
  69. os->video_mode.fullscreen = p_event->isFullscreen;
  70. if (os->video_mode.fullscreen) {
  71. os->entering_fullscreen = false;
  72. } else {
  73. // Restoring maximized window now will cause issues,
  74. // so delay until main_loop_iterate.
  75. os->just_exited_fullscreen = true;
  76. }
  77. }
  78. return false;
  79. }
  80. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  81. video_mode = p_video_mode;
  82. }
  83. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  84. return video_mode;
  85. }
  86. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  87. EmscriptenFullscreenChangeEvent ev;
  88. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  89. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  90. return Size2(ev.screenWidth, ev.screenHeight);
  91. }
  92. void OS_JavaScript::set_window_size(const Size2 p_size) {
  93. windowed_size = p_size;
  94. if (video_mode.fullscreen) {
  95. window_maximized = false;
  96. set_window_fullscreen(false);
  97. } else {
  98. if (window_maximized) {
  99. emscripten_exit_soft_fullscreen();
  100. window_maximized = false;
  101. }
  102. emscripten_set_canvas_size(p_size.x, p_size.y);
  103. }
  104. }
  105. Size2 OS_JavaScript::get_window_size() const {
  106. int canvas[3];
  107. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  108. return Size2(canvas[0], canvas[1]);
  109. }
  110. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  111. if (video_mode.fullscreen) {
  112. window_maximized = p_enabled;
  113. set_window_fullscreen(false);
  114. } else if (!p_enabled) {
  115. emscripten_exit_soft_fullscreen();
  116. window_maximized = false;
  117. } else if (!window_maximized) {
  118. // Prevent calling emscripten_enter_soft_fullscreen mutltiple times,
  119. // this would hide page elements permanently.
  120. EmscriptenFullscreenStrategy strategy;
  121. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  122. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  123. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  124. strategy.canvasResizedCallback = NULL;
  125. emscripten_enter_soft_fullscreen(NULL, &strategy);
  126. window_maximized = p_enabled;
  127. }
  128. }
  129. bool OS_JavaScript::is_window_maximized() const {
  130. return window_maximized;
  131. }
  132. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  133. if (p_enabled == video_mode.fullscreen) {
  134. return;
  135. }
  136. // Just request changes here, if successful, logic continues in
  137. // fullscreen_change_callback.
  138. if (p_enabled) {
  139. if (window_maximized) {
  140. // Soft fullsreen during real fullscreen can cause issues, so exit.
  141. // This must be called before requesting full screen.
  142. emscripten_exit_soft_fullscreen();
  143. }
  144. EmscriptenFullscreenStrategy strategy;
  145. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  146. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  147. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  148. strategy.canvasResizedCallback = NULL;
  149. EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(NULL, false, &strategy);
  150. ERR_EXPLAIN("Enabling fullscreen is only possible from an input callback for the HTML5 platform");
  151. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  152. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  153. // Not fullscreen yet, so prevent "windowed" canvas dimensions from
  154. // being overwritten.
  155. entering_fullscreen = true;
  156. } else {
  157. // No logic allowed here, since exiting w/ ESC key won't use this function.
  158. ERR_FAIL_COND(emscripten_exit_fullscreen() != EMSCRIPTEN_RESULT_SUCCESS);
  159. }
  160. }
  161. bool OS_JavaScript::is_window_fullscreen() const {
  162. return video_mode.fullscreen;
  163. }
  164. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  165. Size2 screen = get_screen_size();
  166. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  167. }
  168. // Keys
  169. template <typename T>
  170. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  171. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  172. godot_event->set_alt(emscripten_event_ptr->altKey);
  173. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  174. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  175. }
  176. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  177. Ref<InputEventKey> ev;
  178. ev.instance();
  179. ev->set_echo(emscripten_event->repeat);
  180. dom2godot_mod(emscripten_event, ev);
  181. ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode));
  182. String unicode = String::utf8(emscripten_event->key);
  183. // Check if empty or multi-character (e.g. `CapsLock`).
  184. if (unicode.length() != 1) {
  185. // Might be empty as well, but better than nonsense.
  186. unicode = String::utf8(emscripten_event->charValue);
  187. }
  188. if (unicode.length() == 1) {
  189. ev->set_unicode(unicode[0]);
  190. }
  191. return ev;
  192. }
  193. EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  194. OS_JavaScript *os = get_singleton();
  195. Ref<InputEventKey> ev = setup_key_event(p_event);
  196. ev->set_pressed(true);
  197. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  198. // Defer to keypress event for legacy unicode retrieval.
  199. os->deferred_key_event = ev;
  200. // Do not suppress keypress event.
  201. return false;
  202. }
  203. os->input->parse_input_event(ev);
  204. return true;
  205. }
  206. EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  207. OS_JavaScript *os = get_singleton();
  208. os->deferred_key_event->set_unicode(p_event->charCode);
  209. os->input->parse_input_event(os->deferred_key_event);
  210. return true;
  211. }
  212. EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  213. Ref<InputEventKey> ev = setup_key_event(p_event);
  214. ev->set_pressed(false);
  215. get_singleton()->input->parse_input_event(ev);
  216. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  217. }
  218. // Mouse
  219. Point2 OS_JavaScript::get_mouse_position() const {
  220. return input->get_mouse_position();
  221. }
  222. int OS_JavaScript::get_mouse_button_state() const {
  223. return input->get_mouse_button_mask();
  224. }
  225. EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  226. OS_JavaScript *os = get_singleton();
  227. Ref<InputEventMouseButton> ev;
  228. ev.instance();
  229. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  230. ev->set_position(Point2(p_event->canvasX, p_event->canvasY));
  231. ev->set_global_position(ev->get_position());
  232. dom2godot_mod(p_event, ev);
  233. switch (p_event->button) {
  234. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  235. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  236. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  237. case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break;
  238. case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break;
  239. default: return false;
  240. }
  241. int mask = os->input->get_mouse_button_mask();
  242. int button_flag = 1 << (ev->get_button_index() - 1);
  243. if (ev->is_pressed()) {
  244. // Since the event is consumed, focus manually. The containing iframe,
  245. // if exists, may not have focus yet, so focus even if already focused.
  246. focus_canvas();
  247. mask |= button_flag;
  248. } else if (mask & button_flag) {
  249. mask &= ~button_flag;
  250. } else {
  251. // Received release event, but press was outside the canvas, so ignore.
  252. return false;
  253. }
  254. ev->set_button_mask(mask);
  255. os->input->parse_input_event(ev);
  256. // Prevent multi-click text selection and wheel-click scrolling anchor.
  257. // Context menu is prevented through contextmenu event.
  258. return true;
  259. }
  260. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  261. OS_JavaScript *os = get_singleton();
  262. int input_mask = os->input->get_mouse_button_mask();
  263. Point2 pos = Point2(p_event->canvasX, p_event->canvasY);
  264. // For motion outside the canvas, only read mouse movement if dragging
  265. // started inside the canvas; imitating desktop app behaviour.
  266. if (!cursor_inside_canvas && !input_mask)
  267. return false;
  268. Ref<InputEventMouseMotion> ev;
  269. ev.instance();
  270. dom2godot_mod(p_event, ev);
  271. ev->set_button_mask(input_mask);
  272. ev->set_position(pos);
  273. ev->set_global_position(ev->get_position());
  274. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  275. os->input->set_mouse_position(ev->get_position());
  276. ev->set_speed(os->input->get_last_mouse_speed());
  277. os->input->parse_input_event(ev);
  278. // Don't suppress mouseover/-leave events.
  279. return false;
  280. }
  281. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  282. switch (p_shape) {
  283. case OS::CURSOR_ARROW:
  284. default:
  285. return "auto";
  286. case OS::CURSOR_IBEAM: return "text";
  287. case OS::CURSOR_POINTING_HAND: return "pointer";
  288. case OS::CURSOR_CROSS: return "crosshair";
  289. case OS::CURSOR_WAIT: return "progress";
  290. case OS::CURSOR_BUSY: return "wait";
  291. case OS::CURSOR_DRAG: return "grab";
  292. case OS::CURSOR_CAN_DROP: return "grabbing";
  293. case OS::CURSOR_FORBIDDEN: return "no-drop";
  294. case OS::CURSOR_VSIZE: return "ns-resize";
  295. case OS::CURSOR_HSIZE: return "ew-resize";
  296. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  297. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  298. case OS::CURSOR_MOVE: return "move";
  299. case OS::CURSOR_VSPLIT: return "row-resize";
  300. case OS::CURSOR_HSPLIT: return "col-resize";
  301. case OS::CURSOR_HELP: return "help";
  302. }
  303. }
  304. static void set_css_cursor(const char *p_cursor) {
  305. /* clang-format off */
  306. EM_ASM_({
  307. Module.canvas.style.cursor = UTF8ToString($0);
  308. }, p_cursor);
  309. /* clang-format on */
  310. }
  311. static const char *get_css_cursor() {
  312. char cursor[16];
  313. /* clang-format off */
  314. EM_ASM_INT({
  315. stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  316. }, cursor);
  317. /* clang-format on */
  318. return cursor;
  319. }
  320. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  321. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  322. cursor_shape = p_shape;
  323. if (get_mouse_mode() != MOUSE_MODE_HIDDEN)
  324. set_css_cursor(godot2dom_cursor(cursor_shape));
  325. }
  326. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  327. }
  328. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  329. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  330. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  331. if (p_mode == get_mouse_mode())
  332. return;
  333. if (p_mode == MOUSE_MODE_VISIBLE) {
  334. set_css_cursor(godot2dom_cursor(cursor_shape));
  335. emscripten_exit_pointerlock();
  336. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  337. set_css_cursor("none");
  338. emscripten_exit_pointerlock();
  339. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  340. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  341. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  342. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  343. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  344. set_css_cursor(godot2dom_cursor(cursor_shape));
  345. }
  346. }
  347. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  348. if (String::utf8(get_css_cursor()) == "none")
  349. return MOUSE_MODE_HIDDEN;
  350. EmscriptenPointerlockChangeEvent ev;
  351. emscripten_get_pointerlock_status(&ev);
  352. return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  353. }
  354. // Wheel
  355. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  356. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  357. if (!is_canvas_focused()) {
  358. if (cursor_inside_canvas) {
  359. focus_canvas();
  360. } else {
  361. return false;
  362. }
  363. }
  364. InputDefault *input = get_singleton()->input;
  365. Ref<InputEventMouseButton> ev;
  366. ev.instance();
  367. ev->set_button_mask(input->get_mouse_button_mask());
  368. ev->set_position(input->get_mouse_position());
  369. ev->set_global_position(ev->get_position());
  370. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  371. ev->set_alt(input->is_key_pressed(KEY_ALT));
  372. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  373. ev->set_metakey(input->is_key_pressed(KEY_META));
  374. if (p_event->deltaY < 0)
  375. ev->set_button_index(BUTTON_WHEEL_UP);
  376. else if (p_event->deltaY > 0)
  377. ev->set_button_index(BUTTON_WHEEL_DOWN);
  378. else if (p_event->deltaX > 0)
  379. ev->set_button_index(BUTTON_WHEEL_LEFT);
  380. else if (p_event->deltaX < 0)
  381. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  382. else
  383. return false;
  384. // Different browsers give wildly different delta values, and we can't
  385. // interpret deltaMode, so use default value for wheel events' factor.
  386. ev->set_pressed(true);
  387. input->parse_input_event(ev);
  388. ev->set_pressed(false);
  389. input->parse_input_event(ev);
  390. return true;
  391. }
  392. // Touch
  393. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  394. /* clang-format off */
  395. return EM_ASM_INT_V(
  396. return 'ontouchstart' in window;
  397. );
  398. /* clang-format on */
  399. }
  400. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  401. OS_JavaScript *os = get_singleton();
  402. Ref<InputEventScreenTouch> ev;
  403. ev.instance();
  404. int lowest_id_index = -1;
  405. for (int i = 0; i < p_event->numTouches; ++i) {
  406. const EmscriptenTouchPoint &touch = p_event->touches[i];
  407. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  408. lowest_id_index = i;
  409. if (!touch.isChanged)
  410. continue;
  411. ev->set_index(touch.identifier);
  412. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  413. os->touches[i] = ev->get_position();
  414. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  415. os->input->parse_input_event(ev);
  416. }
  417. return true;
  418. }
  419. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  420. OS_JavaScript *os = get_singleton();
  421. Ref<InputEventScreenDrag> ev;
  422. ev.instance();
  423. int lowest_id_index = -1;
  424. for (int i = 0; i < p_event->numTouches; ++i) {
  425. const EmscriptenTouchPoint &touch = p_event->touches[i];
  426. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  427. lowest_id_index = i;
  428. if (!touch.isChanged)
  429. continue;
  430. ev->set_index(touch.identifier);
  431. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  432. Point2 &prev = os->touches[i];
  433. ev->set_relative(ev->get_position() - prev);
  434. prev = ev->get_position();
  435. os->input->parse_input_event(ev);
  436. }
  437. return true;
  438. }
  439. // Gamepad
  440. EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  441. InputDefault *input = get_singleton()->input;
  442. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  443. String guid = "";
  444. if (String::utf8(p_event->mapping) == "standard")
  445. guid = "Default HTML5 Gamepad";
  446. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  447. } else {
  448. input->joy_connection_changed(p_event->index, false, "");
  449. }
  450. return true;
  451. }
  452. void OS_JavaScript::process_joypads() {
  453. int joypad_count = emscripten_get_num_gamepads();
  454. for (int joypad = 0; joypad < joypad_count; joypad++) {
  455. EmscriptenGamepadEvent state;
  456. EMSCRIPTEN_RESULT query_result = emscripten_get_gamepad_status(joypad, &state);
  457. // Chromium reserves gamepads slots, so NO_DATA is an expected result.
  458. ERR_CONTINUE(query_result != EMSCRIPTEN_RESULT_SUCCESS &&
  459. query_result != EMSCRIPTEN_RESULT_NO_DATA);
  460. if (query_result == EMSCRIPTEN_RESULT_SUCCESS && state.connected) {
  461. int button_count = MIN(state.numButtons, 18);
  462. int axis_count = MIN(state.numAxes, 8);
  463. for (int button = 0; button < button_count; button++) {
  464. float value = state.analogButton[button];
  465. if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) {
  466. InputDefault::JoyAxis joy_axis;
  467. joy_axis.min = 0;
  468. joy_axis.value = value;
  469. input->joy_axis(joypad, button, joy_axis);
  470. } else {
  471. input->joy_button(joypad, button, value);
  472. }
  473. }
  474. for (int axis = 0; axis < axis_count; axis++) {
  475. InputDefault::JoyAxis joy_axis;
  476. joy_axis.min = -1;
  477. joy_axis.value = state.axis[axis];
  478. input->joy_axis(joypad, axis, joy_axis);
  479. }
  480. }
  481. }
  482. }
  483. bool OS_JavaScript::is_joy_known(int p_device) {
  484. return input->is_joy_mapped(p_device);
  485. }
  486. String OS_JavaScript::get_joy_guid(int p_device) const {
  487. return input->get_joy_guid_remapped(p_device);
  488. }
  489. // Video
  490. int OS_JavaScript::get_video_driver_count() const {
  491. return VIDEO_DRIVER_MAX;
  492. }
  493. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  494. switch (p_driver) {
  495. case VIDEO_DRIVER_GLES3:
  496. return "GLES3";
  497. case VIDEO_DRIVER_GLES2:
  498. return "GLES2";
  499. }
  500. ERR_EXPLAIN("Invalid video driver index " + itos(p_driver));
  501. ERR_FAIL_V(NULL);
  502. }
  503. // Audio
  504. int OS_JavaScript::get_audio_driver_count() const {
  505. return 1;
  506. }
  507. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  508. return "JavaScript";
  509. }
  510. // Lifecycle
  511. int OS_JavaScript::get_current_video_driver() const {
  512. return video_driver_index;
  513. }
  514. void OS_JavaScript::initialize_core() {
  515. OS_Unix::initialize_core();
  516. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  517. }
  518. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  519. EmscriptenWebGLContextAttributes attributes;
  520. emscripten_webgl_init_context_attributes(&attributes);
  521. attributes.alpha = false;
  522. attributes.antialias = false;
  523. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  524. bool gles3 = true;
  525. if (p_video_driver == VIDEO_DRIVER_GLES2) {
  526. gles3 = false;
  527. }
  528. bool gl_initialization_error = false;
  529. while (true) {
  530. if (gles3) {
  531. if (RasterizerGLES3::is_viable() == OK) {
  532. attributes.majorVersion = 2;
  533. RasterizerGLES3::register_config();
  534. RasterizerGLES3::make_current();
  535. break;
  536. } else {
  537. if (GLOBAL_GET("rendering/quality/driver/driver_fallback") == "Best") {
  538. p_video_driver = VIDEO_DRIVER_GLES2;
  539. gles3 = false;
  540. continue;
  541. } else {
  542. gl_initialization_error = true;
  543. break;
  544. }
  545. }
  546. } else {
  547. if (RasterizerGLES2::is_viable() == OK) {
  548. attributes.majorVersion = 1;
  549. RasterizerGLES2::register_config();
  550. RasterizerGLES2::make_current();
  551. break;
  552. } else {
  553. gl_initialization_error = true;
  554. break;
  555. }
  556. }
  557. }
  558. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  559. if (emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS) {
  560. gl_initialization_error = true;
  561. }
  562. if (gl_initialization_error) {
  563. OS::get_singleton()->alert("Your browser does not support any of the supported WebGL versions.\n"
  564. "Please update your browser version.",
  565. "Unable to initialize Video driver");
  566. return ERR_UNAVAILABLE;
  567. }
  568. video_driver_index = p_video_driver;
  569. video_mode = p_desired;
  570. // Can't fulfill fullscreen request during start-up due to browser security.
  571. video_mode.fullscreen = false;
  572. /* clang-format off */
  573. if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) {
  574. /* clang-format on */
  575. set_window_size(Size2(video_mode.width, video_mode.height));
  576. } else {
  577. set_window_size(get_window_size());
  578. }
  579. char locale_ptr[16];
  580. /* clang-format off */
  581. EM_ASM_ARGS({
  582. stringToUTF8(Module.locale, $0, 16);
  583. }, locale_ptr);
  584. /* clang-format on */
  585. setenv("LANG", locale_ptr, true);
  586. AudioDriverManager::initialize(p_audio_driver);
  587. VisualServer *visual_server = memnew(VisualServerRaster());
  588. input = memnew(InputDefault);
  589. EMSCRIPTEN_RESULT result;
  590. #define EM_CHECK(ev) \
  591. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  592. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  593. #define SET_EM_CALLBACK(target, ev, cb) \
  594. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  595. EM_CHECK(ev)
  596. #define SET_EM_CALLBACK_NOTARGET(ev, cb) \
  597. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  598. EM_CHECK(ev)
  599. // These callbacks from Emscripten's html5.h suffice to access most
  600. // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM
  601. // is used below.
  602. SET_EM_CALLBACK("#window", mousemove, mousemove_callback)
  603. SET_EM_CALLBACK("#canvas", mousedown, mouse_button_callback)
  604. SET_EM_CALLBACK("#window", mouseup, mouse_button_callback)
  605. SET_EM_CALLBACK("#window", wheel, wheel_callback)
  606. SET_EM_CALLBACK("#window", touchstart, touch_press_callback)
  607. SET_EM_CALLBACK("#window", touchmove, touchmove_callback)
  608. SET_EM_CALLBACK("#window", touchend, touch_press_callback)
  609. SET_EM_CALLBACK("#window", touchcancel, touch_press_callback)
  610. SET_EM_CALLBACK("#canvas", keydown, keydown_callback)
  611. SET_EM_CALLBACK("#canvas", keypress, keypress_callback)
  612. SET_EM_CALLBACK("#canvas", keyup, keyup_callback)
  613. SET_EM_CALLBACK(NULL, fullscreenchange, fullscreen_change_callback)
  614. SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback)
  615. SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback)
  616. #undef SET_EM_CALLBACK_NODATA
  617. #undef SET_EM_CALLBACK
  618. #undef EM_CHECK
  619. /* clang-format off */
  620. EM_ASM_ARGS({
  621. const send_notification = cwrap('send_notification', null, ['number']);
  622. const notifications = arguments;
  623. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) {
  624. Module.canvas.addEventListener(event, send_notification.bind(null, notifications[index]));
  625. });
  626. },
  627. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  628. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  629. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  630. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  631. );
  632. /* clang-format on */
  633. visual_server->init();
  634. return OK;
  635. }
  636. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  637. main_loop = p_main_loop;
  638. input->set_main_loop(p_main_loop);
  639. }
  640. MainLoop *OS_JavaScript::get_main_loop() const {
  641. return main_loop;
  642. }
  643. void OS_JavaScript::run_async() {
  644. main_loop->init();
  645. emscripten_set_main_loop(main_loop_callback, -1, false);
  646. }
  647. void OS_JavaScript::main_loop_callback() {
  648. get_singleton()->main_loop_iterate();
  649. }
  650. bool OS_JavaScript::main_loop_iterate() {
  651. if (is_userfs_persistent() && sync_wait_time >= 0) {
  652. int64_t current_time = get_ticks_msec();
  653. int64_t elapsed_time = current_time - last_sync_check_time;
  654. last_sync_check_time = current_time;
  655. sync_wait_time -= elapsed_time;
  656. if (sync_wait_time < 0) {
  657. /* clang-format off */
  658. EM_ASM(
  659. FS.syncfs(function(err) {
  660. if (err) { console.warn('Failed to save IDB file system: ' + err.message); }
  661. });
  662. );
  663. /* clang-format on */
  664. }
  665. }
  666. process_joypads();
  667. if (just_exited_fullscreen) {
  668. if (window_maximized) {
  669. EmscriptenFullscreenStrategy strategy;
  670. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  671. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  672. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  673. strategy.canvasResizedCallback = NULL;
  674. emscripten_enter_soft_fullscreen(NULL, &strategy);
  675. } else {
  676. emscripten_set_canvas_size(windowed_size.width, windowed_size.height);
  677. }
  678. just_exited_fullscreen = false;
  679. }
  680. int canvas[3];
  681. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  682. video_mode.width = canvas[0];
  683. video_mode.height = canvas[1];
  684. if (!window_maximized && !video_mode.fullscreen && !just_exited_fullscreen && !entering_fullscreen) {
  685. windowed_size.width = canvas[0];
  686. windowed_size.height = canvas[1];
  687. }
  688. return Main::iteration();
  689. }
  690. void OS_JavaScript::delete_main_loop() {
  691. memdelete(main_loop);
  692. }
  693. void OS_JavaScript::finalize() {
  694. memdelete(input);
  695. }
  696. // Miscellaneous
  697. extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) {
  698. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  699. cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  700. }
  701. OS_JavaScript::get_singleton()->get_main_loop()->notification(p_notification);
  702. }
  703. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  704. if (p_feature == "HTML5" || p_feature == "web")
  705. return true;
  706. #ifdef JAVASCRIPT_EVAL_ENABLED
  707. if (p_feature == "JavaScript")
  708. return true;
  709. #endif
  710. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
  711. // All extensions are already automatically enabled, this function allows
  712. // checking WebGL extension support without inline JavaScript
  713. if (p_feature == "s3tc")
  714. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb");
  715. if (p_feature == "etc")
  716. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1");
  717. if (p_feature == "etc2")
  718. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc");
  719. return false;
  720. }
  721. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  722. /* clang-format off */
  723. EM_ASM_({
  724. window.alert(UTF8ToString($0));
  725. }, p_alert.utf8().get_data());
  726. /* clang-format on */
  727. }
  728. void OS_JavaScript::set_window_title(const String &p_title) {
  729. /* clang-format off */
  730. EM_ASM_({
  731. document.title = UTF8ToString($0);
  732. }, p_title.utf8().get_data());
  733. /* clang-format on */
  734. }
  735. String OS_JavaScript::get_executable_path() const {
  736. return OS::get_executable_path();
  737. }
  738. Error OS_JavaScript::shell_open(String p_uri) {
  739. // Open URI in a new tab, browser will deal with it by protocol.
  740. /* clang-format off */
  741. EM_ASM_({
  742. window.open(UTF8ToString($0), '_blank');
  743. }, p_uri.utf8().get_data());
  744. /* clang-format on */
  745. return OK;
  746. }
  747. String OS_JavaScript::get_name() {
  748. return "HTML5";
  749. }
  750. bool OS_JavaScript::can_draw() const {
  751. return true; // Always?
  752. }
  753. String OS_JavaScript::get_user_data_dir() const {
  754. return "/userfs";
  755. };
  756. String OS_JavaScript::get_resource_dir() const {
  757. return "/";
  758. }
  759. OS::PowerState OS_JavaScript::get_power_state() {
  760. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  761. return OS::POWERSTATE_UNKNOWN;
  762. }
  763. int OS_JavaScript::get_power_seconds_left() {
  764. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  765. return -1;
  766. }
  767. int OS_JavaScript::get_power_percent_left() {
  768. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  769. return -1;
  770. }
  771. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  772. OS_JavaScript *os = get_singleton();
  773. if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  774. os->last_sync_check_time = OS::get_singleton()->get_ticks_msec();
  775. // Wait five seconds in case more files are about to be closed.
  776. os->sync_wait_time = 5000;
  777. }
  778. }
  779. void OS_JavaScript::set_idb_available(bool p_idb_available) {
  780. idb_available = p_idb_available;
  781. }
  782. bool OS_JavaScript::is_userfs_persistent() const {
  783. return idb_available;
  784. }
  785. OS_JavaScript *OS_JavaScript::get_singleton() {
  786. return static_cast<OS_JavaScript *>(OS::get_singleton());
  787. }
  788. OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) {
  789. List<String> arguments;
  790. for (int i = 1; i < p_argc; i++) {
  791. arguments.push_back(String::utf8(p_argv[i]));
  792. }
  793. set_cmdline(p_argv[0], arguments);
  794. window_maximized = false;
  795. entering_fullscreen = false;
  796. just_exited_fullscreen = false;
  797. main_loop = NULL;
  798. idb_available = false;
  799. sync_wait_time = -1;
  800. AudioDriverManager::add_driver(&audio_driver_javascript);
  801. Vector<Logger *> loggers;
  802. loggers.push_back(memnew(StdLogger));
  803. _set_logger(memnew(CompositeLogger(loggers)));
  804. FileAccessUnix::close_notification_func = file_access_close_callback;
  805. }