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