| 1 | // SPDX-License-Identifier: LGPL-2.1-only |
| 2 | // Copyright (C) 2021 James Hogan <[email protected]> |
| 3 | |
| 4 | #include "XRState.h" |
| 5 | #include "XRStateCallbacks.h" |
| 6 | #include "ActionSet.h" |
| 7 | #include "CompositionLayer.h" |
| 8 | #include "DebugCallbackOsg.h" |
| 9 | #include "InteractionProfile.h" |
| 10 | #include "Subaction.h" |
| 11 | #include "projection.h" |
| 12 | |
| 13 | #include <osgXR/Manager> |
| 14 | |
| 15 | #include <osg/Camera> |
| 16 | #include <osg/ColorMask> |
| 17 | #include <osg/Depth> |
| 18 | #include <osg/DisplaySettings> |
| 19 | #include <osg/FrameBufferObject> |
| 20 | #include <osg/Notify> |
| 21 | #include <osg/MatrixTransform> |
| 22 | #include <osg/RenderInfo> |
| 23 | #include <osg/Texture> |
| 24 | #include <osg/View> |
| 25 | |
| 26 | #include <osgUtil/SceneView> |
| 27 | |
| 28 | #include <osgViewer/GraphicsWindow> |
| 29 | #include <osgViewer/Renderer> |
| 30 | #include <osgViewer/View> |
| 31 | |
| 32 | #include <cassert> |
| 33 | #include <climits> |
| 34 | #include <cmath> |
| 35 | #include <sstream> |
| 36 | |
| 37 | #ifndef GL_DEPTH32F_STENCIL8 |
| 38 | #define GL_DEPTH32F_STENCIL8 0x8cad |
| 39 | #endif |
| 40 | |
| 41 | using namespace osgXR; |
| 42 | |
| 43 | XRState::XRState(Settings *settings, Manager *manager) : |
| 44 | _settings(settings), |
| 45 | _settingsCopy(*settings), |
| 46 | _manager(manager), |
| 47 | _visibilityMaskLeft(0), |
| 48 | _visibilityMaskRight(0), |
| 49 | _actionsUpdated(false), |
| 50 | _compositionLayersUpdated(false), |
| 51 | _currentState(VRSTATE_DISABLED), |
| 52 | _downState(VRSTATE_MAX), |
| 53 | _upState(VRSTATE_DISABLED), |
| 54 | _upDelay(0), |
| 55 | _probing(false), |
| 56 | _stateChanged(false), |
| 57 | _probed(false), |
| 58 | _useDepthInfo(false), |
| 59 | _useVisibilityMask(false), |
| 60 | _formFactor(XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY), |
| 61 | _system(nullptr), |
| 62 | _chosenViewConfig(nullptr), |
| 63 | _chosenEnvBlendMode(XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM), |
| 64 | _vrMode(VRMode::VRMODE_AUTOMATIC), |
| 65 | _swapchainMode(SwapchainMode::SWAPCHAIN_AUTOMATIC) |
| 66 | { |
| 67 | } |
| 68 | |
| 69 | XRState::XRSwapchain::XRSwapchain(XRState *state, |
| 70 | osg::ref_ptr<OpenXR::Session> session, |
| 71 | const OpenXR::System::ViewConfiguration::View &view, |
| 72 | int64_t chosenRGBAFormat, |
| 73 | int64_t chosenDepthFormat, |
| 74 | GLenum fallbackDepthFormat) : |
| 75 | OpenXR::SwapchainGroup(session, view, |
| 76 | XR_SWAPCHAIN_USAGE_COLOR_ATTACHMENT_BIT, |
| 77 | chosenRGBAFormat, |
| 78 | XR_SWAPCHAIN_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, |
| 79 | chosenDepthFormat), |
| 80 | _state(state), |
| 81 | _forcedAlpha(-1.0f), |
| 82 | _numDrawPasses(0), |
| 83 | _drawPassesDone(0), |
| 84 | _imagesReady(false) |
| 85 | { |
| 86 | if (valid()) |
| 87 | { |
| 88 | // Create framebuffer objects for each image in swapchain |
| 89 | auto &textures = getImageTextures(); |
| 90 | const ImageTextures *depthTextures = nullptr; |
| 91 | if (depthValid()) |
| 92 | { |
| 93 | depthTextures = &getDepthImageTextures(); |
| 94 | if (textures.size() != depthTextures->size()) |
| 95 | OSG_WARN << "osgXR: Depth swapchain image count mismatch, expected " << textures.size() << ", got " << depthTextures->size() << std::endl; |
| 96 | } |
| 97 | |
| 98 | _imageFramebuffers.reserve(textures.size()); |
| 99 | for (unsigned int i = 0; i < textures.size(); ++i) |
| 100 | { |
| 101 | GLuint texture = textures[i]; |
| 102 | GLuint depthTexture = 0; |
| 103 | if (depthTextures) |
| 104 | depthTexture = (*depthTextures)[i]; |
| 105 | XRFramebuffer *fb = new XRFramebuffer(getWidth(), |
| 106 | getHeight(), |
| 107 | texture, depthTexture); |
| 108 | fb->setDepthFormat(fallbackDepthFormat); |
| 109 | _imageFramebuffers.push_back(fb); |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | XRState::XRSwapchain::~XRSwapchain() |
| 115 | { |
| 116 | osg::State *state = _state->_window->getState(); |
| 117 | // FIXME window has no state on shutdown... |
| 118 | if (!state) |
| 119 | return; |
| 120 | // Explicitly release FBOs etc |
| 121 | // GL context must be current |
| 122 | for (unsigned int i = 0; i < _imageFramebuffers.size(); ++i) |
| 123 | _imageFramebuffers[i]->releaseGLObjects(*state); |
| 124 | } |
| 125 | |
| 126 | void XRState::XRSwapchain::setupImage(const osg::FrameStamp *stamp) |
| 127 | { |
| 128 | auto opt_fbo = _imageFramebuffers[stamp]; |
| 129 | bool firstPass = !opt_fbo.has_value(); |
| 130 | int imageIndex; |
| 131 | if (firstPass) |
| 132 | { |
| 133 | // Acquire a swapchain image |
| 134 | imageIndex = acquireImages(); |
| 135 | if (imageIndex < 0 || (unsigned int)imageIndex >= _imageFramebuffers.size()) |
| 136 | { |
| 137 | OSG_WARN << "osgXR: Failure to acquire OpenXR swapchain image (got image index " << imageIndex << ")" << std::endl; |
| 138 | return; |
| 139 | } |
| 140 | _imageFramebuffers.setStamp(imageIndex, stamp); |
| 141 | opt_fbo.emplace(_imageFramebuffers[imageIndex]); |
| 142 | _drawPassesDone = 0; |
| 143 | // Images aren't ready until we've waited for them to be so |
| 144 | _imagesReady = false; |
| 145 | } |
| 146 | } |
| 147 | |
| 148 | void XRState::XRSwapchain::preDrawCallback(osg::RenderInfo &renderInfo) |
| 149 | { |
| 150 | const osg::FrameStamp *stamp = renderInfo.getState()->getFrameStamp(); |
| 151 | setupImage(stamp); |
| 152 | |
| 153 | auto opt_fbo = _imageFramebuffers[stamp]; |
| 154 | if (!opt_fbo.has_value()) |
| 155 | return; |
| 156 | |
| 157 | const auto &fbo = opt_fbo.value(); |
| 158 | |
| 159 | // Bind the framebuffer |
| 160 | osg::State &state = *renderInfo.getState(); |
| 161 | fbo->bind(state); |
| 162 | |
| 163 | if (!_imagesReady) |
| 164 | { |
| 165 | // Wait for the image to be ready to render into |
| 166 | if (!waitImages(100e6 /* 100ms */)) |
| 167 | { |
| 168 | OSG_WARN << "osgXR: Failure to wait for OpenXR swapchain image" << std::endl; |
| 169 | |
| 170 | // Unclear what the best course of action is here... |
| 171 | fbo->unbind(state); |
| 172 | return; |
| 173 | } |
| 174 | |
| 175 | _imagesReady = true; |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | void XRState::XRSwapchain::postDrawCallback(osg::RenderInfo &renderInfo) |
| 180 | { |
| 181 | const osg::FrameStamp *stamp = renderInfo.getState()->getFrameStamp(); |
| 182 | auto opt_fbo = _imageFramebuffers[stamp]; |
| 183 | if (!opt_fbo.has_value()) |
| 184 | return; |
| 185 | const auto &fbo = opt_fbo.value(); |
| 186 | |
| 187 | // Unbind the framebuffer |
| 188 | osg::State& state = *renderInfo.getState(); |
| 189 | |
| 190 | if (++_drawPassesDone == _numDrawPasses && _imagesReady) |
| 191 | { |
| 192 | if (_forcedAlpha >= 0) |
| 193 | { |
| 194 | // Hack the alpha to a particular value, unpremultiplied |
| 195 | // FIXME this overwrites clear colour! |
| 196 | glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_TRUE); |
| 197 | glClearColor(0, 0, 0, _forcedAlpha); |
| 198 | glClear(GL_COLOR_BUFFER_BIT); |
| 199 | glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); |
| 200 | glClearColor(0, 0, 0, 1); |
| 201 | } |
| 202 | |
| 203 | fbo->unbind(state); |
| 204 | |
| 205 | // Done rendering. release the swapchain image |
| 206 | releaseImages(); |
| 207 | |
| 208 | _imagesReady = false; |
| 209 | } |
| 210 | else |
| 211 | { |
| 212 | fbo->unbind(state); |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | void XRState::XRSwapchain::endFrame() |
| 217 | { |
| 218 | // Double check images are released |
| 219 | if (_imagesReady) |
| 220 | { |
| 221 | releaseImages(); |
| 222 | _imagesReady = false; |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | osg::ref_ptr<osg::Texture2D> XRState::XRSwapchain::getOsgTexture(const osg::FrameStamp *stamp) |
| 227 | { |
| 228 | int index = _imageFramebuffers.findStamp(stamp); |
| 229 | if (index < 0) |
| 230 | return nullptr; |
| 231 | return getSwapchain()->getImageOsgTexture(index); |
| 232 | } |
| 233 | |
| 234 | XRState::XRView::XRView(XRState *state, |
| 235 | uint32_t viewIndex, |
| 236 | osg::ref_ptr<XRSwapchain> swapchain) : |
| 237 | _state(state), |
| 238 | _swapchainSubImage(swapchain), |
| 239 | _viewIndex(viewIndex) |
| 240 | { |
| 241 | } |
| 242 | |
| 243 | XRState::XRView::XRView(XRState *state, |
| 244 | uint32_t viewIndex, |
| 245 | osg::ref_ptr<XRSwapchain> swapchain, |
| 246 | const OpenXR::System::ViewConfiguration::View::Viewport &viewport) : |
| 247 | _state(state), |
| 248 | _swapchainSubImage(swapchain, viewport), |
| 249 | _viewIndex(viewIndex) |
| 250 | { |
| 251 | } |
| 252 | |
| 253 | XRState::XRView::~XRView() |
| 254 | { |
| 255 | } |
| 256 | |
| 257 | void XRState::XRView::setupCamera(osg::ref_ptr<osg::Camera> camera) |
| 258 | { |
| 259 | camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); |
| 260 | // FIXME necessary I expect... |
| 261 | //camera->setRenderOrder(osg::Camera::PRE_RENDER, eye); |
| 262 | //camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR); |
| 263 | camera->setAllowEventFocus(false); |
| 264 | camera->setReferenceFrame(osg::Camera::RELATIVE_RF); |
| 265 | //camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF); |
| 266 | //camera->setReferenceFrame(osg::Camera::ABSOLUTE_RF_INHERIT_VIEWPOINT); |
| 267 | camera->setViewport(_swapchainSubImage.getX(), |
| 268 | _swapchainSubImage.getY(), |
| 269 | _swapchainSubImage.getWidth(), |
| 270 | _swapchainSubImage.getHeight()); |
| 271 | |
| 272 | // Here we avoid doing anything regarding OSG camera RTT attachment. |
| 273 | // Ideally we would use automatic methods within OSG for handling RTT but in this |
| 274 | // case it seemed simpler to handle FBO creation and selection within this class. |
| 275 | |
| 276 | // This initial draw callback is used to disable normal OSG camera setup which |
| 277 | // would undo our RTT FBO configuration. |
| 278 | camera->setInitialDrawCallback(new InitialDrawCallback(_state)); |
| 279 | |
| 280 | camera->setPreDrawCallback(new PreDrawCallback(getSwapchain())); |
| 281 | camera->setFinalDrawCallback(new PostDrawCallback(getSwapchain())); |
| 282 | } |
| 283 | |
| 284 | void XRState::XRView::endFrame(OpenXR::Session::Frame *frame) |
| 285 | { |
| 286 | // Double check images are released |
| 287 | getSwapchain()->endFrame(); |
| 288 | |
| 289 | // Add view info to projection layer for compositor |
| 290 | osg::ref_ptr<OpenXR::CompositionLayerProjection> proj = _state->getProjectionLayer(); |
| 291 | if (proj != nullptr) |
| 292 | { |
| 293 | proj->addView(frame, _viewIndex, _swapchainSubImage, |
| 294 | _state->_useDepthInfo ? &_state->_depthInfo : nullptr); |
| 295 | } |
| 296 | else |
| 297 | { |
| 298 | OSG_WARN << "osgXR: No projection layer" << std::endl; |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | XRState::AppView::AppView(XRState *state, |
| 303 | osgViewer::GraphicsWindow *window, |
| 304 | osgViewer::View *osgView) : |
| 305 | View(window, osgView), |
| 306 | _valid(false), |
| 307 | _state(state) |
| 308 | { |
| 309 | } |
| 310 | |
| 311 | void XRState::AppView::init() |
| 312 | { |
| 313 | // Notify app to create a new view |
| 314 | if (_state->_manager.valid()) |
| 315 | _state->_manager->doCreateView(this); |
| 316 | _valid = true; |
| 317 | } |
| 318 | |
| 319 | XRState::AppView::~AppView() |
| 320 | { |
| 321 | destroy(); |
| 322 | } |
| 323 | |
| 324 | void XRState::AppView::destroy() |
| 325 | { |
| 326 | // Notify app to destroy this view |
| 327 | if (_valid && _state->_manager.valid()) |
| 328 | _state->_manager->doDestroyView(this); |
| 329 | _valid = false; |
| 330 | } |
| 331 | |
| 332 | XRState::SlaveCamsAppView::SlaveCamsAppView(XRState *state, |
| 333 | uint32_t viewIndex, |
| 334 | osgViewer::GraphicsWindow *window, |
| 335 | osgViewer::View *osgView) : |
| 336 | AppView(state, window, osgView), |
| 337 | _viewIndex(viewIndex) |
| 338 | { |
| 339 | } |
| 340 | |
| 341 | void XRState::SlaveCamsAppView::addSlave(osg::Camera *slaveCamera) |
| 342 | { |
| 343 | XRView *xrView = _state->_xrViews[_viewIndex]; |
| 344 | xrView->setupCamera(slaveCamera); |
| 345 | xrView->getSwapchain()->incNumDrawPasses(); |
| 346 | |
| 347 | osg::ref_ptr<osg::MatrixTransform> visMaskTransform; |
| 348 | // Set up visibility mask for this slave camera |
| 349 | // We'll keep track of the transform in the slave callback so it can be |
| 350 | // positioned at the appropriate range |
| 351 | if (_state->needsVisibilityMask(slaveCamera)) |
| 352 | _state->setupVisibilityMask(slaveCamera, _viewIndex, visMaskTransform); |
| 353 | |
| 354 | osg::View::Slave *slave = _osgView->findSlaveForCamera(slaveCamera); |
| 355 | slave->_updateSlaveCallback = new SlaveCamsUpdateSlaveCallback(_viewIndex, _state, visMaskTransform.get()); |
| 356 | } |
| 357 | |
| 358 | void XRState::SlaveCamsAppView::removeSlave(osg::Camera *slaveCamera) |
| 359 | { |
| 360 | XRView *xrView = _state->_xrViews[_viewIndex]; |
| 361 | xrView->getSwapchain()->decNumDrawPasses(); |
| 362 | } |
| 363 | |
| 364 | XRState::SceneViewAppView::SceneViewAppView(XRState *state, |
| 365 | osgViewer::GraphicsWindow *window, |
| 366 | osgViewer::View *osgView) : |
| 367 | AppView(state, window, osgView) |
| 368 | { |
| 369 | } |
| 370 | |
| 371 | void XRState::SceneViewAppView::addSlave(osg::Camera *slaveCamera) |
| 372 | { |
| 373 | _state->setupSceneViewCamera(slaveCamera); |
| 374 | _state->_xrViews[0]->getSwapchain()->incNumDrawPasses(2); |
| 375 | |
| 376 | osg::ref_ptr<osg::MatrixTransform> visMaskTransform; |
| 377 | // Set up visibility masks for this slave camera |
| 378 | // We'll keep track of the transform in the slave callback so it can be |
| 379 | // positioned at the appropriate range |
| 380 | if (_state->needsVisibilityMask(slaveCamera)) |
| 381 | _state->setupSceneViewVisibilityMasks(slaveCamera, visMaskTransform); |
| 382 | |
| 383 | if (visMaskTransform.valid()) |
| 384 | { |
| 385 | osg::View::Slave *slave = _osgView->findSlaveForCamera(slaveCamera); |
| 386 | if (slave) |
| 387 | slave->_updateSlaveCallback = new SceneViewUpdateSlaveCallback(_state, visMaskTransform.get()); |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | void XRState::SceneViewAppView::removeSlave(osg::Camera *slaveCamera) |
| 392 | { |
| 393 | _state->_xrViews[0]->getSwapchain()->decNumDrawPasses(2); |
| 394 | } |
| 395 | |
| 396 | std::shared_ptr<Subaction::Private> XRState::getSubaction(const std::string &path) |
| 397 | { |
| 398 | auto it = _subactions.find(path); |
| 399 | if (it != _subactions.end()) |
| 400 | { |
| 401 | auto ret = (*it).second.lock(); |
| 402 | if (ret) |
| 403 | return ret; |
| 404 | } |
| 405 | |
| 406 | auto subaction = std::make_shared<Subaction::Private>(this, path); |
| 407 | _subactions[path] = subaction; |
| 408 | return subaction; |
| 409 | } |
| 410 | |
| 411 | InteractionProfile *XRState::getCurrentInteractionProfile(const OpenXR::Path &subactionPath) const |
| 412 | { |
| 413 | if (_session.valid()) |
| 414 | { |
| 415 | // Find the path of the current profile |
| 416 | OpenXR::Path profilePath = _session->getCurrentInteractionProfile(subactionPath); |
| 417 | if (!profilePath.valid()) |
| 418 | return nullptr; |
| 419 | |
| 420 | // Compare against the paths of known interaction profiles |
| 421 | for (auto *profile: _interactionProfiles) |
| 422 | if (profile->getPath() == profilePath) |
| 423 | return profile->getPublic(); |
| 424 | } |
| 425 | return nullptr; |
| 426 | } |
| 427 | |
| 428 | const char *XRState::getStateString() const |
| 429 | { |
| 430 | static const char *vrStateNames[VRSTATE_MAX] = { |
| 431 | "disabled", |
| 432 | "inactive", |
| 433 | "detected", |
| 434 | "session", |
| 435 | "actions", |
| 436 | }; |
| 437 | static const char *sessionStateNames[] = { |
| 438 | "unknown", |
| 439 | "idle", |
| 440 | "starting", |
| 441 | "invisible", |
| 442 | "visible unfocused", |
| 443 | "focused", |
| 444 | "stopping", |
| 445 | "loss pending", |
| 446 | "ending" |
| 447 | }; |
| 448 | static const char *vrStateChangeNames[VRSTATE_MAX + 1][VRSTATE_MAX] = { |
| 449 | { // down = VRSTATE_DISABLED |
| 450 | "disabling", // up = VRSTATE_DISABLED |
| 451 | "reinitialising", // up = VRSTATE_INSTANCE |
| 452 | "reinitialising & probing", // up = VRSTATE_SYSTEM |
| 453 | "restarting session", // up = VRSTATE_SESSION |
| 454 | "restarting" // up = VRSTATE_ACTIONS |
| 455 | }, |
| 456 | { // down = VRSTATE_INSTANCE |
| 457 | nullptr, // up = VRSTATE_DISABLED |
| 458 | "deactivating", // up = VRSTATE_INSTANCE |
| 459 | "reprobing", // up = VRSTATE_SYSTEM |
| 460 | "reprobing session", // up = VRSTATE_SESSION |
| 461 | "reprobing session" // up = VRSTATE_ACTIONS |
| 462 | }, |
| 463 | { // down = VRSTATE_SYSTEM |
| 464 | nullptr, // up = VRSTATE_DISABLED |
| 465 | nullptr, // up = VRSTATE_INSTANCE |
| 466 | "ending session", // up = VRSTATE_SYSTEM |
| 467 | "restarting session", // up = VRSTATE_SESSION |
| 468 | "restarting" // up = VRSTATE_ACTIONS |
| 469 | }, |
| 470 | { // down = VRSTATE_SESSION |
| 471 | nullptr, // up = VRSTATE_DISABLED |
| 472 | nullptr, // up = VRSTATE_INSTANCE |
| 473 | nullptr, // up = VRSTATE_SYSTEM |
| 474 | nullptr, // up = VRSTATE_SESSION |
| 475 | "attaching actions" // up = VRSTATE_ACTIONS |
| 476 | }, |
| 477 | { // down = VRSTATE_ACTIONS |
| 478 | nullptr, // up = VRSTATE_DISABLED |
| 479 | nullptr, // up = VRSTATE_INSTANCE |
| 480 | nullptr, // up = VRSTATE_SYSTEM |
| 481 | nullptr, // up = VRSTATE_SESSION |
| 482 | nullptr, // up = VRSTATE_ACTIONS |
| 483 | }, |
| 484 | { // down = VRSTATE_MAX |
| 485 | nullptr, // up = VRSTATE_DISABLED |
| 486 | "initialising", // up = VRSTATE_INSTANCE |
| 487 | "probing", // up = VRSTATE_SYSTEM |
| 488 | "starting session", // up = VRSTATE_SESSION |
| 489 | "attaching actions" // up = VRSTATE_ACTIONS |
| 490 | }, |
| 491 | }; |
| 492 | |
| 493 | std::string out = vrStateNames[_currentState]; |
| 494 | if (_currentState >= VRSTATE_SESSION) |
| 495 | { |
| 496 | out += " "; |
| 497 | out += sessionStateNames[_session->getState()]; |
| 498 | } |
| 499 | if (isStateUpdateNeeded()) |
| 500 | { |
| 501 | const char *str = vrStateChangeNames[_downState][_upState]; |
| 502 | if (str) |
| 503 | { |
| 504 | out += " ("; |
| 505 | out += str; |
| 506 | out += ")"; |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | // Find last error |
| 511 | OpenXR::Instance::Result error{}; |
| 512 | const char *errorType[] = { |
| 513 | "Failed to ", |
| 514 | "Previously failed to ", |
| 515 | }; |
| 516 | const OpenXR::Instance::Result *errorp[2] = { |
| 517 | &error, |
| 518 | &_lastRunError, |
| 519 | }; |
| 520 | if (_instance.valid()) |
| 521 | _instance->getError(error); |
| 522 | else |
| 523 | errorp[0] = &_lastError; |
| 524 | |
| 525 | // If there was a failure, report it |
| 526 | for (unsigned int i = 0; i < 2; ++i) |
| 527 | { |
| 528 | auto *curError = errorp[i]; |
| 529 | if (curError->failed()) |
| 530 | { |
| 531 | out += "\n "; |
| 532 | out += errorType[i]; |
| 533 | out += curError->action; |
| 534 | out += " ("; |
| 535 | if (curError->resultName[0] == '\0') |
| 536 | out += std::to_string(curError->result); |
| 537 | else |
| 538 | out += curError->resultName; |
| 539 | out += ")"; |
| 540 | } |
| 541 | } |
| 542 | |
| 543 | _stateString = out; |
| 544 | return _stateString.c_str(); |
| 545 | } |
| 546 | |
| 547 | bool XRState::hasValidationLayer() const |
| 548 | { |
| 549 | if (!_probed) |
| 550 | probe(); |
| 551 | return _hasValidationLayer; |
| 552 | } |
| 553 | |
| 554 | bool XRState::hasDepthInfoExtension() const |
| 555 | { |
| 556 | if (!_probed) |
| 557 | probe(); |
| 558 | return _hasDepthInfoExtension; |
| 559 | } |
| 560 | |
| 561 | bool XRState::hasVisibilityMaskExtension() const |
| 562 | { |
| 563 | if (!_probed) |
| 564 | probe(); |
| 565 | return _hasVisibilityMaskExtension; |
| 566 | } |
| 567 | |
| 568 | void XRState::syncSettings() |
| 569 | { |
| 570 | unsigned int diff = _settingsCopy._diff(*_settings.get()); |
| 571 | if (diff & (Settings::DIFF_APP_INFO | |
| 572 | Settings::DIFF_VALIDATION_LAYER)) |
| 573 | // Recreate instance |
| 574 | setDownState(VRSTATE_DISABLED); |
| 575 | else if (diff & (Settings::DIFF_FORM_FACTOR | |
| 576 | Settings::DIFF_BLEND_MODE)) |
| 577 | // Reread system |
| 578 | setDownState(VRSTATE_INSTANCE); |
| 579 | else if (diff & (Settings::DIFF_DEPTH_INFO | |
| 580 | Settings::DIFF_VISIBILITY_MASK | |
| 581 | Settings::DIFF_VR_MODE | |
| 582 | Settings::DIFF_SWAPCHAIN_MODE | |
| 583 | Settings::DIFF_RGB_ENCODING | |
| 584 | Settings::DIFF_DEPTH_ENCODING | |
| 585 | Settings::DIFF_RGB_BITS | |
| 586 | Settings::DIFF_ALPHA_BITS | |
| 587 | Settings::DIFF_DEPTH_BITS | |
| 588 | Settings::DIFF_STENCIL_BITS)) |
| 589 | // Recreate session |
| 590 | setDownState(VRSTATE_SYSTEM); |
| 591 | } |
| 592 | |
| 593 | bool XRState::getActionsUpdated() const |
| 594 | { |
| 595 | // Have action sets or interaction profiles been added or removed? |
| 596 | if (_actionsUpdated) |
| 597 | return true; |
| 598 | |
| 599 | // Have action sets or their actions been altered? |
| 600 | for (auto *actionSet: _actionSets) |
| 601 | if (actionSet->getUpdated()) |
| 602 | return true; |
| 603 | |
| 604 | // Have interaction profile bindings been altered? |
| 605 | for (auto *interactionProfile: _interactionProfiles) |
| 606 | if (interactionProfile->getUpdated()) |
| 607 | return true; |
| 608 | |
| 609 | return false; |
| 610 | } |
| 611 | |
| 612 | void XRState::syncActionSetup() |
| 613 | { |
| 614 | // Nothing is required if actions haven't been attached yet |
| 615 | if (_currentState < VRSTATE_ACTIONS) |
| 616 | return; |
| 617 | |
| 618 | // Restart session if actions have been updated |
| 619 | if (getActionsUpdated()) |
| 620 | setDownState(VRSTATE_SYSTEM); |
| 621 | } |
| 622 | |
| 623 | void XRState::addCompositionLayer(CompositionLayer::Private *layer) |
| 624 | { |
| 625 | _compositionLayers.push_back(layer); |
| 626 | _compositionLayersUpdated = true; |
| 627 | } |
| 628 | |
| 629 | void XRState::removeCompositionLayer(CompositionLayer::Private *layer) |
| 630 | { |
| 631 | auto it = std::find(_compositionLayers.begin(), _compositionLayers.end(), |
| 632 | layer); |
| 633 | if (it != _compositionLayers.end()) |
| 634 | { |
| 635 | _compositionLayers.erase(it); |
| 636 | _compositionLayersUpdated = true; |
| 637 | } |
| 638 | } |
| 639 | |
| 640 | bool XRState::checkAndResetStateChanged() |
| 641 | { |
| 642 | bool ret = _stateChanged; |
| 643 | _stateChanged = false; |
| 644 | return ret; |
| 645 | } |
| 646 | |
| 647 | void XRState::update() |
| 648 | { |
| 649 | typedef UpResult (XRState::*UpHandler)(); |
| 650 | static UpHandler upStateHandlers[VRSTATE_MAX - 1] = { |
| 651 | &XRState::upInstance, |
| 652 | &XRState::upSystem, |
| 653 | &XRState::upSession, |
| 654 | &XRState::upActions, |
| 655 | }; |
| 656 | typedef DownResult (XRState::*DownHandler)(); |
| 657 | static DownHandler downStateHandlers[VRSTATE_MAX - 1] = { |
| 658 | &XRState::downInstance, |
| 659 | &XRState::downSystem, |
| 660 | &XRState::downSession, |
| 661 | &XRState::downActions, |
| 662 | }; |
| 663 | |
| 664 | bool wasThreading = _viewer.valid() && _viewer->areThreadsRunning(); |
| 665 | bool pollNeeded = true; |
| 666 | for (;;) |
| 667 | { |
| 668 | // Poll first |
| 669 | if (pollNeeded && _instance.valid() && _instance->valid()) |
| 670 | { |
| 671 | // Poll for events |
| 672 | _instance->pollEvents(this); |
| 673 | |
| 674 | // Sync actions |
| 675 | if (_session.valid()) |
| 676 | _session->syncActions(); |
| 677 | |
| 678 | // Check for session lost |
| 679 | if (_session.valid() && _session->isLost()) |
| 680 | setDownState(VRSTATE_INSTANCE); |
| 681 | |
| 682 | // Check for instance lost |
| 683 | if (_instance->lost()) |
| 684 | setDownState(VRSTATE_DISABLED); |
| 685 | |
| 686 | pollNeeded = false; |
| 687 | } |
| 688 | // Then down transitions |
| 689 | else if (_downState < _currentState) |
| 690 | { |
| 691 | DownResult res = (this->*downStateHandlers[_currentState-1])(); |
| 692 | if (res == DOWN_SUCCESS) |
| 693 | { |
| 694 | _currentState = (VRState)((int)_currentState - 1); |
| 695 | if (_currentState == _downState) |
| 696 | _downState = VRSTATE_MAX; |
| 697 | _stateChanged = true; |
| 698 | } |
| 699 | else // DOWN_SOON |
| 700 | { |
| 701 | break; |
| 702 | } |
| 703 | } |
| 704 | // Then up transitions |
| 705 | else if (_upState > _currentState) |
| 706 | { |
| 707 | if (_upDelay > 0) |
| 708 | { |
| 709 | // try again soon |
| 710 | --_upDelay; |
| 711 | break; |
| 712 | } |
| 713 | UpResult res = (this->*upStateHandlers[_currentState])(); |
| 714 | if (res == UP_SUCCESS) |
| 715 | { |
| 716 | if (_currentState <= _downState) |
| 717 | _downState = VRSTATE_MAX; |
| 718 | _currentState = (VRState)((int)_currentState + 1); |
| 719 | // Poll events again after bringing up session |
| 720 | if (_currentState >= VRSTATE_SESSION) |
| 721 | pollNeeded = true; |
| 722 | _stateChanged = true; |
| 723 | } |
| 724 | else if (res == UP_ABORT) |
| 725 | { |
| 726 | VRState probingState = getProbingState(); |
| 727 | if (probingState < _currentState) |
| 728 | // Drop down to probing state |
| 729 | setDestState(getProbingState()); |
| 730 | else |
| 731 | // Go up no further |
| 732 | _upState = _currentState; |
| 733 | _stateChanged = true; |
| 734 | } |
| 735 | else // UP_SOON or UP_LATER |
| 736 | { |
| 737 | if (res == UP_LATER) |
| 738 | { |
| 739 | // Don't poll incessantly |
| 740 | _upDelay = 500; |
| 741 | } |
| 742 | break; |
| 743 | } |
| 744 | } |
| 745 | else |
| 746 | { |
| 747 | _upDelay = 0; |
| 748 | break; |
| 749 | } |
| 750 | } |
| 751 | |
| 752 | // Restart threading in case we had to disable it to prevent the GL context |
| 753 | // being bound in another thread during certain OpenXR calls. |
| 754 | if (_viewer.valid() && wasThreading) |
| 755 | _viewer->startThreading(); |
| 756 | } |
| 757 | |
| 758 | void XRState::onInstanceLossPending(OpenXR::Instance *instance, |
| 759 | const XrEventDataInstanceLossPending *event) |
| 760 | { |
| 761 | // Reinitialize instance |
| 762 | setDownState(VRSTATE_DISABLED); |
| 763 | // FIXME use event.lossTime? |
| 764 | _upDelay = 500; |
| 765 | } |
| 766 | |
| 767 | void XRState::onInteractionProfileChanged(OpenXR::Session *session, |
| 768 | const XrEventDataInteractionProfileChanged *event) |
| 769 | { |
| 770 | // notify subactions so they can invalidate their cached current profile |
| 771 | for (auto &pair: _subactions) |
| 772 | { |
| 773 | auto subaction = pair.second.lock(); |
| 774 | if (subaction) |
| 775 | subaction->onInteractionProfileChanged(session); |
| 776 | } |
| 777 | } |
| 778 | |
| 779 | void XRState::onSessionStateChanged(OpenXR::Session *session, |
| 780 | const XrEventDataSessionStateChanged *event) |
| 781 | { |
| 782 | OpenXR::EventHandler::onSessionStateChanged(session, event); |
| 783 | _stateChanged = true; |
| 784 | } |
| 785 | |
| 786 | void XRState::onSessionStateStart(OpenXR::Session *session) |
| 787 | { |
| 788 | } |
| 789 | |
| 790 | void XRState::onSessionStateEnd(OpenXR::Session *session, bool retry) |
| 791 | { |
| 792 | if (!session->isExiting()) |
| 793 | { |
| 794 | // If the exit wasn't requested, drop back to a safe state |
| 795 | if (retry) |
| 796 | setDownState(VRSTATE_INSTANCE); |
| 797 | else |
| 798 | setDestState(getProbingState()); |
| 799 | } |
| 800 | } |
| 801 | |
| 802 | void XRState::onSessionStateReady(OpenXR::Session *session) |
| 803 | { |
| 804 | assert(session == _session); |
| 805 | if (!session->begin(*_chosenViewConfig)) |
| 806 | { |
| 807 | // This should normally have succeeded |
| 808 | setDestState(getProbingState()); |
| 809 | return; |
| 810 | } |
| 811 | |
| 812 | // Set up cameras |
| 813 | switch (_vrMode) |
| 814 | { |
| 815 | case VRMode::VRMODE_SLAVE_CAMERAS: |
| 816 | setupSlaveCameras(); |
| 817 | break; |
| 818 | |
| 819 | case VRMode::VRMODE_AUTOMATIC: |
| 820 | // Should already have been handled by upSession() |
| 821 | case VRMode::VRMODE_SCENE_VIEW: |
| 822 | setupSceneViewCameras(); |
| 823 | break; |
| 824 | } |
| 825 | |
| 826 | // Attach a callback to detect swap |
| 827 | osg::ref_ptr<osg::GraphicsContext> gc = _window.get(); |
| 828 | osg::ref_ptr<SwapCallback> swapCallback = new SwapCallback(this); |
| 829 | gc->setSwapCallback(swapCallback); |
| 830 | |
| 831 | // Finally set up any mirrors that may be queued in the manager |
| 832 | if (_manager.valid()) |
| 833 | { |
| 834 | // FIXME consider |
| 835 | _manager->_setupMirrors(); |
| 836 | _manager->onRunning(); |
| 837 | } |
| 838 | } |
| 839 | |
| 840 | void XRState::onSessionStateStopping(OpenXR::Session *session, bool loss) |
| 841 | { |
| 842 | // check no frame in progress |
| 843 | |
| 844 | // clean up appViews |
| 845 | for (auto appView: _appViews) |
| 846 | appView->destroy(); |
| 847 | _appViews.resize(0); |
| 848 | |
| 849 | osg::ref_ptr<osg::GraphicsContext> gc = _window.get(); |
| 850 | gc->setSwapCallback(nullptr); |
| 851 | |
| 852 | if (!loss) |
| 853 | session->end(); |
| 854 | |
| 855 | if (_manager.valid()) |
| 856 | _manager->onStopped(); |
| 857 | } |
| 858 | |
| 859 | void XRState::onSessionStateFocus(OpenXR::Session *session) |
| 860 | { |
| 861 | if (_manager.valid()) |
| 862 | _manager->onFocus(); |
| 863 | } |
| 864 | |
| 865 | void XRState::onSessionStateUnfocus(OpenXR::Session *session) |
| 866 | { |
| 867 | if (_manager.valid()) |
| 868 | _manager->onUnfocus(); |
| 869 | } |
| 870 | |
| 871 | void XRState::probe() const |
| 872 | { |
| 873 | _hasValidationLayer = OpenXR::Instance::hasLayer(XR_APILAYER_LUNARG_core_validation); |
| 874 | _hasDepthInfoExtension = OpenXR::Instance::hasExtension(XR_KHR_COMPOSITION_LAYER_DEPTH_EXTENSION_NAME); |
| 875 | _hasVisibilityMaskExtension = OpenXR::Instance::hasExtension(XR_KHR_VISIBILITY_MASK_EXTENSION_NAME); |
| 876 | |
| 877 | _probed = true; |
| 878 | } |
| 879 | |
| 880 | void XRState::unprobe() const |
| 881 | { |
| 882 | OpenXR::Instance::invalidateLayers(); |
| 883 | OpenXR::Instance::invalidateExtensions(); |
| 884 | |
| 885 | _probed = false; |
| 886 | } |
| 887 | |
| 888 | XRState::UpResult XRState::upInstance() |
| 889 | { |
| 890 | assert(!_instance.valid()); |
| 891 | |
| 892 | // Create OpenXR instance |
| 893 | |
| 894 | // Update needed settings that may have changed |
| 895 | _settingsCopy.setApp(_settings->getAppName(), _settings->getAppVersion()); |
| 896 | _settingsCopy.setValidationLayer(_settings->getValidationLayer()); |
| 897 | |
| 898 | _instance = new OpenXR::Instance(); |
| 899 | _instance->setValidationLayer(_settingsCopy.getValidationLayer()); |
| 900 | _instance->setDebugUtils(true); |
| 901 | _instance->setDepthInfo(true); |
| 902 | _instance->setVisibilityMask(true); |
| 903 | auto severity = //XR_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | |
| 904 | XR_DEBUG_UTILS_MESSAGE_SEVERITY_INFO_BIT_EXT | |
| 905 | XR_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | |
| 906 | XR_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; |
| 907 | auto types = XR_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | |
| 908 | XR_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | |
| 909 | XR_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT | |
| 910 | XR_DEBUG_UTILS_MESSAGE_TYPE_CONFORMANCE_BIT_EXT; |
| 911 | _instance->setDefaultDebugCallback(new DebugCallbackOsg(severity, types)); |
| 912 | switch (_instance->init(_settingsCopy.getAppName().c_str(), |
| 913 | _settingsCopy.getAppVersion())) |
| 914 | { |
| 915 | case OpenXR::Instance::INIT_SUCCESS: |
| 916 | break; |
| 917 | case OpenXR::Instance::INIT_LATER: |
| 918 | _instance->getError(_lastError); |
| 919 | _instance = nullptr; |
| 920 | return UP_LATER; |
| 921 | case OpenXR::Instance::INIT_FAIL: |
| 922 | _instance->getError(_lastError); |
| 923 | _instance = nullptr; |
| 924 | return UP_ABORT; |
| 925 | } |
| 926 | |
| 927 | return UP_SUCCESS; |
| 928 | } |
| 929 | |
| 930 | XRState::DownResult XRState::downInstance() |
| 931 | { |
| 932 | assert(_instance.valid()); |
| 933 | |
| 934 | // This should destroy actions and action sets |
| 935 | for (auto *profile: _interactionProfiles) |
| 936 | profile->cleanupInstance(); |
| 937 | for (auto *actionSet: _actionSets) |
| 938 | actionSet->cleanupInstance(); |
| 939 | |
| 940 | for (auto &pair: _subactions) |
| 941 | { |
| 942 | auto subaction = pair.second.lock(); |
| 943 | if (subaction) |
| 944 | subaction->cleanupInstance(); |
| 945 | } |
| 946 | |
| 947 | _instance->deinit(); |
| 948 | |
| 949 | if (_probed) |
| 950 | unprobe(); |
| 951 | |
| 952 | osg::observer_ptr<OpenXR::Instance> oldInstance = _instance; |
| 953 | _instance->getError(_lastRunError); |
| 954 | _lastError = {}; |
| 955 | _instance = nullptr; |
| 956 | assert(!oldInstance.valid()); |
| 957 | |
| 958 | return DOWN_SUCCESS; |
| 959 | } |
| 960 | |
| 961 | XRState::UpResult XRState::upSystem() |
| 962 | { |
| 963 | assert(!_system); |
| 964 | |
| 965 | // Update needed settings that may have changed |
| 966 | _settingsCopy.setFormFactor(_settings->getFormFactor()); |
| 967 | _settingsCopy.setPreferredEnvBlendModeMask(_settings->getPreferredEnvBlendModeMask()); |
| 968 | _settingsCopy.setAllowedEnvBlendModeMask(_settings->getAllowedEnvBlendModeMask()); |
| 969 | |
| 970 | // Get OpenXR system for chosen form factor |
| 971 | |
| 972 | switch (_settingsCopy.getFormFactor()) |
| 973 | { |
| 974 | case Settings::HEAD_MOUNTED_DISPLAY: |
| 975 | _formFactor = XR_FORM_FACTOR_HEAD_MOUNTED_DISPLAY; |
| 976 | break; |
| 977 | case Settings::HANDHELD_DISPLAY: |
| 978 | _formFactor = XR_FORM_FACTOR_HANDHELD_DISPLAY; |
| 979 | break; |
| 980 | } |
| 981 | bool supported; |
| 982 | _system = _instance->getSystem(_formFactor, &supported); |
| 983 | if (!_system) |
| 984 | return supported ? UP_LATER : UP_ABORT; |
| 985 | |
| 986 | // Choose the first supported view configuration |
| 987 | |
| 988 | for (const auto &viewConfig: _system->getViewConfigurations()) |
| 989 | { |
| 990 | switch (viewConfig.getType()) |
| 991 | { |
| 992 | case XR_VIEW_CONFIGURATION_TYPE_PRIMARY_MONO: |
| 993 | case XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO: |
| 994 | _chosenViewConfig = &viewConfig; |
| 995 | break; |
| 996 | default: |
| 997 | break; |
| 998 | } |
| 999 | if (_chosenViewConfig) |
| 1000 | break; |
| 1001 | } |
| 1002 | if (!_chosenViewConfig) |
| 1003 | { |
| 1004 | OSG_WARN << "osgXR: No supported view configuration" << std::endl; |
| 1005 | _system = nullptr; |
| 1006 | return UP_ABORT; |
| 1007 | } |
| 1008 | |
| 1009 | // Choose an environment blend mode |
| 1010 | |
| 1011 | for (XrEnvironmentBlendMode envBlendMode: _chosenViewConfig->getEnvBlendModes()) |
| 1012 | { |
| 1013 | if ((unsigned int)envBlendMode > 31) |
| 1014 | continue; |
| 1015 | uint32_t mask = (1u << (unsigned int)envBlendMode); |
| 1016 | if (_settingsCopy.getPreferredEnvBlendModeMask() & mask) |
| 1017 | { |
| 1018 | _chosenEnvBlendMode = envBlendMode; |
| 1019 | break; |
| 1020 | } |
| 1021 | if (_chosenEnvBlendMode != XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM && |
| 1022 | _settingsCopy.getAllowedEnvBlendModeMask() & mask) |
| 1023 | { |
| 1024 | _chosenEnvBlendMode = envBlendMode; |
| 1025 | } |
| 1026 | } |
| 1027 | if (_chosenEnvBlendMode == XR_ENVIRONMENT_BLEND_MODE_MAX_ENUM) |
| 1028 | { |
| 1029 | OSG_WARN << "osgXR: No supported environment blend mode" << std::endl; |
| 1030 | _system = nullptr; |
| 1031 | return UP_ABORT; |
| 1032 | } |
| 1033 | |
| 1034 | return UP_SUCCESS; |
| 1035 | } |
| 1036 | |
| 1037 | XRState::DownResult XRState::downSystem() |
| 1038 | { |
| 1039 | _system = nullptr; |
| 1040 | _instance->invalidateSystem(_formFactor); |
| 1041 | return DOWN_SUCCESS; |
| 1042 | } |
| 1043 | |
| 1044 | XRState::UpResult XRState::upSession() |
| 1045 | { |
| 1046 | assert(_system); |
| 1047 | assert(!_session.valid()); |
| 1048 | |
| 1049 | if (!_window.valid() || !_view.valid()) |
| 1050 | // Maybe window & view haven't been initialized yet |
| 1051 | return UP_SOON; |
| 1052 | |
| 1053 | // Update needed settings that may have changed |
| 1054 | _settingsCopy.setDepthInfo(_settings->getDepthInfo()); |
| 1055 | _settingsCopy.setVisibilityMask(_settings->getVisibilityMask()); |
| 1056 | _settingsCopy.setVRMode(_settings->getVRMode()); |
| 1057 | _settingsCopy.setSwapchainMode(_settings->getSwapchainMode()); |
| 1058 | _settingsCopy.setPreferredRGBEncodingMask(_settings->getPreferredRGBEncodingMask()); |
| 1059 | _settingsCopy.setAllowedRGBEncodingMask(_settings->getAllowedRGBEncodingMask()); |
| 1060 | _settingsCopy.setPreferredDepthEncodingMask(_settings->getPreferredDepthEncodingMask()); |
| 1061 | _settingsCopy.setAllowedDepthEncodingMask(_settings->getAllowedDepthEncodingMask()); |
| 1062 | _settingsCopy.setRGBBits(_settings->getRGBBits()); |
| 1063 | _settingsCopy.setAlphaBits(_settings->getAlphaBits()); |
| 1064 | _settingsCopy.setDepthBits(_settings->getDepthBits()); |
| 1065 | _settingsCopy.setStencilBits(_settings->getStencilBits()); |
| 1066 | _useDepthInfo = _settingsCopy.getDepthInfo(); |
| 1067 | _useVisibilityMask = _settingsCopy.getVisibilityMask(); |
| 1068 | _vrMode = _settingsCopy.getVRMode(); |
| 1069 | _swapchainMode = _settingsCopy.getSwapchainMode(); |
| 1070 | |
| 1071 | if (_useDepthInfo && !_instance->supportsCompositionLayerDepth()) |
| 1072 | { |
| 1073 | OSG_WARN << "osgXR: CompositionLayerDepth extension not supported, depth info will be disabled" << std::endl; |
| 1074 | _useDepthInfo = false; |
| 1075 | } |
| 1076 | if (_useVisibilityMask && !_instance->supportsVisibilityMask()) |
| 1077 | { |
| 1078 | OSG_WARN << "osgXR: VisibilityMask extension not supported, visibility masking will be disabled" << std::endl; |
| 1079 | _useVisibilityMask = false; |
| 1080 | } |
| 1081 | |
| 1082 | // Decide on the algorithm to use. SceneView mode is faster. |
| 1083 | if (_vrMode == VRMode::VRMODE_AUTOMATIC) |
| 1084 | _vrMode = VRMode::VRMODE_SCENE_VIEW; |
| 1085 | |
| 1086 | // SceneView mode only works with a stereo view config |
| 1087 | if (_vrMode == VRMode::VRMODE_SCENE_VIEW && |
| 1088 | _chosenViewConfig->getType() != XR_VIEW_CONFIGURATION_TYPE_PRIMARY_STEREO) |
| 1089 | { |
| 1090 | _vrMode = VRMode::VRMODE_SLAVE_CAMERAS; |
| 1091 | if (_settingsCopy.getVRMode() == VRMode::VRMODE_SCENE_VIEW) |
| 1092 | OSG_WARN << "osgXR: No stereo view config for VR mode SCENE_VIEW, falling back to SLAVE_CAMERAS" << std::endl; |
| 1093 | } |
| 1094 | |
| 1095 | // SceneView mode requires a single swapchain |
| 1096 | if (_vrMode == VRMode::VRMODE_SCENE_VIEW) |
| 1097 | { |
| 1098 | if (_swapchainMode != SwapchainMode::SWAPCHAIN_AUTOMATIC && |
| 1099 | _swapchainMode != SwapchainMode::SWAPCHAIN_SINGLE) |
| 1100 | { |
| 1101 | OSG_WARN << "osgXR: Overriding VR swapchain mode to SINGLE for VR mode SCENE_VIEW" << std::endl; |
| 1102 | } |
| 1103 | _swapchainMode = SwapchainMode::SWAPCHAIN_SINGLE; |
| 1104 | } |
| 1105 | |
| 1106 | // Decide on a swapchain mode to use |
| 1107 | if (_swapchainMode == SwapchainMode::SWAPCHAIN_AUTOMATIC) |
| 1108 | _swapchainMode = SwapchainMode::SWAPCHAIN_MULTIPLE; |
| 1109 | |
| 1110 | // Stop threading to prevent the GL context being bound in another thread |
| 1111 | // during certain OpenXR calls (session & swapchain handling). |
| 1112 | if (_viewer.valid()) |
| 1113 | _viewer->stopThreading(); |
| 1114 | |
| 1115 | // Create session using the GraphicsWindow |
| 1116 | _session = new OpenXR::Session(_system, _window.get()); |
| 1117 | if (!_session->valid()) |
| 1118 | { |
| 1119 | _session = nullptr; |
| 1120 | return UP_ABORT; |
| 1121 | } |
| 1122 | |
| 1123 | // Decide on ideal bit depths |
| 1124 | unsigned int bestRGBBits = 24; // combined |
| 1125 | unsigned int bestAlphaBits = 0; |
| 1126 | unsigned int bestDepthBits = 16; |
| 1127 | unsigned int bestStencilBits = 0; |
| 1128 | // Use graphics window traits |
| 1129 | auto *traits = _window->getTraits(); |
| 1130 | if (traits) |
| 1131 | { |
| 1132 | bestRGBBits = traits->red + traits->green + traits->blue; |
| 1133 | bestAlphaBits = traits->alpha; |
| 1134 | bestDepthBits = traits->depth; |
| 1135 | bestStencilBits = traits->stencil; |
| 1136 | } |
| 1137 | // Override from osgXR::Settings |
| 1138 | if (_settingsCopy.getRGBBits() >= 0) |
| 1139 | bestRGBBits = _settingsCopy.getRGBBits() * 3; |
| 1140 | if (_settingsCopy.getAlphaBits() >= 0) |
| 1141 | bestAlphaBits = _settingsCopy.getAlphaBits(); |
| 1142 | if (_settingsCopy.getDepthBits() >= 0) |
| 1143 | bestDepthBits = _settingsCopy.getDepthBits(); |
| 1144 | if (_settingsCopy.getStencilBits() >= 0) |
| 1145 | bestStencilBits = _settingsCopy.getStencilBits(); |
| 1146 | |
| 1147 | int64_t chosenRGBAFormat; |
| 1148 | int64_t chosenDepthFormat = 0; |
| 1149 | GLenum fallbackDepthFormat; |
| 1150 | |
| 1151 | // Choose OpenXR RGBA swapchain format |
| 1152 | chosenRGBAFormat = chooseRGBAFormat(bestRGBBits, |
| 1153 | bestAlphaBits, |
| 1154 | _settingsCopy.getPreferredRGBEncodingMask(), |
| 1155 | _settingsCopy.getAllowedRGBEncodingMask()); |
| 1156 | if (!chosenRGBAFormat) |
| 1157 | { |
| 1158 | std::stringstream formats; |
| 1159 | formats << std::hex; |
| 1160 | for (int64_t format: _session->getSwapchainFormats()) |
| 1161 | formats << " 0x" << format; |
| 1162 | OSG_WARN << "osgXR: No supported projection swapchain format found in [" |
| 1163 | << formats.str() << " ]" << std::endl; |
| 1164 | _session = nullptr; |
| 1165 | return UP_ABORT; |
| 1166 | } |
| 1167 | |
| 1168 | // Choose a fallback depth format in case we can't submit depth to OpenXR |
| 1169 | fallbackDepthFormat = chooseFallbackDepthFormat(bestDepthBits, |
| 1170 | bestStencilBits, |
| 1171 | _settingsCopy.getPreferredDepthEncodingMask(), |
| 1172 | _settingsCopy.getAllowedDepthEncodingMask()); |
| 1173 | |
| 1174 | // Choose OpenXR depth swapchain format |
| 1175 | if (_useDepthInfo) |
| 1176 | { |
| 1177 | chosenDepthFormat = chooseDepthFormat(bestDepthBits, |
| 1178 | bestStencilBits, |
| 1179 | _settingsCopy.getPreferredDepthEncodingMask(), |
| 1180 | _settingsCopy.getAllowedDepthEncodingMask()); |
| 1181 | if (!chosenDepthFormat) |
| 1182 | { |
| 1183 | std::stringstream formats; |
| 1184 | formats << std::hex; |
| 1185 | for (int64_t format: _session->getSwapchainFormats()) |
| 1186 | formats << " 0x" << format; |
| 1187 | OSG_WARN << "osgXR: No supported projection depth swapchain format found in [" |
| 1188 | << formats.str() << " ]" << std::endl; |
| 1189 | _useDepthInfo = false; |
| 1190 | } |
| 1191 | } |
| 1192 | |
| 1193 | // Set up swapchains & viewports |
| 1194 | switch (_swapchainMode) |
| 1195 | { |
| 1196 | case SwapchainMode::SWAPCHAIN_SINGLE: |
| 1197 | if (!setupSingleSwapchain(chosenRGBAFormat, |
| 1198 | chosenDepthFormat, |
| 1199 | fallbackDepthFormat)) |
| 1200 | { |
| 1201 | dropSessionCheck(); |
| 1202 | return UP_ABORT; |
| 1203 | } |
| 1204 | break; |
| 1205 | |
| 1206 | case SwapchainMode::SWAPCHAIN_AUTOMATIC: |
| 1207 | // Should already have been handled by upSession() |
| 1208 | case SwapchainMode::SWAPCHAIN_MULTIPLE: |
| 1209 | if (!setupMultipleSwapchains(chosenRGBAFormat, |
| 1210 | chosenDepthFormat, |
| 1211 | fallbackDepthFormat)) |
| 1212 | { |
| 1213 | dropSessionCheck(); |
| 1214 | return UP_ABORT; |
| 1215 | } |
| 1216 | break; |
| 1217 | } |
| 1218 | |
| 1219 | // Finally set up other composition layers |
| 1220 | // Ensure layers are sorted |
| 1221 | if (_compositionLayersUpdated) |
| 1222 | { |
| 1223 | _compositionLayersUpdated = false; |
| 1224 | _compositionLayers.sort(CompositionLayer::Private::compareOrder); |
| 1225 | } |
| 1226 | // Set up all layers |
| 1227 | for (auto *layer: _compositionLayers) |
| 1228 | layer->setup(_session); |
| 1229 | |
| 1230 | return UP_SUCCESS; |
| 1231 | } |
| 1232 | |
| 1233 | XRState::DownResult XRState::downSession() |
| 1234 | { |
| 1235 | assert(_session.valid()); |
| 1236 | |
| 1237 | if (_session->isLost()) |
| 1238 | { |
| 1239 | XrSessionState curState = _session->getState(); |
| 1240 | if (curState == XR_SESSION_STATE_FOCUSED) |
| 1241 | onSessionStateUnfocus(_session); |
| 1242 | if (_session->isRunning()) |
| 1243 | onSessionStateStopping(_session, true); |
| 1244 | // Attempt restart |
| 1245 | onSessionStateEnd(_session, true); |
| 1246 | } |
| 1247 | else if (_session->isRunning()) |
| 1248 | { |
| 1249 | if (!_session->isExiting()) |
| 1250 | _session->requestExit(); |
| 1251 | return DOWN_SOON; |
| 1252 | } |
| 1253 | |
| 1254 | // no frames should be in progress |
| 1255 | assert(!_frames.countFrames()); |
| 1256 | |
| 1257 | // Stop threading to prevent the GL context being bound in another thread |
| 1258 | // during certain OpenXR calls (session & swapchain destruction). |
| 1259 | if (_viewer.valid()) |
| 1260 | _viewer->stopThreading(); |
| 1261 | |
| 1262 | // Ensure the GL context is active for destruction of FBOs in XRFramebuffer |
| 1263 | _session->makeCurrent(); |
| 1264 | _xrViews.resize(0); |
| 1265 | _session->releaseContext(); |
| 1266 | |
| 1267 | // Clean compilation layers |
| 1268 | for (auto *layer: _compositionLayers) |
| 1269 | layer->cleanupSession(); |
| 1270 | |
| 1271 | // this will destroy the session |
| 1272 | for (auto *actionSet: _actionSets) |
| 1273 | actionSet->cleanupSession(); |
| 1274 | for (auto &pair: _subactions) |
| 1275 | { |
| 1276 | auto subaction = pair.second.lock(); |
| 1277 | if (subaction) |
| 1278 | subaction->cleanupSession(); |
| 1279 | } |
| 1280 | dropSessionCheck(); |
| 1281 | |
| 1282 | return DOWN_SUCCESS; |
| 1283 | } |
| 1284 | |
| 1285 | XRState::UpResult XRState::upActions() |
| 1286 | { |
| 1287 | // Wait until the app has set up action sets and interaction profiles |
| 1288 | if (_actionSets.empty() || _interactionProfiles.empty()) |
| 1289 | return UP_SOON; |
| 1290 | |
| 1291 | // Set up anything needed for interaction profiles |
| 1292 | for (auto *profile: _interactionProfiles) |
| 1293 | profile->setup(_instance); |
| 1294 | |
| 1295 | // Attach action sets to the session |
| 1296 | for (auto *actionSet: _actionSets) |
| 1297 | actionSet->setup(_session); |
| 1298 | if (_session->attachActionSets()) |
| 1299 | _actionsUpdated = false; |
| 1300 | // Treat attach fail as success, as VR can still continue without input |
| 1301 | return UP_SUCCESS; |
| 1302 | } |
| 1303 | |
| 1304 | XRState::DownResult XRState::downActions() |
| 1305 | { |
| 1306 | // Action setup cannot be undone |
| 1307 | return DOWN_SUCCESS; |
| 1308 | } |
| 1309 | |
| 1310 | bool XRState::dropSessionCheck() |
| 1311 | { |
| 1312 | osg::observer_ptr<OpenXR::Session> oldSession = _session; |
| 1313 | _session = nullptr; |
| 1314 | if (oldSession.valid()) { |
| 1315 | OSG_WARN << "osgXR: Session not cleaned up" << std::endl; |
| 1316 | return false; |
| 1317 | } |
| 1318 | return true; |
| 1319 | } |
| 1320 | |
| 1321 | static void applyDefaultRGBEncoding(uint32_t &preferredRGBEncodingMask, |
| 1322 | uint32_t &allowedRGBEncodingMask) |
| 1323 | { |
| 1324 | if (!allowedRGBEncodingMask) |
| 1325 | { |
| 1326 | // Play safe and default to preferring sRGB over linear/float RGB, since |
| 1327 | // this is what apps are normally tuned for. This avoids incorrect |
| 1328 | // behaviour in SteamVR (no gamma correction) and also correct but |
| 1329 | // potentially unexpected behaviour in Monado (extra gamma correction of |
| 1330 | // linear RGB framebuffer when app produces sRGBish images already). |
| 1331 | allowedRGBEncodingMask = 1u << Settings::ENCODING_SRGB; |
| 1332 | } |
| 1333 | if (!preferredRGBEncodingMask) |
| 1334 | { |
| 1335 | // If no preferred RGB encodings, mark all allowed ones as preferred. |
| 1336 | preferredRGBEncodingMask = allowedRGBEncodingMask; |
| 1337 | } |
| 1338 | } |
| 1339 | |
| 1340 | static void applyDefaultDepthEncoding(uint32_t &preferredDepthEncodingMask, |
| 1341 | uint32_t &allowedDepthEncodingMask) |
| 1342 | { |
| 1343 | if (!allowedDepthEncodingMask) |
| 1344 | { |
| 1345 | // Default to allowing both discrete or floating point depth. |
| 1346 | allowedDepthEncodingMask = 1u << Settings::ENCODING_LINEAR | |
| 1347 | 1u << Settings::ENCODING_FLOAT; |
| 1348 | } |
| 1349 | if (!preferredDepthEncodingMask) |
| 1350 | { |
| 1351 | // If no preferred depth encodings, mark all allowed ones as preferred. |
| 1352 | preferredDepthEncodingMask = allowedDepthEncodingMask; |
| 1353 | } |
| 1354 | } |
| 1355 | |
| 1356 | int64_t XRState::chooseRGBAFormat(unsigned int bestRGBBits, |
| 1357 | unsigned int bestAlphaBits, |
| 1358 | uint32_t preferredRGBEncodingMask, |
| 1359 | uint32_t allowedRGBEncodingMask) const |
| 1360 | { |
| 1361 | applyDefaultRGBEncoding(preferredRGBEncodingMask, |
| 1362 | allowedRGBEncodingMask); |
| 1363 | |
| 1364 | // Choose a swapchain format |
| 1365 | int64_t chosenRGBAFormat = 0; |
| 1366 | unsigned int chosenAlphaBits = 0; |
| 1367 | uint32_t chosenRGBSat = 0; |
| 1368 | for (int64_t format: _session->getSwapchainFormats()) |
| 1369 | { |
| 1370 | auto thisEncoding = Settings::ENCODING_LINEAR; |
| 1371 | uint32_t encodingMask = 0; |
| 1372 | unsigned int thisRGBBits = 0; |
| 1373 | unsigned int thisAlphaBits = 0; |
| 1374 | unsigned int thisSat = 0; |
| 1375 | switch (format) |
| 1376 | { |
| 1377 | // Discrete linear RGB(A) |
| 1378 | case GL_RGBA16: |
| 1379 | thisRGBBits = 16 * 3; |
| 1380 | thisAlphaBits = 16; |
| 1381 | goto handleRGBA; |
| 1382 | case GL_RGB10_A2: |
| 1383 | thisRGBBits = 10 * 3; |
| 1384 | thisAlphaBits = 2; |
| 1385 | goto handleRGBA; |
| 1386 | case GL_RGBA8: |
| 1387 | thisRGBBits = 8 * 3; |
| 1388 | thisAlphaBits = 8; |
| 1389 | goto handleRGBA; |
| 1390 | // Linear floating point RGB(A) |
| 1391 | case GL_RGB16F_ARB: |
| 1392 | thisRGBBits = 16 * 3; |
| 1393 | thisEncoding = Settings::ENCODING_FLOAT; |
| 1394 | goto handleRGBA; |
| 1395 | case GL_RGBA16F_ARB: |
| 1396 | thisRGBBits = 16 * 3; |
| 1397 | thisEncoding = Settings::ENCODING_FLOAT; |
| 1398 | thisAlphaBits = 16; |
| 1399 | goto handleRGBA; |
| 1400 | // Discrete sRGB (linear A) |
| 1401 | case GL_SRGB8_ALPHA8: |
| 1402 | thisEncoding = Settings::ENCODING_SRGB; |
| 1403 | thisAlphaBits = 8; |
| 1404 | goto handleRGBA; |
| 1405 | case GL_SRGB8: |
| 1406 | thisEncoding = Settings::ENCODING_SRGB; |
| 1407 | goto handleRGBA; |
| 1408 | handleRGBA: |
| 1409 | // Don't even consider a disallowed RGB encoding |
| 1410 | encodingMask = (1u << (unsigned int)thisEncoding); |
| 1411 | if (!(allowedRGBEncodingMask & encodingMask)) |
| 1412 | break; |
| 1413 | |
| 1414 | // Consider whether our preferences are satisfied |
| 1415 | if (preferredRGBEncodingMask & encodingMask) |
| 1416 | thisSat |= 0x1; |
| 1417 | if (thisEncoding == Settings::ENCODING_SRGB || thisRGBBits >= bestRGBBits) |
| 1418 | thisSat |= 0x2; |
| 1419 | if (thisAlphaBits >= bestAlphaBits) |
| 1420 | thisSat |= 0x4; |
| 1421 | |
| 1422 | // Skip formats that no longer satisfies some preference |
| 1423 | if (chosenRGBSat & ~thisSat) |
| 1424 | break; |
| 1425 | |
| 1426 | // Decide whether to choose this format |
| 1427 | if (// Anything is better than nothing |
| 1428 | !chosenRGBAFormat || |
| 1429 | // New preferences satisfied is always better |
| 1430 | (~chosenRGBSat & thisSat) || |
| 1431 | // All else being equal, allow improved alpha bits |
| 1432 | // A higher number of alpha bits is better than not enough |
| 1433 | (thisAlphaBits > chosenAlphaBits && chosenAlphaBits < bestAlphaBits)) |
| 1434 | { |
| 1435 | chosenRGBAFormat = format; |
| 1436 | chosenAlphaBits = thisAlphaBits; |
| 1437 | chosenRGBSat = thisSat; |
| 1438 | } |
| 1439 | break; |
| 1440 | |
| 1441 | default: |
| 1442 | break; |
| 1443 | } |
| 1444 | } |
| 1445 | return chosenRGBAFormat; |
| 1446 | } |
| 1447 | |
| 1448 | GLenum XRState::chooseFallbackDepthFormat(unsigned int bestDepthBits, |
| 1449 | unsigned int bestStencilBits, |
| 1450 | uint32_t preferredDepthEncodingMask, |
| 1451 | uint32_t allowedDepthEncodingMask) const |
| 1452 | { |
| 1453 | applyDefaultDepthEncoding(preferredDepthEncodingMask, |
| 1454 | allowedDepthEncodingMask); |
| 1455 | |
| 1456 | if (preferredDepthEncodingMask & (1u << (unsigned int)Settings::ENCODING_LINEAR)) |
| 1457 | { |
| 1458 | bool allowFloatDepth = allowedDepthEncodingMask & (1u << (unsigned int)Settings::ENCODING_FLOAT); |
| 1459 | if (bestDepthBits > 24 && allowFloatDepth) |
| 1460 | return bestStencilBits ? GL_DEPTH32F_STENCIL8 |
| 1461 | : GL_DEPTH_COMPONENT32F; |
| 1462 | else if (bestStencilBits) |
| 1463 | return GL_DEPTH24_STENCIL8_EXT; |
| 1464 | else if (bestDepthBits > 16) |
| 1465 | return GL_DEPTH_COMPONENT24; |
| 1466 | else |
| 1467 | return GL_DEPTH_COMPONENT16; |
| 1468 | } |
| 1469 | else // preferredDepthEncodingMask & (1 << ENCODING_FLOAT) |
| 1470 | { |
| 1471 | if (bestStencilBits) |
| 1472 | return GL_DEPTH32F_STENCIL8; |
| 1473 | else |
| 1474 | return GL_DEPTH_COMPONENT32F; |
| 1475 | } |
| 1476 | } |
| 1477 | |
| 1478 | int64_t XRState::chooseDepthFormat(unsigned int bestDepthBits, |
| 1479 | unsigned int bestStencilBits, |
| 1480 | uint32_t preferredDepthEncodingMask, |
| 1481 | uint32_t allowedDepthEncodingMask) const |
| 1482 | { |
| 1483 | applyDefaultDepthEncoding(preferredDepthEncodingMask, |
| 1484 | allowedDepthEncodingMask); |
| 1485 | |
| 1486 | // Choose a swapchain format |
| 1487 | int64_t chosenDepthFormat = 0; |
| 1488 | unsigned int chosenDepthBits = 0; |
| 1489 | unsigned int chosenStencilBits = 0; |
| 1490 | uint32_t chosenDepthSat = 0; |
| 1491 | for (int64_t format: _session->getSwapchainFormats()) |
| 1492 | { |
| 1493 | auto thisEncoding = Settings::ENCODING_LINEAR; |
| 1494 | uint32_t encodingMask = 0; |
| 1495 | unsigned int thisDepthBits = 0; |
| 1496 | unsigned int thisStencilBits = 0; |
| 1497 | unsigned int thisSat = 0; |
| 1498 | switch (format) |
| 1499 | { |
| 1500 | // Discrete depth (stencil) |
| 1501 | case GL_DEPTH_COMPONENT16: |
| 1502 | thisDepthBits = 16; |
| 1503 | goto handleDepth; |
| 1504 | case GL_DEPTH_COMPONENT24: |
| 1505 | thisDepthBits = 24; |
| 1506 | goto handleDepth; |
| 1507 | #if 0 // crashes nvidia (495.46, with monado) |
| 1508 | case GL_DEPTH24_STENCIL8_EXT: |
| 1509 | thisDepthBits = 24; |
| 1510 | thisStencilBits = 8; |
| 1511 | goto handleDepth; |
| 1512 | #endif |
| 1513 | case GL_DEPTH_COMPONENT32: |
| 1514 | thisDepthBits = 32; |
| 1515 | goto handleDepth; |
| 1516 | // Floating point depth, discrete stencil |
| 1517 | case GL_DEPTH_COMPONENT32F: |
| 1518 | thisEncoding = Settings::ENCODING_FLOAT; |
| 1519 | thisDepthBits = 32; |
| 1520 | goto handleDepth; |
| 1521 | case GL_DEPTH32F_STENCIL8: |
| 1522 | thisEncoding = Settings::ENCODING_FLOAT; |
| 1523 | thisDepthBits = 32; |
| 1524 | thisStencilBits = 8; |
| 1525 | goto handleDepth; |
| 1526 | |
| 1527 | handleDepth: |
| 1528 | // Don't even consider a disallowed depth encoding |
| 1529 | encodingMask = (1u << (unsigned int)thisEncoding); |
| 1530 | if (!(allowedDepthEncodingMask & encodingMask)) |
| 1531 | break; |
| 1532 | |
| 1533 | // Consider whether our preferences are satisfied |
| 1534 | if (preferredDepthEncodingMask & encodingMask) |
| 1535 | thisSat |= 0x1; |
| 1536 | if (thisDepthBits >= bestDepthBits) |
| 1537 | thisSat |= 0x2; |
| 1538 | if (thisStencilBits >= bestStencilBits) |
| 1539 | thisSat |= 0x4; |
| 1540 | |
| 1541 | // Skip formats that no longer satisfies some preference |
| 1542 | if (chosenDepthSat & ~thisSat) |
| 1543 | break; |
| 1544 | |
| 1545 | if (// Anything is better than nothing |
| 1546 | !chosenDepthFormat || |
| 1547 | // New preferences satisfied is always better |
| 1548 | (~chosenDepthSat & thisSat) || |
| 1549 | // A higher number of depth bits is better than not enough |
| 1550 | (thisDepthBits > chosenDepthBits && chosenDepthBits < bestDepthBits) || |
| 1551 | // A higher number of stencil bits is better than not enough |
| 1552 | // so long as depth bits are no worse or good enough |
| 1553 | ((thisDepthBits >= chosenDepthBits || thisDepthBits >= bestDepthBits) && |
| 1554 | thisStencilBits > chosenStencilBits && chosenStencilBits < bestStencilBits) || |
| 1555 | // A lower number of depth bits may still be enough |
| 1556 | // so long as stencil bits are no worse or good enough |
| 1557 | ((thisStencilBits >= chosenStencilBits || thisStencilBits >= bestStencilBits) && |
| 1558 | bestDepthBits < thisDepthBits && thisDepthBits < chosenDepthBits)) |
| 1559 | { |
| 1560 | chosenDepthFormat = format; |
| 1561 | chosenDepthBits = thisDepthBits; |
| 1562 | chosenStencilBits = thisStencilBits; |
| 1563 | chosenDepthSat = thisSat; |
| 1564 | } |
| 1565 | break; |
| 1566 | |
| 1567 | default: |
| 1568 | break; |
| 1569 | } |
| 1570 | } |
| 1571 | return chosenDepthFormat; |
| 1572 | } |
| 1573 | |
| 1574 | bool XRState::setupSingleSwapchain(int64_t format, int64_t depthFormat, |
| 1575 | GLenum fallbackDepthFormat) |
| 1576 | { |
| 1577 | const auto &views = _chosenViewConfig->getViews(); |
| 1578 | _xrViews.reserve(views.size()); |
| 1579 | |
| 1580 | // Arrange viewports on a single swapchain image |
| 1581 | OpenXR::System::ViewConfiguration::View singleView(0, 0); |
| 1582 | std::vector<OpenXR::System::ViewConfiguration::View::Viewport> viewports; |
| 1583 | viewports.resize(views.size()); |
| 1584 | for (uint32_t i = 0; i < views.size(); ++i) |
| 1585 | viewports[i] = singleView.tileHorizontally(views[i]); |
| 1586 | |
| 1587 | // Create a single swapchain |
| 1588 | osg::ref_ptr<XRSwapchain> xrSwapchain = new XRSwapchain(this, _session, |
| 1589 | singleView, format, |
| 1590 | depthFormat, |
| 1591 | fallbackDepthFormat); |
| 1592 | if (!xrSwapchain->valid()) { |
| 1593 | OSG_WARN << "osgXR: Invalid single swapchain" << std::endl; |
| 1594 | return false; // failure |
| 1595 | } |
| 1596 | |
| 1597 | // And the views |
| 1598 | _xrViews.reserve(views.size()); |
| 1599 | for (uint32_t i = 0; i < views.size(); ++i) |
| 1600 | { |
| 1601 | osg::ref_ptr<XRView> xrView = new XRView(this, i, xrSwapchain, |
| 1602 | viewports[i]); |
| 1603 | if (!xrView.valid()) |
| 1604 | { |
| 1605 | _xrViews.resize(0); |
| 1606 | return false; // failure |
| 1607 | } |
| 1608 | _xrViews.push_back(xrView); |
| 1609 | } |
| 1610 | |
| 1611 | return true; |
| 1612 | } |
| 1613 | |
| 1614 | bool XRState::setupMultipleSwapchains(int64_t format, int64_t depthFormat, |
| 1615 | GLenum fallbackDepthFormat) |
| 1616 | { |
| 1617 | const auto &views = _chosenViewConfig->getViews(); |
| 1618 | _xrViews.reserve(views.size()); |
| 1619 | |
| 1620 | for (uint32_t i = 0; i < views.size(); ++i) |
| 1621 | { |
| 1622 | const auto &vcView = views[i]; |
| 1623 | osg::ref_ptr<XRSwapchain> xrSwapchain = new XRSwapchain(this, _session, |
| 1624 | vcView, format, |
| 1625 | depthFormat, |
| 1626 | fallbackDepthFormat); |
| 1627 | if (!xrSwapchain->valid()) { |
| 1628 | OSG_WARN << "osgXR: Invalid swapchain for view " << i << std::endl; |
| 1629 | _xrViews.resize(0); |
| 1630 | return false; // failure |
| 1631 | } |
| 1632 | osg::ref_ptr<XRView> xrView = new XRView(this, i, xrSwapchain); |
| 1633 | if (!xrView.valid()) |
| 1634 | { |
| 1635 | _xrViews.resize(0); |
| 1636 | return false; // failure |
| 1637 | } |
| 1638 | _xrViews.push_back(xrView); |
| 1639 | } |
| 1640 | |
| 1641 | return true; |
| 1642 | } |
| 1643 | |
| 1644 | void XRState::setupSlaveCameras() |
| 1645 | { |
| 1646 | osg::ref_ptr<osg::GraphicsContext> gc = _window.get(); |
| 1647 | osg::Camera *camera = _view.valid() ? _view->getCamera() : nullptr; |
| 1648 | //camera->setName("Main"); |
| 1649 | |
| 1650 | _appViews.resize(_xrViews.size()); |
| 1651 | for (uint32_t i = 0; i < _xrViews.size(); ++i) |
| 1652 | { |
| 1653 | SlaveCamsAppView *appView = new SlaveCamsAppView(this, i, _window.get(), |
| 1654 | _view.get()); |
| 1655 | appView->init(); |
| 1656 | _appViews[i] = appView; |
| 1657 | |
| 1658 | if (camera && !_manager.valid()) |
| 1659 | { |
| 1660 | // The app isn't using a manager class, so create the new slave |
| 1661 | // camera ourselves |
| 1662 | osg::ref_ptr<osg::Camera> cam = new osg::Camera(); |
| 1663 | cam->setClearColor(camera->getClearColor()); |
| 1664 | cam->setClearMask(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); |
| 1665 | cam->setGraphicsContext(gc); |
| 1666 | |
| 1667 | // Add as a slave to the OSG view |
| 1668 | if (!_view->addSlave(cam.get(), osg::Matrix::identity(), |
| 1669 | osg::Matrix::identity(), true)) |
| 1670 | { |
| 1671 | OSG_WARN << "osgXR: Couldn't add slave camera" << std::endl; |
| 1672 | continue; |
| 1673 | } |
| 1674 | |
| 1675 | // And ensure it gets configured for VR |
| 1676 | appView->addSlave(cam.get()); |
| 1677 | } |
| 1678 | } |
| 1679 | |
| 1680 | if (camera && !_manager.valid()) |
| 1681 | { |
| 1682 | // Disable rendering of main camera since its being overwritten by the swap texture anyway |
| 1683 | camera->setGraphicsContext(nullptr); |
| 1684 | } |
| 1685 | } |
| 1686 | |
| 1687 | void XRState::setupSceneViewCameras() |
| 1688 | { |
| 1689 | _stereoDisplaySettings = new osg::DisplaySettings(*osg::DisplaySettings::instance().get()); |
| 1690 | _stereoDisplaySettings->setStereo(true); |
| 1691 | _stereoDisplaySettings->setStereoMode(osg::DisplaySettings::HORIZONTAL_SPLIT); |
| 1692 | _stereoDisplaySettings->setSplitStereoHorizontalEyeMapping(osg::DisplaySettings::LEFT_EYE_LEFT_VIEWPORT); |
| 1693 | _stereoDisplaySettings->setUseSceneViewForStereoHint(true); |
| 1694 | |
| 1695 | _appViews.resize(1); |
| 1696 | SceneViewAppView *appView = new SceneViewAppView(this, _window.get(), |
| 1697 | _view.get()); |
| 1698 | appView->init(); |
| 1699 | _appViews[0] = appView; |
| 1700 | |
| 1701 | if (_view.valid() && !_manager.valid()) |
| 1702 | { |
| 1703 | // If the main camera is for rendering, set up that |
| 1704 | osg::ref_ptr<osg::Camera> camera = _view->getCamera(); |
| 1705 | if (camera->getGraphicsContext() != nullptr) |
| 1706 | { |
| 1707 | _appViews[0]->addSlave(camera); |
| 1708 | } |
| 1709 | else |
| 1710 | { |
| 1711 | // Otherwise, we'll have to go and poke about in the slave cameras |
| 1712 | unsigned int numSlaves = _view->getNumSlaves(); |
| 1713 | for (unsigned int i = 0; i < numSlaves; ++i) |
| 1714 | { |
| 1715 | osg::ref_ptr<osg::Camera> slaveCam = _view->getSlave(i)._camera; |
| 1716 | if (slaveCam->getRenderTargetImplementation() == osg::Camera::FRAME_BUFFER) |
| 1717 | { |
| 1718 | OSG_WARN << "osgXR: slave " << slaveCam->getName() << std::endl; |
| 1719 | _appViews[0]->addSlave(slaveCam); |
| 1720 | } |
| 1721 | } |
| 1722 | |
| 1723 | if (!_xrViews[0]->getSwapchain()->getNumDrawPasses()) |
| 1724 | { |
| 1725 | OSG_WARN << "osgXR: Failed to find suitable slave camera" << std::endl; |
| 1726 | return; |
| 1727 | } |
| 1728 | } |
| 1729 | } |
| 1730 | } |
| 1731 | |
| 1732 | void XRState::setupSceneViewCamera(osg::Camera *camera) |
| 1733 | { |
| 1734 | camera->setRenderTargetImplementation(osg::Camera::FRAME_BUFFER_OBJECT); |
| 1735 | camera->setDrawBuffer(GL_COLOR_ATTACHMENT0_EXT); |
| 1736 | camera->setReadBuffer(GL_COLOR_ATTACHMENT0_EXT); |
| 1737 | |
| 1738 | // Here we avoid doing anything regarding OSG camera RTT attachment. |
| 1739 | // Ideally we would use automatic methods within OSG for handling RTT but in this |
| 1740 | // case it seemed simpler to handle FBO creation and selection within this class. |
| 1741 | |
| 1742 | // This initial draw callback is used to disable normal OSG camera setup which |
| 1743 | // would undo our RTT FBO configuration. |
| 1744 | camera->setInitialDrawCallback(new InitialDrawCallback(this)); |
| 1745 | |
| 1746 | camera->setPreDrawCallback(new PreDrawCallback(_xrViews[0]->getSwapchain())); |
| 1747 | camera->setFinalDrawCallback(new PostDrawCallback(_xrViews[0]->getSwapchain())); |
| 1748 | |
| 1749 | // Set the viewport (seems to need redoing!) |
| 1750 | camera->setViewport(0, 0, |
| 1751 | _xrViews[0]->getSwapchain()->getWidth(), |
| 1752 | _xrViews[0]->getSwapchain()->getHeight()); |
| 1753 | |
| 1754 | // Set the stereo matrices callback on each SceneView |
| 1755 | osgViewer::Renderer *renderer = static_cast<osgViewer::Renderer *>(camera->getRenderer()); |
| 1756 | for (unsigned int i = 0; i < 2; ++i) |
| 1757 | { |
| 1758 | osgUtil::SceneView *sceneView = renderer->getSceneView(i); |
| 1759 | sceneView->setComputeStereoMatricesCallback( |
| 1760 | new ComputeStereoMatricesCallback(this, sceneView)); |
| 1761 | } |
| 1762 | |
| 1763 | camera->setDisplaySettings(_stereoDisplaySettings); |
| 1764 | } |
| 1765 | |
| 1766 | void XRState::setupSceneViewVisibilityMasks(osg::Camera *camera, |
| 1767 | osg::ref_ptr<osg::MatrixTransform> &transform) |
| 1768 | { |
| 1769 | for (uint32_t i = 0; i < _xrViews.size(); ++i) |
| 1770 | { |
| 1771 | osg::ref_ptr<osg::Geode> geode = setupVisibilityMask(camera, i, transform); |
| 1772 | if (geode.valid()) |
| 1773 | { |
| 1774 | if (i == 0) |
| 1775 | geode->setNodeMask(_visibilityMaskLeft); |
| 1776 | else |
| 1777 | geode->setNodeMask(_visibilityMaskRight); |
| 1778 | } |
| 1779 | } |
| 1780 | } |
| 1781 | |
| 1782 | osg::ref_ptr<osg::Geode> XRState::setupVisibilityMask(osg::Camera *camera, uint32_t viewIndex, |
| 1783 | osg::ref_ptr<osg::MatrixTransform> &transform) |
| 1784 | { |
| 1785 | osg::ref_ptr<osg::Geometry> geometry; |
| 1786 | geometry = _session->getVisibilityMask(viewIndex, |
| 1787 | XR_VISIBILITY_MASK_TYPE_HIDDEN_TRIANGLE_MESH_KHR); |
| 1788 | if (!geometry.valid()) |
| 1789 | return nullptr; |
| 1790 | |
| 1791 | osg::ref_ptr<osg::Geode> geode = new osg::Geode; |
| 1792 | geode->setCullingActive(false); |
| 1793 | geode->addDrawable(geometry); |
| 1794 | |
| 1795 | osg::ref_ptr<osg::StateSet> state = geode->getOrCreateStateSet(); |
| 1796 | int forceOff = osg::StateAttribute::OFF | osg::StateAttribute::PROTECTED; |
| 1797 | state->setMode(GL_LIGHTING, forceOff); |
| 1798 | state->setAttribute(new osg::ColorMask(false, false, false, false), |
| 1799 | osg::StateAttribute::OVERRIDE); |
| 1800 | state->setAttribute(new osg::Depth(osg::Depth::ALWAYS, 0.0f, 0.0f, true), |
| 1801 | osg::StateAttribute::OVERRIDE); |
| 1802 | state->setRenderBinDetails(INT_MIN, "RenderBin"); |
| 1803 | |
| 1804 | if (!transform.valid()) |
| 1805 | { |
| 1806 | transform = new osg::MatrixTransform; |
| 1807 | transform->setReferenceFrame(osg::Camera::ABSOLUTE_RF); |
| 1808 | } |
| 1809 | transform->addChild(geode); |
| 1810 | |
| 1811 | camera->addChild(transform); |
| 1812 | |
| 1813 | return geode; |
| 1814 | } |
| 1815 | |
| 1816 | osg::ref_ptr<OpenXR::Session::Frame> XRState::getFrame(osg::FrameStamp *stamp) |
| 1817 | { |
| 1818 | // Fast path |
| 1819 | osg::ref_ptr<OpenXR::Session::Frame> frame = _frames.getFrame(stamp); |
| 1820 | if (frame.valid()) |
| 1821 | return frame; |
| 1822 | |
| 1823 | if (!_session->isRunning()) |
| 1824 | return nullptr; |
| 1825 | |
| 1826 | // Slow path |
| 1827 | return _frames.getFrame(stamp, _session); |
| 1828 | } |
| 1829 | |
| 1830 | void XRState::startRendering(osg::FrameStamp *stamp) |
| 1831 | { |
| 1832 | osg::ref_ptr<OpenXR::Session::Frame> frame = getFrame(stamp); |
| 1833 | if (frame.valid() && !frame->hasBegun()) |
| 1834 | { |
| 1835 | frame->begin(); |
| 1836 | _projectionLayer = new OpenXR::CompositionLayerProjection(_xrViews.size()); |
| 1837 | _projectionLayer->setLayerFlags(XR_COMPOSITION_LAYER_BLEND_TEXTURE_SOURCE_ALPHA_BIT); |
| 1838 | _projectionLayer->setSpace(_session->getLocalSpace()); |
| 1839 | } |
| 1840 | } |
| 1841 | |
| 1842 | void XRState::endFrame(osg::FrameStamp *stamp) |
| 1843 | { |
| 1844 | osg::ref_ptr<OpenXR::Session::Frame> frame = _frames.getFrame(stamp); |
| 1845 | if (!frame.valid()) |
| 1846 | { |
| 1847 | OSG_WARN << "osgXR: OpenXR frame not waited for" << std::endl; |
| 1848 | return; |
| 1849 | } |
| 1850 | if (!frame->hasBegun()) |
| 1851 | { |
| 1852 | OSG_WARN << "osgXR: OpenXR frame not begun" << std::endl; |
| 1853 | _frames.killFrame(stamp); |
| 1854 | return; |
| 1855 | } |
| 1856 | for (auto &view: _xrViews) |
| 1857 | view->endFrame(frame); |
| 1858 | frame->setEnvBlendMode(_chosenEnvBlendMode); |
| 1859 | for (auto *layer: _compositionLayers) |
| 1860 | { |
| 1861 | if (layer->getOrder() >= 0) |
| 1862 | break; |
| 1863 | if (layer->getVisible()) |
| 1864 | layer->endFrame(frame); |
| 1865 | } |
| 1866 | frame->addLayer(_projectionLayer.get()); |
| 1867 | for (auto *layer: _compositionLayers) |
| 1868 | if (layer->getOrder() >= 0 && layer->getVisible()) |
| 1869 | layer->endFrame(frame); |
| 1870 | _frames.endFrame(stamp); |
| 1871 | } |
| 1872 | |
| 1873 | void XRState::updateSlave(uint32_t viewIndex, osg::View& view, |
| 1874 | osg::View::Slave& slave) |
| 1875 | { |
| 1876 | bool setProjection = false; |
| 1877 | osg::Matrix projectionMatrix; |
| 1878 | |
| 1879 | osg::ref_ptr<OpenXR::Session::Frame> frame = getFrame(view.getFrameStamp()); |
| 1880 | if (frame.valid()) |
| 1881 | { |
| 1882 | if (frame->isPositionValid() && frame->isOrientationValid()) |
| 1883 | { |
| 1884 | const auto &pose = frame->getViewPose(viewIndex); |
| 1885 | osg::Vec3 position(pose.position.x, |
| 1886 | pose.position.y, |
| 1887 | pose.position.z); |
| 1888 | osg::Quat orientation(pose.orientation.x, |
| 1889 | pose.orientation.y, |
| 1890 | pose.orientation.z, |
| 1891 | pose.orientation.w); |
| 1892 | |
| 1893 | osg::Matrix viewOffset; |
| 1894 | viewOffset.setTrans(viewOffset.getTrans() + position * _settings->getUnitsPerMeter()); |
| 1895 | viewOffset.preMultRotate(orientation); |
| 1896 | viewOffset = osg::Matrix::inverse(viewOffset); |
| 1897 | slave._viewOffset = viewOffset; |
| 1898 | |
| 1899 | double left, right, bottom, top, zNear, zFar; |
| 1900 | if (view.getCamera()->getProjectionMatrixAsFrustum(left, right, |
| 1901 | bottom, top, |
| 1902 | zNear, zFar)) |
| 1903 | { |
| 1904 | const auto &fov = frame->getViewFov(viewIndex); |
| 1905 | createProjectionFov(projectionMatrix, fov, zNear, zFar); |
| 1906 | setProjection = true; |
| 1907 | } |
| 1908 | } |
| 1909 | } |
| 1910 | |
| 1911 | //slave._camera->setViewMatrix(view.getCamera()->getViewMatrix() * slave._viewOffset); |
| 1912 | slave.updateSlaveImplementation(view); |
| 1913 | if (setProjection) |
| 1914 | { |
| 1915 | slave._camera->setProjectionMatrix(projectionMatrix); |
| 1916 | } |
| 1917 | } |
| 1918 | |
| 1919 | void XRState::updateVisibilityMaskTransform(osg::Camera *camera, |
| 1920 | osg::MatrixTransform *transform) |
| 1921 | { |
| 1922 | float scale = 1.0f; |
| 1923 | double left, right, bottom, top, zNear, zFar; |
| 1924 | if (camera->getProjectionMatrixAsFrustum(left, right, |
| 1925 | bottom, top, |
| 1926 | zNear, zFar)) |
| 1927 | { |
| 1928 | if (isinf(zFar)) |
| 1929 | scale = zNear * 1.1; |
| 1930 | else |
| 1931 | scale = (zNear + zFar) / 2; |
| 1932 | } |
| 1933 | transform->setMatrix(osg::Matrix::translate(0, 0, -1)); |
| 1934 | transform->postMult(osg::Matrix::scale(scale, scale, scale)); |
| 1935 | } |
| 1936 | |
| 1937 | osg::Matrixd XRState::getEyeProjection(osg::FrameStamp *stamp, |
| 1938 | uint32_t viewIndex, |
| 1939 | const osg::Matrixd& projection) |
| 1940 | { |
| 1941 | osg::ref_ptr<OpenXR::Session::Frame> frame = getFrame(stamp); |
| 1942 | if (frame.valid()) |
| 1943 | { |
| 1944 | double left, right, bottom, top, zNear, zFar; |
| 1945 | if (projection.getFrustum(left, right, |
| 1946 | bottom, top, |
| 1947 | zNear, zFar)) |
| 1948 | { |
| 1949 | const auto &fov = frame->getViewFov(viewIndex); |
| 1950 | osg::Matrix projectionMatrix; |
| 1951 | createProjectionFov(projectionMatrix, fov, zNear, zFar); |
| 1952 | return projectionMatrix; |
| 1953 | } |
| 1954 | } |
| 1955 | return projection; |
| 1956 | } |
| 1957 | |
| 1958 | osg::Matrixd XRState::getEyeView(osg::FrameStamp *stamp, uint32_t viewIndex, |
| 1959 | const osg::Matrixd& view) |
| 1960 | { |
| 1961 | osg::ref_ptr<OpenXR::Session::Frame> frame = getFrame(stamp); |
| 1962 | if (frame.valid()) |
| 1963 | { |
| 1964 | if (frame->isPositionValid() && frame->isOrientationValid()) |
| 1965 | { |
| 1966 | const auto &pose = frame->getViewPose(viewIndex); |
| 1967 | osg::Vec3 position(pose.position.x, |
| 1968 | pose.position.y, |
| 1969 | pose.position.z); |
| 1970 | osg::Quat orientation(pose.orientation.x, |
| 1971 | pose.orientation.y, |
| 1972 | pose.orientation.z, |
| 1973 | pose.orientation.w); |
| 1974 | |
| 1975 | osg::Matrix viewOffset; |
| 1976 | viewOffset.setTrans(viewOffset.getTrans() + position * _settings->getUnitsPerMeter()); |
| 1977 | viewOffset.preMultRotate(orientation); |
| 1978 | viewOffset = osg::Matrix::inverse(viewOffset); |
| 1979 | return view * viewOffset; |
| 1980 | } |
| 1981 | } |
| 1982 | return view; |
| 1983 | } |
| 1984 | |
| 1985 | void XRState::initialDrawCallback(osg::RenderInfo &renderInfo) |
| 1986 | { |
| 1987 | osg::GraphicsOperation *graphicsOperation = renderInfo.getCurrentCamera()->getRenderer(); |
| 1988 | osgViewer::Renderer *renderer = dynamic_cast<osgViewer::Renderer*>(graphicsOperation); |
| 1989 | if (renderer != nullptr) |
| 1990 | { |
| 1991 | // Disable normal OSG FBO camera setup because it will undo the MSAA FBO configuration. |
| 1992 | renderer->setCameraRequiresSetUp(false); |
| 1993 | } |
| 1994 | |
| 1995 | startRendering(renderInfo.getState()->getFrameStamp()); |
| 1996 | |
| 1997 | // Get up to date depth info from camera's projection matrix |
| 1998 | _depthInfo.setZRangeFromProjection(renderInfo.getCurrentCamera()->getProjectionMatrix()); |
| 1999 | } |
| 2000 | |
| 2001 | void XRState::releaseGLObjects(osg::State *state) |
| 2002 | { |
| 2003 | // Release GL objects managed by the OpenXR session before the GL context is |
| 2004 | // destroyed |
| 2005 | if (_currentState >= VRSTATE_SESSION) |
| 2006 | _session->releaseGLObjects(state); |
| 2007 | } |
| 2008 | |
| 2009 | void XRState::swapBuffersImplementation(osg::GraphicsContext* gc) |
| 2010 | { |
| 2011 | // Submit rendered frame to compositor |
| 2012 | //m_device->submitFrame(); |
| 2013 | |
| 2014 | endFrame(gc->getState()->getFrameStamp()); |
| 2015 | |
| 2016 | // Blit mirror texture to backbuffer |
| 2017 | //m_device->blitMirrorTexture(gc); |
| 2018 | |
| 2019 | // Run the default system swapBufferImplementation |
| 2020 | gc->swapBuffersImplementation(); |
| 2021 | } |