openxr_spatial_anchor.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  1. /**************************************************************************/
  2. /* openxr_spatial_anchor.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "openxr_spatial_anchor.h"
  31. #include "../../openxr_api.h"
  32. #include "../../openxr_util.h"
  33. #include "../openxr_future_extension.h"
  34. #include "core/config/project_settings.h"
  35. #include "servers/xr_server.h"
  36. ////////////////////////////////////////////////////////////////////////////
  37. // OpenXRSpatialCapabilityConfigurationAnchor
  38. void OpenXRSpatialCapabilityConfigurationAnchor::_bind_methods() {
  39. ClassDB::bind_method(D_METHOD("get_enabled_components"), &OpenXRSpatialCapabilityConfigurationAnchor::_get_enabled_components);
  40. }
  41. bool OpenXRSpatialCapabilityConfigurationAnchor::has_valid_configuration() const {
  42. OpenXRSpatialAnchorCapability *capability = OpenXRSpatialAnchorCapability::get_singleton();
  43. ERR_FAIL_NULL_V(capability, false);
  44. return capability->is_spatial_anchor_supported();
  45. }
  46. XrSpatialCapabilityConfigurationBaseHeaderEXT *OpenXRSpatialCapabilityConfigurationAnchor::get_configuration() {
  47. OpenXRSpatialAnchorCapability *capability = OpenXRSpatialAnchorCapability::get_singleton();
  48. ERR_FAIL_NULL_V(capability, nullptr);
  49. if (capability->is_spatial_anchor_supported()) {
  50. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  51. ERR_FAIL_NULL_V(se_extension, nullptr);
  52. anchor_enabled_components.clear();
  53. // Guaranteed components:
  54. anchor_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_ANCHOR_EXT);
  55. // enable optional components
  56. if (capability->is_spatial_persistence_supported()) {
  57. anchor_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_PERSISTENCE_EXT);
  58. }
  59. anchor_config.enabledComponentCount = anchor_enabled_components.size();
  60. anchor_config.enabledComponents = anchor_enabled_components.ptr();
  61. // and return this.
  62. return (XrSpatialCapabilityConfigurationBaseHeaderEXT *)&anchor_config;
  63. }
  64. return nullptr;
  65. }
  66. PackedInt64Array OpenXRSpatialCapabilityConfigurationAnchor::_get_enabled_components() const {
  67. PackedInt64Array components;
  68. for (const XrSpatialComponentTypeEXT &component_type : anchor_enabled_components) {
  69. components.push_back((int64_t)component_type);
  70. }
  71. return components;
  72. }
  73. ////////////////////////////////////////////////////////////////////////////
  74. // OpenXRSpatialComponentAnchorList
  75. void OpenXRSpatialComponentAnchorList::_bind_methods() {
  76. ClassDB::bind_method(D_METHOD("get_entity_pose", "index"), &OpenXRSpatialComponentAnchorList::get_entity_pose);
  77. }
  78. void OpenXRSpatialComponentAnchorList::set_capacity(uint32_t p_capacity) {
  79. entity_poses.resize(p_capacity);
  80. anchor_list.locationCount = uint32_t(entity_poses.size());
  81. anchor_list.locations = entity_poses.ptrw();
  82. }
  83. XrSpatialComponentTypeEXT OpenXRSpatialComponentAnchorList::get_component_type() const {
  84. return XR_SPATIAL_COMPONENT_TYPE_ANCHOR_EXT;
  85. }
  86. void *OpenXRSpatialComponentAnchorList::get_structure_data(void *p_next) {
  87. anchor_list.next = p_next;
  88. return &anchor_list;
  89. }
  90. Transform3D OpenXRSpatialComponentAnchorList::get_entity_pose(int64_t p_index) const {
  91. ERR_FAIL_INDEX_V(p_index, entity_poses.size(), Transform3D());
  92. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  93. ERR_FAIL_NULL_V(openxr_api, Transform3D());
  94. return openxr_api->transform_from_pose(entity_poses[p_index]);
  95. }
  96. ////////////////////////////////////////////////////////////////////////////
  97. // OpenXRSpatialContextPersistenceConfig
  98. void OpenXRSpatialContextPersistenceConfig::_bind_methods() {
  99. ClassDB::bind_method(D_METHOD("add_persistence_context", "persistence_context"), &OpenXRSpatialContextPersistenceConfig::add_persistence_context);
  100. ClassDB::bind_method(D_METHOD("remove_persistence_context", "persistence_context"), &OpenXRSpatialContextPersistenceConfig::remove_persistence_context);
  101. }
  102. bool OpenXRSpatialContextPersistenceConfig::has_valid_configuration() const {
  103. OpenXRSpatialAnchorCapability *capability = OpenXRSpatialAnchorCapability::get_singleton();
  104. ERR_FAIL_NULL_V(capability, false);
  105. if (!capability->is_spatial_persistence_supported()) {
  106. return false;
  107. }
  108. // Check if we have a valid config.
  109. if (persistence_contexts.is_empty()) {
  110. return false;
  111. }
  112. return true;
  113. }
  114. void *OpenXRSpatialContextPersistenceConfig::get_header(void *p_next) {
  115. void *n = p_next;
  116. if (get_next().is_valid()) {
  117. n = get_next()->get_header(n);
  118. }
  119. if (has_valid_configuration()) {
  120. OpenXRSpatialAnchorCapability *anchor_capability = OpenXRSpatialAnchorCapability::get_singleton();
  121. ERR_FAIL_NULL_V(anchor_capability, nullptr);
  122. // Prepare our buffer.
  123. context_handles.resize(persistence_contexts.size());
  124. // Copy our handles.
  125. XrSpatialPersistenceContextEXT *ptr = context_handles.ptrw();
  126. int i = 0;
  127. for (const RID &rid : persistence_contexts) {
  128. ptr[i++] = anchor_capability->get_persistence_context_handle(rid);
  129. }
  130. persistence_config.next = n;
  131. persistence_config.persistenceContextCount = (uint32_t)context_handles.size();
  132. persistence_config.persistenceContexts = context_handles.ptr();
  133. // and return this.
  134. return (XrSpatialCapabilityConfigurationBaseHeaderEXT *)&persistence_config;
  135. }
  136. return n;
  137. }
  138. XrStructureType OpenXRSpatialContextPersistenceConfig::get_structure_type() {
  139. return XR_TYPE_SPATIAL_CONTEXT_PERSISTENCE_CONFIG_EXT;
  140. }
  141. void OpenXRSpatialContextPersistenceConfig::add_persistence_context(RID p_persistence_context) {
  142. ERR_FAIL_COND(persistence_contexts.has(p_persistence_context));
  143. persistence_contexts.push_back(p_persistence_context);
  144. }
  145. void OpenXRSpatialContextPersistenceConfig::remove_persistence_context(RID p_persistence_context) {
  146. ERR_FAIL_COND(!persistence_contexts.has(p_persistence_context));
  147. persistence_contexts.erase(p_persistence_context);
  148. }
  149. ////////////////////////////////////////////////////////////////////////////
  150. // OpenXRSpatialComponentPersistenceList
  151. void OpenXRSpatialComponentPersistenceList::_bind_methods() {
  152. ClassDB::bind_method(D_METHOD("get_persistent_uuid", "index"), &OpenXRSpatialComponentPersistenceList::_get_persistent_uuid);
  153. ClassDB::bind_method(D_METHOD("get_persistent_state", "index"), &OpenXRSpatialComponentPersistenceList::_get_persistent_state);
  154. }
  155. void OpenXRSpatialComponentPersistenceList::set_capacity(uint32_t p_capacity) {
  156. persist_data.resize(p_capacity);
  157. persistence_list.persistDataCount = uint32_t(persist_data.size());
  158. persistence_list.persistData = persist_data.ptrw();
  159. }
  160. XrSpatialComponentTypeEXT OpenXRSpatialComponentPersistenceList::get_component_type() const {
  161. return XR_SPATIAL_COMPONENT_TYPE_PERSISTENCE_EXT;
  162. }
  163. void *OpenXRSpatialComponentPersistenceList::get_structure_data(void *p_next) {
  164. persistence_list.next = p_next;
  165. return &persistence_list;
  166. }
  167. XrUuid OpenXRSpatialComponentPersistenceList::get_persistent_uuid(int64_t p_index) const {
  168. XrUuid null_uuid = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  169. ERR_FAIL_INDEX_V(p_index, persist_data.size(), null_uuid);
  170. return persist_data[p_index].persistUuid;
  171. }
  172. String OpenXRSpatialComponentPersistenceList::_get_persistent_uuid(int64_t p_index) const {
  173. return OpenXRUtil::string_from_xruuid(get_persistent_uuid(p_index));
  174. }
  175. XrSpatialPersistenceStateEXT OpenXRSpatialComponentPersistenceList::get_persistent_state(int64_t p_index) const {
  176. ERR_FAIL_INDEX_V(p_index, persist_data.size(), XR_SPATIAL_PERSISTENCE_STATE_MAX_ENUM_EXT);
  177. return persist_data[p_index].persistState;
  178. }
  179. uint64_t OpenXRSpatialComponentPersistenceList::_get_persistent_state(int64_t p_index) const {
  180. // TODO make a Godot constant that mirrors XrSpatialPersistenceStateEXT and return that
  181. return (uint64_t)get_persistent_state(p_index);
  182. }
  183. String OpenXRSpatialComponentPersistenceList::get_persistence_state_name(XrSpatialPersistenceStateEXT p_state) {
  184. XR_ENUM_SWITCH(XrSpatialPersistenceStateEXT, p_state)
  185. }
  186. ////////////////////////////////////////////////////////////////////////////
  187. // OpenXRAnchorTracker
  188. void OpenXRAnchorTracker::_bind_methods() {
  189. ClassDB::bind_method(D_METHOD("has_uuid"), &OpenXRAnchorTracker::has_uuid);
  190. ClassDB::bind_method(D_METHOD("set_uuid", "uuid"), &OpenXRAnchorTracker::_set_uuid);
  191. ClassDB::bind_method(D_METHOD("get_uuid"), &OpenXRAnchorTracker::_get_uuid);
  192. ADD_PROPERTY(PropertyInfo(Variant::STRING, "uuid"), "set_uuid", "get_uuid");
  193. ADD_SIGNAL(MethodInfo("uuid_changed"));
  194. }
  195. bool OpenXRAnchorTracker::has_uuid() const {
  196. for (int i = 0; i < XR_UUID_SIZE; i++) {
  197. if (uuid.data[i] != 0) {
  198. return true;
  199. }
  200. }
  201. return false;
  202. }
  203. XrUuid OpenXRAnchorTracker::get_uuid() const {
  204. return uuid;
  205. }
  206. void OpenXRAnchorTracker::set_uuid(const XrUuid &p_uuid) {
  207. if (uuid_is_equal(uuid, p_uuid)) {
  208. return;
  209. }
  210. uuid = p_uuid;
  211. emit_signal(SNAME("uuid_changed"));
  212. }
  213. String OpenXRAnchorTracker::_get_uuid() const {
  214. return OpenXRUtil::string_from_xruuid(uuid);
  215. }
  216. void OpenXRAnchorTracker::_set_uuid(const String &p_uuid) {
  217. set_uuid(OpenXRUtil::xruuid_from_string(p_uuid));
  218. }
  219. bool OpenXRAnchorTracker::uuid_is_equal(const XrUuid &p_a, const XrUuid &p_b) {
  220. for (int i = 0; i < XR_UUID_SIZE; i++) {
  221. if (p_a.data[i] != p_b.data[i]) {
  222. return false;
  223. }
  224. }
  225. return true;
  226. }
  227. ////////////////////////////////////////////////////////////////////////////
  228. // OpenXRSpatialAnchorCapability
  229. OpenXRSpatialAnchorCapability *OpenXRSpatialAnchorCapability::singleton = nullptr;
  230. OpenXRSpatialAnchorCapability *OpenXRSpatialAnchorCapability::get_singleton() {
  231. return singleton;
  232. }
  233. OpenXRSpatialAnchorCapability::OpenXRSpatialAnchorCapability() {
  234. singleton = this;
  235. }
  236. OpenXRSpatialAnchorCapability::~OpenXRSpatialAnchorCapability() {
  237. singleton = nullptr;
  238. }
  239. void OpenXRSpatialAnchorCapability::_bind_methods() {
  240. ClassDB::bind_method(D_METHOD("is_spatial_anchor_supported"), &OpenXRSpatialAnchorCapability::is_spatial_anchor_supported);
  241. ClassDB::bind_method(D_METHOD("is_spatial_persistence_supported"), &OpenXRSpatialAnchorCapability::is_spatial_persistence_supported);
  242. ClassDB::bind_method(D_METHOD("is_persistence_scope_supported", "scope"), &OpenXRSpatialAnchorCapability::_is_persistence_scope_supported);
  243. ClassDB::bind_method(D_METHOD("create_persistence_context", "scope", "user_callback"), &OpenXRSpatialAnchorCapability::_create_persistence_context, DEFVAL(Callable()));
  244. ClassDB::bind_method(D_METHOD("get_persistence_context_handle", "persistence_context"), &OpenXRSpatialAnchorCapability::_get_persistence_context_handle);
  245. ClassDB::bind_method(D_METHOD("free_persistence_context", "persistence_context"), &OpenXRSpatialAnchorCapability::free_persistence_context);
  246. ClassDB::bind_method(D_METHOD("create_new_anchor", "transform", "spatial_context"), &OpenXRSpatialAnchorCapability::create_new_anchor, DEFVAL(RID()));
  247. ClassDB::bind_method(D_METHOD("remove_anchor", "anchor_tracker"), &OpenXRSpatialAnchorCapability::remove_anchor);
  248. ClassDB::bind_method(D_METHOD("persist_anchor", "anchor_tracker", "persistence_context", "user_callback"), &OpenXRSpatialAnchorCapability::persist_anchor, DEFVAL(RID()), DEFVAL(Callable()));
  249. ClassDB::bind_method(D_METHOD("unpersist_anchor", "anchor_tracker", "persistence_context", "user_callback"), &OpenXRSpatialAnchorCapability::unpersist_anchor, DEFVAL(RID()), DEFVAL(Callable()));
  250. BIND_ENUM_CONSTANT(PERSISTENCE_SCOPE_SYSTEM_MANAGED);
  251. BIND_ENUM_CONSTANT(PERSISTENCE_SCOPE_LOCAL_ANCHORS);
  252. }
  253. HashMap<String, bool *> OpenXRSpatialAnchorCapability::get_requested_extensions() {
  254. HashMap<String, bool *> request_extensions;
  255. if (GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enabled") && GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enable_spatial_anchors")) {
  256. request_extensions[XR_EXT_SPATIAL_ANCHOR_EXTENSION_NAME] = &spatial_anchor_ext;
  257. if (GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enable_persistent_anchors")) {
  258. request_extensions[XR_EXT_SPATIAL_PERSISTENCE_EXTENSION_NAME] = &spatial_persistence_ext;
  259. request_extensions[XR_EXT_SPATIAL_PERSISTENCE_OPERATIONS_EXTENSION_NAME] = &spatial_persistence_operations_ext;
  260. }
  261. }
  262. return request_extensions;
  263. }
  264. void OpenXRSpatialAnchorCapability::on_instance_created(const XrInstance p_instance) {
  265. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  266. ERR_FAIL_NULL(se_extension);
  267. if (spatial_anchor_ext) {
  268. EXT_INIT_XR_FUNC(xrCreateSpatialAnchorEXT);
  269. }
  270. if (spatial_persistence_ext) {
  271. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  272. ERR_FAIL_NULL(openxr_api);
  273. // TODO REMOVE THIS WORKAROUND ONCE POSSIBLE
  274. // There has been some back and forth between stores and scopes. Scopes won out.
  275. XrResult xr_result = openxr_api->get_instance_proc_addr("xrEnumerateSpatialPersistenceScopesEXT", (PFN_xrVoidFunction *)&xrEnumerateSpatialPersistenceScopesEXT_ptr);
  276. if (xr_result != XR_SUCCESS) {
  277. // Check for stores for compatibility with beta runtimes.
  278. // Lucky for us, related structs and enums are compatible.
  279. print_verbose("OpenXR: xrEnumerateSpatialPersistenceScopesEXT is not supported, falling back to xrEnumerateSpatialPersistenceStoresEXT!")
  280. xr_result = openxr_api->get_instance_proc_addr("xrEnumerateSpatialPersistenceStoresEXT", (PFN_xrVoidFunction *)&xrEnumerateSpatialPersistenceScopesEXT_ptr);
  281. }
  282. ERR_FAIL_COND(XR_FAILED(xr_result));
  283. //EXT_INIT_XR_FUNC(xrEnumerateSpatialPersistenceScopesEXT);
  284. EXT_INIT_XR_FUNC(xrCreateSpatialPersistenceContextAsyncEXT);
  285. EXT_INIT_XR_FUNC(xrCreateSpatialPersistenceContextCompleteEXT);
  286. EXT_INIT_XR_FUNC(xrDestroySpatialPersistenceContextEXT);
  287. }
  288. if (spatial_persistence_operations_ext) {
  289. EXT_INIT_XR_FUNC(xrPersistSpatialEntityAsyncEXT);
  290. EXT_INIT_XR_FUNC(xrPersistSpatialEntityCompleteEXT);
  291. EXT_INIT_XR_FUNC(xrUnpersistSpatialEntityAsyncEXT);
  292. EXT_INIT_XR_FUNC(xrUnpersistSpatialEntityCompleteEXT);
  293. }
  294. }
  295. void OpenXRSpatialAnchorCapability::on_instance_destroyed() {
  296. xrCreateSpatialAnchorEXT_ptr = nullptr;
  297. xrEnumerateSpatialPersistenceScopesEXT_ptr = nullptr;
  298. xrCreateSpatialPersistenceContextAsyncEXT_ptr = nullptr;
  299. xrCreateSpatialPersistenceContextCompleteEXT_ptr = nullptr;
  300. xrDestroySpatialPersistenceContextEXT_ptr = nullptr;
  301. }
  302. void OpenXRSpatialAnchorCapability::on_session_created(const XrSession p_session) {
  303. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  304. ERR_FAIL_NULL(se_extension);
  305. if (!spatial_anchor_ext) {
  306. return;
  307. }
  308. spatial_anchor_supported = se_extension->supports_component_type(XR_SPATIAL_CAPABILITY_ANCHOR_EXT, XR_SPATIAL_COMPONENT_TYPE_ANCHOR_EXT);
  309. if (!spatial_anchor_supported) {
  310. // Supported by XR runtime but not by device? We're done.
  311. return;
  312. }
  313. _load_supported_persistence_scopes();
  314. se_extension->connect(SNAME("spatial_discovery_recommended"), callable_mp(this, &OpenXRSpatialAnchorCapability::_on_spatial_discovery_recommended));
  315. if (GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enable_builtin_anchor_detection")) {
  316. if (spatial_persistence_ext && !supported_persistence_scopes.is_empty()) {
  317. // TODO make something nicer to select the persistence scope we want.
  318. // We may even want to create multiple here so we get access to all
  319. // but then mark one that we use to create our persistent anchors on.
  320. XrSpatialPersistenceScopeEXT scope = XR_SPATIAL_PERSISTENCE_SCOPE_MAX_ENUM_EXT;
  321. // Lets check these in order of importance to us and find the best applicable scope.
  322. if (supported_persistence_scopes.has(XR_SPATIAL_PERSISTENCE_SCOPE_LOCAL_ANCHORS_EXT)) {
  323. // This scope allows for local storage and is required if we want to create our own anchors.
  324. scope = XR_SPATIAL_PERSISTENCE_SCOPE_LOCAL_ANCHORS_EXT;
  325. } else if (supported_persistence_scopes.has(XR_SPATIAL_PERSISTENCE_SCOPE_SYSTEM_MANAGED_EXT)) {
  326. // The system managed scope is a read only scope with system managed anchors.
  327. scope = XR_SPATIAL_PERSISTENCE_SCOPE_SYSTEM_MANAGED_EXT;
  328. } else {
  329. // Just use the first supported scope, but this will be an unknown type.
  330. scope = supported_persistence_scopes[0];
  331. }
  332. // Output what we're using:
  333. print_verbose("OpenXR: Using persistence scope " + get_spatial_persistence_scope_name(scope));
  334. // Start by creating our persistence context.
  335. create_persistence_context(scope, callable_mp(this, &OpenXRSpatialAnchorCapability::_on_persistence_context_completed));
  336. } else {
  337. // Start by creating our spatial context
  338. _create_spatial_context();
  339. }
  340. }
  341. }
  342. void OpenXRSpatialAnchorCapability::on_session_destroyed() {
  343. if (!spatial_anchor_supported) {
  344. return;
  345. }
  346. spatial_anchor_supported = false;
  347. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  348. ERR_FAIL_NULL(se_extension);
  349. XRServer *xr_server = XRServer::get_singleton();
  350. ERR_FAIL_NULL(xr_server);
  351. // Free and unregister our anchors
  352. for (const KeyValue<XrSpatialEntityIdEXT, Ref<OpenXRAnchorTracker>> &anchor : anchors) {
  353. xr_server->remove_tracker(anchor.value);
  354. }
  355. anchors.clear();
  356. // Free our configurations
  357. anchor_configuration.unref();
  358. // Free our spatial context
  359. if (spatial_context.is_valid()) {
  360. se_extension->free_spatial_context(spatial_context);
  361. spatial_context = RID();
  362. }
  363. // Free our persistence context
  364. if (persistence_context.is_valid()) {
  365. free_persistence_context(persistence_context);
  366. persistence_context = RID();
  367. }
  368. se_extension->disconnect(SNAME("spatial_discovery_recommended"), callable_mp(this, &OpenXRSpatialAnchorCapability::_on_spatial_discovery_recommended));
  369. supported_persistence_scopes.clear();
  370. // Clean up all remaining persistence context RIDs.
  371. LocalVector<RID> persistence_context_rids = persistence_context_owner.get_owned_list();
  372. for (const RID &rid : persistence_context_rids) {
  373. if (is_print_verbose_enabled()) {
  374. PersistenceContextData *persistence_context_data = persistence_context_owner.get_or_null(rid);
  375. if (persistence_context_data) { // Should never be nullptr seeing we called get_owned_list just now, but just in case.
  376. print_line("OpenXR: Found orphaned persistence context for scope ", get_spatial_persistence_scope_name(persistence_context_data->scope));
  377. }
  378. }
  379. free_persistence_context(rid);
  380. }
  381. }
  382. void OpenXRSpatialAnchorCapability::on_process() {
  383. if (!spatial_context.is_valid()) {
  384. return;
  385. }
  386. // Protection against plane discovery happening too often.
  387. if (discovery_cooldown > 0) {
  388. discovery_cooldown--;
  389. }
  390. // Check if we need to start our discovery.
  391. if (need_discovery && discovery_cooldown == 0 && !discovery_query_result.is_valid()) {
  392. need_discovery = false;
  393. discovery_cooldown = 60; // Set our cooldown to 60 frames, it doesn't need to be an exact science.
  394. _start_entity_discovery();
  395. }
  396. // If we have a valid spatial context, and we have anchors, we want updates!
  397. if (spatial_context.is_valid() && !anchors.is_empty()) {
  398. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  399. ERR_FAIL_NULL(se_extension);
  400. // We want updates for all anchors
  401. thread_local LocalVector<RID> entities;
  402. entities.resize(anchors.size());
  403. RID *entity = entities.ptr();
  404. for (const KeyValue<XrSpatialEntityIdEXT, Ref<OpenXRAnchorTracker>> &e : anchors) {
  405. *entity = e.value->get_entity();
  406. entity++;
  407. }
  408. // We just want our anchor component
  409. thread_local LocalVector<XrSpatialComponentTypeEXT> component_types;
  410. component_types.push_back(XR_SPATIAL_COMPONENT_TYPE_ANCHOR_EXT);
  411. // And we get our update snapshot, this is NOT async!
  412. RID snapshot = se_extension->update_spatial_entities(spatial_context, entities, component_types, nullptr);
  413. if (snapshot.is_valid()) {
  414. _process_update_snapshot(snapshot);
  415. }
  416. }
  417. }
  418. bool OpenXRSpatialAnchorCapability::is_spatial_anchor_supported() {
  419. return spatial_anchor_supported;
  420. }
  421. bool OpenXRSpatialAnchorCapability::is_spatial_persistence_supported() {
  422. // Need anchor support for persistence to be usable
  423. if (!is_spatial_anchor_supported()) {
  424. return false;
  425. }
  426. return spatial_persistence_ext;
  427. }
  428. ////////////////////////////////////////////////////////////////////////////
  429. // Persistence scopes
  430. bool OpenXRSpatialAnchorCapability::_load_supported_persistence_scopes() {
  431. ERR_FAIL_COND_V(!is_spatial_persistence_supported(), false);
  432. if (supported_persistence_scopes.is_empty()) {
  433. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  434. ERR_FAIL_NULL_V(openxr_api, false);
  435. uint32_t size;
  436. XrInstance instance = openxr_api->get_instance();
  437. XrSystemId system_id = openxr_api->get_system_id();
  438. ERR_FAIL_COND_V(instance == XR_NULL_HANDLE, false);
  439. XrResult result = xrEnumerateSpatialPersistenceScopesEXT(instance, system_id, 0, &size, nullptr);
  440. if (XR_FAILED(result)) {
  441. ERR_FAIL_V_MSG(false, "OpenXR: Failed to query persistence scope count [" + openxr_api->get_error_string(result) + "]");
  442. }
  443. if (size > 0) {
  444. supported_persistence_scopes.resize(size);
  445. result = xrEnumerateSpatialPersistenceScopesEXT(instance, system_id, supported_persistence_scopes.size(), &size, supported_persistence_scopes.ptrw());
  446. if (XR_FAILED(result)) {
  447. ERR_FAIL_V_MSG(false, "OpenXR: Failed to query persistence scopes [" + openxr_api->get_error_string(result) + "]");
  448. }
  449. }
  450. if (is_print_verbose_enabled()) {
  451. if (!supported_persistence_scopes.is_empty()) {
  452. print_verbose("OpenXR: Supported spatial persistence scopes:");
  453. for (const XrSpatialPersistenceScopeEXT &scope : supported_persistence_scopes) {
  454. print_verbose(" - " + get_spatial_persistence_scope_name(scope));
  455. }
  456. } else {
  457. WARN_PRINT("OpenXR: No persistence scopes found!");
  458. }
  459. }
  460. }
  461. return true;
  462. }
  463. bool OpenXRSpatialAnchorCapability::is_persistence_scope_supported(XrSpatialPersistenceScopeEXT p_scope) {
  464. if (!is_spatial_persistence_supported()) {
  465. return false;
  466. }
  467. if (!_load_supported_persistence_scopes()) {
  468. return false;
  469. }
  470. return supported_persistence_scopes.has(p_scope);
  471. }
  472. bool OpenXRSpatialAnchorCapability::_is_persistence_scope_supported(PersistenceScope p_scope) {
  473. return is_persistence_scope_supported((XrSpatialPersistenceScopeEXT)p_scope);
  474. }
  475. Ref<OpenXRFutureResult> OpenXRSpatialAnchorCapability::create_persistence_context(XrSpatialPersistenceScopeEXT p_scope, const Callable &p_user_callback) {
  476. if (!is_spatial_persistence_supported()) {
  477. return nullptr;
  478. }
  479. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  480. ERR_FAIL_NULL_V(openxr_api, nullptr);
  481. OpenXRFutureExtension *future_api = OpenXRFutureExtension::get_singleton();
  482. ERR_FAIL_NULL_V(future_api, nullptr);
  483. XrSpatialPersistenceContextCreateInfoEXT create_info = {
  484. XR_TYPE_SPATIAL_PERSISTENCE_CONTEXT_CREATE_INFO_EXT, // type
  485. nullptr, // next
  486. p_scope // scope
  487. };
  488. XrFutureEXT future = XR_NULL_HANDLE;
  489. XrResult result = xrCreateSpatialPersistenceContextAsyncEXT(openxr_api->get_session(), &create_info, &future);
  490. if (XR_FAILED(result)) {
  491. // Not successful? then exit.
  492. ERR_FAIL_V_MSG(Ref<OpenXRFutureResult>(), "OpenXR: Failed to create persistence scope [" + openxr_api->get_error_string(result) + "]");
  493. }
  494. // Create our future result
  495. Ref<OpenXRFutureResult> future_result = future_api->register_future(future, callable_mp(this, &OpenXRSpatialAnchorCapability::_on_persistence_context_ready).bind((uint64_t)p_scope, p_user_callback));
  496. return future_result;
  497. }
  498. Ref<OpenXRFutureResult> OpenXRSpatialAnchorCapability::_create_persistence_context(PersistenceScope p_scope, Callable p_user_callback) {
  499. return create_persistence_context((XrSpatialPersistenceScopeEXT)p_scope, p_user_callback);
  500. }
  501. void OpenXRSpatialAnchorCapability::_on_persistence_context_ready(Ref<OpenXRFutureResult> p_future_result, uint64_t p_scope, Callable p_user_callback) {
  502. // Complete context creation...
  503. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  504. ERR_FAIL_NULL(openxr_api);
  505. XrCreateSpatialPersistenceContextCompletionEXT completion = {
  506. XR_TYPE_CREATE_SPATIAL_PERSISTENCE_CONTEXT_COMPLETION_EXT, // type
  507. nullptr, // next
  508. XR_RESULT_MAX_ENUM, // futureResult
  509. XR_SPATIAL_PERSISTENCE_CONTEXT_RESULT_MAX_ENUM_EXT, // createResult
  510. XR_NULL_HANDLE // persistenceContext
  511. };
  512. XrResult result = xrCreateSpatialPersistenceContextCompleteEXT(openxr_api->get_session(), p_future_result->get_future(), &completion);
  513. if (XR_FAILED(result)) { // Did our xrCreateSpatialContextCompleteEXT call fail?
  514. // Log issue and fail.
  515. ERR_FAIL_MSG("OpenXR: Failed to complete persistence context create future [" + openxr_api->get_error_string(result) + "]");
  516. }
  517. if (XR_FAILED(completion.futureResult)) { // Did our completion fail?
  518. // Log issue and fail.
  519. ERR_FAIL_MSG("OpenXR: Failed to complete persistence context creation [" + openxr_api->get_error_string(completion.futureResult) + "]");
  520. }
  521. if (completion.createResult != XR_SPATIAL_PERSISTENCE_CONTEXT_RESULT_SUCCESS_EXT) { // Did our persist fail?
  522. // Log issue and fail.
  523. ERR_FAIL_MSG("OpenXR: Failed to complete persistence context creation [" + get_spatial_persistence_context_result_name(completion.createResult) + "]");
  524. }
  525. // Wrap our persistence context
  526. PersistenceContextData persistence_context_data;
  527. // Update our spatial context data
  528. persistence_context_data.scope = (XrSpatialPersistenceScopeEXT)p_scope;
  529. persistence_context_data.persistence_context = completion.persistenceContext;
  530. // Store this as an RID so we keep track of it.
  531. RID context_rid = persistence_context_owner.make_rid(persistence_context_data);
  532. // Set our RID as our result value on our future.
  533. p_future_result->set_result_value(context_rid);
  534. // And perform our callback if we have one.
  535. if (p_user_callback.is_valid()) {
  536. p_user_callback.call(context_rid);
  537. }
  538. }
  539. XrSpatialPersistenceContextEXT OpenXRSpatialAnchorCapability::get_persistence_context_handle(RID p_persistence_context) const {
  540. PersistenceContextData *persistence_context_data = persistence_context_owner.get_or_null(p_persistence_context);
  541. ERR_FAIL_NULL_V(persistence_context_data, XR_NULL_HANDLE);
  542. return persistence_context_data->persistence_context;
  543. }
  544. uint64_t OpenXRSpatialAnchorCapability::_get_persistence_context_handle(RID p_persistence_context) const {
  545. return (uint64_t)get_persistence_context_handle(p_persistence_context);
  546. }
  547. void OpenXRSpatialAnchorCapability::free_persistence_context(RID p_persistence_context) {
  548. PersistenceContextData *persistence_context_data = persistence_context_owner.get_or_null(p_persistence_context);
  549. ERR_FAIL_NULL(persistence_context_data);
  550. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  551. ERR_FAIL_NULL(openxr_api);
  552. if (persistence_context_data->persistence_context != XR_NULL_HANDLE) {
  553. // Destroy our spatial context
  554. XrResult result = xrDestroySpatialPersistenceContextEXT(persistence_context_data->persistence_context);
  555. if (XR_FAILED(result)) {
  556. WARN_PRINT("OpenXR: Failed to destroy the persistence context [" + openxr_api->get_error_string(result) + "]");
  557. }
  558. persistence_context_data->persistence_context = XR_NULL_HANDLE;
  559. }
  560. // And remove our RID.
  561. persistence_context_owner.free(p_persistence_context);
  562. }
  563. ////////////////////////////////////////////////////////////////////////////
  564. // Discovery logic
  565. void OpenXRSpatialAnchorCapability::_on_persistence_context_completed(RID p_persistence_context) {
  566. persistence_context = p_persistence_context;
  567. _create_spatial_context();
  568. }
  569. Ref<OpenXRFutureResult> OpenXRSpatialAnchorCapability::_create_spatial_context() {
  570. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  571. ERR_FAIL_NULL_V(se_extension, nullptr);
  572. TypedArray<OpenXRSpatialCapabilityConfigurationBaseHeader> capability_configurations;
  573. // Create our configuration objects.
  574. anchor_configuration.instantiate();
  575. capability_configurations.push_back(anchor_configuration);
  576. if (persistence_context.is_valid()) {
  577. persistence_configuration.instantiate();
  578. persistence_configuration->add_persistence_context(persistence_context);
  579. } else {
  580. // Shouldn't be instantiated in the first place but JIC
  581. persistence_configuration.unref();
  582. }
  583. return se_extension->create_spatial_context(capability_configurations, persistence_configuration, callable_mp(this, &OpenXRSpatialAnchorCapability::_on_spatial_context_created));
  584. }
  585. void OpenXRSpatialAnchorCapability::_on_spatial_context_created(RID p_spatial_context) {
  586. spatial_context = p_spatial_context;
  587. need_discovery = true;
  588. }
  589. void OpenXRSpatialAnchorCapability::_on_spatial_discovery_recommended(RID p_spatial_context) {
  590. if (p_spatial_context == spatial_context) {
  591. // Trigger new discovery.
  592. need_discovery = true;
  593. }
  594. }
  595. Ref<OpenXRFutureResult> OpenXRSpatialAnchorCapability::_start_entity_discovery() {
  596. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  597. ERR_FAIL_NULL_V(se_extension, nullptr);
  598. // It makes no sense to discover non persistent anchors as we'd have created them during this session.
  599. if (!persistence_context.is_valid()) {
  600. return nullptr;
  601. }
  602. // Already running or ran discovery, cancel/clean up.
  603. if (discovery_query_result.is_valid()) {
  604. discovery_query_result->cancel_future();
  605. discovery_query_result.unref();
  606. }
  607. // We want both our anchor and persistence component.
  608. Vector<XrSpatialComponentTypeEXT> component_types;
  609. component_types.push_back(XR_SPATIAL_COMPONENT_TYPE_ANCHOR_EXT);
  610. component_types.push_back(XR_SPATIAL_COMPONENT_TYPE_PERSISTENCE_EXT);
  611. // Start our new snapshot.
  612. discovery_query_result = se_extension->discover_spatial_entities(spatial_context, component_types, nullptr, callable_mp(this, &OpenXRSpatialAnchorCapability::_process_discovery_snapshot));
  613. return discovery_query_result;
  614. }
  615. void OpenXRSpatialAnchorCapability::_process_discovery_snapshot(RID p_snapshot) {
  616. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  617. ERR_FAIL_NULL(se_extension);
  618. XRServer *xr_server = XRServer::get_singleton();
  619. ERR_FAIL_NULL(xr_server);
  620. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  621. ERR_FAIL_NULL(openxr_api);
  622. // Build our component data.
  623. TypedArray<OpenXRSpatialComponentData> component_data;
  624. // We always need a query result data object.
  625. Ref<OpenXRSpatialQueryResultData> query_result_data;
  626. query_result_data.instantiate();
  627. component_data.push_back(query_result_data);
  628. // And an anchor list object.
  629. Ref<OpenXRSpatialComponentAnchorList> anchor_list_data;
  630. anchor_list_data.instantiate();
  631. component_data.push_back(anchor_list_data);
  632. // Note that adding this data object means our snapshot will only return persistent anchors!
  633. Ref<OpenXRSpatialComponentPersistenceList> persistence_list_data;
  634. persistence_list_data.instantiate();
  635. component_data.push_back(persistence_list_data);
  636. if (se_extension->query_snapshot(p_snapshot, component_data, nullptr)) {
  637. // Now loop through our data and update our anchors.
  638. int64_t size = query_result_data->get_capacity();
  639. for (int64_t i = 0; i < size; i++) {
  640. XrSpatialEntityIdEXT entity_id = query_result_data->get_entity_id(i);
  641. XrSpatialEntityTrackingStateEXT entity_state = query_result_data->get_entity_state(i);
  642. if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT) {
  643. // We shouldn't get stopped anchors for discovery queries, but JIC.
  644. if (anchors.has(entity_id)) {
  645. Ref<OpenXRAnchorTracker> anchor = anchors[entity_id];
  646. anchor->invalidate_pose(SNAME("default"));
  647. anchor->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT);
  648. }
  649. } else {
  650. // Process our entity.
  651. bool add_to_xr_server = false;
  652. Ref<OpenXRAnchorTracker> anchor;
  653. if (anchors.has(entity_id)) {
  654. // We know about this one already.
  655. anchor = anchors[entity_id];
  656. } else {
  657. // Create a new anchor.
  658. anchor.instantiate();
  659. anchor->set_entity(se_extension->make_spatial_entity(se_extension->get_spatial_snapshot_context(p_snapshot), entity_id));
  660. anchors[entity_id] = anchor;
  661. add_to_xr_server = true;
  662. }
  663. // Handle component data.
  664. if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_PAUSED_EXT) {
  665. anchor->invalidate_pose(SNAME("default"));
  666. anchor->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_PAUSED_EXT);
  667. // No further component data will be valid in this state, we need to ignore it!
  668. } else if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_TRACKING_EXT) {
  669. Transform3D transform = anchor_list_data->get_entity_pose(i);
  670. anchor->set_pose(SNAME("default"), transform, Vector3(), Vector3());
  671. anchor->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_TRACKING_EXT);
  672. }
  673. // Persistence is the only component that will contain valid data if entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_PAUSED_EXT.
  674. const XrSpatialPersistenceStateEXT persistent_state = persistence_list_data->get_persistent_state(i);
  675. if (persistent_state == XR_SPATIAL_PERSISTENCE_STATE_LOADED_EXT) {
  676. anchor->set_uuid(persistence_list_data->get_persistent_uuid(i));
  677. }
  678. if (add_to_xr_server) {
  679. // Register with XR server.
  680. xr_server->add_tracker(anchor);
  681. }
  682. }
  683. }
  684. // We don't remove trackers here, users will be removing anchors.
  685. // Maybe at some point when shared anchors between headsets result
  686. // in another device removing the shared anchor we need to deal with this.
  687. }
  688. // Now that we're done, clean up our snapshot!
  689. se_extension->free_spatial_snapshot(p_snapshot);
  690. // And if this was our discovery snapshot, let's reset it.
  691. if (discovery_query_result.is_valid() && discovery_query_result->get_result_value() == p_snapshot) {
  692. discovery_query_result.unref();
  693. }
  694. }
  695. void OpenXRSpatialAnchorCapability::_process_update_snapshot(RID p_snapshot) {
  696. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  697. ERR_FAIL_NULL(se_extension);
  698. XRServer *xr_server = XRServer::get_singleton();
  699. ERR_FAIL_NULL(xr_server);
  700. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  701. ERR_FAIL_NULL(openxr_api);
  702. // Build our component data.
  703. TypedArray<OpenXRSpatialComponentData> component_data;
  704. // We always need a query result data object.
  705. Ref<OpenXRSpatialQueryResultData> query_result_data;
  706. query_result_data.instantiate();
  707. component_data.push_back(query_result_data);
  708. // And an anchor list object.
  709. Ref<OpenXRSpatialComponentAnchorList> anchor_list_data;
  710. anchor_list_data.instantiate();
  711. component_data.push_back(anchor_list_data);
  712. if (se_extension->query_snapshot(p_snapshot, component_data, nullptr)) {
  713. // Now loop through our data and update our anchors.
  714. int64_t size = query_result_data->get_capacity();
  715. for (int64_t i = 0; i < size; i++) {
  716. XrSpatialEntityIdEXT entity_id = query_result_data->get_entity_id(i);
  717. XrSpatialEntityTrackingStateEXT entity_state = query_result_data->get_entity_state(i);
  718. if (anchors.has(entity_id)) {
  719. // Process our entity.
  720. Ref<OpenXRAnchorTracker> anchor = anchors[entity_id];
  721. if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT) {
  722. anchor->invalidate_pose(SNAME("default"));
  723. anchor->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT);
  724. } else if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_PAUSED_EXT) {
  725. anchor->invalidate_pose(SNAME("default"));
  726. anchor->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_PAUSED_EXT);
  727. } else if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_TRACKING_EXT) {
  728. Transform3D transform = anchor_list_data->get_entity_pose(i);
  729. anchor->set_pose(SNAME("default"), transform, Vector3(), Vector3());
  730. anchor->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_TRACKING_EXT);
  731. }
  732. } else {
  733. WARN_PRINT("OpenXR: Anchor update query returned unknown anchor with entity ID: " + String::num_int64(entity_id));
  734. }
  735. }
  736. }
  737. // Now that we're done, clean up our snapshot!
  738. se_extension->free_spatial_snapshot(p_snapshot);
  739. }
  740. ////////////////////////////////////////////////////////////////////////////
  741. // Anchor creation
  742. Ref<OpenXRAnchorTracker> OpenXRSpatialAnchorCapability::create_new_anchor(const Transform3D &p_transform, RID p_spatial_context) {
  743. Ref<OpenXRAnchorTracker> tracker;
  744. ERR_FAIL_COND_V_MSG(!is_spatial_anchor_supported(), tracker, "OpenXR: Spatial entity anchor capability is not supported on this hardware!");
  745. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  746. ERR_FAIL_NULL_V(openxr_api, tracker);
  747. XRServer *xr_server = XRServer::get_singleton();
  748. ERR_FAIL_NULL_V(xr_server, tracker);
  749. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  750. ERR_FAIL_NULL_V(se_extension, tracker);
  751. // TODO reverse apply world scale and reference frame to transform.
  752. XrPosef pose = openxr_api->pose_from_transform(p_transform);
  753. RID sc = p_spatial_context.is_valid() ? p_spatial_context : spatial_context;
  754. ERR_FAIL_COND_V(sc.is_null(), tracker);
  755. XrSpatialAnchorCreateInfoEXT create_info = {
  756. XR_TYPE_SPATIAL_ANCHOR_CREATE_INFO_EXT, // type
  757. nullptr, // next
  758. openxr_api->get_play_space(), // baseSpace
  759. openxr_api->get_predicted_display_time(), // time
  760. pose // pose
  761. };
  762. XrSpatialEntityIdEXT entity_id;
  763. XrSpatialEntityEXT entity;
  764. XrResult result = xrCreateSpatialAnchorEXT(se_extension->get_spatial_context_handle(sc), &create_info, &entity_id, &entity);
  765. if (XR_FAILED(result)) { // Did our xrCreateSpatialContextCompleteEXT call fail?
  766. ERR_FAIL_V_MSG(tracker, "OpenXR: Failed to create anchor [" + openxr_api->get_error_string(result) + "]");
  767. }
  768. tracker.instantiate();
  769. tracker->set_entity(se_extension->add_spatial_entity(sc, entity_id, entity));
  770. tracker->set_tracker_desc("Anchor");
  771. tracker->set_pose(SNAME("default"), p_transform, Vector3(), Vector3());
  772. // Remember our tracker.
  773. anchors[entity_id] = tracker;
  774. xr_server->add_tracker(tracker);
  775. return tracker;
  776. }
  777. void OpenXRSpatialAnchorCapability::remove_anchor(Ref<OpenXRAnchorTracker> p_anchor_tracker) {
  778. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  779. ERR_FAIL_NULL(openxr_api);
  780. XRServer *xr_server = XRServer::get_singleton();
  781. ERR_FAIL_NULL(xr_server);
  782. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  783. ERR_FAIL_NULL(se_extension);
  784. // We check for this here. We could do this asynchronous but the caller may than wrongly expect this method to be instant.
  785. ERR_FAIL_COND_MSG(p_anchor_tracker->has_uuid(), "OpenXR: This anchor is persistent. It must first be made unpersistent.");
  786. // Attempt to unregister it from our xr_server.
  787. xr_server->remove_tracker(p_anchor_tracker);
  788. // Get our entity.
  789. RID entity = p_anchor_tracker->get_entity();
  790. ERR_FAIL_COND(entity.is_null());
  791. // Get our entity id.
  792. XrSpatialEntityIdEXT entity_id = se_extension->get_spatial_entity_id(entity);
  793. ERR_FAIL_COND(entity_id == XR_NULL_ENTITY);
  794. // Remove it from our entity list.
  795. if (anchors.has(entity_id)) {
  796. anchors.erase(entity_id);
  797. }
  798. // Clear our entity, this will free it as well.
  799. p_anchor_tracker->set_entity(RID());
  800. // The anchor tracker will be cleaned up once its fully dereferenced.
  801. }
  802. Ref<OpenXRFutureResult> OpenXRSpatialAnchorCapability::persist_anchor(Ref<OpenXRAnchorTracker> p_anchor_tracker, RID p_persistence_context, const Callable &p_user_callback) {
  803. ERR_FAIL_COND_V(!is_spatial_persistence_supported(), nullptr);
  804. RID pc = p_persistence_context.is_valid() ? p_persistence_context : persistence_context;
  805. ERR_FAIL_COND_V(pc.is_null(), nullptr);
  806. ERR_FAIL_COND_V(p_anchor_tracker.is_null(), nullptr);
  807. PersistenceContextData *persistence_context_data = persistence_context_owner.get_or_null(pc);
  808. ERR_FAIL_NULL_V(persistence_context_data, nullptr);
  809. const XrSpatialPersistenceContextEXT persistence_context_handle = persistence_context_data->persistence_context;
  810. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  811. ERR_FAIL_NULL_V(openxr_api, nullptr);
  812. OpenXRFutureExtension *future_api = OpenXRFutureExtension::get_singleton();
  813. ERR_FAIL_NULL_V(future_api, nullptr);
  814. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  815. ERR_FAIL_NULL_V(se_extension, nullptr);
  816. RID entity = p_anchor_tracker->get_entity();
  817. ERR_FAIL_COND_V(entity.is_null(), nullptr);
  818. XrSpatialEntityIdEXT entity_id = se_extension->get_spatial_entity_id(entity);
  819. ERR_FAIL_COND_V(entity_id == XR_NULL_ENTITY, nullptr);
  820. RID spatial_context_rid = se_extension->get_spatial_entity_context(entity);
  821. const XrSpatialContextEXT spatial_context_handle = se_extension->get_spatial_context_handle(spatial_context_rid);
  822. XrFutureEXT future = XR_NULL_HANDLE;
  823. XrSpatialEntityPersistInfoEXT persist_info = {
  824. XR_TYPE_SPATIAL_ENTITY_PERSIST_INFO_EXT, // type
  825. nullptr, // next
  826. spatial_context_handle, // spatialContext
  827. entity_id // entityId
  828. };
  829. XrResult result = xrPersistSpatialEntityAsyncEXT(persistence_context_handle, &persist_info, &future);
  830. if (XR_FAILED(result)) {
  831. ERR_FAIL_V_MSG(nullptr, "OpenXR: Failed to start making anchor persistent [" + openxr_api->get_error_string(result) + "]");
  832. }
  833. // Create our future result.
  834. Ref<OpenXRFutureResult> future_result = future_api->register_future(future, callable_mp(this, &OpenXRSpatialAnchorCapability::_on_made_anchor_persistent).bind(pc, p_anchor_tracker, p_user_callback));
  835. return future_result;
  836. }
  837. void OpenXRSpatialAnchorCapability::_on_made_anchor_persistent(Ref<OpenXRFutureResult> p_future_result, RID p_persistence_context, Ref<OpenXRAnchorTracker> p_anchor_tracker, const Callable &p_user_callback) {
  838. ERR_FAIL_COND(p_anchor_tracker.is_null());
  839. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  840. ERR_FAIL_NULL(openxr_api);
  841. PersistenceContextData *persistence_context_data = persistence_context_owner.get_or_null(p_persistence_context);
  842. ERR_FAIL_NULL(persistence_context_data);
  843. XrFutureEXT future = p_future_result->get_future();
  844. XrPersistSpatialEntityCompletionEXT completion = {
  845. XR_TYPE_PERSIST_SPATIAL_ENTITY_COMPLETION_EXT, // type
  846. nullptr, // next
  847. XR_RESULT_MAX_ENUM, // futureResult
  848. XR_SPATIAL_PERSISTENCE_CONTEXT_RESULT_MAX_ENUM_EXT, // persistResult
  849. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } // persistUuid
  850. };
  851. XrResult result = xrPersistSpatialEntityCompleteEXT(persistence_context_data->persistence_context, future, &completion);
  852. if (XR_FAILED(result)) { // Did our xrCreateSpatialContextCompleteEXT call fail?
  853. p_future_result->set_result_value(false);
  854. ERR_FAIL_MSG("OpenXR: Failed to complete anchor persistent future [" + openxr_api->get_error_string(result) + "]");
  855. }
  856. if (XR_FAILED(completion.futureResult)) { // Did our completion fail?
  857. p_future_result->set_result_value(false);
  858. ERR_FAIL_MSG("OpenXR: Failed to complete making anchor persistent [" + openxr_api->get_error_string(completion.futureResult) + "]");
  859. }
  860. if (completion.persistResult != XR_SPATIAL_PERSISTENCE_CONTEXT_RESULT_SUCCESS_EXT) { // Did our process fail?
  861. p_future_result->set_result_value(false);
  862. ERR_FAIL_MSG("OpenXR: Failed to make anchor persistent [" + get_spatial_persistence_context_result_name(completion.persistResult) + "]");
  863. }
  864. // Set our new UUID.
  865. p_anchor_tracker->set_uuid(completion.persistUuid);
  866. // Set true our result value on our future.
  867. p_future_result->set_result_value(true);
  868. // Do our callback.
  869. p_user_callback.call(p_anchor_tracker);
  870. }
  871. Ref<OpenXRFutureResult> OpenXRSpatialAnchorCapability::unpersist_anchor(Ref<OpenXRAnchorTracker> p_anchor_tracker, RID p_persistence_context, const Callable &p_user_callback) {
  872. ERR_FAIL_COND_V(!is_spatial_persistence_supported(), nullptr);
  873. RID pc = p_persistence_context.is_valid() ? p_persistence_context : persistence_context;
  874. ERR_FAIL_COND_V(pc.is_null(), nullptr);
  875. ERR_FAIL_COND_V(p_anchor_tracker.is_null(), nullptr);
  876. PersistenceContextData *persistence_context_data = persistence_context_owner.get_or_null(pc);
  877. ERR_FAIL_NULL_V(persistence_context_data, nullptr);
  878. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  879. ERR_FAIL_NULL_V(openxr_api, nullptr);
  880. OpenXRFutureExtension *future_api = OpenXRFutureExtension::get_singleton();
  881. ERR_FAIL_NULL_V(future_api, nullptr);
  882. OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
  883. ERR_FAIL_NULL_V(se_extension, nullptr);
  884. XrFutureEXT future;
  885. XrSpatialEntityUnpersistInfoEXT unpersist_info = {
  886. XR_TYPE_SPATIAL_ENTITY_UNPERSIST_INFO_EXT, // type
  887. nullptr, // next
  888. p_anchor_tracker->get_uuid() // persistUuid
  889. };
  890. XrResult result = xrUnpersistSpatialEntityAsyncEXT(persistence_context_data->persistence_context, &unpersist_info, &future);
  891. if (XR_FAILED(result)) {
  892. ERR_FAIL_V_MSG(nullptr, "OpenXR: Failed to make anchor unpersistent [" + openxr_api->get_error_string(result) + "]");
  893. }
  894. // Create our future result.
  895. Ref<OpenXRFutureResult> future_result = future_api->register_future(future, callable_mp(this, &OpenXRSpatialAnchorCapability::_on_made_anchor_unpersistent).bind(pc, p_anchor_tracker, p_user_callback));
  896. return future_result;
  897. }
  898. void OpenXRSpatialAnchorCapability::_on_made_anchor_unpersistent(Ref<OpenXRFutureResult> p_future_result, RID p_persistence_context, Ref<OpenXRAnchorTracker> p_anchor_tracker, const Callable &p_user_callback) {
  899. ERR_FAIL_COND(p_anchor_tracker.is_null());
  900. OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
  901. ERR_FAIL_NULL(openxr_api);
  902. PersistenceContextData *persistence_context_data = persistence_context_owner.get_or_null(p_persistence_context);
  903. ERR_FAIL_NULL(persistence_context_data);
  904. XrFutureEXT future = p_future_result->get_future();
  905. XrUnpersistSpatialEntityCompletionEXT completion = {
  906. XR_TYPE_UNPERSIST_SPATIAL_ENTITY_COMPLETION_EXT, // type
  907. nullptr, // next
  908. XR_RESULT_MAX_ENUM, // futureResult
  909. XR_SPATIAL_PERSISTENCE_CONTEXT_RESULT_MAX_ENUM_EXT, // unpersistResult
  910. };
  911. XrResult result = xrUnpersistSpatialEntityCompleteEXT(persistence_context_data->persistence_context, future, &completion);
  912. if (XR_FAILED(result)) { // Did our xrCreateSpatialContextCompleteEXT call fail?
  913. p_future_result->set_result_value(false);
  914. ERR_FAIL_MSG("OpenXR: Failed to complete anchor unpersistent future [" + openxr_api->get_error_string(result) + "]");
  915. }
  916. if (XR_FAILED(completion.futureResult)) { // Did our completion fail?
  917. p_future_result->set_result_value(false);
  918. ERR_FAIL_MSG("OpenXR: Failed to complete making anchor unpersistent [" + openxr_api->get_error_string(completion.futureResult) + "]");
  919. }
  920. if (completion.unpersistResult != XR_SPATIAL_PERSISTENCE_CONTEXT_RESULT_SUCCESS_EXT) { // Did our process fail?
  921. p_future_result->set_result_value(false);
  922. ERR_FAIL_MSG("OpenXR: Failed to make anchor unpersistent [" + get_spatial_persistence_context_result_name(completion.unpersistResult) + "]");
  923. }
  924. // Unset our UUID.
  925. XrUuid empty_uid = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  926. p_anchor_tracker->set_uuid(empty_uid);
  927. // Set true our result value on our future.
  928. p_future_result->set_result_value(true);
  929. // Do our callback.
  930. p_user_callback.call(p_anchor_tracker);
  931. }
  932. String OpenXRSpatialAnchorCapability::get_spatial_persistence_scope_name(XrSpatialPersistenceScopeEXT p_scope){
  933. XR_ENUM_SWITCH(XrSpatialPersistenceScopeEXT, p_scope)
  934. }
  935. String OpenXRSpatialAnchorCapability::get_spatial_persistence_context_result_name(XrSpatialPersistenceContextResultEXT p_result) {
  936. XR_ENUM_SWITCH(XrSpatialPersistenceContextResultEXT, p_result)
  937. }