openxr_api.cpp 87 KB

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