Debian Codegraph @

3rdparty/osgXR/src/OpenXR/Instance.cpp

raw symbols SCIP
1 // SPDX-License-Identifier: LGPL-2.1-only
2 // Copyright (C) 2021 James Hogan <[email protected]>
3
4 #include "DebugUtilsMessenger.h"
5 #include "EventHandler.h"
6 #include "Instance.h"
7 #include "Session.h"
8 #include "System.h"
9 #include "generated/Version.h"
10
11 #include <osg/Notify>
12 #include <osg/Version>
13 #include <osg/ref_ptr>
14
15 #include <cstring>
16 #include <vector>
17
18 #define ENGINE_NAME "osgXR"
19 #define ENGINE_VERSION (OSGXR_MAJOR_VERSION << 16 | \
20 OSGXR_MINOR_VERSION << 8 | \
21 OSGXR_PATCH_VERSION)
22 #define API_VERSION XR_MAKE_VERSION(1, 0, 0)
23
24 // Preserve compatibility with older versions of OpenXR SDK as best we can
25 #if XR_CURRENT_API_VERSION < XR_MAKE_VERSION(1, 0, 16)
26 #define XR_ERROR_RUNTIME_UNAVAILABLE (-51)
27 #endif
28
29 using namespace osgXR::OpenXR;
30
31 static std::vector<XrApiLayerProperties> layers;
32 static std::vector<XrExtensionProperties> extensions;
33
34 static bool enumerateLayers(bool invalidate = false)
35 {
36 static bool layersEnumerated = false;
37 if (invalidate)
38 {
39 layers.resize(0);
40 layersEnumerated = false;
41 return false;
42 }
43 if (layersEnumerated)
44 {
45 return true;
46 }
47
48 // Count layers
49 uint32_t layerCount = 0;
50 XrResult res = xrEnumerateApiLayerProperties(0, &layerCount, nullptr);
51 if (XR_FAILED(res))
52 {
53 OSG_WARN << "osgXR: Failed to count OpenXR API layers: " << res << std::endl;
54 return false;
55 }
56
57 if (layerCount)
58 {
59 // Allocate memory
60 layers.resize(layerCount);
61 for (auto &layer: layers)
62 {
63 layer.type = XR_TYPE_API_LAYER_PROPERTIES;
64 layer.next = nullptr;
65 }
66
67 // Enumerate layers
68 res = xrEnumerateApiLayerProperties(layers.size(), &layerCount, layers.data());
69 if (XR_FAILED(res))
70 {
71 OSG_WARN << "osgXR: Failed to enumerate " << layerCount
72 << " OpenXR API layers: " << res << std::endl;
73 return false;
74 }
75
76 // Layers may change at any time
77 layers.resize(layerCount);
78 }
79
80 layersEnumerated = true;
81 return true;
82 }
83
84 static bool enumerateExtensions(bool invalidate = false)
85 {
86 static bool extensionsEnumerated = false;
87 if (invalidate)
88 {
89 extensions.resize(0);
90 extensionsEnumerated = false;
91 return false;
92 }
93 if (extensionsEnumerated)
94 {
95 return true;
96 }
97
98 // Count extensions
99 uint32_t extensionCount;
100 XrResult res = xrEnumerateInstanceExtensionProperties(nullptr, 0, &extensionCount, nullptr);
101 if (XR_FAILED(res))
102 {
103 OSG_WARN << "osgXR: Failed to count OpenXR instance extensions: " << res << std::endl;
104 return false;
105 }
106
107 if (extensionCount)
108 {
109 // Allocate memory
110 extensions.resize(extensionCount);
111 for (auto &extension: extensions)
112 {
113 extension.type = XR_TYPE_EXTENSION_PROPERTIES;
114 extension.next = nullptr;
115 }
116
117 // Enumerate extensions
118 res = xrEnumerateInstanceExtensionProperties(nullptr, extensions.size(),
119 &extensionCount, extensions.data());
120 if (XR_FAILED(res))
121 {
122 OSG_WARN << "osgXR: Failed to enumerate " << extensionCount
123 << " OpenXR instance extensions: " << res << std::endl;
124 return false;
125 }
126
127 // Extensions may change (?)
128 extensions.resize(extensionCount);
129 }
130
131 extensionsEnumerated = true;
132 return true;
133 }
134
135 void Instance::invalidateLayers()
136 {
137 enumerateLayers(true);
138 }
139
140 void Instance::invalidateExtensions()
141 {
142 enumerateExtensions(true);
143 }
144
145 bool Instance::hasLayer(const char *name)
146 {
147 enumerateLayers();
148
149 for (auto &layer: layers)
150 {
151 if (!strncmp(name, layer.layerName, XR_MAX_API_LAYER_NAME_SIZE))
152 {
153 return true;
154 }
155 }
156 return false;
157 }
158
159 bool Instance::hasExtension(const char *name)
160 {
161 enumerateExtensions();
162
163 for (auto &extension: extensions)
164 {
165 if (!strncmp(name, extension.extensionName, XR_MAX_EXTENSION_NAME_SIZE))
166 {
167 return true;
168 }
169 }
170 return false;
171 }
172
173 Instance *Instance::instance()
174 {
175 static osg::ref_ptr<Instance> s_instance = new Instance();
176 return s_instance;
177 }
178
179 Instance::Instance():
180 _layerValidation(false),
181 _debugUtils(false),
182 _depthInfo(false),
183 _visibilityMask(true),
184 _instance(XR_NULL_HANDLE),
185 _lost(false)
186 {
187 }
188
189 Instance::~Instance()
190 {
191 if (valid())
192 {
193 // Delete the systems
194 for (System *system: _systems)
195 {
196 delete system;
197 }
198
199 // Destroy the OpenXR instance
200 XrResult res = xrDestroyInstance(_instance);
201 if (XR_FAILED(res))
202 {
203 OSG_WARN << "osgXR: Failed to destroy OpenXR instance" << std::endl;
204 }
205 }
206 }
207
208 void Instance::setDefaultDebugCallback(OpenXR::DebugUtilsCallback *callback)
209 {
210 if (!valid())
211 _defaultDebugCallback = callback;
212 }
213
214 Instance::InitResult Instance::init(const char *appName, uint32_t appVersion)
215 {
216 if (valid())
217 {
218 return INIT_SUCCESS;
219 }
220
221 std::vector<const char *> layerNames;
222 std::vector<const char *> extensionNames;
223
224 // Enable validation layer if selected
225 if (_layerValidation && hasLayer(XR_APILAYER_LUNARG_core_validation))
226 {
227 layerNames.push_back(XR_APILAYER_LUNARG_core_validation);
228 }
229
230 // We need OpenGL support
231 if (!hasExtension(XR_KHR_OPENGL_ENABLE_EXTENSION_NAME))
232 {
233 OSG_WARN << "osgXR: OpenXR runtime doesn't support XR_KHR_opengl_enable extension" << std::endl;
234 return INIT_FAIL;
235 }
236 extensionNames.push_back(XR_KHR_OPENGL_ENABLE_EXTENSION_NAME);
237
238 // Enable debug utils if supported
239 _supportsDebugUtils = hasExtension(XR_EXT_DEBUG_UTILS_EXTENSION_NAME);
240 if (_debugUtils)
241 {
242 if (_supportsDebugUtils)
243 extensionNames.push_back(XR_EXT_DEBUG_UTILS_EXTENSION_NAME);
244 else
245 _debugUtils = false;
246 }
247
248 // Enable depth composition layer support if supported
249 _supportsCompositionLayerDepth = hasExtension(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME);
250 if (_depthInfo)
251 {
252 if (_supportsCompositionLayerDepth)
253 extensionNames.push_back(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME);
254 else
255 _depthInfo = false;
256 }
257
258 // Enable visibility mask support if supported
259 _supportsVisibilityMask = hasExtension(XR_KHR_VISIBILITY_MASK_EXTENSION_NAME);
260 if (_visibilityMask)
261 {
262 if (_supportsVisibilityMask)
263 extensionNames.push_back(XR_KHR_VISIBILITY_MASK_EXTENSION_NAME);
264 else
265 _visibilityMask = false;
266 }
267
268 // Create the instance
269 XrInstanceCreateInfo info{ XR_TYPE_INSTANCE_CREATE_INFO };
270 strncpy(info.applicationInfo.applicationName, appName,
271 XR_MAX_APPLICATION_NAME_SIZE - 1);
272 info.applicationInfo.applicationVersion = appVersion;
273 strncpy(info.applicationInfo.engineName, ENGINE_NAME,
274 XR_MAX_ENGINE_NAME_SIZE - 1);
275 info.applicationInfo.engineVersion = ENGINE_VERSION;
276 info.applicationInfo.apiVersion = API_VERSION;
277 info.enabledApiLayerCount = layerNames.size();
278 info.enabledApiLayerNames = layerNames.data();
279 info.enabledExtensionCount = extensionNames.size();
280 info.enabledExtensionNames = extensionNames.data();
281
282
283 DebugUtilsCallback::CreateInfo debugCallback;
284 if (_debugUtils && _defaultDebugCallback.valid())
285 {
286 _defaultDebugCallback->writeCreateInfo(&debugCallback);
287 info.next = &debugCallback;
288 }
289
290 XrResult res = xrCreateInstance(&info, &_instance);
291 if (!check(res, "create OpenXR instance"))
292 {
293 // cast to handle XR_ERROR_RUNTIME_UNAVAILABLE as a preprocessor define
294 switch ((int)res)
295 {
296 // prior to OpenXR 1.0.16
297 case XR_ERROR_INSTANCE_LOST:
298 // since OpenXR 1.0.16
299 case XR_ERROR_RUNTIME_UNAVAILABLE:
300 // Monado returns this when service not running
301 case XR_ERROR_RUNTIME_FAILURE:
302 return INIT_LATER;
303
304 default:
305 return INIT_FAIL;
306 }
307 }
308
309 if (_debugUtils)
310 {
311 _xrCreateDebugUtilsMessengerEXT = (PFN_xrCreateDebugUtilsMessengerEXT) getProcAddr("xrCreateDebugUtilsMessengerEXT");
312 if (_defaultDebugCallback.valid())
313 {
314 _defaultDebugMessenger = new DebugUtilsMessenger(this, _defaultDebugCallback);
315 if (!_defaultDebugMessenger->valid()) {
316 OSG_WARN << "osgXR: Failed to create default debug utils messenger" << std::endl;
317 _defaultDebugMessenger = nullptr;
318 }
319 }
320 }
321
322 // Log the runtime properties
323 _properties.type = XR_TYPE_INSTANCE_PROPERTIES;
324 _properties.next = nullptr;
325
326 if (XR_SUCCEEDED(xrGetInstanceProperties(_instance, &_properties)))
327 {
328 OSG_INFO << "osgXR: OpenXR Runtime: \"" << _properties.runtimeName
329 << "\" version " << XR_VERSION_MAJOR(_properties.runtimeVersion)
330 << "." << XR_VERSION_MINOR(_properties.runtimeVersion)
331 << "." << XR_VERSION_PATCH(_properties.runtimeVersion) << std::endl;
332 _quirks.probe(this);
333 }
334
335 // Get extension functions
336 _xrGetOpenGLGraphicsRequirementsKHR = (PFN_xrGetOpenGLGraphicsRequirementsKHR)getProcAddr("xrGetOpenGLGraphicsRequirementsKHR");
337 if (_debugUtils)
338 {
339 _xrSetDebugUtilsObjectNameEXT = (PFN_xrSetDebugUtilsObjectNameEXT) getProcAddr("xrSetDebugUtilsObjectNameEXT");
340 // _xrCreateDebugUtilsMessengerEXT already obtained above
341 _xrDestroyDebugUtilsMessengerEXT = (PFN_xrDestroyDebugUtilsMessengerEXT) getProcAddr("xrDestroyDebugUtilsMessengerEXT");
342 _xrSubmitDebugUtilsMessageEXT = (PFN_xrSubmitDebugUtilsMessageEXT) getProcAddr("xrSubmitDebugUtilsMessageEXT");
343 _xrSessionBeginDebugUtilsLabelRegionEXT = (PFN_xrSessionBeginDebugUtilsLabelRegionEXT) getProcAddr("xrSessionBeginDebugUtilsLabelRegionEXT");
344 _xrSessionEndDebugUtilsLabelRegionEXT = (PFN_xrSessionEndDebugUtilsLabelRegionEXT) getProcAddr("xrSessionEndDebugUtilsLabelRegionEXT");
345 _xrSessionInsertDebugUtilsLabelEXT = (PFN_xrSessionInsertDebugUtilsLabelEXT) getProcAddr("xrSessionInsertDebugUtilsLabelEXT");
346 }
347 if (_visibilityMask)
348 _xrGetVisibilityMaskKHR = (PFN_xrGetVisibilityMaskKHR)getProcAddr("xrGetVisibilityMaskKHR");
349
350 return INIT_SUCCESS;
351 }
352
353 void Instance::deinit()
354 {
355 // Destroy the default debug messenger so it doesn't prevent destruction
356 _defaultDebugMessenger = nullptr;
357 }
358
359 bool Instance::check(XrResult result, const char *actionMsg) const
360 {
361 if (XR_FAILED(result))
362 {
363 if (result == XR_ERROR_INSTANCE_LOST)
364 _lost = true;
365
366 _lastError.action = actionMsg;
367 char resultName[XR_MAX_RESULT_STRING_SIZE];
368 if (!valid() || XR_FAILED(xrResultToString(_instance, result, resultName)))
369 {
370 OSG_WARN << "osgXR: Failed to " << actionMsg << ": " << result << std::endl;
371 _lastError.resultName[0] = '\0';
372 }
373 else
374 {
375 OSG_WARN << "osgXR: Failed to " << actionMsg << ": " << resultName << std::endl;
376 strncpy(_lastError.resultName, resultName, XR_MAX_RESULT_STRING_SIZE);
377 }
378 _lastError.result = result;
379 return false;
380 }
381 return true;
382 }
383
384 PFN_xrVoidFunction Instance::getProcAddr(const char *name) const
385 {
386 PFN_xrVoidFunction ret = nullptr;
387 check(xrGetInstanceProcAddr(_instance, name, &ret),
388 "get OpenXR procedure address");
389 return ret;
390 }
391
392 System *Instance::getSystem(XrFormFactor formFactor, bool *supported)
393 {
394 unsigned long ffId = formFactor - 1;
395 if (ffId < _systems.size() && _systems[ffId])
396 {
397 if (supported)
398 *supported = true;
399 return _systems[ffId];
400 }
401
402 XrSystemGetInfo getInfo{ XR_TYPE_SYSTEM_GET_INFO };
403 getInfo.formFactor = formFactor;
404
405 XrSystemId systemId;
406 XrResult res = xrGetSystem(_instance, &getInfo, &systemId);
407 if (res == XR_ERROR_FORM_FACTOR_UNAVAILABLE)
408 {
409 // The system is only *TEMPORARILY* unavailable
410 if (supported)
411 *supported = true;
412 return nullptr;
413 }
414 else if (check(res, "get OpenXR system"))
415 {
416 if (ffId >= _systems.size())
417 _systems.resize(ffId+1, nullptr);
418
419 if (supported)
420 *supported = true;
421 return _systems[ffId] = new System(this, systemId);
422 }
423
424 if (supported)
425 *supported = false;
426 return nullptr;
427 }
428
429 void Instance::invalidateSystem(XrFormFactor formFactor)
430 {
431 unsigned long ffId = formFactor - 1;
432 if (ffId < _systems.size())
433 {
434 delete _systems[ffId];
435 _systems[ffId] = nullptr;
436 }
437 }
438
439 void Instance::registerSession(Session *session)
440 {
441 _sessions[session->getXrSession()] = session;
442 }
443
444 void Instance::unregisterSession(Session *session)
445 {
446 _sessions.erase(session->getXrSession());
447 }
448
449 Session *Instance::getSession(XrSession xrSession)
450 {
451 auto it = _sessions.find(xrSession);
452 if (it == _sessions.end())
453 return nullptr;
454 return (*it).second;
455 }
456
457 void Instance::pollEvents(EventHandler *handler)
458 {
459 for (;;)
460 {
461 XrEventDataBuffer event;
462 event.type = XR_TYPE_EVENT_DATA_BUFFER;
463 event.next = nullptr;
464
465 XrResult res = xrPollEvent(_instance, &event);
466 if (XR_FAILED(res))
467 break;
468 if (res == XR_EVENT_UNAVAILABLE)
469 break;
470
471 handler->onEvent(this, &event);
472 }
473 }