-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRockTheVote.as
1420 lines (1146 loc) · 43.5 KB
/
RockTheVote.as
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 "MenuVote"
#include "GameVotes"
#include "Stats"
#include "HashMap"
#include "inc/RelaySay"
// TODO:
// - play 50% of a series for it to count as a play, not just a sinle map
// - configurable min active time and min series map plays
// - reopen menu should close again or not show messsage
// per-map states
class RtvState {
bool didRtv = false; // player wants to rock the vote?
string nom; // what map this player nominated
int afkTime = 0; // AFK players ignored for rtv requirement
}
class SortableMap {
string map;
uint64 hashKey; // pre-hashed key for faster lookups
uint64 sort; // value used for sorting
SortableMap() {}
SortableMap(SortableMap@ other) {
map = other.map;
hashKey = other.hashKey;
sort = other.sort;
}
SortableMap(string map) {
this.map = map;
hashKey = hash_FNV1a(map);
}
}
CClientCommand forcertv("forcertv", "Lets admin force a vote", @consoleCmd);
CClientCommand cancelrtv("cancelrtv", "Lets admin cancel an ongoing RTV vote", @consoleCmd);
CClientCommand set_nextmap("set_nextmap", "Set the next map cycle", @consoleCmd);
CClientCommand map("map", "Force a map change", @consoleCmd);
CClientCommand vote("vote", "Start a vote or reopen the vote menu", @consoleCmd);
CClientCommand poll("poll", "Start a custom poll", @consoleCmd);
CClientCommand mapstats("mapstats", "Show previous play times for a map", @consoleCmd);
CClientCommand recentmaps("recentmaps", "Show recently played maps", @consoleCmd);
CClientCommand newmaps("newmaps", "Show maps that haven't been played for the longest time", @consoleCmd);
CClientCommand mapinfo("mapinfo", "Show maps that haven't been played for the longest time", @consoleCmd);
CCVar@ g_SecondsUntilVote;
CCVar@ g_MaxMapsToVote;
CCVar@ g_VotingPeriodTime;
CCVar@ g_PercentageRequired;
CCVar@ g_NormalMapCooldown;
CCVar@ g_MemeMapCooldown;
CCVar@ g_EnableGameVotes; // enable text menu replacements for the default game votes
CCVar@ g_EnableForceSurvivalVotes; // enable semi-survival vote (requires ForceSurvival plugin)
CCVar@ g_EnableRestartVotes;
CCVar@ g_EnableDiffVotes;
CCVar@ g_EnableAfkKickVotes;
// maps that can be nominated with a normal cooldown
const string votelistFile = "scripts/plugins/cfg/mapvote.txt";
array<string> g_normalMaps;
// maps that have a large nom cooldown and never randomly show up in the vote menu
const string hiddenMapsFile = "scripts/plugins/cfg/hidden_nom_maps.txt";
array<string> g_hiddenMaps;
// maps that are split into multiple bsp files
const string seriesMapsFile = "scripts/plugins/RockTheVote/series_maps.txt";
dictionary g_seriesMaps; // maps a votable map to a list of maps
string g_previous_map = "";
array<SortableMap>@ g_current_series_maps = null;
array<SortableMap>@ g_previous_series_maps = null;
array<RtvState> g_playerStates;
array<SortableMap> g_everyMap; // sorted combination of normal and hidden maps
array<SortableMap> g_randomRtvChoices; // normal votable maps (all maps besides the meme ones)
array<SortableMap> g_randomCycleMaps; // map cycle maps (only the "good" maps)
array<string> g_nomList; // maps nominated by players
dictionary g_memeMapsHashed; // for faster meme map checks
dictionary g_everyMapHashed; // for faster votable map checks
MenuVote::MenuVote g_rtvVote;
uint g_maxNomMapNameLength = 0; // used for even spacing in the full console map list
CScheduledFunction@ g_timer = null;
bool g_generating_rtv_list = false; // true while maps are being sorted for rtv menu
bool g_autostart_allowed = true;
const float levelChangeDelay = 5.0f; // time in seconds intermission is shown for game_end
dictionary g_lastLaggyCommands;
float g_lastQuestion = 0;
const int LAGGY_COMAND_COOLDOWN = 3; // not laggy when run a few at a time, but the server would freeze if spammed
const int QUESTION_COOLDOWN = 60;
void PluginInit() {
g_Module.ScriptInfo.SetAuthor("w00tguy");
g_Module.ScriptInfo.SetContactInfo("https://github.com/wootguy");
g_Hooks.RegisterHook( Hooks::Player::ClientPutInServer, @ClientJoin );
g_Hooks.RegisterHook(Hooks::Player::ClientDisconnect, @ClientLeave);
g_Hooks.RegisterHook(Hooks::Player::ClientSay, @ClientSay);
g_Hooks.RegisterHook(Hooks::Game::MapChange, @MapChange);
@g_SecondsUntilVote = CCVar("secondsUntilVote", 0, "Delay before players can RTV after map has started", ConCommandFlag::AdminOnly);
@g_MaxMapsToVote = CCVar("iMaxMaps", 6, "How many maps can players nominate and vote for later", ConCommandFlag::AdminOnly);
@g_VotingPeriodTime = CCVar("secondsToVote", 25, "How long can players vote for a map before a map is chosen", ConCommandFlag::AdminOnly);
@g_PercentageRequired = CCVar("iPercentReq", 66, "0-100, percent of players required to RTV before voting happens", ConCommandFlag::AdminOnly);
@g_NormalMapCooldown = CCVar("NormalMapCooldown", 12, "Time in hours before a map can be nommed again", ConCommandFlag::AdminOnly);
@g_MemeMapCooldown = CCVar("MemeMapCooldown", 24*5, "Time in hours before a meme map can be nommed again", ConCommandFlag::AdminOnly);
@g_EnableGameVotes = CCVar("gameVotes", 1, "Text menu replacements for the default game votes", ConCommandFlag::AdminOnly);
@g_EnableForceSurvivalVotes = CCVar("forceSurvivalVotes", 0, "Enable semi-survival vote (requires ForceSurvival plugin)", ConCommandFlag::AdminOnly);
@g_EnableRestartVotes = CCVar("restartVotes", 0, "Enable map restart votes", ConCommandFlag::AdminOnly);
@g_EnableDiffVotes = CCVar("diffVotes", 0, "Enable dynamic difficulty votes", ConCommandFlag::AdminOnly);
@g_EnableAfkKickVotes = CCVar("afkKickVotes", 1, "Enable AFK kick votes", ConCommandFlag::AdminOnly);
reset();
initStats();
g_Scheduler.SetInterval("autoStartRtvCheck", 1.0f, -1);
g_Scheduler.SetInterval("reduceKillPenalties", 60*60, -1);
}
void MapInit() {
g_SoundSystem.PrecacheSound("fvox/one.wav");
g_SoundSystem.PrecacheSound("fvox/two.wav");
g_SoundSystem.PrecacheSound("fvox/three.wav");
g_SoundSystem.PrecacheSound("fvox/four.wav");
g_SoundSystem.PrecacheSound("fvox/five.wav");
g_SoundSystem.PrecacheSound("gman/gman_choose1.wav");
g_SoundSystem.PrecacheSound("gman/gman_choose2.wav");
g_SoundSystem.PrecacheSound("buttons/blip3.wav");
reset();
@g_previous_series_maps = @g_current_series_maps;
@g_current_series_maps = getMapSeriesMaps(g_Engine.mapname);
string next_series_map = getNextSeriesMap(g_current_series_maps);
SemiSurvivalMapInit();
if (next_series_map.Length() > 0 and g_EngineFuncs.IsMapValid(next_series_map)) {
g_EngineFuncs.ServerCommand("mp_nextmap_cycle " + next_series_map + "\n");
} else {
setFreshMapAsNextMap(g_randomCycleMaps); // something most haven't played in the longest time
}
}
void MapStart() {
DiffMapStart();
}
HookReturnCode MapChange() {
writeActivePlayerStats();
g_player_activity.clear();
g_Scheduler.RemoveTimer(g_timer);
g_previous_map = g_Engine.mapname;
return HOOK_CONTINUE;
}
void reset() {
g_playerStates.resize(0);
g_playerStates.resize(33);
g_nomList.resize(0);
g_Scheduler.RemoveTimer(g_timer);
loadAllMapLists();
g_rtvVote.reset();
g_gameVote.reset();
g_lastLaggyCommands.clear();
g_lastGameVote = 0;
g_anyone_joined = false;
g_generating_rtv_list = false;
g_autostart_allowed = true;
g_lastQuestion = -999;
}
void loadCrossPluginAfkState() {
CBaseEntity@ afkEnt = g_EntityFuncs.FindEntityByTargetname(null, "PlayerStatusPlugin");
if (afkEnt is null) {
return;
}
CustomKeyvalues@ customKeys = afkEnt.GetCustomKeyvalues();
for ( int i = 1; i <= g_Engine.maxClients; i++ )
{
CustomKeyvalue key = customKeys.GetKeyvalue("$i_afk" + i);
if (key.Exists()) {
g_playerStates[i].afkTime = key.GetInteger();
}
// don't count loading/disconnected players either
CustomKeyvalue key2 = customKeys.GetKeyvalue("$i_state" + i);
if (key2.Exists() && key2.GetInteger() > 0 && g_playerStates[i].afkTime == 0) {
g_playerStates[i].afkTime = 999;
}
}
}
void autoStartRtvCheck() {
loadCrossPluginAfkState();
if (canAutoStartRtv()) {
startVote("(vote requirement lowered due to leaving/AFK players)");
}
}
void print(string text) { g_Game.AlertMessage( at_console, text); }
void println(string text) { print(text + "\n"); }
void delay_print(EHandle h_plr, string message) {
CBasePlayer @ plr = cast < CBasePlayer @ > (h_plr.GetEntity());
if (plr !is null) {
g_PlayerFuncs.ClientPrint(plr, HUD_PRINTCONSOLE, message);
}
}
void delay_print(EHandle h_plr, array<string> messages) {
CBasePlayer @ plr = cast<CBasePlayer@>(h_plr.GetEntity());
if (plr !is null) {
for (uint i = 0; i < messages.size(); i++) {
g_PlayerFuncs.ClientPrint(plr, HUD_PRINTCONSOLE, messages[i]);
}
}
}
void playSoundGlobal(string file, float volume, int pitch) {
for (int i = 1; i <= g_Engine.maxClients; i++) {
CBasePlayer@ plr = g_PlayerFuncs.FindPlayerByIndex(i);
if (plr is null or !plr.IsConnected()) {
continue;
}
g_SoundSystem.PlaySound(plr.edict(), CHAN_VOICE, file, volume, ATTN_NONE, 0, pitch, plr.entindex());
}
}
void game_end(string nextMap) {
// using a game_end instead of changelevel command so that game_end detection works here and in other plugins
g_EngineFuncs.ServerCommand("mp_nextmap_cycle " + nextMap + "\n");
CBaseEntity@ endEnt = g_EntityFuncs.CreateEntity("game_end");
endEnt.Use(null, null, USE_TOGGLE);
}
int getCurrentRtvCount(bool excludeAfks=true) {
int count = 0;
for (uint i = 0; i < g_playerStates.size(); i++) {
count += g_playerStates[i].didRtv and (g_playerStates[i].afkTime == 0 || !excludeAfks) ? 1 : 0;
}
return count;
}
int getRequiredRtvCount(bool excludeAfks=true) {
uint playerCount = 0;
for (int i = 1; i <= g_Engine.maxClients; i++) {
CBasePlayer@ p = g_PlayerFuncs.FindPlayerByIndex(i);
if (p is null or !p.IsConnected()) {
continue;
}
if (g_playerStates[i].afkTime >= 60 && excludeAfks) {
continue; // PlayerStatus plugin says this player is afk
}
playerCount++;
}
float percent = g_PercentageRequired.GetInt() / 100.0f;
return int(Math.Ceil(percent * float(playerCount)));
}
bool canAutoStartRtv() {
if (g_rtvVote.status == MVOTE_NOT_STARTED && g_Engine.time > g_SecondsUntilVote.GetInt()) {
if (getCurrentRtvCount() >= getRequiredRtvCount() and getCurrentRtvCount() > 0) {
return !g_generating_rtv_list and g_autostart_allowed;
}
}
return false;
}
void createRtvMenu(dictionary args) {
array<string> rtvList;
if (!g_generating_rtv_list) {
return; // game_end interrupted sort
}
g_generating_rtv_list = false;
for (uint i = 0; i < g_nomList.size(); i++) {
rtvList.insertLast(g_nomList[i]);
}
uint maxMenuItems = Math.min(g_MaxMapsToVote.GetInt(), 8);
// always have at least one good map, or the next map if this is a series
rtvList.insertLast(g_MapCycle.GetNextMap());
array<string> shuffleChoices;
array<string> randChoices;
array<string> goodChoices;
uint firstPlayedMapIdx = 0;
uint mapsNeeded = maxMenuItems - rtvList.size();
// prevent the same maps always being shown for players who have little history
for (uint i = 0; i < g_randomRtvChoices.size(); i++) {
if (g_randomRtvChoices[i].sort != 0 and shuffleChoices.size() > mapsNeeded) {
break;
}
shuffleChoices.insertLast(g_randomRtvChoices[i].map);
}
for (uint i = 0; i < g_randomCycleMaps.size() && i < mapsNeeded; i++) {
string map = g_randomCycleMaps[Math.RandomLong(0, g_randomCycleMaps.size()-1)].map;
bool alreadyAdded = goodChoices.find(map) != -1 || shuffleChoices.find(map) != -1;
bool enoughInPool = g_randomCycleMaps.size() > mapsNeeded*2;
bool wasPlayedSuperRecently = g_Engine.mapname == map || g_previous_map == map;
if ((alreadyAdded || wasPlayedSuperRecently) && enoughInPool) {
i--; // try again
continue;
}
goodChoices.insertLast(map);
}
for (uint i = 0; i < g_randomRtvChoices.size() && i < mapsNeeded; i++) {
string map = g_randomRtvChoices[Math.RandomLong(0, g_randomRtvChoices.size()-1)].map;
bool alreadyAdded = goodChoices.find(map) != -1 || randChoices.find(map) != -1 || shuffleChoices.find(map) != -1;
bool enoughInPool = g_randomRtvChoices.size() > mapsNeeded*2;
bool wasPlayedSuperRecently = g_Engine.mapname == map || g_previous_map == map;
if ((alreadyAdded || wasPlayedSuperRecently) && enoughInPool) {
i--; // try again
continue;
}
randChoices.insertLast(map);
}
// rtv layout for when there are no noms
// 1 - (exit)
// 2 - next map (good map or map cycle)
// 3 - good map (map cycle)
// 4 - lesser played map
// 5 - lesser played map
// 6 - decent map (map cycle)
// 7 - decent map (map cycle)
int addedMaps = 0;
for (uint failsafe = 0; failsafe < g_randomRtvChoices.size(); failsafe++) {
if (rtvList.size() >= maxMenuItems) {
break;
}
if (addedMaps <= 0 && goodChoices.size() > 0) {
int idx = Math.RandomLong(0, goodChoices.size()-1);
string goodMap = goodChoices[idx];
goodChoices.removeAt(idx);
if (rtvList.find(goodMap) == -1 && g_EngineFuncs.IsMapValid(goodMap)) {
rtvList.insertLast(goodMap);
addedMaps++;
}
}
else if (addedMaps <= 2 && shuffleChoices.size() > 0) {
int idx = Math.RandomLong(0, shuffleChoices.size()-1);
string lesserPlayedMap = shuffleChoices[idx];
shuffleChoices.removeAt(idx);
if (rtvList.find(lesserPlayedMap) == -1 && g_EngineFuncs.IsMapValid(lesserPlayedMap)) {
rtvList.insertLast(lesserPlayedMap);
addedMaps++;
}
} else if (randChoices.size() > 0) {
int idx = Math.RandomLong(0, randChoices.size()-1);
string randomMap = randChoices[idx];
randChoices.removeAt(idx);
if (rtvList.find(randomMap) == -1 && g_EngineFuncs.IsMapValid(randomMap)) {
rtvList.insertLast(randomMap);
addedMaps++;
}
} else {
break;
}
}
array<MenuOption> menuOptions;
menuOptions.insertLast(MenuOption("\\d(exit)"));
menuOptions[0].isVotable = false;
for (uint i = 0; i < rtvList.size(); i++) {
menuOptions.insertLast(MenuOption(rtvList[i]));
}
MenuVoteParams voteParams;
voteParams.title = "Next map";
voteParams.options = menuOptions;
voteParams.voteTime = g_VotingPeriodTime.GetInt();
@voteParams.optionCallback = @mapChosenCallback;
@voteParams.thinkCallback = @voteThinkCallback;
@voteParams.finishCallback = @voteFinishCallback;
g_rtvVote.start(voteParams, null);
}
void disable_level_changes() {
// TODO: this will break if a once-only trigger is activated during rtv and then rtv is cancelled or fails.
CBaseEntity@ ent = null;
do {
@ent = g_EntityFuncs.FindEntityByClassname(ent, "trigger_changelevel");
if (ent !is null) {
ent.pev.solid = SOLID_NOT;
}
} while (ent !is null);
@ent = null;
do {
@ent = g_EntityFuncs.FindEntityByClassname(ent, "game_end");
if (ent !is null) {
ent.pev.targetname = "RTV_" + ent.pev.targetname;
}
} while (ent !is null);
}
void enable_level_changes() {
CBaseEntity@ ent = null;
do {
@ent = g_EntityFuncs.FindEntityByClassname(ent, "trigger_changelevel");
if (ent !is null) {
ent.pev.solid = SOLID_TRIGGER;
}
} while (ent !is null);
@ent = null;
do {
@ent = g_EntityFuncs.FindEntityByClassname(ent, "game_end");
if (ent !is null) {
if (string(ent.pev.targetname).Find("RTV_") == 0) {
ent.pev.targetname = string(ent.pev.targetname).SubString(4);
}
}
} while (ent !is null);
}
void startVote(string reason="") {
if (g_gameVote.status == MVOTE_IN_PROGRESS) {
g_gameVote.cancel();
} else if (g_gameVote.status == MVOTE_FINISHED) {
println("Waiting for game vote to end...");
g_Scheduler.SetTimeout("startVote", 1.0f, reason);
g_generating_rtv_list = true; // prevent auto-start starting rtv
return;
}
g_PlayerFuncs.ClientPrintAll(HUD_PRINTTALK, "[RTV] Vote starting! " + reason + "\n");
if (g_randomRtvChoices.size() == 0) {
g_Log.PrintF("[RTV] All maps are excluded by the previous map list! Make sure g_ExcludePrevMaps value is less than the total nommable maps.\n");
createRtvMenu({});
return;
}
g_autostart_allowed = false;
g_generating_rtv_list = true;
disable_level_changes();
sortMapsByFreshness(g_randomRtvChoices, getActivePlayers(), 0, createRtvMenu, {});
}
void voteThinkCallback(MenuVote::MenuVote@ voteMenu, int secondsLeft) {
int voteTime = g_VotingPeriodTime.GetInt();
if (secondsLeft == voteTime) { playSoundGlobal("gman/gman_choose1.wav", 1.0f, 100); }
else if (secondsLeft == 8) { playSoundGlobal("gman/gman_choose2.wav", 1.0f, 100); }
else if (secondsLeft == 5) { playSoundGlobal("fvox/five.wav", 0.8f, 85); }
else if (secondsLeft == 4) { playSoundGlobal("fvox/four.wav", 0.8f, 85); }
else if (secondsLeft == 3) { playSoundGlobal("fvox/three.wav", 0.8f, 85); }
else if (secondsLeft == 2) { playSoundGlobal("fvox/two.wav", 0.8f, 85); }
else if (secondsLeft == 1) { playSoundGlobal("fvox/one.wav", 0.8f, 85); }
}
void voteFinishCallback(MenuVote::MenuVote@ voteMenu, MenuOption@ chosenOption, int resultReason) {
string nextMap = chosenOption.value;
if (resultReason == MVOTE_RESULT_TIED) {
g_PlayerFuncs.ClientPrintAll(HUD_PRINTTALK, "[RTV] \"" + nextMap + "\" has been randomly chosen amongst the tied.\n");
} else if (resultReason == MVOTE_RESULT_NO_VOTES) {
g_PlayerFuncs.ClientPrintAll(HUD_PRINTTALK, "[RTV] \"" + nextMap + "\" has been randomly chosen since nobody picked.\n");
} else {
g_PlayerFuncs.ClientPrintAll(HUD_PRINTTALK, "[RTV] \"" + nextMap + "\" has been chosen!\n");
}
playSoundGlobal("buttons/blip3.wav", 1.0f, 70);
g_Log.PrintF("[RTV] chose " + nextMap + "\n");
RelaySay("Map ended by vote.");
g_Scheduler.SetTimeout("game_end", MenuVote::g_resultTime, nextMap);
g_Scheduler.SetTimeout("reset_failsafe", MenuVote::g_resultTime + levelChangeDelay + 0.1f);
}
void reset_failsafe() {
g_rtvVote.reset();
g_gameVote.reset();
g_lastGameVote = 0;
g_playerStates.resize(0);
g_playerStates.resize(33);
g_nomList.resize(0);
g_generating_rtv_list = false;
g_autostart_allowed = true;
}
void mapChosenCallback(MenuVote::MenuVote@ voteMenu, MenuOption@ chosenOption, CBasePlayer@ plr) {
if (chosenOption !is null) {
if (chosenOption.label == "\\d(exit)") {
g_PlayerFuncs.ClientPrint(plr, HUD_PRINTCENTER, "Say \"rtv\" to reopen the menu\n");
voteMenu.closeMenu(plr);
}
}
}
// return 1 = show chat, 2 = hide chat
int tryRtv(CBasePlayer@ plr) {
int eidx = plr.entindex();
if (g_rtvVote.status == MVOTE_FINISHED) {
return 1;
}
if (g_generating_rtv_list) {
return 2;
}
if (g_rtvVote.status == MVOTE_IN_PROGRESS) {
g_rtvVote.reopen(plr);
return 2;
}
if (g_Engine.time < g_SecondsUntilVote.GetInt()) {
int timeLeft = int(Math.Ceil(float(g_SecondsUntilVote.GetInt()) - g_Engine.time));
g_PlayerFuncs.SayText(plr, "[RTV] RTV will enable in " + timeLeft + " seconds.\n");
return 2;
}
if (g_playerStates[eidx].didRtv) {
g_PlayerFuncs.SayText(plr, "[RTV] " + getCurrentRtvCount() + " of " + getRequiredRtvCount() + " players until vote starts! You already rtv'd.\n");
return 2;
}
g_playerStates[eidx].didRtv = true;
if (getCurrentRtvCount() >= getRequiredRtvCount() and getCurrentRtvCount() > 0) {
sayRtvCount(plr);
startVote();
} else {
sayRtvCount(plr);
}
return 2;
}
int unRtv(CBasePlayer@ plr) {
int eidx = plr.entindex();
if (g_rtvVote.status == MVOTE_FINISHED) {
return 1;
}
if (g_generating_rtv_list) {
return 2;
}
if (g_rtvVote.status == MVOTE_IN_PROGRESS) {
g_rtvVote.reopen(plr);
return 2;
}
if (g_Engine.time < g_SecondsUntilVote.GetInt()) {
int timeLeft = int(Math.Ceil(float(g_SecondsUntilVote.GetInt()) - g_Engine.time));
g_PlayerFuncs.SayText(plr, "[RTV] RTV will enable in " + timeLeft + " seconds.\n");
return 2;
}
if (!g_playerStates[eidx].didRtv) {
g_PlayerFuncs.SayText(plr, "[RTV] " + getCurrentRtvCount() + " of " + getRequiredRtvCount() + " players until vote starts! You haven't rtv'd yet.\n");
return 2;
}
g_playerStates[eidx].didRtv = false;
g_PlayerFuncs.ClientPrintAll(HUD_PRINTTALK, "[RTV] " + plr.pev.netname + " took their \"rtv\" back.\n");
return 2;
}
void sayRtvCount(CBasePlayer@ plr=null) {
string msg = "[RTV] " + getCurrentRtvCount() + " of " + getRequiredRtvCount() + " players until vote starts!";
if (plr !is null) {
msg += " -" + plr.pev.netname;
if (g_playerStates[plr.entindex()].afkTime > 0) {
msg += " (AFK)";
}
}
g_PlayerFuncs.ClientPrintAll(HUD_PRINTTALK, msg + "\n");
}
void cancelRtv(CBasePlayer@ plr) {
if (g_rtvVote.status != MVOTE_IN_PROGRESS) {
g_PlayerFuncs.SayText(plr, "[RTV] There is no vote to cancel.\n");
return;
}
for (uint i = 0; i < g_playerStates.size(); i++) {
g_playerStates[i].didRtv = false;
}
g_rtvVote.cancel();
enable_level_changes();
g_PlayerFuncs.SayTextAll(plr, "[RTV] Vote cancelled by " + plr.pev.netname + "!\n");
}
// returns true if someone in the server played the map too recently for it to be nominated again
bool isMapExcluded(string mapname, array<SteamName> activePlayers, CBasePlayer@ plr) {
bool isMemeMap = g_memeMapsHashed.exists(mapname);
int cooldown = (isMemeMap ? g_MemeMapCooldown.GetInt() : g_NormalMapCooldown.GetInt()) * 60*60;
int recentCount = 0;
string recentName;
string steamid = getPlayerUniqueId(plr);
for (uint i = 0; i < activePlayers.size(); i++) {
if (steamid == activePlayers[i].steamid) {
continue;
}
uint64 lastPlay = getLastPlayTime(activePlayers[i].steamid, mapname);
int diff = int(DateTime().ToUnixTimestamp() - lastPlay);
if (diff < cooldown) {
recentCount += 1;
recentName = activePlayers[i].name;
}
}
if (recentCount > 0) {
string splr = recentCount == 1 ? recentName : "" + recentCount + " people here";
string smap = g_seriesMaps.exists(mapname) ? "that map series" : "that map";
g_PlayerFuncs.SayText(plr, "[RTV] Can't nom \"" + mapname + "\" yet. " + splr + " played " + smap + " fewer than " + formatLastPlayedTime(cooldown) + " ago.\n");
}
return recentCount > 0;
}
void nomMenuCallback(CTextMenu@ menu, CBasePlayer@ plr, int page, const CTextMenuItem@ item) {
if (item is null or plr is null or !plr.IsConnected() or g_rtvVote.status != MVOTE_NOT_STARTED) {
return;
}
string nomChoice;
item.m_pUserData.retrieve(nomChoice);
array<string> parts = nomChoice.Split(":");
string mapname = parts[0];
string mapfilter = parts[1];
int itempage = atoi(parts[2]);
if (!tryNominate(plr, mapname, false)) {
array<string> similarNames = generateNomMenu(mapfilter);
g_Scheduler.SetTimeout("openNomMenu", 0.0f, EHandle(plr), mapfilter, similarNames, itempage);
}
}
void openNomMenu(EHandle h_plr, string mapfilter, array<string> maps, int page) {
CBasePlayer@ plr = cast<CBasePlayer@>(h_plr.GetEntity());
if (plr is null) {
return;
}
int eidx = plr.entindex();
@g_menus[eidx] = CTextMenu(@nomMenuCallback);
string title = "\\yMaps containing \"" + mapfilter + "\" ";
if (mapfilter.Length() == 0) {
title = "\\yNominate... ";
}
g_menus[eidx].SetTitle(title);
array<SteamName> activePlayers = getActivePlayers();
for (uint i = 0; i < maps.size(); i++) {
int itempage = i / 7;
string label = maps[i] + "\\y";
label = "\\w" + label;
g_menus[eidx].AddItem(label, any(maps[i] + ":" + mapfilter + ":" + itempage));
}
if (!(g_menus[eidx].IsRegistered()))
g_menus[eidx].Register();
g_menus[eidx].Open(0, page, plr);
}
array<string> generateNomMenu(string mapname) {
bool fullNomMenu = mapname.Length() == 0;
array<string> similarNames;
if (fullNomMenu) {
for (uint i = 0; i < g_everyMap.size(); i++) {
similarNames.insertLast(g_everyMap[i].map);
}
}
else {
for (uint i = 0; i < g_everyMap.size(); i++) {
if (int(g_everyMap[i].map.Find(mapname)) != -1) {
similarNames.insertLast(g_everyMap[i].map);
}
}
}
return similarNames;
}
bool tryNominate(CBasePlayer@ plr, string mapname, bool isRandom) {
if (g_rtvVote.status != MVOTE_NOT_STARTED) {
return false;
}
int eidx = plr.entindex();
bool dontAutoNom = int(mapname.Find("*")) != -1; // player just wants to search for maps with this string
mapname.Replace("*", "");
mapname.Replace(":", ""); // used as delimiter in nom menu option data
bool fullNomMenu = mapname.Length() == 0;
bool mapExists = false;
for (uint i = 0; i < g_everyMap.size(); i++) {
if (g_everyMap[i].map == mapname) {
mapExists = true;
}
}
if (fullNomMenu || dontAutoNom || !mapExists) {
array<string> similarNames = generateNomMenu(mapname);
if (similarNames.size() == 0) {
g_PlayerFuncs.SayText(plr, "[RTV] No maps containing \"" + mapname + "\" exist.");
}
else if (similarNames.size() > 1 || dontAutoNom) {
openNomMenu(plr, mapname, similarNames, 0);
}
else if (similarNames.size() == 1) {
return tryNominate(plr, similarNames[0], isRandom);
}
return false;
}
if (g_Engine.time < g_SecondsUntilVote.GetInt()) {
int timeLeft = int(Math.Ceil(float(g_SecondsUntilVote.GetInt()) - g_Engine.time));
g_PlayerFuncs.SayText(plr, "[RTV] Nominations will enable in " + timeLeft + " seconds.\n");
return false;
}
if (mapname == g_Engine.mapname) {
g_PlayerFuncs.SayText(plr, "[RTV] Can't nominate the current map!\n");
return false;
}
if (g_nomList.find(mapname) != -1) {
g_PlayerFuncs.SayText(plr, "[RTV] \"" + mapname + "\" has already been nominated.\n");
return false;
}
// leave one slot empty for next map in series, or at least one "good map" in case everyone is nomming meme maps
if (int(g_nomList.size()) >= g_MaxMapsToVote.GetInt()-1 && g_playerStates[eidx].nom == "") {
g_PlayerFuncs.SayText(plr, "[RTV] The max number of nominations has been reached!\n");
return false;
}
if (!g_EngineFuncs.IsMapValid(mapname)) {
g_PlayerFuncs.SayText(plr, "[RTV] \"" + mapname + "\" does not exist! Why is it in the nom list???\n");
return false;
}
if (isMapExcluded(mapname, getActivePlayers(true), plr)) {
return false;
}
string oldNomMap = g_playerStates[eidx].nom;
g_playerStates[eidx].nom = mapname;
g_nomList.insertLast(mapname);
if (oldNomMap.IsEmpty()) {
g_PlayerFuncs.SayTextAll(plr, "[RTV] " + plr.pev.netname + (isRandom ? " randomly" : "") + " nominated \"" + mapname + "\".\n");
} else {
g_nomList.removeAt(g_nomList.find(oldNomMap));
g_PlayerFuncs.SayTextAll(plr, "[RTV] " + plr.pev.netname + (isRandom ? " randomly" : "") + " changed their nomination to \"" + mapname + "\".\n");
}
return true;
}
void sendMapList(CBasePlayer@ plr) {
const float delayStep = 0.1f; // chunks might arrive out of order any faster than this
const uint chunkSize = 12;
float delay = 0;
array<string> buffer;
g_Scheduler.SetTimeout("delay_print", delay, EHandle(plr), "\n--Map list---------------\n");
delay += delayStep;
// send in chunks to prevent overflows
for (uint i = 0; i < g_everyMap.length(); i += 4) {
string msg = "";
for (uint k = 0; k < 4 && i + k < g_everyMap.length(); k++) {
msg += g_everyMap[i + k].map;
int padding = (g_maxNomMapNameLength + 1) - g_everyMap[i + k].map.Length();
for (int p = 0; p < padding; p++) {
msg += " ";
}
}
buffer.insertLast(msg + "\n");
if (buffer.size() >= chunkSize) {
g_Scheduler.SetTimeout("delay_print", delay, EHandle(plr), buffer);
buffer = array<string>();
delay += delayStep;
}
}
if (buffer.size() > 0) {
g_Scheduler.SetTimeout("delay_print", delay, EHandle(plr), buffer);
buffer = array<string>();
delay += delayStep;
}
delay += delayStep;
g_Scheduler.SetTimeout("delay_print", delay, EHandle(plr), "----------------------------- (" + g_everyMap.length() +" maps)\n\n");
g_PlayerFuncs.SayText(plr, "[RTV] Map list written to console");
}
array<string> loadMapList(string path, bool ignoreDuplicates=false) {
array<string> maplist;
File@ file = g_FileSystem.OpenFile(path, OpenFile::READ);
dictionary unique;
if (file !is null && file.IsOpen()) {
while (!file.EOFReached()) {
string line;
file.ReadLine(line);
line.Trim();
int commentIdx = line.Find("//");
if (commentIdx != -1) {
line = line.SubString(0, commentIdx);
line.Trim();
}
if (line.IsEmpty())
continue;
array<string> parts = line.Split(" ");
// allow either mapcycle or mapvote format
string mapname;
if (parts[0] == "addvotemap" && parts.size() > 1) {
mapname = parts[1].ToLowercase();
} else {
mapname = parts[0].ToLowercase();
}
mapname.Trim(); // TODO: doesn't work on linux for some reason. Tabs are not stripped. Replacing tabs also doesn't work.
if (!ignoreDuplicates && unique.exists(mapname)) {
g_Log.PrintF("[RTV] duplicate map " + mapname + " in list: " + path + "\n");
continue;
}
unique[mapname] = true;
maplist.insertLast(mapname);
}
file.Close();
} else {
g_Log.PrintF("[RTV] map list file not found: " + path + "\n");
}
return maplist;
}
void loadSeriesMaps() {
g_seriesMaps.clear();
File@ file = g_FileSystem.OpenFile(seriesMapsFile, OpenFile::READ);
dictionary unique;
if (file !is null && file.IsOpen()) {
while (!file.EOFReached()) {
string line;
file.ReadLine(line);
line.Trim();
int commentIdx = line.Find("//");
if (commentIdx != -1) {
line = line.SubString(0, commentIdx);
line.Trim();
}
if (line.IsEmpty())
continue;
array<string> maps = line.Split(" ");
array<SortableMap> sortableMaps;
for (uint i = 0; i < maps.size(); i++) {
sortableMaps.insertLast(SortableMap(maps[i]));
}
bool foundAnyVotable = false;
for (uint i = 0; i < maps.size(); i++) {
if (g_everyMapHashed.exists(maps[i])) {
g_seriesMaps[maps[i]] = sortableMaps;
foundAnyVotable = true;
}
}
if (!foundAnyVotable) {
g_seriesMaps[maps[0]] = sortableMaps;
}
}
file.Close();
} else {
g_Log.PrintF("[RTV] map list file not found: " + seriesMapsFile + "\n");
}
}
void loadAllMapLists() {
g_normalMaps = loadMapList(votelistFile);
g_hiddenMaps = loadMapList(hiddenMapsFile);
g_memeMapsHashed.clear();
g_everyMapHashed.clear();
g_everyMap.resize(0);
g_randomRtvChoices.resize(0);
g_randomCycleMaps.resize(0);
for (uint i = 0; i < g_hiddenMaps.size(); i++) {
g_everyMap.insertLast(SortableMap(g_hiddenMaps[i]));
g_everyMapHashed[g_hiddenMaps[i]] = true;
g_memeMapsHashed[g_hiddenMaps[i]] = true;
if (g_hiddenMaps[i].Length() > g_maxNomMapNameLength) {
g_maxNomMapNameLength = g_hiddenMaps[i].Length();
}
}
for (uint i = 0; i < g_normalMaps.size(); i++) {
if (g_memeMapsHashed.exists(g_normalMaps[i])) {
g_Log.PrintF("[RTV] Map \"" + g_normalMaps[i] + "\" should either be in mapvote.cfg or hidden_nom_maps.txt, but not both.\n");
continue;
}
g_everyMap.insertLast(SortableMap(g_normalMaps[i]));
g_everyMapHashed[g_normalMaps[i]] = true;
if (g_normalMaps[i].Length() > g_maxNomMapNameLength) {
g_maxNomMapNameLength = g_normalMaps[i].Length();
}
if (g_normalMaps[i] != g_Engine.mapname) {
g_randomRtvChoices.insertLast(SortableMap(g_normalMaps[i]));
}
}
array<string> mapCycleMaps = g_MapCycle.GetMapCycle();
for (uint i = 0; i < mapCycleMaps.size(); i++) {
if (mapCycleMaps[i] != g_Engine.mapname) {
g_randomCycleMaps.insertLast(SortableMap(mapCycleMaps[i]));
}