diff --git a/CMakeLists.txt b/CMakeLists.txt index 6688ba44..ae843f0e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -105,7 +105,6 @@ set (REACTPHYSICS3D_HEADERS "include/reactphysics3d/engine/Island.h" "include/reactphysics3d/engine/Islands.h" "include/reactphysics3d/engine/Material.h" - "include/reactphysics3d/engine/Timer.h" "include/reactphysics3d/engine/OverlappingPairs.h" "include/reactphysics3d/systems/BroadPhaseSystem.h" "include/reactphysics3d/components/Components.h" @@ -204,7 +203,6 @@ set (REACTPHYSICS3D_SOURCES "src/engine/PhysicsWorld.cpp" "src/engine/Island.cpp" "src/engine/Material.cpp" - "src/engine/Timer.cpp" "src/engine/OverlappingPairs.cpp" "src/engine/Entity.cpp" "src/engine/EntityManager.cpp" diff --git a/include/reactphysics3d/configuration.h b/include/reactphysics3d/configuration.h index 4aca00cf..be47bc7b 100644 --- a/include/reactphysics3d/configuration.h +++ b/include/reactphysics3d/configuration.h @@ -35,15 +35,6 @@ #include #include -// Platforms -#if defined(WIN32) ||defined(_WIN32) || defined(_WIN64) ||defined(__WIN32__) || defined(__WINDOWS__) - #define WINDOWS_OS -#elif defined(__APPLE__) - #define APPLE_OS -#elif defined(__linux__) || defined(linux) || defined(__linux) // Linux platform - #define LINUX_OS -#endif - // Compilers #if defined(_MSC_VER) #define RP3D_COMPILER_VISUAL_STUDIO diff --git a/include/reactphysics3d/engine/Timer.h b/include/reactphysics3d/engine/Timer.h deleted file mode 100644 index 70d887a9..00000000 --- a/include/reactphysics3d/engine/Timer.h +++ /dev/null @@ -1,196 +0,0 @@ -/******************************************************************************** -* ReactPhysics3D physics library, http://www.reactphysics3d.com * -* Copyright (c) 2010-2020 Daniel Chappuis * -********************************************************************************* -* * -* This software is provided 'as-is', without any express or implied warranty. * -* In no event will the authors be held liable for any damages arising from the * -* use of this software. * -* * -* Permission is granted to anyone to use this software for any purpose, * -* including commercial applications, and to alter it and redistribute it * -* freely, subject to the following restrictions: * -* * -* 1. The origin of this software must not be misrepresented; you must not claim * -* that you wrote the original software. If you use this software in a * -* product, an acknowledgment in the product documentation would be * -* appreciated but is not required. * -* * -* 2. Altered source versions must be plainly marked as such, and must not be * -* misrepresented as being the original software. * -* * -* 3. This notice may not be removed or altered from any source distribution. * -* * -********************************************************************************/ - -#ifndef REACTPHYSICS3D_TIMER_H -#define REACTPHYSICS3D_TIMER_H - -// Libraries -#include -#include -#include - -#if defined(WINDOWS_OS) // For Windows platform - #define NOMINMAX // This is used to avoid definition of max() and min() macros - #include -#else // For Mac OS or Linux platform - #include -#endif - - -/// Namespace ReactPhysics3D -namespace reactphysics3d { - -// Class Timer -/** - * This class will take care of the time in the physics engine. It - * uses functions that depend on the current platform to get the - * current time. - */ -class Timer { - - private : - - // -------------------- Attributes -------------------- // - - /// Timestep dt of the physics engine (timestep > 0.0) - double mTimeStep; - - /// Last time the timer has been updated - long double mLastUpdateTime; - - /// Time difference between the two last timer update() calls - long double mDeltaTime; - - /// Used to fix the time step and avoid strange time effects - double mAccumulator; - - /// True if the timer is running - bool mIsRunning; - - public : - - // -------------------- Methods -------------------- // - - /// Constructor - Timer(double timeStep); - - /// Destructor - ~Timer() = default; - - /// Deleted copy-constructor - Timer(const Timer& timer) = delete; - - /// Deleted assignment operator - Timer& operator=(const Timer& timer) = delete; - - /// Return the timestep of the physics engine - double getTimeStep() const; - - /// Set the timestep of the physics engine - void setTimeStep(double timeStep); - - /// Return the current time of the physics engine - long double getPhysicsTime() const; - - /// Start the timer - void start(); - - /// Stop the timer - void stop(); - - /// Return true if the timer is running - bool getIsRunning() const; - - /// True if it's possible to take a new step - bool isPossibleToTakeStep() const; - - /// Compute the time since the last update() call and add it to the accumulator - void update(); - - /// Take a new step => update the timer by adding the timeStep value to the current time - void nextStep(); - - /// Compute the interpolation factor - decimal computeInterpolationFactor(); - - /// Return the current time of the system in seconds - static long double getCurrentSystemTime(); -}; - -// Return the timestep of the physics engine -RP3D_FORCE_INLINE double Timer::getTimeStep() const { - return mTimeStep; -} - -// Set the timestep of the physics engine -RP3D_FORCE_INLINE void Timer::setTimeStep(double timeStep) { - assert(timeStep > 0.0f); - mTimeStep = timeStep; -} - -// Return the current time -RP3D_FORCE_INLINE long double Timer::getPhysicsTime() const { - return mLastUpdateTime; -} - -// Return if the timer is running -RP3D_FORCE_INLINE bool Timer::getIsRunning() const { - return mIsRunning; -} - -// Start the timer -RP3D_FORCE_INLINE void Timer::start() { - if (!mIsRunning) { - - // Get the current system time - mLastUpdateTime = getCurrentSystemTime(); - - mAccumulator = 0.0; - mIsRunning = true; - } -} - -// Stop the timer -RP3D_FORCE_INLINE void Timer::stop() { - mIsRunning = false; -} - -// True if it's possible to take a new step -RP3D_FORCE_INLINE bool Timer::isPossibleToTakeStep() const { - return (mAccumulator >= mTimeStep); -} - -// Take a new step => update the timer by adding the timeStep value to the current time -RP3D_FORCE_INLINE void Timer::nextStep() { - assert(mIsRunning); - - // Update the accumulator value - mAccumulator -= mTimeStep; -} - -// Compute the interpolation factor -RP3D_FORCE_INLINE decimal Timer::computeInterpolationFactor() { - return (decimal(mAccumulator / mTimeStep)); -} - -// Compute the time since the last update() call and add it to the accumulator -RP3D_FORCE_INLINE void Timer::update() { - - // Get the current system time - long double currentTime = getCurrentSystemTime(); - - // Compute the delta display time between two display frames - mDeltaTime = currentTime - mLastUpdateTime; - - // Update the current display time - mLastUpdateTime = currentTime; - - // Update the accumulator value - mAccumulator += mDeltaTime; -} - -} - - #endif diff --git a/include/reactphysics3d/utils/Profiler.h b/include/reactphysics3d/utils/Profiler.h index 8c46e7ca..5c59b81b 100644 --- a/include/reactphysics3d/utils/Profiler.h +++ b/include/reactphysics3d/utils/Profiler.h @@ -29,16 +29,17 @@ // If profiling is enabled #ifdef IS_RP3D_PROFILING_ENABLED - // Libraries #include -#include #include +#include #include /// ReactPhysics3D namespace namespace reactphysics3d { +using clock = std::chrono::high_resolution_clock; + // Class ProfileNode /** * It represents a profile sample in the profiler tree. @@ -56,10 +57,10 @@ class ProfileNode { uint mNbTotalCalls; /// Starting time of the sampling of corresponding block of code - long double mStartingTime; + std::chrono::time_point mStartingTime; /// Total time spent in the block of code - long double mTotalTime; + std::chrono::duration mTotalTime; /// Recursion counter int mRecursionCounter; @@ -102,7 +103,7 @@ class ProfileNode { uint getNbTotalCalls() const; /// Return the total time spent in the block of code - long double getTotalTime() const; + std::chrono::duration getTotalTime() const; /// Called when we enter the block of code corresponding to this profile node void enterBlockOfCode(); @@ -162,7 +163,7 @@ class ProfileNodeIterator { const char* getCurrentName(); /// Return the total time of the current node - long double getCurrentTotalTime(); + std::chrono::duration getCurrentTotalTime(); /// Return the total number of calls of the current node uint getCurrentNbTotalCalls(); @@ -171,7 +172,7 @@ class ProfileNodeIterator { const char* getCurrentParentName(); /// Return the total time of the current parent node - long double getCurrentParentTotalTime(); + std::chrono::duration getCurrentParentTotalTime(); /// Return the total number of calls of the current parent node uint getCurrentParentNbTotalCalls(); @@ -290,7 +291,7 @@ class Profiler { uint mFrameCounter; /// Starting profiling time - long double mProfilingStartTime; + std::chrono::time_point mProfilingStartTime; /// Number of allocated destinations uint mNbAllocatedDestinations; @@ -336,7 +337,7 @@ class Profiler { uint getNbFrames(); /// Return the elasped time since the start/reset of the profiling - long double getElapsedTimeSinceStart(); + std::chrono::duration getElapsedTimeSinceStart(); /// Increment the frame counter void incrementFrameCounter(); @@ -416,7 +417,7 @@ RP3D_FORCE_INLINE const char* ProfileNodeIterator::getCurrentName() { } // Return the total time of the current node -RP3D_FORCE_INLINE long double ProfileNodeIterator::getCurrentTotalTime() { +RP3D_FORCE_INLINE std::chrono::duration ProfileNodeIterator::getCurrentTotalTime() { return mCurrentChildNode->getTotalTime(); } @@ -431,7 +432,7 @@ RP3D_FORCE_INLINE const char* ProfileNodeIterator::getCurrentParentName() { } // Return the total time of the current parent node -RP3D_FORCE_INLINE long double ProfileNodeIterator::getCurrentParentTotalTime() { +RP3D_FORCE_INLINE std::chrono::duration ProfileNodeIterator::getCurrentParentTotalTime() { return mCurrentParentNode->getTotalTime(); } @@ -476,7 +477,7 @@ RP3D_FORCE_INLINE uint ProfileNode::getNbTotalCalls() const { } // Return the total time spent in the block of code -RP3D_FORCE_INLINE long double ProfileNode::getTotalTime() const { +RP3D_FORCE_INLINE std::chrono::duration ProfileNode::getTotalTime() const { return mTotalTime; } @@ -486,9 +487,8 @@ RP3D_FORCE_INLINE uint Profiler::getNbFrames() { } // Return the elasped time since the start/reset of the profiling -RP3D_FORCE_INLINE long double Profiler::getElapsedTimeSinceStart() { - long double currentTime = Timer::getCurrentSystemTime() * 1000.0L; - return currentTime - mProfilingStartTime; +RP3D_FORCE_INLINE std::chrono::duration Profiler::getElapsedTimeSinceStart() { + return (clock::now() - mProfilingStartTime); } // Increment the frame counter diff --git a/src/engine/Timer.cpp b/src/engine/Timer.cpp deleted file mode 100644 index aa29397b..00000000 --- a/src/engine/Timer.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/******************************************************************************** -* ReactPhysics3D physics library, http://www.reactphysics3d.com * -* Copyright (c) 2010-2020 Daniel Chappuis * -********************************************************************************* -* * -* This software is provided 'as-is', without any express or implied warranty. * -* In no event will the authors be held liable for any damages arising from the * -* use of this software. * -* * -* Permission is granted to anyone to use this software for any purpose, * -* including commercial applications, and to alter it and redistribute it * -* freely, subject to the following restrictions: * -* * -* 1. The origin of this software must not be misrepresented; you must not claim * -* that you wrote the original software. If you use this software in a * -* product, an acknowledgment in the product documentation would be * -* appreciated but is not required. * -* * -* 2. Altered source versions must be plainly marked as such, and must not be * -* misrepresented as being the original software. * -* * -* 3. This notice may not be removed or altered from any source distribution. * -* * -********************************************************************************/ - -// Libraries -#include - -// We want to use the ReactPhysics3D namespace -using namespace reactphysics3d; - -// Constructor -Timer::Timer(double timeStep) : mTimeStep(timeStep), mLastUpdateTime(0), mDeltaTime(0), mIsRunning(false) { - assert(timeStep > 0.0); -} - -// Return the current time of the system in seconds -long double Timer::getCurrentSystemTime() { - - #if defined(WINDOWS_OS) - LARGE_INTEGER ticksPerSecond; - LARGE_INTEGER ticks; - QueryPerformanceFrequency(&ticksPerSecond); - QueryPerformanceCounter(&ticks); - return ((long double)(ticks.QuadPart) / (long double)(ticksPerSecond.QuadPart)); - #else - // Initialize the lastUpdateTime with the current time in seconds - timeval timeValue; - gettimeofday(&timeValue, nullptr); - return (timeValue.tv_sec + (timeValue.tv_usec / 1000000.0)); - #endif -} - - - - - - - - - diff --git a/src/utils/Profiler.cpp b/src/utils/Profiler.cpp index 3fd27841..7b2dda99 100644 --- a/src/utils/Profiler.cpp +++ b/src/utils/Profiler.cpp @@ -36,7 +36,7 @@ using namespace reactphysics3d; // Constructor ProfileNode::ProfileNode(const char* name, ProfileNode* parentNode) - :mName(name), mNbTotalCalls(0), mStartingTime(0), mTotalTime(0), + :mName(name), mNbTotalCalls(0), mStartingTime(), mTotalTime(0), mRecursionCounter(0), mParentNode(parentNode), mChildNode(nullptr), mSiblingNode(nullptr) { reset(); @@ -79,7 +79,7 @@ void ProfileNode::enterBlockOfCode() { // Get the current system time to initialize the starting time of // the profiling of the current block of code - mStartingTime = Timer::getCurrentSystemTime() * 1000.0L; + mStartingTime = clock::now(); } mRecursionCounter++; @@ -92,7 +92,7 @@ bool ProfileNode::exitBlockOfCode() { if (mRecursionCounter == 0 && mNbTotalCalls != 0) { // Get the current system time - long double currentTime = Timer::getCurrentSystemTime() * 1000.0L; + std::chrono::time_point currentTime = std::chrono::high_resolution_clock::now(); // Increase the total elasped time in the current block of code mTotalTime += currentTime - mStartingTime; @@ -105,7 +105,7 @@ bool ProfileNode::exitBlockOfCode() { // Reset the profiling of the node void ProfileNode::reset() { mNbTotalCalls = 0; - mTotalTime = 0.0L; + mTotalTime = std::chrono::duration::zero(); // Reset the child node if (mChildNode != nullptr) { @@ -161,7 +161,7 @@ Profiler::Profiler() :mRootNode("Root", nullptr) { mCurrentNode = &mRootNode; mNbDestinations = 0; mNbAllocatedDestinations = 0; - mProfilingStartTime = Timer::getCurrentSystemTime() * 1000.0L; + mProfilingStartTime = clock::now(); mFrameCounter = 0; allocatedDestinations(1); @@ -215,7 +215,7 @@ void Profiler::reset() { mRootNode.reset(); mRootNode.enterBlockOfCode(); mFrameCounter = 0; - mProfilingStartTime = Timer::getCurrentSystemTime() * 1000.0L; + mProfilingStartTime = clock::now(); } // Print the report of the profiler in a given output stream @@ -283,27 +283,27 @@ void Profiler::printRecursiveNodeReport(ProfileNodeIterator* iterator, return; } - long double parentTime = iterator->isRoot() ? getElapsedTimeSinceStart() : + std::chrono::duration parentTime = iterator->isRoot() ? getElapsedTimeSinceStart() : iterator->getCurrentParentTotalTime(); - long double accumulatedTime = 0.0L; + std::chrono::duration accumulatedTime = std::chrono::duration::zero(); uint nbFrames = Profiler::getNbFrames(); for (int i=0; igetCurrentParentName() << - " (total running time : " << parentTime << " ms) ---" << std::endl; + " (total running time : " << parentTime.count() << " ms) ---" << std::endl; // Recurse over the children of the current node int nbChildren = 0; for (int i=0; !iterator->isEnd(); i++, iterator->next()) { nbChildren++; - long double currentTotalTime = iterator->getCurrentTotalTime(); + std::chrono::duration currentTotalTime = iterator->getCurrentTotalTime(); accumulatedTime += currentTotalTime; - long double fraction = parentTime > std::numeric_limits::epsilon() ? - (currentTotalTime / parentTime) * 100.0L : 0.0L; + long double fraction = parentTime.count() > std::numeric_limits::epsilon() ? + (currentTotalTime.count() / parentTime.count()) * 100.0L : 0.0L; for (int j=0; jgetCurrentName() << " : " << - fraction << " % | " << (currentTotalTime / (long double) (nbFrames)) << + fraction << " % | " << (currentTotalTime.count() / (long double) (nbFrames)) << " ms/frame (" << iterator->getCurrentNbTotalCalls() << " calls)" << std::endl; } @@ -312,10 +312,10 @@ void Profiler::printRecursiveNodeReport(ProfileNodeIterator* iterator, outputStream << "Something is wrong !" << std::endl; } for (int i=0; i std::numeric_limits::epsilon() ? + long double percentage = parentTime.count() > std::numeric_limits::epsilon() ? ((parentTime - accumulatedTime) / parentTime) * 100.0L : 0.0L; - long double difference = parentTime - accumulatedTime; - outputStream << "| Unaccounted : " << difference << " ms (" << percentage << " %)" << std::endl; + std::chrono::duration difference = parentTime - accumulatedTime; + outputStream << "| Unaccounted : " << difference.count() << " ms (" << percentage << " %)" << std::endl; for (int i=0; ienterChild(i); diff --git a/testbed/CMakeLists.txt b/testbed/CMakeLists.txt index d73f4fc2..b8438af5 100755 --- a/testbed/CMakeLists.txt +++ b/testbed/CMakeLists.txt @@ -91,7 +91,6 @@ set(TESTBED_SOURCES src/SceneDemo.h src/SceneDemo.cpp src/Timer.h - src/Timer.cpp ) # Common source files diff --git a/testbed/scenes/bridge/BridgeScene.cpp b/testbed/scenes/bridge/BridgeScene.cpp index 12b5fae2..969196fb 100644 --- a/testbed/scenes/bridge/BridgeScene.cpp +++ b/testbed/scenes/bridge/BridgeScene.cpp @@ -183,7 +183,7 @@ void BridgeScene::updatePhysics() { if (joint != nullptr) { - if (joint->getReactionForce(mEngineSettings.timeStep).lengthSquare() > 60000000) { + if (joint->getReactionForce(mEngineSettings.timeStep.count()).lengthSquare() > 60000000) { mPhysicsWorld->destroyJoint(joint); mHingeJoints[jointIndex] = nullptr; } diff --git a/testbed/scenes/joints/JointsScene.cpp b/testbed/scenes/joints/JointsScene.cpp index d0e49075..fa4c54c6 100644 --- a/testbed/scenes/joints/JointsScene.cpp +++ b/testbed/scenes/joints/JointsScene.cpp @@ -129,7 +129,7 @@ JointsScene::~JointsScene() { void JointsScene::updatePhysics() { // Update the motor speed of the Slider Joint (to move up and down) - double motorSpeed = 2.0 * std::cos(static_cast(mEngineSettings.elapsedTime) * 1.5); + double motorSpeed = 2.0 * std::cos(mEngineSettings.elapsedTime.count() * 1.5); mSliderJoint->setMotorSpeed(rp3d::decimal(motorSpeed)); SceneDemo::updatePhysics(); diff --git a/testbed/src/Gui.cpp b/testbed/src/Gui.cpp index db36a49c..479a3464 100644 --- a/testbed/src/Gui.cpp +++ b/testbed/src/Gui.cpp @@ -201,7 +201,7 @@ void Gui::createSettingsPanel() { textboxTimeStep->set_fixed_size(Vector2i(70, 25)); textboxTimeStep->set_editable(true); std::ostringstream out; - out << std::setprecision(1) << std::fixed << (mApp->mEngineSettings.timeStep * 1000); + out << std::setprecision(1) << std::fixed << (mApp->mEngineSettings.timeStep.count() * 1000); textboxTimeStep->set_value(out.str()); textboxTimeStep->set_units("ms"); textboxTimeStep->set_callback([&, textboxTimeStep](const std::string &str) { @@ -214,7 +214,7 @@ void Gui::createSettingsPanel() { if (finalValue < 1 || finalValue > 1000) return false; - mApp->mEngineSettings.timeStep = finalValue / 1000.0f; + mApp->mEngineSettings.timeStep = std::chrono::duration(finalValue / 1000.0f); mApp->notifyEngineSetttingsChanged(); textboxTimeStep->set_value(out.str()); } diff --git a/testbed/src/Scene.h b/testbed/src/Scene.h index 14e7bfbb..80fec68b 100644 --- a/testbed/src/Scene.h +++ b/testbed/src/Scene.h @@ -30,6 +30,8 @@ #include "openglframework.h" #include +using namespace std::chrono_literals; + // Structure ContactPoint struct SceneContactPoint { @@ -51,8 +53,8 @@ struct EngineSettings { public: - long double elapsedTime; // Elapsed time (in seconds) - float timeStep; // Current time step (in seconds) + std::chrono::duration elapsedTime; // Elapsed time (in seconds) + std::chrono::duration timeStep; // Current time step (in seconds) unsigned int nbVelocitySolverIterations; // Nb of velocity solver iterations unsigned int nbPositionSolverIterations; // Nb of position solver iterations bool isSleepingEnabled; // True if sleeping technique is enabled @@ -73,7 +75,7 @@ struct EngineSettings { EngineSettings defaultSettings; rp3d::PhysicsWorld::WorldSettings worldSettings; - defaultSettings.timeStep = 1.0f / 60.0f; + defaultSettings.timeStep = std::chrono::duration(1.0f / 60.0f); defaultSettings.nbVelocitySolverIterations = worldSettings.defaultVelocitySolverNbIterations; defaultSettings.nbPositionSolverIterations = worldSettings.defaultPositionSolverNbIterations; defaultSettings.isSleepingEnabled = worldSettings.isSleepingEnabled; diff --git a/testbed/src/SceneDemo.cpp b/testbed/src/SceneDemo.cpp index d547cce8..4b661f77 100644 --- a/testbed/src/SceneDemo.cpp +++ b/testbed/src/SceneDemo.cpp @@ -155,7 +155,7 @@ void SceneDemo::updatePhysics() { if (mIsPhysicsWorldSimulated) { // Take a simulation step - mPhysicsWorld->update(mEngineSettings.timeStep); + mPhysicsWorld->update(mEngineSettings.timeStep.count()); } } diff --git a/testbed/src/TestbedApplication.cpp b/testbed/src/TestbedApplication.cpp index 090d2595..b9534bd9 100755 --- a/testbed/src/TestbedApplication.cpp +++ b/testbed/src/TestbedApplication.cpp @@ -205,7 +205,7 @@ void TestbedApplication::updateSinglePhysicsStep() { void TestbedApplication::updatePhysics() { // Update the elapsed time - mEngineSettings.elapsedTime = mTimer.getPhysicsTime(); + mEngineSettings.elapsedTime = mTimer.getElapsedPhysicsTime(); if (mTimer.isRunning()) { diff --git a/testbed/src/Timer.cpp b/testbed/src/Timer.cpp deleted file mode 100644 index 5c3e964f..00000000 --- a/testbed/src/Timer.cpp +++ /dev/null @@ -1,64 +0,0 @@ -/******************************************************************************** -* ReactPhysics3D physics library, http://www.reactphysics3d.com * -* Copyright (c) 2010-2016 Daniel Chappuis * -********************************************************************************* -* * -* This software is provided 'as-is', without any express or implied warranty. * -* In no event will the authors be held liable for any damages arising from the * -* use of this software. * -* * -* Permission is granted to anyone to use this software for any purpose, * -* including commercial applications, and to alter it and redistribute it * -* freely, subject to the following restrictions: * -* * -* 1. The origin of this software must not be misrepresented; you must not claim * -* that you wrote the original software. If you use this software in a * -* product, an acknowledgment in the product documentation would be * -* appreciated but is not required. * -* * -* 2. Altered source versions must be plainly marked as such, and must not be * -* misrepresented as being the original software. * -* * -* 3. This notice may not be removed or altered from any source distribution. * -* * -********************************************************************************/ - -// Libraries -#include "Timer.h" - - -// Constructor -Timer::Timer() : mLastUpdateTime(0), mDeltaTime(0), mAccumulator(0), mIsRunning(false) { - -} - -// Destructor -Timer::~Timer() { - -} - -// Return the current time of the system in seconds -long double Timer::getCurrentSystemTime() { - - #if defined(WINDOWS_OS) - LARGE_INTEGER ticksPerSecond; - LARGE_INTEGER ticks; - QueryPerformanceFrequency(&ticksPerSecond); - QueryPerformanceCounter(&ticks); - return (long double(ticks.QuadPart) / long double(ticksPerSecond.QuadPart)); - #else - // Initialize the lastUpdateTime with the current time in seconds - timeval timeValue; - gettimeofday(&timeValue, NULL); - return (timeValue.tv_sec + (timeValue.tv_usec / 1000000.0)); - #endif -} - - - - - - - - - diff --git a/testbed/src/Timer.h b/testbed/src/Timer.h index 9983cd93..81013284 100644 --- a/testbed/src/Timer.h +++ b/testbed/src/Timer.h @@ -29,17 +29,10 @@ // Libraries #include #include -#include +#include #include #include -#if defined(WINDOWS_OS) // For Windows platform - #define NOMINMAX // This is used to avoid definition of max() and min() macros - #include -#else // For Mac OS or Linux platform - #include -#endif - // Class Timer /** * This class will take care of the time in the physics engine. It @@ -48,18 +41,20 @@ */ class Timer { + using clock = std::chrono::high_resolution_clock; + private : // -------------------- Attributes -------------------- // - /// Last time the timer has been updated - long double mLastUpdateTime; + /// Start physics time + std::chrono::time_point mStartTime; - /// Time difference between the two last timer update() calls - long double mDeltaTime; + /// Last time the timer has been updated + std::chrono::time_point mLastUpdateTime; /// Used to fix the time step and avoid strange time effects - double mAccumulator; + std::chrono::duration mAccumulator; /// True if the timer is running bool mIsRunning; @@ -77,13 +72,12 @@ class Timer { // -------------------- Methods -------------------- // /// Constructor - Timer(); + Timer() : mAccumulator(0), mIsRunning(false) { - /// Destructor - ~Timer(); + } - /// Return the current time of the physics engine - long double getPhysicsTime() const; + /// Return the elapsed physics time + std::chrono::duration getElapsedPhysicsTime() const; /// Start the timer void start(); @@ -95,24 +89,24 @@ class Timer { bool isRunning() const; /// True if it's possible to take a new step - bool isPossibleToTakeStep(float timeStep) const; + bool isPossibleToTakeStep(std::chrono::duration timeStep) const; /// Compute the time since the last update() call and add it to the accumulator void update(); /// Take a new step => update the timer by adding the timeStep value to the current time - void nextStep(float timeStep); + void nextStep(std::chrono::duration timeStep); /// Compute the interpolation factor - float computeInterpolationFactor(float timeStep); + float computeInterpolationFactor(std::chrono::duration timeStep); /// Return the current time of the system in seconds - static long double getCurrentSystemTime(); + static std::chrono::time_point getCurrentSystemTime(); }; -// Return the current time -inline long double Timer::getPhysicsTime() const { - return mLastUpdateTime; +// Return the elapsed physics time +inline std::chrono::duration Timer::getElapsedPhysicsTime() const { + return mLastUpdateTime - mStartTime; } // Return if the timer is running @@ -122,12 +116,13 @@ inline bool Timer::isRunning() const { // Start the timer inline void Timer::start() { + if (!mIsRunning) { // Get the current system time - mLastUpdateTime = getCurrentSystemTime(); + mLastUpdateTime = clock::now(); - mAccumulator = 0.0; + mAccumulator = std::chrono::duration::zero(); mIsRunning = true; } } @@ -138,12 +133,12 @@ inline void Timer::stop() { } // True if it's possible to take a new step -inline bool Timer::isPossibleToTakeStep(float timeStep) const { +inline bool Timer::isPossibleToTakeStep(std::chrono::duration timeStep) const { return (mAccumulator >= timeStep); } // Take a new step => update the timer by adding the timeStep value to the current time -inline void Timer::nextStep(float timeStep) { +inline void Timer::nextStep(std::chrono::duration timeStep) { assert(mIsRunning); // Update the accumulator value @@ -151,24 +146,24 @@ inline void Timer::nextStep(float timeStep) { } // Compute the interpolation factor -inline float Timer::computeInterpolationFactor(float timeStep) { - return (float(mAccumulator) / timeStep); +inline float Timer::computeInterpolationFactor(std::chrono::duration timeStep) { + return float(mAccumulator.count() / timeStep.count()); } // Compute the time since the last update() call and add it to the accumulator inline void Timer::update() { // Get the current system time - long double currentTime = getCurrentSystemTime(); + std::chrono::time_point currentTime = clock::now(); // Compute the delta display time between two display frames - mDeltaTime = currentTime - mLastUpdateTime; + std::chrono::duration deltaTime = currentTime - mLastUpdateTime; // Update the current display time mLastUpdateTime = currentTime; // Update the accumulator value - mAccumulator += mDeltaTime; + mAccumulator += deltaTime; } #endif