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