11#include "LkEngine/Core/Assert.h"
12#include "LkEngine/Core/Log/Log.h"
13#include "LkEngine/Core/Delegate/Delegate.h"
15#include "LkEngine/Core/Time/Time.h"
32 LK_DECLARE_DELEGATE(FTimerDelegate);
47 const float DelayInSeconds,
48 const bool Loop =
false)
50 using namespace std::chrono;
52 Internal_FTimer Timer;
53 Timer.Delegate = TimerDelegate;
54 Timer.EndTime = high_resolution_clock::now() + milliseconds(
static_cast<int>(DelayInSeconds * 1000));
55 Timer.bShouldLoop = Loop;
56 Timer.Delay = DelayInSeconds;
58 Timers[Handle] = std::move(Timer);
70 if (Timers.contains(Handle))
76 LK_CORE_ERROR_TAG(
"TimerManager",
"Timer with handle {} is not in timer collection", Handle.GetID());
86 return Timers.find(Handle) != Timers.end();
94 using namespace std::chrono;
95 const high_resolution_clock::time_point Now = high_resolution_clock::now();
97 uint8_t ExpiredTimers = 0;
98 std::array<FTimerHandle, MaxExpiredTimerStackSize> ExpiredTimersArray;
100 for (
auto& [Handle, Timer] : Timers)
102 if (Now >= Timer.EndTime)
104 Timer.Delegate.ExecuteIfBound();
106 if (Timer.bShouldLoop)
109 Timer.EndTime = Now + milliseconds(
static_cast<int>(Timer.Delay * 1000));
114 LK_CORE_ASSERT((ExpiredTimers + 1) < MaxExpiredTimerStackSize,
"Expired timer index exceed max stack count");
115 ExpiredTimersArray[ExpiredTimers++] = Handle;
121 for (uint8_t TimerIndex = 0; TimerIndex < ExpiredTimers; TimerIndex++)
123 Timers.erase(ExpiredTimersArray[TimerIndex]);
133 struct Internal_FTimer
135 FTimerDelegate Delegate;
136 std::chrono::high_resolution_clock::time_point EndTime{};
138 bool bShouldLoop =
false;
146 std::unordered_map<FTimerHandle, Internal_FTimer> Timers{};
152 static constexpr uint8_t MaxExpiredTimerStackSize = 40;
Core macros used by the entire engine.
Definition TimerHandle.h:18
Definition TimerManager.h:40
FTimerHandle SetTimer(const FTimerDelegate &TimerDelegate, const float DelayInSeconds, const bool Loop=false)
Set a timer with a delegate, delay and optional looping.
Definition TimerManager.h:46
FORCEINLINE void Update()
Update timers, execute callbacks as they expire.
Definition TimerManager.h:92
FORCEINLINE bool IsTimerActive(const FTimerHandle Handle) const
Check if a timer is active.
Definition TimerManager.h:84
FORCEINLINE void ClearTimer(const FTimerHandle Handle)
Clear a timer by its handle.
Definition TimerManager.h:68