openxr_api.cpp 117 KB

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