openxr_api.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724
  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've enabled submitting depth buffer
  601. // - we support our depth layer extension
  602. // - we have our spacewarp extension (not yet implemented)
  603. if (submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available()) {
  604. // Build a vector with swapchain formats we want to use, from best fit to worst
  605. Vector<int64_t> usable_swapchain_formats;
  606. int64_t swapchain_format_to_use = 0;
  607. graphics_extension->get_usable_depth_formats(usable_swapchain_formats);
  608. // now find out which one is supported
  609. for (int i = 0; i < usable_swapchain_formats.size() && swapchain_format_to_use == 0; i++) {
  610. if (is_swapchain_format_supported(usable_swapchain_formats[i])) {
  611. swapchain_format_to_use = usable_swapchain_formats[i];
  612. }
  613. }
  614. if (swapchain_format_to_use == 0) {
  615. swapchain_format_to_use = usable_swapchain_formats[0]; // just use the first one and hope for the best...
  616. print_line("Couldn't find usable depth swap chain format, using", get_swapchain_format_name(swapchain_format_to_use), "instead.");
  617. } else {
  618. print_verbose(String("Using depth swap chain format:") + get_swapchain_format_name(swapchain_format_to_use));
  619. }
  620. 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)) {
  621. return false;
  622. }
  623. depth_views = (XrCompositionLayerDepthInfoKHR *)memalloc(sizeof(XrCompositionLayerDepthInfoKHR) * view_count);
  624. ERR_FAIL_NULL_V_MSG(depth_views, false, "OpenXR Couldn't allocate memory for depth views");
  625. }
  626. // We create our velocity swapchain if:
  627. // - we have our spacewarp extension (not yet implemented)
  628. {
  629. // TBD
  630. }
  631. for (uint32_t i = 0; i < view_count; i++) {
  632. views[i].type = XR_TYPE_VIEW;
  633. views[i].next = nullptr;
  634. projection_views[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
  635. projection_views[i].next = nullptr;
  636. projection_views[i].subImage.swapchain = swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain;
  637. projection_views[i].subImage.imageArrayIndex = i;
  638. projection_views[i].subImage.imageRect.offset.x = 0;
  639. projection_views[i].subImage.imageRect.offset.y = 0;
  640. projection_views[i].subImage.imageRect.extent.width = recommended_size.width;
  641. projection_views[i].subImage.imageRect.extent.height = recommended_size.height;
  642. if (submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available() && depth_views) {
  643. projection_views[i].next = &depth_views[i];
  644. depth_views[i].type = XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR;
  645. depth_views[i].next = nullptr;
  646. depth_views[i].subImage.swapchain = swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain;
  647. depth_views[i].subImage.imageArrayIndex = i;
  648. depth_views[i].subImage.imageRect.offset.x = 0;
  649. depth_views[i].subImage.imageRect.offset.y = 0;
  650. depth_views[i].subImage.imageRect.extent.width = recommended_size.width;
  651. depth_views[i].subImage.imageRect.extent.height = recommended_size.height;
  652. depth_views[i].minDepth = 0.0;
  653. depth_views[i].maxDepth = 1.0;
  654. depth_views[i].nearZ = 0.01; // Near and far Z will be set to the correct values in fill_projection_matrix
  655. depth_views[i].farZ = 100.0;
  656. }
  657. };
  658. return true;
  659. };
  660. void OpenXRAPI::destroy_session() {
  661. if (running && session != XR_NULL_HANDLE) {
  662. xrEndSession(session);
  663. }
  664. if (graphics_extension) {
  665. graphics_extension->cleanup_swapchain_graphics_data(&swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data);
  666. }
  667. if (views != nullptr) {
  668. memfree(views);
  669. views = nullptr;
  670. }
  671. if (projection_views != nullptr) {
  672. memfree(projection_views);
  673. projection_views = nullptr;
  674. }
  675. if (depth_views != nullptr) {
  676. memfree(depth_views);
  677. depth_views = nullptr;
  678. }
  679. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  680. if (swapchains[i].swapchain != XR_NULL_HANDLE) {
  681. xrDestroySwapchain(swapchains[i].swapchain);
  682. swapchains[i].swapchain = XR_NULL_HANDLE;
  683. }
  684. }
  685. if (supported_swapchain_formats != nullptr) {
  686. memfree(supported_swapchain_formats);
  687. supported_swapchain_formats = nullptr;
  688. }
  689. // destroy our spaces
  690. if (play_space != XR_NULL_HANDLE) {
  691. xrDestroySpace(play_space);
  692. play_space = XR_NULL_HANDLE;
  693. }
  694. if (view_space != XR_NULL_HANDLE) {
  695. xrDestroySpace(view_space);
  696. view_space = XR_NULL_HANDLE;
  697. }
  698. if (supported_reference_spaces != nullptr) {
  699. // free previous results
  700. memfree(supported_reference_spaces);
  701. supported_reference_spaces = nullptr;
  702. }
  703. if (session != XR_NULL_HANDLE) {
  704. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  705. wrapper->on_session_destroyed();
  706. }
  707. xrDestroySession(session);
  708. session = XR_NULL_HANDLE;
  709. }
  710. }
  711. 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) {
  712. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  713. ERR_FAIL_NULL_V(graphics_extension, false);
  714. XrResult result;
  715. void *next_pointer = nullptr;
  716. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  717. void *np = wrapper->set_swapchain_create_info_and_get_next_pointer(next_pointer);
  718. if (np != nullptr) {
  719. next_pointer = np;
  720. }
  721. }
  722. XrSwapchainCreateInfo swapchain_create_info = {
  723. XR_TYPE_SWAPCHAIN_CREATE_INFO, // type
  724. next_pointer, // next
  725. 0, // createFlags
  726. p_usage_flags, // usageFlags
  727. p_swapchain_format, // format
  728. p_sample_count, // sampleCount
  729. p_width, // width
  730. p_height, // height
  731. 1, // faceCount
  732. p_array_size, // arraySize
  733. 1 // mipCount
  734. };
  735. XrSwapchain new_swapchain;
  736. result = xrCreateSwapchain(session, &swapchain_create_info, &new_swapchain);
  737. if (XR_FAILED(result)) {
  738. print_line("OpenXR: Failed to get swapchain [", get_error_string(result), "]");
  739. return false;
  740. }
  741. 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)) {
  742. xrDestroySwapchain(new_swapchain);
  743. return false;
  744. }
  745. r_swapchain = new_swapchain;
  746. return true;
  747. }
  748. bool OpenXRAPI::on_state_idle() {
  749. print_verbose("On state idle");
  750. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  751. wrapper->on_state_idle();
  752. }
  753. return true;
  754. }
  755. bool OpenXRAPI::on_state_ready() {
  756. print_verbose("On state ready");
  757. // begin session
  758. XrSessionBeginInfo session_begin_info = {
  759. XR_TYPE_SESSION_BEGIN_INFO, // type
  760. nullptr, // next
  761. view_configuration // primaryViewConfigurationType
  762. };
  763. XrResult result = xrBeginSession(session, &session_begin_info);
  764. if (XR_FAILED(result)) {
  765. print_line("OpenXR: Failed to begin session [", get_error_string(result), "]");
  766. return false;
  767. }
  768. // This is when we create our swapchain, this can be a "long" time after Godot finishes, we can deal with this for now
  769. // but once we want to provide Viewports for additional layers where OpenXR requires us to create further swapchains,
  770. // we'll be creating those viewport WAY before we reach this point.
  771. // We may need to implement a wait in our init in main.cpp polling our events until the session is ready.
  772. // That will be very very ugly
  773. // The other possibility is to create a separate OpenXRViewport type specifically for this goal as part of our OpenXR module
  774. if (!create_swapchains()) {
  775. return false;
  776. }
  777. // we're running
  778. running = true;
  779. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  780. wrapper->on_state_ready();
  781. }
  782. if (xr_interface) {
  783. xr_interface->on_state_ready();
  784. }
  785. // TODO Tell android
  786. return true;
  787. }
  788. bool OpenXRAPI::on_state_synchronized() {
  789. print_verbose("On state synchronized");
  790. // Just in case, see if we already have active trackers...
  791. List<RID> trackers;
  792. tracker_owner.get_owned_list(&trackers);
  793. for (int i = 0; i < trackers.size(); i++) {
  794. tracker_check_profile(trackers[i]);
  795. }
  796. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  797. wrapper->on_state_synchronized();
  798. }
  799. return true;
  800. }
  801. bool OpenXRAPI::on_state_visible() {
  802. print_verbose("On state visible");
  803. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  804. wrapper->on_state_visible();
  805. }
  806. if (xr_interface) {
  807. xr_interface->on_state_visible();
  808. }
  809. return true;
  810. }
  811. bool OpenXRAPI::on_state_focused() {
  812. print_verbose("On state focused");
  813. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  814. wrapper->on_state_focused();
  815. }
  816. if (xr_interface) {
  817. xr_interface->on_state_focused();
  818. }
  819. return true;
  820. }
  821. bool OpenXRAPI::on_state_stopping() {
  822. print_verbose("On state stopping");
  823. if (xr_interface) {
  824. xr_interface->on_state_stopping();
  825. }
  826. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  827. wrapper->on_state_stopping();
  828. }
  829. if (running) {
  830. XrResult result = xrEndSession(session);
  831. if (XR_FAILED(result)) {
  832. // we only report this..
  833. print_line("OpenXR: Failed to end session [", get_error_string(result), "]");
  834. }
  835. running = false;
  836. }
  837. // TODO further cleanup
  838. return true;
  839. }
  840. bool OpenXRAPI::on_state_loss_pending() {
  841. print_verbose("On state loss pending");
  842. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  843. wrapper->on_state_loss_pending();
  844. }
  845. // 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)
  846. return true;
  847. }
  848. bool OpenXRAPI::on_state_exiting() {
  849. print_verbose("On state existing");
  850. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  851. wrapper->on_state_exiting();
  852. }
  853. // 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)
  854. return true;
  855. }
  856. void OpenXRAPI::set_form_factor(XrFormFactor p_form_factor) {
  857. ERR_FAIL_COND(is_initialized());
  858. form_factor = p_form_factor;
  859. }
  860. void OpenXRAPI::set_view_configuration(XrViewConfigurationType p_view_configuration) {
  861. ERR_FAIL_COND(is_initialized());
  862. view_configuration = p_view_configuration;
  863. }
  864. void OpenXRAPI::set_reference_space(XrReferenceSpaceType p_reference_space) {
  865. ERR_FAIL_COND(is_initialized());
  866. reference_space = p_reference_space;
  867. }
  868. void OpenXRAPI::set_submit_depth_buffer(bool p_submit_depth_buffer) {
  869. ERR_FAIL_COND(is_initialized());
  870. submit_depth_buffer = p_submit_depth_buffer;
  871. }
  872. bool OpenXRAPI::is_initialized() {
  873. return (instance != XR_NULL_HANDLE);
  874. }
  875. bool OpenXRAPI::is_running() {
  876. if (instance == XR_NULL_HANDLE) {
  877. return false;
  878. }
  879. if (session == XR_NULL_HANDLE) {
  880. return false;
  881. }
  882. return running;
  883. }
  884. bool OpenXRAPI::openxr_loader_init() {
  885. #ifdef ANDROID_ENABLED
  886. ERR_FAIL_COND_V_MSG(openxr_loader_library_handle != nullptr, false, "OpenXR Loader library is already loaded.");
  887. {
  888. Error error_code = OS::get_singleton()->open_dynamic_library(OPENXR_LOADER_NAME, openxr_loader_library_handle);
  889. ERR_FAIL_COND_V_MSG(error_code != OK, false, "OpenXR loader not found.");
  890. }
  891. {
  892. Error error_code = OS::get_singleton()->get_dynamic_library_symbol_handle(openxr_loader_library_handle, "xrGetInstanceProcAddr", (void *&)xrGetInstanceProcAddr);
  893. ERR_FAIL_COND_V_MSG(error_code != OK, false, "Symbol xrGetInstanceProcAddr not found in OpenXR Loader library.");
  894. }
  895. #endif
  896. // Resolve the symbols that don't require an instance
  897. OPENXR_API_INIT_XR_FUNC_V(xrCreateInstance);
  898. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateApiLayerProperties);
  899. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateInstanceExtensionProperties);
  900. return true;
  901. }
  902. bool OpenXRAPI::resolve_instance_openxr_symbols() {
  903. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  904. OPENXR_API_INIT_XR_FUNC_V(xrAcquireSwapchainImage);
  905. OPENXR_API_INIT_XR_FUNC_V(xrApplyHapticFeedback);
  906. OPENXR_API_INIT_XR_FUNC_V(xrAttachSessionActionSets);
  907. OPENXR_API_INIT_XR_FUNC_V(xrBeginFrame);
  908. OPENXR_API_INIT_XR_FUNC_V(xrBeginSession);
  909. OPENXR_API_INIT_XR_FUNC_V(xrCreateAction);
  910. OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSet);
  911. OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSpace);
  912. OPENXR_API_INIT_XR_FUNC_V(xrCreateReferenceSpace);
  913. OPENXR_API_INIT_XR_FUNC_V(xrCreateSession);
  914. OPENXR_API_INIT_XR_FUNC_V(xrCreateSwapchain);
  915. OPENXR_API_INIT_XR_FUNC_V(xrDestroyAction);
  916. OPENXR_API_INIT_XR_FUNC_V(xrDestroyActionSet);
  917. OPENXR_API_INIT_XR_FUNC_V(xrDestroyInstance);
  918. OPENXR_API_INIT_XR_FUNC_V(xrDestroySession);
  919. OPENXR_API_INIT_XR_FUNC_V(xrDestroySpace);
  920. OPENXR_API_INIT_XR_FUNC_V(xrDestroySwapchain);
  921. OPENXR_API_INIT_XR_FUNC_V(xrEndFrame);
  922. OPENXR_API_INIT_XR_FUNC_V(xrEndSession);
  923. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateReferenceSpaces);
  924. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateSwapchainFormats);
  925. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurations);
  926. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurationViews);
  927. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateBoolean);
  928. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateFloat);
  929. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateVector2f);
  930. OPENXR_API_INIT_XR_FUNC_V(xrGetCurrentInteractionProfile);
  931. OPENXR_API_INIT_XR_FUNC_V(xrGetSystem);
  932. OPENXR_API_INIT_XR_FUNC_V(xrGetSystemProperties);
  933. OPENXR_API_INIT_XR_FUNC_V(xrLocateViews);
  934. OPENXR_API_INIT_XR_FUNC_V(xrLocateSpace);
  935. OPENXR_API_INIT_XR_FUNC_V(xrPathToString);
  936. OPENXR_API_INIT_XR_FUNC_V(xrPollEvent);
  937. OPENXR_API_INIT_XR_FUNC_V(xrReleaseSwapchainImage);
  938. OPENXR_API_INIT_XR_FUNC_V(xrResultToString);
  939. OPENXR_API_INIT_XR_FUNC_V(xrStringToPath);
  940. OPENXR_API_INIT_XR_FUNC_V(xrSuggestInteractionProfileBindings);
  941. OPENXR_API_INIT_XR_FUNC_V(xrSyncActions);
  942. OPENXR_API_INIT_XR_FUNC_V(xrWaitFrame);
  943. OPENXR_API_INIT_XR_FUNC_V(xrWaitSwapchainImage);
  944. return true;
  945. }
  946. XrResult OpenXRAPI::get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) {
  947. XrResult result = xrGetInstanceProcAddr(instance, p_name, p_addr);
  948. if (result != XR_SUCCESS) {
  949. String error_message = String("Symbol ") + p_name + " not found in OpenXR instance.";
  950. ERR_FAIL_COND_V_MSG(true, result, error_message.utf8().get_data());
  951. }
  952. return result;
  953. }
  954. bool OpenXRAPI::initialize(const String &p_rendering_driver) {
  955. ERR_FAIL_COND_V_MSG(instance != XR_NULL_HANDLE, false, "OpenXR instance was already created");
  956. if (!openxr_loader_init()) {
  957. return false;
  958. }
  959. if (p_rendering_driver == "vulkan") {
  960. #ifdef VULKAN_ENABLED
  961. graphics_extension = memnew(OpenXRVulkanExtension(this));
  962. register_extension_wrapper(graphics_extension);
  963. #else
  964. // shouldn't be possible...
  965. ERR_FAIL_V(false);
  966. #endif
  967. } else if (p_rendering_driver == "opengl3") {
  968. #ifdef GLES3_ENABLED
  969. graphics_extension = memnew(OpenXROpenGLExtension(this));
  970. register_extension_wrapper(graphics_extension);
  971. #else
  972. // shouldn't be possible...
  973. ERR_FAIL_V(false);
  974. #endif
  975. } else {
  976. ERR_FAIL_V_MSG(false, "OpenXR: Unsupported rendering device.");
  977. }
  978. // initialize
  979. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  980. wrapper->on_before_instance_created();
  981. }
  982. if (!load_layer_properties()) {
  983. destroy_instance();
  984. return false;
  985. }
  986. if (!load_supported_extensions()) {
  987. destroy_instance();
  988. return false;
  989. }
  990. if (!create_instance()) {
  991. destroy_instance();
  992. return false;
  993. }
  994. if (!resolve_instance_openxr_symbols()) {
  995. destroy_instance();
  996. return false;
  997. }
  998. if (!get_system_info()) {
  999. destroy_instance();
  1000. return false;
  1001. }
  1002. if (!load_supported_view_configuration_types()) {
  1003. destroy_instance();
  1004. return false;
  1005. }
  1006. if (!load_supported_view_configuration_views(view_configuration)) {
  1007. destroy_instance();
  1008. return false;
  1009. }
  1010. return true;
  1011. }
  1012. bool OpenXRAPI::initialize_session() {
  1013. if (!create_session()) {
  1014. destroy_session();
  1015. return false;
  1016. }
  1017. if (!load_supported_reference_spaces()) {
  1018. destroy_session();
  1019. return false;
  1020. }
  1021. if (!setup_spaces()) {
  1022. destroy_session();
  1023. return false;
  1024. }
  1025. if (!load_supported_swapchain_formats()) {
  1026. destroy_session();
  1027. return false;
  1028. }
  1029. return true;
  1030. }
  1031. void OpenXRAPI::finish() {
  1032. destroy_session();
  1033. destroy_instance();
  1034. }
  1035. void OpenXRAPI::set_xr_interface(OpenXRInterface *p_xr_interface) {
  1036. xr_interface = p_xr_interface;
  1037. }
  1038. void OpenXRAPI::register_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
  1039. registered_extension_wrappers.push_back(p_extension_wrapper);
  1040. }
  1041. Size2 OpenXRAPI::get_recommended_target_size() {
  1042. ERR_FAIL_NULL_V(view_configuration_views, Size2());
  1043. Size2 target_size;
  1044. target_size.width = view_configuration_views[0].recommendedImageRectWidth;
  1045. target_size.height = view_configuration_views[0].recommendedImageRectHeight;
  1046. return target_size;
  1047. }
  1048. XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  1049. XrResult result;
  1050. ERR_FAIL_COND_V(!running, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  1051. // xrWaitFrame not run yet
  1052. if (frame_state.predictedDisplayTime == 0) {
  1053. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1054. }
  1055. // Get timing for the next frame, as that is the current frame we're processing
  1056. XrTime display_time = get_next_frame_time();
  1057. XrSpaceVelocity velocity = {
  1058. XR_TYPE_SPACE_VELOCITY, // type
  1059. nullptr, // next
  1060. 0, // velocityFlags
  1061. { 0.0, 0.0, 0.0 }, // linearVelocity
  1062. { 0.0, 0.0, 0.0 } // angularVelocity
  1063. };
  1064. XrSpaceLocation location = {
  1065. XR_TYPE_SPACE_LOCATION, // type
  1066. &velocity, // next
  1067. 0, // locationFlags
  1068. {
  1069. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  1070. { 0.0, 0.0, 0.0 } // position
  1071. } // pose
  1072. };
  1073. result = xrLocateSpace(view_space, play_space, display_time, &location);
  1074. if (XR_FAILED(result)) {
  1075. print_line("OpenXR: Failed to locate view space in play space [", get_error_string(result), "]");
  1076. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1077. }
  1078. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  1079. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  1080. if (head_pose_confidence != confidence) {
  1081. // prevent error spam
  1082. head_pose_confidence = confidence;
  1083. if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  1084. print_line("OpenXR head space location not valid (check tracking?)");
  1085. } else if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_LOW) {
  1086. print_verbose("OpenVR Head pose now tracking with low confidence");
  1087. } else {
  1088. print_verbose("OpenVR Head pose now tracking with high confidence");
  1089. }
  1090. }
  1091. return confidence;
  1092. }
  1093. bool OpenXRAPI::get_view_transform(uint32_t p_view, Transform3D &r_transform) {
  1094. ERR_FAIL_COND_V(!running, false);
  1095. // xrWaitFrame not run yet
  1096. if (frame_state.predictedDisplayTime == 0) {
  1097. return false;
  1098. }
  1099. // we don't have valid view info
  1100. if (views == nullptr || !view_pose_valid) {
  1101. return false;
  1102. }
  1103. // Note, the timing of this is set right before rendering, which is what we need here.
  1104. r_transform = transform_from_pose(views[p_view].pose);
  1105. return true;
  1106. }
  1107. bool OpenXRAPI::get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, Projection &p_camera_matrix) {
  1108. ERR_FAIL_COND_V(!running, false);
  1109. ERR_FAIL_NULL_V(graphics_extension, false);
  1110. // xrWaitFrame not run yet
  1111. if (frame_state.predictedDisplayTime == 0) {
  1112. return false;
  1113. }
  1114. // we don't have valid view info
  1115. if (views == nullptr || !view_pose_valid) {
  1116. return false;
  1117. }
  1118. // if we're using depth views, make sure we update our near and far there...
  1119. if (depth_views != nullptr) {
  1120. for (uint32_t i = 0; i < view_count; i++) {
  1121. depth_views[i].nearZ = p_z_near;
  1122. depth_views[i].farZ = p_z_far;
  1123. }
  1124. }
  1125. // now update our projection
  1126. return graphics_extension->create_projection_fov(views[p_view].fov, p_z_near, p_z_far, p_camera_matrix);
  1127. }
  1128. bool OpenXRAPI::poll_events() {
  1129. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1130. XrEventDataBuffer runtimeEvent;
  1131. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  1132. runtimeEvent.next = nullptr;
  1133. // runtimeEvent.varying = ...
  1134. XrResult pollResult = xrPollEvent(instance, &runtimeEvent);
  1135. while (pollResult == XR_SUCCESS) {
  1136. bool handled = false;
  1137. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1138. handled |= wrapper->on_event_polled(runtimeEvent);
  1139. }
  1140. switch (runtimeEvent.type) {
  1141. case XR_TYPE_EVENT_DATA_EVENTS_LOST: {
  1142. XrEventDataEventsLost *event = (XrEventDataEventsLost *)&runtimeEvent;
  1143. // We probably didn't poll fast enough, just output warning
  1144. WARN_PRINT("OpenXR EVENT: " + itos(event->lostEventCount) + " event data lost!");
  1145. } break;
  1146. case XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR: {
  1147. // XrEventDataVisibilityMaskChangedKHR *event = (XrEventDataVisibilityMaskChangedKHR *)&runtimeEvent;
  1148. // TODO implement this in the future, we should call xrGetVisibilityMaskKHR to obtain a mask,
  1149. // this will allow us to prevent rendering the part of our view which is never displayed giving us
  1150. // a decent performance improvement.
  1151. print_verbose("OpenXR EVENT: STUB: visibility mask changed");
  1152. } break;
  1153. case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: {
  1154. XrEventDataInstanceLossPending *event = (XrEventDataInstanceLossPending *)&runtimeEvent;
  1155. // TODO We get this event if we're about to loose our OpenXR instance.
  1156. // We should queue exiting Godot at this point.
  1157. print_verbose(String("OpenXR EVENT: instance loss pending at ") + itos(event->lossTime));
  1158. return false;
  1159. } break;
  1160. case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
  1161. XrEventDataSessionStateChanged *event = (XrEventDataSessionStateChanged *)&runtimeEvent;
  1162. session_state = event->state;
  1163. if (session_state >= XR_SESSION_STATE_MAX_ENUM) {
  1164. print_verbose(String("OpenXR EVENT: session state changed to UNKNOWN - ") + itos(session_state));
  1165. } else {
  1166. print_verbose(String("OpenXR EVENT: session state changed to ") + OpenXRUtil::get_session_state_name(session_state));
  1167. switch (session_state) {
  1168. case XR_SESSION_STATE_IDLE:
  1169. on_state_idle();
  1170. break;
  1171. case XR_SESSION_STATE_READY:
  1172. on_state_ready();
  1173. break;
  1174. case XR_SESSION_STATE_SYNCHRONIZED:
  1175. on_state_synchronized();
  1176. break;
  1177. case XR_SESSION_STATE_VISIBLE:
  1178. on_state_visible();
  1179. break;
  1180. case XR_SESSION_STATE_FOCUSED:
  1181. on_state_focused();
  1182. break;
  1183. case XR_SESSION_STATE_STOPPING:
  1184. on_state_stopping();
  1185. break;
  1186. case XR_SESSION_STATE_LOSS_PENDING:
  1187. on_state_loss_pending();
  1188. break;
  1189. case XR_SESSION_STATE_EXITING:
  1190. on_state_exiting();
  1191. break;
  1192. default:
  1193. break;
  1194. }
  1195. }
  1196. } break;
  1197. case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: {
  1198. XrEventDataReferenceSpaceChangePending *event = (XrEventDataReferenceSpaceChangePending *)&runtimeEvent;
  1199. print_verbose(String("OpenXR EVENT: reference space type ") + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!");
  1200. if (event->poseValid && xr_interface) {
  1201. xr_interface->on_pose_recentered();
  1202. }
  1203. } break;
  1204. case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: {
  1205. print_verbose("OpenXR EVENT: interaction profile changed!");
  1206. XrEventDataInteractionProfileChanged *event = (XrEventDataInteractionProfileChanged *)&runtimeEvent;
  1207. List<RID> trackers;
  1208. tracker_owner.get_owned_list(&trackers);
  1209. for (int i = 0; i < trackers.size(); i++) {
  1210. tracker_check_profile(trackers[i], event->session);
  1211. }
  1212. } break;
  1213. default:
  1214. if (!handled) {
  1215. print_verbose(String("OpenXR Unhandled event type ") + OpenXRUtil::get_structure_type_name(runtimeEvent.type));
  1216. }
  1217. break;
  1218. }
  1219. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  1220. pollResult = xrPollEvent(instance, &runtimeEvent);
  1221. }
  1222. if (pollResult == XR_EVENT_UNAVAILABLE) {
  1223. // processed all events in the queue
  1224. return true;
  1225. } else {
  1226. ERR_FAIL_V_MSG(false, "OpenXR: Failed to poll events!");
  1227. }
  1228. }
  1229. bool OpenXRAPI::process() {
  1230. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1231. if (!poll_events()) {
  1232. return false;
  1233. }
  1234. if (!running) {
  1235. return false;
  1236. }
  1237. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1238. wrapper->on_process();
  1239. }
  1240. return true;
  1241. }
  1242. bool OpenXRAPI::acquire_image(OpenXRSwapChainInfo &p_swapchain) {
  1243. ERR_FAIL_COND_V(p_swapchain.image_acquired, true); // this was not released when it should be, error out and re-use...
  1244. XrResult result;
  1245. XrSwapchainImageAcquireInfo swapchain_image_acquire_info = {
  1246. XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, // type
  1247. nullptr // next
  1248. };
  1249. result = xrAcquireSwapchainImage(p_swapchain.swapchain, &swapchain_image_acquire_info, &p_swapchain.image_index);
  1250. if (XR_FAILED(result)) {
  1251. print_line("OpenXR: failed to acquire swapchain image [", get_error_string(result), "]");
  1252. return false;
  1253. }
  1254. XrSwapchainImageWaitInfo swapchain_image_wait_info = {
  1255. XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, // type
  1256. nullptr, // next
  1257. 17000000 // timeout in nanoseconds
  1258. };
  1259. result = xrWaitSwapchainImage(p_swapchain.swapchain, &swapchain_image_wait_info);
  1260. if (XR_FAILED(result)) {
  1261. print_line("OpenXR: failed to wait for swapchain image [", get_error_string(result), "]");
  1262. return false;
  1263. }
  1264. return true;
  1265. }
  1266. bool OpenXRAPI::release_image(OpenXRSwapChainInfo &p_swapchain) {
  1267. XrSwapchainImageReleaseInfo swapchain_image_release_info = {
  1268. XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, // type
  1269. nullptr // next
  1270. };
  1271. XrResult result = xrReleaseSwapchainImage(p_swapchain.swapchain, &swapchain_image_release_info);
  1272. if (XR_FAILED(result)) {
  1273. print_line("OpenXR: failed to release swapchain image! [", get_error_string(result), "]");
  1274. return false;
  1275. }
  1276. return true;
  1277. }
  1278. void OpenXRAPI::pre_render() {
  1279. ERR_FAIL_COND(instance == XR_NULL_HANDLE);
  1280. if (!running) {
  1281. return;
  1282. }
  1283. // Waitframe does 2 important things in our process:
  1284. // 1) It provides us with predictive timing, telling us when OpenXR expects to display the frame we're about to commit
  1285. // 2) It will use the previous timing to pause our thread so that rendering starts as close to displaying as possible
  1286. // This must thus be called as close to when we start rendering as possible
  1287. XrFrameWaitInfo frame_wait_info = { XR_TYPE_FRAME_WAIT_INFO, nullptr };
  1288. frame_state.predictedDisplayTime = 0;
  1289. frame_state.predictedDisplayPeriod = 0;
  1290. frame_state.shouldRender = false;
  1291. XrResult result = xrWaitFrame(session, &frame_wait_info, &frame_state);
  1292. if (XR_FAILED(result)) {
  1293. print_line("OpenXR: xrWaitFrame() was not successful [", get_error_string(result), "]");
  1294. // reset just in case
  1295. frame_state.predictedDisplayTime = 0;
  1296. frame_state.predictedDisplayPeriod = 0;
  1297. frame_state.shouldRender = false;
  1298. return;
  1299. }
  1300. if (frame_state.predictedDisplayPeriod > 500000000) {
  1301. // display period more then 0.5 seconds? must be wrong data
  1302. print_verbose(String("OpenXR resetting invalid display period ") + rtos(frame_state.predictedDisplayPeriod));
  1303. frame_state.predictedDisplayPeriod = 0;
  1304. }
  1305. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1306. wrapper->on_pre_render();
  1307. }
  1308. // Get our view info for the frame we're about to render, note from the OpenXR manual:
  1309. // "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"
  1310. // We're calling this "relatively" early, the positioning we're obtaining here will be used to do our frustum culling,
  1311. // occlusion culling, etc. There is however a technique that we can investigate in the future where after our entire
  1312. // Vulkan command buffer is build, but right before vkSubmitQueue is called, we call xrLocateViews one more time and
  1313. // update the view and projection matrix once more with a slightly more accurate predication and then submit the
  1314. // command queues.
  1315. // That is not possible yet but worth investigating in the future.
  1316. XrViewLocateInfo view_locate_info = {
  1317. XR_TYPE_VIEW_LOCATE_INFO, // type
  1318. nullptr, // next
  1319. view_configuration, // viewConfigurationType
  1320. frame_state.predictedDisplayTime, // displayTime
  1321. play_space // space
  1322. };
  1323. XrViewState view_state = {
  1324. XR_TYPE_VIEW_STATE, // type
  1325. nullptr, // next
  1326. 0 // viewStateFlags
  1327. };
  1328. uint32_t view_count_output;
  1329. result = xrLocateViews(session, &view_locate_info, &view_state, view_count, &view_count_output, views);
  1330. if (XR_FAILED(result)) {
  1331. print_line("OpenXR: Couldn't locate views [", get_error_string(result), "]");
  1332. return;
  1333. }
  1334. bool pose_valid = true;
  1335. for (uint64_t i = 0; i < view_count_output; i++) {
  1336. if ((view_state.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0 ||
  1337. (view_state.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0) {
  1338. pose_valid = false;
  1339. }
  1340. }
  1341. if (view_pose_valid != pose_valid) {
  1342. view_pose_valid = pose_valid;
  1343. if (!view_pose_valid) {
  1344. print_verbose("OpenXR View pose became invalid");
  1345. } else {
  1346. print_verbose("OpenXR View pose became valid");
  1347. }
  1348. }
  1349. // let's start our frame..
  1350. XrFrameBeginInfo frame_begin_info = {
  1351. XR_TYPE_FRAME_BEGIN_INFO, // type
  1352. nullptr // next
  1353. };
  1354. result = xrBeginFrame(session, &frame_begin_info);
  1355. if (XR_FAILED(result)) {
  1356. print_line("OpenXR: failed to being frame [", get_error_string(result), "]");
  1357. return;
  1358. }
  1359. }
  1360. bool OpenXRAPI::pre_draw_viewport(RID p_render_target) {
  1361. if (!can_render()) {
  1362. return false;
  1363. }
  1364. // TODO: at some point in time we may support multiple viewports in which case we need to handle that...
  1365. // Acquire our images
  1366. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  1367. if (!swapchains[i].image_acquired && swapchains[i].swapchain != XR_NULL_HANDLE) {
  1368. if (!acquire_image(swapchains[i])) {
  1369. return false;
  1370. }
  1371. swapchains[i].image_acquired = true;
  1372. }
  1373. }
  1374. return true;
  1375. }
  1376. RID OpenXRAPI::get_color_texture() {
  1377. if (swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) {
  1378. return graphics_extension->get_texture(swapchains[OPENXR_SWAPCHAIN_COLOR].swapchain_graphics_data, swapchains[OPENXR_SWAPCHAIN_COLOR].image_index);
  1379. } else {
  1380. return RID();
  1381. }
  1382. }
  1383. RID OpenXRAPI::get_depth_texture() {
  1384. if (submit_depth_buffer && swapchains[OPENXR_SWAPCHAIN_DEPTH].image_acquired) {
  1385. return graphics_extension->get_texture(swapchains[OPENXR_SWAPCHAIN_DEPTH].swapchain_graphics_data, swapchains[OPENXR_SWAPCHAIN_DEPTH].image_index);
  1386. } else {
  1387. return RID();
  1388. }
  1389. }
  1390. void OpenXRAPI::post_draw_viewport(RID p_render_target) {
  1391. if (!can_render()) {
  1392. return;
  1393. }
  1394. // Nothing to do here at this point in time...
  1395. };
  1396. void OpenXRAPI::end_frame() {
  1397. XrResult result;
  1398. ERR_FAIL_COND(instance == XR_NULL_HANDLE);
  1399. if (!running) {
  1400. return;
  1401. }
  1402. if (frame_state.shouldRender && view_pose_valid && !swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) {
  1403. print_line("OpenXR: No viewport was marked with use_xr, there is no rendered output!");
  1404. }
  1405. // must have:
  1406. // - shouldRender set to true
  1407. // - a valid view pose for projection_views[eye].pose to submit layer
  1408. // - an image to render
  1409. if (!frame_state.shouldRender || !view_pose_valid || !swapchains[OPENXR_SWAPCHAIN_COLOR].image_acquired) {
  1410. // submit 0 layers when we shouldn't render
  1411. XrFrameEndInfo frame_end_info = {
  1412. XR_TYPE_FRAME_END_INFO, // type
  1413. nullptr, // next
  1414. frame_state.predictedDisplayTime, // displayTime
  1415. XR_ENVIRONMENT_BLEND_MODE_OPAQUE, // environmentBlendMode
  1416. 0, // layerCount
  1417. nullptr // layers
  1418. };
  1419. result = xrEndFrame(session, &frame_end_info);
  1420. if (XR_FAILED(result)) {
  1421. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1422. return;
  1423. }
  1424. // neither eye is rendered
  1425. return;
  1426. }
  1427. // release our swapchain image if we acquired it
  1428. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  1429. if (swapchains[i].image_acquired) {
  1430. swapchains[i].image_acquired = false; // whether we succeed or not, consider this released.
  1431. release_image(swapchains[i]);
  1432. }
  1433. }
  1434. for (uint32_t eye = 0; eye < view_count; eye++) {
  1435. projection_views[eye].fov = views[eye].fov;
  1436. projection_views[eye].pose = views[eye].pose;
  1437. }
  1438. Vector<const XrCompositionLayerBaseHeader *> layers_list;
  1439. // Add composition layers from providers
  1440. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  1441. XrCompositionLayerBaseHeader *layer = provider->get_composition_layer();
  1442. if (layer) {
  1443. layers_list.push_back(layer);
  1444. }
  1445. }
  1446. XrCompositionLayerProjection projection_layer = {
  1447. XR_TYPE_COMPOSITION_LAYER_PROJECTION, // type
  1448. nullptr, // next
  1449. 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
  1450. play_space, // space
  1451. view_count, // viewCount
  1452. projection_views, // views
  1453. };
  1454. layers_list.push_back((const XrCompositionLayerBaseHeader *)&projection_layer);
  1455. XrFrameEndInfo frame_end_info = {
  1456. XR_TYPE_FRAME_END_INFO, // type
  1457. nullptr, // next
  1458. frame_state.predictedDisplayTime, // displayTime
  1459. XR_ENVIRONMENT_BLEND_MODE_OPAQUE, // environmentBlendMode
  1460. static_cast<uint32_t>(layers_list.size()), // layerCount
  1461. layers_list.ptr() // layers
  1462. };
  1463. result = xrEndFrame(session, &frame_end_info);
  1464. if (XR_FAILED(result)) {
  1465. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1466. return;
  1467. }
  1468. }
  1469. float OpenXRAPI::get_display_refresh_rate() const {
  1470. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1471. if (drrext) {
  1472. return drrext->get_refresh_rate();
  1473. }
  1474. return 0.0;
  1475. }
  1476. void OpenXRAPI::set_display_refresh_rate(float p_refresh_rate) {
  1477. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1478. if (drrext != nullptr) {
  1479. drrext->set_refresh_rate(p_refresh_rate);
  1480. }
  1481. }
  1482. Array OpenXRAPI::get_available_display_refresh_rates() const {
  1483. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1484. if (drrext != nullptr) {
  1485. return drrext->get_available_refresh_rates();
  1486. }
  1487. return Array();
  1488. }
  1489. OpenXRAPI::OpenXRAPI() {
  1490. // OpenXRAPI is only constructed if OpenXR is enabled.
  1491. singleton = this;
  1492. if (Engine::get_singleton()->is_editor_hint()) {
  1493. // Enabled OpenXR in the editor? Adjust our settings for the editor
  1494. } else {
  1495. // Load settings from project settings
  1496. int ff = GLOBAL_GET("xr/openxr/form_factor");
  1497. switch (ff) {
  1498. case 0: {
  1499. form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
  1500. } break;
  1501. case 1: {
  1502. form_factor = XR_FORM_FACTOR_HANDHELD_DISPLAY;
  1503. } break;
  1504. default:
  1505. break;
  1506. }
  1507. int vc = GLOBAL_GET("xr/openxr/view_configuration");
  1508. switch (vc) {
  1509. case 0: {
  1510. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO;
  1511. } break;
  1512. case 1: {
  1513. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
  1514. } break;
  1515. /* we don't support quad and observer configurations (yet)
  1516. case 2: {
  1517. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO;
  1518. } break;
  1519. case 3: {
  1520. view_configuration = XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT;
  1521. } break;
  1522. */
  1523. default:
  1524. break;
  1525. }
  1526. int rs = GLOBAL_GET("xr/openxr/reference_space");
  1527. switch (rs) {
  1528. case 0: {
  1529. reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
  1530. } break;
  1531. case 1: {
  1532. reference_space = XR_REFERENCE_SPACE_TYPE_STAGE;
  1533. } break;
  1534. default:
  1535. break;
  1536. }
  1537. submit_depth_buffer = GLOBAL_GET("xr/openxr/submit_depth_buffer");
  1538. }
  1539. // reset a few things that can't be done in our class definition
  1540. frame_state.predictedDisplayTime = 0;
  1541. frame_state.predictedDisplayPeriod = 0;
  1542. #ifdef ANDROID_ENABLED
  1543. // our android wrapper will initialize our android loader at this point
  1544. register_extension_wrapper(memnew(OpenXRAndroidExtension(this)));
  1545. #endif
  1546. // register our other extensions
  1547. register_extension_wrapper(memnew(OpenXRPalmPoseExtension(this)));
  1548. register_extension_wrapper(memnew(OpenXRCompositionLayerDepthExtension(this)));
  1549. register_extension_wrapper(memnew(OpenXRHTCViveTrackerExtension(this)));
  1550. register_extension_wrapper(memnew(OpenXRHandTrackingExtension(this)));
  1551. register_extension_wrapper(memnew(OpenXRFbPassthroughExtensionWrapper(this)));
  1552. register_extension_wrapper(memnew(OpenXRDisplayRefreshRateExtension(this)));
  1553. }
  1554. OpenXRAPI::~OpenXRAPI() {
  1555. // cleanup our composition layer providers
  1556. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  1557. memdelete(provider);
  1558. }
  1559. composition_layer_providers.clear();
  1560. // cleanup our extension wrappers
  1561. for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
  1562. memdelete(extension_wrapper);
  1563. }
  1564. registered_extension_wrappers.clear();
  1565. if (supported_extensions != nullptr) {
  1566. memfree(supported_extensions);
  1567. supported_extensions = nullptr;
  1568. }
  1569. if (layer_properties != nullptr) {
  1570. memfree(layer_properties);
  1571. layer_properties = nullptr;
  1572. }
  1573. #ifdef ANDROID_ENABLED
  1574. if (openxr_loader_library_handle) {
  1575. OS::get_singleton()->close_dynamic_library(openxr_loader_library_handle);
  1576. openxr_loader_library_handle = nullptr;
  1577. }
  1578. #endif
  1579. singleton = nullptr;
  1580. }
  1581. Transform3D OpenXRAPI::transform_from_pose(const XrPosef &p_pose) {
  1582. Quaternion q(p_pose.orientation.x, p_pose.orientation.y, p_pose.orientation.z, p_pose.orientation.w);
  1583. Basis basis(q);
  1584. Vector3 origin(p_pose.position.x, p_pose.position.y, p_pose.position.z);
  1585. return Transform3D(basis, origin);
  1586. }
  1587. template <typename T>
  1588. XRPose::TrackingConfidence _transform_from_location(const T &p_location, Transform3D &r_transform) {
  1589. Basis basis;
  1590. Vector3 origin;
  1591. XRPose::TrackingConfidence confidence = XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1592. const auto &pose = p_location.pose;
  1593. // Check orientation
  1594. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) {
  1595. Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
  1596. r_transform.basis = Basis(q);
  1597. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) {
  1598. // Fully valid orientation, so either 3DOF or 6DOF tracking with high confidence so default to HIGH_TRACKING
  1599. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  1600. } else {
  1601. // Orientation is being tracked but we're using old/predicted data, so low tracking confidence
  1602. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  1603. }
  1604. } else {
  1605. r_transform.basis = Basis();
  1606. }
  1607. // Check location
  1608. if (p_location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) {
  1609. r_transform.origin = Vector3(pose.position.x, pose.position.y, pose.position.z);
  1610. if (!(p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)) {
  1611. // Location is being tracked but we're using old/predicted data, so low tracking confidence
  1612. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  1613. } else if (confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  1614. // Position tracking without orientation tracking?
  1615. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  1616. }
  1617. } else {
  1618. // No tracking or 3DOF I guess..
  1619. r_transform.origin = Vector3();
  1620. }
  1621. return confidence;
  1622. }
  1623. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrSpaceLocation &p_location, Transform3D &r_transform) {
  1624. return _transform_from_location(p_location, r_transform);
  1625. }
  1626. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform) {
  1627. return _transform_from_location(p_location, r_transform);
  1628. }
  1629. void OpenXRAPI::parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  1630. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT) {
  1631. XrVector3f linear_velocity = p_velocity.linearVelocity;
  1632. r_linear_velocity = Vector3(linear_velocity.x, linear_velocity.y, linear_velocity.z);
  1633. } else {
  1634. r_linear_velocity = Vector3();
  1635. }
  1636. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT) {
  1637. XrVector3f angular_velocity = p_velocity.angularVelocity;
  1638. r_angular_velocity = Vector3(angular_velocity.x, angular_velocity.y, angular_velocity.z);
  1639. } else {
  1640. r_angular_velocity = Vector3();
  1641. }
  1642. }
  1643. bool OpenXRAPI::xr_result(XrResult result, const char *format, Array args) const {
  1644. if (XR_SUCCEEDED(result))
  1645. return true;
  1646. char resultString[XR_MAX_RESULT_STRING_SIZE];
  1647. xrResultToString(instance, result, resultString);
  1648. print_error(String("OpenXR ") + String(format).format(args) + String(" [") + String(resultString) + String("]"));
  1649. return false;
  1650. }
  1651. RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
  1652. List<RID> current;
  1653. tracker_owner.get_owned_list(&current);
  1654. for (int i = 0; i < current.size(); i++) {
  1655. Tracker *tracker = tracker_owner.get_or_null(current[i]);
  1656. if (tracker && tracker->toplevel_path == p_path) {
  1657. return current[i];
  1658. }
  1659. }
  1660. return RID();
  1661. }
  1662. RID OpenXRAPI::tracker_create(const String p_name) {
  1663. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1664. Tracker new_tracker;
  1665. new_tracker.name = p_name;
  1666. new_tracker.toplevel_path = XR_NULL_PATH;
  1667. new_tracker.active_profile_rid = RID();
  1668. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_tracker.toplevel_path);
  1669. if (XR_FAILED(result)) {
  1670. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  1671. return RID();
  1672. }
  1673. return tracker_owner.make_rid(new_tracker);
  1674. }
  1675. String OpenXRAPI::tracker_get_name(RID p_tracker) {
  1676. if (p_tracker.is_null()) {
  1677. return String("None");
  1678. }
  1679. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1680. ERR_FAIL_NULL_V(tracker, String());
  1681. return tracker->name;
  1682. }
  1683. void OpenXRAPI::tracker_check_profile(RID p_tracker, XrSession p_session) {
  1684. if (p_session == XR_NULL_HANDLE) {
  1685. p_session = session;
  1686. }
  1687. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1688. ERR_FAIL_NULL(tracker);
  1689. if (tracker->toplevel_path == XR_NULL_PATH) {
  1690. // no path, how was this even created?
  1691. return;
  1692. }
  1693. XrInteractionProfileState profile_state = {
  1694. XR_TYPE_INTERACTION_PROFILE_STATE, // type
  1695. nullptr, // next
  1696. XR_NULL_PATH // interactionProfile
  1697. };
  1698. XrResult result = xrGetCurrentInteractionProfile(p_session, tracker->toplevel_path, &profile_state);
  1699. if (XR_FAILED(result)) {
  1700. print_line("OpenXR: Failed to get interaction profile for", itos(tracker->toplevel_path), "[", get_error_string(result), "]");
  1701. return;
  1702. }
  1703. XrPath new_profile = profile_state.interactionProfile;
  1704. XrPath was_profile = get_interaction_profile_path(tracker->active_profile_rid);
  1705. if (was_profile != new_profile) {
  1706. tracker->active_profile_rid = get_interaction_profile_rid(new_profile);
  1707. if (xr_interface) {
  1708. xr_interface->tracker_profile_changed(p_tracker, tracker->active_profile_rid);
  1709. }
  1710. }
  1711. }
  1712. void OpenXRAPI::tracker_free(RID p_tracker) {
  1713. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  1714. ERR_FAIL_NULL(tracker);
  1715. // there is nothing to free here
  1716. tracker_owner.free(p_tracker);
  1717. }
  1718. RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_name, const int p_priority) {
  1719. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1720. ActionSet action_set;
  1721. action_set.name = p_name;
  1722. action_set.is_attached = false;
  1723. // create our action set...
  1724. XrActionSetCreateInfo action_set_info = {
  1725. XR_TYPE_ACTION_SET_CREATE_INFO, // type
  1726. nullptr, // next
  1727. "", // actionSetName
  1728. "", // localizedActionSetName
  1729. uint32_t(p_priority) // priority
  1730. };
  1731. copy_string_to_char_buffer(p_name, action_set_info.actionSetName, XR_MAX_ACTION_SET_NAME_SIZE);
  1732. copy_string_to_char_buffer(p_localized_name, action_set_info.localizedActionSetName, XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE);
  1733. XrResult result = xrCreateActionSet(instance, &action_set_info, &action_set.handle);
  1734. if (XR_FAILED(result)) {
  1735. print_line("OpenXR: failed to create action set ", p_name, "! [", get_error_string(result), "]");
  1736. return RID();
  1737. }
  1738. return action_set_owner.make_rid(action_set);
  1739. }
  1740. String OpenXRAPI::action_set_get_name(RID p_action_set) {
  1741. if (p_action_set.is_null()) {
  1742. return String("None");
  1743. }
  1744. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1745. ERR_FAIL_NULL_V(action_set, String());
  1746. return action_set->name;
  1747. }
  1748. bool OpenXRAPI::action_set_attach(RID p_action_set) {
  1749. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1750. ERR_FAIL_NULL_V(action_set, false);
  1751. if (action_set->is_attached) {
  1752. // already attached
  1753. return true;
  1754. }
  1755. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  1756. // So according to the docs, once we attach our action set to our session it becomes read only..
  1757. // https://www.khronos.org/registry/OpenXR/specs/1.0/man/html/xrAttachSessionActionSets.html
  1758. XrSessionActionSetsAttachInfo attach_info = {
  1759. XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, // type
  1760. nullptr, // next
  1761. 1, // countActionSets,
  1762. &action_set->handle // actionSets
  1763. };
  1764. XrResult result = xrAttachSessionActionSets(session, &attach_info);
  1765. if (XR_FAILED(result)) {
  1766. print_line("OpenXR: failed to attach action set! [", get_error_string(result), "]");
  1767. return false;
  1768. }
  1769. action_set->is_attached = true;
  1770. /* For debugging:
  1771. print_verbose("Attached set " + action_set->name);
  1772. List<RID> action_rids;
  1773. action_owner.get_owned_list(&action_rids);
  1774. for (int i = 0; i < action_rids.size(); i++) {
  1775. Action * action = action_owner.get_or_null(action_rids[i]);
  1776. if (action && action->action_set_rid == p_action_set) {
  1777. print_verbose(" - Action " + action->name + ": " + OpenXRUtil::get_action_type_name(action->action_type));
  1778. for (int j = 0; j < action->trackers.size(); j++) {
  1779. Tracker * tracker = tracker_owner.get_or_null(action->trackers[j].tracker_rid);
  1780. if (tracker) {
  1781. print_verbose(" - " + tracker->name);
  1782. }
  1783. }
  1784. }
  1785. }
  1786. */
  1787. return true;
  1788. }
  1789. void OpenXRAPI::action_set_free(RID p_action_set) {
  1790. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1791. ERR_FAIL_NULL(action_set);
  1792. if (action_set->handle != XR_NULL_HANDLE) {
  1793. xrDestroyActionSet(action_set->handle);
  1794. }
  1795. action_set_owner.free(p_action_set);
  1796. }
  1797. RID OpenXRAPI::get_action_rid(XrAction p_action) {
  1798. List<RID> current;
  1799. action_owner.get_owned_list(&current);
  1800. for (int i = 0; i < current.size(); i++) {
  1801. Action *action = action_owner.get_or_null(current[i]);
  1802. if (action && action->handle == p_action) {
  1803. return current[i];
  1804. }
  1805. }
  1806. return RID();
  1807. }
  1808. 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) {
  1809. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  1810. Action action;
  1811. action.name = p_name;
  1812. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  1813. ERR_FAIL_NULL_V(action_set, RID());
  1814. ERR_FAIL_COND_V(action_set->handle == XR_NULL_HANDLE, RID());
  1815. action.action_set_rid = p_action_set;
  1816. switch (p_action_type) {
  1817. case OpenXRAction::OPENXR_ACTION_BOOL:
  1818. action.action_type = XR_ACTION_TYPE_BOOLEAN_INPUT;
  1819. break;
  1820. case OpenXRAction::OPENXR_ACTION_FLOAT:
  1821. action.action_type = XR_ACTION_TYPE_FLOAT_INPUT;
  1822. break;
  1823. case OpenXRAction::OPENXR_ACTION_VECTOR2:
  1824. action.action_type = XR_ACTION_TYPE_VECTOR2F_INPUT;
  1825. break;
  1826. case OpenXRAction::OPENXR_ACTION_POSE:
  1827. action.action_type = XR_ACTION_TYPE_POSE_INPUT;
  1828. break;
  1829. case OpenXRAction::OPENXR_ACTION_HAPTIC:
  1830. action.action_type = XR_ACTION_TYPE_VIBRATION_OUTPUT;
  1831. break;
  1832. default:
  1833. ERR_FAIL_V(RID());
  1834. break;
  1835. }
  1836. Vector<XrPath> toplevel_paths;
  1837. for (int i = 0; i < p_trackers.size(); i++) {
  1838. Tracker *tracker = tracker_owner.get_or_null(p_trackers[i]);
  1839. if (tracker != nullptr && tracker->toplevel_path != XR_NULL_PATH) {
  1840. ActionTracker action_tracker = {
  1841. p_trackers[i], // tracker
  1842. XR_NULL_HANDLE, // space
  1843. false // was_location_valid
  1844. };
  1845. action.trackers.push_back(action_tracker);
  1846. toplevel_paths.push_back(tracker->toplevel_path);
  1847. }
  1848. }
  1849. XrActionCreateInfo action_info = {
  1850. XR_TYPE_ACTION_CREATE_INFO, // type
  1851. nullptr, // next
  1852. "", // actionName
  1853. action.action_type, // actionType
  1854. uint32_t(toplevel_paths.size()), // countSubactionPaths
  1855. toplevel_paths.ptr(), // subactionPaths
  1856. "" // localizedActionName
  1857. };
  1858. copy_string_to_char_buffer(p_name, action_info.actionName, XR_MAX_ACTION_NAME_SIZE);
  1859. copy_string_to_char_buffer(p_localized_name, action_info.localizedActionName, XR_MAX_LOCALIZED_ACTION_NAME_SIZE);
  1860. XrResult result = xrCreateAction(action_set->handle, &action_info, &action.handle);
  1861. if (XR_FAILED(result)) {
  1862. print_line("OpenXR: failed to create action ", p_name, "! [", get_error_string(result), "]");
  1863. return RID();
  1864. }
  1865. return action_owner.make_rid(action);
  1866. }
  1867. String OpenXRAPI::action_get_name(RID p_action) {
  1868. if (p_action.is_null()) {
  1869. return String("None");
  1870. }
  1871. Action *action = action_owner.get_or_null(p_action);
  1872. ERR_FAIL_NULL_V(action, String());
  1873. return action->name;
  1874. }
  1875. void OpenXRAPI::action_free(RID p_action) {
  1876. Action *action = action_owner.get_or_null(p_action);
  1877. ERR_FAIL_NULL(action);
  1878. if (action->handle != XR_NULL_HANDLE) {
  1879. xrDestroyAction(action->handle);
  1880. }
  1881. action_owner.free(p_action);
  1882. }
  1883. RID OpenXRAPI::get_interaction_profile_rid(XrPath p_path) {
  1884. List<RID> current;
  1885. interaction_profile_owner.get_owned_list(&current);
  1886. for (int i = 0; i < current.size(); i++) {
  1887. InteractionProfile *ip = interaction_profile_owner.get_or_null(current[i]);
  1888. if (ip && ip->path == p_path) {
  1889. return current[i];
  1890. }
  1891. }
  1892. return RID();
  1893. }
  1894. XrPath OpenXRAPI::get_interaction_profile_path(RID p_interaction_profile) {
  1895. if (p_interaction_profile.is_null()) {
  1896. return XR_NULL_PATH;
  1897. }
  1898. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1899. ERR_FAIL_NULL_V(ip, XR_NULL_PATH);
  1900. return ip->path;
  1901. }
  1902. RID OpenXRAPI::interaction_profile_create(const String p_name) {
  1903. if (!is_path_supported(p_name)) {
  1904. // The extension enabling this path must not be active, we will silently skip this interaction profile
  1905. return RID();
  1906. }
  1907. InteractionProfile new_interaction_profile;
  1908. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_interaction_profile.path);
  1909. if (XR_FAILED(result)) {
  1910. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  1911. return RID();
  1912. }
  1913. RID existing_ip = get_interaction_profile_rid(new_interaction_profile.path);
  1914. if (existing_ip.is_valid()) {
  1915. return existing_ip;
  1916. }
  1917. new_interaction_profile.name = p_name;
  1918. return interaction_profile_owner.make_rid(new_interaction_profile);
  1919. }
  1920. String OpenXRAPI::interaction_profile_get_name(RID p_interaction_profile) {
  1921. if (p_interaction_profile.is_null()) {
  1922. return String("None");
  1923. }
  1924. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1925. ERR_FAIL_NULL_V(ip, String());
  1926. return ip->name;
  1927. }
  1928. void OpenXRAPI::interaction_profile_clear_bindings(RID p_interaction_profile) {
  1929. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1930. ERR_FAIL_NULL(ip);
  1931. ip->bindings.clear();
  1932. }
  1933. bool OpenXRAPI::interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String p_path) {
  1934. if (!is_path_supported(p_path)) {
  1935. // The extension enabling this path must not be active, we will silently skip this binding
  1936. return false;
  1937. }
  1938. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1939. ERR_FAIL_NULL_V(ip, false);
  1940. XrActionSuggestedBinding binding;
  1941. Action *action = action_owner.get_or_null(p_action);
  1942. ERR_FAIL_COND_V(action == nullptr || action->handle == XR_NULL_HANDLE, false);
  1943. binding.action = action->handle;
  1944. XrResult result = xrStringToPath(instance, p_path.utf8().get_data(), &binding.binding);
  1945. if (XR_FAILED(result)) {
  1946. print_line("OpenXR: failed to get path for ", p_path, "! [", get_error_string(result), "]");
  1947. return false;
  1948. }
  1949. ip->bindings.push_back(binding);
  1950. return true;
  1951. }
  1952. bool OpenXRAPI::interaction_profile_suggest_bindings(RID p_interaction_profile) {
  1953. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1954. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1955. ERR_FAIL_NULL_V(ip, false);
  1956. const XrInteractionProfileSuggestedBinding suggested_bindings = {
  1957. XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, // type
  1958. nullptr, // next
  1959. ip->path, // interactionProfile
  1960. uint32_t(ip->bindings.size()), // countSuggestedBindings
  1961. ip->bindings.ptr() // suggestedBindings
  1962. };
  1963. XrResult result = xrSuggestInteractionProfileBindings(instance, &suggested_bindings);
  1964. if (result == XR_ERROR_PATH_UNSUPPORTED) {
  1965. // this is fine, not all runtimes support all devices.
  1966. print_verbose("OpenXR Interaction profile " + ip->name + " is not supported on this runtime");
  1967. } else if (XR_FAILED(result)) {
  1968. print_line("OpenXR: failed to suggest bindings for ", ip->name, "! [", get_error_string(result), "]");
  1969. // reporting is enough...
  1970. }
  1971. /* For debugging:
  1972. print_verbose("Suggested bindings for " + ip->name);
  1973. for (int i = 0; i < ip->bindings.size(); i++) {
  1974. uint32_t strlen;
  1975. char path[XR_MAX_PATH_LENGTH];
  1976. String action_name = action_get_name(get_action_rid(ip->bindings[i].action));
  1977. XrResult result = xrPathToString(instance, ip->bindings[i].binding, XR_MAX_PATH_LENGTH, &strlen, path);
  1978. if (XR_FAILED(result)) {
  1979. print_line("OpenXR: failed to retrieve bindings for ", action_name, "! [", get_error_string(result), "]");
  1980. }
  1981. print_verbose(" - " + action_name + " => " + String(path));
  1982. }
  1983. */
  1984. return true;
  1985. }
  1986. void OpenXRAPI::interaction_profile_free(RID p_interaction_profile) {
  1987. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  1988. ERR_FAIL_NULL(ip);
  1989. ip->bindings.clear();
  1990. interaction_profile_owner.free(p_interaction_profile);
  1991. }
  1992. bool OpenXRAPI::sync_action_sets(const Vector<RID> p_active_sets) {
  1993. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  1994. if (!running) {
  1995. return false;
  1996. }
  1997. Vector<XrActiveActionSet> active_sets;
  1998. for (int i = 0; i < p_active_sets.size(); i++) {
  1999. ActionSet *action_set = action_set_owner.get_or_null(p_active_sets[i]);
  2000. if (action_set && action_set->handle != XR_NULL_HANDLE) {
  2001. XrActiveActionSet aset;
  2002. aset.actionSet = action_set->handle;
  2003. aset.subactionPath = XR_NULL_PATH;
  2004. active_sets.push_back(aset);
  2005. }
  2006. }
  2007. ERR_FAIL_COND_V(active_sets.size() == 0, false);
  2008. XrActionsSyncInfo sync_info = {
  2009. XR_TYPE_ACTIONS_SYNC_INFO, // type
  2010. nullptr, // next
  2011. uint32_t(active_sets.size()), // countActiveActionSets
  2012. active_sets.ptr() // activeActionSets
  2013. };
  2014. XrResult result = xrSyncActions(session, &sync_info);
  2015. if (XR_FAILED(result)) {
  2016. print_line("OpenXR: failed to sync active action sets! [", get_error_string(result), "]");
  2017. return false;
  2018. }
  2019. return true;
  2020. }
  2021. bool OpenXRAPI::get_action_bool(RID p_action, RID p_tracker) {
  2022. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2023. Action *action = action_owner.get_or_null(p_action);
  2024. ERR_FAIL_NULL_V(action, false);
  2025. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2026. ERR_FAIL_NULL_V(tracker, false);
  2027. if (!running) {
  2028. return false;
  2029. }
  2030. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_BOOLEAN_INPUT, false);
  2031. XrActionStateGetInfo get_info = {
  2032. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2033. nullptr, // next
  2034. action->handle, // action
  2035. tracker->toplevel_path // subactionPath
  2036. };
  2037. XrActionStateBoolean result_state;
  2038. result_state.type = XR_TYPE_ACTION_STATE_BOOLEAN,
  2039. result_state.next = nullptr;
  2040. XrResult result = xrGetActionStateBoolean(session, &get_info, &result_state);
  2041. if (XR_FAILED(result)) {
  2042. print_line("OpenXR: couldn't get action boolean! [", get_error_string(result), "]");
  2043. return false;
  2044. }
  2045. return result_state.isActive && result_state.currentState;
  2046. }
  2047. float OpenXRAPI::get_action_float(RID p_action, RID p_tracker) {
  2048. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, 0.0);
  2049. Action *action = action_owner.get_or_null(p_action);
  2050. ERR_FAIL_NULL_V(action, 0.0);
  2051. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2052. ERR_FAIL_NULL_V(tracker, 0.0);
  2053. if (!running) {
  2054. return 0.0;
  2055. }
  2056. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_FLOAT_INPUT, 0.0);
  2057. XrActionStateGetInfo get_info = {
  2058. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2059. nullptr, // next
  2060. action->handle, // action
  2061. tracker->toplevel_path // subactionPath
  2062. };
  2063. XrActionStateFloat result_state;
  2064. result_state.type = XR_TYPE_ACTION_STATE_FLOAT,
  2065. result_state.next = nullptr;
  2066. XrResult result = xrGetActionStateFloat(session, &get_info, &result_state);
  2067. if (XR_FAILED(result)) {
  2068. print_line("OpenXR: couldn't get action float! [", get_error_string(result), "]");
  2069. return 0.0;
  2070. }
  2071. return result_state.isActive ? result_state.currentState : 0.0;
  2072. }
  2073. Vector2 OpenXRAPI::get_action_vector2(RID p_action, RID p_tracker) {
  2074. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, Vector2());
  2075. Action *action = action_owner.get_or_null(p_action);
  2076. ERR_FAIL_NULL_V(action, Vector2());
  2077. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2078. ERR_FAIL_NULL_V(tracker, Vector2());
  2079. if (!running) {
  2080. return Vector2();
  2081. }
  2082. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VECTOR2F_INPUT, Vector2());
  2083. XrActionStateGetInfo get_info = {
  2084. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2085. nullptr, // next
  2086. action->handle, // action
  2087. tracker->toplevel_path // subactionPath
  2088. };
  2089. XrActionStateVector2f result_state;
  2090. result_state.type = XR_TYPE_ACTION_STATE_VECTOR2F,
  2091. result_state.next = nullptr;
  2092. XrResult result = xrGetActionStateVector2f(session, &get_info, &result_state);
  2093. if (XR_FAILED(result)) {
  2094. print_line("OpenXR: couldn't get action vector2! [", get_error_string(result), "]");
  2095. return Vector2();
  2096. }
  2097. return result_state.isActive ? Vector2(result_state.currentState.x, result_state.currentState.y) : Vector2();
  2098. }
  2099. XRPose::TrackingConfidence OpenXRAPI::get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  2100. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2101. Action *action = action_owner.get_or_null(p_action);
  2102. ERR_FAIL_NULL_V(action, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2103. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2104. ERR_FAIL_NULL_V(tracker, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2105. if (!running) {
  2106. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2107. }
  2108. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_POSE_INPUT, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2109. // print_verbose("Checking " + action->name + " => " + tracker->name + " (" + itos(tracker->toplevel_path) + ")");
  2110. uint64_t index = 0xFFFFFFFF;
  2111. uint64_t size = uint64_t(action->trackers.size());
  2112. for (uint64_t i = 0; i < size && index == 0xFFFFFFFF; i++) {
  2113. if (action->trackers[i].tracker_rid == p_tracker) {
  2114. index = i;
  2115. }
  2116. }
  2117. if (index == 0xFFFFFFFF) {
  2118. // couldn't find it?
  2119. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2120. }
  2121. XrTime display_time = get_next_frame_time();
  2122. if (display_time == 0) {
  2123. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2124. }
  2125. if (action->trackers[index].space == XR_NULL_HANDLE) {
  2126. // if this is a pose we need to define spaces
  2127. XrActionSpaceCreateInfo action_space_info = {
  2128. XR_TYPE_ACTION_SPACE_CREATE_INFO, // type
  2129. nullptr, // next
  2130. action->handle, // action
  2131. tracker->toplevel_path, // subactionPath
  2132. {
  2133. { 0.0, 0.0, 0.0, 1.0 }, // orientation
  2134. { 0.0, 0.0, 0.0 } // position
  2135. } // poseInActionSpace
  2136. };
  2137. XrSpace space;
  2138. XrResult result = xrCreateActionSpace(session, &action_space_info, &space);
  2139. if (XR_FAILED(result)) {
  2140. print_line("OpenXR: couldn't create action space! [", get_error_string(result), "]");
  2141. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2142. }
  2143. action->trackers.ptrw()[index].space = space;
  2144. }
  2145. XrSpaceVelocity velocity = {
  2146. XR_TYPE_SPACE_VELOCITY, // type
  2147. nullptr, // next
  2148. 0, // velocityFlags
  2149. { 0.0, 0.0, 0.0 }, // linearVelocity
  2150. { 0.0, 0.0, 0.0 } // angularVelocity
  2151. };
  2152. XrSpaceLocation location = {
  2153. XR_TYPE_SPACE_LOCATION, // type
  2154. &velocity, // next
  2155. 0, // locationFlags
  2156. {
  2157. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  2158. { 0.0, 0.0, 0.0 } // position
  2159. } // pose
  2160. };
  2161. XrResult result = xrLocateSpace(action->trackers[index].space, play_space, display_time, &location);
  2162. if (XR_FAILED(result)) {
  2163. print_line("OpenXR: failed to locate space! [", get_error_string(result), "]");
  2164. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2165. }
  2166. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  2167. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  2168. return confidence;
  2169. }
  2170. bool OpenXRAPI::trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns) {
  2171. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2172. Action *action = action_owner.get_or_null(p_action);
  2173. ERR_FAIL_NULL_V(action, false);
  2174. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2175. ERR_FAIL_NULL_V(tracker, false);
  2176. if (!running) {
  2177. return false;
  2178. }
  2179. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT, false);
  2180. XrHapticActionInfo action_info = {
  2181. XR_TYPE_HAPTIC_ACTION_INFO, // type
  2182. nullptr, // next
  2183. action->handle, // action
  2184. tracker->toplevel_path // subactionPath
  2185. };
  2186. XrHapticVibration vibration = {
  2187. XR_TYPE_HAPTIC_VIBRATION, // type
  2188. nullptr, // next
  2189. p_duration_ns, // duration
  2190. p_frequency, // frequency
  2191. p_amplitude, // amplitude
  2192. };
  2193. XrResult result = xrApplyHapticFeedback(session, &action_info, (const XrHapticBaseHeader *)&vibration);
  2194. if (XR_FAILED(result)) {
  2195. print_line("OpenXR: failed to apply haptic feedback! [", get_error_string(result), "]");
  2196. return false;
  2197. }
  2198. return true;
  2199. }
  2200. void OpenXRAPI::register_composition_layer_provider(OpenXRCompositionLayerProvider *provider) {
  2201. composition_layer_providers.append(provider);
  2202. }
  2203. void OpenXRAPI::unregister_composition_layer_provider(OpenXRCompositionLayerProvider *provider) {
  2204. composition_layer_providers.erase(provider);
  2205. }