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