os_javascript.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  1. /*************************************************************************/
  2. /* os_javascript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "os_javascript.h"
  31. #include "gles2/rasterizer_gles2.h"
  32. #include "gles3/rasterizer_gles3.h"
  33. #include "io/file_access_buffered_fa.h"
  34. #include "main/main.h"
  35. #include "servers/visual/visual_server_raster.h"
  36. #include "unix/dir_access_unix.h"
  37. #include "unix/file_access_unix.h"
  38. #include <emscripten.h>
  39. #include <stdlib.h>
  40. #include "dom_keys.inc"
  41. #define DOM_BUTTON_LEFT 0
  42. #define DOM_BUTTON_MIDDLE 1
  43. #define DOM_BUTTON_RIGHT 2
  44. #define DOM_BUTTON_XBUTTON1 3
  45. #define DOM_BUTTON_XBUTTON2 4
  46. // Window (canvas)
  47. static void focus_canvas() {
  48. /* clang-format off */
  49. EM_ASM(
  50. Module.canvas.focus();
  51. );
  52. /* clang-format on */
  53. }
  54. static bool is_canvas_focused() {
  55. /* clang-format off */
  56. return EM_ASM_INT_V(
  57. return document.activeElement == Module.canvas;
  58. );
  59. /* clang-format on */
  60. }
  61. static bool cursor_inside_canvas = true;
  62. EM_BOOL OS_JavaScript::fullscreen_change_callback(int p_event_type, const EmscriptenFullscreenChangeEvent *p_event, void *p_user_data) {
  63. OS_JavaScript *os = get_singleton();
  64. // Empty ID is canvas.
  65. String target_id = String::utf8(p_event->id);
  66. if (target_id.empty() || target_id == "canvas") {
  67. // This event property is the only reliable data on
  68. // browser fullscreen state.
  69. os->video_mode.fullscreen = p_event->isFullscreen;
  70. if (os->video_mode.fullscreen) {
  71. os->entering_fullscreen = false;
  72. } else {
  73. // Restoring maximized window now will cause issues,
  74. // so delay until main_loop_iterate.
  75. os->just_exited_fullscreen = true;
  76. }
  77. }
  78. return false;
  79. }
  80. void OS_JavaScript::set_video_mode(const VideoMode &p_video_mode, int p_screen) {
  81. video_mode = p_video_mode;
  82. }
  83. OS::VideoMode OS_JavaScript::get_video_mode(int p_screen) const {
  84. return video_mode;
  85. }
  86. Size2 OS_JavaScript::get_screen_size(int p_screen) const {
  87. EmscriptenFullscreenChangeEvent ev;
  88. EMSCRIPTEN_RESULT result = emscripten_get_fullscreen_status(&ev);
  89. ERR_FAIL_COND_V(result != EMSCRIPTEN_RESULT_SUCCESS, Size2());
  90. return Size2(ev.screenWidth, ev.screenHeight);
  91. }
  92. void OS_JavaScript::set_window_size(const Size2 p_size) {
  93. windowed_size = p_size;
  94. if (video_mode.fullscreen) {
  95. window_maximized = false;
  96. set_window_fullscreen(false);
  97. } else {
  98. if (window_maximized) {
  99. emscripten_exit_soft_fullscreen();
  100. window_maximized = false;
  101. }
  102. emscripten_set_canvas_size(p_size.x, p_size.y);
  103. }
  104. }
  105. Size2 OS_JavaScript::get_window_size() const {
  106. int canvas[3];
  107. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  108. return Size2(canvas[0], canvas[1]);
  109. }
  110. void OS_JavaScript::set_window_maximized(bool p_enabled) {
  111. if (video_mode.fullscreen) {
  112. window_maximized = p_enabled;
  113. set_window_fullscreen(false);
  114. } else if (!p_enabled) {
  115. emscripten_exit_soft_fullscreen();
  116. window_maximized = false;
  117. } else if (!window_maximized) {
  118. // Prevent calling emscripten_enter_soft_fullscreen mutltiple times,
  119. // this would hide page elements permanently.
  120. EmscriptenFullscreenStrategy strategy;
  121. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  122. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  123. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  124. strategy.canvasResizedCallback = NULL;
  125. emscripten_enter_soft_fullscreen(NULL, &strategy);
  126. window_maximized = p_enabled;
  127. }
  128. }
  129. bool OS_JavaScript::is_window_maximized() const {
  130. return window_maximized;
  131. }
  132. void OS_JavaScript::set_window_fullscreen(bool p_enabled) {
  133. if (p_enabled == video_mode.fullscreen) {
  134. return;
  135. }
  136. // Just request changes here, if successful, logic continues in
  137. // fullscreen_change_callback.
  138. if (p_enabled) {
  139. if (window_maximized) {
  140. // Soft fullsreen during real fullscreen can cause issues, so exit.
  141. // This must be called before requesting full screen.
  142. emscripten_exit_soft_fullscreen();
  143. }
  144. EmscriptenFullscreenStrategy strategy;
  145. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  146. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  147. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  148. strategy.canvasResizedCallback = NULL;
  149. EMSCRIPTEN_RESULT result = emscripten_request_fullscreen_strategy(NULL, false, &strategy);
  150. ERR_EXPLAIN("Enabling fullscreen is only possible from an input callback for the HTML5 platform");
  151. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  152. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  153. // Not fullscreen yet, so prevent "windowed" canvas dimensions from
  154. // being overwritten.
  155. entering_fullscreen = true;
  156. } else {
  157. // No logic allowed here, since exiting w/ ESC key won't use this function.
  158. ERR_FAIL_COND(emscripten_exit_fullscreen() != EMSCRIPTEN_RESULT_SUCCESS);
  159. }
  160. }
  161. bool OS_JavaScript::is_window_fullscreen() const {
  162. return video_mode.fullscreen;
  163. }
  164. void OS_JavaScript::get_fullscreen_mode_list(List<VideoMode> *p_list, int p_screen) const {
  165. Size2 screen = get_screen_size();
  166. p_list->push_back(OS::VideoMode(screen.width, screen.height, true));
  167. }
  168. // Keys
  169. template <typename T>
  170. static void dom2godot_mod(T *emscripten_event_ptr, Ref<InputEventWithModifiers> godot_event) {
  171. godot_event->set_shift(emscripten_event_ptr->shiftKey);
  172. godot_event->set_alt(emscripten_event_ptr->altKey);
  173. godot_event->set_control(emscripten_event_ptr->ctrlKey);
  174. godot_event->set_metakey(emscripten_event_ptr->metaKey);
  175. }
  176. static Ref<InputEventKey> setup_key_event(const EmscriptenKeyboardEvent *emscripten_event) {
  177. Ref<InputEventKey> ev;
  178. ev.instance();
  179. ev->set_echo(emscripten_event->repeat);
  180. dom2godot_mod(emscripten_event, ev);
  181. ev->set_scancode(dom2godot_scancode(emscripten_event->keyCode));
  182. String unicode = String::utf8(emscripten_event->key);
  183. // Check if empty or multi-character (e.g. `CapsLock`).
  184. if (unicode.length() != 1) {
  185. // Might be empty as well, but better than nonsense.
  186. unicode = String::utf8(emscripten_event->charValue);
  187. }
  188. if (unicode.length() == 1) {
  189. ev->set_unicode(unicode[0]);
  190. }
  191. return ev;
  192. }
  193. EM_BOOL OS_JavaScript::keydown_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  194. OS_JavaScript *os = get_singleton();
  195. Ref<InputEventKey> ev = setup_key_event(p_event);
  196. ev->set_pressed(true);
  197. if (ev->get_unicode() == 0 && keycode_has_unicode(ev->get_scancode())) {
  198. // Defer to keypress event for legacy unicode retrieval.
  199. os->deferred_key_event = ev;
  200. // Do not suppress keypress event.
  201. return false;
  202. }
  203. os->input->parse_input_event(ev);
  204. return true;
  205. }
  206. EM_BOOL OS_JavaScript::keypress_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  207. OS_JavaScript *os = get_singleton();
  208. os->deferred_key_event->set_unicode(p_event->charCode);
  209. os->input->parse_input_event(os->deferred_key_event);
  210. return true;
  211. }
  212. EM_BOOL OS_JavaScript::keyup_callback(int p_event_type, const EmscriptenKeyboardEvent *p_event, void *p_user_data) {
  213. Ref<InputEventKey> ev = setup_key_event(p_event);
  214. ev->set_pressed(false);
  215. get_singleton()->input->parse_input_event(ev);
  216. return ev->get_scancode() != KEY_UNKNOWN && ev->get_scancode() != 0;
  217. }
  218. // Mouse
  219. Point2 OS_JavaScript::get_mouse_position() const {
  220. return input->get_mouse_position();
  221. }
  222. int OS_JavaScript::get_mouse_button_state() const {
  223. return input->get_mouse_button_mask();
  224. }
  225. EM_BOOL OS_JavaScript::mouse_button_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  226. OS_JavaScript *os = get_singleton();
  227. Ref<InputEventMouseButton> ev;
  228. ev.instance();
  229. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_MOUSEDOWN);
  230. ev->set_position(Point2(p_event->canvasX, p_event->canvasY));
  231. ev->set_global_position(ev->get_position());
  232. dom2godot_mod(p_event, ev);
  233. switch (p_event->button) {
  234. case DOM_BUTTON_LEFT: ev->set_button_index(BUTTON_LEFT); break;
  235. case DOM_BUTTON_MIDDLE: ev->set_button_index(BUTTON_MIDDLE); break;
  236. case DOM_BUTTON_RIGHT: ev->set_button_index(BUTTON_RIGHT); break;
  237. case DOM_BUTTON_XBUTTON1: ev->set_button_index(BUTTON_XBUTTON1); break;
  238. case DOM_BUTTON_XBUTTON2: ev->set_button_index(BUTTON_XBUTTON2); break;
  239. default: return false;
  240. }
  241. int mask = os->input->get_mouse_button_mask();
  242. int button_flag = 1 << (ev->get_button_index() - 1);
  243. if (ev->is_pressed()) {
  244. // Since the event is consumed, focus manually. The containing iframe,
  245. // if exists, may not have focus yet, so focus even if already focused.
  246. focus_canvas();
  247. mask |= button_flag;
  248. } else if (mask & button_flag) {
  249. mask &= ~button_flag;
  250. } else {
  251. // Received release event, but press was outside the canvas, so ignore.
  252. return false;
  253. }
  254. ev->set_button_mask(mask);
  255. os->input->parse_input_event(ev);
  256. // Prevent multi-click text selection and wheel-click scrolling anchor.
  257. // Context menu is prevented through contextmenu event.
  258. return true;
  259. }
  260. EM_BOOL OS_JavaScript::mousemove_callback(int p_event_type, const EmscriptenMouseEvent *p_event, void *p_user_data) {
  261. OS_JavaScript *os = get_singleton();
  262. int input_mask = os->input->get_mouse_button_mask();
  263. Point2 pos = Point2(p_event->canvasX, p_event->canvasY);
  264. // For motion outside the canvas, only read mouse movement if dragging
  265. // started inside the canvas; imitating desktop app behaviour.
  266. if (!cursor_inside_canvas && !input_mask)
  267. return false;
  268. Ref<InputEventMouseMotion> ev;
  269. ev.instance();
  270. dom2godot_mod(p_event, ev);
  271. ev->set_button_mask(input_mask);
  272. ev->set_position(pos);
  273. ev->set_global_position(ev->get_position());
  274. ev->set_relative(Vector2(p_event->movementX, p_event->movementY));
  275. os->input->set_mouse_position(ev->get_position());
  276. ev->set_speed(os->input->get_last_mouse_speed());
  277. os->input->parse_input_event(ev);
  278. // Don't suppress mouseover/-leave events.
  279. return false;
  280. }
  281. static const char *godot2dom_cursor(OS::CursorShape p_shape) {
  282. switch (p_shape) {
  283. case OS::CURSOR_ARROW:
  284. default:
  285. return "auto";
  286. case OS::CURSOR_IBEAM: return "text";
  287. case OS::CURSOR_POINTING_HAND: return "pointer";
  288. case OS::CURSOR_CROSS: return "crosshair";
  289. case OS::CURSOR_WAIT: return "progress";
  290. case OS::CURSOR_BUSY: return "wait";
  291. case OS::CURSOR_DRAG: return "grab";
  292. case OS::CURSOR_CAN_DROP: return "grabbing";
  293. case OS::CURSOR_FORBIDDEN: return "no-drop";
  294. case OS::CURSOR_VSIZE: return "ns-resize";
  295. case OS::CURSOR_HSIZE: return "ew-resize";
  296. case OS::CURSOR_BDIAGSIZE: return "nesw-resize";
  297. case OS::CURSOR_FDIAGSIZE: return "nwse-resize";
  298. case OS::CURSOR_MOVE: return "move";
  299. case OS::CURSOR_VSPLIT: return "row-resize";
  300. case OS::CURSOR_HSPLIT: return "col-resize";
  301. case OS::CURSOR_HELP: return "help";
  302. }
  303. }
  304. static void set_css_cursor(const char *p_cursor) {
  305. /* clang-format off */
  306. EM_ASM_({
  307. Module.canvas.style.cursor = UTF8ToString($0);
  308. }, p_cursor);
  309. /* clang-format on */
  310. }
  311. static const char *get_css_cursor() {
  312. char cursor[16];
  313. /* clang-format off */
  314. EM_ASM_INT({
  315. stringToUTF8(Module.canvas.style.cursor ? Module.canvas.style.cursor : 'auto', $0, 16);
  316. }, cursor);
  317. /* clang-format on */
  318. return cursor;
  319. }
  320. void OS_JavaScript::set_cursor_shape(CursorShape p_shape) {
  321. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  322. cursor_shape = p_shape;
  323. if (get_mouse_mode() != MOUSE_MODE_HIDDEN)
  324. set_css_cursor(godot2dom_cursor(cursor_shape));
  325. }
  326. void OS_JavaScript::set_custom_mouse_cursor(const RES &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  327. }
  328. void OS_JavaScript::set_mouse_mode(OS::MouseMode p_mode) {
  329. ERR_EXPLAIN("MOUSE_MODE_CONFINED is not supported for the HTML5 platform");
  330. ERR_FAIL_COND(p_mode == MOUSE_MODE_CONFINED);
  331. if (p_mode == get_mouse_mode())
  332. return;
  333. if (p_mode == MOUSE_MODE_VISIBLE) {
  334. set_css_cursor(godot2dom_cursor(cursor_shape));
  335. emscripten_exit_pointerlock();
  336. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  337. set_css_cursor("none");
  338. emscripten_exit_pointerlock();
  339. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  340. EMSCRIPTEN_RESULT result = emscripten_request_pointerlock("canvas", false);
  341. ERR_EXPLAIN("MOUSE_MODE_CAPTURED can only be entered from within an appropriate input callback");
  342. ERR_FAIL_COND(result == EMSCRIPTEN_RESULT_FAILED_NOT_DEFERRED);
  343. ERR_FAIL_COND(result != EMSCRIPTEN_RESULT_SUCCESS);
  344. set_css_cursor(godot2dom_cursor(cursor_shape));
  345. }
  346. }
  347. OS::MouseMode OS_JavaScript::get_mouse_mode() const {
  348. if (String::utf8(get_css_cursor()) == "none")
  349. return MOUSE_MODE_HIDDEN;
  350. EmscriptenPointerlockChangeEvent ev;
  351. emscripten_get_pointerlock_status(&ev);
  352. return (ev.isActive && String::utf8(ev.id) == "canvas") ? MOUSE_MODE_CAPTURED : MOUSE_MODE_VISIBLE;
  353. }
  354. // Wheel
  355. EM_BOOL OS_JavaScript::wheel_callback(int p_event_type, const EmscriptenWheelEvent *p_event, void *p_user_data) {
  356. ERR_FAIL_COND_V(p_event_type != EMSCRIPTEN_EVENT_WHEEL, false);
  357. if (!is_canvas_focused()) {
  358. if (cursor_inside_canvas) {
  359. focus_canvas();
  360. } else {
  361. return false;
  362. }
  363. }
  364. InputDefault *input = get_singleton()->input;
  365. Ref<InputEventMouseButton> ev;
  366. ev.instance();
  367. ev->set_button_mask(input->get_mouse_button_mask());
  368. ev->set_position(input->get_mouse_position());
  369. ev->set_global_position(ev->get_position());
  370. ev->set_shift(input->is_key_pressed(KEY_SHIFT));
  371. ev->set_alt(input->is_key_pressed(KEY_ALT));
  372. ev->set_control(input->is_key_pressed(KEY_CONTROL));
  373. ev->set_metakey(input->is_key_pressed(KEY_META));
  374. if (p_event->deltaY < 0)
  375. ev->set_button_index(BUTTON_WHEEL_UP);
  376. else if (p_event->deltaY > 0)
  377. ev->set_button_index(BUTTON_WHEEL_DOWN);
  378. else if (p_event->deltaX > 0)
  379. ev->set_button_index(BUTTON_WHEEL_LEFT);
  380. else if (p_event->deltaX < 0)
  381. ev->set_button_index(BUTTON_WHEEL_RIGHT);
  382. else
  383. return false;
  384. // Different browsers give wildly different delta values, and we can't
  385. // interpret deltaMode, so use default value for wheel events' factor.
  386. ev->set_pressed(true);
  387. input->parse_input_event(ev);
  388. ev->set_pressed(false);
  389. input->parse_input_event(ev);
  390. return true;
  391. }
  392. // Touch
  393. bool OS_JavaScript::has_touchscreen_ui_hint() const {
  394. /* clang-format off */
  395. return EM_ASM_INT_V(
  396. return 'ontouchstart' in window;
  397. );
  398. /* clang-format on */
  399. }
  400. EM_BOOL OS_JavaScript::touch_press_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  401. OS_JavaScript *os = get_singleton();
  402. Ref<InputEventScreenTouch> ev;
  403. ev.instance();
  404. int lowest_id_index = -1;
  405. for (int i = 0; i < p_event->numTouches; ++i) {
  406. const EmscriptenTouchPoint &touch = p_event->touches[i];
  407. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  408. lowest_id_index = i;
  409. if (!touch.isChanged)
  410. continue;
  411. ev->set_index(touch.identifier);
  412. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  413. os->touches[i] = ev->get_position();
  414. ev->set_pressed(p_event_type == EMSCRIPTEN_EVENT_TOUCHSTART);
  415. os->input->parse_input_event(ev);
  416. }
  417. return true;
  418. }
  419. EM_BOOL OS_JavaScript::touchmove_callback(int p_event_type, const EmscriptenTouchEvent *p_event, void *p_user_data) {
  420. OS_JavaScript *os = get_singleton();
  421. Ref<InputEventScreenDrag> ev;
  422. ev.instance();
  423. int lowest_id_index = -1;
  424. for (int i = 0; i < p_event->numTouches; ++i) {
  425. const EmscriptenTouchPoint &touch = p_event->touches[i];
  426. if (lowest_id_index == -1 || touch.identifier < p_event->touches[lowest_id_index].identifier)
  427. lowest_id_index = i;
  428. if (!touch.isChanged)
  429. continue;
  430. ev->set_index(touch.identifier);
  431. ev->set_position(Point2(touch.canvasX, touch.canvasY));
  432. Point2 &prev = os->touches[i];
  433. ev->set_relative(ev->get_position() - prev);
  434. prev = ev->get_position();
  435. os->input->parse_input_event(ev);
  436. }
  437. return true;
  438. }
  439. // Gamepad
  440. EM_BOOL OS_JavaScript::gamepad_change_callback(int p_event_type, const EmscriptenGamepadEvent *p_event, void *p_user_data) {
  441. InputDefault *input = get_singleton()->input;
  442. if (p_event_type == EMSCRIPTEN_EVENT_GAMEPADCONNECTED) {
  443. String guid = "";
  444. if (String::utf8(p_event->mapping) == "standard")
  445. guid = "Default HTML5 Gamepad";
  446. input->joy_connection_changed(p_event->index, true, String::utf8(p_event->id), guid);
  447. } else {
  448. input->joy_connection_changed(p_event->index, false, "");
  449. }
  450. return true;
  451. }
  452. void OS_JavaScript::process_joypads() {
  453. int joypad_count = emscripten_get_num_gamepads();
  454. for (int joypad = 0; joypad < joypad_count; joypad++) {
  455. EmscriptenGamepadEvent state;
  456. emscripten_get_gamepad_status(joypad, &state);
  457. if (state.connected) {
  458. int button_count = MIN(state.numButtons, 18);
  459. int axis_count = MIN(state.numAxes, 8);
  460. for (int button = 0; button < button_count; button++) {
  461. float value = state.analogButton[button];
  462. if (String::utf8(state.mapping) == "standard" && (button == JOY_ANALOG_L2 || button == JOY_ANALOG_R2)) {
  463. InputDefault::JoyAxis joy_axis;
  464. joy_axis.min = 0;
  465. joy_axis.value = value;
  466. input->joy_axis(joypad, button, joy_axis);
  467. } else {
  468. input->joy_button(joypad, button, value);
  469. }
  470. }
  471. for (int axis = 0; axis < axis_count; axis++) {
  472. InputDefault::JoyAxis joy_axis;
  473. joy_axis.min = -1;
  474. joy_axis.value = state.axis[axis];
  475. input->joy_axis(joypad, axis, joy_axis);
  476. }
  477. }
  478. }
  479. }
  480. bool OS_JavaScript::is_joy_known(int p_device) {
  481. return input->is_joy_mapped(p_device);
  482. }
  483. String OS_JavaScript::get_joy_guid(int p_device) const {
  484. return input->get_joy_guid_remapped(p_device);
  485. }
  486. // Video
  487. int OS_JavaScript::get_video_driver_count() const {
  488. return VIDEO_DRIVER_MAX;
  489. }
  490. const char *OS_JavaScript::get_video_driver_name(int p_driver) const {
  491. switch (p_driver) {
  492. case VIDEO_DRIVER_GLES3:
  493. return "GLES3";
  494. case VIDEO_DRIVER_GLES2:
  495. return "GLES2";
  496. }
  497. ERR_EXPLAIN("Invalid video driver index " + itos(p_driver));
  498. ERR_FAIL_V(NULL);
  499. }
  500. // Audio
  501. int OS_JavaScript::get_audio_driver_count() const {
  502. return 1;
  503. }
  504. const char *OS_JavaScript::get_audio_driver_name(int p_driver) const {
  505. return "JavaScript";
  506. }
  507. // Lifecycle
  508. int OS_JavaScript::get_current_video_driver() const {
  509. return video_driver_index;
  510. }
  511. void OS_JavaScript::initialize_core() {
  512. OS_Unix::initialize_core();
  513. FileAccess::make_default<FileAccessBufferedFA<FileAccessUnix> >(FileAccess::ACCESS_RESOURCES);
  514. }
  515. Error OS_JavaScript::initialize(const VideoMode &p_desired, int p_video_driver, int p_audio_driver) {
  516. EmscriptenWebGLContextAttributes attributes;
  517. emscripten_webgl_init_context_attributes(&attributes);
  518. attributes.alpha = false;
  519. attributes.antialias = false;
  520. ERR_FAIL_INDEX_V(p_video_driver, VIDEO_DRIVER_MAX, ERR_INVALID_PARAMETER);
  521. switch (p_video_driver) {
  522. case VIDEO_DRIVER_GLES3:
  523. attributes.majorVersion = 2;
  524. RasterizerGLES3::register_config();
  525. RasterizerGLES3::make_current();
  526. break;
  527. case VIDEO_DRIVER_GLES2:
  528. attributes.majorVersion = 1;
  529. RasterizerGLES2::register_config();
  530. RasterizerGLES2::make_current();
  531. break;
  532. }
  533. video_driver_index = p_video_driver;
  534. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_create_context(NULL, &attributes);
  535. ERR_EXPLAIN("WebGL " + itos(attributes.majorVersion) + ".0 not available");
  536. ERR_FAIL_COND_V(emscripten_webgl_make_context_current(ctx) != EMSCRIPTEN_RESULT_SUCCESS, ERR_UNAVAILABLE);
  537. video_mode = p_desired;
  538. // Can't fulfil fullscreen request during start-up due to browser security.
  539. video_mode.fullscreen = false;
  540. /* clang-format off */
  541. if (EM_ASM_INT_V({ return Module.resizeCanvasOnStart })) {
  542. /* clang-format on */
  543. set_window_size(Size2(video_mode.width, video_mode.height));
  544. } else {
  545. set_window_size(get_window_size());
  546. }
  547. char locale_ptr[16];
  548. /* clang-format off */
  549. EM_ASM_ARGS({
  550. stringToUTF8(Module.locale, $0, 16);
  551. }, locale_ptr);
  552. /* clang-format on */
  553. setenv("LANG", locale_ptr, true);
  554. AudioDriverManager::initialize(p_audio_driver);
  555. VisualServer *visual_server = memnew(VisualServerRaster());
  556. input = memnew(InputDefault);
  557. EMSCRIPTEN_RESULT result;
  558. #define EM_CHECK(ev) \
  559. if (result != EMSCRIPTEN_RESULT_SUCCESS) \
  560. ERR_PRINTS("Error while setting " #ev " callback: Code " + itos(result))
  561. #define SET_EM_CALLBACK(target, ev, cb) \
  562. result = emscripten_set_##ev##_callback(target, NULL, true, &cb); \
  563. EM_CHECK(ev)
  564. #define SET_EM_CALLBACK_NOTARGET(ev, cb) \
  565. result = emscripten_set_##ev##_callback(NULL, true, &cb); \
  566. EM_CHECK(ev)
  567. // These callbacks from Emscripten's html5.h suffice to access most
  568. // JavaScript APIs. For APIs that are not (sufficiently) exposed, EM_ASM
  569. // is used below.
  570. SET_EM_CALLBACK("#window", mousemove, mousemove_callback)
  571. SET_EM_CALLBACK("#canvas", mousedown, mouse_button_callback)
  572. SET_EM_CALLBACK("#window", mouseup, mouse_button_callback)
  573. SET_EM_CALLBACK("#window", wheel, wheel_callback)
  574. SET_EM_CALLBACK("#window", touchstart, touch_press_callback)
  575. SET_EM_CALLBACK("#window", touchmove, touchmove_callback)
  576. SET_EM_CALLBACK("#window", touchend, touch_press_callback)
  577. SET_EM_CALLBACK("#window", touchcancel, touch_press_callback)
  578. SET_EM_CALLBACK("#canvas", keydown, keydown_callback)
  579. SET_EM_CALLBACK("#canvas", keypress, keypress_callback)
  580. SET_EM_CALLBACK("#canvas", keyup, keyup_callback)
  581. SET_EM_CALLBACK(NULL, fullscreenchange, fullscreen_change_callback)
  582. SET_EM_CALLBACK_NOTARGET(gamepadconnected, gamepad_change_callback)
  583. SET_EM_CALLBACK_NOTARGET(gamepaddisconnected, gamepad_change_callback)
  584. #undef SET_EM_CALLBACK_NODATA
  585. #undef SET_EM_CALLBACK
  586. #undef EM_CHECK
  587. /* clang-format off */
  588. EM_ASM_ARGS({
  589. const send_notification = cwrap('send_notification', null, ['number']);
  590. const notifications = arguments;
  591. (['mouseover', 'mouseleave', 'focus', 'blur']).forEach(function(event, index) {
  592. Module.canvas.addEventListener(event, send_notification.bind(null, notifications[index]));
  593. });
  594. },
  595. MainLoop::NOTIFICATION_WM_MOUSE_ENTER,
  596. MainLoop::NOTIFICATION_WM_MOUSE_EXIT,
  597. MainLoop::NOTIFICATION_WM_FOCUS_IN,
  598. MainLoop::NOTIFICATION_WM_FOCUS_OUT
  599. );
  600. /* clang-format on */
  601. visual_server->init();
  602. return OK;
  603. }
  604. void OS_JavaScript::set_main_loop(MainLoop *p_main_loop) {
  605. main_loop = p_main_loop;
  606. input->set_main_loop(p_main_loop);
  607. }
  608. MainLoop *OS_JavaScript::get_main_loop() const {
  609. return main_loop;
  610. }
  611. void OS_JavaScript::run_async() {
  612. main_loop->init();
  613. emscripten_set_main_loop(main_loop_callback, -1, false);
  614. }
  615. void OS_JavaScript::main_loop_callback() {
  616. get_singleton()->main_loop_iterate();
  617. }
  618. bool OS_JavaScript::main_loop_iterate() {
  619. if (is_userfs_persistent() && sync_wait_time >= 0) {
  620. int64_t current_time = get_ticks_msec();
  621. int64_t elapsed_time = current_time - last_sync_check_time;
  622. last_sync_check_time = current_time;
  623. sync_wait_time -= elapsed_time;
  624. if (sync_wait_time < 0) {
  625. /* clang-format off */
  626. EM_ASM(
  627. FS.syncfs(function(err) {
  628. if (err) { console.warn('Failed to save IDB file system: ' + err.message); }
  629. });
  630. );
  631. /* clang-format on */
  632. }
  633. }
  634. process_joypads();
  635. if (just_exited_fullscreen) {
  636. if (window_maximized) {
  637. EmscriptenFullscreenStrategy strategy;
  638. strategy.scaleMode = EMSCRIPTEN_FULLSCREEN_SCALE_STRETCH;
  639. strategy.canvasResolutionScaleMode = EMSCRIPTEN_FULLSCREEN_CANVAS_SCALE_STDDEF;
  640. strategy.filteringMode = EMSCRIPTEN_FULLSCREEN_FILTERING_DEFAULT;
  641. strategy.canvasResizedCallback = NULL;
  642. emscripten_enter_soft_fullscreen(NULL, &strategy);
  643. } else {
  644. emscripten_set_canvas_size(windowed_size.width, windowed_size.height);
  645. }
  646. just_exited_fullscreen = false;
  647. }
  648. int canvas[3];
  649. emscripten_get_canvas_size(canvas, canvas + 1, canvas + 2);
  650. video_mode.width = canvas[0];
  651. video_mode.height = canvas[1];
  652. if (!window_maximized && !video_mode.fullscreen && !just_exited_fullscreen && !entering_fullscreen) {
  653. windowed_size.width = canvas[0];
  654. windowed_size.height = canvas[1];
  655. }
  656. return Main::iteration();
  657. }
  658. void OS_JavaScript::delete_main_loop() {
  659. memdelete(main_loop);
  660. }
  661. void OS_JavaScript::finalize() {
  662. memdelete(input);
  663. }
  664. // Miscellaneous
  665. extern "C" EMSCRIPTEN_KEEPALIVE void send_notification(int p_notification) {
  666. if (p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER || p_notification == MainLoop::NOTIFICATION_WM_MOUSE_EXIT) {
  667. cursor_inside_canvas = p_notification == MainLoop::NOTIFICATION_WM_MOUSE_ENTER;
  668. }
  669. OS_JavaScript::get_singleton()->get_main_loop()->notification(p_notification);
  670. }
  671. bool OS_JavaScript::_check_internal_feature_support(const String &p_feature) {
  672. if (p_feature == "HTML5" || p_feature == "web")
  673. return true;
  674. #ifdef JAVASCRIPT_EVAL_ENABLED
  675. if (p_feature == "JavaScript")
  676. return true;
  677. #endif
  678. EMSCRIPTEN_WEBGL_CONTEXT_HANDLE ctx = emscripten_webgl_get_current_context();
  679. // All extensions are already automatically enabled, this function allows
  680. // checking WebGL extension support without inline JavaScript
  681. if (p_feature == "s3tc")
  682. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_s3tc_srgb");
  683. if (p_feature == "etc")
  684. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc1");
  685. if (p_feature == "etc2")
  686. return emscripten_webgl_enable_extension(ctx, "WEBGL_compressed_texture_etc");
  687. return false;
  688. }
  689. void OS_JavaScript::alert(const String &p_alert, const String &p_title) {
  690. /* clang-format off */
  691. EM_ASM_({
  692. window.alert(UTF8ToString($0));
  693. }, p_alert.utf8().get_data());
  694. /* clang-format on */
  695. }
  696. void OS_JavaScript::set_window_title(const String &p_title) {
  697. /* clang-format off */
  698. EM_ASM_({
  699. document.title = UTF8ToString($0);
  700. }, p_title.utf8().get_data());
  701. /* clang-format on */
  702. }
  703. String OS_JavaScript::get_executable_path() const {
  704. return OS::get_executable_path();
  705. }
  706. Error OS_JavaScript::shell_open(String p_uri) {
  707. // Open URI in a new tab, browser will deal with it by protocol.
  708. /* clang-format off */
  709. EM_ASM_({
  710. window.open(UTF8ToString($0), '_blank');
  711. }, p_uri.utf8().get_data());
  712. /* clang-format on */
  713. return OK;
  714. }
  715. String OS_JavaScript::get_name() {
  716. return "HTML5";
  717. }
  718. bool OS_JavaScript::can_draw() const {
  719. return true; // Always?
  720. }
  721. String OS_JavaScript::get_user_data_dir() const {
  722. return "/userfs";
  723. };
  724. String OS_JavaScript::get_resource_dir() const {
  725. return "/";
  726. }
  727. OS::PowerState OS_JavaScript::get_power_state() {
  728. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to POWERSTATE_UNKNOWN");
  729. return OS::POWERSTATE_UNKNOWN;
  730. }
  731. int OS_JavaScript::get_power_seconds_left() {
  732. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  733. return -1;
  734. }
  735. int OS_JavaScript::get_power_percent_left() {
  736. WARN_PRINT("Power management is not supported for the HTML5 platform, defaulting to -1");
  737. return -1;
  738. }
  739. void OS_JavaScript::file_access_close_callback(const String &p_file, int p_flags) {
  740. OS_JavaScript *os = get_singleton();
  741. if (os->is_userfs_persistent() && p_file.begins_with("/userfs") && p_flags & FileAccess::WRITE) {
  742. os->last_sync_check_time = OS::get_singleton()->get_ticks_msec();
  743. // Wait five seconds in case more files are about to be closed.
  744. os->sync_wait_time = 5000;
  745. }
  746. }
  747. void OS_JavaScript::set_idb_available(bool p_idb_available) {
  748. idb_available = p_idb_available;
  749. }
  750. bool OS_JavaScript::is_userfs_persistent() const {
  751. return idb_available;
  752. }
  753. OS_JavaScript *OS_JavaScript::get_singleton() {
  754. return static_cast<OS_JavaScript *>(OS::get_singleton());
  755. }
  756. OS_JavaScript::OS_JavaScript(int p_argc, char *p_argv[]) {
  757. List<String> arguments;
  758. for (int i = 1; i < p_argc; i++) {
  759. arguments.push_back(String::utf8(p_argv[i]));
  760. }
  761. set_cmdline(p_argv[0], arguments);
  762. window_maximized = false;
  763. entering_fullscreen = false;
  764. just_exited_fullscreen = false;
  765. main_loop = NULL;
  766. idb_available = false;
  767. sync_wait_time = -1;
  768. AudioDriverManager::add_driver(&audio_driver_javascript);
  769. Vector<Logger *> loggers;
  770. loggers.push_back(memnew(StdLogger));
  771. _set_logger(memnew(CompositeLogger(loggers)));
  772. FileAccessUnix::close_notification_func = file_access_close_callback;
  773. }