os_javascript.cpp 29 KB

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