openxr_api.cpp 76 KB

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