openxr_api.cpp 111 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381
  1. /**************************************************************************/
  2. /* openxr_api.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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 "extensions/openxr_extension_wrapper_extension.h"
  32. #include "openxr_interface.h"
  33. #include "openxr_util.h"
  34. #include "core/config/engine.h"
  35. #include "core/config/project_settings.h"
  36. #include "core/os/memory.h"
  37. #include "core/version.h"
  38. #ifdef TOOLS_ENABLED
  39. #include "editor/editor_settings.h"
  40. #endif
  41. #include "openxr_platform_inc.h"
  42. #ifdef VULKAN_ENABLED
  43. #include "extensions/platform/openxr_vulkan_extension.h"
  44. #endif
  45. #if defined(GLES3_ENABLED) && !defined(MACOS_ENABLED)
  46. #include "extensions/platform/openxr_opengl_extension.h"
  47. #endif
  48. #include "extensions/openxr_composition_layer_depth_extension.h"
  49. #include "extensions/openxr_fb_display_refresh_rate_extension.h"
  50. #include "extensions/openxr_fb_foveation_extension.h"
  51. #include "extensions/openxr_fb_update_swapchain_extension.h"
  52. #include "extensions/openxr_hand_tracking_extension.h"
  53. #ifdef ANDROID_ENABLED
  54. #define OPENXR_LOADER_NAME "libopenxr_loader.so"
  55. #endif
  56. ////////////////////////////////////
  57. // OpenXRAPI::OpenXRSwapChainInfo
  58. Vector<OpenXRAPI::OpenXRSwapChainInfo> OpenXRAPI::OpenXRSwapChainInfo::free_queue;
  59. bool OpenXRAPI::OpenXRSwapChainInfo::create(XrSwapchainCreateFlags p_create_flags, 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) {
  60. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  61. ERR_FAIL_NULL_V(openxr_api, false);
  62. XrSession xr_session = openxr_api->get_session();
  63. ERR_FAIL_COND_V(xr_session == XR_NULL_HANDLE, false);
  64. OpenXRGraphicsExtensionWrapper *xr_graphics_extension = openxr_api->get_graphics_extension();
  65. ERR_FAIL_NULL_V(xr_graphics_extension, false);
  66. // We already have a swapchain?
  67. ERR_FAIL_COND_V(swapchain != XR_NULL_HANDLE, false);
  68. XrResult result;
  69. void *next_pointer = nullptr;
  70. for (OpenXRExtensionWrapper *wrapper : openxr_api->get_registered_extension_wrappers()) {
  71. void *np = wrapper->set_swapchain_create_info_and_get_next_pointer(next_pointer);
  72. if (np != nullptr) {
  73. next_pointer = np;
  74. }
  75. }
  76. XrSwapchainCreateInfo swapchain_create_info = {
  77. XR_TYPE_SWAPCHAIN_CREATE_INFO, // type
  78. next_pointer, // next
  79. p_create_flags, // createFlags
  80. p_usage_flags, // usageFlags
  81. p_swapchain_format, // format
  82. p_sample_count, // sampleCount
  83. p_width, // width
  84. p_height, // height
  85. 1, // faceCount
  86. p_array_size, // arraySize
  87. 1 // mipCount
  88. };
  89. XrSwapchain new_swapchain;
  90. result = openxr_api->xrCreateSwapchain(xr_session, &swapchain_create_info, &new_swapchain);
  91. if (XR_FAILED(result)) {
  92. print_line("OpenXR: Failed to get swapchain [", openxr_api->get_error_string(result), "]");
  93. return false;
  94. }
  95. if (!xr_graphics_extension->get_swapchain_image_data(new_swapchain, p_swapchain_format, p_width, p_height, p_sample_count, p_array_size, &swapchain_graphics_data)) {
  96. openxr_api->xrDestroySwapchain(new_swapchain);
  97. return false;
  98. }
  99. swapchain = new_swapchain;
  100. return true;
  101. }
  102. void OpenXRAPI::OpenXRSwapChainInfo::queue_free() {
  103. if (image_acquired) {
  104. release();
  105. }
  106. if (swapchain != XR_NULL_HANDLE) {
  107. free_queue.push_back(*this);
  108. swapchain_graphics_data = nullptr;
  109. swapchain = XR_NULL_HANDLE;
  110. }
  111. }
  112. void OpenXRAPI::OpenXRSwapChainInfo::free_queued() {
  113. for (OpenXRAPI::OpenXRSwapChainInfo &swapchain_info : free_queue) {
  114. swapchain_info.free();
  115. }
  116. free_queue.clear();
  117. }
  118. void OpenXRAPI::OpenXRSwapChainInfo::free() {
  119. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  120. ERR_FAIL_NULL(openxr_api);
  121. if (image_acquired) {
  122. release();
  123. }
  124. if (openxr_api->get_graphics_extension() && swapchain_graphics_data != nullptr) {
  125. openxr_api->get_graphics_extension()->cleanup_swapchain_graphics_data(&swapchain_graphics_data);
  126. }
  127. if (swapchain != XR_NULL_HANDLE) {
  128. openxr_api->xrDestroySwapchain(swapchain);
  129. swapchain = XR_NULL_HANDLE;
  130. }
  131. }
  132. bool OpenXRAPI::OpenXRSwapChainInfo::acquire(bool &p_should_render) {
  133. ERR_FAIL_COND_V(image_acquired, true); // This was not released when it should be, error out and reuse...
  134. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  135. ERR_FAIL_NULL_V(openxr_api, false);
  136. XrResult result;
  137. if (!skip_acquire_swapchain) {
  138. XrSwapchainImageAcquireInfo swapchain_image_acquire_info = {
  139. XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, // type
  140. nullptr // next
  141. };
  142. result = openxr_api->xrAcquireSwapchainImage(swapchain, &swapchain_image_acquire_info, &image_index);
  143. if (!XR_UNQUALIFIED_SUCCESS(result)) {
  144. // Make sure end_frame knows we need to submit an empty frame
  145. p_should_render = false;
  146. if (XR_FAILED(result)) {
  147. // Unexpected failure, log this!
  148. print_line("OpenXR: failed to acquire swapchain image [", openxr_api->get_error_string(result), "]");
  149. return false;
  150. } else {
  151. // In this scenario we silently fail, the XR runtime is simply not ready yet to acquire the swapchain.
  152. return false;
  153. }
  154. }
  155. }
  156. XrSwapchainImageWaitInfo swapchain_image_wait_info = {
  157. XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, // type
  158. nullptr, // next
  159. 1000000000 // 1s timeout in nanoseconds
  160. };
  161. // Wait for a maximum of 10 seconds before calling it a critical failure...
  162. for (int retry = 0; retry < 10; retry++) {
  163. result = openxr_api->xrWaitSwapchainImage(swapchain, &swapchain_image_wait_info);
  164. if (result != XR_TIMEOUT_EXPIRED) {
  165. break;
  166. }
  167. WARN_PRINT("OpenXR: timed out waiting for swapchain image.");
  168. }
  169. if (!XR_UNQUALIFIED_SUCCESS(result)) {
  170. // Make sure end_frame knows we need to submit an empty frame
  171. p_should_render = false;
  172. if (XR_FAILED(result)) {
  173. // Unexpected failure, log this!
  174. print_line("OpenXR: failed to wait for swapchain image [", openxr_api->get_error_string(result), "]");
  175. return false;
  176. } else {
  177. WARN_PRINT("OpenXR: couldn't to wait for swapchain but not a complete error [" + openxr_api->get_error_string(result) + "]");
  178. // Make sure to skip trying to acquire the swapchain image in the next frame
  179. skip_acquire_swapchain = true;
  180. return false;
  181. }
  182. } else {
  183. skip_acquire_swapchain = false;
  184. }
  185. image_acquired = true;
  186. return true;
  187. }
  188. bool OpenXRAPI::OpenXRSwapChainInfo::release() {
  189. if (!image_acquired) {
  190. // Already released or never acquired.
  191. return true;
  192. }
  193. image_acquired = false; // Regardless if we succeed or not, consider this released.
  194. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  195. ERR_FAIL_NULL_V(openxr_api, false);
  196. XrSwapchainImageReleaseInfo swapchain_image_release_info = {
  197. XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, // type
  198. nullptr // next
  199. };
  200. XrResult result = openxr_api->xrReleaseSwapchainImage(swapchain, &swapchain_image_release_info);
  201. if (XR_FAILED(result)) {
  202. print_line("OpenXR: failed to release swapchain image! [", openxr_api->get_error_string(result), "]");
  203. return false;
  204. }
  205. return true;
  206. }
  207. RID OpenXRAPI::OpenXRSwapChainInfo::get_image() {
  208. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  209. if (image_acquired && openxr_api && openxr_api->get_graphics_extension()) {
  210. return OpenXRAPI::get_singleton()->get_graphics_extension()->get_texture(swapchain_graphics_data, image_index);
  211. } else {
  212. return RID();
  213. }
  214. }
  215. ////////////////////////////////////
  216. // OpenXRAPI
  217. OpenXRAPI *OpenXRAPI::singleton = nullptr;
  218. Vector<OpenXRExtensionWrapper *> OpenXRAPI::registered_extension_wrappers;
  219. bool OpenXRAPI::openxr_is_enabled(bool p_check_run_in_editor) {
  220. // @TODO we need an overrule switch so we can force enable openxr, i.e run "godot --openxr_enabled"
  221. if (Engine::get_singleton()->is_editor_hint() && p_check_run_in_editor) {
  222. // Disabled for now, using XR inside of the editor we'll be working on during the coming months.
  223. return false;
  224. } else {
  225. if (XRServer::get_xr_mode() == XRServer::XRMODE_DEFAULT) {
  226. return GLOBAL_GET("xr/openxr/enabled");
  227. } else {
  228. return XRServer::get_xr_mode() == XRServer::XRMODE_ON;
  229. }
  230. }
  231. }
  232. String OpenXRAPI::get_default_action_map_resource_name() {
  233. String name = GLOBAL_GET("xr/openxr/default_action_map");
  234. return name;
  235. }
  236. String OpenXRAPI::get_error_string(XrResult result) const {
  237. if (XR_SUCCEEDED(result)) {
  238. return String("Succeeded");
  239. }
  240. if (instance == XR_NULL_HANDLE) {
  241. Array args;
  242. args.push_back(Variant(result));
  243. return String("Error code {0}").format(args);
  244. }
  245. char resultString[XR_MAX_RESULT_STRING_SIZE];
  246. xrResultToString(instance, result, resultString);
  247. return String(resultString);
  248. }
  249. String OpenXRAPI::get_swapchain_format_name(int64_t p_swapchain_format) const {
  250. // This is rendering engine dependent...
  251. if (graphics_extension) {
  252. return graphics_extension->get_swapchain_format_name(p_swapchain_format);
  253. }
  254. return String("Swapchain format ") + String::num_int64(int64_t(p_swapchain_format));
  255. }
  256. bool OpenXRAPI::load_layer_properties() {
  257. // This queries additional layers that are available and can be initialized when we create our OpenXR instance
  258. if (layer_properties != nullptr) {
  259. // already retrieved this
  260. return true;
  261. }
  262. // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
  263. XrResult result = xrEnumerateApiLayerProperties(0, &num_layer_properties, nullptr);
  264. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of api layer properties");
  265. layer_properties = (XrApiLayerProperties *)memalloc(sizeof(XrApiLayerProperties) * num_layer_properties);
  266. ERR_FAIL_NULL_V(layer_properties, false);
  267. for (uint32_t i = 0; i < num_layer_properties; i++) {
  268. layer_properties[i].type = XR_TYPE_API_LAYER_PROPERTIES;
  269. layer_properties[i].next = nullptr;
  270. }
  271. result = xrEnumerateApiLayerProperties(num_layer_properties, &num_layer_properties, layer_properties);
  272. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate api layer properties");
  273. for (uint32_t i = 0; i < num_layer_properties; i++) {
  274. print_verbose(String("OpenXR: Found OpenXR layer ") + layer_properties[i].layerName);
  275. }
  276. return true;
  277. }
  278. bool OpenXRAPI::load_supported_extensions() {
  279. // This queries supported extensions that are available and can be initialized when we create our OpenXR instance
  280. if (supported_extensions != nullptr) {
  281. // already retrieved this
  282. return true;
  283. }
  284. // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
  285. XrResult result = xrEnumerateInstanceExtensionProperties(nullptr, 0, &num_supported_extensions, nullptr);
  286. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of extension properties");
  287. supported_extensions = (XrExtensionProperties *)memalloc(sizeof(XrExtensionProperties) * num_supported_extensions);
  288. ERR_FAIL_NULL_V(supported_extensions, false);
  289. // set our types
  290. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  291. supported_extensions[i].type = XR_TYPE_EXTENSION_PROPERTIES;
  292. supported_extensions[i].next = nullptr;
  293. }
  294. result = xrEnumerateInstanceExtensionProperties(nullptr, num_supported_extensions, &num_supported_extensions, supported_extensions);
  295. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate extension properties");
  296. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  297. print_verbose(String("OpenXR: Found OpenXR extension ") + supported_extensions[i].extensionName);
  298. }
  299. return true;
  300. }
  301. bool OpenXRAPI::is_extension_supported(const String &p_extension) const {
  302. for (uint32_t i = 0; i < num_supported_extensions; i++) {
  303. if (supported_extensions[i].extensionName == p_extension) {
  304. return true;
  305. }
  306. }
  307. return false;
  308. }
  309. bool OpenXRAPI::is_extension_enabled(const String &p_extension) const {
  310. CharString extension = p_extension.ascii();
  311. for (int i = 0; i < enabled_extensions.size(); i++) {
  312. if (strcmp(enabled_extensions[i].ptr(), extension.ptr()) == 0) {
  313. return true;
  314. }
  315. }
  316. return false;
  317. }
  318. bool OpenXRAPI::is_top_level_path_supported(const String &p_toplevel_path) {
  319. String required_extension = OpenXRInteractionProfileMetadata::get_singleton()->get_top_level_extension(p_toplevel_path);
  320. // If unsupported is returned we likely have a misspelled interaction profile path in our action map. Always output that as an error.
  321. ERR_FAIL_COND_V_MSG(required_extension == XR_PATH_UNSUPPORTED_NAME, false, "OpenXR: Unsupported toplevel path " + p_toplevel_path);
  322. if (required_extension == "") {
  323. // no extension needed, core top level are always "supported", they just won't be used if not really supported
  324. return true;
  325. }
  326. if (!is_extension_enabled(required_extension)) {
  327. // It is very likely we have top level paths for which the extension is not available so don't flood the logs with unnecessary spam.
  328. print_verbose("OpenXR: Top level path " + p_toplevel_path + " requires extension " + required_extension);
  329. return false;
  330. }
  331. return true;
  332. }
  333. bool OpenXRAPI::is_interaction_profile_supported(const String &p_ip_path) {
  334. String required_extension = OpenXRInteractionProfileMetadata::get_singleton()->get_interaction_profile_extension(p_ip_path);
  335. // If unsupported is returned we likely have a misspelled interaction profile path in our action map. Always output that as an error.
  336. ERR_FAIL_COND_V_MSG(required_extension == XR_PATH_UNSUPPORTED_NAME, false, "OpenXR: Unsupported interaction profile " + p_ip_path);
  337. if (required_extension == "") {
  338. // no extension needed, core interaction profiles are always "supported", they just won't be used if not really supported
  339. return true;
  340. }
  341. if (!is_extension_enabled(required_extension)) {
  342. // It is very likely we have interaction profiles for which the extension is not available so don't flood the logs with unnecessary spam.
  343. print_verbose("OpenXR: Interaction profile " + p_ip_path + " requires extension " + required_extension);
  344. return false;
  345. }
  346. return true;
  347. }
  348. bool OpenXRAPI::interaction_profile_supports_io_path(const String &p_ip_path, const String &p_io_path) {
  349. if (!is_interaction_profile_supported(p_ip_path)) {
  350. return false;
  351. }
  352. const OpenXRInteractionProfileMetadata::IOPath *io_path = OpenXRInteractionProfileMetadata::get_singleton()->get_io_path(p_ip_path, p_io_path);
  353. // If the io_path is not part of our metadata we've likely got a misspelled name or a bad action map, report
  354. ERR_FAIL_NULL_V_MSG(io_path, false, "OpenXR: Unsupported io path " + String(p_ip_path) + String(p_io_path));
  355. if (io_path->openxr_extension_name == "") {
  356. // no extension needed, core io paths are always "supported", they just won't be used if not really supported
  357. return true;
  358. }
  359. if (!is_extension_enabled(io_path->openxr_extension_name)) {
  360. // It is very likely we have io paths for which the extension is not available so don't flood the logs with unnecessary spam.
  361. print_verbose("OpenXR: IO path " + String(p_ip_path) + String(p_io_path) + " requires extension " + io_path->openxr_extension_name);
  362. return false;
  363. }
  364. return true;
  365. }
  366. void OpenXRAPI::copy_string_to_char_buffer(const String p_string, char *p_buffer, int p_buffer_len) {
  367. CharString char_string = p_string.utf8();
  368. int len = char_string.length();
  369. if (len < p_buffer_len - 1) {
  370. // was having weird CI issues with strcpy so....
  371. memcpy(p_buffer, char_string.get_data(), len);
  372. p_buffer[len] = '\0';
  373. } else {
  374. memcpy(p_buffer, char_string.get_data(), p_buffer_len - 1);
  375. p_buffer[p_buffer_len - 1] = '\0';
  376. }
  377. }
  378. bool OpenXRAPI::create_instance() {
  379. // Create our OpenXR instance, this will query any registered extension wrappers for extensions we need to enable.
  380. // Append the extensions requested by the registered extension wrappers.
  381. HashMap<String, bool *> requested_extensions;
  382. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  383. const HashMap<String, bool *> &wrapper_request_extensions = wrapper->get_requested_extensions();
  384. for (const KeyValue<String, bool *> &requested_extension : wrapper_request_extensions) {
  385. requested_extensions[requested_extension.key] = requested_extension.value;
  386. }
  387. }
  388. // Check which extensions are supported.
  389. enabled_extensions.clear();
  390. for (KeyValue<String, bool *> &requested_extension : requested_extensions) {
  391. if (!is_extension_supported(requested_extension.key)) {
  392. if (requested_extension.value == nullptr) {
  393. // Null means this is a mandatory extension so we fail.
  394. ERR_FAIL_V_MSG(false, String("OpenXR: OpenXR Runtime does not support ") + requested_extension.key + String(" extension!"));
  395. } else {
  396. // Set this extension as not supported.
  397. *requested_extension.value = false;
  398. }
  399. } else if (requested_extension.value != nullptr) {
  400. // Set this extension as supported.
  401. *requested_extension.value = true;
  402. // And record that we want to enable it.
  403. enabled_extensions.push_back(requested_extension.key.ascii());
  404. } else {
  405. // Record that we want to enable this.
  406. enabled_extensions.push_back(requested_extension.key.ascii());
  407. }
  408. }
  409. Vector<const char *> extension_ptrs;
  410. for (int i = 0; i < enabled_extensions.size(); i++) {
  411. print_verbose(String("OpenXR: Enabling extension ") + String(enabled_extensions[i]));
  412. extension_ptrs.push_back(enabled_extensions[i].get_data());
  413. }
  414. // Get our project name
  415. String project_name = GLOBAL_GET("application/config/name");
  416. // Create our OpenXR instance
  417. XrApplicationInfo application_info{
  418. "", // applicationName, we'll set this down below
  419. 1, // applicationVersion, we don't currently have this
  420. "Godot Game Engine", // engineName
  421. VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_PATCH, // engineVersion 4.0 -> 40000, 4.0.1 -> 40001, 4.1 -> 40100, etc.
  422. XR_CURRENT_API_VERSION // apiVersion
  423. };
  424. void *next_pointer = nullptr;
  425. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  426. void *np = wrapper->set_instance_create_info_and_get_next_pointer(next_pointer);
  427. if (np != nullptr) {
  428. next_pointer = np;
  429. }
  430. }
  431. XrInstanceCreateInfo instance_create_info = {
  432. XR_TYPE_INSTANCE_CREATE_INFO, // type
  433. next_pointer, // next
  434. 0, // createFlags
  435. application_info, // applicationInfo
  436. 0, // enabledApiLayerCount, need to find out if we need support for this?
  437. nullptr, // enabledApiLayerNames
  438. uint32_t(extension_ptrs.size()), // enabledExtensionCount
  439. extension_ptrs.ptr() // enabledExtensionNames
  440. };
  441. copy_string_to_char_buffer(project_name, instance_create_info.applicationInfo.applicationName, XR_MAX_APPLICATION_NAME_SIZE);
  442. XrResult result = xrCreateInstance(&instance_create_info, &instance);
  443. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "Failed to create XR instance.");
  444. // from this point on we can use get_error_string to get more info about our errors...
  445. XrInstanceProperties instanceProps = {
  446. XR_TYPE_INSTANCE_PROPERTIES, // type;
  447. nullptr, // next
  448. 0, // runtimeVersion, from here will be set by our get call
  449. "" // runtimeName
  450. };
  451. OPENXR_API_INIT_XR_FUNC_V(xrGetInstanceProperties);
  452. result = xrGetInstanceProperties(instance, &instanceProps);
  453. if (XR_FAILED(result)) {
  454. // not fatal probably
  455. print_line("OpenXR: Failed to get XR instance properties [", get_error_string(result), "]");
  456. runtime_name = "";
  457. runtime_version = "";
  458. } else {
  459. runtime_name = instanceProps.runtimeName;
  460. runtime_version = OpenXRUtil::make_xr_version_string(instanceProps.runtimeVersion);
  461. print_line("OpenXR: Running on OpenXR runtime: ", runtime_name, " ", runtime_version);
  462. }
  463. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  464. wrapper->on_instance_created(instance);
  465. }
  466. return true;
  467. }
  468. bool OpenXRAPI::get_system_info() {
  469. // Retrieve basic OpenXR system info based on the form factor we desire
  470. // Retrieve the system for our form factor, fails if form factor is not available
  471. XrSystemGetInfo system_get_info = {
  472. XR_TYPE_SYSTEM_GET_INFO, // type;
  473. nullptr, // next
  474. form_factor // formFactor
  475. };
  476. XrResult result = xrGetSystem(instance, &system_get_info, &system_id);
  477. if (XR_FAILED(result)) {
  478. print_line("OpenXR: Failed to get system for our form factor [", get_error_string(result), "]");
  479. return false;
  480. }
  481. // obtain info about our system, writing this out completely to make CI on Linux happy..
  482. void *next_pointer = nullptr;
  483. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  484. void *np = wrapper->set_system_properties_and_get_next_pointer(next_pointer);
  485. if (np != nullptr) {
  486. next_pointer = np;
  487. }
  488. }
  489. XrSystemProperties system_properties = {
  490. XR_TYPE_SYSTEM_PROPERTIES, // type
  491. next_pointer, // next
  492. 0, // systemId, from here will be set by our get call
  493. 0, // vendorId
  494. "", // systemName
  495. {
  496. 0, // maxSwapchainImageHeight
  497. 0, // maxSwapchainImageWidth
  498. 0, // maxLayerCount
  499. }, // graphicsProperties
  500. {
  501. false, // orientationTracking
  502. false // positionTracking
  503. } // trackingProperties
  504. };
  505. result = xrGetSystemProperties(instance, system_id, &system_properties);
  506. if (XR_FAILED(result)) {
  507. print_line("OpenXR: Failed to get System properties [", get_error_string(result), "]");
  508. return false;
  509. }
  510. // remember this state, we'll use it later
  511. system_name = String(system_properties.systemName);
  512. vendor_id = system_properties.vendorId;
  513. graphics_properties = system_properties.graphicsProperties;
  514. tracking_properties = system_properties.trackingProperties;
  515. return true;
  516. }
  517. bool OpenXRAPI::load_supported_view_configuration_types() {
  518. // This queries the supported configuration types, likely there will only be one choosing between Mono (phone AR) and Stereo (HMDs)
  519. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  520. if (supported_view_configuration_types != nullptr) {
  521. // free previous results
  522. memfree(supported_view_configuration_types);
  523. supported_view_configuration_types = nullptr;
  524. }
  525. XrResult result = xrEnumerateViewConfigurations(instance, system_id, 0, &num_view_configuration_types, nullptr);
  526. if (XR_FAILED(result)) {
  527. print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]");
  528. return false;
  529. }
  530. supported_view_configuration_types = (XrViewConfigurationType *)memalloc(sizeof(XrViewConfigurationType) * num_view_configuration_types);
  531. ERR_FAIL_NULL_V(supported_view_configuration_types, false);
  532. result = xrEnumerateViewConfigurations(instance, system_id, num_view_configuration_types, &num_view_configuration_types, supported_view_configuration_types);
  533. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerateview configurations");
  534. ERR_FAIL_COND_V_MSG(num_view_configuration_types == 0, false, "OpenXR: Failed to enumerateview configurations"); // JIC there should be at least 1!
  535. for (uint32_t i = 0; i < num_view_configuration_types; i++) {
  536. print_verbose(String("OpenXR: Found supported view configuration ") + OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[i]));
  537. }
  538. // Check value we loaded at startup...
  539. if (!is_view_configuration_supported(view_configuration)) {
  540. print_verbose(String("OpenXR: ") + OpenXRUtil::get_view_configuration_name(view_configuration) + String(" isn't supported, defaulting to ") + OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[0]));
  541. view_configuration = supported_view_configuration_types[0];
  542. }
  543. return true;
  544. }
  545. bool OpenXRAPI::load_supported_environmental_blend_modes() {
  546. // This queries the supported environmental blend modes.
  547. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  548. if (supported_environment_blend_modes != nullptr) {
  549. // free previous results
  550. memfree(supported_environment_blend_modes);
  551. supported_environment_blend_modes = nullptr;
  552. num_supported_environment_blend_modes = 0;
  553. }
  554. XrResult result = xrEnumerateEnvironmentBlendModes(instance, system_id, view_configuration, 0, &num_supported_environment_blend_modes, nullptr);
  555. if (XR_FAILED(result)) {
  556. print_line("OpenXR: Failed to get supported environmental blend mode count [", get_error_string(result), "]");
  557. return false;
  558. }
  559. supported_environment_blend_modes = (XrEnvironmentBlendMode *)memalloc(sizeof(XrEnvironmentBlendMode) * num_supported_environment_blend_modes);
  560. ERR_FAIL_NULL_V(supported_environment_blend_modes, false);
  561. result = xrEnumerateEnvironmentBlendModes(instance, system_id, view_configuration, num_supported_environment_blend_modes, &num_supported_environment_blend_modes, supported_environment_blend_modes);
  562. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate environmental blend modes");
  563. ERR_FAIL_COND_V_MSG(num_supported_environment_blend_modes == 0, false, "OpenXR: Failed to enumerate environmental blend modes"); // JIC there should be at least 1!
  564. for (uint32_t i = 0; i < num_supported_environment_blend_modes; i++) {
  565. print_verbose(String("OpenXR: Found environmental blend mode ") + OpenXRUtil::get_environment_blend_mode_name(supported_environment_blend_modes[i]));
  566. }
  567. // Check value we loaded at startup...
  568. if (!is_environment_blend_mode_supported(environment_blend_mode)) {
  569. print_verbose(String("OpenXR: ") + OpenXRUtil::get_environment_blend_mode_name(environment_blend_mode) + String(" isn't supported, defaulting to ") + OpenXRUtil::get_environment_blend_mode_name(supported_environment_blend_modes[0]));
  570. environment_blend_mode = supported_environment_blend_modes[0];
  571. }
  572. return true;
  573. }
  574. bool OpenXRAPI::is_view_configuration_supported(XrViewConfigurationType p_configuration_type) const {
  575. ERR_FAIL_NULL_V(supported_view_configuration_types, false);
  576. for (uint32_t i = 0; i < num_view_configuration_types; i++) {
  577. if (supported_view_configuration_types[i] == p_configuration_type) {
  578. return true;
  579. }
  580. }
  581. return false;
  582. }
  583. bool OpenXRAPI::load_supported_view_configuration_views(XrViewConfigurationType p_configuration_type) {
  584. // This loads our view configuration for each view so for a stereo HMD, we'll get two entries (that are likely identical)
  585. // The returned data supplies us with the recommended render target size
  586. if (!is_view_configuration_supported(p_configuration_type)) {
  587. print_line("OpenXR: View configuration ", OpenXRUtil::get_view_configuration_name(view_configuration), " is not supported.");
  588. return false;
  589. }
  590. if (view_configuration_views != nullptr) {
  591. // free previous results
  592. memfree(view_configuration_views);
  593. view_configuration_views = nullptr;
  594. }
  595. XrResult result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, 0, &view_count, nullptr);
  596. if (XR_FAILED(result)) {
  597. print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]");
  598. return false;
  599. }
  600. view_configuration_views = (XrViewConfigurationView *)memalloc(sizeof(XrViewConfigurationView) * view_count);
  601. ERR_FAIL_NULL_V(view_configuration_views, false);
  602. for (uint32_t i = 0; i < view_count; i++) {
  603. view_configuration_views[i].type = XR_TYPE_VIEW_CONFIGURATION_VIEW;
  604. view_configuration_views[i].next = nullptr;
  605. }
  606. result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, view_count, &view_count, view_configuration_views);
  607. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate view configurations");
  608. for (uint32_t i = 0; i < view_count; i++) {
  609. print_verbose("OpenXR: Found supported view configuration view");
  610. print_verbose(String(" - width: ") + itos(view_configuration_views[i].maxImageRectWidth));
  611. print_verbose(String(" - height: ") + itos(view_configuration_views[i].maxImageRectHeight));
  612. print_verbose(String(" - sample count: ") + itos(view_configuration_views[i].maxSwapchainSampleCount));
  613. print_verbose(String(" - recommended render width: ") + itos(view_configuration_views[i].recommendedImageRectWidth));
  614. print_verbose(String(" - recommended render height: ") + itos(view_configuration_views[i].recommendedImageRectHeight));
  615. print_verbose(String(" - recommended render sample count: ") + itos(view_configuration_views[i].recommendedSwapchainSampleCount));
  616. }
  617. return true;
  618. }
  619. void OpenXRAPI::destroy_instance() {
  620. if (view_configuration_views != nullptr) {
  621. memfree(view_configuration_views);
  622. view_configuration_views = nullptr;
  623. }
  624. if (supported_view_configuration_types != nullptr) {
  625. memfree(supported_view_configuration_types);
  626. supported_view_configuration_types = nullptr;
  627. }
  628. if (supported_environment_blend_modes != nullptr) {
  629. memfree(supported_environment_blend_modes);
  630. supported_environment_blend_modes = nullptr;
  631. num_supported_environment_blend_modes = 0;
  632. }
  633. if (instance != XR_NULL_HANDLE) {
  634. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  635. wrapper->on_instance_destroyed();
  636. }
  637. xrDestroyInstance(instance);
  638. instance = XR_NULL_HANDLE;
  639. }
  640. enabled_extensions.clear();
  641. if (graphics_extension != nullptr) {
  642. unregister_extension_wrapper(graphics_extension);
  643. memdelete(graphics_extension);
  644. graphics_extension = nullptr;
  645. }
  646. }
  647. bool OpenXRAPI::create_session() {
  648. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  649. ERR_FAIL_COND_V(session != XR_NULL_HANDLE, false);
  650. void *next_pointer = nullptr;
  651. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  652. void *np = wrapper->set_session_create_and_get_next_pointer(next_pointer);
  653. if (np != nullptr) {
  654. next_pointer = np;
  655. }
  656. }
  657. XrSessionCreateInfo session_create_info = {
  658. XR_TYPE_SESSION_CREATE_INFO, // type
  659. next_pointer, // next
  660. 0, // createFlags
  661. system_id // systemId
  662. };
  663. XrResult result = xrCreateSession(instance, &session_create_info, &session);
  664. if (XR_FAILED(result)) {
  665. print_line("OpenXR: Failed to create session [", get_error_string(result), "]");
  666. return false;
  667. }
  668. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  669. wrapper->on_session_created(session);
  670. }
  671. return true;
  672. }
  673. bool OpenXRAPI::load_supported_reference_spaces() {
  674. // loads the supported reference spaces for our OpenXR session
  675. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  676. if (supported_reference_spaces != nullptr) {
  677. // free previous results
  678. memfree(supported_reference_spaces);
  679. supported_reference_spaces = nullptr;
  680. }
  681. XrResult result = xrEnumerateReferenceSpaces(session, 0, &num_reference_spaces, nullptr);
  682. if (XR_FAILED(result)) {
  683. print_line("OpenXR: Failed to get reference space count [", get_error_string(result), "]");
  684. return false;
  685. }
  686. supported_reference_spaces = (XrReferenceSpaceType *)memalloc(sizeof(XrReferenceSpaceType) * num_reference_spaces);
  687. ERR_FAIL_NULL_V(supported_reference_spaces, false);
  688. result = xrEnumerateReferenceSpaces(session, num_reference_spaces, &num_reference_spaces, supported_reference_spaces);
  689. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate reference spaces");
  690. ERR_FAIL_COND_V_MSG(num_reference_spaces == 0, false, "OpenXR: Failed to enumerate reference spaces");
  691. for (uint32_t i = 0; i < num_reference_spaces; i++) {
  692. print_verbose(String("OpenXR: Found supported reference space ") + OpenXRUtil::get_reference_space_name(supported_reference_spaces[i]));
  693. }
  694. return true;
  695. }
  696. bool OpenXRAPI::is_reference_space_supported(XrReferenceSpaceType p_reference_space) {
  697. ERR_FAIL_NULL_V(supported_reference_spaces, false);
  698. for (uint32_t i = 0; i < num_reference_spaces; i++) {
  699. if (supported_reference_spaces[i] == p_reference_space) {
  700. return true;
  701. }
  702. }
  703. return false;
  704. }
  705. bool OpenXRAPI::setup_play_space() {
  706. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  707. XrPosef identityPose = {
  708. { 0.0, 0.0, 0.0, 1.0 },
  709. { 0.0, 0.0, 0.0 }
  710. };
  711. XrReferenceSpaceType new_reference_space;
  712. XrSpace new_play_space = XR_NULL_HANDLE;
  713. bool will_emulate_local_floor = false;
  714. if (is_reference_space_supported(requested_reference_space)) {
  715. new_reference_space = requested_reference_space;
  716. } else if (requested_reference_space == XR_REFERENCE_SPACE_TYPE_LOCAL_FLOOR_EXT && is_reference_space_supported(XR_REFERENCE_SPACE_TYPE_STAGE)) {
  717. print_verbose("OpenXR: LOCAL_FLOOR space isn't supported, emulating using STAGE and LOCAL spaces.");
  718. new_reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
  719. will_emulate_local_floor = true;
  720. } else {
  721. // Fallback on LOCAL, which all OpenXR runtimes are required to support.
  722. print_verbose(String("OpenXR: ") + OpenXRUtil::get_reference_space_name(requested_reference_space) + String(" isn't supported, defaulting to LOCAL space."));
  723. new_reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
  724. }
  725. XrReferenceSpaceCreateInfo play_space_create_info = {
  726. XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
  727. nullptr, // next
  728. new_reference_space, // referenceSpaceType
  729. identityPose, // poseInReferenceSpace
  730. };
  731. XrResult result = xrCreateReferenceSpace(session, &play_space_create_info, &new_play_space);
  732. if (XR_FAILED(result)) {
  733. print_line("OpenXR: Failed to create play space [", get_error_string(result), "]");
  734. return false;
  735. }
  736. // If we've previously created a play space, clean it up first.
  737. if (play_space != XR_NULL_HANDLE) {
  738. // TODO Investigate if destroying our play space here is safe,
  739. // it may still be used in the rendering thread.
  740. xrDestroySpace(play_space);
  741. }
  742. play_space = new_play_space;
  743. reference_space = new_reference_space;
  744. emulating_local_floor = will_emulate_local_floor;
  745. if (emulating_local_floor) {
  746. // We'll use the STAGE space to get the floor height, but we can't do that until
  747. // after xrWaitFrame(), so just set this flag for now.
  748. // Render state will be updated then.
  749. should_reset_emulated_floor_height = true;
  750. } else {
  751. // Update render state so this play space is used rendering the upcoming frame.
  752. set_render_play_space(play_space);
  753. }
  754. return true;
  755. }
  756. bool OpenXRAPI::setup_view_space() {
  757. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  758. if (!is_reference_space_supported(XR_REFERENCE_SPACE_TYPE_VIEW)) {
  759. print_line("OpenXR: reference space XR_REFERENCE_SPACE_TYPE_VIEW is not supported.");
  760. return false;
  761. }
  762. XrPosef identityPose = {
  763. { 0.0, 0.0, 0.0, 1.0 },
  764. { 0.0, 0.0, 0.0 }
  765. };
  766. XrReferenceSpaceCreateInfo view_space_create_info = {
  767. XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
  768. nullptr, // next
  769. XR_REFERENCE_SPACE_TYPE_VIEW, // referenceSpaceType
  770. identityPose // poseInReferenceSpace
  771. };
  772. XrResult result = xrCreateReferenceSpace(session, &view_space_create_info, &view_space);
  773. if (XR_FAILED(result)) {
  774. print_line("OpenXR: Failed to create view space [", get_error_string(result), "]");
  775. return false;
  776. }
  777. return true;
  778. }
  779. bool OpenXRAPI::reset_emulated_floor_height() {
  780. ERR_FAIL_COND_V(!emulating_local_floor, false);
  781. // This is based on the example code in the OpenXR spec which shows how to
  782. // emulate LOCAL_FLOOR if it's not supported.
  783. // See: https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html#XR_EXT_local_floor
  784. XrResult result;
  785. XrPosef identityPose = {
  786. { 0.0, 0.0, 0.0, 1.0 },
  787. { 0.0, 0.0, 0.0 }
  788. };
  789. XrSpace local_space = XR_NULL_HANDLE;
  790. XrSpace stage_space = XR_NULL_HANDLE;
  791. XrReferenceSpaceCreateInfo create_info = {
  792. XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
  793. nullptr, // next
  794. XR_REFERENCE_SPACE_TYPE_LOCAL, // referenceSpaceType
  795. identityPose, // poseInReferenceSpace
  796. };
  797. result = xrCreateReferenceSpace(session, &create_info, &local_space);
  798. if (XR_FAILED(result)) {
  799. print_line("OpenXR: Failed to create LOCAL space in order to emulate LOCAL_FLOOR [", get_error_string(result), "]");
  800. return false;
  801. }
  802. create_info.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_STAGE;
  803. result = xrCreateReferenceSpace(session, &create_info, &stage_space);
  804. if (XR_FAILED(result)) {
  805. print_line("OpenXR: Failed to create STAGE space in order to emulate LOCAL_FLOOR [", get_error_string(result), "]");
  806. xrDestroySpace(local_space);
  807. return false;
  808. }
  809. XrSpaceLocation stage_location = {
  810. XR_TYPE_SPACE_LOCATION, // type
  811. nullptr, // next
  812. 0, // locationFlags
  813. identityPose, // pose
  814. };
  815. result = xrLocateSpace(stage_space, local_space, get_predicted_display_time(), &stage_location);
  816. xrDestroySpace(local_space);
  817. xrDestroySpace(stage_space);
  818. if (XR_FAILED(result)) {
  819. print_line("OpenXR: Failed to locate STAGE space in LOCAL space, in order to emulate LOCAL_FLOOR [", get_error_string(result), "]");
  820. return false;
  821. }
  822. XrSpace new_play_space;
  823. create_info.referenceSpaceType = XR_REFERENCE_SPACE_TYPE_LOCAL;
  824. create_info.poseInReferenceSpace.position.y = stage_location.pose.position.y;
  825. result = xrCreateReferenceSpace(session, &create_info, &new_play_space);
  826. if (XR_FAILED(result)) {
  827. print_line("OpenXR: Failed to recreate emulated LOCAL_FLOOR play space with latest floor estimate [", get_error_string(result), "]");
  828. return false;
  829. }
  830. xrDestroySpace(play_space);
  831. play_space = new_play_space;
  832. // If we've made it this far, it means we can properly emulate LOCAL_FLOOR, so we'll
  833. // report that as the reference space to the outside world.
  834. reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL_FLOOR_EXT;
  835. // Update render state so this play space is used rendering the upcoming frame.
  836. set_render_play_space(play_space);
  837. return true;
  838. }
  839. bool OpenXRAPI::load_supported_swapchain_formats() {
  840. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  841. if (supported_swapchain_formats != nullptr) {
  842. // free previous results
  843. memfree(supported_swapchain_formats);
  844. supported_swapchain_formats = nullptr;
  845. }
  846. XrResult result = xrEnumerateSwapchainFormats(session, 0, &num_swapchain_formats, nullptr);
  847. if (XR_FAILED(result)) {
  848. print_line("OpenXR: Failed to get swapchain format count [", get_error_string(result), "]");
  849. return false;
  850. }
  851. supported_swapchain_formats = (int64_t *)memalloc(sizeof(int64_t) * num_swapchain_formats);
  852. ERR_FAIL_NULL_V(supported_swapchain_formats, false);
  853. result = xrEnumerateSwapchainFormats(session, num_swapchain_formats, &num_swapchain_formats, supported_swapchain_formats);
  854. ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate swapchain formats");
  855. for (uint32_t i = 0; i < num_swapchain_formats; i++) {
  856. print_verbose(String("OpenXR: Found supported swapchain format ") + get_swapchain_format_name(supported_swapchain_formats[i]));
  857. }
  858. return true;
  859. }
  860. bool OpenXRAPI::is_swapchain_format_supported(int64_t p_swapchain_format) {
  861. ERR_FAIL_NULL_V(supported_swapchain_formats, false);
  862. for (uint32_t i = 0; i < num_swapchain_formats; i++) {
  863. if (supported_swapchain_formats[i] == p_swapchain_format) {
  864. return true;
  865. }
  866. }
  867. return false;
  868. }
  869. bool OpenXRAPI::obtain_swapchain_formats() {
  870. ERR_FAIL_NULL_V(graphics_extension, false);
  871. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  872. {
  873. // Build a vector with swapchain formats we want to use, from best fit to worst
  874. Vector<int64_t> usable_swapchain_formats;
  875. color_swapchain_format = 0;
  876. graphics_extension->get_usable_swapchain_formats(usable_swapchain_formats);
  877. // now find out which one is supported
  878. for (int i = 0; i < usable_swapchain_formats.size() && color_swapchain_format == 0; i++) {
  879. if (is_swapchain_format_supported(usable_swapchain_formats[i])) {
  880. color_swapchain_format = usable_swapchain_formats[i];
  881. }
  882. }
  883. if (color_swapchain_format == 0) {
  884. color_swapchain_format = usable_swapchain_formats[0]; // just use the first one and hope for the best...
  885. print_line("Couldn't find usable color swap chain format, using", get_swapchain_format_name(color_swapchain_format), "instead.");
  886. } else {
  887. print_verbose(String("Using color swap chain format:") + get_swapchain_format_name(color_swapchain_format));
  888. }
  889. }
  890. {
  891. // Build a vector with swapchain formats we want to use, from best fit to worst
  892. Vector<int64_t> usable_swapchain_formats;
  893. depth_swapchain_format = 0;
  894. graphics_extension->get_usable_depth_formats(usable_swapchain_formats);
  895. // now find out which one is supported
  896. for (int i = 0; i < usable_swapchain_formats.size() && depth_swapchain_format == 0; i++) {
  897. if (is_swapchain_format_supported(usable_swapchain_formats[i])) {
  898. depth_swapchain_format = usable_swapchain_formats[i];
  899. }
  900. }
  901. if (depth_swapchain_format == 0) {
  902. WARN_PRINT_ONCE("Couldn't find usable depth swap chain format, depth buffer will not be submitted if requested.");
  903. } else {
  904. print_verbose(String("Using depth swap chain format:") + get_swapchain_format_name(depth_swapchain_format));
  905. }
  906. }
  907. return true;
  908. }
  909. bool OpenXRAPI::create_main_swapchains(Size2i p_size) {
  910. ERR_NOT_ON_RENDER_THREAD_V(false);
  911. ERR_FAIL_NULL_V(graphics_extension, false);
  912. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  913. /*
  914. TODO: We need to improve on this, for now we're taking our old approach of creating our main swapchains and substituting
  915. those for the ones Godot normally creates.
  916. This however means we can only use swapchains for our main XR view.
  917. It would have been nicer if we could override the swapchain creation in Godot with ours but we have a timing issue here.
  918. We can't create XR swapchains until after our XR session is fully instantiated, yet Godot creates its swapchain much earlier.
  919. We only creates a swapchain for the main output here.
  920. Additional swapchains may be created through our composition layer extension.
  921. Finally an area we need to expand upon is that Foveated rendering is only enabled for the swap chain we create,
  922. as we render 3D content into internal buffers that are copied into the swapchain, we do now have (basic) VRS support
  923. */
  924. render_state.main_swapchain_size = p_size;
  925. uint32_t sample_count = 1;
  926. // We start with our color swapchain...
  927. if (color_swapchain_format != 0) {
  928. if (!render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].create(0, XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT | XR_SWAPCHAIN_USAGE_MUTABLE_FORMAT_BIT, color_swapchain_format, render_state.main_swapchain_size.width, render_state.main_swapchain_size.height, sample_count, view_count)) {
  929. return false;
  930. }
  931. }
  932. // We create our depth swapchain if:
  933. // - we've enabled submitting depth buffer
  934. // - we support our depth layer extension
  935. // - we have our spacewarp extension (not yet implemented)
  936. if (depth_swapchain_format != 0 && submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available()) {
  937. if (!render_state.main_swapchains[OPENXR_SWAPCHAIN_DEPTH].create(0, XR_SWAPCHAIN_USAGE_SAMPLED_BIT | XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, depth_swapchain_format, render_state.main_swapchain_size.width, render_state.main_swapchain_size.height, sample_count, view_count)) {
  938. return false;
  939. }
  940. }
  941. // We create our velocity swapchain if:
  942. // - we have our spacewarp extension (not yet implemented)
  943. {
  944. // TBD
  945. }
  946. for (uint32_t i = 0; i < render_state.view_count; i++) {
  947. render_state.views[i].type = XR_TYPE_VIEW;
  948. render_state.views[i].next = nullptr;
  949. render_state.projection_views[i].type = XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW;
  950. render_state.projection_views[i].next = nullptr;
  951. render_state.projection_views[i].subImage.swapchain = render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].get_swapchain();
  952. render_state.projection_views[i].subImage.imageArrayIndex = i;
  953. render_state.projection_views[i].subImage.imageRect.offset.x = 0;
  954. render_state.projection_views[i].subImage.imageRect.offset.y = 0;
  955. render_state.projection_views[i].subImage.imageRect.extent.width = render_state.main_swapchain_size.width;
  956. render_state.projection_views[i].subImage.imageRect.extent.height = render_state.main_swapchain_size.height;
  957. if (render_state.submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available() && render_state.depth_views) {
  958. render_state.projection_views[i].next = &render_state.depth_views[i];
  959. render_state.depth_views[i].type = XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR;
  960. render_state.depth_views[i].next = nullptr;
  961. render_state.depth_views[i].subImage.swapchain = render_state.main_swapchains[OPENXR_SWAPCHAIN_DEPTH].get_swapchain();
  962. render_state.depth_views[i].subImage.imageArrayIndex = i;
  963. render_state.depth_views[i].subImage.imageRect.offset.x = 0;
  964. render_state.depth_views[i].subImage.imageRect.offset.y = 0;
  965. render_state.depth_views[i].subImage.imageRect.extent.width = render_state.main_swapchain_size.width;
  966. render_state.depth_views[i].subImage.imageRect.extent.height = render_state.main_swapchain_size.height;
  967. // OpenXR spec says that: minDepth < maxDepth.
  968. render_state.depth_views[i].minDepth = 0.0;
  969. render_state.depth_views[i].maxDepth = 1.0;
  970. // But we can reverse near and far for reverse-Z.
  971. render_state.depth_views[i].nearZ = 100.0; // Near and far Z will be set to the correct values in fill_projection_matrix
  972. render_state.depth_views[i].farZ = 0.01;
  973. }
  974. };
  975. return true;
  976. };
  977. void OpenXRAPI::destroy_session() {
  978. // TODO need to figure out if we're still rendering our current frame
  979. // in a separate rendering thread and if so,
  980. // if we need to wait for completion.
  981. // We could be pulling the rug from underneath rendering...
  982. if (running) {
  983. if (session != XR_NULL_HANDLE) {
  984. xrEndSession(session);
  985. }
  986. running = false;
  987. render_state.running = false;
  988. }
  989. if (render_state.views != nullptr) {
  990. memfree(render_state.views);
  991. render_state.views = nullptr;
  992. }
  993. if (render_state.projection_views != nullptr) {
  994. memfree(render_state.projection_views);
  995. render_state.projection_views = nullptr;
  996. }
  997. if (render_state.depth_views != nullptr) {
  998. memfree(render_state.depth_views);
  999. render_state.depth_views = nullptr;
  1000. }
  1001. free_main_swapchains();
  1002. OpenXRSwapChainInfo::free_queued();
  1003. if (supported_swapchain_formats != nullptr) {
  1004. memfree(supported_swapchain_formats);
  1005. supported_swapchain_formats = nullptr;
  1006. }
  1007. // destroy our spaces
  1008. if (play_space != XR_NULL_HANDLE) {
  1009. xrDestroySpace(play_space);
  1010. play_space = XR_NULL_HANDLE;
  1011. render_state.play_space = XR_NULL_HANDLE;
  1012. }
  1013. if (view_space != XR_NULL_HANDLE) {
  1014. xrDestroySpace(view_space);
  1015. view_space = XR_NULL_HANDLE;
  1016. }
  1017. if (supported_reference_spaces != nullptr) {
  1018. // free previous results
  1019. memfree(supported_reference_spaces);
  1020. supported_reference_spaces = nullptr;
  1021. }
  1022. if (session != XR_NULL_HANDLE) {
  1023. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1024. wrapper->on_session_destroyed();
  1025. }
  1026. xrDestroySession(session);
  1027. session = XR_NULL_HANDLE;
  1028. }
  1029. }
  1030. bool OpenXRAPI::on_state_idle() {
  1031. print_verbose("On state idle");
  1032. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1033. wrapper->on_state_idle();
  1034. }
  1035. return true;
  1036. }
  1037. bool OpenXRAPI::on_state_ready() {
  1038. print_verbose("On state ready");
  1039. // begin session
  1040. XrSessionBeginInfo session_begin_info = {
  1041. XR_TYPE_SESSION_BEGIN_INFO, // type
  1042. nullptr, // next
  1043. view_configuration // primaryViewConfigurationType
  1044. };
  1045. XrResult result = xrBeginSession(session, &session_begin_info);
  1046. if (XR_FAILED(result)) {
  1047. print_line("OpenXR: Failed to begin session [", get_error_string(result), "]");
  1048. return false;
  1049. }
  1050. // we're running
  1051. running = true;
  1052. set_render_session_running(true);
  1053. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1054. wrapper->on_state_ready();
  1055. }
  1056. if (xr_interface) {
  1057. xr_interface->on_state_ready();
  1058. }
  1059. return true;
  1060. }
  1061. bool OpenXRAPI::on_state_synchronized() {
  1062. print_verbose("On state synchronized");
  1063. // Just in case, see if we already have active trackers...
  1064. List<RID> trackers;
  1065. tracker_owner.get_owned_list(&trackers);
  1066. for (int i = 0; i < trackers.size(); i++) {
  1067. tracker_check_profile(trackers[i]);
  1068. }
  1069. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1070. wrapper->on_state_synchronized();
  1071. }
  1072. return true;
  1073. }
  1074. bool OpenXRAPI::on_state_visible() {
  1075. print_verbose("On state visible");
  1076. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1077. wrapper->on_state_visible();
  1078. }
  1079. if (xr_interface) {
  1080. xr_interface->on_state_visible();
  1081. }
  1082. return true;
  1083. }
  1084. bool OpenXRAPI::on_state_focused() {
  1085. print_verbose("On state focused");
  1086. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1087. wrapper->on_state_focused();
  1088. }
  1089. if (xr_interface) {
  1090. xr_interface->on_state_focused();
  1091. }
  1092. return true;
  1093. }
  1094. bool OpenXRAPI::on_state_stopping() {
  1095. print_verbose("On state stopping");
  1096. if (xr_interface) {
  1097. xr_interface->on_state_stopping();
  1098. }
  1099. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1100. wrapper->on_state_stopping();
  1101. }
  1102. if (running) {
  1103. XrResult result = xrEndSession(session);
  1104. if (XR_FAILED(result)) {
  1105. // we only report this..
  1106. print_line("OpenXR: Failed to end session [", get_error_string(result), "]");
  1107. }
  1108. running = false;
  1109. set_render_session_running(false);
  1110. }
  1111. return true;
  1112. }
  1113. bool OpenXRAPI::on_state_loss_pending() {
  1114. print_verbose("On state loss pending");
  1115. if (xr_interface) {
  1116. xr_interface->on_state_loss_pending();
  1117. }
  1118. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1119. wrapper->on_state_loss_pending();
  1120. }
  1121. return true;
  1122. }
  1123. bool OpenXRAPI::on_state_exiting() {
  1124. print_verbose("On state existing");
  1125. if (xr_interface) {
  1126. xr_interface->on_state_exiting();
  1127. }
  1128. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1129. wrapper->on_state_exiting();
  1130. }
  1131. return true;
  1132. }
  1133. void OpenXRAPI::set_form_factor(XrFormFactor p_form_factor) {
  1134. ERR_FAIL_COND(is_initialized());
  1135. form_factor = p_form_factor;
  1136. }
  1137. void OpenXRAPI::set_view_configuration(XrViewConfigurationType p_view_configuration) {
  1138. ERR_FAIL_COND(is_initialized());
  1139. view_configuration = p_view_configuration;
  1140. }
  1141. bool OpenXRAPI::set_requested_reference_space(XrReferenceSpaceType p_requested_reference_space) {
  1142. requested_reference_space = p_requested_reference_space;
  1143. play_space_is_dirty = true;
  1144. return true;
  1145. }
  1146. void OpenXRAPI::set_submit_depth_buffer(bool p_submit_depth_buffer) {
  1147. ERR_FAIL_COND(is_initialized());
  1148. submit_depth_buffer = p_submit_depth_buffer;
  1149. }
  1150. bool OpenXRAPI::is_initialized() {
  1151. return (instance != XR_NULL_HANDLE);
  1152. }
  1153. bool OpenXRAPI::is_running() {
  1154. if (instance == XR_NULL_HANDLE) {
  1155. return false;
  1156. }
  1157. if (session == XR_NULL_HANDLE) {
  1158. return false;
  1159. }
  1160. return running;
  1161. }
  1162. bool OpenXRAPI::openxr_loader_init() {
  1163. #ifdef ANDROID_ENABLED
  1164. ERR_FAIL_COND_V_MSG(openxr_loader_library_handle != nullptr, false, "OpenXR Loader library is already loaded.");
  1165. {
  1166. Error error_code = OS::get_singleton()->open_dynamic_library(OPENXR_LOADER_NAME, openxr_loader_library_handle);
  1167. ERR_FAIL_COND_V_MSG(error_code != OK, false, "OpenXR loader not found.");
  1168. }
  1169. {
  1170. Error error_code = OS::get_singleton()->get_dynamic_library_symbol_handle(openxr_loader_library_handle, "xrGetInstanceProcAddr", (void *&)xrGetInstanceProcAddr);
  1171. ERR_FAIL_COND_V_MSG(error_code != OK, false, "Symbol xrGetInstanceProcAddr not found in OpenXR Loader library.");
  1172. }
  1173. #endif
  1174. // Resolve the symbols that don't require an instance
  1175. OPENXR_API_INIT_XR_FUNC_V(xrCreateInstance);
  1176. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateApiLayerProperties);
  1177. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateInstanceExtensionProperties);
  1178. return true;
  1179. }
  1180. bool OpenXRAPI::resolve_instance_openxr_symbols() {
  1181. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1182. OPENXR_API_INIT_XR_FUNC_V(xrAcquireSwapchainImage);
  1183. OPENXR_API_INIT_XR_FUNC_V(xrApplyHapticFeedback);
  1184. OPENXR_API_INIT_XR_FUNC_V(xrAttachSessionActionSets);
  1185. OPENXR_API_INIT_XR_FUNC_V(xrBeginFrame);
  1186. OPENXR_API_INIT_XR_FUNC_V(xrBeginSession);
  1187. OPENXR_API_INIT_XR_FUNC_V(xrCreateAction);
  1188. OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSet);
  1189. OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSpace);
  1190. OPENXR_API_INIT_XR_FUNC_V(xrCreateReferenceSpace);
  1191. OPENXR_API_INIT_XR_FUNC_V(xrCreateSession);
  1192. OPENXR_API_INIT_XR_FUNC_V(xrCreateSwapchain);
  1193. OPENXR_API_INIT_XR_FUNC_V(xrDestroyAction);
  1194. OPENXR_API_INIT_XR_FUNC_V(xrDestroyActionSet);
  1195. OPENXR_API_INIT_XR_FUNC_V(xrDestroyInstance);
  1196. OPENXR_API_INIT_XR_FUNC_V(xrDestroySession);
  1197. OPENXR_API_INIT_XR_FUNC_V(xrDestroySpace);
  1198. OPENXR_API_INIT_XR_FUNC_V(xrDestroySwapchain);
  1199. OPENXR_API_INIT_XR_FUNC_V(xrEndFrame);
  1200. OPENXR_API_INIT_XR_FUNC_V(xrEndSession);
  1201. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateEnvironmentBlendModes);
  1202. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateReferenceSpaces);
  1203. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateSwapchainFormats);
  1204. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurations);
  1205. OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurationViews);
  1206. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateBoolean);
  1207. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateFloat);
  1208. OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateVector2f);
  1209. OPENXR_API_INIT_XR_FUNC_V(xrGetCurrentInteractionProfile);
  1210. OPENXR_API_INIT_XR_FUNC_V(xrGetReferenceSpaceBoundsRect);
  1211. OPENXR_API_INIT_XR_FUNC_V(xrGetSystem);
  1212. OPENXR_API_INIT_XR_FUNC_V(xrGetSystemProperties);
  1213. OPENXR_API_INIT_XR_FUNC_V(xrLocateViews);
  1214. OPENXR_API_INIT_XR_FUNC_V(xrLocateSpace);
  1215. OPENXR_API_INIT_XR_FUNC_V(xrPathToString);
  1216. OPENXR_API_INIT_XR_FUNC_V(xrPollEvent);
  1217. OPENXR_API_INIT_XR_FUNC_V(xrReleaseSwapchainImage);
  1218. OPENXR_API_INIT_XR_FUNC_V(xrResultToString);
  1219. OPENXR_API_INIT_XR_FUNC_V(xrStringToPath);
  1220. OPENXR_API_INIT_XR_FUNC_V(xrSuggestInteractionProfileBindings);
  1221. OPENXR_API_INIT_XR_FUNC_V(xrSyncActions);
  1222. OPENXR_API_INIT_XR_FUNC_V(xrWaitFrame);
  1223. OPENXR_API_INIT_XR_FUNC_V(xrWaitSwapchainImage);
  1224. return true;
  1225. }
  1226. XrResult OpenXRAPI::try_get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) {
  1227. return xrGetInstanceProcAddr(instance, p_name, p_addr);
  1228. }
  1229. XrResult OpenXRAPI::get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) {
  1230. XrResult result = try_get_instance_proc_addr(p_name, p_addr);
  1231. if (result != XR_SUCCESS) {
  1232. String error_message = String("Symbol ") + p_name + " not found in OpenXR instance.";
  1233. ERR_FAIL_V_MSG(result, error_message.utf8().get_data());
  1234. }
  1235. return result;
  1236. }
  1237. bool OpenXRAPI::initialize(const String &p_rendering_driver) {
  1238. ERR_FAIL_COND_V_MSG(instance != XR_NULL_HANDLE, false, "OpenXR instance was already created");
  1239. if (!openxr_loader_init()) {
  1240. return false;
  1241. }
  1242. if (p_rendering_driver == "vulkan") {
  1243. #ifdef VULKAN_ENABLED
  1244. graphics_extension = memnew(OpenXRVulkanExtension);
  1245. register_extension_wrapper(graphics_extension);
  1246. #else
  1247. // shouldn't be possible...
  1248. ERR_FAIL_V(false);
  1249. #endif
  1250. } else if (p_rendering_driver == "opengl3") {
  1251. #if defined(GLES3_ENABLED) && !defined(MACOS_ENABLED)
  1252. graphics_extension = memnew(OpenXROpenGLExtension);
  1253. register_extension_wrapper(graphics_extension);
  1254. #else
  1255. // shouldn't be possible...
  1256. ERR_FAIL_V(false);
  1257. #endif
  1258. } else {
  1259. ERR_FAIL_V_MSG(false, "OpenXR: Unsupported rendering device.");
  1260. }
  1261. // Also register our rendering extensions
  1262. register_extension_wrapper(memnew(OpenXRFBUpdateSwapchainExtension(p_rendering_driver)));
  1263. register_extension_wrapper(memnew(OpenXRFBFoveationExtension(p_rendering_driver)));
  1264. // initialize
  1265. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1266. wrapper->on_before_instance_created();
  1267. }
  1268. if (!load_layer_properties()) {
  1269. destroy_instance();
  1270. return false;
  1271. }
  1272. if (!load_supported_extensions()) {
  1273. destroy_instance();
  1274. return false;
  1275. }
  1276. if (!create_instance()) {
  1277. destroy_instance();
  1278. return false;
  1279. }
  1280. if (!resolve_instance_openxr_symbols()) {
  1281. destroy_instance();
  1282. return false;
  1283. }
  1284. if (!get_system_info()) {
  1285. destroy_instance();
  1286. return false;
  1287. }
  1288. if (!load_supported_view_configuration_types()) {
  1289. destroy_instance();
  1290. return false;
  1291. }
  1292. if (!load_supported_view_configuration_views(view_configuration)) {
  1293. destroy_instance();
  1294. return false;
  1295. }
  1296. if (!load_supported_environmental_blend_modes()) {
  1297. destroy_instance();
  1298. return false;
  1299. }
  1300. return true;
  1301. }
  1302. bool OpenXRAPI::initialize_session() {
  1303. if (!create_session()) {
  1304. destroy_session();
  1305. return false;
  1306. }
  1307. if (!load_supported_reference_spaces()) {
  1308. destroy_session();
  1309. return false;
  1310. }
  1311. if (!setup_view_space()) {
  1312. destroy_session();
  1313. return false;
  1314. }
  1315. if (!load_supported_swapchain_formats()) {
  1316. destroy_session();
  1317. return false;
  1318. }
  1319. if (!obtain_swapchain_formats()) {
  1320. destroy_session();
  1321. return false;
  1322. }
  1323. allocate_view_buffers(view_count, submit_depth_buffer);
  1324. return true;
  1325. }
  1326. void OpenXRAPI::finish() {
  1327. destroy_session();
  1328. destroy_instance();
  1329. }
  1330. void OpenXRAPI::set_xr_interface(OpenXRInterface *p_xr_interface) {
  1331. xr_interface = p_xr_interface;
  1332. }
  1333. void OpenXRAPI::register_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
  1334. registered_extension_wrappers.push_back(p_extension_wrapper);
  1335. }
  1336. void OpenXRAPI::unregister_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
  1337. registered_extension_wrappers.erase(p_extension_wrapper);
  1338. }
  1339. const Vector<OpenXRExtensionWrapper *> &OpenXRAPI::get_registered_extension_wrappers() {
  1340. return registered_extension_wrappers;
  1341. }
  1342. void OpenXRAPI::register_extension_metadata() {
  1343. for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
  1344. extension_wrapper->on_register_metadata();
  1345. }
  1346. }
  1347. void OpenXRAPI::cleanup_extension_wrappers() {
  1348. for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
  1349. // Fix crash when the extension wrapper comes from GDExtension.
  1350. OpenXRExtensionWrapperExtension *gdextension_extension_wrapper = dynamic_cast<OpenXRExtensionWrapperExtension *>(extension_wrapper);
  1351. if (gdextension_extension_wrapper) {
  1352. memdelete(gdextension_extension_wrapper);
  1353. } else {
  1354. memdelete(extension_wrapper);
  1355. }
  1356. }
  1357. registered_extension_wrappers.clear();
  1358. }
  1359. XrHandTrackerEXT OpenXRAPI::get_hand_tracker(int p_hand_index) {
  1360. ERR_FAIL_INDEX_V(p_hand_index, OpenXRHandTrackingExtension::HandTrackedHands::OPENXR_MAX_TRACKED_HANDS, XR_NULL_HANDLE);
  1361. OpenXRHandTrackingExtension::HandTrackedHands hand = static_cast<OpenXRHandTrackingExtension::HandTrackedHands>(p_hand_index);
  1362. return OpenXRHandTrackingExtension::get_singleton()->get_hand_tracker(hand)->hand_tracker;
  1363. }
  1364. Size2 OpenXRAPI::get_recommended_target_size() {
  1365. RenderingServer *rendering_server = RenderingServer::get_singleton();
  1366. ERR_FAIL_NULL_V(view_configuration_views, Size2());
  1367. Size2 target_size;
  1368. if (rendering_server && rendering_server->is_on_render_thread()) {
  1369. target_size.width = view_configuration_views[0].recommendedImageRectWidth * render_state.render_target_size_multiplier;
  1370. target_size.height = view_configuration_views[0].recommendedImageRectHeight * render_state.render_target_size_multiplier;
  1371. } else {
  1372. target_size.width = view_configuration_views[0].recommendedImageRectWidth * render_target_size_multiplier;
  1373. target_size.height = view_configuration_views[0].recommendedImageRectHeight * render_target_size_multiplier;
  1374. }
  1375. return target_size;
  1376. }
  1377. XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  1378. XrResult result;
  1379. if (!running) {
  1380. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1381. }
  1382. // Get display time
  1383. XrTime display_time = get_predicted_display_time();
  1384. if (display_time == 0) {
  1385. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1386. }
  1387. XrSpaceVelocity velocity = {
  1388. XR_TYPE_SPACE_VELOCITY, // type
  1389. nullptr, // next
  1390. 0, // velocityFlags
  1391. { 0.0, 0.0, 0.0 }, // linearVelocity
  1392. { 0.0, 0.0, 0.0 } // angularVelocity
  1393. };
  1394. XrSpaceLocation location = {
  1395. XR_TYPE_SPACE_LOCATION, // type
  1396. &velocity, // next
  1397. 0, // locationFlags
  1398. {
  1399. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  1400. { 0.0, 0.0, 0.0 } // position
  1401. } // pose
  1402. };
  1403. result = xrLocateSpace(view_space, play_space, display_time, &location);
  1404. if (XR_FAILED(result)) {
  1405. print_line("OpenXR: Failed to locate view space in play space [", get_error_string(result), "]");
  1406. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  1407. }
  1408. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  1409. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  1410. if (head_pose_confidence != confidence) {
  1411. // prevent error spam
  1412. head_pose_confidence = confidence;
  1413. if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  1414. print_line("OpenXR head space location not valid (check tracking?)");
  1415. } else if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_LOW) {
  1416. print_verbose("OpenVR Head pose now tracking with low confidence");
  1417. } else {
  1418. print_verbose("OpenVR Head pose now tracking with high confidence");
  1419. }
  1420. }
  1421. return confidence;
  1422. }
  1423. bool OpenXRAPI::get_view_transform(uint32_t p_view, Transform3D &r_transform) {
  1424. ERR_NOT_ON_RENDER_THREAD_V(false);
  1425. if (!render_state.running) {
  1426. return false;
  1427. }
  1428. // we don't have valid view info
  1429. if (render_state.views == nullptr || !render_state.view_pose_valid) {
  1430. return false;
  1431. }
  1432. // Note, the timing of this is set right before rendering, which is what we need here.
  1433. r_transform = transform_from_pose(render_state.views[p_view].pose);
  1434. return true;
  1435. }
  1436. bool OpenXRAPI::get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, Projection &p_camera_matrix) {
  1437. ERR_NOT_ON_RENDER_THREAD_V(false);
  1438. ERR_FAIL_NULL_V(graphics_extension, false);
  1439. if (!render_state.running) {
  1440. return false;
  1441. }
  1442. // we don't have valid view info
  1443. if (render_state.views == nullptr || !render_state.view_pose_valid) {
  1444. return false;
  1445. }
  1446. // if we're using depth views, make sure we update our near and far there...
  1447. if (render_state.depth_views != nullptr) {
  1448. for (uint32_t i = 0; i < render_state.view_count; i++) {
  1449. // As we are using reverse-Z these need to be flipped.
  1450. render_state.depth_views[i].nearZ = p_z_far;
  1451. render_state.depth_views[i].farZ = p_z_near;
  1452. }
  1453. }
  1454. // now update our projection
  1455. return graphics_extension->create_projection_fov(render_state.views[p_view].fov, p_z_near, p_z_far, p_camera_matrix);
  1456. }
  1457. bool OpenXRAPI::poll_events() {
  1458. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1459. XrEventDataBuffer runtimeEvent;
  1460. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  1461. runtimeEvent.next = nullptr;
  1462. // runtimeEvent.varying = ...
  1463. XrResult pollResult = xrPollEvent(instance, &runtimeEvent);
  1464. while (pollResult == XR_SUCCESS) {
  1465. bool handled = false;
  1466. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1467. handled |= wrapper->on_event_polled(runtimeEvent);
  1468. }
  1469. switch (runtimeEvent.type) {
  1470. case XR_TYPE_EVENT_DATA_EVENTS_LOST: {
  1471. XrEventDataEventsLost *event = (XrEventDataEventsLost *)&runtimeEvent;
  1472. // We probably didn't poll fast enough, just output warning
  1473. WARN_PRINT("OpenXR EVENT: " + itos(event->lostEventCount) + " event data lost!");
  1474. } break;
  1475. case XR_TYPE_EVENT_DATA_VISIBILITY_MASK_CHANGED_KHR: {
  1476. // XrEventDataVisibilityMaskChangedKHR *event = (XrEventDataVisibilityMaskChangedKHR *)&runtimeEvent;
  1477. // TODO implement this in the future, we should call xrGetVisibilityMaskKHR to obtain a mask,
  1478. // this will allow us to prevent rendering the part of our view which is never displayed giving us
  1479. // a decent performance improvement.
  1480. print_verbose("OpenXR EVENT: STUB: visibility mask changed");
  1481. } break;
  1482. case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: {
  1483. XrEventDataInstanceLossPending *event = (XrEventDataInstanceLossPending *)&runtimeEvent;
  1484. // TODO We get this event if we're about to loose our OpenXR instance.
  1485. // We should queue exiting Godot at this point.
  1486. print_verbose(String("OpenXR EVENT: instance loss pending at ") + itos(event->lossTime));
  1487. return false;
  1488. } break;
  1489. case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
  1490. XrEventDataSessionStateChanged *event = (XrEventDataSessionStateChanged *)&runtimeEvent;
  1491. session_state = event->state;
  1492. if (session_state >= XR_SESSION_STATE_MAX_ENUM) {
  1493. print_verbose(String("OpenXR EVENT: session state changed to UNKNOWN - ") + itos(session_state));
  1494. } else {
  1495. print_verbose(String("OpenXR EVENT: session state changed to ") + OpenXRUtil::get_session_state_name(session_state));
  1496. switch (session_state) {
  1497. case XR_SESSION_STATE_IDLE:
  1498. on_state_idle();
  1499. break;
  1500. case XR_SESSION_STATE_READY:
  1501. on_state_ready();
  1502. break;
  1503. case XR_SESSION_STATE_SYNCHRONIZED:
  1504. on_state_synchronized();
  1505. break;
  1506. case XR_SESSION_STATE_VISIBLE:
  1507. on_state_visible();
  1508. break;
  1509. case XR_SESSION_STATE_FOCUSED:
  1510. on_state_focused();
  1511. break;
  1512. case XR_SESSION_STATE_STOPPING:
  1513. on_state_stopping();
  1514. break;
  1515. case XR_SESSION_STATE_LOSS_PENDING:
  1516. on_state_loss_pending();
  1517. break;
  1518. case XR_SESSION_STATE_EXITING:
  1519. on_state_exiting();
  1520. break;
  1521. default:
  1522. break;
  1523. }
  1524. }
  1525. } break;
  1526. case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: {
  1527. XrEventDataReferenceSpaceChangePending *event = (XrEventDataReferenceSpaceChangePending *)&runtimeEvent;
  1528. print_verbose(String("OpenXR EVENT: reference space type ") + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!");
  1529. if (emulating_local_floor) {
  1530. should_reset_emulated_floor_height = true;
  1531. }
  1532. if (event->poseValid && xr_interface) {
  1533. xr_interface->on_pose_recentered();
  1534. }
  1535. } break;
  1536. case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: {
  1537. print_verbose("OpenXR EVENT: interaction profile changed!");
  1538. XrEventDataInteractionProfileChanged *event = (XrEventDataInteractionProfileChanged *)&runtimeEvent;
  1539. List<RID> trackers;
  1540. tracker_owner.get_owned_list(&trackers);
  1541. for (int i = 0; i < trackers.size(); i++) {
  1542. tracker_check_profile(trackers[i], event->session);
  1543. }
  1544. } break;
  1545. default:
  1546. if (!handled) {
  1547. print_verbose(String("OpenXR Unhandled event type ") + OpenXRUtil::get_structure_type_name(runtimeEvent.type));
  1548. }
  1549. break;
  1550. }
  1551. runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
  1552. pollResult = xrPollEvent(instance, &runtimeEvent);
  1553. }
  1554. if (pollResult == XR_EVENT_UNAVAILABLE) {
  1555. // processed all events in the queue
  1556. return true;
  1557. } else {
  1558. ERR_FAIL_V_MSG(false, "OpenXR: Failed to poll events!");
  1559. }
  1560. }
  1561. void OpenXRAPI::_allocate_view_buffers(uint32_t p_view_count, bool p_submit_depth_buffer) {
  1562. // Must be called from rendering thread!
  1563. ERR_NOT_ON_RENDER_THREAD;
  1564. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  1565. ERR_FAIL_NULL(openxr_api);
  1566. openxr_api->render_state.view_count = p_view_count;
  1567. openxr_api->render_state.submit_depth_buffer = p_submit_depth_buffer;
  1568. // Allocate buffers we'll be populating with view information.
  1569. openxr_api->render_state.views = (XrView *)memalloc(sizeof(XrView) * p_view_count);
  1570. ERR_FAIL_NULL_MSG(openxr_api->render_state.views, "OpenXR Couldn't allocate memory for views");
  1571. memset(openxr_api->render_state.views, 0, sizeof(XrView) * p_view_count);
  1572. openxr_api->render_state.projection_views = (XrCompositionLayerProjectionView *)memalloc(sizeof(XrCompositionLayerProjectionView) * p_view_count);
  1573. ERR_FAIL_NULL_MSG(openxr_api->render_state.projection_views, "OpenXR Couldn't allocate memory for projection views");
  1574. memset(openxr_api->render_state.projection_views, 0, sizeof(XrCompositionLayerProjectionView) * p_view_count);
  1575. if (p_submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available()) {
  1576. openxr_api->render_state.depth_views = (XrCompositionLayerDepthInfoKHR *)memalloc(sizeof(XrCompositionLayerDepthInfoKHR) * p_view_count);
  1577. ERR_FAIL_NULL_MSG(openxr_api->render_state.depth_views, "OpenXR Couldn't allocate memory for depth views");
  1578. memset(openxr_api->render_state.depth_views, 0, sizeof(XrCompositionLayerDepthInfoKHR) * p_view_count);
  1579. }
  1580. }
  1581. void OpenXRAPI::_set_render_session_running(bool p_is_running) {
  1582. // Must be called from rendering thread!
  1583. ERR_NOT_ON_RENDER_THREAD;
  1584. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  1585. ERR_FAIL_NULL(openxr_api);
  1586. openxr_api->render_state.running = p_is_running;
  1587. }
  1588. void OpenXRAPI::_set_render_display_info(XrTime p_predicted_display_time, bool p_should_render) {
  1589. // Must be called from rendering thread!
  1590. ERR_NOT_ON_RENDER_THREAD;
  1591. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  1592. ERR_FAIL_NULL(openxr_api);
  1593. openxr_api->render_state.predicted_display_time = p_predicted_display_time;
  1594. openxr_api->render_state.should_render = p_should_render;
  1595. }
  1596. void OpenXRAPI::_set_render_play_space(uint64_t p_play_space) {
  1597. // Must be called from rendering thread!
  1598. ERR_NOT_ON_RENDER_THREAD;
  1599. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  1600. ERR_FAIL_NULL(openxr_api);
  1601. openxr_api->render_state.play_space = XrSpace(p_play_space);
  1602. }
  1603. void OpenXRAPI::_set_render_state_multiplier(double p_render_target_size_multiplier) {
  1604. // Must be called from rendering thread!
  1605. ERR_NOT_ON_RENDER_THREAD;
  1606. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  1607. ERR_FAIL_NULL(openxr_api);
  1608. openxr_api->render_state.render_target_size_multiplier = p_render_target_size_multiplier;
  1609. }
  1610. bool OpenXRAPI::process() {
  1611. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  1612. if (!poll_events()) {
  1613. return false;
  1614. }
  1615. if (!running) {
  1616. return false;
  1617. }
  1618. // We call xrWaitFrame as early as possible, this will allow OpenXR to get
  1619. // proper timing info between this point, and when we're ready to start rendering.
  1620. // As the name suggests, OpenXR can pause the thread to minimize the time between
  1621. // retrieving tracking data and using that tracking data to render.
  1622. // OpenXR thus works best if rendering is performed on a separate thread.
  1623. XrFrameWaitInfo frame_wait_info = { XR_TYPE_FRAME_WAIT_INFO, nullptr };
  1624. frame_state.predictedDisplayTime = 0;
  1625. frame_state.predictedDisplayPeriod = 0;
  1626. frame_state.shouldRender = false;
  1627. XrResult result = xrWaitFrame(session, &frame_wait_info, &frame_state);
  1628. if (XR_FAILED(result)) {
  1629. print_line("OpenXR: xrWaitFrame() was not successful [", get_error_string(result), "]");
  1630. // reset just in case
  1631. frame_state.predictedDisplayTime = 0;
  1632. frame_state.predictedDisplayPeriod = 0;
  1633. frame_state.shouldRender = false;
  1634. set_render_display_info(0, false);
  1635. return false;
  1636. }
  1637. if (frame_state.predictedDisplayPeriod > 500000000) {
  1638. // display period more then 0.5 seconds? must be wrong data
  1639. print_verbose(String("OpenXR resetting invalid display period ") + rtos(frame_state.predictedDisplayPeriod));
  1640. frame_state.predictedDisplayPeriod = 0;
  1641. }
  1642. set_render_display_info(frame_state.predictedDisplayTime, frame_state.shouldRender);
  1643. if (unlikely(play_space_is_dirty)) {
  1644. setup_play_space();
  1645. play_space_is_dirty = false;
  1646. }
  1647. if (unlikely(should_reset_emulated_floor_height)) {
  1648. reset_emulated_floor_height();
  1649. should_reset_emulated_floor_height = false;
  1650. }
  1651. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1652. wrapper->on_process();
  1653. }
  1654. return true;
  1655. }
  1656. void OpenXRAPI::free_main_swapchains() {
  1657. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  1658. render_state.main_swapchains[i].queue_free();
  1659. }
  1660. }
  1661. void OpenXRAPI::pre_render() {
  1662. ERR_FAIL_COND(session == XR_NULL_HANDLE);
  1663. // Must be called from rendering thread!
  1664. ERR_NOT_ON_RENDER_THREAD;
  1665. if (!render_state.running) {
  1666. return;
  1667. }
  1668. // Process any swapchains that were queued to be freed
  1669. OpenXRSwapChainInfo::free_queued();
  1670. Size2i swapchain_size = get_recommended_target_size();
  1671. if (swapchain_size != render_state.main_swapchain_size) {
  1672. // Out with the old.
  1673. free_main_swapchains();
  1674. // In with the new.
  1675. create_main_swapchains(swapchain_size);
  1676. }
  1677. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1678. wrapper->on_pre_render();
  1679. }
  1680. // Get our view info for the frame we're about to render, note from the OpenXR manual:
  1681. // "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"
  1682. // We're calling this "relatively" early, the positioning we're obtaining here will be used to do our frustum culling,
  1683. // occlusion culling, etc. There is however a technique that we can investigate in the future where after our entire
  1684. // Vulkan command buffer is build, but right before vkSubmitQueue is called, we call xrLocateViews one more time and
  1685. // update the view and projection matrix once more with a slightly more accurate predication and then submit the
  1686. // command queues.
  1687. // That is not possible yet but worth investigating in the future.
  1688. XrViewLocateInfo view_locate_info = {
  1689. XR_TYPE_VIEW_LOCATE_INFO, // type
  1690. nullptr, // next
  1691. view_configuration, // viewConfigurationType
  1692. render_state.predicted_display_time, // displayTime
  1693. render_state.play_space // space
  1694. };
  1695. XrViewState view_state = {
  1696. XR_TYPE_VIEW_STATE, // type
  1697. nullptr, // next
  1698. 0 // viewStateFlags
  1699. };
  1700. uint32_t view_count_output;
  1701. XrResult result = xrLocateViews(session, &view_locate_info, &view_state, render_state.view_count, &view_count_output, render_state.views);
  1702. if (XR_FAILED(result)) {
  1703. print_line("OpenXR: Couldn't locate views [", get_error_string(result), "]");
  1704. return;
  1705. }
  1706. bool pose_valid = true;
  1707. for (uint64_t i = 0; i < view_count_output; i++) {
  1708. if ((view_state.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0 ||
  1709. (view_state.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0) {
  1710. pose_valid = false;
  1711. }
  1712. }
  1713. if (render_state.view_pose_valid != pose_valid) {
  1714. render_state.view_pose_valid = pose_valid;
  1715. if (!render_state.view_pose_valid) {
  1716. print_verbose("OpenXR View pose became invalid");
  1717. } else {
  1718. print_verbose("OpenXR View pose became valid");
  1719. }
  1720. }
  1721. // let's start our frame..
  1722. XrFrameBeginInfo frame_begin_info = {
  1723. XR_TYPE_FRAME_BEGIN_INFO, // type
  1724. nullptr // next
  1725. };
  1726. result = xrBeginFrame(session, &frame_begin_info);
  1727. if (XR_FAILED(result)) {
  1728. print_line("OpenXR: failed to being frame [", get_error_string(result), "]");
  1729. return;
  1730. }
  1731. // Reset this, we haven't found a viewport for output yet
  1732. render_state.has_xr_viewport = false;
  1733. }
  1734. bool OpenXRAPI::pre_draw_viewport(RID p_render_target) {
  1735. // Must be called from rendering thread!
  1736. ERR_NOT_ON_RENDER_THREAD_V(false);
  1737. // We found an XR viewport!
  1738. render_state.has_xr_viewport = true;
  1739. if (instance == XR_NULL_HANDLE || session == XR_NULL_HANDLE || !render_state.running || !render_state.view_pose_valid || !render_state.should_render) {
  1740. return false;
  1741. }
  1742. // Acquire our images
  1743. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  1744. if (!render_state.main_swapchains[i].is_image_acquired() && render_state.main_swapchains[i].get_swapchain() != XR_NULL_HANDLE) {
  1745. if (!render_state.main_swapchains[i].acquire(render_state.should_render)) {
  1746. return false;
  1747. }
  1748. }
  1749. }
  1750. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1751. wrapper->on_pre_draw_viewport(p_render_target);
  1752. }
  1753. return true;
  1754. }
  1755. XrSwapchain OpenXRAPI::get_color_swapchain() {
  1756. ERR_NOT_ON_RENDER_THREAD_V(XR_NULL_HANDLE);
  1757. return render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].get_swapchain();
  1758. }
  1759. RID OpenXRAPI::get_color_texture() {
  1760. ERR_NOT_ON_RENDER_THREAD_V(RID());
  1761. return render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].get_image();
  1762. }
  1763. RID OpenXRAPI::get_depth_texture() {
  1764. ERR_NOT_ON_RENDER_THREAD_V(RID());
  1765. // Note, image will not be acquired if we didn't have a suitable swap chain format.
  1766. if (render_state.submit_depth_buffer && render_state.main_swapchains[OPENXR_SWAPCHAIN_DEPTH].is_image_acquired()) {
  1767. return render_state.main_swapchains[OPENXR_SWAPCHAIN_DEPTH].get_image();
  1768. } else {
  1769. return RID();
  1770. }
  1771. }
  1772. void OpenXRAPI::post_draw_viewport(RID p_render_target) {
  1773. // Must be called from rendering thread!
  1774. ERR_NOT_ON_RENDER_THREAD;
  1775. if (instance == XR_NULL_HANDLE || session == XR_NULL_HANDLE || !render_state.running || !render_state.view_pose_valid || !render_state.should_render) {
  1776. return;
  1777. }
  1778. for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
  1779. wrapper->on_post_draw_viewport(p_render_target);
  1780. }
  1781. };
  1782. void OpenXRAPI::end_frame() {
  1783. XrResult result;
  1784. ERR_FAIL_COND(session == XR_NULL_HANDLE);
  1785. // Must be called from rendering thread!
  1786. ERR_NOT_ON_RENDER_THREAD;
  1787. if (!render_state.running) {
  1788. return;
  1789. }
  1790. if (render_state.should_render && render_state.view_pose_valid) {
  1791. if (!render_state.has_xr_viewport) {
  1792. print_line("OpenXR: No viewport was marked with use_xr, there is no rendered output!");
  1793. } else if (!render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].is_image_acquired()) {
  1794. print_line("OpenXR: No swapchain could be acquired to render to!");
  1795. }
  1796. }
  1797. // must have:
  1798. // - should_render set to true
  1799. // - a valid view pose for projection_views[eye].pose to submit layer
  1800. // - an image to render
  1801. if (!render_state.should_render || !render_state.view_pose_valid || !render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].is_image_acquired()) {
  1802. // submit 0 layers when we shouldn't render
  1803. XrFrameEndInfo frame_end_info = {
  1804. XR_TYPE_FRAME_END_INFO, // type
  1805. nullptr, // next
  1806. render_state.predicted_display_time, // displayTime
  1807. environment_blend_mode, // environmentBlendMode
  1808. 0, // layerCount
  1809. nullptr // layers
  1810. };
  1811. result = xrEndFrame(session, &frame_end_info);
  1812. if (XR_FAILED(result)) {
  1813. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1814. return;
  1815. }
  1816. // neither eye is rendered
  1817. return;
  1818. }
  1819. // release our swapchain image if we acquired it
  1820. for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
  1821. if (render_state.main_swapchains[i].is_image_acquired()) {
  1822. render_state.main_swapchains[i].release();
  1823. }
  1824. }
  1825. for (uint32_t eye = 0; eye < render_state.view_count; eye++) {
  1826. render_state.projection_views[eye].fov = render_state.views[eye].fov;
  1827. render_state.projection_views[eye].pose = render_state.views[eye].pose;
  1828. }
  1829. Vector<OrderedCompositionLayer> ordered_layers_list;
  1830. bool projection_layer_is_first = true;
  1831. // Add composition layers from providers
  1832. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  1833. for (int i = 0; i < provider->get_composition_layer_count(); i++) {
  1834. OrderedCompositionLayer layer = {
  1835. provider->get_composition_layer(i),
  1836. provider->get_composition_layer_order(i),
  1837. };
  1838. if (layer.composition_layer) {
  1839. ordered_layers_list.push_back(layer);
  1840. if (layer.sort_order == 0) {
  1841. WARN_PRINT_ONCE_ED("Composition layer returned sort order 0, it may be overwritten by projection layer.");
  1842. } else if (layer.sort_order < 0) {
  1843. projection_layer_is_first = false;
  1844. }
  1845. }
  1846. }
  1847. }
  1848. XrCompositionLayerFlags layer_flags = XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT;
  1849. if (!projection_layer_is_first || environment_blend_mode != XR_ENVIRONMENT_BLEND_MODE_OPAQUE) {
  1850. layer_flags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
  1851. }
  1852. XrCompositionLayerProjection projection_layer = {
  1853. XR_TYPE_COMPOSITION_LAYER_PROJECTION, // type
  1854. nullptr, // next
  1855. layer_flags, // layerFlags
  1856. render_state.play_space, // space
  1857. render_state.view_count, // viewCount
  1858. render_state.projection_views, // views
  1859. };
  1860. ordered_layers_list.push_back({ (const XrCompositionLayerBaseHeader *)&projection_layer, 0 });
  1861. // Sort our layers.
  1862. ordered_layers_list.sort_custom<OrderedCompositionLayer>();
  1863. // Now make a list we can pass on to OpenXR.
  1864. Vector<const XrCompositionLayerBaseHeader *> layers_list;
  1865. for (OrderedCompositionLayer &ordered_layer : ordered_layers_list) {
  1866. layers_list.push_back(ordered_layer.composition_layer);
  1867. }
  1868. XrFrameEndInfo frame_end_info = {
  1869. XR_TYPE_FRAME_END_INFO, // type
  1870. nullptr, // next
  1871. render_state.predicted_display_time, // displayTime
  1872. environment_blend_mode, // environmentBlendMode
  1873. static_cast<uint32_t>(layers_list.size()), // layerCount
  1874. layers_list.ptr() // layers
  1875. };
  1876. result = xrEndFrame(session, &frame_end_info);
  1877. if (XR_FAILED(result)) {
  1878. print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
  1879. return;
  1880. }
  1881. }
  1882. float OpenXRAPI::get_display_refresh_rate() const {
  1883. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1884. if (drrext) {
  1885. return drrext->get_refresh_rate();
  1886. }
  1887. return 0.0;
  1888. }
  1889. void OpenXRAPI::set_display_refresh_rate(float p_refresh_rate) {
  1890. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1891. if (drrext != nullptr) {
  1892. drrext->set_refresh_rate(p_refresh_rate);
  1893. }
  1894. }
  1895. Array OpenXRAPI::get_available_display_refresh_rates() const {
  1896. OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
  1897. if (drrext != nullptr) {
  1898. return drrext->get_available_refresh_rates();
  1899. }
  1900. return Array();
  1901. }
  1902. double OpenXRAPI::get_render_target_size_multiplier() const {
  1903. return render_target_size_multiplier;
  1904. }
  1905. void OpenXRAPI::set_render_target_size_multiplier(double multiplier) {
  1906. render_target_size_multiplier = multiplier;
  1907. set_render_state_multiplier(multiplier);
  1908. }
  1909. bool OpenXRAPI::is_foveation_supported() const {
  1910. OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
  1911. return fov_ext != nullptr && fov_ext->is_enabled();
  1912. }
  1913. int OpenXRAPI::get_foveation_level() const {
  1914. OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
  1915. if (fov_ext != nullptr && fov_ext->is_enabled()) {
  1916. switch (fov_ext->get_foveation_level()) {
  1917. case XR_FOVEATION_LEVEL_NONE_FB:
  1918. return 0;
  1919. case XR_FOVEATION_LEVEL_LOW_FB:
  1920. return 1;
  1921. case XR_FOVEATION_LEVEL_MEDIUM_FB:
  1922. return 2;
  1923. case XR_FOVEATION_LEVEL_HIGH_FB:
  1924. return 3;
  1925. default:
  1926. return 0;
  1927. }
  1928. }
  1929. return 0;
  1930. }
  1931. void OpenXRAPI::set_foveation_level(int p_foveation_level) {
  1932. ERR_FAIL_UNSIGNED_INDEX(p_foveation_level, 4);
  1933. OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
  1934. if (fov_ext != nullptr && fov_ext->is_enabled()) {
  1935. XrFoveationLevelFB levels[] = { XR_FOVEATION_LEVEL_NONE_FB, XR_FOVEATION_LEVEL_LOW_FB, XR_FOVEATION_LEVEL_MEDIUM_FB, XR_FOVEATION_LEVEL_HIGH_FB };
  1936. fov_ext->set_foveation_level(levels[p_foveation_level]);
  1937. }
  1938. }
  1939. bool OpenXRAPI::get_foveation_dynamic() const {
  1940. OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
  1941. if (fov_ext != nullptr && fov_ext->is_enabled()) {
  1942. return fov_ext->get_foveation_dynamic() == XR_FOVEATION_DYNAMIC_LEVEL_ENABLED_FB;
  1943. }
  1944. return false;
  1945. }
  1946. void OpenXRAPI::set_foveation_dynamic(bool p_foveation_dynamic) {
  1947. OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
  1948. if (fov_ext != nullptr && fov_ext->is_enabled()) {
  1949. fov_ext->set_foveation_dynamic(p_foveation_dynamic ? XR_FOVEATION_DYNAMIC_LEVEL_ENABLED_FB : XR_FOVEATION_DYNAMIC_DISABLED_FB);
  1950. }
  1951. }
  1952. Size2 OpenXRAPI::get_play_space_bounds() const {
  1953. Size2 ret;
  1954. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, Size2());
  1955. XrExtent2Df extents;
  1956. XrResult result = xrGetReferenceSpaceBoundsRect(session, reference_space, &extents);
  1957. if (XR_FAILED(result)) {
  1958. print_line("OpenXR: failed to get play space bounds! [", get_error_string(result), "]");
  1959. return ret;
  1960. }
  1961. ret.width = extents.width;
  1962. ret.height = extents.height;
  1963. return ret;
  1964. }
  1965. OpenXRAPI::OpenXRAPI() {
  1966. // OpenXRAPI is only constructed if OpenXR is enabled.
  1967. singleton = this;
  1968. if (Engine::get_singleton()->is_editor_hint()) {
  1969. // Enabled OpenXR in the editor? Adjust our settings for the editor
  1970. } else {
  1971. // Load settings from project settings
  1972. int form_factor_setting = GLOBAL_GET("xr/openxr/form_factor");
  1973. switch (form_factor_setting) {
  1974. case 0: {
  1975. form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
  1976. } break;
  1977. case 1: {
  1978. form_factor = XR_FORM_FACTOR_HANDHELD_DISPLAY;
  1979. } break;
  1980. default:
  1981. break;
  1982. }
  1983. int view_configuration_setting = GLOBAL_GET("xr/openxr/view_configuration");
  1984. switch (view_configuration_setting) {
  1985. case 0: {
  1986. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO;
  1987. } break;
  1988. case 1: {
  1989. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
  1990. } break;
  1991. /* we don't support quad and observer configurations (yet)
  1992. case 2: {
  1993. view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO;
  1994. } break;
  1995. case 3: {
  1996. view_configuration = XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT;
  1997. } break;
  1998. */
  1999. default:
  2000. break;
  2001. }
  2002. int reference_space_setting = GLOBAL_GET("xr/openxr/reference_space");
  2003. switch (reference_space_setting) {
  2004. case 0: {
  2005. requested_reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
  2006. } break;
  2007. case 1: {
  2008. requested_reference_space = XR_REFERENCE_SPACE_TYPE_STAGE;
  2009. } break;
  2010. case 2: {
  2011. requested_reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL_FLOOR_EXT;
  2012. } break;
  2013. default:
  2014. break;
  2015. }
  2016. int environment_blend_mode_setting = GLOBAL_GET("xr/openxr/environment_blend_mode");
  2017. switch (environment_blend_mode_setting) {
  2018. case 0: {
  2019. environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
  2020. } break;
  2021. case 1: {
  2022. environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_ADDITIVE;
  2023. } break;
  2024. case 2: {
  2025. environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND;
  2026. } break;
  2027. default:
  2028. break;
  2029. }
  2030. submit_depth_buffer = GLOBAL_GET("xr/openxr/submit_depth_buffer");
  2031. }
  2032. }
  2033. OpenXRAPI::~OpenXRAPI() {
  2034. // cleanup our composition layer providers
  2035. for (OpenXRCompositionLayerProvider *provider : composition_layer_providers) {
  2036. memdelete(provider);
  2037. }
  2038. composition_layer_providers.clear();
  2039. if (supported_extensions != nullptr) {
  2040. memfree(supported_extensions);
  2041. supported_extensions = nullptr;
  2042. }
  2043. if (layer_properties != nullptr) {
  2044. memfree(layer_properties);
  2045. layer_properties = nullptr;
  2046. }
  2047. #ifdef ANDROID_ENABLED
  2048. if (openxr_loader_library_handle) {
  2049. OS::get_singleton()->close_dynamic_library(openxr_loader_library_handle);
  2050. openxr_loader_library_handle = nullptr;
  2051. }
  2052. #endif
  2053. singleton = nullptr;
  2054. }
  2055. Transform3D OpenXRAPI::transform_from_pose(const XrPosef &p_pose) {
  2056. Quaternion q(p_pose.orientation.x, p_pose.orientation.y, p_pose.orientation.z, p_pose.orientation.w);
  2057. Basis basis(q);
  2058. Vector3 origin(p_pose.position.x, p_pose.position.y, p_pose.position.z);
  2059. return Transform3D(basis, origin);
  2060. }
  2061. template <typename T>
  2062. XRPose::TrackingConfidence _transform_from_location(const T &p_location, Transform3D &r_transform) {
  2063. Basis basis;
  2064. Vector3 origin;
  2065. XRPose::TrackingConfidence confidence = XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2066. const XrPosef &pose = p_location.pose;
  2067. // Check orientation
  2068. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) {
  2069. Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
  2070. r_transform.basis = Basis(q);
  2071. if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) {
  2072. // Fully valid orientation, so either 3DOF or 6DOF tracking with high confidence so default to HIGH_TRACKING
  2073. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  2074. } else {
  2075. // Orientation is being tracked but we're using old/predicted data, so low tracking confidence
  2076. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  2077. }
  2078. } else {
  2079. r_transform.basis = Basis();
  2080. }
  2081. // Check location
  2082. if (p_location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) {
  2083. r_transform.origin = Vector3(pose.position.x, pose.position.y, pose.position.z);
  2084. if (!(p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)) {
  2085. // Location is being tracked but we're using old/predicted data, so low tracking confidence
  2086. confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
  2087. } else if (confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
  2088. // Position tracking without orientation tracking?
  2089. confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
  2090. }
  2091. } else {
  2092. // No tracking or 3DOF I guess..
  2093. r_transform.origin = Vector3();
  2094. }
  2095. return confidence;
  2096. }
  2097. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrSpaceLocation &p_location, Transform3D &r_transform) {
  2098. return _transform_from_location(p_location, r_transform);
  2099. }
  2100. XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform) {
  2101. return _transform_from_location(p_location, r_transform);
  2102. }
  2103. void OpenXRAPI::parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  2104. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT) {
  2105. XrVector3f linear_velocity = p_velocity.linearVelocity;
  2106. r_linear_velocity = Vector3(linear_velocity.x, linear_velocity.y, linear_velocity.z);
  2107. } else {
  2108. r_linear_velocity = Vector3();
  2109. }
  2110. if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT) {
  2111. XrVector3f angular_velocity = p_velocity.angularVelocity;
  2112. r_angular_velocity = Vector3(angular_velocity.x, angular_velocity.y, angular_velocity.z);
  2113. } else {
  2114. r_angular_velocity = Vector3();
  2115. }
  2116. }
  2117. bool OpenXRAPI::xr_result(XrResult result, const char *format, Array args) const {
  2118. if (XR_SUCCEEDED(result))
  2119. return true;
  2120. char resultString[XR_MAX_RESULT_STRING_SIZE];
  2121. xrResultToString(instance, result, resultString);
  2122. print_error(String("OpenXR ") + String(format).format(args) + String(" [") + String(resultString) + String("]"));
  2123. return false;
  2124. }
  2125. RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
  2126. List<RID> current;
  2127. tracker_owner.get_owned_list(&current);
  2128. for (int i = 0; i < current.size(); i++) {
  2129. Tracker *tracker = tracker_owner.get_or_null(current[i]);
  2130. if (tracker && tracker->toplevel_path == p_path) {
  2131. return current[i];
  2132. }
  2133. }
  2134. return RID();
  2135. }
  2136. RID OpenXRAPI::tracker_create(const String p_name) {
  2137. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  2138. Tracker new_tracker;
  2139. new_tracker.name = p_name;
  2140. new_tracker.toplevel_path = XR_NULL_PATH;
  2141. new_tracker.active_profile_rid = RID();
  2142. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_tracker.toplevel_path);
  2143. if (XR_FAILED(result)) {
  2144. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  2145. return RID();
  2146. }
  2147. return tracker_owner.make_rid(new_tracker);
  2148. }
  2149. String OpenXRAPI::tracker_get_name(RID p_tracker) {
  2150. if (p_tracker.is_null()) {
  2151. return String("None");
  2152. }
  2153. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2154. ERR_FAIL_NULL_V(tracker, String());
  2155. return tracker->name;
  2156. }
  2157. void OpenXRAPI::tracker_check_profile(RID p_tracker, XrSession p_session) {
  2158. if (p_session == XR_NULL_HANDLE) {
  2159. p_session = session;
  2160. }
  2161. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2162. ERR_FAIL_NULL(tracker);
  2163. if (tracker->toplevel_path == XR_NULL_PATH) {
  2164. // no path, how was this even created?
  2165. return;
  2166. }
  2167. XrInteractionProfileState profile_state = {
  2168. XR_TYPE_INTERACTION_PROFILE_STATE, // type
  2169. nullptr, // next
  2170. XR_NULL_PATH // interactionProfile
  2171. };
  2172. XrResult result = xrGetCurrentInteractionProfile(p_session, tracker->toplevel_path, &profile_state);
  2173. if (XR_FAILED(result)) {
  2174. print_line("OpenXR: Failed to get interaction profile for", itos(tracker->toplevel_path), "[", get_error_string(result), "]");
  2175. return;
  2176. }
  2177. XrPath new_profile = profile_state.interactionProfile;
  2178. XrPath was_profile = get_interaction_profile_path(tracker->active_profile_rid);
  2179. if (was_profile != new_profile) {
  2180. tracker->active_profile_rid = get_interaction_profile_rid(new_profile);
  2181. if (xr_interface) {
  2182. xr_interface->tracker_profile_changed(p_tracker, tracker->active_profile_rid);
  2183. }
  2184. }
  2185. }
  2186. void OpenXRAPI::tracker_free(RID p_tracker) {
  2187. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2188. ERR_FAIL_NULL(tracker);
  2189. // there is nothing to free here
  2190. tracker_owner.free(p_tracker);
  2191. }
  2192. RID OpenXRAPI::action_set_create(const String p_name, const String p_localized_name, const int p_priority) {
  2193. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  2194. ActionSet action_set;
  2195. action_set.name = p_name;
  2196. action_set.is_attached = false;
  2197. // create our action set...
  2198. XrActionSetCreateInfo action_set_info = {
  2199. XR_TYPE_ACTION_SET_CREATE_INFO, // type
  2200. nullptr, // next
  2201. "", // actionSetName
  2202. "", // localizedActionSetName
  2203. uint32_t(p_priority) // priority
  2204. };
  2205. copy_string_to_char_buffer(p_name, action_set_info.actionSetName, XR_MAX_ACTION_SET_NAME_SIZE);
  2206. copy_string_to_char_buffer(p_localized_name, action_set_info.localizedActionSetName, XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE);
  2207. XrResult result = xrCreateActionSet(instance, &action_set_info, &action_set.handle);
  2208. if (XR_FAILED(result)) {
  2209. print_line("OpenXR: failed to create action set ", p_name, "! [", get_error_string(result), "]");
  2210. return RID();
  2211. }
  2212. return action_set_owner.make_rid(action_set);
  2213. }
  2214. String OpenXRAPI::action_set_get_name(RID p_action_set) {
  2215. if (p_action_set.is_null()) {
  2216. return String("None");
  2217. }
  2218. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  2219. ERR_FAIL_NULL_V(action_set, String());
  2220. return action_set->name;
  2221. }
  2222. bool OpenXRAPI::attach_action_sets(const Vector<RID> &p_action_sets) {
  2223. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2224. Vector<XrActionSet> action_handles;
  2225. action_handles.resize(p_action_sets.size());
  2226. for (int i = 0; i < p_action_sets.size(); i++) {
  2227. ActionSet *action_set = action_set_owner.get_or_null(p_action_sets[i]);
  2228. ERR_FAIL_NULL_V(action_set, false);
  2229. if (action_set->is_attached) {
  2230. return false;
  2231. }
  2232. action_handles.set(i, action_set->handle);
  2233. }
  2234. // So according to the docs, once we attach our action set to our session it becomes read only..
  2235. // https://www.khronos.org/registry/OpenXR/specs/1.0/man/html/xrAttachSessionActionSets.html
  2236. XrSessionActionSetsAttachInfo attach_info = {
  2237. XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, // type
  2238. nullptr, // next
  2239. (uint32_t)p_action_sets.size(), // countActionSets,
  2240. action_handles.ptr() // actionSets
  2241. };
  2242. XrResult result = xrAttachSessionActionSets(session, &attach_info);
  2243. if (XR_FAILED(result)) {
  2244. print_line("OpenXR: failed to attach action sets! [", get_error_string(result), "]");
  2245. return false;
  2246. }
  2247. for (int i = 0; i < p_action_sets.size(); i++) {
  2248. ActionSet *action_set = action_set_owner.get_or_null(p_action_sets[i]);
  2249. ERR_FAIL_NULL_V(action_set, false);
  2250. action_set->is_attached = true;
  2251. }
  2252. /* For debugging:
  2253. print_verbose("Attached set " + action_set->name);
  2254. List<RID> action_rids;
  2255. action_owner.get_owned_list(&action_rids);
  2256. for (int i = 0; i < action_rids.size(); i++) {
  2257. Action * action = action_owner.get_or_null(action_rids[i]);
  2258. if (action && action->action_set_rid == p_action_set) {
  2259. print_verbose(" - Action " + action->name + ": " + OpenXRUtil::get_action_type_name(action->action_type));
  2260. for (int j = 0; j < action->trackers.size(); j++) {
  2261. Tracker * tracker = tracker_owner.get_or_null(action->trackers[j].tracker_rid);
  2262. if (tracker) {
  2263. print_verbose(" - " + tracker->name);
  2264. }
  2265. }
  2266. }
  2267. }
  2268. */
  2269. return true;
  2270. }
  2271. void OpenXRAPI::action_set_free(RID p_action_set) {
  2272. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  2273. ERR_FAIL_NULL(action_set);
  2274. if (action_set->handle != XR_NULL_HANDLE) {
  2275. xrDestroyActionSet(action_set->handle);
  2276. }
  2277. action_set_owner.free(p_action_set);
  2278. }
  2279. RID OpenXRAPI::get_action_rid(XrAction p_action) {
  2280. List<RID> current;
  2281. action_owner.get_owned_list(&current);
  2282. for (int i = 0; i < current.size(); i++) {
  2283. Action *action = action_owner.get_or_null(current[i]);
  2284. if (action && action->handle == p_action) {
  2285. return current[i];
  2286. }
  2287. }
  2288. return RID();
  2289. }
  2290. 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) {
  2291. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
  2292. Action action;
  2293. action.name = p_name;
  2294. ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
  2295. ERR_FAIL_NULL_V(action_set, RID());
  2296. ERR_FAIL_COND_V(action_set->handle == XR_NULL_HANDLE, RID());
  2297. action.action_set_rid = p_action_set;
  2298. switch (p_action_type) {
  2299. case OpenXRAction::OPENXR_ACTION_BOOL:
  2300. action.action_type = XR_ACTION_TYPE_BOOLEAN_INPUT;
  2301. break;
  2302. case OpenXRAction::OPENXR_ACTION_FLOAT:
  2303. action.action_type = XR_ACTION_TYPE_FLOAT_INPUT;
  2304. break;
  2305. case OpenXRAction::OPENXR_ACTION_VECTOR2:
  2306. action.action_type = XR_ACTION_TYPE_VECTOR2F_INPUT;
  2307. break;
  2308. case OpenXRAction::OPENXR_ACTION_POSE:
  2309. action.action_type = XR_ACTION_TYPE_POSE_INPUT;
  2310. break;
  2311. case OpenXRAction::OPENXR_ACTION_HAPTIC:
  2312. action.action_type = XR_ACTION_TYPE_VIBRATION_OUTPUT;
  2313. break;
  2314. default:
  2315. ERR_FAIL_V(RID());
  2316. break;
  2317. }
  2318. Vector<XrPath> toplevel_paths;
  2319. for (int i = 0; i < p_trackers.size(); i++) {
  2320. Tracker *tracker = tracker_owner.get_or_null(p_trackers[i]);
  2321. if (tracker != nullptr && tracker->toplevel_path != XR_NULL_PATH) {
  2322. ActionTracker action_tracker = {
  2323. p_trackers[i], // tracker
  2324. XR_NULL_HANDLE, // space
  2325. false // was_location_valid
  2326. };
  2327. action.trackers.push_back(action_tracker);
  2328. toplevel_paths.push_back(tracker->toplevel_path);
  2329. }
  2330. }
  2331. XrActionCreateInfo action_info = {
  2332. XR_TYPE_ACTION_CREATE_INFO, // type
  2333. nullptr, // next
  2334. "", // actionName
  2335. action.action_type, // actionType
  2336. uint32_t(toplevel_paths.size()), // countSubactionPaths
  2337. toplevel_paths.ptr(), // subactionPaths
  2338. "" // localizedActionName
  2339. };
  2340. copy_string_to_char_buffer(p_name, action_info.actionName, XR_MAX_ACTION_NAME_SIZE);
  2341. copy_string_to_char_buffer(p_localized_name, action_info.localizedActionName, XR_MAX_LOCALIZED_ACTION_NAME_SIZE);
  2342. XrResult result = xrCreateAction(action_set->handle, &action_info, &action.handle);
  2343. if (XR_FAILED(result)) {
  2344. print_line("OpenXR: failed to create action ", p_name, "! [", get_error_string(result), "]");
  2345. return RID();
  2346. }
  2347. return action_owner.make_rid(action);
  2348. }
  2349. String OpenXRAPI::action_get_name(RID p_action) {
  2350. if (p_action.is_null()) {
  2351. return String("None");
  2352. }
  2353. Action *action = action_owner.get_or_null(p_action);
  2354. ERR_FAIL_NULL_V(action, String());
  2355. return action->name;
  2356. }
  2357. void OpenXRAPI::action_free(RID p_action) {
  2358. Action *action = action_owner.get_or_null(p_action);
  2359. ERR_FAIL_NULL(action);
  2360. if (action->handle != XR_NULL_HANDLE) {
  2361. xrDestroyAction(action->handle);
  2362. }
  2363. action_owner.free(p_action);
  2364. }
  2365. RID OpenXRAPI::get_interaction_profile_rid(XrPath p_path) {
  2366. List<RID> current;
  2367. interaction_profile_owner.get_owned_list(&current);
  2368. for (int i = 0; i < current.size(); i++) {
  2369. InteractionProfile *ip = interaction_profile_owner.get_or_null(current[i]);
  2370. if (ip && ip->path == p_path) {
  2371. return current[i];
  2372. }
  2373. }
  2374. return RID();
  2375. }
  2376. XrPath OpenXRAPI::get_interaction_profile_path(RID p_interaction_profile) {
  2377. if (p_interaction_profile.is_null()) {
  2378. return XR_NULL_PATH;
  2379. }
  2380. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2381. ERR_FAIL_NULL_V(ip, XR_NULL_PATH);
  2382. return ip->path;
  2383. }
  2384. RID OpenXRAPI::interaction_profile_create(const String p_name) {
  2385. if (!is_interaction_profile_supported(p_name)) {
  2386. // The extension enabling this path must not be active, we will silently skip this interaction profile
  2387. return RID();
  2388. }
  2389. InteractionProfile new_interaction_profile;
  2390. XrResult result = xrStringToPath(instance, p_name.utf8().get_data(), &new_interaction_profile.path);
  2391. if (XR_FAILED(result)) {
  2392. print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
  2393. return RID();
  2394. }
  2395. RID existing_ip = get_interaction_profile_rid(new_interaction_profile.path);
  2396. if (existing_ip.is_valid()) {
  2397. return existing_ip;
  2398. }
  2399. new_interaction_profile.name = p_name;
  2400. return interaction_profile_owner.make_rid(new_interaction_profile);
  2401. }
  2402. String OpenXRAPI::interaction_profile_get_name(RID p_interaction_profile) {
  2403. if (p_interaction_profile.is_null()) {
  2404. return String("None");
  2405. }
  2406. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2407. ERR_FAIL_NULL_V(ip, String());
  2408. return ip->name;
  2409. }
  2410. void OpenXRAPI::interaction_profile_clear_bindings(RID p_interaction_profile) {
  2411. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2412. ERR_FAIL_NULL(ip);
  2413. ip->bindings.clear();
  2414. }
  2415. bool OpenXRAPI::interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String p_path) {
  2416. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2417. ERR_FAIL_NULL_V(ip, false);
  2418. if (!interaction_profile_supports_io_path(ip->name, p_path)) {
  2419. return false;
  2420. }
  2421. XrActionSuggestedBinding binding;
  2422. Action *action = action_owner.get_or_null(p_action);
  2423. ERR_FAIL_COND_V(action == nullptr || action->handle == XR_NULL_HANDLE, false);
  2424. binding.action = action->handle;
  2425. XrResult result = xrStringToPath(instance, p_path.utf8().get_data(), &binding.binding);
  2426. if (XR_FAILED(result)) {
  2427. print_line("OpenXR: failed to get path for ", p_path, "! [", get_error_string(result), "]");
  2428. return false;
  2429. }
  2430. ip->bindings.push_back(binding);
  2431. return true;
  2432. }
  2433. bool OpenXRAPI::interaction_profile_suggest_bindings(RID p_interaction_profile) {
  2434. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  2435. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2436. ERR_FAIL_NULL_V(ip, false);
  2437. const XrInteractionProfileSuggestedBinding suggested_bindings = {
  2438. XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, // type
  2439. nullptr, // next
  2440. ip->path, // interactionProfile
  2441. uint32_t(ip->bindings.size()), // countSuggestedBindings
  2442. ip->bindings.ptr() // suggestedBindings
  2443. };
  2444. XrResult result = xrSuggestInteractionProfileBindings(instance, &suggested_bindings);
  2445. if (result == XR_ERROR_PATH_UNSUPPORTED) {
  2446. // this is fine, not all runtimes support all devices.
  2447. print_verbose("OpenXR Interaction profile " + ip->name + " is not supported on this runtime");
  2448. } else if (XR_FAILED(result)) {
  2449. print_line("OpenXR: failed to suggest bindings for ", ip->name, "! [", get_error_string(result), "]");
  2450. // reporting is enough...
  2451. }
  2452. /* For debugging:
  2453. print_verbose("Suggested bindings for " + ip->name);
  2454. for (int i = 0; i < ip->bindings.size(); i++) {
  2455. uint32_t strlen;
  2456. char path[XR_MAX_PATH_LENGTH];
  2457. String action_name = action_get_name(get_action_rid(ip->bindings[i].action));
  2458. XrResult result = xrPathToString(instance, ip->bindings[i].binding, XR_MAX_PATH_LENGTH, &strlen, path);
  2459. if (XR_FAILED(result)) {
  2460. print_line("OpenXR: failed to retrieve bindings for ", action_name, "! [", get_error_string(result), "]");
  2461. }
  2462. print_verbose(" - " + action_name + " => " + String(path));
  2463. }
  2464. */
  2465. return true;
  2466. }
  2467. void OpenXRAPI::interaction_profile_free(RID p_interaction_profile) {
  2468. InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
  2469. ERR_FAIL_NULL(ip);
  2470. ip->bindings.clear();
  2471. interaction_profile_owner.free(p_interaction_profile);
  2472. }
  2473. bool OpenXRAPI::sync_action_sets(const Vector<RID> p_active_sets) {
  2474. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2475. if (!running) {
  2476. return false;
  2477. }
  2478. Vector<XrActiveActionSet> active_sets;
  2479. for (int i = 0; i < p_active_sets.size(); i++) {
  2480. ActionSet *action_set = action_set_owner.get_or_null(p_active_sets[i]);
  2481. if (action_set && action_set->handle != XR_NULL_HANDLE) {
  2482. XrActiveActionSet aset;
  2483. aset.actionSet = action_set->handle;
  2484. aset.subactionPath = XR_NULL_PATH;
  2485. active_sets.push_back(aset);
  2486. }
  2487. }
  2488. ERR_FAIL_COND_V(active_sets.is_empty(), false);
  2489. XrActionsSyncInfo sync_info = {
  2490. XR_TYPE_ACTIONS_SYNC_INFO, // type
  2491. nullptr, // next
  2492. uint32_t(active_sets.size()), // countActiveActionSets
  2493. active_sets.ptr() // activeActionSets
  2494. };
  2495. XrResult result = xrSyncActions(session, &sync_info);
  2496. if (XR_FAILED(result)) {
  2497. print_line("OpenXR: failed to sync active action sets! [", get_error_string(result), "]");
  2498. return false;
  2499. }
  2500. return true;
  2501. }
  2502. bool OpenXRAPI::get_action_bool(RID p_action, RID p_tracker) {
  2503. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2504. Action *action = action_owner.get_or_null(p_action);
  2505. ERR_FAIL_NULL_V(action, false);
  2506. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2507. ERR_FAIL_NULL_V(tracker, false);
  2508. if (!running) {
  2509. return false;
  2510. }
  2511. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_BOOLEAN_INPUT, false);
  2512. XrActionStateGetInfo get_info = {
  2513. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2514. nullptr, // next
  2515. action->handle, // action
  2516. tracker->toplevel_path // subactionPath
  2517. };
  2518. XrActionStateBoolean result_state;
  2519. result_state.type = XR_TYPE_ACTION_STATE_BOOLEAN,
  2520. result_state.next = nullptr;
  2521. XrResult result = xrGetActionStateBoolean(session, &get_info, &result_state);
  2522. if (XR_FAILED(result)) {
  2523. print_line("OpenXR: couldn't get action boolean! [", get_error_string(result), "]");
  2524. return false;
  2525. }
  2526. return result_state.isActive && result_state.currentState;
  2527. }
  2528. float OpenXRAPI::get_action_float(RID p_action, RID p_tracker) {
  2529. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, 0.0);
  2530. Action *action = action_owner.get_or_null(p_action);
  2531. ERR_FAIL_NULL_V(action, 0.0);
  2532. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2533. ERR_FAIL_NULL_V(tracker, 0.0);
  2534. if (!running) {
  2535. return 0.0;
  2536. }
  2537. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_FLOAT_INPUT, 0.0);
  2538. XrActionStateGetInfo get_info = {
  2539. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2540. nullptr, // next
  2541. action->handle, // action
  2542. tracker->toplevel_path // subactionPath
  2543. };
  2544. XrActionStateFloat result_state;
  2545. result_state.type = XR_TYPE_ACTION_STATE_FLOAT,
  2546. result_state.next = nullptr;
  2547. XrResult result = xrGetActionStateFloat(session, &get_info, &result_state);
  2548. if (XR_FAILED(result)) {
  2549. print_line("OpenXR: couldn't get action float! [", get_error_string(result), "]");
  2550. return 0.0;
  2551. }
  2552. return result_state.isActive ? result_state.currentState : 0.0;
  2553. }
  2554. Vector2 OpenXRAPI::get_action_vector2(RID p_action, RID p_tracker) {
  2555. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, Vector2());
  2556. Action *action = action_owner.get_or_null(p_action);
  2557. ERR_FAIL_NULL_V(action, Vector2());
  2558. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2559. ERR_FAIL_NULL_V(tracker, Vector2());
  2560. if (!running) {
  2561. return Vector2();
  2562. }
  2563. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VECTOR2F_INPUT, Vector2());
  2564. XrActionStateGetInfo get_info = {
  2565. XR_TYPE_ACTION_STATE_GET_INFO, // type
  2566. nullptr, // next
  2567. action->handle, // action
  2568. tracker->toplevel_path // subactionPath
  2569. };
  2570. XrActionStateVector2f result_state;
  2571. result_state.type = XR_TYPE_ACTION_STATE_VECTOR2F,
  2572. result_state.next = nullptr;
  2573. XrResult result = xrGetActionStateVector2f(session, &get_info, &result_state);
  2574. if (XR_FAILED(result)) {
  2575. print_line("OpenXR: couldn't get action vector2! [", get_error_string(result), "]");
  2576. return Vector2();
  2577. }
  2578. return result_state.isActive ? Vector2(result_state.currentState.x, result_state.currentState.y) : Vector2();
  2579. }
  2580. XRPose::TrackingConfidence OpenXRAPI::get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
  2581. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2582. Action *action = action_owner.get_or_null(p_action);
  2583. ERR_FAIL_NULL_V(action, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2584. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2585. ERR_FAIL_NULL_V(tracker, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2586. if (!running) {
  2587. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2588. }
  2589. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_POSE_INPUT, XRPose::XR_TRACKING_CONFIDENCE_NONE);
  2590. // print_verbose("Checking " + action->name + " => " + tracker->name + " (" + itos(tracker->toplevel_path) + ")");
  2591. uint64_t index = 0xFFFFFFFF;
  2592. uint64_t size = uint64_t(action->trackers.size());
  2593. for (uint64_t i = 0; i < size && index == 0xFFFFFFFF; i++) {
  2594. if (action->trackers[i].tracker_rid == p_tracker) {
  2595. index = i;
  2596. }
  2597. }
  2598. if (index == 0xFFFFFFFF) {
  2599. // couldn't find it?
  2600. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2601. }
  2602. XrTime display_time = get_predicted_display_time();
  2603. if (display_time == 0) {
  2604. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2605. }
  2606. if (action->trackers[index].space == XR_NULL_HANDLE) {
  2607. // if this is a pose we need to define spaces
  2608. XrActionSpaceCreateInfo action_space_info = {
  2609. XR_TYPE_ACTION_SPACE_CREATE_INFO, // type
  2610. nullptr, // next
  2611. action->handle, // action
  2612. tracker->toplevel_path, // subactionPath
  2613. {
  2614. { 0.0, 0.0, 0.0, 1.0 }, // orientation
  2615. { 0.0, 0.0, 0.0 } // position
  2616. } // poseInActionSpace
  2617. };
  2618. XrSpace space;
  2619. XrResult result = xrCreateActionSpace(session, &action_space_info, &space);
  2620. if (XR_FAILED(result)) {
  2621. print_line("OpenXR: couldn't create action space! [", get_error_string(result), "]");
  2622. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2623. }
  2624. action->trackers.ptrw()[index].space = space;
  2625. }
  2626. XrSpaceVelocity velocity = {
  2627. XR_TYPE_SPACE_VELOCITY, // type
  2628. nullptr, // next
  2629. 0, // velocityFlags
  2630. { 0.0, 0.0, 0.0 }, // linearVelocity
  2631. { 0.0, 0.0, 0.0 } // angularVelocity
  2632. };
  2633. XrSpaceLocation location = {
  2634. XR_TYPE_SPACE_LOCATION, // type
  2635. &velocity, // next
  2636. 0, // locationFlags
  2637. {
  2638. { 0.0, 0.0, 0.0, 0.0 }, // orientation
  2639. { 0.0, 0.0, 0.0 } // position
  2640. } // pose
  2641. };
  2642. XrResult result = xrLocateSpace(action->trackers[index].space, play_space, display_time, &location);
  2643. if (XR_FAILED(result)) {
  2644. print_line("OpenXR: failed to locate space! [", get_error_string(result), "]");
  2645. return XRPose::XR_TRACKING_CONFIDENCE_NONE;
  2646. }
  2647. XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
  2648. parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
  2649. return confidence;
  2650. }
  2651. bool OpenXRAPI::trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns) {
  2652. ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
  2653. Action *action = action_owner.get_or_null(p_action);
  2654. ERR_FAIL_NULL_V(action, false);
  2655. Tracker *tracker = tracker_owner.get_or_null(p_tracker);
  2656. ERR_FAIL_NULL_V(tracker, false);
  2657. if (!running) {
  2658. return false;
  2659. }
  2660. ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT, false);
  2661. XrHapticActionInfo action_info = {
  2662. XR_TYPE_HAPTIC_ACTION_INFO, // type
  2663. nullptr, // next
  2664. action->handle, // action
  2665. tracker->toplevel_path // subactionPath
  2666. };
  2667. XrHapticVibration vibration = {
  2668. XR_TYPE_HAPTIC_VIBRATION, // type
  2669. nullptr, // next
  2670. p_duration_ns, // duration
  2671. p_frequency, // frequency
  2672. p_amplitude, // amplitude
  2673. };
  2674. XrResult result = xrApplyHapticFeedback(session, &action_info, (const XrHapticBaseHeader *)&vibration);
  2675. if (XR_FAILED(result)) {
  2676. print_line("OpenXR: failed to apply haptic feedback! [", get_error_string(result), "]");
  2677. return false;
  2678. }
  2679. return true;
  2680. }
  2681. void OpenXRAPI::register_composition_layer_provider(OpenXRCompositionLayerProvider *provider) {
  2682. composition_layer_providers.append(provider);
  2683. }
  2684. void OpenXRAPI::unregister_composition_layer_provider(OpenXRCompositionLayerProvider *provider) {
  2685. composition_layer_providers.erase(provider);
  2686. }
  2687. const XrEnvironmentBlendMode *OpenXRAPI::get_supported_environment_blend_modes(uint32_t &count) {
  2688. count = num_supported_environment_blend_modes;
  2689. return supported_environment_blend_modes;
  2690. }
  2691. bool OpenXRAPI::is_environment_blend_mode_supported(XrEnvironmentBlendMode p_blend_mode) const {
  2692. ERR_FAIL_NULL_V(supported_environment_blend_modes, false);
  2693. for (uint32_t i = 0; i < num_supported_environment_blend_modes; i++) {
  2694. if (supported_environment_blend_modes[i] == p_blend_mode) {
  2695. return true;
  2696. }
  2697. }
  2698. return false;
  2699. }
  2700. bool OpenXRAPI::set_environment_blend_mode(XrEnvironmentBlendMode p_blend_mode) {
  2701. if (emulate_environment_blend_mode_alpha_blend && p_blend_mode == XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND) {
  2702. requested_environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND;
  2703. environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
  2704. return true;
  2705. }
  2706. // We allow setting this when not initialized and will check if it is supported when initializing.
  2707. // After OpenXR is initialized we verify we're setting a supported blend mode.
  2708. else if (!is_initialized() || is_environment_blend_mode_supported(p_blend_mode)) {
  2709. requested_environment_blend_mode = p_blend_mode;
  2710. environment_blend_mode = p_blend_mode;
  2711. return true;
  2712. }
  2713. return false;
  2714. }
  2715. void OpenXRAPI::set_emulate_environment_blend_mode_alpha_blend(bool p_enabled) {
  2716. emulate_environment_blend_mode_alpha_blend = p_enabled;
  2717. }
  2718. OpenXRAPI::OpenXRAlphaBlendModeSupport OpenXRAPI::is_environment_blend_mode_alpha_blend_supported() {
  2719. if (is_environment_blend_mode_supported(XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND)) {
  2720. return OPENXR_ALPHA_BLEND_MODE_SUPPORT_REAL;
  2721. } else if (emulate_environment_blend_mode_alpha_blend) {
  2722. return OPENXR_ALPHA_BLEND_MODE_SUPPORT_EMULATING;
  2723. }
  2724. return OPENXR_ALPHA_BLEND_MODE_SUPPORT_NONE;
  2725. }