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