openxr_api.cpp 76 KB

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