]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
change all spawn functions to use the spawnfunc_ prefix; sync dpextensions
[divverent/nexuiz.git] / data / qcsrc / server / g_world.qc
1 float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
2 string redirection_target;
3 float world_initialized;
4
5 string GetMapname();
6 string GetGametype();
7 void GotoNextMap();
8 void ShuffleMaplist()
9 float() DoNextMapOverride;
10
11 void SetDefaultAlpha()
12 {
13         if(cvar("g_running_guns"))
14         {
15                 default_player_alpha = -1;
16                 default_weapon_alpha = +1;
17         }
18         else if(g_cloaked)
19         {
20                 default_player_alpha = cvar("g_balance_cloaked_alpha");
21                 default_weapon_alpha = default_player_alpha;
22         }
23         else
24         {
25                 default_player_alpha = cvar("g_player_alpha");
26                 if(default_player_alpha <= 0)
27                         default_player_alpha = 1;
28                 default_weapon_alpha = default_player_alpha;
29         }
30 }
31
32 void fteqcc_testbugs()
33 {
34         float a, b;
35
36         if(!cvar("developer_fteqccbugs"))
37                 return;
38
39         dprint("*** fteqcc test: checking for bugs...\n");
40
41         a = 1;
42         b = 5;
43         if(sqrt(a) - sqrt(b - a) == 0)
44                 dprint("*** fteqcc test: found same-function-twice bug\n");
45         else
46                 dprint("*** fteqcc test: same-function-twice bug got FINALLY FIXED! HOORAY!\n");
47
48         world.frags = -10;
49         world.enemy = world;
50         world.enemy.frags += 10;
51         if(world.frags > 0.2 || world.frags < -0.2) // don't error out if it's just roundoff errors
52                 dprint("*** fteqcc test: found += bug\n");
53         else
54                 dprint("*** fteqcc test: += bug got FINALLY FIXED! HOORAY!\n");
55         world.frags = 0;
56 }
57
58 /**
59  * Takes care of pausing and unpausing the game.
60  * Centerprints the information about an upcoming or active timeout to all active
61  * players. Also plays reminder sounds.
62  */
63 void timeoutHandler_Think() {
64         local string timeStr;
65         local entity plr;
66         if (timeoutStatus == 1) {
67                 if (remainingLeadTime > 0) {
68                         //centerprint the information to every player
69                         timeStr = getTimeoutText(0);
70                         FOR_EACH_REALCLIENT(plr) {
71                                 if(plr.classname == "player") {
72                                         centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
73                                 }
74                         }
75                         remainingLeadTime -= 1;
76                         //think again in 1 second:
77                         self.nextthink = time + 1;
78                 }
79                 else {
80                         //now pause the game:
81                         timeoutStatus = 2;
82                         cvar_set("slowmo", ftos(TIMEOUT_SLOWMO_VALUE));
83                         //copy .v_angle to .lastV_angle for every player in order to fix their view during pause (see PlayerPreThink)
84                         FOR_EACH_REALPLAYER(plr) {
85                                 plr.lastV_angle = plr.v_angle;
86                         }
87                         self.nextthink = time;
88                 }
89         }
90         else if (timeoutStatus == 2) {
91                 if (remainingTimeoutTime > 0) {
92                         timeStr = getTimeoutText(0);
93                         FOR_EACH_REALCLIENT(plr) {
94                                 if(plr.classname == "player") {
95                                         centerprint_atprio(plr, CENTERPRIO_SPAM, timeStr);
96                                 }
97                         }
98                         if(remainingTimeoutTime == cvar("sv_timeout_resumetime")) { //play a warning sound when only <sv_timeout_resumetime> seconds are left
99                                 sound(world, CHAN_AUTO, "announcer/robotic/prepareforbattle.wav", 1, ATTN_NONE);
100                         }
101                         remainingTimeoutTime -= 1;
102                         self.nextthink = time + TIMEOUT_SLOWMO_VALUE;
103                 }
104                 else {
105                         //unpause the game again
106                         remainingTimeoutTime = timeoutStatus = 0;
107                         cvar_set("slowmo", ftos(orig_slowmo));
108                         //and unlock the fixed view again once there is no timeout active anymore
109                         FOR_EACH_REALPLAYER(plr) {
110                                 plr.fixangle = FALSE;
111                         }
112                         //get rid of the countdown message
113                         FOR_EACH_REALCLIENT(plr) {
114                                 if(plr.classname == "player") {
115                                         centerprint_atprio(plr, CENTERPRIO_SPAM, "");
116                                 }
117                         }
118                         remove(self);
119                         return;
120                 }
121                 
122         }
123         else if (timeoutStatus == 0) { //if a player called the resumegame command (which set timeoutStatus to 0 already)
124                 FOR_EACH_REALCLIENT(plr) {
125                         if(plr.classname == "player") {
126                                 centerprint_atprio(plr, CENTERPRIO_SPAM, "");
127                         }
128                 }
129                 remove(self);
130                 return;
131         }
132 }
133
134 float GotoFirstMap()
135 {
136         if(cvar("_sv_init"))
137         {
138                 cvar_set("_sv_init", "0");
139                 if(cvar("g_maplist_shuffle"))
140                         ShuffleMaplist();
141 #ifdef MAPINFO
142                 tokenizebyseparator(cvar_string("g_maplist"), " ");
143 #else
144                 tokenize(cvar_string("g_maplist"));
145                 if(argv(0) != GetMapname())
146 #endif
147                 {
148                         cvar_set("nextmap", argv(0));
149
150 #ifdef MAPINFO
151                         MapInfo_Enumerate();
152                         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 0);
153 #endif
154
155                         if(!DoNextMapOverride())
156                                 GotoNextMap();
157
158                         return 1;
159                 }
160         }
161         return 0;
162 }
163
164 float world_already_spawned;
165 void spawnfunc_worldspawn (void)
166 {
167         dprint_load(); // load dprint status from cvar
168
169         if(world_already_spawned)
170                 error("world already spawned - you may have EXACTLY ONE spawnfunc_worldspawn!");
171         world_already_spawned = TRUE;
172
173         if(GotoFirstMap())
174                 return;
175
176 #ifdef MAPINFO
177         MapInfo_LoadMapSettings(mapname);
178 #endif
179
180         if(sv_cheats)
181                 ServerProgsDB = db_create();
182         else
183                 ServerProgsDB = db_load("server.db");
184
185         /*
186         TODO sound pack system
187         // initialize sound pack system
188         soundpack = cvar_string("g_soundpack");
189         if(soundpack != "")
190                 soundpack = strcat(soundpack, "/");
191         soundpack = strzone(soundpack);
192         */
193
194         // 0 normal
195         lightstyle(0, "m");
196
197         // 1 FLICKER (first variety)
198         lightstyle(1, "mmnmmommommnonmmonqnmmo");
199
200         // 2 SLOW STRONG PULSE
201         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
202
203         // 3 CANDLE (first variety)
204         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
205
206         // 4 FAST STROBE
207         lightstyle(4, "mamamamamama");
208
209         // 5 GENTLE PULSE 1
210         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
211
212         // 6 FLICKER (second variety)
213         lightstyle(6, "nmonqnmomnmomomno");
214
215         // 7 CANDLE (second variety)
216         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
217
218         // 8 CANDLE (third variety)
219         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
220
221         // 9 SLOW STROBE (fourth variety)
222         lightstyle(9, "aaaaaaaazzzzzzzz");
223
224         // 10 FLUORESCENT FLICKER
225         lightstyle(10, "mmamammmmammamamaaamammma");
226
227         // 11 SLOW PULSE NOT FADE TO BLACK
228         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
229
230         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
231
232         // 63 testing
233         lightstyle(63, "a");
234
235         // for setting by mapinfo
236         q3acompat_machineshotgunswap = cvar("sv_q3acompat_machineshotgunswap");
237         cvar_set("sv_q3acompat_machineshotgunswap", "0");
238
239         player_count = 0;
240         lms_lowest_lives = 0;
241         lms_next_place = 0;
242
243         bot_waypoints_for_items = cvar("g_waypoints_for_items");
244         if(bot_waypoints_for_items == 1)
245                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
246                         bot_waypoints_for_items = 0;
247
248         if(cvar("g_campaign"))
249                 CampaignPreInit();
250
251         InitGameplayMode();
252         readlevelcvars();
253         precache();
254
255         WaypointSprite_Init();
256
257         //if (g_domination)
258         //      dom_init();
259
260         local entity head;
261         head = nextent(world);
262         maxclients = 0;
263         while(head)
264         {
265                 maxclients++;
266                 head = nextent(head);
267         }
268
269         GameLogInit(); // prepare everything
270         if(cvar("sv_eventlog"))
271         {
272                 local string s;
273                 GameLogEcho(":logversion:2", FALSE);
274                 s = strcat(cvar_string("sv_eventlog_files_counter"), ".");
275                 s = strcat(s, ftos(random()));
276 #ifdef MAPINFO
277                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s), FALSE);
278 #else
279                 GameLogEcho(strcat(":gamestart:", GetMapname(), ":", s), FALSE);
280 #endif
281                 s = ":gameinfo:mutators:LIST";
282                 if(cvar("g_grappling_hook"))
283                         s = strcat(s, ":grappling_hook");
284                 if(!cvar("g_use_ammunition"))
285                         s = strcat(s, ":no_use_ammunition");
286                 if(!cvar("g_pickup_items"))
287                         s = strcat(s, ":no_pickup_items");
288                 if(cvar("g_instagib"))
289                         s = strcat(s, ":instagib");
290                 if(cvar("g_rocketarena"))
291                         s = strcat(s, ":rockerarena");
292                 if(cvar("g_nixnex"))
293                         s = strcat(s, ":nixnex");
294                 if(cvar("g_vampire"))
295                         s = strcat(s, ":vampire");
296                 if(cvar("g_laserguided_missile"))
297                         s = strcat(s, ":laserguided_missile");
298                 if(cvar("g_norecoil"))
299                         s = strcat(s, ":norecoil");
300                 if(cvar("g_midair"))
301                         s = strcat(s, ":midair");
302                 if(cvar("g_minstagib"))
303                         s = strcat(s, ":minstagib");
304                 GameLogEcho(s, FALSE);
305                 GameLogEcho(":gameinfo:end", FALSE);
306         }
307
308         cvar_set("nextmap", "");
309
310         SetDefaultAlpha();
311
312         if(cvar("g_campaign"))
313                 CampaignPostInit();
314
315         fteqcc_testbugs();
316
317         Ban_LoadBans();
318
319         //initialise globals related to sv_timeout
320         sys_ticrate = cvar("sys_ticrate");
321         orig_slowmo = cvar("slowmo");
322
323 #ifdef MAPINFO
324         MapInfo_Enumerate();
325         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1);
326 #endif
327
328         //if tourney is used map starts in warmup mode. if this mode shall stay unlimited, reset timelimit, but save the original one
329         if(g_tourney && cvar("g_tourney_warmup_unlimited_time")) {
330                 timelimit_orig = cvar("timelimit");
331                 cvar_set("timelimit", "0");
332         }
333
334         world_initialized = 1;
335 }
336
337 void spawnfunc_light (void)
338 {
339         //makestatic (self); // Who the f___ did that?
340         remove(self);
341 }
342
343 float( string pFilename ) TryFile =
344 {
345         local float lHandle;
346         dprint("TryFile(\"", pFilename, "\")\n");
347         lHandle = fopen( pFilename, FILE_READ );
348         if( lHandle != -1 ) {
349                 fclose( lHandle );
350                 return TRUE;
351         } else {
352                 return FALSE;
353         }
354 };
355
356 string GetGametype()
357 {
358         if (game == GAME_DEATHMATCH)
359                 return "dm";
360         else if (game == GAME_TEAM_DEATHMATCH)
361                 return "tdm";
362         else if (game == GAME_DOMINATION)
363                 return "dom";
364         else if (game == GAME_CTF)
365                 return "ctf";
366         else if (game == GAME_RUNEMATCH)
367                 return "rune";
368         else if (game == GAME_LMS)
369                 return "lms";
370         else if (game == GAME_KEYHUNT)
371                 return "kh";
372         else if (game == GAME_ONSLAUGHT)
373                 return "ons";
374         else if (game == GAME_ASSAULT)
375                 return "as";
376         return "dm";
377 }
378
379 float IsSameGametype(string mapcfgname)
380 {
381 #ifdef MAPINFO
382         return TRUE; // can't change game type by map name here
383 #else
384         string gt;
385         gt = GetGametype();
386         if(substring(mapcfgname, 0, strlen(gt) + 1) == strcat(gt, "_"))
387                 return TRUE;
388         return FALSE;
389 #endif
390 }
391
392 string getmapname_stored;
393 string GetMapname()
394 {
395 #ifdef MAPINFO
396         return mapname;
397 #else
398         if(getmapname_stored == "")
399                 getmapname_stored = strzone(strcat(GetGametype(), "_", mapname));
400         return getmapname_stored;
401 #endif
402 }
403
404 float Map_Count, Map_Current;
405 string Map_Current_Name;
406
407 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
408 float GetMaplistPosition()
409 {
410         float pos, idx;
411         string map;
412
413         map = GetMapname();
414         idx = cvar("g_maplist_index");
415
416         if(idx >= 0)
417                 if(idx < Map_Count)
418                         if(map == argv(idx))
419                                 return idx;
420
421         for(pos = 0; pos < Map_Count; ++pos)
422                 if(map == argv(pos))
423                         return pos;
424
425         // resume normal maplist rotation if current map is not in g_maplist
426         return idx;
427 }
428
429 float MapHasRightSize(string map)
430 {
431         float fh;
432         if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
433         if(cvar("g_maplist_check_waypoints"))
434         {
435                 dprint("checkwp "); dprint(map);
436                 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
437                 if(fh < 0)
438                 {
439                         dprint(": no waypoints\n");
440                         return FALSE;
441                 }
442                 dprint(": has waypoints\n");
443                 fclose(fh);
444         }
445
446         // open map size restriction file
447         dprint("opensize "); dprint(map);
448         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
449         if(fh >= 0)
450         {
451                 float mapmin, mapmax;
452                 dprint(": ok, ");
453                 mapmin = stof(fgets(fh));
454                 mapmax = stof(fgets(fh));
455                 fclose(fh);
456                 if(player_count < mapmin)
457                 {
458                         dprint("not enough\n");
459                         return FALSE;
460                 }
461                 if(player_count > mapmax)
462                 {
463                         dprint("too many\n");
464                         return FALSE;
465                 }
466                 dprint("right size\n");
467                 return TRUE;
468         }
469         dprint(": not found\n");
470         return TRUE;
471 }
472
473 string Map_Filename(float position)
474 {
475 #ifdef MAPINFO
476         return strcat("maps/", argv(position), ".bsp");
477 #else
478         return strcat("maps/", argv(position), ".mapcfg");
479 #endif
480 }
481
482 string strwords(string s, float w)
483 {
484         float endpos;
485         for(endpos = 0; w && endpos >= 0; --w)
486                 endpos = strstrofs(s, " ", endpos + 1);
487         if(endpos < 0)
488                 return s;
489         else
490                 return substring(s, 0, endpos);
491 }
492
493 float strhasword(string s, string w)
494 {
495         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
496 }
497
498 void Map_MarkAsRecent(string m)
499 {
500         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), cvar("g_maplist_mostrecent_count")));
501 }
502
503 float Map_IsRecent(string m)
504 {
505         return strhasword(cvar_string("g_maplist_mostrecent"), m);
506 }
507
508 float(float position, float pass) Map_Check =
509 {
510         string filename;
511         string map_next;
512         map_next = argv(position);
513         if(pass <= 1)
514         {
515                 if(map_next == Map_Current_Name) // same map again in first pass?
516                         return 0;
517                 if(Map_IsRecent(map_next))
518                         return 0;
519         }
520         filename = Map_Filename(position);
521 #ifdef MAPINFO
522         if(MapInfo_CheckMap(map_next))
523 #else
524         if(TryFile(filename))
525 #endif
526         {
527                 if(pass == 2)
528                         return 1;
529                 if(MapHasRightSize(map_next))
530                         return 1;
531                 return 0;
532         }
533         else
534                 dprint( "Couldn't select '", filename, "'..\n" );
535
536         return 0;
537 }
538
539 void(string nextmapname) Map_Goto_SetStr =
540 {
541         if(getmapname_stored != "")
542                 strunzone(getmapname_stored);
543         if(nextmapname == "")
544                 getmapname_stored = "";
545         else
546                 getmapname_stored = strzone(nextmapname);
547 }
548
549 void(float position) Map_Goto_SetFloat =
550 {
551         cvar_set("g_maplist_index", ftos(position));
552         Map_Goto_SetStr(argv(position));
553 }
554
555 void() GameResetCfg =
556 {
557 #ifdef MAPINFO
558         // settings persist, except...
559         if(cvar("g_campaign"))
560                 localcmd("\nexec mutator_reset.cfg\n");
561         localcmd("\nsettemp_restore\n");
562 #else
563         // if an exit cfg is defined by exiting map, exec it.
564         string exit_cfg;
565         exit_cfg = cvar_string("exit_cfg");
566         if(exit_cfg != "")
567                 localcmd(strcat("exec \"", exit_cfg, "\"\n"));
568
569         localcmd("exec game_reset.cfg\n");
570 #endif
571 };
572
573 void() Map_Goto =
574 {
575         Map_MarkAsRecent(getmapname_stored);
576         GameResetCfg();
577 #ifdef MAPINFO
578         MapInfo_LoadMap(getmapname_stored);
579 #else
580         localcmd(strcat("exec \"maps/", getmapname_stored ,".mapcfg\"\n"));
581 #endif
582 }
583
584 // return codes of map selectors:
585 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
586 //   -2 = permanent failure
587 float() MaplistMethod_Iterate = // usual method
588 {
589         float pass, i;
590
591         for(pass = 1; pass <= 2; ++pass)
592         {
593                 for(i = 1; i < Map_Count; ++i)
594                 {
595                         float mapindex;
596                         mapindex = mod(i + Map_Current, Map_Count);
597                         if(Map_Check(mapindex, pass))
598                                 return mapindex;
599                 }
600         }
601         return -1;
602 }
603
604 float() MaplistMethod_Repeat = // fallback method
605 {
606         if(Map_Check(Map_Current, 2))
607                 return Map_Current;
608         return -2;
609 }
610
611 float() MaplistMethod_Random = // random map selection
612 {
613         float i, imax;
614
615         imax = 42;
616
617         for(i = 0; i <= imax; ++i)
618         {
619                 float mapindex;
620                 mapindex = mod(Map_Current + ceil(random() * (Map_Count - 1)), Map_Count); // any OTHER map
621                 if(Map_Check(mapindex, 1))
622                         return mapindex;
623         }
624         return -1;
625 }
626
627 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
628 // the exponent sets a bias on the map selection:
629 // the higher the exponent, the less likely "shortly repeated" same maps are
630 {
631         float i, j, imax, insertpos;
632
633         imax = 42;
634
635         for(i = 0; i <= imax; ++i)
636         {
637                 string newlist;
638
639                 // now reinsert this at another position
640                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
641                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
642                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
643                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
644
645                 // insert the current map there
646                 newlist = "";
647 #ifdef MAPINFO
648                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
649                         newlist = strcat(newlist, " ", argv(j));
650                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
651                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
652                         newlist = strcat(newlist, " ", argv(j));
653                 newlist = substring(newlist, 1, strlen(newlist) - 1);
654 #else
655                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
656                         newlist = strcat(newlist, "'", argv(j), "'");
657                 newlist = strcat(newlist, "'", argv(0), "'");  // now insert the just selected map
658                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
659                         newlist = strcat(newlist, "'", argv(j), "'");
660 #endif
661                 cvar_set("g_maplist", newlist);
662 #ifdef MAPINFO
663                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
664 #else
665                 Map_Count = tokenize(newlist);
666 #endif
667
668                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
669                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
670                 if(Map_Check(Map_Current, 1))
671                         return Map_Current;
672         }
673         return -1;
674 }
675
676 void() Maplist_Init =
677 {
678         string temp;
679         temp = cvar_string("g_maplist");
680 #ifdef MAPINFO
681         Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
682 #else
683         Map_Count = tokenize(temp);
684 #endif
685         if(Map_Count == 0)
686         {
687                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
688 #ifdef MAPINFO
689                 cvar_set("g_maplist", temp = MapInfo_ListAllowedMaps());
690                 localcmd("\nmenu_cmd sync\n");
691                 Map_Count = tokenizebyseparator(temp, " ");
692 #else
693                 cvar_set("g_maplist", temp = cvar_string("g_maplist_defaultlist"));
694                 Map_Count = tokenize(temp);
695 #endif
696         }
697         if(Map_Count == 0)
698                 error("empty maplist, cannot select a new map");
699         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
700
701         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
702         // this may or may not be correct, but who cares, in the worst case a map
703         // isn't chosen in the first pass that should have been
704 }
705
706 string() GetNextMap =
707 {
708         float nextMap;
709
710         Maplist_Init();
711         nextMap = -1;
712
713         if(nextMap == -1)
714                 if(cvar("g_maplist_shuffle") > 0)
715                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
716
717         if(nextMap == -1)
718                 if(cvar("g_maplist_selectrandom"))
719                         nextMap = MaplistMethod_Random();
720
721         if(nextMap == -1)
722                 nextMap = MaplistMethod_Iterate();
723
724         if(nextMap == -1)
725                 nextMap = MaplistMethod_Repeat();
726
727         if(nextMap >= 0)
728         {
729                 Map_Goto_SetFloat(nextMap);
730                 return getmapname_stored;
731         }
732
733         return "";
734 };
735
736 float() DoNextMapOverride =
737 {
738         if(cvar("g_campaign"))
739         {
740                 CampaignPostIntermission();
741                 alreadychangedlevel = TRUE;
742                 return TRUE;
743         }
744         if(cvar("quit_when_empty"))
745         {
746                 if(player_count <= currentbots)
747                 {
748                         localcmd("quit\n");
749                         alreadychangedlevel = TRUE;
750                         return TRUE;
751                 }
752         }
753         if(cvar_string("quit_and_redirect") != "")
754         {
755                 redirection_target = strzone(cvar_string("quit_and_redirect"));
756                 alreadychangedlevel = TRUE;
757                 return TRUE;
758         }
759         if (cvar("samelevel")) // if samelevel is set, stay on same level
760         {
761                 // 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)
762                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
763                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
764                 localcmd("restart\n");
765                 //changelevel (mapname);
766                 alreadychangedlevel = TRUE;
767                 return TRUE;
768         }
769         if(cvar_string("nextmap") != "")
770 #ifdef MAPINFO
771                 if(MapInfo_CheckMap(cvar_string("nextmap")))
772 #else
773                 if(TryFile(strcat("maps/", cvar_string("nextmap"), ".mapcfg")))
774 #endif
775                 {
776                         Map_Goto_SetStr(cvar_string("nextmap"));
777                         Map_Goto();
778                         alreadychangedlevel = TRUE;
779                         return TRUE;
780                 }
781         if(cvar("lastlevel"))
782         {
783                 GameResetCfg();
784                 localcmd("set lastlevel 0\ntogglemenu\n");
785                 alreadychangedlevel = TRUE;
786                 return TRUE;
787         }
788         return FALSE;
789 };
790
791 void() GotoNextMap =
792 {
793         //local string nextmap;
794         //local float n, nummaps;
795         //local string s;
796         if (alreadychangedlevel)
797                 return;
798         alreadychangedlevel = TRUE;
799
800         {
801                 string nextMap;
802                 float allowReset;
803
804                 for(allowReset = 1; allowReset >= 0; --allowReset)
805                 {
806                         nextMap = GetNextMap();
807                         if(nextMap != "")
808                                 break;
809
810                         if(allowReset)
811                         {
812                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
813 #ifdef MAPINFO
814                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
815                                 localcmd("\nmenu_cmd sync\n");
816 #else
817                                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
818 #endif
819                         }
820                         else
821                         {
822                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
823                         }
824                 }
825                 Map_Goto();
826         }
827 };
828
829
830 /*
831 ============
832 IntermissionThink
833
834 When the player presses attack or jump, change to the next level
835 ============
836 */
837 .float autoscreenshot;
838 void() MapVote_Start;
839 void() MapVote_Think;
840 float mapvote_initialized;
841 void() IntermissionThink =
842 {
843         FixIntermissionClient(self);
844
845         if(cvar("sv_autoscreenshot"))
846         if(self.autoscreenshot > 0)
847         if(time > self.autoscreenshot)
848         {
849                 self.autoscreenshot = -1;
850                 if(clienttype(self) == CLIENTTYPE_REAL)
851                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
852                 return;
853         }
854
855         if (time < intermission_exittime)
856                 return;
857
858         if(!mapvote_initialized)
859                 if (time < intermission_exittime + 10 && !self.button0 && !self.button2 && !self.button3 && !self.button6 && !self.buttonuse)
860                         return;
861
862         MapVote_Start();
863 };
864
865 /*
866 ============
867 FindIntermission
868
869 Returns the entity to view from
870 ============
871 */
872 /*
873 entity() FindIntermission =
874 {
875         local   entity spot;
876         local   float cyc;
877
878 // look for info_intermission first
879         spot = find (world, classname, "info_intermission");
880         if (spot)
881         {       // pick a random one
882                 cyc = random() * 4;
883                 while (cyc > 1)
884                 {
885                         spot = find (spot, classname, "info_intermission");
886                         if (!spot)
887                                 spot = find (spot, classname, "info_intermission");
888                         cyc = cyc - 1;
889                 }
890                 return spot;
891         }
892
893 // then look for the start position
894         spot = find (world, classname, "spawnfunc_info_player_start");
895         if (spot)
896                 return spot;
897
898 // testinfo_player_start is only found in regioned levels
899         spot = find (world, classname, "testplayerstart");
900         if (spot)
901                 return spot;
902
903 // then look for the start position
904         spot = find (world, classname, "spawnfunc_info_player_deathmatch");
905         if (spot)
906                 return spot;
907
908         //objerror ("FindIntermission: no spot");
909         return world;
910 };
911 */
912
913 /*
914 ===============================================================================
915
916 RULES
917
918 ===============================================================================
919 */
920
921 void(float final) DumpStats =
922 {
923         local float file;
924         local string s;
925         local float to_console;
926         local float to_eventlog;
927         local float to_file;
928
929         to_console = cvar("sv_logscores_console");
930         to_eventlog = cvar("sv_eventlog");
931         to_file = cvar("sv_logscores_file");
932
933         if(!final)
934         {
935                 to_console = TRUE; // always print printstats replies
936                 to_eventlog = FALSE; // but never print them to the event log
937         }
938
939         if(to_eventlog)
940                 if(cvar("sv_eventlog_console"))
941                         to_console = FALSE; // otherwise we get the output twice
942
943         if(final)
944                 s = ":scores:";
945         else
946                 s = ":status:";
947 #ifdef MAPINFO
948         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
949 #else
950         s = strcat(s, GetMapname(), ":", ftos(rint(time)));
951 #endif
952
953         if(to_console)
954                 ServerConsoleEcho(s, FALSE);
955         if(to_eventlog)
956                 GameLogEcho(s, FALSE);
957         if(to_file)
958         {
959                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
960                 if(file == -1)
961                         to_file = FALSE;
962                 else
963                         fputs(file, strcat(s, "\n"));
964         }
965
966         FOR_EACH_CLIENT(other)
967         {
968                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
969                 {
970                         s = strcat(":player:", ftos(other.frags), ":");
971                         s = strcat(s, ftos(other.deaths), ":");
972                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
973                         s = strcat(s, ftos(other.team), ":");
974
975                         if(to_console)
976                                 ServerConsoleEcho(strcat(s, other.netname), TRUE);
977                         if(to_eventlog)
978                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname), TRUE);
979                         if(to_file)
980                                 fputs(file, strcat(s, other.netname, "\n"));
981                 }
982         }
983
984         if(to_console)
985                 ServerConsoleEcho(":end", FALSE);
986         if(to_eventlog)
987                 GameLogEcho(":end", FALSE);
988         if(to_file)
989         {
990                 fputs(file, ":end\n");
991                 fclose(file);
992         }
993 }
994
995 void FixIntermissionClient(entity e)
996 {
997         if(!e.autoscreenshot) // initial call
998         {
999                 e.angles = e.v_angle;
1000                 e.angles_x = -e.angles_x;
1001                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1002                 e.health = -2342;
1003                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1004                 e.solid = SOLID_NOT;
1005                 e.movetype = MOVETYPE_NONE;
1006                 e.takedamage = DAMAGE_NO;
1007                 if(e.weaponentity)
1008                         e.weaponentity.effects = EF_NODRAW;
1009                 stuffcmd(e, "\nscr_printspeed 1000000\n");
1010                 if(clienttype(e) == CLIENTTYPE_REAL)
1011                 {
1012                         msg_entity = e;
1013                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1014                 }
1015         }
1016
1017         //e.velocity = '0 0 0';
1018         //e.fixangle = TRUE;
1019
1020         // TODO halt weapon animation
1021 }
1022
1023
1024 /*
1025 go to the next level for deathmatch
1026 only called if a time or frag limit has expired
1027 */
1028 void() NextLevel =
1029 {
1030         float minTotalFrags;
1031         float maxTotalFrags;
1032         float score;
1033         float f;
1034
1035         gameover = TRUE;
1036
1037         intermission_running = 1;
1038
1039 // enforce a wait time before allowing changelevel
1040         if(player_count > 0)
1041                 intermission_exittime = time + cvar("sv_mapchange_delay");
1042         else
1043                 intermission_exittime = -1;
1044
1045         WriteByte (MSG_ALL, SVC_CDTRACK);
1046         WriteByte (MSG_ALL, 3);
1047         WriteByte (MSG_ALL, 3);
1048
1049         //pos = FindIntermission ();
1050
1051         VoteReset();
1052
1053         DumpStats(TRUE);
1054
1055         if(cvar("sv_eventlog"))
1056                 GameLogEcho(":gameover", FALSE);
1057
1058         GameLogClose();
1059
1060         FOR_EACH_CLIENT(other)
1061         {
1062                 FixIntermissionClient(other);
1063
1064                 if(other.winning)
1065                         bprint(other.netname, " ^7wins.\n");
1066         }
1067
1068         minTotalFrags = 0;
1069         maxTotalFrags = 0;
1070         FOR_EACH_PLAYER(other)
1071         {
1072                 if(maxTotalFrags < other.totalfrags)
1073                         maxTotalFrags = other.totalfrags;
1074                 if(minTotalFrags > other.totalfrags)
1075                         minTotalFrags = other.totalfrags;
1076         }
1077
1078         if(!currentbots)
1079         {
1080                 FOR_EACH_PLAYER(other)
1081                 {
1082                         score = (other.totalfrags - minTotalFrags) / max(maxTotalFrags - minTotalFrags, 1);
1083                         f = bound(0, other.play_time / max(time, 1), 1);
1084                         // store some statistics?
1085                 }
1086         }
1087
1088         if(cvar("g_campaign"))
1089                 CampaignPreIntermission();
1090
1091         // WriteByte (MSG_ALL, SVC_INTERMISSION);
1092 };
1093
1094 /*
1095 ============
1096 CheckRules_Player
1097
1098 Exit deathmatch games upon conditions
1099 ============
1100 */
1101 void() CheckRules_Player =
1102 {
1103         if (gameover)   // someone else quit the game already
1104                 return;
1105
1106         if(self.deadflag == DEAD_NO)
1107                 self.play_time += frametime;
1108
1109         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1110         //   (div0: and that in CheckRules_World please)
1111 };
1112
1113 float checkrules_oneminutewarning;
1114 float checkrules_leaderfrags;
1115 float tdm_max_score, tdm_old_score;
1116
1117 float checkrules_equality;
1118 float checkrules_overtimewarning;
1119 float checkrules_overtimeend;
1120
1121 void() InitiateOvertime =
1122 {
1123         if(!checkrules_overtimeend)
1124                 checkrules_overtimeend = time + 60 * cvar("timelimit_maxovertime");
1125 }
1126
1127 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1128 float WINNING_YES = 1; // winner found
1129 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1130 float WINNING_STARTOVERTIME = 3; // no winner, enter overtime NOW
1131
1132 float(float fraglimitreached, float equality) GetWinningCode =
1133 {
1134         if(equality)
1135                 if(fraglimitreached)
1136                         return WINNING_STARTOVERTIME;
1137                 else
1138                         return WINNING_NEVER;
1139         else
1140                 if(fraglimitreached)
1141                         return WINNING_YES;
1142                 else
1143                         return WINNING_NO;
1144 }
1145
1146 // set the .winning flag for exactly those players with a given field value
1147 void(.float field, float value) SetWinners =
1148 {
1149         entity head;
1150         FOR_EACH_PLAYER(head)
1151                 head.winning = (head.field == value);
1152 }
1153
1154 // set the .winning flag for those players with a given field value
1155 void(.float field, float value) AddWinners =
1156 {
1157         entity head;
1158         FOR_EACH_PLAYER(head)
1159                 if(head.field == value)
1160                         head.winning = 1;
1161 }
1162
1163 // clear frags for all players but the team given (when they ran out of spawnpoints)
1164 void(.float field, float value) ClearFragsForEveryoneBut =
1165 {
1166         entity head;
1167         FOR_EACH_PLAYER(head)
1168                 if(head.field != value)
1169                         head.frags = max(head.frags, 0);
1170 }
1171
1172 // clear the .winning flags
1173 void(void) ClearWinners =
1174 {
1175         entity head;
1176         FOR_EACH_PLAYER(head)
1177                 head.winning = 0;
1178 }
1179
1180 // Onslaught winning condition:
1181 // game terminates if only one team has a working generator (or none)
1182 float() WinningCondition_Onslaught =
1183 {
1184         entity head;
1185         local float t1, t2, t3, t4;
1186         // first check if the game has ended
1187         t1 = t2 = t3 = t4 = 0;
1188         head = find(world, classname, "spawnfunc_onslaught_generator");
1189         while (head)
1190         {
1191                 if (head.health > 0)
1192                 {
1193                         if (head.team == COLOR_TEAM1) t1 = 1;
1194                         if (head.team == COLOR_TEAM2) t2 = 1;
1195                         if (head.team == COLOR_TEAM3) t3 = 1;
1196                         if (head.team == COLOR_TEAM4) t4 = 1;
1197                 }
1198                 head = find(head, classname, "spawnfunc_onslaught_generator");
1199         }
1200         if (t1 + t2 + t3 + t4 < 2)
1201         {
1202                 // game over, only one team remains (or none)
1203                 ClearWinners();
1204                 if (t1) SetWinners(team, COLOR_TEAM1);
1205                 if (t2) SetWinners(team, COLOR_TEAM2);
1206                 if (t3) SetWinners(team, COLOR_TEAM3);
1207                 if (t4) SetWinners(team, COLOR_TEAM4);
1208                 dprint("Have a winner, ending game.\n");
1209                 return WINNING_YES;
1210         }
1211
1212         // Two or more teams remain
1213         return WINNING_NO;
1214 }
1215
1216 float() LMS_NewPlayerLives =
1217 {
1218         float fl;
1219         fl = cvar("fraglimit");
1220         if(fl == 0)
1221                 fl = 999;
1222
1223         // first player has left the game for dying too much? Nobody else can get in.
1224         if(lms_lowest_lives < 1)
1225                 return FALSE;
1226
1227         if(!cvar("g_lms_join_anytime"))
1228                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1229                         return FALSE;
1230
1231         return bound(1, lms_lowest_lives, fl);
1232 }
1233
1234 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1235 // they win. Otherwise the defending team wins once the timelimit passes.
1236 void assault_new_round();
1237 float() WinningCondition_Assault =
1238 {
1239         local float status;
1240         status = WINNING_NO;
1241
1242         // as the timelimit has not yet passed just assume the defending team will win
1243         if(assault_attacker_team == COLOR_TEAM1)
1244         {
1245                 SetWinners(team, COLOR_TEAM2);
1246         }
1247         else
1248         {
1249                 SetWinners(team, COLOR_TEAM1);
1250         }
1251
1252         local entity ent;
1253         ent = find(world, classname, "spawnfunc_target_assault_roundend");
1254         if(ent)
1255         {
1256                 if(ent.winning) // round end has been triggered by attacking team
1257                 {
1258                         SetWinners(team, assault_attacker_team);
1259                         if(assault_attacker_team == COLOR_TEAM1)
1260                         {
1261                                 team1_score = team1_score + 50;
1262                         }
1263                         else
1264                         {
1265                                 team2_score = team2_score + 50;
1266                         }
1267
1268                         if(ent.cnt == 1) // this was the second round
1269                         {
1270                                 status = WINNING_YES;
1271                         }
1272                         else
1273                         {
1274                                 cvar_set("timelimit", ftos((2*time)/60));
1275                                 assault_new_round();
1276                         }
1277                 }
1278         }
1279
1280         return status;
1281
1282 }
1283
1284
1285 // LMS winning condition: game terminates if and only if there's at most one
1286 // one player who's living lives. Top two scores being equal cancels the time
1287 // limit.
1288 float() WinningCondition_LMS =
1289 {
1290         entity head;
1291         float have_player;
1292         float have_players;
1293         float l;
1294
1295         have_player = FALSE;
1296         have_players = FALSE;
1297         l = LMS_NewPlayerLives();
1298
1299         head = find(world, classname, "player");
1300         if(head)
1301                 have_player = TRUE;
1302         head = find(head, classname, "player");
1303         if(head)
1304                 have_players = TRUE;
1305
1306         if(have_player)
1307         {
1308                 // we have at least one player
1309                 if(have_players)
1310                 {
1311                         // two or more active players - continue with the game
1312                 }
1313                 else
1314                 {
1315                         // exactly one player?
1316                         if(l)
1317                         {
1318                                 // but no game has taken place yet
1319                         }
1320                         else
1321                         {
1322                                 // a winner!
1323                                 ClearWinners(); SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1324                                 dprint("Have a winner, ending game.\n");
1325                                 return WINNING_YES;
1326                         }
1327                 }
1328         }
1329         else
1330         {
1331                 // nobody is playing at all...
1332                 if(l)
1333                 {
1334                         // wait for players...
1335                 }
1336                 else
1337                 {
1338                         // SNAFU (maybe a draw game?)
1339                         ClearWinners();
1340                         dprint("No players, ending game.\n");
1341                         return WINNING_YES;
1342                 }
1343         }
1344
1345         // When we get here, we have at least two players who are actually LIVING,
1346         // or one player who is still waiting for a victim to join the server. Now
1347         // check if the top two players have equal score.
1348
1349         checkrules_leaderfrags = 0;
1350         checkrules_equality = FALSE;
1351         FOR_EACH_PLAYER(head)
1352         {
1353                 if(head.frags > checkrules_leaderfrags)
1354                 {
1355                         checkrules_leaderfrags = head.frags;
1356                         checkrules_equality = FALSE;
1357                 }
1358                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1359                         checkrules_equality = TRUE;
1360         }
1361
1362         SetWinners(frags, checkrules_leaderfrags);
1363
1364         // The top two players have the same amount of lives? No timelimit then,
1365         // enter overtime...
1366
1367         if(checkrules_equality)
1368                 return WINNING_NEVER;
1369
1370         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1371         return WINNING_NO;
1372 }
1373
1374 // DM winning condition: game terminates if a player reached the fraglimit,
1375 // unless the first two players have the same score. The latter case also
1376 // breaks the time limit.
1377 float(float fraglimit) WinningCondition_MaxIndividualScore =
1378 {
1379         float checkrules_oldleaderfrags;
1380         entity head;
1381
1382         checkrules_oldleaderfrags = checkrules_leaderfrags;
1383         checkrules_leaderfrags = 0;
1384         checkrules_equality = FALSE;
1385         FOR_EACH_PLAYER(head)
1386         {
1387                 if(head.frags > checkrules_leaderfrags)
1388                 {
1389                         checkrules_leaderfrags = head.frags;
1390                         checkrules_equality = FALSE;
1391                 }
1392                 else if(head.frags > 0 && head.frags == checkrules_leaderfrags)
1393                         checkrules_equality = TRUE;
1394         }
1395
1396         if(checkrules_leaderfrags > 0)
1397                 SetWinners(frags, checkrules_leaderfrags);
1398         else
1399                 ClearWinners();
1400
1401         if (!g_runematch)
1402                 if (checkrules_leaderfrags != checkrules_oldleaderfrags)
1403                 {
1404                         if (checkrules_leaderfrags == fraglimit - 1)
1405                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1406                         else if (checkrules_leaderfrags == fraglimit - 2)
1407                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1408                         else if (checkrules_leaderfrags == fraglimit - 3)
1409                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1410                 }
1411
1412         return GetWinningCode(fraglimit && checkrules_leaderfrags >= fraglimit, checkrules_equality);
1413 }
1414
1415 float(float fraglimit) WinningConditionBase_Teamplay =
1416 {
1417         tdm_old_score = tdm_max_score;
1418         tdm_max_score = max4(team1_score, team2_score, team3_score, team4_score);
1419
1420         checkrules_equality =
1421         (
1422                 (tdm_max_score > 0)
1423                 &&
1424                 (
1425                           (team1_score == tdm_max_score)
1426                         + (team2_score == tdm_max_score)
1427                         + (team3_score == tdm_max_score)
1428                         + (team4_score == tdm_max_score)
1429                         >= 2));
1430
1431         ClearWinners();
1432         if(tdm_max_score > 0)
1433         {
1434                 if(team1_score == tdm_max_score)
1435                         AddWinners(team, COLOR_TEAM1);
1436                 if(team2_score == tdm_max_score)
1437                         AddWinners(team, COLOR_TEAM2);
1438                 if(team3_score == tdm_max_score)
1439                         AddWinners(team, COLOR_TEAM3);
1440                 if(team4_score == tdm_max_score)
1441                         AddWinners(team, COLOR_TEAM4);
1442         }
1443
1444         if(!g_runematch && !g_domination)
1445                 if(tdm_max_score != tdm_old_score)
1446                 {
1447                         if(tdm_max_score == fraglimit - 1)
1448                                 sound(world, CHAN_AUTO, "announcer/robotic/1fragleft.wav", 1, ATTN_NONE);
1449                         else if(tdm_max_score == fraglimit - 2)
1450                                 sound(world, CHAN_AUTO, "announcer/robotic/2fragsleft.wav", 1, ATTN_NONE);
1451                         else if(tdm_max_score == fraglimit - 3)
1452                                 sound(world, CHAN_AUTO, "announcer/robotic/3fragsleft.wav", 1, ATTN_NONE);
1453                 }
1454
1455         return GetWinningCode(fraglimit && tdm_max_score >= fraglimit, checkrules_equality);
1456 }
1457
1458 // TDM winning condition: game terminates if a team's score sum reached the
1459 // fraglimit, unless the first two teams have the same total score. The latter
1460 // case also breaks the time limit.
1461 float(float fraglimit) WinningCondition_MaxTeamSum =
1462 {
1463         entity head;
1464
1465         team1_score = team2_score = team3_score = team4_score = 0;
1466
1467         FOR_EACH_PLAYER(head)
1468         {
1469                 if(head.team == COLOR_TEAM1)
1470                         team1_score += head.frags;
1471                 else if(head.team == COLOR_TEAM2)
1472                         team2_score += head.frags;
1473                 else if(head.team == COLOR_TEAM3)
1474                         team3_score += head.frags;
1475                 else if(head.team == COLOR_TEAM4)
1476                         team4_score += head.frags;
1477         }
1478
1479         return WinningConditionBase_Teamplay(fraglimit);
1480 }
1481
1482 // DOM/CTF winning condition: game terminates if the max of a team's players'
1483 // score reached the fraglimit, unless the first two teams have the same
1484 // maximum score. The latter case also breaks the time limit.
1485 float(float fraglimit) WinningCondition_MaxTeamMax =
1486 {
1487         entity head;
1488
1489         team1_score = team2_score = team3_score = team4_score = 0;
1490
1491         FOR_EACH_PLAYER(head)
1492         {
1493                 if(head.team == COLOR_TEAM1)
1494                 {
1495                         if(head.frags > team1_score)
1496                                 team1_score = head.frags;
1497                 }
1498                 else if(head.team == COLOR_TEAM2)
1499                 {
1500                         if(head.frags > team2_score)
1501                                 team2_score = head.frags;
1502                 }
1503                 else if(head.team == COLOR_TEAM3)
1504                 {
1505                         if(head.frags > team3_score)
1506                                 team3_score = head.frags;
1507                 }
1508                 else if(head.team == COLOR_TEAM4)
1509                 {
1510                         if(head.frags > team4_score)
1511                                 team4_score = head.frags;
1512                 }
1513         }
1514
1515         return WinningConditionBase_Teamplay(fraglimit);
1516 }
1517
1518 void print_to(entity e, string s)
1519 {
1520         if(e)
1521                 sprint(e, strcat(s, "\n"));
1522         else
1523                 ServerConsoleEcho(s, TRUE);
1524 }
1525
1526 void PrintScoreboardFor(entity e, string name, string colorcode, float whichteam)
1527 {
1528         entity head;
1529         float v;
1530         float teamvalue;
1531         float fragtotal;
1532         string s;
1533         float found;
1534         found = FALSE;
1535         teamvalue = 0;
1536         FOR_EACH_PLAYER(head)
1537         {
1538                 if(!whichteam || head.team == whichteam)
1539                 {
1540                         if(name != "")
1541                                 if(!found)
1542                                         print_to(e, strcat(" ", colorcode, name, ":"));
1543                         found = TRUE;
1544                         fragtotal = fragtotal + head.frags;
1545                         s = ftos(head.frags);
1546                         s = strcat(s, "/", ftos(head.deaths));
1547                         s = strcat(s, " @ ", ftos(head.ping));
1548                         if(clienttype(head) == CLIENTTYPE_BOT)
1549                                 s = strcat(s, "botms");
1550                         else
1551                                 s = strcat(s, "ms");
1552                         v = PlayerValue(head);
1553                         teamvalue += v;
1554                         s = strcat(s, " / ", ftos(v));
1555                         print_to(e, strcat("  ", colorcode, head.netname, colorcode, " (", s, ")"));
1556                 }
1557         }
1558         if(whichteam && found)
1559         {
1560                 s = ftos(fragtotal);
1561                 s = strcat(s, " / ", ftos(teamvalue));
1562                 print_to(e, strcat(colorcode, "  (total: ", s, ")"));
1563         }
1564 }
1565
1566 void PrintScoreboard(entity e)
1567 {
1568         print_to(e, strcat("Time:      ", ftos(time / 60)));
1569         print_to(e, strcat("Timelimit: ", ftos(cvar("timelimit"))));
1570         print_to(e, strcat("Fraglimit: ", ftos(cvar("fraglimit"))));
1571         print_to(e, "Scoreboard:");
1572         if(teams_matter)
1573         {
1574                 PrintScoreboardFor(e, "Red", "^1", COLOR_TEAM1);
1575                 PrintScoreboardFor(e, "Blue", "^4", COLOR_TEAM2);
1576                 PrintScoreboardFor(e, "Yellow", "^3", COLOR_TEAM3);
1577                 PrintScoreboardFor(e, "Pink", "^6", COLOR_TEAM4);
1578         }
1579         else
1580         {
1581                 PrintScoreboardFor(e, "", "^7", 0);
1582         }
1583         print_to(e, ".");
1584 }
1585
1586 void ShuffleMaplist()
1587 {
1588         string result;
1589         float start;
1590         float litems;
1591         float selected;
1592         float i;
1593
1594         result = cvar_string("g_maplist");
1595 #ifdef MAPINFO
1596         litems = tokenizebyseparator(result, " ");
1597 #else
1598         litems = tokenize(result);
1599 #endif
1600
1601         for(start = 0; start < litems - 1; ++start)
1602         {
1603                 result = "";
1604
1605                 // select a random item
1606                 selected = ceil(random() * (litems - start) + start) - 1;
1607
1608                 // shift this item to the place start
1609 #ifdef MAPINFO
1610                 for(i = 0; i < start; ++i)
1611                         result = strcat(result, " ", argv(i));
1612                 result = strcat(result, " ", argv(selected));
1613                 for(i = start; i < litems; ++i)
1614                         if(i != selected)
1615                                 result = strcat(result, " ", argv(i));
1616                 result = substring(result, 1, strlen(result) - 1);
1617
1618                 litems = tokenizebyseparator(result, " ");
1619 #else
1620                 for(i = 0; i < start; ++i)
1621                         result = strcat(result, "'", argv(i), "'");
1622                 result = strcat(result, "'", argv(selected), "'");
1623                 for(i = start; i < litems; ++i)
1624                         if(i != selected)
1625                                 result = strcat(result, "'", argv(i), "'");
1626
1627                 litems = tokenize(result);
1628 #endif
1629
1630                 //dprint(result, "\n");
1631         }
1632
1633         cvar_set("g_maplist", result);
1634 }
1635
1636 float WinningCondition_RanOutOfSpawns()
1637 {
1638         entity head;
1639
1640         if(!have_team_spawns)
1641                 return WINNING_NO;
1642
1643         if(!some_spawn_has_been_used)
1644                 return WINNING_NO;
1645
1646         team1_score = team2_score = team3_score = team4_score = 0;
1647
1648         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1649         {
1650                 if(head.team == COLOR_TEAM1)
1651                         team1_score = 1;
1652                 else if(head.team == COLOR_TEAM2)
1653                         team2_score = 1;
1654                 else if(head.team == COLOR_TEAM3)
1655                         team3_score = 1;
1656                 else if(head.team == COLOR_TEAM4)
1657                         team4_score = 1;
1658         }
1659
1660         for(head = world; (head = find(head, classname, "spawnfunc_info_player_deathmatch")) != world; )
1661         {
1662                 if(head.team == COLOR_TEAM1)
1663                         team1_score = 1;
1664                 else if(head.team == COLOR_TEAM2)
1665                         team2_score = 1;
1666                 else if(head.team == COLOR_TEAM3)
1667                         team3_score = 1;
1668                 else if(head.team == COLOR_TEAM4)
1669                         team4_score = 1;
1670         }
1671
1672         ClearWinners();
1673         if(team1_score + team2_score + team3_score + team4_score == 0)
1674         {
1675                 checkrules_equality = TRUE;
1676                 return WINNING_YES;
1677         }
1678         else if(team1_score + team2_score + team3_score + team4_score == 1)
1679         {
1680                 if(team1_score)
1681                 {
1682                         AddWinners(team, COLOR_TEAM1);
1683                         ClearFragsForEveryoneBut(team, COLOR_TEAM1);
1684                 }
1685                 if(team2_score)
1686                 {
1687                         AddWinners(team, COLOR_TEAM2);
1688                         ClearFragsForEveryoneBut(team, COLOR_TEAM2);
1689                 }
1690                 if(team3_score)
1691                 {
1692                         AddWinners(team, COLOR_TEAM3);
1693                         ClearFragsForEveryoneBut(team, COLOR_TEAM3);
1694                 }
1695                 if(team4_score)
1696                 {
1697                         AddWinners(team, COLOR_TEAM4);
1698                         ClearFragsForEveryoneBut(team, COLOR_TEAM4);
1699                 }
1700                 return WINNING_YES;
1701         }
1702         else
1703                 return WINNING_NO;
1704 }
1705
1706 /*
1707 ============
1708 CheckRules_World
1709
1710 Exit deathmatch games upon conditions
1711 ============
1712 */
1713 void() CheckRules_World =
1714 {
1715         local float status;
1716         local float timelimit;
1717         local float fraglimit;
1718
1719         VoteThink();
1720         MapVote_Think();
1721
1722         SetDefaultAlpha();
1723
1724         /*
1725         MapVote_Think should now do that part
1726         if (intermission_running)
1727                 if (time >= intermission_exittime + 60)
1728                 {
1729                         if(!DoNextMapOverride())
1730                                 GotoNextMap();
1731                         return;
1732                 }
1733         */
1734
1735         if (gameover)   // someone else quit the game already
1736         {
1737                 if(player_count == 0) // Nobody there? Then let's go to the next map
1738                         MapVote_Start();
1739                         // this will actually check the player count in the next frame
1740                         // again, but this shouldn't hurt
1741                 return;
1742         }
1743
1744         timelimit = cvar("timelimit") * 60;
1745         fraglimit = cvar("fraglimit");
1746
1747         if(checkrules_overtimeend)
1748         {
1749                 if(!checkrules_overtimewarning)
1750                 {
1751                         checkrules_overtimewarning = TRUE;
1752                         //sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1753                         bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1754                 }
1755         }
1756         else
1757         {
1758                 if (timelimit && time >= timelimit)
1759                         InitiateOvertime();
1760         }
1761
1762         if (checkrules_overtimeend && time >= checkrules_overtimeend)
1763         {
1764                 NextLevel();
1765                 return;
1766         }
1767
1768         if (!checkrules_oneminutewarning && timelimit > 0 && time > timelimit - 60)
1769         {
1770                 checkrules_oneminutewarning = TRUE;
1771                 sound(world, CHAN_AUTO, "announcer/robotic/1minuteremains.wav", 1, ATTN_NONE);
1772         }
1773
1774         status = WinningCondition_RanOutOfSpawns();
1775         if(status == WINNING_YES)
1776         {
1777                 bprint("Hey! Someone ran out of spawns!\n");
1778         }
1779         else if(g_assault)
1780         {
1781                 status = WinningCondition_Assault();
1782         }
1783         else if(g_lms)
1784         {
1785                 status = WinningCondition_LMS();
1786         }
1787         else if (g_onslaught)
1788         {
1789                 status = WinningCondition_Onslaught();
1790         }
1791         else
1792         {
1793                 if(teams_matter)
1794                 {
1795                         if(g_tdm || g_runematch || g_ctf || g_domination || g_keyhunt)
1796                                 status = WinningCondition_MaxTeamSum(fraglimit);
1797                         //else if()
1798                         //      status = WinningCondition_MaxTeamMax(fraglimit);
1799                         else
1800                         {
1801                                 dprint("div0: How can this happen?\n");
1802                                 status = WinningCondition_MaxTeamMax(fraglimit);
1803                         }
1804                 }
1805                 else
1806                         status = WinningCondition_MaxIndividualScore(fraglimit);
1807         }
1808
1809         if(status == WINNING_STARTOVERTIME)
1810         {
1811                 status = WINNING_NEVER;
1812                 InitiateOvertime();
1813         }
1814
1815         if(status == WINNING_NEVER)
1816                 // equality cases! Nobody wins if the overtime ends in a draw.
1817                 ClearWinners();
1818
1819         if(checkrules_overtimeend)
1820                 if(status != WINNING_NEVER || time >= checkrules_overtimeend)
1821                         status = WINNING_YES;
1822
1823         if(status == WINNING_YES)
1824                 NextLevel();
1825 };
1826
1827 float randsel_value;
1828 float randsel_priority;
1829 float randsel_count;
1830 void RandSel_Init()
1831 {
1832         randsel_value = -1;
1833         randsel_priority = -1;
1834         randsel_count = -1;
1835 }
1836 void RandSel_Add(float priority, float value)
1837 {
1838         if(priority > randsel_priority)
1839         {
1840                 randsel_priority = priority;
1841                 randsel_value = value;
1842                 randsel_count = 1;
1843         }
1844         else if(priority == randsel_priority)
1845         {
1846                 randsel_count += 1;
1847                 if(ceil(random() * randsel_count) == 1)
1848                         randsel_value = value;
1849         }
1850 }
1851
1852 float mapvote_nextthink;
1853 float mapvote_initialized;
1854 float mapvote_keeptwotime;
1855 float mapvote_timeout;
1856 string mapvote_message;
1857
1858 #define MAPVOTE_COUNT 10
1859 float mapvote_count;
1860 float mapvote_count_real;
1861 string mapvote_maps[MAPVOTE_COUNT];
1862 float mapvote_maps_suggested[MAPVOTE_COUNT];
1863 string mapvote_suggestions[MAPVOTE_COUNT];
1864 float mapvote_suggestion_ptr;
1865 float mapvote_maxlen;
1866 float mapvote_voters;
1867 float mapvote_votes[MAPVOTE_COUNT];
1868 float mapvote_run;
1869 float mapvote_detail;
1870 float mapvote_abstain;
1871 .float mapvote;
1872
1873 void MapVote_ClearAllVotes()
1874 {
1875         FOR_EACH_CLIENT(other)
1876                 other.mapvote = 0;
1877 }
1878
1879 string MapVote_Suggest(string m)
1880 {
1881         float i;
1882         if(m == "")
1883                 return "That's not how to use this command.";
1884         if(!cvar("g_maplist_votable_suggestions"))
1885                 return "Suggestions are not accepted on this server.";
1886         if(mapvote_initialized)
1887                 return "Can't suggest - voting is already in progress!";
1888 #ifdef MAPINFO
1889         m = MapInfo_FixName(m);
1890         if(!m)
1891                 return "The map you suggested is not available on this server.";
1892 #else
1893         if(!cvar("g_maplist_votable_suggestions_change_gametype"))
1894                 if(!IsSameGametype(m))
1895                         return "This server does not allow changing the game type by map suggestions.";
1896 #endif
1897         if(!cvar("g_maplist_votable_override_mostrecent"))
1898                 if(Map_IsRecent(m))
1899                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
1900
1901 #ifdef MAPINFO
1902         if(!MapInfo_CheckMap(m))
1903                 return "The map you suggested does not support the current game mode.";
1904 #else
1905         if(!TryFile(strcat("maps/", m, ".mapcfg")))
1906                 return "The map you suggested is not available on this server.";
1907 #endif
1908         for(i = 0; i < mapvote_suggestion_ptr; ++i)
1909                 if(mapvote_suggestions[i] == m)
1910                         return "This map was already suggested.";
1911         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
1912         {
1913                 i = ceil(random() * mapvote_suggestion_ptr) - 1;
1914         }
1915         else
1916         {
1917                 i = mapvote_suggestion_ptr;
1918                 mapvote_suggestion_ptr += 1;
1919         }
1920         if(mapvote_suggestions[i] != "")
1921                 strunzone(mapvote_suggestions[i]);
1922         mapvote_suggestions[i] = strzone(m);
1923         GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid), ":", self.netname), TRUE);
1924         return strcat("Suggestion of ", m, " accepted.");
1925 }
1926
1927 void MapVote_AddVotable(string nextMap, float isSuggestion)
1928 {
1929         float j;
1930         if(nextMap == "")
1931                 return;
1932         for(j = 0; j < mapvote_count; ++j)
1933                 if(mapvote_maps[j] == nextMap)
1934                         return;
1935         if(strlen(nextMap) > mapvote_maxlen)
1936                 mapvote_maxlen = strlen(nextMap);
1937         mapvote_maps[mapvote_count] = strzone(nextMap);
1938         mapvote_maps_suggested[mapvote_count] = isSuggestion;
1939         mapvote_count += 1;
1940 }
1941
1942 void MapVote_Init()
1943 {
1944         float i;
1945         float nmax, smax;
1946
1947         MapVote_ClearAllVotes();
1948
1949         mapvote_count = 0;
1950         mapvote_detail = !cvar("g_maplist_votable_nodetail");
1951         mapvote_abstain = cvar("g_maplist_votable_abstain");
1952
1953         if(mapvote_abstain)
1954                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
1955         else
1956                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
1957         smax = min(nmax, cvar("g_maplist_votable_suggestions"));
1958
1959         for(i = 0; i < 100 && mapvote_count < smax; ++i)
1960                 MapVote_AddVotable(mapvote_suggestions[ceil(random() * mapvote_suggestion_ptr) - 1], TRUE);
1961
1962         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1963                 MapVote_AddVotable(GetNextMap(), FALSE);
1964
1965         if(mapvote_count == 0)
1966         {
1967                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1968 #ifdef MAPINFO
1969                 cvar_set("g_maplist", MapInfo_ListAllowedMaps());
1970                 localcmd("\nmenu_cmd sync\n");
1971 #else
1972                 cvar_set("g_maplist", cvar_string("g_maplist_defaultlist"));
1973 #endif
1974                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
1975                         MapVote_AddVotable(GetNextMap(), FALSE);
1976         }
1977
1978         mapvote_count_real = mapvote_count;
1979         if(mapvote_abstain)
1980                 MapVote_AddVotable("don't care", 0);
1981
1982         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
1983
1984         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
1985         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
1986         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
1987                 mapvote_keeptwotime = 0;
1988         mapvote_message = "Choose a map and press its key!";
1989 }
1990 float MapVote_Finished(float mappos)
1991 {
1992         string result;
1993         float i;
1994         float didntvote;
1995
1996         result = strcat(":vote:finished:", mapvote_maps[mappos]);
1997         result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
1998         didntvote = mapvote_voters;
1999         for(i = 0; i < mapvote_count; ++i)
2000                 if(mapvote_maps[i] != "")
2001                 {
2002                         didntvote -= mapvote_votes[i];
2003                         if(i != mappos)
2004                         {
2005                                 result = strcat(result, ":", mapvote_maps[i]);
2006                                 result = strcat(result, ":", ftos(mapvote_votes[i]));
2007                         }
2008                 }
2009         result = strcat(result, ":didn't vote:", ftos(didntvote));
2010
2011         GameLogEcho(result, FALSE);
2012         if(mapvote_maps_suggested[mappos])
2013                 GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]), FALSE);
2014
2015         FOR_EACH_REALCLIENT(other)
2016                 FixClientCvars(other);
2017
2018         Map_Goto_SetStr(mapvote_maps[mappos]);
2019         Map_Goto();
2020         alreadychangedlevel = TRUE;
2021         return TRUE;
2022 }
2023 void MapVote_CheckRules_1()
2024 {
2025         float i;
2026
2027         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2028         {
2029                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2030                 mapvote_votes[i] = 0;
2031         }
2032
2033         mapvote_voters = 0;
2034         FOR_EACH_REALCLIENT(other)
2035         {
2036                 ++mapvote_voters;
2037                 if(other.mapvote)
2038                 {
2039                         i = other.mapvote - 1;
2040                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2041                         mapvote_votes[i] = mapvote_votes[i] + 1;
2042                 }
2043         }
2044 }
2045
2046 float MapVote_CheckRules_2()
2047 {
2048         float i;
2049         float firstPlace, secondPlace;
2050         float firstPlaceVotes, secondPlaceVotes;
2051         float mapvote_voters_real;
2052         string result;
2053
2054         mapvote_voters_real = mapvote_voters;
2055         if(mapvote_abstain)
2056                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2057
2058         RandSel_Init();
2059         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2060                 RandSel_Add(mapvote_votes[i], i);
2061         firstPlace = randsel_value;
2062         firstPlaceVotes = randsel_priority;
2063         //dprint("First place: ", ftos(firstPlace), "\n");
2064         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2065
2066         RandSel_Init();
2067         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2068                 if(i != firstPlace)
2069                         RandSel_Add(mapvote_votes[i], i);
2070         secondPlace = randsel_value;
2071         secondPlaceVotes = randsel_priority;
2072         //dprint("Second place: ", ftos(secondPlace), "\n");
2073         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2074
2075         if(firstPlace == -1)
2076                 error("No first place in map vote... WTF?");
2077
2078         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2079                 return MapVote_Finished(firstPlace);
2080
2081         if(mapvote_keeptwotime)
2082                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2083                 {
2084                         float didntvote;
2085                         mapvote_message = "Now decide between the TOP TWO!";
2086                         mapvote_keeptwotime = 0;
2087                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2088                         result = strcat(result, ":", ftos(firstPlaceVotes));
2089                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2090                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2091                         didntvote = mapvote_voters;
2092                         for(i = 0; i < mapvote_count; ++i)
2093                                 if(mapvote_maps[i] != "")
2094                                 {
2095                                         didntvote -= mapvote_votes[i];
2096                                         if(i != firstPlace)
2097                                                 if(i != secondPlace)
2098                                                 {
2099                                                         result = strcat(result, ":", mapvote_maps[i]);
2100                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2101                                                         if(i < mapvote_count_real)
2102                                                         {
2103                                                                 strunzone(mapvote_maps[i]);
2104                                                                 mapvote_maps[i] = "";
2105                                                         }
2106                                                 }
2107                                 }
2108                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2109                         GameLogEcho(result, FALSE);
2110                 }
2111
2112         return FALSE;
2113 }
2114 void MapVote_Tick()
2115 {
2116         string msgstr;
2117         string tmp;
2118         float i;
2119         float keeptwo;
2120         float totalvotes;
2121
2122         keeptwo = mapvote_keeptwotime;
2123         MapVote_CheckRules_1(); // count
2124         if(MapVote_CheckRules_2()) // decide
2125                 return;
2126
2127         totalvotes = 0;
2128         FOR_EACH_REALCLIENT(other)
2129         {
2130                 // hide scoreboard again
2131                 if(other.health != 2342)
2132                 {
2133                         other.health = 2342;
2134                         other.impulse = 0;
2135                         if(clienttype(other) == CLIENTTYPE_REAL)
2136                         {
2137                                 stuffcmd(other, "\nin_bind 7 1 \"impulse 1\"; in_bind 7 2 \"impulse 2\"; in_bind 7 3 \"impulse 3\"; in_bind 7 4 \"impulse 4\"; in_bind 7 5 \"impulse 5\"; in_bind 7 6 \"impulse 6\"; in_bind 7 7 \"impulse 7\"; in_bind 7 8 \"impulse 8\"; in_bind 7 9 \"impulse 9\"; in_bind 7 0 \"impulse 10\"; in_bind 7 KP_1 \"impulse 1\"; in_bind 7 KP_2 \"impulse 2\"; in_bind 7 KP_3 \"impulse 3\"; in_bind 7 KP_4 \"impulse 4\"; in_bind 7 KP_5 \"impulse 5\"; in_bind 7 KP_6 \"impulse 6\"; in_bind 7 KP_7 \"impulse 7\"; in_bind 7 KP_8 \"impulse 8\"; in_bind 7 KP_9 \"impulse 9\"; in_bind 7 KP_0 \"impulse 10\"; in_bindmap 7 0\n");
2138                                 msg_entity = other;
2139                                 WriteByte(MSG_ONE, SVC_FINALE);
2140                                 WriteString(MSG_ONE, "");
2141                         }
2142                 }
2143
2144                 // notify about keep-two
2145                 if(keeptwo != 0 && mapvote_keeptwotime == 0)
2146                         play2(other, "misc/invshot.wav");
2147
2148                 // clear possibly invalid votes
2149                 if(mapvote_maps[other.mapvote - 1] == "")
2150                         other.mapvote = 0;
2151                 // use impulses as new vote
2152                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2153                         if(mapvote_maps[other.impulse - 1] != "")
2154                                 other.mapvote = other.impulse;
2155                 other.impulse = 0;
2156
2157                 if(other.mapvote)
2158                         ++totalvotes;
2159         }
2160
2161         MapVote_CheckRules_1(); // just count
2162
2163         FOR_EACH_REALCLIENT(other)
2164         {
2165                 // display voting screen
2166                 msgstr = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
2167                 msgstr = substring(msgstr, 0, strlen(msgstr) - mapvote_count);
2168                 if(mapvote_abstain)
2169                         msgstr = substring(msgstr, 1, strlen(msgstr) - 1);
2170                 msgstr = strcat(msgstr, mapvote_message);
2171                 msgstr = strcat(msgstr, "\n\n");
2172                 for(i = 0; i < mapvote_count; ++i)
2173                         if(mapvote_maps[i] == "")
2174                                 msgstr = strcat(msgstr, "\n");
2175                         else
2176                         {
2177                                 tmp = mapvote_maps[i];
2178                                 tmp = strpad(mapvote_maxlen, tmp);
2179                                 tmp = strcat(ftos(mod(i + 1, 10)), ": ", tmp);
2180                                 if(mapvote_detail)
2181                                 {
2182                                         tmp = strcat(tmp, " ^2(", ftos(mapvote_votes[i]), " vote");
2183                                         if(mapvote_votes[i] != 1)
2184                                                 tmp = strcat(tmp, "s");
2185                                         tmp = strcat(tmp, ")");
2186                                         tmp = strpad(mapvote_maxlen + 15, tmp);
2187                                 }
2188                                 if(mapvote_abstain)
2189                                         if(i == mapvote_count - 1)
2190                                                 msgstr = strcat(msgstr, "\n");
2191                                 if(other.mapvote == i + 1)
2192                                         msgstr = strcat(msgstr, "^3> ", tmp, "\n");
2193                                 else
2194                                         msgstr = strcat(msgstr, "^7  ", tmp, "\n");
2195                         }
2196
2197                 msgstr = strcat(msgstr, "\n\n^2", ftos(totalvotes), " vote");
2198                 if(totalvotes != 1)
2199                         msgstr = strcat(msgstr, "s");
2200                 msgstr = strcat(msgstr, " cast");
2201                 i = ceil(mapvote_timeout - time);
2202                 msgstr = strcat(msgstr, "\n", ftos(i), " second");
2203                 if(i != 1)
2204                         msgstr = strcat(msgstr, "s");
2205                 msgstr = strcat(msgstr, " left");
2206
2207                 centerprint_atprio(other, CENTERPRIO_MAPVOTE, msgstr);
2208         }
2209 }
2210 void MapVote_Start()
2211 {
2212         if(mapvote_run)
2213                 return;
2214
2215 #ifdef MAPINFO
2216         MapInfo_Enumerate();
2217         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), 1))
2218 #endif
2219                 mapvote_run = TRUE;
2220 }
2221 void MapVote_Think()
2222 {
2223         if(!mapvote_run)
2224                 return;
2225
2226         if(alreadychangedlevel)
2227                 return;
2228
2229         if(time < mapvote_nextthink)
2230                 return;
2231         //dprint("tick\n");
2232
2233         mapvote_nextthink = time + 0.5;
2234
2235         if(!mapvote_initialized)
2236         {
2237                 mapvote_initialized = TRUE;
2238                 if(DoNextMapOverride())
2239                         return;
2240                 if(!cvar("g_maplist_votable") || player_count <= 0)
2241                 {
2242                         GotoNextMap();
2243                         return;
2244                 }
2245                 MapVote_Init();
2246         }
2247
2248         MapVote_Tick();
2249 };
2250
2251 string GotoMap(string m)
2252 {
2253 #ifdef MAPINFO
2254         if(!MapInfo_CheckMap(m))
2255 #else
2256         if(!TryFile(strcat("maps/", m, ".mapcfg")))
2257 #endif
2258                 return "The map you chose is not available on this server.";
2259         cvar_set("nextmap", m);
2260         cvar_set("timelimit", "-1");
2261         if(mapvote_initialized || alreadychangedlevel)
2262         {
2263                 if(DoNextMapOverride())
2264                         return "Map switch initiated.";
2265                 else
2266                         return "Hm... no. For some reason I like THIS map more.";
2267         }
2268         else
2269                 return "Map switch will happen after scoreboard.";
2270 }
2271
2272
2273 void EndFrame()
2274 {
2275         FOR_EACH_REALCLIENT(self)
2276         {
2277                 if(self.classname == "spectator")
2278                 {
2279                         if(self.enemy.hitsound)
2280                                 play2(self, "misc/hit.wav");
2281                 }
2282                 else
2283                 {
2284                         if(self.hitsound)
2285                                 play2(self, "misc/hit.wav");
2286                 }
2287         }
2288         FOR_EACH_CLIENT(self)
2289                 self.hitsound = FALSE;
2290 }
2291
2292
2293 /*
2294  * RedirectionThink:
2295  * returns TRUE if redirecting
2296  */
2297 float redirection_timeout;
2298 float redirection_nextthink;
2299 float RedirectionThink()
2300 {
2301         float clients_found;
2302
2303         if(redirection_target == "")
2304                 return FALSE;
2305
2306         if(!redirection_timeout)
2307         {
2308                 cvar_set("sv_public", "-2");
2309                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2310                 if(redirection_target == "self")
2311                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2312                 else
2313                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2314         }
2315
2316         if(time < redirection_nextthink)
2317                 return TRUE;
2318
2319         redirection_nextthink = time + 1;
2320
2321         clients_found = 0;
2322         FOR_EACH_REALCLIENT(self)
2323         {
2324                 ServerConsoleEcho(strcat("Redirecting: sending connect command to ", self.netname), FALSE);
2325                 if(redirection_target == "self")
2326                         stuffcmd(self, "\ndisconnect; reconnect\n");
2327                 else
2328                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2329                 ++clients_found;
2330         }
2331
2332         ServerConsoleEcho(strcat("Redirecting: ", ftos(clients_found), " clients left."), FALSE);
2333
2334         if(time > redirection_timeout || clients_found == 0)
2335                 localcmd("\nwait; wait; wait; quit\n");
2336
2337         return TRUE;
2338 }
2339
2340 void SV_Shutdown()
2341 {
2342         if(world_initialized)
2343         {
2344                 world_initialized = 0;
2345                 print("Saving persistent data...\n");
2346                 Ban_SaveBans();
2347                 if(!sv_cheats)
2348                         db_save(ServerProgsDB, "server.db");
2349                 print("done!\n");
2350                 // tell the bot system the game is ending now
2351                 bot_endgame();
2352         }
2353         else
2354         {
2355                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2356         }
2357 }