-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreplay-bots.sp
2183 lines (1907 loc) · 54.9 KB
/
replay-bots.sp
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
/* Headers */
#include <sourcemod>
#include <sdktools>
#include <sdkhooks>
#include <cstrike>
/* Preprocessor directives */
#pragma semicolon 1 // Enforce the usage of semicolons
#pragma newdecls required // Enforce the new syntax
#define PLUGIN_VERSION "1.0.2" // Using semantic versioning: https://semver.org/
#define MAX_LEVELS 2 // Main, bonus. Be careful with that.
#define MAX_STYLES 6 // N, SW, HSW, etc. Styles should match the KV file at {STYLES_CFG}
#define MAX_GHOSTS 2 // 1 which previews normal WR and 1 which allows players to replay a specific style.
#define NORMAL_GHOST 0 // The index of the standard replay ghost which previews normal WR
#define CUSTOM_GHOST 1 // The index of the +use / !replay custom replay ghost
#define BACKUP_REPLAYS // Uncomment to keep a backup of the last WRs
#define TEAM_GHOST "CT" // Replay bots team. "any", "T" or "CT"
#define STYLES_CFG "configs/timer/bots.cfg" // Path to the styles KV cfg file
#define REPLAYS_PATH "data/ghostrecords" // Path to where replays are stored
#define CORRECT_POSITION_DIST 100.0 // Teleport using position if replay goes out of sync.
#define MAX_WEAPONS 48 // Max weapon slots that the m_hMyWeapons array holds
#define PLAYBACK_DELAY 3.0 // Delay before the playback begins
#define MAX_ALLOWED_NAME 12 // Max chars allowed of a name
#define MAX_STYLETAG_LEN 16 // Max number of characters a style tag can hold
#define MAX_LEVELNAME_LEN 16 // Max number of characters a level name can hold
#define MEME "(⌐■_■)" // Custom ghost's clantag when inactive
#define SPECMODE_FIRSTPERSON 4 // Observer mode constant indicating firstperson
#define SPECMODE_3RDPERSON 5 // Observer mode constant indicating thirdperson
#define PLAYBACK_RENDER RENDERFX_NONE // RENDERFX_NONE or RENDERFX_HOLOGRAM is a good choice
/* Global variables */
enum
{
RUNDATA_POSITION_X,
RUNDATA_POSITION_Y,
RUNDATA_POSITION_Z,
RUNDATA_PITCH,
RUNDATA_YAW,
RUNDATA_BUTTONS,
RUNDATA_IMPULSE,
RUNDATA_WEAPONID,
RUNDATA_MAX
}
// Replays
ArrayList g_arrayReplay[MAX_LEVELS][MAX_STYLES]; //Replays
float g_fReplayTimes[MAX_LEVELS][MAX_STYLES]; //Time of the replays
int g_iReplayJumps[MAX_LEVELS][MAX_STYLES]; //Number of jumps of the replays
char g_sReplayNames[MAX_LEVELS][MAX_STYLES][MAX_NAME_LENGTH]; //Names of the players on the replays
bool g_bNoRecord[MAX_LEVELS][MAX_STYLES]; //Does it have a record?
// Ghosts
int g_iGhost[MAX_GHOSTS]; //Indexes of the two ghosts, (0 = invalid ghost)
int g_iGhostFrame[MAX_GHOSTS]; //What frame is it going, (-1 = ghost is not in motion)
char g_sGhostName[MAX_GHOSTS][MAX_NAME_LENGTH];
char g_sGhostClanTag[MAX_GHOSTS][MAX_NAME_LENGTH];
int g_iGhostLevel[MAX_GHOSTS]; //What level the ghost is replaying
int g_iGhostStyle[MAX_GHOSTS]; //What style the ghost is replaying
int g_iNumBotsConnected = 0; //Keeps track of the number of connected bots
float g_fGhostLastAngles[MAX_GHOSTS][3];
float g_fGhostTime[MAX_GHOSTS];
float g_fLastUsed; // Time since the custom ghost has been last used by a player
float g_fSpawnPoint[3];
// Humans
ArrayList g_arrayRun[MAXPLAYERS + 1]; //Current runs
bool g_bPaused[MAXPLAYERS + 1]; //Is player active?
// Others
char g_sMapName[64]; //Current map name
int g_iGhostStylesCount = 0; //Number of styles found in the KV file
char g_sStyleNames[MAX_STYLES][MAX_NAME_LENGTH]; //Style names
char g_sStyleTags[MAX_STYLES][MAX_STYLETAG_LEN]; //Style tags
char g_sLevelNames[MAX_LEVELS][MAX_LEVELNAME_LEN] = { "main", "bonus" };
float g_fTickrate; // Used to cache the tickrate of the server
// Offsets (netprops)
int m_vecOrigin; // CBaseEntity::m_vecOrigin
int m_hActiveWeapon; // CBaseCombatCharacter::m_hActiveWeapon
int m_hObserverTarget; // CCSPlayer::m_hObserverTarget
int m_iObserverMode; // CCSPlayer::m_iObserverMode
int m_hMyWeapons; // CBaseCombatCharacter::m_hMyWeapons
int m_vecVelocity; // CBaseEntity::m_vecVelocity
/**
* Plugin public information.
*/
public Plugin myinfo =
{
name = "[Timer] Replay Bots",
author = "Pan32, ici",
description = "Shows a bot that replays the top times",
version = PLUGIN_VERSION,
url = ""
};
/**
* Called when the plugin is fully initialized and all known external references
* are resolved. This is only called once in the lifetime of the plugin, and is
* paired with OnPluginEnd().
*
* If any run-time error is thrown during this callback, the plugin will be marked
* as failed.
*/
public void OnPluginStart()
{
GetOffsets();
g_iGhostStylesCount = LoadStyles();
CheckDirectories( g_iGhostStylesCount );
g_fTickrate = 1.0 / GetTickInterval();
// Handle timer communication
RegServerCmd("sm_startrecord", SM_StartRecord);
RegServerCmd("sm_endrecord", SM_EndRecord);
RegServerCmd("sm_timerpause", SM_TimerPause);
RegServerCmd("sm_timerunpause", SM_TimerResume);
HookEvent("player_spawn", Event_PlayerSpawn_Post, EventHookMode_Post);
HookEvent("player_death", Event_PlayerDeath_Post, EventHookMode_Post);
HookUserMessage(GetUserMessageId("SayText2"), SayText2, true);
RegConsoleCmd("sm_replay", SM_Replay, "Choose a WR on the map to replay.");
RegAdminCmd("sm_reloadreplays", SM_ReloadReplays, ADMFLAG_GENERIC, "Reloads replays");
RegAdminCmd("sm_unloadreplays", SM_UnloadReplays, ADMFLAG_GENERIC, "Unloads replays");
// Late plugin load
for (int i = 1; i <= MaxClients; ++i)
{
if (IsClientInGame(i))
{
OnClientConnected(i);
OnClientPutInServer(i);
}
}
CreateTimer(0.1, Timer_HudLoop, 0, TIMER_REPEAT);
}
/**
* Retrieves and caches offsets for future use.
*/
void GetOffsets()
{
m_vecOrigin = FindSendPropInfo("CBaseEntity", "m_vecOrigin");
if (m_vecOrigin == -1)
{
SetFailState("Couldn't find CBaseEntity::m_vecOrigin");
}
if (m_vecOrigin == 0)
{
SetFailState("No offset available for CBaseEntity::m_vecOrigin");
}
m_hActiveWeapon = FindSendPropInfo("CBaseCombatCharacter", "m_hActiveWeapon");
if (m_hActiveWeapon == -1)
{
SetFailState("Couldn't find CBaseCombatCharacter::m_hActiveWeapon");
}
if (m_hActiveWeapon == 0)
{
SetFailState("No offset available for CBaseCombatCharacter::m_hActiveWeapon");
}
m_hObserverTarget = FindSendPropInfo("CCSPlayer", "m_hObserverTarget");
if (m_hObserverTarget == -1)
{
SetFailState("Couldn't find CCSPlayer::m_hObserverTarget");
}
if (m_hObserverTarget == 0)
{
SetFailState("No offset available for CCSPlayer::m_hObserverTarget");
}
m_iObserverMode = FindSendPropInfo("CCSPlayer", "m_iObserverMode");
if (m_iObserverMode == -1)
{
SetFailState("Couldn't find CCSPlayer::m_iObserverMode");
}
if (m_iObserverMode == 0)
{
SetFailState("No offset available for CCSPlayer::m_iObserverMode");
}
m_hMyWeapons = FindSendPropInfo("CBaseCombatCharacter", "m_hMyWeapons");
if (m_hMyWeapons == -1)
{
SetFailState("Couldn't find CBaseCombatCharacter::m_hMyWeapons");
}
if (m_hMyWeapons == 0)
{
SetFailState("No offset available for CBaseCombatCharacter::m_hMyWeapons");
}
m_vecVelocity = FindSendPropInfo("CBasePlayer", "m_vecVelocity[0]");
if (m_vecVelocity == -1)
{
SetFailState("Couldn't find CBasePlayer::m_vecVelocity[0]");
}
if (m_vecVelocity == 0)
{
SetFailState("No offset available for CBasePlayer::m_vecVelocity[0]");
}
}
public Action SayText2(UserMsg msg_id, BfRead msg, const int[] players, int playersNum, bool reliable, bool init)
{
if (!reliable)
{
return Plugin_Continue;
}
char buffer[25];
if (GetUserMessageType() == UM_BitBuf)
{
msg.ReadChar();
msg.ReadChar();
msg.ReadString(buffer, sizeof(buffer));
if (StrEqual(buffer, "#Cstrike_Name_Change"))
{
return Plugin_Handled;
}
}
return Plugin_Continue;
}
/**
* Caches style names stored at configs/timer/bots.cfg
*
* @return int The number of styles found
*/
int LoadStyles()
{
// Create the path to the KV file
char path[PLATFORM_MAX_PATH];
BuildPath(Path_SM, path, sizeof(path), STYLES_CFG);
if (!FileExists(path))
{
SetFailState("ERROR: KV configuration file \"%s\" does not exist, unloading", path);
}
KeyValues kv = new KeyValues("styles");
if (!kv.ImportFromFile(path))
{
SetFailState("ERROR: Couldn't import keyvalues from file");
}
// Iry to get the first style
if (!kv.GotoFirstSubKey(true))
{
SetFailState("ERROR: KV configuration file \"%s\" is empty or with formating errors, unloading", path);
}
int numStyles = 0;
do
{
if (numStyles == MAX_STYLES)
{
SetFailState("The plugin supports only up to %d styles.", MAX_STYLES);
}
//Get Style name and tag
kv.GetString("name", g_sStyleNames[numStyles], MAX_NAME_LENGTH);
kv.GetString("tag", g_sStyleTags[numStyles], MAX_STYLETAG_LEN);
++numStyles;
} while (kv.GotoNextKey(true));
delete kv;
return numStyles;
}
/*
* Checks if directories exist and creates them if they don't.
*
* @param int numStyles The number of styles to create subfolders for.
* @noreturn
*/
void CheckDirectories(int numStyles)
{
char path[PLATFORM_MAX_PATH];
BuildPath(Path_SM, path, sizeof(path), REPLAYS_PATH);
if (!DirExists(path))
CreateDirectory(path, 711);
for (int i = 0; i < MAX_LEVELS; ++i)
{
BuildPath(Path_SM, path, sizeof(path), "%s/%s", REPLAYS_PATH, g_sLevelNames[i]);
if (!DirExists(path))
CreateDirectory(path, 711);
for (int s = 0; s < numStyles; ++s)
{
BuildPath(Path_SM, path, sizeof(path), "%s/%s/%d", REPLAYS_PATH, g_sLevelNames[i], s);
if (!DirExists(path))
CreateDirectory(path, 711);
}
}
}
/**
* Adjusts convars so that bots work properly
*
* @noreturn
*/
void SetConVars()
{
ConVar cvar = FindConVar("bot_stop");
cvar.SetBool(true);
cvar = FindConVar("bot_quota");
cvar.SetInt(MAX_GHOSTS);
cvar = FindConVar("bot_quota_mode");
cvar.SetString("normal");
cvar = FindConVar("mp_autoteambalance");
cvar.SetBool(false);
cvar = FindConVar("mp_limitteams");
cvar.SetInt(0);
cvar = FindConVar("bot_join_after_player");
cvar.SetBool(false);
cvar = FindConVar("bot_chatter");
cvar.SetString("off");
cvar = FindConVar("bot_join_team");
cvar.SetString(TEAM_GHOST);
cvar = FindConVar("bot_auto_vacate");
cvar.SetBool(false);
cvar = FindConVar("bot_mimic");
cvar.SetInt(0);
cvar = FindConVar("bot_zombie");
cvar.Flags = FCVAR_GAMEDLL | FCVAR_REPLICATED;
cvar.SetBool(true);
// Fixes a crash if you spam +use to spec the custom ghost
cvar = FindConVar("sv_disablefreezecam");
cvar.SetBool(true);
}
/**
* Called when the map is loaded.
*
* @note This used to be OnServerLoad(), which is now deprecated.
* Plugins still using the old forward will work.
*/
public void OnMapStart()
{
g_fLastUsed = GetGameTime();
GetCurrentMap(g_sMapName, sizeof(g_sMapName));
CreateTimer(0.1, Timer_HudLoop, 0, TIMER_REPEAT|TIMER_FLAG_NO_MAPCHANGE);
}
/**
* Called when the map has loaded, servercfgfile (server.cfg) has been
* executed, and all plugin configs are done executing. This is the best
* place to initialize plugin functions which are based on cvar data.
*
* @note This will always be called once and only once per map. It will be
* called after OnMapStart().
*/
public void OnConfigsExecuted()
{
SetConVars();
UnloadReplays();
CacheReplays();
CreateGhosts();
}
/**
* Called right before a map ends.
*/
public void OnMapEnd()
{
RemoveGhosts();
}
/**
* Called when the plugin is about to be unloaded.
*
* It is not necessary to close any handles or remove hooks in this function.
* SourceMod guarantees that plugin shutdown automatically and correctly releases
* all resources.
*/
public void OnPluginEnd()
{
RemoveGhosts();
}
/**
* Called when a client is entering the game.
*
* Whether a client has a steamid is undefined until OnClientAuthorized
* is called, which may occur either before or after OnClientPutInServer.
* Similarly, use OnClientPostAdminCheck() if you need to verify whether
* connecting players are admins.
*
* GetClientCount() will include clients as they are passed through this
* function, as clients are already in game at this point.
*
* @param client Client index.
*/
public void OnClientPutInServer(int client)
{
if (IsFakeClient(client))
{
if (g_iNumBotsConnected == MAX_GHOSTS)
{
OnGhostsPutInServer( g_iNumBotsConnected );
}
}
else // Human
{
if (g_arrayRun[client] != null)
{
delete g_arrayRun[client];
}
g_arrayRun[client] = new ArrayList( RUNDATA_MAX );
g_bPaused[client] = true; // avoids unnecessary saving of data
}
}
/**
* Called once a client successfully connects. This callback is paired with OnClientDisconnect.
*
* @param client Client index.
*/
public void OnClientConnected(int client)
{
if (IsFakeClient(client) && !IsClientSourceTV(client))
{
++g_iNumBotsConnected;
//PrintToServer("g_iNumBotsConnected: %d", g_iNumBotsConnected);
}
}
/**
* Called when a client is disconnecting from the server.
*
* @param client Client index.
*/
public void OnClientDisconnect(int client)
{
if (IsFakeClient(client) && !IsClientSourceTV(client))
{
--g_iNumBotsConnected;
//PrintToServer("g_iNumBotsConnected: %d", g_iNumBotsConnected);
for (int i = 0; i < MAX_GHOSTS; ++i)
{
if (client == g_iGhost[i])
{
g_iGhost[i] = 0;
ResetGhost(i);
return;
}
}
}
else // Human
{
if (g_arrayRun[client] != null)
{
delete g_arrayRun[client];
g_arrayRun[client] = null;
}
}
}
/**
* Caches replays for all levels and styles on the current map so that they
* can be played back later by the ghosts.
*
* @return int The total number of replays cached.
*/
int CacheReplays()
{
int numReplays = 0;
for (int level = 0; level < MAX_LEVELS; ++level)
{
for (int style = 0; style < MAX_STYLES; ++style)
{
g_bNoRecord[level][style] = !LoadRecord(level, style);
if ( !g_bNoRecord[level][style] )
++numReplays;
}
}
return numReplays;
}
/**
* Unloads the cached replays.
*
* @return int The total number of replays unloaded.
*/
int UnloadReplays()
{
int numReplays = 0;
for (int level = 0; level < MAX_LEVELS; ++level)
{
for (int style = 0; style < MAX_STYLES; ++style)
{
if (g_arrayReplay[level][style] != null)
{
delete g_arrayReplay[level][style];
g_arrayReplay[level][style] = null;
g_bNoRecord[level][style] = true;
++numReplays;
OnReplayUnloaded(level, style);
}
}
}
return numReplays;
}
/*
* Loads a replay that is stored on the hard disk at data/ghostrecords/
*
* @param int level Main / bonus?
* @param int style Style ID
* @return bool True on success, false otherwise.
*/
bool LoadRecord(int level, int style)
{
if (level < 0 || level > MAX_LEVELS)
{
LogError("Level out of bounds: %d", level);
return false;
}
if (style < 0 || style > MAX_STYLES)
{
LogError("Style out of bounds: %d", style);
return false;
}
char path[PLATFORM_MAX_PATH];
BuildPath(Path_SM, path, sizeof(path), "%s/%s/%d/%s.meme", REPLAYS_PATH, g_sLevelNames[level], style, g_sMapName);
if (!FileExists(path))
{
return false;
}
File file = OpenFile(path, "rb");
if (file)
{
file.ReadString(g_sReplayNames[level][style], MAX_NAME_LENGTH, -1);
file.ReadInt32(view_as<int>(g_fReplayTimes[level][style]));
file.ReadInt16(g_iReplayJumps[level][style]);
if (g_arrayReplay[level][style] != null)
g_arrayReplay[level][style].Clear();
else
g_arrayReplay[level][style] = new ArrayList( RUNDATA_MAX );
int values[RUNDATA_MAX];
while (!file.EndOfFile())
{
// Read up until the weaponid since it's only 1 byte.
file.Read(values, RUNDATA_MAX-1, 4);
file.ReadInt8(values[RUNDATA_WEAPONID]);
g_arrayReplay[level][style].PushArray(values, RUNDATA_MAX);
}
file.Close();
OnReplayCached(level, style);
return true;
}
LogError("Could not open file \"%s\" for reading", path);
return false;
}
/**
* Stores a binary representation of player's rundata at data/ghostrecords/
*
* @param int client The client index
* @param float time Time of player's run
* @param int jumps Number of jumps
* @param int level Main / bonus?
* @param int style Style ID provided by the timer
* @return bool True on success, false otherwise.
*/
bool SaveRecord(int client, float time, int jumps, int level, int style)
{
if (level < 0 || level > MAX_LEVELS)
{
LogError("Level out of bounds: %d", level);
return false;
}
if (style < 0 || style > MAX_STYLES)
{
LogError("Style out of bounds: %d", style);
return false;
}
if ( !IsValidClientIndex(client) )
{
LogError("Client index out of bounds: %d", client);
return false;
}
if ( !IsClientInGame(client) )
{
LogError("Client %d is not in game", client);
return false;
}
char path[PLATFORM_MAX_PATH];
BuildPath(Path_SM, path, sizeof(path), "%s/%s/%d/%s.meme", REPLAYS_PATH, g_sLevelNames[level], style, g_sMapName);
if (FileExists(path))
{
#if defined BACKUP_REPLAYS
BackupRecord(path);
#endif
DeleteFile(path); // Kinda unnecessary? Opening the file later will truncate it.
}
File file = OpenFile(path, "wb");
if (file)
{
int size = g_arrayRun[client].Length;
if (!size)
{
LogError("Couldn't save record. Run array is empty.");
return false;
}
GetClientName(client, g_sReplayNames[level][style], MAX_NAME_LENGTH);
file.WriteString(g_sReplayNames[level][style], true);
g_fReplayTimes[level][style] = time;
file.WriteInt32(view_as<int>(time));
g_iReplayJumps[level][style] = jumps;
file.WriteInt16(jumps);
if (g_arrayReplay[level][style] != null)
g_arrayReplay[level][style].Clear();
else
g_arrayReplay[level][style] = new ArrayList( RUNDATA_MAX );
int values[RUNDATA_MAX];
for (int i = 0; i < size; ++i)
{
g_arrayRun[client].GetArray(i, values, RUNDATA_MAX);
file.Write(values, RUNDATA_MAX-1, 4);
file.WriteInt8(values[RUNDATA_WEAPONID]);
g_arrayReplay[level][style].PushArray(values, RUNDATA_MAX);
}
file.Close();
OnReplayCached(level, style);
return true;
}
LogError("Could not open the file \"%s\" for writing.", path);
return false;
}
/**
* Called whenever a recording gets cached.
*
* @param int level Main / bonus?
* @param int style Style id
* @noreturn
*/
void OnReplayCached(int level, int style)
{
g_bNoRecord[level][style] = false;
// Are any of the ghosts already replaying this record?
for (int i = 0; i < MAX_GHOSTS; ++i)
{
if (i == CUSTOM_GHOST)
continue;
if (g_iGhostLevel[i] == level && g_iGhostStyle[i] == style)
{
// Double check the ghost exists
if (IsValidClientIndex(g_iGhost[i]) && IsClientInGame(g_iGhost[i]))
{
if ( SetGhostReplay(i, level, style) )
{
StartPlayback(i, PLAYBACK_DELAY, true);
}
}
}
}
// If the custom ghost is currently replaying the old record
if ( IsValidClientIndex(g_iGhost[CUSTOM_GHOST])
&& IsClientInGame(g_iGhost[CUSTOM_GHOST])
&& IsPlayerAlive(g_iGhost[CUSTOM_GHOST])
&& g_iGhostLevel[CUSTOM_GHOST] == level
&& g_iGhostStyle[CUSTOM_GHOST] == style
&& g_iGhostFrame[CUSTOM_GHOST] != -1)
{
if ( SetGhostReplay(CUSTOM_GHOST, level, style) )
{
StartPlayback(CUSTOM_GHOST, PLAYBACK_DELAY, true);
}
}
else // Check if the custom ghost needs respawning
{
SetupCustomGhost();
}
}
/**
* Called when a cached recording gets unloaded.
*
* @param int level Main / bonus
* @param int style Style id
* @noreturn
*/
void OnReplayUnloaded(int level, int style)
{
g_bNoRecord[level][style] = true;
// Was any of the bots replaying this record before it was unloaded?
for (int i = 0; i < MAX_GHOSTS; ++i)
{
if (g_iGhostLevel[i] == level && g_iGhostStyle[i] == style)
{
ResetGhost(i);
}
}
}
/**
* Stores a backup of the old record at data/ghostrecords/
*
* @param char recordPath Path to the file to be backed up
* @noreturn
*/
void BackupRecord(char[] recordPath)
{
char sPath[PLATFORM_MAX_PATH];
FormatEx(sPath, sizeof(sPath), "%s_old", recordPath);
// Delete the last backup
if (FileExists(sPath))
{
DeleteFile(sPath);
}
RenameFile(sPath, recordPath);
}
/*
* Creates ghosts for the current map.
*
* @param int numGhosts The number of ghosts to create.
* @noreturn
*/
bool CreateGhosts(int numGhosts = MAX_GHOSTS)
{
CreateTimer(1.0, Timer_CheckIfGhostsExist, numGhosts, TIMER_FLAG_NO_MAPCHANGE|TIMER_REPEAT);
}
/**
* Kicks ghosts and resets vars.
*
* @noreturn
*/
void RemoveGhosts()
{
ConVar cvar = FindConVar("bot_quota");
cvar.SetInt(0);
ServerCommand("bot_kick");
for (int i = 0; i < MAX_GHOSTS; ++i)
{
g_iGhost[i] = 0;
ResetGhost(i);
}
}
/**
* Called when the timer interval has elapsed.
*
* @param timer Handle to the timer object.
* @param hndl Handle passed to CreateTimer() when timer was created.
* @return Plugin_Stop to stop a repeating timer, any other value for
* default behavior.
*/
public Action Timer_CheckIfGhostsExist(Handle timer, int numGhosts)
{
ConVar cvar = FindConVar("bot_quota");
if (cvar.IntValue != numGhosts)
{
cvar.SetInt(numGhosts);
return Plugin_Continue;
}
return Plugin_Stop;
}
/**
* Called when all ghosts have joined the server.
*
* @param int numGhosts The total number of ghosts that have joined the server
* @noreturn
*/
void OnGhostsPutInServer(int numGhosts)
{
CreateTimer(1.0, Timer_SetupGhosts, numGhosts, TIMER_FLAG_NO_MAPCHANGE);
}
/**
* Called when the timer interval has elapsed.
*
* @param timer Handle to the timer object.
* @param hndl Handle passed to CreateTimer() when timer was created.
* @return Plugin_Stop to stop a repeating timer, any other value for
* default behavior.
*/
public Action Timer_SetupGhosts(Handle timer, any numGhosts)
{
// Assign ghost client indexes
int ghostID = 0;
for (int i = 1; i <= MaxClients; ++i)
{
if (IsClientInGame(i) && IsFakeClient(i) && !IsClientSourceTV(i))
{
g_iGhost[ghostID] = i;
g_iGhostFrame[ghostID] = -1;
++ghostID;
SetEntProp(i, Prop_Data, "m_iFrags", 1337);
SetEntProp(i, Prop_Data, "m_iDeaths", 1337);
}
if (ghostID == numGhosts)
{
break;
}
}
if (ghostID != numGhosts)
{
return Plugin_Stop; // Couldn't find enough bots.
}
if ( SetGhostReplay(NORMAL_GHOST, 0, 0) )
{
StartPlayback(NORMAL_GHOST, PLAYBACK_DELAY);
}
// Remember initial spawn position
// The player_spawn event couldn't pick it up because
// the bots had already been spawned and no g_iGhost were assigned before that.
if ( IsPlayerAlive(g_iGhost[CUSTOM_GHOST]) )
{
RememberSpawnPoint(g_iGhost[CUSTOM_GHOST]);
}
SetupCustomGhost();
return Plugin_Stop;
}
/**
* Checks if there is an available record given the level and style passed,
* respawns the ghost if there is and binds the recording to it.
*
* @param int ghostID The ghost ID. NORMAL_GHOST / CUSTOM_GHOST
* @param int level Main / bonus?
* @param int style Style ID provided by the timer.
* @return bool True on success, false otherwise.
*/
bool SetGhostReplay(int ghostID, int level, int style)
{
if (ghostID < 0 || ghostID > MAX_GHOSTS)
{
LogError("Ghost ID out of bounds: %d", ghostID);
return false;
}
if (level < 0 || level > MAX_LEVELS)
{
LogError("Level out of bounds: %d", level);
return false;
}
if (style < 0 || style > MAX_STYLES)
{
LogError("Style out of bounds: %d", style);
return false;
}
if ( !IsValidClientIndex(g_iGhost[ghostID]) )
{
LogError("Ghost's client index is invalid.");
return false;
}
if ( !IsClientInGame(g_iGhost[ ghostID ]) )
{
LogError("The ghost appears to be not in game.");
return false;
}
if (ghostID != CUSTOM_GHOST)
{
if (g_bNoRecord[level][style])
{
// No recording found for this level and style.
ResetGhost( ghostID );
return false;
}
}
else
{
// Is there even any available record for the custom bot to replay?
if ( !IsAnyRecordAvailable() )
{
// No recordings available for the custom bot to replay.
ResetGhost( ghostID );
return false;
}
}
if (!IsPlayerAlive(g_iGhost[ ghostID ]))
{
CS_RespawnPlayer(g_iGhost[ ghostID ]);
}
else
{
ApplyGhostFX( ghostID, false );
}
// Prepare and set bot name
char time[16];
char smallName[MAX_ALLOWED_NAME];
TimerFormat(g_fReplayTimes[level][style], time, sizeof(time), true, false);
strcopy(smallName, sizeof(smallName), g_sReplayNames[level][style]);
FormatEx(g_sGhostName[ghostID], MAX_NAME_LENGTH, "%s - %s, %d Jumps", smallName, time, g_iReplayJumps[level][style]);
SetClientName(g_iGhost[ghostID], g_sGhostName[ghostID]);
// Prepare and set bot tag
if (level == 1)
FormatEx(g_sGhostClanTag[ghostID], MAX_NAME_LENGTH, "B - %s", g_sStyleTags[style]);
else
strcopy(g_sGhostClanTag[ghostID], MAX_NAME_LENGTH, g_sStyleTags[style]);
CS_SetClientClanTag(g_iGhost[ghostID], g_sGhostClanTag[ghostID]);
// Bind the recording
g_iGhostLevel[ ghostID ] = level;
g_iGhostStyle[ ghostID ] = style;
return true;
}
/**
* Sets up the custom ghost. It either becomes in a state waiting for someone to
* tell it to replay something or goes inactive and dead indicating there are
* no available records to playback.
*
* @return bool True if it's gone into an active waiting state, false otherwise.
*/
bool SetupCustomGhost()
{
if ( IsAnyRecordAvailable() )
{
if ( IsValidClientIndex(g_iGhost[CUSTOM_GHOST]) && IsClientInGame(g_iGhost[CUSTOM_GHOST]) )
{
FormatEx(g_sGhostClanTag[CUSTOM_GHOST], MAX_NAME_LENGTH, MEME);
FormatEx(g_sGhostName[CUSTOM_GHOST], MAX_NAME_LENGTH, "!replay / +use");
SetClientName(g_iGhost[CUSTOM_GHOST], g_sGhostName[CUSTOM_GHOST]);
CS_SetClientClanTag(g_iGhost[CUSTOM_GHOST], g_sGhostClanTag[CUSTOM_GHOST]);
if (!IsPlayerAlive(g_iGhost[CUSTOM_GHOST]))
{
CS_RespawnPlayer(g_iGhost[CUSTOM_GHOST]);
}
else
{
ApplyGhostFX( CUSTOM_GHOST, false );
}