Extra2D/Extra2D/include/extra2d/utils/timer.h

100 lines
2.1 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#pragma once
#include <chrono>
#include <extra2d/core/types.h>
#include <map>
#include <memory>
#include <vector>
namespace extra2d {
// ============================================================================
// Timer 类 - 单次/重复计时器
// ============================================================================
class Timer {
public:
using Clock = std::chrono::steady_clock;
using TimePoint = Clock::time_point;
using Duration = Clock::duration;
using Fn = std::function<void()>;
Timer(f32 interval, bool repeat, Fn fn);
/// 更新计时器,返回 true 如果触发了回调
bool update(f32 dt);
/// 重置计时器
void reset();
/// 暂停计时器
void pause();
/// 恢复计时器
void resume();
/// 取消计时器(标记为无效)
void cancel();
/// 是否有效
bool valid() const { return valid_; }
/// 是否暂停
bool paused() const { return paused_; }
/// 获取剩余时间(秒)
f32 remaining() const;
/// 获取唯一ID
u32 id() const { return id_; }
private:
u32 id_;
f32 interval_;
f32 elapsed_;
bool repeat_;
bool paused_;
bool valid_;
Fn fn_;
static u32 nextId_;
};
// ============================================================================
// TimerManager 类 - 管理所有计时器
// ============================================================================
class TimerManager {
public:
TimerManager() = default;
~TimerManager() = default;
/// 创建单次计时器返回计时器ID
u32 add(f32 delay, Timer::Fn fn);
/// 创建重复计时器返回计时器ID
u32 addRepeat(f32 interval, Timer::Fn fn);
/// 取消指定ID的计时器
void cancel(u32 timerId);
/// 暂停指定ID的计时器
void pause(u32 timerId);
/// 恢复指定ID的计时器
void resume(u32 timerId);
/// 更新所有计时器(每帧调用)
void update(f32 dt);
/// 清除所有计时器
void clear();
/// 获取计时器数量
size_t count() const { return timers_.size(); }
private:
std::map<u32, std::unique_ptr<Timer>> timers_;
std::vector<u32> timersToRemove_;
};
} // namespace extra2d