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