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