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