This repository has been archived by the owner on Aug 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Scheduler.cpp
315 lines (250 loc) · 8.26 KB
/
Scheduler.cpp
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#include <algorithm>
#include <iterator>
#include <limits>
#include <string>
#include "AngelscriptUtils/execution/Execution.h"
#include "AngelscriptUtils/ScriptAPI/Scheduler.h"
#include "AngelscriptUtils/utility/ContextUtils.h"
#include "AngelscriptUtils/utility/Objects.h"
#include "AngelscriptUtils/utility/RegistrationUtils.h"
#include "AngelscriptUtils/utility/TypeInfo.h"
namespace asutils
{
void Scheduler::ClearTimer(TimerID id)
{
if (m_ExecutingFunctions)
{
//Delay until functios have finished executing
m_FunctionsToRemove.emplace_back(id);
return;
}
auto end = m_Functions.end();
for (auto it = m_Functions.begin(); it != end; ++it)
{
if ((*it)->m_ID == id)
{
m_Functions.erase(it);
break;
}
}
}
void Scheduler::Think(const float currentTime, asIScriptContext& context)
{
m_ExecutingFunctions = true;
for (auto it = m_Functions.begin(); it != m_Functions.end();)
{
auto& function = **it;
if (function.m_ExecutionTime <= currentTime &&
ExecuteFunction(function, context))
{
it = m_Functions.erase(it);
}
else
{
++it;
}
}
m_ExecutingFunctions = false;
//Add new functions
if (!m_FunctionsToAdd.empty())
{
if (m_Functions.empty())
{
m_Functions = std::move(m_FunctionsToAdd);
}
else
{
m_Functions.reserve(m_Functions.size() + m_FunctionsToAdd.size());
std::move(m_FunctionsToAdd.begin(), m_FunctionsToAdd.end(), std::back_inserter(m_Functions));
m_FunctionsToAdd.clear();
}
}
//Remove functions flagged for removal
//This can include functions that were added from m_FunctionsToAdd, so perform this operation after adding those
if (!m_FunctionsToRemove.empty())
{
for (auto id : m_FunctionsToRemove)
{
ClearTimer(id);
}
m_FunctionsToRemove.clear();
}
}
bool Scheduler::ExecuteFunction(ScheduledFunction& function, asIScriptContext& context)
{
//Call will log any errors if the context has logging enabled
PackedCall(*function.m_Function, context, function.m_Parameters);
if (function.m_RepeatCount != REPEAT_INFINITE_TIMES)
{
--function.m_RepeatCount;
}
const auto shouldRemove = function.m_RepeatCount == 0;
if (!shouldRemove)
{
//This must not use m_CurrentTime as a base because otherwise additional delays will creep in over time
//This is because m_ExecutionTime is <= currentTime, not ==
function.m_ExecutionTime += function.m_RepeatInterval;
}
return shouldRemove;
}
void Scheduler::AdjustExecutionTimes(float adjustAmount)
{
for (auto& function : m_Functions)
{
function->m_ExecutionTime += adjustAmount;
}
}
void Scheduler::RemoveFunctionsOfModule(asIScriptModule& module)
{
for (auto it = m_Functions.begin(); it != m_Functions.end();)
{
if ((*it)->m_Function->GetModule() == &module)
{
it = m_Functions.erase(it);
}
else
{
++it;
}
}
}
void Scheduler::SetTimeout(asIScriptGeneric* parameters)
{
auto& scheduler = *reinterpret_cast<Scheduler*>(parameters->GetObject());
scheduler.TrySetInterval(*parameters, ScheduleType::Timeout);
}
void Scheduler::SetInterval(asIScriptGeneric* parameters)
{
auto& scheduler = *reinterpret_cast<Scheduler*>(parameters->GetObject());
scheduler.TrySetInterval(*parameters, ScheduleType::Interval);
}
void Scheduler::SetRepeating(asIScriptGeneric* parameters)
{
auto& scheduler = *reinterpret_cast<Scheduler*>(parameters->GetObject());
scheduler.TrySetInterval(*parameters, ScheduleType::Repeating);
}
void Scheduler::TrySetInterval(asIScriptGeneric& parameters, const ScheduleType scheduleType)
{
const auto potentiallyAFunction = parameters.GetArgAddress(0);
const auto typeId = parameters.GetArgTypeId(0);
const auto repeatInterval = parameters.GetArgFloat(1);
int repeatCount;
switch (scheduleType)
{
case ScheduleType::Timeout:
//Repeat once if timeout
repeatCount = 1;
break;
case ScheduleType::Interval:
repeatCount = static_cast<int>(parameters.GetArgDWord(2));
break;
//Default case should never be hit but the compiler doesn't agree
default:
case ScheduleType::Repeating:
//Repeat until caller clears timer
repeatCount = REPEAT_INFINITE_TIMES;
break;
}
const asUINT startIndex = scheduleType == ScheduleType::Interval ? 3 : 2;
const auto timerID = TrySchedule(potentiallyAFunction, typeId, parameters, startIndex, repeatInterval, repeatCount);
parameters.SetReturnDWord(timerID);
}
Scheduler::TimerID Scheduler::TrySchedule(void* potentiallyAFunction, int typeId,
asIScriptGeneric& parameters, asUINT startIndex, float repeatInterval, int repeatCount)
{
auto& engine = *parameters.GetEngine();
auto function = TryGetFunctionFromVariableParameter(engine, potentiallyAFunction, typeId);
if (!function)
{
WriteError("Function parameter must be a function or function delegate");
return INVALID_ID;
}
{
auto context = asGetActiveContext();
auto caller = context->GetFunction(context->GetCallstackSize() - 1);
if (caller->GetModule() != function->GetModule())
{
WriteError("The given function must be part of the same script as the function that is scheduling the timer");
return INVALID_ID;
}
}
//This is not off by one; if there are no variadic parameters then startIndex will be equal to the parameter count
if (startIndex > static_cast<asUINT>(parameters.GetArgCount()))
{
WriteError("Application error: starting index must be in range");
return INVALID_ID;
}
const asUINT parameterCount = parameters.GetArgCount() - startIndex;
//Validate the parameters
if (function->GetParamCount() != parameterCount)
{
WriteError("Parameter count must match the target function");
return INVALID_ID;
}
//Validate repeat settings
//Allow 0 to execute a function every frame
if (repeatInterval < 0)
{
WriteError("Repeat interval must be a positive value");
return INVALID_ID;
}
if (repeatCount <= 0 && repeatCount != REPEAT_INFINITE_TIMES)
{
WriteError("Repeat count must be larger than zero or REPEAT_INFINITE_TIMES");
return INVALID_ID;
}
//Construct parameter list and convert types to match exactly the target function
//This is more efficient than converting on execution
ScriptParameters parameterList;
try
{
parameterList = CreateGenericParameterList(parameters, startIndex);
}
catch (const ScriptParameterErrorException& e)
{
WriteError((std::string{"Application error: Error creating parameter list: "} + e.what()).c_str());
return INVALID_ID;
}
return Schedule(*function, std::move(parameterList), m_CurrentTime + repeatInterval, repeatInterval, repeatCount);
}
Scheduler::TimerID Scheduler::Schedule(asIScriptFunction& function, ScriptParameters&& parameters, float executionTime, float repeatInterval, int repeatCount)
{
const auto timerID = m_NextID++;
//Unlikely to happen but will occur on long running scripts
if (m_NextID == std::numeric_limits<TimerID>::max())
{
m_NextID = 1;
}
auto scheduled = std::make_unique<ScheduledFunction>(timerID,
ReferencePointer<asIScriptFunction>(&function), std::move(parameters), executionTime, repeatInterval, repeatCount);
if (m_ExecutingFunctions)
{
m_FunctionsToAdd.emplace_back(std::move(scheduled));
}
else
{
m_Functions.emplace_back(std::move(scheduled));
}
return timerID;
}
void Scheduler::WriteError(const char* message)
{
auto context = asGetActiveContext();
auto& engine = *context->GetEngine();
LocationInfo info;
GetCallerInfo(*context, info);
engine.WriteMessage(info.section.c_str(), info.line, info.column, asMSGTYPE_ERROR, message);
}
void RegisterSchedulerAPI(asIScriptEngine& engine)
{
const auto className = "ScriptScheduler";
const size_t MaxVarArgs = 8;
engine.RegisterObjectType(className, 0, asOBJ_REF | asOBJ_NOCOUNT);
//Use a typedef for this to make it possible to change the underlying type to 64 bit if it's ever needed
engine.RegisterTypedef("TimerID", "uint32");
RegisterVariadicMethod(engine, className, "TimerID", "SetTimeout", "?& in function, float delay", 0, MaxVarArgs, asFUNCTION(Scheduler::SetTimeout));
RegisterVariadicMethod(engine, className, "TimerID", "SetInterval", "?& in function, float repeatInterval, int repeatCount", 0, MaxVarArgs, asFUNCTION(Scheduler::SetInterval));
RegisterVariadicMethod(engine, className, "TimerID", "SetRepeating", "?& in function, float repeatInterval", 0, MaxVarArgs, asFUNCTION(Scheduler::SetRepeating));
engine.RegisterObjectMethod(className, "void ClearTimer(TimerID id)", asMETHOD(Scheduler, ClearTimer), asCALL_THISCALL);
}
}