os_javascript.cpp 29 KB

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