os_javascript.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  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_position(input->get_mouse_position());
  372. ev->set_global_position(ev->get_position());
  373. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  374. ev->set_alt(input->is_key_pressed(KEY_ALT));
  375. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  376. ev->set_metakey(input->is_key_pressed(KEY_META));
  377. if (p_event->deltaY < 0)
  378. ev->set_button_index(BUTTON_WHEEL_UP);
  379. else if (p_event->deltaY > 0)
  380. ev->set_button_index(BUTTON_WHEEL_DOWN);
  381. else if (p_event->deltaX > 0)
  382. ev->set_button_index(BUTTON_WHEEL_LEFT);
  383. else if (p_event->deltaX < 0)
  384. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  385. else
  386. return false;
  387. // Different browsers give wildly different delta values, and we can't
  388. // interpret deltaMode, so use default value for wheel events' factor.
  389. int button_flag = 1 << (ev->get_button_index() - 1);
  390. ev->set_pressed(true);
  391. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  392. input->parse_input_event(ev);
  393. ev->set_pressed(false);
  394. ev->set_button_mask(input->get_mouse_button_mask() & ~button_flag);
  395. input->parse_input_event(ev);
  396. return true;
  397. }
  398. // Touch
  399. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  400. /* clang-format off */
  401. return EM_ASM_INT_V(
  402. return 'ontouchstart' in window;
  403. );
  404. /* clang-format on */
  405. }
  406. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  407. OS_JavaScript *os = get_singleton();
  408. Ref<InputEventScreenTouch> ev;
  409. ev.instance();
  410. int lowest_id_index = -1;
  411. for (int i = 0; i < p_event->numTouches; ++i) {
  412. const EmscriptenTouchPoint &touch = p_event->touches[i];
  413. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  414. lowest_id_index = i;
  415. if (!touch.isChanged)
  416. continue;
  417. ev->set_index(touch.identifier);
  418. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  419. os->touches[i] = ev->get_position();
  420. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  421. os->input->parse_input_event(ev);
  422. }
  423. return true;
  424. }
  425. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  426. OS_JavaScript *os = get_singleton();
  427. Ref<InputEventScreenDrag> ev;
  428. ev.instance();
  429. int lowest_id_index = -1;
  430. for (int i = 0; i < p_event->numTouches; ++i) {
  431. const EmscriptenTouchPoint &touch = p_event->touches[i];
  432. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  433. lowest_id_index = i;
  434. if (!touch.isChanged)
  435. continue;
  436. ev->set_index(touch.identifier);
  437. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  438. Point2 &prev = os->touches[i];
  439. ev->set_relative(ev->get_position() - prev);
  440. prev = ev->get_position();
  441. os->input->parse_input_event(ev);
  442. }
  443. return true;
  444. }
  445. // Gamepad
  446. EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  447. InputDefault *input = get_singleton()->input;
  448. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  449. String guid = "";
  450. if (String::utf8(p_event->mapping) == "standard")
  451. guid = "Default HTML5 Gamepad";
  452. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  453. } else {
  454. input->joy_connection_changed(p_event->index, false, "");
  455. }
  456. return true;
  457. }
  458. void OS_JavaScript::process_joypads() {
  459. int joypad_count = emscripten_get_num_gamepads();
  460. for (int joypad = 0; joypad < joypad_count; joypad++) {
  461. EmscriptenGamepadEvent state;
  462. emscripten_get_gamepad_status(joypad, &state);
  463. if (state.connected) {
  464. int button_count = MIN(state.numButtons, 18);
  465. int axis_count = MIN(state.numAxes, 8);
  466. for (int button = 0; button < button_count; button++) {
  467. float value = state.analogButton[button];
  468. if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) {
  469. InputDefault::JoyAxis joy_axis;
  470. joy_axis.min = 0;
  471. joy_axis.value = value;
  472. input->joy_axis(joypad, button, joy_axis);
  473. } else {
  474. input->joy_button(joypad, button, value);
  475. }
  476. }
  477. for (int axis = 0; axis < axis_count; axis++) {
  478. InputDefault::JoyAxis joy_axis;
  479. joy_axis.min = -1;
  480. joy_axis.value = state.axis[axis];
  481. input->joy_axis(joypad, axis, joy_axis);
  482. }
  483. }
  484. }
  485. }
  486. bool OS_JavaScript::is_joy_known(int p_device) {
  487. return input->is_joy_mapped(p_device);
  488. }
  489. String OS_JavaScript::get_joy_guid(int p_device) const {
  490. return input->get_joy_guid_remapped(p_device);
  491. }
  492. // Video
  493. int OS_JavaScript::get_video_driver_count() const {
  494. return VIDEO_DRIVER_MAX;
  495. }
  496. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  497. switch (p_driver) {
  498. case VIDEO_DRIVER_GLES3:
  499. return "GLES3";
  500. case VIDEO_DRIVER_GLES2:
  501. return "GLES2";
  502. }
  503. ERR_EXPLAIN("Invalid video driver index " + itos(p_driver));
  504. ERR_FAIL_V(NULL);
  505. }
  506. // Audio
  507. int OS_JavaScript::get_audio_driver_count() const {
  508. return 1;
  509. }
  510. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  511. return "JavaScript";
  512. }
  513. // Lifecycle
  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. switch (p_video_driver) {
  525. case VIDEO_DRIVER_GLES3:
  526. attributes.majorVersion = 2;
  527. RasterizerGLES3::register_config();
  528. RasterizerGLES3::make_current();
  529. break;
  530. case VIDEO_DRIVER_GLES2:
  531. attributes.majorVersion = 1;
  532. RasterizerGLES2::register_config();
  533. RasterizerGLES2::make_current();
  534. break;
  535. }
  536. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  537. ERR_EXPLAIN("WebGL " + itos(attributes.majorVersion) + ".0 not available");
  538. ERR_FAIL_COND_V(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS, ERR_UNAVAILABLE);
  539. video_mode = p_desired;
  540. // Can't fulfil fullscreen request during start-up due to browser security.
  541. video_mode.fullscreen = false;
  542. /* clang-format off */
  543. if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) {
  544. /* clang-format on */
  545. set_window_size(Size2(video_mode.width, video_mode.height));
  546. } else {
  547. set_window_size(get_window_size());
  548. }
  549. char locale_ptr[16];
  550. /* clang-format off */
  551. EM_ASM_ARGS({
  552. stringToUTF8(Module.locale, $0, 16);
  553. }, locale_ptr);
  554. /* clang-format on */
  555. setenv("LANG", locale_ptr, true);
  556. AudioDriverManager::initialize(p_audio_driver);
  557. VisualServer *visual_server = memnew(VisualServerRaster());
  558. input = memnew(InputDefault);
  559. EMSCRIPTEN_RESULT result;
  560. #define EM_CHECK(ev) \
  561. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  562. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  563. #define SET_EM_CALLBACK(target, ev, cb) \
  564. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  565. EM_CHECK(ev)
  566. #define SET_EM_CALLBACK_NOTARGET(ev, cb) \
  567. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  568. EM_CHECK(ev)
  569. // These callbacks from Emscripten's html5.h suffice to access most
  570. // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM
  571. // is used below.
  572. SET_EM_CALLBACK("#window", mousemove, mousemove_callback)
  573. SET_EM_CALLBACK("#canvas", mousedown, mouse_button_callback)
  574. SET_EM_CALLBACK("#window", mouseup, mouse_button_callback)
  575. SET_EM_CALLBACK("#window", wheel, wheel_callback)
  576. SET_EM_CALLBACK("#window", touchstart, touch_press_callback)
  577. SET_EM_CALLBACK("#window", touchmove, touchmove_callback)
  578. SET_EM_CALLBACK("#window", touchend, touch_press_callback)
  579. SET_EM_CALLBACK("#window", touchcancel, touch_press_callback)
  580. SET_EM_CALLBACK("#canvas", keydown, keydown_callback)
  581. SET_EM_CALLBACK("#canvas", keypress, keypress_callback)
  582. SET_EM_CALLBACK("#canvas", keyup, keyup_callback)
  583. SET_EM_CALLBACK(NULL, resize, browser_resize_callback)
  584. SET_EM_CALLBACK(NULL, fullscreenchange, fullscreen_change_callback)
  585. SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback)
  586. SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback)
  587. #undef SET_EM_CALLBACK_NODATA
  588. #undef SET_EM_CALLBACK
  589. #undef EM_CHECK
  590. /* clang-format off */
  591. EM_ASM_ARGS({
  592. const send_notification = cwrap('send_notification', null, ['number']);
  593. const notifications = arguments;
  594. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) {
  595. Module.canvas.addEventListener(event, send_notification.bind(null, notifications[index]));
  596. });
  597. },
  598. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  599. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  600. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  601. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  602. );
  603. /* clang-format on */
  604. visual_server->init();
  605. return OK;
  606. }
  607. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  608. main_loop = p_main_loop;
  609. input->set_main_loop(p_main_loop);
  610. }
  611. MainLoop *OS_JavaScript::get_main_loop() const {
  612. return main_loop;
  613. }
  614. void OS_JavaScript::run_async() {
  615. main_loop->init();
  616. emscripten_set_main_loop(main_loop_callback, -1, false);
  617. }
  618. void OS_JavaScript::main_loop_callback() {
  619. get_singleton()->main_loop_iterate();
  620. }
  621. bool OS_JavaScript::main_loop_iterate() {
  622. if (is_userfs_persistent() && sync_wait_time >= 0) {
  623. int64_t current_time = get_ticks_msec();
  624. int64_t elapsed_time = current_time - last_sync_check_time;
  625. last_sync_check_time = current_time;
  626. sync_wait_time -= elapsed_time;
  627. if (sync_wait_time < 0) {
  628. /* clang-format off */
  629. EM_ASM(
  630. FS.syncfs(function(err) {
  631. if (err) { Module.printErr('Failed to save IDB file system: ' + err.message); }
  632. });
  633. );
  634. /* clang-format on */
  635. }
  636. }
  637. process_joypads();
  638. if (canvas_size_adjustment_requested) {
  639. if (video_mode.fullscreen || window_maximized) {
  640. video_mode.width = get_window_size().width;
  641. video_mode.height = get_window_size().height;
  642. }
  643. if (!video_mode.fullscreen) {
  644. set_window_maximized(window_maximized);
  645. }
  646. canvas_size_adjustment_requested = false;
  647. }
  648. return Main::iteration();
  649. }
  650. void OS_JavaScript::delete_main_loop() {
  651. memdelete(main_loop);
  652. }
  653. void OS_JavaScript::finalize() {
  654. memdelete(input);
  655. }
  656. // Miscellaneous
  657. extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) {
  658. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  659. cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  660. }
  661. OS_JavaScript::get_singleton()->get_main_loop()->notification(p_notification);
  662. }
  663. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  664. if (p_feature == "HTML5" || p_feature == "web")
  665. return true;
  666. #ifdef JAVASCRIPT_EVAL_ENABLED
  667. if (p_feature == "JavaScript")
  668. return true;
  669. #endif
  670. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
  671. // All extensions are already automatically enabled, this function allows
  672. // checking WebGL extension support without inline JavaScript
  673. if (p_feature == "s3tc")
  674. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb");
  675. if (p_feature == "etc")
  676. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1");
  677. if (p_feature == "etc2")
  678. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc");
  679. return false;
  680. }
  681. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  682. /* clang-format off */
  683. EM_ASM_({
  684. window.alert(UTF8ToString($0));
  685. }, p_alert.utf8().get_data());
  686. /* clang-format on */
  687. }
  688. void OS_JavaScript::set_window_title(const String &p_title) {
  689. /* clang-format off */
  690. EM_ASM_({
  691. document.title = UTF8ToString($0);
  692. }, p_title.utf8().get_data());
  693. /* clang-format on */
  694. }
  695. String OS_JavaScript::get_executable_path() const {
  696. return OS::get_executable_path();
  697. }
  698. Error OS_JavaScript::shell_open(String p_uri) {
  699. // Open URI in a new tab, browser will deal with it by protocol.
  700. /* clang-format off */
  701. EM_ASM_({
  702. window.open(UTF8ToString($0), '_blank');
  703. }, p_uri.utf8().get_data());
  704. /* clang-format on */
  705. return OK;
  706. }
  707. String OS_JavaScript::get_name() {
  708. return "HTML5";
  709. }
  710. bool OS_JavaScript::can_draw() const {
  711. return true; // Always?
  712. }
  713. String OS_JavaScript::get_user_data_dir() const {
  714. return "/userfs";
  715. };
  716. String OS_JavaScript::get_resource_dir() const {
  717. return "/";
  718. }
  719. OS::PowerState OS_JavaScript::get_power_state() {
  720. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  721. return OS::POWERSTATE_UNKNOWN;
  722. }
  723. int OS_JavaScript::get_power_seconds_left() {
  724. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  725. return -1;
  726. }
  727. int OS_JavaScript::get_power_percent_left() {
  728. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  729. return -1;
  730. }
  731. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  732. OS_JavaScript *os = get_singleton();
  733. if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  734. os->last_sync_check_time = OS::get_singleton()->get_ticks_msec();
  735. // Wait five seconds in case more files are about to be closed.
  736. os->sync_wait_time = 5000;
  737. }
  738. }
  739. void OS_JavaScript::set_idb_available(bool p_idb_available) {
  740. idb_available = p_idb_available;
  741. }
  742. bool OS_JavaScript::is_userfs_persistent() const {
  743. return idb_available;
  744. }
  745. OS_JavaScript *OS_JavaScript::get_singleton() {
  746. return static_cast<OS_JavaScript *>(OS::get_singleton());
  747. }
  748. OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) {
  749. List<String> arguments;
  750. for (int i = 1; i < p_argc; i++) {
  751. arguments.push_back(String::utf8(p_argv[i]));
  752. }
  753. set_cmdline(p_argv[0], arguments);
  754. window_maximized = false;
  755. soft_fullscreen_enabled = false;
  756. canvas_size_adjustment_requested = false;
  757. main_loop = NULL;
  758. idb_available = false;
  759. sync_wait_time = -1;
  760. AudioDriverManager::add_driver(&audio_driver_javascript);
  761. Vector<Logger *> loggers;
  762. loggers.push_back(memnew(StdLogger));
  763. _set_logger(memnew(CompositeLogger(loggers)));
  764. FileAccessUnix::close_notification_func = file_access_close_callback;
  765. }