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