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