openxr_api.cpp 75 KB

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