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