openxr_api.cpp 90 KB

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