-
Notifications
You must be signed in to change notification settings - Fork 4
/
DejaVu.cpp
1093 lines (920 loc) · 33.7 KB
/
DejaVu.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
#include "pch.h"
#include "DejaVu.h"
/**
* TODO
* - Add option to show total record across all playlists
* - Create 2-way cvar binding
* - IMGUI stuff
*/
INITIALIZE_EASYLOGGINGPP
BAKKESMOD_PLUGIN(DejaVu, "Deja Vu", PluginVersion, 0)
// to_string overloads for cvars
namespace std {
inline string to_string(const std::string& str) {
return str;
}
string to_string(const LinearColor& color) {
char buf[49];
sprintf(buf, "(%f, %f, %f, %f)", color.R, color.G, color.B, color.A);
return buf;
}
string to_string(const Record& record) {
return to_string(record.wins) + ":" + to_string(record.losses);
}
string to_string(const PlaylistID& playlist) {
return to_string(static_cast<int>(playlist));
}
}
void SetupLogger(std::string logPath, bool enabled)
{
el::Configurations defaultConf;
defaultConf.setToDefault();
defaultConf.setGlobally(el::ConfigurationType::Filename, logPath);
defaultConf.setGlobally(el::ConfigurationType::Format, "%datetime %level [%fbase:%line] %msg");
defaultConf.setGlobally(el::ConfigurationType::Enabled, enabled ? "true" : "false");
el::Loggers::reconfigureLogger("default", defaultConf);
}
void DejaVu::HookAndLogEvent(std::string eventName)
{
this->gameWrapper->HookEvent(eventName, std::bind(&DejaVu::LogChatbox, this, std::placeholders::_1));
this->gameWrapper->HookEvent(eventName, std::bind(&DejaVu::Log, this, std::placeholders::_1));
}
void DejaVu::CleanUpJson()
{
for (auto player : this->data["players"].items())
{
json::value_type playerData = player.value();
for (auto playlistData : playerData["playlistData"].items())
{
bool containsRecords = playlistData.value().contains("records");
bool recordsIsNull = containsRecords && playlistData.value()["records"].is_null();
if (!containsRecords || recordsIsNull)
this->data["players"][player.key()]["playlistData"].erase(playlistData.key());
}
}
WriteData();
}
void DejaVu::onLoad()
{
this->isAlreadyAddedToStats = false;
// At end of match in unranked when people leave and get replaced by bots the event fires and for some reason IsInOnlineGame turns back on
// Check 1v1. Player added event didn't fire after joining last
// Add debug
this->mmrWrapper = this->gameWrapper->GetMMRWrapper();
this->dataDir = this->gameWrapper->GetDataFolder().append("dejavu");
this->mainPath = std::filesystem::path(dataDir).append(this->mainFile);
this->tmpPath = std::filesystem::path(dataDir).append(this->tmpFile);
this->bakPath = std::filesystem::path(dataDir).append(this->bakFile);
this->logPath = std::filesystem::path(dataDir).append(this->logFile);
this->cvarManager->registerNotifier("dejavu_reload", [this](const std::vector<std::string>& commands) {
LoadData();
}, "Reloads the json data from file", PERMISSION_ALL);
this->cvarManager->registerNotifier("dejavu_track_current", [this](const std::vector<std::string>& commands) {
HandlePlayerAdded("dejavu_track_current");
}, "Tracks current lobby", PERMISSION_ONLINE);
this->cvarManager->registerNotifier("dejavu_launch_quick_note", [this](const std::vector<std::string>& commands) {
#if !DEV
if (IsInRealGame())
#endif !DEV
LaunchQuickNoteModal();
}, "Launches the quick note modal", PERMISSION_ONLINE);
#if DEV
this->cvarManager->registerNotifier("dejavu_test", [this](const std::vector<std::string>& commands) {
this->gameWrapper->SetTimeout([this](GameWrapper* gameWrapper) {
Log("test after 5");
}, 5);
}, "test", PERMISSION_ALL);
this->cvarManager->registerNotifier("dejavu_cleanup", [this](const std::vector<std::string>& commands) {
CleanUpJson();
}, "Cleans up the json", PERMISSION_ALL);
this->cvarManager->registerNotifier("dejavu_dump_list", [this](const std::vector<std::string>& commands) {
if (this->matchesMetLists.size() == 0)
{
this->cvarManager->log("No entries in list");
return;
}
for (auto& match : this->matchesMetLists)
{
std::string guid = match.first;
this->cvarManager->log("For match GUID:" + guid);
auto& set = match.second;
for (auto& playerID : set)
{
this->cvarManager->log(" " + playerID);
}
}
}, "Dumps met list", PERMISSION_ALL);
this->cvarManager->registerNotifier("dejavu_test_cvar_binding", [this](const std::vector<std::string>& commands) {
this->enabledDebug = !*this->enabledDebug;
}, "Tests cvar binding", PERMISSION_ALL);
#endif DEV
#pragma region register cvars
this->enabled.Register(this->cvarManager);
this->trackOpponents.Register(this->cvarManager);
this->trackTeammates.Register(this->cvarManager);
this->trackGrouped.Register(this->cvarManager);
this->showMetCount.Register(this->cvarManager);
this->showRecord.Register(this->cvarManager);
this->showAllPlaylistsRecord.Register(this->cvarManager);
auto visualCVar = this->enabledVisuals.Register(this->cvarManager);
visualCVar.addOnValueChanged([this](std::string oldValue, CVarWrapper cvar) {
if (!cvar.getBoolValue())
this->enabledDebug = false;
});
this->toggleWithScoreboard.Register(this->cvarManager);
this->showNotes.Register(this->cvarManager);
auto debugCVar = this->enabledDebug.Register(this->cvarManager);
debugCVar.addOnValueChanged([this](std::string oldValue, CVarWrapper cvar) {
bool val = cvar.getBoolValue();
if (this->gameWrapper->IsInOnlineGame()) {
if (val)
cvar.setValue(false);
return;
}
this->blueTeamRenderData.clear();
this->orangeTeamRenderData.clear();
if (val) {
this->blueTeamRenderData.push_back({ "0", "Blue Player 1", 5, { 5, 5 }, { 5, 5 }, "This guy was a great team player" });
this->blueTeamRenderData.push_back({ "0", "Blue Player 2", 15, { 15, 15 }, { 15, 15 }, "Quick chat spammer" });
this->blueTeamRenderData.push_back({ "0", "Blue Player 3 with a loooonngggg name", 9999, { 999, 999 }, { 9999, 9999 } });
this->orangeTeamRenderData.push_back({ "0", "Orange Player 1", 5, { 5, 5 }, { 55, 55 } });
this->orangeTeamRenderData.push_back({ "0", "Orange Player 2", 15, { 15, 15 }, { 150, 150 }, "Left early" });
}
});
#if DEV
this->enabledDebug = true;
#endif DEV
this->scale.Register(this->cvarManager);
this->alpha.Register(this->cvarManager);
this->xPos.Register(this->cvarManager);
this->yPos.Register(this->cvarManager);
this->width.Register(this->cvarManager);
#pragma warning(suppress : 4996)
this->textColorR.Register(this->cvarManager);
#pragma warning(suppress : 4996)
this->textColorG.Register(this->cvarManager);
#pragma warning(suppress : 4996)
this->textColorB.Register(this->cvarManager);
this->textColor.Register(this->cvarManager);
this->enabledBorders.Register(this->cvarManager);
this->borderColor.Register(this->cvarManager);
this->enabledBackground.Register(this->cvarManager);
#pragma warning(suppress : 4996)
this->backgroundColorR.Register(this->cvarManager);
#pragma warning(suppress : 4996)
this->backgroundColorG.Register(this->cvarManager);
#pragma warning(suppress : 4996)
this->backgroundColorB.Register(this->cvarManager);
this->backgroundColor.Register(this->cvarManager);
this->hasUpgradedColors.Register(this->cvarManager);
auto logCVar = this->enabledLog.Register(this->cvarManager);
logCVar.addOnValueChanged([this](std::string oldValue, CVarWrapper cvar) {
bool val = cvar.getBoolValue();
SetupLogger(this->logPath.string(), val);
});
this->mainGUIKeybind.Register(this->cvarManager).addOnValueChanged([this](std::string oldValue, CVarWrapper cvar) {
std::string newBind = cvar.getStringValue();
if (!oldValue.empty() && oldValue != "None")
this->cvarManager->executeCommand("unbind " + oldValue, false);
if (newBind != "None")
this->cvarManager->setBind(newBind, "togglemenu dejavu");
});
this->quickNoteKeybind.Register(this->cvarManager).addOnValueChanged([this](std::string oldValue, CVarWrapper cvar) {
std::string newBind = cvar.getStringValue();
if (!oldValue.empty() && oldValue != "None")
this->cvarManager->executeCommand("unbind " + oldValue, false);
if (newBind != "None")
this->cvarManager->setBind(newBind, "dejavu_launch_quick_note");
});
#pragma endregion register cvars
// I guess this doesn't fire for "you"
this->gameWrapper->HookEvent("Function TAGame.GameEvent_TA.EventPlayerAdded", std::bind(&DejaVu::HandlePlayerAdded, this, std::placeholders::_1));
this->gameWrapper->HookEvent("Function GameEvent_TA.Countdown.BeginState", std::bind(&DejaVu::HandlePlayerAdded, this, std::placeholders::_1));
this->gameWrapper->HookEvent("Function TAGame.Team_TA.EventScoreUpdated", std::bind(&DejaVu::HandlePlayerAdded, this, std::placeholders::_1));
// TODO: Look for event like "spawning" so that when you join an in progress match it will gather data
this->gameWrapper->HookEvent("Function TAGame.GameEvent_TA.EventPlayerRemoved", std::bind(&DejaVu::HandlePlayerRemoved, this, std::placeholders::_1));
// Don't think this one ever actually works
this->gameWrapper->HookEvent("Function TAGame.GameEvent_Soccar_TA.InitGame", bind(&DejaVu::HandleGameStart, this, std::placeholders::_1));
// Fires when joining a game
this->gameWrapper->HookEvent("Function OnlineGameJoinGame_X.JoiningBase.IsJoiningGame", std::bind(&DejaVu::HandleGameStart, this, std::placeholders::_1));
// Fires when the match is first initialized
this->gameWrapper->HookEvent("Function TAGame.GameEvent_Soccar_TA.OnAllTeamsCreated", std::bind(&DejaVu::HandleGameStart, this, std::placeholders::_1));
this->gameWrapper->HookEvent("Function TAGame.GameEvent_Soccar_TA.OnMatchWinnerSet", std::bind(&DejaVu::HandleWinnerSet, this, std::placeholders::_1));
this->gameWrapper->HookEvent("Function TAGame.GameEvent_TA.OnCanVoteForfeitChanged", std::bind(&DejaVu::HandleForfeitChanged, this, std::placeholders::_1));
this->gameWrapper->HookEvent("Function TAGame.GameEvent_Soccar_TA.OnGameTimeUpdated", std::bind(&DejaVu::HandleGameTimeUpdate, this, std::placeholders::_1));
this->gameWrapper->HookEvent("Function TAGame.GFxShell_TA.LeaveMatch", std::bind(&DejaVu::HandleGameLeave, this, std::placeholders::_1));
// Function TAGame.GFxHUD_TA.HandlePenaltyChanged
this->gameWrapper->HookEvent("Function TAGame.GFxData_GameEvent_TA.OnOpenScoreboard", std::bind(&DejaVu::OpenScoreboard, this, std::placeholders::_1));
this->gameWrapper->HookEvent("Function TAGame.GFxData_GameEvent_TA.OnCloseScoreboard", std::bind(&DejaVu::CloseScoreboard, this, std::placeholders::_1));
this->gameWrapper->UnregisterDrawables();
this->gameWrapper->RegisterDrawable(bind(&DejaVu::RenderDrawable, this, std::placeholders::_1));
/*
HookEventWithCaller<ServerWrapper>("FUNCTION", bind(&CLASSNAME::FUNCTIONNAME, this, placeholders::_1, 2, 3);
void CLASSNAME::FUNCTIONNAME(ServerWrapper caller, void* params, string funcName)
{
bool returnVal = (bool)params;
}
*/
//std::string eventsToLog[] = {
//"Function TAGame.GameEvent_Soccar_TA.EndGame",
//"Function TAGame.GameEvent_Soccar_TA.EndRound",
//"Function TAGame.GameEvent_Soccar_TA.EventMatchEnded",
//"Function TAGame.GameEvent_Soccar_TA.EventGameEnded",
//"Function TAGame.GameEvent_Soccar_TA.EventGameWinnerSet",
//"Function TAGame.GameEvent_Soccar_TA.EventMatchWinnerSet",
//"Function TAGame.GameEvent_Soccar_TA.HasWinner",
//"Function TAGame.GameEvent_Soccar_TA.EventEndGameCountDown",
//"Function TAGame.GameEvent_Soccar_TA.EventGameTimeUpdated",
//"Function TAGame.GameEvent_Soccar_TA.Finished.BeginState",
//"Function TAGame.GameEvent_Soccar_TA.Finished.OnFinished",
//"Function TAGame.GameEvent_Soccar_TA.FinishEvent",
//"Function TAGame.GameEvent_Soccar_TA.HasWinner",
//"Function TAGame.GameEvent_Soccar_TA.OnGameWinnerSet",
//"Function TAGame.GameEvent_Soccar_TA.SetMatchWinner",
//"Function TAGame.GameEvent_Soccar_TA.SubmitMatch",
//"Function TAGame.GameEvent_Soccar_TA.SubmitMatchComplete",
//"Function TAGame.GameEvent_Soccar_TA.WaitForEndRound",
//"Function TAGame.GameEvent_Soccar_TA.EventActiveRoundChanged",
//"Function TAGame.GameEvent_Soccar_TA.GetWinningTeam",
//"Function TAGame.GameEvent_TA.EventGameStateChanged",
//"Function TAGame.GameEvent_TA.Finished.EndState",
//"Function TAGame.GameEvent_TA.Finished.BeginState",
//"Function TAGame.GameEvent_Soccar_TA.Destroyed",
//"Function TAGame.GameEvent_TA.IsFinished",
//};
//for (std::string eventName : eventsToLog)
//{
// HookAndLogEvent(eventName);
//}
/*
Goal Scored event: "Function TAGame.Team_TA.EventScoreUpdated"
Game Start event: "Function TAGame.GameEvent_Soccar_TA.InitGame"
Game End event: "Function TAGame.GameEvent_Soccar_TA.EventMatchEnded"
Function TAGame.GameEvent_Soccar_TA.Destroyed
Function TAGame.GameEvent_Soccar_TA.EventMatchEnded
Function GameEvent_TA.Countdown.BeginState
Function TAGame.GameEvent_Soccar_TA.InitField
Function TAGame.GameEvent_Soccar_TA.InitGame
Function TAGame.GameEvent_Soccar_TA.InitGame
Function TAGame.GameEvent_Soccar_TA.EventGameWinnerSet
Function TAGame.GameEvent_Soccar_TA.EventMatchWinnerSet
*/
LoadData();
GenerateSettingsFile();
this->gameWrapper->SetTimeout([this](GameWrapper* gameWrapper) {
if (!*this->hasUpgradedColors)
{
LOG(INFO) << "Upgrading colors...";
#pragma warning(suppress : 4996)
this->textColor = LinearColor{ (float)*this->textColorR, (float)*this->textColorG, (float)*this->textColorB, 0xff };
#pragma warning(suppress : 4996)
this->backgroundColor = LinearColor{ (float)*this->backgroundColorR, (float)*this->backgroundColorG, (float)*this->backgroundColorB, 0xff };
this->hasUpgradedColors = true;
this->cvarManager->executeCommand("writeconfig");
}
LOG(INFO) << "---DEJAVU LOADED---";
}, 0.001f);
#if DEV
this->cvarManager->executeCommand("exec tmp.cfg");
#endif
}
void DejaVu::onUnload()
{
LOG(INFO) << "---DEJAVU UNLOADED---";
WriteData();
#if DEV
this->cvarManager->backupCfg("./bakkesmod/cfg/tmp.cfg");
#endif
if (this->isWindowOpen)
this->cvarManager->executeCommand("togglemenu " + GetMenuName());
}
void DejaVu::OpenScoreboard(std::string eventName)
{
this->isScoreboardOpen = true;
}
void DejaVu::CloseScoreboard(std::string eventName)
{
this->isScoreboardOpen = false;
}
void DejaVu::Log(std::string msg)
{
this->cvarManager->log(msg);
}
void DejaVu::LogError(std::string msg)
{
this->cvarManager->log("ERROR: " + msg);
}
void DejaVu::LogChatbox(std::string msg)
{
this->gameWrapper->LogToChatbox(msg);
LOG(INFO) << msg;
}
void DejaVu::LoadData()
{
// Upgrade old file path
if (std::filesystem::exists(this->mainFile)) {
Log("Upgrading old file path");
std::filesystem::create_directories(this->dataDir);
std::filesystem::rename(this->mainFile, this->mainPath);
std::filesystem::rename(this->bakFile, this->bakPath);
}
std::ifstream in(this->mainPath);
if (in.fail()) {
LogError("Failed to open file");
LogError(strerror(errno));
this->data["players"] = json::object();
WriteData();
in.open(this->mainPath);
}
try {
in >> this->data;
}
catch (const nlohmann::detail::exception& e) {
in.close();
LogError("Failed to parse json");
LogError(e.what());
}
if (!this->data.contains("players")) {
Log("Data doesn't contain players");
this->data["players"] = json::object();
}
Log("Successfully loaded existing data");
in.close();
// Fix any nulls that shouldn't be
for (auto& player : this->data["players"].items())
{
if (player.value().count("metCount") && player.value()["metCount"].is_null())
player.value()["metCount"] = 1;
if (player.value().count("name") && player.value()["name"].is_null())
player.value()["name"] = player.key();
}
WriteData();
}
void DejaVu::WriteData()
{
LOG(INFO) << "WriteData";
std::filesystem::create_directories(this->dataDir);
std::ofstream out(this->tmpPath);
try {
out << this->data.dump(4, ' ', false, json::error_handler_t::replace) << std::endl;
out.close();
std::error_code err;
std::filesystem::remove(this->bakPath, err);
if (std::filesystem::exists(this->mainPath)) {
std::filesystem::rename(this->mainPath, this->bakPath, err);
if (err.value() != 0) {
LogError("Could not backup player counter");
LogError(err.message());
return;
}
}
std::filesystem::rename(this->tmpPath, this->mainPath, err);
if (err.value() != 0) {
LogError("Could not move temp file to main");
LogError(err.message());
std::filesystem::rename(this->bakPath, this->mainPath, err);
return;
}
}
catch (const nlohmann::detail::exception& e) {
LogError("failed to serialize json");
LogError(e.what());
}
catch (...) {
LogError("failed to serialize json (unknown)");
}
}
std::optional<std::string> DejaVu::GetMatchGUID()
{
ServerWrapper server = GetCurrentServer();
if (server.IsNull())
return std::nullopt;
if (server.IsPlayingPrivate())
return std::nullopt;
const std::string& curMatchGUID = server.GetMatchGUID();
if (curMatchGUID == "No worldInfo" || curMatchGUID.length() == 0)
return std::nullopt;
return curMatchGUID;
}
ServerWrapper DejaVu::GetCurrentServer()
{
return this->gameWrapper->GetCurrentGameState();
}
PriWrapper DejaVu::GetLocalPlayerPRI()
{
auto server = GetCurrentServer();
if (server.IsNull())
return NULL;
auto player = server.GetLocalPrimaryPlayer();
if (player.IsNull())
return NULL;
return player.GetPRI();
}
void DejaVu::HandlePlayerAdded(std::string eventName)
{
if (!IsInRealGame())
return;
LOG(INFO) << "HandlePlayerAdded: " << eventName;
if (this->gameIsOver)
return;
ServerWrapper server = GetCurrentServer();
LOG(INFO) << "server is null: " << (server.IsNull() ? "true" : "false");
if (server.IsNull())
return;
if (server.IsPlayingPrivate())
return;
auto matchGUID = GetMatchGUID();
if (!matchGUID.has_value())
return;
LOG(INFO) << "Match GUID: " << matchGUID.value();
if (!this->curMatchGUID.has_value())
this->curMatchGUID = matchGUID;
MMRWrapper mw = this->gameWrapper->GetMMRWrapper();
ArrayWrapper<PriWrapper> pris = server.GetPRIs();
int len = pris.Count();
bool needsSave = false;
for (int i = 0; i < len; i++)
{
PriWrapper player = pris.Get(i);
bool isSpectator = player.GetbIsSpectator();
if (isSpectator)
{
LOG(INFO) << "player is spectator. skipping";
continue;
}
PriWrapper localPlayer = GetLocalPlayerPRI();
if (!localPlayer.IsNull())
{
bool isTeammate = player.GetTeamNum() == localPlayer.GetTeamNum();
std::string myLeaderID = localPlayer.GetPartyLeaderID().str();
bool isInMyGroup = myLeaderID != "0" && player.GetPartyLeaderID().str() == myLeaderID;
if (isTeammate && !*this->trackTeammates)
{
continue;
}
if (!isTeammate && !*this->trackOpponents)
{
continue;
}
if (isInMyGroup && !*this->trackGrouped)
{
continue;
}
UniqueIDWrapper uniqueID = player.GetUniqueIdWrapper();
std::string uniqueIDStr = uniqueID.str();
UniqueIDWrapper localUniqueID = localPlayer.GetUniqueIdWrapper();
std::string localUniqueIDStr = localUniqueID.str();
// Skip self
if (uniqueIDStr == localUniqueIDStr) {
continue;
//} else
//{
//this->gameWrapper->LogToChatbox(uniqueID.str() + " != " + localUniqueID.str());
}
std::string playerName = player.GetPlayerName().ToString();
LOG(INFO) << "uniqueID: " << uniqueIDStr << " name: " << playerName;
// Bots
if (uniqueIDStr == "0")
{
playerName = "[BOT]";
continue;
}
int curPlaylist = mw.GetCurrentPlaylist();
//GetAndSetMetMMR(localUniqueID, curPlaylist, uniqueID);
//GetAndSetMetMMR(uniqueID, curPlaylist, uniqueID);
// Only do met count logic if we haven't yet
if (this->matchesMetLists[this->curMatchGUID.value()].count(uniqueIDStr) == 0)
{
LOG(INFO) << "Haven't processed yet: " << playerName;
this->matchesMetLists[this->curMatchGUID.value()].emplace(uniqueIDStr);
int metCount = 0;
if (!this->data["players"].contains(uniqueIDStr))
{
LOG(INFO) << "Haven't met yet: " << playerName;
metCount = 1;
std::time_t now = std::time(0);
auto dateTime = std::ctime(&now);
this->data["players"][uniqueIDStr] = json({
{ "metCount", metCount },
{ "name", playerName },
{ "timeMet", dateTime },
});
} else
{
LOG(INFO) << "Have met before: " << playerName;
std::time_t now = std::time(0);
auto dateTime = std::ctime(&now);
json& playerData = this->data["players"][uniqueIDStr];
try
{
metCount = playerData["metCount"].get<int>();
metCount++;
}
catch (const std::exception& e)
{
this->gameWrapper->Toast("DejaVu Error", "Check console/log for details");
this->cvarManager->log(e.what());
LOG(INFO) << e.what();
}
playerData["metCount"] = metCount;
playerData["name"] = playerName;
playerData["updatedAt"] = dateTime;
}
needsSave = true;
}
AddPlayerToRenderData(player);
}
else {
LOG(INFO) << "localPlayer is null";
}
}
if (needsSave)
WriteData();
}
void DejaVu::AddPlayerToRenderData(PriWrapper player)
{
auto uniqueIDStr = player.GetUniqueIdWrapper().str();
// If we've already added him to the list, return
if (this->currentMatchPRIs.count(uniqueIDStr) != 0)
return;
auto server = GetCurrentServer();
auto myTeamNum = server.GetLocalPrimaryPlayer().GetPRI().GetTeamNum();
auto theirTeamNum = player.GetTeamNum();
if (myTeamNum == TEAM_NOT_SET || theirTeamNum == TEAM_NOT_SET)
{
LOG(INFO) << "No team set for " << player.GetPlayerName().ToString() << ", retrying in 5 seconds: " << (int)myTeamNum << ":" << (int)theirTeamNum;
// No team set. Try again in a couple seconds
this->gameWrapper->SetTimeout([this](GameWrapper* gameWrapper) {
HandlePlayerAdded("NoTeamSetRetry");
}, 5);
return;
}
// Team set, so we all good
this->currentMatchPRIs.emplace(uniqueIDStr, player);
LOG(INFO) << "adding player: " << player.GetPlayerName().ToString();
int metCount = 0;
try
{
if (this->data["players"].count(uniqueIDStr) &&
this->data["players"][uniqueIDStr].count("metCount") &&
!this->data["players"][uniqueIDStr]["metCount"].is_null())
metCount = this->data["players"][uniqueIDStr]["metCount"].get<int>();
}
catch (const std::exception& e)
{
this->gameWrapper->Toast("DejaVu Error", "Check console/log for details");
this->cvarManager->log(e.what());
LOG(INFO) << e.what();
}
bool sameTeam = theirTeamNum == myTeamNum;
Record record = GetRecord(uniqueIDStr, static_cast<PlaylistID>(server.GetPlaylist().GetPlaylistId()), sameTeam ? Side::Same : Side::Other);
Record allRecord = GetRecord(uniqueIDStr, PlaylistID::ANY, sameTeam ? Side::Same : Side::Other);
LOG(INFO) << "player team num: " << std::to_string(theirTeamNum);
std::string playerName = player.GetPlayerName().ToString();
std::string playerNote = this->data["players"][uniqueIDStr].value("note", "");
if (theirTeamNum == TEAM_BLUE)
this->blueTeamRenderData.push_back({ uniqueIDStr, playerName, metCount, record, allRecord, playerNote });
else
this->orangeTeamRenderData.push_back({ uniqueIDStr, playerName, metCount, record, allRecord, playerNote });
}
void DejaVu::RemovePlayerFromRenderData(PriWrapper player)
{
if (player.IsNull())
return;
if (!player.GetPlayerName().IsNull())
LOG(INFO) << "Removing player: " << player.GetPlayerName().ToString();
std::string steamID = player.GetUniqueIdWrapper().str();
LOG(INFO) << "Player SteamID: " << steamID;
this->blueTeamRenderData.erase(std::remove_if(this->blueTeamRenderData.begin(), this->blueTeamRenderData.end(), [steamID](const RenderData& data) {
return data.id == steamID;
}), this->blueTeamRenderData.end());
this->orangeTeamRenderData.erase(std::remove_if(this->orangeTeamRenderData.begin(), this->orangeTeamRenderData.end(), [steamID](const RenderData& data) {
return data.id == steamID;
}), this->orangeTeamRenderData.end());
}
void DejaVu::HandlePlayerRemoved(std::string eventName)
{
if (!IsInRealGame())
return;
LOG(INFO) << eventName;
auto server = GetCurrentServer();
auto pris = server.GetPRIs();
for (auto it = this->currentMatchPRIs.begin(); it != this->currentMatchPRIs.end(); )
{
std::string playerID = it->first;
auto player = it->second;
bool isInGame = false;
for (int i = 0; i < pris.Count(); i++)
{
auto playerInGame = pris.Get(i);
std::string playerInGameID = playerInGame.GetUniqueIdWrapper().str();
if (playerID == playerInGameID)
isInGame = true;
}
if (!isInGame)
{
if (!player.IsNull() && !player.GetPlayerName().IsNull())
LOG(INFO) << "Player is no longer in game: " << player.GetPlayerName().ToString();
it = this->currentMatchPRIs.erase(it);
RemovePlayerFromRenderData(player);
}
else
++it;
}
}
void DejaVu::HandleGameStart(std::string eventName)
{
LOG(INFO) << eventName;
Reset();
this->cvarManager->getCvar("cl_dejavu_debug").setValue(false);
this->curMatchGUID = GetMatchGUID();
this->isAlreadyAddedToStats = false;
}
void DejaVu::HandleWinnerSet(std::string eventName)
{
LOG(INFO) << eventName;
GameOver();
}
void DejaVu::HandleForfeitChanged(std::string eventName)
{
LOG(INFO) << eventName;
ServerWrapper server = this->gameWrapper->GetCurrentGameState();
if (server.IsNull())
return;
if (server.GetbCanVoteToForfeit())
return;
// that means some team forfeited the game
GameOver();
}
void DejaVu::HandleGameTimeUpdate(std::string eventName)
{
LOG(INFO) << eventName;
ServerWrapper server = this->gameWrapper->GetCurrentGameState();
if (server.IsNull())
return;
if (!server.IsFinished())
return;
float time = server.GetGameTimeRemaining();
// Overtime is over or 0 goal is scored meaning game is finished
if (time <= 0) {
GameOver();
}
}
void DejaVu::GameOver()
{
if (!this->isAlreadyAddedToStats) {
SetRecord();
WriteData();
Reset();
this->gameIsOver = true;
this->isAlreadyAddedToStats = true;
}
}
void DejaVu::HandleGameLeave(std::string eventName)
{
LOG(INFO) << eventName;
WriteData();
Reset();
this->curMatchGUID = std::nullopt;
this->isAlreadyAddedToStats = false;
}
void DejaVu::Reset()
{
this->gameIsOver = false;
this->currentMatchPRIs.clear();
// Maybe move this to HandleGameLeave but probably don't need to worry about it
//this->matchesMetLists.clear();
this->blueTeamRenderData.clear();
this->orangeTeamRenderData.clear();
}
void DejaVu::GetAndSetMetMMR(SteamID steamID, int playlist, SteamID idToSet)
{
this->gameWrapper->SetTimeout([this, steamID, playlist, idToSet](GameWrapper* gameWrapper) {
float mmrValue = this->mmrWrapper.GetPlayerMMR(steamID, playlist);
// For some reason getting a lot of these values 100.01998901367188
if (mmrValue < 0 && !this->mmrWrapper.IsSynced(steamID, playlist)) {
Log("Not synced yet: " + std::to_string(mmrValue) + "|" + std::to_string(this->mmrWrapper.IsSyncing(steamID)));
GetAndSetMetMMR(steamID, playlist, idToSet);
return;
}
json& player = this->data["players"][std::to_string(idToSet.ID)];
std::string keyToSet = (steamID.ID == idToSet.ID) ? "otherMetMMR" : "playerMetMMR";
if (!player.contains(keyToSet))
{
player[keyToSet] = json::object();
}
player[keyToSet][std::to_string(playlist)] = mmrValue;
WriteData();
}, 5);
}
Record DejaVu::GetRecord(UniqueIDWrapper uniqueID, PlaylistID playlist, Side side)
{
return GetRecord(uniqueID.str(), playlist, side);
}
Record DejaVu::GetRecord(std::string uniqueID, PlaylistID playlist, Side side)
{
std::string sideStr;
if (side == Side::Same)
sideStr = "with";
else if (side == Side::Other)
sideStr = "against";
else
return { 0, 0 };
json playerData = this->data["players"][uniqueID];
if (!playerData.contains("playlistData"))
return { 0, 0 };
json data = playerData["playlistData"];
if (playlist == PlaylistID::ANY)
{
Record combinedRecord{};
for (auto it = data.begin(); it != data.end(); ++it)
{
if (it.key().empty())
continue;
auto playlistInt = std::stoi(it.key());
auto temp = GetRecord(uniqueID, static_cast<PlaylistID>(playlistInt), side);
combinedRecord.wins += temp.wins;
combinedRecord.losses += temp.losses;
}
return combinedRecord;
}
std::string playlistIdxStr = std::to_string(playlist);
if (!data.contains(playlistIdxStr))
return { 0, 0 };
json recordJson = data[playlistIdxStr]["records"];
if (recordJson.contains(sideStr))
{
try
{
return recordJson[sideStr].get<Record>();
}
catch (const std::exception& e)
{
this->gameWrapper->Toast("DejaVu Error", "Check console/log for details");
this->cvarManager->log(e.what());
LOG(INFO) << e.what();
return { 0, 0 };
}
}
return { 0, 0 };
}
void DejaVu::SetRecord()
{
if (!IsInRealGame())
return;
auto server = this->gameWrapper->GetOnlineGame();
if (server.IsNull())
return;
auto winningTeam = server.GetWinningTeam();
if (winningTeam.IsNull())
return;
auto localPlayer = server.GetLocalPrimaryPlayer();
if (localPlayer.IsNull())
return;
auto localPRI = localPlayer.GetPRI();
if (localPRI.IsNull())
return;
PlaylistID playlist = static_cast<PlaylistID>(server.GetPlaylist().GetPlaylistId());
bool myTeamWon = winningTeam.GetTeamNum() == localPRI.GetTeamNum();
Log(myTeamWon ? "YOU WON!" : "YOU LOST!");
UniqueIDWrapper myID = localPRI.GetUniqueIdWrapper();
auto players = server.GetPRIs();
for (int i = 0; i < players.Count(); i++)
{
auto player = players.Get(i);
std::string uniqueIDStr = player.GetUniqueIdWrapper().str();
if (uniqueIDStr == myID.str() || uniqueIDStr == "0")
continue;
bool sameTeam = player.GetTeamNum() == localPRI.GetTeamNum();
Record record = GetRecord(uniqueIDStr, playlist, sameTeam ? Side::Same : Side::Other);
if (myTeamWon)
record.wins++;
else
record.losses++;
std::string sideStr;
if (sameTeam)
sideStr = "with";
else
sideStr = "against";
this->data["players"][uniqueIDStr]["playlistData"][std::to_string(playlist)]["records"][sideStr] = record;
}
}
bool DejaVu::IsInRealGame()
{
return this->gameWrapper->IsInOnlineGame() && !this->gameWrapper->IsInReplay() && !this->gameWrapper->IsInFreeplay();
}
static float MetCountColumnWidth;
static float RecordColumnWidth;
void DejaVu::RenderDrawable(CanvasWrapper canvas)
{
if (!Canvas::IsContextSet())
{
Canvas::SetContext(canvas);
MetCountColumnWidth = Canvas::GetStringWidth("9999") + 11;
RecordColumnWidth = Canvas::GetStringWidth("9999:9999") + 11;
}
Canvas::SetGlobalAlpha((char)(*this->alpha * 255));
Canvas::SetScale(*this->scale);
bool inGame = IsInRealGame();
bool noData = this->blueTeamRenderData.size() == 0 && this->orangeTeamRenderData.size() == 0;
bool scoreboardIsClosedAndToggleIsOn = *this->toggleWithScoreboard && !this->isScoreboardOpen;
if (
(!*this->enabled || !*this->enabledVisuals || !inGame || noData || scoreboardIsClosedAndToggleIsOn) && !*this->enabledDebug
)
return;
int blueSize = (int)this->blueTeamRenderData.size();
int orangeSize = (int)this->orangeTeamRenderData.size();
bool renderPlayerBlue = false;
bool renderPlayerOrange = false;
auto pri = GetLocalPlayerPRI();
if (!pri.IsNull())
{
auto isBlueTeam = pri.GetTeamNum() == 0;
if (isBlueTeam)
{
blueSize++;
orangeSize = max(orangeSize, 1);
}
else
{
orangeSize++;
blueSize = max(blueSize, 1);
}
renderPlayerBlue = isBlueTeam;
renderPlayerOrange = !isBlueTeam;
}