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