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