os_javascript.cpp 29 KB

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