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