openxr_api.cpp 87 KB

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