Gondwana Game Engine Development (master) - 2.7.0
Gondwana is a cross-platform 2.5D game and rendering engine written in C#/.NET 8. It provides fine-grained control over rendering, timing, and scene composition, with built-in support for parallax, z-ordering, pixel overhang, collision detection, and particle effects. Gondwana targets desktop and web platforms using SkiaSharp for graphics and pluggable audio backends for desktop and browser targets.
Loading...
Searching...
No Matches
Timer.cs
1using System.Collections.Concurrent;
2
3namespace Gondwana.Timers;
4
15public sealed class Timer : IDisposable
16{
23 public event Action? Tick;
24
28 public TimerType Type { get; }
29
33 public TimerCycles Cycles { get; }
34
38 public long Length { get; }
39
43 public string TimerID { get; internal set; } = string.Empty;
44
48 public bool Paused { get; set; }
49
50 private long _lastEventTick { get; set; }
51 private bool _disposed;
52
53 private Timer(
54 TimerType type,
55 TimerCycles cycles,
56 long startTick,
57 double length)
58 {
59 if (!double.IsFinite(length) || length <= 0)
60 throw new ArgumentOutOfRangeException(
61 nameof(length),
62 length,
63 "Timer length must be finite and greater than zero.");
64
65 double lengthInTicks = length * HighResTimer.TicksPerSecond;
66
67 if (lengthInTicks < 1 || lengthInTicks >= long.MaxValue)
68 throw new ArgumentOutOfRangeException(
69 nameof(length),
70 length,
71 "Timer length must convert to at least one high-resolution tick and fit in a positive Int64.");
72
73 Type = type;
74 Cycles = cycles;
75 _lastEventTick = startTick;
76 Length = (long)lengthInTicks;
77 Paused = false;
78 }
79
80 internal void RaiseTickEvent() => Tick?.Invoke();
81
103 public void Dispose()
104 {
105 if (_disposed)
106 return;
107
108 GC.SuppressFinalize(this);
109 _timers.TryRemove(TimerID, out _);
110 Tick = null;
111 _disposed = true;
112 }
113
123 ~Timer() => Dispose();
124
125 #region static members
126
127 private static readonly ConcurrentDictionary<string, Timer> _timers = new();
128
132 public static bool PausedAll { get; set; }
133
144 public static Timer Add(
145 string timerID,
146 TimerType type,
147 TimerCycles cycles,
148 double length)
149 {
150 long startTick = type == TimerType.PreCycle
151 ? EngineSimulationClock.GetCurrentTick()
152 : HighResTimer.GetCurrentTick();
153
154 var timer = new Timer(
155 type,
156 cycles,
157 startTick,
158 length)
159 {
160 TimerID = timerID
161 };
162
163 _timers[timerID] = timer;
164 return timer;
165 }
166
174 public static Timer Add(TimerType type, TimerCycles cycles, double length)
175 {
176 string timerID = Guid.NewGuid().ToString();
177
178 return Add(
179 timerID,
180 type,
181 cycles,
182 length);
183 }
184
191 public static void Remove(string timerID)
192 {
193 if (_timers.TryRemove(timerID, out var timer))
194 timer.Dispose();
195 }
196
202 public static Timer Get(string timerID) => _timers[timerID];
203
207 public static int Count => _timers.Count;
208
212 public static string[] TimerIDs => _timers.Keys.ToArray();
213
231 public static void ClearAll()
232 {
233 foreach (var key in _timers.Keys.ToArray())
234 Remove(key);
235 }
236
237 internal static void RaiseTimerEvents(TimerType type, long engineTick)
238 {
239 var expired = new List<string>();
240
241 foreach (var (key, timer) in _timers.ToArray())
242 {
243 // checking this TimerType (i.e., PreCycle or PostCycle)
244 if (timer.Type != type)
245 continue;
246
247 // "push" time forward for Paused Timer instances
248 if (PausedAll || timer.Paused)
249 {
250 timer._lastEventTick += (engineTick - timer._lastEventTick);
251 continue;
252 }
253
254 // check if Timer.Length time has passed
255 while (engineTick - timer._lastEventTick >= timer.Length)
256 {
257 // save the time this event was scheduled to run
258 // might be different from current system tick, but storing this value
259 // will ensure that a lag in repeating timer events does not
260 // accumulate over time
261 timer._lastEventTick += timer.Length;
262 timer.RaiseTickEvent();
263
264 // check for any expired timers
265 if (timer.Cycles == TimerCycles.Once)
266 {
267 expired.Add(key);
268 break;
269 }
270 }
271 }
272
273 foreach (var key in expired)
274 _timers.TryRemove(key, out _);
275 }
276
277 #endregion static members
278}
Represents a high-resolution timer that can trigger events at specified intervals and supports variou...
Definition Timer.cs:16
bool Paused
Gets or sets a value indicating whether the Timer is currently paused.
Definition Timer.cs:48
static void ClearAll()
Removes and disposes all active timers, clearing the entire timer collection.
Definition Timer.cs:231
static Timer Add(TimerType type, TimerCycles cycles, double length)
Creates and adds a new timer with the specified type, cycle count, and duration.
Definition Timer.cs:174
static bool PausedAll
Gets or sets a value indicating whether all operations are globally paused.
Definition Timer.cs:132
string TimerID
Gets the unique identifier for the Timer.
Definition Timer.cs:43
long Length
Gets the length of the current timer interval in seconds.
Definition Timer.cs:38
static string[] TimerIDs
Gets an array of timer identifiers currently managed by the Engine.
Definition Timer.cs:212
static int Count
Gets the total number of active timers.
Definition Timer.cs:207
static Timer Get(string timerID)
Retrieves the Timer instance associated with the specified timer ID.
Action? Tick
Occurs when the timer interval has elapsed.
Definition Timer.cs:23
static void Remove(string timerID)
Removes the timer associated with the specified timer ID and releases its resources.
Definition Timer.cs:191
void Dispose()
Releases all resources used by the Timer and removes it from the collection of active timers.
Definition Timer.cs:103
TimerCycles Cycles
Gets the current timer cycles, representing whether the timer is set to run once or repeatedly.
Definition Timer.cs:33
TimerType Type
Gets the type of the timer, indicating whether it is a pre-cycle or post-cycle timer.
Definition Timer.cs:28
static Timer Add(string timerID, TimerType type, TimerCycles cycles, double length)
Creates a new timer with the specified parameters and adds it to the collection of active timers.
Definition Timer.cs:144
TimerType
Specifies when a Timer should have its Timer.Tick event raised relative to the engine's main update a...
Definition TimerType.cs:22
@ PreCycle
The timer's Timer.Tick event is raised during the background task phase, before the engine performs i...
Definition TimerType.cs:47
TimerCycles
Specifies the cycle behavior of a Timer, determining whether it executes once or repeatedly at its co...
@ Cycles
Represents the animation cycles state, including sprite animations, frame sequences,...