os_javascript.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  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. void OS_JavaScript::set_css_cursor(const char *p_cursor) {
  407. /* clang-format off */
  408. EM_ASM_({
  409. Module.canvas.style.cursor = Module.UTF8ToString($0);
  410. }, p_cursor);
  411. /* clang-format on */
  412. }
  413. const char *OS_JavaScript::get_css_cursor() const {
  414. char cursor[16];
  415. /* clang-format off */
  416. EM_ASM_INT({
  417. Module.stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  418. }, cursor);
  419. /* clang-format on */
  420. return cursor;
  421. }
  422. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  423. ERR_FAIL_INDEX(p_mode, MOUSE_MODE_CONFINED + 1);
  424. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  425. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  426. if (p_mode == get_mouse_mode())
  427. return;
  428. if (p_mode == MOUSE_MODE_VISIBLE) {
  429. set_css_cursor("auto");
  430. emscripten_exit_pointerlock();
  431. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  432. set_css_cursor("none");
  433. emscripten_exit_pointerlock();
  434. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  435. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  436. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  437. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  438. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  439. set_css_cursor("auto");
  440. }
  441. }
  442. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  443. if (!strcmp(get_css_cursor(), "none"))
  444. return MOUSE_MODE_HIDDEN;
  445. EmscriptenPointerlockChangeEvent ev;
  446. emscripten_get_pointerlock_status(&ev);
  447. return ev.isActive && (strcmp(ev.id, "canvas") == 0) ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  448. }
  449. Point2 OS_JavaScript::get_mouse_position() const {
  450. return input->get_mouse_position();
  451. }
  452. int OS_JavaScript::get_mouse_button_state() const {
  453. return input->get_mouse_button_mask();
  454. }
  455. void OS_JavaScript::set_window_title(const String &p_title) {
  456. /* clang-format off */
  457. EM_ASM_({
  458. document.title = UTF8ToString($0);
  459. }, p_title.utf8().get_data());
  460. /* clang-format on */
  461. }
  462. //interesting byt not yet
  463. //void set_clipboard(const String& p_text);
  464. //String get_clipboard() const;
  465. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  466. video_mode = p_video_mode;
  467. }
  468. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  469. return video_mode;
  470. }
  471. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  472. ERR_FAIL_COND_V(p_screen != 0, Size2());
  473. EmscriptenFullscreenChangeEvent ev;
  474. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  475. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  476. return Size2(ev.screenWidth, ev.screenHeight);
  477. }
  478. void OS_JavaScript::set_window_size(const Size2 p_size) {
  479. window_maximized = false;
  480. if (is_window_fullscreen()) {
  481. set_window_fullscreen(false);
  482. }
  483. _windowed_size = p_size;
  484. video_mode.width = p_size.x;
  485. video_mode.height = p_size.y;
  486. emscripten_set_canvas_size(p_size.x, p_size.y);
  487. }
  488. Size2 OS_JavaScript::get_window_size() const {
  489. int canvas[3];
  490. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  491. return Size2(canvas[0], canvas[1]);
  492. }
  493. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  494. window_maximized = p_enabled;
  495. if (p_enabled) {
  496. if (is_window_fullscreen()) {
  497. // _browser_resize callback will set canvas size
  498. set_window_fullscreen(false);
  499. } else {
  500. /* clang-format off */
  501. video_mode.width = EM_ASM_INT_V(return window.innerWidth);
  502. video_mode.height = EM_ASM_INT_V(return window.innerHeight);
  503. /* clang-format on */
  504. emscripten_set_canvas_size(video_mode.width, video_mode.height);
  505. }
  506. } else {
  507. set_window_size(_windowed_size);
  508. }
  509. }
  510. void OS_JavaScript::set_window_fullscreen(bool p_enable) {
  511. if (p_enable == is_window_fullscreen()) {
  512. return;
  513. }
  514. // only requesting changes here, if successful, canvas is resized in
  515. // _browser_resize_callback or _fullscreen_change_callback
  516. EMSCRIPTEN_RESULT result;
  517. if (p_enable) {
  518. /* clang-format off */
  519. EM_ASM(Module.requestFullscreen(false, false););
  520. /* clang-format on */
  521. } else {
  522. result = emscripten_exit_fullscreen();
  523. if (result != EMSCRIPTEN_RESULT_SUCCESS) {
  524. ERR_PRINTS("Failed to exit fullscreen: Code " + itos(result));
  525. }
  526. }
  527. }
  528. bool OS_JavaScript::is_window_fullscreen() const {
  529. return video_mode.fullscreen;
  530. }
  531. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  532. Size2 screen = get_screen_size();
  533. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  534. }
  535. String OS_JavaScript::get_name() {
  536. return "HTML5";
  537. }
  538. MainLoop *OS_JavaScript::get_main_loop() const {
  539. return main_loop;
  540. }
  541. bool OS_JavaScript::can_draw() const {
  542. return true; //always?
  543. }
  544. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  545. //javascript really really really has no mouse.. how amazing..
  546. }
  547. void OS_JavaScript::main_loop_begin() {
  548. if (main_loop)
  549. main_loop->init();
  550. }
  551. bool OS_JavaScript::main_loop_iterate() {
  552. if (!main_loop)
  553. return false;
  554. if (time_to_save_sync >= 0) {
  555. int64_t newtime = get_ticks_msec();
  556. int64_t elapsed = newtime - last_sync_time;
  557. last_sync_time = newtime;
  558. time_to_save_sync -= elapsed;
  559. if (time_to_save_sync < 0) {
  560. //time to sync, for real
  561. /* clang-format off */
  562. EM_ASM(
  563. FS.syncfs(function(err) {
  564. if (err) { Module.printErr('Failed to save IDB file system: ' + err.message); }
  565. });
  566. );
  567. /* clang-format on */
  568. }
  569. }
  570. process_joypads();
  571. return Main::iteration();
  572. }
  573. void OS_JavaScript::main_loop_end() {
  574. if (main_loop)
  575. main_loop->finish();
  576. }
  577. void OS_JavaScript::main_loop_focusout() {
  578. if (main_loop)
  579. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
  580. //audio_driver_javascript.set_pause(true);
  581. }
  582. void OS_JavaScript::main_loop_focusin() {
  583. if (main_loop)
  584. main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
  585. //audio_driver_javascript.set_pause(false);
  586. }
  587. void OS_JavaScript::process_accelerometer(const Vector3 &p_accelerometer) {
  588. input->set_accelerometer(p_accelerometer);
  589. }
  590. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  591. return false; //???
  592. }
  593. void OS_JavaScript::main_loop_request_quit() {
  594. if (main_loop)
  595. main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
  596. }
  597. Error OS_JavaScript::shell_open(String p_uri) {
  598. /* clang-format off */
  599. EM_ASM_({
  600. window.open(UTF8ToString($0), '_blank');
  601. }, p_uri.utf8().get_data());
  602. /* clang-format on */
  603. return OK;
  604. }
  605. String OS_JavaScript::get_resource_dir() const {
  606. return "/"; //javascript has it's own filesystem for resources inside the APK
  607. }
  608. String OS_JavaScript::get_data_dir() const {
  609. /*
  610. if (get_data_dir_func)
  611. return get_data_dir_func();
  612. */
  613. return "/userfs";
  614. //return GlobalConfig::get_singleton()->get_singleton_object("GodotOS")->call("get_data_dir");
  615. };
  616. String OS_JavaScript::get_executable_path() const {
  617. return OS::get_executable_path();
  618. }
  619. void OS_JavaScript::_close_notification_funcs(const String &p_file, int p_flags) {
  620. print_line("close " + p_file + " flags " + itos(p_flags));
  621. if (p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  622. static_cast<OS_JavaScript *>(get_singleton())->last_sync_time = OS::get_singleton()->get_ticks_msec();
  623. static_cast<OS_JavaScript *>(get_singleton())->time_to_save_sync = 5000; //five seconds since last save
  624. }
  625. }
  626. void OS_JavaScript::process_joypads() {
  627. int joy_count = emscripten_get_num_gamepads();
  628. for (int i = 0; i < joy_count; i++) {
  629. EmscriptenGamepadEvent state;
  630. emscripten_get_gamepad_status(i, &state);
  631. if (state.connected) {
  632. int num_buttons = MIN(state.numButtons, 18);
  633. int num_axes = MIN(state.numAxes, 8);
  634. for (int j = 0; j < num_buttons; j++) {
  635. float value = state.analogButton[j];
  636. if (String(state.mapping) == "standard" && (j == 6 || j == 7)) {
  637. InputDefault::JoyAxis jx;
  638. jx.min = 0;
  639. jx.value = value;
  640. input->joy_axis(i, j, jx);
  641. } else {
  642. input->joy_button(i, j, value);
  643. }
  644. }
  645. for (int j = 0; j < num_axes; j++) {
  646. InputDefault::JoyAxis jx;
  647. jx.min = -1;
  648. jx.value = state.axis[j];
  649. input->joy_axis(i, j, jx);
  650. }
  651. }
  652. }
  653. }
  654. bool OS_JavaScript::joy_connection_changed(int p_type, const EmscriptenGamepadEvent *p_event) {
  655. if (p_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  656. String guid = "";
  657. if (String(p_event->mapping) == "standard")
  658. guid = "Default HTML5 Gamepad";
  659. input->joy_connection_changed(p_event->index, true, String(p_event->id), guid);
  660. } else {
  661. input->joy_connection_changed(p_event->index, false, "");
  662. }
  663. return true;
  664. }
  665. bool OS_JavaScript::is_joy_known(int p_device) {
  666. return input->is_joy_mapped(p_device);
  667. }
  668. String OS_JavaScript::get_joy_guid(int p_device) const {
  669. return input->get_joy_guid_remapped(p_device);
  670. }
  671. PowerState OS_JavaScript::get_power_state() {
  672. return power_manager->get_power_state();
  673. }
  674. int OS_JavaScript::get_power_seconds_left() {
  675. return power_manager->get_power_seconds_left();
  676. }
  677. int OS_JavaScript::get_power_percent_left() {
  678. return power_manager->get_power_percent_left();
  679. }
  680. OS_JavaScript::OS_JavaScript(const char *p_execpath, GetDataDirFunc p_get_data_dir_func) {
  681. set_cmdline(p_execpath, get_cmdline_args());
  682. main_loop = NULL;
  683. gl_extensions = NULL;
  684. window_maximized = false;
  685. get_data_dir_func = p_get_data_dir_func;
  686. FileAccessUnix::close_notification_func = _close_notification_funcs;
  687. time_to_save_sync = -1;
  688. }
  689. OS_JavaScript::~OS_JavaScript() {
  690. }