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