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