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