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