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