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