os_javascript.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  1. /*************************************************************************/
  2. /* os_javascript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* http://www.godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2017 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2017 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/global_config.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 InputModifierState dom2godot_mod(T emscripten_event_ptr) {
  46. InputModifierState mod;
  47. mod.shift = emscripten_event_ptr->shiftKey;
  48. mod.alt = emscripten_event_ptr->altKey;
  49. mod.control = emscripten_event_ptr->ctrlKey;
  50. mod.meta = emscripten_event_ptr->metaKey;
  51. return mod;
  52. }
  53. int OS_JavaScript::get_video_driver_count() const {
  54. return 1;
  55. }
  56. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  57. return "GLES3";
  58. }
  59. OS::VideoMode OS_JavaScript::get_default_video_mode() const {
  60. return OS::VideoMode();
  61. }
  62. int OS_JavaScript::get_audio_driver_count() const {
  63. return 1;
  64. }
  65. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  66. return "JavaScript";
  67. }
  68. void OS_JavaScript::initialize_core() {
  69. OS_Unix::initialize_core();
  70. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  71. }
  72. void OS_JavaScript::set_opengl_extensions(const char *p_gl_extensions) {
  73. ERR_FAIL_COND(!p_gl_extensions);
  74. gl_extensions = p_gl_extensions;
  75. }
  76. static EM_BOOL _browser_resize_callback(int event_type, const EmscriptenUiEvent *ui_event, void *user_data) {
  77. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_RESIZE, false);
  78. OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
  79. // the order in which _browser_resize_callback and
  80. // _fullscreen_change_callback are called is browser-dependent,
  81. // so try adjusting for fullscreen in both
  82. if (os->is_window_fullscreen() || os->is_window_maximized()) {
  83. OS::VideoMode vm = os->get_video_mode();
  84. vm.width = ui_event->windowInnerWidth;
  85. vm.height = ui_event->windowInnerHeight;
  86. os->set_video_mode(vm);
  87. emscripten_set_canvas_size(ui_event->windowInnerWidth, ui_event->windowInnerHeight);
  88. }
  89. return false;
  90. }
  91. static Size2 _windowed_size;
  92. static EM_BOOL _fullscreen_change_callback(int event_type, const EmscriptenFullscreenChangeEvent *event, void *user_data) {
  93. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_FULLSCREENCHANGE, false);
  94. OS_JavaScript *os = static_cast<OS_JavaScript *>(user_data);
  95. String id = String::utf8(event->id);
  96. // empty id is canvas
  97. if (id.empty() || id == "canvas") {
  98. OS::VideoMode vm = os->get_video_mode();
  99. // this event property is the only reliable information on
  100. // browser fullscreen state
  101. vm.fullscreen = event->isFullscreen;
  102. if (event->isFullscreen) {
  103. vm.width = event->screenWidth;
  104. vm.height = event->screenHeight;
  105. os->set_video_mode(vm);
  106. emscripten_set_canvas_size(vm.width, vm.height);
  107. } else {
  108. os->set_video_mode(vm);
  109. if (!os->is_window_maximized()) {
  110. os->set_window_size(_windowed_size);
  111. }
  112. }
  113. }
  114. return false;
  115. }
  116. static InputDefault *_input;
  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. InputEvent ev;
  120. ev.type = InputEvent::MOUSE_BUTTON;
  121. ev.mouse_button.pressed = event_type == EMSCRIPTEN_EVENT_MOUSEDOWN;
  122. ev.mouse_button.global_x = ev.mouse_button.x = mouse_event->canvasX;
  123. ev.mouse_button.global_y = ev.mouse_button.y = mouse_event->canvasY;
  124. ev.mouse_button.mod = dom2godot_mod(mouse_event);
  125. switch (mouse_event->button) {
  126. case DOM_BUTTON_LEFT: ev.mouse_button.button_index = BUTTON_LEFT; break;
  127. case DOM_BUTTON_MIDDLE: ev.mouse_button.button_index = BUTTON_MIDDLE; break;
  128. case DOM_BUTTON_RIGHT: ev.mouse_button.button_index = BUTTON_RIGHT; break;
  129. default: return false;
  130. }
  131. ev.mouse_button.button_mask = _input->get_mouse_button_mask();
  132. if (ev.mouse_button.pressed)
  133. ev.mouse_button.button_mask |= 1 << ev.mouse_button.button_index;
  134. else
  135. ev.mouse_button.button_mask &= ~(1 << ev.mouse_button.button_index);
  136. ev.mouse_button.button_mask >>= 1;
  137. _input->parse_input_event(ev);
  138. return true;
  139. }
  140. static EM_BOOL _mousemove_callback(int event_type, const EmscriptenMouseEvent *mouse_event, void *user_data) {
  141. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_MOUSEMOVE, false);
  142. InputEvent ev;
  143. ev.type = InputEvent::MOUSE_MOTION;
  144. ev.mouse_motion.mod = dom2godot_mod(mouse_event);
  145. ev.mouse_motion.button_mask = _input->get_mouse_button_mask() >> 1;
  146. ev.mouse_motion.global_x = ev.mouse_motion.x = mouse_event->canvasX;
  147. ev.mouse_motion.global_y = ev.mouse_motion.y = mouse_event->canvasY;
  148. ev.mouse_motion.relative_x = _input->get_mouse_position().x - ev.mouse_motion.x;
  149. ev.mouse_motion.relative_y = _input->get_mouse_position().y - ev.mouse_motion.y;
  150. _input->set_mouse_position(Point2(ev.mouse_motion.x, ev.mouse_motion.y));
  151. ev.mouse_motion.speed_x = _input->get_last_mouse_speed().x;
  152. ev.mouse_motion.speed_y = _input->get_last_mouse_speed().y;
  153. _input->parse_input_event(ev);
  154. return true;
  155. }
  156. static EM_BOOL _wheel_callback(int event_type, const EmscriptenWheelEvent *wheel_event, void *user_data) {
  157. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  158. InputEvent ev;
  159. ev.type = InputEvent::MOUSE_BUTTON;
  160. ev.mouse_button.button_mask = _input->get_mouse_button_mask() >> 1;
  161. ev.mouse_button.global_x = ev.mouse_button.x = _input->get_mouse_position().x;
  162. ev.mouse_button.global_y = ev.mouse_button.y = _input->get_mouse_position().y;
  163. ev.mouse_button.mod.shift = _input->is_key_pressed(KEY_SHIFT);
  164. ev.mouse_button.mod.alt = _input->is_key_pressed(KEY_ALT);
  165. ev.mouse_button.mod.control = _input->is_key_pressed(KEY_CONTROL);
  166. ev.mouse_button.mod.meta = _input->is_key_pressed(KEY_META);
  167. if (wheel_event->deltaY < 0)
  168. ev.mouse_button.button_index = BUTTON_WHEEL_UP;
  169. else if (wheel_event->deltaY > 0)
  170. ev.mouse_button.button_index = BUTTON_WHEEL_DOWN;
  171. else if (wheel_event->deltaX > 0)
  172. ev.mouse_button.button_index = BUTTON_WHEEL_LEFT;
  173. else if (wheel_event->deltaX < 0)
  174. ev.mouse_button.button_index = BUTTON_WHEEL_RIGHT;
  175. else
  176. return false;
  177. ev.mouse_button.pressed = true;
  178. _input->parse_input_event(ev);
  179. ev.mouse_button.pressed = false;
  180. _input->parse_input_event(ev);
  181. return true;
  182. }
  183. static Point2 _prev_touches[32];
  184. static EM_BOOL _touchpress_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) {
  185. ERR_FAIL_COND_V(
  186. event_type != EMSCRIPTEN_EVENT_TOUCHSTART &&
  187. event_type != EMSCRIPTEN_EVENT_TOUCHEND &&
  188. event_type != EMSCRIPTEN_EVENT_TOUCHCANCEL,
  189. false);
  190. InputEvent ev;
  191. ev.type = InputEvent::SCREEN_TOUCH;
  192. int lowest_id_index = -1;
  193. for (int i = 0; i < touch_event->numTouches; ++i) {
  194. const EmscriptenTouchPoint &touch = touch_event->touches[i];
  195. if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier)
  196. lowest_id_index = i;
  197. if (!touch.isChanged)
  198. continue;
  199. ev.screen_touch.index = touch.identifier;
  200. _prev_touches[i].x = ev.screen_touch.x = touch.canvasX;
  201. _prev_touches[i].y = ev.screen_touch.y = touch.canvasY;
  202. ev.screen_touch.pressed = event_type == EMSCRIPTEN_EVENT_TOUCHSTART;
  203. _input->parse_input_event(ev);
  204. }
  205. if (touch_event->touches[lowest_id_index].isChanged) {
  206. ev.type = InputEvent::MOUSE_BUTTON;
  207. ev.mouse_button.mod = dom2godot_mod(touch_event);
  208. ev.mouse_button.button_mask = _input->get_mouse_button_mask() >> 1;
  209. ev.mouse_button.global_x = ev.mouse_button.x = touch_event->touches[lowest_id_index].canvasX;
  210. ev.mouse_button.global_y = ev.mouse_button.y = touch_event->touches[lowest_id_index].canvasY;
  211. ev.mouse_button.button_index = BUTTON_LEFT;
  212. ev.mouse_button.pressed = event_type == EMSCRIPTEN_EVENT_TOUCHSTART;
  213. _input->parse_input_event(ev);
  214. }
  215. return true;
  216. }
  217. static EM_BOOL _touchmove_callback(int event_type, const EmscriptenTouchEvent *touch_event, void *user_data) {
  218. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_TOUCHMOVE, false);
  219. InputEvent ev;
  220. ev.type = InputEvent::SCREEN_DRAG;
  221. int lowest_id_index = -1;
  222. for (int i = 0; i < touch_event->numTouches; ++i) {
  223. const EmscriptenTouchPoint &touch = touch_event->touches[i];
  224. if (lowest_id_index == -1 || touch.identifier < touch_event->touches[lowest_id_index].identifier)
  225. lowest_id_index = i;
  226. if (!touch.isChanged)
  227. continue;
  228. ev.screen_drag.index = touch.identifier;
  229. ev.screen_drag.x = touch.canvasX;
  230. ev.screen_drag.y = touch.canvasY;
  231. Point2 &prev = _prev_touches[i];
  232. ev.screen_drag.relative_x = touch.canvasX - prev.x;
  233. ev.screen_drag.relative_y = touch.canvasY - prev.y;
  234. prev.x = ev.screen_drag.x;
  235. prev.y = ev.screen_drag.y;
  236. _input->parse_input_event(ev);
  237. }
  238. if (touch_event->touches[lowest_id_index].isChanged) {
  239. ev.type = InputEvent::MOUSE_MOTION;
  240. ev.mouse_motion.mod = dom2godot_mod(touch_event);
  241. ev.mouse_motion.button_mask = _input->get_mouse_button_mask() >> 1;
  242. ev.mouse_motion.global_x = ev.mouse_motion.x = touch_event->touches[lowest_id_index].canvasX;
  243. ev.mouse_motion.global_y = ev.mouse_motion.y = touch_event->touches[lowest_id_index].canvasY;
  244. ev.mouse_motion.relative_x = _input->get_mouse_position().x - ev.mouse_motion.x;
  245. ev.mouse_motion.relative_y = _input->get_mouse_position().y - ev.mouse_motion.y;
  246. _input->set_mouse_position(Point2(ev.mouse_motion.x, ev.mouse_motion.y));
  247. ev.mouse_motion.speed_x = _input->get_last_mouse_speed().x;
  248. ev.mouse_motion.speed_y = _input->get_last_mouse_speed().y;
  249. _input->parse_input_event(ev);
  250. }
  251. return true;
  252. }
  253. static InputEvent _setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  254. InputEvent ev;
  255. ev.type = InputEvent::KEY;
  256. ev.key.echo = emscripten_event->repeat;
  257. ev.key.mod = dom2godot_mod(emscripten_event);
  258. ev.key.scancode = dom2godot_scancode(emscripten_event->keyCode);
  259. String unicode = String::utf8(emscripten_event->key);
  260. // check if empty or multi-character (e.g. `CapsLock`)
  261. if (unicode.length() != 1) {
  262. // might be empty as well, but better than nonsense
  263. unicode = String::utf8(emscripten_event->charValue);
  264. }
  265. if (unicode.length() == 1) {
  266. ev.key.unicode = unicode[0];
  267. }
  268. return ev;
  269. }
  270. static InputEvent deferred_key_event;
  271. static EM_BOOL _keydown_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  272. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYDOWN, false);
  273. InputEvent ev = _setup_key_event(key_event);
  274. ev.key.pressed = true;
  275. if (ev.key.unicode == 0 && keycode_has_unicode(ev.key.scancode)) {
  276. // defer to keypress event for legacy unicode retrieval
  277. deferred_key_event = ev;
  278. return false; // do not suppress keypress event
  279. }
  280. _input->parse_input_event(ev);
  281. return true;
  282. }
  283. static EM_BOOL _keypress_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  284. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYPRESS, false);
  285. deferred_key_event.key.unicode = key_event->charCode;
  286. _input->parse_input_event(deferred_key_event);
  287. return true;
  288. }
  289. static EM_BOOL _keyup_callback(int event_type, const EmscriptenKeyboardEvent *key_event, void *user_data) {
  290. ERR_FAIL_COND_V(event_type != EMSCRIPTEN_EVENT_KEYUP, false);
  291. InputEvent ev = _setup_key_event(key_event);
  292. ev.key.pressed = false;
  293. _input->parse_input_event(ev);
  294. return ev.key.scancode != KEY_UNKNOWN && ev.key.scancode != 0;
  295. }
  296. static EM_BOOL joy_callback_func(int p_type, const EmscriptenGamepadEvent *p_event, void *p_user) {
  297. OS_JavaScript *os = (OS_JavaScript *)OS::get_singleton();
  298. if (os) {
  299. return os->joy_connection_changed(p_type, p_event);
  300. }
  301. return false;
  302. }
  303. void OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  304. print_line("Init OS");
  305. EmscriptenWebGLContextAttributes attributes;
  306. emscripten_webgl_init_context_attributes(&attributes);
  307. attributes.alpha = false;
  308. attributes.antialias = false;
  309. attributes.majorVersion = 2;
  310. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  311. ERR_FAIL_COND(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS);
  312. video_mode = p_desired;
  313. // can't fulfil fullscreen request due to browser security
  314. video_mode.fullscreen = false;
  315. set_window_size(Size2(p_desired.width, p_desired.height));
  316. // find locale, emscripten only sets "C"
  317. char locale_ptr[16];
  318. /* clang-format off */
  319. EM_ASM_({
  320. var locale = "";
  321. if (Module.locale) {
  322. // best case: server-side script reads Accept-Language early and
  323. // defines the locale to be read here
  324. locale = Module.locale;
  325. } else {
  326. // no luck, use what the JS engine can tell us
  327. // if this turns out not compatible enough, add tests for
  328. // browserLanguage, systemLanguage and userLanguage
  329. locale = navigator.languages ? navigator.languages[0] : navigator.language;
  330. }
  331. locale = locale.split('.')[0];
  332. stringToUTF8(locale, $0, 16);
  333. }, locale_ptr);
  334. /* clang-format on */
  335. setenv("LANG", locale_ptr, true);
  336. print_line("Init Audio");
  337. AudioDriverManager::add_driver(&audio_driver_javascript);
  338. audio_driver_javascript.set_singleton();
  339. if (audio_driver_javascript.init() != OK) {
  340. ERR_PRINT("Initializing audio failed.");
  341. }
  342. RasterizerGLES3::register_config();
  343. RasterizerGLES3::make_current();
  344. print_line("Init VS");
  345. visual_server = memnew(VisualServerRaster());
  346. visual_server->cursor_set_visible(false, 0);
  347. print_line("Init Physicsserver");
  348. physics_server = memnew(PhysicsServerSW);
  349. physics_server->init();
  350. physics_2d_server = memnew(Physics2DServerSW);
  351. physics_2d_server->init();
  352. input = memnew(InputDefault);
  353. _input = input;
  354. power_manager = memnew(PowerJavascript);
  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("#canvas", mousemove, _mousemove_callback)
  366. SET_EM_CALLBACK("#canvas", mousedown, _mousebutton_callback)
  367. SET_EM_CALLBACK("#canvas", mouseup, _mousebutton_callback)
  368. SET_EM_CALLBACK("#canvas", wheel, _wheel_callback)
  369. SET_EM_CALLBACK("#canvas", touchstart, _touchpress_callback)
  370. SET_EM_CALLBACK("#canvas", touchmove, _touchmove_callback)
  371. SET_EM_CALLBACK("#canvas", touchend, _touchpress_callback)
  372. SET_EM_CALLBACK("#canvas", touchcancel, _touchpress_callback)
  373. SET_EM_CALLBACK(NULL, keydown, _keydown_callback)
  374. SET_EM_CALLBACK(NULL, keypress, _keypress_callback)
  375. SET_EM_CALLBACK(NULL, 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. #ifdef JAVASCRIPT_EVAL_ENABLED
  384. javascript_eval = memnew(JavaScript);
  385. GlobalConfig::get_singleton()->add_singleton(GlobalConfig::Singleton("JavaScript", javascript_eval));
  386. #endif
  387. visual_server->init();
  388. }
  389. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  390. main_loop = p_main_loop;
  391. input->set_main_loop(p_main_loop);
  392. }
  393. void OS_JavaScript::delete_main_loop() {
  394. memdelete(main_loop);
  395. }
  396. void OS_JavaScript::finalize() {
  397. memdelete(input);
  398. }
  399. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  400. /* clang-format off */
  401. EM_ASM_({
  402. window.alert(UTF8ToString($0));
  403. }, p_alert.utf8().get_data());
  404. /* clang-format on */
  405. }
  406. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  407. switch (p_shape) {
  408. case OS::CURSOR_ARROW:
  409. default:
  410. return "auto";
  411. case OS::CURSOR_IBEAM: return "text";
  412. case OS::CURSOR_POINTING_HAND: return "pointer";
  413. case OS::CURSOR_CROSS: return "crosshair";
  414. case OS::CURSOR_WAIT: return "progress";
  415. case OS::CURSOR_BUSY: return "wait";
  416. case OS::CURSOR_DRAG: return "grab";
  417. case OS::CURSOR_CAN_DROP: return "grabbing";
  418. case OS::CURSOR_FORBIDDEN: return "no-drop";
  419. case OS::CURSOR_VSIZE: return "ns-resize";
  420. case OS::CURSOR_HSIZE: return "ew-resize";
  421. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  422. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  423. case OS::CURSOR_MOVE: return "move";
  424. case OS::CURSOR_VSPLIT: return "row-resize";
  425. case OS::CURSOR_HSPLIT: return "col-resize";
  426. case OS::CURSOR_HELP: return "help";
  427. }
  428. }
  429. void OS_JavaScript::set_css_cursor(const char *p_cursor) {
  430. /* clang-format off */
  431. EM_ASM_({
  432. Module.canvas.style.cursor = Module.UTF8ToString($0);
  433. }, p_cursor);
  434. /* clang-format on */
  435. }
  436. const char *OS_JavaScript::get_css_cursor() const {
  437. char cursor[16];
  438. /* clang-format off */
  439. EM_ASM_INT({
  440. Module.stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  441. }, cursor);
  442. /* clang-format on */
  443. return cursor;
  444. }
  445. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  446. ERR_FAIL_INDEX(p_mode, MOUSE_MODE_CONFINED + 1);
  447. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  448. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  449. if (p_mode == get_mouse_mode())
  450. return;
  451. if (p_mode == MOUSE_MODE_VISIBLE) {
  452. set_css_cursor(godot2dom_cursor(cursor_shape));
  453. emscripten_exit_pointerlock();
  454. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  455. set_css_cursor("none");
  456. emscripten_exit_pointerlock();
  457. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  458. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  459. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  460. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  461. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  462. set_css_cursor(godot2dom_cursor(cursor_shape));
  463. }
  464. }
  465. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  466. if (!strcmp(get_css_cursor(), "none"))
  467. return MOUSE_MODE_HIDDEN;
  468. EmscriptenPointerlockChangeEvent ev;
  469. emscripten_get_pointerlock_status(&ev);
  470. return ev.isActive && (strcmp(ev.id, "canvas") == 0) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  471. }
  472. Point2 OS_JavaScript::get_mouse_position() const {
  473. return input->get_mouse_position();
  474. }
  475. int OS_JavaScript::get_mouse_button_state() const {
  476. return input->get_mouse_button_mask();
  477. }
  478. void OS_JavaScript::set_window_title(const String &p_title) {
  479. /* clang-format off */
  480. EM_ASM_({
  481. document.title = UTF8ToString($0);
  482. }, p_title.utf8().get_data());
  483. /* clang-format on */
  484. }
  485. //interesting byt not yet
  486. //void set_clipboard(const String& p_text);
  487. //String get_clipboard() const;
  488. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  489. video_mode = p_video_mode;
  490. }
  491. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  492. return video_mode;
  493. }
  494. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  495. ERR_FAIL_COND_V(p_screen != 0, Size2());
  496. EmscriptenFullscreenChangeEvent ev;
  497. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  498. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  499. return Size2(ev.screenWidth, ev.screenHeight);
  500. }
  501. void OS_JavaScript::set_window_size(const Size2 p_size) {
  502. window_maximized = false;
  503. if (is_window_fullscreen()) {
  504. set_window_fullscreen(false);
  505. }
  506. _windowed_size = p_size;
  507. video_mode.width = p_size.x;
  508. video_mode.height = p_size.y;
  509. emscripten_set_canvas_size(p_size.x, p_size.y);
  510. }
  511. Size2 OS_JavaScript::get_window_size() const {
  512. int canvas[3];
  513. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  514. return Size2(canvas[0], canvas[1]);
  515. }
  516. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  517. window_maximized = p_enabled;
  518. if (p_enabled) {
  519. if (is_window_fullscreen()) {
  520. // _browser_resize callback will set canvas size
  521. set_window_fullscreen(false);
  522. } else {
  523. /* clang-format off */
  524. video_mode.width = EM_ASM_INT_V(return window.innerWidth);
  525. video_mode.height = EM_ASM_INT_V(return window.innerHeight);
  526. /* clang-format on */
  527. emscripten_set_canvas_size(video_mode.width, video_mode.height);
  528. }
  529. } else {
  530. set_window_size(_windowed_size);
  531. }
  532. }
  533. void OS_JavaScript::set_window_fullscreen(bool p_enable) {
  534. if (p_enable == is_window_fullscreen()) {
  535. return;
  536. }
  537. // only requesting changes here, if successful, canvas is resized in
  538. // _browser_resize_callback or _fullscreen_change_callback
  539. EMSCRIPTEN_RESULT result;
  540. if (p_enable) {
  541. /* clang-format off */
  542. EM_ASM(Module.requestFullscreen(false, false););
  543. /* clang-format on */
  544. } else {
  545. result = emscripten_exit_fullscreen();
  546. if (result != EMSCRIPTEN_RESULT_SUCCESS) {
  547. ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result));
  548. }
  549. }
  550. }
  551. bool OS_JavaScript::is_window_fullscreen() const {
  552. return video_mode.fullscreen;
  553. }
  554. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  555. Size2 screen = get_screen_size();
  556. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  557. }
  558. String OS_JavaScript::get_name() {
  559. return "HTML5";
  560. }
  561. MainLoop *OS_JavaScript::get_main_loop() const {
  562. return main_loop;
  563. }
  564. bool OS_JavaScript::can_draw() const {
  565. return true; //always?
  566. }
  567. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  568. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  569. cursor_shape = p_shape;
  570. if (get_mouse_mode() != MOUSE_MODE_HIDDEN)
  571. set_css_cursor(godot2dom_cursor(cursor_shape));
  572. }
  573. void OS_JavaScript::main_loop_begin() {
  574. if (main_loop)
  575. main_loop->init();
  576. }
  577. bool OS_JavaScript::main_loop_iterate() {
  578. if (!main_loop)
  579. return false;
  580. if (time_to_save_sync >= 0) {
  581. int64_t newtime = get_ticks_msec();
  582. int64_t elapsed = newtime - last_sync_time;
  583. last_sync_time = newtime;
  584. time_to_save_sync -= elapsed;
  585. if (time_to_save_sync < 0) {
  586. //time to sync, for real
  587. /* clang-format off */
  588. EM_ASM(
  589. FS.syncfs(function(err) {
  590. if (err) { Module.printErr('Failed to save IDB file system: ' + err.message); }
  591. });
  592. );
  593. /* clang-format on */
  594. }
  595. }
  596. process_joypads();
  597. return Main::iteration();
  598. }
  599. void OS_JavaScript::main_loop_end() {
  600. if (main_loop)
  601. main_loop->finish();
  602. }
  603. void OS_JavaScript::main_loop_focusout() {
  604. if (main_loop)
  605. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  606. //audio_driver_javascript.set_pause(true);
  607. }
  608. void OS_JavaScript::main_loop_focusin() {
  609. if (main_loop)
  610. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  611. //audio_driver_javascript.set_pause(false);
  612. }
  613. void OS_JavaScript::process_accelerometer(const Vector3 &p_accelerometer) {
  614. input->set_accelerometer(p_accelerometer);
  615. }
  616. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  617. return false; //???
  618. }
  619. void OS_JavaScript::main_loop_request_quit() {
  620. if (main_loop)
  621. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  622. }
  623. Error OS_JavaScript::shell_open(String p_uri) {
  624. /* clang-format off */
  625. EM_ASM_({
  626. window.open(UTF8ToString($0), '_blank');
  627. }, p_uri.utf8().get_data());
  628. /* clang-format on */
  629. return OK;
  630. }
  631. String OS_JavaScript::get_resource_dir() const {
  632. return "/"; //javascript has it's own filesystem for resources inside the APK
  633. }
  634. String OS_JavaScript::get_data_dir() const {
  635. /*
  636. if (get_data_dir_func)
  637. return get_data_dir_func();
  638. */
  639. return "/userfs";
  640. //return GlobalConfig::get_singleton()->get_singleton_object("GodotOS")->call("get_data_dir");
  641. };
  642. String OS_JavaScript::get_executable_path() const {
  643. return OS::get_executable_path();
  644. }
  645. void OS_JavaScript::_close_notification_funcs(const String &p_file, int p_flags) {
  646. print_line("close " + p_file + " flags " + itos(p_flags));
  647. if (p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  648. static_cast<OS_JavaScript *>(get_singleton())->last_sync_time = OS::get_singleton()->get_ticks_msec();
  649. static_cast<OS_JavaScript *>(get_singleton())->time_to_save_sync = 5000; //five seconds since last save
  650. }
  651. }
  652. void OS_JavaScript::process_joypads() {
  653. int joy_count = emscripten_get_num_gamepads();
  654. for (int i = 0; i < joy_count; i++) {
  655. EmscriptenGamepadEvent state;
  656. emscripten_get_gamepad_status(i, &state);
  657. if (state.connected) {
  658. int num_buttons = MIN(state.numButtons, 18);
  659. int num_axes = MIN(state.numAxes, 8);
  660. for (int j = 0; j < num_buttons; j++) {
  661. float value = state.analogButton[j];
  662. if (String(state.mapping) == "standard" && (j == 6 || j == 7)) {
  663. InputDefault::JoyAxis jx;
  664. jx.min = 0;
  665. jx.value = value;
  666. input->joy_axis(i, j, jx);
  667. } else {
  668. input->joy_button(i, j, value);
  669. }
  670. }
  671. for (int j = 0; j < num_axes; j++) {
  672. InputDefault::JoyAxis jx;
  673. jx.min = -1;
  674. jx.value = state.axis[j];
  675. input->joy_axis(i, j, jx);
  676. }
  677. }
  678. }
  679. }
  680. bool OS_JavaScript::joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event) {
  681. if (p_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  682. String guid = "";
  683. if (String(p_event->mapping) == "standard")
  684. guid = "Default HTML5 Gamepad";
  685. input->joy_connection_changed(p_event->index, true, String(p_event->id), guid);
  686. } else {
  687. input->joy_connection_changed(p_event->index, false, "");
  688. }
  689. return true;
  690. }
  691. bool OS_JavaScript::is_joy_known(int p_device) {
  692. return input->is_joy_mapped(p_device);
  693. }
  694. String OS_JavaScript::get_joy_guid(int p_device) const {
  695. return input->get_joy_guid_remapped(p_device);
  696. }
  697. PowerState OS_JavaScript::get_power_state() {
  698. return power_manager->get_power_state();
  699. }
  700. int OS_JavaScript::get_power_seconds_left() {
  701. return power_manager->get_power_seconds_left();
  702. }
  703. int OS_JavaScript::get_power_percent_left() {
  704. return power_manager->get_power_percent_left();
  705. }
  706. OS_JavaScript::OS_JavaScript(const char *p_execpath, GetDataDirFunc p_get_data_dir_func) {
  707. set_cmdline(p_execpath, get_cmdline_args());
  708. main_loop = NULL;
  709. gl_extensions = NULL;
  710. window_maximized = false;
  711. get_data_dir_func = p_get_data_dir_func;
  712. FileAccessUnix::close_notification_func = _close_notification_funcs;
  713. time_to_save_sync = -1;
  714. }
  715. OS_JavaScript::~OS_JavaScript() {
  716. }