openxr_api.cpp 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860
  1. /**************************************************************************/
  2. /* openxr_api.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 "openxr_api.h"
  31. #include "extensions/openxr_extension_wrapper_extension.h"
  32. #include "openxr_interface.h"
  33. #include "openxr_util.h"
  34. #include "core/config/engine.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/os/memory.h"
  37. #include "core/version.h"
  38. #ifdef TOOLS_ENABLED
  39. #include "editor/editor_settings.h"
  40. #endif
  41. // We need to have all the graphics API defines before the Vulkan or OpenGL
  42. // extensions are included, otherwise we'll only get one graphics API.
  43. #ifdef VULKAN_ENABLED
  44. #define XR_USE_GRAPHICS_API_VULKAN
  45. #endif
  46. #ifdef GLES3_ENABLED
  47. #ifdef ANDROID_ENABLED
  48. #define XR_USE_GRAPHICS_API_OPENGL_ES
  49. #include <EGL/egl.h>
  50. #include <EGL/eglext.h>
  51. #include <GLES3/gl3.h>
  52. #include <GLES3/gl3ext.h>
  53. #else
  54. #define XR_USE_GRAPHICS_API_OPENGL
  55. #endif // ANDROID_ENABLED
  56. #ifdef X11_ENABLED
  57. #include OPENGL_INCLUDE_H
  58. #define GL_GLEXT_PROTOTYPES 1
  59. #define GL3_PROTOTYPES 1
  60. #include "thirdparty/glad/glad/gl.h"
  61. #include "thirdparty/glad/glad/glx.h"
  62. #include <X11/Xlib.h>
  63. #endif // X11_ENABLED
  64. #endif // GLES_ENABLED
  65. #ifdef VULKAN_ENABLED
  66. #include "extensions/openxr_vulkan_extension.h"
  67. #endif
  68. #ifdef GLES3_ENABLED
  69. #include "extensions/openxr_opengl_extension.h"
  70. #endif
  71. #include "extensions/openxr_composition_layer_depth_extension.h"
  72. #include "extensions/openxr_fb_display_refresh_rate_extension.h"
  73. #include "extensions/openxr_fb_passthrough_extension_wrapper.h"
  74. #ifdef ANDROID_ENABLED
  75. #define OPENXR_LOADER_NAME "libopenxr_loader.so"
  76. #endif
  77. OpenXRAPI *OpenXRAPI::singleton = nullptr;
  78. Vector<OpenXRExtensionWrapper *> OpenXRAPI::registered_extension_wrappers;
  79. bool OpenXRAPI::openxr_is_enabled(bool p_check_run_in_editor) {
  80. // @TODO we need an overrule switch so we can force enable openxr, i.e run "godot --openxr_enabled"
  81. if (Engine::get_singleton()->is_editor_hint() && p_check_run_in_editor) {
  82. // Disabled for now, using XR inside of the editor we'll be working on during the coming months.
  83. return false;
  84. } else {
  85. if (XRServer::get_xr_mode() == XRServer::XRMODE_DEFAULT) {
  86. return GLOBAL_GET("xr/openxr/enabled");
  87. } else {
  88. return XRServer::get_xr_mode() == XRServer::XRMODE_ON;
  89. }
  90. }
  91. }
  92. String OpenXRAPI::get_default_action_map_resource_name() {
  93. String name = GLOBAL_GET("xr/openxr/default_action_map");
  94. return name;
  95. }
  96. String OpenXRAPI::get_error_string(XrResult result) {
  97. if (XR_SUCCEEDED(result)) {
  98. return String("Succeeded");
  99. }
  100. if (instance == XR_NULL_HANDLE) {
  101. Array args;
  102. args.push_back(Variant(result));
  103. return String("Error code {0}").format(args);
  104. }
  105. char resultString[XR_MAX_RESULT_STRING_SIZE];
  106. xrResultToString(instance, result, resultString);
  107. return String(resultString);
  108. }
  109. String OpenXRAPI::get_swapchain_format_name(int64_t p_swapchain_format) const {
  110. // This is rendering engine dependent...
  111. if (graphics_extension) {
  112. return graphics_extension->get_swapchain_format_name(p_swapchain_format);
  113. }
  114. return String("Swapchain format ") + String::num_int64(int64_t(p_swapchain_format));
  115. }
  116. bool OpenXRAPI::load_layer_properties() {
  117. // This queries additional layers that are available and can be initialized when we create our OpenXR instance
  118. if (layer_properties != nullptr) {
  119. // already retrieved this
  120. return true;
  121. }
  122. // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
  123. XrResult result = xrEnumerateApiLayerProperties(0, &num_layer_properties, nullptr);
  124. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of api layer properties");
  125. layer_properties = (XrApiLayerProperties *)memalloc(sizeof(XrApiLayerProperties) * num_layer_properties);
  126. ERR_FAIL_NULL_V(layer_properties, false);
  127. for (uint32_t i = 0; i < num_layer_properties; i++) {
  128. layer_properties[i].type = XR_TYPE_API_LAYER_PROPERTIES;
  129. layer_properties[i].next = nullptr;
  130. }
  131. result = xrEnumerateApiLayerProperties(num_layer_properties, &num_layer_properties, layer_properties);
  132. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate api layer properties");
  133. for (uint32_t i = 0; i < num_layer_properties; i++) {
  134. print_verbose(String("OpenXR: Found OpenXR layer ") + layer_properties[i].layerName);
  135. }
  136. return true;
  137. }
  138. bool OpenXRAPI::load_supported_extensions() {
  139. // This queries supported extensions that are available and can be initialized when we create our OpenXR instance
  140. if (supported_extensions != nullptr) {
  141. // already retrieved this
  142. return true;
  143. }
  144. // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
  145. XrResult result = xrEnumerateInstanceExtensionProperties(nullptr, 0, &num_supported_extensions, nullptr);
  146. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of extension properties");
  147. supported_extensions = (XrExtensionProperties *)memalloc(sizeof(XrExtensionProperties) * num_supported_extensions);
  148. ERR_FAIL_NULL_V(supported_extensions, false);
  149. // set our types
  150. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  151. supported_extensions[i].type = XR_TYPE_EXTENSION_PROPERTIES;
  152. supported_extensions[i].next = nullptr;
  153. }
  154. result = xrEnumerateInstanceExtensionProperties(nullptr, num_supported_extensions, &num_supported_extensions, supported_extensions);
  155. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate extension properties");
  156. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  157. print_verbose(String("OpenXR: Found OpenXR extension ") + supported_extensions[i].extensionName);
  158. }
  159. return true;
  160. }
  161. bool OpenXRAPI::is_extension_supported(const String &p_extension) const {
  162. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  163. if (supported_extensions[i].extensionName == p_extension) {
  164. return true;
  165. }
  166. }
  167. return false;
  168. }
  169. bool OpenXRAPI::is_extension_enabled(const String &p_extension) const {
  170. CharString extension = p_extension.ascii();
  171. for (int i = 0; i < enabled_extensions.size(); i++) {
  172. if (strcmp(enabled_extensions[i].ptr(), extension.ptr()) == 0) {
  173. return true;
  174. }
  175. }
  176. return false;
  177. }
  178. bool OpenXRAPI::is_top_level_path_supported(const String &p_toplevel_path) {
  179. String required_extension = OpenXRInteractionProfileMetaData::get_singleton()->get_top_level_extension(p_toplevel_path);
  180. // If unsupported is returned we likely have a misspelled interaction profile path in our action map. Always output that as an error.
  181. ERR_FAIL_COND_V_MSG(required_extension == XR_PATH_UNSUPPORTED_NAME, false, "OpenXR: Unsupported toplevel path " + p_toplevel_path);
  182. if (required_extension == "") {
  183. // no extension needed, core top level are always "supported", they just won't be used if not really supported
  184. return true;
  185. }
  186. if (!is_extension_enabled(required_extension)) {
  187. // It is very likely we have top level paths for which the extension is not available so don't flood the logs with unnecessary spam.
  188. print_verbose("OpenXR: Top level path " + p_toplevel_path + " requires extension " + required_extension);
  189. return false;
  190. }
  191. return true;
  192. }
  193. bool OpenXRAPI::is_interaction_profile_supported(const String &p_ip_path) {
  194. String required_extension = OpenXRInteractionProfileMetaData::get_singleton()->get_interaction_profile_extension(p_ip_path);
  195. // If unsupported is returned we likely have a misspelled interaction profile path in our action map. Always output that as an error.
  196. ERR_FAIL_COND_V_MSG(required_extension == XR_PATH_UNSUPPORTED_NAME, false, "OpenXR: Unsupported interaction profile " + p_ip_path);
  197. if (required_extension == "") {
  198. // no extension needed, core interaction profiles are always "supported", they just won't be used if not really supported
  199. return true;
  200. }
  201. if (!is_extension_enabled(required_extension)) {
  202. // It is very likely we have interaction profiles for which the extension is not available so don't flood the logs with unnecessary spam.
  203. print_verbose("OpenXR: Interaction profile " + p_ip_path + " requires extension " + required_extension);
  204. return false;
  205. }
  206. return true;
  207. }
  208. bool OpenXRAPI::interaction_profile_supports_io_path(const String &p_ip_path, const String &p_io_path) {
  209. if (!is_interaction_profile_supported(p_ip_path)) {
  210. return false;
  211. }
  212. const OpenXRInteractionProfileMetaData::IOPath *io_path = OpenXRInteractionProfileMetaData::get_singleton()->get_io_path(p_ip_path, p_io_path);
  213. // If the io_path is not part of our meta data we've likely got a misspelled name or a bad action map, report
  214. ERR_FAIL_NULL_V_MSG(io_path, false, "OpenXR: Unsupported io path " + String(p_ip_path) + String(p_io_path));
  215. if (io_path->openxr_extension_name == "") {
  216. // no extension needed, core io paths are always "supported", they just won't be used if not really supported
  217. return true;
  218. }
  219. if (!is_extension_enabled(io_path->openxr_extension_name)) {
  220. // It is very likely we have io paths for which the extension is not available so don't flood the logs with unnecessary spam.
  221. print_verbose("OpenXR: IO path " + String(p_ip_path) + String(p_io_path) + " requires extension " + io_path->openxr_extension_name);
  222. return false;
  223. }
  224. return true;
  225. }
  226. void OpenXRAPI::copy_string_to_char_buffer(const String p_string, char *p_buffer, int p_buffer_len) {
  227. CharString char_string = p_string.utf8();
  228. int len = char_string.length();
  229. if (len < p_buffer_len - 1) {
  230. // was having weird CI issues with strcpy so....
  231. memcpy(p_buffer, char_string.get_data(), len);
  232. p_buffer[len] = '\0';
  233. } else {
  234. memcpy(p_buffer, char_string.get_data(), p_buffer_len - 1);
  235. p_buffer[p_buffer_len - 1] = '\0';
  236. }
  237. }
  238. bool OpenXRAPI::create_instance() {
  239. // Create our OpenXR instance, this will query any registered extension wrappers for extensions we need to enable.
  240. // Append the extensions requested by the registered extension wrappers.
  241. HashMap<String, bool *> requested_extensions;
  242. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  243. const HashMap<String, bool *> &wrapper_request_extensions = wrapper->get_requested_extensions();
  244. // requested_extensions.insert(wrapper_request_extensions.begin(), wrapper_request_extensions.end());
  245. for (auto &requested_extension : wrapper_request_extensions) {
  246. requested_extensions[requested_extension.key] = requested_extension.value;
  247. }
  248. }
  249. // Check which extensions are supported
  250. enabled_extensions.clear();
  251. for (auto &requested_extension : requested_extensions) {
  252. if (!is_extension_supported(requested_extension.key)) {
  253. if (requested_extension.value == nullptr) {
  254. // nullptr means this is a manditory extension so we fail
  255. ERR_FAIL_V_MSG(false, String("OpenXR: OpenXR Runtime does not support ") + requested_extension.key + String(" extension!"));
  256. } else {
  257. // set this extension as not supported
  258. *requested_extension.value = false;
  259. }
  260. } else if (requested_extension.value != nullptr) {
  261. // set this extension as supported
  262. *requested_extension.value = true;
  263. // and record that we want to enable it
  264. enabled_extensions.push_back(requested_extension.key.ascii());
  265. } else {
  266. // record that we want to enable this
  267. enabled_extensions.push_back(requested_extension.key.ascii());
  268. }
  269. }
  270. Vector<const char *> extension_ptrs;
  271. for (int i = 0; i < enabled_extensions.size(); i++) {
  272. print_verbose(String("OpenXR: Enabling extension ") + String(enabled_extensions[i]));
  273. extension_ptrs.push_back(enabled_extensions[i].get_data());
  274. }
  275. // Get our project name
  276. String project_name = GLOBAL_GET("application/config/name");
  277. // Create our OpenXR instance
  278. XrApplicationInfo application_info{
  279. "", // applicationName, we'll set this down below
  280. 1, // applicationVersion, we don't currently have this
  281. "Godot Game Engine", // engineName
  282. VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_PATCH, // engineVersion 4.0 -> 40000, 4.0.1 -> 40001, 4.1 -> 40100, etc.
  283. XR_CURRENT_API_VERSION // apiVersion
  284. };
  285. void *next_pointer = nullptr;
  286. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  287. void *np = wrapper->set_instance_create_info_and_get_next_pointer(next_pointer);
  288. if (np != nullptr) {
  289. next_pointer = np;
  290. }
  291. }
  292. XrInstanceCreateInfo instance_create_info = {
  293. XR_TYPE_INSTANCE_CREATE_INFO, // type
  294. next_pointer, // next
  295. 0, // createFlags
  296. application_info, // applicationInfo
  297. 0, // enabledApiLayerCount, need to find out if we need support for this?
  298. nullptr, // enabledApiLayerNames
  299. uint32_t(extension_ptrs.size()), // enabledExtensionCount
  300. extension_ptrs.ptr() // enabledExtensionNames
  301. };
  302. copy_string_to_char_buffer(project_name, instance_create_info.applicationInfo.applicationName, XR_MAX_APPLICATION_NAME_SIZE);
  303. XrResult result = xrCreateInstance(&instance_create_info, &instance);
  304. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "Failed to create XR instance.");
  305. // from this point on we can use get_error_string to get more info about our errors...
  306. XrInstanceProperties instanceProps = {
  307. XR_TYPE_INSTANCE_PROPERTIES, // type;
  308. nullptr, // next
  309. 0, // runtimeVersion, from here will be set by our get call
  310. "" // runtimeName
  311. };
  312. OPENXR_API_INIT_XR_FUNC_V(xrGetInstanceProperties);
  313. result = xrGetInstanceProperties(instance, &instanceProps);
  314. if (XR_FAILED(result)) {
  315. // not fatal probably
  316. print_line("OpenXR: Failed to get XR instance properties [", get_error_string(result), "]");
  317. runtime_name = "";
  318. runtime_version = "";
  319. } else {
  320. runtime_name = instanceProps.runtimeName;
  321. runtime_version = OpenXRUtil::make_xr_version_string(instanceProps.runtimeVersion);
  322. print_line("OpenXR: Running on OpenXR runtime: ", runtime_name, " ", runtime_version);
  323. }
  324. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  325. wrapper->on_instance_created(instance);
  326. }
  327. return true;
  328. }
  329. bool OpenXRAPI::get_system_info() {
  330. // Retrieve basic OpenXR system info based on the form factor we desire
  331. // Retrieve the system for our form factor, fails if form factor is not available
  332. XrSystemGetInfo system_get_info = {
  333. XR_TYPE_SYSTEM_GET_INFO, // type;
  334. nullptr, // next
  335. form_factor // formFactor
  336. };
  337. XrResult result = xrGetSystem(instance, &system_get_info, &system_id);
  338. if (XR_FAILED(result)) {
  339. print_line("OpenXR: Failed to get system for our form factor [", get_error_string(result), "]");
  340. return false;
  341. }
  342. // obtain info about our system, writing this out completely to make CI on Linux happy..
  343. void *next_pointer = nullptr;
  344. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  345. void *np = wrapper->set_system_properties_and_get_next_pointer(next_pointer);
  346. if (np != nullptr) {
  347. next_pointer = np;
  348. }
  349. }
  350. XrSystemProperties system_properties = {
  351. XR_TYPE_SYSTEM_PROPERTIES, // type
  352. next_pointer, // next
  353. 0, // systemId, from here will be set by our get call
  354. 0, // vendorId
  355. "", // systemName
  356. {
  357. 0, // maxSwapchainImageHeight
  358. 0, // maxSwapchainImageWidth
  359. 0, // maxLayerCount
  360. }, // graphicsProperties
  361. {
  362. false, // orientationTracking
  363. false // positionTracking
  364. } // trackingProperties
  365. };
  366. result = xrGetSystemProperties(instance, system_id, &system_properties);
  367. if (XR_FAILED(result)) {
  368. print_line("OpenXR: Failed to get System properties [", get_error_string(result), "]");
  369. return false;
  370. }
  371. // remember this state, we'll use it later
  372. system_name = String(system_properties.systemName);
  373. vendor_id = system_properties.vendorId;
  374. graphics_properties = system_properties.graphicsProperties;
  375. tracking_properties = system_properties.trackingProperties;
  376. return true;
  377. }
  378. bool OpenXRAPI::load_supported_view_configuration_types() {
  379. // This queries the supported configuration types, likely there will only be one choosing between Mono (phone AR) and Stereo (HMDs)
  380. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  381. if (supported_view_configuration_types != nullptr) {
  382. // free previous results
  383. memfree(supported_view_configuration_types);
  384. supported_view_configuration_types = nullptr;
  385. }
  386. XrResult result = xrEnumerateViewConfigurations(instance, system_id, 0, &num_view_configuration_types, nullptr);
  387. if (XR_FAILED(result)) {
  388. print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]");
  389. return false;
  390. }
  391. supported_view_configuration_types = (XrViewConfigurationType *)memalloc(sizeof(XrViewConfigurationType) * num_view_configuration_types);
  392. ERR_FAIL_NULL_V(supported_view_configuration_types, false);
  393. result = xrEnumerateViewConfigurations(instance, system_id, num_view_configuration_types, &num_view_configuration_types, supported_view_configuration_types);
  394. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerateview configurations");
  395. for (uint32_t i = 0; i < num_view_configuration_types; i++) {
  396. print_verbose(String("OpenXR: Found supported view configuration ") + OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[i]));
  397. }
  398. return true;
  399. }
  400. bool OpenXRAPI::load_supported_environmental_blend_modes() {
  401. // This queries the supported environmental blend modes.
  402. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  403. if (supported_environment_blend_modes != nullptr) {
  404. // free previous results
  405. memfree(supported_environment_blend_modes);
  406. supported_environment_blend_modes = nullptr;
  407. num_supported_environment_blend_modes = 0;
  408. }
  409. XrResult result = xrEnumerateEnvironmentBlendModes(instance, system_id, view_configuration, 0, &num_supported_environment_blend_modes, nullptr);
  410. if (XR_FAILED(result)) {
  411. print_line("OpenXR: Failed to get supported environmental blend mode count [", get_error_string(result), "]");
  412. return false;
  413. }
  414. supported_environment_blend_modes = (XrEnvironmentBlendMode *)memalloc(sizeof(XrEnvironmentBlendMode) * num_supported_environment_blend_modes);
  415. ERR_FAIL_NULL_V(supported_environment_blend_modes, false);
  416. result = xrEnumerateEnvironmentBlendModes(instance, system_id, view_configuration, num_supported_environment_blend_modes, &num_supported_environment_blend_modes, supported_environment_blend_modes);
  417. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate environmental blend modes");
  418. for (uint32_t i = 0; i < num_supported_environment_blend_modes; i++) {
  419. print_verbose(String("OpenXR: Found environmental blend mode ") + OpenXRUtil::get_environment_blend_mode_name(supported_environment_blend_modes[i]));
  420. }
  421. return true;
  422. }
  423. bool OpenXRAPI::is_view_configuration_supported(XrViewConfigurationType p_configuration_type) const {
  424. ERR_FAIL_NULL_V(supported_view_configuration_types, false);
  425. for (uint32_t i = 0; i < num_view_configuration_types; i++) {
  426. if (supported_view_configuration_types[i] == p_configuration_type) {
  427. return true;
  428. }
  429. }
  430. return false;
  431. }
  432. bool OpenXRAPI::load_supported_view_configuration_views(XrViewConfigurationType p_configuration_type) {
  433. // This loads our view configuration for each view so for a stereo HMD, we'll get two entries (that are likely identical)
  434. // The returned data supplies us with the recommended render target size
  435. if (!is_view_configuration_supported(p_configuration_type)) {
  436. print_line("OpenXR: View configuration ", OpenXRUtil::get_view_configuration_name(view_configuration), " is not supported.");
  437. return false;
  438. }
  439. if (view_configuration_views != nullptr) {
  440. // free previous results
  441. memfree(view_configuration_views);
  442. view_configuration_views = nullptr;
  443. }
  444. XrResult result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, 0, &view_count, nullptr);
  445. if (XR_FAILED(result)) {
  446. print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]");
  447. return false;
  448. }
  449. view_configuration_views = (XrViewConfigurationView *)memalloc(sizeof(XrViewConfigurationView) * view_count);
  450. ERR_FAIL_NULL_V(view_configuration_views, false);
  451. for (uint32_t i = 0; i < view_count; i++) {
  452. view_configuration_views[i].type = XR_TYPE_VIEW_CONFIGURATION_VIEW;
  453. view_configuration_views[i].next = nullptr;
  454. }
  455. result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, view_count, &view_count, view_configuration_views);
  456. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate view configurations");
  457. for (uint32_t i = 0; i < view_count; i++) {
  458. print_verbose("OpenXR: Found supported view configuration view");
  459. print_verbose(String(" - width: ") + itos(view_configuration_views[i].maxImageRectWidth));
  460. print_verbose(String(" - height: ") + itos(view_configuration_views[i].maxImageRectHeight));
  461. print_verbose(String(" - sample count: ") + itos(view_configuration_views[i].maxSwapchainSampleCount));
  462. print_verbose(String(" - recommended render width: ") + itos(view_configuration_views[i].recommendedImageRectWidth));
  463. print_verbose(String(" - recommended render height: ") + itos(view_configuration_views[i].recommendedImageRectHeight));
  464. print_verbose(String(" - recommended render sample count: ") + itos(view_configuration_views[i].recommendedSwapchainSampleCount));
  465. }
  466. return true;
  467. }
  468. void OpenXRAPI::destroy_instance() {
  469. if (view_configuration_views != nullptr) {
  470. memfree(view_configuration_views);
  471. view_configuration_views = nullptr;
  472. }
  473. if (supported_view_configuration_types != nullptr) {
  474. memfree(supported_view_configuration_types);
  475. supported_view_configuration_types = nullptr;
  476. }
  477. if (supported_environment_blend_modes != nullptr) {
  478. memfree(supported_environment_blend_modes);
  479. supported_environment_blend_modes = nullptr;
  480. num_supported_environment_blend_modes = 0;
  481. }
  482. if (instance != XR_NULL_HANDLE) {
  483. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  484. wrapper->on_instance_destroyed();
  485. }
  486. xrDestroyInstance(instance);
  487. instance = XR_NULL_HANDLE;
  488. }
  489. enabled_extensions.clear();
  490. if (graphics_extension != nullptr) {
  491. unregister_extension_wrapper(graphics_extension);
  492. memdelete(graphics_extension);
  493. graphics_extension = nullptr;
  494. }
  495. }
  496. bool OpenXRAPI::create_session() {
  497. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  498. ERR_FAIL_COND_V(session != XR_NULL_HANDLE, false);
  499. void *next_pointer = nullptr;
  500. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  501. void *np = wrapper->set_session_create_and_get_next_pointer(next_pointer);
  502. if (np != nullptr) {
  503. next_pointer = np;
  504. }
  505. }
  506. XrSessionCreateInfo session_create_info = {
  507. XR_TYPE_SESSION_CREATE_INFO, // type
  508. next_pointer, // next
  509. 0, // createFlags
  510. system_id // systemId
  511. };
  512. XrResult result = xrCreateSession(instance, &session_create_info, &session);
  513. if (XR_FAILED(result)) {
  514. print_line("OpenXR: Failed to create session [", get_error_string(result), "]");
  515. return false;
  516. }
  517. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  518. wrapper->on_session_created(session);
  519. }
  520. return true;
  521. }
  522. bool OpenXRAPI::load_supported_reference_spaces() {
  523. // loads the supported reference spaces for our OpenXR session
  524. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  525. if (supported_reference_spaces != nullptr) {
  526. // free previous results
  527. memfree(supported_reference_spaces);
  528. supported_reference_spaces = nullptr;
  529. }
  530. XrResult result = xrEnumerateReferenceSpaces(session, 0, &num_reference_spaces, nullptr);
  531. if (XR_FAILED(result)) {
  532. print_line("OpenXR: Failed to get reference space count [", get_error_string(result), "]");
  533. return false;
  534. }
  535. supported_reference_spaces = (XrReferenceSpaceType *)memalloc(sizeof(XrReferenceSpaceType) * num_reference_spaces);
  536. ERR_FAIL_NULL_V(supported_reference_spaces, false);
  537. result = xrEnumerateReferenceSpaces(session, num_reference_spaces, &num_reference_spaces, supported_reference_spaces);
  538. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate reference spaces");
  539. for (uint32_t i = 0; i < num_reference_spaces; i++) {
  540. print_verbose(String("OpenXR: Found supported reference space ") + OpenXRUtil::get_reference_space_name(supported_reference_spaces[i]));
  541. }
  542. return true;
  543. }
  544. bool OpenXRAPI::is_reference_space_supported(XrReferenceSpaceType p_reference_space) {
  545. ERR_FAIL_NULL_V(supported_reference_spaces, false);
  546. for (uint32_t i = 0; i < num_reference_spaces; i++) {
  547. if (supported_reference_spaces[i] == p_reference_space) {
  548. return true;
  549. }
  550. }
  551. return false;
  552. }
  553. bool OpenXRAPI::setup_spaces() {
  554. XrResult result;
  555. XrPosef identityPose = {
  556. { 0.0, 0.0, 0.0, 1.0 },
  557. { 0.0, 0.0, 0.0 }
  558. };
  559. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  560. // create play space
  561. {
  562. if (!is_reference_space_supported(reference_space)) {
  563. print_line("OpenXR: reference space ", OpenXRUtil::get_reference_space_name(reference_space), " is not supported.");
  564. return false;
  565. }
  566. XrReferenceSpaceCreateInfo play_space_create_info = {
  567. XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
  568. nullptr, // next
  569. reference_space, // referenceSpaceType
  570. identityPose // poseInReferenceSpace
  571. };
  572. result = xrCreateReferenceSpace(session, &play_space_create_info, &play_space);
  573. if (XR_FAILED(result)) {
  574. print_line("OpenXR: Failed to create play space [", get_error_string(result), "]");
  575. return false;
  576. }
  577. }
  578. // create view space
  579. {
  580. if (!is_reference_space_supported(XR_REFERENCE_SPACE_TYPE_VIEW)) {
  581. print_line("OpenXR: reference space XR_REFERENCE_SPACE_TYPE_VIEW is not supported.");
  582. return false;
  583. }
  584. XrReferenceSpaceCreateInfo view_space_create_info = {
  585. XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
  586. nullptr, // next
  587. XR_REFERENCE_SPACE_TYPE_VIEW, // referenceSpaceType
  588. identityPose // poseInReferenceSpace
  589. };
  590. result = xrCreateReferenceSpace(session, &view_space_create_info, &view_space);
  591. if (XR_FAILED(result)) {
  592. print_line("OpenXR: Failed to create view space [", get_error_string(result), "]");
  593. return false;
  594. }
  595. }
  596. return true;
  597. }
  598. bool OpenXRAPI::load_supported_swapchain_formats() {
  599. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  600. if (supported_swapchain_formats != nullptr) {
  601. // free previous results
  602. memfree(supported_swapchain_formats);
  603. supported_swapchain_formats = nullptr;
  604. }
  605. XrResult result = xrEnumerateSwapchainFormats(session, 0, &num_swapchain_formats, nullptr);
  606. if (XR_FAILED(result)) {
  607. print_line("OpenXR: Failed to get swapchain format count [", get_error_string(result), "]");
  608. return false;
  609. }
  610. supported_swapchain_formats = (int64_t *)memalloc(sizeof(int64_t) * num_swapchain_formats);
  611. ERR_FAIL_NULL_V(supported_swapchain_formats, false);
  612. result = xrEnumerateSwapchainFormats(session, num_swapchain_formats, &num_swapchain_formats, supported_swapchain_formats);
  613. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate swapchain formats");
  614. for (uint32_t i = 0; i < num_swapchain_formats; i++) {
  615. print_verbose(String("OpenXR: Found supported swapchain format ") + get_swapchain_format_name(supported_swapchain_formats[i]));
  616. }
  617. return true;
  618. }
  619. bool OpenXRAPI::is_swapchain_format_supported(int64_t p_swapchain_format) {
  620. ERR_FAIL_NULL_V(supported_swapchain_formats, false);
  621. for (uint32_t i = 0; i < num_swapchain_formats; i++) {
  622. if (supported_swapchain_formats[i] == p_swapchain_format) {
  623. return true;
  624. }
  625. }
  626. return false;
  627. }
  628. bool OpenXRAPI::create_swapchains() {
  629. ERR_FAIL_NULL_V(graphics_extension, false);
  630. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  631. /*
  632. TODO: We need to improve on this, for now we're taking our old approach of creating our main swapchains and substituting
  633. those for the ones Godot normally creates.
  634. This however means we can only use swapchains for our main XR view.
  635. It would have been nicer if we could override the swapchain creation in Godot with ours but we have a timing issue here.
  636. We can't create XR swapchains until after our XR session is fully instantiated, yet Godot creates its swapchain much earlier.
  637. Also Godot only creates a swapchain for the main output.
  638. OpenXR will require us to create swapchains as the render target for additional viewports if we want to use the layer system
  639. to optimize text rendering and background rendering as OpenXR may choose to re-use the results for reprojection while we're
  640. already rendering the next frame.
  641. Finally an area we need to expand upon is that Foveated rendering is only enabled for the swap chain we create,
  642. as we render 3D content into internal buffers that are copied into the swapchain, we do now have (basic) VRS support
  643. */
  644. Size2 recommended_size = get_recommended_target_size();
  645. // We start with our color swapchain...
  646. {
  647. // Build a vector with swapchain formats we want to use, from best fit to worst
  648. Vector<int64_t> usable_swapchain_formats;
  649. int64_t swapchain_format_to_use = 0;
  650. graphics_extension->get_usable_swapchain_formats(usable_swapchain_formats);
  651. // now find out which one is supported
  652. for (int i = 0; i < usable_swapchain_formats.size() && swapchain_format_to_use == 0; i++) {
  653. if (is_swapchain_format_supported(usable_swapchain_formats[i])) {
  654. swapchain_format_to_use = usable_swapchain_formats[i];
  655. }
  656. }
  657. if (swapchain_format_to_use == 0) {
  658. swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best...
  659. print_line("Couldn't find usable color swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead.");
  660. } else {
  661. print_verbose(String("Using color swap chain format:") + get_swapchain_format_name(swapchain_format_to_use));
  662. }
  663. if (!create_swapchain(XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain, &swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data)) {
  664. return false;
  665. }
  666. }
  667. views = (XrView *)memalloc(sizeof(XrView) * view_count);
  668. ERR_FAIL_NULL_V_MSG(views, false, "OpenXR Couldn't allocate memory for views");
  669. projection_views = (XrCompositionLayerProjectionView *)memalloc(sizeof(XrCompositionLayerProjectionView) * view_count);
  670. ERR_FAIL_NULL_V_MSG(projection_views, false, "OpenXR Couldn't allocate memory for projection views");
  671. // We create our depth swapchain if:
  672. // - we've enabled submitting depth buffer
  673. // - we support our depth layer extension
  674. // - we have our spacewarp extension (not yet implemented)
  675. if (submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available()) {
  676. // Build a vector with swapchain formats we want to use, from best fit to worst
  677. Vector<int64_t> usable_swapchain_formats;
  678. int64_t swapchain_format_to_use = 0;
  679. graphics_extension->get_usable_depth_formats(usable_swapchain_formats);
  680. // now find out which one is supported
  681. for (int i = 0; i < usable_swapchain_formats.size() && swapchain_format_to_use == 0; i++) {
  682. if (is_swapchain_format_supported(usable_swapchain_formats[i])) {
  683. swapchain_format_to_use = usable_swapchain_formats[i];
  684. }
  685. }
  686. if (swapchain_format_to_use == 0) {
  687. print_line("Couldn't find usable depth swap chain format, depth buffer will not be submitted.");
  688. } else {
  689. print_verbose(String("Using depth swap chain format:") + get_swapchain_format_name(swapchain_format_to_use));
  690. // Note, if VK_FORMAT_D32_SFLOAT is used here but we're using the forward+ renderer, we should probably output a warning.
  691. if (!create_swapchain(XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, swapchain_format_to_use, recommended_size.width, recommended_size.height, view_configuration_views[0].recommendedSwapchainSampleCount, view_count, swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain, &swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain_graphics_data)) {
  692. return false;
  693. }
  694. depth_views = (XrCompositionLayerDepthInfoKHR *)memalloc(sizeof(XrCompositionLayerDepthInfoKHR) * view_count);
  695. ERR_FAIL_NULL_V_MSG(depth_views, false, "OpenXR Couldn't allocate memory for depth views");
  696. }
  697. }
  698. // We create our velocity swapchain if:
  699. // - we have our spacewarp extension (not yet implemented)
  700. {
  701. // TBD
  702. }
  703. for (uint32_t i = 0; i < view_count; i++) {
  704. views[i].type = XR_TYPE_VIEW;
  705. views[i].next = nullptr;
  706. projection_views[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
  707. projection_views[i].next = nullptr;
  708. projection_views[i].subImage.swapchain = swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain;
  709. projection_views[i].subImage.imageArrayIndex = i;
  710. projection_views[i].subImage.imageRect.offset.x = 0;
  711. projection_views[i].subImage.imageRect.offset.y = 0;
  712. projection_views[i].subImage.imageRect.extent.width = recommended_size.width;
  713. projection_views[i].subImage.imageRect.extent.height = recommended_size.height;
  714. if (submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available() && depth_views) {
  715. projection_views[i].next = &depth_views[i];
  716. depth_views[i].type = XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR;
  717. depth_views[i].next = nullptr;
  718. depth_views[i].subImage.swapchain = swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain;
  719. depth_views[i].subImage.imageArrayIndex = i;
  720. depth_views[i].subImage.imageRect.offset.x = 0;
  721. depth_views[i].subImage.imageRect.offset.y = 0;
  722. depth_views[i].subImage.imageRect.extent.width = recommended_size.width;
  723. depth_views[i].subImage.imageRect.extent.height = recommended_size.height;
  724. depth_views[i].minDepth = 0.0;
  725. depth_views[i].maxDepth = 1.0;
  726. depth_views[i].nearZ = 0.01; // Near and far Z will be set to the correct values in fill_projection_matrix
  727. depth_views[i].farZ = 100.0;
  728. }
  729. };
  730. return true;
  731. };
  732. void OpenXRAPI::destroy_session() {
  733. if (running && session != XR_NULL_HANDLE) {
  734. xrEndSession(session);
  735. }
  736. if (graphics_extension) {
  737. graphics_extension->cleanup_swapchain_graphics_data(&swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data);
  738. }
  739. if (views != nullptr) {
  740. memfree(views);
  741. views = nullptr;
  742. }
  743. if (projection_views != nullptr) {
  744. memfree(projection_views);
  745. projection_views = nullptr;
  746. }
  747. if (depth_views != nullptr) {
  748. memfree(depth_views);
  749. depth_views = nullptr;
  750. }
  751. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  752. if (swapchains[i].swapchain != XR_NULL_HANDLE) {
  753. xrDestroySwapchain(swapchains[i].swapchain);
  754. swapchains[i].swapchain = XR_NULL_HANDLE;
  755. }
  756. }
  757. if (supported_swapchain_formats != nullptr) {
  758. memfree(supported_swapchain_formats);
  759. supported_swapchain_formats = nullptr;
  760. }
  761. // destroy our spaces
  762. if (play_space != XR_NULL_HANDLE) {
  763. xrDestroySpace(play_space);
  764. play_space = XR_NULL_HANDLE;
  765. }
  766. if (view_space != XR_NULL_HANDLE) {
  767. xrDestroySpace(view_space);
  768. view_space = XR_NULL_HANDLE;
  769. }
  770. if (supported_reference_spaces != nullptr) {
  771. // free previous results
  772. memfree(supported_reference_spaces);
  773. supported_reference_spaces = nullptr;
  774. }
  775. if (session != XR_NULL_HANDLE) {
  776. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  777. wrapper->on_session_destroyed();
  778. }
  779. xrDestroySession(session);
  780. session = XR_NULL_HANDLE;
  781. }
  782. }
  783. bool OpenXRAPI::create_swapchain(XrSwapchainUsageFlags p_usage_flags, int64_t p_swapchain_format, uint32_t p_width, uint32_t p_height, uint32_t p_sample_count, uint32_t p_array_size, XrSwapchain &r_swapchain, void **r_swapchain_graphics_data) {
  784. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  785. ERR_FAIL_NULL_V(graphics_extension, false);
  786. XrResult result;
  787. void *next_pointer = nullptr;
  788. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  789. void *np = wrapper->set_swapchain_create_info_and_get_next_pointer(next_pointer);
  790. if (np != nullptr) {
  791. next_pointer = np;
  792. }
  793. }
  794. XrSwapchainCreateInfo swapchain_create_info = {
  795. XR_TYPE_SWAPCHAIN_CREATE_INFO, // type
  796. next_pointer, // next
  797. 0, // createFlags
  798. p_usage_flags, // usageFlags
  799. p_swapchain_format, // format
  800. p_sample_count, // sampleCount
  801. p_width, // width
  802. p_height, // height
  803. 1, // faceCount
  804. p_array_size, // arraySize
  805. 1 // mipCount
  806. };
  807. XrSwapchain new_swapchain;
  808. result = xrCreateSwapchain(session, &swapchain_create_info, &new_swapchain);
  809. if (XR_FAILED(result)) {
  810. print_line("OpenXR: Failed to get swapchain [", get_error_string(result), "]");
  811. return false;
  812. }
  813. if (!graphics_extension->get_swapchain_image_data(new_swapchain, p_swapchain_format, p_width, p_height, p_sample_count, p_array_size, r_swapchain_graphics_data)) {
  814. xrDestroySwapchain(new_swapchain);
  815. return false;
  816. }
  817. r_swapchain = new_swapchain;
  818. return true;
  819. }
  820. bool OpenXRAPI::on_state_idle() {
  821. print_verbose("On state idle");
  822. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  823. wrapper->on_state_idle();
  824. }
  825. return true;
  826. }
  827. bool OpenXRAPI::on_state_ready() {
  828. print_verbose("On state ready");
  829. // begin session
  830. XrSessionBeginInfo session_begin_info = {
  831. XR_TYPE_SESSION_BEGIN_INFO, // type
  832. nullptr, // next
  833. view_configuration // primaryViewConfigurationType
  834. };
  835. XrResult result = xrBeginSession(session, &session_begin_info);
  836. if (XR_FAILED(result)) {
  837. print_line("OpenXR: Failed to begin session [", get_error_string(result), "]");
  838. return false;
  839. }
  840. // This is when we create our swapchain, this can be a "long" time after Godot finishes, we can deal with this for now
  841. // but once we want to provide Viewports for additional layers where OpenXR requires us to create further swapchains,
  842. // we'll be creating those viewport WAY before we reach this point.
  843. // We may need to implement a wait in our init in main.cpp polling our events until the session is ready.
  844. // That will be very very ugly
  845. // The other possibility is to create a separate OpenXRViewport type specifically for this goal as part of our OpenXR module
  846. if (!create_swapchains()) {
  847. return false;
  848. }
  849. // we're running
  850. running = true;
  851. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  852. wrapper->on_state_ready();
  853. }
  854. if (xr_interface) {
  855. xr_interface->on_state_ready();
  856. }
  857. // TODO Tell android
  858. return true;
  859. }
  860. bool OpenXRAPI::on_state_synchronized() {
  861. print_verbose("On state synchronized");
  862. // Just in case, see if we already have active trackers...
  863. List<RID> trackers;
  864. tracker_owner.get_owned_list(&trackers);
  865. for (int i = 0; i < trackers.size(); i++) {
  866. tracker_check_profile(trackers[i]);
  867. }
  868. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  869. wrapper->on_state_synchronized();
  870. }
  871. return true;
  872. }
  873. bool OpenXRAPI::on_state_visible() {
  874. print_verbose("On state visible");
  875. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  876. wrapper->on_state_visible();
  877. }
  878. if (xr_interface) {
  879. xr_interface->on_state_visible();
  880. }
  881. return true;
  882. }
  883. bool OpenXRAPI::on_state_focused() {
  884. print_verbose("On state focused");
  885. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  886. wrapper->on_state_focused();
  887. }
  888. if (xr_interface) {
  889. xr_interface->on_state_focused();
  890. }
  891. return true;
  892. }
  893. bool OpenXRAPI::on_state_stopping() {
  894. print_verbose("On state stopping");
  895. if (xr_interface) {
  896. xr_interface->on_state_stopping();
  897. }
  898. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  899. wrapper->on_state_stopping();
  900. }
  901. if (running) {
  902. XrResult result = xrEndSession(session);
  903. if (XR_FAILED(result)) {
  904. // we only report this..
  905. print_line("OpenXR: Failed to end session [", get_error_string(result), "]");
  906. }
  907. running = false;
  908. }
  909. // TODO further cleanup
  910. return true;
  911. }
  912. bool OpenXRAPI::on_state_loss_pending() {
  913. print_verbose("On state loss pending");
  914. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  915. wrapper->on_state_loss_pending();
  916. }
  917. // TODO need to look into the correct action here, read up on the spec but we may need to signal Godot to exit (if it's not already exiting)
  918. return true;
  919. }
  920. bool OpenXRAPI::on_state_exiting() {
  921. print_verbose("On state existing");
  922. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  923. wrapper->on_state_exiting();
  924. }
  925. // TODO need to look into the correct action here, read up on the spec but we may need to signal Godot to exit (if it's not already exiting)
  926. return true;
  927. }
  928. void OpenXRAPI::set_form_factor(XrFormFactor p_form_factor) {
  929. ERR_FAIL_COND(is_initialized());
  930. form_factor = p_form_factor;
  931. }
  932. void OpenXRAPI::set_view_configuration(XrViewConfigurationType p_view_configuration) {
  933. ERR_FAIL_COND(is_initialized());
  934. view_configuration = p_view_configuration;
  935. }
  936. void OpenXRAPI::set_reference_space(XrReferenceSpaceType p_reference_space) {
  937. ERR_FAIL_COND(is_initialized());
  938. reference_space = p_reference_space;
  939. }
  940. void OpenXRAPI::set_submit_depth_buffer(bool p_submit_depth_buffer) {
  941. ERR_FAIL_COND(is_initialized());
  942. submit_depth_buffer = p_submit_depth_buffer;
  943. }
  944. bool OpenXRAPI::is_initialized() {
  945. return (instance != XR_NULL_HANDLE);
  946. }
  947. bool OpenXRAPI::is_running() {
  948. if (instance == XR_NULL_HANDLE) {
  949. return false;
  950. }
  951. if (session == XR_NULL_HANDLE) {
  952. return false;
  953. }
  954. return running;
  955. }
  956. bool OpenXRAPI::openxr_loader_init() {
  957. #ifdef ANDROID_ENABLED
  958. ERR_FAIL_COND_V_MSG(openxr_loader_library_handle != nullptr, false, "OpenXR Loader library is already loaded.");
  959. {
  960. Error error_code = OS::get_singleton()->open_dynamic_library(OPENXR_LOADER_NAME, openxr_loader_library_handle);
  961. ERR_FAIL_COND_V_MSG(error_code != OK, false, "OpenXR loader not found.");
  962. }
  963. {
  964. Error error_code = OS::get_singleton()->get_dynamic_library_symbol_handle(openxr_loader_library_handle, "xrGetInstanceProcAddr", (void *&)xrGetInstanceProcAddr);
  965. ERR_FAIL_COND_V_MSG(error_code != OK, false, "Symbol xrGetInstanceProcAddr not found in OpenXR Loader library.");
  966. }
  967. #endif
  968. // Resolve the symbols that don't require an instance
  969. OPENXR_API_INIT_XR_FUNC_V(xrCreateInstance);
  970. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateApiLayerProperties);
  971. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateInstanceExtensionProperties);
  972. return true;
  973. }
  974. bool OpenXRAPI::resolve_instance_openxr_symbols() {
  975. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  976. OPENXR_API_INIT_XR_FUNC_V(xrAcquireSwapchainImage);
  977. OPENXR_API_INIT_XR_FUNC_V(xrApplyHapticFeedback);
  978. OPENXR_API_INIT_XR_FUNC_V(xrAttachSessionActionSets);
  979. OPENXR_API_INIT_XR_FUNC_V(xrBeginFrame);
  980. OPENXR_API_INIT_XR_FUNC_V(xrBeginSession);
  981. OPENXR_API_INIT_XR_FUNC_V(xrCreateAction);
  982. OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSet);
  983. OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSpace);
  984. OPENXR_API_INIT_XR_FUNC_V(xrCreateReferenceSpace);
  985. OPENXR_API_INIT_XR_FUNC_V(xrCreateSession);
  986. OPENXR_API_INIT_XR_FUNC_V(xrCreateSwapchain);
  987. OPENXR_API_INIT_XR_FUNC_V(xrDestroyAction);
  988. OPENXR_API_INIT_XR_FUNC_V(xrDestroyActionSet);
  989. OPENXR_API_INIT_XR_FUNC_V(xrDestroyInstance);
  990. OPENXR_API_INIT_XR_FUNC_V(xrDestroySession);
  991. OPENXR_API_INIT_XR_FUNC_V(xrDestroySpace);
  992. OPENXR_API_INIT_XR_FUNC_V(xrDestroySwapchain);
  993. OPENXR_API_INIT_XR_FUNC_V(xrEndFrame);
  994. OPENXR_API_INIT_XR_FUNC_V(xrEndSession);
  995. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateEnvironmentBlendModes);
  996. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateReferenceSpaces);
  997. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateSwapchainFormats);
  998. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurations);
  999. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurationViews);
  1000. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateBoolean);
  1001. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateFloat);
  1002. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateVector2f);
  1003. OPENXR_API_INIT_XR_FUNC_V(xrGetCurrentInteractionProfile);
  1004. OPENXR_API_INIT_XR_FUNC_V(xrGetSystem);
  1005. OPENXR_API_INIT_XR_FUNC_V(xrGetSystemProperties);
  1006. OPENXR_API_INIT_XR_FUNC_V(xrLocateViews);
  1007. OPENXR_API_INIT_XR_FUNC_V(xrLocateSpace);
  1008. OPENXR_API_INIT_XR_FUNC_V(xrPathToString);
  1009. OPENXR_API_INIT_XR_FUNC_V(xrPollEvent);
  1010. OPENXR_API_INIT_XR_FUNC_V(xrReleaseSwapchainImage);
  1011. OPENXR_API_INIT_XR_FUNC_V(xrResultToString);
  1012. OPENXR_API_INIT_XR_FUNC_V(xrStringToPath);
  1013. OPENXR_API_INIT_XR_FUNC_V(xrSuggestInteractionProfileBindings);
  1014. OPENXR_API_INIT_XR_FUNC_V(xrSyncActions);
  1015. OPENXR_API_INIT_XR_FUNC_V(xrWaitFrame);
  1016. OPENXR_API_INIT_XR_FUNC_V(xrWaitSwapchainImage);
  1017. return true;
  1018. }
  1019. XrResult OpenXRAPI::try_get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) {
  1020. return xrGetInstanceProcAddr(instance, p_name, p_addr);
  1021. }
  1022. XrResult OpenXRAPI::get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) {
  1023. XrResult result = try_get_instance_proc_addr(p_name, p_addr);
  1024. if (result != XR_SUCCESS) {
  1025. String error_message = String("Symbol ") + p_name + " not found in OpenXR instance.";
  1026. ERR_FAIL_V_MSG(result, error_message.utf8().get_data());
  1027. }
  1028. return result;
  1029. }
  1030. bool OpenXRAPI::initialize(const String &p_rendering_driver) {
  1031. ERR_FAIL_COND_V_MSG(instance != XR_NULL_HANDLE, false, "OpenXR instance was already created");
  1032. if (!openxr_loader_init()) {
  1033. return false;
  1034. }
  1035. if (p_rendering_driver == "vulkan") {
  1036. #ifdef VULKAN_ENABLED
  1037. graphics_extension = memnew(OpenXRVulkanExtension);
  1038. register_extension_wrapper(graphics_extension);
  1039. #else
  1040. // shouldn't be possible...
  1041. ERR_FAIL_V(false);
  1042. #endif
  1043. } else if (p_rendering_driver == "opengl3") {
  1044. #ifdef GLES3_ENABLED
  1045. graphics_extension = memnew(OpenXROpenGLExtension);
  1046. register_extension_wrapper(graphics_extension);
  1047. #else
  1048. // shouldn't be possible...
  1049. ERR_FAIL_V(false);
  1050. #endif
  1051. } else {
  1052. ERR_FAIL_V_MSG(false, "OpenXR: Unsupported rendering device.");
  1053. }
  1054. // initialize
  1055. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1056. wrapper->on_before_instance_created();
  1057. }
  1058. if (!load_layer_properties()) {
  1059. destroy_instance();
  1060. return false;
  1061. }
  1062. if (!load_supported_extensions()) {
  1063. destroy_instance();
  1064. return false;
  1065. }
  1066. if (!create_instance()) {
  1067. destroy_instance();
  1068. return false;
  1069. }
  1070. if (!resolve_instance_openxr_symbols()) {
  1071. destroy_instance();
  1072. return false;
  1073. }
  1074. if (!get_system_info()) {
  1075. destroy_instance();
  1076. return false;
  1077. }
  1078. if (!load_supported_view_configuration_types()) {
  1079. destroy_instance();
  1080. return false;
  1081. }
  1082. if (!load_supported_view_configuration_views(view_configuration)) {
  1083. destroy_instance();
  1084. return false;
  1085. }
  1086. if (!load_supported_environmental_blend_modes()) {
  1087. destroy_instance();
  1088. return false;
  1089. }
  1090. return true;
  1091. }
  1092. bool OpenXRAPI::initialize_session() {
  1093. if (!create_session()) {
  1094. destroy_session();
  1095. return false;
  1096. }
  1097. if (!load_supported_reference_spaces()) {
  1098. destroy_session();
  1099. return false;
  1100. }
  1101. if (!setup_spaces()) {
  1102. destroy_session();
  1103. return false;
  1104. }
  1105. if (!load_supported_swapchain_formats()) {
  1106. destroy_session();
  1107. return false;
  1108. }
  1109. return true;
  1110. }
  1111. void OpenXRAPI::finish() {
  1112. destroy_session();
  1113. destroy_instance();
  1114. }
  1115. void OpenXRAPI::set_xr_interface(OpenXRInterface *p_xr_interface) {
  1116. xr_interface = p_xr_interface;
  1117. }
  1118. void OpenXRAPI::register_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
  1119. registered_extension_wrappers.push_back(p_extension_wrapper);
  1120. }
  1121. void OpenXRAPI::unregister_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
  1122. registered_extension_wrappers.erase(p_extension_wrapper);
  1123. }
  1124. void OpenXRAPI::register_extension_metadata() {
  1125. for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
  1126. extension_wrapper->on_register_metadata();
  1127. }
  1128. }
  1129. void OpenXRAPI::cleanup_extension_wrappers() {
  1130. for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
  1131. memdelete(extension_wrapper);
  1132. }
  1133. registered_extension_wrappers.clear();
  1134. }
  1135. Size2 OpenXRAPI::get_recommended_target_size() {
  1136. ERR_FAIL_NULL_V(view_configuration_views, Size2());
  1137. Size2 target_size;
  1138. target_size.width = view_configuration_views[0].recommendedImageRectWidth * render_target_size_multiplier;
  1139. target_size.height = view_configuration_views[0].recommendedImageRectHeight * render_target_size_multiplier;
  1140. return target_size;
  1141. }
  1142. XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  1143. XrResult result;
  1144. ERR_FAIL_COND_V(!running, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  1145. // xrWaitFrame not run yet
  1146. if (frame_state.predictedDisplayTime == 0) {
  1147. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1148. }
  1149. // Get timing for the next frame, as that is the current frame we're processing
  1150. XrTime display_time = get_next_frame_time();
  1151. XrSpaceVelocity velocity = {
  1152. XR_TYPE_SPACE_VELOCITY, // type
  1153. nullptr, // next
  1154. 0, // velocityFlags
  1155. { 0.0, 0.0, 0.0 }, // linearVelocity
  1156. { 0.0, 0.0, 0.0 } // angularVelocity
  1157. };
  1158. XrSpaceLocation location = {
  1159. XR_TYPE_SPACE_LOCATION, // type
  1160. &velocity, // next
  1161. 0, // locationFlags
  1162. {
  1163. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  1164. { 0.0, 0.0, 0.0 } // position
  1165. } // pose
  1166. };
  1167. result = xrLocateSpace(view_space, play_space, display_time, &location);
  1168. if (XR_FAILED(result)) {
  1169. print_line("OpenXR: Failed to locate view space in play space [", get_error_string(result), "]");
  1170. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1171. }
  1172. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  1173. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  1174. if (head_pose_confidence != confidence) {
  1175. // prevent error spam
  1176. head_pose_confidence = confidence;
  1177. if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  1178. print_line("OpenXR head space location not valid (check tracking?)");
  1179. } else if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_LOW) {
  1180. print_verbose("OpenVR Head pose now tracking with low confidence");
  1181. } else {
  1182. print_verbose("OpenVR Head pose now tracking with high confidence");
  1183. }
  1184. }
  1185. return confidence;
  1186. }
  1187. bool OpenXRAPI::get_view_transform(uint32_t p_view, Transform3D &r_transform) {
  1188. ERR_FAIL_COND_V(!running, false);
  1189. // xrWaitFrame not run yet
  1190. if (frame_state.predictedDisplayTime == 0) {
  1191. return false;
  1192. }
  1193. // we don't have valid view info
  1194. if (views == nullptr || !view_pose_valid) {
  1195. return false;
  1196. }
  1197. // Note, the timing of this is set right before rendering, which is what we need here.
  1198. r_transform = transform_from_pose(views[p_view].pose);
  1199. return true;
  1200. }
  1201. bool OpenXRAPI::get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, Projection &p_camera_matrix) {
  1202. ERR_FAIL_COND_V(!running, false);
  1203. ERR_FAIL_NULL_V(graphics_extension, false);
  1204. // xrWaitFrame not run yet
  1205. if (frame_state.predictedDisplayTime == 0) {
  1206. return false;
  1207. }
  1208. // we don't have valid view info
  1209. if (views == nullptr || !view_pose_valid) {
  1210. return false;
  1211. }
  1212. // if we're using depth views, make sure we update our near and far there...
  1213. if (depth_views != nullptr) {
  1214. for (uint32_t i = 0; i < view_count; i++) {
  1215. depth_views[i].nearZ = p_z_near;
  1216. depth_views[i].farZ = p_z_far;
  1217. }
  1218. }
  1219. // now update our projection
  1220. return graphics_extension->create_projection_fov(views[p_view].fov, p_z_near, p_z_far, p_camera_matrix);
  1221. }
  1222. bool OpenXRAPI::poll_events() {
  1223. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1224. XrEventDataBuffer runtimeEvent;
  1225. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  1226. runtimeEvent.next = nullptr;
  1227. // runtimeEvent.varying = ...
  1228. XrResult pollResult = xrPollEvent(instance, &runtimeEvent);
  1229. while (pollResult == XR_SUCCESS) {
  1230. bool handled = false;
  1231. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1232. handled |= wrapper->on_event_polled(runtimeEvent);
  1233. }
  1234. switch (runtimeEvent.type) {
  1235. case XR_TYPE_EVENT_DATA_EVENTS_LOST: {
  1236. XrEventDataEventsLost *event = (XrEventDataEventsLost *)&runtimeEvent;
  1237. // We probably didn't poll fast enough, just output warning
  1238. WARN_PRINT("OpenXR EVENT: " + itos(event->lostEventCount) + " event data lost!");
  1239. } break;
  1240. case XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR: {
  1241. // XrEventDataVisibilityMaskChangedKHR *event = (XrEventDataVisibilityMaskChangedKHR *)&runtimeEvent;
  1242. // TODO implement this in the future, we should call xrGetVisibilityMaskKHR to obtain a mask,
  1243. // this will allow us to prevent rendering the part of our view which is never displayed giving us
  1244. // a decent performance improvement.
  1245. print_verbose("OpenXR EVENT: STUB: visibility mask changed");
  1246. } break;
  1247. case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: {
  1248. XrEventDataInstanceLossPending *event = (XrEventDataInstanceLossPending *)&runtimeEvent;
  1249. // TODO We get this event if we're about to loose our OpenXR instance.
  1250. // We should queue exiting Godot at this point.
  1251. print_verbose(String("OpenXR EVENT: instance loss pending at ") + itos(event->lossTime));
  1252. return false;
  1253. } break;
  1254. case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
  1255. XrEventDataSessionStateChanged *event = (XrEventDataSessionStateChanged *)&runtimeEvent;
  1256. session_state = event->state;
  1257. if (session_state >= XR_SESSION_STATE_MAX_ENUM) {
  1258. print_verbose(String("OpenXR EVENT: session state changed to UNKNOWN - ") + itos(session_state));
  1259. } else {
  1260. print_verbose(String("OpenXR EVENT: session state changed to ") + OpenXRUtil::get_session_state_name(session_state));
  1261. switch (session_state) {
  1262. case XR_SESSION_STATE_IDLE:
  1263. on_state_idle();
  1264. break;
  1265. case XR_SESSION_STATE_READY:
  1266. on_state_ready();
  1267. break;
  1268. case XR_SESSION_STATE_SYNCHRONIZED:
  1269. on_state_synchronized();
  1270. break;
  1271. case XR_SESSION_STATE_VISIBLE:
  1272. on_state_visible();
  1273. break;
  1274. case XR_SESSION_STATE_FOCUSED:
  1275. on_state_focused();
  1276. break;
  1277. case XR_SESSION_STATE_STOPPING:
  1278. on_state_stopping();
  1279. break;
  1280. case XR_SESSION_STATE_LOSS_PENDING:
  1281. on_state_loss_pending();
  1282. break;
  1283. case XR_SESSION_STATE_EXITING:
  1284. on_state_exiting();
  1285. break;
  1286. default:
  1287. break;
  1288. }
  1289. }
  1290. } break;
  1291. case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: {
  1292. XrEventDataReferenceSpaceChangePending *event = (XrEventDataReferenceSpaceChangePending *)&runtimeEvent;
  1293. print_verbose(String("OpenXR EVENT: reference space type ") + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!");
  1294. if (event->poseValid && xr_interface) {
  1295. xr_interface->on_pose_recentered();
  1296. }
  1297. } break;
  1298. case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: {
  1299. print_verbose("OpenXR EVENT: interaction profile changed!");
  1300. XrEventDataInteractionProfileChanged *event = (XrEventDataInteractionProfileChanged *)&runtimeEvent;
  1301. List<RID> trackers;
  1302. tracker_owner.get_owned_list(&trackers);
  1303. for (int i = 0; i < trackers.size(); i++) {
  1304. tracker_check_profile(trackers[i], event->session);
  1305. }
  1306. } break;
  1307. default:
  1308. if (!handled) {
  1309. print_verbose(String("OpenXR Unhandled event type ") + OpenXRUtil::get_structure_type_name(runtimeEvent.type));
  1310. }
  1311. break;
  1312. }
  1313. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  1314. pollResult = xrPollEvent(instance, &runtimeEvent);
  1315. }
  1316. if (pollResult == XR_EVENT_UNAVAILABLE) {
  1317. // processed all events in the queue
  1318. return true;
  1319. } else {
  1320. ERR_FAIL_V_MSG(false, "OpenXR: Failed to poll events!");
  1321. }
  1322. }
  1323. bool OpenXRAPI::process() {
  1324. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1325. if (!poll_events()) {
  1326. return false;
  1327. }
  1328. if (!running) {
  1329. return false;
  1330. }
  1331. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1332. wrapper->on_process();
  1333. }
  1334. return true;
  1335. }
  1336. bool OpenXRAPI::acquire_image(OpenXRSwapChainInfo &p_swapchain) {
  1337. ERR_FAIL_COND_V(p_swapchain.image_acquired, true); // this was not released when it should be, error out and re-use...
  1338. XrResult result;
  1339. XrSwapchainImageAcquireInfo swapchain_image_acquire_info = {
  1340. XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, // type
  1341. nullptr // next
  1342. };
  1343. result = xrAcquireSwapchainImage(p_swapchain.swapchain, &swapchain_image_acquire_info, &p_swapchain.image_index);
  1344. if (XR_FAILED(result)) {
  1345. print_line("OpenXR: failed to acquire swapchain image [", get_error_string(result), "]");
  1346. return false;
  1347. }
  1348. XrSwapchainImageWaitInfo swapchain_image_wait_info = {
  1349. XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, // type
  1350. nullptr, // next
  1351. 17000000 // timeout in nanoseconds
  1352. };
  1353. result = xrWaitSwapchainImage(p_swapchain.swapchain, &swapchain_image_wait_info);
  1354. if (XR_FAILED(result)) {
  1355. print_line("OpenXR: failed to wait for swapchain image [", get_error_string(result), "]");
  1356. return false;
  1357. }
  1358. return true;
  1359. }
  1360. bool OpenXRAPI::release_image(OpenXRSwapChainInfo &p_swapchain) {
  1361. XrSwapchainImageReleaseInfo swapchain_image_release_info = {
  1362. XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, // type
  1363. nullptr // next
  1364. };
  1365. XrResult result = xrReleaseSwapchainImage(p_swapchain.swapchain, &swapchain_image_release_info);
  1366. if (XR_FAILED(result)) {
  1367. print_line("OpenXR: failed to release swapchain image! [", get_error_string(result), "]");
  1368. return false;
  1369. }
  1370. return true;
  1371. }
  1372. void OpenXRAPI::pre_render() {
  1373. ERR_FAIL_COND(instance == XR_NULL_HANDLE);
  1374. if (!running) {
  1375. return;
  1376. }
  1377. // Waitframe does 2 important things in our process:
  1378. // 1) It provides us with predictive timing, telling us when OpenXR expects to display the frame we're about to commit
  1379. // 2) It will use the previous timing to pause our thread so that rendering starts as close to displaying as possible
  1380. // This must thus be called as close to when we start rendering as possible
  1381. XrFrameWaitInfo frame_wait_info = { XR_TYPE_FRAME_WAIT_INFO, nullptr };
  1382. frame_state.predictedDisplayTime = 0;
  1383. frame_state.predictedDisplayPeriod = 0;
  1384. frame_state.shouldRender = false;
  1385. XrResult result = xrWaitFrame(session, &frame_wait_info, &frame_state);
  1386. if (XR_FAILED(result)) {
  1387. print_line("OpenXR: xrWaitFrame() was not successful [", get_error_string(result), "]");
  1388. // reset just in case
  1389. frame_state.predictedDisplayTime = 0;
  1390. frame_state.predictedDisplayPeriod = 0;
  1391. frame_state.shouldRender = false;
  1392. return;
  1393. }
  1394. if (frame_state.predictedDisplayPeriod > 500000000) {
  1395. // display period more then 0.5 seconds? must be wrong data
  1396. print_verbose(String("OpenXR resetting invalid display period ") + rtos(frame_state.predictedDisplayPeriod));
  1397. frame_state.predictedDisplayPeriod = 0;
  1398. }
  1399. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1400. wrapper->on_pre_render();
  1401. }
  1402. // Get our view info for the frame we're about to render, note from the OpenXR manual:
  1403. // "Repeatedly calling xrLocateViews with the same time may not necessarily return the same result. Instead the prediction gets increasingly accurate as the function is called closer to the given time for which a prediction is made"
  1404. // We're calling this "relatively" early, the positioning we're obtaining here will be used to do our frustum culling,
  1405. // occlusion culling, etc. There is however a technique that we can investigate in the future where after our entire
  1406. // Vulkan command buffer is build, but right before vkSubmitQueue is called, we call xrLocateViews one more time and
  1407. // update the view and projection matrix once more with a slightly more accurate predication and then submit the
  1408. // command queues.
  1409. // That is not possible yet but worth investigating in the future.
  1410. XrViewLocateInfo view_locate_info = {
  1411. XR_TYPE_VIEW_LOCATE_INFO, // type
  1412. nullptr, // next
  1413. view_configuration, // viewConfigurationType
  1414. frame_state.predictedDisplayTime, // displayTime
  1415. play_space // space
  1416. };
  1417. XrViewState view_state = {
  1418. XR_TYPE_VIEW_STATE, // type
  1419. nullptr, // next
  1420. 0 // viewStateFlags
  1421. };
  1422. uint32_t view_count_output;
  1423. result = xrLocateViews(session, &view_locate_info, &view_state, view_count, &view_count_output, views);
  1424. if (XR_FAILED(result)) {
  1425. print_line("OpenXR: Couldn't locate views [", get_error_string(result), "]");
  1426. return;
  1427. }
  1428. bool pose_valid = true;
  1429. for (uint64_t i = 0; i < view_count_output; i++) {
  1430. if ((view_state.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0 ||
  1431. (view_state.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0) {
  1432. pose_valid = false;
  1433. }
  1434. }
  1435. if (view_pose_valid != pose_valid) {
  1436. view_pose_valid = pose_valid;
  1437. if (!view_pose_valid) {
  1438. print_verbose("OpenXR View pose became invalid");
  1439. } else {
  1440. print_verbose("OpenXR View pose became valid");
  1441. }
  1442. }
  1443. // let's start our frame..
  1444. XrFrameBeginInfo frame_begin_info = {
  1445. XR_TYPE_FRAME_BEGIN_INFO, // type
  1446. nullptr // next
  1447. };
  1448. result = xrBeginFrame(session, &frame_begin_info);
  1449. if (XR_FAILED(result)) {
  1450. print_line("OpenXR: failed to being frame [", get_error_string(result), "]");
  1451. return;
  1452. }
  1453. }
  1454. bool OpenXRAPI::pre_draw_viewport(RID p_render_target) {
  1455. if (!can_render()) {
  1456. return false;
  1457. }
  1458. // TODO: at some point in time we may support multiple viewports in which case we need to handle that...
  1459. // Acquire our images
  1460. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  1461. if (!swapchains[i].image_acquired && swapchains[i].swapchain != XR_NULL_HANDLE) {
  1462. if (!acquire_image(swapchains[i])) {
  1463. return false;
  1464. }
  1465. swapchains[i].image_acquired = true;
  1466. }
  1467. }
  1468. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1469. wrapper->on_pre_draw_viewport(p_render_target);
  1470. }
  1471. return true;
  1472. }
  1473. RID OpenXRAPI::get_color_texture() {
  1474. if (swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) {
  1475. return graphics_extension->get_texture(swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data, swapchains[OPENXR_SWAPCHAIN_COLOR].image_index);
  1476. } else {
  1477. return RID();
  1478. }
  1479. }
  1480. RID OpenXRAPI::get_depth_texture() {
  1481. // Note, image will not be acquired if we didn't have a suitable swap chain format.
  1482. if (submit_depth_buffer && swapchains[OPENXR_SWAPCHAIN_DEPTH].image_acquired) {
  1483. return graphics_extension->get_texture(swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain_graphics_data, swapchains[OPENXR_SWAPCHAIN_DEPTH].image_index);
  1484. } else {
  1485. return RID();
  1486. }
  1487. }
  1488. void OpenXRAPI::post_draw_viewport(RID p_render_target) {
  1489. if (!can_render()) {
  1490. return;
  1491. }
  1492. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1493. wrapper->on_post_draw_viewport(p_render_target);
  1494. }
  1495. };
  1496. void OpenXRAPI::end_frame() {
  1497. XrResult result;
  1498. ERR_FAIL_COND(instance == XR_NULL_HANDLE);
  1499. if (!running) {
  1500. return;
  1501. }
  1502. if (frame_state.shouldRender && view_pose_valid && !swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) {
  1503. print_line("OpenXR: No viewport was marked with use_xr, there is no rendered output!");
  1504. }
  1505. // must have:
  1506. // - shouldRender set to true
  1507. // - a valid view pose for projection_views[eye].pose to submit layer
  1508. // - an image to render
  1509. if (!frame_state.shouldRender || !view_pose_valid || !swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) {
  1510. // submit 0 layers when we shouldn't render
  1511. XrFrameEndInfo frame_end_info = {
  1512. XR_TYPE_FRAME_END_INFO, // type
  1513. nullptr, // next
  1514. frame_state.predictedDisplayTime, // displayTime
  1515. environment_blend_mode, // environmentBlendMode
  1516. 0, // layerCount
  1517. nullptr // layers
  1518. };
  1519. result = xrEndFrame(session, &frame_end_info);
  1520. if (XR_FAILED(result)) {
  1521. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1522. return;
  1523. }
  1524. // neither eye is rendered
  1525. return;
  1526. }
  1527. // release our swapchain image if we acquired it
  1528. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  1529. if (swapchains[i].image_acquired) {
  1530. swapchains[i].image_acquired = false; // whether we succeed or not, consider this released.
  1531. release_image(swapchains[i]);
  1532. }
  1533. }
  1534. for (uint32_t eye = 0; eye < view_count; eye++) {
  1535. projection_views[eye].fov = views[eye].fov;
  1536. projection_views[eye].pose = views[eye].pose;
  1537. }
  1538. Vector<const XrCompositionLayerBaseHeader *> layers_list;
  1539. // Add composition layers from providers
  1540. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  1541. XrCompositionLayerBaseHeader *layer = provider->get_composition_layer();
  1542. if (layer) {
  1543. layers_list.push_back(layer);
  1544. }
  1545. }
  1546. XrCompositionLayerProjection projection_layer = {
  1547. XR_TYPE_COMPOSITION_LAYER_PROJECTION, // type
  1548. nullptr, // next
  1549. layers_list.size() > 0 ? XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT | XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT : XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT, // layerFlags
  1550. play_space, // space
  1551. view_count, // viewCount
  1552. projection_views, // views
  1553. };
  1554. layers_list.push_back((const XrCompositionLayerBaseHeader *)&projection_layer);
  1555. XrFrameEndInfo frame_end_info = {
  1556. XR_TYPE_FRAME_END_INFO, // type
  1557. nullptr, // next
  1558. frame_state.predictedDisplayTime, // displayTime
  1559. environment_blend_mode, // environmentBlendMode
  1560. static_cast<uint32_t>(layers_list.size()), // layerCount
  1561. layers_list.ptr() // layers
  1562. };
  1563. result = xrEndFrame(session, &frame_end_info);
  1564. if (XR_FAILED(result)) {
  1565. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1566. return;
  1567. }
  1568. }
  1569. float OpenXRAPI::get_display_refresh_rate() const {
  1570. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1571. if (drrext) {
  1572. return drrext->get_refresh_rate();
  1573. }
  1574. return 0.0;
  1575. }
  1576. void OpenXRAPI::set_display_refresh_rate(float p_refresh_rate) {
  1577. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1578. if (drrext != nullptr) {
  1579. drrext->set_refresh_rate(p_refresh_rate);
  1580. }
  1581. }
  1582. Array OpenXRAPI::get_available_display_refresh_rates() const {
  1583. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1584. if (drrext != nullptr) {
  1585. return drrext->get_available_refresh_rates();
  1586. }
  1587. return Array();
  1588. }
  1589. double OpenXRAPI::get_render_target_size_multiplier() const {
  1590. return render_target_size_multiplier;
  1591. }
  1592. void OpenXRAPI::set_render_target_size_multiplier(double multiplier) {
  1593. render_target_size_multiplier = multiplier;
  1594. }
  1595. OpenXRAPI::OpenXRAPI() {
  1596. // OpenXRAPI is only constructed if OpenXR is enabled.
  1597. singleton = this;
  1598. if (Engine::get_singleton()->is_editor_hint()) {
  1599. // Enabled OpenXR in the editor? Adjust our settings for the editor
  1600. } else {
  1601. // Load settings from project settings
  1602. int ff = GLOBAL_GET("xr/openxr/form_factor");
  1603. switch (ff) {
  1604. case 0: {
  1605. form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
  1606. } break;
  1607. case 1: {
  1608. form_factor = XR_FORM_FACTOR_HANDHELD_DISPLAY;
  1609. } break;
  1610. default:
  1611. break;
  1612. }
  1613. int vc = GLOBAL_GET("xr/openxr/view_configuration");
  1614. switch (vc) {
  1615. case 0: {
  1616. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO;
  1617. } break;
  1618. case 1: {
  1619. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
  1620. } break;
  1621. /* we don't support quad and observer configurations (yet)
  1622. case 2: {
  1623. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO;
  1624. } break;
  1625. case 3: {
  1626. view_configuration = XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT;
  1627. } break;
  1628. */
  1629. default:
  1630. break;
  1631. }
  1632. int rs = GLOBAL_GET("xr/openxr/reference_space");
  1633. switch (rs) {
  1634. case 0: {
  1635. reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
  1636. } break;
  1637. case 1: {
  1638. reference_space = XR_REFERENCE_SPACE_TYPE_STAGE;
  1639. } break;
  1640. default:
  1641. break;
  1642. }
  1643. submit_depth_buffer = GLOBAL_GET("xr/openxr/submit_depth_buffer");
  1644. }
  1645. // reset a few things that can't be done in our class definition
  1646. frame_state.predictedDisplayTime = 0;
  1647. frame_state.predictedDisplayPeriod = 0;
  1648. }
  1649. OpenXRAPI::~OpenXRAPI() {
  1650. // cleanup our composition layer providers
  1651. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  1652. memdelete(provider);
  1653. }
  1654. composition_layer_providers.clear();
  1655. if (supported_extensions != nullptr) {
  1656. memfree(supported_extensions);
  1657. supported_extensions = nullptr;
  1658. }
  1659. if (layer_properties != nullptr) {
  1660. memfree(layer_properties);
  1661. layer_properties = nullptr;
  1662. }
  1663. #ifdef ANDROID_ENABLED
  1664. if (openxr_loader_library_handle) {
  1665. OS::get_singleton()->close_dynamic_library(openxr_loader_library_handle);
  1666. openxr_loader_library_handle = nullptr;
  1667. }
  1668. #endif
  1669. singleton = nullptr;
  1670. }
  1671. Transform3D OpenXRAPI::transform_from_pose(const XrPosef &p_pose) {
  1672. Quaternion q(p_pose.orientation.x, p_pose.orientation.y, p_pose.orientation.z, p_pose.orientation.w);
  1673. Basis basis(q);
  1674. Vector3 origin(p_pose.position.x, p_pose.position.y, p_pose.position.z);
  1675. return Transform3D(basis, origin);
  1676. }
  1677. template <typename T>
  1678. XRPose::TrackingConfidence _transform_from_location(const T &p_location, Transform3D &r_transform) {
  1679. Basis basis;
  1680. Vector3 origin;
  1681. XRPose::TrackingConfidence confidence = XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1682. const auto &pose = p_location.pose;
  1683. // Check orientation
  1684. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) {
  1685. Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
  1686. r_transform.basis = Basis(q);
  1687. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) {
  1688. // Fully valid orientation, so either 3DOF or 6DOF tracking with high confidence so default to HIGH_TRACKING
  1689. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  1690. } else {
  1691. // Orientation is being tracked but we're using old/predicted data, so low tracking confidence
  1692. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  1693. }
  1694. } else {
  1695. r_transform.basis = Basis();
  1696. }
  1697. // Check location
  1698. if (p_location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) {
  1699. r_transform.origin = Vector3(pose.position.x, pose.position.y, pose.position.z);
  1700. if (!(p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)) {
  1701. // Location is being tracked but we're using old/predicted data, so low tracking confidence
  1702. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  1703. } else if (confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  1704. // Position tracking without orientation tracking?
  1705. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  1706. }
  1707. } else {
  1708. // No tracking or 3DOF I guess..
  1709. r_transform.origin = Vector3();
  1710. }
  1711. return confidence;
  1712. }
  1713. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrSpaceLocation &p_location, Transform3D &r_transform) {
  1714. return _transform_from_location(p_location, r_transform);
  1715. }
  1716. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform) {
  1717. return _transform_from_location(p_location, r_transform);
  1718. }
  1719. void OpenXRAPI::parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  1720. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT) {
  1721. XrVector3f linear_velocity = p_velocity.linearVelocity;
  1722. r_linear_velocity = Vector3(linear_velocity.x, linear_velocity.y, linear_velocity.z);
  1723. } else {
  1724. r_linear_velocity = Vector3();
  1725. }
  1726. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT) {
  1727. XrVector3f angular_velocity = p_velocity.angularVelocity;
  1728. r_angular_velocity = Vector3(angular_velocity.x, angular_velocity.y, angular_velocity.z);
  1729. } else {
  1730. r_angular_velocity = Vector3();
  1731. }
  1732. }
  1733. bool OpenXRAPI::xr_result(XrResult result, const char *format, Array args) const {
  1734. if (XR_SUCCEEDED(result))
  1735. return true;
  1736. char resultString[XR_MAX_RESULT_STRING_SIZE];
  1737. xrResultToString(instance, result, resultString);
  1738. print_error(String("OpenXR ") + String(format).format(args) + String(" [") + String(resultString) + String("]"));
  1739. return false;
  1740. }
  1741. RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
  1742. List<RID> current;
  1743. tracker_owner.get_owned_list(&current);
  1744. for (int i = 0; i < current.size(); i++) {
  1745. Tracker *tracker = tracker_owner.get_or_null(current[i]);
  1746. if (tracker && tracker->toplevel_path == p_path) {
  1747. return current[i];
  1748. }
  1749. }
  1750. return RID();
  1751. }
  1752. RID OpenXRAPI::tracker_create(const String p_name) {
  1753. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1754. Tracker new_tracker;
  1755. new_tracker.name = p_name;
  1756. new_tracker.toplevel_path = XR_NULL_PATH;
  1757. new_tracker.active_profile_rid = RID();
  1758. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_tracker.toplevel_path);
  1759. if (XR_FAILED(result)) {
  1760. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  1761. return RID();
  1762. }
  1763. return tracker_owner.make_rid(new_tracker);
  1764. }
  1765. String OpenXRAPI::tracker_get_name(RID p_tracker) {
  1766. if (p_tracker.is_null()) {
  1767. return String("None");
  1768. }
  1769. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1770. ERR_FAIL_NULL_V(tracker, String());
  1771. return tracker->name;
  1772. }
  1773. void OpenXRAPI::tracker_check_profile(RID p_tracker, XrSession p_session) {
  1774. if (p_session == XR_NULL_HANDLE) {
  1775. p_session = session;
  1776. }
  1777. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1778. ERR_FAIL_NULL(tracker);
  1779. if (tracker->toplevel_path == XR_NULL_PATH) {
  1780. // no path, how was this even created?
  1781. return;
  1782. }
  1783. XrInteractionProfileState profile_state = {
  1784. XR_TYPE_INTERACTION_PROFILE_STATE, // type
  1785. nullptr, // next
  1786. XR_NULL_PATH // interactionProfile
  1787. };
  1788. XrResult result = xrGetCurrentInteractionProfile(p_session, tracker->toplevel_path, &profile_state);
  1789. if (XR_FAILED(result)) {
  1790. print_line("OpenXR: Failed to get interaction profile for", itos(tracker->toplevel_path), "[", get_error_string(result), "]");
  1791. return;
  1792. }
  1793. XrPath new_profile = profile_state.interactionProfile;
  1794. XrPath was_profile = get_interaction_profile_path(tracker->active_profile_rid);
  1795. if (was_profile != new_profile) {
  1796. tracker->active_profile_rid = get_interaction_profile_rid(new_profile);
  1797. if (xr_interface) {
  1798. xr_interface->tracker_profile_changed(p_tracker, tracker->active_profile_rid);
  1799. }
  1800. }
  1801. }
  1802. void OpenXRAPI::tracker_free(RID p_tracker) {
  1803. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1804. ERR_FAIL_NULL(tracker);
  1805. // there is nothing to free here
  1806. tracker_owner.free(p_tracker);
  1807. }
  1808. RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_name, const int p_priority) {
  1809. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1810. ActionSet action_set;
  1811. action_set.name = p_name;
  1812. action_set.is_attached = false;
  1813. // create our action set...
  1814. XrActionSetCreateInfo action_set_info = {
  1815. XR_TYPE_ACTION_SET_CREATE_INFO, // type
  1816. nullptr, // next
  1817. "", // actionSetName
  1818. "", // localizedActionSetName
  1819. uint32_t(p_priority) // priority
  1820. };
  1821. copy_string_to_char_buffer(p_name, action_set_info.actionSetName, XR_MAX_ACTION_SET_NAME_SIZE);
  1822. copy_string_to_char_buffer(p_localized_name, action_set_info.localizedActionSetName, XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE);
  1823. XrResult result = xrCreateActionSet(instance, &action_set_info, &action_set.handle);
  1824. if (XR_FAILED(result)) {
  1825. print_line("OpenXR: failed to create action set ", p_name, "! [", get_error_string(result), "]");
  1826. return RID();
  1827. }
  1828. return action_set_owner.make_rid(action_set);
  1829. }
  1830. String OpenXRAPI::action_set_get_name(RID p_action_set) {
  1831. if (p_action_set.is_null()) {
  1832. return String("None");
  1833. }
  1834. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1835. ERR_FAIL_NULL_V(action_set, String());
  1836. return action_set->name;
  1837. }
  1838. bool OpenXRAPI::action_set_attach(RID p_action_set) {
  1839. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1840. ERR_FAIL_NULL_V(action_set, false);
  1841. if (action_set->is_attached) {
  1842. // already attached
  1843. return true;
  1844. }
  1845. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  1846. // So according to the docs, once we attach our action set to our session it becomes read only..
  1847. // https://www.khronos.org/registry/OpenXR/specs/1.0/man/html/xrAttachSessionActionSets.html
  1848. XrSessionActionSetsAttachInfo attach_info = {
  1849. XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, // type
  1850. nullptr, // next
  1851. 1, // countActionSets,
  1852. &action_set->handle // actionSets
  1853. };
  1854. XrResult result = xrAttachSessionActionSets(session, &attach_info);
  1855. if (XR_FAILED(result)) {
  1856. print_line("OpenXR: failed to attach action set! [", get_error_string(result), "]");
  1857. return false;
  1858. }
  1859. action_set->is_attached = true;
  1860. /* For debugging:
  1861. print_verbose("Attached set " + action_set->name);
  1862. List<RID> action_rids;
  1863. action_owner.get_owned_list(&action_rids);
  1864. for (int i = 0; i < action_rids.size(); i++) {
  1865. Action * action = action_owner.get_or_null(action_rids[i]);
  1866. if (action && action->action_set_rid == p_action_set) {
  1867. print_verbose(" - Action " + action->name + ": " + OpenXRUtil::get_action_type_name(action->action_type));
  1868. for (int j = 0; j < action->trackers.size(); j++) {
  1869. Tracker * tracker = tracker_owner.get_or_null(action->trackers[j].tracker_rid);
  1870. if (tracker) {
  1871. print_verbose(" - " + tracker->name);
  1872. }
  1873. }
  1874. }
  1875. }
  1876. */
  1877. return true;
  1878. }
  1879. void OpenXRAPI::action_set_free(RID p_action_set) {
  1880. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1881. ERR_FAIL_NULL(action_set);
  1882. if (action_set->handle != XR_NULL_HANDLE) {
  1883. xrDestroyActionSet(action_set->handle);
  1884. }
  1885. action_set_owner.free(p_action_set);
  1886. }
  1887. RID OpenXRAPI::get_action_rid(XrAction p_action) {
  1888. List<RID> current;
  1889. action_owner.get_owned_list(&current);
  1890. for (int i = 0; i < current.size(); i++) {
  1891. Action *action = action_owner.get_or_null(current[i]);
  1892. if (action && action->handle == p_action) {
  1893. return current[i];
  1894. }
  1895. }
  1896. return RID();
  1897. }
  1898. RID OpenXRAPI::action_create(RID p_action_set, const String p_name, const String p_localized_name, OpenXRAction::ActionType p_action_type, const Vector<RID> &p_trackers) {
  1899. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1900. Action action;
  1901. action.name = p_name;
  1902. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1903. ERR_FAIL_NULL_V(action_set, RID());
  1904. ERR_FAIL_COND_V(action_set->handle == XR_NULL_HANDLE, RID());
  1905. action.action_set_rid = p_action_set;
  1906. switch (p_action_type) {
  1907. case OpenXRAction::OPENXR_ACTION_BOOL:
  1908. action.action_type = XR_ACTION_TYPE_BOOLEAN_INPUT;
  1909. break;
  1910. case OpenXRAction::OPENXR_ACTION_FLOAT:
  1911. action.action_type = XR_ACTION_TYPE_FLOAT_INPUT;
  1912. break;
  1913. case OpenXRAction::OPENXR_ACTION_VECTOR2:
  1914. action.action_type = XR_ACTION_TYPE_VECTOR2F_INPUT;
  1915. break;
  1916. case OpenXRAction::OPENXR_ACTION_POSE:
  1917. action.action_type = XR_ACTION_TYPE_POSE_INPUT;
  1918. break;
  1919. case OpenXRAction::OPENXR_ACTION_HAPTIC:
  1920. action.action_type = XR_ACTION_TYPE_VIBRATION_OUTPUT;
  1921. break;
  1922. default:
  1923. ERR_FAIL_V(RID());
  1924. break;
  1925. }
  1926. Vector<XrPath> toplevel_paths;
  1927. for (int i = 0; i < p_trackers.size(); i++) {
  1928. Tracker *tracker = tracker_owner.get_or_null(p_trackers[i]);
  1929. if (tracker != nullptr && tracker->toplevel_path != XR_NULL_PATH) {
  1930. ActionTracker action_tracker = {
  1931. p_trackers[i], // tracker
  1932. XR_NULL_HANDLE, // space
  1933. false // was_location_valid
  1934. };
  1935. action.trackers.push_back(action_tracker);
  1936. toplevel_paths.push_back(tracker->toplevel_path);
  1937. }
  1938. }
  1939. XrActionCreateInfo action_info = {
  1940. XR_TYPE_ACTION_CREATE_INFO, // type
  1941. nullptr, // next
  1942. "", // actionName
  1943. action.action_type, // actionType
  1944. uint32_t(toplevel_paths.size()), // countSubactionPaths
  1945. toplevel_paths.ptr(), // subactionPaths
  1946. "" // localizedActionName
  1947. };
  1948. copy_string_to_char_buffer(p_name, action_info.actionName, XR_MAX_ACTION_NAME_SIZE);
  1949. copy_string_to_char_buffer(p_localized_name, action_info.localizedActionName, XR_MAX_LOCALIZED_ACTION_NAME_SIZE);
  1950. XrResult result = xrCreateAction(action_set->handle, &action_info, &action.handle);
  1951. if (XR_FAILED(result)) {
  1952. print_line("OpenXR: failed to create action ", p_name, "! [", get_error_string(result), "]");
  1953. return RID();
  1954. }
  1955. return action_owner.make_rid(action);
  1956. }
  1957. String OpenXRAPI::action_get_name(RID p_action) {
  1958. if (p_action.is_null()) {
  1959. return String("None");
  1960. }
  1961. Action *action = action_owner.get_or_null(p_action);
  1962. ERR_FAIL_NULL_V(action, String());
  1963. return action->name;
  1964. }
  1965. void OpenXRAPI::action_free(RID p_action) {
  1966. Action *action = action_owner.get_or_null(p_action);
  1967. ERR_FAIL_NULL(action);
  1968. if (action->handle != XR_NULL_HANDLE) {
  1969. xrDestroyAction(action->handle);
  1970. }
  1971. action_owner.free(p_action);
  1972. }
  1973. RID OpenXRAPI::get_interaction_profile_rid(XrPath p_path) {
  1974. List<RID> current;
  1975. interaction_profile_owner.get_owned_list(&current);
  1976. for (int i = 0; i < current.size(); i++) {
  1977. InteractionProfile *ip = interaction_profile_owner.get_or_null(current[i]);
  1978. if (ip && ip->path == p_path) {
  1979. return current[i];
  1980. }
  1981. }
  1982. return RID();
  1983. }
  1984. XrPath OpenXRAPI::get_interaction_profile_path(RID p_interaction_profile) {
  1985. if (p_interaction_profile.is_null()) {
  1986. return XR_NULL_PATH;
  1987. }
  1988. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1989. ERR_FAIL_NULL_V(ip, XR_NULL_PATH);
  1990. return ip->path;
  1991. }
  1992. RID OpenXRAPI::interaction_profile_create(const String p_name) {
  1993. if (!is_interaction_profile_supported(p_name)) {
  1994. // The extension enabling this path must not be active, we will silently skip this interaction profile
  1995. return RID();
  1996. }
  1997. InteractionProfile new_interaction_profile;
  1998. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_interaction_profile.path);
  1999. if (XR_FAILED(result)) {
  2000. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  2001. return RID();
  2002. }
  2003. RID existing_ip = get_interaction_profile_rid(new_interaction_profile.path);
  2004. if (existing_ip.is_valid()) {
  2005. return existing_ip;
  2006. }
  2007. new_interaction_profile.name = p_name;
  2008. return interaction_profile_owner.make_rid(new_interaction_profile);
  2009. }
  2010. String OpenXRAPI::interaction_profile_get_name(RID p_interaction_profile) {
  2011. if (p_interaction_profile.is_null()) {
  2012. return String("None");
  2013. }
  2014. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2015. ERR_FAIL_NULL_V(ip, String());
  2016. return ip->name;
  2017. }
  2018. void OpenXRAPI::interaction_profile_clear_bindings(RID p_interaction_profile) {
  2019. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2020. ERR_FAIL_NULL(ip);
  2021. ip->bindings.clear();
  2022. }
  2023. bool OpenXRAPI::interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String p_path) {
  2024. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2025. ERR_FAIL_NULL_V(ip, false);
  2026. if (!interaction_profile_supports_io_path(ip->name, p_path)) {
  2027. return false;
  2028. }
  2029. XrActionSuggestedBinding binding;
  2030. Action *action = action_owner.get_or_null(p_action);
  2031. ERR_FAIL_COND_V(action == nullptr || action->handle == XR_NULL_HANDLE, false);
  2032. binding.action = action->handle;
  2033. XrResult result = xrStringToPath(instance, p_path.utf8().get_data(), &binding.binding);
  2034. if (XR_FAILED(result)) {
  2035. print_line("OpenXR: failed to get path for ", p_path, "! [", get_error_string(result), "]");
  2036. return false;
  2037. }
  2038. ip->bindings.push_back(binding);
  2039. return true;
  2040. }
  2041. bool OpenXRAPI::interaction_profile_suggest_bindings(RID p_interaction_profile) {
  2042. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  2043. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2044. ERR_FAIL_NULL_V(ip, false);
  2045. const XrInteractionProfileSuggestedBinding suggested_bindings = {
  2046. XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, // type
  2047. nullptr, // next
  2048. ip->path, // interactionProfile
  2049. uint32_t(ip->bindings.size()), // countSuggestedBindings
  2050. ip->bindings.ptr() // suggestedBindings
  2051. };
  2052. XrResult result = xrSuggestInteractionProfileBindings(instance, &suggested_bindings);
  2053. if (result == XR_ERROR_PATH_UNSUPPORTED) {
  2054. // this is fine, not all runtimes support all devices.
  2055. print_verbose("OpenXR Interaction profile " + ip->name + " is not supported on this runtime");
  2056. } else if (XR_FAILED(result)) {
  2057. print_line("OpenXR: failed to suggest bindings for ", ip->name, "! [", get_error_string(result), "]");
  2058. // reporting is enough...
  2059. }
  2060. /* For debugging:
  2061. print_verbose("Suggested bindings for " + ip->name);
  2062. for (int i = 0; i < ip->bindings.size(); i++) {
  2063. uint32_t strlen;
  2064. char path[XR_MAX_PATH_LENGTH];
  2065. String action_name = action_get_name(get_action_rid(ip->bindings[i].action));
  2066. XrResult result = xrPathToString(instance, ip->bindings[i].binding, XR_MAX_PATH_LENGTH, &strlen, path);
  2067. if (XR_FAILED(result)) {
  2068. print_line("OpenXR: failed to retrieve bindings for ", action_name, "! [", get_error_string(result), "]");
  2069. }
  2070. print_verbose(" - " + action_name + " => " + String(path));
  2071. }
  2072. */
  2073. return true;
  2074. }
  2075. void OpenXRAPI::interaction_profile_free(RID p_interaction_profile) {
  2076. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2077. ERR_FAIL_NULL(ip);
  2078. ip->bindings.clear();
  2079. interaction_profile_owner.free(p_interaction_profile);
  2080. }
  2081. bool OpenXRAPI::sync_action_sets(const Vector<RID> p_active_sets) {
  2082. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2083. if (!running) {
  2084. return false;
  2085. }
  2086. Vector<XrActiveActionSet> active_sets;
  2087. for (int i = 0; i < p_active_sets.size(); i++) {
  2088. ActionSet *action_set = action_set_owner.get_or_null(p_active_sets[i]);
  2089. if (action_set && action_set->handle != XR_NULL_HANDLE) {
  2090. XrActiveActionSet aset;
  2091. aset.actionSet = action_set->handle;
  2092. aset.subactionPath = XR_NULL_PATH;
  2093. active_sets.push_back(aset);
  2094. }
  2095. }
  2096. ERR_FAIL_COND_V(active_sets.size() == 0, false);
  2097. XrActionsSyncInfo sync_info = {
  2098. XR_TYPE_ACTIONS_SYNC_INFO, // type
  2099. nullptr, // next
  2100. uint32_t(active_sets.size()), // countActiveActionSets
  2101. active_sets.ptr() // activeActionSets
  2102. };
  2103. XrResult result = xrSyncActions(session, &sync_info);
  2104. if (XR_FAILED(result)) {
  2105. print_line("OpenXR: failed to sync active action sets! [", get_error_string(result), "]");
  2106. return false;
  2107. }
  2108. return true;
  2109. }
  2110. bool OpenXRAPI::get_action_bool(RID p_action, RID p_tracker) {
  2111. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2112. Action *action = action_owner.get_or_null(p_action);
  2113. ERR_FAIL_NULL_V(action, false);
  2114. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2115. ERR_FAIL_NULL_V(tracker, false);
  2116. if (!running) {
  2117. return false;
  2118. }
  2119. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_BOOLEAN_INPUT, false);
  2120. XrActionStateGetInfo get_info = {
  2121. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2122. nullptr, // next
  2123. action->handle, // action
  2124. tracker->toplevel_path // subactionPath
  2125. };
  2126. XrActionStateBoolean result_state;
  2127. result_state.type = XR_TYPE_ACTION_STATE_BOOLEAN,
  2128. result_state.next = nullptr;
  2129. XrResult result = xrGetActionStateBoolean(session, &get_info, &result_state);
  2130. if (XR_FAILED(result)) {
  2131. print_line("OpenXR: couldn't get action boolean! [", get_error_string(result), "]");
  2132. return false;
  2133. }
  2134. return result_state.isActive && result_state.currentState;
  2135. }
  2136. float OpenXRAPI::get_action_float(RID p_action, RID p_tracker) {
  2137. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, 0.0);
  2138. Action *action = action_owner.get_or_null(p_action);
  2139. ERR_FAIL_NULL_V(action, 0.0);
  2140. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2141. ERR_FAIL_NULL_V(tracker, 0.0);
  2142. if (!running) {
  2143. return 0.0;
  2144. }
  2145. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_FLOAT_INPUT, 0.0);
  2146. XrActionStateGetInfo get_info = {
  2147. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2148. nullptr, // next
  2149. action->handle, // action
  2150. tracker->toplevel_path // subactionPath
  2151. };
  2152. XrActionStateFloat result_state;
  2153. result_state.type = XR_TYPE_ACTION_STATE_FLOAT,
  2154. result_state.next = nullptr;
  2155. XrResult result = xrGetActionStateFloat(session, &get_info, &result_state);
  2156. if (XR_FAILED(result)) {
  2157. print_line("OpenXR: couldn't get action float! [", get_error_string(result), "]");
  2158. return 0.0;
  2159. }
  2160. return result_state.isActive ? result_state.currentState : 0.0;
  2161. }
  2162. Vector2 OpenXRAPI::get_action_vector2(RID p_action, RID p_tracker) {
  2163. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, Vector2());
  2164. Action *action = action_owner.get_or_null(p_action);
  2165. ERR_FAIL_NULL_V(action, Vector2());
  2166. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2167. ERR_FAIL_NULL_V(tracker, Vector2());
  2168. if (!running) {
  2169. return Vector2();
  2170. }
  2171. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VECTOR2F_INPUT, Vector2());
  2172. XrActionStateGetInfo get_info = {
  2173. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2174. nullptr, // next
  2175. action->handle, // action
  2176. tracker->toplevel_path // subactionPath
  2177. };
  2178. XrActionStateVector2f result_state;
  2179. result_state.type = XR_TYPE_ACTION_STATE_VECTOR2F,
  2180. result_state.next = nullptr;
  2181. XrResult result = xrGetActionStateVector2f(session, &get_info, &result_state);
  2182. if (XR_FAILED(result)) {
  2183. print_line("OpenXR: couldn't get action vector2! [", get_error_string(result), "]");
  2184. return Vector2();
  2185. }
  2186. return result_state.isActive ? Vector2(result_state.currentState.x, result_state.currentState.y) : Vector2();
  2187. }
  2188. XRPose::TrackingConfidence OpenXRAPI::get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  2189. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2190. Action *action = action_owner.get_or_null(p_action);
  2191. ERR_FAIL_NULL_V(action, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2192. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2193. ERR_FAIL_NULL_V(tracker, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2194. if (!running) {
  2195. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2196. }
  2197. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_POSE_INPUT, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2198. // print_verbose("Checking " + action->name + " => " + tracker->name + " (" + itos(tracker->toplevel_path) + ")");
  2199. uint64_t index = 0xFFFFFFFF;
  2200. uint64_t size = uint64_t(action->trackers.size());
  2201. for (uint64_t i = 0; i < size && index == 0xFFFFFFFF; i++) {
  2202. if (action->trackers[i].tracker_rid == p_tracker) {
  2203. index = i;
  2204. }
  2205. }
  2206. if (index == 0xFFFFFFFF) {
  2207. // couldn't find it?
  2208. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2209. }
  2210. XrTime display_time = get_next_frame_time();
  2211. if (display_time == 0) {
  2212. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2213. }
  2214. if (action->trackers[index].space == XR_NULL_HANDLE) {
  2215. // if this is a pose we need to define spaces
  2216. XrActionSpaceCreateInfo action_space_info = {
  2217. XR_TYPE_ACTION_SPACE_CREATE_INFO, // type
  2218. nullptr, // next
  2219. action->handle, // action
  2220. tracker->toplevel_path, // subactionPath
  2221. {
  2222. { 0.0, 0.0, 0.0, 1.0 }, // orientation
  2223. { 0.0, 0.0, 0.0 } // position
  2224. } // poseInActionSpace
  2225. };
  2226. XrSpace space;
  2227. XrResult result = xrCreateActionSpace(session, &action_space_info, &space);
  2228. if (XR_FAILED(result)) {
  2229. print_line("OpenXR: couldn't create action space! [", get_error_string(result), "]");
  2230. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2231. }
  2232. action->trackers.ptrw()[index].space = space;
  2233. }
  2234. XrSpaceVelocity velocity = {
  2235. XR_TYPE_SPACE_VELOCITY, // type
  2236. nullptr, // next
  2237. 0, // velocityFlags
  2238. { 0.0, 0.0, 0.0 }, // linearVelocity
  2239. { 0.0, 0.0, 0.0 } // angularVelocity
  2240. };
  2241. XrSpaceLocation location = {
  2242. XR_TYPE_SPACE_LOCATION, // type
  2243. &velocity, // next
  2244. 0, // locationFlags
  2245. {
  2246. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  2247. { 0.0, 0.0, 0.0 } // position
  2248. } // pose
  2249. };
  2250. XrResult result = xrLocateSpace(action->trackers[index].space, play_space, display_time, &location);
  2251. if (XR_FAILED(result)) {
  2252. print_line("OpenXR: failed to locate space! [", get_error_string(result), "]");
  2253. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2254. }
  2255. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  2256. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  2257. return confidence;
  2258. }
  2259. bool OpenXRAPI::trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns) {
  2260. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2261. Action *action = action_owner.get_or_null(p_action);
  2262. ERR_FAIL_NULL_V(action, false);
  2263. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2264. ERR_FAIL_NULL_V(tracker, false);
  2265. if (!running) {
  2266. return false;
  2267. }
  2268. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT, false);
  2269. XrHapticActionInfo action_info = {
  2270. XR_TYPE_HAPTIC_ACTION_INFO, // type
  2271. nullptr, // next
  2272. action->handle, // action
  2273. tracker->toplevel_path // subactionPath
  2274. };
  2275. XrHapticVibration vibration = {
  2276. XR_TYPE_HAPTIC_VIBRATION, // type
  2277. nullptr, // next
  2278. p_duration_ns, // duration
  2279. p_frequency, // frequency
  2280. p_amplitude, // amplitude
  2281. };
  2282. XrResult result = xrApplyHapticFeedback(session, &action_info, (const XrHapticBaseHeader *)&vibration);
  2283. if (XR_FAILED(result)) {
  2284. print_line("OpenXR: failed to apply haptic feedback! [", get_error_string(result), "]");
  2285. return false;
  2286. }
  2287. return true;
  2288. }
  2289. void OpenXRAPI::register_composition_layer_provider(OpenXRCompositionLayerProvider *provider) {
  2290. composition_layer_providers.append(provider);
  2291. }
  2292. void OpenXRAPI::unregister_composition_layer_provider(OpenXRCompositionLayerProvider *provider) {
  2293. composition_layer_providers.erase(provider);
  2294. }
  2295. const XrEnvironmentBlendMode *OpenXRAPI::get_supported_environment_blend_modes(uint32_t &count) {
  2296. count = num_supported_environment_blend_modes;
  2297. return supported_environment_blend_modes;
  2298. }
  2299. bool OpenXRAPI::set_environment_blend_mode(XrEnvironmentBlendMode mode) {
  2300. for (uint32_t i = 0; i < num_supported_environment_blend_modes; i++) {
  2301. if (supported_environment_blend_modes[i] == mode) {
  2302. environment_blend_mode = mode;
  2303. return true;
  2304. }
  2305. }
  2306. return false;
  2307. }