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