Debian Codegraph @

modules/openxr/extensions/spatial_entities/openxr_spatial_plane_tracking.cpp

raw symbols SCIP
1 /**************************************************************************/
2 /* openxr_spatial_plane_tracking.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_spatial_plane_tracking.h"
32
33 #include "../../openxr_api.h"
34 #include "core/config/project_settings.h"
35 #include "scene/resources/3d/box_shape_3d.h"
36 #include "scene/resources/3d/concave_polygon_shape_3d.h"
37 #include "scene/resources/3d/primitive_meshes.h"
38 #include "servers/xr/xr_server.h"
39
40 ////////////////////////////////////////////////////////////////////////////
41 // OpenXRSpatialCapabilityConfigurationPlaneTracking
42
43 void OpenXRSpatialCapabilityConfigurationPlaneTracking::_bind_methods() {
44 ClassDB::bind_method(D_METHOD("supports_mesh_2d"), &OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_mesh_2d);
45 ClassDB::bind_method(D_METHOD("supports_polygons"), &OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_polygons);
46 ClassDB::bind_method(D_METHOD("supports_labels"), &OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_labels);
47
48 ClassDB::bind_method(D_METHOD("get_enabled_components"), &OpenXRSpatialCapabilityConfigurationPlaneTracking::_get_enabled_components);
49 }
50
51 bool OpenXRSpatialCapabilityConfigurationPlaneTracking::has_valid_configuration() const {
52 OpenXRSpatialPlaneTrackingCapability *capability = OpenXRSpatialPlaneTrackingCapability::get_singleton();
53 ERR_FAIL_NULL_V(capability, false);
54
55 return capability->is_supported();
56 }
57
58 XrSpatialCapabilityConfigurationBaseHeaderEXT *OpenXRSpatialCapabilityConfigurationPlaneTracking::get_configuration() {
59 OpenXRSpatialPlaneTrackingCapability *capability = OpenXRSpatialPlaneTrackingCapability::get_singleton();
60 ERR_FAIL_NULL_V(capability, nullptr);
61
62 if (capability->is_supported()) {
63 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
64 ERR_FAIL_NULL_V(se_extension, nullptr);
65
66 // Guaranteed components:
67 plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_BOUNDED_2D_EXT);
68 plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_PLANE_ALIGNMENT_EXT);
69
70 // Optional components:
71 if (get_supports_mesh_2d()) {
72 plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_MESH_2D_EXT);
73 } else if (get_supports_polygons()) {
74 plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_POLYGON_2D_EXT);
75 }
76 if (get_supports_labels()) {
77 plane_enabled_components.push_back(XR_SPATIAL_COMPONENT_TYPE_PLANE_SEMANTIC_LABEL_EXT);
78 }
79
80 // Set up our enabled components.
81 plane_config.enabledComponentCount = plane_enabled_components.size();
82 plane_config.enabledComponents = plane_enabled_components.ptr();
83
84 // and return this.
85 return (XrSpatialCapabilityConfigurationBaseHeaderEXT *)&plane_config;
86 }
87
88 return nullptr;
89 }
90
91 bool OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_mesh_2d() {
92 if (supports_mesh_2d == -1) {
93 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
94 ERR_FAIL_NULL_V(se_extension, false);
95
96 supports_mesh_2d = se_extension->supports_component_type(XR_SPATIAL_CAPABILITY_PLANE_TRACKING_EXT, XR_SPATIAL_COMPONENT_TYPE_MESH_2D_EXT) ? 1 : 0;
97 }
98
99 return supports_mesh_2d == 1;
100 }
101
102 bool OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_polygons() {
103 if (supports_polygons == -1) {
104 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
105 ERR_FAIL_NULL_V(se_extension, false);
106
107 supports_polygons = se_extension->supports_component_type(XR_SPATIAL_CAPABILITY_PLANE_TRACKING_EXT, XR_SPATIAL_COMPONENT_TYPE_POLYGON_2D_EXT) ? 1 : 0;
108 }
109
110 return supports_polygons == 1;
111 }
112
113 bool OpenXRSpatialCapabilityConfigurationPlaneTracking::get_supports_labels() {
114 if (supports_labels == -1) {
115 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
116 ERR_FAIL_NULL_V(se_extension, false);
117
118 supports_labels = se_extension->supports_component_type(XR_SPATIAL_CAPABILITY_PLANE_TRACKING_EXT, XR_SPATIAL_COMPONENT_TYPE_PLANE_SEMANTIC_LABEL_EXT) ? 1 : 0;
119 }
120
121 return supports_labels == 1;
122 }
123
124 PackedInt64Array OpenXRSpatialCapabilityConfigurationPlaneTracking::_get_enabled_components() const {
125 PackedInt64Array components;
126
127 for (const XrSpatialComponentTypeEXT &component_type : plane_enabled_components) {
128 components.push_back((int64_t)component_type);
129 }
130
131 return components;
132 }
133
134 ////////////////////////////////////////////////////////////////////////////
135 // OpenXRSpatialComponentPlaneAlignmentList
136
137 void OpenXRSpatialComponentPlaneAlignmentList::_bind_methods() {
138 ClassDB::bind_method(D_METHOD("get_plane_alignment", "index"), &OpenXRSpatialComponentPlaneAlignmentList::_get_plane_alignment);
139
140 BIND_ENUM_CONSTANT(PLANE_ALIGNMENT_HORIZONTAL_UPWARD);
141 BIND_ENUM_CONSTANT(PLANE_ALIGNMENT_HORIZONTAL_DOWNWARD);
142 BIND_ENUM_CONSTANT(PLANE_ALIGNMENT_VERTICAL);
143 BIND_ENUM_CONSTANT(PLANE_ALIGNMENT_ARBITRARY);
144 }
145
146 void OpenXRSpatialComponentPlaneAlignmentList::set_capacity(uint32_t p_capacity) {
147 plane_alignment_data.resize(p_capacity);
148
149 plane_alignment_list.planeAlignmentCount = uint32_t(plane_alignment_data.size());
150 plane_alignment_list.planeAlignments = plane_alignment_data.ptrw();
151 }
152
153 XrSpatialComponentTypeEXT OpenXRSpatialComponentPlaneAlignmentList::get_component_type() const {
154 return XR_SPATIAL_COMPONENT_TYPE_PLANE_ALIGNMENT_EXT;
155 }
156
157 void *OpenXRSpatialComponentPlaneAlignmentList::get_structure_data(void *p_next) {
158 plane_alignment_list.next = p_next;
159 return &plane_alignment_list;
160 }
161
162 XrSpatialPlaneAlignmentEXT OpenXRSpatialComponentPlaneAlignmentList::get_plane_alignment(int64_t p_index) const {
163 ERR_FAIL_INDEX_V(p_index, plane_alignment_data.size(), XR_SPATIAL_PLANE_ALIGNMENT_MAX_ENUM_EXT);
164
165 return plane_alignment_data[p_index];
166 }
167
168 OpenXRSpatialComponentPlaneAlignmentList::PlaneAlignment OpenXRSpatialComponentPlaneAlignmentList::_get_plane_alignment(int64_t p_index) const {
169 return (PlaneAlignment)get_plane_alignment(p_index);
170 }
171
172 ////////////////////////////////////////////////////////////////////////////
173 // Spatial component polygon2d list
174
175 void OpenXRSpatialComponentPolygon2DList::_bind_methods() {
176 ClassDB::bind_method(D_METHOD("get_transform", "index"), &OpenXRSpatialComponentPolygon2DList::get_transform);
177 ClassDB::bind_method(D_METHOD("get_vertices", "snapshot", "index"), &OpenXRSpatialComponentPolygon2DList::get_vertices);
178 }
179
180 void OpenXRSpatialComponentPolygon2DList::set_capacity(uint32_t p_capacity) {
181 polygon2d_data.resize(p_capacity);
182
183 polygon2d_list.polygonCount = uint32_t(polygon2d_data.size());
184 polygon2d_list.polygons = polygon2d_data.ptrw();
185 }
186
187 XrSpatialComponentTypeEXT OpenXRSpatialComponentPolygon2DList::get_component_type() const {
188 return XR_SPATIAL_COMPONENT_TYPE_POLYGON_2D_EXT;
189 }
190
191 void *OpenXRSpatialComponentPolygon2DList::get_structure_data(void *p_next) {
192 polygon2d_list.next = p_next;
193 return &polygon2d_list;
194 }
195
196 Transform3D OpenXRSpatialComponentPolygon2DList::get_transform(int64_t p_index) const {
197 ERR_FAIL_INDEX_V(p_index, polygon2d_data.size(), Transform3D());
198
199 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
200 ERR_FAIL_NULL_V(openxr_api, Transform3D());
201
202 return openxr_api->transform_from_pose(polygon2d_data[p_index].origin);
203 }
204
205 PackedVector2Array OpenXRSpatialComponentPolygon2DList::get_vertices(RID p_snapshot, int64_t p_index) const {
206 ERR_FAIL_INDEX_V(p_index, polygon2d_data.size(), PackedVector2Array());
207
208 const XrSpatialBufferEXT &buffer = polygon2d_data[p_index].vertexBuffer;
209 if (buffer.bufferId == XR_NULL_SPATIAL_BUFFER_ID_EXT) {
210 // We don't have data (yet).
211 return PackedVector2Array();
212 }
213
214 ERR_FAIL_COND_V(buffer.bufferType != XR_SPATIAL_BUFFER_TYPE_VECTOR2F_EXT, PackedVector2Array());
215
216 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
217 ERR_FAIL_NULL_V(se_extension, PackedVector2Array());
218
219 return se_extension->get_vector2_buffer(p_snapshot, buffer.bufferId);
220 }
221
222 ////////////////////////////////////////////////////////////////////////////
223 // OpenXRSpatialComponentPlaneSemanticLabelList
224
225 void OpenXRSpatialComponentPlaneSemanticLabelList::_bind_methods() {
226 ClassDB::bind_method(D_METHOD("get_plane_semantic_label", "index"), &OpenXRSpatialComponentPlaneSemanticLabelList::_get_plane_semantic_label);
227
228 BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_UNCATEGORIZED);
229 BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_FLOOR);
230 BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_WALL);
231 BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_CEILING);
232 BIND_ENUM_CONSTANT(PLANE_SEMANTIC_LABEL_TABLE);
233 }
234
235 void OpenXRSpatialComponentPlaneSemanticLabelList::set_capacity(uint32_t p_capacity) {
236 plane_semantic_label_data.resize(p_capacity);
237
238 plane_semantic_label_list.semanticLabelCount = uint32_t(plane_semantic_label_data.size());
239 plane_semantic_label_list.semanticLabels = plane_semantic_label_data.ptrw();
240 }
241
242 XrSpatialComponentTypeEXT OpenXRSpatialComponentPlaneSemanticLabelList::get_component_type() const {
243 return XR_SPATIAL_COMPONENT_TYPE_PLANE_SEMANTIC_LABEL_EXT;
244 }
245
246 void *OpenXRSpatialComponentPlaneSemanticLabelList::get_structure_data(void *p_next) {
247 plane_semantic_label_list.next = p_next;
248 return &plane_semantic_label_list;
249 }
250
251 XrSpatialPlaneSemanticLabelEXT OpenXRSpatialComponentPlaneSemanticLabelList::get_plane_semantic_label(int64_t p_index) const {
252 ERR_FAIL_INDEX_V(p_index, plane_semantic_label_data.size(), XR_SPATIAL_PLANE_SEMANTIC_LABEL_MAX_ENUM_EXT);
253
254 return plane_semantic_label_data[p_index];
255 }
256
257 OpenXRSpatialComponentPlaneSemanticLabelList::PlaneSemanticLabel OpenXRSpatialComponentPlaneSemanticLabelList::_get_plane_semantic_label(int64_t p_index) const {
258 return (PlaneSemanticLabel)get_plane_semantic_label(p_index);
259 }
260
261 ////////////////////////////////////////////////////////////////////////////
262 // OpenXRPlaneTracker
263
264 void OpenXRPlaneTracker::_bind_methods() {
265 ClassDB::bind_method(D_METHOD("set_bounds_size", "bounds_size"), &OpenXRPlaneTracker::set_bounds_size);
266 ClassDB::bind_method(D_METHOD("get_bounds_size"), &OpenXRPlaneTracker::get_bounds_size);
267 ADD_PROPERTY(PropertyInfo(Variant::INT, "bounds_size"), "set_bounds_size", "get_bounds_size");
268
269 ClassDB::bind_method(D_METHOD("set_plane_alignment", "plane_alignment"), &OpenXRPlaneTracker::set_plane_alignment);
270 ClassDB::bind_method(D_METHOD("get_plane_alignment"), &OpenXRPlaneTracker::get_plane_alignment);
271 ADD_PROPERTY(PropertyInfo(Variant::INT, "plane_alignment"), "set_plane_alignment", "get_plane_alignment");
272
273 ClassDB::bind_method(D_METHOD("set_plane_label", "plane_label"), &OpenXRPlaneTracker::set_plane_label);
274 ClassDB::bind_method(D_METHOD("get_plane_label"), &OpenXRPlaneTracker::get_plane_label);
275 ADD_PROPERTY(PropertyInfo(Variant::STRING, "plane_label"), "set_plane_label", "get_plane_label");
276
277 ClassDB::bind_method(D_METHOD("set_mesh_data", "origin", "vertices", "indices"), &OpenXRPlaneTracker::set_mesh_data, DEFVAL(PackedInt32Array()));
278 ClassDB::bind_method(D_METHOD("clear_mesh_data"), &OpenXRPlaneTracker::clear_mesh_data);
279
280 ClassDB::bind_method(D_METHOD("get_mesh_offset"), &OpenXRPlaneTracker::get_mesh_offset);
281 ClassDB::bind_method(D_METHOD("get_mesh"), &OpenXRPlaneTracker::get_mesh);
282 ClassDB::bind_method(D_METHOD("get_shape", "thickness"), &OpenXRPlaneTracker::get_shape, DEFVAL(0.01));
283
284 ADD_SIGNAL(MethodInfo("mesh_changed"));
285 }
286
287 void OpenXRPlaneTracker::set_bounds_size(const Vector2 &p_bounds_size) {
288 if (Math::abs(bounds_size.x - p_bounds_size.x) > 0.001 || Math::abs(bounds_size.y - p_bounds_size.y) > 0.001) {
289 bounds_size = p_bounds_size;
290
291 if (!mesh.has_mesh_data) {
292 // Bounds changing only effects mesh data if we don't have polygon data.
293 clear_mesh_data();
294 emit_signal(SNAME("mesh_changed"));
295 }
296 }
297 }
298
299 Vector2 OpenXRPlaneTracker::get_bounds_size() const {
300 return bounds_size;
301 }
302
303 void OpenXRPlaneTracker::set_plane_alignment(OpenXRSpatialComponentPlaneAlignmentList::PlaneAlignment p_plane_alignment) {
304 if (plane_alignment != p_plane_alignment) {
305 plane_alignment = p_plane_alignment;
306 }
307 }
308
309 OpenXRSpatialComponentPlaneAlignmentList::PlaneAlignment OpenXRPlaneTracker::get_plane_alignment() const {
310 return plane_alignment;
311 }
312
313 void OpenXRPlaneTracker::set_plane_label(const String &p_plane_label) {
314 if (plane_label != p_plane_label) {
315 plane_label = p_plane_label;
316
317 // Also copy to description, should do something nicer here.
318 set_tracker_desc(plane_label);
319 }
320 }
321
322 String OpenXRPlaneTracker::get_plane_label() const {
323 return plane_label;
324 }
325
326 void OpenXRPlaneTracker::set_mesh_data(const Transform3D &p_origin, const PackedVector2Array &p_vertices, const PackedInt32Array &p_indices) {
327 if (p_vertices.size() < 3) {
328 if (mesh.has_mesh_data) {
329 clear_mesh_data();
330 emit_signal(SNAME("mesh_changed"));
331 }
332 } else {
333 bool has_changed = !mesh.has_mesh_data;
334
335 mesh.has_mesh_data = true;
336 mesh.origin = p_origin;
337
338 if (mesh.vertices.size() != p_vertices.size()) {
339 has_changed = true;
340 } else {
341 // Compare the vertices with a bit of margin, we ignore small jittering on vertices.
342 for (uint32_t i = 0; i < p_vertices.size() && !has_changed; i++) {
343 const Vector2 &a = p_vertices[i];
344 const Vector2 &b = mesh.vertices[i];
345 has_changed = (Math::abs(a.x - b.x) > 0.001) || (Math::abs(a.y - b.y) > 0.001);
346 }
347 }
348 if (has_changed) {
349 mesh.vertices = p_vertices;
350 }
351
352 // Q: Should we keep our indices list empty if we get polygon data
353 // and create different meshes/collision shapes as a result?
354 if (p_indices.is_empty()) {
355 // Assume polygon, turn into triangle strip...
356 int count = (p_vertices.size() - 2) * 3;
357
358 // If our vertices haven't changed and our indices are already the correct size,
359 // assume we don't need to rerun this.
360 if (has_changed || mesh.indices.size() != count) {
361 has_changed = true;
362
363 int offset = 1;
364 mesh.indices.resize(count);
365 int32_t *idx = mesh.indices.ptrw();
366 for (int i = 0; i < count; i += 3) {
367 idx[i + 0] = 0;
368 idx[i + 2] = offset++;
369 idx[i + 1] = offset;
370 }
371 }
372 } else {
373 if (mesh.indices.size() != p_indices.size()) {
374 has_changed = true;
375 } else {
376 for (uint32_t i = 0; i < p_indices.size() && !has_changed; i++) {
377 has_changed = mesh.indices[i] != p_indices[i];
378 }
379 }
380 if (has_changed) {
381 mesh.indices = p_indices;
382 }
383 }
384
385 if (has_changed) {
386 mesh.mesh.unref();
387 mesh.shape3d.unref();
388
389 emit_signal(SNAME("mesh_changed"));
390 }
391 }
392 }
393
394 void OpenXRPlaneTracker::clear_mesh_data() {
395 mesh.mesh.unref();
396 mesh.shape3d.unref();
397
398 if (mesh.has_mesh_data) {
399 mesh.has_mesh_data = false;
400 mesh.origin = Transform3D();
401 mesh.vertices.clear();
402 mesh.indices.clear();
403
404 emit_signal(SNAME("mesh_changed"));
405 }
406 }
407
408 Transform3D OpenXRPlaneTracker::get_mesh_offset() const {
409 Transform3D offset;
410
411 if (mesh.has_mesh_data) {
412 offset = mesh.origin;
413
414 Ref<XRPose> pose = get_pose(SNAME("default"));
415 if (pose.is_valid()) {
416 // Q is this offset * transform.inverse?
417 offset = pose->get_transform().inverse() * offset;
418 }
419
420 // Reference frame will already be applied to pose used on our XRNode3D but we do need to apply our scale
421 XRServer *xr_server = XRServer::get_singleton();
422 if (xr_server) {
423 offset.origin *= xr_server->get_world_scale();
424 }
425 }
426
427 return offset;
428 }
429
430 Ref<Mesh> OpenXRPlaneTracker::get_mesh() {
431 // We've already created this? Just return it!
432 if (mesh.mesh.is_valid()) {
433 return mesh.mesh;
434 }
435
436 if (mesh.has_mesh_data) {
437 Ref<ArrayMesh> array_mesh;
438 Array arr;
439
440 // We need our vertices as Vector3
441 PackedVector3Array vertices;
442 vertices.resize(mesh.vertices.size());
443 const Vector2 *read = mesh.vertices.ptr();
444 Vector3 *write = vertices.ptrw();
445 for (int v = 0; v < mesh.vertices.size(); v++) {
446 write[v] = Vector3(read[v].x, read[v].y, 0.0);
447 }
448
449 // Build our array with data.
450 arr.resize(RS::ARRAY_MAX);
451 arr[RS::ARRAY_VERTEX] = vertices;
452 arr[RS::ARRAY_INDEX] = mesh.indices;
453
454 // Create our array mesh.
455 array_mesh.instantiate();
456 array_mesh->add_surface_from_arrays(Mesh::PrimitiveType::PRIMITIVE_TRIANGLES, arr);
457
458 // Cache this.
459 mesh.mesh = array_mesh;
460 } else if (bounds_size.x > 0.0 && bounds_size.y > 0.0) {
461 // We can use a plane mesh here.
462 Ref<PlaneMesh> plane_mesh;
463
464 plane_mesh.instantiate();
465 plane_mesh->set_orientation(PlaneMesh::Orientation::FACE_Z);
466 plane_mesh->set_size(bounds_size);
467
468 // Cache this.
469 mesh.mesh = plane_mesh;
470 } else {
471 print_verbose("OpenXR: Can't create mesh for plane, no data.");
472 }
473 return mesh.mesh;
474 }
475
476 Ref<Shape3D> OpenXRPlaneTracker::get_shape(real_t p_thickness) {
477 // We've already created this? Just return it!
478 if (mesh.shape3d.is_valid()) {
479 return mesh.shape3d;
480 }
481
482 if (mesh.has_mesh_data) {
483 Ref<ConcavePolygonShape3D> shape;
484 Vector<Vector3> faces;
485
486 // Get some direct access to our data.
487 int isize = mesh.indices.size();
488 const Vector2 *vr = mesh.vertices.ptr();
489 const int32_t *ir = mesh.indices.ptr();
490
491 // Find our edges.
492 HashMap<Edge, int, Edge> edge_counts;
493 for (int i = 0; i < isize; i += 3) {
494 for (int j = 0; j < 3; j++) {
495 Edge e(ir[i + j], ir[i + ((j + 1) % 3)]);
496 edge_counts[e]++;
497 }
498 }
499
500 // Find our outer edges.
501 thread_local LocalVector<Edge> outer_edges;
502 outer_edges.clear();
503 for (const KeyValue<Edge, int> &e : edge_counts) {
504 if (e.value > 1) {
505 outer_edges.push_back(e.key);
506 }
507 }
508
509 // Make space for these.
510 faces.resize(2 * isize + 6 * outer_edges.size());
511 Vector3 *write = faces.ptrw();
512
513 // Add top and bottom.
514 for (int i = 0; i < isize; i += 3) {
515 Vector3 a = Vector3(vr[ir[i]].x, vr[ir[i]].y, 0.0);
516 Vector3 b = Vector3(vr[ir[i + 1]].x, vr[ir[i + 1]].y, 0.0);
517 Vector3 c = Vector3(vr[ir[i + 2]].x, vr[ir[i + 2]].y, 0.0);
518
519 *write++ = a;
520 *write++ = b;
521 *write++ = c;
522
523 a.z = -p_thickness;
524 b.z = -p_thickness;
525 c.z = -p_thickness;
526
527 *write++ = a;
528 *write++ = c;
529 *write++ = b;
530 }
531
532 // Add outer edges.
533 for (const Edge &edge : outer_edges) {
534 Vector3 a = Vector3(vr[edge.a].x, vr[edge.a].y, 0.0);
535 Vector3 b = Vector3(vr[edge.b].x, vr[edge.b].y, 0.0);
536 Vector3 c = b + Vector3(0.0, 0.0, -p_thickness);
537 Vector3 d = a + Vector3(0.0, 0.0, -p_thickness);
538
539 *write++ = a;
540 *write++ = b;
541 *write++ = c;
542
543 *write++ = a;
544 *write++ = c;
545 *write++ = d;
546 }
547
548 // Create our shape.
549 shape.instantiate();
550 shape->set_faces(faces);
551
552 mesh.shape3d = shape;
553 } else if (bounds_size.x > 0.0 && bounds_size.y > 0.0) {
554 // We can use a box shape here
555 Ref<BoxShape3D> box_shape;
556 box_shape.instantiate();
557 box_shape->set_size(Vector3(bounds_size.x, bounds_size.y, p_thickness));
558
559 mesh.shape3d = box_shape;
560 }
561
562 return mesh.shape3d;
563 }
564
565 ////////////////////////////////////////////////////////////////////////////
566 // OpenXRSpatialPlaneTrackingCapability
567
568 OpenXRSpatialPlaneTrackingCapability *OpenXRSpatialPlaneTrackingCapability::singleton = nullptr;
569
570 OpenXRSpatialPlaneTrackingCapability *OpenXRSpatialPlaneTrackingCapability::get_singleton() {
571 return singleton;
572 }
573
574 OpenXRSpatialPlaneTrackingCapability::OpenXRSpatialPlaneTrackingCapability() {
575 singleton = this;
576 }
577
578 OpenXRSpatialPlaneTrackingCapability::~OpenXRSpatialPlaneTrackingCapability() {
579 singleton = nullptr;
580 }
581
582 void OpenXRSpatialPlaneTrackingCapability::_bind_methods() {
583 ClassDB::bind_method(D_METHOD("is_supported"), &OpenXRSpatialPlaneTrackingCapability::is_supported);
584 }
585
586 HashMap<String, bool *> OpenXRSpatialPlaneTrackingCapability::get_requested_extensions(XrVersion p_version) {
587 HashMap<String, bool *> request_extensions;
588
589 if (GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enabled") && GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enable_plane_tracking")) {
590 request_extensions[XR_EXT_SPATIAL_PLANE_TRACKING_EXTENSION_NAME] = &spatial_plane_tracking_ext;
591 }
592
593 return request_extensions;
594 }
595
596 void OpenXRSpatialPlaneTrackingCapability::on_session_created(const XrSession p_session) {
597 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
598 ERR_FAIL_NULL(se_extension);
599
600 if (!spatial_plane_tracking_ext) {
601 return;
602 }
603
604 spatial_plane_tracking_supported = se_extension->supports_capability(XR_SPATIAL_CAPABILITY_PLANE_TRACKING_EXT);
605 if (!spatial_plane_tracking_supported) {
606 // Supported by XR runtime but not by device? We're done.
607 return;
608 }
609
610 se_extension->connect(SNAME("spatial_discovery_recommended"), callable_mp(this, &OpenXRSpatialPlaneTrackingCapability::_on_spatial_discovery_recommended));
611
612 if (GLOBAL_GET_CACHED(bool, "xr/openxr/extensions/spatial_entity/enable_builtin_plane_detection")) {
613 // Start by creating our spatial context
614 _create_spatial_context();
615 }
616 }
617
618 void OpenXRSpatialPlaneTrackingCapability::on_session_destroyed() {
619 if (!spatial_plane_tracking_supported) {
620 return;
621 }
622 spatial_plane_tracking_supported = false;
623
624 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
625 ERR_FAIL_NULL(se_extension);
626 XRServer *xr_server = XRServer::get_singleton();
627 ERR_FAIL_NULL(xr_server);
628
629 // Free and unregister our anchors
630 for (const KeyValue<XrSpatialEntityIdEXT, Ref<OpenXRPlaneTracker>> &plane_tracker : plane_trackers) {
631 xr_server->remove_tracker(plane_tracker.value);
632 }
633 plane_trackers.clear();
634
635 // Free our spatial context
636 if (spatial_context.is_valid()) {
637 se_extension->free_spatial_context(spatial_context);
638 spatial_context = RID();
639 }
640
641 se_extension->disconnect(SNAME("spatial_discovery_recommended"), callable_mp(this, &OpenXRSpatialPlaneTrackingCapability::_on_spatial_discovery_recommended));
642 }
643
644 void OpenXRSpatialPlaneTrackingCapability::on_process() {
645 if (!spatial_context.is_valid()) {
646 return;
647 }
648
649 // Protection against plane discovery happening too often.
650 if (discovery_cooldown > 0) {
651 discovery_cooldown--;
652 }
653
654 // Check if we need to start our discovery.
655 if (need_discovery && discovery_cooldown == 0 && !discovery_query_result.is_valid()) {
656 need_discovery = false;
657 discovery_cooldown = 60; // Set our cooldown to 60 frames, it doesn't need to be an exact science.
658
659 _start_entity_discovery();
660 }
661 }
662
663 bool OpenXRSpatialPlaneTrackingCapability::is_supported() {
664 return spatial_plane_tracking_supported;
665 }
666
667 ////////////////////////////////////////////////////////////////////////////
668 // Discovery logic
669 Ref<OpenXRFutureResult> OpenXRSpatialPlaneTrackingCapability::_create_spatial_context() {
670 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
671 ERR_FAIL_NULL_V(se_extension, nullptr);
672
673 TypedArray<OpenXRSpatialCapabilityConfigurationBaseHeader> capability_configurations;
674
675 // Create our configuration objects.
676 plane_configuration.instantiate();
677 capability_configurations.push_back(plane_configuration);
678
679 return se_extension->create_spatial_context(capability_configurations, nullptr, callable_mp(this, &OpenXRSpatialPlaneTrackingCapability::_on_spatial_context_created));
680 }
681
682 void OpenXRSpatialPlaneTrackingCapability::_on_spatial_context_created(RID p_spatial_context) {
683 spatial_context = p_spatial_context;
684 need_discovery = true;
685 }
686
687 void OpenXRSpatialPlaneTrackingCapability::_on_spatial_discovery_recommended(RID p_spatial_context) {
688 if (p_spatial_context == spatial_context) {
689 // Trigger new discovery.
690 need_discovery = true;
691 }
692 }
693
694 Ref<OpenXRFutureResult> OpenXRSpatialPlaneTrackingCapability::_start_entity_discovery() {
695 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
696 ERR_FAIL_NULL_V(se_extension, nullptr);
697
698 // Already running or ran discovery, cancel/clean up.
699 if (discovery_query_result.is_valid()) {
700 WARN_PRINT("OpenXR: Starting new discovery before previous discovery has been processed!");
701 discovery_query_result->cancel_future();
702 discovery_query_result.unref();
703 }
704
705 // Start our new snapshot.
706 discovery_query_result = se_extension->discover_spatial_entities(spatial_context, plane_configuration->get_enabled_components(), nullptr, callable_mp(this, &OpenXRSpatialPlaneTrackingCapability::_process_snapshot));
707
708 return discovery_query_result;
709 }
710
711 void OpenXRSpatialPlaneTrackingCapability::_process_snapshot(RID p_snapshot) {
712 OpenXRSpatialEntityExtension *se_extension = OpenXRSpatialEntityExtension::get_singleton();
713 ERR_FAIL_NULL(se_extension);
714 XRServer *xr_server = XRServer::get_singleton();
715 ERR_FAIL_NULL(xr_server);
716 OpenXRAPI *openxr_api = OpenXRAPI::get_singleton();
717 ERR_FAIL_NULL(openxr_api);
718
719 // Make a copy of the planes we have right now, so we know which ones to clean up.
720 LocalVector<XrSpatialEntityIdEXT> current_planes;
721 current_planes.resize(plane_trackers.size());
722 int p = 0;
723 for (const KeyValue<XrSpatialEntityIdEXT, Ref<OpenXRPlaneTracker>> &plane : plane_trackers) {
724 current_planes[p++] = plane.key;
725 }
726
727 // Build our component data
728 TypedArray<OpenXRSpatialComponentData> component_data;
729
730 // We always need a query result data object
731 Ref<OpenXRSpatialQueryResultData> query_result_data;
732 query_result_data.instantiate();
733 component_data.push_back(query_result_data);
734
735 // Add bounded2D
736 Ref<OpenXRSpatialComponentBounded2DList> bounded2d_list;
737 bounded2d_list.instantiate();
738 component_data.push_back(bounded2d_list);
739
740 // Plane alignment list
741 Ref<OpenXRSpatialComponentPlaneAlignmentList> alignment_list;
742 alignment_list.instantiate();
743 component_data.push_back(alignment_list);
744
745 Ref<OpenXRSpatialComponentMesh2DList> mesh2d_list;
746 Ref<OpenXRSpatialComponentPolygon2DList> poly2d_list;
747 if (plane_configuration->get_supports_mesh_2d()) {
748 mesh2d_list.instantiate();
749 component_data.push_back(mesh2d_list);
750 } else if (plane_configuration->get_supports_polygons()) {
751 poly2d_list.instantiate();
752 component_data.push_back(poly2d_list);
753 }
754
755 // Plane semantic label
756 Ref<OpenXRSpatialComponentPlaneSemanticLabelList> label_list;
757 if (plane_configuration->get_supports_labels()) {
758 label_list.instantiate();
759 component_data.push_back(label_list);
760 }
761
762 if (se_extension->query_snapshot(p_snapshot, component_data, nullptr)) {
763 // Now loop through our data and update our anchors.
764 // Q we're assuming entity ID, size and state size are equal, is there ever a situation where they would not be?
765 int64_t size = query_result_data->get_capacity();
766 for (int64_t i = 0; i < size; i++) {
767 XrSpatialEntityIdEXT entity_id = query_result_data->get_entity_id(i);
768 XrSpatialEntityTrackingStateEXT entity_state = query_result_data->get_entity_state(i);
769
770 // Erase it from our current planes (if we have it, else this is ignored).
771 current_planes.erase(entity_id);
772
773 if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT) {
774 // We should only get this status on updates as a prelude to needing to remove this marker.
775 // So we just update the status.
776 if (plane_trackers.has(entity_id)) {
777 Ref<OpenXRPlaneTracker> plane_tracker = plane_trackers[entity_id];
778 plane_tracker->invalidate_pose(SNAME("default"));
779 plane_tracker->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT);
780 }
781 } else {
782 // Process our entity
783 bool add_to_xr_server = false;
784 Ref<OpenXRPlaneTracker> plane_tracker;
785
786 if (plane_trackers.has(entity_id)) {
787 // We know about this one already
788 plane_tracker = plane_trackers[entity_id];
789 } else {
790 // Create a new anchor
791 plane_tracker.instantiate();
792 plane_tracker->set_entity(se_extension->make_spatial_entity(se_extension->get_spatial_snapshot_context(p_snapshot), entity_id));
793 plane_trackers[entity_id] = plane_tracker;
794
795 add_to_xr_server = true;
796 }
797
798 // Handle component data
799 if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_PAUSED_EXT) {
800 plane_tracker->invalidate_pose(SNAME("default"));
801 plane_tracker->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_PAUSED_EXT);
802
803 // No further component data will be valid in this state, we need to ignore it!
804 } else if (entity_state == XR_SPATIAL_ENTITY_TRACKING_STATE_TRACKING_EXT) {
805 Transform3D transform = bounded2d_list->get_center_pose(i);
806 plane_tracker->set_pose(SNAME("default"), transform, Vector3(), Vector3());
807 plane_tracker->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_TRACKING_EXT);
808
809 // Process our component data.
810 plane_tracker->set_bounds_size(bounded2d_list->get_size(i));
811 plane_tracker->set_plane_alignment((OpenXRSpatialComponentPlaneAlignmentList::PlaneAlignment)alignment_list->get_plane_alignment(i));
812
813 if (mesh2d_list.is_valid()) {
814 plane_tracker->set_mesh_data(mesh2d_list->get_transform(i), mesh2d_list->get_vertices(p_snapshot, i), mesh2d_list->get_indices(p_snapshot, i));
815 } else if (poly2d_list.is_valid()) {
816 plane_tracker->set_mesh_data(poly2d_list->get_transform(i), poly2d_list->get_vertices(p_snapshot, i));
817 } else {
818 // Just in case we set this before.
819 plane_tracker->clear_mesh_data();
820 }
821
822 if (label_list.is_valid()) {
823 switch (label_list->get_plane_semantic_label(i)) {
824 case XR_SPATIAL_PLANE_SEMANTIC_LABEL_UNCATEGORIZED_EXT: {
825 plane_tracker->set_plane_label("Uncategorized plane");
826 } break;
827 case XR_SPATIAL_PLANE_SEMANTIC_LABEL_FLOOR_EXT: {
828 plane_tracker->set_plane_label("Floor plane");
829 } break;
830 case XR_SPATIAL_PLANE_SEMANTIC_LABEL_WALL_EXT: {
831 plane_tracker->set_plane_label("Wall plane");
832 } break;
833 case XR_SPATIAL_PLANE_SEMANTIC_LABEL_CEILING_EXT: {
834 plane_tracker->set_plane_label("Ceiling plane");
835 } break;
836 case XR_SPATIAL_PLANE_SEMANTIC_LABEL_TABLE_EXT: {
837 plane_tracker->set_plane_label("Table plane");
838 } break;
839 default: {
840 plane_tracker->set_plane_label("Unknown plane");
841 } break;
842 }
843 }
844 }
845
846 if (add_to_xr_server) {
847 // Register with XR server
848 xr_server->add_tracker(plane_tracker);
849 }
850 }
851 }
852
853 // Remove any planes that are no longer there...
854 for (const XrSpatialEntityIdEXT &entity_id : current_planes) {
855 if (plane_trackers.has(entity_id)) {
856 Ref<OpenXRPlaneTracker> plane_tracker = plane_trackers[entity_id];
857
858 // Just in case there are still references out there to this marker,
859 // reset some stuff.
860 plane_tracker->invalidate_pose(SNAME("default"));
861 plane_tracker->set_spatial_tracking_state(XR_SPATIAL_ENTITY_TRACKING_STATE_STOPPED_EXT);
862
863 // Remove it from our XRServer
864 xr_server->remove_tracker(plane_tracker);
865
866 // Remove it from our trackers
867 plane_trackers.erase(entity_id);
868 }
869 }
870 }
871
872 // Now that we're done, clean up our snapshot!
873 se_extension->free_spatial_snapshot(p_snapshot);
874
875 // And if this was our discovery snapshot, lets reset it
876 if (discovery_query_result.is_valid() && discovery_query_result->get_result_value() == p_snapshot) {
877 discovery_query_result.unref();
878 }
879 }