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