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