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