]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
CRLF fixes, .gitattributes file updated
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 entity pingplreport;
2 void PingPLReport_Think()
3 {
4         float delta;
5         entity e;
6
7         delta = 3 / maxclients;
8         if(delta < sys_frametime)
9                 delta = 0;
10         self.nextthink = time + delta;
11
12         e = edict_num(self.cnt + 1);
13         if(clienttype(e) == CLIENTTYPE_REAL)
14         {
15                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
16                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
17                 WriteByte(MSG_BROADCAST, self.cnt);
18                 WriteShort(MSG_BROADCAST, max(1, e.ping));
19                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
20                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
21         }
22         else
23         {
24                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
25                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
26                 WriteByte(MSG_BROADCAST, self.cnt);
27                 WriteShort(MSG_BROADCAST, 0);
28                 WriteByte(MSG_BROADCAST, 0);
29                 WriteByte(MSG_BROADCAST, 0);
30         }
31         self.cnt = mod(self.cnt + 1, maxclients);
32 }
33 void PingPLReport_Spawn()
34 {
35         pingplreport = spawn();
36         pingplreport.classname = "pingplreport";
37         pingplreport.think = PingPLReport_Think;
38         pingplreport.nextthink = time;
39 }
40
41 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
42 string redirection_target;
43 float world_initialized;
44
45 string GetMapname();
46 string GetGametype();
47 void GotoNextMap();
48 void ShuffleMaplist()
49 float() DoNextMapOverride;
50
51 void SetDefaultAlpha()
52 {
53         if(cvar("g_running_guns"))
54         {
55                 default_player_alpha = -1;
56                 default_weapon_alpha = +1;
57         }
58         else if(g_cloaked)
59         {
60                 default_player_alpha = cvar("g_balance_cloaked_alpha");
61                 default_weapon_alpha = default_player_alpha;
62         }
63         else
64         {
65                 default_player_alpha = cvar("g_player_alpha");
66                 if(default_player_alpha == 0)
67                         default_player_alpha = 1;
68                 default_weapon_alpha = default_player_alpha;
69         }
70 }
71
72 void fteqcc_testbugs()
73 {
74         float a, b;
75
76         if(!cvar("developer_fteqccbugs"))
77                 return;
78
79         dprint("*** fteqcc test: checking for bugs...\n");
80
81         a = 1;
82         b = 5;
83         if(sqrt(a) - sqrt(b - a) == 0)
84                 dprint("*** fteqcc test: found same-function-twice bug\n");
85         else
86                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
87
88         world.cnt = -10;
89         world.enemy = world;
90         world.enemy.cnt += 10;
91         if(world.cnt > 0.2 || world.cnt < -0.2) // don't error out if it's just roundoff errors
92                 dprint("*** fteqcc test: found += bug\n");
93         else
94                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
95         world.cnt = 0;
96 }
97
98 /**
99  * Takes care of pausing and unpausing the game.
100  * Centerprints the information about an upcoming or active timeout to all active
101  * players. Also plays reminder sounds.
102  */
103 void timeoutHandler_Think() {
104         local string timeStr;
105         local entity plr;
106         if (timeoutStatus == 1) {
107                 if (remainingLeadTime > 0) {
108                         //centerprint the information to every player
109                         timeStr = getTimeoutText(0);
110                         FOR_EACH_REALCLIENT(plr) {
111                                 if(plr.classname == "player") {
112                                         centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
113                                 }
114                         }
115                         remainingLeadTime -= 1;
116                         //think again in 1 second:
117                         self.nextthink = time + 1;
118                 }
119                 else {
120                         //now pause the game:
121                         timeoutStatus = 2;
122                         //reset all the flood variables
123                         FOR_EACH_CLIENT(plr) {
124                                 plr.nickspamcount = plr.nickspamtime = plr.floodcontrol_chat = plr.floodcontrol_chatteam = plr.floodcontrol_chattell = plr.floodcontrol_voice = plr.floodcontrol_voiceteam = 0;
125                         }
126                         cvar_set("slowmo", ftos(TIMEOUT_SLOWMO_VALUE));
127                         //copy .v_angle to .lastV_angle for every player in order to fix their view during pause (see PlayerPreThink)
128                         FOR_EACH_REALPLAYER(plr) {
129                                 plr.lastV_angle = plr.v_angle;
130                         }
131                         self.nextthink = time;
132                 }
133         }
134         else if (timeoutStatus == 2) {
135                 if (remainingTimeoutTime > 0) {
136                         timeStr = getTimeoutText(0);
137                         FOR_EACH_REALCLIENT(plr) {
138                                 if(plr.classname == "player") {
139                                         centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
140                                 }
141                         }
142                         if(remainingTimeoutTime == cvar("sv_timeout_resumetime")) { //play a warning sound when only <sv_timeout_resumetime> seconds are left
143                                 Announce("prepareforbattle");
144                         }
145                         remainingTimeoutTime -= 1;
146                         self.nextthink = time + TIMEOUT_SLOWMO_VALUE;
147                 }
148                 else {
149                         //unpause the game again
150                         remainingTimeoutTime = timeoutStatus = 0;
151                         cvar_set("slowmo", ftos(orig_slowmo));
152                         //and unlock the fixed view again once there is no timeout active anymore
153                         FOR_EACH_REALPLAYER(plr) {
154                                 plr.fixangle = FALSE;
155                         }
156                         //get rid of the countdown message
157                         FOR_EACH_REALCLIENT(plr) {
158                                 if(plr.classname == "player") {
159                                         centerprint_atprio(plr, CENTERPRIO_SPAM, "");
160                                 }
161                         }
162                         remove(self);
163                         return;
164                 }
165
166         }
167         else if (timeoutStatus == 0) { //if a player called the resumegame command (which set timeoutStatus to 0 already)
168                 FOR_EACH_REALCLIENT(plr) {
169                         if(plr.classname == "player") {
170                                 centerprint_atprio(plr, CENTERPRIO_SPAM, "");
171                         }
172                 }
173                 remove(self);
174                 return;
175         }
176 }
177
178 void GotoFirstMap()
179 {
180         float n;
181         if(cvar("_sv_init"))
182         {
183                 // cvar_set("_sv_init", "0");
184                 // we do NOT set this to 0 any more, so someone "accidentally" changing
185                 // to this "init" map on a dedicated server will cause no permanent
186                 // harm
187                 if(cvar("g_maplist_shuffle"))
188                         ShuffleMaplist();
189                 n = tokenizebyseparator(cvar_string("g_maplist"), " ");
190                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
191
192                 MapInfo_Enumerate();
193                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
194
195                 if(!DoNextMapOverride())
196                         GotoNextMap();
197
198                 return;
199         }
200
201         if(time < 5)
202         {
203                 self.nextthink = time;
204         }
205         else
206         {
207                 self.nextthink = time + 1;
208                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
209         }
210 }
211
212 void cvar_changes_init()
213 {
214         float h;
215         string k, v, d;
216         float n, i;
217
218         if(cvar_changes)
219                 strunzone(cvar_changes);
220         cvar_changes = string_null;
221
222         h = buf_create();
223         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
224         n = buf_getsize(h);
225
226         for(i = 0; i < n; ++i)
227         {
228                 k = bufstr_get(h, i);
229
230 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
231 #define BADCVAR(p) if(k == p) continue
232                 // internal
233                 BADPREFIX("csqc_");
234                 BADPREFIX("cvar_check_");
235                 BADCVAR("gamecfg");
236                 BADCVAR("g_configversion");
237                 BADCVAR("g_maplist_index");
238                 BADCVAR("halflifebsp");
239
240                 // client
241                 BADPREFIX("cl_");
242                 BADPREFIX("con_");
243                 BADPREFIX("g_campaign");
244                 BADPREFIX("gl_");
245                 BADPREFIX("joy");
246                 BADPREFIX("menu_");
247                 BADPREFIX("net_slist_");
248                 BADPREFIX("r_");
249                 BADPREFIX("sbar_");
250                 BADPREFIX("scr_");
251                 BADPREFIX("userbind");
252                 BADPREFIX("v_");
253                 BADPREFIX("vid_");
254                 BADPREFIX("crosshair");
255                 BADCVAR("mod_q3bsp_lightmapmergepower");
256                 BADCVAR("mod_q3bsp_nolightmaps");
257
258                 // private
259                 BADCVAR("serverconfig");
260                 BADPREFIX("g_ban_");
261                 BADPREFIX("g_chat_flood_");
262                 BADPREFIX("g_voice_flood_");
263                 BADPREFIX("rcon_");
264                 BADPREFIX("settemp_");
265                 BADPREFIX("sv_allowdownloads_");
266                 BADPREFIX("sv_autodemo");
267                 BADPREFIX("sv_curl_");
268                 BADPREFIX("sv_eventlog");
269                 BADPREFIX("sv_logscores_");
270                 BADPREFIX("sv_master");
271                 BADCVAR("g_banned_list");
272                 BADCVAR("log_dest_udp");
273                 BADCVAR("log_file");
274                 BADCVAR("net_address");
275                 BADCVAR("port");
276                 BADCVAR("savedgamecfg");
277                 BADCVAR("sv_heartbeatperiod");
278                 BADCVAR("sv_vote_master_password");
279                 BADCVAR("sys_colortranslation");
280                 BADCVAR("sys_specialcharactertranslation");
281                 BADCVAR("timestamps");
282
283                 // mapinfo
284                 BADCVAR("timelimit");
285                 BADCVAR("fraglimit");
286                 BADCVAR("g_arena");
287                 BADCVAR("g_ca");
288                 BADCVAR("g_assault");
289                 BADCVAR("g_ctf");
290                 BADCVAR("g_dm");
291                 BADCVAR("g_domination");
292                 BADCVAR("g_keyhunt");
293                 BADCVAR("g_keyhunt_teams");
294                 BADCVAR("g_onslaught");
295                 BADCVAR("g_race");
296                 BADCVAR("g_cts");
297                 BADCVAR("g_runematch");
298                 BADCVAR("g_tdm");
299                 BADCVAR("g_nexball");
300                 BADCVAR("teamplay");
301
302                 // long
303                 BADCVAR("hostname");
304                 BADCVAR("g_maplist");
305                 BADCVAR("g_maplist_mostrecent");
306                 BADCVAR("sv_motd");
307 #undef BADPREFIX
308 #undef BADCVAR
309
310                 v = cvar_string(k);
311                 d = cvar_defstring(k);
312                 if(v != d)
313                 {
314                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
315                         if(strlen(cvar_changes) > 16384)
316                         {
317                                 cvar_changes = "// too many settings have been changed to show them here\n";
318                                 break;
319                         }
320                 }
321         }
322         buf_del(h);
323         if(cvar_changes == "")
324                 cvar_changes = "// this server runs at default settings\n";
325         else
326                 cvar_changes = strcat("// this server runs at modified settings:\n", cvar_changes);
327         cvar_changes = strzone(cvar_changes);
328 }
329
330 void detect_maptype()
331 {
332 #if 0
333         vector o, v;
334         float i;
335
336         for(;;)
337         {
338                 o = world.mins;
339                 o_x += random() * (world.maxs_x - world.mins_x);
340                 o_y += random() * (world.maxs_y - world.mins_y);
341                 o_z += random() * (world.maxs_z - world.mins_z);
342
343                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
344                 if(trace_fraction == 1)
345                         continue;
346
347                 v = trace_endpos;
348
349                 for(i = 0; i < 64; i += 4)
350                 {
351                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
352         if(trace_fraction == 1)
353                 continue;
354                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
355                 }
356
357                 break;
358         }
359 #endif
360 }
361
362 entity randomseed;
363 float RandomSeed_Send(entity to, float sf)
364 {
365         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
366         WriteShort(MSG_ENTITY, self.cnt);
367         return TRUE;
368 }
369 void RandomSeed_Think()
370 {
371         self.cnt = bound(0, floor(random() * 65536), 65535);
372         self.nextthink = time + 5;
373
374         self.SendFlags |= 1;
375 }
376 void RandomSeed_Spawn()
377 {
378         randomseed = spawn();
379         randomseed.think = RandomSeed_Think;
380         Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
381
382         entity oldself;
383         oldself = self;
384         self = randomseed;
385         self.think(); // sets random seed and nextthink
386         self = oldself;
387 }
388
389 void spawnfunc___init_dedicated_server(void)
390 {
391         // handler for _init/_init map (only for dedicated server initialization)
392
393         world_initialized = -1; // don't complain
394         cvar = cvar_normal;
395         cvar_string = cvar_string_normal;
396         cvar_set = cvar_set_normal;
397
398         remove = remove_unsafely;
399
400         entity e;
401         e = spawn();
402         e.think = GotoFirstMap;
403         e.nextthink = time; // this is usually 1 at this point
404
405         e = spawn();
406         e.classname = "info_player_deathmatch"; // safeguard against player joining
407
408         self.classname = "worldspawn"; // safeguard against various stuff ;)
409
410         MapInfo_Enumerate();
411         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
412 }
413
414 void Map_MarkAsRecent(string m);
415 float world_already_spawned;
416 void RegisterWeapons();
417 void Nagger_Init();
418 void ClientInit_Spawn();
419 void WeaponStats_Init();
420 void WeaponStats_Shutdown();
421 void spawnfunc_worldspawn (void)
422 {
423         float fd, l, i, j, n;
424         string s, col;
425
426         cvar = cvar_normal;
427         cvar_string = cvar_string_normal;
428         cvar_set = cvar_set_normal;
429
430         if(world_already_spawned)
431                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
432         world_already_spawned = TRUE;
433
434         remove = remove_safely; // during spawning, watch what you remove!
435
436         check_unacceptable_compiler_bugs();
437
438         compressShortVector_init();
439
440         local entity head;
441         head = nextent(world);
442         maxclients = 0;
443         while(head)
444         {
445                 ++maxclients;
446                 head = nextent(head);
447         }
448
449         // needs to be done so early as they would still spawn
450         RegisterWeapons();
451
452         ServerProgsDB = db_load("server.db");
453
454         TemporaryDB = db_create();
455
456         /*
457         TODO sound pack system
458         // initialize sound pack system
459         soundpack = cvar_string("g_soundpack");
460         if(soundpack != "")
461                 soundpack = strcat(soundpack, "/");
462         soundpack = strzone(soundpack);
463         */
464
465         // 0 normal
466         lightstyle(0, "m");
467
468         // 1 FLICKER (first variety)
469         lightstyle(1, "mmnmmommommnonmmonqnmmo");
470
471         // 2 SLOW STRONG PULSE
472         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
473
474         // 3 CANDLE (first variety)
475         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
476
477         // 4 FAST STROBE
478         lightstyle(4, "mamamamamama");
479
480         // 5 GENTLE PULSE 1
481         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
482
483         // 6 FLICKER (second variety)
484         lightstyle(6, "nmonqnmomnmomomno");
485
486         // 7 CANDLE (second variety)
487         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
488
489         // 8 CANDLE (third variety)
490         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
491
492         // 9 SLOW STROBE (fourth variety)
493         lightstyle(9, "aaaaaaaazzzzzzzz");
494
495         // 10 FLUORESCENT FLICKER
496         lightstyle(10, "mmamammmmammamamaaamammma");
497
498         // 11 SLOW PULSE NOT FADE TO BLACK
499         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
500
501         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
502
503         // 63 testing
504         lightstyle(63, "a");
505
506         if(cvar("g_campaign"))
507                 CampaignPreInit();
508
509         Map_MarkAsRecent(mapname);
510
511         precache_model ("null"); // we need this one before InitGameplayMode
512         InitGameplayMode();
513         readlevelcvars();
514         GrappleHookInit();
515         ElectroInit();
516
517         player_count = 0;
518         bot_waypoints_for_items = cvar("g_waypoints_for_items");
519         if(bot_waypoints_for_items == 1)
520                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
521                         bot_waypoints_for_items = 0;
522
523         // for setting by mapinfo
524         q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
525         cvar_set("sv_q3acompat_machineshotgunswap", "0");
526
527         precache();
528
529         WaypointSprite_Init();
530
531         //if (g_domination)
532         //      dom_init();
533
534         GameLogInit(); // prepare everything
535         if(cvar("sv_eventlog"))
536         {
537                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
538                 s = strcat(s, ftos(random()));
539                 matchid = strzone(s);
540
541                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
542                 s = ":gameinfo:mutators:LIST";
543
544                 ret_string = s;
545                 MUTATOR_CALLHOOK(BuildMutatorsString);
546                 s = ret_string;
547
548                 if(cvar("g_grappling_hook"))
549                         s = strcat(s, ":grappling_hook");
550                 if(!cvar("g_use_ammunition"))
551                         s = strcat(s, ":no_use_ammunition");
552                 if(!cvar("g_pickup_items"))
553                         s = strcat(s, ":no_pickup_items");
554                 if(cvar_string("g_weaponarena") != "0")
555                         s = strcat(s, ":", cvar_string("g_weaponarena"), " arena");
556                 if(cvar("g_vampire"))
557                         s = strcat(s, ":vampire");
558                 if(cvar("g_laserguided_missile"))
559                         s = strcat(s, ":laserguided_missile");
560                 if(cvar("g_norecoil"))
561                         s = strcat(s, ":norecoil");
562                 if(cvar("g_midair"))
563                         s = strcat(s, ":midair");
564                 if(cvar("g_minstagib"))
565                         s = strcat(s, ":minstagib");
566                 GameLogEcho(s);
567                 GameLogEcho(":gameinfo:end");
568         }
569         else
570                 matchid = strzone(ftos(random()));
571
572         cvar_set("nextmap", "");
573
574         SetDefaultAlpha();
575
576         if(cvar("g_campaign"))
577                 CampaignPostInit();
578
579         fteqcc_testbugs();
580
581         Ban_LoadBans();
582
583         MapInfo_Enumerate();
584         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
585
586         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
587         {
588                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
589                 if(fd != -1)
590                 {
591                         while((s = fgets(fd)))
592                         {
593                                 l = tokenize_console(s);
594                                 if(l < 2)
595                                         continue;
596                                 if(argv(0) == "cd")
597                                 {
598                                         print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
599                                         print("  cdtrack ", argv(2), "\n");
600                                 }
601                                 else if(argv(0) == "fog")
602                                 {
603                                         print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
604                                         print("  \"fog\" \"", s, "\"\n");
605                                 }
606                                 else if(argv(0) == "set")
607                                 {
608                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
609                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
610                                 }
611                                 else if(argv(0) != "//")
612                                 {
613                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
614                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
615                                 }
616                         }
617                         fclose(fd);
618                 }
619         }
620
621         WeaponStats_Init();
622
623         addstat(STAT_WEAPONS, AS_INT, weapons);
624         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
625         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
626         addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
627         Nagger_Init();
628
629         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
630         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
631         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
632         addstat(STAT_FUEL, AS_INT, ammo_fuel);
633         addstat(STAT_DAMAGE_HITS, AS_INT, stat_hit);
634         addstat(STAT_DAMAGE_FIRED, AS_INT, stat_fired);
635         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
636         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
637         addstat(STAT_BULLETS_LOADED, AS_INT, campingrifle_bulletcounter);
638
639         // g_movementspeed hack
640         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
641         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
642         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
643
644         next_pingtime = time + 5;
645         InitializeEntity(self, cvar_changes_init, INITPRIO_CVARS);
646
647         detect_maptype();
648
649         lsmaps_reply = "^7Maps available: ";
650         lsnewmaps_reply = "^7Maps without a record set: ";
651         for(i = 0, j = 0; i < MapInfo_count; ++i)
652         {
653                 if(MapInfo_Get_ByID(i))
654                         if not(MapInfo_Map_flags & (MAPINFO_FLAG_HIDDEN | MAPINFO_FLAG_FORBIDDEN))
655                         {
656                                 if(mod(i, 2))
657                                         col = "^2";
658                                 else
659                                         col = "^3";
660                                 ++j;
661                                 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
662                                 if(g_race && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, RACE_RECORD, "time"))))
663                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
664                                 else if(g_cts && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, CTS_RECORD, "time"))))
665                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
666                         }
667         }
668         lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
669         if (!g_race && !g_cts)
670                 lsnewmaps_reply = "Need to be playing race or CTS for lsnewmaps to work.";
671         lsnewmaps_reply = strzone(strcat(lsnewmaps_reply, "\n"));
672
673         maplist_reply = "^7Maps in list: ";
674         n = tokenize_console(cvar_string("g_maplist"));
675         for(i = 0, j = 0; i < n; ++i)
676         {
677                 if(MapInfo_CheckMap(argv(i)))
678                 {
679                         if(mod(j, 2))
680                                 col = "^2";
681                         else
682                                 col = "^3";
683                         maplist_reply = strcat(maplist_reply, col, argv(i), " ");
684                         ++j;
685                 }
686         }
687         maplist_reply = strzone(strcat(maplist_reply, "\n"));
688         MapInfo_ClearTemps();
689
690         for(i = 0; i < 10; ++i)
691         {
692                 records_reply[i] = strzone(getrecords(i));
693         }
694
695         rankings_reply = strzone(getrankings());
696
697         ClientInit_Spawn();
698         RandomSeed_Spawn();
699         PingPLReport_Spawn();
700
701         CheatInit();
702
703         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
704
705         world_initialized = 1;
706 }
707
708 void spawnfunc_light (void)
709 {
710         //makestatic (self); // Who the f___ did that?
711         remove(self);
712 }
713
714 float TryFile( string pFilename )
715 {
716         local float lHandle;
717         dprint("TryFile(\"", pFilename, "\")\n");
718         lHandle = fopen( pFilename, FILE_READ );
719         if( lHandle != -1 ) {
720                 fclose( lHandle );
721                 return TRUE;
722         } else {
723                 return FALSE;
724         }
725 };
726
727 string GetGametype()
728 {
729         return GametypeNameFromType(game);
730 }
731
732 string getmapname_stored;
733 string GetMapname()
734 {
735         return mapname;
736 }
737
738 float Map_Count, Map_Current;
739 string Map_Current_Name;
740
741 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
742 float GetMaplistPosition()
743 {
744         float pos, idx;
745         string map;
746
747         map = GetMapname();
748         idx = cvar("g_maplist_index");
749
750         if(idx >= 0)
751                 if(idx < Map_Count)
752                         if(map == argv(idx))
753                                 return idx;
754
755         for(pos = 0; pos < Map_Count; ++pos)
756                 if(map == argv(pos))
757                         return pos;
758
759         // resume normal maplist rotation if current map is not in g_maplist
760         return idx;
761 }
762
763 float MapHasRightSize(string map)
764 {
765         float fh;
766         if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
767         if(cvar("g_maplist_check_waypoints"))
768         {
769                 dprint("checkwp "); dprint(map);
770                 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
771                 if(fh < 0)
772                 {
773                         dprint(": no waypoints\n");
774                         return FALSE;
775                 }
776                 dprint(": has waypoints\n");
777                 fclose(fh);
778         }
779
780         // open map size restriction file
781         dprint("opensize "); dprint(map);
782         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
783         if(fh >= 0)
784         {
785                 float mapmin, mapmax;
786                 dprint(": ok, ");
787                 mapmin = stof(fgets(fh));
788                 mapmax = stof(fgets(fh));
789                 fclose(fh);
790                 if(player_count < mapmin)
791                 {
792                         dprint("not enough\n");
793                         return FALSE;
794                 }
795                 if(player_count > mapmax)
796                 {
797                         dprint("too many\n");
798                         return FALSE;
799                 }
800                 dprint("right size\n");
801                 return TRUE;
802         }
803         dprint(": not found\n");
804         return TRUE;
805 }
806
807 string Map_Filename(float position)
808 {
809         return strcat("maps/", argv(position), ".bsp");
810 }
811
812 string strwords(string s, float w)
813 {
814         float endpos;
815         for(endpos = 0; w && endpos >= 0; --w)
816                 endpos = strstrofs(s, " ", endpos + 1);
817         if(endpos < 0)
818                 return s;
819         else
820                 return substring(s, 0, endpos);
821 }
822
823 float strhasword(string s, string w)
824 {
825         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
826 }
827
828 void Map_MarkAsRecent(string m)
829 {
830         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), max(0, cvar("g_maplist_mostrecent_count"))));
831 }
832
833 float Map_IsRecent(string m)
834 {
835         return strhasword(cvar_string("g_maplist_mostrecent"), m);
836 }
837
838 float Map_Check(float position, float pass)
839 {
840         string filename;
841         string map_next;
842         map_next = argv(position);
843         if(pass <= 1)
844         {
845                 if(Map_IsRecent(map_next))
846                         return 0;
847         }
848         filename = Map_Filename(position);
849         if(MapInfo_CheckMap(map_next))
850         {
851                 if(pass == 2)
852                         return 1;
853                 if(MapHasRightSize(map_next))
854                         return 1;
855                 return 0;
856         }
857         else
858                 dprint( "Couldn't select '", filename, "'..\n" );
859
860         return 0;
861 }
862
863 void Map_Goto_SetStr(string nextmapname)
864 {
865         if(getmapname_stored != "")
866                 strunzone(getmapname_stored);
867         if(nextmapname == "")
868                 getmapname_stored = "";
869         else
870                 getmapname_stored = strzone(nextmapname);
871 }
872
873 void Map_Goto_SetFloat(float position)
874 {
875         cvar_set("g_maplist_index", ftos(position));
876         Map_Goto_SetStr(argv(position));
877 }
878
879 void GameResetCfg()
880 {
881         // settings persist, except...
882         localcmd("\nsettemp_restore\n");
883 };
884
885 void Map_Goto()
886 {
887         GameResetCfg();
888         MapInfo_LoadMap(getmapname_stored);
889 }
890
891 // return codes of map selectors:
892 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
893 //   -2 = permanent failure
894 float() MaplistMethod_Iterate = // usual method
895 {
896         float pass, i;
897
898         for(pass = 1; pass <= 2; ++pass)
899         {
900                 for(i = 1; i < Map_Count; ++i)
901                 {
902                         float mapindex;
903                         mapindex = mod(i + Map_Current, Map_Count);
904                         if(Map_Check(mapindex, pass))
905                                 return mapindex;
906                 }
907         }
908         return -1;
909 }
910
911 float() MaplistMethod_Repeat = // fallback method
912 {
913         if(Map_Check(Map_Current, 2))
914                 return Map_Current;
915         return -2;
916 }
917
918 float() MaplistMethod_Random = // random map selection
919 {
920         float i, imax;
921
922         imax = 42;
923
924         for(i = 0; i <= imax; ++i)
925         {
926                 float mapindex;
927                 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
928                 if(Map_Check(mapindex, 1))
929                         return mapindex;
930         }
931         return -1;
932 }
933
934 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
935 // the exponent sets a bias on the map selection:
936 // the higher the exponent, the less likely "shortly repeated" same maps are
937 {
938         float i, j, imax, insertpos;
939
940         imax = 42;
941
942         for(i = 0; i <= imax; ++i)
943         {
944                 string newlist;
945
946                 // now reinsert this at another position
947                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
948                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
949                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
950                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
951
952                 // insert the current map there
953                 newlist = "";
954                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
955                         newlist = strcat(newlist, " ", argv(j));
956                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
957                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
958                         newlist = strcat(newlist, " ", argv(j));
959                 newlist = substring(newlist, 1, strlen(newlist) - 1);
960                 cvar_set("g_maplist", newlist);
961                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
962
963                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
964                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
965                 if(Map_Check(Map_Current, 1))
966                         return Map_Current;
967         }
968         return -1;
969 }
970
971 void Maplist_Init()
972 {
973         Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
974         if(Map_Count == 0)
975         {
976                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
977                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
978                 if(cvar("g_maplist_shuffle"))
979                         ShuffleMaplist();
980                 localcmd("\nmenu_cmd sync\n");
981                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
982         }
983         if(Map_Count == 0)
984                 error("empty maplist, cannot select a new map");
985         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
986
987         if(Map_Current_Name)
988                 strunzone(Map_Current_Name);
989         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
990         // this may or may not be correct, but who cares, in the worst case a map
991         // isn't chosen in the first pass that should have been
992 }
993
994 string GetNextMap()
995 {
996         float nextMap;
997
998         Maplist_Init();
999         nextMap = -1;
1000
1001         if(nextMap == -1)
1002                 if(cvar("g_maplist_shuffle") > 0)
1003                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
1004
1005         if(nextMap == -1)
1006                 if(cvar("g_maplist_selectrandom"))
1007                         nextMap = MaplistMethod_Random();
1008
1009         if(nextMap == -1)
1010                 nextMap = MaplistMethod_Iterate();
1011
1012         if(nextMap == -1)
1013                 nextMap = MaplistMethod_Repeat();
1014
1015         if(nextMap >= 0)
1016         {
1017                 Map_Goto_SetFloat(nextMap);
1018                 return getmapname_stored;
1019         }
1020
1021         return "";
1022 };
1023
1024 float DoNextMapOverride()
1025 {
1026         if(cvar("g_campaign"))
1027         {
1028                 CampaignPostIntermission();
1029                 alreadychangedlevel = TRUE;
1030                 return TRUE;
1031         }
1032         if(cvar("quit_when_empty"))
1033         {
1034                 if(player_count <= currentbots)
1035                 {
1036                         localcmd("quit\n");
1037                         alreadychangedlevel = TRUE;
1038                         return TRUE;
1039                 }
1040         }
1041         if(cvar_string("quit_and_redirect") != "")
1042         {
1043                 redirection_target = strzone(cvar_string("quit_and_redirect"));
1044                 alreadychangedlevel = TRUE;
1045                 return TRUE;
1046         }
1047         if (cvar("samelevel")) // if samelevel is set, stay on same level
1048         {
1049                 // this does not work because it tries to exec maps/nexdm01.mapcfg (which doesn't exist, it should be trying maps/dm_nexdm01.mapcfg for example)
1050                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
1051                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
1052                 localcmd("restart\n");
1053                 //changelevel (mapname);
1054                 alreadychangedlevel = TRUE;
1055                 return TRUE;
1056         }
1057         if(cvar_string("nextmap") != "")
1058                 if(MapInfo_CheckMap(cvar_string("nextmap")))
1059                 {
1060                         Map_Goto_SetStr(cvar_string("nextmap"));
1061                         Map_Goto();
1062                         alreadychangedlevel = TRUE;
1063                         return TRUE;
1064                 }
1065         if(cvar("lastlevel"))
1066         {
1067                 GameResetCfg();
1068                 localcmd("set lastlevel 0\ntogglemenu\n");
1069                 alreadychangedlevel = TRUE;
1070                 return TRUE;
1071         }
1072         return FALSE;
1073 };
1074
1075 void GotoNextMap()
1076 {
1077         //local string nextmap;
1078         //local float n, nummaps;
1079         //local string s;
1080         if (alreadychangedlevel)
1081                 return;
1082         alreadychangedlevel = TRUE;
1083
1084         {
1085                 string nextMap;
1086                 float allowReset;
1087
1088                 for(allowReset = 1; allowReset >= 0; --allowReset)
1089                 {
1090                         nextMap = GetNextMap();
1091                         if(nextMap != "")
1092                                 break;
1093
1094                         if(allowReset)
1095                         {
1096                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1097                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1098                                 if(cvar("g_maplist_shuffle"))
1099                                         ShuffleMaplist();
1100                                 localcmd("\nmenu_cmd sync\n");
1101                         }
1102                         else
1103                         {
1104                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1105                         }
1106                 }
1107                 Map_Goto();
1108         }
1109 };
1110
1111
1112 /*
1113 ============
1114 IntermissionThink
1115
1116 When the player presses attack or jump, change to the next level
1117 ============
1118 */
1119 .float autoscreenshot;
1120 void() MapVote_Start;
1121 void() MapVote_Think;
1122 float mapvote_initialized;
1123 void IntermissionThink()
1124 {
1125         FixIntermissionClient(self);
1126
1127         if(cvar("sv_autoscreenshot"))
1128         if(self.autoscreenshot > 0)
1129         if(time > self.autoscreenshot)
1130         {
1131                 self.autoscreenshot = -1;
1132                 if(clienttype(self) == CLIENTTYPE_REAL)
1133                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
1134                 return;
1135         }
1136
1137         if (time < intermission_exittime)
1138                 return;
1139
1140         if(!mapvote_initialized)
1141                 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
1142                         return;
1143
1144         MapVote_Start();
1145 };
1146
1147 /*
1148 ============
1149 FindIntermission
1150
1151 Returns the entity to view from
1152 ============
1153 */
1154 /*
1155 entity FindIntermission()
1156 {
1157         local   entity spot;
1158         local   float cyc;
1159
1160 // look for info_intermission first
1161         spot = find (world, classname, "info_intermission");
1162         if (spot)
1163         {       // pick a random one
1164                 cyc = random() * 4;
1165                 while (cyc > 1)
1166                 {
1167                         spot = find (spot, classname, "info_intermission");
1168                         if (!spot)
1169                                 spot = find (spot, classname, "info_intermission");
1170                         cyc = cyc - 1;
1171                 }
1172                 return spot;
1173         }
1174
1175 // then look for the start position
1176         spot = find (world, classname, "info_player_start");
1177         if (spot)
1178                 return spot;
1179
1180 // testinfo_player_start is only found in regioned levels
1181         spot = find (world, classname, "testplayerstart");
1182         if (spot)
1183                 return spot;
1184
1185 // then look for the start position
1186         spot = find (world, classname, "info_player_deathmatch");
1187         if (spot)
1188                 return spot;
1189
1190         //objerror ("FindIntermission: no spot");
1191         return world;
1192 };
1193 */
1194
1195 /*
1196 ===============================================================================
1197
1198 RULES
1199
1200 ===============================================================================
1201 */
1202
1203 void DumpStats(float final)
1204 {
1205         local float file;
1206         local string s;
1207         local float to_console;
1208         local float to_eventlog;
1209         local float to_file;
1210         local float i;
1211
1212         to_console = cvar("sv_logscores_console");
1213         to_eventlog = cvar("sv_eventlog");
1214         to_file = cvar("sv_logscores_file");
1215
1216         if(!final)
1217         {
1218                 to_console = TRUE; // always print printstats replies
1219                 to_eventlog = FALSE; // but never print them to the event log
1220         }
1221
1222         if(to_eventlog)
1223                 if(cvar("sv_eventlog_console"))
1224                         to_console = FALSE; // otherwise we get the output twice
1225
1226         if(final)
1227                 s = ":scores:";
1228         else
1229                 s = ":status:";
1230         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1231
1232         if(to_console)
1233                 print(s, "\n");
1234         if(to_eventlog)
1235                 GameLogEcho(s);
1236         if(to_file)
1237         {
1238                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
1239                 if(file == -1)
1240                         to_file = FALSE;
1241                 else
1242                         fputs(file, strcat(s, "\n"));
1243         }
1244
1245         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1246         if(to_console)
1247                 print(s, "\n");
1248         if(to_eventlog)
1249                 GameLogEcho(s);
1250         if(to_file)
1251                 fputs(file, strcat(s, "\n"));
1252
1253         FOR_EACH_CLIENT(other)
1254         {
1255                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
1256                 {
1257                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1258                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1259                         if(other.classname == "player" || g_arena || g_ca || g_lms)
1260                                 s = strcat(s, ftos(other.team), ":");
1261                         else
1262                                 s = strcat(s, "spectator:");
1263
1264                         if(to_console)
1265                                 print(s, other.netname, "\n");
1266                         if(to_eventlog)
1267                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1268                         if(to_file)
1269                                 fputs(file, strcat(s, other.netname, "\n"));
1270                 }
1271         }
1272
1273         if(teams_matter)
1274         {
1275                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1276                 if(to_console)
1277                         print(s, "\n");
1278                 if(to_eventlog)
1279                         GameLogEcho(s);
1280                 if(to_file)
1281                         fputs(file, strcat(s, "\n"));
1282
1283                 for(i = 1; i < 16; ++i)
1284                 {
1285                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1286                         s = strcat(s, ":", ftos(i));
1287                         if(to_console)
1288                                 print(s, "\n");
1289                         if(to_eventlog)
1290                                 GameLogEcho(s);
1291                         if(to_file)
1292                                 fputs(file, strcat(s, "\n"));
1293                 }
1294         }
1295
1296         if(to_console)
1297                 print(":end\n");
1298         if(to_eventlog)
1299                 GameLogEcho(":end");
1300         if(to_file)
1301         {
1302                 fputs(file, ":end\n");
1303                 fclose(file);
1304         }
1305 }
1306
1307 void FixIntermissionClient(entity e)
1308 {
1309         string s;
1310         if(!e.autoscreenshot) // initial call
1311         {
1312                 e.angles = e.v_angle;
1313                 e.angles_x = -e.angles_x;
1314                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1315                 e.health = -2342;
1316                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1317                 e.solid = SOLID_NOT;
1318                 e.movetype = MOVETYPE_NONE;
1319                 e.takedamage = DAMAGE_NO;
1320                 if(e.weaponentity)
1321                 {
1322                         e.weaponentity.effects = EF_NODRAW;
1323                         if (e.weaponentity.weaponentity)
1324                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1325                 }
1326                 if(clienttype(e) == CLIENTTYPE_REAL)
1327                 {
1328                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1329                         s = cvar_string("sv_intermission_cdtrack");
1330                         if(s != "")
1331                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1332                         msg_entity = e;
1333                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1334                 }
1335         }
1336
1337         //e.velocity = '0 0 0';
1338         //e.fixangle = TRUE;
1339
1340         // TODO halt weapon animation
1341 }
1342
1343
1344 /*
1345 go to the next level for deathmatch
1346 only called if a time or frag limit has expired
1347 */
1348 void NextLevel()
1349 {
1350         float i;
1351
1352         gameover = TRUE;
1353
1354         intermission_running = 1;
1355
1356 // enforce a wait time before allowing changelevel
1357         if(player_count > 0)
1358                 intermission_exittime = time + cvar("sv_mapchange_delay");
1359         else
1360                 intermission_exittime = -1;
1361
1362         /*
1363         WriteByte (MSG_ALL, SVC_CDTRACK);
1364         WriteByte (MSG_ALL, 3);
1365         WriteByte (MSG_ALL, 3);
1366         // done in FixIntermission
1367         */
1368
1369         //pos = FindIntermission ();
1370
1371         VoteReset();
1372
1373         DumpStats(TRUE);
1374
1375         if(cvar("sv_eventlog"))
1376                 GameLogEcho(":gameover");
1377
1378         GameLogClose();
1379
1380 // TO DO
1381
1382 // save the stats to a text file on the client
1383 // stuffcmd(other, log_stats "stats/file_name");
1384 // bprint stats
1385 // stuffcmd(other, log_stats "");
1386 // use a filename similar to the demo name
1387         // string file_name;
1388         // file_name = strcat("\nlog_file \"stats/", strftime(TRUE, "%Y-%m-%d_%H-%M"), "_", mapname, ".txt\"");  // open the log file
1389
1390 // write a stats parser for the menu
1391
1392         if(cvar("sv_accuracy_data_send")) {
1393                 string stats_to_send;
1394
1395                 FOR_EACH_CLIENT(other) {  // make the string to send
1396                         FixIntermissionClient(other);
1397
1398                         if(other.cvar_cl_accuracy_data_share) {
1399                                 stats_to_send = strcat(stats_to_send, ":hits:", other.netname);
1400
1401                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1402                                         stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_hit[i-1]));
1403
1404                                 stats_to_send = strcat(stats_to_send, "\n:fired:", other.netname);
1405
1406                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1407                                         stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_fired[i-1]));
1408
1409                                 stats_to_send = strcat(stats_to_send, "\n");
1410                         }
1411                 }
1412
1413                 FOR_EACH_REALCLIENT(other) {  // only spam humans
1414                         Score_NicePrint(other);  // print the score
1415
1416                         if(other.cvar_cl_accuracy_data_receive)  // send the stats string to all the willing clients
1417                                 bprint(stats_to_send);
1418                 }
1419         } else { // ye olde message
1420                 FOR_EACH_PLAYER(other) {
1421                         FixIntermissionClient(other);
1422
1423                         if(other.winning)
1424                                 bprint(other.netname, " ^7wins.\n");
1425                 }
1426         }
1427
1428         if(cvar("g_campaign"))
1429                 CampaignPreIntermission();
1430
1431         localcmd("\nsv_hook_gameend\n");
1432 }
1433
1434 /*
1435 ============
1436 CheckRules_Player
1437
1438 Exit deathmatch games upon conditions
1439 ============
1440 */
1441 void CheckRules_Player()
1442 {
1443         if (gameover)   // someone else quit the game already
1444                 return;
1445
1446         if(self.deadflag == DEAD_NO)
1447                 self.play_time += frametime;
1448
1449         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1450         //   (div0: and that in CheckRules_World please)
1451 };
1452
1453 float checkrules_equality;
1454 float checkrules_suddendeathwarning;
1455 float checkrules_suddendeathend;
1456 float checkrules_overtimesadded; //how many overtimes have been already added
1457
1458 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1459 float WINNING_YES = 1; // winner found
1460 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1461 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1462
1463 float InitiateSuddenDeath()
1464 {
1465         // Check first whether normal overtimes could be added before initiating suddendeath mode
1466         // - for this timelimit_overtime needs to be >0 of course
1467         // - also check the winning condition calculated in the previous frame and only add normal overtime
1468         //   again, if at the point at which timelimit would be extended again, still no winner was found
1469         if ((checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < cvar("timelimit_overtimes")) && cvar("timelimit_overtime") && !(g_race && !g_race_qualifying))
1470         {
1471                 return 1; // need to call InitiateOvertime later
1472         }
1473         else
1474         {
1475                 if(!checkrules_suddendeathend)
1476                 {
1477                         checkrules_suddendeathend = time + 60 * cvar("timelimit_suddendeath");
1478                         if(g_race && !g_race_qualifying)
1479                                 race_StartCompleting();
1480                 }
1481                 return 0;
1482         }
1483 }
1484
1485 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1486 {
1487         ++checkrules_overtimesadded;
1488         //add one more overtime by simply extending the timelimit
1489         float tl;
1490         tl = cvar("timelimit");
1491         tl += cvar("timelimit_overtime");
1492         cvar_set("timelimit", ftos(tl));
1493         string minutesPlural;
1494         if (cvar("timelimit_overtime") == 1)
1495                 minutesPlural = " ^3minute";
1496         else
1497                 minutesPlural = " ^3minutes";
1498
1499         bcenterprint(
1500                 strcat(
1501                         "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1502                         ftos(cvar("timelimit_overtime")),
1503                         minutesPlural,
1504                         " to the game!"
1505                 )
1506         );
1507 }
1508
1509 float GetWinningCode(float fraglimitreached, float equality)
1510 {
1511         if(equality)
1512                 if(fraglimitreached)
1513                         return WINNING_STARTSUDDENDEATHOVERTIME;
1514                 else
1515                         return WINNING_NEVER;
1516         else
1517                 if(fraglimitreached)
1518                         return WINNING_YES;
1519                 else
1520                         return WINNING_NO;
1521 }
1522
1523 // set the .winning flag for exactly those players with a given field value
1524 void SetWinners(.float field, float value)
1525 {
1526         entity head;
1527         FOR_EACH_PLAYER(head)
1528                 head.winning = (head.field == value);
1529 }
1530
1531 // set the .winning flag for those players with a given field value
1532 void AddWinners(.float field, float value)
1533 {
1534         entity head;
1535         FOR_EACH_PLAYER(head)
1536                 if(head.field == value)
1537                         head.winning = 1;
1538 }
1539
1540 // clear the .winning flags
1541 void ClearWinners(void)
1542 {
1543         entity head;
1544         FOR_EACH_PLAYER(head)
1545                 head.winning = 0;
1546 }
1547
1548 // Onslaught winning condition:
1549 // game terminates if only one team has a working generator (or none)
1550 float WinningCondition_Onslaught()
1551 {
1552         entity head;
1553         local float t1, t2, t3, t4;
1554
1555         WinningConditionHelper(); // set worldstatus
1556
1557         if(inWarmupStage)
1558                 return WINNING_NO;
1559
1560         // first check if the game has ended
1561         t1 = t2 = t3 = t4 = 0;
1562         head = find(world, classname, "onslaught_generator");
1563         while (head)
1564         {
1565                 if (head.health > 0)
1566                 {
1567                         if (head.team == COLOR_TEAM1) t1 = 1;
1568                         if (head.team == COLOR_TEAM2) t2 = 1;
1569                         if (head.team == COLOR_TEAM3) t3 = 1;
1570                         if (head.team == COLOR_TEAM4) t4 = 1;
1571                 }
1572                 head = find(head, classname, "onslaught_generator");
1573         }
1574         if (t1 + t2 + t3 + t4 < 2)
1575         {
1576                 // game over, only one team remains (or none)
1577                 ClearWinners();
1578                 if (t1) SetWinners(team, COLOR_TEAM1);
1579                 if (t2) SetWinners(team, COLOR_TEAM2);
1580                 if (t3) SetWinners(team, COLOR_TEAM3);
1581                 if (t4) SetWinners(team, COLOR_TEAM4);
1582                 dprint("Have a winner, ending game.\n");
1583                 return WINNING_YES;
1584         }
1585
1586         // Two or more teams remain
1587         return WINNING_NO;
1588 }
1589
1590 float LMS_NewPlayerLives()
1591 {
1592         float fl;
1593         fl = cvar("fraglimit");
1594         if(fl == 0)
1595                 fl = 999;
1596
1597         // first player has left the game for dying too much? Nobody else can get in.
1598         if(lms_lowest_lives < 1)
1599                 return 0;
1600
1601         if(!cvar("g_lms_join_anytime"))
1602                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1603                         return 0;
1604
1605         return bound(1, lms_lowest_lives, fl);
1606 }
1607
1608 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1609 // they win. Otherwise the defending team wins once the timelimit passes.
1610 void assault_new_round();
1611 float WinningCondition_Assault()
1612 {
1613         local float status;
1614
1615         WinningConditionHelper(); // set worldstatus
1616
1617         status = WINNING_NO;
1618         // as the timelimit has not yet passed just assume the defending team will win
1619         if(assault_attacker_team == COLOR_TEAM1)
1620         {
1621                 SetWinners(team, COLOR_TEAM2);
1622         }
1623         else
1624         {
1625                 SetWinners(team, COLOR_TEAM1);
1626         }
1627
1628         local entity ent;
1629         ent = find(world, classname, "target_assault_roundend");
1630         if(ent)
1631         {
1632                 if(ent.winning) // round end has been triggered by attacking team
1633                 {
1634                         bprint("ASSAULT: round completed...\n");
1635                         SetWinners(team, assault_attacker_team);
1636
1637                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1638
1639                         if(ent.cnt == 1) // this was the second round
1640                         {
1641                                 status = WINNING_YES;
1642                         }
1643                         else
1644                         {
1645                                 local entity oldself;
1646                                 oldself = self;
1647                                 self = ent;
1648                                 assault_new_round();
1649                                 self = oldself;
1650                         }
1651                 }
1652         }
1653
1654         return status;
1655 }
1656
1657 // LMS winning condition: game terminates if and only if there's at most one
1658 // one player who's living lives. Top two scores being equal cancels the time
1659 // limit.
1660 float WinningCondition_LMS()
1661 {
1662         entity head, head2;
1663         float have_player;
1664         float have_players;
1665         float l;
1666
1667         have_player = FALSE;
1668         have_players = FALSE;
1669         l = LMS_NewPlayerLives();
1670
1671         head = find(world, classname, "player");
1672         if(head)
1673                 have_player = TRUE;
1674         head2 = find(head, classname, "player");
1675         if(head2)
1676                 have_players = TRUE;
1677
1678         if(have_player)
1679         {
1680                 // we have at least one player
1681                 if(have_players)
1682                 {
1683                         // two or more active players - continue with the game
1684                 }
1685                 else
1686                 {
1687                         // exactly one player?
1688
1689                         ClearWinners();
1690                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1691
1692                         if(l)
1693                         {
1694                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1695                                 return WINNING_NO;
1696                         }
1697                         else
1698                         {
1699                                 // a winner!
1700                                 // and assign him his first place
1701                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1702                                 return WINNING_YES;
1703                         }
1704                 }
1705         }
1706         else
1707         {
1708                 // nobody is playing at all...
1709                 if(l)
1710                 {
1711                         // wait for players...
1712                 }
1713                 else
1714                 {
1715                         // SNAFU (maybe a draw game?)
1716                         ClearWinners();
1717                         dprint("No players, ending game.\n");
1718                         return WINNING_YES;
1719                 }
1720         }
1721
1722         // When we get here, we have at least two players who are actually LIVING,
1723         // now check if the top two players have equal score.
1724         WinningConditionHelper();
1725
1726         ClearWinners();
1727         if(WinningConditionHelper_winner)
1728                 WinningConditionHelper_winner.winning = TRUE;
1729         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1730                 return WINNING_NEVER;
1731
1732         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1733         return WINNING_NO;
1734 }
1735
1736 void ShuffleMaplist()
1737 {
1738         cvar_set("g_maplist", shufflewords(cvar_string("g_maplist")));
1739 }
1740
1741 float leaderfrags;
1742 float WinningCondition_Scores(float limit, float leadlimit)
1743 {
1744         float limitreached;
1745
1746         // TODO make everything use THIS winning condition (except LMS)
1747         WinningConditionHelper();
1748
1749         if(teams_matter)
1750         {
1751                 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1752                 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1753                 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1754                 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1755         }
1756
1757         ClearWinners();
1758         if(WinningConditionHelper_winner)
1759                 WinningConditionHelper_winner.winning = 1;
1760         if(WinningConditionHelper_winnerteam >= 0)
1761                 SetWinners(team, WinningConditionHelper_winnerteam);
1762
1763         if(WinningConditionHelper_lowerisbetter)
1764         {
1765                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1766                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1767                 limit = -limit;
1768         }
1769
1770         if(WinningConditionHelper_zeroisworst)
1771                 leadlimit = 0; // not supported in this mode
1772
1773         if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1774         // these modes always score in increments of 1, thus this makes sense
1775         {
1776                 if(leaderfrags != WinningConditionHelper_topscore)
1777                 {
1778                         leaderfrags = WinningConditionHelper_topscore;
1779
1780                         if (limit)
1781                         if (leaderfrags == limit - 1)
1782                                 Announce("1fragleft");
1783                         else if (leaderfrags == limit - 2)
1784                                 Announce("2fragsleft");
1785                         else if (leaderfrags == limit - 3)
1786                                 Announce("3fragsleft");
1787                 }
1788         }
1789
1790         limitreached = FALSE;
1791         if(limit)
1792                 if(WinningConditionHelper_topscore >= limit)
1793                         limitreached = TRUE;
1794         if(leadlimit)
1795         {
1796                 float leadlimitreached;
1797                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1798                 if(cvar("leadlimit_and_fraglimit"))
1799                         limitreached = (limitreached && leadlimitreached);
1800                 else
1801                         limitreached = (limitreached || leadlimitreached);
1802         }
1803
1804         return GetWinningCode(
1805                 WinningConditionHelper_topscore && limitreached,
1806                 WinningConditionHelper_equality
1807         );
1808 }
1809
1810 float WinningCondition_Race(float fraglimit)
1811 {
1812         float wc;
1813         entity p;
1814         float n, c;
1815
1816         n = 0;
1817         c = 0;
1818         FOR_EACH_PLAYER(p)
1819         {
1820                 ++n;
1821                 if(p.race_completed)
1822                         ++c;
1823         }
1824         if(n && (n == c))
1825                 return WINNING_YES;
1826         wc = WinningCondition_Scores(fraglimit, 0);
1827
1828         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1829         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1830         // do NOT support equality when the laps are all raced!
1831                 return WINNING_STARTSUDDENDEATHOVERTIME;
1832         else
1833                 return WINNING_NEVER;
1834         return wc;
1835 }
1836
1837 void ReadyRestart();
1838 float WinningCondition_QualifyingThenRace(float limit)
1839 {
1840         float wc;
1841         wc = WinningCondition_Scores(limit, 0);
1842
1843         // NEVER initiate overtime
1844         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1845         {
1846                 return WINNING_YES;
1847         }
1848
1849         return wc;
1850 }
1851
1852 float WinningCondition_RanOutOfSpawns()
1853 {
1854         entity head;
1855
1856         if(have_team_spawns <= 0)
1857                 return WINNING_NO;
1858
1859         if(!some_spawn_has_been_used)
1860                 return WINNING_NO;
1861
1862         team1_score = team2_score = team3_score = team4_score = 0;
1863
1864         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1865         {
1866                 if(head.team == COLOR_TEAM1)
1867                         team1_score = 1;
1868                 else if(head.team == COLOR_TEAM2)
1869                         team2_score = 1;
1870                 else if(head.team == COLOR_TEAM3)
1871                         team3_score = 1;
1872                 else if(head.team == COLOR_TEAM4)
1873                         team4_score = 1;
1874         }
1875
1876         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1877         {
1878                 if(head.team == COLOR_TEAM1)
1879                         team1_score = 1;
1880                 else if(head.team == COLOR_TEAM2)
1881                         team2_score = 1;
1882                 else if(head.team == COLOR_TEAM3)
1883                         team3_score = 1;
1884                 else if(head.team == COLOR_TEAM4)
1885                         team4_score = 1;
1886         }
1887
1888         ClearWinners();
1889         if(team1_score + team2_score + team3_score + team4_score == 0)
1890         {
1891                 checkrules_equality = TRUE;
1892                 return WINNING_YES;
1893         }
1894         else if(team1_score + team2_score + team3_score + team4_score == 1)
1895         {
1896                 float t, i;
1897                 if(team1_score) t = COLOR_TEAM1;
1898                 if(team2_score) t = COLOR_TEAM2;
1899                 if(team3_score) t = COLOR_TEAM3;
1900                 if(team4_score) t = COLOR_TEAM4;
1901                 CheckAllowedTeams(world);
1902                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1903                 {
1904                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1905                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1906                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1907                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1908                 }
1909
1910                 AddWinners(team, t);
1911                 return WINNING_YES;
1912         }
1913         else
1914                 return WINNING_NO;
1915 }
1916
1917 /*
1918 ============
1919 CheckRules_World
1920
1921 Exit deathmatch games upon conditions
1922 ============
1923 */
1924 void CheckRules_World()
1925 {
1926         float timelimit;
1927         float fraglimit;
1928         float leadlimit;
1929
1930         VoteThink();
1931         MapVote_Think();
1932
1933         SetDefaultAlpha();
1934
1935         /*
1936         MapVote_Think should now do that part
1937         if (intermission_running)
1938                 if (time >= intermission_exittime + 60)
1939                 {
1940                         if(!DoNextMapOverride())
1941                                 GotoNextMap();
1942                         return;
1943                 }
1944         */
1945
1946         if (gameover)   // someone else quit the game already
1947         {
1948                 if(player_count == 0) // Nobody there? Then let's go to the next map
1949                         MapVote_Start();
1950                         // this will actually check the player count in the next frame
1951                         // again, but this shouldn't hurt
1952                 return;
1953         }
1954
1955         timelimit = cvar("timelimit") * 60;
1956         fraglimit = cvar("fraglimit");
1957         leadlimit = cvar("leadlimit");
1958
1959         if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1960         {
1961                 if(timelimit > 0)
1962                         timelimit = 0; // timelimit is not made for warmup
1963                 if(fraglimit > 0)
1964                         fraglimit = 0; // no fraglimit for now
1965                 leadlimit = 0; // no leadlimit for now
1966         }
1967
1968         if(g_onslaught)
1969                 timelimit = 0; // ONS has its own overtime rule
1970
1971         if(timelimit > 0)
1972         {
1973                 timelimit += game_starttime;
1974         }
1975         else if (timelimit < 0)
1976         {
1977                 // endmatch
1978                 NextLevel();
1979                 return;
1980         }
1981
1982         float wantovertime;
1983         wantovertime = 0;
1984
1985         if(checkrules_suddendeathend)
1986         {
1987                 if(!checkrules_suddendeathwarning)
1988                 {
1989                         checkrules_suddendeathwarning = TRUE;
1990                         if(g_race && !g_race_qualifying)
1991                                 bcenterprint("^3Everyone, finish your lap! The race is over!");
1992                         else
1993                                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1994                 }
1995         }
1996         else
1997         {
1998                 if (timelimit && time >= timelimit)
1999                 {
2000                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2001                         {
2002                                 float totalplayers;
2003                                 float playerswithlaps;
2004                                 float readyplayers;
2005                                 entity head;
2006                                 totalplayers = playerswithlaps = readyplayers = 0;
2007                                 FOR_EACH_PLAYER(head)
2008                                 {
2009                                         ++totalplayers;
2010                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2011                                                 ++playerswithlaps;
2012                                         if(head.ready)
2013                                                 ++readyplayers;
2014                                 }
2015
2016                                 // at least 2 of the players have completed a lap: start the RACE
2017                                 // otherwise, the players should end the qualifying on their own
2018                                 if(readyplayers || playerswithlaps >= 2)
2019                                 {
2020                                         checkrules_suddendeathend = 0;
2021                                         ReadyRestart(); // go to race
2022                                         return;
2023                                 }
2024                                 else
2025                                         wantovertime |= InitiateSuddenDeath();
2026                         }
2027                         else
2028                                 wantovertime |= InitiateSuddenDeath();
2029                 }
2030         }
2031
2032         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2033         {
2034                 NextLevel();
2035                 return;
2036         }
2037
2038         float checkrules_status;
2039         checkrules_status = WinningCondition_RanOutOfSpawns();
2040         if(checkrules_status == WINNING_YES)
2041         {
2042                 bprint("Hey! Someone ran out of spawns!\n");
2043         }
2044         else if(g_race && !g_race_qualifying && timelimit >= 0)
2045         {
2046                 checkrules_status = WinningCondition_Race(fraglimit);
2047                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2048         }
2049         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2050         {
2051                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2052                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2053         }
2054         else if(g_assault)
2055         {
2056                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2057         }
2058         else if(g_lms)
2059         {
2060                 checkrules_status = WinningCondition_LMS();
2061         }
2062         else if (g_onslaught)
2063         {
2064                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2065         }
2066         else
2067         {
2068                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2069                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2070         }
2071
2072         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2073         {
2074                 checkrules_status = WINNING_NEVER;
2075                 checkrules_overtimesadded = -1;
2076                 wantovertime |= InitiateSuddenDeath();
2077         }
2078
2079         if(checkrules_status == WINNING_NEVER)
2080                 // equality cases! Nobody wins if the overtime ends in a draw.
2081                 ClearWinners();
2082
2083         if(wantovertime)
2084         {
2085                 if(checkrules_status == WINNING_NEVER)
2086                         InitiateOvertime();
2087                 else
2088                         checkrules_status = WINNING_YES;
2089         }
2090
2091         if(checkrules_suddendeathend)
2092                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2093                         checkrules_status = WINNING_YES;
2094
2095         if(checkrules_status == WINNING_YES)
2096         {
2097                 //print("WINNING\n");
2098                 NextLevel();
2099         }
2100 };
2101
2102 float mapvote_nextthink;
2103 float mapvote_initialized;
2104 float mapvote_keeptwotime;
2105 float mapvote_timeout;
2106 string mapvote_message;
2107 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2108 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2109 float mapvote_screenshot_dirs_count;
2110
2111 float mapvote_count;
2112 float mapvote_count_real;
2113 string mapvote_maps[MAPVOTE_COUNT];
2114 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2115 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2116 float mapvote_maps_suggested[MAPVOTE_COUNT];
2117 string mapvote_suggestions[MAPVOTE_COUNT];
2118 float mapvote_suggestion_ptr;
2119 float mapvote_maxlen;
2120 float mapvote_voters;
2121 float mapvote_votes[MAPVOTE_COUNT];
2122 float mapvote_run;
2123 float mapvote_detail;
2124 float mapvote_abstain;
2125 .float mapvote;
2126
2127 void MapVote_ClearAllVotes()
2128 {
2129         FOR_EACH_CLIENT(other)
2130                 other.mapvote = 0;
2131 }
2132
2133 string MapVote_Suggest(string m)
2134 {
2135         float i;
2136         if(m == "")
2137                 return "That's not how to use this command.";
2138         if(!cvar("g_maplist_votable_suggestions"))
2139                 return "Suggestions are not accepted on this server.";
2140         if(mapvote_initialized)
2141                 return "Can't suggest - voting is already in progress!";
2142         m = MapInfo_FixName(m);
2143         if(!m)
2144                 return "The map you suggested is not available on this server.";
2145         if(!cvar("g_maplist_votable_suggestions_override_mostrecent"))
2146                 if(Map_IsRecent(m))
2147                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2148
2149         if(!MapInfo_CheckMap(m))
2150                 return "The map you suggested does not support the current game mode.";
2151         for(i = 0; i < mapvote_suggestion_ptr; ++i)
2152                 if(mapvote_suggestions[i] == m)
2153                         return "This map was already suggested.";
2154         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2155         {
2156                 i = floor(random() * mapvote_suggestion_ptr);
2157         }
2158         else
2159         {
2160                 i = mapvote_suggestion_ptr;
2161                 mapvote_suggestion_ptr += 1;
2162         }
2163         if(mapvote_suggestions[i] != "")
2164                 strunzone(mapvote_suggestions[i]);
2165         mapvote_suggestions[i] = strzone(m);
2166         if(cvar("sv_eventlog"))
2167                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2168         return strcat("Suggestion of ", m, " accepted.");
2169 }
2170
2171 void MapVote_AddVotable(string nextMap, float isSuggestion)
2172 {
2173         float j, i, o;
2174         string pakfile, mapfile;
2175
2176         if(nextMap == "")
2177                 return;
2178         for(j = 0; j < mapvote_count; ++j)
2179                 if(mapvote_maps[j] == nextMap)
2180                         return;
2181         if(strlen(nextMap) > mapvote_maxlen)
2182                 mapvote_maxlen = strlen(nextMap);
2183         mapvote_maps[mapvote_count] = strzone(nextMap);
2184         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2185
2186         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2187         {
2188                 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2189                 pakfile = whichpack(strcat(mapfile, ".tga"));
2190                 if(pakfile == "")
2191                         pakfile = whichpack(strcat(mapfile, ".jpg"));
2192                 if(pakfile == "")
2193                         pakfile = whichpack(strcat(mapfile, ".png"));
2194                 if(pakfile != "")
2195                         break;
2196         }
2197         if(i >= mapvote_screenshot_dirs_count)
2198                 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2199         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2200                 pakfile = substring(pakfile, o, -1);
2201
2202         mapvote_maps_screenshot_dir[mapvote_count] = i;
2203         mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2204
2205         mapvote_count += 1;
2206 }
2207
2208 void MapVote_Spawn();
2209 void MapVote_Init()
2210 {
2211         float i;
2212         float nmax, smax;
2213
2214         MapVote_ClearAllVotes();
2215
2216         mapvote_count = 0;
2217         mapvote_detail = !cvar("g_maplist_votable_nodetail");
2218         mapvote_abstain = cvar("g_maplist_votable_abstain");
2219
2220         if(mapvote_abstain)
2221                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2222         else
2223                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2224         smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2225
2226         // we need this for AddVotable, as that cycles through the screenshot dirs
2227         mapvote_screenshot_dirs_count = tokenize_console(cvar_string("g_maplist_votable_screenshot_dir"));
2228         if(mapvote_screenshot_dirs_count == 0)
2229                 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2230         mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2231         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2232                 mapvote_screenshot_dirs[i] = strzone(argv(i));
2233
2234         if(mapvote_suggestion_ptr)
2235                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2236                         MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2237
2238         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2239                 MapVote_AddVotable(GetNextMap(), FALSE);
2240
2241         if(mapvote_count == 0)
2242         {
2243                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2244                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2245                 if(cvar("g_maplist_shuffle"))
2246                         ShuffleMaplist();
2247                 localcmd("\nmenu_cmd sync\n");
2248                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2249                         MapVote_AddVotable(GetNextMap(), FALSE);
2250         }
2251
2252         mapvote_count_real = mapvote_count;
2253         if(mapvote_abstain)
2254                 MapVote_AddVotable("don't care", 0);
2255
2256         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2257
2258         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2259         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2260         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2261                 mapvote_keeptwotime = 0;
2262         mapvote_message = "Choose a map and press its key!";
2263
2264         MapVote_Spawn();
2265 }
2266
2267 void MapVote_SendPicture(float id)
2268 {
2269         msg_entity = self;
2270         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2271         WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2272         WriteByte(MSG_ONE, id);
2273         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2274 }
2275
2276 float GameCommand_MapVote(string cmd)
2277 {
2278         if(!intermission_running)
2279                 return FALSE;
2280
2281         if(cmd == "mv_getpic")
2282         {
2283                 MapVote_SendPicture(stof(argv(1)));
2284                 return TRUE;
2285         }
2286
2287         return FALSE;
2288 }
2289
2290 float MapVote_GetMapMask()
2291 {
2292         float mask, i, power;
2293         mask = 0;
2294         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2295                 if(mapvote_maps[i] != "")
2296                         mask |= power;
2297         return mask;
2298 }
2299
2300 entity mapvote_ent;
2301 float MapVote_SendEntity(entity to, float sf)
2302 {
2303         float i;
2304
2305         if(sf & 1)
2306                 sf &~= 2; // if we send 1, we don't need to also send 2
2307
2308         WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2309         WriteByte(MSG_ENTITY, sf);
2310
2311         if(sf & 1)
2312         {
2313                 // flag 1 == initialization
2314                 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2315                         WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2316                 WriteString(MSG_ENTITY, "");
2317                 WriteByte(MSG_ENTITY, mapvote_count);
2318                 WriteByte(MSG_ENTITY, mapvote_abstain);
2319                 WriteByte(MSG_ENTITY, mapvote_detail);
2320                 WriteCoord(MSG_ENTITY, mapvote_timeout);
2321                 if(mapvote_count <= 8)
2322                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2323                 else
2324                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2325                 for(i = 0; i < mapvote_count; ++i)
2326                         if(mapvote_maps[i] != "")
2327                         {
2328                                 if(mapvote_abstain && i == mapvote_count - 1)
2329                                 {
2330                                         WriteString(MSG_ENTITY, ""); // abstain needs no text
2331                                         WriteString(MSG_ENTITY, ""); // abstain needs no pack
2332                                         WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2333                                 }
2334                                 else
2335                                 {
2336                                         WriteString(MSG_ENTITY, mapvote_maps[i]);
2337                                         WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2338                                         WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2339                                 }
2340                         }
2341         }
2342
2343         if(sf & 2)
2344         {
2345                 // flag 2 == update of mask
2346                 if(mapvote_count <= 8)
2347                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2348                 else
2349                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2350         }
2351
2352         if(sf & 4)
2353         {
2354                 if(mapvote_detail)
2355                         for(i = 0; i < mapvote_count; ++i)
2356                                 if(mapvote_maps[i] != "")
2357                                         WriteByte(MSG_ENTITY, mapvote_votes[i]);
2358
2359                 WriteByte(MSG_ENTITY, to.mapvote);
2360         }
2361
2362         return TRUE;
2363 }
2364
2365 void MapVote_Spawn()
2366 {
2367         Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2368 }
2369
2370 void MapVote_TouchMask()
2371 {
2372         mapvote_ent.SendFlags |= 2;
2373 }
2374
2375 void MapVote_TouchVotes(entity voter)
2376 {
2377         mapvote_ent.SendFlags |= 4;
2378 }
2379
2380 float MapVote_Finished(float mappos)
2381 {
2382         string result;
2383         float i;
2384         float didntvote;
2385
2386         if(cvar("sv_eventlog"))
2387         {
2388                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2389                 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2390                 didntvote = mapvote_voters;
2391                 for(i = 0; i < mapvote_count; ++i)
2392                         if(mapvote_maps[i] != "")
2393                         {
2394                                 didntvote -= mapvote_votes[i];
2395                                 if(i != mappos)
2396                                 {
2397                                         result = strcat(result, ":", mapvote_maps[i]);
2398                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2399                                 }
2400                         }
2401                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2402
2403                 GameLogEcho(result);
2404                 if(mapvote_maps_suggested[mappos])
2405                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2406         }
2407
2408         FOR_EACH_REALCLIENT(other)
2409                 FixClientCvars(other);
2410
2411         Map_Goto_SetStr(mapvote_maps[mappos]);
2412         Map_Goto();
2413         alreadychangedlevel = TRUE;
2414         return TRUE;
2415 }
2416 void MapVote_CheckRules_1()
2417 {
2418         float i;
2419
2420         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2421         {
2422                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2423                 mapvote_votes[i] = 0;
2424         }
2425
2426         mapvote_voters = 0;
2427         FOR_EACH_REALCLIENT(other)
2428         {
2429                 ++mapvote_voters;
2430                 if(other.mapvote)
2431                 {
2432                         i = other.mapvote - 1;
2433                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2434                         mapvote_votes[i] = mapvote_votes[i] + 1;
2435                 }
2436         }
2437 }
2438
2439 float MapVote_CheckRules_2()
2440 {
2441         float i;
2442         float firstPlace, secondPlace;
2443         float firstPlaceVotes, secondPlaceVotes;
2444         float mapvote_voters_real;
2445         string result;
2446
2447         if(mapvote_count_real == 1)
2448                 return MapVote_Finished(0);
2449
2450         mapvote_voters_real = mapvote_voters;
2451         if(mapvote_abstain)
2452                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2453
2454         RandomSelection_Init();
2455         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2456                 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2457         firstPlace = RandomSelection_chosen_float;
2458         firstPlaceVotes = RandomSelection_best_priority;
2459         //dprint("First place: ", ftos(firstPlace), "\n");
2460         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2461
2462         RandomSelection_Init();
2463         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2464                 if(i != firstPlace)
2465                         RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2466         secondPlace = RandomSelection_chosen_float;
2467         secondPlaceVotes = RandomSelection_best_priority;
2468         //dprint("Second place: ", ftos(secondPlace), "\n");
2469         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2470
2471         if(firstPlace == -1)
2472                 error("No first place in map vote... WTF?");
2473
2474         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2475                 return MapVote_Finished(firstPlace);
2476
2477         if(mapvote_keeptwotime)
2478                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2479                 {
2480                         float didntvote;
2481                         MapVote_TouchMask();
2482                         mapvote_message = "Now decide between the TOP TWO!";
2483                         mapvote_keeptwotime = 0;
2484                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2485                         result = strcat(result, ":", ftos(firstPlaceVotes));
2486                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2487                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2488                         didntvote = mapvote_voters;
2489                         for(i = 0; i < mapvote_count; ++i)
2490                                 if(mapvote_maps[i] != "")
2491                                 {
2492                                         didntvote -= mapvote_votes[i];
2493                                         if(i != firstPlace)
2494                                                 if(i != secondPlace)
2495                                                 {
2496                                                         result = strcat(result, ":", mapvote_maps[i]);
2497                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2498                                                         if(i < mapvote_count_real)
2499                                                         {
2500                                                                 strunzone(mapvote_maps[i]);
2501                                                                 mapvote_maps[i] = "";
2502                                                                 strunzone(mapvote_maps_pakfile[i]);
2503                                                                 mapvote_maps_pakfile[i] = "";
2504                                                         }
2505                                                 }
2506                                 }
2507                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2508                         if(cvar("sv_eventlog"))
2509                                 GameLogEcho(result);
2510                 }
2511
2512         return FALSE;
2513 }
2514 void MapVote_Tick()
2515 {
2516         float keeptwo;
2517         float totalvotes;
2518
2519         keeptwo = mapvote_keeptwotime;
2520         MapVote_CheckRules_1(); // count
2521         if(MapVote_CheckRules_2()) // decide
2522                 return;
2523
2524         totalvotes = 0;
2525         FOR_EACH_REALCLIENT(other)
2526         {
2527                 // hide scoreboard again
2528                 if(other.health != 2342)
2529                 {
2530                         other.health = 2342;
2531                         other.impulse = 0;
2532                         if(clienttype(other) == CLIENTTYPE_REAL)
2533                         {
2534                                 msg_entity = other;
2535                                 WriteByte(MSG_ONE, SVC_FINALE);
2536                                 WriteString(MSG_ONE, "");
2537                         }
2538                 }
2539
2540                 // clear possibly invalid votes
2541                 if(mapvote_maps[other.mapvote - 1] == "")
2542                         other.mapvote = 0;
2543                 // use impulses as new vote
2544                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2545                         if(mapvote_maps[other.impulse - 1] != "")
2546                         {
2547                                 other.mapvote = other.impulse;
2548                                 MapVote_TouchVotes(other);
2549                         }
2550                 other.impulse = 0;
2551
2552                 if(other.mapvote)
2553                         ++totalvotes;
2554         }
2555
2556         MapVote_CheckRules_1(); // just count
2557 }
2558 void MapVote_Start()
2559 {
2560         if(mapvote_run)
2561                 return;
2562
2563         MapInfo_Enumerate();
2564         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2565                 mapvote_run = TRUE;
2566 }
2567 void MapVote_Think()
2568 {
2569         if(!mapvote_run)
2570                 return;
2571
2572         if(alreadychangedlevel)
2573                 return;
2574
2575         if(time < mapvote_nextthink)
2576                 return;
2577         //dprint("tick\n");
2578
2579         mapvote_nextthink = time + 0.5;
2580
2581         if(!mapvote_initialized)
2582         {
2583                 if(cvar("rescan_pending") == 1)
2584                 {
2585                         cvar_set("rescan_pending", "2");
2586                         localcmd("fs_rescan\nrescan_pending 3\n");
2587                         return;
2588                 }
2589                 else if(cvar("rescan_pending") == 2)
2590                 {
2591                         return;
2592                 }
2593                 else if(cvar("rescan_pending") == 3)
2594                 {
2595                         // now build missing mapinfo files
2596                         if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2597                                 return;
2598
2599                         // we're done, start the timer
2600                         cvar_set("rescan_pending", "0");
2601                 }
2602
2603                 mapvote_initialized = TRUE;
2604                 if(DoNextMapOverride())
2605                         return;
2606                 if(!cvar("g_maplist_votable") || player_count <= 0)
2607                 {
2608                         GotoNextMap();
2609                         return;
2610                 }
2611                 MapVote_Init();
2612         }
2613
2614         MapVote_Tick();
2615 };
2616
2617 string GotoMap(string m)
2618 {
2619         if(!MapInfo_CheckMap(m))
2620                 return "The map you chose is not available on this server.";
2621         cvar_set("nextmap", m);
2622         cvar_set("timelimit", "-1");
2623         if(mapvote_initialized || alreadychangedlevel)
2624         {
2625                 if(DoNextMapOverride())
2626                         return "Map switch initiated.";
2627                 else
2628                         return "Hm... no. For some reason I like THIS map more.";
2629         }
2630         else
2631                 return "Map switch will happen after scoreboard.";
2632 }
2633
2634
2635 void EndFrame()
2636 {
2637         float altime;
2638         FOR_EACH_REALCLIENT(self)
2639         {
2640                 if(self.classname == "spectator")
2641                 {
2642                         if(self.enemy.typehitsound)
2643                                 play2(self, "misc/typehit.wav");
2644                         else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2645                                 play2(self, "misc/hit.wav");
2646                 }
2647                 else
2648                 {
2649                         if(self.typehitsound)
2650                                 play2(self, "misc/typehit.wav");
2651                         else if(self.hitsound && self.cvar_cl_hitsound)
2652                                 play2(self, "misc/hit.wav");
2653                 }
2654         }
2655         altime = time + frametime * (1 + cvar("g_antilag_nudge"));
2656         // add 1 frametime because after this, engine SV_Physics
2657         // increases time by a frametime and then networks the frame
2658         // add another frametime because client shows everything with
2659         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2660         // needed!
2661         FOR_EACH_CLIENT(self)
2662         {
2663                 self.hitsound = FALSE;
2664                 self.typehitsound = FALSE;
2665                 antilag_record(self, altime);
2666         }
2667 }
2668
2669
2670 /*
2671  * RedirectionThink:
2672  * returns TRUE if redirecting
2673  */
2674 float redirection_timeout;
2675 float redirection_nextthink;
2676 float RedirectionThink()
2677 {
2678         float clients_found;
2679
2680         if(redirection_target == "")
2681                 return FALSE;
2682
2683         if(!redirection_timeout)
2684         {
2685                 cvar_set("sv_public", "-2");
2686                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2687                 if(redirection_target == "self")
2688                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2689                 else
2690                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2691         }
2692
2693         if(time < redirection_nextthink)
2694                 return TRUE;
2695
2696         redirection_nextthink = time + 1;
2697
2698         clients_found = 0;
2699         FOR_EACH_REALCLIENT(self)
2700         {
2701                 print("Redirecting: sending connect command to ", self.netname, "\n");
2702                 if(redirection_target == "self")
2703                         stuffcmd(self, "\ndisconnect; reconnect\n");
2704                 else
2705                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2706                 ++clients_found;
2707         }
2708
2709         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2710
2711         if(time > redirection_timeout || clients_found == 0)
2712                 localcmd("\nwait; wait; wait; quit\n");
2713
2714         return TRUE;
2715 }
2716
2717 void TargetMusic_RestoreGame();
2718 void RestoreGame()
2719 {
2720         // Loaded from a save game
2721         // some things then break, so let's work around them...
2722
2723         // Progs DB (capture records)
2724         ServerProgsDB = db_load("server.db");
2725
2726         // Mapinfo
2727         MapInfo_Shutdown();
2728         MapInfo_Enumerate();
2729         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2730         WeaponStats_Init();
2731
2732         TargetMusic_RestoreGame();
2733 }
2734
2735 void SV_Shutdown()
2736 {
2737         if(gameover > 1) // shutting down already?
2738                 return;
2739
2740         gameover = 2; // 2 = server shutting down
2741
2742         if(world_initialized > 0)
2743         {
2744                 world_initialized = 0;
2745                 print("Saving persistent data...\n");
2746                 Ban_SaveBans();
2747                 if(!cheatcount_total)
2748                         db_save(ServerProgsDB, "server.db");
2749                 if(cvar("developer"))
2750                         db_save(TemporaryDB, "server-temp.db");
2751                 CheatShutdown(); // must be after cheatcount check
2752                 db_close(ServerProgsDB);
2753                 db_close(TemporaryDB);
2754                 print("done!\n");
2755                 // tell the bot system the game is ending now
2756                 bot_endgame();
2757
2758                 WeaponStats_Shutdown();
2759                 MapInfo_Shutdown();
2760         }
2761         else if(world_initialized == 0)
2762         {
2763                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2764         }
2765 }