os_javascript.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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 "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
  127. if (!is_canvas_focused()) {
  128. focus_canvas();
  129. }
  130. mask |= button_flag;
  131. } else if (mask & button_flag) {
  132. mask &= ~button_flag;
  133. } else {
  134. // release event, but press was outside the canvas, so ignore
  135. return false;
  136. }
  137. ev->set_button_mask(mask);
  138. _input->parse_input_event(ev);
  139. // prevent selection dragging
  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(ev->get_position() - _input->get_mouse_position());
  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. if (touch_event->touches[lowest_id_index].isChanged) {
  223. Ref<InputEventMouseButton> ev_mouse;
  224. ev_mouse.instance();
  225. ev_mouse->set_button_mask(_input->get_mouse_button_mask());
  226. dom2godot_mod(touch_event, ev_mouse);
  227. const EmscriptenTouchPoint &first_touch = touch_event->touches[lowest_id_index];
  228. ev_mouse->set_position(Point2(first_touch.canvasX, first_touch.canvasY));
  229. ev_mouse->set_global_position(ev_mouse->get_position());
  230. ev_mouse->set_button_index(BUTTON_LEFT);
  231. ev_mouse->set_pressed(event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  232. _input->parse_input_event(ev_mouse);
  233. }
  234. return true;
  235. }
  236. static EM_BOOL _touchmove_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) {
  237. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_TOUCHMOVE, false);
  238. Ref<InputEventScreenDrag> ev;
  239. ev.instance();
  240. int lowest_id_index = -1;
  241. for (int i = 0; i < touch_event->numTouches; ++i) {
  242. const EmscriptenTouchPoint &touch = touch_event->touches[i];
  243. if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier)
  244. lowest_id_index = i;
  245. if (!touch.isChanged)
  246. continue;
  247. ev->set_index(touch.identifier);
  248. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  249. Point2 &prev = _prev_touches[i];
  250. ev->set_relative(ev->get_position() - prev);
  251. prev = ev->get_position();
  252. _input->parse_input_event(ev);
  253. }
  254. if (touch_event->touches[lowest_id_index].isChanged) {
  255. Ref<InputEventMouseMotion> ev_mouse;
  256. ev_mouse.instance();
  257. dom2godot_mod(touch_event, ev_mouse);
  258. ev_mouse->set_button_mask(_input->get_mouse_button_mask());
  259. const EmscriptenTouchPoint &first_touch = touch_event->touches[lowest_id_index];
  260. ev_mouse->set_position(Point2(first_touch.canvasX, first_touch.canvasY));
  261. ev_mouse->set_global_position(ev_mouse->get_position());
  262. ev_mouse->set_relative(ev_mouse->get_position() - _input->get_mouse_position());
  263. _input->set_mouse_position(ev_mouse->get_position());
  264. ev_mouse->set_speed(_input->get_last_mouse_speed());
  265. _input->parse_input_event(ev_mouse);
  266. }
  267. return true;
  268. }
  269. static Ref<InputEventKey> _setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  270. Ref<InputEventKey> ev;
  271. ev.instance();
  272. ev->set_echo(emscripten_event->repeat);
  273. dom2godot_mod(emscripten_event, ev);
  274. ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode));
  275. String unicode = String::utf8(emscripten_event->key);
  276. // check if empty or multi-character (e.g. `CapsLock`)
  277. if (unicode.length() != 1) {
  278. // might be empty as well, but better than nonsense
  279. unicode = String::utf8(emscripten_event->charValue);
  280. }
  281. if (unicode.length() == 1) {
  282. ev->set_unicode(unicode[0]);
  283. }
  284. return ev;
  285. }
  286. static Ref<InputEventKey> deferred_key_event;
  287. static EM_BOOL _keydown_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  288. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYDOWN, false);
  289. Ref<InputEventKey> ev = _setup_key_event(key_event);
  290. ev->set_pressed(true);
  291. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  292. // defer to keypress event for legacy unicode retrieval
  293. deferred_key_event = ev;
  294. return false; // do not suppress keypress event
  295. }
  296. _input->parse_input_event(ev);
  297. return true;
  298. }
  299. static EM_BOOL _keypress_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  300. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYPRESS, false);
  301. deferred_key_event->set_unicode(key_event->charCode);
  302. _input->parse_input_event(deferred_key_event);
  303. return true;
  304. }
  305. static EM_BOOL _keyup_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  306. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYUP, false);
  307. Ref<InputEventKey> ev = _setup_key_event(key_event);
  308. ev->set_pressed(false);
  309. _input->parse_input_event(ev);
  310. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  311. }
  312. static EM_BOOL joy_callback_func(int p_type, const EmscriptenGamepadEvent *p_event, void *p_user) {
  313. OS_JavaScript *os = (OS_JavaScript *)OS::get_singleton();
  314. if (os) {
  315. return os->joy_connection_changed(p_type, p_event);
  316. }
  317. return false;
  318. }
  319. extern "C" {
  320. void send_notification(int notif) {
  321. if (notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || notif == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  322. _cursor_inside_canvas = notif == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  323. }
  324. OS_JavaScript::get_singleton()->get_main_loop()->notification(notif);
  325. }
  326. }
  327. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  328. print_line("Init OS");
  329. EmscriptenWebGLContextAttributes attributes;
  330. emscripten_webgl_init_context_attributes(&attributes);
  331. attributes.alpha = false;
  332. attributes.antialias = false;
  333. attributes.majorVersion = 2;
  334. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  335. ERR_FAIL_COND_V(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS, ERR_UNAVAILABLE);
  336. video_mode = p_desired;
  337. // can't fulfil fullscreen request due to browser security
  338. video_mode.fullscreen = false;
  339. /* clang-format off */
  340. bool resize_canvas_on_start = EM_ASM_INT_V(
  341. return Module.resizeCanvasOnStart;
  342. );
  343. /* clang-format on */
  344. if (resize_canvas_on_start) {
  345. set_window_size(Size2(video_mode.width, video_mode.height));
  346. } else {
  347. Size2 canvas_size = get_window_size();
  348. video_mode.width = canvas_size.width;
  349. video_mode.height = canvas_size.height;
  350. }
  351. char locale_ptr[16];
  352. /* clang-format off */
  353. EM_ASM_ARGS({
  354. stringToUTF8(Module.locale, $0, 16);
  355. }, locale_ptr);
  356. /* clang-format on */
  357. setenv("LANG", locale_ptr, true);
  358. print_line("Init Audio");
  359. AudioDriverManager::add_driver(&audio_driver_javascript);
  360. AudioDriverManager::initialize(p_audio_driver);
  361. RasterizerGLES3::register_config();
  362. RasterizerGLES3::make_current();
  363. print_line("Init VS");
  364. visual_server = memnew(VisualServerRaster());
  365. // visual_server->cursor_set_visible(false, 0);
  366. print_line("Init Physicsserver");
  367. input = memnew(InputDefault);
  368. _input = input;
  369. power_manager = memnew(PowerJavascript);
  370. #define EM_CHECK(ev) \
  371. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  372. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  373. #define SET_EM_CALLBACK(target, ev, cb) \
  374. result = emscripten_set_##ev##_callback(target, this, true, &cb); \
  375. EM_CHECK(ev)
  376. #define SET_EM_CALLBACK_NODATA(ev, cb) \
  377. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  378. EM_CHECK(ev)
  379. EMSCRIPTEN_RESULT result;
  380. SET_EM_CALLBACK("#window", mousemove, _mousemove_callback)
  381. SET_EM_CALLBACK("#canvas", mousedown, _mousebutton_callback)
  382. SET_EM_CALLBACK("#window", mouseup, _mousebutton_callback)
  383. SET_EM_CALLBACK("#window", wheel, _wheel_callback)
  384. SET_EM_CALLBACK("#window", touchstart, _touchpress_callback)
  385. SET_EM_CALLBACK("#window", touchmove, _touchmove_callback)
  386. SET_EM_CALLBACK("#window", touchend, _touchpress_callback)
  387. SET_EM_CALLBACK("#window", touchcancel, _touchpress_callback)
  388. SET_EM_CALLBACK("#canvas", keydown, _keydown_callback)
  389. SET_EM_CALLBACK("#canvas", keypress, _keypress_callback)
  390. SET_EM_CALLBACK("#canvas", keyup, _keyup_callback)
  391. SET_EM_CALLBACK(NULL, resize, _browser_resize_callback)
  392. SET_EM_CALLBACK(NULL, fullscreenchange, _fullscreen_change_callback)
  393. SET_EM_CALLBACK_NODATA(gamepadconnected, joy_callback_func)
  394. SET_EM_CALLBACK_NODATA(gamepaddisconnected, joy_callback_func)
  395. #undef SET_EM_CALLBACK_NODATA
  396. #undef SET_EM_CALLBACK
  397. #undef EM_CHECK
  398. visual_server->init();
  399. return OK;
  400. }
  401. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  402. main_loop = p_main_loop;
  403. input->set_main_loop(p_main_loop);
  404. }
  405. void OS_JavaScript::delete_main_loop() {
  406. memdelete(main_loop);
  407. }
  408. void OS_JavaScript::finalize() {
  409. memdelete(input);
  410. }
  411. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  412. /* clang-format off */
  413. EM_ASM_({
  414. window.alert(UTF8ToString($0));
  415. }, p_alert.utf8().get_data());
  416. /* clang-format on */
  417. }
  418. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  419. switch (p_shape) {
  420. case OS::CURSOR_ARROW:
  421. default:
  422. return "auto";
  423. case OS::CURSOR_IBEAM: return "text";
  424. case OS::CURSOR_POINTING_HAND: return "pointer";
  425. case OS::CURSOR_CROSS: return "crosshair";
  426. case OS::CURSOR_WAIT: return "progress";
  427. case OS::CURSOR_BUSY: return "wait";
  428. case OS::CURSOR_DRAG: return "grab";
  429. case OS::CURSOR_CAN_DROP: return "grabbing";
  430. case OS::CURSOR_FORBIDDEN: return "no-drop";
  431. case OS::CURSOR_VSIZE: return "ns-resize";
  432. case OS::CURSOR_HSIZE: return "ew-resize";
  433. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  434. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  435. case OS::CURSOR_MOVE: return "move";
  436. case OS::CURSOR_VSPLIT: return "row-resize";
  437. case OS::CURSOR_HSPLIT: return "col-resize";
  438. case OS::CURSOR_HELP: return "help";
  439. }
  440. }
  441. void OS_JavaScript::set_css_cursor(const char *p_cursor) {
  442. /* clang-format off */
  443. EM_ASM_({
  444. Module.canvas.style.cursor = UTF8ToString($0);
  445. }, p_cursor);
  446. /* clang-format on */
  447. }
  448. const char *OS_JavaScript::get_css_cursor() const {
  449. char cursor[16];
  450. /* clang-format off */
  451. EM_ASM_INT({
  452. stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  453. }, cursor);
  454. /* clang-format on */
  455. return cursor;
  456. }
  457. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  458. ERR_FAIL_INDEX(p_mode, MOUSE_MODE_CONFINED + 1);
  459. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  460. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  461. if (p_mode == get_mouse_mode())
  462. return;
  463. if (p_mode == MOUSE_MODE_VISIBLE) {
  464. set_css_cursor(godot2dom_cursor(cursor_shape));
  465. emscripten_exit_pointerlock();
  466. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  467. set_css_cursor("none");
  468. emscripten_exit_pointerlock();
  469. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  470. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  471. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  472. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  473. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  474. set_css_cursor(godot2dom_cursor(cursor_shape));
  475. }
  476. }
  477. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  478. if (!strcmp(get_css_cursor(), "none"))
  479. return MOUSE_MODE_HIDDEN;
  480. EmscriptenPointerlockChangeEvent ev;
  481. emscripten_get_pointerlock_status(&ev);
  482. return ev.isActive && (strcmp(ev.id, "canvas") == 0) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  483. }
  484. Point2 OS_JavaScript::get_mouse_position() const {
  485. return input->get_mouse_position();
  486. }
  487. int OS_JavaScript::get_mouse_button_state() const {
  488. return input->get_mouse_button_mask();
  489. }
  490. void OS_JavaScript::set_window_title(const String &p_title) {
  491. /* clang-format off */
  492. EM_ASM_({
  493. document.title = UTF8ToString($0);
  494. }, p_title.utf8().get_data());
  495. /* clang-format on */
  496. }
  497. //interesting byt not yet
  498. //void set_clipboard(const String& p_text);
  499. //String get_clipboard() const;
  500. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  501. video_mode = p_video_mode;
  502. }
  503. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  504. return video_mode;
  505. }
  506. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  507. EmscriptenFullscreenChangeEvent ev;
  508. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  509. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  510. return Size2(ev.screenWidth, ev.screenHeight);
  511. }
  512. void OS_JavaScript::set_window_size(const Size2 p_size) {
  513. windowed_size = p_size;
  514. if (is_window_fullscreen()) {
  515. window_maximized = false;
  516. set_window_fullscreen(false);
  517. } else if (is_window_maximized()) {
  518. set_window_maximized(false);
  519. } else {
  520. video_mode.width = p_size.x;
  521. video_mode.height = p_size.y;
  522. emscripten_set_canvas_size(p_size.x, p_size.y);
  523. }
  524. }
  525. Size2 OS_JavaScript::get_window_size() const {
  526. int canvas[3];
  527. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  528. return Size2(canvas[0], canvas[1]);
  529. }
  530. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  531. window_maximized = p_enabled;
  532. if (is_window_fullscreen()) {
  533. set_window_fullscreen(false);
  534. return;
  535. }
  536. // Calling emscripten_enter_soft_fullscreen mutltiple times hides all
  537. // page elements except the canvas permanently, so track state
  538. if (p_enabled && !soft_fs_enabled) {
  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_enter_soft_fullscreen(NULL, &strategy);
  545. soft_fs_enabled = true;
  546. video_mode.width = get_window_size().width;
  547. video_mode.height = get_window_size().height;
  548. } else if (!p_enabled) {
  549. emscripten_exit_soft_fullscreen();
  550. soft_fs_enabled = false;
  551. video_mode.width = windowed_size.width;
  552. video_mode.height = windowed_size.height;
  553. emscripten_set_canvas_size(video_mode.width, video_mode.height);
  554. }
  555. }
  556. void OS_JavaScript::set_window_fullscreen(bool p_enable) {
  557. if (p_enable == is_window_fullscreen()) {
  558. return;
  559. }
  560. // only requesting changes here, if successful, canvas is resized in
  561. // _browser_resize_callback or _fullscreen_change_callback
  562. EMSCRIPTEN_RESULT result;
  563. if (p_enable) {
  564. if (window_maximized) {
  565. // soft fs during real fs can cause issues
  566. set_window_maximized(false);
  567. window_maximized = true;
  568. }
  569. EmscriptenFullscreenStrategy strategy;
  570. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  571. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  572. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  573. strategy.canvasResizedCallback = NULL;
  574. emscripten_request_fullscreen_strategy(NULL, false, &strategy);
  575. } else {
  576. result = emscripten_exit_fullscreen();
  577. if (result != EMSCRIPTEN_RESULT_SUCCESS) {
  578. ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result));
  579. }
  580. }
  581. }
  582. bool OS_JavaScript::is_window_fullscreen() const {
  583. return video_mode.fullscreen;
  584. }
  585. void OS_JavaScript::request_canvas_size_adjustment() {
  586. canvas_size_adjustment_requested = true;
  587. }
  588. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  589. Size2 screen = get_screen_size();
  590. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  591. }
  592. String OS_JavaScript::get_name() {
  593. return "HTML5";
  594. }
  595. MainLoop *OS_JavaScript::get_main_loop() const {
  596. return main_loop;
  597. }
  598. bool OS_JavaScript::can_draw() const {
  599. return true; //always?
  600. }
  601. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  602. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  603. cursor_shape = p_shape;
  604. if (get_mouse_mode() != MOUSE_MODE_HIDDEN)
  605. set_css_cursor(godot2dom_cursor(cursor_shape));
  606. }
  607. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  608. }
  609. void OS_JavaScript::main_loop_begin() {
  610. if (main_loop)
  611. main_loop->init();
  612. /* clang-format off */
  613. EM_ASM_ARGS({
  614. const send_notification = cwrap('send_notification', null, ['number']);
  615. const notifs = arguments;
  616. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, i) {
  617. Module.canvas.addEventListener(event, send_notification.bind(null, notifs[i]));
  618. });
  619. },
  620. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  621. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  622. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  623. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  624. );
  625. /* clang-format on */
  626. }
  627. bool OS_JavaScript::main_loop_iterate() {
  628. if (!main_loop)
  629. return false;
  630. if (idbfs_available && time_to_save_sync >= 0) {
  631. int64_t newtime = get_ticks_msec();
  632. int64_t elapsed = newtime - last_sync_time;
  633. last_sync_time = newtime;
  634. time_to_save_sync -= elapsed;
  635. if (time_to_save_sync < 0) {
  636. //time to sync, for real
  637. /* clang-format off */
  638. EM_ASM(
  639. FS.syncfs(function(err) {
  640. if (err) { Module.printErr('Failed to save IDB file system: ' + err.message); }
  641. });
  642. );
  643. /* clang-format on */
  644. }
  645. }
  646. process_joypads();
  647. if (canvas_size_adjustment_requested) {
  648. if (video_mode.fullscreen || window_maximized) {
  649. video_mode.width = get_window_size().width;
  650. video_mode.height = get_window_size().height;
  651. }
  652. if (!video_mode.fullscreen) {
  653. set_window_maximized(window_maximized);
  654. }
  655. canvas_size_adjustment_requested = false;
  656. }
  657. return Main::iteration();
  658. }
  659. void OS_JavaScript::main_loop_end() {
  660. if (main_loop)
  661. main_loop->finish();
  662. }
  663. void OS_JavaScript::process_accelerometer(const Vector3 &p_accelerometer) {
  664. input->set_accelerometer(p_accelerometer);
  665. }
  666. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  667. /* clang-format off */
  668. return EM_ASM_INT_V(
  669. return 'ontouchstart' in window;
  670. );
  671. /* clang-format on */
  672. }
  673. void OS_JavaScript::main_loop_request_quit() {
  674. if (main_loop)
  675. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  676. }
  677. Error OS_JavaScript::shell_open(String p_uri) {
  678. /* clang-format off */
  679. EM_ASM_({
  680. window.open(UTF8ToString($0), '_blank');
  681. }, p_uri.utf8().get_data());
  682. /* clang-format on */
  683. return OK;
  684. }
  685. String OS_JavaScript::get_resource_dir() const {
  686. return "/"; //javascript has it's own filesystem for resources inside the APK
  687. }
  688. String OS_JavaScript::get_user_data_dir() const {
  689. /*
  690. if (get_user_data_dir_func)
  691. return get_user_data_dir_func();
  692. */
  693. return "/userfs";
  694. };
  695. String OS_JavaScript::get_executable_path() const {
  696. return OS::get_executable_path();
  697. }
  698. void OS_JavaScript::_close_notification_funcs(const String &p_file, int p_flags) {
  699. OS_JavaScript *os = static_cast<OS_JavaScript *>(get_singleton());
  700. if (os->idbfs_available && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  701. os->last_sync_time = OS::get_singleton()->get_ticks_msec();
  702. os->time_to_save_sync = 5000; //five seconds since last save
  703. }
  704. }
  705. void OS_JavaScript::process_joypads() {
  706. int joy_count = emscripten_get_num_gamepads();
  707. for (int i = 0; i < joy_count; i++) {
  708. EmscriptenGamepadEvent state;
  709. emscripten_get_gamepad_status(i, &state);
  710. if (state.connected) {
  711. int num_buttons = MIN(state.numButtons, 18);
  712. int num_axes = MIN(state.numAxes, 8);
  713. for (int j = 0; j < num_buttons; j++) {
  714. float value = state.analogButton[j];
  715. if (String(state.mapping) == "standard" && (j == 6 || j == 7)) {
  716. InputDefault::JoyAxis jx;
  717. jx.min = 0;
  718. jx.value = value;
  719. input->joy_axis(i, j, jx);
  720. } else {
  721. input->joy_button(i, j, value);
  722. }
  723. }
  724. for (int j = 0; j < num_axes; j++) {
  725. InputDefault::JoyAxis jx;
  726. jx.min = -1;
  727. jx.value = state.axis[j];
  728. input->joy_axis(i, j, jx);
  729. }
  730. }
  731. }
  732. }
  733. bool OS_JavaScript::joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event) {
  734. if (p_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  735. String guid = "";
  736. if (String(p_event->mapping) == "standard")
  737. guid = "Default HTML5 Gamepad";
  738. input->joy_connection_changed(p_event->index, true, String(p_event->id), guid);
  739. } else {
  740. input->joy_connection_changed(p_event->index, false, "");
  741. }
  742. return true;
  743. }
  744. bool OS_JavaScript::is_joy_known(int p_device) {
  745. return input->is_joy_mapped(p_device);
  746. }
  747. String OS_JavaScript::get_joy_guid(int p_device) const {
  748. return input->get_joy_guid_remapped(p_device);
  749. }
  750. OS::PowerState OS_JavaScript::get_power_state() {
  751. return power_manager->get_power_state();
  752. }
  753. int OS_JavaScript::get_power_seconds_left() {
  754. return power_manager->get_power_seconds_left();
  755. }
  756. int OS_JavaScript::get_power_percent_left() {
  757. return power_manager->get_power_percent_left();
  758. }
  759. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  760. if (p_feature == "HTML5" || p_feature == "web")
  761. return true;
  762. #ifdef JAVASCRIPT_EVAL_ENABLED
  763. if (p_feature == "JavaScript")
  764. return true;
  765. #endif
  766. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
  767. // all extensions are already automatically enabled, this function allows
  768. // checking WebGL extension support without inline JavaScript
  769. if (p_feature == "s3tc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb"))
  770. return true;
  771. if (p_feature == "etc" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1"))
  772. return true;
  773. if (p_feature == "etc2" && emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc"))
  774. return true;
  775. return false;
  776. }
  777. void OS_JavaScript::set_idbfs_available(bool p_idbfs_available) {
  778. idbfs_available = p_idbfs_available;
  779. }
  780. bool OS_JavaScript::is_userfs_persistent() const {
  781. return idbfs_available;
  782. }
  783. OS_JavaScript::OS_JavaScript(const char *p_execpath, GetUserDataDirFunc p_get_user_data_dir_func) {
  784. set_cmdline(p_execpath, get_cmdline_args());
  785. main_loop = NULL;
  786. window_maximized = false;
  787. soft_fs_enabled = false;
  788. canvas_size_adjustment_requested = false;
  789. get_user_data_dir_func = p_get_user_data_dir_func;
  790. FileAccessUnix::close_notification_func = _close_notification_funcs;
  791. idbfs_available = false;
  792. time_to_save_sync = -1;
  793. Vector<Logger *> loggers;
  794. loggers.push_back(memnew(StdLogger));
  795. _set_logger(memnew(CompositeLogger(loggers)));
  796. }
  797. OS_JavaScript::~OS_JavaScript() {
  798. }