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