]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Merge branch 'master' into terencehill/ca_arena_freezetag_bugfixes
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 #define LATENCY_THINKRATE 10
2 .float latency_sum;
3 .float latency_cnt;
4 .float latency_time;
5 entity pingplreport;
6 void PingPLReport_Think()
7 {
8         float delta;
9         entity e;
10
11         delta = 3 / maxclients;
12         if(delta < sys_frametime)
13                 delta = 0;
14         self.nextthink = time + delta;
15
16         e = edict_num(self.cnt + 1);
17         if(clienttype(e) == CLIENTTYPE_REAL)
18         {
19                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
20                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
21                 WriteByte(MSG_BROADCAST, self.cnt);
22                 WriteShort(MSG_BROADCAST, max(1, e.ping));
23                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
24                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
25
26                 // record latency times for clients throughout the match so we can report it to playerstats
27                 if(time > (e.latency_time + LATENCY_THINKRATE))
28                 {
29                         e.latency_sum += e.ping;
30                         e.latency_cnt += 1;
31                         e.latency_time = time;
32                         //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
33                 }
34         }
35         else
36         {
37                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
38                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
39                 WriteByte(MSG_BROADCAST, self.cnt);
40                 WriteShort(MSG_BROADCAST, 0);
41                 WriteByte(MSG_BROADCAST, 0);
42                 WriteByte(MSG_BROADCAST, 0);
43         }
44         self.cnt = mod(self.cnt + 1, maxclients);
45 }
46 void PingPLReport_Spawn()
47 {
48         pingplreport = spawn();
49         pingplreport.classname = "pingplreport";
50         pingplreport.think = PingPLReport_Think;
51         pingplreport.nextthink = time;
52 }
53
54 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
55 string redirection_target;
56 float world_initialized;
57
58 string GetMapname();
59 string GetGametype();
60 void GotoNextMap(float reinit);
61 void ShuffleMaplist();
62 float(float reinit) DoNextMapOverride;
63
64 void SetDefaultAlpha()
65 {
66         if(autocvar_g_running_guns)
67         {
68                 default_player_alpha = -1;
69                 default_weapon_alpha = +1;
70         }
71         else if(g_cloaked)
72         {
73                 default_player_alpha = autocvar_g_balance_cloaked_alpha;
74                 default_weapon_alpha = default_player_alpha;
75         }
76         else
77         {
78                 default_player_alpha = autocvar_g_player_alpha;
79                 if(default_player_alpha == 0)
80                         default_player_alpha = 1;
81                 default_weapon_alpha = default_player_alpha;
82         }
83 }
84
85 void fteqcc_testbugs()
86 {
87         float a, b;
88
89         if(!autocvar_developer_fteqccbugs)
90                 return;
91
92         dprint("*** fteqcc test: checking for bugs...\n");
93
94         a = 1;
95         b = 5;
96         if(sqrt(a) - sqrt(b - a) == 0)
97                 dprint("*** fteqcc test: found same-function-twice bug\n");
98         else
99                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
100
101         world.cnt = -10;
102         world.enemy = world;
103         world.enemy.cnt += 10;
104         if(world.cnt > 0.2 || world.cnt < -0.2) // don't error out if it's just roundoff errors
105                 dprint("*** fteqcc test: found += bug\n");
106         else
107                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
108         world.cnt = 0;
109 }
110
111 void GotoFirstMap()
112 {
113         float n;
114         if(autocvar__sv_init)
115         {
116                 // cvar_set("_sv_init", "0");
117                 // we do NOT set this to 0 any more, so someone "accidentally" changing
118                 // to this "init" map on a dedicated server will cause no permanent
119                 // harm
120                 if(autocvar_g_maplist_shuffle)
121                         ShuffleMaplist();
122                 n = tokenizebyseparator(autocvar_g_maplist, " ");
123                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
124
125                 MapInfo_Enumerate();
126                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
127
128                 if(!DoNextMapOverride(1))
129                         GotoNextMap(1);
130
131                 return;
132         }
133
134         if(time < 5)
135         {
136                 self.nextthink = time;
137         }
138         else
139         {
140                 self.nextthink = time + 1;
141                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
142         }
143 }
144
145 void cvar_changes_init()
146 {
147         float h;
148         string k, v, d;
149         float n, i, adding, pureadding;
150
151         if(cvar_changes)
152                 strunzone(cvar_changes);
153         cvar_changes = string_null;
154         if(cvar_purechanges)
155                 strunzone(cvar_purechanges);
156         cvar_purechanges = string_null;
157         cvar_purechanges_count = 0;
158
159         h = buf_create();
160         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
161         n = buf_getsize(h);
162
163         adding = TRUE;
164         pureadding = TRUE;
165
166         for(i = 0; i < n; ++i)
167         {
168                 k = bufstr_get(h, i);
169
170 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
171 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
172 #define BADCVAR(p) if(k == p) continue
173
174                 // general excludes and namespaces for server admin used cvars
175                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
176
177                 // internal
178                 BADPREFIX("csqc_");
179                 BADPREFIX("cvar_check_");
180                 BADCVAR("gamecfg");
181                 BADCVAR("g_configversion");
182                 BADCVAR("g_maplist_index");
183                 BADCVAR("halflifebsp");
184                 BADPREFIX("sv_world");
185
186                 // client
187                 BADPREFIX("chase_");
188                 BADPREFIX("cl_");
189                 BADPREFIX("con_");
190                 BADPREFIX("scoreboard_");
191                 BADPREFIX("g_campaign");
192                 BADPREFIX("g_waypointsprite_");
193                 BADPREFIX("gl_");
194                 BADPREFIX("joy");
195                 BADPREFIX("hud_");
196                 BADPREFIX("m_");
197                 BADPREFIX("menu_");
198                 BADPREFIX("net_slist_");
199                 BADPREFIX("r_");
200                 BADPREFIX("sbar_");
201                 BADPREFIX("scr_");
202                 BADPREFIX("snd_");
203                 BADPREFIX("show");
204                 BADPREFIX("sensitivity");
205                 BADPREFIX("userbind");
206                 BADPREFIX("v_");
207                 BADPREFIX("vid_");
208                 BADPREFIX("crosshair");
209                 BADCVAR("mod_q3bsp_lightmapmergepower");
210                 BADCVAR("mod_q3bsp_nolightmaps");
211                 BADCVAR("fov");
212                 BADCVAR("mastervolume");
213                 BADCVAR("volume");
214                 BADCVAR("bgmvolume");
215
216                 // private
217                 BADCVAR("developer");
218                 BADCVAR("log_dest_udp");
219                 BADCVAR("log_file");
220                 BADCVAR("net_address");
221                 BADCVAR("net_address_ipv6");
222                 BADCVAR("port");
223                 BADCVAR("savedgamecfg");
224                 BADCVAR("serverconfig");
225                 BADCVAR("sv_autoscreenshot");
226                 BADCVAR("sv_heartbeatperiod");
227                 BADCVAR("sv_vote_master_password");
228                 BADCVAR("sys_colortranslation");
229                 BADCVAR("sys_specialcharactertranslation");
230                 BADCVAR("timeformat");
231                 BADCVAR("timestamps");
232                 BADPREFIX("developer_");
233                 BADPREFIX("g_ban_");
234                 BADPREFIX("g_banned_list");
235                 BADPREFIX("g_chat_flood_");
236                 BADPREFIX("g_ghost_items");
237                 BADPREFIX("g_playerstats_");
238                 BADPREFIX("g_respawn_ghosts");
239                 BADPREFIX("g_voice_flood_");
240                 BADPREFIX("rcon_");
241                 BADPREFIX("sv_allowdownloads");
242                 BADPREFIX("sv_autodemo");
243                 BADPREFIX("sv_curl_");
244                 BADPREFIX("sv_eventlog");
245                 BADPREFIX("sv_logscores_");
246                 BADPREFIX("sv_master");
247                 BADPREFIX("sv_weaponstats_");
248                 BADPREFIX("sv_waypointsprite_");
249                 BADCVAR("rescan_pending");
250
251                 // these can contain player IDs, so better hide
252                 BADPREFIX("g_forced_team_");
253
254                 // mapinfo
255                 BADCVAR("fraglimit");
256                 BADCVAR("g_arena");
257                 BADCVAR("g_assault");
258                 BADCVAR("g_ca");
259                 BADCVAR("g_ctf");
260                 BADCVAR("g_cts");
261                 BADCVAR("g_dm");
262                 BADCVAR("g_domination");
263                 BADCVAR("g_domination_default_teams");
264                 BADCVAR("g_freezetag");
265                 BADCVAR("g_keepaway");
266                 BADCVAR("g_keyhunt");
267                 BADCVAR("g_keyhunt_teams");
268                 BADCVAR("g_keyhunt_teams");
269                 BADCVAR("g_lms");
270                 BADCVAR("g_nexball");
271                 BADCVAR("g_onslaught");
272                 BADCVAR("g_race");
273                 BADCVAR("g_race_qualifying_timelimit");
274                 BADCVAR("g_runematch");
275                 BADCVAR("g_tdm");
276                 BADCVAR("g_tdm_teams");
277                 BADCVAR("leadlimit");
278                 BADCVAR("nextmap");
279                 BADCVAR("teamplay");
280                 BADCVAR("timelimit");
281
282                 // long
283                 BADCVAR("hostname");
284                 BADCVAR("g_maplist");
285                 BADCVAR("g_maplist_mostrecent");
286                 BADCVAR("sv_motd");
287
288                 v = cvar_string(k);
289                 d = cvar_defstring(k);
290                 if(v == d)
291                         continue;
292
293                 if(adding)
294                 {
295                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
296                         if(strlen(cvar_changes) > 16384)
297                         {
298                                 cvar_changes = "// too many settings have been changed to show them here\n";
299                                 adding = 0;
300                         }
301                 }
302
303                 // now check if the changes are actually gameplay relevant
304
305                 // does nothing visible
306                 BADCVAR("captureleadlimit_override");
307                 BADCVAR("g_arena_point_leadlimit");
308                 BADCVAR("g_balance_kill_delay");
309                 BADCVAR("g_ca_point_leadlimit");
310                 BADCVAR("g_ctf_captimerecord_always");
311                 BADCVAR("g_ctf_flag_glowtrails");
312                 BADCVAR("g_ctf_flag_pickup_verbosename");
313                 BADCVAR("g_domination_point_leadlimit");
314                 BADCVAR("g_forced_respawn");
315                 BADCVAR("g_keyhunt_point_leadlimit");
316                 BADPREFIX("g_mod_");
317                 BADCVAR("g_nexball_goalleadlimit");
318                 BADCVAR("g_runematch_point_leadlimit");
319                 BADCVAR("leadlimit_and_fraglimit");
320                 BADCVAR("leadlimit_override");
321                 BADCVAR("pausable");
322                 BADCVAR("sv_allow_fullbright");
323                 BADCVAR("sv_checkforpacketsduringsleep");
324                 BADCVAR("sv_fraginfo");
325                 BADCVAR("sv_timeout");
326                 BADPREFIX("sv_timeout_");
327                 BADCVAR("welcome_message_time");
328                 BADPREFIX("crypto_");
329                 BADPREFIX("g_chat_");
330                 BADPREFIX("g_ctf_captimerecord_");
331                 BADPREFIX("g_maplist_votable_");
332                 BADPREFIX("net_");
333                 BADPREFIX("prvm_");
334                 BADPREFIX("skill_");
335                 BADPREFIX("sv_cullentities_");
336                 BADPREFIX("sv_fraginfo_");
337                 BADPREFIX("sv_maxidle_");
338                 BADPREFIX("sv_vote_");
339                 BADPREFIX("timelimit_");
340                 BADCVAR("gameversion");
341                 BADPREFIX("gameversion_");
342                 BADCVAR("sv_namechangetimer");
343 #ifndef NO_LEGACY_NETWORKING
344                 BADCVAR("sv_use_csqc_players"); // transition
345 #endif
346
347                 // allowed changes to server admins (please sync this to server.cfg)
348                 // vi commands:
349                 //   :/"impure"/,$d
350                 //   :g!,^\/\/[^ /],d
351                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
352                 //   :%!sort
353                 // yes, this does contain some redundant stuff, don't really care
354                 BADCVAR("bot_config_file");
355                 BADCVAR("bot_number");
356                 BADCVAR("bot_prefix");
357                 BADCVAR("bot_suffix");
358                 BADCVAR("capturelimit_override");
359                 BADCVAR("fraglimit_override");
360                 BADCVAR("gametype");
361                 BADCVAR("g_antilag");
362                 BADCVAR("g_balance_teams");
363                 BADCVAR("g_balance_teams_prevent_imbalance");
364                 BADCVAR("g_balance_teams_scorefactor");
365                 BADCVAR("g_ban_sync_trusted_servers");
366                 BADCVAR("g_ban_sync_uri");
367                 BADCVAR("g_ctf_ignore_frags");
368                 BADCVAR("g_domination_point_limit");
369                 BADCVAR("g_friendlyfire");
370                 BADCVAR("g_fullbrightitems");
371                 BADCVAR("g_fullbrightplayers");
372                 BADCVAR("g_keyhunt_point_limit");
373                 BADCVAR("g_keyhunt_teams_override");
374                 BADCVAR("g_lms_lives_override");
375                 BADCVAR("g_maplist");
376                 BADCVAR("g_maplist_check_waypoints");
377                 BADCVAR("g_maplist_mostrecent_count");
378                 BADCVAR("g_maplist_shuffle");
379                 BADCVAR("g_maplist_votable");
380                 BADCVAR("g_maplist_votable_abstain");
381                 BADCVAR("g_maplist_votable_nodetail");
382                 BADCVAR("g_maplist_votable_suggestions");
383                 BADCVAR("g_maxplayers");
384                 BADCVAR("g_mirrordamage");
385                 BADCVAR("g_nexball_goallimit");
386                 BADCVAR("g_powerups");
387                 BADCVAR("g_runematch_point_limit");
388                 BADCVAR("g_start_delay");
389                 BADCVAR("g_warmup");
390                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
391                 BADCVAR("hostname");
392                 BADCVAR("log_file");
393                 BADCVAR("maxplayers");
394                 BADCVAR("minplayers");
395                 BADCVAR("net_address");
396                 BADCVAR("port");
397                 BADCVAR("rcon_password");
398                 BADCVAR("rcon_restricted_commands");
399                 BADCVAR("rcon_restricted_password");
400                 BADCVAR("skill");
401                 BADCVAR("sv_adminnick");
402                 BADCVAR("sv_autoscreenshot");
403                 BADCVAR("sv_autotaunt");
404                 BADCVAR("sv_curl_defaulturl");
405                 BADCVAR("sv_defaultcharacter");
406                 BADCVAR("sv_defaultplayercolors");
407                 BADCVAR("sv_defaultplayermodel");
408                 BADCVAR("sv_defaultplayerskin");
409                 BADCVAR("sv_maxidle");
410                 BADCVAR("sv_maxrate");
411                 BADCVAR("sv_motd");
412                 BADCVAR("sv_public");
413                 BADCVAR("sv_ready_restart");
414                 BADCVAR("sv_status_privacy");
415                 BADCVAR("sv_taunt");
416                 BADCVAR("sv_vote_call");
417                 BADCVAR("sv_vote_commands");
418                 BADCVAR("sv_vote_majority_factor");
419                 BADCVAR("sv_vote_master");
420                 BADCVAR("sv_vote_master_commands");
421                 BADCVAR("sv_vote_master_password");
422                 BADCVAR("sv_vote_simple_majority_factor");
423                 BADCVAR("sys_ticrate");
424                 BADCVAR("teamplay_mode");
425                 BADCVAR("timelimit_override");
426                 BADCVAR("g_spawnshieldtime");
427                 BADPREFIX("g_warmup_");
428                 BADPREFIX("sv_ready_restart_");
429
430                 // mutators that announce themselves properly to the server browser
431                 BADCVAR("g_minstagib");
432                 BADCVAR("g_new_toys");
433                 BADCVAR("g_nix");
434
435                 if(autocvar_g_minstagib)
436                 {
437                         BADCVAR("g_grappling_hook");
438                         BADCVAR("g_jetpack");
439                 }
440 #undef BADPREFIX
441 #undef BADCVAR
442
443                 if(pureadding)
444                 {
445                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
446                         if(strlen(cvar_purechanges) > 16384)
447                         {
448                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
449                                 pureadding = 0;
450                         }
451                 }
452                 ++cvar_purechanges_count;
453                 // WARNING: this variable is used for the server list
454                 // NEVER dare to skip this code!
455                 // Hacks to intentionally appearing as "pure server" even though you DO have
456                 // modified settings may be punished by removal from the server list.
457                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
458                 // though.
459         }
460         buf_del(h);
461         if(cvar_changes == "")
462                 cvar_changes = "// this server runs at default server settings\n";
463         else
464                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
465         cvar_changes = strzone(cvar_changes);
466         if(cvar_purechanges == "")
467                 cvar_purechanges = "// this server runs at default gameplay settings\n";
468         else
469                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
470         cvar_purechanges = strzone(cvar_purechanges);
471 }
472
473 void detect_maptype()
474 {
475 #if 0
476         vector o, v;
477         float i;
478
479         for(;;)
480         {
481                 o = world.mins;
482                 o_x += random() * (world.maxs_x - world.mins_x);
483                 o_y += random() * (world.maxs_y - world.mins_y);
484                 o_z += random() * (world.maxs_z - world.mins_z);
485
486                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
487                 if(trace_fraction == 1)
488                         continue;
489
490                 v = trace_endpos;
491
492                 for(i = 0; i < 64; i += 4)
493                 {
494                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
495         if(trace_fraction == 1)
496                 continue;
497                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
498                 }
499
500                 break;
501         }
502 #endif
503 }
504
505 entity randomseed;
506 float RandomSeed_Send(entity to, float sf)
507 {
508         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
509         WriteShort(MSG_ENTITY, self.cnt);
510         return TRUE;
511 }
512 void RandomSeed_Think()
513 {
514         self.cnt = bound(0, floor(random() * 65536), 65535);
515         self.nextthink = time + 5;
516
517         self.SendFlags |= 1;
518 }
519 void RandomSeed_Spawn()
520 {
521         randomseed = spawn();
522         randomseed.think = RandomSeed_Think;
523         Net_LinkEntity(randomseed, FALSE, 0, RandomSeed_Send);
524
525         entity oldself;
526         oldself = self;
527         self = randomseed;
528         self.think(); // sets random seed and nextthink
529         self = oldself;
530 }
531
532 void spawnfunc___init_dedicated_server(void)
533 {
534         // handler for _init/_init map (only for dedicated server initialization)
535
536         world_initialized = -1; // don't complain
537         cvar = cvar_normal;
538         cvar_string = cvar_string_normal;
539         cvar_set = cvar_set_normal;
540
541         remove = remove_unsafely;
542
543         entity e;
544         e = spawn();
545         e.think = GotoFirstMap;
546         e.nextthink = time; // this is usually 1 at this point
547
548         e = spawn();
549         e.classname = "info_player_deathmatch"; // safeguard against player joining
550
551         self.classname = "worldspawn"; // safeguard against various stuff ;)
552
553         // needs to be done so early because of the constants they create
554         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
555         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
556
557         MapInfo_Enumerate();
558         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
559 }
560
561 void Map_MarkAsRecent(string m);
562 float world_already_spawned;
563 void Nagger_Init();
564 void ClientInit_Spawn();
565 void WeaponStats_Init();
566 void WeaponStats_Shutdown();
567 void spawnfunc_worldspawn (void)
568 {
569         float fd, l, i, j, n;
570         string s, col;
571
572         cvar = cvar_normal;
573         cvar_string = cvar_string_normal;
574         cvar_set = cvar_set_normal;
575
576         if(world_already_spawned)
577                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
578         world_already_spawned = TRUE;
579
580         remove = remove_safely; // during spawning, watch what you remove!
581
582         check_unacceptable_compiler_bugs();
583
584         cvar_changes_init(); // do this very early now so it REALLY matches the server config
585
586         compressShortVector_init();
587
588         entity head;
589         head = nextent(world);
590         maxclients = 0;
591         while(head)
592         {
593                 ++maxclients;
594                 head = nextent(head);
595         }
596
597         // needs to be done so early because of the constants they create
598         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
599         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
600
601         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
602
603         TemporaryDB = db_create();
604
605         // 0 normal
606         lightstyle(0, "m");
607
608         // 1 FLICKER (first variety)
609         lightstyle(1, "mmnmmommommnonmmonqnmmo");
610
611         // 2 SLOW STRONG PULSE
612         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
613
614         // 3 CANDLE (first variety)
615         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
616
617         // 4 FAST STROBE
618         lightstyle(4, "mamamamamama");
619
620         // 5 GENTLE PULSE 1
621         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
622
623         // 6 FLICKER (second variety)
624         lightstyle(6, "nmonqnmomnmomomno");
625
626         // 7 CANDLE (second variety)
627         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
628
629         // 8 CANDLE (third variety)
630         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
631
632         // 9 SLOW STROBE (fourth variety)
633         lightstyle(9, "aaaaaaaazzzzzzzz");
634
635         // 10 FLUORESCENT FLICKER
636         lightstyle(10, "mmamammmmammamamaaamammma");
637
638         // 11 SLOW PULSE NOT FADE TO BLACK
639         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
640
641         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
642
643         // 63 testing
644         lightstyle(63, "a");
645
646         if(autocvar_g_campaign)
647                 CampaignPreInit();
648
649         Map_MarkAsRecent(mapname);
650
651         PlayerStats_Init(); // we need this to be initiated before InitGameplayMode
652
653         precache_model ("null"); // we need this one before InitGameplayMode
654         InitGameplayMode();
655         readlevelcvars();
656         GrappleHookInit();
657         ElectroInit();
658         LaserInit();
659
660         player_count = 0;
661         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
662         if(bot_waypoints_for_items == 1)
663                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
664                         bot_waypoints_for_items = 0;
665
666         precache();
667
668         WaypointSprite_Init();
669
670         GameLogInit(); // prepare everything
671         // NOTE for matchid:
672         // changing the logic generating it is okay. But:
673         // it HAS to stay <= 64 chars
674         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
675         if(autocvar_sv_eventlog)
676         {
677                 s = sprintf("%d.%s.%06d", ftos(autocvar_sv_eventlog_files_counter), strftime(FALSE, "%s"), floor(random() * 1000000));
678                 matchid = strzone(s);
679
680                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
681                 s = ":gameinfo:mutators:LIST";
682
683                 ret_string = s;
684                 MUTATOR_CALLHOOK(BuildMutatorsString);
685                 s = ret_string;
686
687                 // simple, probably not good in the mutator system
688                 if(autocvar_g_grappling_hook)
689                         s = strcat(s, ":grappling_hook");
690
691                 // initialiation stuff, not good in the mutator system
692                 if(!autocvar_g_use_ammunition)
693                         s = strcat(s, ":no_use_ammunition");
694
695                 // initialiation stuff, not good in the mutator system
696                 if(autocvar_g_pickup_items == 0)
697                         s = strcat(s, ":no_pickup_items");
698                 if(autocvar_g_pickup_items > 0)
699                         s = strcat(s, ":pickup_items");
700
701                 // initialiation stuff, not good in the mutator system
702                 if(autocvar_g_weaponarena != "0")
703                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
704
705                 // TODO to mutator system
706                 if(autocvar_g_norecoil)
707                         s = strcat(s, ":norecoil");
708
709                 // TODO to mutator system
710                 if(autocvar_g_midair)
711                         s = strcat(s, ":midair");
712
713                 // TODO to mutator system
714                 if(autocvar_g_minstagib)
715                         s = strcat(s, ":minstagib");
716
717                 // TODO to mutator system
718                 if(autocvar_g_powerups == 0)
719                         s = strcat(s, ":no_powerups");
720                 if(autocvar_g_powerups > 0)
721                         s = strcat(s, ":powerups");
722
723                 GameLogEcho(s);
724                 GameLogEcho(":gameinfo:end");
725         }
726         else
727                 matchid = strzone(ftos(random()));
728
729         cvar_set("nextmap", "");
730
731         SetDefaultAlpha();
732
733         if(autocvar_g_campaign)
734                 CampaignPostInit();
735
736         fteqcc_testbugs();
737
738         Ban_LoadBans();
739
740         MapInfo_Enumerate();
741         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
742
743         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
744         {
745                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
746                 if(fd != -1)
747                 {
748                         while((s = fgets(fd)))
749                         {
750                                 l = tokenize_console(s);
751                                 if(l < 2)
752                                         continue;
753                                 if(argv(0) == "cd")
754                                 {
755                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
756                                         print("  cdtrack ", argv(2), "\n");
757                                 }
758                                 else if(argv(0) == "fog")
759                                 {
760                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
761                                         print("  \"fog\" \"", s, "\"\n");
762                                 }
763                                 else if(argv(0) == "set")
764                                 {
765                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
766                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
767                                 }
768                                 else if(argv(0) != "//")
769                                 {
770                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
771                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
772                                 }
773                         }
774                         fclose(fd);
775                 }
776         }
777
778         WeaponStats_Init();
779
780         WEPSET_ADDSTAT();
781         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
782         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
783         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
784         addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
785         Nagger_Init();
786
787         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
788         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
789         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
790         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
791         addstat(STAT_FUEL, AS_INT, ammo_fuel);
792         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
793         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
794         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
795         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
796         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
797         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
798         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
799         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
800
801         addstat(STAT_NEX_CHARGE, AS_FLOAT, nex_charge);
802         addstat(STAT_NEX_CHARGEPOOL, AS_FLOAT, nex_chargepool_ammo);
803
804         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
805
806         if(g_ca)
807         {
808                 addstat(STAT_REDALIVE, AS_INT, redalive_stat);
809                 addstat(STAT_BLUEALIVE, AS_INT, bluealive_stat);
810         }
811
812         // g_movementspeed hack
813         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
814         addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
815         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
816         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
817
818         // secrets
819         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
820         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
821
822         // misc
823         addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
824
825         next_pingtime = time + 5;
826
827         detect_maptype();
828
829         // set up information replies for clients and server to use
830         lsmaps_reply = "^7Maps available: ";
831         lsnewmaps_reply = "^7Maps without a record set: ";
832         for(i = 0, j = 0; i < MapInfo_count; ++i)
833         {
834                 if(MapInfo_Get_ByID(i))
835                         if not(MapInfo_Map_flags & (MAPINFO_FLAG_HIDDEN | MAPINFO_FLAG_FORBIDDEN))
836                         {
837                                 if(mod(i, 2))
838                                         col = "^2";
839                                 else
840                                         col = "^3";
841
842                                 ++j;
843
844                                 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
845
846                                 if(g_race && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, RACE_RECORD, "time"))))
847                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
848                                 else if(g_cts && !stof(db_get(ServerProgsDB, strcat(MapInfo_Map_bspname, CTS_RECORD, "time"))))
849                                         lsnewmaps_reply = strcat(lsnewmaps_reply, col, MapInfo_Map_bspname, " ");
850                         }
851         }
852
853         lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
854         lsnewmaps_reply = strzone(strcat(((!g_race && !g_cts) ? "Need to be playing race or CTS for lsnewmaps to work." : lsnewmaps_reply), "\n"));
855
856         maplist_reply = "^7Maps in list: ";
857         n = tokenize_console(autocvar_g_maplist);
858         for(i = 0, j = 0; i < n; ++i)
859         {
860                 if(MapInfo_CheckMap(argv(i)))
861                 {
862                         if(mod(j, 2))
863                                 col = "^2";
864                         else
865                                 col = "^3";
866                         maplist_reply = strcat(maplist_reply, col, argv(i), " ");
867                         ++j;
868                 }
869         }
870         maplist_reply = strzone(strcat(maplist_reply, "\n"));
871         MapInfo_ClearTemps();
872
873         for(i = 0; i < 10; ++i)
874         {
875                 s = getrecords(i);
876                 if (s)
877                         records_reply[i] = strzone(s);
878         }
879
880         ladder_reply = strzone(getladder());
881
882         rankings_reply = strzone(getrankings());
883
884         // begin other init
885         ClientInit_Spawn();
886         RandomSeed_Spawn();
887         PingPLReport_Spawn();
888
889         CheatInit();
890
891         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
892
893         // fill sv_curl_serverpackages from .serverpackage files
894         if(autocvar_sv_curl_serverpackages_auto)
895         {
896                 s = "";
897                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
898                 for(i = 0; i < n; ++i)
899                         if(substring(argv(i), -14, -1) != "-serverpackage.txt")
900                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
901                                 s = strcat(s, " ", argv(i));
902                 fd = search_begin("*-serverpackage.txt", TRUE, FALSE);
903                 if(fd >= 0)
904                 {
905                         j = search_getsize(fd);
906                         for(i = 0; i < j; ++i)
907                                 s = strcat(s, " ", search_getfilename(fd, i));
908                         search_end(fd);
909                 }
910                 fd = search_begin("*.serverpackage", TRUE, FALSE);
911                 if(fd >= 0)
912                 {
913                         j = search_getsize(fd);
914                         for(i = 0; i < j; ++i)
915                                 s = strcat(s, " ", search_getfilename(fd, i));
916                         search_end(fd);
917                 }
918                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
919         }
920
921         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
922         modname = "Xonotic";
923         // physics/balance/config changes that count as mod
924         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
925                 modname = cvar_string("g_mod_physics");
926         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
927                 modname = cvar_string("g_mod_balance");
928         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
929                 modname = cvar_string("g_mod_config");
930         // weird mutators that deserve to count as mod
931         if(autocvar_g_minstagib)
932                 modname = "MinstaGib";
933         // extra mutators that deserve to count as mod
934         MUTATOR_CALLHOOK(SetModname);
935
936         // save it for later
937         modname = strzone(modname);
938
939         WinningConditionHelper(); // set worldstatus
940
941         world_initialized = 1;
942 }
943
944 void spawnfunc_light (void)
945 {
946         //makestatic (self); // Who the f___ did that?
947         remove(self);
948 }
949
950 string GetGametype()
951 {
952         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
953 }
954
955 string getmapname_stored;
956 string GetMapname()
957 {
958         return mapname;
959 }
960
961 float Map_Count, Map_Current;
962 string Map_Current_Name;
963
964 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
965 float GetMaplistPosition()
966 {
967         float pos, idx;
968         string map;
969
970         map = GetMapname();
971         idx = autocvar_g_maplist_index;
972
973         if(idx >= 0)
974                 if(idx < Map_Count)
975                         if(map == argv(idx))
976                                 return idx;
977
978         for(pos = 0; pos < Map_Count; ++pos)
979                 if(map == argv(pos))
980                         return pos;
981
982         // resume normal maplist rotation if current map is not in g_maplist
983         return idx;
984 }
985
986 float MapHasRightSize(string map)
987 {
988         float fh;
989         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
990         if(autocvar_g_maplist_check_waypoints)
991         {
992                 dprint("checkwp "); dprint(map);
993                 if(!fexists(strcat("maps/", map, ".waypoints")))
994                 {
995                         dprint(": no waypoints\n");
996                         return FALSE;
997                 }
998                 dprint(": has waypoints\n");
999         }
1000
1001         // open map size restriction file
1002         dprint("opensize "); dprint(map);
1003         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
1004         if(fh >= 0)
1005         {
1006                 float mapmin, mapmax;
1007                 dprint(": ok, ");
1008                 mapmin = stof(fgets(fh));
1009                 mapmax = stof(fgets(fh));
1010                 fclose(fh);
1011                 if(player_count < mapmin)
1012                 {
1013                         dprint("not enough\n");
1014                         return FALSE;
1015                 }
1016                 if(player_count > mapmax)
1017                 {
1018                         dprint("too many\n");
1019                         return FALSE;
1020                 }
1021                 dprint("right size\n");
1022                 return TRUE;
1023         }
1024         dprint(": not found\n");
1025         return TRUE;
1026 }
1027
1028 string Map_Filename(float position)
1029 {
1030         return strcat("maps/", argv(position), ".bsp");
1031 }
1032
1033 string strwords(string s, float w)
1034 {
1035         float endpos;
1036         for(endpos = 0; w && endpos >= 0; --w)
1037                 endpos = strstrofs(s, " ", endpos + 1);
1038         if(endpos < 0)
1039                 return s;
1040         else
1041                 return substring(s, 0, endpos);
1042 }
1043
1044 float strhasword(string s, string w)
1045 {
1046         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
1047 }
1048
1049 void Map_MarkAsRecent(string m)
1050 {
1051         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1052 }
1053
1054 float Map_IsRecent(string m)
1055 {
1056         return strhasword(autocvar_g_maplist_mostrecent, m);
1057 }
1058
1059 float Map_Check(float position, float pass)
1060 {
1061         string filename;
1062         string map_next;
1063         map_next = argv(position);
1064         if(pass <= 1)
1065         {
1066                 if(Map_IsRecent(map_next))
1067                         return 0;
1068         }
1069         filename = Map_Filename(position);
1070         if(MapInfo_CheckMap(map_next))
1071         {
1072                 if(pass == 2)
1073                         return 1;
1074                 if(MapHasRightSize(map_next))
1075                         return 1;
1076                 return 0;
1077         }
1078         else
1079                 dprint( "Couldn't select '", filename, "'..\n" );
1080
1081         return 0;
1082 }
1083
1084 void Map_Goto_SetStr(string nextmapname)
1085 {
1086         if(getmapname_stored != "")
1087                 strunzone(getmapname_stored);
1088         if(nextmapname == "")
1089                 getmapname_stored = "";
1090         else
1091                 getmapname_stored = strzone(nextmapname);
1092 }
1093
1094 void Map_Goto_SetFloat(float position)
1095 {
1096         cvar_set("g_maplist_index", ftos(position));
1097         Map_Goto_SetStr(argv(position));
1098 }
1099
1100 void Map_Goto(float reinit)
1101 {
1102         MapInfo_LoadMap(getmapname_stored, reinit);
1103 }
1104
1105 // return codes of map selectors:
1106 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1107 //   -2 = permanent failure
1108 float() MaplistMethod_Iterate = // usual method
1109 {
1110         float pass, i;
1111
1112         for(pass = 1; pass <= 2; ++pass)
1113         {
1114                 for(i = 1; i < Map_Count; ++i)
1115                 {
1116                         float mapindex;
1117                         mapindex = mod(i + Map_Current, Map_Count);
1118                         if(Map_Check(mapindex, pass))
1119                                 return mapindex;
1120                 }
1121         }
1122         return -1;
1123 }
1124
1125 float() MaplistMethod_Repeat = // fallback method
1126 {
1127         if(Map_Check(Map_Current, 2))
1128                 return Map_Current;
1129         return -2;
1130 }
1131
1132 float() MaplistMethod_Random = // random map selection
1133 {
1134         float i, imax;
1135
1136         imax = 42;
1137
1138         for(i = 0; i <= imax; ++i)
1139         {
1140                 float mapindex;
1141                 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
1142                 if(Map_Check(mapindex, 1))
1143                         return mapindex;
1144         }
1145         return -1;
1146 }
1147
1148 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1149 // the exponent sets a bias on the map selection:
1150 // the higher the exponent, the less likely "shortly repeated" same maps are
1151 {
1152         float i, j, imax, insertpos;
1153
1154         imax = 42;
1155
1156         for(i = 0; i <= imax; ++i)
1157         {
1158                 string newlist;
1159
1160                 // now reinsert this at another position
1161                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1162                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1163                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1164                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1165
1166                 // insert the current map there
1167                 newlist = "";
1168                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1169                         newlist = strcat(newlist, " ", argv(j));
1170                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1171                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1172                         newlist = strcat(newlist, " ", argv(j));
1173                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1174                 cvar_set("g_maplist", newlist);
1175                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1176
1177                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1178                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1179                 if(Map_Check(Map_Current, 1))
1180                         return Map_Current;
1181         }
1182         return -1;
1183 }
1184
1185 void Maplist_Init()
1186 {
1187         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1188         if(Map_Count == 0)
1189         {
1190                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
1191                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1192                 if(autocvar_g_maplist_shuffle)
1193                         ShuffleMaplist();
1194                 localcmd("\nmenu_cmd sync\n");
1195                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1196         }
1197         if(Map_Count == 0)
1198                 error("empty maplist, cannot select a new map");
1199         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1200
1201         if(Map_Current_Name)
1202                 strunzone(Map_Current_Name);
1203         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1204         // this may or may not be correct, but who cares, in the worst case a map
1205         // isn't chosen in the first pass that should have been
1206 }
1207
1208 string GetNextMap()
1209 {
1210         float nextMap;
1211
1212         Maplist_Init();
1213         nextMap = -1;
1214
1215         if(nextMap == -1)
1216                 if(autocvar_g_maplist_shuffle > 0)
1217                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1218
1219         if(nextMap == -1)
1220                 if(autocvar_g_maplist_selectrandom)
1221                         nextMap = MaplistMethod_Random();
1222
1223         if(nextMap == -1)
1224                 nextMap = MaplistMethod_Iterate();
1225
1226         if(nextMap == -1)
1227                 nextMap = MaplistMethod_Repeat();
1228
1229         if(nextMap >= 0)
1230         {
1231                 Map_Goto_SetFloat(nextMap);
1232                 return getmapname_stored;
1233         }
1234
1235         return "";
1236 }
1237
1238 float DoNextMapOverride(float reinit)
1239 {
1240         if(autocvar_g_campaign)
1241         {
1242                 CampaignPostIntermission();
1243                 alreadychangedlevel = TRUE;
1244                 return TRUE;
1245         }
1246         if(autocvar_quit_when_empty)
1247         {
1248                 if(player_count <= currentbots)
1249                 {
1250                         localcmd("quit\n");
1251                         alreadychangedlevel = TRUE;
1252                         return TRUE;
1253                 }
1254         }
1255         if(autocvar_quit_and_redirect != "")
1256         {
1257                 redirection_target = strzone(autocvar_quit_and_redirect);
1258                 alreadychangedlevel = TRUE;
1259                 return TRUE;
1260         }
1261         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1262         {
1263                 localcmd("restart\n");
1264                 alreadychangedlevel = TRUE;
1265                 return TRUE;
1266         }
1267         if(autocvar_nextmap != "")
1268                 if(MapInfo_CheckMap(autocvar_nextmap))
1269                 {
1270                         Map_Goto_SetStr(autocvar_nextmap);
1271                         Map_Goto(reinit);
1272                         alreadychangedlevel = TRUE;
1273                         return TRUE;
1274                 }
1275         if(!reinit && autocvar_lastlevel)
1276         {
1277                 cvar_settemp_restore();
1278                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1279                 alreadychangedlevel = TRUE;
1280                 return TRUE;
1281         }
1282         return FALSE;
1283 }
1284
1285 void GotoNextMap(float reinit)
1286 {
1287         //string nextmap;
1288         //float n, nummaps;
1289         //string s;
1290         if (alreadychangedlevel)
1291                 return;
1292         alreadychangedlevel = TRUE;
1293
1294         {
1295                 string nextMap;
1296                 float allowReset;
1297
1298                 for(allowReset = 1; allowReset >= 0; --allowReset)
1299                 {
1300                         nextMap = GetNextMap();
1301                         if(nextMap != "")
1302                                 break;
1303
1304                         if(allowReset)
1305                         {
1306                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1307                                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1308                                 if(autocvar_g_maplist_shuffle)
1309                                         ShuffleMaplist();
1310                                 localcmd("\nmenu_cmd sync\n");
1311                         }
1312                         else
1313                         {
1314                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1315                         }
1316                 }
1317                 Map_Goto(reinit);
1318         }
1319 }
1320
1321
1322 /*
1323 ============
1324 IntermissionThink
1325
1326 When the player presses attack or jump, change to the next level
1327 ============
1328 */
1329 .float autoscreenshot;
1330 void() MapVote_Start;
1331 void() MapVote_Think;
1332 float mapvote_initialized;
1333 void IntermissionThink()
1334 {
1335         FixIntermissionClient(self);
1336
1337         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1338         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1339
1340         if( (server_screenshot || client_screenshot)
1341                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1342         {
1343                 self.autoscreenshot = -1;
1344                 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"))); }
1345                 return;
1346         }
1347
1348         if (time < intermission_exittime)
1349                 return;
1350
1351         if(!mapvote_initialized)
1352                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1353                         return;
1354
1355         MapVote_Start();
1356 }
1357
1358 /*
1359 ============
1360 FindIntermission
1361
1362 Returns the entity to view from
1363 ============
1364 */
1365 /*
1366 entity FindIntermission()
1367 {
1368         local   entity spot;
1369         local   float cyc;
1370
1371 // look for info_intermission first
1372         spot = find (world, classname, "info_intermission");
1373         if (spot)
1374         {       // pick a random one
1375                 cyc = random() * 4;
1376                 while (cyc > 1)
1377                 {
1378                         spot = find (spot, classname, "info_intermission");
1379                         if (!spot)
1380                                 spot = find (spot, classname, "info_intermission");
1381                         cyc = cyc - 1;
1382                 }
1383                 return spot;
1384         }
1385
1386 // then look for the start position
1387         spot = find (world, classname, "info_player_start");
1388         if (spot)
1389                 return spot;
1390
1391 // testinfo_player_start is only found in regioned levels
1392         spot = find (world, classname, "testplayerstart");
1393         if (spot)
1394                 return spot;
1395
1396 // then look for the start position
1397         spot = find (world, classname, "info_player_deathmatch");
1398         if (spot)
1399                 return spot;
1400
1401         //objerror ("FindIntermission: no spot");
1402         return world;
1403 }
1404 */
1405
1406 /*
1407 ===============================================================================
1408
1409 RULES
1410
1411 ===============================================================================
1412 */
1413
1414 void DumpStats(float final)
1415 {
1416         float file;
1417         string s;
1418         float to_console;
1419         float to_eventlog;
1420         float to_file;
1421         float i;
1422
1423         to_console = autocvar_sv_logscores_console;
1424         to_eventlog = autocvar_sv_eventlog;
1425         to_file = autocvar_sv_logscores_file;
1426
1427         if(!final)
1428         {
1429                 to_console = TRUE; // always print printstats replies
1430                 to_eventlog = FALSE; // but never print them to the event log
1431         }
1432
1433         if(to_eventlog)
1434                 if(autocvar_sv_eventlog_console)
1435                         to_console = FALSE; // otherwise we get the output twice
1436
1437         if(final)
1438                 s = ":scores:";
1439         else
1440                 s = ":status:";
1441         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1442
1443         if(to_console)
1444                 print(s, "\n");
1445         if(to_eventlog)
1446                 GameLogEcho(s);
1447
1448         file = -1;
1449         if(to_file)
1450         {
1451                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1452                 if(file == -1)
1453                         to_file = FALSE;
1454                 else
1455                         fputs(file, strcat(s, "\n"));
1456         }
1457
1458         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1459         if(to_console)
1460                 print(s, "\n");
1461         if(to_eventlog)
1462                 GameLogEcho(s);
1463         if(to_file)
1464                 fputs(file, strcat(s, "\n"));
1465
1466         FOR_EACH_CLIENT(other)
1467         {
1468                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && autocvar_sv_logscores_bots))
1469                 {
1470                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1471                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1472                         if(other.classname == "player" || g_arena || g_ca || g_lms)
1473                                 s = strcat(s, ftos(other.team), ":");
1474                         else
1475                                 s = strcat(s, "spectator:");
1476
1477                         if(to_console)
1478                                 print(s, other.netname, "\n");
1479                         if(to_eventlog)
1480                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1481                         if(to_file)
1482                                 fputs(file, strcat(s, other.netname, "\n"));
1483                 }
1484         }
1485
1486         if(teamplay)
1487         {
1488                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1489                 if(to_console)
1490                         print(s, "\n");
1491                 if(to_eventlog)
1492                         GameLogEcho(s);
1493                 if(to_file)
1494                         fputs(file, strcat(s, "\n"));
1495
1496                 for(i = 1; i < 16; ++i)
1497                 {
1498                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1499                         s = strcat(s, ":", ftos(i));
1500                         if(to_console)
1501                                 print(s, "\n");
1502                         if(to_eventlog)
1503                                 GameLogEcho(s);
1504                         if(to_file)
1505                                 fputs(file, strcat(s, "\n"));
1506                 }
1507         }
1508
1509         if(to_console)
1510                 print(":end\n");
1511         if(to_eventlog)
1512                 GameLogEcho(":end");
1513         if(to_file)
1514         {
1515                 fputs(file, ":end\n");
1516                 fclose(file);
1517         }
1518 }
1519
1520 void FixIntermissionClient(entity e)
1521 {
1522         string s;
1523         if(!e.autoscreenshot) // initial call
1524         {
1525                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1526                 e.health = -2342;
1527                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1528                 e.solid = SOLID_NOT;
1529                 e.movetype = MOVETYPE_NONE;
1530                 e.takedamage = DAMAGE_NO;
1531                 if(e.weaponentity)
1532                 {
1533                         e.weaponentity.effects = EF_NODRAW;
1534                         if (e.weaponentity.weaponentity)
1535                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1536                 }
1537                 if(clienttype(e) == CLIENTTYPE_REAL)
1538                 {
1539                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1540                         s = autocvar_sv_intermission_cdtrack;
1541                         if(s != "")
1542                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1543                         msg_entity = e;
1544                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1545                 }
1546         }
1547 }
1548
1549 void minstagib_stop_countdown(entity e);
1550 /*
1551 go to the next level for deathmatch
1552 only called if a time or frag limit has expired
1553 */
1554 void NextLevel()
1555 {
1556         gameover = TRUE;
1557
1558         intermission_running = 1;
1559
1560 // enforce a wait time before allowing changelevel
1561         if(player_count > 0)
1562                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1563         else
1564                 intermission_exittime = -1;
1565
1566         /*
1567         WriteByte (MSG_ALL, SVC_CDTRACK);
1568         WriteByte (MSG_ALL, 3);
1569         WriteByte (MSG_ALL, 3);
1570         // done in FixIntermission
1571         */
1572
1573         //pos = FindIntermission ();
1574
1575         VoteReset();
1576
1577         DumpStats(TRUE);
1578
1579         // send statistics
1580         entity e;
1581         PlayerStats_EndMatch(1);
1582         FOR_EACH_CLIENT(e)
1583                 PlayerStats_AddGlobalInfo(e);
1584         PlayerStats_Shutdown();
1585         WeaponStats_Shutdown();
1586
1587         if(autocvar_sv_eventlog)
1588                 GameLogEcho(":gameover");
1589
1590         GameLogClose();
1591
1592         FOR_EACH_PLAYER(other) {
1593                 minstagib_stop_countdown(other);
1594                 FixIntermissionClient(other);
1595                 if(other.winning)
1596                         bprint(other.netname, " ^7wins.\n");
1597         }
1598
1599         if(autocvar_g_campaign)
1600                 CampaignPreIntermission();
1601
1602         MUTATOR_CALLHOOK(MatchEnd);
1603
1604         localcmd("\nsv_hook_gameend\n");
1605 }
1606
1607 /*
1608 ============
1609 CheckRules_Player
1610
1611 Exit deathmatch games upon conditions
1612 ============
1613 */
1614 void CheckRules_Player()
1615 {
1616         if (gameover)   // someone else quit the game already
1617                 return;
1618
1619         if(self.deadflag == DEAD_NO)
1620                 self.play_time += frametime;
1621
1622         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1623         //   (div0: and that in CheckRules_World please)
1624 }
1625
1626 float checkrules_equality;
1627 float checkrules_suddendeathwarning;
1628 float checkrules_suddendeathend;
1629 float checkrules_overtimesadded; //how many overtimes have been already added
1630
1631 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1632 float WINNING_YES = 1; // winner found
1633 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1634 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1635
1636 float InitiateSuddenDeath()
1637 {
1638         // Check first whether normal overtimes could be added before initiating suddendeath mode
1639         // - for this timelimit_overtime needs to be >0 of course
1640         // - also check the winning condition calculated in the previous frame and only add normal overtime
1641         //   again, if at the point at which timelimit would be extended again, still no winner was found
1642         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1643         {
1644                 return 1; // need to call InitiateOvertime later
1645         }
1646         else
1647         {
1648                 if(!checkrules_suddendeathend)
1649                 {
1650                         if(autocvar_g_campaign)
1651                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1652                         else
1653                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1654                         if(g_race && !g_race_qualifying)
1655                                 race_StartCompleting();
1656                 }
1657                 return 0;
1658         }
1659 }
1660
1661 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1662 {
1663         ++checkrules_overtimesadded;
1664         //add one more overtime by simply extending the timelimit
1665         float tl;
1666         tl = autocvar_timelimit;
1667         tl += autocvar_timelimit_overtime;
1668         cvar_set("timelimit", ftos(tl));
1669         string minutesPlural;
1670         if (autocvar_timelimit_overtime == 1)
1671                 minutesPlural = " ^3minute";
1672         else
1673                 minutesPlural = " ^3minutes";
1674
1675         bcenterprint(
1676                 strcat(
1677                         "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1678                         ftos(autocvar_timelimit_overtime),
1679                         minutesPlural,
1680                         " to the game!"
1681                 )
1682         );
1683 }
1684
1685 float GetWinningCode(float fraglimitreached, float equality)
1686 {
1687         if(autocvar_g_campaign == 1)
1688                 if(fraglimitreached)
1689                         return WINNING_YES;
1690                 else
1691                         return WINNING_NO;
1692
1693         else
1694                 if(equality)
1695                         if(fraglimitreached)
1696                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1697                         else
1698                                 return WINNING_NEVER;
1699                 else
1700                         if(fraglimitreached)
1701                                 return WINNING_YES;
1702                         else
1703                                 return WINNING_NO;
1704 }
1705
1706 // set the .winning flag for exactly those players with a given field value
1707 void SetWinners(.float field, float value)
1708 {
1709         entity head;
1710         FOR_EACH_PLAYER(head)
1711                 head.winning = (head.field == value);
1712 }
1713
1714 // set the .winning flag for those players with a given field value
1715 void AddWinners(.float field, float value)
1716 {
1717         entity head;
1718         FOR_EACH_PLAYER(head)
1719                 if(head.field == value)
1720                         head.winning = 1;
1721 }
1722
1723 // clear the .winning flags
1724 void ClearWinners(void)
1725 {
1726         entity head;
1727         FOR_EACH_PLAYER(head)
1728                 head.winning = 0;
1729 }
1730
1731 // Onslaught winning condition:
1732 // game terminates if only one team has a working generator (or none)
1733 float WinningCondition_Onslaught()
1734 {
1735         entity head;
1736         float t1, t2, t3, t4;
1737
1738         WinningConditionHelper(); // set worldstatus
1739
1740         if(inWarmupStage)
1741                 return WINNING_NO;
1742
1743         // first check if the game has ended
1744         t1 = t2 = t3 = t4 = 0;
1745         head = find(world, classname, "onslaught_generator");
1746         while (head)
1747         {
1748                 if (head.health > 0)
1749                 {
1750                         if (head.team == COLOR_TEAM1) t1 = 1;
1751                         if (head.team == COLOR_TEAM2) t2 = 1;
1752                         if (head.team == COLOR_TEAM3) t3 = 1;
1753                         if (head.team == COLOR_TEAM4) t4 = 1;
1754                 }
1755                 head = find(head, classname, "onslaught_generator");
1756         }
1757         if (t1 + t2 + t3 + t4 < 2)
1758         {
1759                 // game over, only one team remains (or none)
1760                 ClearWinners();
1761                 if (t1) SetWinners(team, COLOR_TEAM1);
1762                 if (t2) SetWinners(team, COLOR_TEAM2);
1763                 if (t3) SetWinners(team, COLOR_TEAM3);
1764                 if (t4) SetWinners(team, COLOR_TEAM4);
1765                 dprint("Have a winner, ending game.\n");
1766                 return WINNING_YES;
1767         }
1768
1769         // Two or more teams remain
1770         return WINNING_NO;
1771 }
1772
1773 float LMS_NewPlayerLives()
1774 {
1775         float fl;
1776         fl = autocvar_fraglimit;
1777         if(fl == 0)
1778                 fl = 999;
1779
1780         // first player has left the game for dying too much? Nobody else can get in.
1781         if(lms_lowest_lives < 1)
1782                 return 0;
1783
1784         if(!autocvar_g_lms_join_anytime)
1785                 if(lms_lowest_lives < fl - autocvar_g_lms_last_join)
1786                         return 0;
1787
1788         return bound(1, lms_lowest_lives, fl);
1789 }
1790
1791 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1792 // they win. Otherwise the defending team wins once the timelimit passes.
1793 void assault_new_round();
1794 float WinningCondition_Assault()
1795 {
1796         float status;
1797
1798         WinningConditionHelper(); // set worldstatus
1799
1800         status = WINNING_NO;
1801         // as the timelimit has not yet passed just assume the defending team will win
1802         if(assault_attacker_team == COLOR_TEAM1)
1803         {
1804                 SetWinners(team, COLOR_TEAM2);
1805         }
1806         else
1807         {
1808                 SetWinners(team, COLOR_TEAM1);
1809         }
1810
1811         entity ent;
1812         ent = find(world, classname, "target_assault_roundend");
1813         if(ent)
1814         {
1815                 if(ent.winning) // round end has been triggered by attacking team
1816                 {
1817                         bprint("ASSAULT: round completed...\n");
1818                         SetWinners(team, assault_attacker_team);
1819
1820                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1821
1822                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1823                         {
1824                                 status = WINNING_YES;
1825                         }
1826                         else
1827                         {
1828                                 entity oldself;
1829                                 oldself = self;
1830                                 self = ent;
1831                                 assault_new_round();
1832                                 self = oldself;
1833                         }
1834                 }
1835         }
1836
1837         return status;
1838 }
1839
1840 // LMS winning condition: game terminates if and only if there's at most one
1841 // one player who's living lives. Top two scores being equal cancels the time
1842 // limit.
1843 float WinningCondition_LMS()
1844 {
1845         entity head, head2;
1846         float have_player;
1847         float have_players;
1848         float l;
1849
1850         have_player = FALSE;
1851         have_players = FALSE;
1852         l = LMS_NewPlayerLives();
1853
1854         head = find(world, classname, "player");
1855         if(head)
1856                 have_player = TRUE;
1857         head2 = find(head, classname, "player");
1858         if(head2)
1859                 have_players = TRUE;
1860
1861         if(have_player)
1862         {
1863                 // we have at least one player
1864                 if(have_players)
1865                 {
1866                         // two or more active players - continue with the game
1867                 }
1868                 else
1869                 {
1870                         // exactly one player?
1871
1872                         ClearWinners();
1873                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1874
1875                         if(l)
1876                         {
1877                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1878                                 return WINNING_NO;
1879                         }
1880                         else
1881                         {
1882                                 // a winner!
1883                                 // and assign him his first place
1884                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1885                                 return WINNING_YES;
1886                         }
1887                 }
1888         }
1889         else
1890         {
1891                 // nobody is playing at all...
1892                 if(l)
1893                 {
1894                         // wait for players...
1895                 }
1896                 else
1897                 {
1898                         // SNAFU (maybe a draw game?)
1899                         ClearWinners();
1900                         dprint("No players, ending game.\n");
1901                         return WINNING_YES;
1902                 }
1903         }
1904
1905         // When we get here, we have at least two players who are actually LIVING,
1906         // now check if the top two players have equal score.
1907         WinningConditionHelper();
1908
1909         ClearWinners();
1910         if(WinningConditionHelper_winner)
1911                 WinningConditionHelper_winner.winning = TRUE;
1912         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1913                 return WINNING_NEVER;
1914
1915         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1916         return WINNING_NO;
1917 }
1918
1919 void ShuffleMaplist()
1920 {
1921         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1922 }
1923
1924 float leaderfrags;
1925 float WinningCondition_Scores(float limit, float leadlimit)
1926 {
1927         float limitreached;
1928
1929         // TODO make everything use THIS winning condition (except LMS)
1930         WinningConditionHelper();
1931
1932         if(teamplay)
1933         {
1934                 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1935                 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1936                 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1937                 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1938         }
1939
1940         ClearWinners();
1941         if(WinningConditionHelper_winner)
1942                 WinningConditionHelper_winner.winning = 1;
1943         if(WinningConditionHelper_winnerteam >= 0)
1944                 SetWinners(team, WinningConditionHelper_winnerteam);
1945
1946         if(WinningConditionHelper_lowerisbetter)
1947         {
1948                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1949                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1950                 limit = -limit;
1951         }
1952
1953         if(WinningConditionHelper_zeroisworst)
1954                 leadlimit = 0; // not supported in this mode
1955
1956         if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1957         // these modes always score in increments of 1, thus this makes sense
1958         {
1959                 if(leaderfrags != WinningConditionHelper_topscore)
1960                 {
1961                         leaderfrags = WinningConditionHelper_topscore;
1962
1963                         if (limit)
1964                         if (leaderfrags == limit - 1)
1965                                 Announce("1fragleft");
1966                         else if (leaderfrags == limit - 2)
1967                                 Announce("2fragsleft");
1968                         else if (leaderfrags == limit - 3)
1969                                 Announce("3fragsleft");
1970                 }
1971         }
1972
1973         limitreached = FALSE;
1974         if(limit)
1975                 if(WinningConditionHelper_topscore >= limit)
1976                         limitreached = TRUE;
1977         if(leadlimit)
1978         {
1979                 float leadlimitreached;
1980                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1981                 if(autocvar_leadlimit_and_fraglimit)
1982                         limitreached = (limitreached && leadlimitreached);
1983                 else
1984                         limitreached = (limitreached || leadlimitreached);
1985         }
1986
1987         if(limit)
1988                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1989
1990         return GetWinningCode(
1991                 WinningConditionHelper_topscore && limitreached,
1992                 WinningConditionHelper_equality
1993         );
1994 }
1995
1996 float WinningCondition_Race(float fraglimit)
1997 {
1998         float wc;
1999         entity p;
2000         float n, c;
2001
2002         n = 0;
2003         c = 0;
2004         FOR_EACH_PLAYER(p)
2005         {
2006                 ++n;
2007                 if(p.race_completed)
2008                         ++c;
2009         }
2010         if(n && (n == c))
2011                 return WINNING_YES;
2012         wc = WinningCondition_Scores(fraglimit, 0);
2013
2014         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
2015         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
2016         // do NOT support equality when the laps are all raced!
2017                 return WINNING_STARTSUDDENDEATHOVERTIME;
2018         else
2019                 return WINNING_NEVER;
2020 }
2021
2022 float WinningCondition_QualifyingThenRace(float limit)
2023 {
2024         float wc;
2025         wc = WinningCondition_Scores(limit, 0);
2026
2027         // NEVER initiate overtime
2028         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
2029         {
2030                 return WINNING_YES;
2031         }
2032
2033         return wc;
2034 }
2035
2036 float WinningCondition_RanOutOfSpawns()
2037 {
2038         entity head;
2039
2040         if(have_team_spawns <= 0)
2041                 return WINNING_NO;
2042
2043         if(autocvar_g_spawn_useallspawns <= 0)
2044                 return WINNING_NO;
2045
2046         if(!some_spawn_has_been_used)
2047                 return WINNING_NO;
2048
2049         team1_score = team2_score = team3_score = team4_score = 0;
2050
2051         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
2052         {
2053                 if(head.team == COLOR_TEAM1)
2054                         team1_score = 1;
2055                 else if(head.team == COLOR_TEAM2)
2056                         team2_score = 1;
2057                 else if(head.team == COLOR_TEAM3)
2058                         team3_score = 1;
2059                 else if(head.team == COLOR_TEAM4)
2060                         team4_score = 1;
2061         }
2062
2063         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
2064         {
2065                 if(head.team == COLOR_TEAM1)
2066                         team1_score = 1;
2067                 else if(head.team == COLOR_TEAM2)
2068                         team2_score = 1;
2069                 else if(head.team == COLOR_TEAM3)
2070                         team3_score = 1;
2071                 else if(head.team == COLOR_TEAM4)
2072                         team4_score = 1;
2073         }
2074
2075         ClearWinners();
2076         if(team1_score + team2_score + team3_score + team4_score == 0)
2077         {
2078                 checkrules_equality = TRUE;
2079                 return WINNING_YES;
2080         }
2081         else if(team1_score + team2_score + team3_score + team4_score == 1)
2082         {
2083                 float t, i;
2084                 if(team1_score)
2085                         t = COLOR_TEAM1;
2086                 else if(team2_score)
2087                         t = COLOR_TEAM2;
2088                 else if(team3_score)
2089                         t = COLOR_TEAM3;
2090                 else // if(team4_score)
2091                         t = COLOR_TEAM4;
2092                 CheckAllowedTeams(world);
2093                 for(i = 0; i < MAX_TEAMSCORE; ++i)
2094                 {
2095                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
2096                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
2097                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
2098                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
2099                 }
2100
2101                 AddWinners(team, t);
2102                 return WINNING_YES;
2103         }
2104         else
2105                 return WINNING_NO;
2106 }
2107
2108 /*
2109 ============
2110 CheckRules_World
2111
2112 Exit deathmatch games upon conditions
2113 ============
2114 */
2115 void ReadyRestart();
2116 void CheckRules_World()
2117 {
2118         float timelimit;
2119         float fraglimit;
2120         float leadlimit;
2121
2122         VoteThink();
2123         MapVote_Think();
2124
2125         SetDefaultAlpha();
2126
2127         /*
2128         MapVote_Think should now do that part
2129         if (intermission_running)
2130                 if (time >= intermission_exittime + 60)
2131                 {
2132                         if(!DoNextMapOverride())
2133                                 GotoNextMap();
2134                         return;
2135                 }
2136         */
2137
2138         if (gameover)   // someone else quit the game already
2139         {
2140                 if(player_count == 0) // Nobody there? Then let's go to the next map
2141                         MapVote_Start();
2142                         // this will actually check the player count in the next frame
2143                         // again, but this shouldn't hurt
2144                 return;
2145         }
2146
2147         timelimit = autocvar_timelimit * 60;
2148         fraglimit = autocvar_fraglimit;
2149         leadlimit = autocvar_leadlimit;
2150
2151         if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2152         {
2153                 if(timelimit > 0)
2154                         timelimit = 0; // timelimit is not made for warmup
2155                 if(fraglimit > 0)
2156                         fraglimit = 0; // no fraglimit for now
2157                 leadlimit = 0; // no leadlimit for now
2158         }
2159
2160         if(timelimit > 0)
2161         {
2162                 timelimit += game_starttime;
2163         }
2164         else if (timelimit < 0)
2165         {
2166                 // endmatch
2167                 NextLevel();
2168                 return;
2169         }
2170
2171         if(g_onslaught)
2172                 timelimit = 0; // ONS has its own overtime rule
2173
2174         float wantovertime;
2175         wantovertime = 0;
2176
2177         if(timelimit > game_starttime)
2178                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2179         else
2180                 game_completion_ratio = 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 not(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 }