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