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