FastLED 3.9.3
Loading...
Searching...
No Matches
time_warp.h
1#pragma once
2
3#include <stdint.h>
4
5#include "namespace.h"
6
7FASTLED_NAMESPACE_BEGIN
8
9// This class keeps track of the current time and modifies it to allow for time
10// warping effects. You will get the warped time value by calling getTime().
11class TimeWarp {
12 public:
13 enum MODE {
14 EXACT,
15 };
16 TimeWarp(uint32_t realTimeNow, float initialTimeScale = 1.0f)
17 : mRealTime(realTimeNow), mLastRealTime(realTimeNow),
18 mStartTime(realTimeNow), mTimeScale(initialTimeScale) {}
19 void setTimeScale(float timeScale) { mTimeScale = timeScale; }
20 float getTimeScale() const { return mTimeScale; }
21 void update(uint32_t timeNow) {
22 switch (mMode) {
23 case EXACT:
24 applyExact(timeNow);
25 break;
26 }
27 }
28
29 uint32_t getTime() const { return mRealTime; }
30 uint32_t reset(uint32_t timeNow, float timeScale = 1.0f) {
31 mRealTime = timeNow;
32 mLastRealTime = timeNow;
33 mStartTime = timeNow;
34 mTimeScale = timeScale;
35 return mRealTime;
36 }
37
38 void setMode(MODE mode) { mMode = mode; }
39
40 private:
41 void applyExact(uint32_t timeNow) {
42 uint32_t elapsedRealTime = timeNow - mLastRealTime;
43 int32_t diff = static_cast<int32_t>(elapsedRealTime * mTimeScale);
44 if (diff < 0) {
45 if (mRealTime + diff < mStartTime) {
46 mRealTime = mStartTime;
47 mLastRealTime = mStartTime;
48 return;
49 }
50 uint32_t newRealTime = mRealTime + diff;
51 if (newRealTime > mRealTime) {
52 // rolled over to positive territory.
53 mRealTime = mStartTime;
54 mLastRealTime = mStartTime;
55 return;
56 }
57 }
58 mRealTime += diff;
59 mLastRealTime = timeNow;
60 }
61
62 uint32_t mRealTime = 0;
63 uint32_t mLastRealTime = 0;
64 uint32_t mStartTime = 0;
65 float mTimeScale = 1.0f;
66 MODE mMode = EXACT;
67};
68
69FASTLED_NAMESPACE_END