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