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