display_server_web.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066
  1. /*************************************************************************/
  2. /* display_server_web.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 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 "display_server_web.h"
  31. #ifdef GLES3_ENABLED
  32. #include "drivers/gles3/rasterizer_gles3.h"
  33. #endif
  34. #include "platform/web/os_web.h"
  35. #include "servers/rendering/dummy/rasterizer_dummy.h"
  36. #include <emscripten.h>
  37. #include <png.h>
  38. #include "dom_keys.inc"
  39. #include "godot_js.h"
  40. #define DOM_BUTTON_LEFT 0
  41. #define DOM_BUTTON_MIDDLE 1
  42. #define DOM_BUTTON_RIGHT 2
  43. #define DOM_BUTTON_XBUTTON1 3
  44. #define DOM_BUTTON_XBUTTON2 4
  45. DisplayServerWeb *DisplayServerWeb::get_singleton() {
  46. return static_cast<DisplayServerWeb *>(DisplayServer::get_singleton());
  47. }
  48. // Window (canvas)
  49. bool DisplayServerWeb::check_size_force_redraw() {
  50. bool size_changed = godot_js_display_size_update() != 0;
  51. if (size_changed && !rect_changed_callback.is_null()) {
  52. Variant size = Rect2i(Point2i(), window_get_size()); // TODO use window_get_position if implemented.
  53. Variant *vp = &size;
  54. Variant ret;
  55. Callable::CallError ce;
  56. rect_changed_callback.callp((const Variant **)&vp, 1, ret, ce);
  57. }
  58. return size_changed;
  59. }
  60. void DisplayServerWeb::fullscreen_change_callback(int p_fullscreen) {
  61. DisplayServerWeb *display = get_singleton();
  62. if (p_fullscreen) {
  63. display->window_mode = WINDOW_MODE_FULLSCREEN;
  64. } else {
  65. display->window_mode = WINDOW_MODE_WINDOWED;
  66. }
  67. }
  68. // Drag and drop callback.
  69. void DisplayServerWeb::drop_files_js_callback(char **p_filev, int p_filec) {
  70. DisplayServerWeb *ds = get_singleton();
  71. if (!ds) {
  72. ERR_FAIL_MSG("Unable to drop files because the DisplayServer is not active");
  73. }
  74. if (ds->drop_files_callback.is_null()) {
  75. return;
  76. }
  77. Vector<String> files;
  78. for (int i = 0; i < p_filec; i++) {
  79. files.push_back(String::utf8(p_filev[i]));
  80. }
  81. Variant v = files;
  82. Variant *vp = &v;
  83. Variant ret;
  84. Callable::CallError ce;
  85. ds->drop_files_callback.callp((const Variant **)&vp, 1, ret, ce);
  86. }
  87. // Web quit request callback.
  88. void DisplayServerWeb::request_quit_callback() {
  89. DisplayServerWeb *ds = get_singleton();
  90. if (ds && !ds->window_event_callback.is_null()) {
  91. Variant event = int(DisplayServer::WINDOW_EVENT_CLOSE_REQUEST);
  92. Variant *eventp = &event;
  93. Variant ret;
  94. Callable::CallError ce;
  95. ds->window_event_callback.callp((const Variant **)&eventp, 1, ret, ce);
  96. }
  97. }
  98. // Keys
  99. void DisplayServerWeb::dom2godot_mod(Ref<InputEventWithModifiers> ev, int p_mod) {
  100. ev->set_shift_pressed(p_mod & 1);
  101. ev->set_alt_pressed(p_mod & 2);
  102. ev->set_ctrl_pressed(p_mod & 4);
  103. ev->set_meta_pressed(p_mod & 8);
  104. }
  105. void DisplayServerWeb::key_callback(int p_pressed, int p_repeat, int p_modifiers) {
  106. DisplayServerWeb *ds = get_singleton();
  107. JSKeyEvent &key_event = ds->key_event;
  108. // Resume audio context after input in case autoplay was denied.
  109. OS_Web::get_singleton()->resume_audio();
  110. Ref<InputEventKey> ev;
  111. ev.instantiate();
  112. ev->set_echo(p_repeat);
  113. ev->set_keycode(dom_code2godot_scancode(key_event.code, key_event.key, false));
  114. ev->set_physical_keycode(dom_code2godot_scancode(key_event.code, key_event.key, true));
  115. ev->set_pressed(p_pressed);
  116. dom2godot_mod(ev, p_modifiers);
  117. String unicode = String::utf8(key_event.key);
  118. if (unicode.length() == 1) {
  119. ev->set_unicode(unicode[0]);
  120. }
  121. Input::get_singleton()->parse_input_event(ev);
  122. // Make sure to flush all events so we can call restricted APIs inside the event.
  123. Input::get_singleton()->flush_buffered_events();
  124. }
  125. // Mouse
  126. int DisplayServerWeb::mouse_button_callback(int p_pressed, int p_button, double p_x, double p_y, int p_modifiers) {
  127. DisplayServerWeb *ds = get_singleton();
  128. Point2 pos(p_x, p_y);
  129. Ref<InputEventMouseButton> ev;
  130. ev.instantiate();
  131. ev->set_position(pos);
  132. ev->set_global_position(pos);
  133. ev->set_pressed(p_pressed);
  134. dom2godot_mod(ev, p_modifiers);
  135. switch (p_button) {
  136. case DOM_BUTTON_LEFT:
  137. ev->set_button_index(MouseButton::LEFT);
  138. break;
  139. case DOM_BUTTON_MIDDLE:
  140. ev->set_button_index(MouseButton::MIDDLE);
  141. break;
  142. case DOM_BUTTON_RIGHT:
  143. ev->set_button_index(MouseButton::RIGHT);
  144. break;
  145. case DOM_BUTTON_XBUTTON1:
  146. ev->set_button_index(MouseButton::MB_XBUTTON1);
  147. break;
  148. case DOM_BUTTON_XBUTTON2:
  149. ev->set_button_index(MouseButton::MB_XBUTTON2);
  150. break;
  151. default:
  152. return false;
  153. }
  154. if (p_pressed) {
  155. uint64_t diff = (OS::get_singleton()->get_ticks_usec() / 1000) - ds->last_click_ms;
  156. if (ev->get_button_index() == ds->last_click_button_index) {
  157. if (diff < 400 && Point2(ds->last_click_pos).distance_to(ev->get_position()) < 5) {
  158. ds->last_click_ms = 0;
  159. ds->last_click_pos = Point2(-100, -100);
  160. ds->last_click_button_index = MouseButton::NONE;
  161. ev->set_double_click(true);
  162. }
  163. } else {
  164. ds->last_click_button_index = ev->get_button_index();
  165. }
  166. if (!ev->is_double_click()) {
  167. ds->last_click_ms += diff;
  168. ds->last_click_pos = ev->get_position();
  169. }
  170. }
  171. MouseButton mask = Input::get_singleton()->get_mouse_button_mask();
  172. MouseButton button_flag = mouse_button_to_mask(ev->get_button_index());
  173. if (ev->is_pressed()) {
  174. mask |= button_flag;
  175. } else if ((mask & button_flag) != MouseButton::NONE) {
  176. mask &= ~button_flag;
  177. } else {
  178. // Received release event, but press was outside the canvas, so ignore.
  179. return false;
  180. }
  181. ev->set_button_mask(mask);
  182. Input::get_singleton()->parse_input_event(ev);
  183. // Resume audio context after input in case autoplay was denied.
  184. OS_Web::get_singleton()->resume_audio();
  185. // Make sure to flush all events so we can call restricted APIs inside the event.
  186. Input::get_singleton()->flush_buffered_events();
  187. // Prevent multi-click text selection and wheel-click scrolling anchor.
  188. // Context menu is prevented through contextmenu event.
  189. return true;
  190. }
  191. void DisplayServerWeb::mouse_move_callback(double p_x, double p_y, double p_rel_x, double p_rel_y, int p_modifiers) {
  192. MouseButton input_mask = Input::get_singleton()->get_mouse_button_mask();
  193. // For motion outside the canvas, only read mouse movement if dragging
  194. // started inside the canvas; imitating desktop app behavior.
  195. if (!get_singleton()->cursor_inside_canvas && input_mask == MouseButton::NONE) {
  196. return;
  197. }
  198. Point2 pos(p_x, p_y);
  199. Ref<InputEventMouseMotion> ev;
  200. ev.instantiate();
  201. dom2godot_mod(ev, p_modifiers);
  202. ev->set_button_mask(input_mask);
  203. ev->set_position(pos);
  204. ev->set_global_position(pos);
  205. ev->set_relative(Vector2(p_rel_x, p_rel_y));
  206. ev->set_velocity(Input::get_singleton()->get_last_mouse_velocity());
  207. Input::get_singleton()->parse_input_event(ev);
  208. }
  209. // Cursor
  210. const char *DisplayServerWeb::godot2dom_cursor(DisplayServer::CursorShape p_shape) {
  211. switch (p_shape) {
  212. case DisplayServer::CURSOR_ARROW:
  213. return "default";
  214. case DisplayServer::CURSOR_IBEAM:
  215. return "text";
  216. case DisplayServer::CURSOR_POINTING_HAND:
  217. return "pointer";
  218. case DisplayServer::CURSOR_CROSS:
  219. return "crosshair";
  220. case DisplayServer::CURSOR_WAIT:
  221. return "wait";
  222. case DisplayServer::CURSOR_BUSY:
  223. return "progress";
  224. case DisplayServer::CURSOR_DRAG:
  225. return "grab";
  226. case DisplayServer::CURSOR_CAN_DROP:
  227. return "grabbing";
  228. case DisplayServer::CURSOR_FORBIDDEN:
  229. return "no-drop";
  230. case DisplayServer::CURSOR_VSIZE:
  231. return "ns-resize";
  232. case DisplayServer::CURSOR_HSIZE:
  233. return "ew-resize";
  234. case DisplayServer::CURSOR_BDIAGSIZE:
  235. return "nesw-resize";
  236. case DisplayServer::CURSOR_FDIAGSIZE:
  237. return "nwse-resize";
  238. case DisplayServer::CURSOR_MOVE:
  239. return "move";
  240. case DisplayServer::CURSOR_VSPLIT:
  241. return "row-resize";
  242. case DisplayServer::CURSOR_HSPLIT:
  243. return "col-resize";
  244. case DisplayServer::CURSOR_HELP:
  245. return "help";
  246. default:
  247. return "default";
  248. }
  249. }
  250. bool DisplayServerWeb::tts_is_speaking() const {
  251. return godot_js_tts_is_speaking();
  252. }
  253. bool DisplayServerWeb::tts_is_paused() const {
  254. return godot_js_tts_is_paused();
  255. }
  256. void DisplayServerWeb::update_voices_callback(int p_size, const char **p_voice) {
  257. get_singleton()->voices.clear();
  258. for (int i = 0; i < p_size; i++) {
  259. Vector<String> tokens = String::utf8(p_voice[i]).split(";", true, 2);
  260. if (tokens.size() == 2) {
  261. Dictionary voice_d;
  262. voice_d["name"] = tokens[1];
  263. voice_d["id"] = tokens[1];
  264. voice_d["language"] = tokens[0];
  265. get_singleton()->voices.push_back(voice_d);
  266. }
  267. }
  268. }
  269. TypedArray<Dictionary> DisplayServerWeb::tts_get_voices() const {
  270. godot_js_tts_get_voices(update_voices_callback);
  271. return voices;
  272. }
  273. void DisplayServerWeb::tts_speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
  274. if (p_interrupt) {
  275. tts_stop();
  276. }
  277. if (p_text.is_empty()) {
  278. tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, p_utterance_id);
  279. return;
  280. }
  281. CharString string = p_text.utf8();
  282. utterance_ids[p_utterance_id] = string;
  283. godot_js_tts_speak(string.get_data(), p_voice.utf8().get_data(), CLAMP(p_volume, 0, 100), CLAMP(p_pitch, 0.f, 2.f), CLAMP(p_rate, 0.1f, 10.f), p_utterance_id, DisplayServerWeb::_js_utterance_callback);
  284. }
  285. void DisplayServerWeb::tts_pause() {
  286. godot_js_tts_pause();
  287. }
  288. void DisplayServerWeb::tts_resume() {
  289. godot_js_tts_resume();
  290. }
  291. void DisplayServerWeb::tts_stop() {
  292. for (const KeyValue<int, CharString> &E : utterance_ids) {
  293. tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, E.key);
  294. }
  295. utterance_ids.clear();
  296. godot_js_tts_stop();
  297. }
  298. void DisplayServerWeb::_js_utterance_callback(int p_event, int p_id, int p_pos) {
  299. DisplayServerWeb *ds = (DisplayServerWeb *)DisplayServer::get_singleton();
  300. if (ds->utterance_ids.has(p_id)) {
  301. int pos = 0;
  302. if ((TTSUtteranceEvent)p_event == DisplayServer::TTS_UTTERANCE_BOUNDARY) {
  303. // Convert position from UTF-8 to UTF-32.
  304. const CharString &string = ds->utterance_ids[p_id];
  305. for (int i = 0; i < MIN(p_pos, string.length()); i++) {
  306. uint8_t c = string[i];
  307. if ((c & 0xe0) == 0xc0) {
  308. i += 1;
  309. } else if ((c & 0xf0) == 0xe0) {
  310. i += 2;
  311. } else if ((c & 0xf8) == 0xf0) {
  312. i += 3;
  313. }
  314. pos++;
  315. }
  316. } else if ((TTSUtteranceEvent)p_event != DisplayServer::TTS_UTTERANCE_STARTED) {
  317. ds->utterance_ids.erase(p_id);
  318. }
  319. ds->tts_post_utterance_event((TTSUtteranceEvent)p_event, p_id, pos);
  320. }
  321. }
  322. void DisplayServerWeb::cursor_set_shape(CursorShape p_shape) {
  323. ERR_FAIL_INDEX(p_shape, CURSOR_MAX);
  324. if (cursor_shape == p_shape) {
  325. return;
  326. }
  327. cursor_shape = p_shape;
  328. godot_js_display_cursor_set_shape(godot2dom_cursor(cursor_shape));
  329. }
  330. DisplayServer::CursorShape DisplayServerWeb::cursor_get_shape() const {
  331. return cursor_shape;
  332. }
  333. void DisplayServerWeb::cursor_set_custom_image(const Ref<Resource> &p_cursor, CursorShape p_shape, const Vector2 &p_hotspot) {
  334. if (p_cursor.is_valid()) {
  335. Ref<Texture2D> texture = p_cursor;
  336. Ref<AtlasTexture> atlas_texture = p_cursor;
  337. Ref<Image> image;
  338. Size2 texture_size;
  339. Rect2 atlas_rect;
  340. if (texture.is_valid()) {
  341. image = texture->get_image();
  342. }
  343. if (!image.is_valid() && atlas_texture.is_valid()) {
  344. texture = atlas_texture->get_atlas();
  345. atlas_rect.size.width = texture->get_width();
  346. atlas_rect.size.height = texture->get_height();
  347. atlas_rect.position.x = atlas_texture->get_region().position.x;
  348. atlas_rect.position.y = atlas_texture->get_region().position.y;
  349. texture_size.width = atlas_texture->get_region().size.x;
  350. texture_size.height = atlas_texture->get_region().size.y;
  351. } else if (image.is_valid()) {
  352. texture_size.width = texture->get_width();
  353. texture_size.height = texture->get_height();
  354. }
  355. ERR_FAIL_COND(!texture.is_valid());
  356. ERR_FAIL_COND(p_hotspot.x < 0 || p_hotspot.y < 0);
  357. ERR_FAIL_COND(texture_size.width > 256 || texture_size.height > 256);
  358. ERR_FAIL_COND(p_hotspot.x > texture_size.width || p_hotspot.y > texture_size.height);
  359. image = texture->get_image();
  360. ERR_FAIL_COND(!image.is_valid());
  361. image = image->duplicate();
  362. if (atlas_texture.is_valid()) {
  363. image->crop_from_point(
  364. atlas_rect.position.x,
  365. atlas_rect.position.y,
  366. texture_size.width,
  367. texture_size.height);
  368. }
  369. if (image->get_format() != Image::FORMAT_RGBA8) {
  370. image->convert(Image::FORMAT_RGBA8);
  371. }
  372. png_image png_meta;
  373. memset(&png_meta, 0, sizeof png_meta);
  374. png_meta.version = PNG_IMAGE_VERSION;
  375. png_meta.width = texture_size.width;
  376. png_meta.height = texture_size.height;
  377. png_meta.format = PNG_FORMAT_RGBA;
  378. PackedByteArray png;
  379. size_t len;
  380. PackedByteArray data = image->get_data();
  381. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr));
  382. png.resize(len);
  383. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr));
  384. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), png.ptr(), len, p_hotspot.x, p_hotspot.y);
  385. } else {
  386. godot_js_display_cursor_set_custom_shape(godot2dom_cursor(p_shape), nullptr, 0, 0, 0);
  387. }
  388. cursor_set_shape(cursor_shape);
  389. }
  390. // Mouse mode
  391. void DisplayServerWeb::mouse_set_mode(MouseMode p_mode) {
  392. ERR_FAIL_COND_MSG(p_mode == MOUSE_MODE_CONFINED || p_mode == MOUSE_MODE_CONFINED_HIDDEN, "MOUSE_MODE_CONFINED is not supported for the Web platform.");
  393. if (p_mode == mouse_get_mode()) {
  394. return;
  395. }
  396. if (p_mode == MOUSE_MODE_VISIBLE) {
  397. godot_js_display_cursor_set_visible(1);
  398. godot_js_display_cursor_lock_set(0);
  399. } else if (p_mode == MOUSE_MODE_HIDDEN) {
  400. godot_js_display_cursor_set_visible(0);
  401. godot_js_display_cursor_lock_set(0);
  402. } else if (p_mode == MOUSE_MODE_CAPTURED) {
  403. godot_js_display_cursor_set_visible(1);
  404. godot_js_display_cursor_lock_set(1);
  405. }
  406. }
  407. DisplayServer::MouseMode DisplayServerWeb::mouse_get_mode() const {
  408. if (godot_js_display_cursor_is_hidden()) {
  409. return MOUSE_MODE_HIDDEN;
  410. }
  411. if (godot_js_display_cursor_is_locked()) {
  412. return MOUSE_MODE_CAPTURED;
  413. }
  414. return MOUSE_MODE_VISIBLE;
  415. }
  416. Point2i DisplayServerWeb::mouse_get_position() const {
  417. return Input::get_singleton()->get_mouse_position();
  418. }
  419. // Wheel
  420. int DisplayServerWeb::mouse_wheel_callback(double p_delta_x, double p_delta_y) {
  421. if (!godot_js_display_canvas_is_focused()) {
  422. if (get_singleton()->cursor_inside_canvas) {
  423. godot_js_display_canvas_focus();
  424. } else {
  425. return false;
  426. }
  427. }
  428. Input *input = Input::get_singleton();
  429. Ref<InputEventMouseButton> ev;
  430. ev.instantiate();
  431. ev->set_position(input->get_mouse_position());
  432. ev->set_global_position(ev->get_position());
  433. ev->set_shift_pressed(input->is_key_pressed(Key::SHIFT));
  434. ev->set_alt_pressed(input->is_key_pressed(Key::ALT));
  435. ev->set_ctrl_pressed(input->is_key_pressed(Key::CTRL));
  436. ev->set_meta_pressed(input->is_key_pressed(Key::META));
  437. if (p_delta_y < 0) {
  438. ev->set_button_index(MouseButton::WHEEL_UP);
  439. } else if (p_delta_y > 0) {
  440. ev->set_button_index(MouseButton::WHEEL_DOWN);
  441. } else if (p_delta_x > 0) {
  442. ev->set_button_index(MouseButton::WHEEL_LEFT);
  443. } else if (p_delta_x < 0) {
  444. ev->set_button_index(MouseButton::WHEEL_RIGHT);
  445. } else {
  446. return false;
  447. }
  448. // Different browsers give wildly different delta values, and we can't
  449. // interpret deltaMode, so use default value for wheel events' factor.
  450. MouseButton button_flag = mouse_button_to_mask(ev->get_button_index());
  451. ev->set_pressed(true);
  452. ev->set_button_mask(input->get_mouse_button_mask() | button_flag);
  453. input->parse_input_event(ev);
  454. Ref<InputEventMouseButton> release = ev->duplicate();
  455. release->set_pressed(false);
  456. release->set_button_mask(MouseButton(input->get_mouse_button_mask() & ~button_flag));
  457. input->parse_input_event(release);
  458. return true;
  459. }
  460. // Touch
  461. void DisplayServerWeb::touch_callback(int p_type, int p_count) {
  462. DisplayServerWeb *ds = get_singleton();
  463. const JSTouchEvent &touch_event = ds->touch_event;
  464. for (int i = 0; i < p_count; i++) {
  465. Point2 point(touch_event.coords[i * 2], touch_event.coords[i * 2 + 1]);
  466. if (p_type == 2) {
  467. // touchmove
  468. Ref<InputEventScreenDrag> ev;
  469. ev.instantiate();
  470. ev->set_index(touch_event.identifier[i]);
  471. ev->set_position(point);
  472. Point2 &prev = ds->touches[i];
  473. ev->set_relative(ev->get_position() - prev);
  474. prev = ev->get_position();
  475. Input::get_singleton()->parse_input_event(ev);
  476. } else {
  477. // touchstart/touchend
  478. Ref<InputEventScreenTouch> ev;
  479. // Resume audio context after input in case autoplay was denied.
  480. OS_Web::get_singleton()->resume_audio();
  481. ev.instantiate();
  482. ev->set_index(touch_event.identifier[i]);
  483. ev->set_position(point);
  484. ev->set_pressed(p_type == 0);
  485. ds->touches[i] = point;
  486. Input::get_singleton()->parse_input_event(ev);
  487. // Make sure to flush all events so we can call restricted APIs inside the event.
  488. Input::get_singleton()->flush_buffered_events();
  489. }
  490. }
  491. }
  492. bool DisplayServerWeb::screen_is_touchscreen(int p_screen) const {
  493. return godot_js_display_touchscreen_is_available();
  494. }
  495. // Virtual Keyboard
  496. void DisplayServerWeb::vk_input_text_callback(const char *p_text, int p_cursor) {
  497. DisplayServerWeb *ds = DisplayServerWeb::get_singleton();
  498. if (!ds || ds->input_text_callback.is_null()) {
  499. return;
  500. }
  501. // Call input_text
  502. Variant event = String::utf8(p_text);
  503. Variant *eventp = &event;
  504. Variant ret;
  505. Callable::CallError ce;
  506. ds->input_text_callback.callp((const Variant **)&eventp, 1, ret, ce);
  507. // Insert key right to reach position.
  508. Input *input = Input::get_singleton();
  509. Ref<InputEventKey> k;
  510. for (int i = 0; i < p_cursor; i++) {
  511. k.instantiate();
  512. k->set_pressed(true);
  513. k->set_echo(false);
  514. k->set_keycode(Key::RIGHT);
  515. input->parse_input_event(k);
  516. k.instantiate();
  517. k->set_pressed(false);
  518. k->set_echo(false);
  519. k->set_keycode(Key::RIGHT);
  520. input->parse_input_event(k);
  521. }
  522. }
  523. void DisplayServerWeb::virtual_keyboard_show(const String &p_existing_text, const Rect2 &p_screen_rect, VirtualKeyboardType p_type, int p_max_input_length, int p_cursor_start, int p_cursor_end) {
  524. godot_js_display_vk_show(p_existing_text.utf8().get_data(), p_type, p_cursor_start, p_cursor_end);
  525. }
  526. void DisplayServerWeb::virtual_keyboard_hide() {
  527. godot_js_display_vk_hide();
  528. }
  529. void DisplayServerWeb::window_blur_callback() {
  530. Input::get_singleton()->release_pressed_events();
  531. }
  532. // Gamepad
  533. void DisplayServerWeb::gamepad_callback(int p_index, int p_connected, const char *p_id, const char *p_guid) {
  534. Input *input = Input::get_singleton();
  535. if (p_connected) {
  536. input->joy_connection_changed(p_index, true, String::utf8(p_id), String::utf8(p_guid));
  537. } else {
  538. input->joy_connection_changed(p_index, false, "");
  539. }
  540. }
  541. void DisplayServerWeb::process_joypads() {
  542. Input *input = Input::get_singleton();
  543. int32_t pads = godot_js_input_gamepad_sample_count();
  544. int32_t s_btns_num = 0;
  545. int32_t s_axes_num = 0;
  546. int32_t s_standard = 0;
  547. float s_btns[16];
  548. float s_axes[10];
  549. for (int idx = 0; idx < pads; idx++) {
  550. int err = godot_js_input_gamepad_sample_get(idx, s_btns, &s_btns_num, s_axes, &s_axes_num, &s_standard);
  551. if (err) {
  552. continue;
  553. }
  554. for (int b = 0; b < s_btns_num; b++) {
  555. // Buttons 6 and 7 in the standard mapping need to be
  556. // axis to be handled as JoyAxis::TRIGGER by Godot.
  557. if (s_standard && (b == 6 || b == 7)) {
  558. input->joy_axis(idx, (JoyAxis)b, s_btns[b]);
  559. } else {
  560. input->joy_button(idx, (JoyButton)b, s_btns[b]);
  561. }
  562. }
  563. for (int a = 0; a < s_axes_num; a++) {
  564. input->joy_axis(idx, (JoyAxis)a, s_axes[a]);
  565. }
  566. }
  567. }
  568. Vector<String> DisplayServerWeb::get_rendering_drivers_func() {
  569. Vector<String> drivers;
  570. #ifdef GLES3_ENABLED
  571. drivers.push_back("opengl3");
  572. #endif
  573. return drivers;
  574. }
  575. // Clipboard
  576. void DisplayServerWeb::update_clipboard_callback(const char *p_text) {
  577. get_singleton()->clipboard = String::utf8(p_text);
  578. }
  579. void DisplayServerWeb::clipboard_set(const String &p_text) {
  580. clipboard = p_text;
  581. int err = godot_js_display_clipboard_set(p_text.utf8().get_data());
  582. ERR_FAIL_COND_MSG(err, "Clipboard API is not supported.");
  583. }
  584. String DisplayServerWeb::clipboard_get() const {
  585. godot_js_display_clipboard_get(update_clipboard_callback);
  586. return clipboard;
  587. }
  588. void DisplayServerWeb::send_window_event_callback(int p_notification) {
  589. DisplayServerWeb *ds = get_singleton();
  590. if (!ds) {
  591. return;
  592. }
  593. if (p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER || p_notification == DisplayServer::WINDOW_EVENT_MOUSE_EXIT) {
  594. ds->cursor_inside_canvas = p_notification == DisplayServer::WINDOW_EVENT_MOUSE_ENTER;
  595. }
  596. if (!ds->window_event_callback.is_null()) {
  597. Variant event = int(p_notification);
  598. Variant *eventp = &event;
  599. Variant ret;
  600. Callable::CallError ce;
  601. ds->window_event_callback.callp((const Variant **)&eventp, 1, ret, ce);
  602. }
  603. }
  604. void DisplayServerWeb::set_icon(const Ref<Image> &p_icon) {
  605. ERR_FAIL_COND(p_icon.is_null());
  606. Ref<Image> icon = p_icon;
  607. if (icon->is_compressed()) {
  608. icon = icon->duplicate();
  609. ERR_FAIL_COND(icon->decompress() != OK);
  610. }
  611. if (icon->get_format() != Image::FORMAT_RGBA8) {
  612. if (icon == p_icon) {
  613. icon = icon->duplicate();
  614. }
  615. icon->convert(Image::FORMAT_RGBA8);
  616. }
  617. png_image png_meta;
  618. memset(&png_meta, 0, sizeof png_meta);
  619. png_meta.version = PNG_IMAGE_VERSION;
  620. png_meta.width = icon->get_width();
  621. png_meta.height = icon->get_height();
  622. png_meta.format = PNG_FORMAT_RGBA;
  623. PackedByteArray png;
  624. size_t len;
  625. PackedByteArray data = icon->get_data();
  626. ERR_FAIL_COND(!png_image_write_get_memory_size(png_meta, len, 0, data.ptr(), 0, nullptr));
  627. png.resize(len);
  628. ERR_FAIL_COND(!png_image_write_to_memory(&png_meta, png.ptrw(), &len, 0, data.ptr(), 0, nullptr));
  629. godot_js_display_window_icon_set(png.ptr(), len);
  630. }
  631. void DisplayServerWeb::_dispatch_input_event(const Ref<InputEvent> &p_event) {
  632. Callable cb = get_singleton()->input_event_callback;
  633. if (!cb.is_null()) {
  634. Variant ev = p_event;
  635. Variant *evp = &ev;
  636. Variant ret;
  637. Callable::CallError ce;
  638. cb.callp((const Variant **)&evp, 1, ret, ce);
  639. }
  640. }
  641. DisplayServer *DisplayServerWeb::create_func(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Point2i *p_position, const Size2i &p_resolution, Error &r_error) {
  642. return memnew(DisplayServerWeb(p_rendering_driver, p_window_mode, p_vsync_mode, p_flags, p_position, p_resolution, r_error));
  643. }
  644. DisplayServerWeb::DisplayServerWeb(const String &p_rendering_driver, WindowMode p_window_mode, VSyncMode p_vsync_mode, uint32_t p_flags, const Point2i *p_position, const Size2i &p_resolution, Error &r_error) {
  645. r_error = OK; // Always succeeds for now.
  646. // Ensure the canvas ID.
  647. godot_js_config_canvas_id_get(canvas_id, 256);
  648. // Handle contextmenu, webglcontextlost
  649. godot_js_display_setup_canvas(p_resolution.x, p_resolution.y, (p_window_mode == WINDOW_MODE_FULLSCREEN || p_window_mode == WINDOW_MODE_EXCLUSIVE_FULLSCREEN), OS::get_singleton()->is_hidpi_allowed() ? 1 : 0);
  650. // Check if it's windows.
  651. swap_cancel_ok = godot_js_display_is_swap_ok_cancel() == 1;
  652. // Expose method for requesting quit.
  653. godot_js_os_request_quit_cb(request_quit_callback);
  654. #ifdef GLES3_ENABLED
  655. bool webgl2_inited = false;
  656. if (godot_js_display_has_webgl(2)) {
  657. EmscriptenWebGLContextAttributes attributes;
  658. emscripten_webgl_init_context_attributes(&attributes);
  659. attributes.alpha = OS::get_singleton()->is_layered_allowed();
  660. attributes.antialias = false;
  661. attributes.majorVersion = 2;
  662. attributes.explicitSwapControl = true;
  663. webgl_ctx = emscripten_webgl_create_context(canvas_id, &attributes);
  664. webgl2_inited = webgl_ctx && emscripten_webgl_make_context_current(webgl_ctx) == EMSCRIPTEN_RESULT_SUCCESS;
  665. }
  666. if (webgl2_inited) {
  667. if (!emscripten_webgl_enable_extension(webgl_ctx, "OVR_multiview2")) {
  668. print_verbose("Failed to enable WebXR extension.");
  669. }
  670. RasterizerGLES3::make_current();
  671. } else {
  672. OS::get_singleton()->alert("Your browser does not seem to support WebGL2. Please update your browser version.",
  673. "Unable to initialize video driver");
  674. RasterizerDummy::make_current();
  675. }
  676. #else
  677. RasterizerDummy::make_current();
  678. #endif
  679. // JS Input interface (js/libs/library_godot_input.js)
  680. godot_js_input_mouse_button_cb(&DisplayServerWeb::mouse_button_callback);
  681. godot_js_input_mouse_move_cb(&DisplayServerWeb::mouse_move_callback);
  682. godot_js_input_mouse_wheel_cb(&DisplayServerWeb::mouse_wheel_callback);
  683. godot_js_input_touch_cb(&DisplayServerWeb::touch_callback, touch_event.identifier, touch_event.coords);
  684. godot_js_input_key_cb(&DisplayServerWeb::key_callback, key_event.code, key_event.key);
  685. godot_js_input_paste_cb(update_clipboard_callback);
  686. godot_js_input_drop_files_cb(drop_files_js_callback);
  687. godot_js_input_gamepad_cb(&DisplayServerWeb::gamepad_callback);
  688. // JS Display interface (js/libs/library_godot_display.js)
  689. godot_js_display_fullscreen_cb(&DisplayServerWeb::fullscreen_change_callback);
  690. godot_js_display_window_blur_cb(&window_blur_callback);
  691. godot_js_display_notification_cb(&send_window_event_callback,
  692. WINDOW_EVENT_MOUSE_ENTER,
  693. WINDOW_EVENT_MOUSE_EXIT,
  694. WINDOW_EVENT_FOCUS_IN,
  695. WINDOW_EVENT_FOCUS_OUT);
  696. godot_js_display_vk_cb(&vk_input_text_callback);
  697. Input::get_singleton()->set_event_dispatch_function(_dispatch_input_event);
  698. }
  699. DisplayServerWeb::~DisplayServerWeb() {
  700. #ifdef GLES3_ENABLED
  701. if (webgl_ctx) {
  702. emscripten_webgl_commit_frame();
  703. emscripten_webgl_destroy_context(webgl_ctx);
  704. }
  705. #endif
  706. }
  707. bool DisplayServerWeb::has_feature(Feature p_feature) const {
  708. switch (p_feature) {
  709. //case FEATURE_GLOBAL_MENU:
  710. //case FEATURE_HIDPI:
  711. //case FEATURE_IME:
  712. case FEATURE_ICON:
  713. case FEATURE_CLIPBOARD:
  714. case FEATURE_CURSOR_SHAPE:
  715. case FEATURE_CUSTOM_CURSOR_SHAPE:
  716. case FEATURE_MOUSE:
  717. case FEATURE_TOUCHSCREEN:
  718. return true;
  719. //case FEATURE_MOUSE_WARP:
  720. //case FEATURE_NATIVE_DIALOG:
  721. //case FEATURE_NATIVE_ICON:
  722. //case FEATURE_WINDOW_TRANSPARENCY:
  723. //case FEATURE_KEEP_SCREEN_ON:
  724. //case FEATURE_ORIENTATION:
  725. case FEATURE_VIRTUAL_KEYBOARD:
  726. return godot_js_display_vk_available() != 0;
  727. case FEATURE_TEXT_TO_SPEECH:
  728. return godot_js_display_tts_available() != 0;
  729. default:
  730. return false;
  731. }
  732. }
  733. void DisplayServerWeb::register_web_driver() {
  734. register_create_function("web", create_func, get_rendering_drivers_func);
  735. }
  736. String DisplayServerWeb::get_name() const {
  737. return "web";
  738. }
  739. int DisplayServerWeb::get_screen_count() const {
  740. return 1;
  741. }
  742. Point2i DisplayServerWeb::screen_get_position(int p_screen) const {
  743. return Point2i(); // TODO offsetX/Y?
  744. }
  745. Size2i DisplayServerWeb::screen_get_size(int p_screen) const {
  746. int size[2];
  747. godot_js_display_screen_size_get(size, size + 1);
  748. return Size2(size[0], size[1]);
  749. }
  750. Rect2i DisplayServerWeb::screen_get_usable_rect(int p_screen) const {
  751. int size[2];
  752. godot_js_display_window_size_get(size, size + 1);
  753. return Rect2i(0, 0, size[0], size[1]);
  754. }
  755. int DisplayServerWeb::screen_get_dpi(int p_screen) const {
  756. return godot_js_display_screen_dpi_get();
  757. }
  758. float DisplayServerWeb::screen_get_scale(int p_screen) const {
  759. return godot_js_display_pixel_ratio_get();
  760. }
  761. float DisplayServerWeb::screen_get_refresh_rate(int p_screen) const {
  762. return SCREEN_REFRESH_RATE_FALLBACK; // Web doesn't have much of a need for the screen refresh rate, and there's no native way to do so.
  763. }
  764. Vector<DisplayServer::WindowID> DisplayServerWeb::get_window_list() const {
  765. Vector<WindowID> ret;
  766. ret.push_back(MAIN_WINDOW_ID);
  767. return ret;
  768. }
  769. DisplayServerWeb::WindowID DisplayServerWeb::get_window_at_screen_position(const Point2i &p_position) const {
  770. return MAIN_WINDOW_ID;
  771. }
  772. void DisplayServerWeb::window_attach_instance_id(ObjectID p_instance, WindowID p_window) {
  773. window_attached_instance_id = p_instance;
  774. }
  775. ObjectID DisplayServerWeb::window_get_attached_instance_id(WindowID p_window) const {
  776. return window_attached_instance_id;
  777. }
  778. void DisplayServerWeb::window_set_rect_changed_callback(const Callable &p_callable, WindowID p_window) {
  779. rect_changed_callback = p_callable;
  780. }
  781. void DisplayServerWeb::window_set_window_event_callback(const Callable &p_callable, WindowID p_window) {
  782. window_event_callback = p_callable;
  783. }
  784. void DisplayServerWeb::window_set_input_event_callback(const Callable &p_callable, WindowID p_window) {
  785. input_event_callback = p_callable;
  786. }
  787. void DisplayServerWeb::window_set_input_text_callback(const Callable &p_callable, WindowID p_window) {
  788. input_text_callback = p_callable;
  789. }
  790. void DisplayServerWeb::window_set_drop_files_callback(const Callable &p_callable, WindowID p_window) {
  791. drop_files_callback = p_callable;
  792. }
  793. void DisplayServerWeb::window_set_title(const String &p_title, WindowID p_window) {
  794. godot_js_display_window_title_set(p_title.utf8().get_data());
  795. }
  796. int DisplayServerWeb::window_get_current_screen(WindowID p_window) const {
  797. return 1;
  798. }
  799. void DisplayServerWeb::window_set_current_screen(int p_screen, WindowID p_window) {
  800. // Not implemented.
  801. }
  802. Point2i DisplayServerWeb::window_get_position(WindowID p_window) const {
  803. return Point2i(); // TODO Does this need implementation?
  804. }
  805. void DisplayServerWeb::window_set_position(const Point2i &p_position, WindowID p_window) {
  806. // Not supported.
  807. }
  808. void DisplayServerWeb::window_set_transient(WindowID p_window, WindowID p_parent) {
  809. // Not supported.
  810. }
  811. void DisplayServerWeb::window_set_max_size(const Size2i p_size, WindowID p_window) {
  812. // Not supported.
  813. }
  814. Size2i DisplayServerWeb::window_get_max_size(WindowID p_window) const {
  815. return Size2i();
  816. }
  817. void DisplayServerWeb::window_set_min_size(const Size2i p_size, WindowID p_window) {
  818. // Not supported.
  819. }
  820. Size2i DisplayServerWeb::window_get_min_size(WindowID p_window) const {
  821. return Size2i();
  822. }
  823. void DisplayServerWeb::window_set_size(const Size2i p_size, WindowID p_window) {
  824. godot_js_display_desired_size_set(p_size.x, p_size.y);
  825. }
  826. Size2i DisplayServerWeb::window_get_size(WindowID p_window) const {
  827. int size[2];
  828. godot_js_display_window_size_get(size, size + 1);
  829. return Size2i(size[0], size[1]);
  830. }
  831. Size2i DisplayServerWeb::window_get_real_size(WindowID p_window) const {
  832. return window_get_size(p_window);
  833. }
  834. void DisplayServerWeb::window_set_mode(WindowMode p_mode, WindowID p_window) {
  835. if (window_mode == p_mode) {
  836. return;
  837. }
  838. switch (p_mode) {
  839. case WINDOW_MODE_WINDOWED: {
  840. if (window_mode == WINDOW_MODE_FULLSCREEN) {
  841. godot_js_display_fullscreen_exit();
  842. }
  843. window_mode = WINDOW_MODE_WINDOWED;
  844. } break;
  845. case WINDOW_MODE_EXCLUSIVE_FULLSCREEN:
  846. case WINDOW_MODE_FULLSCREEN: {
  847. int result = godot_js_display_fullscreen_request();
  848. ERR_FAIL_COND_MSG(result, "The request was denied. Remember that enabling fullscreen is only possible from an input callback for the Web platform.");
  849. } break;
  850. case WINDOW_MODE_MAXIMIZED:
  851. case WINDOW_MODE_MINIMIZED:
  852. // WindowMode MAXIMIZED and MINIMIZED are not supported in Web platform.
  853. break;
  854. default:
  855. break;
  856. }
  857. }
  858. DisplayServerWeb::WindowMode DisplayServerWeb::window_get_mode(WindowID p_window) const {
  859. return window_mode;
  860. }
  861. bool DisplayServerWeb::window_is_maximize_allowed(WindowID p_window) const {
  862. return false;
  863. }
  864. void DisplayServerWeb::window_set_flag(WindowFlags p_flag, bool p_enabled, WindowID p_window) {
  865. // Not supported.
  866. }
  867. bool DisplayServerWeb::window_get_flag(WindowFlags p_flag, WindowID p_window) const {
  868. return false;
  869. }
  870. void DisplayServerWeb::window_request_attention(WindowID p_window) {
  871. // Not supported.
  872. }
  873. void DisplayServerWeb::window_move_to_foreground(WindowID p_window) {
  874. // Not supported.
  875. }
  876. bool DisplayServerWeb::window_can_draw(WindowID p_window) const {
  877. return true;
  878. }
  879. bool DisplayServerWeb::can_any_window_draw() const {
  880. return true;
  881. }
  882. void DisplayServerWeb::process_events() {
  883. Input::get_singleton()->flush_buffered_events();
  884. if (godot_js_input_gamepad_sample() == OK) {
  885. process_joypads();
  886. }
  887. }
  888. int DisplayServerWeb::get_current_video_driver() const {
  889. return 1;
  890. }
  891. bool DisplayServerWeb::get_swap_cancel_ok() {
  892. return swap_cancel_ok;
  893. }
  894. void DisplayServerWeb::swap_buffers() {
  895. #ifdef GLES3_ENABLED
  896. if (webgl_ctx) {
  897. emscripten_webgl_commit_frame();
  898. }
  899. #endif
  900. }