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