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