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