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