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