]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/g_world.qc
Track whether cheats have been used (cheatcount field)
[divverent/nexuiz.git] / data / 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                                 play2all("announcer/robotic/prepareforbattle.wav");
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                 if(cvar("g_grappling_hook"))
543                         s = strcat(s, ":grappling_hook");
544                 if(!cvar("g_use_ammunition"))
545                         s = strcat(s, ":no_use_ammunition");
546                 if(!cvar("g_pickup_items"))
547                         s = strcat(s, ":no_pickup_items");
548                 if(cvar_string("g_weaponarena") != "0")
549                         s = strcat(s, ":", cvar_string("g_weaponarena"), " arena");
550                 if(cvar("g_nixnex"))
551                         s = strcat(s, ":nixnex");
552                 if(cvar("g_vampire"))
553                         s = strcat(s, ":vampire");
554                 if(cvar("g_laserguided_missile"))
555                         s = strcat(s, ":laserguided_missile");
556                 if(cvar("g_norecoil"))
557                         s = strcat(s, ":norecoil");
558                 if(cvar("g_midair"))
559                         s = strcat(s, ":midair");
560                 if(cvar("g_minstagib"))
561                         s = strcat(s, ":minstagib");
562                 GameLogEcho(s);
563                 GameLogEcho(":gameinfo:end");
564         }
565         else
566                 matchid = strzone(ftos(random()));
567
568         cvar_set("nextmap", "");
569
570         SetDefaultAlpha();
571
572         if(cvar("g_campaign"))
573                 CampaignPostInit();
574
575         fteqcc_testbugs();
576
577         Ban_LoadBans();
578
579         MapInfo_Enumerate();
580         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
581
582         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
583         {
584                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
585                 if(fd != -1)
586                 {
587                         while((s = fgets(fd)))
588                         {
589                                 l = tokenize_console(s);
590                                 if(l < 2)
591                                         continue;
592                                 if(argv(0) == "cd")
593                                 {
594                                         print("Found ^1DEPRECATED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
595                                         print("  cdtrack ", argv(2), "\n");
596                                 }
597                                 else if(argv(0) == "fog")
598                                 {
599                                         print("Found ^1DEPRECATED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
600                                         print("  \"fog\" \"", s, "\"\n");
601                                 }
602                                 else if(argv(0) == "set")
603                                 {
604                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
605                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
606                                 }
607                                 else if(argv(0) != "//")
608                                 {
609                                         print("Found ^1DEPRECATED^7 set command in .cfg file; put this line in mapinfo instead:\n");
610                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
611                                 }
612                         }
613                         fclose(fd);
614                 }
615         }
616
617         WeaponStats_Init();
618
619         addstat(STAT_WEAPONS, AS_INT, weapons);
620         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
621         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
622         addstat(STAT_ALLOW_OLDNEXBEAM, AS_INT, stat_allow_oldnexbeam);
623         Nagger_Init();
624
625         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
626         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
627         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
628         addstat(STAT_FUEL, AS_INT, ammo_fuel);
629         addstat(STAT_DAMAGE_HITS, AS_INT, stat_hit);
630         addstat(STAT_DAMAGE_FIRED, AS_INT, stat_fired);
631         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
632         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
633         addstat(STAT_BULLETS_LOADED, AS_INT, campingrifle_bulletcounter);
634
635         next_pingtime = time + 5;
636         InitializeEntity(self, cvar_changes_init, INITPRIO_CVARS);
637
638         detect_maptype();
639
640         lsmaps_reply = "^7Maps available: ";
641         for(i = 0, j = 0; i < MapInfo_count; ++i)
642         {
643                 if(MapInfo_Get_ByID(i))
644                         if not(MapInfo_Map_flags & (MAPINFO_FLAG_HIDDEN | MAPINFO_FLAG_FORBIDDEN))
645                         {
646                                 if(mod(i, 2))
647                                         col = "^2";
648                                 else
649                                         col = "^3";
650                                 ++j;
651                                 lsmaps_reply = strcat(lsmaps_reply, col, MapInfo_Map_bspname, " ");
652                         }
653         }
654         lsmaps_reply = strzone(strcat(lsmaps_reply, "\n"));
655
656         maplist_reply = "^7Maps in list: ";
657         n = tokenize_console(cvar_string("g_maplist"));
658         for(i = 0, j = 0; i < n; ++i)
659         {
660                 if(MapInfo_CheckMap(argv(i)))
661                 {
662                         if(mod(j, 2))
663                                 col = "^2";
664                         else
665                                 col = "^3";
666                         maplist_reply = strcat(maplist_reply, col, argv(i), " ");
667                         ++j;
668                 }
669         }
670         maplist_reply = strzone(strcat(maplist_reply, "\n"));
671         MapInfo_ClearTemps();
672
673         records_reply = strzone(getrecords());
674         rankings_reply = strzone(getrankings());
675
676         ClientInit_Spawn();
677         RandomSeed_Spawn();
678         PingPLReport_Spawn();
679
680         localcmd("\n_sv_hook_gamestart ", GetGametype(), ";");
681
682         world_initialized = 1;
683 }
684
685 void spawnfunc_light (void)
686 {
687         //makestatic (self); // Who the f___ did that?
688         remove(self);
689 }
690
691 float TryFile( string pFilename )
692 {
693         local float lHandle;
694         dprint("TryFile(\"", pFilename, "\")\n");
695         lHandle = fopen( pFilename, FILE_READ );
696         if( lHandle != -1 ) {
697                 fclose( lHandle );
698                 return TRUE;
699         } else {
700                 return FALSE;
701         }
702 };
703
704 string GetGametype()
705 {
706         return GametypeNameFromType(game);
707 }
708
709 string getmapname_stored;
710 string GetMapname()
711 {
712         return mapname;
713 }
714
715 float Map_Count, Map_Current;
716 string Map_Current_Name;
717
718 // NOTE: this now expects the map list to be already tokenize()d and the count in Map_Count
719 float GetMaplistPosition()
720 {
721         float pos, idx;
722         string map;
723
724         map = GetMapname();
725         idx = cvar("g_maplist_index");
726
727         if(idx >= 0)
728                 if(idx < Map_Count)
729                         if(map == argv(idx))
730                                 return idx;
731
732         for(pos = 0; pos < Map_Count; ++pos)
733                 if(map == argv(pos))
734                         return pos;
735
736         // resume normal maplist rotation if current map is not in g_maplist
737         return idx;
738 }
739
740 float MapHasRightSize(string map)
741 {
742         float fh;
743         if(currentbots || cvar("bot_number") || player_count < cvar("minplayers"))
744         if(cvar("g_maplist_check_waypoints"))
745         {
746                 dprint("checkwp "); dprint(map);
747                 fh = fopen(strcat("maps/", map, ".waypoints"), FILE_READ);
748                 if(fh < 0)
749                 {
750                         dprint(": no waypoints\n");
751                         return FALSE;
752                 }
753                 dprint(": has waypoints\n");
754                 fclose(fh);
755         }
756
757         // open map size restriction file
758         dprint("opensize "); dprint(map);
759         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
760         if(fh >= 0)
761         {
762                 float mapmin, mapmax;
763                 dprint(": ok, ");
764                 mapmin = stof(fgets(fh));
765                 mapmax = stof(fgets(fh));
766                 fclose(fh);
767                 if(player_count < mapmin)
768                 {
769                         dprint("not enough\n");
770                         return FALSE;
771                 }
772                 if(player_count > mapmax)
773                 {
774                         dprint("too many\n");
775                         return FALSE;
776                 }
777                 dprint("right size\n");
778                 return TRUE;
779         }
780         dprint(": not found\n");
781         return TRUE;
782 }
783
784 string Map_Filename(float position)
785 {
786         return strcat("maps/", argv(position), ".bsp");
787 }
788
789 string strwords(string s, float w)
790 {
791         float endpos;
792         for(endpos = 0; w && endpos >= 0; --w)
793                 endpos = strstrofs(s, " ", endpos + 1);
794         if(endpos < 0)
795                 return s;
796         else
797                 return substring(s, 0, endpos);
798 }
799
800 float strhasword(string s, string w)
801 {
802         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
803 }
804
805 void Map_MarkAsRecent(string m)
806 {
807         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", cvar_string("g_maplist_mostrecent")), max(0, cvar("g_maplist_mostrecent_count"))));
808 }
809
810 float Map_IsRecent(string m)
811 {
812         return strhasword(cvar_string("g_maplist_mostrecent"), m);
813 }
814
815 float Map_Check(float position, float pass)
816 {
817         string filename;
818         string map_next;
819         map_next = argv(position);
820         if(pass <= 1)
821         {
822                 if(Map_IsRecent(map_next))
823                         return 0;
824         }
825         filename = Map_Filename(position);
826         if(MapInfo_CheckMap(map_next))
827         {
828                 if(pass == 2)
829                         return 1;
830                 if(MapHasRightSize(map_next))
831                         return 1;
832                 return 0;
833         }
834         else
835                 dprint( "Couldn't select '", filename, "'..\n" );
836
837         return 0;
838 }
839
840 void Map_Goto_SetStr(string nextmapname)
841 {
842         if(getmapname_stored != "")
843                 strunzone(getmapname_stored);
844         if(nextmapname == "")
845                 getmapname_stored = "";
846         else
847                 getmapname_stored = strzone(nextmapname);
848 }
849
850 void Map_Goto_SetFloat(float position)
851 {
852         cvar_set("g_maplist_index", ftos(position));
853         Map_Goto_SetStr(argv(position));
854 }
855
856 void GameResetCfg()
857 {
858         // settings persist, except...
859         localcmd("\nsettemp_restore\n");
860 };
861
862 void Map_Goto()
863 {
864         GameResetCfg();
865         MapInfo_LoadMap(getmapname_stored);
866 }
867
868 // return codes of map selectors:
869 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
870 //   -2 = permanent failure
871 float() MaplistMethod_Iterate = // usual method
872 {
873         float pass, i;
874
875         for(pass = 1; pass <= 2; ++pass)
876         {
877                 for(i = 1; i < Map_Count; ++i)
878                 {
879                         float mapindex;
880                         mapindex = mod(i + Map_Current, Map_Count);
881                         if(Map_Check(mapindex, pass))
882                                 return mapindex;
883                 }
884         }
885         return -1;
886 }
887
888 float() MaplistMethod_Repeat = // fallback method
889 {
890         if(Map_Check(Map_Current, 2))
891                 return Map_Current;
892         return -2;
893 }
894
895 float() MaplistMethod_Random = // random map selection
896 {
897         float i, imax;
898
899         imax = 42;
900
901         for(i = 0; i <= imax; ++i)
902         {
903                 float mapindex;
904                 mapindex = mod(Map_Current + floor(random() * (Map_Count - 1) + 1), Map_Count); // any OTHER map
905                 if(Map_Check(mapindex, 1))
906                         return mapindex;
907         }
908         return -1;
909 }
910
911 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
912 // the exponent sets a bias on the map selection:
913 // the higher the exponent, the less likely "shortly repeated" same maps are
914 {
915         float i, j, imax, insertpos;
916
917         imax = 42;
918
919         for(i = 0; i <= imax; ++i)
920         {
921                 string newlist;
922
923                 // now reinsert this at another position
924                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
925                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
926                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
927                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
928
929                 // insert the current map there
930                 newlist = "";
931                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
932                         newlist = strcat(newlist, " ", argv(j));
933                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
934                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
935                         newlist = strcat(newlist, " ", argv(j));
936                 newlist = substring(newlist, 1, strlen(newlist) - 1);
937                 cvar_set("g_maplist", newlist);
938                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
939
940                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
941                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
942                 if(Map_Check(Map_Current, 1))
943                         return Map_Current;
944         }
945         return -1;
946 }
947
948 void Maplist_Init()
949 {
950         Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
951         if(Map_Count == 0)
952         {
953                 bprint( "Maplist is empty!  Resetting it to default map list.\n" );
954                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
955                 if(cvar("g_maplist_shuffle"))
956                         ShuffleMaplist();
957                 localcmd("\nmenu_cmd sync\n");
958                 Map_Count = tokenizebyseparator(cvar_string("g_maplist"), " ");
959         }
960         if(Map_Count == 0)
961                 error("empty maplist, cannot select a new map");
962         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
963
964         if(Map_Current_Name)
965                 strunzone(Map_Current_Name);
966         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
967         // this may or may not be correct, but who cares, in the worst case a map
968         // isn't chosen in the first pass that should have been
969 }
970
971 string GetNextMap()
972 {
973         float nextMap;
974
975         Maplist_Init();
976         nextMap = -1;
977
978         if(nextMap == -1)
979                 if(cvar("g_maplist_shuffle") > 0)
980                         nextMap = MaplistMethod_Shuffle(cvar("g_maplist_shuffle") + 1);
981
982         if(nextMap == -1)
983                 if(cvar("g_maplist_selectrandom"))
984                         nextMap = MaplistMethod_Random();
985
986         if(nextMap == -1)
987                 nextMap = MaplistMethod_Iterate();
988
989         if(nextMap == -1)
990                 nextMap = MaplistMethod_Repeat();
991
992         if(nextMap >= 0)
993         {
994                 Map_Goto_SetFloat(nextMap);
995                 return getmapname_stored;
996         }
997
998         return "";
999 };
1000
1001 float DoNextMapOverride()
1002 {
1003         if(cvar("g_campaign"))
1004         {
1005                 CampaignPostIntermission();
1006                 alreadychangedlevel = TRUE;
1007                 return TRUE;
1008         }
1009         if(cvar("quit_when_empty"))
1010         {
1011                 if(player_count <= currentbots)
1012                 {
1013                         localcmd("quit\n");
1014                         alreadychangedlevel = TRUE;
1015                         return TRUE;
1016                 }
1017         }
1018         if(cvar_string("quit_and_redirect") != "")
1019         {
1020                 redirection_target = strzone(cvar_string("quit_and_redirect"));
1021                 alreadychangedlevel = TRUE;
1022                 return TRUE;
1023         }
1024         if (cvar("samelevel")) // if samelevel is set, stay on same level
1025         {
1026                 // 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)
1027                 //localcmd(strcat("exec \"maps/", mapname, ".mapcfg\"\n"));
1028                 // so instead just restart the current map using the restart command (DOES NOT WORK PROPERLY WITH exit_cfg STUFF)
1029                 localcmd("restart\n");
1030                 //changelevel (mapname);
1031                 alreadychangedlevel = TRUE;
1032                 return TRUE;
1033         }
1034         if(cvar_string("nextmap") != "")
1035                 if(MapInfo_CheckMap(cvar_string("nextmap")))
1036                 {
1037                         Map_Goto_SetStr(cvar_string("nextmap"));
1038                         Map_Goto();
1039                         alreadychangedlevel = TRUE;
1040                         return TRUE;
1041                 }
1042         if(cvar("lastlevel"))
1043         {
1044                 GameResetCfg();
1045                 localcmd("set lastlevel 0\ntogglemenu\n");
1046                 alreadychangedlevel = TRUE;
1047                 return TRUE;
1048         }
1049         return FALSE;
1050 };
1051
1052 void GotoNextMap()
1053 {
1054         //local string nextmap;
1055         //local float n, nummaps;
1056         //local string s;
1057         if (alreadychangedlevel)
1058                 return;
1059         alreadychangedlevel = TRUE;
1060
1061         {
1062                 string nextMap;
1063                 float allowReset;
1064
1065                 for(allowReset = 1; allowReset >= 0; --allowReset)
1066                 {
1067                         nextMap = GetNextMap();
1068                         if(nextMap != "")
1069                                 break;
1070
1071                         if(allowReset)
1072                         {
1073                                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
1074                                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
1075                                 if(cvar("g_maplist_shuffle"))
1076                                         ShuffleMaplist();
1077                                 localcmd("\nmenu_cmd sync\n");
1078                         }
1079                         else
1080                         {
1081                                 error("Everything is broken - not even the default map list works. Please report this to the developers.");
1082                         }
1083                 }
1084                 Map_Goto();
1085         }
1086 };
1087
1088
1089 /*
1090 ============
1091 IntermissionThink
1092
1093 When the player presses attack or jump, change to the next level
1094 ============
1095 */
1096 .float autoscreenshot;
1097 void() MapVote_Start;
1098 void() MapVote_Think;
1099 float mapvote_initialized;
1100 void IntermissionThink()
1101 {
1102         FixIntermissionClient(self);
1103
1104         if(cvar("sv_autoscreenshot"))
1105         if(self.autoscreenshot > 0)
1106         if(time > self.autoscreenshot)
1107         {
1108                 self.autoscreenshot = -1;
1109                 if(clienttype(self) == CLIENTTYPE_REAL)
1110                         stuffcmd(self, "\nscreenshot\necho \"^5A screenshot has been taken at request of the server.\"\n");
1111                 return;
1112         }
1113
1114         if (time < intermission_exittime)
1115                 return;
1116
1117         if(!mapvote_initialized)
1118                 if (time < intermission_exittime + 10 && !self.BUTTON_ATCK && !self.BUTTON_JUMP && !self.BUTTON_ATCK2 && !self.BUTTON_HOOK && !self.BUTTON_USE)
1119                         return;
1120
1121         MapVote_Start();
1122 };
1123
1124 /*
1125 ============
1126 FindIntermission
1127
1128 Returns the entity to view from
1129 ============
1130 */
1131 /*
1132 entity FindIntermission()
1133 {
1134         local   entity spot;
1135         local   float cyc;
1136
1137 // look for info_intermission first
1138         spot = find (world, classname, "info_intermission");
1139         if (spot)
1140         {       // pick a random one
1141                 cyc = random() * 4;
1142                 while (cyc > 1)
1143                 {
1144                         spot = find (spot, classname, "info_intermission");
1145                         if (!spot)
1146                                 spot = find (spot, classname, "info_intermission");
1147                         cyc = cyc - 1;
1148                 }
1149                 return spot;
1150         }
1151
1152 // then look for the start position
1153         spot = find (world, classname, "info_player_start");
1154         if (spot)
1155                 return spot;
1156
1157 // testinfo_player_start is only found in regioned levels
1158         spot = find (world, classname, "testplayerstart");
1159         if (spot)
1160                 return spot;
1161
1162 // then look for the start position
1163         spot = find (world, classname, "info_player_deathmatch");
1164         if (spot)
1165                 return spot;
1166
1167         //objerror ("FindIntermission: no spot");
1168         return world;
1169 };
1170 */
1171
1172 /*
1173 ===============================================================================
1174
1175 RULES
1176
1177 ===============================================================================
1178 */
1179
1180 void DumpStats(float final)
1181 {
1182         local float file;
1183         local string s;
1184         local float to_console;
1185         local float to_eventlog;
1186         local float to_file;
1187         local float i;
1188
1189         to_console = cvar("sv_logscores_console");
1190         to_eventlog = cvar("sv_eventlog");
1191         to_file = cvar("sv_logscores_file");
1192
1193         if(!final)
1194         {
1195                 to_console = TRUE; // always print printstats replies
1196                 to_eventlog = FALSE; // but never print them to the event log
1197         }
1198
1199         if(to_eventlog)
1200                 if(cvar("sv_eventlog_console"))
1201                         to_console = FALSE; // otherwise we get the output twice
1202
1203         if(final)
1204                 s = ":scores:";
1205         else
1206                 s = ":status:";
1207         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1208
1209         if(to_console)
1210                 print(s, "\n");
1211         if(to_eventlog)
1212                 GameLogEcho(s);
1213         if(to_file)
1214         {
1215                 file = fopen(cvar_string("sv_logscores_filename"), FILE_APPEND);
1216                 if(file == -1)
1217                         to_file = FALSE;
1218                 else
1219                         fputs(file, strcat(s, "\n"));
1220         }
1221
1222         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1223         if(to_console)
1224                 print(s, "\n");
1225         if(to_eventlog)
1226                 GameLogEcho(s);
1227         if(to_file)
1228                 fputs(file, strcat(s, "\n"));
1229
1230         FOR_EACH_CLIENT(other)
1231         {
1232                 if ((clienttype(other) == CLIENTTYPE_REAL) || (clienttype(other) == CLIENTTYPE_BOT && cvar("sv_logscores_bots")))
1233                 {
1234                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1235                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1236                         if(other.classname == "player" || g_arena || g_ca || g_lms)
1237                                 s = strcat(s, ftos(other.team), ":");
1238                         else
1239                                 s = strcat(s, "spectator:");
1240
1241                         if(to_console)
1242                                 print(s, other.netname, "\n");
1243                         if(to_eventlog)
1244                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1245                         if(to_file)
1246                                 fputs(file, strcat(s, other.netname, "\n"));
1247                 }
1248         }
1249
1250         if(teams_matter)
1251         {
1252                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1253                 if(to_console)
1254                         print(s, "\n");
1255                 if(to_eventlog)
1256                         GameLogEcho(s);
1257                 if(to_file)
1258                         fputs(file, strcat(s, "\n"));
1259
1260                 for(i = 1; i < 16; ++i)
1261                 {
1262                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1263                         s = strcat(s, ":", ftos(i));
1264                         if(to_console)
1265                                 print(s, "\n");
1266                         if(to_eventlog)
1267                                 GameLogEcho(s);
1268                         if(to_file)
1269                                 fputs(file, strcat(s, "\n"));
1270                 }
1271         }
1272
1273         if(to_console)
1274                 print(":end\n");
1275         if(to_eventlog)
1276                 GameLogEcho(":end");
1277         if(to_file)
1278         {
1279                 fputs(file, ":end\n");
1280                 fclose(file);
1281         }
1282 }
1283
1284 void FixIntermissionClient(entity e)
1285 {
1286         string s;
1287         if(!e.autoscreenshot) // initial call
1288         {
1289                 e.angles = e.v_angle;
1290                 e.angles_x = -e.angles_x;
1291                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1292                 e.health = -2342;
1293                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1294                 e.solid = SOLID_NOT;
1295                 e.movetype = MOVETYPE_NONE;
1296                 e.takedamage = DAMAGE_NO;
1297                 if(e.weaponentity)
1298                 {
1299                         e.weaponentity.effects = EF_NODRAW;
1300                         if (e.weaponentity.weaponentity)
1301                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1302                 }
1303                 if(clienttype(e) == CLIENTTYPE_REAL)
1304                 {
1305                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1306                         s = cvar_string("sv_intermission_cdtrack");
1307                         if(s != "")
1308                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1309                         msg_entity = e;
1310                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1311                 }
1312         }
1313
1314         //e.velocity = '0 0 0';
1315         //e.fixangle = TRUE;
1316
1317         // TODO halt weapon animation
1318 }
1319
1320
1321 /*
1322 go to the next level for deathmatch
1323 only called if a time or frag limit has expired
1324 */
1325 void NextLevel()
1326 {
1327         float i;
1328
1329         gameover = TRUE;
1330
1331         intermission_running = 1;
1332
1333 // enforce a wait time before allowing changelevel
1334         if(player_count > 0)
1335                 intermission_exittime = time + cvar("sv_mapchange_delay");
1336         else
1337                 intermission_exittime = -1;
1338
1339         /*
1340         WriteByte (MSG_ALL, SVC_CDTRACK);
1341         WriteByte (MSG_ALL, 3);
1342         WriteByte (MSG_ALL, 3);
1343         // done in FixIntermission
1344         */
1345
1346         //pos = FindIntermission ();
1347
1348         VoteReset();
1349
1350         DumpStats(TRUE);
1351
1352         if(cvar("sv_eventlog"))
1353                 GameLogEcho(":gameover");
1354
1355         GameLogClose();
1356
1357 // TO DO
1358
1359 // save the stats to a text file on the client
1360 // stuffcmd(other, log_stats "stats/file_name");
1361 // bprint stats
1362 // stuffcmd(other, log_stats "");
1363 // use a filename similar to the demo name
1364         // string file_name;
1365         // file_name = strcat("\nlog_file \"stats/", strftime(TRUE, "%Y-%m-%d_%H-%M"), "_", mapname, ".txt\"");  // open the log file
1366
1367 // write a stats parser for the menu
1368
1369         if(cvar("sv_accuracy_data_send")) {
1370                 string stats_to_send;
1371
1372                 FOR_EACH_CLIENT(other) {  // make the string to send
1373                         FixIntermissionClient(other);
1374
1375                         if(other.cvar_cl_accuracy_data_share) {
1376                                 stats_to_send = strcat(stats_to_send, ":hits:", other.netname);
1377
1378                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1379                                         stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_hit[i-1]));
1380
1381                                 stats_to_send = strcat(stats_to_send, "\n:fired:", other.netname);
1382
1383                                 for(i = WEP_FIRST; i <= WEP_LAST; ++i)
1384                                         stats_to_send = strcat(stats_to_send, ":", ftos(other.stats_fired[i-1]));
1385
1386                                 stats_to_send = strcat(stats_to_send, "\n");
1387                         }
1388                 }
1389
1390                 FOR_EACH_REALCLIENT(other) {  // only spam humans
1391                         Score_NicePrint(other);  // print the score
1392
1393                         if(other.cvar_cl_accuracy_data_receive)  // send the stats string to all the willing clients
1394                                 bprint(stats_to_send);
1395                 }
1396         } else { // ye olde message
1397                 FOR_EACH_PLAYER(other) {
1398                         FixIntermissionClient(other);
1399
1400                         if(other.winning)
1401                                 bprint(other.netname, " ^7wins.\n");
1402                 }
1403         }
1404
1405         if(cvar("g_campaign"))
1406                 CampaignPreIntermission();
1407
1408         localcmd("\nsv_hook_gameend;");
1409 }
1410
1411 /*
1412 ============
1413 CheckRules_Player
1414
1415 Exit deathmatch games upon conditions
1416 ============
1417 */
1418 void CheckRules_Player()
1419 {
1420         if (gameover)   // someone else quit the game already
1421                 return;
1422
1423         if(self.deadflag == DEAD_NO)
1424                 self.play_time += frametime;
1425
1426         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1427         //   (div0: and that in CheckRules_World please)
1428 };
1429
1430 float checkrules_equality;
1431 float checkrules_suddendeathwarning;
1432 float checkrules_suddendeathend;
1433 float checkrules_overtimesadded; //how many overtimes have been already added
1434
1435 float WINNING_NO = 0; // no winner, but time limits may terminate the game
1436 float WINNING_YES = 1; // winner found
1437 float WINNING_NEVER = 2; // no winner, enter overtime if time limit is reached
1438 float WINNING_STARTSUDDENDEATHOVERTIME = 3; // no winner, enter suddendeath overtime NOW
1439
1440 float InitiateSuddenDeath()
1441 {
1442         // Check first whether normal overtimes could be added before initiating suddendeath mode
1443         // - for this timelimit_overtime needs to be >0 of course
1444         // - also check the winning condition calculated in the previous frame and only add normal overtime
1445         //   again, if at the point at which timelimit would be extended again, still no winner was found
1446         if ((checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < cvar("timelimit_overtimes")) && cvar("timelimit_overtime") && !(g_race && !g_race_qualifying))
1447         {
1448                 return 1; // need to call InitiateOvertime later
1449         }
1450         else
1451         {
1452                 if(!checkrules_suddendeathend)
1453                 {
1454                         checkrules_suddendeathend = time + 60 * cvar("timelimit_suddendeath");
1455                         if(g_race && !g_race_qualifying)
1456                                 race_StartCompleting();
1457                 }
1458                 return 0;
1459         }
1460 }
1461
1462 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1463 {
1464         ++checkrules_overtimesadded;
1465         //add one more overtime by simply extending the timelimit
1466         float tl;
1467         tl = cvar("timelimit");
1468         tl += cvar("timelimit_overtime");
1469         cvar_set("timelimit", ftos(tl));
1470         string minutesPlural;
1471         if (cvar("timelimit_overtime") == 1)
1472                 minutesPlural = " ^3minute";
1473         else
1474                 minutesPlural = " ^3minutes";
1475
1476         bcenterprint(
1477                 strcat(
1478                         "^3Now playing ^1OVERTIME^3!\n\n^3Added ^1",
1479                         ftos(cvar("timelimit_overtime")),
1480                         minutesPlural,
1481                         " to the game!"
1482                 )
1483         );
1484 }
1485
1486 float GetWinningCode(float fraglimitreached, float equality)
1487 {
1488         if(equality)
1489                 if(fraglimitreached)
1490                         return WINNING_STARTSUDDENDEATHOVERTIME;
1491                 else
1492                         return WINNING_NEVER;
1493         else
1494                 if(fraglimitreached)
1495                         return WINNING_YES;
1496                 else
1497                         return WINNING_NO;
1498 }
1499
1500 // set the .winning flag for exactly those players with a given field value
1501 void SetWinners(.float field, float value)
1502 {
1503         entity head;
1504         FOR_EACH_PLAYER(head)
1505                 head.winning = (head.field == value);
1506 }
1507
1508 // set the .winning flag for those players with a given field value
1509 void AddWinners(.float field, float value)
1510 {
1511         entity head;
1512         FOR_EACH_PLAYER(head)
1513                 if(head.field == value)
1514                         head.winning = 1;
1515 }
1516
1517 // clear the .winning flags
1518 void ClearWinners(void)
1519 {
1520         entity head;
1521         FOR_EACH_PLAYER(head)
1522                 head.winning = 0;
1523 }
1524
1525 // Onslaught winning condition:
1526 // game terminates if only one team has a working generator (or none)
1527 float WinningCondition_Onslaught()
1528 {
1529         entity head;
1530         local float t1, t2, t3, t4;
1531
1532         WinningConditionHelper(); // set worldstatus
1533
1534         if(inWarmupStage)
1535                 return WINNING_NO;
1536
1537         // first check if the game has ended
1538         t1 = t2 = t3 = t4 = 0;
1539         head = find(world, classname, "onslaught_generator");
1540         while (head)
1541         {
1542                 if (head.health > 0)
1543                 {
1544                         if (head.team == COLOR_TEAM1) t1 = 1;
1545                         if (head.team == COLOR_TEAM2) t2 = 1;
1546                         if (head.team == COLOR_TEAM3) t3 = 1;
1547                         if (head.team == COLOR_TEAM4) t4 = 1;
1548                 }
1549                 head = find(head, classname, "onslaught_generator");
1550         }
1551         if (t1 + t2 + t3 + t4 < 2)
1552         {
1553                 // game over, only one team remains (or none)
1554                 ClearWinners();
1555                 if (t1) SetWinners(team, COLOR_TEAM1);
1556                 if (t2) SetWinners(team, COLOR_TEAM2);
1557                 if (t3) SetWinners(team, COLOR_TEAM3);
1558                 if (t4) SetWinners(team, COLOR_TEAM4);
1559                 dprint("Have a winner, ending game.\n");
1560                 return WINNING_YES;
1561         }
1562
1563         // Two or more teams remain
1564         return WINNING_NO;
1565 }
1566
1567 float LMS_NewPlayerLives()
1568 {
1569         float fl;
1570         fl = cvar("fraglimit");
1571         if(fl == 0)
1572                 fl = 999;
1573
1574         // first player has left the game for dying too much? Nobody else can get in.
1575         if(lms_lowest_lives < 1)
1576                 return 0;
1577
1578         if(!cvar("g_lms_join_anytime"))
1579                 if(lms_lowest_lives < fl - cvar("g_lms_last_join"))
1580                         return 0;
1581
1582         return bound(1, lms_lowest_lives, fl);
1583 }
1584
1585 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1586 // they win. Otherwise the defending team wins once the timelimit passes.
1587 void assault_new_round();
1588 float WinningCondition_Assault()
1589 {
1590         local float status;
1591
1592         WinningConditionHelper(); // set worldstatus
1593
1594         status = WINNING_NO;
1595         // as the timelimit has not yet passed just assume the defending team will win
1596         if(assault_attacker_team == COLOR_TEAM1)
1597         {
1598                 SetWinners(team, COLOR_TEAM2);
1599         }
1600         else
1601         {
1602                 SetWinners(team, COLOR_TEAM1);
1603         }
1604
1605         local entity ent;
1606         ent = find(world, classname, "target_assault_roundend");
1607         if(ent)
1608         {
1609                 if(ent.winning) // round end has been triggered by attacking team
1610                 {
1611                         bprint("ASSAULT: round completed...\n");
1612                         SetWinners(team, assault_attacker_team);
1613
1614                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1615
1616                         if(ent.cnt == 1) // this was the second round
1617                         {
1618                                 status = WINNING_YES;
1619                         }
1620                         else
1621                         {
1622                                 local entity oldself;
1623                                 oldself = self;
1624                                 self = ent;
1625                                 assault_new_round();
1626                                 self = oldself;
1627                         }
1628                 }
1629         }
1630
1631         return status;
1632 }
1633
1634 // LMS winning condition: game terminates if and only if there's at most one
1635 // one player who's living lives. Top two scores being equal cancels the time
1636 // limit.
1637 float WinningCondition_LMS()
1638 {
1639         entity head, head2;
1640         float have_player;
1641         float have_players;
1642         float l;
1643
1644         have_player = FALSE;
1645         have_players = FALSE;
1646         l = LMS_NewPlayerLives();
1647
1648         head = find(world, classname, "player");
1649         if(head)
1650                 have_player = TRUE;
1651         head2 = find(head, classname, "player");
1652         if(head2)
1653                 have_players = TRUE;
1654
1655         if(have_player)
1656         {
1657                 // we have at least one player
1658                 if(have_players)
1659                 {
1660                         // two or more active players - continue with the game
1661                 }
1662                 else
1663                 {
1664                         // exactly one player?
1665
1666                         ClearWinners();
1667                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1668
1669                         if(l)
1670                         {
1671                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1672                                 return WINNING_NO;
1673                         }
1674                         else
1675                         {
1676                                 // a winner!
1677                                 // and assign him his first place
1678                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1679                                 return WINNING_YES;
1680                         }
1681                 }
1682         }
1683         else
1684         {
1685                 // nobody is playing at all...
1686                 if(l)
1687                 {
1688                         // wait for players...
1689                 }
1690                 else
1691                 {
1692                         // SNAFU (maybe a draw game?)
1693                         ClearWinners();
1694                         dprint("No players, ending game.\n");
1695                         return WINNING_YES;
1696                 }
1697         }
1698
1699         // When we get here, we have at least two players who are actually LIVING,
1700         // now check if the top two players have equal score.
1701         WinningConditionHelper();
1702
1703         ClearWinners();
1704         if(WinningConditionHelper_winner)
1705                 WinningConditionHelper_winner.winning = TRUE;
1706         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1707                 return WINNING_NEVER;
1708
1709         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1710         return WINNING_NO;
1711 }
1712
1713 void ShuffleMaplist()
1714 {
1715         cvar_set("g_maplist", shufflewords(cvar_string("g_maplist")));
1716 }
1717
1718 float leaderfrags;
1719 float WinningCondition_Scores(float limit, float leadlimit)
1720 {
1721         // TODO make everything use THIS winning condition (except LMS)
1722         WinningConditionHelper();
1723
1724         if(teams_matter)
1725         {
1726                 team1_score = TeamScore_GetCompareValue(COLOR_TEAM1);
1727                 team2_score = TeamScore_GetCompareValue(COLOR_TEAM2);
1728                 team3_score = TeamScore_GetCompareValue(COLOR_TEAM3);
1729                 team4_score = TeamScore_GetCompareValue(COLOR_TEAM4);
1730         }
1731
1732         ClearWinners();
1733         if(WinningConditionHelper_winner)
1734                 WinningConditionHelper_winner.winning = 1;
1735         if(WinningConditionHelper_winnerteam >= 0)
1736                 SetWinners(team, WinningConditionHelper_winnerteam);
1737
1738         if(WinningConditionHelper_lowerisbetter)
1739         {
1740                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1741                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1742                 limit = -limit;
1743         }
1744
1745         if(WinningConditionHelper_zeroisworst)
1746                 leadlimit = 0; // not supported in this mode
1747
1748         if(g_dm || g_tdm || g_arena || g_ca || (g_race && !g_race_qualifying) || g_nexball)
1749         // these modes always score in increments of 1, thus this makes sense
1750         {
1751                 if(leaderfrags != WinningConditionHelper_topscore)
1752                 {
1753                         leaderfrags = WinningConditionHelper_topscore;
1754
1755                         if (limit)
1756                         if (leaderfrags == limit - 1)
1757                                 play2all("announcer/robotic/1fragleft.wav");
1758                         else if (leaderfrags == limit - 2)
1759                                 play2all("announcer/robotic/2fragsleft.wav");
1760                         else if (leaderfrags == limit - 3)
1761                                 play2all("announcer/robotic/3fragsleft.wav");
1762                 }
1763         }
1764
1765         return GetWinningCode(
1766                 WinningConditionHelper_topscore &&
1767                 (
1768                         (limit && (WinningConditionHelper_topscore >= limit))
1769                         ||
1770                         (leadlimit && (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit))
1771                 ),
1772                 WinningConditionHelper_equality
1773         );
1774 }
1775
1776 float WinningCondition_Race(float fraglimit)
1777 {
1778         float wc;
1779         entity p;
1780         float n, c;
1781
1782         n = 0;
1783         c = 0;
1784         FOR_EACH_PLAYER(p)
1785         {
1786                 ++n;
1787                 if(p.race_completed)
1788                         ++c;
1789         }
1790         if(n && (n == c))
1791                 return WINNING_YES;
1792         wc = WinningCondition_Scores(fraglimit, 0);
1793
1794         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1795         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1796         // do NOT support equality when the laps are all raced!
1797                 return WINNING_STARTSUDDENDEATHOVERTIME;
1798         else
1799                 return WINNING_NEVER;
1800         return wc;
1801 }
1802
1803 void ReadyRestart();
1804 float WinningCondition_QualifyingThenRace(float limit)
1805 {
1806         float wc;
1807         wc = WinningCondition_Scores(limit, 0);
1808
1809         // NEVER initiate overtime
1810         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1811         {
1812                 return WINNING_YES;
1813         }
1814
1815         return wc;
1816 }
1817
1818 float WinningCondition_RanOutOfSpawns()
1819 {
1820         entity head;
1821
1822         if(have_team_spawns <= 0)
1823                 return WINNING_NO;
1824
1825         if(!some_spawn_has_been_used)
1826                 return WINNING_NO;
1827
1828         team1_score = team2_score = team3_score = team4_score = 0;
1829
1830         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1831         {
1832                 if(head.team == COLOR_TEAM1)
1833                         team1_score = 1;
1834                 else if(head.team == COLOR_TEAM2)
1835                         team2_score = 1;
1836                 else if(head.team == COLOR_TEAM3)
1837                         team3_score = 1;
1838                 else if(head.team == COLOR_TEAM4)
1839                         team4_score = 1;
1840         }
1841
1842         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1843         {
1844                 if(head.team == COLOR_TEAM1)
1845                         team1_score = 1;
1846                 else if(head.team == COLOR_TEAM2)
1847                         team2_score = 1;
1848                 else if(head.team == COLOR_TEAM3)
1849                         team3_score = 1;
1850                 else if(head.team == COLOR_TEAM4)
1851                         team4_score = 1;
1852         }
1853
1854         ClearWinners();
1855         if(team1_score + team2_score + team3_score + team4_score == 0)
1856         {
1857                 checkrules_equality = TRUE;
1858                 return WINNING_YES;
1859         }
1860         else if(team1_score + team2_score + team3_score + team4_score == 1)
1861         {
1862                 float t, i;
1863                 if(team1_score) t = COLOR_TEAM1;
1864                 if(team2_score) t = COLOR_TEAM2;
1865                 if(team3_score) t = COLOR_TEAM3;
1866                 if(team4_score) t = COLOR_TEAM4;
1867                 CheckAllowedTeams(world);
1868                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1869                 {
1870                         if(t != COLOR_TEAM1) if(c1 >= 0) TeamScore_AddToTeam(COLOR_TEAM1, i, -1000);
1871                         if(t != COLOR_TEAM2) if(c2 >= 0) TeamScore_AddToTeam(COLOR_TEAM2, i, -1000);
1872                         if(t != COLOR_TEAM3) if(c3 >= 0) TeamScore_AddToTeam(COLOR_TEAM3, i, -1000);
1873                         if(t != COLOR_TEAM4) if(c4 >= 0) TeamScore_AddToTeam(COLOR_TEAM4, i, -1000);
1874                 }
1875
1876                 AddWinners(team, t);
1877                 return WINNING_YES;
1878         }
1879         else
1880                 return WINNING_NO;
1881 }
1882
1883 /*
1884 ============
1885 CheckRules_World
1886
1887 Exit deathmatch games upon conditions
1888 ============
1889 */
1890 void CheckRules_World()
1891 {
1892         float timelimit;
1893         float fraglimit;
1894         float leadlimit;
1895
1896         VoteThink();
1897         MapVote_Think();
1898
1899         SetDefaultAlpha();
1900
1901         /*
1902         MapVote_Think should now do that part
1903         if (intermission_running)
1904                 if (time >= intermission_exittime + 60)
1905                 {
1906                         if(!DoNextMapOverride())
1907                                 GotoNextMap();
1908                         return;
1909                 }
1910         */
1911
1912         if (gameover)   // someone else quit the game already
1913         {
1914                 if(player_count == 0) // Nobody there? Then let's go to the next map
1915                         MapVote_Start();
1916                         // this will actually check the player count in the next frame
1917                         // again, but this shouldn't hurt
1918                 return;
1919         }
1920
1921         timelimit = cvar("timelimit") * 60;
1922         fraglimit = cvar("fraglimit");
1923         leadlimit = cvar("leadlimit");
1924
1925         if(inWarmupStage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1926         {
1927                 if(timelimit > 0)
1928                         timelimit = 0; // timelimit is not made for warmup
1929                 if(fraglimit > 0)
1930                         fraglimit = 0; // no fraglimit for now
1931                 leadlimit = 0; // no leadlimit for now
1932         }
1933
1934         if(g_onslaught)
1935                 timelimit = 0; // ONS has its own overtime rule
1936
1937         if(timelimit > 0)
1938         {
1939                 timelimit += game_starttime;
1940         }
1941         else if (timelimit < 0)
1942         {
1943                 // endmatch
1944                 NextLevel();
1945                 return;
1946         }
1947
1948         float wantovertime;
1949         wantovertime = 0;
1950
1951         if(checkrules_suddendeathend)
1952         {
1953                 if(!checkrules_suddendeathwarning)
1954                 {
1955                         checkrules_suddendeathwarning = TRUE;
1956                         if(g_race && !g_race_qualifying)
1957                                 bcenterprint("^3Everyone, finish your lap! The race is over!");
1958                         else
1959                                 bcenterprint("^3Now playing ^1OVERTIME^3!\n\n^3Keep fragging until we have a ^1winner^3!");
1960                 }
1961         }
1962         else
1963         {
1964                 if (timelimit && time >= timelimit)
1965                 {
1966                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1967                         {
1968                                 float totalplayers;
1969                                 float playerswithlaps;
1970                                 float readyplayers;
1971                                 entity head;
1972                                 totalplayers = playerswithlaps = readyplayers = 0;
1973                                 FOR_EACH_PLAYER(head)
1974                                 {
1975                                         ++totalplayers;
1976                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
1977                                                 ++playerswithlaps;
1978                                         if(head.ready)
1979                                                 ++readyplayers;
1980                                 }
1981
1982                                 // at least 2 of the players have completed a lap: start the RACE
1983                                 // otherwise, the players should end the qualifying on their own
1984                                 if(readyplayers || playerswithlaps >= 2)
1985                                 {
1986                                         checkrules_suddendeathend = 0;
1987                                         ReadyRestart(); // go to race
1988                                         return;
1989                                 }
1990                                 else
1991                                         wantovertime |= InitiateSuddenDeath();
1992                         }
1993                         else
1994                                 wantovertime |= InitiateSuddenDeath();
1995                 }
1996         }
1997
1998         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1999         {
2000                 NextLevel();
2001                 return;
2002         }
2003
2004         float checkrules_status;
2005         checkrules_status = WinningCondition_RanOutOfSpawns();
2006         if(checkrules_status == WINNING_YES)
2007         {
2008                 bprint("Hey! Someone ran out of spawns!\n");
2009         }
2010         else if(g_race && !g_race_qualifying && timelimit >= 0)
2011         {
2012                 checkrules_status = WinningCondition_Race(fraglimit);
2013                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2014         }
2015         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2016         {
2017                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2018                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2019         }
2020         else if(g_assault)
2021         {
2022                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2023         }
2024         else if(g_lms)
2025         {
2026                 checkrules_status = WinningCondition_LMS();
2027         }
2028         else if (g_onslaught)
2029         {
2030                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2031         }
2032         else
2033         {
2034                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2035                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2036         }
2037
2038         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2039         {
2040                 checkrules_status = WINNING_NEVER;
2041                 checkrules_overtimesadded = -1;
2042                 wantovertime |= InitiateSuddenDeath();
2043         }
2044
2045         if(checkrules_status == WINNING_NEVER)
2046                 // equality cases! Nobody wins if the overtime ends in a draw.
2047                 ClearWinners();
2048
2049         if(wantovertime)
2050         {
2051                 if(checkrules_status == WINNING_NEVER)
2052                         InitiateOvertime();
2053                 else
2054                         checkrules_status = WINNING_YES;
2055         }
2056
2057         if(checkrules_suddendeathend)
2058                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2059                         checkrules_status = WINNING_YES;
2060
2061         if(checkrules_status == WINNING_YES)
2062         {
2063                 //print("WINNING\n");
2064                 NextLevel();
2065         }
2066 };
2067
2068 float mapvote_nextthink;
2069 float mapvote_initialized;
2070 float mapvote_keeptwotime;
2071 float mapvote_timeout;
2072 string mapvote_message;
2073 #define MAPVOTE_SCREENSHOT_DIRS_COUNT 4
2074 string mapvote_screenshot_dirs[MAPVOTE_SCREENSHOT_DIRS_COUNT];
2075 float mapvote_screenshot_dirs_count;
2076
2077 float mapvote_count;
2078 float mapvote_count_real;
2079 string mapvote_maps[MAPVOTE_COUNT];
2080 float mapvote_maps_screenshot_dir[MAPVOTE_COUNT];
2081 string mapvote_maps_pakfile[MAPVOTE_COUNT];
2082 float mapvote_maps_suggested[MAPVOTE_COUNT];
2083 string mapvote_suggestions[MAPVOTE_COUNT];
2084 float mapvote_suggestion_ptr;
2085 float mapvote_maxlen;
2086 float mapvote_voters;
2087 float mapvote_votes[MAPVOTE_COUNT];
2088 float mapvote_run;
2089 float mapvote_detail;
2090 float mapvote_abstain;
2091 .float mapvote;
2092
2093 void MapVote_ClearAllVotes()
2094 {
2095         FOR_EACH_CLIENT(other)
2096                 other.mapvote = 0;
2097 }
2098
2099 string MapVote_Suggest(string m)
2100 {
2101         float i;
2102         if(m == "")
2103                 return "That's not how to use this command.";
2104         if(!cvar("g_maplist_votable_suggestions"))
2105                 return "Suggestions are not accepted on this server.";
2106         if(mapvote_initialized)
2107                 return "Can't suggest - voting is already in progress!";
2108         m = MapInfo_FixName(m);
2109         if(!m)
2110                 return "The map you suggested is not available on this server.";
2111         if(!cvar("g_maplist_votable_suggestions_override_mostrecent"))
2112                 if(Map_IsRecent(m))
2113                         return "This server does not allow for recent maps to be played again. Please be patient for some rounds.";
2114
2115         if(!MapInfo_CheckMap(m))
2116                 return "The map you suggested does not support the current game mode.";
2117         for(i = 0; i < mapvote_suggestion_ptr; ++i)
2118                 if(mapvote_suggestions[i] == m)
2119                         return "This map was already suggested.";
2120         if(mapvote_suggestion_ptr >= MAPVOTE_COUNT)
2121         {
2122                 i = floor(random() * mapvote_suggestion_ptr);
2123         }
2124         else
2125         {
2126                 i = mapvote_suggestion_ptr;
2127                 mapvote_suggestion_ptr += 1;
2128         }
2129         if(mapvote_suggestions[i] != "")
2130                 strunzone(mapvote_suggestions[i]);
2131         mapvote_suggestions[i] = strzone(m);
2132         if(cvar("sv_eventlog"))
2133                 GameLogEcho(strcat(":vote:suggested:", m, ":", ftos(self.playerid)));
2134         return strcat("Suggestion of ", m, " accepted.");
2135 }
2136
2137 void MapVote_AddVotable(string nextMap, float isSuggestion)
2138 {
2139         float j, i, o;
2140         string pakfile, mapfile;
2141
2142         if(nextMap == "")
2143                 return;
2144         for(j = 0; j < mapvote_count; ++j)
2145                 if(mapvote_maps[j] == nextMap)
2146                         return;
2147         if(strlen(nextMap) > mapvote_maxlen)
2148                 mapvote_maxlen = strlen(nextMap);
2149         mapvote_maps[mapvote_count] = strzone(nextMap);
2150         mapvote_maps_suggested[mapvote_count] = isSuggestion;
2151
2152         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2153         {
2154                 mapfile = strcat(mapvote_screenshot_dirs[i], "/", mapvote_maps[i]);
2155                 pakfile = whichpack(strcat(mapfile, ".tga"));
2156                 if(pakfile == "")
2157                         pakfile = whichpack(strcat(mapfile, ".jpg"));
2158                 if(pakfile == "")
2159                         pakfile = whichpack(strcat(mapfile, ".png"));
2160                 if(pakfile != "")
2161                         break;
2162         }
2163         if(i >= mapvote_screenshot_dirs_count)
2164                 i = 0; // FIXME maybe network this error case, as that means there is no mapshot on the server?
2165         for(o = strstr(pakfile, "/", 0)+1; o > 0; o = strstr(pakfile, "/", 0)+1)
2166                 pakfile = substring(pakfile, o, -1);
2167
2168         mapvote_maps_screenshot_dir[mapvote_count] = i;
2169         mapvote_maps_pakfile[mapvote_count] = strzone(pakfile);
2170
2171         mapvote_count += 1;
2172 }
2173
2174 void MapVote_Spawn();
2175 void MapVote_Init()
2176 {
2177         float i;
2178         float nmax, smax;
2179
2180         MapVote_ClearAllVotes();
2181
2182         mapvote_count = 0;
2183         mapvote_detail = !cvar("g_maplist_votable_nodetail");
2184         mapvote_abstain = cvar("g_maplist_votable_abstain");
2185
2186         if(mapvote_abstain)
2187                 nmax = min(MAPVOTE_COUNT - 1, cvar("g_maplist_votable"));
2188         else
2189                 nmax = min(MAPVOTE_COUNT, cvar("g_maplist_votable"));
2190         smax = min3(nmax, cvar("g_maplist_votable_suggestions"), mapvote_suggestion_ptr);
2191
2192         // we need this for AddVotable, as that cycles through the screenshot dirs
2193         mapvote_screenshot_dirs_count = tokenize_console(cvar_string("g_maplist_votable_screenshot_dir"));
2194         if(mapvote_screenshot_dirs_count == 0)
2195                 mapvote_screenshot_dirs_count = tokenize_console("maps levelshots");
2196         mapvote_screenshot_dirs_count = min(mapvote_screenshot_dirs_count, MAPVOTE_SCREENSHOT_DIRS_COUNT);
2197         for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2198                 mapvote_screenshot_dirs[i] = strzone(argv(i));
2199
2200         if(mapvote_suggestion_ptr)
2201                 for(i = 0; i < 100 && mapvote_count < smax; ++i)
2202                         MapVote_AddVotable(mapvote_suggestions[floor(random() * mapvote_suggestion_ptr)], TRUE);
2203
2204         for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2205                 MapVote_AddVotable(GetNextMap(), FALSE);
2206
2207         if(mapvote_count == 0)
2208         {
2209                 bprint( "Maplist contains no single playable map!  Resetting it to default map list.\n" );
2210                 cvar_set("g_maplist", MapInfo_ListAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags()));
2211                 if(cvar("g_maplist_shuffle"))
2212                         ShuffleMaplist();
2213                 localcmd("\nmenu_cmd sync\n");
2214                 for(i = 0; i < 100 && mapvote_count < nmax; ++i)
2215                         MapVote_AddVotable(GetNextMap(), FALSE);
2216         }
2217
2218         mapvote_count_real = mapvote_count;
2219         if(mapvote_abstain)
2220                 MapVote_AddVotable("don't care", 0);
2221
2222         //dprint("mapvote count is ", ftos(mapvote_count), "\n");
2223
2224         mapvote_keeptwotime = time + cvar("g_maplist_votable_keeptwotime");
2225         mapvote_timeout = time + cvar("g_maplist_votable_timeout");
2226         if(mapvote_count_real < 3 || mapvote_keeptwotime <= time)
2227                 mapvote_keeptwotime = 0;
2228         mapvote_message = "Choose a map and press its key!";
2229
2230         MapVote_Spawn();
2231 }
2232
2233 void MapVote_SendPicture(float id)
2234 {
2235         msg_entity = self;
2236         WriteByte(MSG_ONE, SVC_TEMPENTITY);
2237         WriteByte(MSG_ONE, TE_CSQC_PICTURE);
2238         WriteByte(MSG_ONE, id);
2239         WritePicture(MSG_ONE, strcat(mapvote_screenshot_dirs[mapvote_maps_screenshot_dir[id]], "/", mapvote_maps[id]), 3072);
2240 }
2241
2242 float GameCommand_MapVote(string cmd)
2243 {
2244         if(!intermission_running)
2245                 return FALSE;
2246
2247         if(cmd == "mv_getpic")
2248         {
2249                 MapVote_SendPicture(stof(argv(1)));
2250                 return TRUE;
2251         }
2252
2253         return FALSE;
2254 }
2255
2256 float MapVote_GetMapMask()
2257 {
2258         float mask, i, power;
2259         mask = 0;
2260         for(i = 0, power = 1; i < mapvote_count; ++i, power *= 2)
2261                 if(mapvote_maps[i] != "")
2262                         mask |= power;
2263         return mask;
2264 }
2265
2266 entity mapvote_ent;
2267 float MapVote_SendEntity(entity to, float sf)
2268 {
2269         float i;
2270
2271         if(sf & 1)
2272                 sf &~= 2; // if we send 1, we don't need to also send 2
2273
2274         WriteByte(MSG_ENTITY, ENT_CLIENT_MAPVOTE);
2275         WriteByte(MSG_ENTITY, sf);
2276
2277         if(sf & 1)
2278         {
2279                 // flag 1 == initialization
2280                 for(i = 0; i < mapvote_screenshot_dirs_count; ++i)
2281                         WriteString(MSG_ENTITY, mapvote_screenshot_dirs[i]);
2282                 WriteString(MSG_ENTITY, "");
2283                 WriteByte(MSG_ENTITY, mapvote_count);
2284                 WriteByte(MSG_ENTITY, mapvote_abstain);
2285                 WriteByte(MSG_ENTITY, mapvote_detail);
2286                 WriteCoord(MSG_ENTITY, mapvote_timeout);
2287                 if(mapvote_count <= 8)
2288                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2289                 else
2290                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2291                 for(i = 0; i < mapvote_count; ++i)
2292                         if(mapvote_maps[i] != "")
2293                         {
2294                                 if(mapvote_abstain && i == mapvote_count - 1)
2295                                 {
2296                                         WriteString(MSG_ENTITY, ""); // abstain needs no text
2297                                         WriteString(MSG_ENTITY, ""); // abstain needs no pack
2298                                         WriteByte(MSG_ENTITY, 0); // abstain needs no screenshot dir
2299                                 }
2300                                 else
2301                                 {
2302                                         WriteString(MSG_ENTITY, mapvote_maps[i]);
2303                                         WriteString(MSG_ENTITY, mapvote_maps_pakfile[i]);
2304                                         WriteByte(MSG_ENTITY, mapvote_maps_screenshot_dir[i]);
2305                                 }
2306                         }
2307         }
2308
2309         if(sf & 2)
2310         {
2311                 // flag 2 == update of mask
2312                 if(mapvote_count <= 8)
2313                         WriteByte(MSG_ENTITY, MapVote_GetMapMask());
2314                 else
2315                         WriteShort(MSG_ENTITY, MapVote_GetMapMask());
2316         }
2317
2318         if(sf & 4)
2319         {
2320                 if(mapvote_detail)
2321                         for(i = 0; i < mapvote_count; ++i)
2322                                 if(mapvote_maps[i] != "")
2323                                         WriteByte(MSG_ENTITY, mapvote_votes[i]);
2324
2325                 WriteByte(MSG_ENTITY, to.mapvote);
2326         }
2327
2328         return TRUE;
2329 }
2330
2331 void MapVote_Spawn()
2332 {
2333         Net_LinkEntity(mapvote_ent = spawn(), FALSE, 0, MapVote_SendEntity);
2334 }
2335
2336 void MapVote_TouchMask()
2337 {
2338         mapvote_ent.SendFlags |= 2;
2339 }
2340
2341 void MapVote_TouchVotes(entity voter)
2342 {
2343         mapvote_ent.SendFlags |= 4;
2344 }
2345
2346 float MapVote_Finished(float mappos)
2347 {
2348         string result;
2349         float i;
2350         float didntvote;
2351
2352         if(cvar("sv_eventlog"))
2353         {
2354                 result = strcat(":vote:finished:", mapvote_maps[mappos]);
2355                 result = strcat(result, ":", ftos(mapvote_votes[mappos]), "::");
2356                 didntvote = mapvote_voters;
2357                 for(i = 0; i < mapvote_count; ++i)
2358                         if(mapvote_maps[i] != "")
2359                         {
2360                                 didntvote -= mapvote_votes[i];
2361                                 if(i != mappos)
2362                                 {
2363                                         result = strcat(result, ":", mapvote_maps[i]);
2364                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2365                                 }
2366                         }
2367                 result = strcat(result, ":didn't vote:", ftos(didntvote));
2368
2369                 GameLogEcho(result);
2370                 if(mapvote_maps_suggested[mappos])
2371                         GameLogEcho(strcat(":vote:suggestion_accepted:", mapvote_maps[mappos]));
2372         }
2373
2374         FOR_EACH_REALCLIENT(other)
2375                 FixClientCvars(other);
2376
2377         Map_Goto_SetStr(mapvote_maps[mappos]);
2378         Map_Goto();
2379         alreadychangedlevel = TRUE;
2380         return TRUE;
2381 }
2382 void MapVote_CheckRules_1()
2383 {
2384         float i;
2385
2386         for(i = 0; i < mapvote_count; ++i) if(mapvote_maps[i] != "")
2387         {
2388                 //dprint("Map ", ftos(i), ": "); dprint(mapvote_maps[i], "\n");
2389                 mapvote_votes[i] = 0;
2390         }
2391
2392         mapvote_voters = 0;
2393         FOR_EACH_REALCLIENT(other)
2394         {
2395                 ++mapvote_voters;
2396                 if(other.mapvote)
2397                 {
2398                         i = other.mapvote - 1;
2399                         //dprint("Player ", other.netname, " vote = ", ftos(other.mapvote - 1), "\n");
2400                         mapvote_votes[i] = mapvote_votes[i] + 1;
2401                 }
2402         }
2403 }
2404
2405 float MapVote_CheckRules_2()
2406 {
2407         float i;
2408         float firstPlace, secondPlace;
2409         float firstPlaceVotes, secondPlaceVotes;
2410         float mapvote_voters_real;
2411         string result;
2412
2413         if(mapvote_count_real == 1)
2414                 return MapVote_Finished(0);
2415
2416         mapvote_voters_real = mapvote_voters;
2417         if(mapvote_abstain)
2418                 mapvote_voters_real -= mapvote_votes[mapvote_count - 1];
2419
2420         RandomSelection_Init();
2421         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2422                 RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2423         firstPlace = RandomSelection_chosen_float;
2424         firstPlaceVotes = RandomSelection_best_priority;
2425         //dprint("First place: ", ftos(firstPlace), "\n");
2426         //dprint("First place votes: ", ftos(firstPlaceVotes), "\n");
2427
2428         RandomSelection_Init();
2429         for(i = 0; i < mapvote_count_real; ++i) if(mapvote_maps[i] != "")
2430                 if(i != firstPlace)
2431                         RandomSelection_Add(world, i, string_null, 1, mapvote_votes[i]);
2432         secondPlace = RandomSelection_chosen_float;
2433         secondPlaceVotes = RandomSelection_best_priority;
2434         //dprint("Second place: ", ftos(secondPlace), "\n");
2435         //dprint("Second place votes: ", ftos(secondPlaceVotes), "\n");
2436
2437         if(firstPlace == -1)
2438                 error("No first place in map vote... WTF?");
2439
2440         if(secondPlace == -1 || time > mapvote_timeout || (mapvote_voters_real - firstPlaceVotes) < firstPlaceVotes)
2441                 return MapVote_Finished(firstPlace);
2442
2443         if(mapvote_keeptwotime)
2444                 if(time > mapvote_keeptwotime || (mapvote_voters_real - firstPlaceVotes - secondPlaceVotes) < secondPlaceVotes)
2445                 {
2446                         float didntvote;
2447                         MapVote_TouchMask();
2448                         mapvote_message = "Now decide between the TOP TWO!";
2449                         mapvote_keeptwotime = 0;
2450                         result = strcat(":vote:keeptwo:", mapvote_maps[firstPlace]);
2451                         result = strcat(result, ":", ftos(firstPlaceVotes));
2452                         result = strcat(result, ":", mapvote_maps[secondPlace]);
2453                         result = strcat(result, ":", ftos(secondPlaceVotes), "::");
2454                         didntvote = mapvote_voters;
2455                         for(i = 0; i < mapvote_count; ++i)
2456                                 if(mapvote_maps[i] != "")
2457                                 {
2458                                         didntvote -= mapvote_votes[i];
2459                                         if(i != firstPlace)
2460                                                 if(i != secondPlace)
2461                                                 {
2462                                                         result = strcat(result, ":", mapvote_maps[i]);
2463                                                         result = strcat(result, ":", ftos(mapvote_votes[i]));
2464                                                         if(i < mapvote_count_real)
2465                                                         {
2466                                                                 strunzone(mapvote_maps[i]);
2467                                                                 mapvote_maps[i] = "";
2468                                                                 strunzone(mapvote_maps_pakfile[i]);
2469                                                                 mapvote_maps_pakfile[i] = "";
2470                                                         }
2471                                                 }
2472                                 }
2473                         result = strcat(result, ":didn't vote:", ftos(didntvote));
2474                         if(cvar("sv_eventlog"))
2475                                 GameLogEcho(result);
2476                 }
2477
2478         return FALSE;
2479 }
2480 void MapVote_Tick()
2481 {
2482         float keeptwo;
2483         float totalvotes;
2484
2485         keeptwo = mapvote_keeptwotime;
2486         MapVote_CheckRules_1(); // count
2487         if(MapVote_CheckRules_2()) // decide
2488                 return;
2489
2490         totalvotes = 0;
2491         FOR_EACH_REALCLIENT(other)
2492         {
2493                 // hide scoreboard again
2494                 if(other.health != 2342)
2495                 {
2496                         other.health = 2342;
2497                         other.impulse = 0;
2498                         if(clienttype(other) == CLIENTTYPE_REAL)
2499                         {
2500                                 msg_entity = other;
2501                                 WriteByte(MSG_ONE, SVC_FINALE);
2502                                 WriteString(MSG_ONE, "");
2503                         }
2504                 }
2505
2506                 // clear possibly invalid votes
2507                 if(mapvote_maps[other.mapvote - 1] == "")
2508                         other.mapvote = 0;
2509                 // use impulses as new vote
2510                 if(other.impulse >= 1 && other.impulse <= mapvote_count)
2511                         if(mapvote_maps[other.impulse - 1] != "")
2512                         {
2513                                 other.mapvote = other.impulse;
2514                                 MapVote_TouchVotes(other);
2515                         }
2516                 other.impulse = 0;
2517
2518                 if(other.mapvote)
2519                         ++totalvotes;
2520         }
2521
2522         MapVote_CheckRules_1(); // just count
2523 }
2524 void MapVote_Start()
2525 {
2526         if(mapvote_run)
2527                 return;
2528
2529         MapInfo_Enumerate();
2530         if(MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2531                 mapvote_run = TRUE;
2532 }
2533 void MapVote_Think()
2534 {
2535         if(!mapvote_run)
2536                 return;
2537
2538         if(alreadychangedlevel)
2539                 return;
2540
2541         if(time < mapvote_nextthink)
2542                 return;
2543         //dprint("tick\n");
2544
2545         mapvote_nextthink = time + 0.5;
2546
2547         if(!mapvote_initialized)
2548         {
2549                 if(cvar("rescan_pending") == 1)
2550                 {
2551                         cvar_set("rescan_pending", "2");
2552                         localcmd("fs_rescan\nrescan_pending 3\n");
2553                         return;
2554                 }
2555                 else if(cvar("rescan_pending") == 2)
2556                 {
2557                         return;
2558                 }
2559                 else if(cvar("rescan_pending") == 3)
2560                 {
2561                         // now build missing mapinfo files
2562                         if(!MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1))
2563                                 return;
2564
2565                         // we're done, start the timer
2566                         cvar_set("rescan_pending", "0");
2567                 }
2568
2569                 mapvote_initialized = TRUE;
2570                 if(DoNextMapOverride())
2571                         return;
2572                 if(!cvar("g_maplist_votable") || player_count <= 0)
2573                 {
2574                         GotoNextMap();
2575                         return;
2576                 }
2577                 MapVote_Init();
2578         }
2579
2580         MapVote_Tick();
2581 };
2582
2583 string GotoMap(string m)
2584 {
2585         if(!MapInfo_CheckMap(m))
2586                 return "The map you chose is not available on this server.";
2587         cvar_set("nextmap", m);
2588         cvar_set("timelimit", "-1");
2589         if(mapvote_initialized || alreadychangedlevel)
2590         {
2591                 if(DoNextMapOverride())
2592                         return "Map switch initiated.";
2593                 else
2594                         return "Hm... no. For some reason I like THIS map more.";
2595         }
2596         else
2597                 return "Map switch will happen after scoreboard.";
2598 }
2599
2600
2601 void EndFrame()
2602 {
2603         float altime;
2604         FOR_EACH_REALCLIENT(self)
2605         {
2606                 if(self.classname == "spectator")
2607                 {
2608                         if(self.enemy.typehitsound)
2609                                 play2(self, "misc/typehit.wav");
2610                         else if(self.enemy.hitsound && self.cvar_cl_hitsound)
2611                                 play2(self, "misc/hit.wav");
2612                 }
2613                 else
2614                 {
2615                         if(self.typehitsound)
2616                                 play2(self, "misc/typehit.wav");
2617                         else if(self.hitsound && self.cvar_cl_hitsound)
2618                                 play2(self, "misc/hit.wav");
2619                 }
2620         }
2621         altime = time + frametime * (1 + cvar("g_antilag_nudge"));
2622         // add 1 frametime because after this, engine SV_Physics
2623         // increases time by a frametime and then networks the frame
2624         // add another frametime because client shows everything with
2625         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2626         // needed!
2627         FOR_EACH_CLIENT(self)
2628         {
2629                 self.hitsound = FALSE;
2630                 self.typehitsound = FALSE;
2631                 antilag_record(self, altime);
2632         }
2633 }
2634
2635
2636 /*
2637  * RedirectionThink:
2638  * returns TRUE if redirecting
2639  */
2640 float redirection_timeout;
2641 float redirection_nextthink;
2642 float RedirectionThink()
2643 {
2644         float clients_found;
2645
2646         if(redirection_target == "")
2647                 return FALSE;
2648
2649         if(!redirection_timeout)
2650         {
2651                 cvar_set("sv_public", "-2");
2652                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2653                 if(redirection_target == "self")
2654                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2655                 else
2656                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2657         }
2658
2659         if(time < redirection_nextthink)
2660                 return TRUE;
2661
2662         redirection_nextthink = time + 1;
2663
2664         clients_found = 0;
2665         FOR_EACH_REALCLIENT(self)
2666         {
2667                 print("Redirecting: sending connect command to ", self.netname, "\n");
2668                 if(redirection_target == "self")
2669                         stuffcmd(self, "\ndisconnect; reconnect\n");
2670                 else
2671                         stuffcmd(self, strcat("\ndisconnect; connect ", redirection_target, "\n"));
2672                 ++clients_found;
2673         }
2674
2675         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2676
2677         if(time > redirection_timeout || clients_found == 0)
2678                 localcmd("\nwait; wait; wait; quit\n");
2679
2680         return TRUE;
2681 }
2682
2683 void RestoreGame()
2684 {
2685         // Loaded from a save game
2686         // some things then break, so let's work around them...
2687
2688         // Progs DB (capture records)
2689         ServerProgsDB = db_load("server.db");
2690
2691         // Mapinfo
2692         MapInfo_Shutdown();
2693         MapInfo_Enumerate();
2694         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2695         WeaponStats_Init();
2696 }
2697
2698 void SV_Shutdown()
2699 {
2700         if(gameover > 1) // shutting down already?
2701                 return;
2702
2703         gameover = 2; // 2 = server shutting down
2704
2705         if(world_initialized > 0)
2706         {
2707                 world_initialized = 0;
2708                 print("Saving persistent data...\n");
2709                 Ban_SaveBans();
2710                 if(!cheatcount_total)
2711                         db_save(ServerProgsDB, "server.db");
2712                 if(cvar("developer"))
2713                         db_save(TemporaryDB, "server-temp.db");
2714                 db_close(ServerProgsDB);
2715                 db_close(TemporaryDB);
2716                 print("done!\n");
2717                 // tell the bot system the game is ending now
2718                 bot_endgame();
2719
2720                 WeaponStats_Shutdown();
2721                 MapInfo_Shutdown();
2722         }
2723         else if(world_initialized == 0)
2724         {
2725                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2726         }
2727 }