display_server_web.cpp 35 KB

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