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