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