-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathTLuaEngine.cpp
1269 lines (1182 loc) · 51.3 KB
/
TLuaEngine.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
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// BeamMP, the BeamNG.drive multiplayer mod.
// Copyright (C) 2024 BeamMP Ltd., BeamMP team and contributors.
//
// BeamMP Ltd. can be contacted by electronic mail via contact@beammp.com.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include "TLuaEngine.h"
#include "Client.h"
#include "Common.h"
#include "CustomAssert.h"
#include "Http.h"
#include "LuaAPI.h"
#include "Profiling.h"
#include "TLuaPlugin.h"
#include "sol/object.hpp"
#include <chrono>
#include <condition_variable>
#include <fmt/core.h>
#include <nlohmann/json.hpp>
#include <optional>
#include <random>
#include <sol/stack_core.hpp>
#include <thread>
#include <tuple>
TLuaEngine* LuaAPI::MP::Engine;
static sol::protected_function AddTraceback(sol::state_view StateView, sol::protected_function RawFn);
TLuaEngine::TLuaEngine()
: mResourceServerPath(fs::path(Application::Settings.getAsString(Settings::Key::General_ResourceFolder)) / "Server") {
Application::SetSubsystemStatus("LuaEngine", Application::Status::Starting);
LuaAPI::MP::Engine = this;
if (!fs::exists(Application::Settings.getAsString(Settings::Key::General_ResourceFolder))) {
fs::create_directory(Application::Settings.getAsString(Settings::Key::General_ResourceFolder));
}
if (!fs::exists(mResourceServerPath)) {
fs::create_directory(mResourceServerPath);
}
Application::RegisterShutdownHandler([&] {
Application::SetSubsystemStatus("LuaEngine", Application::Status::ShuttingDown);
if (mThread.joinable()) {
mThread.join();
}
Application::SetSubsystemStatus("LuaEngine", Application::Status::Shutdown);
});
IThreaded::Start();
}
TEST_CASE("TLuaEngine ctor & dtor") {
Application::Settings.set(Settings::Key::General_ResourceFolder, "beammp_server_test_resources");
TLuaEngine engine;
Application::GracefullyShutdown();
}
void TLuaEngine::operator()() {
RegisterThread("LuaEngine");
Application::SetSubsystemStatus("LuaEngine", Application::Status::Good);
// lua engine main thread
beammp_infof("Lua v{}.{}.{}", LUA_VERSION_MAJOR, LUA_VERSION_MINOR, LUA_VERSION_RELEASE);
CollectAndInitPlugins();
// now call all onInit's
auto Futures = TriggerEvent("onInit", "");
WaitForAll(Futures, std::chrono::seconds(5));
for (const auto& Future : Futures) {
if (Future->Error && Future->ErrorMessage != BeamMPFnNotFoundError) {
beammp_lua_error("Calling \"onInit\" on \"" + Future->StateId + "\" failed: " + Future->ErrorMessage);
}
}
auto ResultCheckThread = std::thread([&] {
RegisterThread("ResultCheckThread");
while (!Application::IsShuttingDown()) {
std::unique_lock Lock(mResultsToCheckMutex);
if (!mResultsToCheck.empty()) {
mResultsToCheck.remove_if([](const std::shared_ptr<TLuaResult>& Ptr) -> bool {
if (Ptr->Ready) {
if (Ptr->Error) {
if (Ptr->ErrorMessage != BeamMPFnNotFoundError) {
beammp_lua_error(Ptr->Function + ": " + Ptr->ErrorMessage);
}
}
return true;
}
return false;
});
} else {
mResultsToCheckCond.wait_for(Lock, std::chrono::milliseconds(20));
}
}
});
// event loop
auto Before = std::chrono::high_resolution_clock::now();
while (!Application::IsShuttingDown()) {
{ // Timed Events Scope
std::unique_lock Lock(mTimedEventsMutex);
for (auto& Timer : mTimedEvents) {
if (Timer.Expired()) {
auto LastCompletionBeforeReset = Timer.LastCompletion;
Timer.Reset();
auto Handlers = GetEventHandlersForState(Timer.EventName, Timer.StateId);
std::unique_lock StateLock(mLuaStatesMutex);
std::unique_lock Lock2(mResultsToCheckMutex);
for (auto& Handler : Handlers) {
auto Res = mLuaStates[Timer.StateId]->EnqueueFunctionCallFromCustomEvent(Handler, {}, Timer.EventName, Timer.Strategy);
if (Res) {
mResultsToCheck.push_back(Res);
mResultsToCheckCond.notify_one();
} else {
// "revert" reset
Timer.LastCompletion = LastCompletionBeforeReset;
// beammp_trace("Reverted reset of \"" + Timer.EventName + "\" timer");
// no need to try to enqueue more handlers for this event (they will all fail)
break;
}
}
}
}
}
if (mLuaStates.size() == 0) {
beammp_trace("No Lua states, event loop running extremely sparsely");
Application::SleepSafeSeconds(10);
} else {
constexpr double NsFactor = 1000000.0;
constexpr double Expected = 10.0; // ms
const auto Diff = (std::chrono::high_resolution_clock::now() - Before).count() / NsFactor;
if (Diff < Expected) {
std::this_thread::sleep_for(std::chrono::nanoseconds(size_t((Expected - Diff) * NsFactor)));
} else {
beammp_tracef("Event loop cannot keep up! Running {}ms behind", Diff);
}
}
Before = std::chrono::high_resolution_clock::now();
}
if (ResultCheckThread.joinable()) {
ResultCheckThread.join();
}
}
size_t TLuaEngine::CalculateMemoryUsage() {
size_t Usage = 0;
std::unique_lock Lock(mLuaStatesMutex);
for (auto& State : mLuaStates) {
Usage += State.second->State().memory_used();
}
return Usage;
}
sol::state_view TLuaEngine::GetStateForPlugin(const fs::path& PluginPath) {
for (const auto& Plugin : mLuaPlugins) {
if (fs::equivalent(Plugin->GetFolder(), PluginPath)) {
std::unique_lock Lock(mLuaStatesMutex);
return mLuaStates.at(Plugin->GetConfig().StateId)->State();
}
}
beammp_assert_not_reachable();
return mLuaStates.begin()->second->State();
}
TLuaStateId TLuaEngine::GetStateIDForPlugin(const fs::path& PluginPath) {
for (const auto& Plugin : mLuaPlugins) {
if (fs::equivalent(Plugin->GetFolder(), PluginPath)) {
std::unique_lock Lock(mLuaStatesMutex);
return Plugin->GetConfig().StateId;
}
}
beammp_assert_not_reachable();
return "";
}
void TLuaEngine::AddResultToCheck(const std::shared_ptr<TLuaResult>& Result) {
std::unique_lock Lock(mResultsToCheckMutex);
mResultsToCheck.push_back(Result);
mResultsToCheckCond.notify_one();
}
std::unordered_map<std::string /* event name */, std::vector<std::string> /* handlers */> TLuaEngine::Debug_GetEventsForState(TLuaStateId StateId) {
std::unordered_map<std::string, std::vector<std::string>> Result;
std::unique_lock Lock(mLuaEventsMutex);
for (const auto& EventNameToEventMap : mLuaEvents) {
for (const auto& IdSetOfHandlersPair : EventNameToEventMap.second) {
if (IdSetOfHandlersPair.first == StateId) {
for (const auto& Handler : IdSetOfHandlersPair.second) {
Result[EventNameToEventMap.first].push_back(Handler);
}
}
}
}
return Result;
}
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> TLuaEngine::Debug_GetStateExecuteQueueForState(TLuaStateId StateId) {
std::queue<std::pair<TLuaChunk, std::shared_ptr<TLuaResult>>> Result;
std::unique_lock Lock(mLuaStatesMutex);
Result = mLuaStates.at(StateId)->Debug_GetStateExecuteQueue();
return Result;
}
std::vector<TLuaEngine::QueuedFunction> TLuaEngine::Debug_GetStateFunctionQueueForState(TLuaStateId StateId) {
std::vector<TLuaEngine::QueuedFunction> Result;
std::unique_lock Lock(mLuaStatesMutex);
Result = mLuaStates.at(StateId)->Debug_GetStateFunctionQueue();
return Result;
}
std::vector<TLuaResult> TLuaEngine::Debug_GetResultsToCheckForState(TLuaStateId StateId) {
std::unique_lock Lock(mResultsToCheckMutex);
auto ResultsToCheckCopy = mResultsToCheck;
Lock.unlock();
std::vector<TLuaResult> Result;
while (!ResultsToCheckCopy.empty()) {
auto ResultToCheck = std::move(ResultsToCheckCopy.front());
ResultsToCheckCopy.pop_front();
if (ResultToCheck->StateId == StateId) {
Result.push_back(*ResultToCheck);
}
}
return Result;
}
std::vector<std::string> TLuaEngine::GetStateGlobalKeysForState(TLuaStateId StateId) {
std::unique_lock Lock(mLuaStatesMutex);
auto Result = mLuaStates.at(StateId)->GetStateGlobalKeys();
return Result;
}
std::vector<std::string> TLuaEngine::StateThreadData::GetStateGlobalKeys() {
auto globals = mStateView.globals();
std::vector<std::string> Result;
for (const auto& [key, value] : globals) {
Result.push_back(key.as<std::string>());
}
return Result;
}
std::vector<std::string> TLuaEngine::GetStateTableKeysForState(TLuaStateId StateId, std::vector<std::string> keys) {
std::unique_lock Lock(mLuaStatesMutex);
auto Result = mLuaStates.at(StateId)->GetStateTableKeys(keys);
return Result;
}
std::vector<std::string> TLuaEngine::StateThreadData::GetStateTableKeys(const std::vector<std::string>& keys) {
auto globals = mStateView.globals();
sol::table current = globals;
std::vector<std::string> Result {};
for (const auto& [key, value] : current) {
std::string s = key.as<std::string>();
if (value.get_type() == sol::type::function) {
s += "(";
}
Result.push_back(s);
}
if (!keys.empty()) {
Result.clear();
}
for (size_t i = 0; i < keys.size(); ++i) {
auto obj = current.get<sol::object>(keys.at(i));
if (obj.get_type() == sol::type::lua_nil) {
// error
break;
} else if (i == keys.size() - 1) {
if (obj.get_type() == sol::type::table) {
for (const auto& [key, value] : obj.as<sol::table>()) {
std::string s = key.as<std::string>();
if (value.get_type() == sol::type::function) {
s += "(";
}
Result.push_back(s);
}
} else {
Result = { obj.as<std::string>() };
}
break;
}
if (obj.get_type() == sol::type::table) {
current = obj;
} else {
// error
break;
}
}
return Result;
}
/*
_G.a.b.c.d.
*/
void TLuaEngine::WaitForAll(std::vector<std::shared_ptr<TLuaResult>>& Results, const std::optional<std::chrono::high_resolution_clock::duration>& Max) {
for (const auto& Result : Results) {
bool Cancelled = false;
size_t ms = 0;
std::set<std::string> WarnedResults;
while (!Result->Ready && !Cancelled) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
ms += 10;
if (Max.has_value() && std::chrono::milliseconds(ms) > Max.value()) {
beammp_trace("'" + Result->Function + "' in '" + Result->StateId + "' did not finish executing in time (took: " + std::to_string(ms) + "ms).");
Cancelled = true;
} else if (ms > 1000 * 60) {
auto ResultId = Result->StateId + "_" + Result->Function;
if (WarnedResults.count(ResultId) == 0) {
WarnedResults.insert(ResultId);
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' is taking very long. The event it's handling is too important to discard the result of this handler, but may block this event and possibly the whole lua state.");
}
}
}
if (Cancelled) {
beammp_lua_warn("'" + Result->Function + "' in '" + Result->StateId + "' failed to execute in time and was not waited for. It may still finish executing at a later time.");
LuaAPI::MP::Engine->ReportErrors({ Result });
} else if (Result->Error) {
if (Result->ErrorMessage != BeamMPFnNotFoundError) {
beammp_lua_error(Result->Function + ": " + Result->ErrorMessage);
}
}
}
}
// run this on the error checking thread
void TLuaEngine::ReportErrors(const std::vector<std::shared_ptr<TLuaResult>>& Results) {
std::unique_lock Lock2(mResultsToCheckMutex);
for (const auto& Result : Results) {
mResultsToCheck.push_back(Result);
mResultsToCheckCond.notify_one();
}
}
bool TLuaEngine::HasState(TLuaStateId StateId) {
std::unique_lock Lock(mLuaStatesMutex);
return mLuaStates.find(StateId) != mLuaStates.end();
}
std::shared_ptr<TLuaResult> TLuaEngine::EnqueueScript(TLuaStateId StateID, const TLuaChunk& Script) {
std::unique_lock Lock(mLuaStatesMutex);
return mLuaStates.at(StateID)->EnqueueScript(Script);
}
std::shared_ptr<TLuaResult> TLuaEngine::EnqueueFunctionCall(TLuaStateId StateID, const std::string& FunctionName, const std::vector<TLuaValue>& Args) {
std::unique_lock Lock(mLuaStatesMutex);
return mLuaStates.at(StateID)->EnqueueFunctionCall(FunctionName, Args);
}
void TLuaEngine::CollectAndInitPlugins() {
if (!fs::exists(mResourceServerPath)) {
fs::create_directories(mResourceServerPath);
}
std::vector<fs::path> PluginsEntries;
for (const auto& Entry : fs::directory_iterator(mResourceServerPath)) {
if (Entry.is_directory()) {
PluginsEntries.push_back(Entry);
} else {
beammp_error("\"" + Entry.path().string() + "\" is not a directory, skipping");
}
}
std::sort(PluginsEntries.begin(), PluginsEntries.end(), [](const fs::path& first, const fs::path& second) {
auto firstStr = first.string();
auto secondStr = second.string();
std::transform(firstStr.begin(), firstStr.end(), firstStr.begin(), ::tolower);
std::transform(secondStr.begin(), secondStr.end(), secondStr.begin(), ::tolower);
return firstStr < secondStr;
});
for (const auto& Dir : PluginsEntries) {
auto Path = fs::relative(Dir);
TLuaPluginConfig Config { Path.stem().string() };
FindAndParseConfig(Path, Config);
InitializePlugin(Path, Config);
}
}
void TLuaEngine::InitializePlugin(const fs::path& Folder, const TLuaPluginConfig& Config) {
beammp_assert(fs::exists(Folder));
beammp_assert(fs::is_directory(Folder));
std::unique_lock Lock(mLuaStatesMutex);
EnsureStateExists(Config.StateId, Folder.stem().string(), true);
mLuaStates[Config.StateId]->AddPath(Folder); // add to cpath + path
Lock.unlock();
auto Plugin = std::make_shared<TLuaPlugin>(*this, Config, Folder);
mLuaPlugins.emplace_back(std::move(Plugin));
}
void TLuaEngine::FindAndParseConfig(const fs::path& Folder, TLuaPluginConfig& Config) {
auto ConfigFile = Folder / TLuaPluginConfig::FileName;
if (fs::exists(ConfigFile) && fs::is_regular_file(ConfigFile)) {
try {
auto Data = toml::parse(ConfigFile);
if (Data.contains("LuaStateID")) {
auto ID = toml::find<std::string>(Data, "LuaStateID");
if (!ID.empty()) {
beammp_debug("Plugin \"" + Folder.string() + "\" specified it wants LuaStateID \"" + ID + "\"");
Config.StateId = ID;
} else {
beammp_debug("LuaStateID empty, using plugin name");
}
}
} catch (const std::exception& e) {
beammp_error(Folder.string() + ": " + e.what());
}
}
}
void TLuaEngine::EnsureStateExists(TLuaStateId StateId, const std::string& Name, bool DontCallOnInit) {
beammp_assert(!StateId.empty());
std::unique_lock Lock(mLuaStatesMutex);
if (mLuaStates.find(StateId) == mLuaStates.end()) {
beammp_debug("Creating lua state for state id \"" + StateId + "\"");
auto DataPtr = std::make_unique<StateThreadData>(Name, StateId, *this);
mLuaStates[StateId] = std::move(DataPtr);
RegisterEvent("onInit", StateId, "onInit");
if (!DontCallOnInit) {
auto Res = EnqueueFunctionCall(StateId, "onInit", {});
Res->WaitUntilReady();
if (Res->Error && Res->ErrorMessage != TLuaEngine::BeamMPFnNotFoundError) {
beammp_lua_error("Calling \"onInit\" on \"" + StateId + "\" failed: " + Res->ErrorMessage);
}
}
}
}
void TLuaEngine::RegisterEvent(const std::string& EventName, TLuaStateId StateId, const std::string& FunctionName) {
std::unique_lock Lock(mLuaEventsMutex);
mLuaEvents[EventName][StateId].insert(FunctionName);
}
std::set<std::string> TLuaEngine::GetEventHandlersForState(const std::string& EventName, TLuaStateId StateId) {
return mLuaEvents[EventName][StateId];
}
std::vector<sol::object> TLuaEngine::StateThreadData::JsonStringToArray(JsonString Str) {
auto LocalTable = Lua_JsonDecode(Str.value).as<std::vector<sol::object>>();
for (auto& value : LocalTable) {
if (value.is<std::string>() && value.as<std::string>() == BEAMMP_INTERNAL_NIL) {
value = sol::object {};
}
}
return LocalTable;
}
sol::table TLuaEngine::StateThreadData::Lua_TriggerGlobalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
auto Table = mStateView.create_table();
int i = 1;
for (auto Arg : EventArgs) {
switch (Arg.get_type()) {
case sol::type::none:
case sol::type::userdata:
case sol::type::lightuserdata:
case sol::type::thread:
case sol::type::function:
case sol::type::poly:
Table.set(i, BEAMMP_INTERNAL_NIL);
beammp_warnf("Passed a value of type '{}' to TriggerGlobalEvent(\"{}\", ...). This type can not be serialized, and cannot be passed between states. It will arrive as <nil> in handlers.", sol::type_name(EventArgs.lua_state(), Arg.get_type()), EventName);
break;
case sol::type::lua_nil:
Table.set(i, BEAMMP_INTERNAL_NIL);
break;
case sol::type::string:
case sol::type::number:
case sol::type::boolean:
case sol::type::table:
Table.set(i, Arg);
break;
}
++i;
}
JsonString Str { LuaAPI::MP::JsonEncode(Table) };
beammp_debugf("json: {}", Str.value);
auto Return = mEngine->TriggerEvent(EventName, mStateId, Str);
auto MyHandlers = mEngine->GetEventHandlersForState(EventName, mStateId);
sol::variadic_results LocalArgs = JsonStringToArray(Str);
for (const auto& Handler : MyHandlers) {
auto Fn = mStateView[Handler];
Fn = AddTraceback(mStateView, Fn);
if (Fn.valid()) {
auto LuaResult = Fn(LocalArgs);
auto Result = std::make_shared<TLuaResult>();
if (LuaResult.valid()) {
Result->Error = false;
Result->Result = LuaResult;
} else {
Result->Error = true;
sol::error Err = LuaResult;
Result->ErrorMessage = Err.what();
beammp_errorf("An error occured while executing local event handler \"{}\" for event \"{}\": {}", Handler, EventName, Result->ErrorMessage);
}
Result->MarkAsReady();
Return.push_back(Result);
}
}
sol::state_view StateView(mState);
sol::table AsyncEventReturn = StateView.create_table();
AsyncEventReturn["ReturnValueImpl"] = Return;
AsyncEventReturn.set_function("IsDone",
[&](const sol::table& Self) -> bool {
auto Vector = Self.get<std::vector<std::shared_ptr<TLuaResult>>>("ReturnValueImpl");
for (const auto& Value : Vector) {
if (!Value->Ready) {
return false;
}
}
return true;
});
AsyncEventReturn.set_function("GetResults",
[&](const sol::table& Self) -> sol::table {
sol::state_view StateView(mState);
sol::table Result = StateView.create_table();
auto Vector = Self.get<std::vector<std::shared_ptr<TLuaResult>>>("ReturnValueImpl");
int i = 1;
for (const auto& Value : Vector) {
if (!Value->Ready) {
return sol::lua_nil;
}
Result.set(i, Value->Result);
++i;
}
return Result;
});
return AsyncEventReturn;
}
sol::table TLuaEngine::StateThreadData::Lua_TriggerLocalEvent(const std::string& EventName, sol::variadic_args EventArgs) {
// TODO: make asynchronous?
sol::table Result = mStateView.create_table();
int i = 1;
for (const auto& Handler : mEngine->GetEventHandlersForState(EventName, mStateId)) {
auto Fn = mStateView[Handler];
if (Fn.valid() && Fn.get_type() == sol::type::function) {
auto FnRet = Fn(EventArgs);
if (FnRet.valid()) {
Result.set(i, FnRet);
++i;
} else {
sol::error Err = FnRet;
beammp_lua_error(std::string("TriggerLocalEvent: ") + Err.what());
}
}
}
return Result;
}
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerIdentifiers(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) {
auto IDs = MaybeClient.value().lock()->GetIdentifiers();
if (IDs.empty()) {
return sol::lua_nil;
}
sol::table Result = mStateView.create_table();
for (const auto& Pair : IDs) {
Result[Pair.first] = Pair.second;
}
return Result;
} else {
return sol::lua_nil;
}
}
sol::table TLuaEngine::StateThreadData::Lua_GetPlayers() {
sol::table Result = mStateView.create_table();
mEngine->Server().ForEachClient([&](std::weak_ptr<TClient> Client) -> bool {
if (!Client.expired()) {
auto locked = Client.lock();
Result[locked->GetID()] = locked->GetName();
}
return true;
});
return Result;
}
int TLuaEngine::StateThreadData::Lua_GetPlayerIDByName(const std::string& Name) {
int Id = -1;
mEngine->mServer->ForEachClient([&Id, &Name](std::weak_ptr<TClient> Client) -> bool {
if (!Client.expired()) {
auto locked = Client.lock();
if (locked->GetName() == Name) {
Id = locked->GetID();
return false;
}
}
return true;
});
return Id;
}
sol::table TLuaEngine::StateThreadData::Lua_FS_ListFiles(const std::string& Path) {
if (!std::filesystem::exists(Path)) {
return sol::lua_nil;
}
auto table = mStateView.create_table();
for (const auto& entry : std::filesystem::directory_iterator(Path)) {
if (entry.is_regular_file() || entry.is_symlink()) {
table[table.size() + 1] = entry.path().lexically_relative(Path).string();
}
}
return table;
}
sol::table TLuaEngine::StateThreadData::Lua_FS_ListDirectories(const std::string& Path) {
if (!std::filesystem::exists(Path)) {
return sol::lua_nil;
}
auto table = mStateView.create_table();
for (const auto& entry : std::filesystem::directory_iterator(Path)) {
if (entry.is_directory()) {
table[table.size() + 1] = entry.path().lexically_relative(Path).string();
}
}
return table;
}
std::string TLuaEngine::StateThreadData::Lua_GetPlayerName(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) {
return MaybeClient.value().lock()->GetName();
} else {
return "";
}
}
sol::table TLuaEngine::StateThreadData::Lua_GetPlayerVehicles(int ID) {
auto MaybeClient = GetClient(mEngine->Server(), ID);
if (MaybeClient && !MaybeClient.value().expired()) {
auto Client = MaybeClient.value().lock();
TClient::TSetOfVehicleData VehicleData;
{ // Vehicle Data Lock Scope
auto LockedData = Client->GetAllCars();
VehicleData = *LockedData.VehicleData;
} // End Vehicle Data Lock Scope
if (VehicleData.empty()) {
return sol::lua_nil;
}
sol::state_view StateView(mState);
sol::table Result = StateView.create_table();
for (const auto& v : VehicleData) {
Result[v.ID()] = v.Data().substr(3);
}
return Result;
} else
return sol::lua_nil;
}
std::pair<sol::table, std::string> TLuaEngine::StateThreadData::Lua_GetPositionRaw(int PID, int VID) {
std::pair<sol::table, std::string> Result;
auto MaybeClient = GetClient(mEngine->Server(), PID);
if (MaybeClient && !MaybeClient.value().expired()) {
auto Client = MaybeClient.value().lock();
std::string VehiclePos = Client->GetCarPositionRaw(VID);
if (VehiclePos.empty()) {
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Vehicle not found"));
Result.second = "Vehicle not found";
return Result;
}
sol::table t = Lua_JsonDecode(VehiclePos);
if (t == sol::lua_nil) {
Result.second = "Packet decode failed";
}
// return std::make_tuple(Result, sol::make_object(StateView, sol::lua_nil));
Result.first = t;
return Result;
} else {
// return std::make_tuple(sol::lua_nil, sol::make_object(StateView, "Client expired"));
Result.second = "No such player";
return Result;
}
}
sol::table TLuaEngine::StateThreadData::Lua_HttpCreateConnection(const std::string& host, uint16_t port) {
auto table = mStateView.create_table();
constexpr const char* InternalClient = "__InternalClient";
table["host"] = host;
table["port"] = port;
auto client = std::make_shared<httplib::Client>(host, port);
table[InternalClient] = client;
table.set_function("Get", [&InternalClient](const sol::table& table, const std::string& path, const sol::table& headers) {
httplib::Headers GetHeaders;
for (const auto& pair : headers) {
if (pair.first.is<std::string>() && pair.second.is<std::string>()) {
GetHeaders.insert(std::pair(pair.first.as<std::string>(), pair.second.as<std::string>()));
} else {
beammp_lua_error("Http:Get: Expected string-string pairs for headers, got something else, ignoring that header");
}
}
auto client = table[InternalClient].get<std::shared_ptr<httplib::Client>>();
client->Get(path.c_str(), GetHeaders);
});
return table;
}
template <typename T>
static void AddToTable(sol::table& table, const std::string& left, const T& value) {
if (left.empty()) {
table[table.size() + 1] = value;
} else {
table[left] = value;
}
}
static void JsonDecodeRecursive(sol::state_view& StateView, sol::table& table, const std::string& left, const nlohmann::json& right) {
switch (right.type()) {
case nlohmann::detail::value_t::null:
AddToTable(table, left, sol::lua_nil_t {});
return;
case nlohmann::detail::value_t::object: {
auto value = table.create();
value.clear();
for (const auto& entry : right.items()) {
JsonDecodeRecursive(StateView, value, entry.key(), entry.value());
}
AddToTable(table, left, value);
break;
}
case nlohmann::detail::value_t::array: {
auto value = table.create();
value.clear();
for (const auto& entry : right.items()) {
JsonDecodeRecursive(StateView, value, "", entry.value());
}
AddToTable(table, left, value);
break;
}
case nlohmann::detail::value_t::string:
AddToTable(table, left, right.get<std::string>());
break;
case nlohmann::detail::value_t::boolean:
AddToTable(table, left, right.get<bool>());
break;
case nlohmann::detail::value_t::number_integer:
AddToTable(table, left, right.get<int64_t>());
break;
case nlohmann::detail::value_t::number_unsigned:
AddToTable(table, left, right.get<uint64_t>());
break;
case nlohmann::detail::value_t::number_float:
AddToTable(table, left, right.get<double>());
break;
case nlohmann::detail::value_t::binary:
beammp_lua_error("JsonDecode can't handle binary blob in json, ignoring");
return;
case nlohmann::detail::value_t::discarded:
return;
default:
beammp_assert_not_reachable();
}
}
sol::table TLuaEngine::StateThreadData::Lua_JsonDecode(const std::string& str) {
sol::state_view StateView(mState);
auto table = StateView.create_table();
if (!nlohmann::json::accept(str)) {
beammp_lua_error("string given to JsonDecode is not valid json: `" + str + "`");
return sol::lua_nil;
}
nlohmann::json json = nlohmann::json::parse(str);
if (json.is_object()) {
for (const auto& entry : json.items()) {
JsonDecodeRecursive(StateView, table, entry.key(), entry.value());
}
} else if (json.is_array()) {
for (const auto& entry : json) {
JsonDecodeRecursive(StateView, table, "", entry);
}
} else {
beammp_lua_error("JsonDecode expected array or object json, instead got " + std::string(json.type_name()));
return sol::lua_nil;
}
return table;
}
TLuaEngine::StateThreadData::StateThreadData(const std::string& Name, TLuaStateId StateId, TLuaEngine& Engine)
: mName(Name)
, mStateId(StateId)
, mState(luaL_newstate())
, mEngine(&Engine) {
if (!mState) {
beammp_error("failed to create lua state for \"" + StateId + "\"");
return;
}
luaL_openlibs(mState);
sol::state_view StateView(mState);
lua_atpanic(mState, LuaAPI::PanicHandler);
// StateView.globals()["package"].get()
StateView.set_function("print", &LuaAPI::Print);
StateView.set_function("printRaw", &LuaAPI::MP::PrintRaw);
StateView.set_function("exit", &Application::GracefullyShutdown);
auto MPTable = StateView.create_named_table("MP");
MPTable.set_function("CreateTimer", [&]() -> sol::table {
sol::state_view StateView(mState);
sol::table Result = StateView.create_table();
Result["__StartTime"] = std::chrono::high_resolution_clock::now();
Result.set_function("GetCurrent", [&](const sol::table& Table) -> float {
auto End = std::chrono::high_resolution_clock::now();
auto Start = Table.get<std::chrono::high_resolution_clock::time_point>("__StartTime");
return std::chrono::duration_cast<std::chrono::microseconds>(End - Start).count() / 1000000.0f;
});
Result.set_function("Start", [&](sol::table Table) {
Table["__StartTime"] = std::chrono::high_resolution_clock::now();
});
return Result;
});
MPTable.set_function("GetOSName", &LuaAPI::MP::GetOSName);
MPTable.set_function("GetServerVersion", &LuaAPI::MP::GetServerVersion);
MPTable.set_function("RegisterEvent", [this](const std::string& EventName, const std::string& FunctionName) {
RegisterEvent(EventName, FunctionName);
});
MPTable.set_function("TriggerGlobalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> sol::table {
return Lua_TriggerGlobalEvent(EventName, EventArgs);
});
MPTable.set_function("TriggerLocalEvent", [&](const std::string& EventName, sol::variadic_args EventArgs) -> sol::table {
return Lua_TriggerLocalEvent(EventName, EventArgs);
});
MPTable.set_function("TriggerClientEvent", &LuaAPI::MP::TriggerClientEvent);
MPTable.set_function("TriggerClientEventJson", &LuaAPI::MP::TriggerClientEventJson);
MPTable.set_function("GetPlayerCount", &LuaAPI::MP::GetPlayerCount);
MPTable.set_function("IsPlayerConnected", &LuaAPI::MP::IsPlayerConnected);
MPTable.set_function("GetPlayerIDByName", [&](const std::string& Name) -> int {
return Lua_GetPlayerIDByName(Name);
});
MPTable.set_function("GetPlayerName", [&](int ID) -> std::string {
return Lua_GetPlayerName(ID);
});
MPTable.set_function("RemoveVehicle", &LuaAPI::MP::RemoveVehicle);
MPTable.set_function("GetPlayerVehicles", [&](int ID) -> sol::table {
return Lua_GetPlayerVehicles(ID);
});
MPTable.set_function("GetPositionRaw", [&](int PID, int VID) -> std::pair<sol::table, std::string> {
return Lua_GetPositionRaw(PID, VID);
});
MPTable.set_function("SendChatMessage", &LuaAPI::MP::SendChatMessage);
MPTable.set_function("GetPlayers", [&]() -> sol::table {
return Lua_GetPlayers();
});
MPTable.set_function("IsPlayerGuest", &LuaAPI::MP::IsPlayerGuest);
MPTable.set_function("DropPlayer", &LuaAPI::MP::DropPlayer);
MPTable.set_function("GetStateMemoryUsage", [&]() -> size_t {
return mStateView.memory_used();
});
MPTable.set_function("GetLuaMemoryUsage", [&]() -> size_t {
return mEngine->CalculateMemoryUsage();
});
MPTable.set_function("GetPlayerIdentifiers", [&](int ID) -> sol::table {
return Lua_GetPlayerIdentifiers(ID);
});
MPTable.set_function("Sleep", &LuaAPI::MP::Sleep);
// const std::string& EventName, size_t IntervalMS, int strategy
MPTable.set_function("CreateEventTimer", [&](sol::variadic_args Args) {
if (Args.size() < 2 || Args.size() > 3) {
beammp_lua_error("CreateEventTimer expects 2 or 3 arguments.");
}
if (Args.get_type(0) != sol::type::string) {
beammp_lua_error("CreateEventTimer expects 1st argument to be a string");
}
if (Args.get_type(1) != sol::type::number) {
beammp_lua_error("CreateEventTimer expects 2nd argument to be a number");
}
if (Args.size() == 3 && Args.get_type(2) != sol::type::number) {
beammp_lua_error("CreateEventTimer expects 3rd argument to be a number (MP.CallStrategy)");
}
auto EventName = Args.get<std::string>(0);
auto IntervalMS = Args.get<size_t>(1);
CallStrategy Strategy = Args.size() > 2 ? Args.get<CallStrategy>(2) : CallStrategy::BestEffort;
if (IntervalMS < 25) {
beammp_warn("Timer for \"" + EventName + "\" on \"" + mStateId + "\" is set to trigger at <25ms, which is likely too fast and won't cancel properly.");
}
mEngine->CreateEventTimer(EventName, mStateId, IntervalMS, Strategy);
});
MPTable.set_function("CancelEventTimer", [&](const std::string& EventName) {
mEngine->CancelEventTimers(EventName, mStateId);
});
MPTable.set_function("Set", &LuaAPI::MP::Set);
auto UtilTable = StateView.create_named_table("Util");
UtilTable.set_function("LogDebug", [this](sol::variadic_args args) {
std::string ToPrint = "";
for (const auto& arg : args) {
ToPrint += LuaAPI::LuaToString(static_cast<const sol::object>(arg));
ToPrint += "\t";
}
if (Application::Settings.getAsBool(Settings::Key::General_Debug)) {
beammp_lua_log("DEBUG", mStateId, ToPrint);
}
});
UtilTable.set_function("LogInfo", [this](sol::variadic_args args) {
std::string ToPrint = "";
for (const auto& arg : args) {
ToPrint += LuaAPI::LuaToString(static_cast<const sol::object>(arg));
ToPrint += "\t";
}
beammp_lua_log("INFO", mStateId, ToPrint);
});
UtilTable.set_function("LogWarn", [this](sol::variadic_args args) {
std::string ToPrint = "";
for (const auto& arg : args) {
ToPrint += LuaAPI::LuaToString(static_cast<const sol::object>(arg));
ToPrint += "\t";
}
beammp_lua_log("WARN", mStateId, ToPrint);
});
UtilTable.set_function("LogError", [this](sol::variadic_args args) {
std::string ToPrint = "";
for (const auto& arg : args) {
ToPrint += LuaAPI::LuaToString(static_cast<const sol::object>(arg));
ToPrint += "\t";
}
beammp_lua_log("ERROR", mStateId, ToPrint);
});
UtilTable.set_function("JsonEncode", &LuaAPI::MP::JsonEncode);
UtilTable.set_function("JsonDecode", [this](const std::string& str) {
return Lua_JsonDecode(str);
});
UtilTable.set_function("JsonDiff", &LuaAPI::MP::JsonDiff);
UtilTable.set_function("JsonFlatten", &LuaAPI::MP::JsonFlatten);
UtilTable.set_function("JsonUnflatten", &LuaAPI::MP::JsonUnflatten);
UtilTable.set_function("JsonPrettify", &LuaAPI::MP::JsonPrettify);
UtilTable.set_function("JsonMinify", &LuaAPI::MP::JsonMinify);
UtilTable.set_function("Random", [this] {
return mUniformRealDistribution01(mMersenneTwister);
});
UtilTable.set_function("RandomRange", [this](double min, double max) -> double {
return std::uniform_real_distribution(min, max)(mMersenneTwister);
});
UtilTable.set_function("RandomIntRange", [this](int64_t min, int64_t max) -> int64_t {
return std::uniform_int_distribution(min, max)(mMersenneTwister);
});
UtilTable.set_function("DebugExecutionTime", [this]() -> sol::table {
sol::state_view StateView(mState);
sol::table Result = StateView.create_table();
auto stats = mProfile.all_stats();
for (const auto& [name, stat] : stats) {
Result[name] = StateView.create_table();
Result[name]["mean"] = stat.mean;
Result[name]["stdev"] = stat.stdev;
Result[name]["min"] = stat.min;
Result[name]["max"] = stat.max;
Result[name]["n"] = stat.n;
}
return Result;
});
UtilTable.set_function("DebugStartProfile", [this](const std::string& name) {
mProfileStarts[name] = prof::now();
});
UtilTable.set_function("DebugStopProfile", [this](const std::string& name) {
if (!mProfileStarts.contains(name)) {
beammp_lua_errorf("DebugStopProfile('{}') failed, because a profile for '{}' wasn't started", name, name);
return;
}
mProfile.add_sample(name, prof::duration(mProfileStarts.at(name), prof::now()));
});
auto HttpTable = StateView.create_named_table("Http");
HttpTable.set_function("CreateConnection", [this](const std::string& host, uint16_t port) {
return Lua_HttpCreateConnection(host, port);
});
MPTable.create_named("Settings",
"Debug", 0,
"Private", 1,
"MaxCars", 2,
"MaxPlayers", 3,
"Map", 4,
"Name", 5,
"Description", 6);
MPTable.create_named("CallStrategy",
"BestEffort", CallStrategy::BestEffort,
"Precise", CallStrategy::Precise);
auto FSTable = StateView.create_named_table("FS");
FSTable.set_function("CreateDirectory", &LuaAPI::FS::CreateDirectory);
FSTable.set_function("Exists", &LuaAPI::FS::Exists);
FSTable.set_function("Remove", &LuaAPI::FS::Remove);
FSTable.set_function("Rename", &LuaAPI::FS::Rename);
FSTable.set_function("Copy", &LuaAPI::FS::Copy);