openxr_api.h 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. /**************************************************************************/
  2. /* openxr_api.h */
  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. #pragma once
  31. #include "action_map/openxr_action.h"
  32. #include "extensions/openxr_extension_wrapper.h"
  33. #include "util.h"
  34. #include "core/error/error_macros.h"
  35. #include "core/math/projection.h"
  36. #include "core/math/transform_3d.h"
  37. #include "core/math/vector2.h"
  38. #include "core/string/ustring.h"
  39. #include "core/templates/rid_owner.h"
  40. #include "core/templates/vector.h"
  41. #include "servers/rendering/rendering_server.h"
  42. #include "servers/xr/xr_pose.h"
  43. #include <openxr/openxr.h>
  44. // Name we add to our extensions if OpenXR 1.1 context is available.
  45. #define XR_OPENXR_1_1_NAME "OPENXR_1_1"
  46. #define XR_API_VERSION_1_1_0 XR_MAKE_VERSION(1, 1, 0)
  47. // forward declarations, we don't want to include these fully
  48. class OpenXRInterface;
  49. class OpenXRAPI {
  50. public:
  51. class OpenXRSwapChainInfo {
  52. private:
  53. XrSwapchain swapchain = XR_NULL_HANDLE;
  54. void *swapchain_graphics_data = nullptr;
  55. uint32_t image_index = 0;
  56. bool image_acquired = false;
  57. bool skip_acquire_swapchain = false;
  58. static Vector<OpenXRSwapChainInfo> free_queue;
  59. public:
  60. _FORCE_INLINE_ XrSwapchain get_swapchain() const { return swapchain; }
  61. _FORCE_INLINE_ bool is_image_acquired() const { return image_acquired; }
  62. bool 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);
  63. void queue_free();
  64. static void free_queued();
  65. void free();
  66. bool acquire(bool &p_should_render);
  67. bool release();
  68. RID get_image();
  69. RID get_density_map();
  70. };
  71. private:
  72. // our singleton
  73. static OpenXRAPI *singleton;
  74. // Registered extension wrappers
  75. static Vector<OpenXRExtensionWrapper *> registered_extension_wrappers;
  76. // linked XR interface
  77. OpenXRInterface *xr_interface = nullptr;
  78. // layers
  79. LocalVector<XrApiLayerProperties> layer_properties;
  80. // extensions
  81. LocalVector<XrExtensionProperties> supported_extensions;
  82. LocalVector<CharString> enabled_extensions;
  83. // composition layer providers
  84. Vector<OpenXRExtensionWrapper *> composition_layer_providers;
  85. // projection views extensions
  86. Vector<OpenXRExtensionWrapper *> projection_views_extensions;
  87. // frame info extensions
  88. Vector<OpenXRExtensionWrapper *> frame_info_extensions;
  89. // view configuration
  90. LocalVector<XrViewConfigurationType> supported_view_configuration_types;
  91. // reference spaces
  92. LocalVector<XrReferenceSpaceType> supported_reference_spaces;
  93. // swapchains (note these are platform dependent)
  94. PackedInt64Array supported_swapchain_formats;
  95. // system info
  96. XrVersion openxr_version;
  97. String runtime_name;
  98. String runtime_version;
  99. // configuration
  100. XrFormFactor form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
  101. XrViewConfigurationType view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
  102. XrReferenceSpaceType requested_reference_space = XR_REFERENCE_SPACE_TYPE_STAGE;
  103. XrReferenceSpaceType reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
  104. bool submit_depth_buffer = false; // if set to true we submit depth buffers to OpenXR if a suitable extension is enabled.
  105. // blend mode
  106. XrEnvironmentBlendMode environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
  107. XrEnvironmentBlendMode requested_environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
  108. Vector<XrEnvironmentBlendMode> supported_environment_blend_modes;
  109. bool emulate_environment_blend_mode_alpha_blend = false;
  110. // state
  111. XrInstance instance = XR_NULL_HANDLE;
  112. XrSystemId system_id = 0;
  113. String system_name;
  114. uint32_t vendor_id = 0;
  115. XrSystemTrackingProperties tracking_properties;
  116. XrSession session = XR_NULL_HANDLE;
  117. XrSessionState session_state = XR_SESSION_STATE_UNKNOWN;
  118. bool running = false;
  119. XrFrameState frame_state = { XR_TYPE_FRAME_STATE, nullptr, 0, 0, false };
  120. double render_target_size_multiplier = 1.0;
  121. Rect2i render_region;
  122. OpenXRGraphicsExtensionWrapper *graphics_extension = nullptr;
  123. XrSystemGraphicsProperties graphics_properties;
  124. LocalVector<XrViewConfigurationView> view_configuration_views;
  125. enum OpenXRSwapChainTypes {
  126. OPENXR_SWAPCHAIN_COLOR,
  127. OPENXR_SWAPCHAIN_DEPTH,
  128. OPENXR_SWAPCHAIN_MAX
  129. };
  130. int64_t color_swapchain_format = 0;
  131. int64_t depth_swapchain_format = 0;
  132. bool play_space_is_dirty = true;
  133. XrSpace play_space = XR_NULL_HANDLE;
  134. XrSpace custom_play_space = XR_NULL_HANDLE;
  135. XrSpace view_space = XR_NULL_HANDLE;
  136. XRPose::TrackingConfidence head_pose_confidence = XRPose::XR_TRACKING_CONFIDENCE_NONE;
  137. RID velocity_texture;
  138. RID velocity_depth_texture;
  139. Size2i velocity_target_size;
  140. // When LOCAL_FLOOR isn't supported, we use an approach based on the example code in the
  141. // OpenXR spec in order to emulate it.
  142. // See: https://registry.khronos.org/OpenXR/specs/1.0/html/xrspec.html#XR_EXT_local_floor
  143. struct LocalFloorEmulation {
  144. bool enabled = false;
  145. XrSpace local_space = XR_NULL_HANDLE;
  146. XrSpace stage_space = XR_NULL_HANDLE;
  147. bool should_reset_floor_height = false;
  148. } local_floor_emulation;
  149. bool reset_emulated_floor_height();
  150. bool load_layer_properties();
  151. bool load_supported_extensions();
  152. bool is_extension_supported(const String &p_extension) const;
  153. bool is_any_extension_enabled(const String &p_extensions) const;
  154. struct RequestExtension {
  155. String name;
  156. bool *enabled;
  157. };
  158. XrResult attempt_create_instance(XrVersion p_version);
  159. bool openxr_loader_init();
  160. bool resolve_instance_openxr_symbols();
  161. #ifdef ANDROID_ENABLED
  162. // On Android we keep tracker of our external OpenXR loader
  163. void *openxr_loader_library_handle = nullptr;
  164. #endif
  165. // function pointers
  166. #ifdef ANDROID_ENABLED
  167. // On non-Android platforms we use the OpenXR symbol linked into the engine binary.
  168. PFN_xrGetInstanceProcAddr xrGetInstanceProcAddr = nullptr;
  169. #endif
  170. EXT_PROTO_XRRESULT_FUNC3(xrAcquireSwapchainImage, (XrSwapchain), swapchain, (const XrSwapchainImageAcquireInfo *), acquireInfo, (uint32_t *), index)
  171. EXT_PROTO_XRRESULT_FUNC3(xrApplyHapticFeedback, (XrSession), session, (const XrHapticActionInfo *), hapticActionInfo, (const XrHapticBaseHeader *), hapticFeedback)
  172. EXT_PROTO_XRRESULT_FUNC2(xrAttachSessionActionSets, (XrSession), session, (const XrSessionActionSetsAttachInfo *), attachInfo)
  173. EXT_PROTO_XRRESULT_FUNC2(xrBeginFrame, (XrSession), session, (const XrFrameBeginInfo *), frameBeginInfo)
  174. EXT_PROTO_XRRESULT_FUNC2(xrBeginSession, (XrSession), session, (const XrSessionBeginInfo *), beginInfo)
  175. EXT_PROTO_XRRESULT_FUNC3(xrCreateAction, (XrActionSet), actionSet, (const XrActionCreateInfo *), createInfo, (XrAction *), action)
  176. EXT_PROTO_XRRESULT_FUNC3(xrCreateActionSet, (XrInstance), instance, (const XrActionSetCreateInfo *), createInfo, (XrActionSet *), actionSet)
  177. EXT_PROTO_XRRESULT_FUNC3(xrCreateActionSpace, (XrSession), session, (const XrActionSpaceCreateInfo *), createInfo, (XrSpace *), space)
  178. EXT_PROTO_XRRESULT_FUNC2(xrCreateInstance, (const XrInstanceCreateInfo *), createInfo, (XrInstance *), instance)
  179. EXT_PROTO_XRRESULT_FUNC3(xrCreateReferenceSpace, (XrSession), session, (const XrReferenceSpaceCreateInfo *), createInfo, (XrSpace *), space)
  180. EXT_PROTO_XRRESULT_FUNC3(xrCreateSession, (XrInstance), instance, (const XrSessionCreateInfo *), createInfo, (XrSession *), session)
  181. EXT_PROTO_XRRESULT_FUNC3(xrCreateSwapchain, (XrSession), session, (const XrSwapchainCreateInfo *), createInfo, (XrSwapchain *), swapchain)
  182. EXT_PROTO_XRRESULT_FUNC1(xrDestroyAction, (XrAction), action)
  183. EXT_PROTO_XRRESULT_FUNC1(xrDestroyActionSet, (XrActionSet), actionSet)
  184. EXT_PROTO_XRRESULT_FUNC1(xrDestroyInstance, (XrInstance), instance)
  185. EXT_PROTO_XRRESULT_FUNC1(xrDestroySession, (XrSession), session)
  186. EXT_PROTO_XRRESULT_FUNC1(xrDestroySpace, (XrSpace), space)
  187. EXT_PROTO_XRRESULT_FUNC1(xrDestroySwapchain, (XrSwapchain), swapchain)
  188. EXT_PROTO_XRRESULT_FUNC2(xrEndFrame, (XrSession), session, (const XrFrameEndInfo *), frameEndInfo)
  189. EXT_PROTO_XRRESULT_FUNC1(xrEndSession, (XrSession), session)
  190. EXT_PROTO_XRRESULT_FUNC3(xrEnumerateApiLayerProperties, (uint32_t), propertyCapacityInput, (uint32_t *), propertyCountOutput, (XrApiLayerProperties *), properties)
  191. EXT_PROTO_XRRESULT_FUNC6(xrEnumerateEnvironmentBlendModes, (XrInstance), instance, (XrSystemId), systemId, (XrViewConfigurationType), viewConfigurationType, (uint32_t), environmentBlendModeCapacityInput, (uint32_t *), environmentBlendModeCountOutput, (XrEnvironmentBlendMode *), environmentBlendModes)
  192. EXT_PROTO_XRRESULT_FUNC4(xrEnumerateInstanceExtensionProperties, (const char *), layerName, (uint32_t), propertyCapacityInput, (uint32_t *), propertyCountOutput, (XrExtensionProperties *), properties)
  193. EXT_PROTO_XRRESULT_FUNC4(xrEnumerateReferenceSpaces, (XrSession), session, (uint32_t), spaceCapacityInput, (uint32_t *), spaceCountOutput, (XrReferenceSpaceType *), spaces)
  194. EXT_PROTO_XRRESULT_FUNC4(xrEnumerateSwapchainFormats, (XrSession), session, (uint32_t), formatCapacityInput, (uint32_t *), formatCountOutput, (int64_t *), formats)
  195. EXT_PROTO_XRRESULT_FUNC5(xrEnumerateViewConfigurations, (XrInstance), instance, (XrSystemId), systemId, (uint32_t), viewConfigurationTypeCapacityInput, (uint32_t *), viewConfigurationTypeCountOutput, (XrViewConfigurationType *), viewConfigurationTypes)
  196. EXT_PROTO_XRRESULT_FUNC6(xrEnumerateViewConfigurationViews, (XrInstance), instance, (XrSystemId), systemId, (XrViewConfigurationType), viewConfigurationType, (uint32_t), viewCapacityInput, (uint32_t *), viewCountOutput, (XrViewConfigurationView *), views)
  197. EXT_PROTO_XRRESULT_FUNC3(xrGetActionStateBoolean, (XrSession), session, (const XrActionStateGetInfo *), getInfo, (XrActionStateBoolean *), state)
  198. EXT_PROTO_XRRESULT_FUNC3(xrGetActionStateFloat, (XrSession), session, (const XrActionStateGetInfo *), getInfo, (XrActionStateFloat *), state)
  199. EXT_PROTO_XRRESULT_FUNC3(xrGetActionStateVector2f, (XrSession), session, (const XrActionStateGetInfo *), getInfo, (XrActionStateVector2f *), state)
  200. EXT_PROTO_XRRESULT_FUNC3(xrGetCurrentInteractionProfile, (XrSession), session, (XrPath), topLevelUserPath, (XrInteractionProfileState *), interactionProfile)
  201. EXT_PROTO_XRRESULT_FUNC2(xrGetInstanceProperties, (XrInstance), instance, (XrInstanceProperties *), instanceProperties)
  202. EXT_PROTO_XRRESULT_FUNC3(xrGetReferenceSpaceBoundsRect, (XrSession), session, (XrReferenceSpaceType), referenceSpaceType, (XrExtent2Df *), bounds)
  203. EXT_PROTO_XRRESULT_FUNC3(xrGetSystem, (XrInstance), instance, (const XrSystemGetInfo *), getInfo, (XrSystemId *), systemId)
  204. EXT_PROTO_XRRESULT_FUNC3(xrGetSystemProperties, (XrInstance), instance, (XrSystemId), systemId, (XrSystemProperties *), properties)
  205. EXT_PROTO_XRRESULT_FUNC4(xrLocateSpace, (XrSpace), space, (XrSpace), baseSpace, (XrTime), time, (XrSpaceLocation *), location)
  206. EXT_PROTO_XRRESULT_FUNC6(xrLocateViews, (XrSession), session, (const XrViewLocateInfo *), viewLocateInfo, (XrViewState *), viewState, (uint32_t), viewCapacityInput, (uint32_t *), viewCountOutput, (XrView *), views)
  207. EXT_PROTO_XRRESULT_FUNC5(xrPathToString, (XrInstance), instance, (XrPath), path, (uint32_t), bufferCapacityInput, (uint32_t *), bufferCountOutput, (char *), buffer)
  208. EXT_PROTO_XRRESULT_FUNC2(xrPollEvent, (XrInstance), instance, (XrEventDataBuffer *), eventData)
  209. EXT_PROTO_XRRESULT_FUNC2(xrReleaseSwapchainImage, (XrSwapchain), swapchain, (const XrSwapchainImageReleaseInfo *), releaseInfo)
  210. EXT_PROTO_XRRESULT_FUNC3(xrResultToString, (XrInstance), instance, (XrResult), value, (char *), buffer)
  211. EXT_PROTO_XRRESULT_FUNC3(xrStringToPath, (XrInstance), instance, (const char *), pathString, (XrPath *), path)
  212. EXT_PROTO_XRRESULT_FUNC2(xrSuggestInteractionProfileBindings, (XrInstance), instance, (const XrInteractionProfileSuggestedBinding *), suggestedBindings)
  213. EXT_PROTO_XRRESULT_FUNC2(xrSyncActions, (XrSession), session, (const XrActionsSyncInfo *), syncInfo)
  214. EXT_PROTO_XRRESULT_FUNC3(xrWaitFrame, (XrSession), session, (const XrFrameWaitInfo *), frameWaitInfo, (XrFrameState *), frameState)
  215. EXT_PROTO_XRRESULT_FUNC2(xrWaitSwapchainImage, (XrSwapchain), swapchain, (const XrSwapchainImageWaitInfo *), waitInfo)
  216. // instance
  217. bool create_instance();
  218. bool get_system_info();
  219. bool load_supported_view_configuration_types();
  220. bool load_supported_environmental_blend_modes();
  221. bool is_view_configuration_supported(XrViewConfigurationType p_configuration_type) const;
  222. bool load_supported_view_configuration_views(XrViewConfigurationType p_configuration_type);
  223. void destroy_instance();
  224. // session
  225. bool create_session();
  226. bool load_supported_reference_spaces();
  227. bool is_reference_space_supported(XrReferenceSpaceType p_reference_space);
  228. bool setup_play_space();
  229. bool setup_view_space();
  230. bool load_supported_swapchain_formats();
  231. bool is_swapchain_format_supported(int64_t p_swapchain_format);
  232. bool obtain_swapchain_formats();
  233. bool create_main_swapchains(const Size2i &p_size);
  234. void free_main_swapchains();
  235. void destroy_session();
  236. // action map
  237. struct Tracker { // Trackers represent tracked physical objects such as controllers, pucks, etc.
  238. String name; // Name for this tracker (i.e. "/user/hand/left")
  239. XrPath toplevel_path; // OpenXR XrPath for this tracker
  240. RID active_profile_rid; // RID of the active profile for this tracker
  241. };
  242. RID_Owner<Tracker, true> tracker_owner;
  243. RID get_tracker_rid(XrPath p_path);
  244. bool interaction_profile_changed = true; // If true we need to check for updates to our active_profile_rid.
  245. struct ActionSet { // Action sets define a set of actions that can be enabled together
  246. String name; // Name for this action set (i.e. "godot_action_set")
  247. bool is_attached; // If true our action set has been attached to the session and can no longer be modified
  248. XrActionSet handle; // OpenXR handle for this action set
  249. };
  250. RID_Owner<ActionSet, true> action_set_owner;
  251. struct ActionTracker { // Links and action to a tracker
  252. RID tracker_rid; // RID of the tracker
  253. XrSpace space; // Optional space for pose actions
  254. bool was_location_valid; // If true the last position we obtained was valid
  255. };
  256. struct Action { // Actions define the inputs and outputs in OpenXR
  257. RID action_set_rid; // RID of the action set this action belongs to
  258. String name; // Name for this action (i.e. "aim_pose")
  259. XrActionType action_type; // Type of action (bool, float, etc.)
  260. Vector<ActionTracker> trackers; // The trackers this action can be used with
  261. XrAction handle; // OpenXR handle for this action
  262. };
  263. RID_Owner<Action, true> action_owner;
  264. RID get_action_rid(XrAction p_action);
  265. struct InteractionProfile { // Interaction profiles define suggested bindings between the physical inputs on controller types and our actions
  266. String name; // Name of the interaction profile (i.e. "/interaction_profiles/valve/index_controller")
  267. CharString internal_name; // Internal name of the interaction profile (translated if required)
  268. XrPath path; // OpenXR path for this profile
  269. Vector<XrActionSuggestedBinding> bindings; // OpenXR action bindings
  270. Vector<PackedByteArray> modifiers; // Array of modifiers we'll add into XrBindingModificationsKHR
  271. };
  272. RID_Owner<InteractionProfile, true> interaction_profile_owner;
  273. RID get_interaction_profile_rid(XrPath p_path);
  274. XrPath get_interaction_profile_path(RID p_interaction_profile);
  275. CharString get_interaction_profile_internal_name(const String &p_interaction_profile_name) const;
  276. const char *check_profile_path(const CharString &p_interaction_profile_name, const char *p_path) const;
  277. struct OrderedCompositionLayer {
  278. const XrCompositionLayerBaseHeader *composition_layer;
  279. int sort_order;
  280. _FORCE_INLINE_ bool operator()(const OrderedCompositionLayer &a, const OrderedCompositionLayer &b) const {
  281. return a.sort_order < b.sort_order || (a.sort_order == b.sort_order && uint64_t(a.composition_layer) < uint64_t(b.composition_layer));
  282. }
  283. };
  284. // state changes
  285. bool poll_events();
  286. bool on_state_idle();
  287. bool on_state_ready();
  288. bool on_state_synchronized();
  289. bool on_state_visible();
  290. bool on_state_focused();
  291. bool on_state_stopping();
  292. bool on_state_loss_pending();
  293. bool on_state_exiting();
  294. // convenience
  295. void copy_string_to_char_buffer(const String &p_string, char *p_buffer, int p_buffer_len);
  296. // Render state, Only accessible in rendering thread
  297. struct RenderState {
  298. bool running = false;
  299. bool should_render = false;
  300. bool has_xr_viewport = false;
  301. XrTime predicted_display_time = 0;
  302. XrSpace play_space = XR_NULL_HANDLE;
  303. XrEnvironmentBlendMode environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
  304. double render_target_size_multiplier = 1.0;
  305. uint64_t frame = 0;
  306. Rect2i render_region;
  307. LocalVector<XrView> views;
  308. LocalVector<XrCompositionLayerProjectionView> projection_views;
  309. LocalVector<XrCompositionLayerDepthInfoKHR> depth_views; // Only used by Composition Layer Depth Extension if available
  310. bool submit_depth_buffer = false; // if set to true we submit depth buffers to OpenXR if a suitable extension is enabled.
  311. bool view_pose_valid = false;
  312. double z_near = 0.0;
  313. double z_far = 0.0;
  314. XrCompositionLayerProjection projection_layer = {
  315. XR_TYPE_COMPOSITION_LAYER_PROJECTION, // type
  316. nullptr, // next
  317. 0, // layerFlags
  318. XR_NULL_HANDLE, // space
  319. 0, // viewCount
  320. nullptr // views
  321. };
  322. Size2i main_swapchain_size;
  323. OpenXRSwapChainInfo main_swapchains[OPENXR_SWAPCHAIN_MAX];
  324. } render_state;
  325. static void _allocate_view_buffers_rt(uint32_t p_view_count, bool p_submit_depth_buffer);
  326. static void _set_render_session_running_rt(bool p_is_running);
  327. static void _set_render_display_info_rt(XrTime p_predicted_display_time, bool p_should_render);
  328. static void _set_render_play_space_rt(uint64_t p_play_space);
  329. static void _set_render_environment_blend_mode_rt(int32_t p_environment_blend_mode);
  330. static void _set_render_state_multiplier_rt(double p_render_target_size_multiplier);
  331. static void _set_render_state_render_region_rt(const Rect2i &p_render_region);
  332. static void _update_main_swapchain_size_rt();
  333. _FORCE_INLINE_ void allocate_view_buffers(uint32_t p_view_count, bool p_submit_depth_buffer) {
  334. // If we're rendering on a separate thread, we may still be processing the last frame, don't communicate this till we're ready...
  335. RenderingServer *rendering_server = RenderingServer::get_singleton();
  336. ERR_FAIL_NULL(rendering_server);
  337. rendering_server->call_on_render_thread(callable_mp_static(&OpenXRAPI::_allocate_view_buffers_rt).bind(p_view_count, p_submit_depth_buffer));
  338. }
  339. _FORCE_INLINE_ void set_render_session_running(bool p_is_running) {
  340. // If we're rendering on a separate thread, we may still be processing the last frame, don't communicate this till we're ready...
  341. RenderingServer *rendering_server = RenderingServer::get_singleton();
  342. ERR_FAIL_NULL(rendering_server);
  343. rendering_server->call_on_render_thread(callable_mp_static(&OpenXRAPI::_set_render_session_running_rt).bind(p_is_running));
  344. }
  345. _FORCE_INLINE_ void set_render_display_info(XrTime p_predicted_display_time, bool p_should_render) {
  346. // If we're rendering on a separate thread, we may still be processing the last frame, don't communicate this till we're ready...
  347. RenderingServer *rendering_server = RenderingServer::get_singleton();
  348. ERR_FAIL_NULL(rendering_server);
  349. rendering_server->call_on_render_thread(callable_mp_static(&OpenXRAPI::_set_render_display_info_rt).bind(p_predicted_display_time, p_should_render));
  350. }
  351. _FORCE_INLINE_ void set_render_play_space(XrSpace p_play_space) {
  352. // If we're rendering on a separate thread, we may still be processing the last frame, don't communicate this till we're ready...
  353. RenderingServer *rendering_server = RenderingServer::get_singleton();
  354. ERR_FAIL_NULL(rendering_server);
  355. rendering_server->call_on_render_thread(callable_mp_static(&OpenXRAPI::_set_render_play_space_rt).bind(uint64_t(p_play_space)));
  356. }
  357. _FORCE_INLINE_ void set_render_environment_blend_mode(XrEnvironmentBlendMode p_mode) {
  358. // If we're rendering on a separate thread, we may still be processing the last frame, don't communicate this till we're ready...
  359. RenderingServer *rendering_server = RenderingServer::get_singleton();
  360. ERR_FAIL_NULL(rendering_server);
  361. rendering_server->call_on_render_thread(callable_mp_static(&OpenXRAPI::_set_render_environment_blend_mode_rt).bind((int32_t)p_mode));
  362. }
  363. _FORCE_INLINE_ void set_render_state_multiplier(double p_render_target_size_multiplier) {
  364. // If we're rendering on a separate thread, we may still be processing the last frame, don't communicate this till we're ready...
  365. RenderingServer *rendering_server = RenderingServer::get_singleton();
  366. ERR_FAIL_NULL(rendering_server);
  367. rendering_server->call_on_render_thread(callable_mp_static(&OpenXRAPI::_set_render_state_multiplier_rt).bind(p_render_target_size_multiplier));
  368. }
  369. _FORCE_INLINE_ void set_render_state_render_region(const Rect2i &p_render_region) {
  370. RenderingServer *rendering_server = RenderingServer::get_singleton();
  371. ERR_FAIL_NULL(rendering_server);
  372. rendering_server->call_on_render_thread(callable_mp_static(&OpenXRAPI::_set_render_state_render_region_rt).bind(p_render_region));
  373. }
  374. public:
  375. _FORCE_INLINE_ void update_main_swapchain_size() {
  376. RenderingServer *rendering_server = RenderingServer::get_singleton();
  377. ERR_FAIL_NULL(rendering_server);
  378. rendering_server->call_on_render_thread(callable_mp_static(&OpenXRAPI::_update_main_swapchain_size_rt));
  379. }
  380. XrVersion get_openxr_version() const { return openxr_version; }
  381. XrInstance get_instance() const { return instance; }
  382. XrSystemId get_system_id() const { return system_id; }
  383. XrSession get_session() const { return session; }
  384. XrSessionState get_session_state() const { return session_state; }
  385. OpenXRGraphicsExtensionWrapper *get_graphics_extension() const { return graphics_extension; }
  386. String get_runtime_name() const { return runtime_name; }
  387. String get_runtime_version() const { return runtime_version; }
  388. String get_system_name() const { return system_name; }
  389. uint32_t get_vendor_id() const { return vendor_id; }
  390. // helper method to convert an XrPosef to a Transform3D
  391. Transform3D transform_from_pose(const XrPosef &p_pose);
  392. XrPosef pose_from_transform(const Transform3D &p_transform);
  393. // helper method to get a valid Transform3D from an openxr space location
  394. XRPose::TrackingConfidence transform_from_location(const XrSpaceLocation &p_location, Transform3D &r_transform);
  395. XRPose::TrackingConfidence transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform);
  396. void parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity);
  397. bool xr_result(XrResult p_result, const char *p_format, const Array &p_args = Array()) const;
  398. XrPath get_xr_path(const String &p_path);
  399. String get_xr_path_name(const XrPath &p_path);
  400. bool is_top_level_path_supported(const String &p_toplevel_path);
  401. bool is_interaction_profile_supported(const String &p_ip_path);
  402. bool interaction_profile_supports_io_path(const String &p_ip_path, const String &p_io_path);
  403. static bool openxr_is_enabled(bool p_check_run_in_editor = true);
  404. _FORCE_INLINE_ static OpenXRAPI *get_singleton() { return singleton; }
  405. XrResult try_get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr);
  406. XrResult get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr);
  407. String get_error_string(XrResult result) const;
  408. String get_swapchain_format_name(int64_t p_swapchain_format) const;
  409. void set_object_name(XrObjectType p_object_type, uint64_t p_object_handle, const String &p_object_name);
  410. void begin_debug_label_region(const String &p_label_name);
  411. void end_debug_label_region();
  412. void insert_debug_label(const String &p_label_name);
  413. OpenXRInterface *get_xr_interface() const { return xr_interface; }
  414. void set_xr_interface(OpenXRInterface *p_xr_interface);
  415. static void register_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper);
  416. static void unregister_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper);
  417. static const Vector<OpenXRExtensionWrapper *> &get_registered_extension_wrappers();
  418. static void register_extension_metadata();
  419. static void cleanup_extension_wrappers();
  420. static PackedStringArray get_all_requested_extensions(XrVersion p_xr_version);
  421. void set_form_factor(XrFormFactor p_form_factor);
  422. XrFormFactor get_form_factor() const { return form_factor; }
  423. uint32_t get_view_count();
  424. void set_view_configuration(XrViewConfigurationType p_view_configuration);
  425. XrViewConfigurationType get_view_configuration() const { return view_configuration; }
  426. bool set_requested_reference_space(XrReferenceSpaceType p_requested_reference_space);
  427. XrReferenceSpaceType get_requested_reference_space() const { return requested_reference_space; }
  428. XrReferenceSpaceType get_reference_space() const { return reference_space; }
  429. void set_custom_play_space(XrSpace p_custom_space);
  430. void set_submit_depth_buffer(bool p_submit_depth_buffer);
  431. bool get_submit_depth_buffer() const { return submit_depth_buffer; }
  432. bool is_initialized();
  433. bool is_running();
  434. bool initialize(const String &p_rendering_driver);
  435. bool initialize_session();
  436. void finish();
  437. _FORCE_INLINE_ XrSpace get_play_space() const { return play_space; }
  438. _FORCE_INLINE_ XrTime get_predicted_display_time() { return frame_state.predictedDisplayTime; }
  439. _FORCE_INLINE_ XrTime get_next_frame_time() { return frame_state.predictedDisplayTime + frame_state.predictedDisplayPeriod; }
  440. _FORCE_INLINE_ bool can_render() {
  441. return instance != XR_NULL_HANDLE && session != XR_NULL_HANDLE && running && frame_state.shouldRender;
  442. }
  443. XrHandTrackerEXT get_hand_tracker(int p_hand_index);
  444. Size2 get_recommended_target_size();
  445. XRPose::TrackingConfidence get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity);
  446. bool get_view_transform(uint32_t p_view, Transform3D &r_transform);
  447. bool get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, Projection &p_camera_matrix);
  448. Vector2 get_eye_focus(uint32_t p_view, float p_aspect);
  449. bool process();
  450. void pre_render();
  451. bool pre_draw_viewport(RID p_render_target);
  452. XrSwapchain get_color_swapchain();
  453. RID get_color_texture();
  454. RID get_depth_texture();
  455. RID get_density_map_texture();
  456. void set_velocity_texture(RID p_render_target);
  457. RID get_velocity_texture();
  458. void set_velocity_depth_texture(RID p_render_target);
  459. RID get_velocity_depth_texture();
  460. void set_velocity_target_size(const Size2i &p_target_size);
  461. Size2i get_velocity_target_size();
  462. const XrCompositionLayerProjection *get_projection_layer() const;
  463. void post_draw_viewport(RID p_render_target);
  464. void end_frame();
  465. // Display refresh rate
  466. float get_display_refresh_rate() const;
  467. void set_display_refresh_rate(float p_refresh_rate);
  468. Array get_available_display_refresh_rates() const;
  469. // Render Target size multiplier
  470. double get_render_target_size_multiplier() const;
  471. void set_render_target_size_multiplier(double multiplier);
  472. Rect2i get_render_region() const;
  473. void set_render_region(const Rect2i &p_render_region);
  474. // Foveation settings
  475. bool is_foveation_supported() const;
  476. int get_foveation_level() const;
  477. void set_foveation_level(int p_foveation_level);
  478. bool get_foveation_dynamic() const;
  479. void set_foveation_dynamic(bool p_foveation_dynamic);
  480. // Play space.
  481. Size2 get_play_space_bounds() const;
  482. // swapchains
  483. PackedInt64Array get_supported_swapchain_formats();
  484. int64_t get_color_swapchain_format() const { return color_swapchain_format; }
  485. int64_t get_depth_swapchain_format() const { return depth_swapchain_format; }
  486. double get_render_state_z_near() const { return render_state.z_near; }
  487. double get_render_state_z_far() const { return render_state.z_far; }
  488. // action map
  489. String get_default_action_map_resource_name();
  490. RID tracker_create(const String &p_name);
  491. String tracker_get_name(RID p_tracker);
  492. void tracker_check_profile(RID p_tracker, XrSession p_session = XR_NULL_HANDLE);
  493. void tracker_free(RID p_tracker);
  494. RID action_set_create(const String &p_name, const String &p_localized_name, const int p_priority);
  495. String action_set_get_name(RID p_action_set);
  496. XrActionSet action_set_get_handle(RID p_action_set);
  497. bool attach_action_sets(const Vector<RID> &p_action_sets);
  498. void action_set_free(RID p_action_set);
  499. RID 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);
  500. String action_get_name(RID p_action);
  501. XrAction action_get_handle(RID p_action);
  502. void action_free(RID p_action);
  503. RID interaction_profile_create(const String &p_name);
  504. String interaction_profile_get_name(RID p_interaction_profile);
  505. void interaction_profile_clear_bindings(RID p_interaction_profile);
  506. int interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String &p_path);
  507. bool interaction_profile_add_modifier(RID p_interaction_profile, const PackedByteArray &p_modifier);
  508. bool interaction_profile_suggest_bindings(RID p_interaction_profile);
  509. void interaction_profile_free(RID p_interaction_profile);
  510. RID find_tracker(const String &p_name);
  511. RID find_action_set(const String &p_name);
  512. RID find_action(const String &p_name, const RID &p_action_set = RID());
  513. bool sync_action_sets(const Vector<RID> &p_active_sets);
  514. bool get_action_bool(RID p_action, RID p_tracker);
  515. float get_action_float(RID p_action, RID p_tracker);
  516. Vector2 get_action_vector2(RID p_action, RID p_tracker);
  517. XRPose::TrackingConfidence get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity);
  518. bool trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns);
  519. void register_composition_layer_provider(OpenXRExtensionWrapper *p_extension);
  520. void unregister_composition_layer_provider(OpenXRExtensionWrapper *p_extension);
  521. void register_projection_views_extension(OpenXRExtensionWrapper *p_extension);
  522. void unregister_projection_views_extension(OpenXRExtensionWrapper *p_extension);
  523. void register_frame_info_extension(OpenXRExtensionWrapper *p_extension);
  524. void unregister_frame_info_extension(OpenXRExtensionWrapper *p_extension);
  525. const Vector<XrEnvironmentBlendMode> get_supported_environment_blend_modes();
  526. bool is_environment_blend_mode_supported(XrEnvironmentBlendMode p_blend_mode) const;
  527. bool set_environment_blend_mode(XrEnvironmentBlendMode p_blend_mode);
  528. XrEnvironmentBlendMode get_environment_blend_mode() const { return requested_environment_blend_mode; }
  529. enum OpenXRAlphaBlendModeSupport {
  530. OPENXR_ALPHA_BLEND_MODE_SUPPORT_NONE = 0,
  531. OPENXR_ALPHA_BLEND_MODE_SUPPORT_REAL = 1,
  532. OPENXR_ALPHA_BLEND_MODE_SUPPORT_EMULATING = 2,
  533. };
  534. void set_emulate_environment_blend_mode_alpha_blend(bool p_enabled);
  535. OpenXRAlphaBlendModeSupport is_environment_blend_mode_alpha_blend_supported();
  536. OpenXRAPI();
  537. ~OpenXRAPI();
  538. };