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