diff --git a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Docking_BasicDockedTools.py b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Docking_BasicDockedTools.py index 2a91e7a374..6683fc952a 100644 --- a/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Docking_BasicDockedTools.py +++ b/AutomatedTesting/Gem/PythonTests/editor/EditorScripts/Docking_BasicDockedTools.py @@ -140,13 +140,13 @@ def Docking_BasicDockedTools(): # 2.5,6) Send a console command. console_line_edit = console.findChild(QtWidgets.QLineEdit, "lineEdit") - console_line_edit.setText("t_Scale 2") + console_line_edit.setText("t_simulationTickScale 2") QtTest.QTest.keyClick(console_line_edit, QtCore.Qt.Key_Enter) - general.get_cvar("t_Scale") - Report.result(Tests.docked_console_works, general.get_cvar("t_Scale") == "2") + general.get_cvar("t_simulationTickScale") + Report.result(Tests.docked_console_works, general.get_cvar("t_simulationTickScale") == "2") # Reset the altered cvar - console_line_edit.setText("t_Scale 1") + console_line_edit.setText("t_simulationTickScale 1") QtTest.QTest.keyClick(console_line_edit, QtCore.Qt.Key_Enter) run_test() diff --git a/Code/Editor/AnimationContext.cpp b/Code/Editor/AnimationContext.cpp index fce1150878..51dd8deefc 100644 --- a/Code/Editor/AnimationContext.cpp +++ b/Code/Editor/AnimationContext.cpp @@ -21,6 +21,8 @@ #include "Include/IObjectManager.h" #include "Objects/EntityObject.h" +#include + ////////////////////////////////////////////////////////////////////////// // Movie Callback. ////////////////////////////////////////////////////////////////////////// @@ -499,25 +501,24 @@ void CAnimationContext::Update() return; } - ITimer* pTimer = GetIEditor()->GetSystem()->GetITimer(); + const AZ::TimeUs frameDeltaTimeUs = AZ::GetSimulationTickDeltaTimeUs(); + const float frameDeltaTime = AZ::TimeUsToSeconds(frameDeltaTimeUs); if (!m_bAutoRecording) { AnimateActiveSequence(); - float dt = pTimer->GetFrameTime(); - m_currTime += dt * m_fTimeScale; + m_currTime += frameDeltaTime * m_fTimeScale; if (!m_recording) { - GetIEditor()->GetMovieSystem()->PreUpdate(dt); - GetIEditor()->GetMovieSystem()->PostUpdate(dt); + GetIEditor()->GetMovieSystem()->PreUpdate(frameDeltaTime); + GetIEditor()->GetMovieSystem()->PostUpdate(frameDeltaTime); } } else { - float dt = pTimer->GetFrameTime(); - m_fRecordingCurrTime += dt * m_fTimeScale; + m_fRecordingCurrTime += frameDeltaTime * m_fTimeScale; if (fabs(m_fRecordingCurrTime - m_currTime) > m_fRecordingTimeStep) { m_currTime += m_fRecordingTimeStep; @@ -644,7 +645,9 @@ void CAnimationContext::OnPostRender() { SAnimContext ac; ac.dt = 0; - ac.fps = GetIEditor()->GetSystem()->GetITimer()->GetFrameRate(); + const AZ::TimeUs frameDeltaTimeUs = AZ::GetSimulationTickDeltaTimeUs(); + const float frameDeltaTime = AZ::TimeUsToSeconds(frameDeltaTimeUs); + ac.fps = 1.0f / frameDeltaTime; ac.time = m_currTime; ac.singleFrame = true; ac.forcePlay = true; @@ -797,7 +800,9 @@ void CAnimationContext::AnimateActiveSequence() SAnimContext ac; ac.dt = 0; - ac.fps = GetIEditor()->GetSystem()->GetITimer()->GetFrameRate(); + const AZ::TimeUs frameDeltaTimeUs = AZ::GetSimulationTickDeltaTimeUs(); + const float frameDeltaTime = AZ::TimeUsToSeconds(frameDeltaTimeUs); + ac.fps = 1.0f / frameDeltaTime; ac.time = m_currTime; ac.singleFrame = true; ac.forcePlay = true; diff --git a/Code/Editor/CryEdit.cpp b/Code/Editor/CryEdit.cpp index c74d6ac960..fd38d4f52f 100644 --- a/Code/Editor/CryEdit.cpp +++ b/Code/Editor/CryEdit.cpp @@ -80,7 +80,6 @@ AZ_POP_DISABLE_WARNING #include // CryCommon -#include #include // Editor diff --git a/Code/Editor/CryEditDoc.cpp b/Code/Editor/CryEditDoc.cpp index 212606c737..9acaaad842 100644 --- a/Code/Editor/CryEditDoc.cpp +++ b/Code/Editor/CryEditDoc.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -749,7 +750,9 @@ bool CCryEditDoc::OnOpenDocument(const QString& lpszPathName) bool CCryEditDoc::BeforeOpenDocument(const QString& lpszPathName, TOpenDocContext& context) { - CTimeValue loading_start_time = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs(); + const double timeSec = AZ::TimeMsToSecondsDouble(timeMs); + const CTimeValue loading_start_time(timeSec); bool usePrefabSystemForLevels = false; AzFramework::ApplicationRequests::Bus::BroadcastResult( @@ -790,7 +793,7 @@ bool CCryEditDoc::BeforeOpenDocument(const QString& lpszPathName, TOpenDocContex bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) { - CTimeValue& loading_start_time = context.loading_start_time; + const CTimeValue& loading_start_time = context.loading_start_time; bool isPrefabEnabled = false; AzFramework::ApplicationRequests::Bus::BroadcastResult(isPrefabEnabled, &AzFramework::ApplicationRequests::IsPrefabSystemEnabled); @@ -860,7 +863,9 @@ bool CCryEditDoc::DoOpenDocument(TOpenDocContext& context) StartStreamingLoad(); - CTimeValue loading_end_time = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs(); + const double timeSec = AZ::TimeMsToSecondsDouble(timeMs); + const CTimeValue loading_end_time(timeSec); CLogFile::FormatLine("-----------------------------------------------------------"); CLogFile::FormatLine("Successfully opened document %s", context.absoluteLevelPath.toUtf8().data()); diff --git a/Code/Editor/EditorDefs.h b/Code/Editor/EditorDefs.h index 4115e8433a..97c03b2b45 100644 --- a/Code/Editor/EditorDefs.h +++ b/Code/Editor/EditorDefs.h @@ -105,7 +105,6 @@ #include #include #include -#include #include #include diff --git a/Code/Editor/GameEngine.cpp b/Code/Editor/GameEngine.cpp index ff247c1e6c..6f434eda98 100644 --- a/Code/Editor/GameEngine.cpp +++ b/Code/Editor/GameEngine.cpp @@ -822,7 +822,7 @@ void CGameEngine::Update() if (gEnv->pSystem) { gEnv->pSystem->UpdatePreTickBus(); - componentApplication->Tick(gEnv->pTimer->GetFrameTime(ITimer::ETIMER_GAME)); + componentApplication->Tick(); gEnv->pSystem->UpdatePostTickBus(); } @@ -838,7 +838,7 @@ void CGameEngine::Update() unsigned int updateFlags = ESYSUPDATE_EDITOR; GetIEditor()->GetAnimation()->Update(); GetIEditor()->GetSystem()->UpdatePreTickBus(updateFlags); - componentApplication->Tick(gEnv->pTimer->GetFrameTime(ITimer::ETIMER_GAME)); + componentApplication->Tick(); GetIEditor()->GetSystem()->UpdatePostTickBus(updateFlags); } } diff --git a/Code/Editor/Lib/Tests/test_EditorPythonBindings.cpp b/Code/Editor/Lib/Tests/test_EditorPythonBindings.cpp index 1006c339ee..de0eb5df6f 100644 --- a/Code/Editor/Lib/Tests/test_EditorPythonBindings.cpp +++ b/Code/Editor/Lib/Tests/test_EditorPythonBindings.cpp @@ -25,7 +25,6 @@ #include #include #include -#include #include #include "IEditorMock.h" diff --git a/Code/Framework/AtomCore/Tests/Main.cpp b/Code/Framework/AtomCore/Tests/Main.cpp index 29ef408551..eb4c6bc835 100644 --- a/Code/Framework/AtomCore/Tests/Main.cpp +++ b/Code/Framework/AtomCore/Tests/Main.cpp @@ -7,7 +7,6 @@ */ -#include #include #include #include diff --git a/Code/Framework/AzCore/AzCore/AzCoreModule.cpp b/Code/Framework/AzCore/AzCore/AzCoreModule.cpp index 67123ed826..e7e87559b0 100644 --- a/Code/Framework/AzCore/AzCore/AzCoreModule.cpp +++ b/Code/Framework/AzCore/AzCore/AzCoreModule.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include #include @@ -40,7 +39,6 @@ namespace AZ SliceComponent::CreateDescriptor(), SliceSystemComponent::CreateDescriptor(), SliceMetadataInfoComponent::CreateDescriptor(), - TimeSystemComponent::CreateDescriptor(), LoggerSystemComponent::CreateDescriptor(), EventSchedulerSystemComponent::CreateDescriptor(), TaskGraphSystemComponent::CreateDescriptor(), @@ -59,7 +57,6 @@ namespace AZ { return AZ::ComponentTypeList { - azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), azrtti_typeid(), diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp index bd225cf634..cf23d2b4d7 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.cpp @@ -72,6 +72,7 @@ #include #include +#include static void PrintEntityName(const AZ::ConsoleCommandContainer& arguments) { @@ -416,6 +417,7 @@ namespace AZ ComponentApplication::ComponentApplication(int argC, char** argV) : m_eventLogger{} + , m_timeSystem(AZStd::make_unique()) { if (Interface::Get() == nullptr) { @@ -574,7 +576,6 @@ namespace AZ DestroyAllocator(); } - void ReportBadEngineRoot() { AZStd::string errorMessage = {"Unable to determine a valid path to the engine.\n" @@ -677,7 +678,6 @@ namespace AZ ComponentApplicationBus::Handler::BusConnect(); - m_currentTime = AZStd::chrono::system_clock::now(); TickRequestBus::Handler::BusConnect(); #if defined(AZ_ENABLE_DEBUG_TOOLS) @@ -1413,31 +1413,23 @@ namespace AZ #endif } - void ComponentApplication::Tick(float deltaOverride /*= -1.f*/) + void ComponentApplication::Tick() { + AZ_PROFILE_SCOPE(System, "Component application simulation tick"); + { - AZ_PROFILE_SCOPE(System, "Component application simulation tick"); - - AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now(); - - m_deltaTime = 0.0f; - - if (now >= m_currentTime) - { - AZStd::chrono::duration delta = now - m_currentTime; - m_deltaTime = deltaOverride >= 0.f ? deltaOverride : delta.count(); - } - - { - AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:ExecuteQueuedEvents"); - TickBus::ExecuteQueuedEvents(); - } - m_currentTime = now; - { - AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:OnTick"); - EBUS_EVENT(TickBus, OnTick, m_deltaTime, ScriptTimePoint(now)); - } + AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:ExecuteQueuedEvents"); + TickBus::ExecuteQueuedEvents(); } + + { + AZ_PROFILE_SCOPE(AzCore, "ComponentApplication::Tick:OnTick"); + const AZ::TimeUs deltaTimeUs = m_timeSystem->AdvanceTickDeltaTimes(); + const float deltaTimeSeconds = AZ::TimeUsToSeconds(deltaTimeUs); + AZ::TickBus::Broadcast(&TickEvents::OnTick, deltaTimeSeconds, GetTimeAtCurrentTick()); + } + + m_timeSystem->ApplyTickRateLimiterIfNeeded(); } void ComponentApplication::TickSystem() @@ -1519,13 +1511,10 @@ namespace AZ appType.m_maskValue = AZ::ApplicationTypeQuery::Masks::Invalid; } - //========================================================================= - // GetFrameTime - // [1/22/2016] - //========================================================================= float ComponentApplication::GetTickDeltaTime() { - return m_deltaTime; + const AZ::TimeUs gameTickTime = m_timeSystem->GetSimulationTickDeltaTimeUs(); + return AZ::TimeUsToSeconds(gameTickTime); } //========================================================================= @@ -1534,7 +1523,8 @@ namespace AZ //========================================================================= ScriptTimePoint ComponentApplication::GetTimeAtCurrentTick() { - return ScriptTimePoint(m_currentTime); + const AZ::TimeUs lastGameTickTime = m_timeSystem->GetLastSimulationTickTime(); + return ScriptTimePoint(AZ::TimeUsToChrono(lastGameTickTime)); } //========================================================================= diff --git a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h index 4e551b6c47..f245b5f5da 100644 --- a/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h +++ b/Code/Framework/AzCore/AzCore/Component/ComponentApplication.h @@ -30,12 +30,14 @@ #include #include + namespace AZ { class BehaviorContext; class IConsole; class Module; class ModuleManager; + class TimeSystem; } namespace AZ::Debug { @@ -237,7 +239,7 @@ namespace AZ /** * Ticks all components using the \ref AZ::TickBus during simulation time. May not tick if the application is not active (i.e. not in focus) */ - virtual void Tick(float deltaOverride = -1.f); + virtual void Tick(); /** * Ticks all using the \ref AZ::SystemTickBus at all times. Should always tick even if the application is not active. @@ -359,8 +361,6 @@ namespace AZ } } - AZStd::chrono::system_clock::time_point m_currentTime{ AZStd::chrono::system_clock::time_point::max() }; - float m_deltaTime{ 0.0f }; AZStd::unique_ptr m_moduleManager; AZStd::unique_ptr m_settingsRegistry; EntityAddedEvent m_entityAddedEvent; @@ -381,6 +381,8 @@ namespace AZ AZ::SettingsRegistryInterface::NotifyEventHandler m_projectNameChangedHandler; AZ::SettingsRegistryInterface::NotifyEventHandler m_commandLineUpdatedHandler; + AZStd::unique_ptr m_timeSystem; + // ConsoleFunctorHandle is responsible for unregistering the Settings Registry Console // from the m_console member when it goes out of scope AZ::SettingsRegistryConsoleUtils::ConsoleFunctorHandle m_settingsRegistryConsoleFunctors; diff --git a/Code/Framework/AzCore/AzCore/EBus/EventSchedulerSystemComponent.cpp b/Code/Framework/AzCore/AzCore/EBus/EventSchedulerSystemComponent.cpp index 3cdc3fc461..dd92b340c5 100644 --- a/Code/Framework/AzCore/AzCore/EBus/EventSchedulerSystemComponent.cpp +++ b/Code/Framework/AzCore/AzCore/EBus/EventSchedulerSystemComponent.cpp @@ -60,7 +60,7 @@ namespace AZ void EventSchedulerSystemComponent::OnTick([[maybe_unused]] float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - TimeMs startTime = GetElapsedTimeMs(); + TimeMs startTime = AZ::GetElapsedTimeMs(); bool usingTimeslice = bg_maxScheduledEventProcessTimeMs != TimeMs{ 0 }; while (!m_queue.empty()) @@ -76,7 +76,7 @@ namespace AZ while (!m_pendingQueue.empty()) { - if (usingTimeslice && (GetElapsedTimeMs() - startTime > bg_maxScheduledEventProcessTimeMs)) + if (usingTimeslice && (AZ::GetElapsedTimeMs() - startTime > bg_maxScheduledEventProcessTimeMs)) { AZLOG_WARN("Failed to trigger all pending scheduled events, %u events remain on the pending queue", aznumeric_cast(m_pendingQueue.size())); break; @@ -103,7 +103,7 @@ namespace AZ durationMs = TimeMs{ 0 }; } - TimeMs currentMilliseconds = GetElapsedTimeMs(); + TimeMs currentMilliseconds = AZ::GetElapsedTimeMs(); if (timedEvent->m_handle == nullptr) { timedEvent->m_handle = AllocateHandle(); @@ -122,7 +122,7 @@ namespace AZ durationMs = TimeMs{ 0 }; } - TimeMs currentMilliseconds = GetElapsedTimeMs(); + TimeMs currentMilliseconds = AZ::GetElapsedTimeMs(); ScheduledEvent* timedEvent = AllocateManagedEvent(callback, eventName); const bool ownsScheduledEvent = true; *(timedEvent->m_handle) = ScheduledEventHandle(TimeMs(currentMilliseconds + durationMs), durationMs, timedEvent, ownsScheduledEvent); diff --git a/Code/Framework/AzCore/AzCore/EBus/ScheduledEvent.cpp b/Code/Framework/AzCore/AzCore/EBus/ScheduledEvent.cpp index 8e496c3dbc..41230958e4 100644 --- a/Code/Framework/AzCore/AzCore/EBus/ScheduledEvent.cpp +++ b/Code/Framework/AzCore/AzCore/EBus/ScheduledEvent.cpp @@ -76,7 +76,7 @@ namespace AZ TimeMs ScheduledEvent::TimeInQueueMs() const { - return GetElapsedTimeMs() - m_timeInserted; + return AZ::GetElapsedTimeMs() - m_timeInserted; } TimeMs ScheduledEvent::RemainingTimeInQueueMs() const diff --git a/Code/Framework/AzCore/AzCore/Time/ITime.h b/Code/Framework/AzCore/AzCore/Time/ITime.h index a97ba2319a..a3dcca09ea 100644 --- a/Code/Framework/AzCore/AzCore/Time/ITime.h +++ b/Code/Framework/AzCore/AzCore/Time/ITime.h @@ -12,8 +12,8 @@ #include #include #include -#include #include +#include namespace AZ { @@ -24,15 +24,21 @@ namespace AZ //! Using int64_t as the underlying type, this is good to represent approximately 292,471 years AZ_TYPE_SAFE_INTEGRAL(TimeUs, int64_t); + namespace Time + { + static const AZ::TimeMs ZeroTimeMs = AZ::TimeMs{ 0 }; + static const AZ::TimeUs ZeroTimeUs = AZ::TimeUs{ 0 }; + } + //! @class ITime //! @brief This is an AZ::Interface<> for managing time related operations. //! AZ::ITime and associated types may not operate in realtime. These abstractions are to allow our application //! simulation to operate both slower and faster than realtime in a well defined and user controllable manner - //! The rate at which time passes for AZ::ITime is controlled by the cvar t_scale - //! t_scale == 0 means simulation time should halt - //! 0 < t_scale < 1 will cause time to pass slower than realtime, with t_scale 0.1 being roughly 1/10th realtime - //! t_scale == 1 will cause time to pass at roughly realtime - //! t_scale > 1 will cause time to pass faster than normal, with t_scale 10 being roughly 10x realtime + //! The rate at which time passes for AZ::ITime is controlled by the cvar t_simulationTickScale + //! t_simulationTickScale == 0 means simulation time should halt + //! 0 < t_simulationTickScale < 1 will cause time to pass slower than realtime, with t_simulationTickScale 0.1 being roughly 1/10th realtime + //! t_simulationTickScale == 1 will cause time to pass at roughly realtime + //! t_simulationTickScale > 1 will cause time to pass faster than normal, with t_simulationTickScale 10 being roughly 10x realtime class ITime { public: @@ -41,15 +47,72 @@ namespace AZ ITime() = default; virtual ~ITime() = default; - //! Returns the number of milliseconds since application start. - //! @return the number of milliseconds that have elapsed since application start + //! Returns the number of milliseconds since application start scaled by t_simulationTickScale. + //! @return The number of milliseconds that have elapsed since application start. virtual TimeMs GetElapsedTimeMs() const = 0; - //! Returns the number of microseconds since application start. + //! Returns the number of microseconds since application start scaled by t_simulationTickScale. //! @return the number of microseconds that have elapsed since application start virtual TimeUs GetElapsedTimeUs() const = 0; + + //! Returns the number of milliseconds since application start. + //! This value is not affected by the t_simulationTickScale cvar. + //! @return The number of milliseconds that have elapsed since application start. + virtual TimeMs GetRealElapsedTimeMs() const = 0; + + //! Returns the number of microseconds since application start. + //! This value is not affected by the t_simulationTickScale cvar. + //! @return The number of microseconds that have elapsed since application start. + virtual TimeUs GetRealElapsedTimeUs() const = 0; + + //! Returns the current simulation tick delta time. + //! This is affected by the cvars t_simulationTickScale, t_simulationTickDeltaOverride, and t_maxGameTickDelta. + //! @return The number of microseconds elapsed since the last game tick. + virtual TimeUs GetSimulationTickDeltaTimeUs() const = 0; + + //! Returns the non-manipulated tick time. + //! @return The number of microseconds elapsed since the last game tick. + virtual TimeUs GetRealTickDeltaTimeUs() const = 0; + + //! Returns the time since application start of when the last simulation tick was updated. + virtual TimeUs GetLastSimulationTickTime() const = 0; + + //! If > 0 this will override the simulation tick delta time with the provided value. + //! When enabled this will ignore any set simulation tick scale. + //! Setting to 0 disables the override. + //! @param timeMs The time in milliseconds to use for the tick delta. + virtual void SetSimulationTickDeltaOverride(TimeMs timeMs) = 0; + + //! Returns the current simulation tick override. + //! 0 means disabled. + //! @returns The current simulation tick override in milliseconds. + virtual TimeMs GetSimulationTickDeltaOverride() const = 0; + + //! A scalar amount to adjust the passage of time by, 1.0 == realtime, 0.5 == half realtime, 2.0 == doubletime. + //! @param scale The scalar value to apply to the simulation time. + virtual void SetSimulationTickScale(float scale) = 0; + + //! Returns the current simulation tick scale. + //! 1.0 == realtime, 0.5 == half realtime, 2.0 == doubletime. + //! @returns The simulation tick scale value. + virtual float GetSimulationTickScale() const = 0; + + //! The minimum rate to force the simulation tick to run. + //! 0 for as fast as possible. 30 = ~33ms, 60 = ~16ms. + //! Setting to 0 will disable rate limiting. + //! @note It is not guaranteed to hit the requested tick rate exactly. + //! @param rate The rate in frames per second. + virtual void SetSimulationTickRate(int rate) = 0; + + //! Return the current simulation tick rate. + //! 0 means disabled. + //! @return The rate in frames per second. + virtual int32_t GetSimulationTickRate() const = 0; AZ_DISABLE_COPY_MOVE(ITime); + + static const AZ::TimeMs ZeroTimeMs = AZ::TimeMs{ 0 }; + static const AZ::TimeUs ZeroTimeUs = AZ::TimeUs{ 0 }; }; // EBus wrapper for ScriptCanvas @@ -74,6 +137,29 @@ namespace AZ return AZ::Interface::Get()->GetElapsedTimeUs(); } + inline TimeMs GetRealElapsedTimeMs() + { + return AZ::Interface::Get()->GetRealElapsedTimeMs(); + } + + //! This is a simple convenience wrapper + inline TimeUs GetSimulationTickDeltaTimeUs() + { + return AZ::Interface::Get()->GetSimulationTickDeltaTimeUs(); + } + + //! This is a simple convenience wrapper + inline TimeUs GetRealTickDeltaTimeUs() + { + return AZ::Interface::Get()->GetRealTickDeltaTimeUs(); + } + + //! This is a simple convenience wrapper + inline TimeUs GetLastSimulationTickTime() + { + return AZ::Interface::Get()->GetLastSimulationTickTime(); + } + //! Converts from milliseconds to microseconds inline TimeUs TimeMsToUs(TimeMs value) { @@ -92,12 +178,24 @@ namespace AZ return static_cast(value) / 1000.0f; } + //! Converts from milliseconds to seconds + inline double TimeMsToSecondsDouble(TimeMs value) + { + return static_cast(value) / 1000.0; + } + //! Converts from microseconds to seconds inline float TimeUsToSeconds(TimeUs value) { return static_cast(value) / 1000000.0f; } + //! Converts from microseconds to seconds + inline double TimeUsToSecondsDouble(TimeUs value) + { + return static_cast(value) / 1000000.0; + } + //! Converts from milliseconds to AZStd::chrono::time_point inline auto TimeMsToChrono(TimeMs value) { @@ -113,6 +211,20 @@ namespace AZ auto chronoValue = AZStd::chrono::microseconds(aznumeric_cast(value)); return epoch + chronoValue; } + + //! A utility function to convert from seconds to TimeMs + inline TimeMs SecondsToTimeMs(const double value) + { + const double valueMs = value * 1000.0; + return static_cast(static_cast(valueMs)); + } + + //! A utility function to convert from seconds to TimeUs + inline TimeUs SecondsToTimeUs(const double value) + { + const double valueMs = value * 1000000.0; + return static_cast(static_cast(valueMs)); + } } // namespace AZ AZ_TYPE_SAFE_INTEGRAL_SERIALIZEBINDING(AZ::TimeMs); diff --git a/Code/Framework/AzCore/AzCore/Time/TimeSystem.cpp b/Code/Framework/AzCore/AzCore/Time/TimeSystem.cpp new file mode 100644 index 0000000000..cd0170749f --- /dev/null +++ b/Code/Framework/AzCore/AzCore/Time/TimeSystem.cpp @@ -0,0 +1,214 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#include +#include +#include +#include + +namespace AZ +{ + namespace + { + void cvar_t_simulationTickScale_Changed(const float& value) + { + if (auto* timeSystem = AZ::Interface::Get()) + { + timeSystem->SetSimulationTickScale(value); + } + } + + void cvar_t_simulationTickDeltaOverride_Changed(const float& value) + { + if (auto* timeSystem = AZ::Interface::Get()) + { + timeSystem->SetSimulationTickDeltaOverride(AZ::SecondsToTimeMs(value)); + } + } + + void cvar_t_simulationTickRate_Changed(const int& rate) + { + AZ_Warning("tick", false, "Simulation tick rate limiting is currently disabled. Setting will not be applied."); + if (auto* timeSystem = AZ::Interface::Get()) + { + timeSystem->SetSimulationTickRate(rate); + } + } + } // namespace + + AZ_CVAR(float, t_simulationTickScale, 1.0f, cvar_t_simulationTickScale_Changed, AZ::ConsoleFunctorFlags::Null, + "A scalar amount to adjust time passage by, 1.0 == realtime, 0.5 == half realtime, 2.0 == doubletime"); + + AZ_CVAR(float, t_simulationTickDeltaOverride, 0.0f, cvar_t_simulationTickDeltaOverride_Changed, AZ::ConsoleFunctorFlags::Null, + "If > 0, overrides the simulation tick delta time with the provided value (Seconds) and ignores any t_simulationTickScale value."); + + AZ_CVAR(int, t_simulationTickRate, 0, cvar_t_simulationTickRate_Changed, AZ::ConsoleFunctorFlags::Null, + "The minimum rate to force the game simulation tick to run. 0 for as fast as possible. 30 = ~33ms, 60 = ~16ms"); + + void TimeSystem::Reflect(AZ::ReflectContext* context) + { + if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) + { + serializeContext->Class() + ->Version(1); + } + } + + TimeSystem::TimeSystem() + { + m_lastInvokedTimeUs = static_cast(AZStd::GetTimeNowMicroSecond()); + AZ::Interface::Register(this); + ITimeRequestBus::Handler::BusConnect(); + } + + TimeSystem::~TimeSystem() + { + AZ::Interface::Unregister(this); + ITimeRequestBus::Handler::BusDisconnect(); + } + + TimeMs TimeSystem::GetElapsedTimeMs() const + { + return AZ::TimeUsToMs(GetElapsedTimeUs()); + } + + TimeUs TimeSystem::GetElapsedTimeUs() const + { + TimeUs currentTime = static_cast(AZStd::GetTimeNowMicroSecond()); + TimeUs deltaTime = currentTime - m_lastInvokedTimeUs; + + if (t_simulationTickScale != 1.0f) + { + const float floatDelta = AZStd::GetMax(static_cast(deltaTime) * t_simulationTickScale, 1.0f); + deltaTime = static_cast(static_cast(floatDelta)); + } + + m_accumulatedTimeUs += deltaTime; + m_lastInvokedTimeUs = currentTime; + + return m_accumulatedTimeUs; + } + + TimeMs TimeSystem::GetRealElapsedTimeMs() const + { + return AZ::TimeUsToMs(GetRealElapsedTimeUs()); + } + + TimeUs TimeSystem::GetRealElapsedTimeUs() const + { + return static_cast(AZStd::GetTimeNowMicroSecond()); + } + + TimeUs TimeSystem::GetSimulationTickDeltaTimeUs() const + { + return m_simulationTickDeltaTimeUs; + } + + TimeUs TimeSystem::GetRealTickDeltaTimeUs() const + { + return m_realTickDeltaTimeUs; + } + + TimeUs TimeSystem::GetLastSimulationTickTime() const + { + return m_lastSimulationTickTimeUs; + } + + TimeUs TimeSystem::AdvanceTickDeltaTimes() + { + const TimeUs currentTimeUs = static_cast(AZStd::GetTimeNowMicroSecond()); + + //real time + m_realTickDeltaTimeUs = currentTimeUs - m_lastRealTickTimeUs; + m_lastRealTickTimeUs = currentTimeUs; + + //game time + if (m_simulationTickDeltaOverride > AZ::Time::ZeroTimeUs) + { + m_simulationTickDeltaTimeUs = m_simulationTickDeltaOverride; + m_lastSimulationTickTimeUs = m_simulationTickDeltaTimeUs; + return m_simulationTickDeltaTimeUs; + } + + m_simulationTickDeltaTimeUs = currentTimeUs - m_lastSimulationTickTimeUs; + + if (!AZ::IsClose(t_simulationTickScale, 1.0f)) + { + const double floatDelta = AZStd::GetMax(static_cast(m_simulationTickDeltaTimeUs) * static_cast(t_simulationTickScale), 1.0); + m_simulationTickDeltaTimeUs = static_cast(static_cast(floatDelta)); + } + m_lastSimulationTickTimeUs = currentTimeUs; + + return m_simulationTickDeltaTimeUs; + } + + void TimeSystem::ApplyTickRateLimiterIfNeeded() + { + // Currently disabling the Tick rate limiter as there are some reported issues when using it. + #ifdef ENABLE_TICK_RATE_LIMITER + // If tick rate limiting is on, ensure (1 / t_simulationTickRate) ms has elapsed since the last frame, + // sleeping if there's still time remaining. + if (t_simulationTickRate > 0) + { + const TimeUs currentTimeUs = AZ::GetRealElapsedTimeUs(); + const TimeUs timeUntilNextTick = (m_lastSimulationTickTimeUs + m_simulationTickLimitTimeUs) - currentTimeUs; + if (timeUntilNextTick > AZ::Time::ZeroTimeUs) + { + AZ_TracePrintf("tick", "Sleeping for %.2f", AZ::TimeUsToSecondsDouble(timeUntilNextTick)); + AZStd::this_thread::sleep_for(AZStd::chrono::microseconds(static_cast(timeUntilNextTick))); + } + } + #endif // #ifdef ENABLE_TICK_RATE_LIMITER + } + + void TimeSystem::SetSimulationTickDeltaOverride(TimeMs timeMs) + { + const TimeUs timeUs = AZ::TimeMsToUs(timeMs); + if (timeUs != m_simulationTickDeltaOverride) + { + m_simulationTickDeltaOverride = timeUs; + t_simulationTickDeltaOverride = AZ::TimeUsToSeconds(timeUs); //update the cvar + } + } + + TimeMs TimeSystem::GetSimulationTickDeltaOverride() const + { + return AZ::TimeUsToMs(m_simulationTickDeltaOverride); + } + + void TimeSystem::SetSimulationTickScale(float scale) + { + if (!AZ::IsClose(scale, t_simulationTickScale)) + { + t_simulationTickScale = scale; + } + } + + float TimeSystem::GetSimulationTickScale() const + { + return t_simulationTickScale; + } + + void TimeSystem::SetSimulationTickRate(int rate) + { + m_simulationTickLimitRate = AZStd::abs(rate); + if (m_simulationTickLimitRate != 0) + { + m_simulationTickLimitTimeUs = AZ::SecondsToTimeUs(1.0f / m_simulationTickLimitRate); + } + else + { + m_simulationTickLimitTimeUs = AZ::Time::ZeroTimeUs; + } + } + + int32_t TimeSystem::GetSimulationTickRate() const + { + return m_simulationTickLimitRate; + } +} // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/Time/TimeSystem.h b/Code/Framework/AzCore/AzCore/Time/TimeSystem.h new file mode 100644 index 0000000000..d2587c76d8 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/Time/TimeSystem.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ + +#pragma once + +#include +#include + +namespace AZ +{ + class ReflectContext; + + //! Implementation of the ITime system interface. + class TimeSystem + : public ITimeRequestBus::Handler + { + public: + AZ_RTTI(AZ::TimeSystem, "{CE1C5E4F-7DC1-4248-B10C-AC55E8924A48}", AZ::ITime); + + static void Reflect(AZ::ReflectContext* context); + + TimeSystem(); + virtual ~TimeSystem(); + + //! ITime overrides. + //! @{ + TimeMs GetElapsedTimeMs() const override; + TimeUs GetElapsedTimeUs() const override; + TimeMs GetRealElapsedTimeMs() const override; + TimeUs GetRealElapsedTimeUs() const override; + TimeUs GetSimulationTickDeltaTimeUs() const override; + TimeUs GetRealTickDeltaTimeUs() const override; + TimeUs GetLastSimulationTickTime() const override; + void SetSimulationTickDeltaOverride(TimeMs timeMs) override; + TimeMs GetSimulationTickDeltaOverride() const override; + void SetSimulationTickScale(float scale) override; + float GetSimulationTickScale() const override; + void SetSimulationTickRate(int rate) override; + int32_t GetSimulationTickRate() const override; + //! @} + + //! Advances the Simulation and Real tick delta time counters. + //! This is called from the owner of the TimeSystem, ComponentApplication in Tick(). + //! @return The delta in microseconds from the last call to AdvanceTickDeltaTimes(). Value will be the same as GetSimulationTickDeltaTimeUs(). + TimeUs AdvanceTickDeltaTimes(); + + //! If t_simulationTickRate is >0 this will try to have the game delta time run at a maximum of the rate set. + //! This is called from the owner of the TimeSystem, ComponentApplication in Tick(). + //! example. If t_simulationTickRate is set to 60Fps, and the game tick delta is <17ms(60fps), this will add a sleep for the remaining time. + //! example. If t_simulationTickRate is set to 60Fps, and the game tick delta is >=17ms(60fps), this will not sleep at all. + //! @note It is not guaranteed to hit the requested tick rate exactly. + void ApplyTickRateLimiterIfNeeded(); + private: + //! Used to calculate the delta time between calls to GetElapsedTimeMs/TimeUs(). + //! Mutable to allow GetElapsedTimeMs/TimeUs() to be a const functions. + mutable TimeUs m_lastInvokedTimeUs = AZ::Time::ZeroTimeUs; + + //! Accumulates the delta time of GetElapsedTimeMs/TimeUs() calls. + //! Mutable to allow GetElapsedTimeMs/TimeUs() to be a const functions. + mutable TimeUs m_accumulatedTimeUs = AZ::Time::ZeroTimeUs; + + //! The current game tick delta time. + //! Can be affected by time system cvars. + //! Updated in AdvanceTickDeltaTimes(). + TimeUs m_simulationTickDeltaTimeUs = AZ::Time::ZeroTimeUs; + + //! The current real tick delta time. + //! Will not be affected by time system cvars. + //! Updated in AdvanceTickDeltaTimes(). + TimeUs m_realTickDeltaTimeUs = AZ::Time::ZeroTimeUs; + + TimeUs m_lastSimulationTickTimeUs = AZ::Time::ZeroTimeUs; //!< Used to determine the game tick delta time (affected by cvars). + TimeUs m_lastRealTickTimeUs = AZ::Time::ZeroTimeUs; //!< Used to determine the real game tick delta time (not affected by cvars). + + TimeUs m_simulationTickDeltaOverride = AZ::Time::ZeroTimeUs; // -#include -#include - -namespace AZ -{ - AZ_CVAR(float, t_scale, 1.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "A scalar amount to adjust time passage by, 1.0 == realtime, 0.5 == half realtime, 2.0 == doubletime"); - - void TimeSystemComponent::Reflect(AZ::ReflectContext* context) - { - if (AZ::SerializeContext* serializeContext = azrtti_cast(context)) - { - serializeContext->Class() - ->Version(1); - } - } - - void TimeSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided) - { - provided.push_back(AZ_CRC_CE("TimeService")); - } - - void TimeSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible) - { - incompatible.push_back(AZ_CRC_CE("TimeService")); - } - - TimeSystemComponent::TimeSystemComponent() - { - m_lastInvokedTimeUs = static_cast(AZStd::GetTimeNowMicroSecond()); - AZ::Interface::Register(this); - ITimeRequestBus::Handler::BusConnect(); - } - - TimeSystemComponent::~TimeSystemComponent() - { - ITimeRequestBus::Handler::BusDisconnect(); - AZ::Interface::Unregister(this); - } - - void TimeSystemComponent::Activate() - { - ; - } - - void TimeSystemComponent::Deactivate() - { - ; - } - - TimeMs TimeSystemComponent::GetElapsedTimeMs() const - { - return TimeUsToMs(GetElapsedTimeUs()); - } - - TimeUs TimeSystemComponent::GetElapsedTimeUs() const - { - TimeUs currentTime = static_cast(AZStd::GetTimeNowMicroSecond()); - TimeUs deltaTime = currentTime - m_lastInvokedTimeUs; - - if (t_scale != 1.0f) - { - float floatDelta = static_cast(deltaTime) * t_scale; - deltaTime = static_cast(static_cast(floatDelta)); - } - - m_accumulatedTimeUs += deltaTime; - m_lastInvokedTimeUs = currentTime; - - return m_accumulatedTimeUs; - } -} diff --git a/Code/Framework/AzCore/AzCore/Time/TimeSystemComponent.h b/Code/Framework/AzCore/AzCore/Time/TimeSystemComponent.h deleted file mode 100644 index 3ab3dbc234..0000000000 --- a/Code/Framework/AzCore/AzCore/Time/TimeSystemComponent.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - -#pragma once - -#include -#include -#include - -namespace AZ -{ - //! Implementation of the ITime system interface. - class TimeSystemComponent - : public AZ::Component - , public ITimeRequestBus::Handler - { - public: - - AZ_COMPONENT(TimeSystemComponent, "{CE1C5E4F-7DC1-4248-B10C-AC55E8924A48}"); - - static void Reflect(AZ::ReflectContext* context); - static void GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& provided); - static void GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& incompatible); - - TimeSystemComponent(); - virtual ~TimeSystemComponent(); - - //! AZ::Component overrides. - //! @{ - void Activate() override; - void Deactivate() override; - //! @} - - //! ITime overrides. - //! @{ - TimeMs GetElapsedTimeMs() const override; - TimeUs GetElapsedTimeUs() const override; - //! @} - - private: - - mutable TimeUs m_lastInvokedTimeUs = TimeUs{0}; - mutable TimeUs m_accumulatedTimeUs = TimeUs{0}; - }; -} diff --git a/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockITime.h b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockITime.h new file mode 100644 index 0000000000..3d31056e27 --- /dev/null +++ b/Code/Framework/AzCore/AzCore/UnitTest/Mocks/MockITime.h @@ -0,0 +1,119 @@ +/* + * Copyright (c) Contributors to the Open 3D Engine Project. + * For complete copyright and license terms please see the LICENSE at the root of this distribution. + * + * SPDX-License-Identifier: Apache-2.0 OR MIT + * + */ +#pragma once + +#include +#include + +namespace AZ +{ + class MockTimeSystem; + using NiceTimeSystemMock =::testing::NiceMock; + + //used if you wish to mock any of the Get time functions. + class MockTimeSystem + : public ITimeRequestBus::Handler + { + public: + MockTimeSystem() + { + AZ::Interface::Register(this); + ITimeRequestBus::Handler::BusConnect(); + } + virtual ~MockTimeSystem() + { + AZ::Interface::Unregister(this); + ITimeRequestBus::Handler::BusDisconnect(); + } + + MOCK_CONST_METHOD0(GetElapsedTimeMs, TimeMs()); + MOCK_CONST_METHOD0(GetElapsedTimeUs, TimeUs()); + MOCK_CONST_METHOD0(GetRealElapsedTimeMs, TimeMs()); + MOCK_CONST_METHOD0(GetRealElapsedTimeUs, TimeUs()); + MOCK_CONST_METHOD0(GetSimulationTickDeltaTimeUs, TimeUs()); + MOCK_CONST_METHOD0(GetRealTickDeltaTimeUs, TimeUs()); + MOCK_CONST_METHOD0(GetLastSimulationTickTime, TimeUs()); + MOCK_METHOD1(SetSimulationTickDeltaOverride, void(TimeMs)); + MOCK_CONST_METHOD0(GetSimulationTickDeltaOverride, TimeMs()); + MOCK_METHOD1(SetSimulationTickScale, void(float)); + MOCK_CONST_METHOD0(GetSimulationTickScale, float()); + MOCK_METHOD1(SetSimulationTickRate, void(int)); + MOCK_CONST_METHOD0(GetSimulationTickRate, int32_t()); + }; + + //used if you wish to override any of the Get time functions with specific functionality. + class StubTimeSystem + : public AZ::TimeSystem + { + public: + AZ_RTTI(AZ::StubTimeSystem, "{DD5D5A6A-345F-49FD-A61E-A40E63C49CFA}", AZ::TimeSystem); + + virtual AZ::TimeMs GetElapsedTimeMs() const override + { + return AZ::Time::ZeroTimeMs; + } + + virtual AZ::TimeUs GetElapsedTimeUs() const override + { + return AZ::Time::ZeroTimeUs; + } + + virtual AZ::TimeMs GetRealElapsedTimeMs() const override + { + return AZ::Time::ZeroTimeMs; + } + + virtual AZ::TimeUs GetRealElapsedTimeUs() const override + { + return AZ::Time::ZeroTimeUs; + } + + virtual AZ::TimeUs GetSimulationTickDeltaTimeUs() const override + { + return AZ::Time::ZeroTimeUs; + } + + virtual AZ::TimeUs GetRealTickDeltaTimeUs() const override + { + return AZ::Time::ZeroTimeUs; + } + + virtual AZ::TimeUs GetLastSimulationTickTime() const override + { + return AZ::Time::ZeroTimeUs; + } + + virtual void SetSimulationTickDeltaOverride([[maybe_unused]]TimeMs timeMs) override + { + } + + virtual TimeMs GetSimulationTickDeltaOverride() const override + { + return AZ::Time::ZeroTimeMs; + } + + virtual void SetSimulationTickScale([[maybe_unused]] float scale) override + { + } + + virtual float GetSimulationTickScale() const override + { + return 1.0f; + } + + virtual void SetSimulationTickRate([[maybe_unused]] int rate) override + { + } + + virtual int32_t GetSimulationTickRate() const override + { + return 0; + } + }; + +} // namespace AZ diff --git a/Code/Framework/AzCore/AzCore/azcore_files.cmake b/Code/Framework/AzCore/AzCore/azcore_files.cmake index a5cc3fdcd4..30662f37c4 100644 --- a/Code/Framework/AzCore/AzCore/azcore_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcore_files.cmake @@ -654,8 +654,8 @@ set(FILES Threading/ThreadUtils.h Threading/ThreadUtils.cpp Time/ITime.h - Time/TimeSystemComponent.cpp - Time/TimeSystemComponent.h + Time/TimeSystem.cpp + Time/TimeSystem.h ) # Prevent the following files from being grouped in UNITY builds diff --git a/Code/Framework/AzCore/AzCore/azcoretestcommon_files.cmake b/Code/Framework/AzCore/AzCore/azcoretestcommon_files.cmake index 6c25641f9f..e31dc803b9 100644 --- a/Code/Framework/AzCore/AzCore/azcoretestcommon_files.cmake +++ b/Code/Framework/AzCore/AzCore/azcoretestcommon_files.cmake @@ -12,5 +12,6 @@ set(FILES UnitTest/UnitTest.h UnitTest/TestTypes.h UnitTest/Mocks/MockFileIOBase.h + UnitTest/Mocks/MockITime.h UnitTest/Mocks/MockSettingsRegistry.h ) diff --git a/Code/Framework/AzCore/Tests/Debug.cpp b/Code/Framework/AzCore/Tests/Debug.cpp index 0d6e1a51e0..bd90611af3 100644 --- a/Code/Framework/AzCore/Tests/Debug.cpp +++ b/Code/Framework/AzCore/Tests/Debug.cpp @@ -6,7 +6,6 @@ * */ -#include #include #include #include diff --git a/Code/Framework/AzCore/Tests/EBus/ScheduledEventTests.cpp b/Code/Framework/AzCore/Tests/EBus/ScheduledEventTests.cpp index ec9a09fb09..b9c690edcc 100644 --- a/Code/Framework/AzCore/Tests/EBus/ScheduledEventTests.cpp +++ b/Code/Framework/AzCore/Tests/EBus/ScheduledEventTests.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include @@ -26,22 +26,22 @@ namespace UnitTest SetupAllocator(); AZ::NameDictionary::Create(); - m_loggerComponent = new AZ::LoggerSystemComponent; - m_timeComponent = new AZ::TimeSystemComponent; - m_eventSchedulerComponent = new AZ::EventSchedulerSystemComponent; + m_loggerComponent = AZStd::make_unique(); + m_timeSystem = AZStd::make_unique(); + m_eventSchedulerComponent = AZStd::make_unique(); - m_testEvent = new AZ::ScheduledEvent([this] { TestBasicEvent(); }, AZ::Name("UnitTestEvent fire once event")); - m_testRequeue = new AZ::ScheduledEvent([this] { TestAutoRequeuedEvent(); }, AZ::Name("UnitTestEvent auto Requeue")); + m_testEvent = AZStd::make_unique([this] { TestBasicEvent(); }, AZ::Name("UnitTestEvent fire once event")); + m_testRequeue = AZStd::make_unique([this] { TestAutoRequeuedEvent(); }, AZ::Name("UnitTestEvent auto Requeue")); } void TearDown() override { - delete m_testEvent; - delete m_testRequeue; + m_testEvent.reset(); + m_testRequeue.reset(); - delete m_eventSchedulerComponent; - delete m_timeComponent; - delete m_loggerComponent; + m_eventSchedulerComponent.reset(); + m_timeSystem.reset(); + m_loggerComponent.reset(); AZ::NameDictionary::Destroy(); TeardownAllocator(); @@ -60,12 +60,12 @@ namespace UnitTest uint32_t m_basicEventTriggerCount = 0; uint32_t m_requeuedEventTriggerCount = 0; - AZ::ScheduledEvent* m_testEvent = nullptr; - AZ::ScheduledEvent* m_testRequeue = nullptr; + AZStd::unique_ptr m_testEvent; + AZStd::unique_ptr m_testRequeue; - AZ::LoggerSystemComponent* m_loggerComponent = nullptr; - AZ::TimeSystemComponent* m_timeComponent = nullptr; - AZ::EventSchedulerSystemComponent* m_eventSchedulerComponent = nullptr; + AZStd::unique_ptr m_loggerComponent; + AZStd::unique_ptr m_timeSystem; + AZStd::unique_ptr m_eventSchedulerComponent; }; TEST_F(ScheduledEventTests, TestFireOnce) diff --git a/Code/Framework/AzCore/Tests/Time/TimeTests.cpp b/Code/Framework/AzCore/Tests/Time/TimeTests.cpp index 6727ef1501..7ba01ec0e0 100644 --- a/Code/Framework/AzCore/Tests/Time/TimeTests.cpp +++ b/Code/Framework/AzCore/Tests/Time/TimeTests.cpp @@ -6,7 +6,7 @@ * */ -#include +#include #include namespace UnitTest @@ -18,16 +18,16 @@ namespace UnitTest void SetUp() override { SetupAllocator(); - m_timeComponent = new AZ::TimeSystemComponent; + m_timeSystem = AZStd::make_unique(); } void TearDown() override { - delete m_timeComponent; + m_timeSystem.reset(); TeardownAllocator(); } - AZ::TimeSystemComponent* m_timeComponent = nullptr; + AZStd::unique_ptr m_timeSystem; }; TEST_F(TimeTests, TestConversionUsToMs) @@ -44,6 +44,30 @@ namespace UnitTest EXPECT_EQ(timeUs, AZ::TimeUs{ 1000000 }); } + TEST_F(TimeTests, TestConversionTimeMsToSeconds) + { + AZ::TimeMs timeMs = AZ::TimeMs{ 1000 }; + float timeSecondsFloat = AZ::TimeMsToSeconds(timeMs); + EXPECT_TRUE(AZ::IsClose(timeSecondsFloat, 1.0f)); + + double timeSecondsDouble = AZ::TimeMsToSecondsDouble(timeMs); + EXPECT_TRUE(AZ::IsClose(timeSecondsDouble, 1.0)); + } + + TEST_F(TimeTests, TestConversionSecondsToTimeUs) + { + double seconds = 1.0; + AZ::TimeUs timeUs = AZ::SecondsToTimeUs(seconds); + EXPECT_EQ(timeUs, AZ::TimeUs{ 1000000 }); + } + + TEST_F(TimeTests, TestConversionSecondsToTimeMs) + { + double seconds = 1.0; + AZ::TimeMs timeMs = AZ::SecondsToTimeMs(seconds); + EXPECT_EQ(timeMs, AZ::TimeMs{ 1000 }); + } + TEST_F(TimeTests, TestClocks) { AZ::TimeUs timeUs = AZ::GetElapsedTimeUs(); diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp index 768ef1f0b6..b3521a877f 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.cpp +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.cpp @@ -553,11 +553,9 @@ namespace AzFramework //////////////////////////////////////////////////////////////////////////// - AZ_CVAR(float, t_frameTimeOverride, 0.0f, nullptr, AZ::ConsoleFunctorFlags::Null, "If > 0, overrides the application delta frame-time with the provided value"); - - void Application::Tick(float deltaOverride /*= -1.f*/) + void Application::Tick() { - ComponentApplication::Tick((t_frameTimeOverride > 0.0f) ? t_frameTimeOverride : deltaOverride); + ComponentApplication::Tick(); } //////////////////////////////////////////////////////////////////////////// diff --git a/Code/Framework/AzFramework/AzFramework/Application/Application.h b/Code/Framework/AzFramework/AzFramework/Application/Application.h index a318ede4a2..27144e4376 100644 --- a/Code/Framework/AzFramework/AzFramework/Application/Application.h +++ b/Code/Framework/AzFramework/AzFramework/Application/Application.h @@ -87,7 +87,7 @@ namespace AzFramework */ virtual void Stop(); - void Tick(float deltaOverride = -1.f) override; + void Tick() override; AZ::ComponentTypeList GetRequiredSystemComponents() const override; diff --git a/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/ConnectionMetrics.cpp b/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/ConnectionMetrics.cpp index 3a3ab06d02..6705ec8b36 100644 --- a/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/ConnectionMetrics.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/ConnectionMetrics.cpp @@ -42,7 +42,7 @@ namespace AzNetworking { const uint32_t sampleAtom = 1 - m_activeAtom; - if (m_atoms[sampleAtom].m_timeAccumulatorMs == AZ::TimeMs{0}) + if (m_atoms[sampleAtom].m_timeAccumulatorMs == AZ::Time::ZeroTimeMs) { return 0.0f; } diff --git a/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/ConnectionMetrics.h b/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/ConnectionMetrics.h index b576c64e86..19db52b979 100644 --- a/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/ConnectionMetrics.h +++ b/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/ConnectionMetrics.h @@ -19,7 +19,7 @@ namespace AzNetworking { DatarateAtom() = default; - AZ::TimeMs m_timeAccumulatorMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_timeAccumulatorMs = AZ::Time::ZeroTimeMs; uint32_t m_bytesTransmitted = 0; uint32_t m_packetsSent = 0; uint32_t m_packetsLost = 0; @@ -78,7 +78,7 @@ namespace AzNetworking ConnectionPacketEntry(PacketId packetId, AZ::TimeMs sendTimeMs); PacketId m_packetId = InvalidPacketId; - AZ::TimeMs m_sendTimeMs = AZ::TimeMs{0}; + AZ::TimeMs m_sendTimeMs = AZ::Time::ZeroTimeMs; }; //! @class ConnectionComputeRtt diff --git a/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/IConnection.h b/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/IConnection.h index 363fd1d37b..7afbbaee7c 100644 --- a/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/IConnection.h +++ b/Code/Framework/AzNetworking/AzNetworking/ConnectionLayer/IConnection.h @@ -28,8 +28,8 @@ namespace AzNetworking ConnectionQuality(int32_t lossPercentage, AZ::TimeMs latencyMs, AZ::TimeMs varianceMs); int32_t m_lossPercentage = 0; - AZ::TimeMs m_latencyMs = AZ::TimeMs{ 0 }; - AZ::TimeMs m_varianceMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_latencyMs = AZ::Time::ZeroTimeMs; + AZ::TimeMs m_varianceMs = AZ::Time::ZeroTimeMs; }; enum class TrustZone diff --git a/Code/Framework/AzNetworking/AzNetworking/DataStructures/TimeoutQueue.h b/Code/Framework/AzNetworking/AzNetworking/DataStructures/TimeoutQueue.h index 097e45c960..1a4423144f 100644 --- a/Code/Framework/AzNetworking/AzNetworking/DataStructures/TimeoutQueue.h +++ b/Code/Framework/AzNetworking/AzNetworking/DataStructures/TimeoutQueue.h @@ -37,8 +37,8 @@ namespace AzNetworking void UpdateTimeoutTime(AZ::TimeMs currentTimeMs); uint64_t m_userData = 0; - AZ::TimeMs m_timeoutMs = AZ::TimeMs{0}; - AZ::TimeMs m_nextTimeoutTimeMs = AZ::TimeMs{0}; + AZ::TimeMs m_timeoutMs = AZ::Time::ZeroTimeMs; + AZ::TimeMs m_nextTimeoutTimeMs = AZ::Time::ZeroTimeMs; }; TimeoutQueue() = default; diff --git a/Code/Framework/AzNetworking/AzNetworking/Framework/NetworkInterfaceMetrics.h b/Code/Framework/AzNetworking/AzNetworking/Framework/NetworkInterfaceMetrics.h index 8cad6e5537..d4bfabf54a 100644 --- a/Code/Framework/AzNetworking/AzNetworking/Framework/NetworkInterfaceMetrics.h +++ b/Code/Framework/AzNetworking/AzNetworking/Framework/NetworkInterfaceMetrics.h @@ -15,11 +15,11 @@ namespace AzNetworking struct NetworkInterfaceMetrics { //! Returns the total number of milliseconds spent updating this network interface. - AZ::TimeMs m_updateTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_updateTimeMs = AZ::Time::ZeroTimeMs; //! Returns the total number of connections bound to this network interface. uint64_t m_connectionCount = 0; //! Returns the total number of milliseconds spent sending data on this network interface. - AZ::TimeMs m_sendTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_sendTimeMs = AZ::Time::ZeroTimeMs; //! Returns the total number of packets sent on this socket. uint64_t m_sendPackets = 0; //! Returns the total number of encrypted packets sent on this socket. @@ -37,7 +37,7 @@ namespace AzNetworking //! Returns the total number of packets that had to be resent on this network interface due to packet loss. uint64_t m_resentPackets = 0; //! Returns the total number of milliseconds spent processing received data on this network interface. - AZ::TimeMs m_recvTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_recvTimeMs = AZ::Time::ZeroTimeMs; //! Returns the total number of packets received on this socket. uint64_t m_recvPackets = 0; //! Returns the total number of bytes received on this socket after compression. diff --git a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpListenThread.h b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpListenThread.h index 0859e1d0f7..f2dc88cab4 100644 --- a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpListenThread.h +++ b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpListenThread.h @@ -67,6 +67,6 @@ namespace AzNetworking uint32_t m_listenPortCount = 0; TcpSocketManager m_tcpSocketManager; AZ::ThreadSafeDeque m_listenPorts; - AZ::TimeMs m_updateTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_updateTimeMs = AZ::Time::ZeroTimeMs; }; } diff --git a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.cpp b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.cpp index 0278856ce9..18ce25c4dd 100644 --- a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.cpp @@ -107,7 +107,7 @@ namespace AzNetworking auto readCallback = [this, startTimeMs](SocketFd socketFd) { HandleConnectionRecv(socketFd, startTimeMs); }; auto writeCallback = [this](SocketFd socketFd) { HandleConnectionSend(socketFd); }; - m_tcpSocketManager.ProcessEvents(AZ::TimeMs{ 0 }, readCallback, writeCallback); + m_tcpSocketManager.ProcessEvents(AZ::Time::ZeroTimeMs, readCallback, writeCallback); FlushQueuedRemoves(); diff --git a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.h b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.h index 8d45e847a8..d483a89cf3 100644 --- a/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.h +++ b/Code/Framework/AzNetworking/AzNetworking/TcpTransport/TcpNetworkInterface.h @@ -146,7 +146,7 @@ namespace AzNetworking AZ::Name m_name; TrustZone m_trustZone; uint16_t m_port = 0; - AZ::TimeMs m_timeoutMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_timeoutMs = AZ::Time::ZeroTimeMs; IConnectionListener& m_connectionListener; TcpConnectionSet m_connectionSet; TcpSocketManager m_tcpSocketManager; diff --git a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.cpp b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.cpp index b810c7a347..1ca5922753 100644 --- a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.cpp @@ -736,7 +736,7 @@ namespace AzNetworking udpConnection->SendUnreliablePacket(CorePackets::HeartbeatPacket(true)); ++udpConnection->m_timeoutCounter; } - else if (net_UdpTimeoutConnections && (GetTimeoutMs() > AZ::TimeMs{ 0 })) + else if (net_UdpTimeoutConnections && (GetTimeoutMs() > AZ::Time::ZeroTimeMs)) { udpConnection->Disconnect(DisconnectReason::Timeout, TerminationEndpoint::Local); return TimeoutResult::Delete; diff --git a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.h b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.h index e6abeded0d..a640a6e3b8 100644 --- a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.h +++ b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpNetworkInterface.h @@ -171,7 +171,7 @@ namespace AzNetworking TrustZone m_trustZone; uint16_t m_port = 0; bool m_allowIncomingConnections = false; - AZ::TimeMs m_timeoutMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_timeoutMs = AZ::Time::ZeroTimeMs; IConnectionListener& m_connectionListener; UdpConnectionSet m_connectionSet; TimeoutQueue m_connectionTimeoutQueue; diff --git a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpReaderThread.h b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpReaderThread.h index e0c97f157f..1d25a9e6e1 100644 --- a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpReaderThread.h +++ b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpReaderThread.h @@ -94,6 +94,6 @@ namespace AzNetworking int32_t m_backIndex = 0; AZStd::array m_readerBuffers; AZStd::vector m_pendingAdds; - AZ::TimeMs m_updateTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_updateTimeMs = AZ::Time::ZeroTimeMs; }; } diff --git a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpSocket.cpp b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpSocket.cpp index 300b3527fa..85cc3a38f8 100644 --- a/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpSocket.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/UdpTransport/UdpSocket.cpp @@ -135,7 +135,7 @@ namespace AzNetworking int32_t sentBytes = size; #ifdef ENABLE_LATENCY_DEBUG - if (connectionQuality.m_latencyMs <= AZ::TimeMs{ 0 }) + if (connectionQuality.m_latencyMs <= AZ::Time::ZeroTimeMs) #endif { sentBytes = SendInternal(address, data, size, encrypt, dtlsEndpoint); @@ -153,9 +153,9 @@ namespace AzNetworking } } #ifdef ENABLE_LATENCY_DEBUG - else if ((connectionQuality.m_latencyMs > AZ::TimeMs{ 0 }) || (connectionQuality.m_varianceMs > AZ::TimeMs{ 0 })) + else if ((connectionQuality.m_latencyMs > AZ::Time::ZeroTimeMs) || (connectionQuality.m_varianceMs > AZ::Time::ZeroTimeMs)) { - const AZ::TimeMs jitterMs = aznumeric_cast(m_random.GetRandom()) % (connectionQuality.m_varianceMs > AZ::TimeMs{ 0 } + const AZ::TimeMs jitterMs = aznumeric_cast(m_random.GetRandom()) % (connectionQuality.m_varianceMs > AZ::Time::ZeroTimeMs ? connectionQuality.m_varianceMs : AZ::TimeMs{ 1 }); const AZ::TimeMs deferTimeMs = (connectionQuality.m_latencyMs) + jitterMs; diff --git a/Code/Framework/AzNetworking/AzNetworking/Utilities/EncryptionCommon.cpp b/Code/Framework/AzNetworking/AzNetworking/Utilities/EncryptionCommon.cpp index 9f496c3e0c..0903205eb8 100644 --- a/Code/Framework/AzNetworking/AzNetworking/Utilities/EncryptionCommon.cpp +++ b/Code/Framework/AzNetworking/AzNetworking/Utilities/EncryptionCommon.cpp @@ -94,7 +94,7 @@ namespace AzNetworking static const uint32_t MaxCookieHistory = 8; static bool g_encryptionInitialized = false; static int32_t g_azNetworkingTrustDataIndex = 0; - static AZ::TimeMs g_lastCookieTimestamp = AZ::TimeMs{0}; + static AZ::TimeMs g_lastCookieTimestamp = AZ::Time::ZeroTimeMs; static uint64_t g_validCookieArray[MaxCookieHistory]; static uint32_t g_cookieReplaceIndex = 0; diff --git a/Code/Framework/AzNetworking/Tests/Serialization/DeltaSerializerTests.cpp b/Code/Framework/AzNetworking/Tests/Serialization/DeltaSerializerTests.cpp index 32562d9940..4ad9412849 100644 --- a/Code/Framework/AzNetworking/Tests/Serialization/DeltaSerializerTests.cpp +++ b/Code/Framework/AzNetworking/Tests/Serialization/DeltaSerializerTests.cpp @@ -15,7 +15,7 @@ namespace UnitTest { AzNetworking::PacketId m_packetId = AzNetworking::InvalidPacketId; uint32_t m_id = 0; - AZ::TimeMs m_timeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_timeMs = AZ::Time::ZeroTimeMs; float m_blendFactor = 0.f; AZStd::vector m_growVector, m_shrinkVector; diff --git a/Code/Framework/AzNetworking/Tests/TcpTransport/TcpTransportTests.cpp b/Code/Framework/AzNetworking/Tests/TcpTransport/TcpTransportTests.cpp index 77632da572..d3a956bef3 100644 --- a/Code/Framework/AzNetworking/Tests/TcpTransport/TcpTransportTests.cpp +++ b/Code/Framework/AzNetworking/Tests/TcpTransport/TcpTransportTests.cpp @@ -11,7 +11,7 @@ #include #include #include -#include +#include #include #include @@ -102,24 +102,24 @@ namespace UnitTest SetupAllocator(); AZ::NameDictionary::Create(); - m_loggerComponent = new AZ::LoggerSystemComponent; - m_timeComponent = new AZ::TimeSystemComponent; - m_networkingSystemComponent = new AzNetworking::NetworkingSystemComponent; + m_loggerComponent = AZStd::make_unique(); + m_timeSystem = AZStd::make_unique(); + m_networkingSystemComponent = AZStd::make_unique(); } void TearDown() override { - delete m_networkingSystemComponent; - delete m_timeComponent; - delete m_loggerComponent; + m_networkingSystemComponent.reset(); + m_timeSystem.reset(); + m_loggerComponent.reset(); AZ::NameDictionary::Destroy(); TeardownAllocator(); } - AZ::LoggerSystemComponent* m_loggerComponent; - AZ::TimeSystemComponent* m_timeComponent; - AzNetworking::NetworkingSystemComponent* m_networkingSystemComponent; + AZStd::unique_ptr m_loggerComponent; + AZStd::unique_ptr m_timeSystem; + AZStd::unique_ptr m_networkingSystemComponent; }; #if AZ_TRAIT_DISABLE_FAILED_NETWORKING_TESTS diff --git a/Code/Framework/AzNetworking/Tests/UdpTransport/UdpTransportTests.cpp b/Code/Framework/AzNetworking/Tests/UdpTransport/UdpTransportTests.cpp index 65c2cfa2b5..821c261fab 100644 --- a/Code/Framework/AzNetworking/Tests/UdpTransport/UdpTransportTests.cpp +++ b/Code/Framework/AzNetworking/Tests/UdpTransport/UdpTransportTests.cpp @@ -14,7 +14,7 @@ #include #include #include -#include +#include #include #include @@ -105,24 +105,24 @@ namespace UnitTest SetupAllocator(); AZ::NameDictionary::Create(); - m_loggerComponent = new AZ::LoggerSystemComponent; - m_timeComponent = new AZ::TimeSystemComponent; - m_networkingSystemComponent = new AzNetworking::NetworkingSystemComponent; + m_loggerComponent = AZStd::make_unique(); + m_timeSystem = AZStd::make_unique(); + m_networkingSystemComponent = AZStd::make_unique(); } void TearDown() override { - delete m_networkingSystemComponent; - delete m_timeComponent; - delete m_loggerComponent; + m_networkingSystemComponent.reset(); + m_timeSystem.reset(); + m_loggerComponent.reset(); AZ::NameDictionary::Destroy(); TeardownAllocator(); } - AZ::LoggerSystemComponent* m_loggerComponent; - AZ::TimeSystemComponent* m_timeComponent; - AzNetworking::NetworkingSystemComponent* m_networkingSystemComponent; + AZStd::unique_ptr m_loggerComponent; + AZStd::unique_ptr m_timeSystem; + AZStd::unique_ptr m_networkingSystemComponent; }; TEST_F(UdpTransportTests, PacketIdWrap) diff --git a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/LegacyFramework/UIFramework.cpp b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/LegacyFramework/UIFramework.cpp index 98e06b77f3..26234f47e2 100644 --- a/Code/Framework/AzToolsFramework/AzToolsFramework/UI/LegacyFramework/UIFramework.cpp +++ b/Code/Framework/AzToolsFramework/AzToolsFramework/UI/LegacyFramework/UIFramework.cpp @@ -362,23 +362,11 @@ namespace AzToolsFramework // Tick the component app. AZ::ComponentApplication* pApp = nullptr; EBUS_EVENT_RESULT(pApp, AZ::ComponentApplicationBus, GetApplication); - if (pApp) + if (pApp && m_ptrTicker) { - AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now(); - static AZStd::chrono::system_clock::time_point lastUpdate = now; - - AZStd::chrono::duration delta = now - lastUpdate; - float deltaTime = delta.count(); - - lastUpdate = now; - - if (m_ptrTicker) - { - AZ::SystemTickBus::ExecuteQueuedEvents(); - AZ::SystemTickBus::Broadcast(&AZ::SystemTickEvents::OnSystemTick); - pApp->Tick(deltaTime); - } - + AZ::SystemTickBus::ExecuteQueuedEvents(); + AZ::SystemTickBus::Broadcast(&AZ::SystemTickEvents::OnSystemTick); + pApp->Tick(); } m_bTicking = false; diff --git a/Code/LauncherUnified/Launcher.cpp b/Code/LauncherUnified/Launcher.cpp index 1a87626e35..ed01a67f39 100644 --- a/Code/LauncherUnified/Launcher.cpp +++ b/Code/LauncherUnified/Launcher.cpp @@ -26,7 +26,6 @@ #include #include -#include #include #include @@ -113,7 +112,7 @@ namespace } // Update the AzFramework application tick bus - gameApplication.Tick(gEnv->pTimer->GetFrameTime()); + gameApplication.Tick(); // Post-update CrySystem if (system) diff --git a/Code/Legacy/CryCommon/ISystem.h b/Code/Legacy/CryCommon/ISystem.h index c286d4af6c..d97c800763 100644 --- a/Code/Legacy/CryCommon/ISystem.h +++ b/Code/Legacy/CryCommon/ISystem.h @@ -47,7 +47,6 @@ struct IConsole; struct IRemoteConsole; struct IRenderer; struct IProcess; -struct ITimer; struct ICryFont; struct IMovieSystem; namespace Audio @@ -610,7 +609,6 @@ struct SSystemGlobalEnvironment { AZ::IO::IArchive* pCryPak; AZ::IO::FileIOBase* pFileIO; - ITimer* pTimer; ICryFont* pCryFont; ::IConsole* pConsole; ISystem* pSystem = nullptr; @@ -831,8 +829,6 @@ struct ISystem virtual IRemoteConsole* GetIRemoteConsole() = 0; virtual ISystemEventDispatcher* GetISystemEventDispatcher() = 0; - virtual ITimer* GetITimer() = 0; - // Arguments: // bValue - Set to true when running on a cheat protected server or a client that is connected to it (not used in singleplayer). virtual void SetForceNonDevMode(bool bValue) = 0; diff --git a/Code/Legacy/CryCommon/ITimer.h b/Code/Legacy/CryCommon/ITimer.h deleted file mode 100644 index 06bdab61e7..0000000000 --- a/Code/Legacy/CryCommon/ITimer.h +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYCOMMON_ITIMER_H -#define CRYINCLUDE_CRYCOMMON_ITIMER_H -#pragma once - - -#include "TimeValue.h" // CTimeValue -#include "SerializeFwd.h" - -struct tm; - -// Summary: -// Interface to the Timer System. -struct ITimer -{ - enum ETimer - { - ETIMER_GAME = 0, // Pausable, serialized, frametime is smoothed/scaled/clamped. - ETIMER_UI, // Non-pausable, non-serialized, frametime unprocessed. - ETIMER_LAST - }; - - enum ETimeScaleChannels - { - eTSC_Trackview = 0, - eTSC_GameStart - }; - - // - virtual ~ITimer() {}; - - // Summary: - // Resets the timer - // Notes: - // Only needed because float precision wasn't last that long - can be removed if 64bit is used everywhere. - virtual void ResetTimer() = 0; - - // Summary: - // Updates the timer every frame, needs to be called by the system. - virtual void UpdateOnFrameStart() = 0; - - // Summary: - // Returns the absolute time at the last UpdateOnFrameStart() call. - // Todo: - // Remove, use GetFrameStartTime() instead. - // See also: - // UpdateOnFrameStart(),GetFrameStartTime() - virtual float GetCurrTime(ETimer which = ETIMER_GAME) const = 0; - - // Summary: - // Returns the absolute time at the last UpdateOnFrameStart() call. - // See also: - // UpdateOnFrameStart() - //virtual const CTimeValue& GetFrameStartTime(ETimer which = ETIMER_GAME) const = 0; - virtual const CTimeValue& GetFrameStartTime(ETimer which = ETIMER_GAME) const = 0; - - // Summary: - // Returns the absolute current time. - // Notes: - // The value continuously changes, slower than GetFrameStartTime(). - // See also: - // GetFrameStartTime() - virtual CTimeValue GetAsyncTime() const = 0; - - // Summary: - // Returns the absolute current time at the moment of the call. - virtual float GetAsyncCurTime() = 0; - - // Summary: - // Returns the relative time passed from the last UpdateOnFrameStart() in seconds. - // See also: - // UpdateOnFrameStart() - virtual float GetFrameTime(ETimer which = ETIMER_GAME) const = 0; - - // Description: - // Returns the relative time passed from the last UpdateOnFrameStart() in seconds without any dilation, smoothing, clamping, etc... - // See also: - // UpdateOnFrameStart() - virtual float GetRealFrameTime() const = 0; - - // Summary: - // Returns the time scale applied to time values. - virtual float GetTimeScale() const = 0; - - // Summary: - // Returns the time scale factor for the given channel - virtual float GetTimeScale(uint32 channel) const = 0; - - // Summary: - // Clears all current time scale requests - virtual void ClearTimeScales() = 0; - - // Summary: - // Sets the time scale applied to time values. - virtual void SetTimeScale(float s, uint32 channel = 0) = 0; - - // Summary: - // Enables/disables timer. - virtual void EnableTimer(bool bEnable) = 0; - - // Return Value: - // True if timer is enabled - virtual bool IsTimerEnabled() const = 0; - - // Summary: - // Returns the current framerate in frames/second. - virtual float GetFrameRate() = 0; - - // Summary: - // Returns the fraction to blend current frame in profiling stats. - virtual float GetProfileFrameBlending(float* pfBlendTime = 0, int* piBlendMode = 0) = 0; - - // Summary: - // Serialization. - virtual void Serialize(TSerialize ser) = 0; - - // Summary: - // Tries to pause/unpause a timer. - // Return Value: - // True if successfully paused/unpaused, false otherwise. - virtual bool PauseTimer(ETimer which, bool bPause) = 0; - - // Summary: - // Determines if a timer is paused. - // Returns: - // True if paused, false otherwise. - virtual bool IsTimerPaused(ETimer which) = 0; - - // Summary: - // Tries to set a timer. - // Returns: - // True if successful, false otherwise. - virtual bool SetTimer(ETimer which, float timeInSeconds) = 0; - - // Summary: - // Makes a tm struct from a time_t in UTC - // Example: - // Like gmtime. - virtual void SecondsToDateUTC(time_t time, struct tm& outDateUTC) = 0; - - // Summary: - // Makes a UTC time from a tm. - // Example: - // Like timegm, but not available on all platforms. - virtual time_t DateToSecondsUTC(struct tm& timePtr) = 0; - - - // Summary - // Convert from ticks (CryGetTicks()) to seconds - // - virtual float TicksToSeconds(int64 ticks) = 0; - - // Summary - // Get number of ticks per second - // - virtual int64 GetTicksPerSecond() = 0; - - // Summary - // Create a new timer of the same type - // - virtual ITimer* CreateNewTimer() = 0; - - /*! - This is similar to the cvar t_FixedStep. However it is stronger, and will cause even GetRealFrameTime to follow the fixed time stamp. - GetRealFrameTime will always return the same value as GetFrameTime. This mode is mostly intended for Feature tests that have strict requirements - for determinism. It will cause even fps counters to return a fixed value that does not match the actual fps. I could see this also being useful - if rendering a video. - */ - virtual void EnableFixedTimeMode(bool enable, float timeStep) = 0; - // -}; - -// Description: -// This class is used for automatic profiling of a section of the code. -// Creates an instance of this class, and upon exiting from the code section. -template -class CITimerAutoProfiler -{ -public: - CITimerAutoProfiler (ITimer* pTimer, time& rTime) - : m_pTimer (pTimer) - , m_rTime (rTime) - { - rTime -= pTimer->GetAsyncCurTime(); - } - - ~CITimerAutoProfiler () - { - m_rTime += m_pTimer->GetAsyncCurTime(); - } - -protected: - ITimer* m_pTimer; - time& m_rTime; -}; - -// Description: -// Include this string AUTO_PROFILE_SECTION(pITimer, g_fTimer) for the section of code where the profiler timer must be turned on and off. -// The profiler timer is just some global or static float or double value that accumulates the time (in seconds) spent in the given block of code. -// pITimer is a pointer to the ITimer interface, g_fTimer is the global accumulator. -#define AUTO_PROFILE_SECTION(pITimer, g_fTimer) CITimerAutoProfiler __section_auto_profiler(pITimer, g_fTimer) - -#endif // CRYINCLUDE_CRYCOMMON_ITIMER_H diff --git a/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h b/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h index be449bb6ad..a678e238e2 100644 --- a/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h +++ b/Code/Legacy/CryCommon/LyShine/Animation/IUiAnimation.h @@ -9,7 +9,6 @@ #include #include -#include #include #include #include diff --git a/Code/Legacy/CryCommon/Mocks/ICryPakMock.h b/Code/Legacy/CryCommon/Mocks/ICryPakMock.h index 50cae45991..e03038c343 100644 --- a/Code/Legacy/CryCommon/Mocks/ICryPakMock.h +++ b/Code/Legacy/CryCommon/Mocks/ICryPakMock.h @@ -13,7 +13,7 @@ #include #include #include - +#include struct CryPakMock : AZ::IO::IArchive diff --git a/Code/Legacy/CryCommon/Mocks/ISystemMock.h b/Code/Legacy/CryCommon/Mocks/ISystemMock.h index d0f8dbd2e5..4b6669614b 100644 --- a/Code/Legacy/CryCommon/Mocks/ISystemMock.h +++ b/Code/Legacy/CryCommon/Mocks/ISystemMock.h @@ -75,8 +75,6 @@ public: IRemoteConsole * ()); MOCK_METHOD0(GetISystemEventDispatcher, ISystemEventDispatcher * ()); - MOCK_METHOD0(GetITimer, - ITimer * ()); MOCK_METHOD1(SetForceNonDevMode, void(bool bValue)); MOCK_CONST_METHOD0(GetForceNonDevMode, diff --git a/Code/Legacy/CryCommon/Mocks/ITimerMock.h b/Code/Legacy/CryCommon/Mocks/ITimerMock.h deleted file mode 100644 index 13cf5ef73a..0000000000 --- a/Code/Legacy/CryCommon/Mocks/ITimerMock.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#ifndef CRYINCLUDE_CRYSYSTEM_ITIMERMOCK_H -#define CRYINCLUDE_CRYSYSTEM_ITIMERMOCK_H -#pragma once - -#include -#include -#include - -// Implements all common timing routines -class TimerMock - : public ITimer -{ -public: - MOCK_METHOD0(ResetTimer, void()); - MOCK_METHOD0(UpdateOnFrameStart, void()); - MOCK_CONST_METHOD1(GetCurrTime, float(ETimer which)); - MOCK_CONST_METHOD0(GetAsyncTime, CTimeValue()); - MOCK_METHOD0(GetAsyncCurTime, float()); - MOCK_CONST_METHOD1(GetFrameTime, float(ETimer which)); - MOCK_CONST_METHOD0(GetRealFrameTime, float()); - MOCK_CONST_METHOD0(GetTimeScale, float()); - MOCK_CONST_METHOD1(GetTimeScale, float(uint32 channel)); - MOCK_METHOD2(SetTimeScale, void(float scale, uint32 channel)); - MOCK_METHOD0(ClearTimeScales, void()); - MOCK_METHOD1(EnableTimer, void(bool bEnable)); - MOCK_METHOD0(GetFrameRate, float()); - MOCK_METHOD2(GetProfileFrameBlending, float(float* pfBlendTime, int* piBlendMode)); - MOCK_METHOD1(Serialize, void(TSerialize ser)); - MOCK_CONST_METHOD0(IsTimerEnabled, bool()); - MOCK_METHOD2(PauseTimer, bool(ETimer which, bool bPause)); - MOCK_METHOD1(IsTimerPaused, bool(ETimer which)); - MOCK_METHOD2(SetTimer, bool(ETimer which, float timeInSeconds)); - MOCK_METHOD2(SecondsToDateUTC, void(time_t time, struct tm& outDateUTC)); - MOCK_METHOD1(DateToSecondsUTC, time_t(struct tm& timePtr)); - MOCK_METHOD1(TicksToSeconds, float(int64 ticks)); - MOCK_METHOD0(GetTicksPerSecond, int64()); - - MOCK_CONST_METHOD1(GetFrameStartTime, const CTimeValue&(ETimer which)); - MOCK_METHOD0(CreateNewTimer, ITimer * ()); - - MOCK_METHOD2(EnableFixedTimeMode, void(bool enable, float timeStep)); -}; - -#endif // CRYINCLUDE_CRYSYSTEM_ITIMERMOCK_H diff --git a/Code/Legacy/CryCommon/Mocks/StubTimer.h b/Code/Legacy/CryCommon/Mocks/StubTimer.h deleted file mode 100644 index 95df46a49d..0000000000 --- a/Code/Legacy/CryCommon/Mocks/StubTimer.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ -#pragma once - -#include -#include - -//! Simple stub timer that exposes a single simple interface for setting the current time. -class StubTimer - : public ITimer -{ -public: - // Stub methods - void SetTime(float seconds) - { - m_frameStartTime.SetSeconds(seconds); - } - //~Stub methods - - StubTimer(float frameTime) - : m_frameTime(frameTime) - , m_frameRate(1.0f / frameTime) - , m_frameStartTime(0.0f) - { - } - virtual ~StubTimer() {}; - - // ITimer - void ResetTimer() override {} - void UpdateOnFrameStart() override {} - float GetCurrTime([[maybe_unused]] ETimer which = ETIMER_GAME) const override - { - // return the same as the frame start time - return m_frameStartTime.GetSeconds(); - } - const CTimeValue& GetFrameStartTime([[maybe_unused]] ETimer which = ETIMER_GAME) const override - { - return m_frameStartTime; - } - CTimeValue GetAsyncTime() const override - { - return m_frameStartTime; - } - float GetAsyncCurTime() override - { - return m_frameStartTime.GetSeconds(); - } - float GetFrameTime([[maybe_unused]] ETimer which = ETIMER_GAME) const override - { - return m_frameTime; - } - float GetRealFrameTime() const override - { - return m_frameTime; - } - float GetTimeScale() const override - { - return 1.0f; - } - float GetTimeScale([[maybe_unused]] uint32 channel) const override - { - return 1.0f; - } - void ClearTimeScales() override {} - void SetTimeScale([[maybe_unused]] float s, [[maybe_unused]] uint32 channel = 0) override {} - void EnableTimer([[maybe_unused]] bool bEnable) override {} - bool IsTimerEnabled() const override - { - return true; - } - float GetFrameRate() override - { - return m_frameRate; - } - float GetProfileFrameBlending([[maybe_unused]] float* pfBlendTime = 0, [[maybe_unused]] int* piBlendMode = 0) override - { - return 0.0f; - } - void Serialize([[maybe_unused]] TSerialize ser) override {} - bool PauseTimer([[maybe_unused]] ETimer which, [[maybe_unused]] bool bPause) override { return false; } - bool IsTimerPaused([[maybe_unused]] ETimer which) override { return false; } - bool SetTimer([[maybe_unused]] ETimer which, [[maybe_unused]] float timeInSeconds) override { return false; } - void SecondsToDateUTC([[maybe_unused]] time_t time, [[maybe_unused]] struct tm& outDateUTC) override {} - time_t DateToSecondsUTC([[maybe_unused]] struct tm& timePtr) override - { - return 0; - } - float TicksToSeconds([[maybe_unused]] int64 ticks) override - { - return 0.0f; - } - int64 GetTicksPerSecond() override - { - return 0; - } - ITimer* CreateNewTimer() override - { - return nullptr; - } - void EnableFixedTimeMode([[maybe_unused]] bool enable, [[maybe_unused]] float timeStep) override {} - // ~ITimer - -private: - CTimeValue m_frameStartTime; - float m_frameTime; - float m_frameRate; -}; diff --git a/Code/Legacy/CryCommon/Timer.h b/Code/Legacy/CryCommon/Timer.h deleted file mode 100644 index c8c4857971..0000000000 --- a/Code/Legacy/CryCommon/Timer.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#pragma once -#ifndef CRYINCLUDE_CRYCOMMON_TIMER_H -#define CRYINCLUDE_CRYCOMMON_TIMER_H - -struct Timer -{ - Timer() - : endTime(-1.0f) - { - } - - void Reset(float duration, float variation = 0.0f) - { - endTime = gEnv->pSystem->GetITimer()->GetFrameStartTime() + CTimeValue(duration) + CTimeValue(cry_random(0.0f, variation)); - } - - bool Elapsed() const - { - return endTime >= 0.0f && gEnv->pSystem->GetITimer()->GetFrameStartTime() >= endTime; - } - - float GetSecondsLeft() const - { - return (endTime - gEnv->pSystem->GetITimer()->GetFrameStartTime()).GetSeconds(); - } - - CTimeValue endTime; -}; -#endif // CRYINCLUDE_CRYCOMMON_TIMER_H diff --git a/Code/Legacy/CryCommon/crycommon_files.cmake b/Code/Legacy/CryCommon/crycommon_files.cmake index d2c89fee84..d3e13525d7 100644 --- a/Code/Legacy/CryCommon/crycommon_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_files.cmake @@ -34,7 +34,6 @@ set(FILES StatObjBus.h ISystem.h ITexture.h - ITimer.h IValidator.h IWindowMessageHandler.h IXml.h @@ -68,7 +67,6 @@ set(FILES SimpleSerialize.h smartptr.h StlUtils.h - Timer.h TimeValue.h VectorMap.h VertexFormats.h diff --git a/Code/Legacy/CryCommon/crycommon_testing_files.cmake b/Code/Legacy/CryCommon/crycommon_testing_files.cmake index a44d91dd74..42deecd576 100644 --- a/Code/Legacy/CryCommon/crycommon_testing_files.cmake +++ b/Code/Legacy/CryCommon/crycommon_testing_files.cmake @@ -12,6 +12,5 @@ set(FILES Mocks/ICryPakMock.h Mocks/ILogMock.h Mocks/ISystemMock.h - Mocks/ITimerMock.h Mocks/ICVarMock.h ) diff --git a/Code/Legacy/CrySystem/CrySystem_precompiled.h b/Code/Legacy/CrySystem/CrySystem_precompiled.h index 27e41317a4..41090ff321 100644 --- a/Code/Legacy/CrySystem/CrySystem_precompiled.h +++ b/Code/Legacy/CrySystem/CrySystem_precompiled.h @@ -89,7 +89,6 @@ inline int RoundToClosestMB(size_t memSize) #include #include #include -#include #include #include #include diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp index 3a2bba64d3..7bfe6e2f1d 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -553,8 +554,6 @@ ILevel* CLevelSystem::LoadLevelInternal(const char* _levelName) // Not remove a scope!!! { - //m_levelLoadStartTime = gEnv->pTimer->GetAsyncTime(); - CLevelInfo* pLevelInfo = GetLevelInfoInternal(levelName); if (!pLevelInfo) @@ -693,7 +692,9 @@ void CLevelSystem::PrepareNextLevel(const char* levelName) // This work not required in-editor. if (!gEnv || !gEnv->IsEditor()) { - m_levelLoadStartTime = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs(); + const double timeSec = AZ::TimeMsToSecondsDouble(timeMs); + m_levelLoadStartTime = CTimeValue(timeSec); // Open pak file for a new level. pLevelInfo->OpenLevelPak(); @@ -726,7 +727,8 @@ void CLevelSystem::OnLoadingStart(const char* levelName) gEnv->pCryPak->RecordFileOpen(AZ::IO::IArchive::RFOM_Level); } - m_fLastTime = gEnv->pTimer->GetAsyncCurTime(); + const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs(); + m_fLastTime = AZ::TimeMsToSeconds(timeMs); GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START, 0, 0); @@ -757,7 +759,9 @@ void CLevelSystem::OnLoadingError(const char* levelName, const char* error) //------------------------------------------------------------------------ void CLevelSystem::OnLoadingComplete(const char* levelName) { - CTimeValue t = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs(); + const double timeSec = AZ::TimeMsToSecondsDouble(timeMs); + const CTimeValue t(timeSec); m_fLastLevelLoadTime = (t - m_levelLoadStartTime).GetSeconds(); LogLoadingTime(); @@ -851,7 +855,7 @@ void CLevelSystem::UnloadLevel() gEnv->pCryPak->DisableRuntimeFileAccess(false); } - CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs beginTimeMs = AZ::GetRealElapsedTimeMs(); // Clear level entities and prefab instances. EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext); @@ -889,8 +893,8 @@ void CLevelSystem::UnloadLevel() m_bLevelLoaded = false; - CTimeValue tUnloadTime = gEnv->pTimer->GetAsyncTime() - tBegin; - CryLog("UnloadLevel End: %.1f sec", tUnloadTime.GetSeconds()); + const AZ::TimeMs unloadTimeMs = AZ::GetRealElapsedTimeMs() - beginTimeMs; + CryLog("UnloadLevel End: %.1f sec", AZ::TimeMsToSeconds(unloadTimeMs)); // Must be sent last. // Cleanup all containers diff --git a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.h b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.h index d7230347e9..b857d20d15 100644 --- a/Code/Legacy/CrySystem/LevelSystem/LevelSystem.h +++ b/Code/Legacy/CrySystem/LevelSystem/LevelSystem.h @@ -11,6 +11,7 @@ #include "ILevelSystem.h" #include +#include // [LYN-2376] Remove the entire file once legacy slice support is removed diff --git a/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp b/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp index b2b67c3b75..a965b7f1c9 100644 --- a/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp +++ b/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.cpp @@ -24,8 +24,8 @@ #include #include #include - #include +#include namespace LegacyLevelSystem { @@ -368,7 +368,9 @@ namespace LegacyLevelSystem // This work not required in-editor. if (!gEnv || !gEnv->IsEditor()) { - m_levelLoadStartTime = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs(); + const double timeSec = AZ::TimeMsToSecondsDouble(timeMs); + m_levelLoadStartTime = CTimeValue(timeSec); // switched to level heap, so now imm start the loading screen (renderer will be reinitialized in the levelheap) gEnv->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START_LOADINGSCREEN, 0, 0); @@ -409,7 +411,8 @@ namespace LegacyLevelSystem gEnv->pCryPak->RecordFileOpen(AZ::IO::IArchive::RFOM_Level); } - m_fLastTime = gEnv->pTimer->GetAsyncCurTime(); + const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs(); + m_fLastTime = AZ::TimeMsToSeconds(timeMs); GetISystem()->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_LEVEL_LOAD_START, 0, 0); @@ -433,7 +436,9 @@ namespace LegacyLevelSystem //------------------------------------------------------------------------ void SpawnableLevelSystem::OnLoadingComplete(const char* levelName) { - CTimeValue t = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs(); + const double timeSec = AZ::TimeMsToSecondsDouble(timeMs); + const CTimeValue t(timeSec); m_fLastLevelLoadTime = (t - m_levelLoadStartTime).GetSeconds(); LogLoadingTime(); @@ -532,7 +537,7 @@ namespace LegacyLevelSystem gEnv->pCryPak->DisableRuntimeFileAccess(false); } - CTimeValue tBegin = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs beginTimeMs = AZ::GetRealElapsedTimeMs(); // Clear level entities and prefab instances. EBUS_EVENT(AzFramework::GameEntityContextRequestBus, ResetGameContext); @@ -561,8 +566,8 @@ namespace LegacyLevelSystem m_bLevelLoaded = false; - CTimeValue tUnloadTime = gEnv->pTimer->GetAsyncTime() - tBegin; - AZ_TracePrintf("LevelSystem", "UnloadLevel End: %.1f sec\n", tUnloadTime.GetSeconds()); + const AZ::TimeMs unloadTimeMs = AZ::GetRealElapsedTimeMs() - beginTimeMs; + AZ_TracePrintf("LevelSystem", "UnloadLevel End: %.1f sec\n", AZ::TimeMsToSeconds(unloadTimeMs)); // Must be sent last. // Cleanup all containers diff --git a/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.h b/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.h index 0a7b821262..b2e74530ac 100644 --- a/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.h +++ b/Code/Legacy/CrySystem/LevelSystem/SpawnableLevelSystem.h @@ -12,6 +12,7 @@ #include #include #include +#include namespace LegacyLevelSystem { diff --git a/Code/Legacy/CrySystem/LocalizedStringManager.cpp b/Code/Legacy/CrySystem/LocalizedStringManager.cpp index a87800899d..2d43f5b4ee 100644 --- a/Code/Legacy/CrySystem/LocalizedStringManager.cpp +++ b/Code/Legacy/CrySystem/LocalizedStringManager.cpp @@ -136,6 +136,44 @@ static const char* PLATFORM_INDEPENDENT_LANGUAGE_NAMES[ ILocalizationManager::eP "da-DK" // Danish (Denmark) }; +#if defined(WIN32) || defined(WIN64) +namespace +{ +#if defined(WIN32) + time_t gmt_to_local_win32(void) + { + TIME_ZONE_INFORMATION tzinfo; + DWORD dwStandardDaylight; + long bias; + + dwStandardDaylight = GetTimeZoneInformation(&tzinfo); + bias = tzinfo.Bias; + + if (dwStandardDaylight == TIME_ZONE_ID_STANDARD) + { + bias += tzinfo.StandardBias; + } + + if (dwStandardDaylight == TIME_ZONE_ID_DAYLIGHT) + { + bias += tzinfo.DaylightBias; + } + + return (-bias * 60); + } +#endif // #if defined(WIN32) + + time_t DateToSecondsUTC(struct tm& inDate) + { +#if defined(WIN32) + return mktime(&inDate) + gmt_to_local_win32(); +#else + return mktime(&inDate); +#endif // #if defined(WIN32) + } +} +#endif // #if defined(WIN32) || defined(WIN64) + ////////////////////////////////////////////////////////////////////////// #if !defined(_RELEASE) static void ReloadDialogData([[maybe_unused]] IConsoleCmdArgs* pArgs) @@ -2656,7 +2694,7 @@ void CLocalizedStringsManager::LocalizeTime(time_t t, bool bMakeLocalTime, bool { struct tm thetime; localtime_s(&thetime, &t); - t = gEnv->pTimer->DateToSecondsUTC(thetime); + t = DateToSecondsUTC(thetime); } outTimeString.clear(); LCID lcID = g_currentLanguageID.lcID ? g_currentLanguageID.lcID : LOCALE_USER_DEFAULT; @@ -2680,7 +2718,7 @@ void CLocalizedStringsManager::LocalizeDate(time_t t, bool bMakeLocalTime, bool { struct tm thetime; localtime_s(&thetime, &t); - t = gEnv->pTimer->DateToSecondsUTC(thetime); + t = DateToSecondsUTC(thetime); } outDateString.resize(0); LCID lcID = g_currentLanguageID.lcID ? g_currentLanguageID.lcID : LOCALE_USER_DEFAULT; diff --git a/Code/Legacy/CrySystem/Log.cpp b/Code/Legacy/CrySystem/Log.cpp index c08d5870e9..2b2fa65dda 100644 --- a/Code/Legacy/CrySystem/Log.cpp +++ b/Code/Legacy/CrySystem/Log.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #ifdef WIN32 #include @@ -503,7 +504,8 @@ void CLog::LogV(const ELogType type, [[maybe_unused]]int flags, const char* szFo { const int sz = sizeof(m_history) / sizeof(m_history[0]); int i, j; - float time = m_pSystem->GetITimer()->GetCurrTime(); + const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs(); + const float time = AZ::TimeMsToSeconds(realTimeMs); for (i = m_iLastHistoryItem, j = 0; m_history[i].time > time - dt && j < sz; j++, i = i - 1 & sz - 1) { if (m_history[i].type != type) @@ -908,7 +910,7 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[ } #endif - if (m_pLogIncludeTime && gEnv && gEnv->pTimer) + if (m_pLogIncludeTime) { uint32 dwCVarState = m_pLogIncludeTime->GetIVal(); // char szTemp[MAX_TEMP_LENGTH_SIZE]; @@ -933,12 +935,12 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[ } else if (dwCVarState == 2) // Log_IncludeTime { - static CTimeValue lasttime; - CTimeValue currenttime = gEnv->pTimer->GetAsyncTime(); - if (lasttime != CTimeValue()) + static AZ::TimeMs lasttime = AZ::Time::ZeroTimeMs; + const AZ::TimeMs currenttime = AZ::GetRealElapsedTimeMs(); + if (lasttime != AZ::Time::ZeroTimeMs) { timeStr.clear(); - uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds()); + uint32 dwMs = aznumeric_cast(currenttime - lasttime); timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000); tempString = timeStr + tempString; } @@ -960,12 +962,12 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[ #endif tempString = LogStringType(sTime) + tempString; - static CTimeValue lasttime; - CTimeValue currenttime = gEnv->pTimer->GetAsyncTime(); - if (lasttime != CTimeValue()) + static AZ::TimeMs lasttime = AZ::Time::ZeroTimeMs; + const AZ::TimeMs currenttime = AZ::GetRealElapsedTimeMs(); + if (lasttime != AZ::Time::ZeroTimeMs) { timeStr.clear(); - uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds()); + uint32 dwMs = (uint32)(currenttime - lasttime); timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000); tempString = timeStr + tempString; } @@ -975,22 +977,19 @@ void CLog::LogStringToFile(const char* szString, ELogType logType, bool bAdd, [[ { static bool bFirst = true; - if (gEnv->pTimer) + static AZ::TimeMs lasttime = AZ::Time::ZeroTimeMs; + const AZ::TimeMs currenttime = AZ::GetRealElapsedTimeMs(); + if (lasttime != AZ::Time::ZeroTimeMs) { - static CTimeValue lasttime; - CTimeValue currenttime = gEnv->pTimer->GetAsyncTime(); - if (lasttime != CTimeValue()) - { - timeStr.clear(); - uint32 dwMs = (uint32)((currenttime - lasttime).GetMilliSeconds()); - timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000); - tempString = timeStr + tempString; - } - if (bFirst) - { - lasttime = currenttime; - bFirst = false; - } + timeStr.clear(); + uint32 dwMs = (uint32)(currenttime - lasttime); + timeStr = AZStd::string::format("<%3d.%.3d>: ", dwMs / 1000, dwMs % 1000); + tempString = timeStr + tempString; + } + if (bFirst) + { + lasttime = currenttime; + bFirst = false; } } else if (dwCVarState == 5) // Log_IncludeTime @@ -1465,9 +1464,10 @@ void CLog::Update() if (LogCVars::s_log_tick != 0) { - static CTimeValue t0 = GetISystem()->GetITimer()->GetAsyncTime(); - CTimeValue t1 = GetISystem()->GetITimer()->GetAsyncTime(); - if (fabs((t1 - t0).GetSeconds()) > LogCVars::s_log_tick) + static AZ::TimeUs t0 = AZ::GetElapsedTimeUs(); + const AZ::TimeUs t1 = AZ::GetElapsedTimeUs(); + const float tSec = AZ::TimeUsToSeconds(t1 - t0); + if (tSec > LogCVars::s_log_tick) { t0 = t1; diff --git a/Code/Legacy/CrySystem/System.cpp b/Code/Legacy/CrySystem/System.cpp index 6d238c828f..bb48e69cec 100644 --- a/Code/Legacy/CrySystem/System.cpp +++ b/Code/Legacy/CrySystem/System.cpp @@ -29,6 +29,7 @@ #include #include #include +#include #include #include #include @@ -156,6 +157,16 @@ SSystemCVars g_cvars; #include #include "AZCoreLogSink.h" +namespace +{ + float GetMovieFrameDeltaTime() + { + // Use GetRealTickDeltaTimeUs for CryMovie, because it should not be affected by pausing game time + const AZ::TimeUs delta = AZ::GetRealTickDeltaTimeUs(); + return AZ::TimeUsToSeconds(delta); + } +} + ///////////////////////////////////////////////////////////////////////////////// // System Implementation. ////////////////////////////////////////////////////////////////////////// @@ -192,7 +203,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) ////////////////////////////////////////////////////////////////////////// // Initialize global environment interface pointers. m_env.pSystem = this; - m_env.pTimer = &m_Time; m_env.bIgnoreAllAsserts = false; m_env.bNoAssertDialog = false; @@ -563,14 +573,15 @@ ISystem* CSystem::GetCrySystem() ////////////////////////////////////////////////////////////////////////// void CSystem::SleepIfNeeded() { - ITimer* const pTimer = gEnv->pTimer; static bool firstCall = true; typedef MiniQueue PrevNow; static PrevNow prevNow; if (firstCall) { - m_lastTickTime = pTimer->GetAsyncTime(); + const AZ::TimeMs timeMs = AZ::GetRealElapsedTimeMs(); + const double timeSec = AZ::TimeMsToSecondsDouble(timeMs); + m_lastTickTime = CTimeValue(timeSec); prevNow.Push(m_lastTickTime); firstCall = false; return; @@ -578,8 +589,10 @@ void CSystem::SleepIfNeeded() const float maxRate = m_svDedicatedMaxRate->GetFVal(); const float minTime = 1.0f / maxRate; - CTimeValue now = pTimer->GetAsyncTime(); - float elapsed = (now - m_lastTickTime).GetSeconds(); + const AZ::TimeMs nowTimeMs = AZ::GetRealElapsedTimeMs(); + const double nowTimeSec = AZ::TimeMsToSecondsDouble(nowTimeMs); + const CTimeValue now = CTimeValue(nowTimeSec); + const float elapsed = (now - m_lastTickTime).GetSeconds(); if (prevNow.Full()) { @@ -591,7 +604,9 @@ void CSystem::SleepIfNeeded() if (elapsed > minTime && allowStallCatchup) { allowStallCatchup = false; - m_lastTickTime = pTimer->GetAsyncTime(); + const AZ::TimeMs lastTimeMs = AZ::GetRealElapsedTimeMs(); + const double lastTimeSec = AZ::TimeMsToSecondsDouble(lastTimeMs); + m_lastTickTime = CTimeValue(lastTimeSec); return; } allowStallCatchup = true; @@ -607,7 +622,9 @@ void CSystem::SleepIfNeeded() Sleep(sleepMS); } - m_lastTickTime = pTimer->GetAsyncTime(); + const AZ::TimeMs lastTimeMs = AZ::GetRealElapsedTimeMs(); + const double lastTimeSec = AZ::TimeMsToSecondsDouble(lastTimeMs); + m_lastTickTime = CTimeValue(lastTimeSec); } extern DWORD g_idDebugThreads[]; @@ -734,24 +751,21 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) if (maxFPS > 0 && vSync == 0) { - CTimeValue timeFrameMax; const float safeMarginFPS = 0.5f;//save margin to not drop below 30 fps - static CTimeValue sTimeLast = gEnv->pTimer->GetAsyncTime(); - timeFrameMax.SetMilliSeconds((int64)(1000.f / ((float)maxFPS + safeMarginFPS))); - const CTimeValue timeLast = timeFrameMax + sTimeLast; - while (timeLast.GetValue() > gEnv->pTimer->GetAsyncTime().GetValue()) + static AZ::TimeMs sTimeLast = AZ::GetRealElapsedTimeMs(); + const AZ::TimeMs timeFrameMax(static_cast( + (int64)(1000.f / ((float)maxFPS + safeMarginFPS)) + )); + const AZ::TimeMs timeLast = timeFrameMax + sTimeLast; + while (timeLast > AZ::GetRealElapsedTimeMs()) { CrySleep(0); } - sTimeLast = gEnv->pTimer->GetAsyncTime(); + sTimeLast = AZ::GetRealElapsedTimeMs(); } } } - ////////////////////////////////////////////////////////////////////// - //update time subsystem - m_Time.UpdateOnFrameStart(); - ////////////////////////////////////////////////////////////////////// //update console system if (m_env.pConsole) @@ -765,13 +779,10 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) return false; } - // Use UI timer for CryMovie, because it should not be affected by pausing game time - const float fMovieFrameTime = m_Time.GetFrameTime(ITimer::ETIMER_UI); - // Run movie system pre-update if (!bNoUpdate) { - UpdateMovieSystem(updateFlags, fMovieFrameTime, true); + UpdateMovieSystem(updateFlags, GetMovieFrameDeltaTime(), true); } return !IsQuitting(); @@ -780,13 +791,14 @@ bool CSystem::UpdatePreTickBus(int updateFlags, int nPauseMode) ////////////////////////////////////////////////////////////////////// bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/) { - CTimeValue updateStart = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs updateStartTimeMs = AZ::GetRealElapsedTimeMs(); + const double updateStartTimeSec = AZ::TimeMsToSecondsDouble(updateStartTimeMs); + const CTimeValue updateStart(updateStartTimeSec); // Run movie system post-update if (!m_bNoUpdate) { - const float fMovieFrameTime = m_Time.GetFrameTime(ITimer::ETIMER_UI); - UpdateMovieSystem(updateFlags, fMovieFrameTime, false); + UpdateMovieSystem(updateFlags, GetMovieFrameDeltaTime(), false); } ////////////////////////////////////////////////////////////////////// @@ -797,7 +809,9 @@ bool CSystem::UpdatePostTickBus(int updateFlags, int /*nPauseMode*/) } //Now update frame statistics - CTimeValue cur_time = gEnv->pTimer->GetAsyncTime(); + const AZ::TimeMs curTimeMs = AZ::GetRealElapsedTimeMs(); + const double curTimeSec = AZ::TimeMsToSecondsDouble(curTimeMs); + const CTimeValue cur_time(curTimeSec); CTimeValue a_second(g_cvars.sys_update_profile_time); std::vector< std::pair >::iterator it = m_updateTimes.begin(); @@ -1366,19 +1380,16 @@ const char* CSystem::GetSystemGlobalStateName(const ESystemGlobalState systemGlo void CSystem::SetSystemGlobalState(const ESystemGlobalState systemGlobalState) { - static CTimeValue s_startTime = CTimeValue(); + static AZ::TimeMs s_startTime = AZ::Time::ZeroTimeMs; if (systemGlobalState != m_systemGlobalState) { - if (gEnv && gEnv->pTimer) - { - const CTimeValue endTime = gEnv->pTimer->GetAsyncTime(); - [[maybe_unused]] const float numSeconds = endTime.GetDifferenceInSeconds(s_startTime); - CryLog("SetGlobalState %d->%d '%s'->'%s' %3.1f seconds", - m_systemGlobalState, systemGlobalState, - CSystem::GetSystemGlobalStateName(m_systemGlobalState), CSystem::GetSystemGlobalStateName(systemGlobalState), - numSeconds); - s_startTime = gEnv->pTimer->GetAsyncTime(); - } + const AZ::TimeMs endTime = AZ::GetRealElapsedTimeMs(); + [[maybe_unused]] const double numSeconds = AZ::TimeMsToSecondsDouble(endTime - s_startTime); + CryLog("SetGlobalState %d->%d '%s'->'%s' %3.1f seconds", + m_systemGlobalState, systemGlobalState, + CSystem::GetSystemGlobalStateName(m_systemGlobalState), CSystem::GetSystemGlobalStateName(systemGlobalState), + numSeconds); + s_startTime = AZ::GetRealElapsedTimeMs(); } m_systemGlobalState = systemGlobalState; diff --git a/Code/Legacy/CrySystem/System.h b/Code/Legacy/CrySystem/System.h index d25e094692..d48b1797d3 100644 --- a/Code/Legacy/CrySystem/System.h +++ b/Code/Legacy/CrySystem/System.h @@ -13,7 +13,6 @@ #include #include -#include "Timer.h" #include #include "CmdLine.h" @@ -23,6 +22,8 @@ #include #include +#include + #include #include @@ -226,7 +227,6 @@ public: int GetApplicationInstance() override; int GetApplicationLogInstance(const char* logFilePath) override; - ITimer* GetITimer() override{ return m_env.pTimer; } AZ::IO::IArchive* GetIPak() override { return m_env.pCryPak; }; IConsole* GetIConsole() override { return m_env.pConsole; }; IRemoteConsole* GetIRemoteConsole() override; @@ -382,7 +382,6 @@ private: // ------------------------------------------------------ // System environment. SSystemGlobalEnvironment m_env; - CTimer m_Time; //!< bool m_bInitializedSuccessfully; //!< true if the system completed all initialization steps bool m_bRelaunch; //!< relaunching the app or not (true beforerelaunch) int m_iLoadingMode; //!< Game is loading w/o changing context (0 not, 1 quickloading, 2 full loading) diff --git a/Code/Legacy/CrySystem/SystemInit.cpp b/Code/Legacy/CrySystem/SystemInit.cpp index 14d0635da7..8a0586fb13 100644 --- a/Code/Legacy/CrySystem/SystemInit.cpp +++ b/Code/Legacy/CrySystem/SystemInit.cpp @@ -1099,17 +1099,6 @@ AZ_POP_DISABLE_WARNING AzFramework::SystemCursorState::ConstrainedAndHidden); } - ////////////////////////////////////////////////////////////////////////// - // TIME - ////////////////////////////////////////////////////////////////////////// - AZ_Printf(AZ_TRACE_SYSTEM_WINDOW, "Time initialization"); - if (!m_Time.Init()) - { - AZ_Assert(false, "Failed to initialize CTimer instance."); - return false; - } - m_Time.ResetTimer(); - // CONSOLE ////////////////////////////////////////////////////////////////////////// if (!InitConsole()) diff --git a/Code/Legacy/CrySystem/Timer.cpp b/Code/Legacy/CrySystem/Timer.cpp deleted file mode 100644 index 1e1b6859e1..0000000000 --- a/Code/Legacy/CrySystem/Timer.cpp +++ /dev/null @@ -1,725 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#include "CrySystem_precompiled.h" -#include "Timer.h" -#include -#include -#include -#include -#include -///////////////////////////////////////////////////// - -#ifdef WIN32 -#define WIN32_LEAN_AND_MEAN -#include "windows.h" -#include "Mmsystem.h" -#endif - -//#define PROFILING 1 -#ifdef PROFILING -static int64 g_lCurrentTime = 0; -#endif - -//! Profile smoothing time in seconds (original default was .8 / log(10) ~= .35 s) -static const float fDEFAULT_PROFILE_SMOOTHING = 1.0f; - - - -#define DEFAULT_FRAME_SMOOTHING 1 - -///////////////////////////////////////////////////// -CTimer::CTimer() -{ - // Default CVar values - m_fixed_time_step = 0; - m_max_time_step = 0.25f; - m_cvar_time_scale = 1.0f; - m_TimeSmoothing = DEFAULT_FRAME_SMOOTHING; // note: frame numbers (old version - commented out) are not used but is based on time - m_TimeDebug = 0; - - m_profile_smooth_time = fDEFAULT_PROFILE_SMOOTHING; - m_profile_weighting = 1; - - // Persistant state - m_bEnabled = true; - //m_fixedTimeModeEnabled = false; - m_nFrameCounter = 0; - - m_lTicksPerSec = CryGetTicksPerSec(); - m_fSecsPerTick = 1.0 / m_lTicksPerSec; - - m_fAverageFrameTime = 1.0f / 30.0f; - for (int i = 0; i < MAX_FRAME_AVERAGE; i++) - { - m_arrFrameTimes[i] = m_fAverageFrameTime; - } - - m_fAvgFrameTime = 0.0f; - m_fProfileBlend = 1.0f; - m_fSmoothTime = 0; - - m_totalTimeScale = 1.0f; - ClearTimeScales(); - - ResetTimer(); -} - -///////////////////////////////////////////////////// -bool CTimer::Init() -{ - // if game code was accessing them by name there was something wrong anyway - - REGISTER_CVAR2("t_Smoothing", &m_TimeSmoothing, DEFAULT_FRAME_SMOOTHING, 0, - "time smoothing\n" - "0=off, 1=on"); - - REGISTER_CVAR2("t_FixedStep", &m_fixed_time_step, 0, VF_NET_SYNCED | VF_DEV_ONLY, - "Game updated with this fixed frame time\n" - "0=off, number specifies the frame time in seconds\n" - "e.g. 0.033333(30 fps), 0.1(10 fps), 0.01(100 fps)"); - - REGISTER_CVAR2("t_MaxStep", &m_max_time_step, 0.25f, 0, - "Game systems clamped to this frame time"); - - // todo: reconsider exposing that as cvar (negative time, same value is used by Trackview, better would be another value multipled with the internal one) - REGISTER_CVAR2("t_Scale", &m_cvar_time_scale, 1.0f, VF_NET_SYNCED | VF_DEV_ONLY, - "Game time scaled by this - for variable slow motion"); - - REGISTER_CVAR2("t_Debug", &m_TimeDebug, 0, 0, "Timer debug: 0 = off, 1 = events, 2 = verbose"); - - // ----------------- - - REGISTER_CVAR2("profile_smooth", &m_profile_smooth_time, fDEFAULT_PROFILE_SMOOTHING, 0, - "Profiler exponential smoothing interval (seconds)"); - - REGISTER_CVAR2("profile_weighting", &m_profile_weighting, 1, 0, - "Profiler smoothing mode: 0 = legacy, 1 = average, 2 = peak weighted, 3 = peak hold"); - - return true; -} - -///////////////////////////////////////////////////// -float CTimer::GetFrameTime(ETimer which) const -{ - float result = 0.0f; - if (m_bEnabled) - { - if (which != ETIMER_GAME || !m_bGameTimerPaused) - { - if (which == ETIMER_UI) - { - result = m_fRealFrameTime; - } - else - { - result = m_fFrameTime; - } - } - } - return result; -} - -///////////////////////////////////////////////////// -float CTimer::GetCurrTime(ETimer which) const -{ - assert(which >= 0 && which < ETIMER_LAST && "Bad timer index"); - return m_CurrTime[which].GetSeconds(); -} - -///////////////////////////////////////////////////// -float CTimer::GetRealFrameTime() const -{ - return m_bEnabled ? m_fRealFrameTime : 0.0f; -} - -///////////////////////////////////////////////////// -float CTimer::GetTimeScale() const -{ - return m_cvar_time_scale * m_totalTimeScale; -} - -///////////////////////////////////////////////////// -float CTimer::GetTimeScale(uint32 channel) const -{ - assert(channel < NUM_TIME_SCALE_CHANNELS); - if (channel >= NUM_TIME_SCALE_CHANNELS) - { - return GetTimeScale(); - } - return m_cvar_time_scale * m_timeScaleChannels[channel]; -} - -///////////////////////////////////////////////////// -void CTimer::SetTimeScale(float scale, uint32 channel /* = 0 */) -{ - assert(channel < NUM_TIME_SCALE_CHANNELS); - if (channel >= NUM_TIME_SCALE_CHANNELS) - { - return; - } - - const float currentScale = m_timeScaleChannels[channel]; - - if (scale != currentScale) - { - // Need to adjust previous frame times for time scale to have immediate effect - const float adjustFactor = scale / currentScale; - for (uint32 i = 0; i < MAX_FRAME_AVERAGE; ++i) - { - m_arrFrameTimes[i] *= adjustFactor; - } - - // Update total time scale immediately - m_totalTimeScale *= adjustFactor; - } - - m_timeScaleChannels[channel] = scale; -} - -///////////////////////////////////////////////////// -void CTimer::ClearTimeScales() -{ - if (m_totalTimeScale != 1.0f) - { - // Need to adjust previous frame times for time scale to have immediate effect - const float adjustFactor = 1.0f / m_totalTimeScale; - for (uint32 i = 0; i < MAX_FRAME_AVERAGE; ++i) - { - m_arrFrameTimes[i] *= adjustFactor; - } - } - - for (int i = 0; i < NUM_TIME_SCALE_CHANNELS; ++i) - { - m_timeScaleChannels[i] = 1.0f; - } - m_totalTimeScale = 1.0f; -} - -///////////////////////////////////////////////////// -float CTimer::GetAsyncCurTime() -{ - //int64 llNow = CryGetTicks() - m_lBaseTime_Async; - int64 llNow = CryGetTicks() - m_lBaseTime; - return TicksToSeconds(llNow); -} - -///////////////////////////////////////////////////// -float CTimer::GetFrameRate() -{ - // Use real frame time. - if (m_fRealFrameTime != 0.f) - { - return 1.f / m_fRealFrameTime; - } - return 0.f; -} - -void CTimer::UpdateBlending() -{ - // Accumulate smoothing time up to specified max. - float fFrameTime = m_fRealFrameTime; - m_fSmoothTime = min(m_fSmoothTime + fFrameTime, m_profile_smooth_time); - - if (m_fSmoothTime <= fFrameTime) - { - m_fAvgFrameTime = fFrameTime; - m_fProfileBlend = 1.f; - return; - } - - if (m_profile_weighting <= 2) - { - // Update average frame time. - if (m_fSmoothTime < m_fAvgFrameTime) - { - m_fAvgFrameTime = m_fSmoothTime; - } - m_fAvgFrameTime *= m_fSmoothTime / (m_fSmoothTime - fFrameTime + m_fAvgFrameTime); - - if (m_profile_weighting == 1) - { - // Weight all frames equally. - m_fProfileBlend = m_fAvgFrameTime / m_fSmoothTime; - } - else - { - // Weight frames by time. - m_fProfileBlend = fFrameTime / m_fSmoothTime; - } - } - else - { - // Decay avg frame time, set as new peak. - m_fAvgFrameTime *= 1.f - fFrameTime / m_fSmoothTime; - if (fFrameTime > m_fAvgFrameTime) - { - m_fAvgFrameTime = fFrameTime; - m_fProfileBlend = 1.f; - } - else - { - m_fProfileBlend = 0.f; - } - } -} - -float CTimer::GetProfileFrameBlending(float* pfBlendTime, int* piBlendMode) -{ - if (piBlendMode) - { - *piBlendMode = m_profile_weighting; - } - if (pfBlendTime) - { - *pfBlendTime = m_fSmoothTime; - } - return m_fProfileBlend; -} - -///////////////////////////////////////////////////// -void CTimer::RefreshGameTime(int64 curTime) -{ - assert(curTime + m_lOffsetTime >= 0); - m_CurrTime[ETIMER_GAME].SetSeconds(TicksToSeconds(curTime + m_lOffsetTime)); -} - -///////////////////////////////////////////////////// -void CTimer::RefreshUITime(int64 curTime) -{ - assert(curTime >= 0); - m_CurrTime[ETIMER_UI].SetSeconds(TicksToSeconds(curTime)); -} - - -///////////////////////////////////////////////////// -void CTimer::UpdateOnFrameStart() -{ - if (!m_bEnabled) - { - return; - } - - //int64 now; - - //if (m_fixedTimeModeEnabled) - //{ - // m_nFrameCounter++; - // m_fRealFrameTime = m_fFrameTime = m_fixedTimeModeStep; - // m_lCurrentTime += m_fixedTimeModeStep*m_lTicksPerSec; - // now = m_lCurrentTime; - //} - //else - //{ - // On Windows before Vista, frequency can change (even though it should be impossible), - // See also: https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx - // Win2000, WinXP: Uses RDTSC, which may not be monotonic across all cores (a bug), costs in the order of 10~100 cycles (cheap). - // WinVista: Uses HPET or ACPI timer (a kernel call, and much more expensive than RDTSC, but it's not bugged). - // Win7+: RDTSC if the CPU feature bit for monotonic is set, HPET or ACPI otherwise (not bugged). -#if defined(_WIN32_WINNT) && _WIN32_WINNT < 0x0600 - if ((m_nFrameCounter & 127) == 0) - { - // every bunch of frames, check frequency to adapt to - // CPU power management clock rate changes - LARGE_INTEGER TTicksPerSec; - if (QueryPerformanceFrequency(&TTicksPerSec)) - { - // if returns false, no performance counter is available - m_lTicksPerSec = TTicksPerSec.QuadPart; - m_fSecsPerTick = 1.0 / m_lTicksPerSec; - } - } - - m_nFrameCounter++; -#endif - //} - -#ifdef PROFILING - m_fRealFrameTime = m_fFrameTime = 0.020f; // 20ms = 50fps - g_lCurrentTime += (int)(m_fFrameTime * (float)(CTimeValue::TIMEVALUE_PRECISION)); - m_lLastTime = g_lCurrentTime; - RefreshGameTime(m_lLastTime); - RefreshUITime(m_lLastTime); - return; -#endif - - if (m_fixed_time_step < 0.0f) - { - // Enforce real framerate by sleeping. - const int64 elapsedTicks = CryGetTicks() - m_lBaseTime - m_lLastTime; - const int64 minTicks = SecondsToTicks(-m_fixed_time_step); - if (elapsedTicks < minTicks) - { - const int64 ms = (minTicks - elapsedTicks) * 1000 / m_lTicksPerSec; - CrySleep((unsigned int)ms); - } - } - - const int64 now = CryGetTicks(); - assert(now + 1 >= m_lBaseTime && "Invalid base time"); //+1 margin because QPC may be one off across cores - - m_fRealFrameTime = TicksToSeconds(now - m_lBaseTime - m_lLastTime); - - if (0.0f != m_fixed_time_step) - { - // Apply fixed_time_step - m_fFrameTime = abs(m_fixed_time_step); - } - else - { - // Clamp to max_time_step - m_fFrameTime = min(m_fRealFrameTime, m_max_time_step); - } - - // Dilate time. - m_fFrameTime *= GetTimeScale(); - - if (m_TimeSmoothing > 0) - { - m_fFrameTime = GetAverageFrameTime(); - } - - // Time can only go forward. - if (m_fFrameTime < 0.0f) - { - m_fFrameTime = 0.0f; - } - if (m_fRealFrameTime < 0.0f) - { - m_fRealFrameTime = 0.0; - } - - // Adjust the base time so that time actually seems to have moved forward m_fFrameTime - const int64 frameTicks = SecondsToTicks(m_fFrameTime); - const int64 realTicks = SecondsToTicks(m_fRealFrameTime); - m_lBaseTime += realTicks - frameTicks; - if (m_lBaseTime > now) - { - // Guard against rounding errors due to float <-> int64 precision - assert(m_lBaseTime - now <= 10 && "Bad base time or adjustment, too much difference for a rounding error"); - m_lBaseTime = now; - } - const int64 currentTime = now - m_lBaseTime; - - assert(fabsf(TicksToSeconds(currentTime - m_lLastTime) - m_fFrameTime) < 0.01f && "Bad calculation"); - assert(currentTime >= m_lLastTime && "Bad adjustment in previous frame"); - assert(currentTime + m_lOffsetTime >= 0 && "Sum of game time is negative"); - - // Update timers - RefreshUITime(currentTime); - if (!m_bGameTimerPaused) - { - RefreshGameTime(currentTime); - } - - m_lLastTime = currentTime; - - UpdateBlending(); - - if (m_TimeDebug > 1) - { - CryLogAlways("[CTimer]: Cur=%lld Now=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)currentTime, (long long)now, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); - } -} - -//------------------------------------------------------------------------ -//-- average frame-times to avoid stalls and peaks in framerate -//-- note that is is time-base averaging and not frame-based -//------------------------------------------------------------------------ -float CTimer::GetAverageFrameTime() -{ - f32 LastAverageFrameTime = m_fAverageFrameTime; - f32 FrameTime = m_fFrameTime; - - uint32 numFT = MAX_FRAME_AVERAGE; - for (int32 i = (numFT - 2); i > -1; i--) - { - m_arrFrameTimes[i + 1] = m_arrFrameTimes[i]; - } - - if (FrameTime > 0.4f) - { - FrameTime = 0.4f; - } - if (FrameTime < 0.0f) - { - FrameTime = 0.0f; - } - m_arrFrameTimes[0] = FrameTime; - - //get smoothed frame - uint32 avrg_ftime = 1; - if (LastAverageFrameTime) - { - avrg_ftime = uint32(0.25f / LastAverageFrameTime + 0.5f); //average the frame-times for a certain time-period (sec) - if (avrg_ftime > numFT) - { - avrg_ftime = numFT; - } - if (avrg_ftime < 1) - { - avrg_ftime = 1; - } - } - - f32 AverageFrameTime = 0; - for (uint32 i = 0; i < avrg_ftime; i++) - { - AverageFrameTime += m_arrFrameTimes[i]; - } - AverageFrameTime /= avrg_ftime; - - //don't smooth if we pause the game - if (FrameTime < 0.0001f) - { - AverageFrameTime = FrameTime; - } - - m_fAverageFrameTime = AverageFrameTime; - return AverageFrameTime; -} - - -///////////////////////////////////////////////////// -void CTimer::ResetTimer() -{ - m_lBaseTime = CryGetTicks(); - //m_lBaseTime_Async = CryGetTicks(); - m_lLastTime = 0; - m_lOffsetTime = 0; - - m_fFrameTime = 0.0f; - m_fRealFrameTime = 0.0f; - - RefreshGameTime(0); - RefreshUITime(0); - - m_bGameTimerPaused = false; - m_lGameTimerPausedTime = 0; -} - -///////////////////////////////////////////////////// -void CTimer::EnableTimer(bool bEnable) -{ - m_bEnabled = bEnable; -} - -bool CTimer::IsTimerEnabled() const -{ - return m_bEnabled; -} - -///////////////////////////////////////////////////// -CTimeValue CTimer::GetAsyncTime() const -{ - int64 llNow = CryGetTicks(); - double fConvert = CTimeValue::TIMEVALUE_PRECISION * m_fSecsPerTick; - return CTimeValue(int64(llNow * fConvert)); -} - -///////////////////////////////////////////////////// -void CTimer::Serialize(TSerialize ser) -{ - // cannot change m_lBaseTime, as this is used for async time (which shouldn't be affected by save games) - if (ser.IsWriting()) - { - int64 currentGameTime = m_lLastTime + m_lOffsetTime; - - ser.Value("curTime", currentGameTime); - ser.Value("ticksPerSecond", m_lTicksPerSec); - } - else - { - int64 ticksPerSecond = 1, curTime = 1; - ser.Value("curTime", curTime); - ser.Value("ticksPerSecond", ticksPerSecond); - - // Adjust curTime for ticksPerSecond on this machine. - // Some precision will be lost if the frequencies are not identical. - const double multiplier = (double)m_lTicksPerSec / (double)ticksPerSecond; - curTime = (int64)((double)curTime * multiplier); - - SetOffsetToMatchGameTime(curTime); - - if (m_TimeDebug) - { - [[maybe_unused]] const int64 now = CryGetTicks(); - CryLogAlways("[CTimer]: Serialize: Last=%lld Now=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)m_lLastTime, (long long)now, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); - } - } -} - -//! try to pause/unpause a timer -// returns true if successfully paused/unpaused, false otherwise -bool CTimer::PauseTimer(ETimer which, bool bPause) -{ - if (which != ETIMER_GAME) - { - return false; - } - - if (m_bGameTimerPaused == bPause) - { - return false; - } - - m_bGameTimerPaused = bPause; - - if (bPause) - { - m_lGameTimerPausedTime = m_lLastTime + m_lOffsetTime; - if (m_TimeDebug) - { - CryLogAlways("[CTimer]: Pausing ON: Last=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)m_lLastTime, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); - } - } - else - { - SetOffsetToMatchGameTime(m_lGameTimerPausedTime); - m_lGameTimerPausedTime = 0; - if (m_TimeDebug) - { - CryLogAlways("[CTimer]: Pausing OFF: Last=%lld Off=%lld Async=%f CurrTime=%f UI=%f", (long long)m_lLastTime, (long long)m_lOffsetTime, GetAsyncCurTime(), GetCurrTime(ETIMER_GAME), GetCurrTime(ETIMER_UI)); - } - } - - return true; -} - -//! determine if a timer is paused -// returns true if paused, false otherwise -bool CTimer::IsTimerPaused(ETimer which) -{ - if (which != ETIMER_GAME) - { - return false; - } - return m_bGameTimerPaused; -} - -//! try to set a timer -// return true if successful, false otherwise -bool CTimer::SetTimer(ETimer which, float timeInSeconds) -{ - if (which != ETIMER_GAME) - { - return false; - } - - SetOffsetToMatchGameTime(SecondsToTicks(timeInSeconds)); - return true; -} - -ITimer* CTimer::CreateNewTimer() -{ - return new CTimer(); -} - -void CTimer::SecondsToDateUTC(time_t inTime, struct tm& outDateUTC) -{ -#ifdef AZ_COMPILER_MSVC - gmtime_s(&outDateUTC, &inTime); -#else - outDateUTC = *gmtime(&inTime); -#endif -} - -#if defined (WIN32) || defined(WIN64) -time_t gmt_to_local_win32(void) -{ - TIME_ZONE_INFORMATION tzinfo; - DWORD dwStandardDaylight; - long bias; - - dwStandardDaylight = GetTimeZoneInformation(&tzinfo); - bias = tzinfo.Bias; - - if (dwStandardDaylight == TIME_ZONE_ID_STANDARD) - { - bias += tzinfo.StandardBias; - } - - if (dwStandardDaylight == TIME_ZONE_ID_DAYLIGHT) - { - bias += tzinfo.DaylightBias; - } - - return (-bias * 60); -} -#endif - -time_t CTimer::DateToSecondsUTC(struct tm& inDate) -{ -#if defined (WIN32) - return mktime(&inDate) + gmt_to_local_win32(); -#elif defined (LINUX) -#if defined (HAVE_TIMEGM) - // return timegm(&inDate); -#else - // craig: temp disabled the +tm.tm_gmtoff because i can't see the intention here - // and it doesn't compile anymore - // alexl: tm_gmtoff is the offset to greenwhich mean time, whereas mktime uses localtime - // but not all linux distributions have it... - return mktime(&inDate) /*+ tm.tm_gmtoff*/; -#endif -#else - return mktime(&inDate); -#endif -} - -void CTimer::EnableFixedTimeMode([[maybe_unused]] bool enable, [[maybe_unused]] float timeStep) -{ - //if (enable) - //{ - // m_fixedTimeModeEnabled = true; - // m_fixedTimeModeStep = timeStep; - - // m_lBaseTime =0; - // m_lBaseTime_Async = 0; - // m_lLastTime = m_lCurrentTime = 0; - // m_fRealFrameTime = m_fFrameTime = timeStep; - // RefreshGameTime(m_lCurrentTime); - // RefreshUITime(m_lCurrentTime); - // m_lForcedGameTime = -1; - // m_bGameTimerPaused = false; - // m_lGameTimerPausedTime = 0; - //} - //else - //{ - // m_fixedTimeModeEnabled = false; - // ResetTimer(); - //} -} - -void CTimer::SetOffsetToMatchGameTime(int64 ticks) -{ - [[maybe_unused]] const int64 previousOffset = m_lOffsetTime; - [[maybe_unused]] const float previousGameTime = GetCurrTime(ETIMER_GAME); - - m_lOffsetTime = ticks - m_lLastTime; - RefreshGameTime(m_lLastTime); - - if (m_bGameTimerPaused) - { - // On un-pause, we will restore the specified time. - // If we don't do this, the un-pause will over-write the offset again. - m_lGameTimerPausedTime = ticks; - } - - if (m_TimeDebug) - { - CryLogAlways("[CTimer] SetOffset: Offset %lld -> %lld, GameTime %f -> %f", (long long)previousOffset, (long long)m_lOffsetTime, GetCurrTime(ETIMER_GAME), previousGameTime); - } -} - -int64 CTimer::SecondsToTicks(double seconds) const -{ - return (int64)(seconds * (double)m_lTicksPerSec); -} diff --git a/Code/Legacy/CrySystem/Timer.h b/Code/Legacy/CrySystem/Timer.h deleted file mode 100644 index 69fd2357e0..0000000000 --- a/Code/Legacy/CrySystem/Timer.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright (c) Contributors to the Open 3D Engine Project. - * For complete copyright and license terms please see the LICENSE at the root of this distribution. - * - * SPDX-License-Identifier: Apache-2.0 OR MIT - * - */ - - -#ifndef CRYINCLUDE_CRYSYSTEM_TIMER_H -#define CRYINCLUDE_CRYSYSTEM_TIMER_H - -# pragma once -#include - -// Implements all common timing routines -class CTimer - : public ITimer -{ -public: - // constructor - CTimer(); - // destructor - ~CTimer() = default; - - bool Init(); - - // interface ITimer ---------------------------------------------------------- - - // TODO: Review m_time usage in System.cpp - // if it wants Game Time / UI Time or a new Render Time? - - void ResetTimer() override; - void UpdateOnFrameStart() override; - float GetCurrTime(ETimer which = ETIMER_GAME) const override; - CTimeValue GetAsyncTime() const override; - float GetAsyncCurTime() override; // retrieve the actual wall clock time passed since the game started, in seconds - float GetFrameTime(ETimer which = ETIMER_GAME) const override; - float GetRealFrameTime() const override; - float GetTimeScale() const override; - float GetTimeScale(uint32 channel) const override; - void SetTimeScale(float scale, uint32 channel = 0) override; - void ClearTimeScales() override; - void EnableTimer(bool bEnable) override; - float GetFrameRate() override; - float GetProfileFrameBlending(float* pfBlendTime = nullptr, int* piBlendMode = nullptr) override; - void Serialize(TSerialize ser) override; - bool IsTimerEnabled() const override; - - //! try to pause/unpause a timer - // returns true if successfully paused/unpaused, false otherwise - bool PauseTimer(ETimer which, bool bPause) override; - - //! determine if a timer is paused - // returns true if paused, false otherwise - bool IsTimerPaused(ETimer which) override; - - //! try to set a timer - // return true if successful, false otherwise - bool SetTimer(ETimer which, float timeInSeconds) override; - - //! make a tm struct from a time_t in UTC (like gmtime) - void SecondsToDateUTC(time_t time, struct tm& outDateUTC) override; - - //! make a UTC time from a tm (like timegm, but not available on all platforms) - time_t DateToSecondsUTC(struct tm& timePtr) override; - - //! Convert from Tics to Seconds - float TicksToSeconds(int64 ticks) override - { - return float((double)ticks * m_fSecsPerTick); - } - - //! Get number of ticks per second - int64 GetTicksPerSecond() override - { - return m_lTicksPerSec; - } - - const CTimeValue& GetFrameStartTime(ETimer which = ETIMER_GAME) const override { return m_CurrTime[(int)which]; } - ITimer* CreateNewTimer() override; - - void EnableFixedTimeMode(bool enable, float timeStep) override; - -private: // --------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - - // updates m_CurrTime (either pass m_lCurrentTime or custom curTime) - void RefreshGameTime(int64 curTime); - void RefreshUITime(int64 curTime); - void UpdateBlending(); - float GetAverageFrameTime(); - - // Updates the game-time offset to match the the specified time. - // The argument is the new number of ticks since the last Reset(). - void SetOffsetToMatchGameTime(int64 ticks); - - // Convert seconds to ticks using the timer frequency. - // Note: Loss of precision may occur, especially if magnitude of argument or timer frequency is large. - int64 SecondsToTicks(double seconds) const; - - enum - { - MAX_FRAME_AVERAGE = 100, - NUM_TIME_SCALE_CHANNELS = 8, - }; - - ////////////////////////////////////////////////////////////////////////// - // Dynamic state, reset by ResetTimer() - ////////////////////////////////////////////////////////////////////////// - CTimeValue m_CurrTime[ETIMER_LAST]; // Time since last Reset(), cached during Update() - - int64 m_lBaseTime; // Ticks elapsed since system boot, all other tick-unit variables are relative to this. - int64 m_lLastTime; // Ticks since last Reset(). This is the base for UI time. UI time is monotonic, it always moves forward at a constant rate until the timer is Reset()). - int64 m_lOffsetTime; // Additional ticks for Game time (relative to UI time). Game time can be affected by loading, pausing, time smoothing and time clamping, as well as SetTimer(). - - //// the GetcurAsyncTime function appears to want to return the actual wall clock time delta - //// but its using the base time (above) which is adjusted when there is a frame skip. - //int64 m_lBaseTime_Async; - - float m_fFrameTime; // In seconds since the last Update(), clamped/smoothed etc. - float m_fRealFrameTime; // In real seconds since the last Update(), non-clamped/un-smoothed etc. - - bool m_bGameTimerPaused; // Set if the game is paused. GetFrameTime() will return 0, GetCurrTime(ETIMER_GAME) will not progress. - int64 m_lGameTimerPausedTime; // The UI time when the game timer was paused. On un-pause, offset will be adjusted to match. - - ////////////////////////////////////////////////////////////////////////// - // Persistant state, kept by ResetTimer() - ////////////////////////////////////////////////////////////////////////// - bool m_bEnabled; - unsigned int m_nFrameCounter; - - int64 m_lTicksPerSec; // Ticks per second - double m_fSecsPerTick; // Seconds per tick - - // smoothing - float m_arrFrameTimes[MAX_FRAME_AVERAGE]; - float m_fAverageFrameTime; // used for smoothing (AverageFrameTime()) - - float m_fAvgFrameTime; // used for blend weighting (UpdateBlending()) - float m_fProfileBlend; // current blending amount for profile. - float m_fSmoothTime; // smoothing interval (up to m_profile_smooth_time). - - // time scale - float m_timeScaleChannels[NUM_TIME_SCALE_CHANNELS]; - float m_totalTimeScale; - - ////////////////////////////////////////////////////////////////////////// - // Console vars, always have default value on secondary CTimer instances - ////////////////////////////////////////////////////////////////////////// - float m_fixed_time_step; // in seconds - float m_max_time_step; // in seconds - float m_cvar_time_scale; // slow down time cvar - int m_TimeSmoothing; // Console Variable, 0=off, otherwise on - int m_TimeDebug; // Console Variable, 0=off, otherwise on - - // Profile averaging help. - float m_profile_smooth_time; // seconds to exponentially smooth profile results. - int m_profile_weighting; // weighting mode (see RegisterVar desc). - - //bool m_fixedTimeModeEnabled; - //float m_fixedTimeModeStep; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_TIMER_H diff --git a/Code/Legacy/CrySystem/XConsole.cpp b/Code/Legacy/CrySystem/XConsole.cpp index 22c61d3f22..df82e34abe 100644 --- a/Code/Legacy/CrySystem/XConsole.cpp +++ b/Code/Legacy/CrySystem/XConsole.cpp @@ -16,7 +16,6 @@ #include "System.h" #include "ConsoleBatchFile.h" -#include #include #include #include @@ -28,6 +27,7 @@ #include #include #include +#include #include //#define DEFENCE_CVAR_HASH_LOGGING @@ -105,7 +105,8 @@ void Command_SetWaitSeconds(IConsoleCmdArgs* pCmd) if (pCmd->GetArgCount() > 1) { pConsole->m_waitSeconds.SetSeconds(atof(pCmd->GetArg(1))); - pConsole->m_waitSeconds += gEnv->pTimer->GetFrameStartTime(); + const AZ::TimeMs elaspedTimeMs = AZ::GetRealElapsedTimeMs(); + pConsole->m_waitSeconds += CTimeValue(AZ::TimeMsToSecondsDouble(elaspedTimeMs)); } } @@ -305,7 +306,6 @@ void CXConsole::Init(ISystem* pSystem) { m_pFont = pSystem->GetICryFont()->GetFont("default"); } - m_pTimer = pSystem->GetITimer(); AzFramework::InputChannelEventListener::Connect(); AzFramework::InputTextEventListener::Connect(); @@ -934,8 +934,8 @@ void CXConsole::Update() const float fRepeatDelay = 1.0f / 40.0f; // in sec (similar to Windows default but might differ from actual setting) const float fHitchDelay = 1.0f / 10.0f; // in sec. Very low, but still reasonable frame-rate (debug builds) - m_fRepeatTimer -= gEnv->pTimer->GetRealFrameTime(); // works even when time is manipulated - // m_fRepeatTimer -= gEnv->pTimer->GetFrameTime(ITimer::ETIMER_UI); // can be used once ETIMER_UI works even with t_FixedTime + const AZ::TimeUs delta = AZ::GetRealTickDeltaTimeUs(); // works even when time is manipulated + m_fRepeatTimer -= AZ::TimeUsToSeconds(delta); if (m_fRepeatTimer <= 0.0f) { @@ -1961,7 +1961,9 @@ void CXConsole::ExecuteDeferredCommands() if (m_waitSeconds.GetValue()) { - if (m_waitSeconds > gEnv->pTimer->GetFrameStartTime()) + const AZ::TimeMs elaspsedTimeMs = AZ::GetRealElapsedTimeMs(); + const double elaspedTimeSec = AZ::TimeMsToSecondsDouble(elaspsedTimeMs); + if (m_waitSeconds > CTimeValue(elaspedTimeSec)) { return; } diff --git a/Code/Legacy/CrySystem/XConsole.h b/Code/Legacy/CrySystem/XConsole.h index a10adda97b..535f5b8650 100644 --- a/Code/Legacy/CrySystem/XConsole.h +++ b/Code/Legacy/CrySystem/XConsole.h @@ -13,8 +13,8 @@ #pragma once #include -#include "Timer.h" #include +#include #include #include @@ -377,7 +377,6 @@ private: // ---------------------------------------------------------- CSystem* m_pSystem; IFFont* m_pFont; - ITimer* m_pTimer; ICVar* m_pSysDeactivateConsole; diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp index 528e3dbcc5..f58d8c7fcf 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp +++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.cpp @@ -10,6 +10,7 @@ #include "CrySystem_precompiled.h" #include "SerializeXMLReader.h" #include +#include #define TAG_SCRIPT_VALUE "v" #define TAG_SCRIPT_TYPE "t" @@ -21,7 +22,6 @@ CSerializeXMLReaderImpl::CSerializeXMLReaderImpl(const XmlNodeRef& nodeRef) : m_nErrors(0) { - //m_curTime = gEnv->pTimer->GetFrameStartTime(); assert(!!nodeRef); m_nodeStack.push_back(CParseState()); m_nodeStack.back().Init(nodeRef); @@ -87,18 +87,21 @@ bool CSerializeXMLReaderImpl::Value(const char* name, CTimeValue& value) } else { + const AZ::TimeMs elaspsedTimeMs = AZ::GetRealElapsedTimeMs(); + const double elaspedTimeSec = AZ::TimeMsToSecondsDouble(elaspsedTimeMs); + const CTimeValue elaspedTime(elaspedTimeSec); float delta; if (!GetAttr(nodeRef, name, delta)) { //CryWarning( VALIDATOR_MODULE_SYSTEM,VALIDATOR_WARNING,"Failed to read time value %s", name); //Failed(); - value = gEnv->pTimer->GetFrameStartTime(); // in case we don't find the node, it was assumed to be the default value (0.0) + value = elaspedTime; // in case we don't find the node, it was assumed to be the default value (0.0) // 0.0 means current time, whereas "zero" really means CTimeValue(0.0), see above return false; } else { - value = CTimeValue(gEnv->pTimer->GetFrameStartTime() + delta); + value = CTimeValue(elaspedTime + delta); } } return true; diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h index 58c150db24..39f3230521 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLReader.h +++ b/Code/Legacy/CrySystem/XML/SerializeXMLReader.h @@ -11,7 +11,6 @@ #include "SimpleSerialize.h" #include #include -#include #include "xml.h" class CSerializeXMLReaderImpl diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp index 5a3e403218..ee5fe21797 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp +++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.cpp @@ -10,6 +10,8 @@ #include "CrySystem_precompiled.h" #include "SerializeXMLWriter.h" +#include + static const size_t MAX_NODE_STACK_DEPTH = 40; #define TAG_SCRIPT_VALUE "v" @@ -18,7 +20,9 @@ static const size_t MAX_NODE_STACK_DEPTH = 40; CSerializeXMLWriterImpl::CSerializeXMLWriterImpl(const XmlNodeRef& nodeRef) { - m_curTime = gEnv->pTimer->GetFrameStartTime(); + const AZ::TimeMs elaspsedTimeMs = AZ::GetRealElapsedTimeMs(); + const double elaspedTimeSec = AZ::TimeMsToSecondsDouble(elaspsedTimeMs); + m_curTime = CTimeValue(elaspedTimeSec); assert(!!nodeRef); m_nodeStack.push_back(nodeRef); diff --git a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h index 26fbe4b29c..822045a3f5 100644 --- a/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h +++ b/Code/Legacy/CrySystem/XML/SerializeXMLWriter.h @@ -13,7 +13,6 @@ #include -#include #include #include "SimpleSerialize.h" diff --git a/Code/Legacy/CrySystem/crysystem_files.cmake b/Code/Legacy/CrySystem/crysystem_files.cmake index dcf08d5408..6e8f9978fb 100644 --- a/Code/Legacy/CrySystem/crysystem_files.cmake +++ b/Code/Legacy/CrySystem/crysystem_files.cmake @@ -20,7 +20,6 @@ set(FILES SystemEventDispatcher.cpp SystemInit.cpp SystemWin32.cpp - Timer.cpp XConsole.cpp XConsoleVariable.cpp AZCrySystemInitLogSink.h @@ -36,7 +35,6 @@ set(FILES CrySystem_precompiled.h System.h SystemEventDispatcher.h - Timer.h XConsole.h XConsoleVariable.h XML/SerializeXMLReader.cpp diff --git a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp index 65508b6371..07a62eba1f 100644 --- a/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp +++ b/Gems/Atom/RPI/Code/Source/RPI.Public/Culling.cpp @@ -20,7 +20,6 @@ #include #include #include -#include #include #include #include diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h index d55755a242..9eaacbfa4f 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Include/AtomToolsFramework/Application/AtomToolsApplication.h @@ -58,7 +58,7 @@ namespace AtomToolsFramework void CreateStaticModules(AZStd::vector& outModules) override; const char* GetCurrentConfigurationName() const override; void StartCommon(AZ::Entity* systemEntity) override; - void Tick(float deltaOverride = -1.f) override; + void Tick() override; void Stop() override; protected: diff --git a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp index ba3bfe4718..a63a5e6b46 100644 --- a/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp +++ b/Gems/Atom/Tools/AtomToolsFramework/Code/Source/Application/AtomToolsApplication.cpp @@ -454,10 +454,10 @@ namespace AtomToolsFramework return false; } - void AtomToolsApplication::Tick(float deltaOverride) + void AtomToolsApplication::Tick() { TickSystem(); - Base::Tick(deltaOverride); + Base::Tick(); if (WasExitMainLoopRequested()) { diff --git a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp index e6439592b3..79f8d4708a 100644 --- a/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp +++ b/Gems/AtomLyIntegration/AtomBridge/Code/Source/FlyCameraInputComponent.cpp @@ -8,7 +8,6 @@ #include "FlyCameraInputComponent.h" #include -#include #include #include diff --git a/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp b/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp index b7fa03998e..15037793f1 100644 --- a/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp +++ b/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.cpp @@ -514,7 +514,6 @@ namespace EMotionFX AzToolsFramework::EditorEvents::Bus::Handler::BusConnect(); AzToolsFramework::EditorAnimationSystemRequestsBus::Handler::BusConnect(); AzToolsFramework::AssetBrowser::AssetBrowserInteractionNotificationBus::Handler::BusConnect(); - m_updateTimer.Stamp(); // Register custom property handlers for the reflected property editor. m_propertyHandlers = RegisterPropertyTypes(); @@ -604,15 +603,8 @@ namespace EMotionFX } ////////////////////////////////////////////////////////////////////////// - void SystemComponent::OnTick(float delta, AZ::ScriptTimePoint timePoint) + void SystemComponent::OnTick(float delta, [[maybe_unused]]AZ::ScriptTimePoint timePoint) { - AZ_UNUSED(timePoint); - -#if defined (EMOTIONFXANIMATION_EDITOR) - AZ_UNUSED(delta); - delta = m_updateTimer.StampAndGetDeltaTimeInSeconds(); -#endif - // Flush events prior to updating EMotion FX. ActorNotificationBus::ExecuteQueuedEvents(); diff --git a/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.h b/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.h index 5be9afbbaa..b5b990957c 100644 --- a/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.h +++ b/Gems/EMotionFX/Code/Source/Integration/System/SystemComponent.h @@ -20,7 +20,6 @@ #include #if defined (EMOTIONFXANIMATION_EDITOR) -# include # include # include # include @@ -117,7 +116,6 @@ namespace EMotionFX AzToolsFramework::AssetBrowser::SourceFileDetails GetSourceFileDetails(const char* fullSourceFileName) override; ////////////////////////////////////////////////////////////////////////////////////// - AZ::Debug::Timer m_updateTimer; AZStd::vector m_propertyHandlers; #endif // EMOTIONFXANIMATION_EDITOR diff --git a/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp b/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp index 4e06b832e1..3fb60cdaf6 100644 --- a/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp +++ b/Gems/FastNoise/Code/Tests/FastNoiseTest.cpp @@ -7,7 +7,6 @@ */ #include -#include #include #include #include @@ -106,7 +105,6 @@ struct MockGlobalEnvironment { MockGlobalEnvironment() { - m_stubEnv.pTimer = &m_stubTimer; m_stubEnv.pCryPak = &m_stubPak; m_stubEnv.pConsole = &m_stubConsole; m_stubEnv.pSystem = &m_stubSystem; @@ -120,7 +118,6 @@ struct MockGlobalEnvironment private: SSystemGlobalEnvironment m_stubEnv; - testing::NiceMock m_stubTimer; testing::NiceMock m_stubPak; testing::NiceMock m_stubConsole; testing::NiceMock m_stubSystem; diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.h b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.h index 65f4298c38..920bac6516 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.h +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.h @@ -10,6 +10,7 @@ #include "IGestureRecognizer.h" #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// namespace Gestures @@ -83,7 +84,7 @@ namespace Gestures Config m_config; - int64 m_timeOfLastEvent; + AZ::TimeMs m_timeOfLastEvent; ScreenPosition m_positionOfFirstEvent; ScreenPosition m_positionOfLastEvent; diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl index b14ef18994..8a079d7953 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerClickOrTap.inl @@ -8,9 +8,8 @@ #include #include +#include #include -#include -#include //////////////////////////////////////////////////////////////////////////////////////////////////// inline void Gestures::RecognizerClickOrTap::Config::Reflect(AZ::ReflectContext* context) @@ -57,7 +56,7 @@ inline void Gestures::RecognizerClickOrTap::Config::Reflect(AZ::ReflectContext* //////////////////////////////////////////////////////////////////////////////////////////////////// inline Gestures::RecognizerClickOrTap::RecognizerClickOrTap(const Config& config) : m_config(config) - , m_timeOfLastEvent(0) + , m_timeOfLastEvent(AZ::Time::ZeroTimeMs) , m_positionOfFirstEvent() , m_positionOfLastEvent() , m_currentCount(0) @@ -77,13 +76,12 @@ inline bool Gestures::RecognizerClickOrTap::OnPressedEvent(const AZ::Vector2& sc { return false; } - - const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue(); + const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs(); switch (m_currentState) { case State::Idle: { - m_timeOfLastEvent = currentTime.GetValue(); + m_timeOfLastEvent = currentTime; m_positionOfFirstEvent = screenPosition; m_positionOfLastEvent = screenPosition; m_currentCount = 0; @@ -92,7 +90,7 @@ inline bool Gestures::RecognizerClickOrTap::OnPressedEvent(const AZ::Vector2& sc break; case State::Released: { - if ((currentTime.GetDifferenceInSeconds(m_timeOfLastEvent) > m_config.maxSecondsBetweenClicksOrTaps) || + if ((AZ::TimeMsToSeconds(currentTime - m_timeOfLastEvent) > m_config.maxSecondsBetweenClicksOrTaps) || (screenPosition.GetDistance(m_positionOfFirstEvent) > m_config.maxPixelsBetweenClicksOrTaps)) { // Treat this as the start of a new tap sequence. @@ -100,7 +98,7 @@ inline bool Gestures::RecognizerClickOrTap::OnPressedEvent(const AZ::Vector2& sc m_positionOfFirstEvent = screenPosition; } - m_timeOfLastEvent = currentTime.GetValue(); + m_timeOfLastEvent = currentTime; m_positionOfLastEvent = screenPosition; m_currentState = State::Pressed; } @@ -129,8 +127,8 @@ inline bool Gestures::RecognizerClickOrTap::OnDownEvent(const AZ::Vector2& scree { case State::Pressed: { - const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue(); - if ((currentTime.GetDifferenceInSeconds(m_timeOfLastEvent) > m_config.maxSecondsHeld) || + const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs(); + if ((AZ::TimeMsToSeconds(currentTime - m_timeOfLastEvent) > m_config.maxSecondsHeld) || (screenPosition.GetDistance(m_positionOfLastEvent) > m_config.maxPixelsMoved)) { // Tap recognition failed. @@ -168,8 +166,8 @@ inline bool Gestures::RecognizerClickOrTap::OnReleasedEvent(const AZ::Vector2& s { case State::Pressed: { - const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue(); - if ((currentTime.GetDifferenceInSeconds(m_timeOfLastEvent) > m_config.maxSecondsHeld) || + const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs(); + if ((AZ::TimeMsToSeconds(currentTime - m_timeOfLastEvent) > m_config.maxSecondsHeld) || (screenPosition.GetDistance(m_positionOfLastEvent) > m_config.maxPixelsMoved)) { // Tap recognition failed. @@ -179,7 +177,7 @@ inline bool Gestures::RecognizerClickOrTap::OnReleasedEvent(const AZ::Vector2& s else if (++m_currentCount >= m_config.minClicksOrTaps) { // Tap recognition succeeded. - m_timeOfLastEvent = currentTime.GetValue(); + m_timeOfLastEvent = currentTime; m_positionOfLastEvent = screenPosition; OnDiscreteGestureRecognized(); @@ -190,7 +188,7 @@ inline bool Gestures::RecognizerClickOrTap::OnReleasedEvent(const AZ::Vector2& s else { // More taps are needed. - m_timeOfLastEvent = currentTime.GetValue(); + m_timeOfLastEvent = currentTime; m_positionOfLastEvent = screenPosition; m_currentState = State::Released; } diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.h b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.h index 97d76b1ceb..91c045b37f 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.h +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.h @@ -10,6 +10,7 @@ #include "IGestureRecognizer.h" #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// namespace Gestures @@ -75,7 +76,7 @@ namespace Gestures Config m_config; - int64 m_startTime; + AZ::TimeMs m_startTime; ScreenPosition m_startPosition; ScreenPosition m_currentPosition; diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl index 0c83893c9d..a0d0afe6f4 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerDrag.inl @@ -8,7 +8,6 @@ #include #include -#include #include //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -44,7 +43,7 @@ inline void Gestures::RecognizerDrag::Config::Reflect(AZ::ReflectContext* contex //////////////////////////////////////////////////////////////////////////////////////////////////// inline Gestures::RecognizerDrag::RecognizerDrag(const Config& config) : m_config(config) - , m_startTime(0) + , m_startTime(AZ::Time::ZeroTimeMs) , m_startPosition() , m_currentPosition() , m_currentState(State::Idle) @@ -68,7 +67,7 @@ inline bool Gestures::RecognizerDrag::OnPressedEvent(const AZ::Vector2& screenPo { case State::Idle: { - m_startTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0; + m_startTime = AZ::GetRealElapsedTimeMs(); m_startPosition = screenPosition; m_currentPosition = screenPosition; m_currentState = State::Pressed; @@ -101,11 +100,11 @@ inline bool Gestures::RecognizerDrag::OnDownEvent(const AZ::Vector2& screenPosit { case State::Pressed: { - const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue(); - if ((currentTime.GetDifferenceInSeconds(m_startTime) >= m_config.minSecondsHeld) && + const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs(); + if ((AZ::TimeMsToSeconds(currentTime - m_startTime) >= m_config.minSecondsHeld) && (GetDistance() >= m_config.minPixelsMoved)) { - m_startTime = currentTime.GetValue(); + m_startTime = currentTime; m_startPosition = m_currentPosition; OnContinuousGestureInitiated(); m_currentState = State::Dragging; diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h index 11bd56ff4d..a2c4a55166 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.h @@ -10,8 +10,8 @@ #include "IGestureRecognizer.h" #include -#include #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// namespace Gestures @@ -64,7 +64,7 @@ namespace Gestures AZ::Vector2 GetStartPosition() const { return m_startPosition; } AZ::Vector2 GetCurrentPosition() const { return m_currentPosition; } - float GetDuration() const { return (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetDifferenceInSeconds(m_startTime) : 0.0f; } + float GetDuration() const { return AZ::TimeUsToSeconds(AZ::GetLastSimulationTickTime() - m_startTime); } private: enum class State @@ -76,7 +76,7 @@ namespace Gestures Config m_config; - int64 m_startTime; + AZ::TimeUs m_startTime; ScreenPosition m_startPosition; ScreenPosition m_currentPosition; diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl index 6af8a10890..75578edca1 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerHold.inl @@ -8,7 +8,6 @@ #include #include -#include #include //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -44,7 +43,7 @@ inline void Gestures::RecognizerHold::Config::Reflect(AZ::ReflectContext* contex //////////////////////////////////////////////////////////////////////////////////////////////////// inline Gestures::RecognizerHold::RecognizerHold(const Config& config) : m_config(config) - , m_startTime(0) + , m_startTime(AZ::Time::ZeroTimeUs) , m_startPosition() , m_currentPosition() , m_currentState(State::Idle) @@ -68,7 +67,7 @@ inline bool Gestures::RecognizerHold::OnPressedEvent(const AZ::Vector2& screenPo { case State::Idle: { - m_startTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0; + m_startTime = AZ::GetLastSimulationTickTime(); m_startPosition = screenPosition; m_currentPosition = screenPosition; m_currentState = State::Pressed; @@ -101,13 +100,13 @@ inline bool Gestures::RecognizerHold::OnDownEvent(const AZ::Vector2& screenPosit { case State::Pressed: { - const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue(); if (screenPosition.GetDistance(m_startPosition) > m_config.maxPixelsMoved) { // Hold recognition failed. m_currentState = State::Idle; } - else if (currentTime.GetDifferenceInSeconds(m_startTime) >= m_config.minSecondsHeld) + else if (const AZ::TimeUs currentTime = AZ::GetLastSimulationTickTime(); + AZ::TimeUsToSeconds(currentTime - m_startTime) >= m_config.minSecondsHeld) { // Hold recognition succeeded. OnContinuousGestureInitiated(); diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.h b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.h index c5fa773339..8d5cd76e7d 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.h +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.h @@ -10,6 +10,7 @@ #include "IGestureRecognizer.h" #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// namespace Gestures @@ -90,7 +91,7 @@ namespace Gestures ScreenPosition m_startPositions[2]; ScreenPosition m_currentPositions[2]; - int64_t m_lastUpdateTimes[2]; + AZ::TimeMs m_lastUpdateTimes[2]; State m_currentState; }; diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl index 642d781c35..70231becb1 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerPinch.inl @@ -8,7 +8,6 @@ #include #include -#include #include //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -42,8 +41,8 @@ inline Gestures::RecognizerPinch::RecognizerPinch(const Config& config) : m_config(config) , m_currentState(State::Idle) { - m_lastUpdateTimes[0] = 0; - m_lastUpdateTimes[1] = 0; + m_lastUpdateTimes[0] = AZ::Time::ZeroTimeMs; + m_lastUpdateTimes[1] = AZ::Time::ZeroTimeMs; } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -112,7 +111,7 @@ inline bool Gestures::RecognizerPinch::OnDownEvent(const AZ::Vector2& screenPosi } m_currentPositions[pointerIndex] = screenPosition; - m_lastUpdateTimes[pointerIndex] = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0; + m_lastUpdateTimes[pointerIndex] = AZ::GetRealElapsedTimeMs(); if (m_lastUpdateTimes[0] != m_lastUpdateTimes[1]) { // We need to wait until both touches have been updated this frame. diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.h b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.h index b2d31e3d4f..a07aad7d6a 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.h +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.h @@ -10,6 +10,7 @@ #include "IGestureRecognizer.h" #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// namespace Gestures @@ -86,7 +87,7 @@ namespace Gestures ScreenPosition m_startPositions[2]; ScreenPosition m_currentPositions[2]; - int64_t m_lastUpdateTimes[2]; + AZ::TimeMs m_lastUpdateTimes[2]; State m_currentState; }; diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl index 2ae504e309..894a2dd2e8 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerRotate.inl @@ -9,7 +9,6 @@ #include #include #include -#include //////////////////////////////////////////////////////////////////////////////////////////////////// inline void Gestures::RecognizerRotate::Config::Reflect(AZ::ReflectContext* context) @@ -42,8 +41,8 @@ inline Gestures::RecognizerRotate::RecognizerRotate(const Config& config) : m_config(config) , m_currentState(State::Idle) { - m_lastUpdateTimes[0] = 0; - m_lastUpdateTimes[1] = 0; + m_lastUpdateTimes[0] = AZ::Time::ZeroTimeMs; + m_lastUpdateTimes[1] = AZ::Time::ZeroTimeMs; } //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -101,7 +100,7 @@ inline bool Gestures::RecognizerRotate::OnDownEvent(const AZ::Vector2& screenPos } m_currentPositions[pointerIndex] = screenPosition; - m_lastUpdateTimes[pointerIndex] = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0; + m_lastUpdateTimes[pointerIndex] = AZ::GetRealElapsedTimeMs(); if (m_lastUpdateTimes[0] != m_lastUpdateTimes[1]) { // We need to wait until both touches have been updated this frame. diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.h b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.h index bf0181e2b9..ed63991b3a 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.h +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.h @@ -8,8 +8,8 @@ #pragma once #include "IGestureRecognizer.h" -#include #include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// namespace Gestures @@ -66,7 +66,7 @@ namespace Gestures AZ::Vector2 GetDirection() const { return GetDelta().GetNormalized(); } float GetDistance() const { return GetEndPosition().GetDistance(GetStartPosition()); } - float GetDuration() const { return CTimeValue(m_endTime).GetDifferenceInSeconds(m_startTime); } + float GetDuration() const { return AZ::TimeMsToSeconds(m_endTime - m_startTime); } float GetVelocity() const { return GetDistance() / GetDuration(); } private: @@ -81,8 +81,8 @@ namespace Gestures ScreenPosition m_startPosition; ScreenPosition m_endPosition; - int64 m_startTime; - int64 m_endTime; + AZ::TimeMs m_startTime; + AZ::TimeMs m_endTime; State m_currentState; }; diff --git a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl index 5f879ce423..072cebcbb5 100644 --- a/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl +++ b/Gems/Gestures/Code/Include/Gestures/GestureRecognizerSwipe.inl @@ -45,8 +45,8 @@ inline Gestures::RecognizerSwipe::RecognizerSwipe(const Config& config) : m_config(config) , m_startPosition() , m_endPosition() - , m_startTime(0) - , m_endTime(0) + , m_startTime(AZ::Time::ZeroTimeMs) + , m_endTime(AZ::Time::ZeroTimeMs) , m_currentState(State::Idle) { } @@ -68,7 +68,7 @@ inline bool Gestures::RecognizerSwipe::OnPressedEvent(const AZ::Vector2& screenP { case State::Idle: { - m_startTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime().GetValue() : 0; + m_startTime = AZ::GetRealElapsedTimeMs(); m_startPosition = screenPosition; m_endPosition = screenPosition; m_currentState = State::Pressed; @@ -98,8 +98,8 @@ inline bool Gestures::RecognizerSwipe::OnDownEvent([[maybe_unused]] const AZ::Ve { case State::Pressed: { - const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue(); - if (currentTime.GetDifferenceInSeconds(m_startTime) > m_config.maxSecondsHeld) + const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs(); + if (AZ::TimeMsToSeconds(currentTime - m_startTime) > m_config.maxSecondsHeld) { // Swipe recognition failed because we took too long. m_currentState = State::Idle; @@ -134,12 +134,12 @@ inline bool Gestures::RecognizerSwipe::OnReleasedEvent(const AZ::Vector2& screen { case State::Pressed: { - const CTimeValue currentTime = (gEnv && gEnv->pTimer) ? gEnv->pTimer->GetFrameStartTime() : CTimeValue(); - if ((currentTime.GetDifferenceInSeconds(m_startTime) <= m_config.maxSecondsHeld) && + const AZ::TimeMs currentTime = AZ::GetRealElapsedTimeMs(); + if ((AZ::TimeMsToSeconds(currentTime - m_startTime) <= m_config.maxSecondsHeld) && (screenPosition.GetDistance(m_startPosition) >= m_config.minPixelsMoved)) { // Swipe recognition succeeded. - m_endTime = currentTime.GetValue(); + m_endTime = currentTime; m_endPosition = screenPosition; OnDiscreteGestureRecognized(); m_currentState = State::Idle; diff --git a/Gems/Gestures/Code/Tests/BaseGestureTest.h b/Gems/Gestures/Code/Tests/BaseGestureTest.h index b0897e258a..56cc4b6777 100644 --- a/Gems/Gestures/Code/Tests/BaseGestureTest.h +++ b/Gems/Gestures/Code/Tests/BaseGestureTest.h @@ -6,13 +6,25 @@ * */ #pragma once -#include -#include -#include #include +#include +#include +#include -class BaseGestureTest - : public ::testing::Test +namespace GesturesTests +{ + struct StubTimer : public AZ::StubTimeSystem + { + AZ::TimeMs GetRealElapsedTimeMs() const override + { + return m_realElapsedTime; + } + + AZ::TimeMs m_realElapsedTime = AZ::Time::ZeroTimeMs; + }; +} // namespace GesturesTests + +class BaseGestureTest : public ::testing::Test { public: BaseGestureTest() @@ -24,39 +36,30 @@ public: { // global environment stubs m_env = new(AZ_OS_MALLOC(sizeof(SSystemGlobalEnvironment), alignof(SSystemGlobalEnvironment))) SSystemGlobalEnvironment(); - m_stubTimer = new StubTimer(1.0f / 30.0f); gEnv = m_env; - gEnv->pTimer = m_stubTimer; - + m_stubTimer = new GesturesTests::StubTimer(); // simulated position m_pos = AZ::Vector2(0.0f, 0.0f); } void TearDown() override { - gEnv->pTimer = nullptr; gEnv = nullptr; - if (m_stubTimer) - { - delete m_stubTimer; - m_stubTimer = nullptr; - } if (m_env) { m_env->~SSystemGlobalEnvironment(); AZ_OS_FREE(m_env); m_env = nullptr; } + delete m_stubTimer; } - protected: - // time manipulation void SetTime(float sec) { - m_stubTimer->SetTime(sec); + m_stubTimer->m_realElapsedTime = AZ::SecondsToTimeMs(sec); } // simple position caching interface @@ -97,9 +100,7 @@ protected: } private: - SSystemGlobalEnvironment* m_env; - StubTimer* m_stubTimer; + SSystemGlobalEnvironment* m_env = nullptr; + GesturesTests::StubTimer* m_stubTimer = nullptr; AZ::Vector2 m_pos; }; - - diff --git a/Gems/Gestures/Code/Tests/GestureRecognizerClickOrTapTests.cpp b/Gems/Gestures/Code/Tests/GestureRecognizerClickOrTapTests.cpp index 72fca0498d..9337ae87ed 100644 --- a/Gems/Gestures/Code/Tests/GestureRecognizerClickOrTapTests.cpp +++ b/Gems/Gestures/Code/Tests/GestureRecognizerClickOrTapTests.cpp @@ -7,7 +7,6 @@ */ #include -#include #include #include "BaseGestureTest.h" diff --git a/Gems/Gestures/Code/Tests/GestureRecognizerPinchTests.cpp b/Gems/Gestures/Code/Tests/GestureRecognizerPinchTests.cpp index bb7ac4a75a..3d39a888b5 100644 --- a/Gems/Gestures/Code/Tests/GestureRecognizerPinchTests.cpp +++ b/Gems/Gestures/Code/Tests/GestureRecognizerPinchTests.cpp @@ -7,7 +7,6 @@ */ #include -#include #include #include "BaseGestureTest.h" diff --git a/Gems/ImGui/Code/Source/ImGuiManager.cpp b/Gems/ImGui/Code/Source/ImGuiManager.cpp index d631e2f83e..b30eda8825 100644 --- a/Gems/ImGui/Code/Source/ImGuiManager.cpp +++ b/Gems/ImGui/Code/Source/ImGuiManager.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -23,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -333,7 +333,8 @@ void ImGuiManager::Render() } // Advance ImGui by Elapsed Frame Time - io.DeltaTime = gEnv->pTimer->GetFrameTime(); + const AZ::TimeUs gameTickTimeUs = AZ::GetSimulationTickDeltaTimeUs(); + io.DeltaTime = AZ::TimeUsToSeconds(gameTickTimeUs); //// END FROM PREUPDATE AZ::u32 backBufferWidth = m_windowSize.m_width; diff --git a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.cpp b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.cpp index d2f86a65cd..ecc97682de 100644 --- a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.cpp +++ b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.cpp @@ -44,11 +44,15 @@ namespace ImGui m_assetExplorer.Initialize(); m_cameraMonitor.Initialize(); m_entityOutliner.Initialize(); + + m_deltaTimeHistogram.Init("onTick Delta Time (Milliseconds)", 250, LYImGuiUtils::HistogramContainer::ViewType::Histogram, true, 0.0f, 60.0f); + AZ::TickBus::Handler::BusConnect(); } void ImGuiLYCommonMenu::Shutdown() { // Disconnect EBusses + AZ::TickBus::Handler::BusDisconnect(); ImGuiUpdateListenerBus::Handler::BusDisconnect(); // shutdown sub menu objects @@ -187,6 +191,10 @@ namespace ImGui // Main Open 3D Engine menu if (ImGui::BeginMenu("O3DE")) { + if (ImGui::MenuItem("Delta Time Graph")) + { + m_showDeltaTimeGraphs = !m_showDeltaTimeGraphs; + } // Asset Explorer if (ImGui::MenuItem("Asset Explorer")) { @@ -628,6 +636,17 @@ namespace ImGui m_assetExplorer.ImGuiUpdate(); m_cameraMonitor.ImGuiUpdate(); m_entityOutliner.ImGuiUpdate(); + if (m_showDeltaTimeGraphs) + { + ImGui::SetNextWindowSize({ 500, 200 }, ImGuiCond_Once); + if (ImGui::Begin( + "Delta Time Graphs", &m_showDeltaTimeGraphs, + ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_HorizontalScrollbar | ImGuiWindowFlags_NoSavedSettings)) + { + m_deltaTimeHistogram.Draw(ImGui::GetColumnWidth(), 100.0f); + } + ImGui::End(); + } } void ImGuiLYCommonMenu::OnImGuiUpdate_DrawControllerLegend() @@ -754,7 +773,6 @@ namespace ImGui // Set the timer and connect to tick bus to count down. m_telemetryCaptureTimeRemaining = m_telemetryCaptureTime; - AZ::TickBus::Handler::BusConnect(); // Get the current ImGui Display state to restore it later. ImGuiManagerBus::BroadcastResult(m_telemetryCapturePreCaptureState, &IImGuiManager::GetClientMenuBarState); @@ -774,16 +792,20 @@ namespace ImGui // Reset timer and disconnect tick bus m_telemetryCaptureTimeRemaining = 0.0f; - AZ::TickBus::Handler::BusDisconnect(); } // OnTick just used for telemetry captures. void ImGuiLYCommonMenu::OnTick(float deltaTime, [[maybe_unused]] AZ::ScriptTimePoint time) { - m_telemetryCaptureTimeRemaining -= deltaTime; - if (m_telemetryCaptureTimeRemaining <= 0.0f) + m_deltaTimeHistogram.PushValue(deltaTime*1000.0f); // convert to milliseconds + + if (m_telemetryCaptureTimeRemaining > 0.0f) { - StopTelemetryCapture(); + m_telemetryCaptureTimeRemaining -= deltaTime; + if (m_telemetryCaptureTimeRemaining <= 0.0f) + { + StopTelemetryCapture(); + } } } } // namespace ImGui diff --git a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.h b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.h index fae892b4a2..a63d2fd844 100644 --- a/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.h +++ b/Gems/ImGui/Code/Source/LYCommonMenu/ImGuiLYCommonMenu.h @@ -50,6 +50,8 @@ namespace ImGui ImGuiLYAssetExplorer m_assetExplorer; ImGuiLYCameraMonitor m_cameraMonitor; ImGuiLYEntityOutliner m_entityOutliner; + bool m_showDeltaTimeGraphs = false; + ImGui::LYImGuiUtils::HistogramContainer m_deltaTimeHistogram; }; } diff --git a/Gems/LmbrCentral/Code/Source/Scripting/RandomTimedSpawnerComponent.cpp b/Gems/LmbrCentral/Code/Source/Scripting/RandomTimedSpawnerComponent.cpp index 275a50c13b..f426bc6075 100644 --- a/Gems/LmbrCentral/Code/Source/Scripting/RandomTimedSpawnerComponent.cpp +++ b/Gems/LmbrCentral/Code/Source/Scripting/RandomTimedSpawnerComponent.cpp @@ -13,6 +13,7 @@ #include #include +#include namespace LmbrCentral { @@ -88,8 +89,8 @@ namespace LmbrCentral void RandomTimedSpawnerComponent::Activate() { - AZStd::chrono::system_clock::time_point now = AZStd::chrono::system_clock::now(); - m_currentTime = AZ::ScriptTimePoint(now).GetSeconds(); + const AZ::TimeUs elapsedTimeUs = AZ::GetElapsedTimeUs(); + m_currentTime = AZ::TimeUsToSecondsDouble(elapsedTimeUs); RandomTimedSpawnerComponentRequestBus::Handler::BusConnect(GetEntityId()); CalculateNextSpawnTime(); diff --git a/Gems/LyShine/Code/Editor/Animation/AnimationContext.cpp b/Gems/LyShine/Code/Editor/Animation/AnimationContext.cpp index 8f8864106b..1e81f2e179 100644 --- a/Gems/LyShine/Code/Editor/Animation/AnimationContext.cpp +++ b/Gems/LyShine/Code/Editor/Animation/AnimationContext.cpp @@ -13,7 +13,6 @@ #include "AnimationContext.h" #include -#include "ITimer.h" #include "GameEngine.h" #include "Objects/SelectionGroup.h" @@ -29,6 +28,27 @@ #include "IPostRenderer.h" #include "UiEditorAnimationBus.h" +#include + +namespace Internal +{ + float GetFrameDeltaTime() + { + const AZ::TimeUs frameDeltaTimeMs = AZ::GetSimulationTickDeltaTimeUs(); + return AZ::TimeUsToSeconds(frameDeltaTimeMs); + } + + float GetFrameRate() + { + const float deltaTime = GetFrameDeltaTime(); + if (AZ::IsClose(deltaTime, 0.0f)) + { + return 0.0f; + } + return 1.0f / deltaTime; + } +} + ////////////////////////////////////////////////////////////////////////// // Animation Callback. ////////////////////////////////////////////////////////////////////////// @@ -380,17 +400,15 @@ void CUiAnimationContext::Update() return; } - ITimer* pTimer = GetIEditor()->GetSystem()->GetITimer(); - AnimateActiveSequence(); - float dt = pTimer->GetFrameTime(); - m_currTime += dt * m_fTimeScale; + const float frameDeltaTime = Internal::GetFrameDeltaTime(); + m_currTime += frameDeltaTime * m_fTimeScale; if (!m_recording) { - GetUiAnimationSystem()->PreUpdate(dt); - GetUiAnimationSystem()->PostUpdate(dt); + GetUiAnimationSystem()->PreUpdate(frameDeltaTime); + GetUiAnimationSystem()->PostUpdate(frameDeltaTime); } if (m_currTime > m_timeMarker.end) @@ -444,7 +462,7 @@ void CUiAnimationContext::OnPostRender() { SUiAnimContext ac; ac.dt = 0; - ac.fps = GetIEditor()->GetSystem()->GetITimer()->GetFrameRate(); + ac.fps = Internal::GetFrameRate(); ac.time = m_currTime; ac.bSingleFrame = true; ac.bForcePlay = true; @@ -586,7 +604,7 @@ void CUiAnimationContext::AnimateActiveSequence() SUiAnimContext ac; ac.dt = 0; - ac.fps = GetIEditor()->GetSystem()->GetITimer()->GetFrameRate(); + ac.fps = Internal::GetFrameRate(); ac.time = m_currTime; ac.bSingleFrame = true; ac.bForcePlay = true; diff --git a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp index a333183cde..d904be02b1 100644 --- a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp +++ b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.cpp @@ -22,7 +22,6 @@ #include #include #include -#include #include ////////////////////////////////////////////////////////////////////////// @@ -97,7 +96,7 @@ UiAnimationSystem::UiAnimationSystem() m_pCallback = NULL; m_bPaused = false; m_sequenceStopBehavior = eSSB_GotoEndTime; - m_lastUpdateTime.SetValue(0); + m_lastUpdateTime = AZ::Time::ZeroTimeUs; m_nextSequenceId = 1; } @@ -793,7 +792,7 @@ void UiAnimationSystem::UpdateInternal(const float deltaTime, const bool bPreUpd } // don't update more than once if dt==0.0 - CTimeValue curTime = gEnv->pTimer->GetFrameStartTime(); + const AZ::TimeUs curTime = AZ::GetElapsedTimeUs(); if (deltaTime == 0.0f && curTime == m_lastUpdateTime && !gEnv->IsEditor()) { return; diff --git a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.h b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.h index c270d9ca60..cd51cd51d0 100644 --- a/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.h +++ b/Gems/LyShine/Code/Source/Animation/UiAnimationSystem.h @@ -12,6 +12,7 @@ #include #include #include +#include struct PlayingUIAnimSequence { @@ -164,7 +165,7 @@ private: IUiAnimationCallback* m_pCallback; - CTimeValue m_lastUpdateTime; + AZ::TimeUs m_lastUpdateTime; using Sequences = AZStd::vector >; Sequences m_sequences; diff --git a/Gems/LyShine/Code/Source/UiFaderComponent.cpp b/Gems/LyShine/Code/Source/UiFaderComponent.cpp index d9309a7505..cfca774612 100644 --- a/Gems/LyShine/Code/Source/UiFaderComponent.cpp +++ b/Gems/LyShine/Code/Source/UiFaderComponent.cpp @@ -23,8 +23,6 @@ #include #include -#include - #include "UiSerialize.h" #include "RenderToTextureBus.h" diff --git a/Gems/LyShine/Code/Source/UiFlipbookAnimationComponent.cpp b/Gems/LyShine/Code/Source/UiFlipbookAnimationComponent.cpp index 9b09630957..b68f92c0fc 100644 --- a/Gems/LyShine/Code/Source/UiFlipbookAnimationComponent.cpp +++ b/Gems/LyShine/Code/Source/UiFlipbookAnimationComponent.cpp @@ -19,7 +19,6 @@ #include #include #include -#include namespace { diff --git a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp index c6fd144d3a..25498fc316 100644 --- a/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp +++ b/Gems/LyShine/Code/Source/UiParticleEmitterComponent.cpp @@ -15,6 +15,7 @@ #include #include #include +#include #include @@ -73,7 +74,7 @@ void UiParticleEmitterComponent::SetIsEmitting(bool emitParticles) { m_nextEmitTime = (m_isHitParticleCountOnActivate ? -m_particleLifetime : 0.0f); m_emitterAge = 0.0f; - m_random.SetSeed(m_isRandomSeedFixed ? m_randomSeed : gEnv->pTimer->GetAsyncTime().GetMilliSecondsAsInt64()); + m_random.SetSeed(m_isRandomSeedFixed ? m_randomSeed : aznumeric_cast(AZ::GetElapsedTimeMs())); } m_isEmitting = emitParticles; } diff --git a/Gems/LyShine/Code/Source/UiScrollBarComponent.cpp b/Gems/LyShine/Code/Source/UiScrollBarComponent.cpp index f4ea3f5e2c..b1a3530bd8 100644 --- a/Gems/LyShine/Code/Source/UiScrollBarComponent.cpp +++ b/Gems/LyShine/Code/Source/UiScrollBarComponent.cpp @@ -18,7 +18,7 @@ #include #include -#include +#include //////////////////////////////////////////////////////////////////////////////////////////////////// //! UiScrollerNotificationBus Behavior context handler class @@ -436,7 +436,8 @@ bool UiScrollBarComponent::HandlePressed(AZ::Vector2 point, bool& shouldStayActi else { // Move handle - m_lastMoveTime = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); + const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs(); + m_lastMoveTime = AZ::TimeMsToSeconds(realTimeMs); m_moveDelayTime = 0.45f; MoveHandle(pointLoc); @@ -617,7 +618,8 @@ void UiScrollBarComponent::InputPositionUpdate(AZ::Vector2 point) LocRelativeToHandle pointLoc = GetLocationRelativeToHandle(point); if (pointLoc != LocRelativeToHandle::OnHandle) { - const float currentTime = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); + const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs(); + const float currentTime = AZ::TimeMsToSeconds(realTimeMs); if (currentTime - m_lastMoveTime > m_moveDelayTime) { m_lastMoveTime = currentTime; diff --git a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp index e789301572..9a55a3feeb 100644 --- a/Gems/LyShine/Code/Source/UiTextInputComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTextInputComponent.cpp @@ -13,11 +13,11 @@ #include #include #include +#include #include #include -#include #include #include #include @@ -745,19 +745,17 @@ void UiTextInputComponent::Update(float deltaTime) // update cursor blinking, only if: this component is active, and blink interval set, and there is no text selection if (m_isEditing && m_cursorBlinkInterval > 0.0f && m_textSelectionStartPos == m_textCursorPos) { + const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs(); + const float currentTime = AZ::TimeMsToSeconds(realTimeMs); if (m_cursorBlinkStartTime == 0.0f) { - m_cursorBlinkStartTime = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); + m_cursorBlinkStartTime = currentTime; } - else + else if (currentTime - m_cursorBlinkStartTime > m_cursorBlinkInterval * 0.5f) { - const float currentTime = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); - if (currentTime - m_cursorBlinkStartTime > m_cursorBlinkInterval * 0.5f) - { - m_textCursorColor.SetA(m_textCursorColor.GetA() ? 0.0f : 1.0f); - m_cursorBlinkStartTime = currentTime; - EBUS_EVENT_ID(m_textEntity, UiTextBus, SetSelectionRange, m_textSelectionStartPos, m_textCursorPos, m_textCursorColor); - } + m_textCursorColor.SetA(m_textCursorColor.GetA() ? 0.0f : 1.0f); + m_cursorBlinkStartTime = currentTime; + EBUS_EVENT_ID(m_textEntity, UiTextBus, SetSelectionRange, m_textSelectionStartPos, m_textCursorPos, m_textCursorColor); } } } diff --git a/Gems/LyShine/Code/Source/UiTooltipDisplayComponent.cpp b/Gems/LyShine/Code/Source/UiTooltipDisplayComponent.cpp index b1adfb6157..cad2dc2b5f 100644 --- a/Gems/LyShine/Code/Source/UiTooltipDisplayComponent.cpp +++ b/Gems/LyShine/Code/Source/UiTooltipDisplayComponent.cpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include @@ -19,8 +20,6 @@ #include #include -#include - //////////////////////////////////////////////////////////////////////////////////////////////////// // PUBLIC MEMBER FUNCTIONS //////////////////////////////////////////////////////////////////////////////////////////////////// @@ -173,8 +172,8 @@ void UiTooltipDisplayComponent::Hide() { // Since sequences can't have keys that represent current values, // only play the hide animation if the show animation has completed. - - m_timeSinceLastShown = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); + const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs(); + m_timeSinceLastShown = AZ::TimeMsToSeconds(realTimeMs); EndTransitionState(); @@ -184,7 +183,8 @@ void UiTooltipDisplayComponent::Hide() case State::Shown: { - m_timeSinceLastShown = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); + const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs(); + m_timeSinceLastShown = AZ::TimeMsToSeconds(realTimeMs); // Check if there is a hide animation to play IUiAnimationSystem* animSystem = nullptr; @@ -220,7 +220,9 @@ void UiTooltipDisplayComponent::Update() if (m_state == State::DelayBeforeShow) { // Check if it's time to show the tooltip - if ((gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI) - m_stateStartTime) >= m_curDelayTime) + const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs(); + const float currentTime = AZ::TimeMsToSeconds(realTimeMs); + if ((currentTime - m_stateStartTime) >= m_curDelayTime) { // Make sure nothing has changed with the hover interactable if (m_tooltipElement.IsValid() && UiTooltipDataPopulatorBus::FindFirstHandler(m_tooltipElement)) @@ -238,7 +240,9 @@ void UiTooltipDisplayComponent::Update() // Check if it's time to hide the tooltip if (m_displayTime >= 0.0f) { - if ((gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI) - m_stateStartTime) >= m_displayTime) + const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs(); + const float currentTime = AZ::TimeMsToSeconds(realTimeMs); + if ((currentTime - m_stateStartTime) >= m_displayTime) { // Hide tooltip Hide(); @@ -425,7 +429,8 @@ void UiTooltipDisplayComponent::Deactivate() void UiTooltipDisplayComponent::SetState(State state) { m_state = state; - m_stateStartTime = gEnv->pTimer->GetCurrTime(ITimer::ETIMER_UI); + const AZ::TimeMs realTimeMs = AZ::GetRealElapsedTimeMs(); + m_stateStartTime = AZ::TimeMsToSeconds(realTimeMs); switch (m_state) { diff --git a/Gems/LyShine/Code/Tests/AnimationTest.cpp b/Gems/LyShine/Code/Tests/AnimationTest.cpp index 1fc662413f..92762d02ed 100644 --- a/Gems/LyShine/Code/Tests/AnimationTest.cpp +++ b/Gems/LyShine/Code/Tests/AnimationTest.cpp @@ -8,7 +8,8 @@ #include "LyShineTest.h" #include -#include +#include +#include #include #include @@ -17,21 +18,26 @@ namespace UnitTest { - class FrameTimerMock - : public TimerMock + struct AnimationTestStubTimer : public AZ::StubTimeSystem { - public: - const CTimeValue& GetFrameStartTime([[maybe_unused]] ITimer::ETimer which = ITimer::ETIMER_GAME) const override + AZ_RTTI(UnitTest::AnimationTestStubTimer, "{541EBC6C-E793-4433-9402-4CAD2F6770E3}", AZ::StubTimeSystem); + + AZ::TimeMs GetElapsedTimeMs() const override { - return m_frameStartTime; - } - void AddFrameStartTime(float seconds) - { - m_frameStartTime += CTimeValue(seconds); + return AZ::TimeUsToMs(m_timeUs); } - private: - CTimeValue m_frameStartTime = CTimeValue(); + AZ::TimeUs GetElapsedTimeUs() const override + { + return m_timeUs; + } + + void AddFrameTime(float sec) + { + m_timeUs += AZ::SecondsToTimeUs(sec); + } + + AZ::TimeUs m_timeUs = AZ::Time::ZeroTimeUs; }; class TrackEventHandler @@ -65,6 +71,22 @@ namespace UnitTest AZStd::vector m_recievedEvents; }; + class LyShineAnimationTestApplication : public AzFramework::Application + { + public: + LyShineAnimationTestApplication() + : AzFramework::Application() + { + m_timeSystem.reset(); + m_timeSystem = AZStd::make_unique(); + } + + UnitTest::AnimationTestStubTimer* GetTimer() + { + return azdynamic_cast(m_timeSystem.get()); + } + }; + class LyShineAnimationTest : public LyShineTest { @@ -74,31 +96,38 @@ namespace UnitTest { } + void SetupApplication() override + { + AZ::ComponentApplication::Descriptor appDesc; + appDesc.m_memoryBlocksByteSize = 10 * 1024 * 1024; + appDesc.m_recordingMode = AZ::Debug::AllocationRecords::RECORD_FULL; + appDesc.m_stackRecordLevels = 20; + + m_application = aznew LyShineAnimationTestApplication(); + m_systemEntity = m_application->Create(appDesc); + m_systemEntity->Init(); + m_systemEntity->Activate(); + } + void SetupEnvironment() override { LyShineTest::SetupEnvironment(); - m_data = AZStd::make_unique(); - m_env->m_stubEnv.pTimer = &m_data->m_timer; - m_canvasComponent = aznew UiCanvasComponent; } void TearDown() override { delete m_canvasComponent; - m_data.reset(); UiAnimationNotificationBus::ClearQueuedEvents(); LyShineTest::TearDown(); } - struct Data + UnitTest::AnimationTestStubTimer* GetTimer() { - testing::NiceMock m_timer; - }; - - AZStd::unique_ptr m_data; + return static_cast(m_application)->GetTimer(); + } UiCanvasComponent* m_canvasComponent; }; @@ -126,13 +155,14 @@ namespace UnitTest eventHandler.Connect(m_canvasComponent->GetEntityId()); animSys->PlaySequence(sequence, nullptr, true, true); + UnitTest::AnimationTestStubTimer* timer = GetTimer(); for (int frame = 0; frame < 2; ++frame) { static float deltaTime = 1.0f / 60.0f; animSys->PreUpdate(deltaTime); animSys->PostUpdate(deltaTime); - m_data->m_timer.AddFrameStartTime(deltaTime); + timer->AddFrameTime(deltaTime); } UiAnimationNotificationBus::ExecuteQueuedEvents(); diff --git a/Gems/LyShine/Code/Tests/LyShineTest.h b/Gems/LyShine/Code/Tests/LyShineTest.h index 250b53ee40..a2383f87cc 100644 --- a/Gems/LyShine/Code/Tests/LyShineTest.h +++ b/Gems/LyShine/Code/Tests/LyShineTest.h @@ -37,7 +37,7 @@ namespace UnitTest appDesc.m_recordingMode = AZ::Debug::AllocationRecords::RECORD_FULL; appDesc.m_stackRecordLevels = 20; - m_systemEntity = m_application.Create(appDesc); + m_systemEntity = m_application->Create(appDesc); m_systemEntity->Init(); m_systemEntity->Activate(); } @@ -54,7 +54,9 @@ namespace UnitTest { m_env.reset(); gEnv = m_priorEnv; - m_application.Destroy(); + m_application->Destroy(); + delete m_application; + m_application = nullptr; } struct StubEnv @@ -62,8 +64,8 @@ namespace UnitTest SSystemGlobalEnvironment m_stubEnv; }; - AZ::ComponentApplication m_application; - AZ::Entity* m_systemEntity; + AZ::ComponentApplication* m_application = nullptr; + AZ::Entity* m_systemEntity = nullptr; AZStd::unique_ptr m_env; SSystemGlobalEnvironment* m_priorEnv = nullptr; diff --git a/Gems/LyShine/Code/Tests/SerializationTest.cpp b/Gems/LyShine/Code/Tests/SerializationTest.cpp index 70ae590358..61d39294f8 100644 --- a/Gems/LyShine/Code/Tests/SerializationTest.cpp +++ b/Gems/LyShine/Code/Tests/SerializationTest.cpp @@ -30,7 +30,8 @@ namespace UnitTest modules.emplace_back(new LyShine::LyShineModule); }; - m_systemEntity = m_application.Create(appDesc, appStartup); + m_application = aznew AZ::ComponentApplication(); + m_systemEntity = m_application->Create(appDesc, appStartup); m_systemEntity->Init(); m_systemEntity->Activate(); } diff --git a/Gems/LyShine/Code/Tests/SpriteTest.cpp b/Gems/LyShine/Code/Tests/SpriteTest.cpp index 596cf43c2f..2fc82546be 100644 --- a/Gems/LyShine/Code/Tests/SpriteTest.cpp +++ b/Gems/LyShine/Code/Tests/SpriteTest.cpp @@ -31,7 +31,8 @@ namespace UnitTest modules.emplace_back(new LyShine::LyShineModule); }; - m_systemEntity = m_application.Create(appDesc, appStartup); + m_application = aznew AZ::ComponentApplication(); + m_systemEntity = m_application->Create(appDesc, appStartup); m_systemEntity->Init(); m_systemEntity->Activate(); } diff --git a/Gems/LyShine/Code/Tests/UiTooltipComponentTest.cpp b/Gems/LyShine/Code/Tests/UiTooltipComponentTest.cpp index 65ca1ec280..8a3d9f2af6 100644 --- a/Gems/LyShine/Code/Tests/UiTooltipComponentTest.cpp +++ b/Gems/LyShine/Code/Tests/UiTooltipComponentTest.cpp @@ -24,54 +24,38 @@ #include #include #include +#include namespace UnitTest { - class MockTimer : public ITimer + struct UiTooltipTestStubTimer : public AZ::StubTimeSystem { - public: - mutable float m_timer_count = 1.0f; - MOCK_METHOD0(ResetTimer, void()); - MOCK_METHOD0(UpdateOnFrameStart, void()); - float GetCurrTime([[maybe_unused]] ETimer which) const - { - m_timer_count += 1.0f; - return m_timer_count; - } - MOCK_CONST_METHOD1(GetFrameStartTime, CTimeValue&(ETimer)); - MOCK_CONST_METHOD0(GetAsyncTime, CTimeValue()); - MOCK_METHOD0(GetAsyncCurTime, float()); - MOCK_CONST_METHOD1(GetFrameTime, float(ETimer)); - MOCK_CONST_METHOD0(GetRealFrameTime, float()); - MOCK_CONST_METHOD0(GetTimeScale, float()); - MOCK_CONST_METHOD1(GetTimeScale, float(uint32)); - MOCK_METHOD0(ClearTimeScales, void()); - MOCK_METHOD2(SetTimeScale, void(float, uint32)); - MOCK_METHOD1(EnableTimer, void(bool)); - MOCK_CONST_METHOD0(IsTimerEnabled, bool()); - MOCK_METHOD0(GetFrameRate, float()); - MOCK_METHOD2(GetProfileFrameBlending, float(float*, int*)); - MOCK_METHOD1(Serialize, void(TSerialize)); - MOCK_METHOD2(PauseTimer, bool(ETimer, bool)); - MOCK_METHOD1(IsTimerPaused, bool(ETimer)); - MOCK_METHOD2(SetTimer, bool(ETimer, float)); - MOCK_METHOD2(SecondsToDateUTC, void(time_t, struct tm&)); - MOCK_METHOD1(DateToSecondsUTC, time_t(struct tm&)); - MOCK_METHOD1(TicksToSeconds, float(int64)); - MOCK_METHOD0(GetTicksPerSecond, int64()); - MOCK_METHOD0(CreateNewTimer, ITimer*()); - MOCK_METHOD2(EnableFixedTimeMode, void(bool, float)); + AZ::TimeMs GetRealElapsedTimeMs() const override + { + m_time += AZ::TimeMs{ 1000 }; + return m_time; + } + mutable AZ::TimeMs m_time = AZ::Time::ZeroTimeMs; }; class UiTooltipTestApplication : public AzFramework::Application { + public: + UiTooltipTestApplication() + : AzFramework::Application() + { + m_timeSystem.reset(); + m_timeSystem = AZStd::make_unique(); + } + void Reflect(AZ::ReflectContext* context) override { AzFramework::Application::Reflect(context); UiSerialize::ReflectUiTypes(context); //< needed to serialize ui Anchor and Offset } + private: // override and only include system components required for tests. AZ::ComponentTypeList GetRequiredSystemComponents() const override { @@ -153,16 +137,13 @@ namespace UnitTest return AZStd::make_tuple(uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent); } - }; TEST_F(UiTooltipComponentTest, UiTooltipComponent_WillAppearOnHover) { - MockTimer m_timer = MockTimer(); SSystemGlobalEnvironment env; SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; - gEnv->pTimer = &m_timer; gEnv->pLyShine = nullptr; auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); @@ -186,11 +167,9 @@ namespace UnitTest TEST_F(UiTooltipComponentTest, UiTooltipComponent_HoverTooltipDisappearsOnPress) { - MockTimer m_timer = MockTimer(); SSystemGlobalEnvironment env; SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; - gEnv->pTimer = &m_timer; gEnv->pLyShine = nullptr; auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); @@ -212,11 +191,9 @@ namespace UnitTest TEST_F(UiTooltipComponentTest, UiTooltipComponent_TooltipAppearsOnPress) { - MockTimer m_timer = MockTimer(); SSystemGlobalEnvironment env; SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; - gEnv->pTimer = &m_timer; gEnv->pLyShine = nullptr; auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); @@ -238,11 +215,9 @@ namespace UnitTest TEST_F(UiTooltipComponentTest, UiTooltipComponent_TooltipDisappearsOnCanvasPrimaryRelease) { - MockTimer m_timer = MockTimer(); SSystemGlobalEnvironment env; SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; - gEnv->pTimer = &m_timer; gEnv->pLyShine = nullptr; auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); @@ -264,11 +239,9 @@ namespace UnitTest TEST_F(UiTooltipComponentTest, UiTooltipComponent_TooltipAppearsOnClick) { - MockTimer m_timer = MockTimer(); SSystemGlobalEnvironment env; SSystemGlobalEnvironment* prevEnv = gEnv; gEnv = &env; - gEnv->pTimer = &m_timer; gEnv->pLyShine = nullptr; auto [uiCanvasComponent, uiTooltipDisplayComponent, uiTooltipComponent] = CreateUiCanvasWithTooltip(); diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp index 61b5405a2b..9663d3cf56 100644 --- a/Gems/Maestro/Code/Source/Cinematics/Movie.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/Movie.cpp @@ -6,11 +6,11 @@ * */ - #include #include #include #include +#include #include #include #include "Movie.h" @@ -35,7 +35,6 @@ #include #include #include -#include #include #include #include @@ -207,6 +206,22 @@ namespace } } +namespace Internal +{ + float ApplyDeltaTimeOverrideIfEnabled(float deltaTime) + { + if (auto* timeSystem = AZ::Interface::Get()) + { + const AZ::TimeMs deltatimeOverride = timeSystem->GetSimulationTickDeltaOverride(); + if (deltatimeOverride != AZ::Time::ZeroTimeMs) + { + deltaTime = AZ::TimeMsToSeconds(deltatimeOverride); + } + } + return deltaTime; + } +} // namespace Internal + ////////////////////////////////////////////////////////////////////////// CMovieSystem::CMovieSystem(ISystem* pSystem) { @@ -218,18 +233,13 @@ CMovieSystem::CMovieSystem(ISystem* pSystem) m_bEnableCameraShake = true; m_bCutscenesPausedInEditor = true; m_sequenceStopBehavior = eSSB_GotoEndTime; - m_lastUpdateTime.SetValue(0); + m_lastUpdateTime = AZ::Time::ZeroTimeUs; m_bStartCapture = false; m_captureFrame = -1; m_bEndCapture = false; - m_fixedTimeStepBackUp = 0; - m_maxStepBackUp = 0; - m_smoothingBackUp = 0; + m_fixedTimeStepBackUp = AZ::Time::ZeroTimeMs; m_cvar_capture_frame_once = nullptr; m_cvar_capture_folder = nullptr; - m_cvar_t_FixedStep = nullptr; - m_cvar_t_MaxStep = nullptr; - m_cvar_t_Smoothing = nullptr; m_cvar_sys_maxTimeStepForMovieSystem = nullptr; m_cvar_capture_frames = nullptr; m_cvar_capture_file_prefix = nullptr; @@ -1026,13 +1036,13 @@ void CMovieSystem::PreUpdate(float deltaTime) } m_newlyActivatedSequences.clear(); - UpdateInternal(m_cvar_t_FixedStep ? m_cvar_t_FixedStep->GetFVal() : deltaTime, true); + UpdateInternal(Internal::ApplyDeltaTimeOverrideIfEnabled(deltaTime), true); } ////////////////////////////////////////////////////////////////////////// void CMovieSystem::PostUpdate(float deltaTime) { - UpdateInternal(m_cvar_t_FixedStep ? m_cvar_t_FixedStep->GetFVal() : deltaTime, false); + UpdateInternal(Internal::ApplyDeltaTimeOverrideIfEnabled(deltaTime), false); } ////////////////////////////////////////////////////////////////////////// @@ -1046,7 +1056,7 @@ void CMovieSystem::UpdateInternal(const float deltaTime, const bool bPreUpdate) } // don't update more than once if dt==0.0 - CTimeValue curTime = gEnv->pTimer->GetFrameStartTime(); + const AZ::TimeUs curTime = AZ::GetLastSimulationTickTime(); if (deltaTime == 0.0f && curTime == m_lastUpdateTime && !gEnv->IsEditor()) { return; @@ -1498,35 +1508,12 @@ void CMovieSystem::GoToFrame(const char* seqName, float targetFrame) void CMovieSystem::EnableFixedStepForCapture(float step) { - if (nullptr == m_cvar_t_FixedStep) + if (auto* timeSystem = AZ::Interface::Get()) { - m_cvar_t_FixedStep = gEnv->pConsole->GetCVar("t_FixedStep"); + m_fixedTimeStepBackUp = timeSystem->GetSimulationTickDeltaOverride(); + timeSystem->SetSimulationTickDeltaOverride(AZ::SecondsToTimeMs(step)); } - m_fixedTimeStepBackUp = m_cvar_t_FixedStep->GetFVal(); - m_cvar_t_FixedStep->Set(step); - - if (nullptr == m_cvar_t_MaxStep) - { - m_cvar_t_MaxStep = gEnv->pConsole->GetCVar("t_MaxStep"); - } - - // Make sure to make the max step large enough - m_maxStepBackUp = m_cvar_t_MaxStep->GetFVal(); - if (step > m_maxStepBackUp) - { - m_cvar_t_MaxStep->Set(step); - } - - if (nullptr == m_cvar_t_Smoothing) - { - m_cvar_t_Smoothing = gEnv->pConsole->GetCVar("t_Smoothing"); - } - - // Turn off framerate smoothing - m_smoothingBackUp = m_cvar_t_Smoothing->GetFVal(); - m_cvar_t_Smoothing->Set(0); - if (nullptr == m_cvar_sys_maxTimeStepForMovieSystem) { m_cvar_sys_maxTimeStepForMovieSystem = gEnv->pConsole->GetCVar("sys_maxTimeStepForMovieSystem"); @@ -1542,9 +1529,10 @@ void CMovieSystem::EnableFixedStepForCapture(float step) void CMovieSystem::DisableFixedStepForCapture() { - m_cvar_t_FixedStep->Set(m_fixedTimeStepBackUp); - m_cvar_t_MaxStep->Set(m_maxStepBackUp); - m_cvar_t_Smoothing->Set(m_smoothingBackUp); + if (auto* timeSystem = AZ::Interface::Get()) + { + timeSystem->SetSimulationTickDeltaOverride(m_fixedTimeStepBackUp); + } m_cvar_sys_maxTimeStepForMovieSystem->Set(m_maxTimeStepForMovieSystemBackUp); } diff --git a/Gems/Maestro/Code/Source/Cinematics/Movie.h b/Gems/Maestro/Code/Source/Cinematics/Movie.h index 15295da353..ab2c2e649b 100644 --- a/Gems/Maestro/Code/Source/Cinematics/Movie.h +++ b/Gems/Maestro/Code/Source/Cinematics/Movie.h @@ -14,6 +14,7 @@ #pragma once #include +#include #include #include @@ -235,7 +236,7 @@ private: IMovieUser* m_pUser; IMovieCallback* m_pCallback; - CTimeValue m_lastUpdateTime; + AZ::TimeUs m_lastUpdateTime; typedef AZStd::vector > Sequences; Sequences m_sequences; @@ -268,15 +269,10 @@ private: int m_captureFrame; bool m_bEndCapture; ICaptureKey m_captureKey; - float m_fixedTimeStepBackUp; - float m_maxStepBackUp; - float m_smoothingBackUp; + AZ::TimeMs m_fixedTimeStepBackUp; float m_maxTimeStepForMovieSystemBackUp; ICVar* m_cvar_capture_frame_once; ICVar* m_cvar_capture_folder; - ICVar* m_cvar_t_FixedStep; - ICVar* m_cvar_t_MaxStep; - ICVar* m_cvar_t_Smoothing; ICVar* m_cvar_sys_maxTimeStepForMovieSystem; ICVar* m_cvar_capture_frames; ICVar* m_cvar_capture_file_prefix; diff --git a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp index eb88e21932..33c08b0960 100644 --- a/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp +++ b/Gems/Maestro/Code/Source/Cinematics/SceneNode.cpp @@ -6,12 +6,12 @@ * */ - #include #include #include #include #include +#include #include #include "MathConversion.h" @@ -24,7 +24,6 @@ #include "GotoTrack.h" #include "CaptureTrack.h" #include "ISystem.h" -#include "ITimer.h" #include "AnimAZEntityNode.h" #include "AnimComponentNode.h" #include "Movie.h" @@ -198,7 +197,6 @@ CAnimSceneNode::CAnimSceneNode(const int id) m_lastCaptureKey = -1; m_bLastCapturingEnded = true; m_captureFrameCount = 0; - m_cvar_t_FixedStep = NULL; m_pCamNodeOnHoldForInterp = 0; m_CurrentSelectTrack = 0; m_CurrentSelectTrackKeyNumber = 0; @@ -303,7 +301,6 @@ void CAnimSceneNode::Activate(bool bActivate) pSequenceTrack->GetKey(currKey, &key); IAnimSequence* pSequence = GetSequenceFromSequenceKey(key); - if (pSequence) { if (bActivate) @@ -328,11 +325,6 @@ void CAnimSceneNode::Activate(bool bActivate) } } } - - if (m_cvar_t_FixedStep == NULL) - { - m_cvar_t_FixedStep = gEnv->pConsole->GetCVar("t_FixedStep"); - } } ////////////////////////////////////////////////////////////////////////// @@ -421,14 +413,15 @@ void CAnimSceneNode::Animate(SAnimContext& ec) timeScale = .0f; } - // if set, disable fixed time step cvar so timewarping will have an affect. We never set it back though - that is - // likely a bug! - if (m_cvar_t_FixedStep && m_cvar_t_FixedStep->GetFVal() != .0f) + if (auto* timeSystem = AZ::Interface::Get()) { - m_cvar_t_FixedStep->Set(.0f); + m_simulationTickOverrideBackup = timeSystem->GetSimulationTickDeltaOverride(); + // if set, disable fixed time step cvar so timewarping will have an affect. + timeSystem->SetSimulationTickDeltaOverride(AZ::Time::ZeroTimeMs); + + m_timeScaleBackup = timeSystem->GetSimulationTickScale(); + timeSystem->SetSimulationTickScale(timeScale); } - gEnv->pTimer->SetTimeScale(timeScale, ITimer::eTSC_Trackview); - } break; case AnimParamType::FixedTimeStep: @@ -439,9 +432,12 @@ void CAnimSceneNode::Animate(SAnimContext& ec) { timeStep = 0; } - if (m_cvar_t_FixedStep) + + if (auto* timeSystem = AZ::Interface::Get()) { - m_cvar_t_FixedStep->Set(timeStep); + m_simulationTickOverrideBackup = timeSystem->GetSimulationTickDeltaOverride(); + // if set, disable fixed time step cvar so timewarping will have an affect. + timeSystem->SetSimulationTickDeltaOverride(AZ::SecondsToTimeMs(timeStep)); } } break; @@ -621,17 +617,18 @@ void CAnimSceneNode::OnReset() m_bLastCapturingEnded = true; m_captureFrameCount = 0; - if (GetTrackForParameter(AnimParamType::TimeWarp)) + if (auto* timeSystem = AZ::Interface::Get()) { - gEnv->pTimer->SetTimeScale(1.0f, ITimer::eTSC_Trackview); - if (m_cvar_t_FixedStep) + if (GetTrackForParameter(AnimParamType::TimeWarp)) { - m_cvar_t_FixedStep->Set(0); + timeSystem->SetSimulationTickScale(m_timeScaleBackup); + timeSystem->SetSimulationTickDeltaOverride(m_simulationTickOverrideBackup); + } + + if (GetTrackForParameter(AnimParamType::FixedTimeStep)) + { + timeSystem->SetSimulationTickDeltaOverride(m_simulationTickOverrideBackup); } - } - if (GetTrackForParameter(AnimParamType::FixedTimeStep) && m_cvar_t_FixedStep) - { - m_cvar_t_FixedStep->Set(0); } } diff --git a/Gems/Maestro/Code/Source/Cinematics/SceneNode.h b/Gems/Maestro/Code/Source/Cinematics/SceneNode.h index c577839fce..6435b48953 100644 --- a/Gems/Maestro/Code/Source/Cinematics/SceneNode.h +++ b/Gems/Maestro/Code/Source/Cinematics/SceneNode.h @@ -13,6 +13,7 @@ #pragma once #include +#include #include "AnimNode.h" #include "SoundTrack.h" @@ -149,7 +150,8 @@ private: std::vector m_SoundInfo; - ICVar* m_cvar_t_FixedStep; + AZ::TimeMs m_simulationTickOverrideBackup = AZ::Time::ZeroTimeMs; + float m_timeScaleBackup = 1.0f; }; #endif // CRYINCLUDE_CRYMOVIE_SCENENODE_H diff --git a/Gems/Maestro/Code/Tests/MaestroTest.cpp b/Gems/Maestro/Code/Tests/MaestroTest.cpp index 1607d35296..1724e090aa 100644 --- a/Gems/Maestro/Code/Tests/MaestroTest.cpp +++ b/Gems/Maestro/Code/Tests/MaestroTest.cpp @@ -8,7 +8,6 @@ #include #include -#include #include #include #include @@ -33,7 +32,6 @@ protected: { AZ_TEST_CLASS_ALLOCATOR(MockHolder); - NiceMock timer; NiceMock pak; NiceMock console; }; @@ -51,7 +49,6 @@ protected: // manage their lifetime, so this solution manages the lifetime // and ordering via the heap. m_mocks = new MockHolder(); - m_stubEnv.pTimer = &m_mocks->timer; m_stubEnv.pCryPak = &m_mocks->pak; m_stubEnv.pConsole = &m_mocks->console; gEnv = &m_stubEnv; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/Components/LocalPredictionPlayerInputComponent.h b/Gems/Multiplayer/Code/Include/Multiplayer/Components/LocalPredictionPlayerInputComponent.h index 678ec2d6fd..08ba541a1b 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/Components/LocalPredictionPlayerInputComponent.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/Components/LocalPredictionPlayerInputComponent.h @@ -99,8 +99,8 @@ namespace Multiplayer double m_moveAccumulator = 0.0; double m_clientBankedTime = 0.0; - AZ::TimeMs m_lastInputReceivedTimeMs = AZ::TimeMs{ 0 }; - AZ::TimeMs m_lastCorrectionSentTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_lastInputReceivedTimeMs = AZ::Time::ZeroTimeMs; + AZ::TimeMs m_lastCorrectionSentTimeMs = AZ::Time::ZeroTimeMs; ClientInputId m_clientInputId = ClientInputId{ 0 }; // Clients incrementing inputId ClientInputId m_lastClientInputId = ClientInputId{ 0 }; // Last inputId processed by the server diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h index 7245dbde9b..3c1dd370cd 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/IMultiplayer.h @@ -265,7 +265,7 @@ namespace Multiplayer } private: HostFrameId m_previousHostFrameId = InvalidHostFrameId; - AZ::TimeMs m_previousHostTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_previousHostTimeMs = AZ::Time::ZeroTimeMs; AzNetworking::ConnectionId m_previousRewindConnectionId = AzNetworking::InvalidConnectionId; float m_previousBlendFactor = DefaultBlendFactor; }; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h index 98a7b165f8..7bd0e9f527 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/MultiplayerStats.h @@ -27,7 +27,7 @@ namespace Multiplayer uint64_t m_serverConnectionCount = 0; uint64_t m_recordMetricIndex = 0; - AZ::TimeMs m_totalHistoryTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_totalHistoryTimeMs = AZ::Time::ZeroTimeMs; static const uint32_t RingbufferSamples = 32; using MetricRingbuffer = AZStd::array; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/EntityReplication/EntityReplicationManager.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/EntityReplication/EntityReplicationManager.h index 74935d5746..6bd22b39a1 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/EntityReplication/EntityReplicationManager.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkEntity/EntityReplication/EntityReplicationManager.h @@ -201,9 +201,9 @@ namespace Multiplayer AZStd::unique_ptr m_replicationWindow; AZStd::unique_ptr m_remoteEntityDomain; - AZ::TimeMs m_entityActivationTimeSliceMs = AZ::TimeMs{ 0 }; - AZ::TimeMs m_entityPendingRemovalMs = AZ::TimeMs{ 0 }; - AZ::TimeMs m_frameTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_entityActivationTimeSliceMs = AZ::Time::ZeroTimeMs; + AZ::TimeMs m_entityPendingRemovalMs = AZ::Time::ZeroTimeMs; + AZ::TimeMs m_frameTimeMs = AZ::Time::ZeroTimeMs; HostId m_remoteHostId = InvalidHostId; uint32_t m_maxRemoteEntitiesPendingCreationCount = AZStd::numeric_limits::max(); uint32_t m_maxPayloadSize = 0; diff --git a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput/NetworkInput.h b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput/NetworkInput.h index 1e02d6bf56..8e2e809e72 100644 --- a/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput/NetworkInput.h +++ b/Gems/Multiplayer/Code/Include/Multiplayer/NetworkInput/NetworkInput.h @@ -75,7 +75,7 @@ namespace Multiplayer MultiplayerComponentInputVector m_componentInputs; ClientInputId m_inputId = ClientInputId{ 0 }; HostFrameId m_hostFrameId = InvalidHostFrameId; - AZ::TimeMs m_hostTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_hostTimeMs = AZ::Time::ZeroTimeMs; float m_hostBlendFactor = 0.f; ConstNetworkEntityHandle m_owner; bool m_wasAttached = false; diff --git a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp index 96d6a5e31e..262f9d524f 100644 --- a/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp +++ b/Gems/Multiplayer/Code/Source/Components/LocalPredictionPlayerInputComponent.cpp @@ -66,11 +66,6 @@ namespace Multiplayer } } - inline double ConvertTimeMsToSeconds(AZ::TimeMs value) - { - return static_cast(static_cast(value)) / 1000.0; - } - void LocalPredictionPlayerInputComponent::LocalPredictionPlayerInputComponent::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast(context); @@ -162,7 +157,7 @@ namespace Multiplayer } const AZ::TimeMs currentTimeMs = AZ::GetElapsedTimeMs(); - const double clientInputRateSec = ConvertTimeMsToSeconds(cl_InputRateMs); + const double clientInputRateSec = AZ::TimeMsToSecondsDouble(cl_InputRateMs); m_lastInputReceivedTimeMs = currentTimeMs; // Keep track of last inputs received, also allows us to update frame ids @@ -267,7 +262,7 @@ namespace Multiplayer return; } - const double clientInputRateSec = ConvertTimeMsToSeconds(cl_InputRateMs); + const double clientInputRateSec = AZ::TimeMsToSecondsDouble(cl_InputRateMs); // Copy array so we can modify input ids NetworkInputMigrationVector inputArrayCopy = inputArray; @@ -342,7 +337,7 @@ namespace Multiplayer // If this correction is for a move outside our input history window, just start replaying from the oldest move we have available const uint32_t startReplayIndex = (inputHistorySize > historicalDelta) ? (inputHistorySize - historicalDelta) : 0; - const double clientInputRateSec = ConvertTimeMsToSeconds(cl_InputRateMs); + const double clientInputRateSec = AZ::TimeMsToSecondsDouble(cl_InputRateMs); for (uint32_t replayIndex = startReplayIndex; replayIndex < inputHistorySize; ++replayIndex) { // Reprocess the input for this frame @@ -423,9 +418,9 @@ namespace Multiplayer void LocalPredictionPlayerInputComponentController::UpdateAutonomous(AZ::TimeMs deltaTimeMs) { - const double deltaTime = ConvertTimeMsToSeconds(deltaTimeMs); - const double clientInputRateSec = ConvertTimeMsToSeconds(cl_InputRateMs); - const double maxRewindHistory = ConvertTimeMsToSeconds(cl_MaxRewindHistoryMs); + const double deltaTime = AZ::TimeMsToSecondsDouble(deltaTimeMs); + const double clientInputRateSec = AZ::TimeMsToSecondsDouble(cl_InputRateMs); + const double maxRewindHistory = AZ::TimeMsToSecondsDouble(cl_MaxRewindHistoryMs); #ifndef AZ_RELEASE_BUILD m_moveAccumulator += deltaTime * cl_DebugHackTimeMultiplier; diff --git a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp index 392b020748..2989b7629e 100644 --- a/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp +++ b/Gems/Multiplayer/Code/Source/ConnectionData/ClientToServerConnectionData.cpp @@ -13,7 +13,7 @@ namespace Multiplayer // This can be used to help mitigate client side performance when large numbers of entities are created off the network AZ_CVAR(uint32_t, cl_ClientMaxRemoteEntitiesPendingCreationCount, AZStd::numeric_limits::max(), nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Maximum number of entities that we have sent to the client, but have not had a confirmation back from the client"); AZ_CVAR(AZ::TimeMs, cl_ClientEntityReplicatorPendingRemovalTimeMs, AZ::TimeMs{ 10000 }, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "How long should wait prior to removing an entity for the client through a change in the replication window, entity deletes are still immediate"); - AZ_CVAR(AZ::TimeMs, cl_DefaultNetworkEntityActivationTimeSliceMs, AZ::TimeMs{ 0 }, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Max Ms to use to activate entities coming from the network, 0 means instantiate everything"); + AZ_CVAR(AZ::TimeMs, cl_DefaultNetworkEntityActivationTimeSliceMs, AZ::Time::ZeroTimeMs, nullptr, AZ::ConsoleFunctorFlags::DontReplicate, "Max Ms to use to activate entities coming from the network, 0 means instantiate everything"); ClientToServerConnectionData::ClientToServerConnectionData ( diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugHierarchyReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugHierarchyReporter.cpp index ad28307204..78963439ed 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugHierarchyReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugHierarchyReporter.cpp @@ -27,7 +27,7 @@ namespace Multiplayer CollectHierarchyRoots(); AZ::EntitySystemBus::Handler::BusConnect(); - m_updateDebugOverlay.Enqueue(AZ::TimeMs{ 0 }, true); + m_updateDebugOverlay.Enqueue(AZ::Time::ZeroTimeMs, true); } MultiplayerDebugHierarchyReporter::~MultiplayerDebugHierarchyReporter() diff --git a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp index adfef397b6..a53420da84 100644 --- a/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp +++ b/Gems/Multiplayer/Code/Source/Debug/MultiplayerDebugPerEntityReporter.cpp @@ -127,7 +127,7 @@ namespace Multiplayer MultiplayerDebugPerEntityReporter::MultiplayerDebugPerEntityReporter() : m_updateDebugOverlay([this]() { UpdateDebugOverlay(); }, AZ::Name("UpdateDebugPerEntityOverlay")) { - m_updateDebugOverlay.Enqueue(AZ::TimeMs{ 0 }, true); + m_updateDebugOverlay.Enqueue(AZ::Time::ZeroTimeMs, true); m_eventHandlers.m_entitySerializeStart = decltype(m_eventHandlers.m_entitySerializeStart)([this](AzNetworking::SerializerMode mode, AZ::EntityId entityId, const char* entityName) { diff --git a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp index 59446e9889..b896f35b71 100644 --- a/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp +++ b/Gems/Multiplayer/Code/Source/Editor/MultiplayerEditorConnection.cpp @@ -35,7 +35,7 @@ namespace Multiplayer { m_networkEditorInterface = AZ::Interface::Get()->CreateNetworkInterface( AZ::Name(MpEditorInterfaceName), ProtocolType::Tcp, TrustZone::ExternalClientToServer, *this); - m_networkEditorInterface->SetTimeoutMs(AZ::TimeMs{ 0 }); // Disable timeouts on this network interface + m_networkEditorInterface->SetTimeoutMs(AZ::Time::ZeroTimeMs); // Disable timeouts on this network interface // Wait to activate the editor-server until LegacySystemInterfaceCreated so that the logging system is ready // Automated testing listens for these logs diff --git a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h index 53707523bb..d839407fb0 100644 --- a/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h +++ b/Gems/Multiplayer/Code/Source/MultiplayerSystemComponent.h @@ -178,7 +178,7 @@ namespace Multiplayer AZStd::queue m_pendingConnectionTickets; AZStd::unordered_map m_playerRejoinData; - AZ::TimeMs m_lastReplicatedHostTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_lastReplicatedHostTimeMs = AZ::Time::ZeroTimeMs; HostFrameId m_lastReplicatedHostFrameId = HostFrameId(0); uint64_t m_temporaryUserIdentifier = 0; // Used in the event of a migration or rejoin diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp index 583671d1f3..e095af4ae7 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicationManager.cpp @@ -54,10 +54,10 @@ namespace Multiplayer m_maxPayloadSize = connection.GetConnectionMtu() - UdpPacketHeaderSerializeSize - ReplicationManagerPacketOverhead; // Schedule ClearRemovedReplicators() - m_clearRemovedReplicators.Enqueue(AZ::TimeMs{ 0 }, true); + m_clearRemovedReplicators.Enqueue(AZ::Time::ZeroTimeMs, true); // Start window update events - m_updateWindow.Enqueue(AZ::TimeMs{ 0 }, true); + m_updateWindow.Enqueue(AZ::Time::ZeroTimeMs, true); INetworkEntityManager* networkEntityManager = GetNetworkEntityManager(); if (networkEntityManager != nullptr) @@ -97,7 +97,7 @@ namespace Multiplayer notReadyEntities.push_back(entityId); } } - if (m_entityActivationTimeSliceMs > AZ::TimeMs{ 0 } && AZ::GetElapsedTimeMs() > endTimeMs) + if (m_entityActivationTimeSliceMs > AZ::Time::ZeroTimeMs && AZ::GetElapsedTimeMs() > endTimeMs) { // If we go over our timeslice, break out the loop break; diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp index 67527bf962..935850a795 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/EntityReplicator.cpp @@ -344,7 +344,7 @@ namespace Multiplayer void EntityReplicator::SetPendingRemoval(AZ::TimeMs pendingRemovalTimeMs) { AZ_Assert(m_propertyPublisher, "Only valid if we are publishing updates"); - if (pendingRemovalTimeMs > AZ::TimeMs{ 0 }) + if (pendingRemovalTimeMs > AZ::Time::ZeroTimeMs) { if (!IsPendingRemoval()) { diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp index c0e5c09c7b..8cbe542568 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.cpp @@ -26,7 +26,7 @@ namespace Multiplayer bool PropertySubscriber::IsDeleting() const { - return m_markForRemovalTimeMs > AZ::TimeMs{ 0 }; + return m_markForRemovalTimeMs > AZ::Time::ZeroTimeMs; } bool PropertySubscriber::IsDeleted() const diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.h b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.h index 286509b798..7f1a43a743 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.h +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/EntityReplication/PropertySubscriber.h @@ -40,6 +40,6 @@ namespace Multiplayer // The last packet to have been received about this entity AzNetworking::PacketId m_lastReceivedPacketId = AzNetworking::InvalidPacketId; - AZ::TimeMs m_markForRemovalTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_markForRemovalTimeMs = AZ::Time::ZeroTimeMs; }; } diff --git a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp index 6885d78075..fa524d464a 100644 --- a/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp +++ b/Gems/Multiplayer/Code/Source/NetworkEntity/NetworkEntityManager.cpp @@ -123,7 +123,7 @@ namespace Multiplayer AZ_Assert(entityHandle.GetNetBindComponent(), "No NetBindComponent found on networked entity"); } m_removeList.push_back(entityHandle.GetNetEntityId()); - m_removeEntitiesEvent.Enqueue(AZ::TimeMs{ 0 }); + m_removeEntitiesEvent.Enqueue(AZ::Time::ZeroTimeMs); } } diff --git a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h index 2bcf019623..5e865d801c 100644 --- a/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h +++ b/Gems/Multiplayer/Code/Source/NetworkTime/NetworkTime.h @@ -44,7 +44,7 @@ namespace Multiplayer HostFrameId m_hostFrameId = HostFrameId{ 0 }; HostFrameId m_unalteredFrameId = HostFrameId{ 0 }; - AZ::TimeMs m_hostTimeMs = AZ::TimeMs{ 0 }; + AZ::TimeMs m_hostTimeMs = AZ::Time::ZeroTimeMs; float m_hostBlendFactor = DefaultBlendFactor; AzNetworking::ConnectionId m_rewindingConnectionId = AzNetworking::InvalidConnectionId; }; diff --git a/Gems/Multiplayer/Code/Tests/CommonBenchmarkSetup.h b/Gems/Multiplayer/Code/Tests/CommonBenchmarkSetup.h index 23b8316c66..c352dc2bbf 100644 --- a/Gems/Multiplayer/Code/Tests/CommonBenchmarkSetup.h +++ b/Gems/Multiplayer/Code/Tests/CommonBenchmarkSetup.h @@ -14,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -92,20 +93,6 @@ namespace Multiplayer } }; - class BenchmarkTime : public AZ::ITime - { - public: - AZ::TimeMs GetElapsedTimeMs() const override - { - return {}; - } - - AZ::TimeUs GetElapsedTimeUs() const override - { - return {}; - } - }; - class BenchmarkNetworkTime : public Multiplayer::INetworkTime { public: @@ -349,8 +336,7 @@ namespace Multiplayer // Without Multiplayer::RegisterMultiplayerComponents() the stats go to invalid id, which is fine for unit tests GetMultiplayer()->GetStats().ReserveComponentStats(Multiplayer::InvalidNetComponentId, 50, 0); - m_Time = AZStd::make_unique(); - AZ::Interface::Register(m_Time.get()); + m_Time = AZStd::make_unique(); m_NetworkTime = AZStd::make_unique(); AZ::Interface::Register(m_NetworkTime.get()); @@ -381,7 +367,6 @@ namespace Multiplayer m_ConnectionListener.reset(); AZ::Interface::Unregister(m_NetworkTime.get()); - AZ::Interface::Unregister(m_Time.get()); AZ::Interface::Unregister(m_Multiplayer.get()); AZ::Interface::Unregister(m_ComponentApplicationRequests.get()); @@ -414,7 +399,7 @@ namespace Multiplayer AZStd::unique_ptr m_Multiplayer; AZStd::unique_ptr m_NetworkEntityManager; - AZStd::unique_ptr m_Time; + AZStd::unique_ptr m_Time; AZStd::unique_ptr m_NetworkTime; AZStd::unique_ptr m_Connection; diff --git a/Gems/Multiplayer/Code/Tests/CommonHierarchySetup.h b/Gems/Multiplayer/Code/Tests/CommonHierarchySetup.h index 1b64efc5e2..cdc4724c70 100644 --- a/Gems/Multiplayer/Code/Tests/CommonHierarchySetup.h +++ b/Gems/Multiplayer/Code/Tests/CommonHierarchySetup.h @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -117,8 +118,7 @@ namespace Multiplayer ON_CALL(*m_mockNetworkEntityManager, GetEntity(_)).WillByDefault(Invoke(this, &HierarchyTests::GetEntity)); ON_CALL(*m_mockNetworkEntityManager, GetNetEntityIdById(_)).WillByDefault(Invoke(this, &HierarchyTests::GetNetEntityIdById)); - m_mockTime = AZStd::make_unique>(); - AZ::Interface::Register(m_mockTime.get()); + m_mockTime = AZStd::make_unique(); m_eventScheduler = AZStd::make_unique(); @@ -168,7 +168,6 @@ namespace Multiplayer m_networkEntityAuthorityTracker.reset(); AZ::Interface::Unregister(m_mockNetworkTime.get()); - AZ::Interface::Unregister(m_mockTime.get()); AZ::Interface::Unregister(m_mockNetworkEntityManager.get()); AZ::Interface::Unregister(m_mockMultiplayer.get()); AZ::Interface::Unregister(m_mockComponentApplicationRequests.get()); @@ -207,8 +206,8 @@ namespace Multiplayer AZStd::unique_ptr> m_mockMultiplayer; AZStd::unique_ptr m_mockNetworkEntityManager; - AZStd::unique_ptr> m_mockTime; AZStd::unique_ptr m_eventScheduler; + AZStd::unique_ptr m_mockTime; AZStd::unique_ptr> m_mockNetworkTime; AZStd::unique_ptr> m_mockConnection; diff --git a/Gems/Multiplayer/Code/Tests/MockInterfaces.h b/Gems/Multiplayer/Code/Tests/MockInterfaces.h index ee5bfe3b8c..1060006169 100644 --- a/Gems/Multiplayer/Code/Tests/MockInterfaces.h +++ b/Gems/Multiplayer/Code/Tests/MockInterfaces.h @@ -103,13 +103,6 @@ namespace UnitTest MOCK_METHOD3(OnDisconnect, void(IConnection*, DisconnectReason, TerminationEndpoint)); }; - class MockTime : public AZ::ITime - { - public: - MOCK_CONST_METHOD0(GetElapsedTimeUs, AZ::TimeUs()); - MOCK_CONST_METHOD0(GetElapsedTimeMs, AZ::TimeMs()); - }; - class MockNetworkTime : public Multiplayer::INetworkTime { public: diff --git a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp index f6e5d82703..ec6b30ca15 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableContainerTests.cpp @@ -12,7 +12,7 @@ #include #include #include -#include +#include #include namespace UnitTest @@ -23,7 +23,7 @@ namespace UnitTest public: Multiplayer::NetworkTime m_networkTime; AZ::LoggerSystemComponent m_loggerComponent; - AZ::TimeSystemComponent m_timeComponent; + AZ::TimeSystem m_timeSystem; }; static constexpr uint32_t RewindableContainerSize = 7; @@ -43,7 +43,7 @@ namespace UnitTest // Test rewind for all pushed values and overall size for (uint32_t idx = 0; idx < RewindableContainerSize; ++idx) { - Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(idx + 1, test.size()); EXPECT_EQ(idx, test.back()); } @@ -70,9 +70,9 @@ namespace UnitTest EXPECT_TRUE(test.empty()); // Test rewind for pop_back and clear - Multiplayer::ScopedAlterTime pop_time(static_cast(RewindableContainerSize), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime pop_time(static_cast(RewindableContainerSize), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(RewindableContainerSize - 1, test.size()); - Multiplayer::ScopedAlterTime clear_time(static_cast(RewindableContainerSize + 1), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime clear_time(static_cast(RewindableContainerSize + 1), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(0, test.size()); // Test copy_values and resize_no_construct @@ -100,7 +100,7 @@ namespace UnitTest // Test rewind for all values and overall size for (uint32_t idx = 1; idx <= RewindableContainerSize; ++idx) { - Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(idx), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); for (uint32_t testIdx = 0; testIdx < RewindableContainerSize; ++testIdx) { if (testIdx < idx) diff --git a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp index 04de971f0d..0ff2c977d0 100644 --- a/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp +++ b/Gems/Multiplayer/Code/Tests/RewindableObjectTests.cpp @@ -10,7 +10,7 @@ #include #include #include -#include +#include #include namespace UnitTest @@ -21,7 +21,7 @@ namespace UnitTest public: Multiplayer::NetworkTime m_networkTime; AZ::LoggerSystemComponent m_loggerComponent; - AZ::TimeSystemComponent m_timeComponent; + AZ::TimeSystem m_timeSystem; }; static constexpr uint32_t RewindableBufferFrames = 32; @@ -39,7 +39,7 @@ namespace UnitTest for (uint32_t i = 0; i < 16; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(i, test); } @@ -52,7 +52,7 @@ namespace UnitTest for (uint32_t i = 16; i < 48; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(i, test); } } @@ -70,15 +70,15 @@ namespace UnitTest { // Test that Get/GetPrevious return different value when not on the owning connection - Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames - 1), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames - 1), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(RewindableBufferFrames - 1, test.Get()); EXPECT_EQ(RewindableBufferFrames - 2, test.GetPrevious()); } // Test that Get/GetPrevious return the unaltered frame on the owning conection - Multiplayer::GetNetworkTime()->AlterTime(static_cast(RewindableBufferFrames - 1), AZ::TimeMs{ 0 }, 1.f, AzNetworking::ConnectionId(0)); + Multiplayer::GetNetworkTime()->AlterTime(static_cast(RewindableBufferFrames - 1), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::ConnectionId(0)); { - Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames - 1), AZ::TimeMs{ 0 }, 1.f, AzNetworking::ConnectionId(0)); + Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames - 1), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::ConnectionId(0)); test.SetOwningConnectionId(AzNetworking::ConnectionId(0)); EXPECT_EQ(RewindableBufferFrames - 1, test.Get()); EXPECT_EQ(RewindableBufferFrames - 1, test.GetPrevious()); @@ -99,7 +99,7 @@ namespace UnitTest { // Note that we didn't actually set any value for time rewindableBufferFrames, so we're testing fetching a value past the last time set - Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(RewindableBufferFrames), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(RewindableBufferFrames - 1, test); } } @@ -122,7 +122,7 @@ namespace UnitTest for (uint32_t i = 0; i < RewindableBufferFrames; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); const Object& value = test; EXPECT_EQ(value.value, i); } @@ -131,19 +131,19 @@ namespace UnitTest TEST_F(RewindableObjectTests, TestBackfillOnLargeTimestep) { Multiplayer::RewindableObject test(0); - Multiplayer::ScopedAlterTime time1(static_cast(0), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time1(static_cast(0), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); test = 1; - Multiplayer::ScopedAlterTime time2(static_cast(31), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time2(static_cast(31), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); test = 2; for (uint32_t i = 0; i < 31; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(i), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(1, test); } - Multiplayer::ScopedAlterTime time3(static_cast(31), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time3(static_cast(31), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(2, test); } @@ -159,7 +159,7 @@ namespace UnitTest for (uint32_t i = 0; i < 1000; ++i) { - Multiplayer::ScopedAlterTime time(static_cast(1000 - i), AZ::TimeMs{ 0 }, 1.f, AzNetworking::InvalidConnectionId); + Multiplayer::ScopedAlterTime time(static_cast(1000 - i), AZ::Time::ZeroTimeMs, 1.f, AzNetworking::InvalidConnectionId); EXPECT_EQ(1000, test); } } diff --git a/Gems/Profiler/Code/Source/CpuProfilerImpl.cpp b/Gems/Profiler/Code/Source/CpuProfilerImpl.cpp index f0d39d48e4..23a3bbbea4 100644 --- a/Gems/Profiler/Code/Source/CpuProfilerImpl.cpp +++ b/Gems/Profiler/Code/Source/CpuProfilerImpl.cpp @@ -8,7 +8,6 @@ #include -#include #include #include #include diff --git a/Gems/SurfaceData/Code/Tests/SurfaceDataTest.cpp b/Gems/SurfaceData/Code/Tests/SurfaceDataTest.cpp index b25c428cfb..d5384161ad 100644 --- a/Gems/SurfaceData/Code/Tests/SurfaceDataTest.cpp +++ b/Gems/SurfaceData/Code/Tests/SurfaceDataTest.cpp @@ -7,7 +7,6 @@ */ #include -#include #include #include #include @@ -31,7 +30,6 @@ struct MockGlobalEnvironment { MockGlobalEnvironment() { - m_stubEnv.pTimer = &m_stubTimer; m_stubEnv.pCryPak = &m_stubPak; m_stubEnv.pConsole = &m_stubConsole; m_stubEnv.pSystem = &m_stubSystem; @@ -45,7 +43,6 @@ struct MockGlobalEnvironment private: SSystemGlobalEnvironment m_stubEnv; - testing::NiceMock m_stubTimer; testing::NiceMock m_stubPak; testing::NiceMock m_stubConsole; testing::NiceMock m_stubSystem;