Debian Codegraph @

modules/openxr/openxr_api.cpp

raw symbols SCIP
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
31 #include "openxr_api.h"
32
33 #include "openxr_interface.h"
34 #include "openxr_util.h"
35
36 #include "core/config/engine.h"
37 #include "core/config/project_settings.h"
38 #include "core/os/memory.h"
39 #include "core/profiling/profiling.h"
40 #include "core/version.h"
41
42 #include "openxr_platform_inc.h"
43
44 #ifdef VULKAN_ENABLED
45 #include "extensions/platform/openxr_vulkan_extension.h"
46 #endif
47
48 #ifdef METAL_ENABLED
49 #include "extensions/platform/openxr_metal_extension.h"
50 #endif
51
52 #if defined(GLES3_ENABLED) && !defined(MACOS_ENABLED)
53 #include "extensions/platform/openxr_opengl_extension.h"
54 #endif
55
56 #ifdef D3D12_ENABLED
57 #include "extensions/platform/openxr_d3d12_extension.h"
58 #endif
59
60 #include "extensions/openxr_composition_layer_depth_extension.h"
61 #include "extensions/openxr_debug_utils_extension.h"
62 #include "extensions/openxr_eye_gaze_interaction.h"
63 #include "extensions/openxr_fb_display_refresh_rate_extension.h"
64 #include "extensions/openxr_fb_foveation_extension.h"
65 #include "extensions/openxr_fb_update_swapchain_extension.h"
66 #include "extensions/openxr_hand_tracking_extension.h"
67
68 #ifndef DISABLE_DEPRECATED
69 #include "extensions/openxr_extension_wrapper_extension.h"
70 #endif // DISABLE_DEPRECATED
71
72 #ifdef ANDROID_ENABLED
73 #define OPENXR_LOADER_NAME "libopenxr_loader.so"
74 #endif
75
76 ////////////////////////////////////
77 // OpenXRAPI::OpenXRSwapChainInfo
78
79 Vector<OpenXRAPI::OpenXRSwapChainInfo> OpenXRAPI::OpenXRSwapChainInfo::free_queue;
80
81 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) {
82 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
83 ERR_FAIL_NULL_V(openxr_api, false);
84
85 XrSession xr_session = openxr_api->get_session();
86 ERR_FAIL_COND_V(xr_session == XR_NULL_HANDLE, false);
87
88 OpenXRGraphicsExtensionWrapper *xr_graphics_extension = openxr_api->get_graphics_extension();
89 ERR_FAIL_NULL_V(xr_graphics_extension, false);
90
91 // We already have a swapchain?
92 ERR_FAIL_COND_V(swapchain != XR_NULL_HANDLE, false);
93
94 XrResult result;
95
96 void *next_pointer = nullptr;
97 for (OpenXRExtensionWrapper *wrapper : OpenXRAPI::get_registered_extension_wrappers()) {
98 void *np = wrapper->set_swapchain_create_info_and_get_next_pointer(next_pointer);
99 if (np != nullptr) {
100 next_pointer = np;
101 }
102 }
103
104 XrSwapchainCreateInfo swapchain_create_info = {
105 XR_TYPE_SWAPCHAIN_CREATE_INFO, // type
106 next_pointer, // next
107 p_create_flags, // createFlags
108 p_usage_flags, // usageFlags
109 p_swapchain_format, // format
110 p_sample_count, // sampleCount
111 p_width, // width
112 p_height, // height
113 1, // faceCount
114 p_array_size, // arraySize
115 1 // mipCount
116 };
117
118 XrSwapchain new_swapchain;
119 result = openxr_api->xrCreateSwapchain(xr_session, &swapchain_create_info, &new_swapchain);
120 if (XR_FAILED(result)) {
121 print_line("OpenXR: Failed to get swapchain [", openxr_api->get_error_string(result), "]");
122 return false;
123 }
124
125 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)) {
126 openxr_api->xrDestroySwapchain(new_swapchain);
127 return false;
128 }
129
130 swapchain = new_swapchain;
131
132 return true;
133 }
134
135 void OpenXRAPI::OpenXRSwapChainInfo::queue_free() {
136 if (image_acquired) {
137 release();
138 }
139
140 if (swapchain != XR_NULL_HANDLE) {
141 free_queue.push_back(*this);
142
143 swapchain_graphics_data = nullptr;
144 swapchain = XR_NULL_HANDLE;
145 }
146 }
147
148 void OpenXRAPI::OpenXRSwapChainInfo::free_queued() {
149 for (OpenXRAPI::OpenXRSwapChainInfo &swapchain_info : free_queue) {
150 swapchain_info.free();
151 }
152 free_queue.clear();
153 }
154
155 void OpenXRAPI::OpenXRSwapChainInfo::free() {
156 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
157 ERR_FAIL_NULL(openxr_api);
158
159 if (image_acquired) {
160 release();
161 }
162
163 if (openxr_api->get_graphics_extension() && swapchain_graphics_data != nullptr) {
164 openxr_api->get_graphics_extension()->cleanup_swapchain_graphics_data(&swapchain_graphics_data);
165 }
166
167 if (swapchain != XR_NULL_HANDLE) {
168 openxr_api->xrDestroySwapchain(swapchain);
169 swapchain = XR_NULL_HANDLE;
170 }
171 }
172
173 bool OpenXRAPI::OpenXRSwapChainInfo::acquire(bool &p_should_render) {
174 GodotProfileZone("OpenXR: acquire swapchain");
175 ERR_FAIL_COND_V(image_acquired, true); // This was not released when it should be, error out and reuse...
176
177 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
178 ERR_FAIL_NULL_V(openxr_api, false);
179
180 XrResult result;
181
182 if (!skip_acquire_swapchain) {
183 XrSwapchainImageAcquireInfo swapchain_image_acquire_info = {
184 XR_TYPE_SWAPCHAIN_IMAGE_ACQUIRE_INFO, // type
185 nullptr // next
186 };
187
188 result = openxr_api->xrAcquireSwapchainImage(swapchain, &swapchain_image_acquire_info, &image_index);
189 if (!XR_UNQUALIFIED_SUCCESS(result)) {
190 // Make sure end_frame knows we need to submit an empty frame
191 p_should_render = false;
192
193 if (XR_FAILED(result)) {
194 // Unexpected failure, log this!
195 print_line("OpenXR: failed to acquire swapchain image [", openxr_api->get_error_string(result), "]");
196 return false;
197 } else {
198 // In this scenario we silently fail, the XR runtime is simply not ready yet to acquire the swapchain.
199 return false;
200 }
201 }
202 }
203
204 XrSwapchainImageWaitInfo swapchain_image_wait_info = {
205 XR_TYPE_SWAPCHAIN_IMAGE_WAIT_INFO, // type
206 nullptr, // next
207 1000000000 // 1s timeout in nanoseconds
208 };
209
210 // Wait for a maximum of 10 seconds before calling it a critical failure...
211 for (int retry = 0; retry < 10; retry++) {
212 result = openxr_api->xrWaitSwapchainImage(swapchain, &swapchain_image_wait_info);
213 if (result != XR_TIMEOUT_EXPIRED) {
214 break;
215 }
216 WARN_PRINT("OpenXR: timed out waiting for swapchain image.");
217 }
218
219 if (!XR_UNQUALIFIED_SUCCESS(result)) {
220 // Make sure end_frame knows we need to submit an empty frame
221 p_should_render = false;
222
223 if (XR_FAILED(result)) {
224 // Unexpected failure, log this!
225 print_line("OpenXR: failed to wait for swapchain image [", openxr_api->get_error_string(result), "]");
226 return false;
227 } else {
228 WARN_PRINT("OpenXR: couldn't to wait for swapchain but not a complete error [" + openxr_api->get_error_string(result) + "]");
229
230 // Make sure to skip trying to acquire the swapchain image in the next frame
231 skip_acquire_swapchain = true;
232 return false;
233 }
234 } else {
235 skip_acquire_swapchain = false;
236 }
237
238 image_acquired = true;
239 return true;
240 }
241
242 bool OpenXRAPI::OpenXRSwapChainInfo::release() {
243 if (!image_acquired) {
244 // Already released or never acquired.
245 return true;
246 }
247
248 image_acquired = false; // Regardless if we succeed or not, consider this released.
249
250 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
251 ERR_FAIL_NULL_V(openxr_api, false);
252
253 XrSwapchainImageReleaseInfo swapchain_image_release_info = {
254 XR_TYPE_SWAPCHAIN_IMAGE_RELEASE_INFO, // type
255 nullptr // next
256 };
257 XrResult result = openxr_api->xrReleaseSwapchainImage(swapchain, &swapchain_image_release_info);
258 if (XR_FAILED(result)) {
259 print_line("OpenXR: failed to release swapchain image! [", openxr_api->get_error_string(result), "]");
260 return false;
261 }
262
263 return true;
264 }
265
266 RID OpenXRAPI::OpenXRSwapChainInfo::get_image() {
267 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
268
269 if (image_acquired && openxr_api && openxr_api->get_graphics_extension()) {
270 return OpenXRAPI::get_singleton()->get_graphics_extension()->get_texture(swapchain_graphics_data, image_index);
271 } else {
272 return RID();
273 }
274 }
275
276 RID OpenXRAPI::OpenXRSwapChainInfo::get_density_map() {
277 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
278
279 if (image_acquired && openxr_api && openxr_api->get_graphics_extension()) {
280 return openxr_api->get_graphics_extension()->get_density_map(swapchain_graphics_data, image_index);
281 } else {
282 return RID();
283 }
284 }
285
286 ////////////////////////////////////
287 // OpenXRAPI
288
289 OpenXRAPI *OpenXRAPI::singleton = nullptr;
290 Vector<OpenXRExtensionWrapper *> OpenXRAPI::registered_extension_wrappers;
291
292 bool OpenXRAPI::openxr_is_enabled(bool p_check_run_in_editor) {
293 if (XRServer::get_xr_mode() == XRServer::XRMODE_DEFAULT) {
294 if (Engine::get_singleton()->is_editor_hint() && p_check_run_in_editor) {
295 // For now, don't start OpenXR when the editor starts up. In the future, this may change
296 // if we want to integrate more XR features into the editor experience.
297 return false;
298 } else {
299 return GLOBAL_GET("xr/openxr/enabled");
300 }
301 } else {
302 return XRServer::get_xr_mode() == XRServer::XRMODE_ON;
303 }
304 }
305
306 String OpenXRAPI::get_default_action_map_resource_name() {
307 String name = GLOBAL_GET("xr/openxr/default_action_map");
308
309 return name;
310 }
311
312 String OpenXRAPI::get_error_string(XrResult p_result) const {
313 if (XR_SUCCEEDED(p_result)) {
314 return String("Succeeded");
315 }
316
317 if (instance == XR_NULL_HANDLE) {
318 Array args = { Variant(p_result) };
319 return String("Error code {0}").format(args);
320 }
321
322 char resultString[XR_MAX_RESULT_STRING_SIZE];
323 XrResult result = xrResultToString(instance, p_result, resultString);
324 if (XR_FAILED(result)) {
325 XR_ENUM_SWITCH(XrResult, p_result);
326 } else {
327 return String(resultString);
328 }
329 }
330
331 String OpenXRAPI::get_swapchain_format_name(int64_t p_swapchain_format) const {
332 // This is rendering engine dependent...
333 if (graphics_extension) {
334 return graphics_extension->get_swapchain_format_name(p_swapchain_format);
335 }
336
337 return String("Swapchain format ") + String::num_int64(int64_t(p_swapchain_format));
338 }
339
340 void OpenXRAPI::set_object_name(XrObjectType p_object_type, uint64_t p_object_handle, const String &p_object_name) {
341 OpenXRDebugUtilsExtension *debug_utils = OpenXRDebugUtilsExtension::get_singleton();
342 if (!debug_utils || !debug_utils->get_active()) {
343 // Not enabled/active? Ignore.
344 return;
345 }
346
347 debug_utils->set_object_name(p_object_type, p_object_handle, p_object_name.utf8().get_data());
348 }
349
350 void OpenXRAPI::begin_debug_label_region(const String &p_label_name) {
351 OpenXRDebugUtilsExtension *debug_utils = OpenXRDebugUtilsExtension::get_singleton();
352 if (!debug_utils || !debug_utils->get_active()) {
353 // Not enabled/active? Ignore.
354 return;
355 }
356
357 debug_utils->begin_debug_label_region(p_label_name.utf8().get_data());
358 }
359
360 void OpenXRAPI::end_debug_label_region() {
361 OpenXRDebugUtilsExtension *debug_utils = OpenXRDebugUtilsExtension::get_singleton();
362 if (!debug_utils || !debug_utils->get_active()) {
363 // Not enabled/active? Ignore.
364 return;
365 }
366
367 debug_utils->end_debug_label_region();
368 }
369
370 void OpenXRAPI::insert_debug_label(const String &p_label_name) {
371 OpenXRDebugUtilsExtension *debug_utils = OpenXRDebugUtilsExtension::get_singleton();
372 if (!debug_utils || !debug_utils->get_active()) {
373 // Not enabled/active? Ignore.
374 return;
375 }
376
377 debug_utils->insert_debug_label(p_label_name.utf8().get_data());
378 }
379
380 bool OpenXRAPI::load_layer_properties() {
381 // This queries additional layers that are available and can be initialized when we create our OpenXR instance
382 if (!layer_properties.is_empty()) {
383 // already retrieved this
384 return true;
385 }
386
387 // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
388 uint32_t num_layer_properties = 0;
389 XrResult result = xrEnumerateApiLayerProperties(0, &num_layer_properties, nullptr);
390 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of api layer properties");
391
392 layer_properties.resize(num_layer_properties);
393 for (XrApiLayerProperties &layer : layer_properties) {
394 layer.type = XR_TYPE_API_LAYER_PROPERTIES;
395 layer.next = nullptr;
396 }
397
398 result = xrEnumerateApiLayerProperties(num_layer_properties, &num_layer_properties, layer_properties.ptr());
399 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate api layer properties");
400
401 for (const XrApiLayerProperties &layer : layer_properties) {
402 print_verbose(vformat("OpenXR: Found OpenXR layer %s.", layer.layerName));
403 }
404
405 return true;
406 }
407
408 bool OpenXRAPI::load_supported_extensions() {
409 // This queries supported extensions that are available and can be initialized when we create our OpenXR instance
410
411 if (!supported_extensions.is_empty()) {
412 // already retrieved this
413 return true;
414 }
415
416 // Note, instance is not yet setup so we can't use get_error_string to retrieve our error
417 uint32_t num_supported_extensions = 0;
418 XrResult result = xrEnumerateInstanceExtensionProperties(nullptr, 0, &num_supported_extensions, nullptr);
419 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate number of extension properties");
420
421 supported_extensions.resize(num_supported_extensions);
422
423 // set our types
424 for (XrExtensionProperties &extension : supported_extensions) {
425 extension.type = XR_TYPE_EXTENSION_PROPERTIES;
426 extension.next = nullptr;
427 }
428 result = xrEnumerateInstanceExtensionProperties(nullptr, num_supported_extensions, &num_supported_extensions, supported_extensions.ptr());
429 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate extension properties");
430
431 for (const XrExtensionProperties &extension : supported_extensions) {
432 print_verbose(vformat("OpenXR: Found OpenXR extension %s.", extension.extensionName));
433 }
434
435 return true;
436 }
437
438 bool OpenXRAPI::is_extension_supported(const String &p_extension) const {
439 for (const XrExtensionProperties &extension : supported_extensions) {
440 if (extension.extensionName == p_extension) {
441 return true;
442 }
443 }
444
445 return false;
446 }
447
448 bool OpenXRAPI::is_any_extension_enabled(const String &p_extensions) const {
449 // We allow a comma separated list of extensions here, only one needs to be supported.
450 // This allows us to check for extensions that were renamed or that were embedded in core
451 // at a specific OpenXR version.
452 for (const String &name : p_extensions.split(",", false)) {
453 CharString extension = name.utf8();
454
455 if (enabled_extensions.has(extension)) {
456 return true;
457 }
458 }
459
460 return false;
461 }
462
463 bool OpenXRAPI::is_top_level_path_supported(const String &p_toplevel_path) {
464 String required_extensions = OpenXRInteractionProfileMetadata::get_singleton()->get_top_level_extensions(p_toplevel_path);
465
466 // If unsupported is returned we likely have a misspelled interaction profile path in our action map. Always output that as an error.
467 ERR_FAIL_COND_V_MSG(required_extensions == XR_PATH_UNSUPPORTED_NAME, false, "OpenXR: Unsupported toplevel path " + p_toplevel_path);
468
469 if (required_extensions == "") {
470 // no extension needed, core top level are always "supported", they just won't be used if not really supported
471 return true;
472 }
473
474 if (!is_any_extension_enabled(required_extensions)) {
475 // 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.
476 print_verbose("OpenXR: Top level path " + p_toplevel_path + " requires extension " + required_extensions.replace(",", " or "));
477 return false;
478 }
479
480 return true;
481 }
482
483 bool OpenXRAPI::is_interaction_profile_supported(const String &p_ip_path) {
484 String required_extensions = OpenXRInteractionProfileMetadata::get_singleton()->get_interaction_profile_extensions(p_ip_path);
485
486 // If unsupported is returned we likely have a misspelled interaction profile path in our action map. Always output that as an error.
487 ERR_FAIL_COND_V_MSG(required_extensions == XR_PATH_UNSUPPORTED_NAME, false, "OpenXR: Unsupported interaction profile " + p_ip_path);
488
489 if (required_extensions == "") {
490 // no extension needed, core interaction profiles are always "supported", they just won't be used if not really supported
491 return true;
492 }
493
494 if (!is_any_extension_enabled(required_extensions)) {
495 // It is very likely we have interaction profiles for which the extension is not available so don't flood the logs with unnecessary spam.
496 print_verbose("OpenXR: Interaction profile " + p_ip_path + " requires extension " + required_extensions.replace(",", " or "));
497 return false;
498 }
499
500 return true;
501 }
502
503 bool OpenXRAPI::interaction_profile_supports_io_path(const String &p_ip_path, const String &p_io_path) {
504 if (!is_interaction_profile_supported(p_ip_path)) {
505 return false;
506 }
507
508 const OpenXRInteractionProfileMetadata::IOPath *io_path = OpenXRInteractionProfileMetadata::get_singleton()->get_io_path(p_ip_path, p_io_path);
509
510 // If the io_path is not part of our metadata we've likely got a misspelled name or a bad action map, report
511 ERR_FAIL_NULL_V_MSG(io_path, false, "OpenXR: Unsupported io path " + String(p_ip_path) + String(p_io_path));
512
513 if (io_path->openxr_extension_names == "") {
514 // no extension needed, core io paths are always "supported", they just won't be used if not really supported
515 return true;
516 }
517
518 if (!is_any_extension_enabled(io_path->openxr_extension_names)) {
519 // It is very likely we have io paths for which the extension is not available so don't flood the logs with unnecessary spam.
520 print_verbose("OpenXR: IO path " + String(p_ip_path) + String(p_io_path) + " requires extension " + io_path->openxr_extension_names.replace(",", " or "));
521 return false;
522 }
523
524 return true;
525 }
526
527 void OpenXRAPI::copy_string_to_char_buffer(const String &p_string, char *p_buffer, int p_buffer_len) {
528 CharString char_string = p_string.utf8();
529 int len = char_string.length();
530 if (len < p_buffer_len - 1) {
531 // was having weird CI issues with strcpy so....
532 memcpy(p_buffer, char_string.get_data(), len);
533 p_buffer[len] = '\0';
534 } else {
535 memcpy(p_buffer, char_string.get_data(), p_buffer_len - 1);
536 p_buffer[p_buffer_len - 1] = '\0';
537 }
538 }
539
540 PackedStringArray OpenXRAPI::get_all_requested_extensions(XrVersion p_xr_version) {
541 // This returns all extensions we will request regardless of whether they are available.
542 // This is used by the editor to filter features not enabled through project settings.
543
544 PackedStringArray requested_extensions;
545 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
546 const HashMap<String, bool *> &wrapper_request_extensions = wrapper->get_requested_extensions(p_xr_version);
547
548 for (const KeyValue<String, bool *> &requested_extension : wrapper_request_extensions) {
549 if (!requested_extensions.has(requested_extension.key)) {
550 requested_extensions.push_back(requested_extension.key);
551 }
552 }
553 }
554
555 // Also add in our OpenXR Version "extension", so we can switch logic on that.
556 requested_extensions.push_back(XR_OPENXR_1_1_NAME);
557
558 return requested_extensions;
559 }
560
561 XrResult OpenXRAPI::attempt_create_instance(XrVersion p_version) {
562 enabled_extensions.clear();
563
564 // Find all extensions we wish to enable for the requested OpenXR version.
565 LocalVector<RequestExtension> requested_extensions;
566 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
567 const HashMap<String, bool *> &wrapper_request_extensions = wrapper->get_requested_extensions(p_version);
568
569 for (const KeyValue<String, bool *> &requested_extension : wrapper_request_extensions) {
570 requested_extensions.push_back({ requested_extension.key, requested_extension.value });
571 }
572 }
573
574 for (const RequestExtension &requested_extension : requested_extensions) {
575 if (!is_extension_supported(requested_extension.name)) {
576 if (requested_extension.enabled == nullptr) {
577 // Null means this is a mandatory extension so we fail.
578 ERR_FAIL_V_MSG(XR_ERROR_INITIALIZATION_FAILED, String("OpenXR: OpenXR Runtime does not support ") + requested_extension.name + String(" extension!"));
579 } else {
580 // Set this extension as not supported.
581 *requested_extension.enabled = false;
582 }
583 } else {
584 if (requested_extension.enabled != nullptr) {
585 // Set this extension as supported.
586 *requested_extension.enabled = true;
587 }
588
589 // And record that we want to enable it (dependent extensions may be requested multiple times).
590 CharString ext_name = requested_extension.name.utf8();
591 if (!enabled_extensions.has(ext_name)) {
592 enabled_extensions.push_back(ext_name);
593 }
594 }
595 }
596
597 // Convert our enabled extensions so we can send it to OpenXR.
598 LocalVector<const char *> extension_ptrs;
599 extension_ptrs.reserve(enabled_extensions.size());
600
601 for (const CharString &enabled_extension : enabled_extensions) {
602 const char *extension = enabled_extension.get_data();
603 extension_ptrs.push_back(extension);
604 }
605
606 // Attempt to create our OpenXR instance for the requested version.
607 XrApplicationInfo application_info{
608 "Godot Engine", // applicationName, if we're running a game we'll update this down below.
609 1, // applicationVersion, we don't currently have this
610 "Godot Engine", // engineName
611 GODOT_VERSION_MAJOR * 10000 + GODOT_VERSION_MINOR * 100 + GODOT_VERSION_PATCH, // engineVersion 4.0 -> 40000, 4.0.1 -> 40001, 4.1 -> 40100, etc.
612 p_version // apiVersion
613 };
614
615 // Get additional entries from our extension wrappers.
616 void *next_pointer = nullptr;
617 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
618 void *np = wrapper->set_instance_create_info_and_get_next_pointer(p_version, next_pointer);
619 if (np != nullptr) {
620 next_pointer = np;
621 }
622 }
623
624 // Try and create this instance.
625 XrInstanceCreateInfo instance_create_info = {
626 XR_TYPE_INSTANCE_CREATE_INFO, // type
627 next_pointer, // next
628 0, // createFlags
629 application_info, // applicationInfo
630 0, // enabledApiLayerCount, need to find out if we need support for this?
631 nullptr, // enabledApiLayerNames
632 uint32_t(extension_ptrs.size()), // enabledExtensionCount
633 extension_ptrs.ptr() // enabledExtensionNames
634 };
635
636 // Get our project name.
637 String project_name = GLOBAL_GET("application/config/name");
638 if (!project_name.is_empty()) {
639 copy_string_to_char_buffer(project_name, instance_create_info.applicationInfo.applicationName, XR_MAX_APPLICATION_NAME_SIZE);
640 }
641
642 XrResult result = xrCreateInstance(&instance_create_info, &instance);
643 if (XR_SUCCEEDED(result)) {
644 // Record version we've successfully enabled.
645 openxr_version = p_version;
646 print_line("OpenXR: Created instance for OpenXR", OpenXRUtil::make_xr_version_string(openxr_version));
647
648 if (is_print_verbose_enabled()) {
649 // Print out enabled extensions.
650 for (const char *extension : extension_ptrs) {
651 print_line("OpenXR: Enabled extension ", extension);
652 }
653 }
654 }
655
656 return result;
657 }
658
659 bool OpenXRAPI::create_instance() {
660 // Create our OpenXR instance, this will query any registered extension wrappers for extensions we need to enable.
661
662 XrVersion init_version = XR_API_VERSION_1_1;
663
664 String custom_version = GLOBAL_GET("xr/openxr/target_api_version");
665 if (!custom_version.is_empty()) {
666 Vector<int> ints = custom_version.split_ints(".", false);
667 ERR_FAIL_COND_V_MSG(ints.size() != 3, false, "OpenXR target API version must be major.minor.patch.");
668 init_version = XR_MAKE_VERSION(ints[0], ints[1], ints[2]);
669 }
670
671 XrResult result = attempt_create_instance(init_version);
672 if (result == XR_ERROR_API_VERSION_UNSUPPORTED && init_version == XR_API_VERSION_1_1) {
673 print_verbose("OpenXR: Falling back to OpenXR 1.0");
674
675 init_version = XR_API_VERSION_1_0;
676 result = attempt_create_instance(init_version);
677 }
678 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "Failed to create XR instance [" + get_error_string(result) + "].");
679
680 XrInstanceProperties instanceProps = {
681 XR_TYPE_INSTANCE_PROPERTIES, // type;
682 nullptr, // next
683 0, // runtimeVersion, from here will be set by our get call
684 "" // runtimeName
685 };
686
687 OPENXR_API_INIT_XR_FUNC_V(xrGetInstanceProperties);
688
689 result = xrGetInstanceProperties(instance, &instanceProps);
690 if (XR_FAILED(result)) {
691 // not fatal probably
692 print_line("OpenXR: Failed to get XR instance properties [", get_error_string(result), "]");
693
694 runtime_name = "";
695 runtime_version = "";
696 } else {
697 runtime_name = instanceProps.runtimeName;
698 runtime_version = OpenXRUtil::make_xr_version_string(instanceProps.runtimeVersion);
699 print_line("OpenXR: Running on OpenXR runtime: ", runtime_name, " ", runtime_version);
700 }
701
702 // We add an extension string to indicate we're on OpenXR 1.1,
703 // this makes it easier to check for this in various places where we're already checking on extensions.
704 if (XR_VERSION_MAJOR(openxr_version) == 1 && XR_VERSION_MINOR(openxr_version) == 1) {
705 enabled_extensions.push_back(XR_OPENXR_1_1_NAME);
706 }
707
708 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
709 wrapper->on_instance_created(instance);
710 }
711
712 return true;
713 }
714
715 bool OpenXRAPI::get_system_info() {
716 // Retrieve basic OpenXR system info based on the form factor we desire
717
718 // Retrieve the system for our form factor, fails if form factor is not available
719 XrSystemGetInfo system_get_info = {
720 XR_TYPE_SYSTEM_GET_INFO, // type;
721 nullptr, // next
722 form_factor // formFactor
723 };
724
725 XrResult result = xrGetSystem(instance, &system_get_info, &system_id);
726 if (XR_FAILED(result)) {
727 print_line("OpenXR: Failed to get system for our form factor [", get_error_string(result), "]");
728 return false;
729 }
730
731 // obtain info about our system, writing this out completely to make CI on Linux happy..
732 void *next_pointer = nullptr;
733 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
734 void *np = wrapper->set_system_properties_and_get_next_pointer(next_pointer);
735 if (np != nullptr) {
736 next_pointer = np;
737 }
738 }
739
740 XrSystemProperties system_properties = {
741 XR_TYPE_SYSTEM_PROPERTIES, // type
742 next_pointer, // next
743 0, // systemId, from here will be set by our get call
744 0, // vendorId
745 "", // systemName
746 {
747 0, // maxSwapchainImageHeight
748 0, // maxSwapchainImageWidth
749 0, // maxLayerCount
750 }, // graphicsProperties
751 {
752 false, // orientationTracking
753 false // positionTracking
754 } // trackingProperties
755 };
756
757 result = xrGetSystemProperties(instance, system_id, &system_properties);
758 if (XR_FAILED(result)) {
759 print_line("OpenXR: Failed to get System properties [", get_error_string(result), "]");
760 return false;
761 }
762
763 // remember this state, we'll use it later
764 system_name = String(system_properties.systemName);
765 vendor_id = system_properties.vendorId;
766 graphics_properties = system_properties.graphicsProperties;
767 tracking_properties = system_properties.trackingProperties;
768
769 return true;
770 }
771
772 bool OpenXRAPI::load_supported_view_configuration_types() {
773 // This queries the supported configuration types, likely there will only be one choosing between Mono (phone AR) and Stereo (HMDs)
774
775 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
776
777 supported_view_configuration_types.clear();
778
779 uint32_t num_view_configuration_types = 0;
780 XrResult result = xrEnumerateViewConfigurations(instance, system_id, 0, &num_view_configuration_types, nullptr);
781 if (XR_FAILED(result)) {
782 print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]");
783 return false;
784 }
785
786 supported_view_configuration_types.resize(num_view_configuration_types);
787
788 result = xrEnumerateViewConfigurations(instance, system_id, num_view_configuration_types, &num_view_configuration_types, supported_view_configuration_types.ptr());
789 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerateview configurations");
790 ERR_FAIL_COND_V_MSG(num_view_configuration_types == 0, false, "OpenXR: Failed to enumerateview configurations"); // JIC there should be at least 1!
791
792 for (const XrViewConfigurationType &view_configuration_type : supported_view_configuration_types) {
793 print_verbose(vformat("OpenXR: Found supported view configuration %s.", OpenXRUtil::get_view_configuration_name(view_configuration_type)));
794 }
795
796 // Check value we loaded at startup...
797 if (!is_view_configuration_supported(view_configuration)) {
798 print_verbose(vformat("OpenXR: %s isn't supported, defaulting to %s.", OpenXRUtil::get_view_configuration_name(view_configuration), OpenXRUtil::get_view_configuration_name(supported_view_configuration_types[0])));
799
800 view_configuration = supported_view_configuration_types[0];
801 }
802
803 return true;
804 }
805
806 bool OpenXRAPI::load_supported_environmental_blend_modes() {
807 // This queries the supported environmental blend modes.
808
809 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
810
811 supported_environment_blend_modes.clear();
812
813 uint32_t num_supported_environment_blend_modes = 0;
814 XrResult result = xrEnumerateEnvironmentBlendModes(instance, system_id, view_configuration, 0, &num_supported_environment_blend_modes, nullptr);
815 if (XR_FAILED(result)) {
816 print_line("OpenXR: Failed to get supported environmental blend mode count [", get_error_string(result), "]");
817 return false;
818 }
819
820 supported_environment_blend_modes.resize(num_supported_environment_blend_modes);
821
822 result = xrEnumerateEnvironmentBlendModes(instance, system_id, view_configuration, num_supported_environment_blend_modes, &num_supported_environment_blend_modes, supported_environment_blend_modes.ptrw());
823 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate environmental blend modes");
824 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!
825
826 for (const XrEnvironmentBlendMode &supported_environment_blend_mode : supported_environment_blend_modes) {
827 print_verbose(vformat("OpenXR: Found environmental blend mode %s.", OpenXRUtil::get_environment_blend_mode_name(supported_environment_blend_mode)));
828 }
829
830 return true;
831 }
832
833 bool OpenXRAPI::is_view_configuration_supported(XrViewConfigurationType p_configuration_type) const {
834 return supported_view_configuration_types.has(p_configuration_type);
835 }
836
837 bool OpenXRAPI::load_supported_view_configuration_views(XrViewConfigurationType p_configuration_type) {
838 // This loads our view configuration for each view so for a stereo HMD, we'll get two entries (that are likely identical)
839 // The returned data supplies us with the recommended render target size
840
841 if (!is_view_configuration_supported(p_configuration_type)) {
842 print_line("OpenXR: View configuration ", OpenXRUtil::get_view_configuration_name(view_configuration), " is not supported.");
843 return false;
844 }
845
846 if (!view_configuration_views.is_empty()) {
847 // free previous results
848 view_configuration_views.clear();
849 }
850
851 uint32_t view_count = 0;
852 XrResult result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, 0, &view_count, nullptr);
853 if (XR_FAILED(result)) {
854 print_line("OpenXR: Failed to get view configuration count [", get_error_string(result), "]");
855 return false;
856 }
857
858 view_configuration_views.resize(view_count);
859 for (OpenXRExtensionWrapper *extension : registered_extension_wrappers) {
860 extension->prepare_view_configuration(view_count);
861 }
862
863 uint32_t view = 0;
864 for (XrViewConfigurationView &view_configuration_view : view_configuration_views) {
865 view_configuration_view.type = XR_TYPE_VIEW_CONFIGURATION_VIEW;
866 view_configuration_view.next = nullptr;
867
868 for (OpenXRExtensionWrapper *extension : registered_extension_wrappers) {
869 void *np = extension->set_view_configuration_and_get_next_pointer(view, view_configuration_view.next);
870 if (np != nullptr) {
871 view_configuration_view.next = np;
872 }
873 }
874
875 view++;
876 }
877
878 result = xrEnumerateViewConfigurationViews(instance, system_id, p_configuration_type, view_count, &view_count, view_configuration_views.ptr());
879 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate view configurations");
880
881 if (is_print_verbose_enabled()) {
882 view = 0;
883 for (const XrViewConfigurationView &view_configuration_view : view_configuration_views) {
884 print_line("OpenXR: Found supported view configuration view");
885 print_line(" - width: ", itos(view_configuration_view.maxImageRectWidth));
886 print_line(" - height: ", itos(view_configuration_view.maxImageRectHeight));
887 print_line(" - sample count: ", itos(view_configuration_view.maxSwapchainSampleCount));
888 print_line(" - recommended render width: ", itos(view_configuration_view.recommendedImageRectWidth));
889 print_line(" - recommended render height: ", itos(view_configuration_view.recommendedImageRectHeight));
890 print_line(" - recommended render sample count: ", itos(view_configuration_view.recommendedSwapchainSampleCount));
891
892 for (OpenXRExtensionWrapper *extension : registered_extension_wrappers) {
893 extension->print_view_configuration_info(view);
894 }
895
896 view++;
897 }
898 }
899
900 return true;
901 }
902
903 void OpenXRAPI::destroy_instance() {
904 view_configuration_views.clear();
905 supported_view_configuration_types.clear();
906 supported_environment_blend_modes.clear();
907
908 if (instance != XR_NULL_HANDLE) {
909 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
910 wrapper->on_instance_destroyed();
911 }
912
913 xrDestroyInstance(instance);
914 instance = XR_NULL_HANDLE;
915 }
916 enabled_extensions.clear();
917
918 if (graphics_extension != nullptr) {
919 unregister_extension_wrapper(graphics_extension);
920 memdelete(graphics_extension);
921 graphics_extension = nullptr;
922 }
923 }
924
925 bool OpenXRAPI::create_session() {
926 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
927 ERR_FAIL_COND_V(session != XR_NULL_HANDLE, false);
928
929 void *next_pointer = nullptr;
930 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
931 void *np = wrapper->set_session_create_and_get_next_pointer(next_pointer);
932 if (np != nullptr) {
933 next_pointer = np;
934 }
935 }
936
937 XrSessionCreateInfo session_create_info = {
938 XR_TYPE_SESSION_CREATE_INFO, // type
939 next_pointer, // next
940 0, // createFlags
941 system_id // systemId
942 };
943
944 XrResult result = xrCreateSession(instance, &session_create_info, &session);
945 if (XR_FAILED(result)) {
946 print_line("OpenXR: Failed to create session [", get_error_string(result), "]");
947 return false;
948 }
949
950 set_object_name(XR_OBJECT_TYPE_SESSION, uint64_t(session), "Main Godot OpenXR Session");
951
952 begin_debug_label_region("Godot session active");
953
954 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
955 wrapper->on_session_created(session);
956 }
957
958 // Check our environment blend mode. This needs to happen after we call `on_session_created()`
959 // on the extension wrappers, so they can emulate alpha blend mode.
960 if (!set_environment_blend_mode(environment_blend_mode)) {
961 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]));
962 set_environment_blend_mode(supported_environment_blend_modes[0]);
963 }
964
965 return true;
966 }
967
968 bool OpenXRAPI::load_supported_reference_spaces() {
969 // loads the supported reference spaces for our OpenXR session
970
971 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
972
973 supported_reference_spaces.clear();
974
975 uint32_t num_reference_spaces = 0;
976 XrResult result = xrEnumerateReferenceSpaces(session, 0, &num_reference_spaces, nullptr);
977 if (XR_FAILED(result)) {
978 print_line("OpenXR: Failed to get reference space count [", get_error_string(result), "]");
979 return false;
980 }
981
982 supported_reference_spaces.resize(num_reference_spaces);
983
984 result = xrEnumerateReferenceSpaces(session, num_reference_spaces, &num_reference_spaces, supported_reference_spaces.ptr());
985 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate reference spaces");
986 ERR_FAIL_COND_V_MSG(num_reference_spaces == 0, false, "OpenXR: Failed to enumerate reference spaces");
987
988 for (const XrReferenceSpaceType &supported_reference_space : supported_reference_spaces) {
989 print_verbose(vformat("OpenXR: Found supported reference space %s.", OpenXRUtil::get_reference_space_name(supported_reference_space)));
990 }
991
992 return true;
993 }
994
995 bool OpenXRAPI::is_reference_space_supported(XrReferenceSpaceType p_reference_space) {
996 return supported_reference_spaces.has(p_reference_space);
997 }
998
999 bool OpenXRAPI::setup_play_space() {
1000 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
1001
1002 XrPosef identityPose = {
1003 { 0.0, 0.0, 0.0, 1.0 },
1004 { 0.0, 0.0, 0.0 }
1005 };
1006
1007 XrReferenceSpaceType new_reference_space;
1008 XrSpace new_play_space = XR_NULL_HANDLE;
1009 bool will_emulate_local_floor = false;
1010
1011 if (custom_play_space != XR_NULL_HANDLE) {
1012 new_play_space = custom_play_space;
1013 // We use this to mark custom reference spaces.
1014 new_reference_space = XR_REFERENCE_SPACE_TYPE_MAX_ENUM;
1015 } else if (is_reference_space_supported(requested_reference_space)) {
1016 new_reference_space = requested_reference_space;
1017 } else if (requested_reference_space == XR_REFERENCE_SPACE_TYPE_LOCAL_FLOOR_EXT && is_reference_space_supported(XR_REFERENCE_SPACE_TYPE_STAGE)) {
1018 // Note, in OpenXR 1.0 XR_EXT_LOCAL_FLOOR_EXTENSION_NAME needs to be enabled
1019 // but from OpenXR 1.1 onwards this should always be available.
1020 print_verbose("OpenXR: LOCAL_FLOOR space isn't supported, emulating using STAGE and LOCAL spaces.");
1021
1022 new_reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
1023 will_emulate_local_floor = true;
1024
1025 if (local_floor_emulation.local_space == XR_NULL_HANDLE) {
1026 XrReferenceSpaceCreateInfo create_info = {
1027 XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
1028 nullptr, // next
1029 XR_REFERENCE_SPACE_TYPE_LOCAL, // referenceSpaceType
1030 identityPose, // poseInReferenceSpace
1031 };
1032
1033 XrResult result = xrCreateReferenceSpace(session, &create_info, &local_floor_emulation.local_space);
1034 if (XR_FAILED(result)) {
1035 print_line("OpenXR: Failed to create LOCAL space in order to emulate LOCAL_FLOOR [", get_error_string(result), "]");
1036 will_emulate_local_floor = false;
1037 }
1038
1039 set_object_name(XR_OBJECT_TYPE_SPACE, uint64_t(local_floor_emulation.local_space), "Emulation local space");
1040 }
1041
1042 if (local_floor_emulation.stage_space == XR_NULL_HANDLE) {
1043 XrReferenceSpaceCreateInfo create_info = {
1044 XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
1045 nullptr, // next
1046 XR_REFERENCE_SPACE_TYPE_STAGE, // referenceSpaceType
1047 identityPose, // poseInReferenceSpace
1048 };
1049
1050 XrResult result = xrCreateReferenceSpace(session, &create_info, &local_floor_emulation.stage_space);
1051 if (XR_FAILED(result)) {
1052 print_line("OpenXR: Failed to create STAGE space in order to emulate LOCAL_FLOOR [", get_error_string(result), "]");
1053 will_emulate_local_floor = false;
1054 }
1055
1056 set_object_name(XR_OBJECT_TYPE_SPACE, uint64_t(local_floor_emulation.stage_space), "Emulation stage space");
1057 }
1058
1059 if (!will_emulate_local_floor) {
1060 if (local_floor_emulation.local_space != XR_NULL_HANDLE) {
1061 xrDestroySpace(local_floor_emulation.local_space);
1062 local_floor_emulation.local_space = XR_NULL_HANDLE;
1063 }
1064 if (local_floor_emulation.stage_space != XR_NULL_HANDLE) {
1065 xrDestroySpace(local_floor_emulation.stage_space);
1066 local_floor_emulation.stage_space = XR_NULL_HANDLE;
1067 }
1068 }
1069 } else {
1070 // Fallback on LOCAL, which all OpenXR runtimes are required to support.
1071 print_verbose(String("OpenXR: ") + OpenXRUtil::get_reference_space_name(requested_reference_space) + String(" isn't supported, defaulting to LOCAL space."));
1072 new_reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
1073 }
1074
1075 if (new_play_space == XR_NULL_HANDLE) {
1076 void *next_pointer = nullptr;
1077 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1078 void *np = wrapper->set_reference_space_create_info_and_get_next_pointer(
1079 new_reference_space, next_pointer);
1080 if (np != nullptr) {
1081 next_pointer = np;
1082 }
1083 }
1084
1085 XrReferenceSpaceCreateInfo play_space_create_info = {
1086 XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
1087 next_pointer, // next
1088 new_reference_space, // referenceSpaceType
1089 identityPose, // poseInReferenceSpace
1090 };
1091
1092 XrResult result = xrCreateReferenceSpace(session, &play_space_create_info, &new_play_space);
1093 if (XR_FAILED(result)) {
1094 print_line("OpenXR: Failed to create play space [", get_error_string(result), "]");
1095 return false;
1096 }
1097 }
1098
1099 // If we've previously created a play space, clean it up first.
1100 // But if it was a custom reference space, we don't touch it - it's the job of the extension that
1101 // created it to clean it up.
1102 if (play_space != XR_NULL_HANDLE && reference_space != XR_REFERENCE_SPACE_TYPE_MAX_ENUM) {
1103 // TODO Investigate if destroying our play space here is safe,
1104 // it may still be used in the rendering thread.
1105
1106 xrDestroySpace(play_space);
1107 }
1108 play_space = new_play_space;
1109 reference_space = new_reference_space;
1110
1111 set_object_name(XR_OBJECT_TYPE_SPACE, uint64_t(play_space), "Play space");
1112
1113 local_floor_emulation.enabled = will_emulate_local_floor;
1114 local_floor_emulation.should_reset_floor_height = will_emulate_local_floor;
1115
1116 // Update render state so this play space is used rendering the upcoming frame.
1117 set_render_play_space(play_space);
1118
1119 return true;
1120 }
1121
1122 bool OpenXRAPI::setup_view_space() {
1123 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
1124
1125 if (!is_reference_space_supported(XR_REFERENCE_SPACE_TYPE_VIEW)) {
1126 print_line("OpenXR: reference space XR_REFERENCE_SPACE_TYPE_VIEW is not supported.");
1127 return false;
1128 }
1129
1130 XrPosef identityPose = {
1131 { 0.0, 0.0, 0.0, 1.0 },
1132 { 0.0, 0.0, 0.0 }
1133 };
1134
1135 void *next_pointer = nullptr;
1136 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1137 void *np = wrapper->set_reference_space_create_info_and_get_next_pointer(XR_REFERENCE_SPACE_TYPE_VIEW, next_pointer);
1138 if (np != nullptr) {
1139 next_pointer = np;
1140 }
1141 }
1142
1143 XrReferenceSpaceCreateInfo view_space_create_info = {
1144 XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
1145 next_pointer, // next
1146 XR_REFERENCE_SPACE_TYPE_VIEW, // referenceSpaceType
1147 identityPose // poseInReferenceSpace
1148 };
1149
1150 XrResult result = xrCreateReferenceSpace(session, &view_space_create_info, &view_space);
1151 if (XR_FAILED(result)) {
1152 print_line("OpenXR: Failed to create view space [", get_error_string(result), "]");
1153 return false;
1154 }
1155
1156 set_object_name(XR_OBJECT_TYPE_SPACE, uint64_t(view_space), "View space");
1157
1158 return true;
1159 }
1160
1161 bool OpenXRAPI::reset_emulated_floor_height() {
1162 ERR_FAIL_COND_V(!local_floor_emulation.enabled, false);
1163 ERR_FAIL_COND_V(local_floor_emulation.local_space == XR_NULL_HANDLE, false);
1164 ERR_FAIL_COND_V(local_floor_emulation.stage_space == XR_NULL_HANDLE, false);
1165
1166 XrResult result;
1167
1168 XrSpaceLocation stage_location = {
1169 XR_TYPE_SPACE_LOCATION, // type
1170 nullptr, // next
1171 0, // locationFlags
1172 { { 0.0, 0.0, 0.0, 1.0 }, { 0.0, 0.0, 0.0 } }, // pose
1173 };
1174
1175 result = xrLocateSpace(local_floor_emulation.stage_space, local_floor_emulation.local_space, get_predicted_display_time(), &stage_location);
1176
1177 if (XR_FAILED(result)) {
1178 print_line("OpenXR: Failed to locate STAGE space in LOCAL space, in order to emulate LOCAL_FLOOR [", get_error_string(result), "]");
1179 return false;
1180 }
1181
1182 XrPosef pose = {
1183 { 0.0, 0.0, 0.0, 1.0 },
1184 { 0.0, stage_location.pose.position.y, 0.0 }
1185 };
1186
1187 XrReferenceSpaceCreateInfo create_info = {
1188 XR_TYPE_REFERENCE_SPACE_CREATE_INFO, // type
1189 nullptr, // next
1190 XR_REFERENCE_SPACE_TYPE_LOCAL, // referenceSpaceType
1191 pose, // poseInReferenceSpace
1192 };
1193
1194 XrSpace new_play_space;
1195
1196 void *next_pointer = nullptr;
1197 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1198 void *np = wrapper->set_reference_space_create_info_and_get_next_pointer(
1199 create_info.referenceSpaceType, next_pointer);
1200 if (np != nullptr) {
1201 next_pointer = np;
1202 }
1203 }
1204 create_info.next = next_pointer;
1205
1206 result = xrCreateReferenceSpace(session, &create_info, &new_play_space);
1207 if (XR_FAILED(result)) {
1208 print_line("OpenXR: Failed to recreate emulated LOCAL_FLOOR play space with latest floor estimate [", get_error_string(result), "]");
1209 return false;
1210 }
1211
1212 xrDestroySpace(play_space);
1213 play_space = new_play_space;
1214
1215 // If we've made it this far, it means we can properly emulate LOCAL_FLOOR, so we'll
1216 // report that as the reference space to the outside world.
1217 reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL_FLOOR_EXT;
1218
1219 // Update render state so this play space is used rendering the upcoming frame.
1220 set_render_play_space(play_space);
1221
1222 return true;
1223 }
1224
1225 bool OpenXRAPI::load_supported_swapchain_formats() {
1226 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
1227
1228 supported_swapchain_formats.clear();
1229
1230 uint32_t num_swapchain_formats = 0;
1231 XrResult result = xrEnumerateSwapchainFormats(session, 0, &num_swapchain_formats, nullptr);
1232 if (XR_FAILED(result)) {
1233 print_line("OpenXR: Failed to get swapchain format count [", get_error_string(result), "]");
1234 return false;
1235 }
1236
1237 supported_swapchain_formats.resize(num_swapchain_formats);
1238
1239 result = xrEnumerateSwapchainFormats(session, num_swapchain_formats, &num_swapchain_formats, supported_swapchain_formats.ptrw());
1240 ERR_FAIL_COND_V_MSG(XR_FAILED(result), false, "OpenXR: Failed to enumerate swapchain formats");
1241
1242 for (int64_t swapchain_format : supported_swapchain_formats) {
1243 print_verbose(String("OpenXR: Found supported swapchain format ") + get_swapchain_format_name(swapchain_format));
1244 }
1245
1246 return true;
1247 }
1248
1249 bool OpenXRAPI::is_swapchain_format_supported(int64_t p_swapchain_format) {
1250 return supported_swapchain_formats.has(p_swapchain_format);
1251 }
1252
1253 bool OpenXRAPI::obtain_swapchain_formats() {
1254 ERR_FAIL_NULL_V(graphics_extension, false);
1255 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
1256
1257 {
1258 // Build a vector with swapchain formats we want to use, from best fit to worst
1259 Vector<int64_t> usable_swapchain_formats;
1260 color_swapchain_format = 0;
1261
1262 graphics_extension->get_usable_swapchain_formats(usable_swapchain_formats);
1263
1264 // now find out which one is supported
1265 for (int i = 0; i < usable_swapchain_formats.size() && color_swapchain_format == 0; i++) {
1266 if (is_swapchain_format_supported(usable_swapchain_formats[i])) {
1267 color_swapchain_format = usable_swapchain_formats[i];
1268 }
1269 }
1270
1271 ERR_FAIL_COND_V_MSG(color_swapchain_format == 0, false, "OpenXR: No usable color swap chain format available!");
1272
1273 print_verbose(String("Using color swap chain format:") + get_swapchain_format_name(color_swapchain_format));
1274 }
1275
1276 {
1277 // Build a vector with swapchain formats we want to use, from best fit to worst
1278 Vector<int64_t> usable_swapchain_formats;
1279 depth_swapchain_format = 0;
1280
1281 graphics_extension->get_usable_depth_formats(usable_swapchain_formats);
1282
1283 // now find out which one is supported
1284 for (int i = 0; i < usable_swapchain_formats.size() && depth_swapchain_format == 0; i++) {
1285 if (is_swapchain_format_supported(usable_swapchain_formats[i])) {
1286 depth_swapchain_format = usable_swapchain_formats[i];
1287 }
1288 }
1289
1290 ERR_FAIL_COND_V_MSG(depth_swapchain_format == 0, false, "OpenXR: No usable depth swap chain format available!");
1291
1292 print_verbose(String("Using depth swap chain format:") + get_swapchain_format_name(depth_swapchain_format));
1293 }
1294
1295 return true;
1296 }
1297
1298 bool OpenXRAPI::create_main_swapchains(const Size2i &p_size) {
1299 ERR_NOT_ON_RENDER_THREAD_V(false);
1300 ERR_FAIL_NULL_V(graphics_extension, false);
1301 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
1302
1303 /*
1304 TODO: We need to improve on this, for now we're taking our old approach of creating our main swapchains and substituting
1305 those for the ones Godot normally creates.
1306 This however means we can only use swapchains for our main XR view.
1307
1308 It would have been nicer if we could override the swapchain creation in Godot with ours but we have a timing issue here.
1309 We can't create XR swapchains until after our XR session is fully instantiated, yet Godot creates its swapchain much earlier.
1310
1311 We only creates a swapchain for the main output here.
1312 Additional swapchains may be created through our composition layer extension.
1313
1314 Finally an area we need to expand upon is that Foveated rendering is only enabled for the swap chain we create,
1315 as we render 3D content into internal buffers that are copied into the swapchain, we do now have (basic) VRS support
1316 */
1317
1318 render_state.main_swapchain_size = p_size;
1319 uint32_t sample_count = 1;
1320
1321 // We start with our color swapchain...
1322 if (color_swapchain_format != 0) {
1323 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_configuration_views.size())) {
1324 return false;
1325 }
1326
1327 set_object_name(XR_OBJECT_TYPE_SWAPCHAIN, uint64_t(render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].get_swapchain()), "Main color swapchain");
1328 }
1329
1330 // We create our depth swapchain if:
1331 // - we've enabled submitting depth buffer
1332 // - we support our depth layer extension
1333 // - we have our spacewarp extension (not yet implemented)
1334 if (depth_swapchain_format != 0 && submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available()) {
1335 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_configuration_views.size())) {
1336 return false;
1337 }
1338
1339 set_object_name(XR_OBJECT_TYPE_SWAPCHAIN, uint64_t(render_state.main_swapchains[OPENXR_SWAPCHAIN_DEPTH].get_swapchain()), "Main depth swapchain");
1340 }
1341
1342 // We create our velocity swapchain if:
1343 // - we have our spacewarp extension (not yet implemented)
1344 {
1345 // TBD
1346 }
1347
1348 for (uint32_t i = 0; i < render_state.views.size(); i++) {
1349 render_state.projection_views[i].subImage.swapchain = render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].get_swapchain();
1350 render_state.projection_views[i].subImage.imageArrayIndex = i;
1351 render_state.projection_views[i].subImage.imageRect.offset.x = 0;
1352 render_state.projection_views[i].subImage.imageRect.offset.y = 0;
1353 render_state.projection_views[i].subImage.imageRect.extent.width = render_state.main_swapchain_size.width;
1354 render_state.projection_views[i].subImage.imageRect.extent.height = render_state.main_swapchain_size.height;
1355
1356 if (render_state.submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available() && !render_state.depth_views.is_empty()) {
1357 render_state.depth_views[i].subImage.swapchain = render_state.main_swapchains[OPENXR_SWAPCHAIN_DEPTH].get_swapchain();
1358 render_state.depth_views[i].subImage.imageArrayIndex = i;
1359 render_state.depth_views[i].subImage.imageRect.offset.x = 0;
1360 render_state.depth_views[i].subImage.imageRect.offset.y = 0;
1361 render_state.depth_views[i].subImage.imageRect.extent.width = render_state.main_swapchain_size.width;
1362 render_state.depth_views[i].subImage.imageRect.extent.height = render_state.main_swapchain_size.height;
1363 // OpenXR spec says that: minDepth < maxDepth.
1364 render_state.depth_views[i].minDepth = 0.0;
1365 render_state.depth_views[i].maxDepth = 1.0;
1366 // But we can reverse near and far for reverse-Z.
1367 render_state.depth_views[i].nearZ = 100.0; // Near and far Z will be set to the correct values in fill_projection_matrix
1368 render_state.depth_views[i].farZ = 0.01;
1369 }
1370 };
1371
1372 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1373 wrapper->on_main_swapchains_created();
1374 }
1375
1376 return true;
1377 }
1378
1379 void OpenXRAPI::destroy_session() {
1380 // TODO need to figure out if we're still rendering our current frame
1381 // in a separate rendering thread and if so,
1382 // if we need to wait for completion.
1383 // We could be pulling the rug from underneath rendering...
1384
1385 if (running) {
1386 if (session != XR_NULL_HANDLE) {
1387 xrEndSession(session);
1388 }
1389
1390 running = false;
1391 render_state.running = false;
1392 }
1393
1394 render_state.views.clear();
1395 render_state.projection_views.clear();
1396 render_state.depth_views.clear();
1397
1398 free_main_swapchains();
1399 OpenXRSwapChainInfo::free_queued();
1400
1401 supported_swapchain_formats.clear();
1402
1403 // destroy our spaces
1404 if (play_space != XR_NULL_HANDLE) {
1405 xrDestroySpace(play_space);
1406 play_space = XR_NULL_HANDLE;
1407 render_state.play_space = XR_NULL_HANDLE;
1408 }
1409 if (view_space != XR_NULL_HANDLE) {
1410 xrDestroySpace(view_space);
1411 view_space = XR_NULL_HANDLE;
1412 }
1413 if (local_floor_emulation.local_space != XR_NULL_HANDLE) {
1414 xrDestroySpace(local_floor_emulation.local_space);
1415 local_floor_emulation.local_space = XR_NULL_HANDLE;
1416 }
1417 if (local_floor_emulation.stage_space != XR_NULL_HANDLE) {
1418 xrDestroySpace(local_floor_emulation.stage_space);
1419 local_floor_emulation.stage_space = XR_NULL_HANDLE;
1420 }
1421 local_floor_emulation.enabled = false;
1422 local_floor_emulation.should_reset_floor_height = false;
1423
1424 supported_reference_spaces.clear();
1425
1426 if (session != XR_NULL_HANDLE) {
1427 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1428 wrapper->on_session_destroyed();
1429 }
1430
1431 // Rerun this just in case any of our extensions freed up swapchains.
1432 OpenXRSwapChainInfo::free_queued();
1433
1434 end_debug_label_region();
1435
1436 xrDestroySession(session);
1437 session = XR_NULL_HANDLE;
1438 }
1439 }
1440
1441 bool OpenXRAPI::on_state_idle() {
1442 print_verbose("On state idle");
1443
1444 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1445 wrapper->on_state_idle();
1446 }
1447
1448 return true;
1449 }
1450
1451 bool OpenXRAPI::on_state_ready() {
1452 print_verbose("On state ready");
1453
1454 // begin session
1455 XrSessionBeginInfo session_begin_info = {
1456 XR_TYPE_SESSION_BEGIN_INFO, // type
1457 nullptr, // next
1458 view_configuration // primaryViewConfigurationType
1459 };
1460
1461 XrResult result = xrBeginSession(session, &session_begin_info);
1462 if (XR_FAILED(result)) {
1463 print_line("OpenXR: Failed to begin session [", get_error_string(result), "]");
1464 return false;
1465 }
1466
1467 // we're running
1468 running = true;
1469 set_render_session_running(true);
1470
1471 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1472 wrapper->on_state_ready();
1473 }
1474
1475 if (xr_interface) {
1476 xr_interface->on_state_ready();
1477 }
1478
1479 return true;
1480 }
1481
1482 bool OpenXRAPI::on_state_synchronized() {
1483 print_verbose("On state synchronized");
1484
1485 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1486 wrapper->on_state_synchronized();
1487 }
1488
1489 if (xr_interface) {
1490 xr_interface->on_state_synchronized();
1491 }
1492
1493 return true;
1494 }
1495
1496 bool OpenXRAPI::on_state_visible() {
1497 print_verbose("On state visible");
1498
1499 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1500 wrapper->on_state_visible();
1501 }
1502
1503 if (xr_interface) {
1504 xr_interface->on_state_visible();
1505 }
1506
1507 return true;
1508 }
1509
1510 bool OpenXRAPI::on_state_focused() {
1511 print_verbose("On state focused");
1512
1513 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1514 wrapper->on_state_focused();
1515 }
1516
1517 if (xr_interface) {
1518 xr_interface->on_state_focused();
1519 }
1520
1521 return true;
1522 }
1523
1524 bool OpenXRAPI::on_state_stopping() {
1525 print_verbose("On state stopping");
1526
1527 if (xr_interface) {
1528 xr_interface->on_state_stopping();
1529 }
1530
1531 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1532 wrapper->on_state_stopping();
1533 }
1534
1535 if (running) {
1536 XrResult result = xrEndSession(session);
1537 if (XR_FAILED(result)) {
1538 // we only report this..
1539 print_line("OpenXR: Failed to end session [", get_error_string(result), "]");
1540 }
1541
1542 running = false;
1543 set_render_session_running(false);
1544 }
1545
1546 return true;
1547 }
1548
1549 bool OpenXRAPI::on_state_loss_pending() {
1550 print_verbose("On state loss pending");
1551
1552 if (xr_interface) {
1553 xr_interface->on_state_loss_pending();
1554 }
1555
1556 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1557 wrapper->on_state_loss_pending();
1558 }
1559
1560 return true;
1561 }
1562
1563 bool OpenXRAPI::on_state_exiting() {
1564 print_verbose("On state existing");
1565
1566 if (xr_interface) {
1567 xr_interface->on_state_exiting();
1568 }
1569
1570 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1571 wrapper->on_state_exiting();
1572 }
1573
1574 return true;
1575 }
1576
1577 void OpenXRAPI::set_form_factor(XrFormFactor p_form_factor) {
1578 ERR_FAIL_COND(is_initialized());
1579
1580 form_factor = p_form_factor;
1581 }
1582
1583 uint32_t OpenXRAPI::get_view_count() {
1584 return view_configuration_views.size();
1585 }
1586
1587 void OpenXRAPI::set_view_configuration(XrViewConfigurationType p_view_configuration) {
1588 ERR_FAIL_COND(is_initialized());
1589
1590 view_configuration = p_view_configuration;
1591 }
1592
1593 bool OpenXRAPI::set_requested_reference_space(XrReferenceSpaceType p_requested_reference_space) {
1594 if (custom_play_space != XR_NULL_HANDLE) {
1595 return false;
1596 }
1597
1598 requested_reference_space = p_requested_reference_space;
1599 play_space_is_dirty = true;
1600
1601 return true;
1602 }
1603
1604 void OpenXRAPI::set_custom_play_space(XrSpace p_custom_space) {
1605 custom_play_space = p_custom_space;
1606 play_space_is_dirty = true;
1607 }
1608
1609 void OpenXRAPI::set_submit_depth_buffer(bool p_submit_depth_buffer) {
1610 ERR_FAIL_COND(is_initialized());
1611
1612 submit_depth_buffer = p_submit_depth_buffer;
1613 }
1614
1615 bool OpenXRAPI::is_initialized() {
1616 return (instance != XR_NULL_HANDLE);
1617 }
1618
1619 bool OpenXRAPI::is_running() {
1620 if (instance == XR_NULL_HANDLE) {
1621 return false;
1622 }
1623 if (session == XR_NULL_HANDLE) {
1624 return false;
1625 }
1626
1627 return running;
1628 }
1629
1630 bool OpenXRAPI::openxr_loader_init() {
1631 #ifdef ANDROID_ENABLED
1632 ERR_FAIL_COND_V_MSG(openxr_loader_library_handle != nullptr, false, "OpenXR Loader library is already loaded.");
1633
1634 {
1635 Error error_code = OS::get_singleton()->open_dynamic_library(OPENXR_LOADER_NAME, openxr_loader_library_handle);
1636 ERR_FAIL_COND_V_MSG(error_code != OK, false, "OpenXR loader not found.");
1637 }
1638
1639 {
1640 Error error_code = OS::get_singleton()->get_dynamic_library_symbol_handle(openxr_loader_library_handle, "xrGetInstanceProcAddr", (void *&)xrGetInstanceProcAddr);
1641 ERR_FAIL_COND_V_MSG(error_code != OK, false, "Symbol xrGetInstanceProcAddr not found in OpenXR Loader library.");
1642 }
1643 #endif
1644
1645 // Resolve the symbols that don't require an instance
1646 OPENXR_API_INIT_XR_FUNC_V(xrCreateInstance);
1647 OPENXR_API_INIT_XR_FUNC_V(xrEnumerateApiLayerProperties);
1648 OPENXR_API_INIT_XR_FUNC_V(xrEnumerateInstanceExtensionProperties);
1649
1650 return true;
1651 }
1652
1653 bool OpenXRAPI::resolve_instance_openxr_symbols() {
1654 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
1655
1656 OPENXR_API_INIT_XR_FUNC_V(xrAcquireSwapchainImage);
1657 OPENXR_API_INIT_XR_FUNC_V(xrApplyHapticFeedback);
1658 OPENXR_API_INIT_XR_FUNC_V(xrAttachSessionActionSets);
1659 OPENXR_API_INIT_XR_FUNC_V(xrBeginFrame);
1660 OPENXR_API_INIT_XR_FUNC_V(xrBeginSession);
1661 OPENXR_API_INIT_XR_FUNC_V(xrCreateAction);
1662 OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSet);
1663 OPENXR_API_INIT_XR_FUNC_V(xrCreateActionSpace);
1664 OPENXR_API_INIT_XR_FUNC_V(xrCreateReferenceSpace);
1665 OPENXR_API_INIT_XR_FUNC_V(xrCreateSession);
1666 OPENXR_API_INIT_XR_FUNC_V(xrCreateSwapchain);
1667 OPENXR_API_INIT_XR_FUNC_V(xrDestroyAction);
1668 OPENXR_API_INIT_XR_FUNC_V(xrDestroyActionSet);
1669 OPENXR_API_INIT_XR_FUNC_V(xrDestroyInstance);
1670 OPENXR_API_INIT_XR_FUNC_V(xrDestroySession);
1671 OPENXR_API_INIT_XR_FUNC_V(xrDestroySpace);
1672 OPENXR_API_INIT_XR_FUNC_V(xrDestroySwapchain);
1673 OPENXR_API_INIT_XR_FUNC_V(xrEndFrame);
1674 OPENXR_API_INIT_XR_FUNC_V(xrEndSession);
1675 OPENXR_API_INIT_XR_FUNC_V(xrEnumerateEnvironmentBlendModes);
1676 OPENXR_API_INIT_XR_FUNC_V(xrEnumerateReferenceSpaces);
1677 OPENXR_API_INIT_XR_FUNC_V(xrEnumerateSwapchainFormats);
1678 OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurations);
1679 OPENXR_API_INIT_XR_FUNC_V(xrEnumerateViewConfigurationViews);
1680 OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateBoolean);
1681 OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateFloat);
1682 OPENXR_API_INIT_XR_FUNC_V(xrGetActionStateVector2f);
1683 OPENXR_API_INIT_XR_FUNC_V(xrGetCurrentInteractionProfile);
1684 OPENXR_API_INIT_XR_FUNC_V(xrGetReferenceSpaceBoundsRect);
1685 OPENXR_API_INIT_XR_FUNC_V(xrGetSystem);
1686 OPENXR_API_INIT_XR_FUNC_V(xrGetSystemProperties);
1687 OPENXR_API_INIT_XR_FUNC_V(xrLocateViews);
1688 OPENXR_API_INIT_XR_FUNC_V(xrLocateSpace);
1689 OPENXR_API_INIT_XR_FUNC_V(xrPathToString);
1690 OPENXR_API_INIT_XR_FUNC_V(xrPollEvent);
1691 OPENXR_API_INIT_XR_FUNC_V(xrReleaseSwapchainImage);
1692 OPENXR_API_INIT_XR_FUNC_V(xrResultToString);
1693 OPENXR_API_INIT_XR_FUNC_V(xrStringToPath);
1694 OPENXR_API_INIT_XR_FUNC_V(xrSuggestInteractionProfileBindings);
1695 OPENXR_API_INIT_XR_FUNC_V(xrSyncActions);
1696 OPENXR_API_INIT_XR_FUNC_V(xrWaitFrame);
1697 OPENXR_API_INIT_XR_FUNC_V(xrWaitSwapchainImage);
1698
1699 return true;
1700 }
1701
1702 XrResult OpenXRAPI::try_get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) {
1703 return xrGetInstanceProcAddr(instance, p_name, p_addr);
1704 }
1705
1706 XrResult OpenXRAPI::get_instance_proc_addr(const char *p_name, PFN_xrVoidFunction *p_addr) {
1707 XrResult result = try_get_instance_proc_addr(p_name, p_addr);
1708
1709 if (result != XR_SUCCESS) {
1710 String error_message = String("Symbol ") + p_name + " not found in OpenXR instance.";
1711 ERR_FAIL_V_MSG(result, error_message.utf8().get_data());
1712 }
1713
1714 return result;
1715 }
1716
1717 bool OpenXRAPI::initialize(const String &p_rendering_driver) {
1718 ERR_FAIL_COND_V_MSG(instance != XR_NULL_HANDLE, false, "OpenXR instance was already created");
1719
1720 if (!openxr_loader_init()) {
1721 return false;
1722 }
1723
1724 if (p_rendering_driver == "vulkan") {
1725 #ifdef VULKAN_ENABLED
1726 graphics_extension = memnew(OpenXRVulkanExtension);
1727 register_extension_wrapper(graphics_extension);
1728 #else
1729 // shouldn't be possible...
1730 ERR_FAIL_V(false);
1731 #endif
1732 } else if (p_rendering_driver == "metal") {
1733 #ifdef METAL_ENABLED
1734 graphics_extension = memnew(OpenXRMetalExtension);
1735 register_extension_wrapper(graphics_extension);
1736 #else
1737 // shouldn't be possible...
1738 ERR_FAIL_V(false);
1739 #endif
1740 } else if (p_rendering_driver == "opengl3") {
1741 #if defined(GLES3_ENABLED) && !defined(MACOS_ENABLED)
1742 graphics_extension = memnew(OpenXROpenGLExtension);
1743 register_extension_wrapper(graphics_extension);
1744 #else
1745 // shouldn't be possible...
1746 ERR_FAIL_V(false);
1747 #endif
1748 } else if (p_rendering_driver == "d3d12") {
1749 #ifdef D3D12_ENABLED
1750 graphics_extension = memnew(OpenXRD3D12Extension);
1751 register_extension_wrapper(graphics_extension);
1752 #else
1753 // shouldn't be possible...
1754 ERR_FAIL_V(false);
1755 #endif
1756 } else {
1757 ERR_FAIL_V_MSG(false, "OpenXR: Unsupported rendering device.");
1758 }
1759
1760 // Also register our rendering extensions
1761 register_extension_wrapper(memnew(OpenXRFBUpdateSwapchainExtension(p_rendering_driver)));
1762 register_extension_wrapper(memnew(OpenXRFBFoveationExtension(p_rendering_driver)));
1763
1764 // initialize
1765 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
1766 wrapper->on_before_instance_created();
1767 }
1768
1769 if (!load_layer_properties()) {
1770 destroy_instance();
1771 return false;
1772 }
1773
1774 if (!load_supported_extensions()) {
1775 destroy_instance();
1776 return false;
1777 }
1778
1779 if (!create_instance()) {
1780 destroy_instance();
1781 return false;
1782 }
1783
1784 if (!resolve_instance_openxr_symbols()) {
1785 destroy_instance();
1786 return false;
1787 }
1788
1789 if (!get_system_info()) {
1790 destroy_instance();
1791 return false;
1792 }
1793
1794 if (!load_supported_view_configuration_types()) {
1795 destroy_instance();
1796 return false;
1797 }
1798
1799 if (!load_supported_view_configuration_views(view_configuration)) {
1800 destroy_instance();
1801 return false;
1802 }
1803
1804 if (!load_supported_environmental_blend_modes()) {
1805 destroy_instance();
1806 return false;
1807 }
1808
1809 return true;
1810 }
1811
1812 bool OpenXRAPI::initialize_session() {
1813 if (!create_session()) {
1814 destroy_session();
1815 return false;
1816 }
1817
1818 if (!load_supported_reference_spaces()) {
1819 destroy_session();
1820 return false;
1821 }
1822
1823 if (!setup_view_space()) {
1824 destroy_session();
1825 return false;
1826 }
1827
1828 if (!load_supported_swapchain_formats()) {
1829 destroy_session();
1830 return false;
1831 }
1832
1833 if (!obtain_swapchain_formats()) {
1834 destroy_session();
1835 return false;
1836 }
1837
1838 allocate_view_buffers(view_configuration_views.size(), submit_depth_buffer);
1839
1840 return true;
1841 }
1842
1843 void OpenXRAPI::finish() {
1844 destroy_session();
1845
1846 destroy_instance();
1847 }
1848
1849 void OpenXRAPI::set_xr_interface(OpenXRInterface *p_xr_interface) {
1850 xr_interface = p_xr_interface;
1851 }
1852
1853 void OpenXRAPI::register_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
1854 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
1855 ERR_FAIL_COND_MSG(openxr_api && openxr_api->instance != XR_NULL_HANDLE, "Cannot register OpenXR extension wrappers after the OpenXR instance has been created.");
1856 registered_extension_wrappers.push_back(p_extension_wrapper);
1857 }
1858
1859 void OpenXRAPI::unregister_extension_wrapper(OpenXRExtensionWrapper *p_extension_wrapper) {
1860 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
1861 ERR_FAIL_COND_MSG(openxr_api && openxr_api->instance != XR_NULL_HANDLE, "Cannot unregister OpenXR extension wrappers after the OpenXR instance has been created.");
1862 registered_extension_wrappers.erase(p_extension_wrapper);
1863 }
1864
1865 const Vector<OpenXRExtensionWrapper *> &OpenXRAPI::get_registered_extension_wrappers() {
1866 return registered_extension_wrappers;
1867 }
1868
1869 void OpenXRAPI::register_extension_metadata() {
1870 for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
1871 extension_wrapper->on_register_metadata();
1872 }
1873 }
1874
1875 void OpenXRAPI::cleanup_extension_wrappers() {
1876 for (OpenXRExtensionWrapper *extension_wrapper : registered_extension_wrappers) {
1877 #ifndef DISABLE_DEPRECATED
1878 // Fix crash when the extension wrapper comes from GDExtension.
1879 OpenXRExtensionWrapperExtension *gdextension_extension_wrapper = dynamic_cast<OpenXRExtensionWrapperExtension *>(extension_wrapper);
1880 if (gdextension_extension_wrapper) {
1881 memdelete(gdextension_extension_wrapper);
1882 } else
1883 #endif
1884 {
1885 memdelete(extension_wrapper);
1886 }
1887 }
1888 registered_extension_wrappers.clear();
1889 }
1890
1891 XrHandTrackerEXT OpenXRAPI::get_hand_tracker(int p_hand_index) {
1892 ERR_FAIL_INDEX_V(p_hand_index, OpenXRHandTrackingExtension::HandTrackedHands::OPENXR_MAX_TRACKED_HANDS, XR_NULL_HANDLE);
1893
1894 OpenXRHandTrackingExtension *hand_tracking = OpenXRHandTrackingExtension::get_singleton();
1895 ERR_FAIL_NULL_V(hand_tracking, XR_NULL_HANDLE);
1896
1897 OpenXRHandTrackingExtension::HandTrackedHands hand = static_cast<OpenXRHandTrackingExtension::HandTrackedHands>(p_hand_index);
1898 return hand_tracking->get_hand_tracker(hand)->hand_tracker;
1899 }
1900
1901 Size2 OpenXRAPI::get_recommended_target_size() {
1902 RenderingServer *rendering_server = RenderingServer::get_singleton();
1903 ERR_FAIL_COND_V(view_configuration_views.is_empty(), Size2());
1904
1905 Size2 target_size;
1906
1907 if (rendering_server && rendering_server->is_on_render_thread()) {
1908 target_size.width = view_configuration_views[0].recommendedImageRectWidth * render_state.render_target_size_multiplier;
1909 target_size.height = view_configuration_views[0].recommendedImageRectHeight * render_state.render_target_size_multiplier;
1910 } else {
1911 target_size.width = view_configuration_views[0].recommendedImageRectWidth * render_target_size_multiplier;
1912 target_size.height = view_configuration_views[0].recommendedImageRectHeight * render_target_size_multiplier;
1913 }
1914
1915 return target_size;
1916 }
1917
1918 XRPose::TrackingConfidence OpenXRAPI::get_head_center(Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
1919 XrResult result;
1920
1921 if (!running) {
1922 return XRPose::XR_TRACKING_CONFIDENCE_NONE;
1923 }
1924
1925 // Get display time
1926 XrTime display_time = get_predicted_display_time();
1927 if (display_time == 0) {
1928 return XRPose::XR_TRACKING_CONFIDENCE_NONE;
1929 }
1930
1931 XrSpaceVelocity velocity = {
1932 XR_TYPE_SPACE_VELOCITY, // type
1933 nullptr, // next
1934 0, // velocityFlags
1935 { 0.0, 0.0, 0.0 }, // linearVelocity
1936 { 0.0, 0.0, 0.0 } // angularVelocity
1937 };
1938
1939 XrSpaceLocation location = {
1940 XR_TYPE_SPACE_LOCATION, // type
1941 &velocity, // next
1942 0, // locationFlags
1943 {
1944 { 0.0, 0.0, 0.0, 0.0 }, // orientation
1945 { 0.0, 0.0, 0.0 } // position
1946 } // pose
1947 };
1948
1949 result = xrLocateSpace(view_space, play_space, display_time, &location);
1950 if (XR_FAILED(result)) {
1951 print_line("OpenXR: Failed to locate view space in play space [", get_error_string(result), "]");
1952 return XRPose::XR_TRACKING_CONFIDENCE_NONE;
1953 }
1954
1955 XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
1956 parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
1957
1958 if (head_pose_confidence != confidence) {
1959 // prevent error spam
1960 head_pose_confidence = confidence;
1961 if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
1962 print_line("OpenXR head space location not valid (check tracking?)");
1963 } else if (head_pose_confidence == XRPose::XR_TRACKING_CONFIDENCE_LOW) {
1964 print_verbose("OpenVR Head pose now tracking with low confidence");
1965 } else {
1966 print_verbose("OpenVR Head pose now tracking with high confidence");
1967 }
1968 }
1969
1970 return confidence;
1971 }
1972
1973 bool OpenXRAPI::get_view_transform(uint32_t p_view, Transform3D &r_transform) {
1974 ERR_NOT_ON_RENDER_THREAD_V(false);
1975
1976 if (!render_state.running) {
1977 return false;
1978 }
1979
1980 // we don't have valid view info
1981 if (render_state.views.is_empty() || !render_state.view_pose_valid) {
1982 return false;
1983 }
1984
1985 // Note, the timing of this is set right before rendering, which is what we need here.
1986 r_transform = transform_from_pose(render_state.views[p_view].pose);
1987
1988 return true;
1989 }
1990
1991 bool OpenXRAPI::get_view_projection(uint32_t p_view, double p_z_near, double p_z_far, Projection &p_camera_matrix) {
1992 ERR_NOT_ON_RENDER_THREAD_V(false);
1993 ERR_FAIL_NULL_V(graphics_extension, false);
1994
1995 if (!render_state.running) {
1996 return false;
1997 }
1998
1999 // we don't have valid view info
2000 if (render_state.views.is_empty() || !render_state.view_pose_valid) {
2001 return false;
2002 }
2003
2004 // if we're using depth views, make sure we update our near and far there...
2005 if (!render_state.depth_views.is_empty()) {
2006 for (XrCompositionLayerDepthInfoKHR &depth_view : render_state.depth_views) {
2007 // As we are using reverse-Z these need to be flipped.
2008 depth_view.nearZ = p_z_far;
2009 depth_view.farZ = p_z_near;
2010 }
2011 }
2012
2013 render_state.z_near = p_z_near;
2014 render_state.z_far = p_z_far;
2015
2016 // now update our projection
2017 return graphics_extension->create_projection_fov(render_state.views[p_view].fov, p_z_near, p_z_far, p_camera_matrix);
2018 }
2019
2020 Vector2 OpenXRAPI::get_eye_focus(uint32_t p_view, float p_aspect) {
2021 ERR_FAIL_NULL_V(graphics_extension, Vector2());
2022
2023 if (!render_state.running) {
2024 return Vector2();
2025 }
2026
2027 // xrWaitFrame not run yet
2028 if (render_state.predicted_display_time == 0) {
2029 return Vector2();
2030 }
2031
2032 // we don't have valid view info
2033 if (render_state.views.is_empty() || !render_state.view_pose_valid) {
2034 return Vector2();
2035 }
2036
2037 Projection cm;
2038 if (!graphics_extension->create_projection_fov(render_state.views[p_view].fov, 0.1, 1000.0, cm)) {
2039 return Vector2();
2040 }
2041
2042 // Default focus to center...
2043 Vector3 focus = cm.xform(Vector3(0.0, 0.0, 999.9));
2044
2045 // Lets check for eye tracking...
2046 OpenXREyeGazeInteractionExtension *eye_gaze_interaction = OpenXREyeGazeInteractionExtension::get_singleton();
2047 if (eye_gaze_interaction && eye_gaze_interaction->supports_eye_gaze_interaction()) {
2048 Vector3 eye_gaze_pose;
2049 if (eye_gaze_interaction->get_eye_gaze_pose(1.0, eye_gaze_pose)) {
2050 Transform3D view_transform = transform_from_pose(render_state.views[p_view].pose);
2051
2052 eye_gaze_pose = view_transform.xform_inv(eye_gaze_pose);
2053 focus = cm.xform(eye_gaze_pose);
2054 }
2055 }
2056
2057 return Vector2(focus.x, focus.y);
2058 }
2059
2060 bool OpenXRAPI::poll_events() {
2061 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
2062
2063 XrEventDataBuffer runtimeEvent;
2064 runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
2065 runtimeEvent.next = nullptr;
2066 // runtimeEvent.varying = ...
2067
2068 XrResult pollResult = xrPollEvent(instance, &runtimeEvent);
2069 while (pollResult == XR_SUCCESS) {
2070 bool handled = false;
2071 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
2072 handled |= wrapper->on_event_polled(runtimeEvent);
2073 }
2074 switch (runtimeEvent.type) {
2075 case XR_TYPE_EVENT_DATA_EVENTS_LOST: {
2076 XrEventDataEventsLost *event = (XrEventDataEventsLost *)&runtimeEvent;
2077
2078 // We probably didn't poll fast enough, just output warning
2079 WARN_PRINT("OpenXR EVENT: " + itos(event->lostEventCount) + " event data lost!");
2080 } break;
2081 case XR_TYPE_EVENT_DATA_INSTANCE_LOSS_PENDING: {
2082 XrEventDataInstanceLossPending *event = (XrEventDataInstanceLossPending *)&runtimeEvent;
2083
2084 // TODO We get this event if we're about to loose our OpenXR instance.
2085 // We should queue exiting Godot at this point.
2086
2087 print_verbose(String("OpenXR EVENT: instance loss pending at ") + itos(event->lossTime));
2088 return false;
2089 } break;
2090 case XR_TYPE_EVENT_DATA_SESSION_STATE_CHANGED: {
2091 XrEventDataSessionStateChanged *event = (XrEventDataSessionStateChanged *)&runtimeEvent;
2092
2093 session_state = event->state;
2094 if (session_state >= XR_SESSION_STATE_MAX_ENUM) {
2095 print_verbose(String("OpenXR EVENT: session state changed to UNKNOWN - ") + itos(session_state));
2096 } else {
2097 print_verbose(String("OpenXR EVENT: session state changed to ") + OpenXRUtil::get_session_state_name(session_state));
2098
2099 switch (session_state) {
2100 case XR_SESSION_STATE_IDLE:
2101 on_state_idle();
2102 break;
2103 case XR_SESSION_STATE_READY:
2104 on_state_ready();
2105 break;
2106 case XR_SESSION_STATE_SYNCHRONIZED:
2107 on_state_synchronized();
2108 break;
2109 case XR_SESSION_STATE_VISIBLE:
2110 on_state_visible();
2111 break;
2112 case XR_SESSION_STATE_FOCUSED:
2113 on_state_focused();
2114 break;
2115 case XR_SESSION_STATE_STOPPING:
2116 on_state_stopping();
2117 break;
2118 case XR_SESSION_STATE_LOSS_PENDING:
2119 on_state_loss_pending();
2120 break;
2121 case XR_SESSION_STATE_EXITING:
2122 on_state_exiting();
2123 break;
2124 default:
2125 break;
2126 }
2127 }
2128 } break;
2129 case XR_TYPE_EVENT_DATA_REFERENCE_SPACE_CHANGE_PENDING: {
2130 XrEventDataReferenceSpaceChangePending *event = (XrEventDataReferenceSpaceChangePending *)&runtimeEvent;
2131
2132 print_verbose(String("OpenXR EVENT: reference space type ") + OpenXRUtil::get_reference_space_name(event->referenceSpaceType) + " change pending!");
2133 if (local_floor_emulation.enabled) {
2134 local_floor_emulation.should_reset_floor_height = true;
2135 }
2136
2137 if (xr_interface) {
2138 xr_interface->on_reference_space_change_pending(event->referenceSpaceType);
2139 }
2140 } break;
2141 case XR_TYPE_EVENT_DATA_INTERACTION_PROFILE_CHANGED: {
2142 print_verbose("OpenXR EVENT: interaction profile changed!");
2143
2144 XrEventDataInteractionProfileChanged *event = (XrEventDataInteractionProfileChanged *)&runtimeEvent;
2145 if (event->session == session) {
2146 // Make sure we get our interaction profile change
2147 interaction_profile_changed = true;
2148 }
2149 } break;
2150 default:
2151 if (!handled) {
2152 print_verbose(String("OpenXR Unhandled event type ") + OpenXRUtil::get_structure_type_name(runtimeEvent.type));
2153 }
2154 break;
2155 }
2156
2157 runtimeEvent.type = XR_TYPE_EVENT_DATA_BUFFER;
2158 pollResult = xrPollEvent(instance, &runtimeEvent);
2159 }
2160
2161 if (pollResult == XR_EVENT_UNAVAILABLE) {
2162 // processed all events in the queue
2163 return true;
2164 } else {
2165 ERR_FAIL_V_MSG(false, "OpenXR: Failed to poll events!");
2166 }
2167 }
2168
2169 void OpenXRAPI::_allocate_view_buffers_rt(uint32_t p_view_count, bool p_submit_depth_buffer) {
2170 // Must be called from rendering thread!
2171 ERR_NOT_ON_RENDER_THREAD;
2172
2173 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
2174 ERR_FAIL_NULL(openxr_api);
2175
2176 openxr_api->render_state.submit_depth_buffer = p_submit_depth_buffer;
2177
2178 // Allocate buffers we'll be populating with view information.
2179 openxr_api->render_state.views.resize(p_view_count);
2180 openxr_api->render_state.projection_views.resize(p_view_count);
2181
2182 for (uint32_t i = 0; i < p_view_count; i++) {
2183 openxr_api->render_state.views[i] = {
2184 XR_TYPE_VIEW, // type
2185 nullptr, // next
2186 {}, // pose
2187 {}, // fov
2188 };
2189 openxr_api->render_state.projection_views[i] = {
2190 XR_TYPE_COMPOSITION_LAYER_PROJECTION_VIEW, // type
2191 nullptr, // next
2192 {}, // pose
2193 {}, // fov
2194 {}, // subImage
2195 };
2196 }
2197
2198 if (p_submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available()) {
2199 openxr_api->render_state.depth_views.resize(p_view_count);
2200
2201 for (uint32_t i = 0; i < p_view_count; i++) {
2202 openxr_api->render_state.depth_views[i] = {
2203 XR_TYPE_COMPOSITION_LAYER_DEPTH_INFO_KHR, // type
2204 nullptr, // next
2205 {}, // subImage
2206 0.0, // minDepth
2207 0.0, // maxDepth
2208 0.0, // nearZ
2209 0.0, // farZ
2210 };
2211 }
2212 }
2213 }
2214
2215 void OpenXRAPI::_set_render_session_running_rt(bool p_is_running) {
2216 // Must be called from rendering thread!
2217 ERR_NOT_ON_RENDER_THREAD;
2218
2219 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
2220 ERR_FAIL_NULL(openxr_api);
2221 openxr_api->render_state.running = p_is_running;
2222 }
2223
2224 void OpenXRAPI::_set_render_display_info_rt(XrTime p_predicted_display_time, bool p_should_render) {
2225 // Must be called from rendering thread!
2226 ERR_NOT_ON_RENDER_THREAD;
2227
2228 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
2229 ERR_FAIL_NULL(openxr_api);
2230 openxr_api->render_state.predicted_display_time = p_predicted_display_time;
2231 openxr_api->render_state.should_render = p_should_render;
2232 }
2233
2234 void OpenXRAPI::_set_render_environment_blend_mode_rt(int32_t p_environment_blend_mode) {
2235 // Must be called from rendering thread!
2236 ERR_NOT_ON_RENDER_THREAD;
2237
2238 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
2239 ERR_FAIL_NULL(openxr_api);
2240 openxr_api->render_state.environment_blend_mode = XrEnvironmentBlendMode(p_environment_blend_mode);
2241 }
2242
2243 void OpenXRAPI::_set_render_play_space_rt(uint64_t p_play_space) {
2244 // Must be called from rendering thread!
2245 ERR_NOT_ON_RENDER_THREAD;
2246
2247 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
2248 ERR_FAIL_NULL(openxr_api);
2249 openxr_api->render_state.play_space = XrSpace(p_play_space);
2250 }
2251
2252 void OpenXRAPI::_set_render_state_multiplier_rt(double p_render_target_size_multiplier) {
2253 // Must be called from rendering thread!
2254 ERR_NOT_ON_RENDER_THREAD;
2255
2256 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
2257 ERR_FAIL_NULL(openxr_api);
2258 openxr_api->render_state.render_target_size_multiplier = p_render_target_size_multiplier;
2259 }
2260
2261 void OpenXRAPI::_set_render_state_render_region_rt(const Rect2i &p_render_region) {
2262 ERR_NOT_ON_RENDER_THREAD;
2263
2264 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
2265 ERR_FAIL_NULL(openxr_api);
2266 openxr_api->render_state.render_region = p_render_region;
2267 }
2268
2269 void OpenXRAPI::_update_main_swapchain_size_rt() {
2270 ERR_NOT_ON_RENDER_THREAD;
2271
2272 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
2273 ERR_FAIL_NULL(openxr_api);
2274
2275 uint32_t view_count_output = 0;
2276 XrResult result = openxr_api->xrEnumerateViewConfigurationViews(openxr_api->instance, openxr_api->system_id, openxr_api->view_configuration, openxr_api->get_view_count(), &view_count_output, openxr_api->view_configuration_views.ptr());
2277 if (XR_FAILED(result)) {
2278 return;
2279 }
2280
2281 #ifdef DEBUG_ENABLED
2282 for (uint32_t i = 0; i < view_count_output; i++) {
2283 print_verbose("OpenXR: Recommended resolution changed");
2284 print_verbose(String(" - recommended render width: ") + itos(openxr_api->view_configuration_views[i].recommendedImageRectWidth));
2285 print_verbose(String(" - recommended render height: ") + itos(openxr_api->view_configuration_views[i].recommendedImageRectHeight));
2286 }
2287 #endif
2288 }
2289
2290 bool OpenXRAPI::process() {
2291 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
2292
2293 if (!poll_events()) {
2294 return false;
2295 }
2296
2297 if (!running) {
2298 return false;
2299 }
2300
2301 GodotProfileZone("OpenXRAPI::process");
2302 GodotProfileZoneGroupedFirst(_profile_zone, "xrWaitFrame");
2303
2304 // We call xrWaitFrame as early as possible, this will allow OpenXR to get
2305 // proper timing info between this point, and when we're ready to start rendering.
2306 // As the name suggests, OpenXR can pause the thread to minimize the time between
2307 // retrieving tracking data and using that tracking data to render.
2308 // OpenXR thus works best if rendering is performed on a separate thread.
2309
2310 void *frame_wait_info_next_pointer = nullptr;
2311 for (OpenXRExtensionWrapper *extension : frame_info_extensions) {
2312 void *np = extension->set_frame_wait_info_and_get_next_pointer(frame_wait_info_next_pointer);
2313 if (np != nullptr) {
2314 frame_wait_info_next_pointer = np;
2315 }
2316 }
2317
2318 XrFrameWaitInfo frame_wait_info = { XR_TYPE_FRAME_WAIT_INFO, frame_wait_info_next_pointer };
2319 frame_state.predictedDisplayTime = 0;
2320 frame_state.predictedDisplayPeriod = 0;
2321 frame_state.shouldRender = false;
2322
2323 XrResult result = xrWaitFrame(session, &frame_wait_info, &frame_state);
2324 if (XR_FAILED(result)) {
2325 print_line("OpenXR: xrWaitFrame() was not successful [", get_error_string(result), "]");
2326
2327 // reset just in case
2328 frame_state.predictedDisplayTime = 0;
2329 frame_state.predictedDisplayPeriod = 0;
2330 frame_state.shouldRender = false;
2331
2332 set_render_display_info(0, false);
2333
2334 return false;
2335 }
2336
2337 if (frame_state.predictedDisplayPeriod > 500000000) {
2338 // display period more then 0.5 seconds? must be wrong data
2339 print_verbose(String("OpenXR resetting invalid display period ") + rtos(frame_state.predictedDisplayPeriod));
2340 frame_state.predictedDisplayPeriod = 0;
2341 }
2342
2343 GodotProfileZoneGrouped(_profile_zone, "set_render_display_info");
2344 set_render_display_info(frame_state.predictedDisplayTime, frame_state.shouldRender);
2345
2346 // This is before setup_play_space() to ensure that it happens on the frame after
2347 // the play space has been created.
2348 if (unlikely(local_floor_emulation.should_reset_floor_height && !play_space_is_dirty)) {
2349 GodotProfileZoneGrouped(_profile_zone, "reset_emulated_floor_height");
2350 reset_emulated_floor_height();
2351 local_floor_emulation.should_reset_floor_height = false;
2352 }
2353
2354 if (unlikely(play_space_is_dirty)) {
2355 GodotProfileZoneGrouped(_profile_zone, "setup_play_space");
2356 setup_play_space();
2357 play_space_is_dirty = false;
2358 }
2359
2360 GodotProfileZoneGrouped(_profile_zone, "extension wrappers on_process");
2361 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
2362 wrapper->on_process();
2363 }
2364
2365 return true;
2366 }
2367
2368 void OpenXRAPI::free_main_swapchains() {
2369 for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
2370 render_state.main_swapchains[i].queue_free();
2371 }
2372 }
2373
2374 void OpenXRAPI::pre_render() {
2375 ERR_FAIL_COND(session == XR_NULL_HANDLE);
2376
2377 // Must be called from rendering thread!
2378 ERR_NOT_ON_RENDER_THREAD;
2379
2380 if (!render_state.running) {
2381 return;
2382 }
2383
2384 // Process any swapchains that were queued to be freed
2385 OpenXRSwapChainInfo::free_queued();
2386
2387 Size2i swapchain_size = get_recommended_target_size();
2388 if (swapchain_size != render_state.main_swapchain_size) {
2389 // Out with the old.
2390 free_main_swapchains();
2391
2392 // In with the new.
2393 create_main_swapchains(swapchain_size);
2394 }
2395
2396 void *view_locate_info_next_pointer = nullptr;
2397 for (OpenXRExtensionWrapper *extension : frame_info_extensions) {
2398 void *np = extension->set_view_locate_info_and_get_next_pointer(view_locate_info_next_pointer);
2399 if (np != nullptr) {
2400 view_locate_info_next_pointer = np;
2401 }
2402 }
2403
2404 // Get our view info for the frame we're about to render, note from the OpenXR manual:
2405 // "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"
2406
2407 // We're calling this "relatively" early, the positioning we're obtaining here will be used to do our frustum culling,
2408 // occlusion culling, etc. There is however a technique that we can investigate in the future where after our entire
2409 // Vulkan command buffer is build, but right before vkSubmitQueue is called, we call xrLocateViews one more time and
2410 // update the view and projection matrix once more with a slightly more accurate predication and then submit the
2411 // command queues.
2412
2413 // That is not possible yet but worth investigating in the future.
2414
2415 XrViewLocateInfo view_locate_info = {
2416 XR_TYPE_VIEW_LOCATE_INFO, // type
2417 view_locate_info_next_pointer, // next
2418 view_configuration, // viewConfigurationType
2419 render_state.predicted_display_time, // displayTime
2420 render_state.play_space // space
2421 };
2422 XrViewState view_state = {
2423 XR_TYPE_VIEW_STATE, // type
2424 nullptr, // next
2425 0 // viewStateFlags
2426 };
2427 uint32_t view_count_output;
2428 XrResult result = xrLocateViews(session, &view_locate_info, &view_state, render_state.views.size(), &view_count_output, render_state.views.ptr());
2429 if (XR_FAILED(result)) {
2430 print_line("OpenXR: Couldn't locate views [", get_error_string(result), "]");
2431 return;
2432 }
2433
2434 bool pose_valid = true;
2435 for (uint64_t i = 0; i < view_count_output; i++) {
2436 if ((view_state.viewStateFlags & XR_VIEW_STATE_ORIENTATION_VALID_BIT) == 0 ||
2437 (view_state.viewStateFlags & XR_VIEW_STATE_POSITION_VALID_BIT) == 0) {
2438 pose_valid = false;
2439 }
2440 }
2441 if (render_state.view_pose_valid != pose_valid) {
2442 render_state.view_pose_valid = pose_valid;
2443 if (!render_state.view_pose_valid) {
2444 print_verbose("OpenXR View pose became invalid");
2445 } else {
2446 print_verbose("OpenXR View pose became valid");
2447 }
2448 }
2449
2450 // We should get our frame no from the rendering server, but this will do.
2451 begin_debug_label_region(String("Session Frame ") + String::num_uint64(++render_state.frame));
2452
2453 // let's start our frame..
2454 XrFrameBeginInfo frame_begin_info = {
2455 XR_TYPE_FRAME_BEGIN_INFO, // type
2456 nullptr // next
2457 };
2458 result = xrBeginFrame(session, &frame_begin_info);
2459 if (XR_FAILED(result)) {
2460 print_line("OpenXR: failed to begin frame [", get_error_string(result), "]");
2461 return;
2462 }
2463
2464 // Reset this, we haven't found a viewport for output yet
2465 render_state.has_xr_viewport = false;
2466
2467 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
2468 wrapper->on_pre_render();
2469 }
2470 }
2471
2472 bool OpenXRAPI::pre_draw_viewport(RID p_render_target) {
2473 // Must be called from rendering thread!
2474 ERR_NOT_ON_RENDER_THREAD_V(false);
2475
2476 // We found an XR viewport!
2477 render_state.has_xr_viewport = true;
2478
2479 if (instance == XR_NULL_HANDLE || session == XR_NULL_HANDLE || !render_state.running || !render_state.view_pose_valid || !render_state.should_render) {
2480 return false;
2481 }
2482
2483 // Acquire our images
2484 for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
2485 if (!render_state.main_swapchains[i].is_image_acquired() && render_state.main_swapchains[i].get_swapchain() != XR_NULL_HANDLE) {
2486 if (!render_state.main_swapchains[i].acquire(render_state.should_render)) {
2487 return false;
2488 }
2489 }
2490 }
2491
2492 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
2493 wrapper->on_pre_draw_viewport(p_render_target);
2494 }
2495
2496 return true;
2497 }
2498
2499 XrSwapchain OpenXRAPI::get_color_swapchain() {
2500 ERR_NOT_ON_RENDER_THREAD_V(XR_NULL_HANDLE);
2501
2502 return render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].get_swapchain();
2503 }
2504
2505 RID OpenXRAPI::get_color_texture() {
2506 ERR_NOT_ON_RENDER_THREAD_V(RID());
2507
2508 return render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].get_image();
2509 }
2510
2511 RID OpenXRAPI::get_depth_texture() {
2512 ERR_NOT_ON_RENDER_THREAD_V(RID());
2513
2514 // Note, image will not be acquired if we didn't have a suitable swap chain format.
2515 if (render_state.submit_depth_buffer && render_state.main_swapchains[OPENXR_SWAPCHAIN_DEPTH].is_image_acquired()) {
2516 return render_state.main_swapchains[OPENXR_SWAPCHAIN_DEPTH].get_image();
2517 } else {
2518 return RID();
2519 }
2520 }
2521
2522 RID OpenXRAPI::get_density_map_texture() {
2523 ERR_NOT_ON_RENDER_THREAD_V(RID());
2524
2525 OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
2526 if (fov_ext && fov_ext->is_enabled()) {
2527 return render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].get_density_map();
2528 }
2529
2530 return RID();
2531 }
2532
2533 void OpenXRAPI::set_velocity_texture(RID p_render_target) {
2534 velocity_texture = p_render_target;
2535 }
2536
2537 RID OpenXRAPI::get_velocity_texture() {
2538 return velocity_texture;
2539 }
2540
2541 void OpenXRAPI::set_velocity_depth_texture(RID p_render_target) {
2542 velocity_depth_texture = p_render_target;
2543 }
2544
2545 RID OpenXRAPI::get_velocity_depth_texture() {
2546 return velocity_depth_texture;
2547 }
2548
2549 void OpenXRAPI::set_velocity_target_size(const Size2i &p_target_size) {
2550 velocity_target_size = p_target_size;
2551 }
2552
2553 Size2i OpenXRAPI::get_velocity_target_size() {
2554 return velocity_target_size;
2555 }
2556
2557 const XrCompositionLayerProjection *OpenXRAPI::get_projection_layer() const {
2558 ERR_NOT_ON_RENDER_THREAD_V(nullptr);
2559
2560 return &render_state.projection_layer;
2561 }
2562
2563 void OpenXRAPI::post_draw_viewport(RID p_render_target) {
2564 // Must be called from rendering thread!
2565 ERR_NOT_ON_RENDER_THREAD;
2566
2567 if (instance == XR_NULL_HANDLE || session == XR_NULL_HANDLE || !render_state.running || !render_state.view_pose_valid || !render_state.should_render) {
2568 return;
2569 }
2570
2571 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
2572 wrapper->on_post_draw_viewport(p_render_target);
2573 }
2574 }
2575
2576 void OpenXRAPI::end_frame() {
2577 XrResult result;
2578
2579 ERR_FAIL_COND(session == XR_NULL_HANDLE);
2580
2581 // Must be called from rendering thread!
2582 ERR_NOT_ON_RENDER_THREAD;
2583
2584 if (!render_state.running) {
2585 return;
2586 }
2587
2588 if (render_state.should_render && render_state.view_pose_valid) {
2589 if (!render_state.has_xr_viewport) {
2590 print_line("OpenXR: No viewport was marked with use_xr, there is no rendered output!");
2591 } else if (!render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].is_image_acquired()) {
2592 print_line("OpenXR: No swapchain could be acquired to render to!");
2593 }
2594 }
2595
2596 Rect2i new_render_region = (render_state.render_region != Rect2i()) ? render_state.render_region : Rect2i(Point2i(0, 0), render_state.main_swapchain_size);
2597
2598 for (XrCompositionLayerProjectionView &projection_view : render_state.projection_views) {
2599 projection_view.subImage.imageRect.offset.x = new_render_region.position.x;
2600 projection_view.subImage.imageRect.offset.y = new_render_region.position.y;
2601 projection_view.subImage.imageRect.extent.width = new_render_region.size.width;
2602 projection_view.subImage.imageRect.extent.height = new_render_region.size.height;
2603 }
2604 if (render_state.submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available() && !render_state.depth_views.is_empty()) {
2605 for (XrCompositionLayerDepthInfoKHR &depth_view : render_state.depth_views) {
2606 depth_view.subImage.imageRect.offset.x = new_render_region.position.x;
2607 depth_view.subImage.imageRect.offset.y = new_render_region.position.y;
2608 depth_view.subImage.imageRect.extent.width = new_render_region.size.width;
2609 depth_view.subImage.imageRect.extent.height = new_render_region.size.height;
2610 }
2611 }
2612
2613 // must have:
2614 // - should_render set to true
2615 // - a valid view pose for projection_views[eye].pose to submit layer
2616 // - an image to render
2617 if (!render_state.should_render || !render_state.view_pose_valid || !render_state.main_swapchains[OPENXR_SWAPCHAIN_COLOR].is_image_acquired()) {
2618 // submit 0 layers when we shouldn't render
2619 XrFrameEndInfo frame_end_info = {
2620 XR_TYPE_FRAME_END_INFO, // type
2621 nullptr, // next
2622 render_state.predicted_display_time, // displayTime
2623 render_state.environment_blend_mode, // environmentBlendMode
2624 0, // layerCount
2625 nullptr // layers
2626 };
2627 result = xrEndFrame(session, &frame_end_info);
2628 if (XR_FAILED(result)) {
2629 print_line("OpenXR: rendering skipped and failed to end frame! [", get_error_string(result), "]");
2630 return;
2631 }
2632
2633 end_debug_label_region(); // Session frame #
2634
2635 // neither eye is rendered
2636 return;
2637 }
2638
2639 // release our swapchain image if we acquired it
2640 for (int i = 0; i < OPENXR_SWAPCHAIN_MAX; i++) {
2641 if (render_state.main_swapchains[i].is_image_acquired()) {
2642 render_state.main_swapchains[i].release();
2643 }
2644 }
2645
2646 for (uint32_t eye = 0; eye < render_state.views.size(); eye++) {
2647 render_state.projection_views[eye].fov = render_state.views[eye].fov;
2648 render_state.projection_views[eye].pose = render_state.views[eye].pose;
2649 }
2650
2651 Vector<OrderedCompositionLayer> ordered_layers_list;
2652 bool projection_layer_is_first = true;
2653
2654 // Add composition layers from providers
2655 for (OpenXRExtensionWrapper *extension : composition_layer_providers) {
2656 for (int i = 0; i < extension->get_composition_layer_count(); i++) {
2657 OrderedCompositionLayer layer = {
2658 extension->get_composition_layer(i),
2659 extension->get_composition_layer_order(i),
2660 };
2661 if (layer.composition_layer) {
2662 ordered_layers_list.push_back(layer);
2663 if (layer.sort_order == 0) {
2664 WARN_PRINT_ONCE_ED("Composition layer returned sort order 0, it may be overwritten by projection layer.");
2665 } else if (layer.sort_order < 0) {
2666 projection_layer_is_first = false;
2667 }
2668 }
2669 }
2670 }
2671
2672 XrCompositionLayerFlags layer_flags = XR_COMPOSITION_LAYER_CORRECT_CHROMATIC_ABERRATION_BIT;
2673 if (!projection_layer_is_first || render_state.environment_blend_mode != XR_ENVIRONMENT_BLEND_MODE_OPAQUE) {
2674 layer_flags |= XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT;
2675 }
2676
2677 render_state.projection_layer.layerFlags = layer_flags;
2678 render_state.projection_layer.space = render_state.play_space;
2679 render_state.projection_layer.viewCount = (uint32_t)render_state.projection_views.size();
2680 render_state.projection_layer.views = render_state.projection_views.ptr();
2681
2682 const bool submit_depth_views = render_state.submit_depth_buffer && OpenXRCompositionLayerDepthExtension::get_singleton()->is_available() && !render_state.depth_views.is_empty();
2683 for (uint32_t v = 0; v < render_state.projection_views.size(); v++) {
2684 void *next_pointer = nullptr;
2685 // Start next chain with depth_views if submitting the depth buffer since this is handled here as a special case currently.
2686 // TODO: Depth composition logic should be moved out into OpenXRCompositionLayerDepthExtension and register as a projection views extension.
2687 if (submit_depth_views) {
2688 next_pointer = &render_state.depth_views[v];
2689 }
2690 for (OpenXRExtensionWrapper *wrapper : projection_views_extensions) {
2691 void *np = wrapper->set_projection_views_and_get_next_pointer(v, next_pointer);
2692 if (np != nullptr) {
2693 next_pointer = np;
2694 }
2695 }
2696 render_state.projection_views[v].next = next_pointer;
2697 }
2698
2699 ordered_layers_list.push_back({ (const XrCompositionLayerBaseHeader *)&render_state.projection_layer, 0 });
2700
2701 // Sort our layers.
2702 ordered_layers_list.sort_custom<OrderedCompositionLayer>();
2703
2704 // Now make a list we can pass on to OpenXR.
2705 Vector<const XrCompositionLayerBaseHeader *> layers_list;
2706 for (OrderedCompositionLayer &ordered_layer : ordered_layers_list) {
2707 layers_list.push_back(ordered_layer.composition_layer);
2708 }
2709
2710 void *frame_end_info_next_pointer = nullptr;
2711 for (OpenXRExtensionWrapper *extension : frame_info_extensions) {
2712 void *np = extension->set_frame_end_info_and_get_next_pointer(frame_end_info_next_pointer);
2713 if (np != nullptr) {
2714 frame_end_info_next_pointer = np;
2715 }
2716 }
2717
2718 XrFrameEndInfo frame_end_info = {
2719 XR_TYPE_FRAME_END_INFO, // type
2720 frame_end_info_next_pointer, // next
2721 render_state.predicted_display_time, // displayTime
2722 render_state.environment_blend_mode, // environmentBlendMode
2723 static_cast<uint32_t>(layers_list.size()), // layerCount
2724 layers_list.ptr() // layers
2725 };
2726 result = xrEndFrame(session, &frame_end_info);
2727 if (XR_FAILED(result)) {
2728 print_line("OpenXR: failed to end frame! [", get_error_string(result), "]");
2729 return;
2730 }
2731
2732 end_debug_label_region(); // Session frame #
2733 }
2734
2735 float OpenXRAPI::get_display_refresh_rate() const {
2736 OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
2737 if (drrext) {
2738 return drrext->get_refresh_rate();
2739 }
2740
2741 return 0.0;
2742 }
2743
2744 void OpenXRAPI::set_display_refresh_rate(float p_refresh_rate) {
2745 OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
2746 if (drrext != nullptr) {
2747 drrext->set_refresh_rate(p_refresh_rate);
2748 }
2749 }
2750
2751 Array OpenXRAPI::get_available_display_refresh_rates() const {
2752 OpenXRDisplayRefreshRateExtension *drrext = OpenXRDisplayRefreshRateExtension::get_singleton();
2753 if (drrext != nullptr) {
2754 return drrext->get_available_refresh_rates();
2755 }
2756
2757 return Array();
2758 }
2759
2760 double OpenXRAPI::get_render_target_size_multiplier() const {
2761 return render_target_size_multiplier;
2762 }
2763
2764 void OpenXRAPI::set_render_target_size_multiplier(double multiplier) {
2765 render_target_size_multiplier = multiplier;
2766 set_render_state_multiplier(multiplier);
2767 }
2768
2769 Rect2i OpenXRAPI::get_render_region() const {
2770 return render_region;
2771 }
2772
2773 void OpenXRAPI::set_render_region(const Rect2i &p_render_region) {
2774 render_region = p_render_region;
2775 set_render_state_render_region(p_render_region);
2776 }
2777
2778 bool OpenXRAPI::is_foveation_supported() const {
2779 OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
2780 return fov_ext != nullptr && fov_ext->is_enabled();
2781 }
2782
2783 int OpenXRAPI::get_foveation_level() const {
2784 OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
2785 if (fov_ext != nullptr && fov_ext->is_enabled()) {
2786 switch (fov_ext->get_foveation_level()) {
2787 case XR_FOVEATION_LEVEL_NONE_FB:
2788 return 0;
2789 case XR_FOVEATION_LEVEL_LOW_FB:
2790 return 1;
2791 case XR_FOVEATION_LEVEL_MEDIUM_FB:
2792 return 2;
2793 case XR_FOVEATION_LEVEL_HIGH_FB:
2794 return 3;
2795 default:
2796 return 0;
2797 }
2798 }
2799
2800 return 0;
2801 }
2802
2803 void OpenXRAPI::set_foveation_level(int p_foveation_level) {
2804 ERR_FAIL_UNSIGNED_INDEX(p_foveation_level, 4);
2805 OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
2806 if (fov_ext != nullptr && fov_ext->is_enabled()) {
2807 XrFoveationLevelFB levels[] = { XR_FOVEATION_LEVEL_NONE_FB, XR_FOVEATION_LEVEL_LOW_FB, XR_FOVEATION_LEVEL_MEDIUM_FB, XR_FOVEATION_LEVEL_HIGH_FB };
2808 fov_ext->set_foveation_level(levels[p_foveation_level]);
2809 }
2810 }
2811
2812 bool OpenXRAPI::get_foveation_dynamic() const {
2813 OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
2814 if (fov_ext != nullptr && fov_ext->is_enabled()) {
2815 return fov_ext->get_foveation_dynamic() == XR_FOVEATION_DYNAMIC_LEVEL_ENABLED_FB;
2816 }
2817 return false;
2818 }
2819
2820 void OpenXRAPI::set_foveation_dynamic(bool p_foveation_dynamic) {
2821 OpenXRFBFoveationExtension *fov_ext = OpenXRFBFoveationExtension::get_singleton();
2822 if (fov_ext != nullptr && fov_ext->is_enabled()) {
2823 fov_ext->set_foveation_dynamic(p_foveation_dynamic ? XR_FOVEATION_DYNAMIC_LEVEL_ENABLED_FB : XR_FOVEATION_DYNAMIC_DISABLED_FB);
2824 }
2825 }
2826
2827 Size2 OpenXRAPI::get_play_space_bounds() const {
2828 Size2 ret;
2829
2830 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, Size2());
2831
2832 XrExtent2Df extents;
2833
2834 XrResult result = xrGetReferenceSpaceBoundsRect(session, reference_space, &extents);
2835 if (XR_FAILED(result)) {
2836 print_line("OpenXR: failed to get play space bounds! [", get_error_string(result), "]");
2837 return ret;
2838 }
2839
2840 ret.width = extents.width;
2841 ret.height = extents.height;
2842
2843 return ret;
2844 }
2845
2846 PackedInt64Array OpenXRAPI::get_supported_swapchain_formats() {
2847 return supported_swapchain_formats;
2848 }
2849
2850 OpenXRAPI::OpenXRAPI() {
2851 // OpenXRAPI is only constructed if OpenXR is enabled.
2852 singleton = this;
2853
2854 if (Engine::get_singleton()->is_editor_hint()) {
2855 // Enabled OpenXR in the editor? Adjust our settings for the editor
2856 } else {
2857 // Load settings from project settings
2858 int form_factor_setting = GLOBAL_GET("xr/openxr/form_factor");
2859 switch (form_factor_setting) {
2860 case 0: {
2861 form_factor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY;
2862 } break;
2863 case 1: {
2864 form_factor = XR_FORM_FACTOR_HANDHELD_DISPLAY;
2865 } break;
2866 default:
2867 break;
2868 }
2869
2870 int view_configuration_setting = GLOBAL_GET("xr/openxr/view_configuration");
2871 switch (view_configuration_setting) {
2872 case 0: {
2873 view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO;
2874 } break;
2875 case 1: {
2876 view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO;
2877 } break;
2878 /* we don't support quad and observer configurations (yet)
2879 case 2: {
2880 view_configuration = XR_VIEW_CONFIGURATION_TYPE_PRIMARY_QUAD_VARJO;
2881 } break;
2882 case 3: {
2883 view_configuration = XR_VIEW_CONFIGURATION_TYPE_SECONDARY_MONO_FIRST_PERSON_OBSERVER_MSFT;
2884 } break;
2885 */
2886 default:
2887 break;
2888 }
2889
2890 int reference_space_setting = GLOBAL_GET("xr/openxr/reference_space");
2891 switch (reference_space_setting) {
2892 case 0: {
2893 requested_reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL;
2894 } break;
2895 case 1: {
2896 requested_reference_space = XR_REFERENCE_SPACE_TYPE_STAGE;
2897 } break;
2898 case 2: {
2899 requested_reference_space = XR_REFERENCE_SPACE_TYPE_LOCAL_FLOOR_EXT;
2900 } break;
2901 default:
2902 break;
2903 }
2904
2905 int environment_blend_mode_setting = GLOBAL_GET("xr/openxr/environment_blend_mode");
2906 switch (environment_blend_mode_setting) {
2907 case 0: {
2908 environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
2909 } break;
2910 case 1: {
2911 environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_ADDITIVE;
2912 } break;
2913 case 2: {
2914 environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND;
2915 } break;
2916 default:
2917 break;
2918 }
2919
2920 submit_depth_buffer = GLOBAL_GET("xr/openxr/submit_depth_buffer");
2921 }
2922 }
2923
2924 OpenXRAPI::~OpenXRAPI() {
2925 composition_layer_providers.clear();
2926 frame_info_extensions.clear();
2927 supported_extensions.clear();
2928 layer_properties.clear();
2929
2930 #ifdef ANDROID_ENABLED
2931 if (openxr_loader_library_handle) {
2932 OS::get_singleton()->close_dynamic_library(openxr_loader_library_handle);
2933 openxr_loader_library_handle = nullptr;
2934 }
2935 #endif
2936
2937 singleton = nullptr;
2938 }
2939
2940 Transform3D OpenXRAPI::transform_from_pose(const XrPosef &p_pose) {
2941 Quaternion q(p_pose.orientation.x, p_pose.orientation.y, p_pose.orientation.z, p_pose.orientation.w);
2942 Basis basis(q);
2943 Vector3 origin(p_pose.position.x, p_pose.position.y, p_pose.position.z);
2944
2945 return Transform3D(basis, origin);
2946 }
2947
2948 XrPosef OpenXRAPI::pose_from_transform(const Transform3D &p_transform) {
2949 XrPosef pose;
2950
2951 Quaternion q(p_transform.basis);
2952 pose.orientation.x = q.x;
2953 pose.orientation.y = q.y;
2954 pose.orientation.z = q.z;
2955 pose.orientation.w = q.w;
2956
2957 pose.position.x = p_transform.origin.x;
2958 pose.position.y = p_transform.origin.y;
2959 pose.position.z = p_transform.origin.z;
2960
2961 return pose;
2962 }
2963
2964 template <typename T>
2965 XRPose::TrackingConfidence _transform_from_location(const T &p_location, Transform3D &r_transform) {
2966 XRPose::TrackingConfidence confidence = XRPose::XR_TRACKING_CONFIDENCE_NONE;
2967 const XrPosef &pose = p_location.pose;
2968
2969 // Check orientation
2970 if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_VALID_BIT) {
2971 Quaternion q(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w);
2972 r_transform.basis = Basis(q);
2973
2974 if (p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT) {
2975 // Fully valid orientation, so either 3DOF or 6DOF tracking with high confidence so default to HIGH_TRACKING
2976 confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
2977 } else {
2978 // Orientation is being tracked but we're using old/predicted data, so low tracking confidence
2979 confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
2980 }
2981 } else {
2982 r_transform.basis = Basis();
2983 }
2984
2985 // Check location
2986 if (p_location.locationFlags & XR_SPACE_LOCATION_POSITION_VALID_BIT) {
2987 r_transform.origin = Vector3(pose.position.x, pose.position.y, pose.position.z);
2988
2989 if (!(p_location.locationFlags & XR_SPACE_LOCATION_ORIENTATION_TRACKED_BIT)) {
2990 // Location is being tracked but we're using old/predicted data, so low tracking confidence
2991 confidence = XRPose::XR_TRACKING_CONFIDENCE_LOW;
2992 } else if (confidence == XRPose::XR_TRACKING_CONFIDENCE_NONE) {
2993 // Position tracking without orientation tracking?
2994 confidence = XRPose::XR_TRACKING_CONFIDENCE_HIGH;
2995 }
2996 } else {
2997 // No tracking or 3DOF I guess..
2998 r_transform.origin = Vector3();
2999 }
3000
3001 return confidence;
3002 }
3003
3004 XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrSpaceLocation &p_location, Transform3D &r_transform) {
3005 return _transform_from_location(p_location, r_transform);
3006 }
3007
3008 XRPose::TrackingConfidence OpenXRAPI::transform_from_location(const XrHandJointLocationEXT &p_location, Transform3D &r_transform) {
3009 return _transform_from_location(p_location, r_transform);
3010 }
3011
3012 void OpenXRAPI::parse_velocities(const XrSpaceVelocity &p_velocity, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
3013 if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_LINEAR_VALID_BIT) {
3014 XrVector3f linear_velocity = p_velocity.linearVelocity;
3015 r_linear_velocity = Vector3(linear_velocity.x, linear_velocity.y, linear_velocity.z);
3016 } else {
3017 r_linear_velocity = Vector3();
3018 }
3019 if (p_velocity.velocityFlags & XR_SPACE_VELOCITY_ANGULAR_VALID_BIT) {
3020 XrVector3f angular_velocity = p_velocity.angularVelocity;
3021 r_angular_velocity = Vector3(angular_velocity.x, angular_velocity.y, angular_velocity.z);
3022 } else {
3023 r_angular_velocity = Vector3();
3024 }
3025 }
3026
3027 bool OpenXRAPI::xr_result(XrResult p_result, const char *p_format, const Array &p_args) const {
3028 if (XR_SUCCEEDED(p_result)) {
3029 return true;
3030 }
3031
3032 char resultString[XR_MAX_RESULT_STRING_SIZE];
3033 xrResultToString(instance, p_result, resultString);
3034
3035 print_error(String("OpenXR ") + String(p_format).format(p_args) + String(" [") + String(resultString) + String("]"));
3036
3037 return false;
3038 }
3039
3040 XrPath OpenXRAPI::get_xr_path(const String &p_path) {
3041 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, XR_NULL_PATH);
3042
3043 if (p_path.is_empty()) {
3044 // This isn't necesairily an issue, so silently return a null path.
3045 return XR_NULL_PATH;
3046 }
3047
3048 XrPath path = XR_NULL_PATH;
3049
3050 XrResult result = xrStringToPath(instance, p_path.utf8().get_data(), &path);
3051 if (XR_FAILED(result)) {
3052 print_line("OpenXR: failed to get path for ", p_path, "! [", get_error_string(result), "]");
3053 return XR_NULL_PATH;
3054 }
3055
3056 return path;
3057 }
3058
3059 String OpenXRAPI::get_xr_path_name(const XrPath &p_path) {
3060 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, String());
3061
3062 uint32_t size = 0;
3063 char path_name[XR_MAX_PATH_LENGTH];
3064
3065 XrResult result = xrPathToString(instance, p_path, XR_MAX_PATH_LENGTH, &size, path_name);
3066 if (XR_FAILED(result)) {
3067 ERR_FAIL_V_MSG(String(), "OpenXR: failed to get name for a path! [" + get_error_string(result) + "]");
3068 }
3069
3070 return String(path_name);
3071 }
3072
3073 RID OpenXRAPI::get_tracker_rid(XrPath p_path) {
3074 for (const RID &tracker_rid : tracker_owner.get_owned_list()) {
3075 Tracker *tracker = tracker_owner.get_or_null(tracker_rid);
3076 if (tracker && tracker->toplevel_path == p_path) {
3077 return tracker_rid;
3078 }
3079 }
3080
3081 return RID();
3082 }
3083
3084 RID OpenXRAPI::find_tracker(const String &p_name) {
3085 for (const RID &tracker_rid : tracker_owner.get_owned_list()) {
3086 Tracker *tracker = tracker_owner.get_or_null(tracker_rid);
3087 if (tracker && tracker->name == p_name) {
3088 return tracker_rid;
3089 }
3090 }
3091
3092 return RID();
3093 }
3094
3095 RID OpenXRAPI::tracker_create(const String &p_name) {
3096 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
3097
3098 Tracker new_tracker;
3099 new_tracker.name = p_name;
3100 new_tracker.toplevel_path = XR_NULL_PATH;
3101 new_tracker.active_profile_rid = RID();
3102
3103 new_tracker.toplevel_path = get_xr_path(p_name);
3104 ERR_FAIL_COND_V(new_tracker.toplevel_path == XR_NULL_PATH, RID());
3105
3106 return tracker_owner.make_rid(new_tracker);
3107 }
3108
3109 String OpenXRAPI::tracker_get_name(RID p_tracker) {
3110 if (p_tracker.is_null()) {
3111 return String("None");
3112 }
3113
3114 Tracker *tracker = tracker_owner.get_or_null(p_tracker);
3115 ERR_FAIL_NULL_V(tracker, String());
3116
3117 return tracker->name;
3118 }
3119
3120 void OpenXRAPI::tracker_check_profile(RID p_tracker, XrSession p_session) {
3121 if (p_session == XR_NULL_HANDLE) {
3122 p_session = session;
3123 }
3124
3125 Tracker *tracker = tracker_owner.get_or_null(p_tracker);
3126 ERR_FAIL_NULL(tracker);
3127
3128 if (tracker->toplevel_path == XR_NULL_PATH) {
3129 // no path, how was this even created?
3130 return;
3131 }
3132
3133 XrInteractionProfileState profile_state = {
3134 XR_TYPE_INTERACTION_PROFILE_STATE, // type
3135 nullptr, // next
3136 XR_NULL_PATH // interactionProfile
3137 };
3138
3139 XrResult result = xrGetCurrentInteractionProfile(p_session, tracker->toplevel_path, &profile_state);
3140 if (XR_FAILED(result)) {
3141 print_line("OpenXR: Failed to get interaction profile for", itos(tracker->toplevel_path), "[", get_error_string(result), "]");
3142 return;
3143 }
3144
3145 XrPath new_profile = profile_state.interactionProfile;
3146 XrPath was_profile = get_interaction_profile_path(tracker->active_profile_rid);
3147 if (was_profile != new_profile) {
3148 tracker->active_profile_rid = get_interaction_profile_rid(new_profile);
3149
3150 if (xr_interface) {
3151 xr_interface->tracker_profile_changed(p_tracker, tracker->active_profile_rid);
3152 }
3153 }
3154 }
3155
3156 void OpenXRAPI::tracker_free(RID p_tracker) {
3157 Tracker *tracker = tracker_owner.get_or_null(p_tracker);
3158 ERR_FAIL_NULL(tracker);
3159
3160 // there is nothing to free here
3161
3162 tracker_owner.free(p_tracker);
3163 }
3164
3165 RID OpenXRAPI::action_set_create(const String &p_name, const String &p_localized_name, const int p_priority) {
3166 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
3167 ActionSet action_set;
3168
3169 action_set.name = p_name;
3170 action_set.is_attached = false;
3171
3172 // create our action set...
3173 XrActionSetCreateInfo action_set_info = {
3174 XR_TYPE_ACTION_SET_CREATE_INFO, // type
3175 nullptr, // next
3176 "", // actionSetName
3177 "", // localizedActionSetName
3178 uint32_t(p_priority) // priority
3179 };
3180
3181 copy_string_to_char_buffer(p_name, action_set_info.actionSetName, XR_MAX_ACTION_SET_NAME_SIZE);
3182 copy_string_to_char_buffer(p_localized_name, action_set_info.localizedActionSetName, XR_MAX_LOCALIZED_ACTION_SET_NAME_SIZE);
3183
3184 XrResult result = xrCreateActionSet(instance, &action_set_info, &action_set.handle);
3185 if (XR_FAILED(result)) {
3186 print_line("OpenXR: failed to create action set ", p_name, "! [", get_error_string(result), "]");
3187 return RID();
3188 }
3189
3190 set_object_name(XR_OBJECT_TYPE_ACTION_SET, uint64_t(action_set.handle), p_name);
3191
3192 return action_set_owner.make_rid(action_set);
3193 }
3194
3195 RID OpenXRAPI::find_action_set(const String &p_name) {
3196 for (const RID &action_set_rid : action_set_owner.get_owned_list()) {
3197 ActionSet *action_set = action_set_owner.get_or_null(action_set_rid);
3198 if (action_set && action_set->name == p_name) {
3199 return action_set_rid;
3200 }
3201 }
3202
3203 return RID();
3204 }
3205
3206 String OpenXRAPI::action_set_get_name(RID p_action_set) {
3207 if (p_action_set.is_null()) {
3208 return String("None");
3209 }
3210
3211 ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
3212 ERR_FAIL_NULL_V(action_set, String());
3213
3214 return action_set->name;
3215 }
3216
3217 XrActionSet OpenXRAPI::action_set_get_handle(RID p_action_set) {
3218 if (p_action_set.is_null()) {
3219 return XR_NULL_HANDLE;
3220 }
3221
3222 ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
3223 ERR_FAIL_NULL_V(action_set, XR_NULL_HANDLE);
3224
3225 return action_set->handle;
3226 }
3227
3228 bool OpenXRAPI::attach_action_sets(const Vector<RID> &p_action_sets) {
3229 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
3230
3231 Vector<XrActionSet> action_handles;
3232 action_handles.resize(p_action_sets.size());
3233 for (int i = 0; i < p_action_sets.size(); i++) {
3234 ActionSet *action_set = action_set_owner.get_or_null(p_action_sets[i]);
3235 ERR_FAIL_NULL_V(action_set, false);
3236
3237 if (action_set->is_attached) {
3238 return false;
3239 }
3240
3241 action_handles.set(i, action_set->handle);
3242 }
3243
3244 // So according to the docs, once we attach our action set to our session it becomes read only..
3245 // https://www.khronos.org/registry/OpenXR/specs/1.0/man/html/xrAttachSessionActionSets.html
3246 XrSessionActionSetsAttachInfo attach_info = {
3247 XR_TYPE_SESSION_ACTION_SETS_ATTACH_INFO, // type
3248 nullptr, // next
3249 (uint32_t)p_action_sets.size(), // countActionSets,
3250 action_handles.ptr() // actionSets
3251 };
3252
3253 XrResult result = xrAttachSessionActionSets(session, &attach_info);
3254 if (XR_FAILED(result)) {
3255 print_line("OpenXR: failed to attach action sets! [", get_error_string(result), "]");
3256 return false;
3257 }
3258
3259 for (int i = 0; i < p_action_sets.size(); i++) {
3260 ActionSet *action_set = action_set_owner.get_or_null(p_action_sets[i]);
3261 ERR_FAIL_NULL_V(action_set, false);
3262 action_set->is_attached = true;
3263 }
3264
3265 /* For debugging:
3266 print_verbose("Attached set " + action_set->name);
3267 List<RID> action_rids;
3268 action_owner.get_owned_list(&action_rids);
3269 for (int i = 0; i < action_rids.size(); i++) {
3270 Action * action = action_owner.get_or_null(action_rids[i]);
3271 if (action && action->action_set_rid == p_action_set) {
3272 print_verbose(" - Action " + action->name + ": " + OpenXRUtil::get_action_type_name(action->action_type));
3273 for (int j = 0; j < action->trackers.size(); j++) {
3274 Tracker * tracker = tracker_owner.get_or_null(action->trackers[j].tracker_rid);
3275 if (tracker) {
3276 print_verbose(" - " + tracker->name);
3277 }
3278 }
3279 }
3280 }
3281 */
3282
3283 return true;
3284 }
3285
3286 void OpenXRAPI::action_set_free(RID p_action_set) {
3287 ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
3288 ERR_FAIL_NULL(action_set);
3289
3290 if (action_set->handle != XR_NULL_HANDLE) {
3291 xrDestroyActionSet(action_set->handle);
3292 }
3293
3294 action_set_owner.free(p_action_set);
3295 }
3296
3297 RID OpenXRAPI::get_action_rid(XrAction p_action) {
3298 for (const RID &action_rid : action_owner.get_owned_list()) {
3299 Action *action = action_owner.get_or_null(action_rid);
3300 if (action && action->handle == p_action) {
3301 return action_rid;
3302 }
3303 }
3304
3305 return RID();
3306 }
3307
3308 RID OpenXRAPI::find_action(const String &p_name, const RID &p_action_set) {
3309 for (const RID &action_rid : action_owner.get_owned_list()) {
3310 Action *action = action_owner.get_or_null(action_rid);
3311 if (action && action->name == p_name && (p_action_set.is_null() || action->action_set_rid == p_action_set)) {
3312 return action_rid;
3313 }
3314 }
3315
3316 return RID();
3317 }
3318
3319 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) {
3320 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, RID());
3321
3322 Action action;
3323 action.name = p_name;
3324
3325 ActionSet *action_set = action_set_owner.get_or_null(p_action_set);
3326 ERR_FAIL_NULL_V(action_set, RID());
3327 ERR_FAIL_COND_V(action_set->handle == XR_NULL_HANDLE, RID());
3328 action.action_set_rid = p_action_set;
3329
3330 switch (p_action_type) {
3331 case OpenXRAction::OPENXR_ACTION_BOOL:
3332 action.action_type = XR_ACTION_TYPE_BOOLEAN_INPUT;
3333 break;
3334 case OpenXRAction::OPENXR_ACTION_FLOAT:
3335 action.action_type = XR_ACTION_TYPE_FLOAT_INPUT;
3336 break;
3337 case OpenXRAction::OPENXR_ACTION_VECTOR2:
3338 action.action_type = XR_ACTION_TYPE_VECTOR2F_INPUT;
3339 break;
3340 case OpenXRAction::OPENXR_ACTION_POSE:
3341 action.action_type = XR_ACTION_TYPE_POSE_INPUT;
3342 break;
3343 case OpenXRAction::OPENXR_ACTION_HAPTIC:
3344 action.action_type = XR_ACTION_TYPE_VIBRATION_OUTPUT;
3345 break;
3346 default:
3347 ERR_FAIL_V(RID());
3348 break;
3349 }
3350
3351 Vector<XrPath> toplevel_paths;
3352 for (int i = 0; i < p_trackers.size(); i++) {
3353 Tracker *tracker = tracker_owner.get_or_null(p_trackers[i]);
3354 if (tracker != nullptr && tracker->toplevel_path != XR_NULL_PATH) {
3355 ActionTracker action_tracker = {
3356 p_trackers[i], // tracker
3357 XR_NULL_HANDLE, // space
3358 false // was_location_valid
3359 };
3360 action.trackers.push_back(action_tracker);
3361
3362 toplevel_paths.push_back(tracker->toplevel_path);
3363 }
3364 }
3365
3366 XrActionCreateInfo action_info = {
3367 XR_TYPE_ACTION_CREATE_INFO, // type
3368 nullptr, // next
3369 "", // actionName
3370 action.action_type, // actionType
3371 uint32_t(toplevel_paths.size()), // countSubactionPaths
3372 toplevel_paths.ptr(), // subactionPaths
3373 "" // localizedActionName
3374 };
3375
3376 copy_string_to_char_buffer(p_name, action_info.actionName, XR_MAX_ACTION_NAME_SIZE);
3377 copy_string_to_char_buffer(p_localized_name, action_info.localizedActionName, XR_MAX_LOCALIZED_ACTION_NAME_SIZE);
3378
3379 XrResult result = xrCreateAction(action_set->handle, &action_info, &action.handle);
3380 if (XR_FAILED(result)) {
3381 print_line("OpenXR: failed to create action ", p_name, "! [", get_error_string(result), "]");
3382 return RID();
3383 }
3384
3385 set_object_name(XR_OBJECT_TYPE_ACTION, uint64_t(action.handle), p_name);
3386
3387 return action_owner.make_rid(action);
3388 }
3389
3390 String OpenXRAPI::action_get_name(RID p_action) {
3391 if (p_action.is_null()) {
3392 return String("None");
3393 }
3394
3395 Action *action = action_owner.get_or_null(p_action);
3396 ERR_FAIL_NULL_V(action, String());
3397
3398 return action->name;
3399 }
3400
3401 XrAction OpenXRAPI::action_get_handle(RID p_action) {
3402 if (p_action.is_null()) {
3403 return XR_NULL_HANDLE;
3404 }
3405
3406 Action *action = action_owner.get_or_null(p_action);
3407 ERR_FAIL_NULL_V(action, XR_NULL_HANDLE);
3408
3409 return action->handle;
3410 }
3411
3412 void OpenXRAPI::action_free(RID p_action) {
3413 Action *action = action_owner.get_or_null(p_action);
3414 ERR_FAIL_NULL(action);
3415
3416 if (action->handle != XR_NULL_HANDLE) {
3417 xrDestroyAction(action->handle);
3418 }
3419
3420 action_owner.free(p_action);
3421 }
3422
3423 RID OpenXRAPI::get_interaction_profile_rid(XrPath p_path) {
3424 for (const RID &ip_rid : interaction_profile_owner.get_owned_list()) {
3425 InteractionProfile *ip = interaction_profile_owner.get_or_null(ip_rid);
3426 if (ip && ip->path == p_path) {
3427 return ip_rid;
3428 }
3429 }
3430
3431 return RID();
3432 }
3433
3434 XrPath OpenXRAPI::get_interaction_profile_path(RID p_interaction_profile) {
3435 if (p_interaction_profile.is_null()) {
3436 return XR_NULL_PATH;
3437 }
3438
3439 InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
3440 ERR_FAIL_NULL_V(ip, XR_NULL_PATH);
3441
3442 return ip->path;
3443 }
3444
3445 RID OpenXRAPI::interaction_profile_create(const String &p_name) {
3446 if (!is_interaction_profile_supported(p_name)) {
3447 // The extension enabling this path must not be active, we will silently skip this interaction profile
3448 return RID();
3449 }
3450
3451 InteractionProfile new_interaction_profile;
3452
3453 new_interaction_profile.internal_name = get_interaction_profile_internal_name(p_name);
3454
3455 XrResult result = xrStringToPath(instance, new_interaction_profile.internal_name.get_data(), &new_interaction_profile.path);
3456 if (XR_FAILED(result)) {
3457 print_line("OpenXR: failed to get path for ", p_name, "! [", get_error_string(result), "]");
3458 return RID();
3459 }
3460
3461 RID existing_ip = get_interaction_profile_rid(new_interaction_profile.path);
3462 if (existing_ip.is_valid()) {
3463 return existing_ip;
3464 }
3465
3466 new_interaction_profile.name = p_name;
3467 return interaction_profile_owner.make_rid(new_interaction_profile);
3468 }
3469
3470 String OpenXRAPI::interaction_profile_get_name(RID p_interaction_profile) {
3471 if (p_interaction_profile.is_null()) {
3472 return String("None");
3473 }
3474
3475 InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
3476 ERR_FAIL_NULL_V(ip, String());
3477
3478 return ip->name;
3479 }
3480
3481 void OpenXRAPI::interaction_profile_clear_bindings(RID p_interaction_profile) {
3482 InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
3483 ERR_FAIL_NULL(ip);
3484
3485 ip->bindings.clear();
3486 }
3487
3488 CharString OpenXRAPI::get_interaction_profile_internal_name(const String &p_interaction_profile_name) const {
3489 CharString internal_name = p_interaction_profile_name.utf8();
3490
3491 if (openxr_version < XR_API_VERSION_1_1_0) {
3492 // These interaction profiles were renamed in OpenXR 1.1,
3493 // if we don't support OpenXR 1.1, rename them back.
3494 if (internal_name == "/interaction_profiles/meta/touch_pro_controller") {
3495 return "/interaction_profiles/facebook/touch_controller_pro";
3496 } else if (internal_name == "/interaction_profiles/meta/touch_plus_controller") {
3497 return "/interaction_profiles/meta/touch_controller_plus";
3498 }
3499 }
3500
3501 return internal_name;
3502 }
3503
3504 const char *OpenXRAPI::check_profile_path(const CharString &p_interaction_profile_name, const char *p_path) const {
3505 // We store the new names of these paths in our action map, so if we're on older versions of OpenXR,
3506 // we need to use the old names.
3507
3508 struct RenameMap {
3509 const XrVersion before_version; // If we're on an older version of OpenXR than this (if none zero).
3510 const char *from; // Rename from this
3511 const char *to; // to this
3512 const char *profile; // limiting to this profile (unless nullptr)
3513 };
3514
3515 // The order of entries is important as we early exit when we encounter a before_version value before our current value (excluding 0).
3516 const RenameMap renames[] = {
3517 // The touch_controller is an exception where it is still using the vendor names because they were introduced after OpenXR 1.1 was defined.
3518 { 0, "/user/hand/left/input/trigger/proximity", "/user/hand/left/input/trigger/proximity_fb", "/interaction_profiles/oculus/touch_controller" },
3519 { 0, "/user/hand/right/input/trigger/proximity", "/user/hand/right/input/trigger/proximity_fb", "/interaction_profiles/oculus/touch_controller" },
3520 { 0, "/user/hand/left/input/thumb_resting_surfaces/proximity", "/user/hand/left/input/thumb_fb/proximity_fb", "/interaction_profiles/oculus/touch_controller" },
3521 { 0, "/user/hand/right/input/thumb_resting_surfaces/proximity", "/user/hand/right/input/thumb_fb/proximity_fb", "/interaction_profiles/oculus/touch_controller" },
3522
3523 // Once applicable, add XR_API_VERSION_1_2 here.
3524
3525 // Before OpenXR 1.1 we're using palm_ext/pose (we're checking for enabled palm pose extension elsewhere).
3526 { XR_API_VERSION_1_1_0, "/user/hand/left/input/grip_surface/pose", "/user/hand/left/input/palm_ext/pose", nullptr },
3527 { XR_API_VERSION_1_1_0, "/user/hand/right/input/grip_surface/pose", "/user/hand/right/input/palm_ext/pose", nullptr },
3528
3529 // Specific renames for touch_controller_pro, note that we would have already renamed it to the old name.
3530 { XR_API_VERSION_1_1_0, "/user/hand/left/input/grip_surface/pose", "/user/hand/left/input/palm_ext/pose", "/interaction_profiles/facebook/touch_controller_pro" },
3531 { XR_API_VERSION_1_1_0, "/user/hand/right/input/grip_surface/pose", "/user/hand/right/input/palm_ext/pose", "/interaction_profiles/facebook/touch_controller_pro" },
3532 { XR_API_VERSION_1_1_0, "/user/hand/left/input/stylus/force", "/user/hand/left/input/stylus_fb/force", "/interaction_profiles/facebook/touch_controller_pro" },
3533 { XR_API_VERSION_1_1_0, "/user/hand/right/input/stylus/force", "/user/hand/right/input/stylus_fb/force", "/interaction_profiles/facebook/touch_controller_pro" },
3534 { XR_API_VERSION_1_1_0, "/user/hand/left/input/trigger/proximity", "/user/hand/left/input/trigger/proximity_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3535 { XR_API_VERSION_1_1_0, "/user/hand/right/input/trigger/proximity", "/user/hand/right/input/trigger/proximity_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3536 { XR_API_VERSION_1_1_0, "/user/hand/left/output/haptic_trigger", "/user/hand/left/output/haptic_trigger_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3537 { XR_API_VERSION_1_1_0, "/user/hand/right/output/haptic_trigger", "/user/hand/right/output/haptic_trigger_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3538 { XR_API_VERSION_1_1_0, "/user/hand/left/output/haptic_thumb", "/user/hand/left/output/haptic_thumb_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3539 { XR_API_VERSION_1_1_0, "/user/hand/right/output/haptic_thumb", "/user/hand/right/output/haptic_thumb_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3540 { XR_API_VERSION_1_1_0, "/user/hand/left/input/thumb_resting_surfaces/proximity", "/user/hand/left/input/thumb_fb/proximity_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3541 { XR_API_VERSION_1_1_0, "/user/hand/right/input/thumb_resting_surfaces/proximity", "/user/hand/right/input/thumb_fb/proximity_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3542 { XR_API_VERSION_1_1_0, "/user/hand/left/input/trigger_curl/value", "/user/hand/left/input/trigger/curl_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3543 { XR_API_VERSION_1_1_0, "/user/hand/right/input/trigger_curl/value", "/user/hand/right/input/trigger/curl_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3544 { XR_API_VERSION_1_1_0, "/user/hand/left/input/trigger_slide/value", "/user/hand/left/input/trigger/slide_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3545 { XR_API_VERSION_1_1_0, "/user/hand/right/input/trigger_slide/value", "/user/hand/right/input/trigger/slide_fb", "/interaction_profiles/facebook/touch_controller_pro" },
3546
3547 // Specific renames for touch_controller_plus, note that we would have already renamed it to the old name.
3548 { XR_API_VERSION_1_1_0, "/user/hand/left/input/trigger/proximity", "/user/hand/left/input/trigger/proximity_meta", "/interaction_profiles/facebook/touch_controller_plus" },
3549 { XR_API_VERSION_1_1_0, "/user/hand/right/input/trigger/proximity", "/user/hand/right/input/trigger/proximity_meta", "/interaction_profiles/facebook/touch_controller_plus" },
3550 { XR_API_VERSION_1_1_0, "/user/hand/left/input/thumb_resting_surfaces/proximity", "/user/hand/left/input/thumb_meta/proximity_meta", "/interaction_profiles/facebook/touch_controller_plus" },
3551 { XR_API_VERSION_1_1_0, "/user/hand/right/input/thumb_resting_surfaces/proximity", "/user/hand/right/input/thumb_meta/proximity_meta", "/interaction_profiles/facebook/touch_controller_plus" },
3552 { XR_API_VERSION_1_1_0, "/user/hand/left/input/trigger_curl/value", "/user/hand/left/input/trigger/curl_meta", "/interaction_profiles/facebook/touch_controller_plus" },
3553 { XR_API_VERSION_1_1_0, "/user/hand/right/input/trigger_curl/value", "/user/hand/right/input/trigger/curl_meta", "/interaction_profiles/facebook/touch_controller_plus" },
3554 { XR_API_VERSION_1_1_0, "/user/hand/left/input/trigger_slide/value", "/user/hand/left/input/trigger/slide_meta", "/interaction_profiles/facebook/touch_controller_plus" },
3555 { XR_API_VERSION_1_1_0, "/user/hand/right/input/trigger_slide/value", "/user/hand/right/input/trigger/slide_meta", "/interaction_profiles/facebook/touch_controller_plus" },
3556 };
3557 constexpr size_t length = sizeof(renames) / sizeof(renames[0]);
3558
3559 for (size_t i = 0; i < length; i++) {
3560 const RenameMap &rename = renames[i];
3561
3562 if (rename.before_version != 0 && openxr_version >= rename.before_version) {
3563 // We're done, we are on a new version than this, no need to check further.
3564 return p_path;
3565 }
3566
3567 if ((rename.profile == nullptr || p_interaction_profile_name == rename.profile) && strcmp(p_path, rename.from) == 0) {
3568 return rename.to;
3569 }
3570 }
3571
3572 return p_path;
3573 }
3574
3575 int OpenXRAPI::interaction_profile_add_binding(RID p_interaction_profile, RID p_action, const String &p_path) {
3576 InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
3577 ERR_FAIL_NULL_V(ip, -1);
3578
3579 if (!interaction_profile_supports_io_path(ip->name, p_path)) {
3580 return -1;
3581 }
3582
3583 XrActionSuggestedBinding binding;
3584
3585 Action *action = action_owner.get_or_null(p_action);
3586 ERR_FAIL_COND_V(action == nullptr || action->handle == XR_NULL_HANDLE, -1);
3587
3588 binding.action = action->handle;
3589
3590 XrResult result = xrStringToPath(instance, check_profile_path(ip->internal_name, p_path.utf8().get_data()), &binding.binding);
3591 if (XR_FAILED(result)) {
3592 print_line("OpenXR: failed to get path for ", p_path, "! [", get_error_string(result), "]");
3593 return -1;
3594 }
3595
3596 ip->bindings.push_back(binding);
3597
3598 return ip->bindings.size() - 1;
3599 }
3600
3601 bool OpenXRAPI::interaction_profile_add_modifier(RID p_interaction_profile, const PackedByteArray &p_modifier) {
3602 InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
3603 ERR_FAIL_NULL_V(ip, false);
3604
3605 if (!p_modifier.is_empty()) {
3606 // Add it to our stack.
3607 ip->modifiers.push_back(p_modifier);
3608 }
3609
3610 return true;
3611 }
3612
3613 bool OpenXRAPI::interaction_profile_suggest_bindings(RID p_interaction_profile) {
3614 ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
3615
3616 InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
3617 ERR_FAIL_NULL_V(ip, false);
3618
3619 void *next = nullptr;
3620
3621 // Note, extensions should only add binding modifiers if they are supported, else this may fail.
3622 XrBindingModificationsKHR binding_modifiers;
3623 Vector<const XrBindingModificationBaseHeaderKHR *> modifiers;
3624 if (!ip->modifiers.is_empty()) {
3625 for (const PackedByteArray &modifier : ip->modifiers) {
3626 const XrBindingModificationBaseHeaderKHR *ptr = (const XrBindingModificationBaseHeaderKHR *)modifier.ptr();
3627 modifiers.push_back(ptr);
3628 }
3629
3630 binding_modifiers.type = XR_TYPE_BINDING_MODIFICATIONS_KHR;
3631 binding_modifiers.next = next;
3632 binding_modifiers.bindingModificationCount = modifiers.size();
3633 binding_modifiers.bindingModifications = modifiers.ptr();
3634 next = &binding_modifiers;
3635 }
3636
3637 const XrInteractionProfileSuggestedBinding suggested_bindings = {
3638 XR_TYPE_INTERACTION_PROFILE_SUGGESTED_BINDING, // type
3639 next, // next
3640 ip->path, // interactionProfile
3641 uint32_t(ip->bindings.size()), // countSuggestedBindings
3642 ip->bindings.ptr() // suggestedBindings
3643 };
3644
3645 XrResult result = xrSuggestInteractionProfileBindings(instance, &suggested_bindings);
3646 if (result == XR_ERROR_PATH_UNSUPPORTED) {
3647 // this is fine, not all runtimes support all devices.
3648 print_verbose("OpenXR Interaction profile " + ip->name + " is not supported on this runtime");
3649 } else if (XR_FAILED(result)) {
3650 print_line("OpenXR: failed to suggest bindings for ", ip->name, "! [", get_error_string(result), "]");
3651 // reporting is enough...
3652 }
3653
3654 /* For debugging:
3655 print_verbose("Suggested bindings for " + ip->name);
3656 for (int i = 0; i < ip->bindings.size(); i++) {
3657 uint32_t strlen;
3658 char path[XR_MAX_PATH_LENGTH];
3659
3660 String action_name = action_get_name(get_action_rid(ip->bindings[i].action));
3661
3662 XrResult result = xrPathToString(instance, ip->bindings[i].binding, XR_MAX_PATH_LENGTH, &strlen, path);
3663 if (XR_FAILED(result)) {
3664 print_line("OpenXR: failed to retrieve bindings for ", action_name, "! [", get_error_string(result), "]");
3665 }
3666 print_verbose(" - " + action_name + " => " + String(path));
3667 }
3668 */
3669
3670 return true;
3671 }
3672
3673 void OpenXRAPI::interaction_profile_free(RID p_interaction_profile) {
3674 InteractionProfile *ip = interaction_profile_owner.get_or_null(p_interaction_profile);
3675 ERR_FAIL_NULL(ip);
3676
3677 ip->bindings.clear();
3678 ip->modifiers.clear();
3679
3680 interaction_profile_owner.free(p_interaction_profile);
3681 }
3682
3683 bool OpenXRAPI::sync_action_sets(const Vector<RID> &p_active_sets) {
3684 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
3685
3686 if (!running) {
3687 return false;
3688 }
3689
3690 Vector<XrActiveActionSet> active_sets;
3691 for (int i = 0; i < p_active_sets.size(); i++) {
3692 ActionSet *action_set = action_set_owner.get_or_null(p_active_sets[i]);
3693 if (action_set && action_set->handle != XR_NULL_HANDLE) {
3694 XrActiveActionSet aset;
3695 aset.actionSet = action_set->handle;
3696 aset.subactionPath = XR_NULL_PATH;
3697 active_sets.push_back(aset);
3698 }
3699 }
3700
3701 ERR_FAIL_COND_V(active_sets.is_empty(), false);
3702
3703 XrActionsSyncInfo sync_info = {
3704 XR_TYPE_ACTIONS_SYNC_INFO, // type
3705 nullptr, // next
3706 uint32_t(active_sets.size()), // countActiveActionSets
3707 active_sets.ptr() // activeActionSets
3708 };
3709
3710 XrResult result = xrSyncActions(session, &sync_info);
3711 if (XR_FAILED(result)) {
3712 ERR_FAIL_V_MSG(false, "OpenXR: failed to sync active action sets! [" + get_error_string(result) + "]");
3713 }
3714
3715 if (interaction_profile_changed) {
3716 // Just in case, see if we already have active trackers...
3717 for (const RID &tracker : tracker_owner.get_owned_list()) {
3718 tracker_check_profile(tracker);
3719 }
3720
3721 interaction_profile_changed = false;
3722 }
3723
3724 for (OpenXRExtensionWrapper *wrapper : registered_extension_wrappers) {
3725 wrapper->on_sync_actions();
3726 }
3727
3728 return true;
3729 }
3730
3731 bool OpenXRAPI::get_action_bool(RID p_action, RID p_tracker) {
3732 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
3733 Action *action = action_owner.get_or_null(p_action);
3734 ERR_FAIL_NULL_V(action, false);
3735 Tracker *tracker = tracker_owner.get_or_null(p_tracker);
3736 ERR_FAIL_NULL_V(tracker, false);
3737
3738 if (!running) {
3739 return false;
3740 }
3741
3742 ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_BOOLEAN_INPUT, false);
3743
3744 XrActionStateGetInfo get_info = {
3745 XR_TYPE_ACTION_STATE_GET_INFO, // type
3746 nullptr, // next
3747 action->handle, // action
3748 tracker->toplevel_path // subactionPath
3749 };
3750
3751 XrActionStateBoolean result_state;
3752 result_state.type = XR_TYPE_ACTION_STATE_BOOLEAN,
3753 result_state.next = nullptr;
3754 XrResult result = xrGetActionStateBoolean(session, &get_info, &result_state);
3755 if (XR_FAILED(result)) {
3756 print_line("OpenXR: couldn't get action boolean! [", get_error_string(result), "]");
3757 return false;
3758 }
3759
3760 return result_state.isActive && result_state.currentState;
3761 }
3762
3763 float OpenXRAPI::get_action_float(RID p_action, RID p_tracker) {
3764 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, 0.0);
3765 Action *action = action_owner.get_or_null(p_action);
3766 ERR_FAIL_NULL_V(action, 0.0);
3767 Tracker *tracker = tracker_owner.get_or_null(p_tracker);
3768 ERR_FAIL_NULL_V(tracker, 0.0);
3769
3770 if (!running) {
3771 return 0.0;
3772 }
3773
3774 ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_FLOAT_INPUT, 0.0);
3775
3776 XrActionStateGetInfo get_info = {
3777 XR_TYPE_ACTION_STATE_GET_INFO, // type
3778 nullptr, // next
3779 action->handle, // action
3780 tracker->toplevel_path // subactionPath
3781 };
3782
3783 XrActionStateFloat result_state;
3784 result_state.type = XR_TYPE_ACTION_STATE_FLOAT,
3785 result_state.next = nullptr;
3786 XrResult result = xrGetActionStateFloat(session, &get_info, &result_state);
3787 if (XR_FAILED(result)) {
3788 print_line("OpenXR: couldn't get action float! [", get_error_string(result), "]");
3789 return 0.0;
3790 }
3791
3792 return result_state.isActive ? result_state.currentState : 0.0;
3793 }
3794
3795 Vector2 OpenXRAPI::get_action_vector2(RID p_action, RID p_tracker) {
3796 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, Vector2());
3797 Action *action = action_owner.get_or_null(p_action);
3798 ERR_FAIL_NULL_V(action, Vector2());
3799 Tracker *tracker = tracker_owner.get_or_null(p_tracker);
3800 ERR_FAIL_NULL_V(tracker, Vector2());
3801
3802 if (!running) {
3803 return Vector2();
3804 }
3805
3806 ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VECTOR2F_INPUT, Vector2());
3807
3808 XrActionStateGetInfo get_info = {
3809 XR_TYPE_ACTION_STATE_GET_INFO, // type
3810 nullptr, // next
3811 action->handle, // action
3812 tracker->toplevel_path // subactionPath
3813 };
3814
3815 XrActionStateVector2f result_state;
3816 result_state.type = XR_TYPE_ACTION_STATE_VECTOR2F,
3817 result_state.next = nullptr;
3818 XrResult result = xrGetActionStateVector2f(session, &get_info, &result_state);
3819 if (XR_FAILED(result)) {
3820 print_line("OpenXR: couldn't get action vector2! [", get_error_string(result), "]");
3821 return Vector2();
3822 }
3823
3824 return result_state.isActive ? Vector2(result_state.currentState.x, result_state.currentState.y) : Vector2();
3825 }
3826
3827 XRPose::TrackingConfidence OpenXRAPI::get_action_pose(RID p_action, RID p_tracker, Transform3D &r_transform, Vector3 &r_linear_velocity, Vector3 &r_angular_velocity) {
3828 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, XRPose::XR_TRACKING_CONFIDENCE_NONE);
3829 Action *action = action_owner.get_or_null(p_action);
3830 ERR_FAIL_NULL_V(action, XRPose::XR_TRACKING_CONFIDENCE_NONE);
3831 Tracker *tracker = tracker_owner.get_or_null(p_tracker);
3832 ERR_FAIL_NULL_V(tracker, XRPose::XR_TRACKING_CONFIDENCE_NONE);
3833
3834 if (!running) {
3835 return XRPose::XR_TRACKING_CONFIDENCE_NONE;
3836 }
3837
3838 ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_POSE_INPUT, XRPose::XR_TRACKING_CONFIDENCE_NONE);
3839
3840 // print_verbose("Checking " + action->name + " => " + tracker->name + " (" + itos(tracker->toplevel_path) + ")");
3841
3842 uint64_t index = 0xFFFFFFFF;
3843 uint64_t size = uint64_t(action->trackers.size());
3844 for (uint64_t i = 0; i < size && index == 0xFFFFFFFF; i++) {
3845 if (action->trackers[i].tracker_rid == p_tracker) {
3846 index = i;
3847 }
3848 }
3849
3850 if (index == 0xFFFFFFFF) {
3851 // couldn't find it?
3852 return XRPose::XR_TRACKING_CONFIDENCE_NONE;
3853 }
3854
3855 XrTime display_time = get_predicted_display_time();
3856 if (display_time == 0) {
3857 return XRPose::XR_TRACKING_CONFIDENCE_NONE;
3858 }
3859
3860 if (action->trackers[index].space == XR_NULL_HANDLE) {
3861 // if this is a pose we need to define spaces
3862
3863 XrActionSpaceCreateInfo action_space_info = {
3864 XR_TYPE_ACTION_SPACE_CREATE_INFO, // type
3865 nullptr, // next
3866 action->handle, // action
3867 tracker->toplevel_path, // subactionPath
3868 {
3869 { 0.0, 0.0, 0.0, 1.0 }, // orientation
3870 { 0.0, 0.0, 0.0 } // position
3871 } // poseInActionSpace
3872 };
3873
3874 XrSpace space;
3875 XrResult result = xrCreateActionSpace(session, &action_space_info, &space);
3876 if (XR_FAILED(result)) {
3877 print_line("OpenXR: couldn't create action space! [", get_error_string(result), "]");
3878 return XRPose::XR_TRACKING_CONFIDENCE_NONE;
3879 }
3880
3881 action->trackers.ptrw()[index].space = space;
3882 }
3883
3884 XrSpaceVelocity velocity = {
3885 XR_TYPE_SPACE_VELOCITY, // type
3886 nullptr, // next
3887 0, // velocityFlags
3888 { 0.0, 0.0, 0.0 }, // linearVelocity
3889 { 0.0, 0.0, 0.0 } // angularVelocity
3890 };
3891
3892 XrSpaceLocation location = {
3893 XR_TYPE_SPACE_LOCATION, // type
3894 &velocity, // next
3895 0, // locationFlags
3896 {
3897 { 0.0, 0.0, 0.0, 0.0 }, // orientation
3898 { 0.0, 0.0, 0.0 } // position
3899 } // pose
3900 };
3901
3902 XrResult result = xrLocateSpace(action->trackers[index].space, play_space, display_time, &location);
3903 if (XR_FAILED(result)) {
3904 print_line("OpenXR: failed to locate space! [", get_error_string(result), "]");
3905 return XRPose::XR_TRACKING_CONFIDENCE_NONE;
3906 }
3907
3908 XRPose::TrackingConfidence confidence = transform_from_location(location, r_transform);
3909 parse_velocities(velocity, r_linear_velocity, r_angular_velocity);
3910
3911 return confidence;
3912 }
3913
3914 bool OpenXRAPI::trigger_haptic_pulse(RID p_action, RID p_tracker, float p_frequency, float p_amplitude, XrDuration p_duration_ns) {
3915 ERR_FAIL_COND_V(session == XR_NULL_HANDLE, false);
3916 Action *action = action_owner.get_or_null(p_action);
3917 ERR_FAIL_NULL_V(action, false);
3918 Tracker *tracker = tracker_owner.get_or_null(p_tracker);
3919 ERR_FAIL_NULL_V(tracker, false);
3920
3921 if (!running) {
3922 return false;
3923 }
3924
3925 ERR_FAIL_COND_V(action->action_type != XR_ACTION_TYPE_VIBRATION_OUTPUT, false);
3926
3927 XrHapticActionInfo action_info = {
3928 XR_TYPE_HAPTIC_ACTION_INFO, // type
3929 nullptr, // next
3930 action->handle, // action
3931 tracker->toplevel_path // subactionPath
3932 };
3933
3934 XrHapticVibration vibration = {
3935 XR_TYPE_HAPTIC_VIBRATION, // type
3936 nullptr, // next
3937 p_duration_ns, // duration
3938 p_frequency, // frequency
3939 p_amplitude, // amplitude
3940 };
3941
3942 XrResult result = xrApplyHapticFeedback(session, &action_info, (const XrHapticBaseHeader *)&vibration);
3943 if (XR_FAILED(result)) {
3944 print_line("OpenXR: failed to apply haptic feedback! [", get_error_string(result), "]");
3945 return false;
3946 }
3947
3948 return true;
3949 }
3950
3951 void OpenXRAPI::register_composition_layer_provider(OpenXRExtensionWrapper *p_extension) {
3952 ERR_FAIL_COND_MSG(running, "Cannot register OpenXR composition layer providers while the session is running.");
3953 composition_layer_providers.append(p_extension);
3954 }
3955
3956 void OpenXRAPI::unregister_composition_layer_provider(OpenXRExtensionWrapper *p_extension) {
3957 ERR_FAIL_COND_MSG(running, "Cannot unregister OpenXR composition layer providers while the session is running.");
3958 composition_layer_providers.erase(p_extension);
3959 }
3960
3961 void OpenXRAPI::register_projection_views_extension(OpenXRExtensionWrapper *p_extension) {
3962 ERR_FAIL_COND_MSG(running, "Cannot register OpenXR projection views extensions while the session is running.");
3963 projection_views_extensions.append(p_extension);
3964 }
3965
3966 void OpenXRAPI::unregister_projection_views_extension(OpenXRExtensionWrapper *p_extension) {
3967 ERR_FAIL_COND_MSG(running, "Cannot unregister OpenXR projection views extensions while the session is running.");
3968 projection_views_extensions.erase(p_extension);
3969 }
3970
3971 void OpenXRAPI::register_frame_info_extension(OpenXRExtensionWrapper *p_extension) {
3972 ERR_FAIL_COND_MSG(running, "Cannot register OpenXR frame info extensions while the session is running.");
3973 frame_info_extensions.append(p_extension);
3974 }
3975
3976 void OpenXRAPI::unregister_frame_info_extension(OpenXRExtensionWrapper *p_extension) {
3977 ERR_FAIL_COND_MSG(running, "Cannot unregister OpenXR frame info extensions while the session is running.");
3978 frame_info_extensions.erase(p_extension);
3979 }
3980
3981 const Vector<XrEnvironmentBlendMode> OpenXRAPI::get_supported_environment_blend_modes() {
3982 return supported_environment_blend_modes;
3983 }
3984
3985 bool OpenXRAPI::is_environment_blend_mode_supported(XrEnvironmentBlendMode p_blend_mode) const {
3986 return supported_environment_blend_modes.has(p_blend_mode);
3987 }
3988
3989 bool OpenXRAPI::set_environment_blend_mode(XrEnvironmentBlendMode p_blend_mode) {
3990 if (emulate_environment_blend_mode_alpha_blend && p_blend_mode == XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND) {
3991 requested_environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND;
3992 environment_blend_mode = XR_ENVIRONMENT_BLEND_MODE_OPAQUE;
3993 set_render_environment_blend_mode(environment_blend_mode);
3994 return true;
3995 }
3996 // We allow setting this when not initialized and will check if it is supported when initializing.
3997 // After OpenXR is initialized we verify we're setting a supported blend mode.
3998 else if (!is_initialized() || is_environment_blend_mode_supported(p_blend_mode)) {
3999 requested_environment_blend_mode = p_blend_mode;
4000 environment_blend_mode = p_blend_mode;
4001 set_render_environment_blend_mode(environment_blend_mode);
4002 return true;
4003 }
4004 return false;
4005 }
4006
4007 void OpenXRAPI::set_emulate_environment_blend_mode_alpha_blend(bool p_enabled) {
4008 emulate_environment_blend_mode_alpha_blend = p_enabled;
4009 }
4010
4011 OpenXRAPI::OpenXRAlphaBlendModeSupport OpenXRAPI::is_environment_blend_mode_alpha_blend_supported() {
4012 if (emulate_environment_blend_mode_alpha_blend) {
4013 return OPENXR_ALPHA_BLEND_MODE_SUPPORT_EMULATING;
4014 } else if (is_environment_blend_mode_supported(XR_ENVIRONMENT_BLEND_MODE_ALPHA_BLEND)) {
4015 return OPENXR_ALPHA_BLEND_MODE_SUPPORT_REAL;
4016 }
4017 return OPENXR_ALPHA_BLEND_MODE_SUPPORT_NONE;
4018 }