Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions DrvOpenXR/DrvOpenXR.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,11 @@ XrResult DrvOpenXR::SetupSession()
return XR_SUCCESS;
}

XrResult DrvOpenXR::FindSystem()
{
return CreateSystemID();
}

void DrvOpenXR::KeepOverlaysInstance()
{
if (currentBackend)
Expand Down
287 changes: 248 additions & 39 deletions DrvOpenXR/XrBackend.cpp

Large diffs are not rendered by default.

81 changes: 78 additions & 3 deletions DrvOpenXR/XrBackend.h
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ class XrBackend : public IBackend {
std::atomic<bool> sessionActive{ false };
std::atomic<bool> sessionLost{ false };
std::atomic<bool> exitExpected{ false };
// The user quit from the runtime: no session is made again
std::atomic<bool> quitting{ false };
// The session went through STOPPING since it last ran (an EXITING after it is the user quitting)
std::atomic<bool> sawStopping{ false };
// The game has been told the devices are deactivated (a loss), and not yet that they're back
std::atomic<bool> devicesDeactivated{ false };
// The last try to find the system again (RecoverLostSession), and whether the lost session is destroyed yet
std::atomic<std::chrono::steady_clock::rep> lastRecoveryTry{ 0 }; // 0 before the first
bool lostSessionDestroyed = false;
std::mutex recoveryLock;
// What the game has been told of the session, as SteamVR tells it: whether it lost input focus (sessionEvents), and
// the IPD (NaN until the session's first)
std::atomic<bool> inputFocusLost{ false };
Expand All @@ -89,15 +99,76 @@ class XrBackend : public IBackend {
// DrvOpenXR::KeepOverlaysInstance
void KeepOverlaysInstance();

/** Why the session is made again (RebuildSession) */
enum class RebuildReason {
AppGraphics, // the game's first Submit: from the temporary device to the game's own
Inputs, // the game's actions, which can only be attached to a session that has none yet
Loss, // the runtime lost the session (or one couldn't be made): a new one once the system is back
};
static const char* RebuildReasonName(RebuildReason reason);

/**
* Makes the session again, under the session lock: never in the middle of a frame (a frame the game has open is
* ended first, as if it had submitted). What the game set on the old session is put back on the new one: its eye
* compositors are made again at its next Submit, the skybox is shown again from the game's texture, and the overlays'
* swapchains are made again from their textures. XR_SUCCESS, or what xrCreateSession answered.
*/
XrResult RebuildSession(RebuildReason reason);

/**
* The session is gone or going (LOSS_PENDING, an EXITING OpenComposite didn't ask for, or a session restart
* that failed): VREvent_Quit is queued once, and no more frames are begun. There's no reconnecting.
* The session is lost (LOSS_PENDING, XR_ERROR_SESSION_LOST, an EXITING the user didn't ask for, or a session that
* couldn't be made): no more frames; the headset and controllers are deactivated, their poses invalid, until
* RecoverLostSession makes a new session. The game isn't told to quit.
*/
void OnSessionLost();
/** Pumps events until done() is true, for at most timeoutMs: whether it was */
bool WaitForEvents(const std::function<bool()>& done, int timeoutMs);
/** The runtime ends the session on its own: VREvent_DriverRequestedQuit, then OnSessionLost */
/**
* The user quit from the runtime (EXITING after STOPPING): VREvent_DriverRequestedQuit and VREvent_Quit, once, and
* no session is made again
*/
void OnRuntimeQuit();
/**
* Whether the game's actions (its manifest's, or legacy input's) and the info set may be attached now: once the
* session is on the game's device (or will stay where it is: a helper program's, or a game whose device can't be
* used). Before that the session restart for its first Submit would follow, and one more for a manifest it loads by
* then. A game that hasn't submitted within kInputsWithoutSubmit of first being asked about gets them all the same.
*/
static bool InputsMayAttach();
static constexpr std::chrono::seconds kInputsWithoutSubmit{ 2 };

/** Whether the current backend's session is gone (lost, or not made again yet): the devices have no poses */
static bool CurrentSessionGone();
/** Whether the current backend's session is lost and is to be made again (not the user quitting) */
static bool CurrentSessionLost();
/** Whether the user quit from the runtime (OnRuntimeQuit): the session isn't made again */
bool IsQuitting() const { return quitting; }

/** What an unasked session state change means for the game */
enum class StateOutcome {
Ignored,
Lost,
Quit,
};
/**
* For a state the session went to: LOSS_PENDING is a loss; EXITING is the user quitting if the session went
* through STOPPING since it last ran (sawStopping), a loss otherwise; neither while OpenLamina ends the session
* itself (exitExpected)
*/
static StateOutcome OutcomeOfState(XrSessionState state, bool sawStopping, bool exitExpected);

/** The wait between tries to find the system again after a loss */
static constexpr std::chrono::milliseconds kRecoveryInterval{ 1000 };
/** Whether a try is due at now: the first at once, then one each kRecoveryInterval (lastTry is {} before the first) */
static bool RecoveryDue(std::chrono::steady_clock::time_point lastTry, std::chrono::steady_clock::time_point now);

/**
* After a loss, on a thread that holds no session lock and no frame: destroys the lost session (once), then about
* once a second asks for the system (xrGetSystem) and, once it's there, makes the session again (RebuildSession);
* the devices are activated again. Retried for as long as it takes; nothing after the user quit. passLock is the
* helper loop's pass lock, taken after the session lock.
*/
void RecoverLostSession(std::mutex* passLock = nullptr);
bool IsSessionLost() const { return sessionLost; }
/** The session is lost, not running, or stopping, exiting or about to be lost: nothing can be shown in it any more */
bool IsSessionEnded() const
Expand Down Expand Up @@ -269,6 +340,8 @@ class XrBackend : public IBackend {
// A skybox asked for while the session wasn't running, shown at the next frame's start; under pendingSkyboxLock
std::mutex pendingSkyboxLock;
SkyboxRequest pendingSkybox;
// The skybox shown until ClearSkyboxOverride, shown again on a new session (RebuildSession); under pendingSkyboxLock
SkyboxRequest shownSkybox;
bool EquirectSkyboxAvailable() const;
// The session lock held (shared) and the session running
IBackend::openvr_enum_t ShowSkybox(const vr::Texture_t* textures, uint32_t count);
Expand Down Expand Up @@ -306,6 +379,8 @@ class XrBackend : public IBackend {

// Whether we've restarted the session to use the application's rendering API yet
std::atomic<bool> usingApplicationGraphicsAPI{ false };
// When InputsMayAttach was first asked before a Submit (steady_clock ticks; 0 before)
std::atomic<std::chrono::steady_clock::rep> inputsFirstAsked{ 0 };
// An overlay application's textures, copied onto its session's device
std::unique_ptr<class OverlayTextureCopy> overlayCopy;

Expand Down
8 changes: 8 additions & 0 deletions DrvOpenXR/XrController.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "XrController.h"
#include "XrBackend.h"

#include "../OpenOVR/Misc/LibMonado.h"

Expand Down Expand Up @@ -146,6 +147,13 @@ void XrController::GetPose(vr::ETrackingUniverseOrigin origin, vr::TrackedDevice
pose->bPoseIsValid = false;
pose->eTrackingResult = vr::TrackingResult_Running_OutOfRange;

// No session (it was lost): deactivated until it's made again
if (XrBackend::CurrentSessionGone()) {
pose->bDeviceIsConnected = false;
pose->eTrackingResult = vr::TrackingResult_Uninitialized;
return;
}

BaseInput* input = GetUnsafeBaseInput();
if (input == nullptr)
return;
Expand Down
2 changes: 2 additions & 0 deletions DrvOpenXR/XrDriverPrivate.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,7 @@ namespace DrvOpenXR {
// XR_SUCCESS, or what xrCreateSession answered (no session then: the caller decides what next)
XrResult SetupSession();
void ShutdownSession();
// xrGetSystem for the headset again (after a loss): XR_SUCCESS once it is there
XrResult FindSystem();
void FullShutdown();
} // namespace DrvOpenXR
8 changes: 6 additions & 2 deletions DrvOpenXR/XrHMD.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,7 @@ void XrHMD::GetPose(vr::ETrackingUniverseOrigin origin, vr::TrackedDevicePose_t*
{
// Held to the end: a session restart on another thread replaces xr_gbl and its spaces, and waits for this to end
auto lock = xr_session.lock_shared();
if (!xr_gbl) {
if (XrBackend::CurrentSessionGone()) {
// No session (it was lost, or a restart failed): no pose
if (pose) {
*pose = {};
Expand Down Expand Up @@ -427,7 +427,11 @@ static const float kDefaultIpd = 0.064f;

float XrHMD::GetIPD()
{
if (!xr_gbl)
const bool haveSession = [] {
auto lock = xr_session.lock_shared(); // held while reading: a session restart waits for it
return xr_gbl != nullptr;
}();
if (!haveSession)
return kDefaultIpd + IpdOffset();

static float ipd = kDefaultIpd;
Expand Down
17 changes: 17 additions & 0 deletions OpenOVR/Misc/xrutil.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,11 @@ SessionLock SessionWrapper::try_lock_shared()
return SessionLock(*this, SessionLock::TryShared{});
}

SessionLock SessionWrapper::try_lock()
{
return SessionLock(*this, SessionLock::TryExclusive{});
}

void SessionWrapper::reset()
{
session = XR_NULL_HANDLE;
Expand Down Expand Up @@ -513,6 +518,18 @@ SessionLock::SessionLock(SessionWrapper& p, TryShared)
owner = true;
}

SessionLock::SessionLock(SessionWrapper& p, TryExclusive)
: parent(p)
{
if (thread_lock != Held::Unlocked)
return; // this thread holds it already
if (!p.mutex.try_lock())
return;
lock = std::unique_lock(p.mutex, std::adopt_lock);
thread_lock = Held::Exclusive;
owner = true;
}

SessionLock::~SessionLock()
{
if (upgraded) {
Expand Down
7 changes: 7 additions & 0 deletions OpenOVR/Misc/xrutil.h
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,11 @@ class SessionWrapper {
*/
[[nodiscard]] SessionLock try_lock_shared();

/*
* The exclusive lock if it's free now, without waiting (see SessionLock::IsHeld)
*/
[[nodiscard]] SessionLock try_lock();

/*
* Resets the underlying XrSession to XR_NULL_HANDLE. Does not actually call xrDestroySession.
*/
Expand All @@ -183,10 +188,12 @@ class SessionLock {

public:
struct TryShared {};
struct TryExclusive {};

SessionLock(SessionWrapper& p, bool exclusive);
SessionLock(SessionWrapper& p, std::chrono::milliseconds limit);
SessionLock(SessionWrapper& p, TryShared);
SessionLock(SessionWrapper& p, TryExclusive);
~SessionLock();
operator XrSession&();
// Whether this thread holds the lock, through this SessionLock or an outer one
Expand Down
9 changes: 9 additions & 0 deletions OpenOVR/Reimpl/BaseInput.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,12 @@ void BaseInput::LoadEmptyManifestIfRequired()
{
if (hasLoadedActions)
return;
// Asked for, legacy input comes in place of the info set (which would cost a session restart)
legacyInputAsked = true;
// Not before the game's first frame on its own device: the session restart for it would come anyway, and a
// manifest the game loads by then would need another
if (!XrBackend::InputsMayAttach())
return;

// As in SetActionManifestPath, exclusive to the end; another thread may have loaded the actions while this waited
auto sessionLock = xr_session.lock();
Expand Down Expand Up @@ -845,6 +851,9 @@ void BaseInput::BindInputsForSession()
// If we didn't request the restart but we also haven't even loaded actions yet, there's nothing to bind yet.
if (restartingSession || !hasLoadedActions)
return;
// No session to bind to (a lost one was destroyed): the one made again binds them
if (!xr_gbl || !xr_session.get())
return;

// Since the session has changed, any actionspaces we previously created are now invalid
for (const std::unique_ptr<Action>& action : actions.GetItems()) {
Expand Down
4 changes: 4 additions & 0 deletions OpenOVR/Reimpl/BaseInput.h
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,9 @@ class BaseInput {
void GetHandSpace(ITrackedDevice::TrackedDeviceType hand, XrSpace& space, bool aimPose);

bool AreActionsLoaded();
// The game asked for legacy input: it's loaded (at once, or at its next call once it may be attached), with no info
// set before it
bool LegacyInputAsked() const { return legacyInputAsked; }

/** One hand's laser for pointing at overlays (LaserMouse) */
struct HandPointer {
Expand Down Expand Up @@ -871,6 +874,7 @@ class BaseInput {

// Set under the exclusive session lock; read without it on the way in to LoadEmptyManifestIfRequired
std::atomic<bool> hasLoadedActions = false;
std::atomic<bool> legacyInputAsked = false;
std::string loadedActionsPath;
std::mutex loadedActionsPathLock; // read before the session lock, to answer a repeated manifest at once
bool usingLegacyInput = false;
Expand Down
12 changes: 12 additions & 0 deletions OpenOVR/Reimpl/BaseOverlay.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1869,6 +1869,18 @@ bool BaseOverlay::_AnyVisible()
return false;
}

void BaseOverlay::_OnSessionRebuilt()
{
std::lock_guard<std::recursive_mutex> lock(layersLock);
for (const auto& kv : overlays) {
OverlayData* overlay = kv.second;
// An image from memory finds its own swapchain gone (its upload is made again); a texture's compositor went
// with the session, and the layer mustn't name its swapchain any more
if (overlay && overlay->rawImage.Empty() && !overlay->compositor.lock())
overlay->compositionLayer.quad.subImage = XrSwapchainSubImage{};
}
}

int BaseOverlay::_BuildLayers(XrCompositionLayerBaseHeader* sceneLayer, XrCompositionLayerBaseHeader const* const*& layers, bool mayUpload)
{
// Note that at least on MSVC, this shouldn't be doing any memory allocations
Expand Down
4 changes: 4 additions & 0 deletions OpenOVR/Reimpl/BaseOverlay.h
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,10 @@ class BaseOverlay {
// Whether the handle is one of this program's overlays
bool _IsOwnOverlay(vr::VROverlayHandle_t handle);

// A new session (XrBackend::RebuildSession): the overlays' texture swapchains went with the old one, and are made
// again from their textures as they're next shown
void _OnSessionRebuilt();

// Whether the keyboard is shown
bool _KeyboardShown()
{
Expand Down
10 changes: 8 additions & 2 deletions OpenOVR/Reimpl/BaseSystem.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,8 @@ ETrackedDeviceClass BaseSystem::GetTrackedDeviceClass(vr::TrackedDeviceIndex_t d

bool BaseSystem::IsTrackedDeviceConnected(vr::TrackedDeviceIndex_t deviceIndex)
{
return BackendManager::Instance().GetDevice(deviceIndex) != nullptr;
// None while the session is lost: the devices are deactivated until it's made again
return BackendManager::Instance().GetDevice(deviceIndex) != nullptr && !XrBackend::CurrentSessionLost();
}

bool BaseSystem::GetBoolTrackedDeviceProperty(vr::TrackedDeviceIndex_t unDeviceIndex, ETrackedDeviceProperty prop, ETrackedPropertyError* pErrorL)
Expand Down Expand Up @@ -843,7 +844,11 @@ bool BaseSystem::GetControllerState(vr::TrackedDeviceIndex_t controllerDeviceInd
memset(controllerState, 0, controllerStateSize);

// The headset's proximity sensor, while the runtime says whether the user wears it
if (controllerDeviceIndex == k_unTrackedDeviceIndex_Hmd && xr_gbl && xr_gbl->supportsUserPresence) {
const bool userPresence = [] {
auto lock = xr_session.lock_shared(); // held while reading: a session restart waits for it
return xr_gbl && xr_gbl->supportsUserPresence;
}();
if (controllerDeviceIndex == k_unTrackedDeviceIndex_Hmd && userPresence) {
std::shared_ptr<ITrackedDevice> hmd = BackendManager::Instance().GetDevice(k_unTrackedDeviceIndex_Hmd);
return hmd && hmd->GetControllerState(controllerState);
}
Expand Down Expand Up @@ -1240,6 +1245,7 @@ static bool GazeInHead(glm::quat* gazeInHead)
// session locked (shared).
static glm::quat EyeInHead(EVREye eye)
{
auto lock = xr_session.lock_shared(); // held while reading: a session restart waits for it
if (!xr_gbl)
return glm::identity<glm::quat>();
XruCachedViews cached = xr_gbl->GetCachedViews(xr_gbl->viewSpace);
Expand Down
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ add_executable(oc_unit_tests
unit/KeyboardTests.cpp
unit/RenderModelTests.cpp
unit/HmdTests.cpp
unit/SessionLifecycleTests.cpp
unit/DeviceSlotsTests.cpp
unit/EntryPointsTests.cpp
unit/BaseMailboxTests.cpp
Expand Down
Loading
Loading