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