-
Notifications
You must be signed in to change notification settings - Fork 34
/
V8ResourceImpl.h
430 lines (342 loc) · 14 KB
/
V8ResourceImpl.h
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#pragma once
#include <chrono>
#include <filesystem>
#include "cpp-sdk/types/MValue.h"
#include "cpp-sdk/IResource.h"
#include "cpp-sdk/objects/IBaseObject.h"
#include "V8Entity.h"
#include "V8Timer.h"
#include "IRuntimeEventHandler.h"
#include "V8Helpers.h"
class V8ResourceImpl : public alt::IResource::Impl
{
public:
class FunctionImpl : public alt::IMValueFunction::Impl
{
public:
FunctionImpl(V8ResourceImpl* _resource, v8::Local<v8::Function> fn) : resource(_resource), function(_resource->GetIsolate(), fn) {}
alt::MValue Call(alt::MValueArgs args) const override;
private:
V8ResourceImpl* resource;
v8::Global<v8::Function> function;
};
V8ResourceImpl(v8::Isolate* _isolate, alt::IResource* _resource) : isolate(_isolate), resource(_resource) {}
bool Start() override;
bool Stop() override;
void OnTick() override;
inline alt::IResource* GetResource()
{
return resource;
}
inline v8::Isolate* GetIsolate()
{
return isolate;
}
inline v8::Local<v8::Context> GetContext()
{
return context.Get(isolate);
}
void SubscribeLocal(const std::string& ev, v8::Local<v8::Function> cb, V8Helpers::SourceLocation&& location, bool once = false)
{
alt::CEvent::Type type = V8Helpers::EventHandler::GetTypeForEventName(ev);
if(type != alt::CEvent::Type::NONE) IRuntimeEventHandler::Instance().EventHandlerAdded(type);
localHandlers.insert({ ev, V8Helpers::EventCallback{ isolate, cb, std::move(location), once } });
}
void SubscribeRemote(const std::string& ev, v8::Local<v8::Function> cb, V8Helpers::SourceLocation&& location, bool once = false)
{
remoteHandlers.insert({ ev, V8Helpers::EventCallback{ isolate, cb, std::move(location), once } });
}
void SubscribeGenericLocal(v8::Local<v8::Function> cb, V8Helpers::SourceLocation&& location, bool once = false)
{
localGenericHandlers.push_back(V8Helpers::EventCallback{ isolate, cb, std::move(location), once });
}
void SubscribeGenericRemote(v8::Local<v8::Function> cb, V8Helpers::SourceLocation&& location, bool once = false)
{
remoteGenericHandlers.push_back(V8Helpers::EventCallback{ isolate, cb, std::move(location), once });
}
void UnsubscribeLocal(const std::string& ev, v8::Local<v8::Function> cb, V8Helpers::SourceLocation&& location)
{
auto range = localHandlers.equal_range(ev);
bool anyHandlerRemoved = false;
for(auto it = range.first; it != range.second; ++it)
{
if(it->second.fn.Get(isolate)->StrictEquals(cb))
{
it->second.removed = true;
anyHandlerRemoved = true;
}
}
if(!anyHandlerRemoved)
{
Log::Warning << location.ToString(isolate) << " alt.off was called for event \"" << ev << "\" with function reference that was not subscribed" << Log::Endl;
return;
}
alt::CEvent::Type type = V8Helpers::EventHandler::GetTypeForEventName(ev);
if(type != alt::CEvent::Type::NONE) IRuntimeEventHandler::Instance().EventHandlerRemoved(type);
}
void UnsubscribeRemote(const std::string& ev, v8::Local<v8::Function> cb)
{
auto range = remoteHandlers.equal_range(ev);
for(auto it = range.first; it != range.second; ++it)
{
if(it->second.fn.Get(isolate)->StrictEquals(cb)) it->second.removed = true;
}
}
void UnsubscribeGenericLocal(v8::Local<v8::Function> cb)
{
for(auto& it : localGenericHandlers)
{
if(it.fn.Get(isolate)->StrictEquals(cb)) it.removed = true;
}
}
void UnsubscribeGenericRemote(v8::Local<v8::Function> cb)
{
for(auto& it : remoteGenericHandlers)
{
if(it.fn.Get(isolate)->StrictEquals(cb)) it.removed = true;
}
}
void DispatchStartEvent(bool error)
{
std::vector<v8::Local<v8::Value>> args;
args.push_back(V8Helpers::JSValue(error));
InvokeEventHandlers(nullptr, GetLocalHandlers("resourceStart"), args, true);
}
void DispatchStopEvent()
{
std::vector<v8::Local<v8::Value>> args;
InvokeEventHandlers(nullptr, GetLocalHandlers("resourceStop"), args, true);
}
void DispatchErrorEvent(const std::string& errorMsg, const std::string& file, int32_t line, const std::string& stackTrace)
{
std::vector<v8::Local<v8::Value>> args = { v8::Exception::Error(V8Helpers::JSValue(errorMsg)), V8Helpers::JSValue(file), V8Helpers::JSValue(line), V8Helpers::JSValue(stackTrace) };
InvokeEventHandlers(nullptr, GetLocalHandlers("resourceError"), args);
}
V8Entity* GetEntity(alt::IBaseObject* handle)
{
auto it = entities.find(handle);
if(it == entities.end()) return nullptr;
return it->second;
}
V8Entity* CreateEntity(alt::IBaseObject* handle)
{
V8Class* _class = V8Entity::GetClass(handle);
if(!_class)
{
Log::Error << "Failed to create entity: Type " << (int)handle->GetType() << " has no class" << Log::Endl;
return nullptr;
}
V8Entity* ent = new V8Entity(GetContext(), _class, _class->CreateInstance(GetContext()), handle);
entities.insert({ handle, ent });
return ent;
}
void BindEntity(v8::Local<v8::Object> val, alt::IBaseObject* handle);
V8Entity* GetOrCreateEntity(alt::IBaseObject* handle, const char* className = "")
{
if(!handle) Log::Error << __FUNCTION__ << " received invalid handle please contact developers if you see this" << Log::Endl;
V8Entity* ent = GetEntity(handle);
if(!ent) ent = CreateEntity(handle);
return ent;
}
v8::Local<v8::Value> GetBaseObjectOrNull(alt::IBaseObject* handle);
template<class T>
v8::Local<v8::Value> GetBaseObjectOrNull(const T*& handle)
{
return GetBaseObjectOrNull(handle->Get());
}
v8::Local<v8::Value> CreateVector3(alt::Vector3f vec);
v8::Local<v8::Value> CreateVector2(alt::Vector2f vec);
v8::Local<v8::Value> CreateQuaternion(alt::Quaternion quat);
v8::Local<v8::Value> CreateRGBA(alt::RGBA rgba);
/*bool IsVector3(v8::Local<v8::Value> val);
bool IsVector2(v8::Local<v8::Value> val);
bool IsQuaternion(v8::Local<v8::Value> val);
bool IsRGBA(v8::Local<v8::Value> val);
bool IsBaseObject(v8::Local<v8::Value> val);*/
void OnCreateBaseObject(alt::IBaseObject* handle) override;
void OnRemoveBaseObject(alt::IBaseObject* handle) override;
alt::MValue GetFunction(v8::Local<v8::Value> val)
{
FunctionImpl* impl = new FunctionImpl{ this, val.As<v8::Function>() };
return alt::ICore::Instance().CreateMValueFunction(impl);
}
uint32_t CreateTimer(v8::Local<v8::Context> context, v8::Local<v8::Function> callback, uint32_t interval, bool once, V8Helpers::SourceLocation&& location)
{
uint32_t id = ++nextTimerId;
timers[id] = new V8Timer{ isolate, context, GetTime(), callback, interval, once, std::move(location) };
return id;
}
void RemoveTimer(uint32_t id)
{
oldTimers.push_back(id);
}
bool DoesTimerExist(uint32_t id)
{
return timers.count(id) != 0;
}
void TimerBenchmark()
{
size_t totalCount = 0, everyTickCount = 0, intervalCount = 0, timeoutCount = 0;
totalCount = timers.size();
for(auto [id, timer] : timers)
{
if(timer->GetInterval() == 0 && !timer->IsOnce()) everyTickCount += 1;
else if(timer->IsOnce())
timeoutCount += 1;
else
intervalCount += 1;
}
Log::Info << GetResource()->GetName() << ": " << totalCount << " running timers (" << everyTickCount << " EveryTick, " << intervalCount << " Interval, " << timeoutCount << " Timeout"
<< ")" << Log::Endl;
}
void NotifyPoolUpdate(alt::IBaseObject* ent);
v8::Local<v8::Array> GetAllPlayers();
v8::Local<v8::Array> GetAllVehicles();
v8::Local<v8::Array> GetAllBlips();
v8::Local<v8::Array> GetAllAudioOutputs();
v8::Local<v8::Array> GetAllCheckpoints();
v8::Local<v8::Array> GetAllVirtualEntityGroups();
v8::Local<v8::Array> GetAllVirtualEntities();
v8::Local<v8::Array> GetAllPeds();
v8::Local<v8::Array> GetAllMarkers();
v8::Local<v8::Array> GetAllColshapes();
#ifdef ALT_SERVER_API
v8::Local<v8::Array> GetAllConnectionInfos();
#endif
#ifdef ALT_CLIENT_API
v8::Local<v8::Array> GetAllLocalObjects();
v8::Local<v8::Array> GetAllWeaponObjects();
#endif
v8::Local<v8::Array> GetAllObjects();
v8::Local<v8::Array> GetAllTextLabels();
std::vector<V8Helpers::EventCallback*> GetLocalHandlers(const std::string& name);
std::vector<V8Helpers::EventCallback*> GetRemoteHandlers(const std::string& name);
std::vector<V8Helpers::EventCallback*> GetGenericHandlers(bool local);
using NextTickCallback = std::function<void()>;
void RunOnNextTick(NextTickCallback&& callback)
{
nextTickCallbacks.push_back(callback);
}
v8::Local<v8::Object> GetOrCreateResourceObject(alt::IResource* resource);
void DeleteResourceObject(alt::IResource* resource);
bool HasBenchmarkTimer(const std::string& name)
{
return benchmarkTimers.count(name) != 0;
}
void CreateBenchmarkTimer(const std::string& name)
{
benchmarkTimers.insert({ name, std::chrono::high_resolution_clock::now() });
}
void RemoveBenchmarkTimer(const std::string& name)
{
benchmarkTimers.erase(name);
}
std::chrono::high_resolution_clock::time_point GetBenchmarkTimerStart(const std::string& name)
{
return benchmarkTimers.at(name);
}
v8::Local<v8::Function> GetLogFunction()
{
return logFunction.Get(isolate);
}
void SetLogFunction(v8::Local<v8::Function> function)
{
logFunction.Reset(isolate, function);
}
void SetupScriptGlobals();
static V8ResourceImpl* Get(v8::Local<v8::Context> ctx)
{
alt::IResource* resource = GetResource(ctx);
return resource ? static_cast<V8ResourceImpl*>(resource->GetImpl()) : nullptr;
}
static alt::IResource* GetResource(v8::Local<v8::Context> ctx)
{
return static_cast<alt::IResource*>(ctx->GetAlignedPointerFromEmbedderData(1));
}
struct AwaitableRPCHandler
{
#ifdef ALT_SERVER_API
alt::IPlayer* Player;
#endif
uint16_t AnswerId;
v8::Global<v8::Promise> Promise;
};
#ifdef ALT_SERVER_API
// Vehicle passengers
static inline std::unordered_map<alt::IVehicle*, std::unordered_map<uint8_t, alt::IPlayer*>> vehiclePassengers{};
struct RemoteRPCHandler
{
uint16_t AnswerId;
V8Helpers::CPersistent<v8::Promise::Resolver> PromiseResolver;
};
// rpcs
std::unordered_map<std::string, v8::Global<v8::Function>> rpcHandlers{};
std::unordered_map<alt::IPlayer*, std::vector<RemoteRPCHandler>> remoteRPCHandlers{};
std::vector<AwaitableRPCHandler> awaitableRPCHandlers{};
#else
std::unordered_map<uint16_t, V8Helpers::CPersistent<v8::Promise::Resolver>> remoteRPCHandlers{};
std::unordered_map<std::string, v8::Global<v8::Function>> rpcHandlers{};
std::vector<AwaitableRPCHandler> awaitableRPCHandlers{};
#endif
protected:
v8::Isolate* isolate;
alt::IResource* resource;
V8Helpers::CPersistent<v8::Context> context;
std::unordered_map<alt::IBaseObject*, V8Entity*> entities;
std::unordered_map<uint32_t, V8Timer*> timers;
// Key = Name, Value = Start time
std::unordered_map<std::string, std::chrono::high_resolution_clock::time_point> benchmarkTimers;
std::unordered_multimap<std::string, V8Helpers::EventCallback> localHandlers;
std::unordered_multimap<std::string, V8Helpers::EventCallback> remoteHandlers;
std::vector<V8Helpers::EventCallback> localGenericHandlers;
std::vector<V8Helpers::EventCallback> remoteGenericHandlers;
uint32_t nextTimerId = 0;
std::vector<uint32_t> oldTimers;
bool playerPoolDirty = true;
V8Helpers::CPersistent<v8::Array> players;
bool vehiclePoolDirty = true;
V8Helpers::CPersistent<v8::Array> vehicles;
bool objectPoolDirty = true;
V8Helpers::CPersistent<v8::Array> objects;
bool weaponObjectPoolDirty = true;
V8Helpers::CPersistent<v8::Array> weaponObjects;
V8Helpers::CPersistent<v8::Function> vector3Class;
V8Helpers::CPersistent<v8::Function> vector2Class;
V8Helpers::CPersistent<v8::Function> quaternionClass;
V8Helpers::CPersistent<v8::Function> rgbaClass;
V8Helpers::CPersistent<v8::Function> baseObjectClass;
V8Helpers::CPersistent<v8::Function> logFunction;
std::unordered_map<alt::IResource*, V8Helpers::CPersistent<v8::Object>> resourceObjects;
std::vector<NextTickCallback> nextTickCallbacks;
// TEMP
static int64_t GetTime()
{
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
}
void InvokeEventHandlers(const alt::CEvent* ev, const std::vector<V8Helpers::EventCallback*>& handlers, std::vector<v8::Local<v8::Value>>& args, bool waitForPromiseResolve = false);
public:
struct ObjectKey
{
ObjectKey(V8ResourceImpl* _resource, const char* _key) : resource(_resource), keyStr(_key) {}
v8::Local<v8::String> operator()()
{
if(key.IsEmpty()) key.Reset(resource->GetIsolate(), v8::String::NewFromUtf8(resource->GetIsolate(), keyStr, v8::NewStringType::kInternalized).ToLocalChecked());
return key.Get(resource->GetIsolate());
}
private:
V8ResourceImpl* resource;
const char* keyStr;
v8::Persistent<v8::String> key;
};
ObjectKey XKey{ this, "x" };
ObjectKey YKey{ this, "y" };
ObjectKey ZKey{ this, "z" };
ObjectKey WKey{ this, "w" };
ObjectKey RKey{ this, "r" };
ObjectKey GKey{ this, "g" };
ObjectKey BKey{ this, "b" };
ObjectKey AKey{ this, "a" };
ObjectKey PosKey{ this, "pos" };
ObjectKey WeaponKey{ this, "weapon" };
void PrintHealth();
};