History

Merge branch 'master' of github.com:highfidelity/hifi into fix-stanard-library-include-some-more

Seth Alves committed 10 years ago

Commit 68201742 parents b0a5d8b 0de721e49 files · +690 −327Browse files

Showing the changes to libraries/script-engine/src/ScriptEngine.cpp (1 of 49 files). Show all

Unified · Split

libraries/script-engine/src/ScriptEngine.cpp+32−6
@@ -9,6 +9,9 @@ · 8 unmodified lines
99 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
1010 //
1111
12+#include <chrono>
13+#include <thread>
14+
1215 #include <QtCore/QCoreApplication>
1316 #include <QtCore/QEventLoop>
1417 #include <QtCore/QFileInfo>
@@ -706,9 +709,15 @@ void ScriptEngine::run() { · 691 unmodified lines
706709
707710 QScriptValue result = evaluate(_scriptContents, _fileNameString);
708711
709− QElapsedTimer startTime;
710− startTime.start();
712+#ifdef _WIN32
713+ // VS13 does not sleep_until unless it uses the system_clock, see:
714+ // https://www.reddit.com/r/cpp_questions/comments/3o71ic/sleep_until_not_working_with_a_time_pointsteady/
715+ using clock = std::chrono::system_clock;
716+#else
717+ using clock = std::chrono::high_resolution_clock;
718+#endif
711719
720+ clock::time_point startTime = clock::now();
712721 int thisFrame = 0;
713722
714723 auto nodeList = DependencyManager::get<NodeList>();
@@ -716,12 +725,29 @@ void ScriptEngine::run() { · 1 unmodified line
716725
717726 qint64 lastUpdate = usecTimestampNow();
718727
728+ // TODO: Integrate this with signals/slots instead of reimplementing throttling for ScriptEngine
719729 while (!_isFinished) {
720− int usecToSleep = (thisFrame++ * SCRIPT_DATA_CALLBACK_USECS) - startTime.nsecsElapsed() / 1000; // nsec to usec
721− if (usecToSleep > 0) {
722− usleep(usecToSleep);
730+ // Throttle to SCRIPT_FPS
731+ const std::chrono::microseconds FRAME_DURATION(USECS_PER_SECOND / SCRIPT_FPS + 1);
732+ clock::time_point sleepTime(startTime + thisFrame++ * FRAME_DURATION);
733+ std::this_thread::sleep_until(sleepTime);
734+
735+#ifdef SCRIPT_DELAY_DEBUG
736+ {
737+ auto now = clock::now();
738+ uint64_t seconds = std::chrono::duration_cast<std::chrono::seconds>(now - startTime).count();
739+ if (seconds > 0) { // avoid division by zero and time travel
740+ uint64_t fps = thisFrame / seconds;
741+ // Overreporting artificially reduces the reported rate
742+ if (thisFrame % SCRIPT_FPS == 0) {
743+ qCDebug(scriptengine) <<
744+ "Frame:" << thisFrame <<
745+ "Slept (us):" << std::chrono::duration_cast<std::chrono::microseconds>(now - sleepTime).count() <<
746+ "FPS:" << fps;
747+ }
748+ }
723749 }
724−
750+#endif
725751 if (_isFinished) {
726752 break;
727753 }