webxr_interface_js.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884
  1. /**************************************************************************/
  2. /* webxr_interface_js.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 "webxr_interface_js.h"
  31. #ifdef WEB_ENABLED
  32. #include "godot_webxr.h"
  33. #include "core/input/input.h"
  34. #include "core/os/os.h"
  35. #include "drivers/gles3/storage/texture_storage.h"
  36. #include "scene/main/scene_tree.h"
  37. #include "scene/main/window.h"
  38. #include "scene/scene_string_names.h"
  39. #include "servers/rendering/renderer_compositor.h"
  40. #include "servers/rendering/rendering_server_globals.h"
  41. #include "servers/xr/xr_hand_tracker.h"
  42. #include <emscripten.h>
  43. #include <stdlib.h>
  44. void _emwebxr_on_session_supported(char *p_session_mode, int p_supported) {
  45. XRServer *xr_server = XRServer::get_singleton();
  46. ERR_FAIL_NULL(xr_server);
  47. Ref<WebXRInterfaceJS> interface = xr_server->find_interface("WebXR");
  48. ERR_FAIL_COND(interface.is_null());
  49. String session_mode = String(p_session_mode);
  50. interface->emit_signal(SNAME("session_supported"), session_mode, p_supported ? true : false);
  51. }
  52. void _emwebxr_on_session_started(char *p_reference_space_type, char *p_enabled_features, char *p_environment_blend_mode) {
  53. XRServer *xr_server = XRServer::get_singleton();
  54. ERR_FAIL_NULL(xr_server);
  55. Ref<WebXRInterfaceJS> interface = xr_server->find_interface("WebXR");
  56. ERR_FAIL_COND(interface.is_null());
  57. String reference_space_type = String(p_reference_space_type);
  58. interface->_set_reference_space_type(reference_space_type);
  59. interface->_set_enabled_features(p_enabled_features);
  60. interface->_set_environment_blend_mode(p_environment_blend_mode);
  61. interface->emit_signal(SNAME("session_started"));
  62. }
  63. void _emwebxr_on_session_ended() {
  64. XRServer *xr_server = XRServer::get_singleton();
  65. ERR_FAIL_NULL(xr_server);
  66. Ref<WebXRInterfaceJS> interface = xr_server->find_interface("WebXR");
  67. ERR_FAIL_COND(interface.is_null());
  68. interface->uninitialize();
  69. interface->emit_signal(SNAME("session_ended"));
  70. }
  71. void _emwebxr_on_session_failed(char *p_message) {
  72. XRServer *xr_server = XRServer::get_singleton();
  73. ERR_FAIL_NULL(xr_server);
  74. Ref<WebXRInterfaceJS> interface = xr_server->find_interface("WebXR");
  75. ERR_FAIL_COND(interface.is_null());
  76. interface->uninitialize();
  77. String message = String(p_message);
  78. interface->emit_signal(SNAME("session_failed"), message);
  79. }
  80. extern "C" EMSCRIPTEN_KEEPALIVE void _emwebxr_on_input_event(int p_event_type, int p_input_source_id) {
  81. XRServer *xr_server = XRServer::get_singleton();
  82. ERR_FAIL_NULL(xr_server);
  83. Ref<WebXRInterfaceJS> interface = xr_server->find_interface("WebXR");
  84. ERR_FAIL_COND(interface.is_null());
  85. interface->_on_input_event(p_event_type, p_input_source_id);
  86. }
  87. extern "C" EMSCRIPTEN_KEEPALIVE void _emwebxr_on_simple_event(char *p_signal_name) {
  88. XRServer *xr_server = XRServer::get_singleton();
  89. ERR_FAIL_NULL(xr_server);
  90. Ref<WebXRInterfaceJS> interface = xr_server->find_interface("WebXR");
  91. ERR_FAIL_COND(interface.is_null());
  92. StringName signal_name = StringName(p_signal_name);
  93. interface->emit_signal(signal_name);
  94. }
  95. void WebXRInterfaceJS::is_session_supported(const String &p_session_mode) {
  96. godot_webxr_is_session_supported(p_session_mode.utf8().get_data(), &_emwebxr_on_session_supported);
  97. }
  98. void WebXRInterfaceJS::set_session_mode(String p_session_mode) {
  99. session_mode = p_session_mode;
  100. }
  101. String WebXRInterfaceJS::get_session_mode() const {
  102. return session_mode;
  103. }
  104. void WebXRInterfaceJS::set_required_features(String p_required_features) {
  105. required_features = p_required_features;
  106. }
  107. String WebXRInterfaceJS::get_required_features() const {
  108. return required_features;
  109. }
  110. void WebXRInterfaceJS::set_optional_features(String p_optional_features) {
  111. optional_features = p_optional_features;
  112. }
  113. String WebXRInterfaceJS::get_optional_features() const {
  114. return optional_features;
  115. }
  116. void WebXRInterfaceJS::set_requested_reference_space_types(String p_requested_reference_space_types) {
  117. requested_reference_space_types = p_requested_reference_space_types;
  118. }
  119. String WebXRInterfaceJS::get_requested_reference_space_types() const {
  120. return requested_reference_space_types;
  121. }
  122. String WebXRInterfaceJS::get_reference_space_type() const {
  123. return reference_space_type;
  124. }
  125. String WebXRInterfaceJS::get_enabled_features() const {
  126. return enabled_features;
  127. }
  128. bool WebXRInterfaceJS::is_input_source_active(int p_input_source_id) const {
  129. ERR_FAIL_INDEX_V(p_input_source_id, input_source_count, false);
  130. return input_sources[p_input_source_id].active;
  131. }
  132. Ref<XRControllerTracker> WebXRInterfaceJS::get_input_source_tracker(int p_input_source_id) const {
  133. ERR_FAIL_INDEX_V(p_input_source_id, input_source_count, Ref<XRControllerTracker>());
  134. return input_sources[p_input_source_id].tracker;
  135. }
  136. WebXRInterface::TargetRayMode WebXRInterfaceJS::get_input_source_target_ray_mode(int p_input_source_id) const {
  137. ERR_FAIL_INDEX_V(p_input_source_id, input_source_count, WebXRInterface::TARGET_RAY_MODE_UNKNOWN);
  138. if (!input_sources[p_input_source_id].active) {
  139. return WebXRInterface::TARGET_RAY_MODE_UNKNOWN;
  140. }
  141. return input_sources[p_input_source_id].target_ray_mode;
  142. }
  143. String WebXRInterfaceJS::get_visibility_state() const {
  144. char *c_str = godot_webxr_get_visibility_state();
  145. if (c_str) {
  146. String visibility_state = String(c_str);
  147. free(c_str);
  148. return visibility_state;
  149. }
  150. return String();
  151. }
  152. PackedVector3Array WebXRInterfaceJS::get_play_area() const {
  153. PackedVector3Array ret;
  154. float *points;
  155. int point_count = godot_webxr_get_bounds_geometry(&points);
  156. if (point_count > 0) {
  157. ret.resize(point_count);
  158. for (int i = 0; i < point_count; i++) {
  159. float *js_vector3 = points + (i * 3);
  160. ret.set(i, Vector3(js_vector3[0], js_vector3[1], js_vector3[2]));
  161. }
  162. free(points);
  163. }
  164. return ret;
  165. }
  166. float WebXRInterfaceJS::get_display_refresh_rate() const {
  167. return godot_webxr_get_frame_rate();
  168. }
  169. void WebXRInterfaceJS::set_display_refresh_rate(float p_refresh_rate) {
  170. godot_webxr_update_target_frame_rate(p_refresh_rate);
  171. }
  172. Array WebXRInterfaceJS::get_available_display_refresh_rates() const {
  173. Array ret;
  174. float *rates;
  175. int rate_count = godot_webxr_get_supported_frame_rates(&rates);
  176. if (rate_count > 0) {
  177. ret.resize(rate_count);
  178. for (int i = 0; i < rate_count; i++) {
  179. ret[i] = rates[i];
  180. }
  181. free(rates);
  182. }
  183. return ret;
  184. }
  185. Array WebXRInterfaceJS::get_supported_environment_blend_modes() {
  186. Array blend_modes;
  187. // The blend mode can't be changed, so return the current blend mode as the only supported one.
  188. blend_modes.push_back(environment_blend_mode);
  189. return blend_modes;
  190. }
  191. XRInterface::EnvironmentBlendMode WebXRInterfaceJS::get_environment_blend_mode() const {
  192. return environment_blend_mode;
  193. }
  194. bool WebXRInterfaceJS::set_environment_blend_mode(EnvironmentBlendMode p_new_environment_blend_mode) {
  195. if (environment_blend_mode == p_new_environment_blend_mode) {
  196. // Environment blend mode can't be changed, but we'll consider it a success to set it
  197. // to what it already is.
  198. return true;
  199. }
  200. return false;
  201. }
  202. void WebXRInterfaceJS::_set_environment_blend_mode(String p_blend_mode_string) {
  203. if (p_blend_mode_string == "opaque") {
  204. environment_blend_mode = XRInterface::XR_ENV_BLEND_MODE_OPAQUE;
  205. } else if (p_blend_mode_string == "additive") {
  206. environment_blend_mode = XRInterface::XR_ENV_BLEND_MODE_ADDITIVE;
  207. } else if (p_blend_mode_string == "alpha-blend") {
  208. environment_blend_mode = XRInterface::XR_ENV_BLEND_MODE_ALPHA_BLEND;
  209. } else {
  210. // Not all browsers can give us this information, so as a fallback,
  211. // we'll make some guesses about the blend mode.
  212. if (session_mode == "immersive-ar") {
  213. environment_blend_mode = XRInterface::XR_ENV_BLEND_MODE_ALPHA_BLEND;
  214. } else {
  215. environment_blend_mode = XRInterface::XR_ENV_BLEND_MODE_OPAQUE;
  216. }
  217. }
  218. }
  219. StringName WebXRInterfaceJS::get_name() const {
  220. return "WebXR";
  221. }
  222. uint32_t WebXRInterfaceJS::get_capabilities() const {
  223. return XRInterface::XR_STEREO | XRInterface::XR_MONO | XRInterface::XR_VR | XRInterface::XR_AR;
  224. }
  225. uint32_t WebXRInterfaceJS::get_view_count() {
  226. return godot_webxr_get_view_count();
  227. }
  228. bool WebXRInterfaceJS::is_initialized() const {
  229. return (initialized);
  230. }
  231. bool WebXRInterfaceJS::initialize() {
  232. XRServer *xr_server = XRServer::get_singleton();
  233. ERR_FAIL_NULL_V(xr_server, false);
  234. if (!initialized) {
  235. if (!godot_webxr_is_supported()) {
  236. return false;
  237. }
  238. if (requested_reference_space_types.size() == 0) {
  239. return false;
  240. }
  241. enabled_features.clear();
  242. // We must create a tracker for our head.
  243. head_transform.basis = Basis();
  244. head_transform.origin = Vector3();
  245. head_tracker.instantiate();
  246. head_tracker->set_tracker_type(XRServer::TRACKER_HEAD);
  247. head_tracker->set_tracker_name("head");
  248. head_tracker->set_tracker_desc("Players head");
  249. xr_server->add_tracker(head_tracker);
  250. // Make this our primary interface.
  251. xr_server->set_primary_interface(this);
  252. // Clear render_targetsize to make sure it gets reset to the new size.
  253. // Clearing in uninitialize() doesn't work because a frame can still be
  254. // rendered after it's called, which will fill render_targetsize again.
  255. render_targetsize.width = 0;
  256. render_targetsize.height = 0;
  257. initialized = true;
  258. godot_webxr_initialize(
  259. session_mode.utf8().get_data(),
  260. required_features.utf8().get_data(),
  261. optional_features.utf8().get_data(),
  262. requested_reference_space_types.utf8().get_data(),
  263. &_emwebxr_on_session_started,
  264. &_emwebxr_on_session_ended,
  265. &_emwebxr_on_session_failed,
  266. &_emwebxr_on_input_event,
  267. &_emwebxr_on_simple_event);
  268. };
  269. return true;
  270. }
  271. void WebXRInterfaceJS::uninitialize() {
  272. if (initialized) {
  273. XRServer *xr_server = XRServer::get_singleton();
  274. if (xr_server != nullptr) {
  275. if (head_tracker.is_valid()) {
  276. xr_server->remove_tracker(head_tracker);
  277. head_tracker.unref();
  278. }
  279. for (int i = 0; i < HAND_MAX; i++) {
  280. if (hand_trackers[i].is_valid()) {
  281. xr_server->remove_tracker(hand_trackers[i]);
  282. hand_trackers[i].unref();
  283. }
  284. }
  285. if (xr_server->get_primary_interface() == this) {
  286. // no longer our primary interface
  287. xr_server->set_primary_interface(nullptr);
  288. }
  289. }
  290. godot_webxr_uninitialize();
  291. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  292. if (texture_storage != nullptr) {
  293. for (KeyValue<unsigned int, RID> &E : texture_cache) {
  294. // Forcibly mark as not part of a render target so we can free it.
  295. GLES3::Texture *texture = texture_storage->get_texture(E.value);
  296. texture->is_render_target = false;
  297. texture_storage->texture_free(E.value);
  298. }
  299. }
  300. texture_cache.clear();
  301. reference_space_type.clear();
  302. enabled_features.clear();
  303. environment_blend_mode = XRInterface::XR_ENV_BLEND_MODE_OPAQUE;
  304. initialized = false;
  305. };
  306. }
  307. Dictionary WebXRInterfaceJS::get_system_info() {
  308. Dictionary dict;
  309. // TODO get actual information from WebXR to return here
  310. dict[SNAME("XRRuntimeName")] = String("WebXR");
  311. dict[SNAME("XRRuntimeVersion")] = String("");
  312. return dict;
  313. }
  314. Transform3D WebXRInterfaceJS::_js_matrix_to_transform(float *p_js_matrix) {
  315. Transform3D transform;
  316. transform.basis.rows[0].x = p_js_matrix[0];
  317. transform.basis.rows[1].x = p_js_matrix[1];
  318. transform.basis.rows[2].x = p_js_matrix[2];
  319. transform.basis.rows[0].y = p_js_matrix[4];
  320. transform.basis.rows[1].y = p_js_matrix[5];
  321. transform.basis.rows[2].y = p_js_matrix[6];
  322. transform.basis.rows[0].z = p_js_matrix[8];
  323. transform.basis.rows[1].z = p_js_matrix[9];
  324. transform.basis.rows[2].z = p_js_matrix[10];
  325. transform.origin.x = p_js_matrix[12];
  326. transform.origin.y = p_js_matrix[13];
  327. transform.origin.z = p_js_matrix[14];
  328. return transform;
  329. }
  330. Size2 WebXRInterfaceJS::get_render_target_size() {
  331. if (render_targetsize.width != 0 && render_targetsize.height != 0) {
  332. return render_targetsize;
  333. }
  334. int js_size[2];
  335. bool has_size = godot_webxr_get_render_target_size(js_size);
  336. if (!initialized || !has_size) {
  337. // As a temporary default (until WebXR is fully initialized), use the
  338. // window size.
  339. return DisplayServer::get_singleton()->window_get_size();
  340. }
  341. render_targetsize.width = (float)js_size[0];
  342. render_targetsize.height = (float)js_size[1];
  343. return render_targetsize;
  344. }
  345. Transform3D WebXRInterfaceJS::get_camera_transform() {
  346. Transform3D camera_transform;
  347. XRServer *xr_server = XRServer::get_singleton();
  348. ERR_FAIL_NULL_V(xr_server, camera_transform);
  349. if (initialized) {
  350. double world_scale = xr_server->get_world_scale();
  351. Transform3D _head_transform = head_transform;
  352. _head_transform.origin *= world_scale;
  353. camera_transform = (xr_server->get_reference_frame()) * _head_transform;
  354. }
  355. return camera_transform;
  356. }
  357. Transform3D WebXRInterfaceJS::get_transform_for_view(uint32_t p_view, const Transform3D &p_cam_transform) {
  358. XRServer *xr_server = XRServer::get_singleton();
  359. ERR_FAIL_NULL_V(xr_server, p_cam_transform);
  360. ERR_FAIL_COND_V(!initialized, p_cam_transform);
  361. float js_matrix[16];
  362. bool has_transform = godot_webxr_get_transform_for_view(p_view, js_matrix);
  363. if (!has_transform) {
  364. return p_cam_transform;
  365. }
  366. Transform3D transform_for_view = _js_matrix_to_transform(js_matrix);
  367. double world_scale = xr_server->get_world_scale();
  368. transform_for_view.origin *= world_scale;
  369. return p_cam_transform * xr_server->get_reference_frame() * transform_for_view;
  370. }
  371. Projection WebXRInterfaceJS::get_projection_for_view(uint32_t p_view, double p_aspect, double p_z_near, double p_z_far) {
  372. Projection view;
  373. ERR_FAIL_COND_V(!initialized, view);
  374. float js_matrix[16];
  375. bool has_projection = godot_webxr_get_projection_for_view(p_view, js_matrix);
  376. if (!has_projection) {
  377. return view;
  378. }
  379. int k = 0;
  380. for (int i = 0; i < 4; i++) {
  381. for (int j = 0; j < 4; j++) {
  382. view.columns[i][j] = js_matrix[k++];
  383. }
  384. }
  385. // Copied from godot_oculus_mobile's ovr_mobile_session.cpp
  386. view.columns[2][2] = -(p_z_far + p_z_near) / (p_z_far - p_z_near);
  387. view.columns[3][2] = -(2.0f * p_z_far * p_z_near) / (p_z_far - p_z_near);
  388. return view;
  389. }
  390. bool WebXRInterfaceJS::pre_draw_viewport(RID p_render_target) {
  391. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  392. if (texture_storage == nullptr) {
  393. return false;
  394. }
  395. // Cache the resources so we don't have to get them from JS twice.
  396. color_texture = _get_color_texture();
  397. depth_texture = _get_depth_texture();
  398. // Per the WebXR spec, it returns "opaque textures" to us, which may be the
  399. // same WebGLTexture object (which would be the same GLuint in C++) but
  400. // represent a different underlying resource (probably the next texture in
  401. // the XR device's swap chain). In order to render to this texture, we need
  402. // to re-attach it to the FBO, otherwise we get an "incomplete FBO" error.
  403. //
  404. // See: https://immersive-web.github.io/layers/#xropaquetextures
  405. //
  406. // So, even if the color and depth textures have the same GLuint as the last
  407. // frame, we need to re-attach them again.
  408. texture_storage->render_target_set_reattach_textures(p_render_target, true);
  409. return true;
  410. }
  411. Vector<BlitToScreen> WebXRInterfaceJS::post_draw_viewport(RID p_render_target, const Rect2 &p_screen_rect) {
  412. Vector<BlitToScreen> blit_to_screen;
  413. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  414. if (texture_storage == nullptr) {
  415. return blit_to_screen;
  416. }
  417. texture_storage->render_target_set_reattach_textures(p_render_target, false);
  418. return blit_to_screen;
  419. }
  420. RID WebXRInterfaceJS::_get_color_texture() {
  421. unsigned int texture_id = godot_webxr_get_color_texture();
  422. if (texture_id == 0) {
  423. return RID();
  424. }
  425. return _get_texture(texture_id);
  426. }
  427. RID WebXRInterfaceJS::_get_depth_texture() {
  428. unsigned int texture_id = godot_webxr_get_depth_texture();
  429. if (texture_id == 0) {
  430. return RID();
  431. }
  432. return _get_texture(texture_id);
  433. }
  434. RID WebXRInterfaceJS::_get_texture(unsigned int p_texture_id) {
  435. RBMap<unsigned int, RID>::Element *cache = texture_cache.find(p_texture_id);
  436. if (cache != nullptr) {
  437. return cache->get();
  438. }
  439. GLES3::TextureStorage *texture_storage = GLES3::TextureStorage::get_singleton();
  440. if (texture_storage == nullptr) {
  441. return RID();
  442. }
  443. uint32_t view_count = godot_webxr_get_view_count();
  444. Size2 texture_size = get_render_target_size();
  445. RID texture = texture_storage->texture_create_from_native_handle(
  446. view_count == 1 ? RS::TEXTURE_TYPE_2D : RS::TEXTURE_TYPE_LAYERED,
  447. Image::FORMAT_RGBA8,
  448. p_texture_id,
  449. (int)texture_size.width,
  450. (int)texture_size.height,
  451. 1,
  452. view_count);
  453. texture_cache.insert(p_texture_id, texture);
  454. return texture;
  455. }
  456. RID WebXRInterfaceJS::get_color_texture() {
  457. return color_texture;
  458. }
  459. RID WebXRInterfaceJS::get_depth_texture() {
  460. return depth_texture;
  461. }
  462. RID WebXRInterfaceJS::get_velocity_texture() {
  463. unsigned int texture_id = godot_webxr_get_velocity_texture();
  464. if (texture_id == 0) {
  465. return RID();
  466. }
  467. return _get_texture(texture_id);
  468. }
  469. void WebXRInterfaceJS::process() {
  470. if (initialized) {
  471. // Get the "head" position.
  472. float js_matrix[16];
  473. if (godot_webxr_get_transform_for_view(-1, js_matrix)) {
  474. head_transform = _js_matrix_to_transform(js_matrix);
  475. }
  476. if (head_tracker.is_valid()) {
  477. head_tracker->set_pose("default", head_transform, Vector3(), Vector3());
  478. }
  479. // Update all input sources.
  480. for (int i = 0; i < input_source_count; i++) {
  481. _update_input_source(i);
  482. }
  483. };
  484. }
  485. void WebXRInterfaceJS::_update_input_source(int p_input_source_id) {
  486. XRServer *xr_server = XRServer::get_singleton();
  487. ERR_FAIL_NULL(xr_server);
  488. InputSource &input_source = input_sources[p_input_source_id];
  489. float target_pose[16];
  490. int tmp_target_ray_mode;
  491. int touch_index;
  492. int has_grip_pose;
  493. float grip_pose[16];
  494. int has_standard_mapping;
  495. int button_count;
  496. float buttons[10];
  497. int axes_count;
  498. float axes[10];
  499. int has_hand_data;
  500. float hand_joints[WEBXR_HAND_JOINT_MAX * 16];
  501. float hand_radii[WEBXR_HAND_JOINT_MAX];
  502. input_source.active = godot_webxr_update_input_source(
  503. p_input_source_id,
  504. target_pose,
  505. &tmp_target_ray_mode,
  506. &touch_index,
  507. &has_grip_pose,
  508. grip_pose,
  509. &has_standard_mapping,
  510. &button_count,
  511. buttons,
  512. &axes_count,
  513. axes,
  514. &has_hand_data,
  515. hand_joints,
  516. hand_radii);
  517. if (!input_source.active) {
  518. if (input_source.tracker.is_valid()) {
  519. xr_server->remove_tracker(input_source.tracker);
  520. input_source.tracker.unref();
  521. }
  522. return;
  523. }
  524. input_source.target_ray_mode = (WebXRInterface::TargetRayMode)tmp_target_ray_mode;
  525. input_source.touch_index = touch_index;
  526. Ref<XRControllerTracker> &tracker = input_source.tracker;
  527. if (tracker.is_null()) {
  528. tracker.instantiate();
  529. StringName tracker_name;
  530. if (input_source.target_ray_mode == WebXRInterface::TargetRayMode::TARGET_RAY_MODE_SCREEN) {
  531. tracker_name = touch_names[touch_index];
  532. } else {
  533. tracker_name = tracker_names[p_input_source_id];
  534. }
  535. // Input source id's 0 and 1 are always the left and right hands.
  536. if (p_input_source_id < 2) {
  537. tracker->set_tracker_name(tracker_name);
  538. tracker->set_tracker_desc(p_input_source_id == 0 ? "Left hand controller" : "Right hand controller");
  539. tracker->set_tracker_hand(p_input_source_id == 0 ? XRPositionalTracker::TRACKER_HAND_LEFT : XRPositionalTracker::TRACKER_HAND_RIGHT);
  540. } else {
  541. tracker->set_tracker_name(tracker_name);
  542. tracker->set_tracker_desc(tracker_name);
  543. }
  544. xr_server->add_tracker(tracker);
  545. }
  546. Transform3D aim_transform = _js_matrix_to_transform(target_pose);
  547. tracker->set_pose(SceneStringName(default_), aim_transform, Vector3(), Vector3());
  548. tracker->set_pose(SNAME("aim"), aim_transform, Vector3(), Vector3());
  549. if (has_grip_pose) {
  550. tracker->set_pose(SNAME("grip"), _js_matrix_to_transform(grip_pose), Vector3(), Vector3());
  551. }
  552. for (int i = 0; i < button_count; i++) {
  553. StringName button_name = has_standard_mapping ? standard_button_names[i] : unknown_button_names[i];
  554. StringName button_pressure_name = has_standard_mapping ? standard_button_pressure_names[i] : unknown_button_pressure_names[i];
  555. float value = buttons[i];
  556. bool state = value > 0.0;
  557. tracker->set_input(button_name, state);
  558. tracker->set_input(button_pressure_name, value);
  559. }
  560. for (int i = 0; i < axes_count; i++) {
  561. StringName axis_name = has_standard_mapping ? standard_axis_names[i] : unknown_axis_names[i];
  562. float value = axes[i];
  563. if (has_standard_mapping && (i == 1 || i == 3)) {
  564. // Invert the Y-axis on thumbsticks and trackpads, in order to
  565. // match OpenXR and other XR platform SDKs.
  566. value = -value;
  567. }
  568. tracker->set_input(axis_name, value);
  569. }
  570. // Also create Vector2's for the thumbstick and trackpad when we have the
  571. // standard mapping.
  572. if (has_standard_mapping) {
  573. if (axes_count >= 2) {
  574. tracker->set_input(standard_vector_names[0], Vector2(axes[0], -axes[1]));
  575. }
  576. if (axes_count >= 4) {
  577. tracker->set_input(standard_vector_names[1], Vector2(axes[2], -axes[3]));
  578. }
  579. }
  580. if (input_source.target_ray_mode == WebXRInterface::TARGET_RAY_MODE_SCREEN) {
  581. if (touch_index < 5 && axes_count >= 2) {
  582. Vector2 joy_vector = Vector2(axes[0], axes[1]);
  583. Vector2 position = _get_screen_position_from_joy_vector(joy_vector);
  584. if (touches[touch_index].is_touching) {
  585. Vector2 delta = position - touches[touch_index].position;
  586. // If position has changed by at least 1 pixel, generate a drag event.
  587. if (abs(delta.x) >= 1.0 || abs(delta.y) >= 1.0) {
  588. Ref<InputEventScreenDrag> event;
  589. event.instantiate();
  590. event->set_index(touch_index);
  591. event->set_position(position);
  592. event->set_relative(delta);
  593. event->set_relative_screen_position(delta);
  594. Input::get_singleton()->parse_input_event(event);
  595. }
  596. }
  597. touches[touch_index].position = position;
  598. }
  599. }
  600. if (p_input_source_id < 2) {
  601. Ref<XRHandTracker> hand_tracker = hand_trackers[p_input_source_id];
  602. if (has_hand_data) {
  603. // Transform orientations to match Godot Humanoid skeleton.
  604. const Basis bone_adjustment(
  605. Vector3(-1.0, 0.0, 0.0),
  606. Vector3(0.0, 0.0, -1.0),
  607. Vector3(0.0, -1.0, 0.0));
  608. if (unlikely(hand_tracker.is_null())) {
  609. hand_tracker.instantiate();
  610. hand_tracker->set_tracker_hand(p_input_source_id == 0 ? XRPositionalTracker::TRACKER_HAND_LEFT : XRPositionalTracker::TRACKER_HAND_RIGHT);
  611. hand_tracker->set_tracker_name(p_input_source_id == 0 ? "/user/hand_tracker/left" : "/user/hand_tracker/right");
  612. // These flags always apply, since WebXR doesn't give us enough insight to be more fine grained.
  613. BitField<XRHandTracker::HandJointFlags> joint_flags(XRHandTracker::HAND_JOINT_FLAG_POSITION_VALID | XRHandTracker::HAND_JOINT_FLAG_ORIENTATION_VALID | XRHandTracker::HAND_JOINT_FLAG_POSITION_TRACKED | XRHandTracker::HAND_JOINT_FLAG_ORIENTATION_TRACKED);
  614. for (int godot_joint = 0; godot_joint < XRHandTracker::HAND_JOINT_MAX; godot_joint++) {
  615. hand_tracker->set_hand_joint_flags((XRHandTracker::HandJoint)godot_joint, joint_flags);
  616. }
  617. hand_trackers[p_input_source_id] = hand_tracker;
  618. xr_server->add_tracker(hand_tracker);
  619. }
  620. hand_tracker->set_has_tracking_data(true);
  621. for (int webxr_joint = 0; webxr_joint < WEBXR_HAND_JOINT_MAX; webxr_joint++) {
  622. XRHandTracker::HandJoint godot_joint = (XRHandTracker::HandJoint)(webxr_joint + 1);
  623. Transform3D joint_transform = _js_matrix_to_transform(hand_joints + (16 * webxr_joint));
  624. joint_transform.basis *= bone_adjustment;
  625. hand_tracker->set_hand_joint_transform(godot_joint, joint_transform);
  626. hand_tracker->set_hand_joint_radius(godot_joint, hand_radii[webxr_joint]);
  627. }
  628. // WebXR doesn't have a palm joint, so we calculate it by finding the middle of the middle finger metacarpal bone.
  629. {
  630. // Start by getting the middle finger metacarpal joint.
  631. // Note: 10 is the WebXR middle finger metacarpal joint.
  632. Transform3D palm_transform = _js_matrix_to_transform(hand_joints + (10 * 16));
  633. palm_transform.basis *= bone_adjustment;
  634. // Get the middle finger phalanx position.
  635. // Note: 11 is the WebXR middle finger phalanx proximal joint and 12 is the origin offset.
  636. const float *phalanx_pos = hand_joints + (11 * 16) + 12;
  637. Vector3 phalanx(phalanx_pos[0], phalanx_pos[1], phalanx_pos[2]);
  638. // Offset the palm half-way towards the phalanx joint.
  639. palm_transform.origin = (palm_transform.origin + phalanx) / 2.0;
  640. // Set the palm joint and the pose.
  641. hand_tracker->set_hand_joint_transform(XRHandTracker::HAND_JOINT_PALM, palm_transform);
  642. hand_tracker->set_pose("default", palm_transform, Vector3(), Vector3());
  643. }
  644. } else if (hand_tracker.is_valid()) {
  645. hand_tracker->set_has_tracking_data(false);
  646. hand_tracker->invalidate_pose("default");
  647. }
  648. }
  649. }
  650. void WebXRInterfaceJS::_on_input_event(int p_event_type, int p_input_source_id) {
  651. // Get the latest data for this input source. For transient input sources,
  652. // we may not have any data at all yet!
  653. _update_input_source(p_input_source_id);
  654. if (p_event_type == WEBXR_INPUT_EVENT_SELECTSTART || p_event_type == WEBXR_INPUT_EVENT_SELECTEND) {
  655. const InputSource &input_source = input_sources[p_input_source_id];
  656. if (input_source.target_ray_mode == WebXRInterface::TARGET_RAY_MODE_SCREEN) {
  657. int touch_index = input_source.touch_index;
  658. if (touch_index >= 0 && touch_index < 5) {
  659. touches[touch_index].is_touching = (p_event_type == WEBXR_INPUT_EVENT_SELECTSTART);
  660. Ref<InputEventScreenTouch> event;
  661. event.instantiate();
  662. event->set_index(touch_index);
  663. event->set_position(touches[touch_index].position);
  664. event->set_pressed(p_event_type == WEBXR_INPUT_EVENT_SELECTSTART);
  665. Input::get_singleton()->parse_input_event(event);
  666. }
  667. }
  668. }
  669. switch (p_event_type) {
  670. case WEBXR_INPUT_EVENT_SELECTSTART:
  671. emit_signal("selectstart", p_input_source_id);
  672. break;
  673. case WEBXR_INPUT_EVENT_SELECTEND:
  674. emit_signal("selectend", p_input_source_id);
  675. // Emit the 'select' event on our own (rather than intercepting the
  676. // one from JavaScript) so that we don't have to needlessly call
  677. // _update_input_source() a second time.
  678. emit_signal("select", p_input_source_id);
  679. break;
  680. case WEBXR_INPUT_EVENT_SQUEEZESTART:
  681. emit_signal("squeezestart", p_input_source_id);
  682. break;
  683. case WEBXR_INPUT_EVENT_SQUEEZEEND:
  684. emit_signal("squeezeend", p_input_source_id);
  685. // Again, we emit the 'squeeze' event on our own to avoid extra work.
  686. emit_signal("squeeze", p_input_source_id);
  687. break;
  688. }
  689. }
  690. Vector2 WebXRInterfaceJS::_get_screen_position_from_joy_vector(const Vector2 &p_joy_vector) {
  691. SceneTree *scene_tree = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop());
  692. if (!scene_tree) {
  693. return Vector2();
  694. }
  695. Window *viewport = scene_tree->get_root();
  696. Vector2 position_percentage((p_joy_vector.x + 1.0f) / 2.0f, ((p_joy_vector.y) + 1.0f) / 2.0f);
  697. Vector2 position = (Size2)viewport->get_size() * position_percentage;
  698. return position;
  699. }
  700. WebXRInterfaceJS::WebXRInterfaceJS() {
  701. initialized = false;
  702. session_mode = "inline";
  703. requested_reference_space_types = "local";
  704. }
  705. WebXRInterfaceJS::~WebXRInterfaceJS() {
  706. // and make sure we cleanup if we haven't already
  707. if (initialized) {
  708. uninitialize();
  709. };
  710. }
  711. #endif // WEB_ENABLED