os_javascript.cpp 29 KB

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