-
Notifications
You must be signed in to change notification settings - Fork 1
/
GameLoop.cs
262 lines (212 loc) · 8.7 KB
/
GameLoop.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using GameUtils.Graphics;
using GameUtils.Logging;
namespace GameUtils
{
/// <summary>
/// The GameLoop is a singletone game component and serves for continous updating and rendering as well as managing all game objects.
/// </summary>
public sealed class GameLoop : RegistrationTargetBase, IEngineComponent
{
readonly int desiredUpdatesPerSecond;
Thread updateThread;
Thread renderThread;
readonly Stopwatch gameTime;
volatile int currentBufferIndex;
readonly TimeSpan[] bufferUpdateTimes;
readonly AutoResetEvent resourceUpdateHandle;
readonly List<float> updateTimes;
volatile float ups;
readonly List<float> frameTimes;
volatile float fps;
internal event EventHandler ResourceUpdateRequested;
/// <summary>
/// The color the surface will be cleared with at the beginning of a render cycle.
/// </summary>
public Color4 BackColor { get; set; }
/// <summary>
/// Indicates whether the loop is currently running.
/// </summary>
public bool IsRunning { get; private set; }
/// <summary>
/// The current update rate.
/// </summary>
public float UpdatesPerSecond => ups;
/// <summary>
/// The current frame rate.
/// </summary>
public float FramesPerSecond => fps;
protected override int CurrentBufferIndex => currentBufferIndex;
bool IEngineComponent.IsCompatibleTo(IEngineComponent component)
{
return !(component is GameLoop);
}
object IEngineComponent.Tag => null;
/// <summary>
/// Creates a new game loop.
/// </summary>
public GameLoop(int desiredUpdatesPerSecond, bool enableDepthBuffering = false)
{
this.desiredUpdatesPerSecond = desiredUpdatesPerSecond;
gameTime = new Stopwatch();
bufferUpdateTimes = new TimeSpan[BufferCount];
this.IsRunning = false;
EnableDepthBuffering = enableDepthBuffering;
resourceUpdateHandle = new AutoResetEvent(true);
updateTimes = new List<float>();
frameTimes = new List<float>();
BackColor = Color4.Black;
}
/// <summary>
/// Starts the loop.
/// </summary>
public void Start()
{
Logger logger = GameEngine.TryQueryComponent<Logger>();
if (this.IsRunning)
{
logger?.PostMessage(
"It has been tried to start an already running game loop.",
LogMessageKind.Warning, LogMessagePriority.Engine);
return;
}
this.IsRunning = true;
for (int i = 0; i < BufferCount; i++)
bufferUpdateTimes[i] = TimeSpan.Zero;
gameTime.Start();
updateThread = new Thread(UpdateLoop) { Name = "game update thread" };
updateThread.Start();
logger?.PostMessage(
"Game loop started.",
LogMessageKind.Information, LogMessagePriority.Engine);
}
/// <summary>
/// Stops the loop.
/// </summary>
/// <remarks>
/// This method blocks until both update and render thread have terminated so don't call it within these threads.
/// </remarks>
/// <exception cref="System.InvalidOperationException">Is thrown when the method was called from the update or the render thread.</exception>
public void Stop()
{
Logger logger = GameEngine.TryQueryComponent<Logger>();
if (Thread.CurrentThread.ManagedThreadId == updateThread.ManagedThreadId
|| Thread.CurrentThread.ManagedThreadId == renderThread.ManagedThreadId)
{
logger?.PostMessage(
"Stopping of a game loop is impossible from the update thread or the render thread.",
LogMessageKind.Error, LogMessagePriority.Engine);
throw new InvalidOperationException("The loop must not be stopped from the update thread or the render thread.");
}
if (!this.IsRunning)
{
logger?.PostMessage(
"It has been tried to stop a already stopped game loop.",
LogMessageKind.Warning, LogMessagePriority.Engine);
return;
}
this.IsRunning = false;
resourceUpdateHandle.Set();
updateThread.Join();
renderThread?.Join();
updateThread = null;
renderThread = null;
resourceUpdateHandle.Set();
gameTime.Reset();
ups = 0;
fps = 0;
updateTimes.Clear();
frameTimes.Clear();
logger?.PostMessage(
"Game loop stopped.",
LogMessageKind.Information, LogMessagePriority.Engine);
}
private static void WaitForElapsed(Stopwatch sw, TimeSpan targetElapsed)
{
var bufferTime = TimeSpan.FromMilliseconds(1);
if (sw.Elapsed < (targetElapsed - bufferTime))
{
Thread.Sleep(targetElapsed - sw.Elapsed - bufferTime);
}
while (sw.Elapsed < targetElapsed) { }
}
private void UpdateLoop()
{
var elapsed = TimeSpan.Zero;
var targetElapsed = TimeSpan.FromTicks((long)((1000.0 / desiredUpdatesPerSecond) * TimeSpan.TicksPerMillisecond));
int bufferIndex = 0;
currentBufferIndex = BufferCount - 1;
while (this.IsRunning)
{
TimeSpan startTime = gameTime.Elapsed;
bufferUpdateTimes[bufferIndex] = startTime;
Parallel.ForEach(Updateables, updateable => updateable.SetCurrentBufferIndex(currentBufferIndex));
Update(bufferIndex, elapsed);
WaitForElapsed(gameTime, startTime + targetElapsed);
currentBufferIndex = bufferIndex;
bufferIndex = (bufferIndex + 1) % BufferCount;
elapsed = gameTime.Elapsed - startTime;
updateTimes.Add((float)elapsed.TotalMilliseconds);
int counter = 0;
int index = updateTimes.Count - 1;
float ms = 0;
while (index >= 0 && ms + updateTimes[index] <= 1000)
{
ms += updateTimes[index];
counter++;
index--;
}
if (index > 0) updateTimes.RemoveRange(0, index);
ups = counter + ((1000 - ms) / updateTimes[0]);
if (renderThread == null)
{
renderThread = new Thread(RenderLoop) { Name = "game render thread" };
renderThread.Start();
}
}
}
private void Update(int bufferIndex, TimeSpan elapsed)
{
//resourceUpdateHandle.WaitOne();
Updateables.ApplyChanges();
Parallel.ForEach(Updateables, updateable => updateable.Update(bufferIndex, elapsed));
}
private void RenderLoop()
{
Renderer renderer = GameEngine.QueryComponent<Renderer>();
while (this.IsRunning)
{
TimeSpan startTime = gameTime.Elapsed;
Render(currentBufferIndex, gameTime.Elapsed - bufferUpdateTimes[currentBufferIndex], renderer);
TimeSpan elapsed = gameTime.Elapsed - startTime;
frameTimes.Add((float)elapsed.TotalMilliseconds);
int counter = 0;
int index = frameTimes.Count - 1;
float ms = 0;
while (index >= 0 && ms + frameTimes[index] <= 1000)
{
ms += frameTimes[index];
counter++;
index--;
}
if (index > 0) frameTimes.RemoveRange(0, index);
fps = counter + ((1000 - ms) / frameTimes[0]);
}
}
private void Render(int bufferIndex, TimeSpan elapsed, Renderer renderer)
{
Renderables.ApplyChanges();
ResourceUpdateRequested?.Invoke(this, EventArgs.Empty);
resourceUpdateHandle.Set();
SortRenderables();
renderer.BeginRender(BackColor);
foreach (RenderContainer renderable in Renderables)
renderable.Render(bufferIndex, elapsed, renderer);
renderer.EndRender();
}
}
}