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