From b1286517c6430072b43d654f3cdbe78a8ea65c3f Mon Sep 17 00:00:00 2001
From: Anthony Thibault <tony@highfidelity.com>
Date: Mon, 21 Mar 2016 21:51:16 -0700
Subject: [PATCH] Removed frame latency in GLEscrow

This could occur if the GLEscrow queue has extra frames in it.
When new textures were fetched, before this fix, they were simply popped from the queue.
This commit introduces a loop, that will fetch from the queue until it is empty.
---
 libraries/gl/src/gl/GLEscrow.h             | 8 +++++---
 plugins/openvr/src/OpenVrDisplayPlugin.cpp | 6 +++---
 2 files changed, 8 insertions(+), 6 deletions(-)

diff --git a/libraries/gl/src/gl/GLEscrow.h b/libraries/gl/src/gl/GLEscrow.h
index 357398c79b..d4772c85e9 100644
--- a/libraries/gl/src/gl/GLEscrow.h
+++ b/libraries/gl/src/gl/GLEscrow.h
@@ -203,13 +203,15 @@ public:
     // Also releases any previous texture held by the caller
     bool fetchSignaledAndRelease(T& value) {
         T originalValue = value;
-        if (fetchSignaled(value)) {
+        bool fetched = false;
+        while (fetchSignaled(value)) {
+            fetched = true;
             if (originalValue != invalid()) {
                 release(originalValue);
             }
-            return true;
+            originalValue = value;
         }
-        return false;
+        return fetched;
     }
 
     bool fetchAndReleaseWithFence(T& value, GLsync& sync) {
diff --git a/plugins/openvr/src/OpenVrDisplayPlugin.cpp b/plugins/openvr/src/OpenVrDisplayPlugin.cpp
index e123512cf9..1b87225388 100644
--- a/plugins/openvr/src/OpenVrDisplayPlugin.cpp
+++ b/plugins/openvr/src/OpenVrDisplayPlugin.cpp
@@ -119,14 +119,14 @@ void OpenVrDisplayPlugin::updateHeadPose(uint32_t frameIndex) {
     float vsyncToPhotons = _system->GetFloatTrackedDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SecondsFromVsyncToPhotons_Float);
 
 #if THREADED_PRESENT
-    // TODO: this seems awfuly long, 44ms total, but it produced the best results.
-    const float NUM_PREDICTION_FRAMES = 3.0f;
+    // 2 frames of prediction + vsyncToPhotons = 33ms total
+    const float NUM_PREDICTION_FRAMES = 2.0f;
     float predictedSecondsFromNow = NUM_PREDICTION_FRAMES * frameDuration + vsyncToPhotons;
 #else
     uint64_t frameCounter;
     float timeSinceLastVsync;
     _system->GetTimeSinceLastVsync(&timeSinceLastVsync, &frameCounter);
-    float predictedSecondsFromNow = 3.0f * frameDuration - timeSinceLastVsync + vsyncToPhotons;
+    float predictedSecondsFromNow = 2.0f * frameDuration - timeSinceLastVsync + vsyncToPhotons;
 #endif
 
     vr::TrackedDevicePose_t predictedTrackedDevicePose[vr::k_unMaxTrackedDeviceCount];