Merge branch 'master' into Mario/turrets
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / g_world.qc
1 #include "g_world.qh"
2
3 #include "../common/buffs.qh"
4
5 #if defined(CSQC)
6 #elif defined(MENUQC)
7 #elif defined(SVQC)
8     #include "../common/constants.qh"
9     #include "../common/stats.qh"
10     #include "../common/teams.qh"
11     #include "../common/util.qh"
12     #include "../common/monsters/sv_monsters.qh"
13     #include "../common/weapons/weapons.qh"
14     #include "weapons/weaponstats.qh"
15     #include "autocvars.qh"
16     #include "constants.qh"
17     #include "defs.qh"
18     #include "../common/notifications.qh"
19     #include "mutators/mutators_include.qh"
20     #include "campaign.qh"
21     #include "../common/mapinfo.qh"
22     #include "command/common.qh"
23     #include "command/vote.qh"
24     #include "command/getreplies.qh"
25     #include "command/sv_cmd.qh"
26     #include "anticheat.qh"
27     #include "cheats.qh"
28         #include "../common/turrets/turrets.qh"
29     #include "../common/playerstats.qh"
30     #include "g_hook.qh"
31     #include "scores.qh"
32     #include "mapvoting.qh"
33     #include "ipban.qh"
34     #include "race.qh"
35     #include "antilag.qh"
36     #include "secret.qh"
37 #endif
38
39 const float LATENCY_THINKRATE = 10;
40 .float latency_sum;
41 .float latency_cnt;
42 .float latency_time;
43 entity pingplreport;
44 void PingPLReport_Think()
45 {
46         float delta;
47         entity e;
48
49         delta = 3 / maxclients;
50         if(delta < sys_frametime)
51                 delta = 0;
52         self.nextthink = time + delta;
53
54         e = edict_num(self.cnt + 1);
55         if(IS_REAL_CLIENT(e))
56         {
57                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
58                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
59                 WriteByte(MSG_BROADCAST, self.cnt);
60                 WriteShort(MSG_BROADCAST, max(1, e.ping));
61                 WriteByte(MSG_BROADCAST, ceil(e.ping_packetloss * 255));
62                 WriteByte(MSG_BROADCAST, ceil(e.ping_movementloss * 255));
63
64                 // record latency times for clients throughout the match so we can report it to playerstats
65                 if(time > (e.latency_time + LATENCY_THINKRATE))
66                 {
67                         e.latency_sum += e.ping;
68                         e.latency_cnt += 1;
69                         e.latency_time = time;
70                         //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
71                 }
72         }
73         else
74         {
75                 WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
76                 WriteByte(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
77                 WriteByte(MSG_BROADCAST, self.cnt);
78                 WriteShort(MSG_BROADCAST, 0);
79                 WriteByte(MSG_BROADCAST, 0);
80                 WriteByte(MSG_BROADCAST, 0);
81         }
82         self.cnt = (self.cnt + 1) % maxclients;
83 }
84 void PingPLReport_Spawn()
85 {
86         pingplreport = spawn();
87         pingplreport.classname = "pingplreport";
88         pingplreport.think = PingPLReport_Think;
89         pingplreport.nextthink = time;
90 }
91
92 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
93 string redirection_target;
94 float world_initialized;
95
96 string GetGametype();
97 void GotoNextMap(float reinit);
98 void ShuffleMaplist();
99 float(float reinit) DoNextMapOverride;
100
101 void SetDefaultAlpha()
102 {
103         if(autocvar_g_running_guns)
104         {
105                 default_player_alpha = -1;
106                 default_weapon_alpha = +1;
107         }
108         else if(g_cloaked)
109         {
110                 default_player_alpha = autocvar_g_balance_cloaked_alpha;
111                 default_weapon_alpha = default_player_alpha;
112         }
113         else
114         {
115                 default_player_alpha = autocvar_g_player_alpha;
116                 if(default_player_alpha == 0)
117                         default_player_alpha = 1;
118                 default_weapon_alpha = default_player_alpha;
119         }
120 }
121
122 void GotoFirstMap()
123 {
124         float n;
125         if(autocvar__sv_init)
126         {
127                 // cvar_set("_sv_init", "0");
128                 // we do NOT set this to 0 any more, so someone "accidentally" changing
129                 // to this "init" map on a dedicated server will cause no permanent
130                 // harm
131                 if(autocvar_g_maplist_shuffle)
132                         ShuffleMaplist();
133                 n = tokenizebyseparator(autocvar_g_maplist, " ");
134                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
135
136                 MapInfo_Enumerate();
137                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
138
139                 if(!DoNextMapOverride(1))
140                         GotoNextMap(1);
141
142                 return;
143         }
144
145         if(time < 5)
146         {
147                 self.nextthink = time;
148         }
149         else
150         {
151                 self.nextthink = time + 1;
152                 print("Waiting for _sv_init being set to 1 by initialization scripts...\n");
153         }
154 }
155
156 void cvar_changes_init()
157 {
158         float h;
159         string k, v, d;
160         float n, i, adding, pureadding;
161
162         if(cvar_changes)
163                 strunzone(cvar_changes);
164         cvar_changes = string_null;
165         if(cvar_purechanges)
166                 strunzone(cvar_purechanges);
167         cvar_purechanges = string_null;
168         cvar_purechanges_count = 0;
169
170         h = buf_create();
171         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
172         n = buf_getsize(h);
173
174         adding = true;
175         pureadding = true;
176
177         for(i = 0; i < n; ++i)
178         {
179                 k = bufstr_get(h, i);
180
181 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
182 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
183 #define BADCVAR(p) if(k == p) continue
184
185                 // general excludes and namespaces for server admin used cvars
186                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
187
188                 // internal
189                 BADPREFIX("csqc_");
190                 BADPREFIX("cvar_check_");
191                 BADCVAR("gamecfg");
192                 BADCVAR("g_configversion");
193                 BADCVAR("g_maplist_index");
194                 BADCVAR("halflifebsp");
195                 BADPREFIX("sv_world");
196
197                 // client
198                 BADPREFIX("chase_");
199                 BADPREFIX("cl_");
200                 BADPREFIX("con_");
201                 BADPREFIX("scoreboard_");
202                 BADPREFIX("g_campaign");
203                 BADPREFIX("g_waypointsprite_");
204                 BADPREFIX("gl_");
205                 BADPREFIX("joy");
206                 BADPREFIX("hud_");
207                 BADPREFIX("m_");
208                 BADPREFIX("menu_");
209                 BADPREFIX("net_slist_");
210                 BADPREFIX("r_");
211                 BADPREFIX("sbar_");
212                 BADPREFIX("scr_");
213                 BADPREFIX("snd_");
214                 BADPREFIX("show");
215                 BADPREFIX("sensitivity");
216                 BADPREFIX("userbind");
217                 BADPREFIX("v_");
218                 BADPREFIX("vid_");
219                 BADPREFIX("crosshair");
220                 BADCVAR("mod_q3bsp_lightmapmergepower");
221                 BADCVAR("mod_q3bsp_nolightmaps");
222                 BADCVAR("fov");
223                 BADCVAR("mastervolume");
224                 BADCVAR("volume");
225                 BADCVAR("bgmvolume");
226
227                 // private
228                 BADCVAR("developer");
229                 BADCVAR("log_dest_udp");
230                 BADCVAR("net_address");
231                 BADCVAR("net_address_ipv6");
232                 BADCVAR("port");
233                 BADCVAR("savedgamecfg");
234                 BADCVAR("serverconfig");
235                 BADCVAR("sv_autoscreenshot");
236                 BADCVAR("sv_heartbeatperiod");
237                 BADCVAR("sv_vote_master_password");
238                 BADCVAR("sys_colortranslation");
239                 BADCVAR("sys_specialcharactertranslation");
240                 BADCVAR("timeformat");
241                 BADCVAR("timestamps");
242                 BADPREFIX("developer_");
243                 BADPREFIX("g_ban_");
244                 BADPREFIX("g_banned_list");
245                 BADPREFIX("g_chat_flood_");
246                 BADPREFIX("g_ghost_items");
247                 BADPREFIX("g_playerstats_");
248                 BADPREFIX("g_respawn_ghosts");
249                 BADPREFIX("g_voice_flood_");
250                 BADPREFIX("log_file");
251                 BADPREFIX("rcon_");
252                 BADPREFIX("sv_allowdownloads");
253                 BADPREFIX("sv_autodemo");
254                 BADPREFIX("sv_curl_");
255                 BADPREFIX("sv_eventlog");
256                 BADPREFIX("sv_logscores_");
257                 BADPREFIX("sv_master");
258                 BADPREFIX("sv_weaponstats_");
259                 BADPREFIX("sv_waypointsprite_");
260                 BADCVAR("rescan_pending");
261
262                 // these can contain player IDs, so better hide
263                 BADPREFIX("g_forced_team_");
264
265                 // mapinfo
266                 BADCVAR("fraglimit");
267                 BADCVAR("g_assault");
268                 BADCVAR("g_ca");
269                 BADCVAR("g_ca_teams");
270                 BADCVAR("g_ctf");
271                 BADCVAR("g_cts");
272                 BADCVAR("g_dm");
273                 BADCVAR("g_domination");
274                 BADCVAR("g_domination_default_teams");
275                 BADCVAR("g_freezetag");
276                 BADCVAR("g_freezetag_teams");
277                 BADCVAR("g_keepaway");
278                 BADCVAR("g_keyhunt");
279                 BADCVAR("g_keyhunt_teams");
280                 BADCVAR("g_lms");
281                 BADCVAR("g_nexball");
282                 BADCVAR("g_onslaught");
283                 BADCVAR("g_race");
284                 BADCVAR("g_race_qualifying_timelimit");
285                 BADCVAR("g_tdm");
286                 BADCVAR("g_tdm_teams");
287                 BADCVAR("leadlimit");
288                 BADCVAR("nextmap");
289                 BADCVAR("teamplay");
290                 BADCVAR("timelimit");
291
292                 // long
293                 BADCVAR("hostname");
294                 BADCVAR("g_maplist");
295                 BADCVAR("g_maplist_mostrecent");
296                 BADCVAR("sv_motd");
297
298                 v = cvar_string(k);
299                 d = cvar_defstring(k);
300                 if(v == d)
301                         continue;
302
303                 if(adding)
304                 {
305                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
306                         if(strlen(cvar_changes) > 16384)
307                         {
308                                 cvar_changes = "// too many settings have been changed to show them here\n";
309                                 adding = 0;
310                         }
311                 }
312
313                 // now check if the changes are actually gameplay relevant
314
315                 // does nothing visible
316                 BADCVAR("captureleadlimit_override");
317                 BADCVAR("g_balance_kill_delay");
318                 BADCVAR("g_ca_point_limit");
319                 BADCVAR("g_ca_point_leadlimit");
320                 BADCVAR("g_ctf_captimerecord_always");
321                 BADCVAR("g_ctf_flag_glowtrails");
322                 BADCVAR("g_ctf_flag_pickup_verbosename");
323                 BADCVAR("g_domination_point_leadlimit");
324                 BADCVAR("g_forced_respawn");
325                 BADCVAR("g_freezetag_point_limit");
326                 BADCVAR("g_freezetag_point_leadlimit");
327                 BADCVAR("g_keyhunt_point_leadlimit");
328                 BADPREFIX("g_mod_");
329                 BADCVAR("g_invasion_point_limit");
330                 BADCVAR("g_nexball_goalleadlimit");
331                 BADCVAR("g_tdm_point_limit");
332                 BADCVAR("g_tdm_point_leadlimit");
333                 BADCVAR("leadlimit_and_fraglimit");
334                 BADCVAR("leadlimit_override");
335                 BADCVAR("pausable");
336                 BADCVAR("sv_allow_fullbright");
337                 BADCVAR("sv_checkforpacketsduringsleep");
338                 BADCVAR("sv_fraginfo");
339                 BADCVAR("sv_timeout");
340                 BADPREFIX("sv_timeout_");
341                 BADPREFIX("crypto_");
342                 BADPREFIX("g_chat_");
343                 BADPREFIX("g_ctf_captimerecord_");
344                 BADPREFIX("g_maplist_votable_");
345                 BADPREFIX("net_");
346                 BADPREFIX("prvm_");
347                 BADPREFIX("skill_");
348                 BADPREFIX("sv_cullentities_");
349                 BADPREFIX("sv_fraginfo_");
350                 BADPREFIX("sv_maxidle_");
351                 BADPREFIX("sv_vote_");
352                 BADPREFIX("timelimit_");
353                 BADCVAR("gameversion");
354                 BADPREFIX("gameversion_");
355                 BADCVAR("sv_namechangetimer");
356
357                 // allowed changes to server admins (please sync this to server.cfg)
358                 // vi commands:
359                 //   :/"impure"/,$d
360                 //   :g!,^\/\/[^ /],d
361                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
362                 //   :%!sort
363                 // yes, this does contain some redundant stuff, don't really care
364                 BADCVAR("bot_config_file");
365                 BADCVAR("bot_number");
366                 BADCVAR("bot_prefix");
367                 BADCVAR("bot_suffix");
368                 BADCVAR("capturelimit_override");
369                 BADCVAR("fraglimit_override");
370                 BADCVAR("gametype");
371                 BADCVAR("g_antilag");
372                 BADCVAR("g_balance_teams");
373                 BADCVAR("g_balance_teams_prevent_imbalance");
374                 BADCVAR("g_balance_teams_scorefactor");
375                 BADCVAR("g_ban_sync_trusted_servers");
376                 BADCVAR("g_ban_sync_uri");
377                 BADCVAR("g_ca_teams_override");
378                 BADCVAR("g_ctf_ignore_frags");
379                 BADCVAR("g_domination_point_limit");
380                 BADCVAR("g_freezetag_teams_override");
381                 BADCVAR("g_friendlyfire");
382                 BADCVAR("g_fullbrightitems");
383                 BADCVAR("g_fullbrightplayers");
384                 BADCVAR("g_keyhunt_point_limit");
385                 BADCVAR("g_keyhunt_teams_override");
386                 BADCVAR("g_lms_lives_override");
387                 BADCVAR("g_maplist");
388                 BADCVAR("g_maplist_check_waypoints");
389                 BADCVAR("g_maplist_mostrecent_count");
390                 BADCVAR("g_maplist_shuffle");
391                 BADCVAR("g_maplist_votable");
392                 BADCVAR("g_maplist_votable_abstain");
393                 BADCVAR("g_maplist_votable_nodetail");
394                 BADCVAR("g_maplist_votable_suggestions");
395                 BADCVAR("g_maxplayers");
396                 BADCVAR("g_mirrordamage");
397                 BADCVAR("g_nexball_goallimit");
398                 BADCVAR("g_powerups");
399                 BADCVAR("g_start_delay");
400                 BADCVAR("g_warmup");
401                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
402                 BADCVAR("hostname");
403                 BADCVAR("log_file");
404                 BADCVAR("maxplayers");
405                 BADCVAR("minplayers");
406                 BADCVAR("net_address");
407                 BADCVAR("port");
408                 BADCVAR("rcon_password");
409                 BADCVAR("rcon_restricted_commands");
410                 BADCVAR("rcon_restricted_password");
411                 BADCVAR("skill");
412                 BADCVAR("sv_adminnick");
413                 BADCVAR("sv_autoscreenshot");
414                 BADCVAR("sv_autotaunt");
415                 BADCVAR("sv_curl_defaulturl");
416                 BADCVAR("sv_defaultcharacter");
417                 BADCVAR("sv_defaultplayercolors");
418                 BADCVAR("sv_defaultplayermodel");
419                 BADCVAR("sv_defaultplayerskin");
420                 BADCVAR("sv_maxidle");
421                 BADCVAR("sv_maxrate");
422                 BADCVAR("sv_motd");
423                 BADCVAR("sv_public");
424                 BADCVAR("sv_ready_restart");
425                 BADCVAR("sv_status_privacy");
426                 BADCVAR("sv_taunt");
427                 BADCVAR("sv_vote_call");
428                 BADCVAR("sv_vote_commands");
429                 BADCVAR("sv_vote_majority_factor");
430                 BADCVAR("sv_vote_master");
431                 BADCVAR("sv_vote_master_commands");
432                 BADCVAR("sv_vote_master_password");
433                 BADCVAR("sv_vote_simple_majority_factor");
434                 BADCVAR("teamplay_mode");
435                 BADCVAR("timelimit_override");
436                 BADCVAR("g_spawnshieldtime");
437                 BADPREFIX("g_warmup_");
438                 BADPREFIX("sv_ready_restart_");
439
440                 // mutators that announce themselves properly to the server browser
441                 BADCVAR("g_instagib");
442                 BADCVAR("g_new_toys");
443                 BADCVAR("g_nix");
444                 BADCVAR("g_grappling_hook");
445                 BADCVAR("g_jetpack");
446
447 #undef BADPREFIX
448 #undef BADCVAR
449
450                 if(pureadding)
451                 {
452                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
453                         if(strlen(cvar_purechanges) > 16384)
454                         {
455                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
456                                 pureadding = 0;
457                         }
458                 }
459                 ++cvar_purechanges_count;
460                 // WARNING: this variable is used for the server list
461                 // NEVER dare to skip this code!
462                 // Hacks to intentionally appearing as "pure server" even though you DO have
463                 // modified settings may be punished by removal from the server list.
464                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
465                 // though.
466         }
467         buf_del(h);
468         if(cvar_changes == "")
469                 cvar_changes = "// this server runs at default server settings\n";
470         else
471                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
472         cvar_changes = strzone(cvar_changes);
473         if(cvar_purechanges == "")
474                 cvar_purechanges = "// this server runs at default gameplay settings\n";
475         else
476                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
477         cvar_purechanges = strzone(cvar_purechanges);
478 }
479
480 void detect_maptype()
481 {
482 #if 0
483         vector o, v;
484         float i;
485
486         for (;;)
487         {
488                 o = world.mins;
489                 o.x += random() * (world.maxs.x - world.mins.x);
490                 o.y += random() * (world.maxs.y - world.mins.y);
491                 o.z += random() * (world.maxs.z - world.mins.z);
492
493                 tracebox(o, PL_MIN, PL_MAX, o - '0 0 32768', MOVE_WORLDONLY, world);
494                 if(trace_fraction == 1)
495                         continue;
496
497                 v = trace_endpos;
498
499                 for(i = 0; i < 64; i += 4)
500                 {
501                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, world);
502         if(trace_fraction == 1)
503                 continue;
504                         print(ftos(i), " -> ", vtos(trace_endpos), "\n");
505                 }
506
507                 break;
508         }
509 #endif
510 }
511
512 entity randomseed;
513 float RandomSeed_Send(entity to, float sf)
514 {
515         WriteByte(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
516         WriteShort(MSG_ENTITY, self.cnt);
517         return true;
518 }
519 void RandomSeed_Think()
520 {
521         self.cnt = bound(0, floor(random() * 65536), 65535);
522         self.nextthink = time + 5;
523
524         self.SendFlags |= 1;
525 }
526 void RandomSeed_Spawn()
527 {
528         randomseed = spawn();
529         randomseed.think = RandomSeed_Think;
530         Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
531
532         entity oldself;
533         oldself = self;
534         self = randomseed;
535         self.think(); // sets random seed and nextthink
536         self = oldself;
537 }
538
539 void spawnfunc___init_dedicated_server(void)
540 {
541         // handler for _init/_init map (only for dedicated server initialization)
542
543         world_initialized = -1; // don't complain
544         cvar = cvar_normal;
545         cvar_string = cvar_string_normal;
546         cvar_set = cvar_set_normal;
547
548         remove = remove_unsafely;
549
550         entity e;
551         e = spawn();
552         e.think = GotoFirstMap;
553         e.nextthink = time; // this is usually 1 at this point
554
555         e = spawn();
556         e.classname = "info_player_deathmatch"; // safeguard against player joining
557
558         self.classname = "worldspawn"; // safeguard against various stuff ;)
559
560         // needs to be done so early because of the constants they create
561         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
562         CALL_ACCUMULATED_FUNCTION(RegisterTurrets);
563         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
564         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
565         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
566         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
567         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
568
569         MapInfo_Enumerate();
570         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
571 }
572
573 void Map_MarkAsRecent(string m);
574 float world_already_spawned;
575 void Nagger_Init();
576 void ClientInit_Spawn();
577 void WeaponStats_Init();
578 void WeaponStats_Shutdown();
579 void spawnfunc_worldspawn (void)
580 {
581         float fd, l, i, j, n;
582         string s;
583
584         cvar = cvar_normal;
585         cvar_string = cvar_string_normal;
586         cvar_set = cvar_set_normal;
587
588         if(world_already_spawned)
589                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
590         world_already_spawned = true;
591
592         remove = remove_safely; // during spawning, watch what you remove!
593
594         cvar_changes_init(); // do this very early now so it REALLY matches the server config
595
596         compressShortVector_init();
597
598         entity head;
599         head = nextent(world);
600         maxclients = 0;
601         while(head)
602         {
603                 ++maxclients;
604                 head = nextent(head);
605         }
606
607         server_is_dedicated = (stof(cvar_defstring("is_dedicated")) ? true : false);
608
609         // needs to be done so early because of the constants they create
610         CALL_ACCUMULATED_FUNCTION(RegisterWeapons);
611         CALL_ACCUMULATED_FUNCTION(RegisterTurrets);
612         CALL_ACCUMULATED_FUNCTION(RegisterMonsters);
613         CALL_ACCUMULATED_FUNCTION(RegisterGametypes);
614         CALL_ACCUMULATED_FUNCTION(RegisterNotifications);
615         CALL_ACCUMULATED_FUNCTION(RegisterDeathtypes);
616         CALL_ACCUMULATED_FUNCTION(RegisterBuffs);
617
618         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
619
620         TemporaryDB = db_create();
621
622         // 0 normal
623         lightstyle(0, "m");
624
625         // 1 FLICKER (first variety)
626         lightstyle(1, "mmnmmommommnonmmonqnmmo");
627
628         // 2 SLOW STRONG PULSE
629         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
630
631         // 3 CANDLE (first variety)
632         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
633
634         // 4 FAST STROBE
635         lightstyle(4, "mamamamamama");
636
637         // 5 GENTLE PULSE 1
638         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
639
640         // 6 FLICKER (second variety)
641         lightstyle(6, "nmonqnmomnmomomno");
642
643         // 7 CANDLE (second variety)
644         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
645
646         // 8 CANDLE (third variety)
647         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
648
649         // 9 SLOW STROBE (fourth variety)
650         lightstyle(9, "aaaaaaaazzzzzzzz");
651
652         // 10 FLUORESCENT FLICKER
653         lightstyle(10, "mmamammmmammamamaaamammma");
654
655         // 11 SLOW PULSE NOT FADE TO BLACK
656         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
657
658         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
659
660         // 63 testing
661         lightstyle(63, "a");
662
663         if(autocvar_g_campaign)
664                 CampaignPreInit();
665
666         Map_MarkAsRecent(mapname);
667
668         PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
669
670         precache_model ("null"); // we need this one before InitGameplayMode
671         InitGameplayMode();
672         readlevelcvars();
673         GrappleHookInit();
674
675         player_count = 0;
676         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
677         if(bot_waypoints_for_items == 1)
678                 if(self.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
679                         bot_waypoints_for_items = 0;
680
681         precache();
682
683         WaypointSprite_Init();
684
685         GameLogInit(); // prepare everything
686         // NOTE for matchid:
687         // changing the logic generating it is okay. But:
688         // it HAS to stay <= 64 chars
689         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
690         if(autocvar_sv_eventlog)
691         {
692                 s = sprintf("%d.%s.%06d", ftos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
693                 matchid = strzone(s);
694
695                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
696                 s = ":gameinfo:mutators:LIST";
697
698                 ret_string = s;
699                 MUTATOR_CALLHOOK(BuildMutatorsString);
700                 s = ret_string;
701
702                 // simple, probably not good in the mutator system
703                 if(autocvar_g_grappling_hook)
704                         s = strcat(s, ":grappling_hook");
705
706                 // initialiation stuff, not good in the mutator system
707                 if(!autocvar_g_use_ammunition)
708                         s = strcat(s, ":no_use_ammunition");
709
710                 // initialiation stuff, not good in the mutator system
711                 if(autocvar_g_pickup_items == 0)
712                         s = strcat(s, ":no_pickup_items");
713                 if(autocvar_g_pickup_items > 0)
714                         s = strcat(s, ":pickup_items");
715
716                 // initialiation stuff, not good in the mutator system
717                 if(autocvar_g_weaponarena != "0")
718                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
719
720                 // TODO to mutator system
721                 if(autocvar_g_norecoil)
722                         s = strcat(s, ":norecoil");
723
724                 // TODO to mutator system
725                 if(autocvar_g_powerups == 0)
726                         s = strcat(s, ":no_powerups");
727                 if(autocvar_g_powerups > 0)
728                         s = strcat(s, ":powerups");
729
730                 GameLogEcho(s);
731                 GameLogEcho(":gameinfo:end");
732         }
733         else
734                 matchid = strzone(ftos(random()));
735
736         cvar_set("nextmap", "");
737
738         SetDefaultAlpha();
739
740         if(autocvar_g_campaign)
741                 CampaignPostInit();
742
743         Ban_LoadBans();
744
745         MapInfo_Enumerate();
746         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
747
748         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
749         {
750                 fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
751                 if(fd != -1)
752                 {
753                         while((s = fgets(fd)))
754                         {
755                                 l = tokenize_console(s);
756                                 if(l < 2)
757                                         continue;
758                                 if(argv(0) == "cd")
759                                 {
760                                         print("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
761                                         print("  cdtrack ", argv(2), "\n");
762                                 }
763                                 else if(argv(0) == "fog")
764                                 {
765                                         print("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
766                                         print("  \"fog\" \"", s, "\"\n");
767                                 }
768                                 else if(argv(0) == "set")
769                                 {
770                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
771                                         print("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
772                                 }
773                                 else if(argv(0) != "//")
774                                 {
775                                         print("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
776                                         print("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
777                                 }
778                         }
779                         fclose(fd);
780                 }
781         }
782
783         WeaponStats_Init();
784
785         WepSet_AddStat();
786         addstat(STAT_SWITCHWEAPON, AS_INT, switchweapon);
787         addstat(STAT_SWITCHINGWEAPON, AS_INT, switchingweapon);
788         addstat(STAT_GAMESTARTTIME, AS_FLOAT, stat_game_starttime);
789         addstat(STAT_ROUNDSTARTTIME, AS_FLOAT, stat_round_starttime);
790         addstat(STAT_ALLOW_OLDVORTEXBEAM, AS_INT, stat_allow_oldvortexbeam);
791         Nagger_Init();
792
793         addstat(STAT_STRENGTH_FINISHED, AS_FLOAT, strength_finished);
794         addstat(STAT_INVINCIBLE_FINISHED, AS_FLOAT, invincible_finished);
795         addstat(STAT_SUPERWEAPONS_FINISHED, AS_FLOAT, superweapons_finished);
796         addstat(STAT_PRESSED_KEYS, AS_FLOAT, pressedkeys);
797         addstat(STAT_FUEL, AS_INT, ammo_fuel);
798         addstat(STAT_PLASMA, AS_INT, ammo_plasma);
799         addstat(STAT_SHOTORG, AS_INT, stat_shotorg);
800         addstat(STAT_LEADLIMIT, AS_FLOAT, stat_leadlimit);
801         addstat(STAT_WEAPON_CLIPLOAD, AS_INT, clip_load);
802         addstat(STAT_WEAPON_CLIPSIZE, AS_INT, clip_size);
803         addstat(STAT_LAST_PICKUP, AS_FLOAT, last_pickup);
804         addstat(STAT_HIT_TIME, AS_FLOAT, hit_time);
805         addstat(STAT_DAMAGE_DEALT_TOTAL, AS_INT, damage_dealt_total);
806         addstat(STAT_TYPEHIT_TIME, AS_FLOAT, typehit_time);
807         addstat(STAT_LAYED_MINES, AS_INT, minelayer_mines);
808
809         addstat(STAT_VORTEX_CHARGE, AS_FLOAT, vortex_charge);
810         addstat(STAT_VORTEX_CHARGEPOOL, AS_FLOAT, vortex_chargepool_ammo);
811
812         addstat(STAT_HAGAR_LOAD, AS_INT, hagar_load);
813
814         addstat(STAT_ARC_HEAT, AS_FLOAT, arc_heat_percent);
815
816         // freeze attacks
817         addstat(STAT_FROZEN, AS_INT, frozen);
818         addstat(STAT_REVIVE_PROGRESS, AS_FLOAT, revive_progress);
819
820         // g_movementspeed hack
821         addstat(STAT_MOVEVARS_AIRSPEEDLIMIT_NONQW, AS_FLOAT, stat_sv_airspeedlimit_nonqw);
822         addstat(STAT_MOVEVARS_MAXSPEED, AS_FLOAT, stat_sv_maxspeed);
823         addstat(STAT_MOVEVARS_AIRACCEL_QW, AS_FLOAT, stat_sv_airaccel_qw);
824         addstat(STAT_MOVEVARS_AIRSTRAFEACCEL_QW, AS_FLOAT, stat_sv_airstrafeaccel_qw);
825
826         // secrets
827         addstat(STAT_SECRETS_TOTAL, AS_FLOAT, stat_secrets_total);
828         addstat(STAT_SECRETS_FOUND, AS_FLOAT, stat_secrets_found);
829
830         // monsters
831         addstat(STAT_MONSTERS_TOTAL, AS_FLOAT, stat_monsters_total);
832         addstat(STAT_MONSTERS_KILLED, AS_FLOAT, stat_monsters_killed);
833
834         // misc
835         addstat(STAT_RESPAWN_TIME, AS_FLOAT, stat_respawn_time);
836
837         next_pingtime = time + 5;
838
839         detect_maptype();
840
841         // set up information replies for clients and server to use
842         maplist_reply = strzone(getmaplist());
843         lsmaps_reply = strzone(getlsmaps());
844         monsterlist_reply = strzone(getmonsterlist());
845         for(i = 0; i < 10; ++i)
846         {
847                 s = getrecords(i);
848                 if (s)
849                         records_reply[i] = strzone(s);
850         }
851         ladder_reply = strzone(getladder());
852         rankings_reply = strzone(getrankings());
853
854         // begin other init
855         ClientInit_Spawn();
856         RandomSeed_Spawn();
857         PingPLReport_Spawn();
858
859         CheatInit();
860
861         localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
862
863         // fill sv_curl_serverpackages from .serverpackage files
864         if(autocvar_sv_curl_serverpackages_auto)
865         {
866                 s = "";
867                 n = tokenize_console(cvar_string("sv_curl_serverpackages"));
868                 for(i = 0; i < n; ++i)
869                         if(substring(argv(i), -18, -1) != "-serverpackage.txt")
870                         if(substring(argv(i), -14, -1) != ".serverpackage") // OLD legacy
871                                 s = strcat(s, " ", argv(i));
872                 fd = search_begin("*-serverpackage.txt", true, false);
873                 if(fd >= 0)
874                 {
875                         j = search_getsize(fd);
876                         for(i = 0; i < j; ++i)
877                                 s = strcat(s, " ", search_getfilename(fd, i));
878                         search_end(fd);
879                 }
880                 fd = search_begin("*.serverpackage", true, false);
881                 if(fd >= 0)
882                 {
883                         j = search_getsize(fd);
884                         for(i = 0; i < j; ++i)
885                                 s = strcat(s, " ", search_getfilename(fd, i));
886                         search_end(fd);
887                 }
888                 cvar_set("sv_curl_serverpackages", substring(s, 1, -1));
889         }
890
891         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
892         modname = "Xonotic";
893         // physics/balance/config changes that count as mod
894         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
895                 modname = cvar_string("g_mod_physics");
896         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
897                 modname = cvar_string("g_mod_balance");
898         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
899                 modname = cvar_string("g_mod_config");
900         // extra mutators that deserve to count as mod
901         MUTATOR_CALLHOOK(SetModname);
902
903         // save it for later
904         modname = strzone(modname);
905
906         WinningConditionHelper(); // set worldstatus
907
908         world_initialized = 1;
909 }
910
911 void spawnfunc_light (void)
912 {
913         //makestatic (self); // Who the f___ did that?
914         remove(self);
915 }
916
917 string GetGametype()
918 {
919         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
920 }
921
922 string GetMapname()
923 {
924         return mapname;
925 }
926
927 float Map_Count, Map_Current;
928 string Map_Current_Name;
929
930 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
931 float GetMaplistPosition()
932 {
933         float pos, idx;
934         string map;
935
936         map = GetMapname();
937         idx = autocvar_g_maplist_index;
938
939         if(idx >= 0)
940                 if(idx < Map_Count)
941                         if(map == argv(idx))
942                                 return idx;
943
944         for(pos = 0; pos < Map_Count; ++pos)
945                 if(map == argv(pos))
946                         return pos;
947
948         // resume normal maplist rotation if current map is not in g_maplist
949         return idx;
950 }
951
952 float MapHasRightSize(string map)
953 {
954         float fh;
955         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
956         if(autocvar_g_maplist_check_waypoints)
957         {
958                 dprint("checkwp "); dprint(map);
959                 if(!fexists(strcat("maps/", map, ".waypoints")))
960                 {
961                         dprint(": no waypoints\n");
962                         return false;
963                 }
964                 dprint(": has waypoints\n");
965         }
966
967         // open map size restriction file
968         dprint("opensize "); dprint(map);
969         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
970         if(fh >= 0)
971         {
972                 float mapmin, mapmax;
973                 dprint(": ok, ");
974                 mapmin = stof(fgets(fh));
975                 mapmax = stof(fgets(fh));
976                 fclose(fh);
977                 if(player_count < mapmin)
978                 {
979                         dprint("not enough\n");
980                         return false;
981                 }
982                 if(player_count > mapmax)
983                 {
984                         dprint("too many\n");
985                         return false;
986                 }
987                 dprint("right size\n");
988                 return true;
989         }
990         dprint(": not found\n");
991         return true;
992 }
993
994 string Map_Filename(float position)
995 {
996         return strcat("maps/", argv(position), ".bsp");
997 }
998
999 string strwords(string s, float w)
1000 {
1001         float endpos;
1002         for(endpos = 0; w && endpos >= 0; --w)
1003                 endpos = strstrofs(s, " ", endpos + 1);
1004         if(endpos < 0)
1005                 return s;
1006         else
1007                 return substring(s, 0, endpos);
1008 }
1009
1010 float strhasword(string s, string w)
1011 {
1012         return strstrofs(strcat(" ", s, " "), strcat(" ", w, " "), 0) >= 0;
1013 }
1014
1015 void Map_MarkAsRecent(string m)
1016 {
1017         cvar_set("g_maplist_mostrecent", strwords(strcat(m, " ", autocvar_g_maplist_mostrecent), max(0, autocvar_g_maplist_mostrecent_count)));
1018 }
1019
1020 float Map_IsRecent(string m)
1021 {
1022         return strhasword(autocvar_g_maplist_mostrecent, m);
1023 }
1024
1025 float Map_Check(float position, float pass)
1026 {
1027         string filename;
1028         string map_next;
1029         map_next = argv(position);
1030         if(pass <= 1)
1031         {
1032                 if(Map_IsRecent(map_next))
1033                         return 0;
1034         }
1035         filename = Map_Filename(position);
1036         if(MapInfo_CheckMap(map_next))
1037         {
1038                 if(pass == 2)
1039                         return 1;
1040                 if(MapHasRightSize(map_next))
1041                         return 1;
1042                 return 0;
1043         }
1044         else
1045                 dprint( "Couldn't select '", filename, "'..\n" );
1046
1047         return 0;
1048 }
1049
1050 void Map_Goto_SetStr(string nextmapname)
1051 {
1052         if(getmapname_stored != "")
1053                 strunzone(getmapname_stored);
1054         if(nextmapname == "")
1055                 getmapname_stored = "";
1056         else
1057                 getmapname_stored = strzone(nextmapname);
1058 }
1059
1060 void Map_Goto_SetFloat(float position)
1061 {
1062         cvar_set("g_maplist_index", ftos(position));
1063         Map_Goto_SetStr(argv(position));
1064 }
1065
1066 void Map_Goto(float reinit)
1067 {
1068         MapInfo_LoadMap(getmapname_stored, reinit);
1069 }
1070
1071 // return codes of map selectors:
1072 //   -1 = temporary failure (that is, try some method that is guaranteed to succeed)
1073 //   -2 = permanent failure
1074 float() MaplistMethod_Iterate = // usual method
1075 {
1076         float pass, i;
1077
1078         dprint("Trying MaplistMethod_Iterate\n");
1079
1080         for(pass = 1; pass <= 2; ++pass)
1081         {
1082                 for(i = 1; i < Map_Count; ++i)
1083                 {
1084                         float mapindex;
1085                         mapindex = (i + Map_Current) % Map_Count;
1086                         if(Map_Check(mapindex, pass))
1087                                 return mapindex;
1088                 }
1089         }
1090         return -1;
1091 }
1092
1093 float() MaplistMethod_Repeat = // fallback method
1094 {
1095         dprint("Trying MaplistMethod_Repeat\n");
1096
1097         if(Map_Check(Map_Current, 2))
1098                 return Map_Current;
1099         return -2;
1100 }
1101
1102 float() MaplistMethod_Random = // random map selection
1103 {
1104         float i, imax;
1105
1106         dprint("Trying MaplistMethod_Random\n");
1107
1108         imax = 42;
1109
1110         for(i = 0; i <= imax; ++i)
1111         {
1112                 float mapindex;
1113                 mapindex = (Map_Current + floor(random() * (Map_Count - 1) + 1)) % Map_Count; // any OTHER map
1114                 if(Map_Check(mapindex, 1))
1115                         return mapindex;
1116         }
1117         return -1;
1118 }
1119
1120 float(float exponent) MaplistMethod_Shuffle = // more clever shuffling
1121 // the exponent sets a bias on the map selection:
1122 // the higher the exponent, the less likely "shortly repeated" same maps are
1123 {
1124         float i, j, imax, insertpos;
1125
1126         dprint("Trying MaplistMethod_Shuffle\n");
1127
1128         imax = 42;
1129
1130         for(i = 0; i <= imax; ++i)
1131         {
1132                 string newlist;
1133
1134                 // now reinsert this at another position
1135                 insertpos = pow(random(), 1 / exponent);       // ]0, 1]
1136                 insertpos = insertpos * (Map_Count - 1);       // ]0, Map_Count - 1]
1137                 insertpos = ceil(insertpos) + 1;               // {2, 3, 4, ..., Map_Count}
1138                 dprint("SHUFFLE: insert pos = ", ftos(insertpos), "\n");
1139
1140                 // insert the current map there
1141                 newlist = "";
1142                 for(j = 1; j < insertpos; ++j)                 // i == 1: no loop, will be inserted as first; however, i == 1 has been excluded above
1143                         newlist = strcat(newlist, " ", argv(j));
1144                 newlist = strcat(newlist, " ", argv(0));       // now insert the just selected map
1145                 for(j = insertpos; j < Map_Count; ++j)         // i == Map_Count: no loop, has just been inserted as last
1146                         newlist = strcat(newlist, " ", argv(j));
1147                 newlist = substring(newlist, 1, strlen(newlist) - 1);
1148                 cvar_set("g_maplist", newlist);
1149                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1150
1151                 // NOTE: the selected map has just been inserted at (insertpos-1)th position
1152                 Map_Current = insertpos - 1; // this is not really valid, but this way the fallback has a chance of working
1153                 if(Map_Check(Map_Current, 1))
1154                         return Map_Current;
1155         }
1156         return -1;
1157 }
1158
1159 void Maplist_Init()
1160 {
1161         Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1162         float i;
1163         for (i = 0; i < Map_Count; ++i)
1164                 if (Map_Check(i, 2))
1165                         break;
1166         if (i == Map_Count)
1167         {
1168                 bprint( "Maplist contains no usable maps!  Resetting it to default map list.\n" );
1169                 cvar_set("g_maplist", MapInfo_ListAllAllowedMaps(MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags() | MAPINFO_FLAG_NOAUTOMAPLIST));
1170                 if(autocvar_g_maplist_shuffle)
1171                         ShuffleMaplist();
1172                 localcmd("\nmenu_cmd sync\n");
1173                 Map_Count = tokenizebyseparator(autocvar_g_maplist, " ");
1174         }
1175         if(Map_Count == 0)
1176                 error("empty maplist, cannot select a new map");
1177         Map_Current = bound(0, GetMaplistPosition(), Map_Count - 1);
1178
1179         if(Map_Current_Name)
1180                 strunzone(Map_Current_Name);
1181         Map_Current_Name = strzone(argv(Map_Current)); // will be automatically freed on exit thanks to DP
1182         // this may or may not be correct, but who cares, in the worst case a map
1183         // isn't chosen in the first pass that should have been
1184 }
1185
1186 string GetNextMap()
1187 {
1188         float nextMap;
1189
1190         Maplist_Init();
1191         nextMap = -1;
1192
1193         if(nextMap == -1)
1194                 if(autocvar_g_maplist_shuffle > 0)
1195                         nextMap = MaplistMethod_Shuffle(autocvar_g_maplist_shuffle + 1);
1196
1197         if(nextMap == -1)
1198                 if(autocvar_g_maplist_selectrandom)
1199                         nextMap = MaplistMethod_Random();
1200
1201         if(nextMap == -1)
1202                 nextMap = MaplistMethod_Iterate();
1203
1204         if(nextMap == -1)
1205                 nextMap = MaplistMethod_Repeat();
1206
1207         if(nextMap >= 0)
1208         {
1209                 Map_Goto_SetFloat(nextMap);
1210                 return getmapname_stored;
1211         }
1212
1213         return "";
1214 }
1215
1216 float DoNextMapOverride(float reinit)
1217 {
1218         if(autocvar_g_campaign)
1219         {
1220                 CampaignPostIntermission();
1221                 alreadychangedlevel = true;
1222                 return true;
1223         }
1224         if(autocvar_quit_when_empty)
1225         {
1226                 if(player_count <= currentbots)
1227                 {
1228                         localcmd("quit\n");
1229                         alreadychangedlevel = true;
1230                         return true;
1231                 }
1232         }
1233         if(autocvar_quit_and_redirect != "")
1234         {
1235                 redirection_target = strzone(autocvar_quit_and_redirect);
1236                 alreadychangedlevel = true;
1237                 return true;
1238         }
1239         if (!reinit && autocvar_samelevel) // if samelevel is set, stay on same level
1240         {
1241                 localcmd("restart\n");
1242                 alreadychangedlevel = true;
1243                 return true;
1244         }
1245         if(autocvar_nextmap != "")
1246         {
1247                 string m;
1248                 m = GameTypeVote_MapInfo_FixName(autocvar_nextmap);
1249                 cvar_set("nextmap",m);
1250
1251                 if(!m || gametypevote)
1252                         return false;
1253                 if(autocvar_sv_vote_gametype)
1254                 {
1255                         Map_Goto_SetStr(m);
1256                         return false;
1257                 }
1258
1259                 if(MapInfo_CheckMap(m))
1260                 {
1261                         Map_Goto_SetStr(m);
1262                         Map_Goto(reinit);
1263                         alreadychangedlevel = true;
1264                         return true;
1265                 }
1266         }
1267         if(!reinit && autocvar_lastlevel)
1268         {
1269                 cvar_settemp_restore();
1270                 localcmd("set lastlevel 0\ntogglemenu 1\n");
1271                 alreadychangedlevel = true;
1272                 return true;
1273         }
1274         return false;
1275 }
1276
1277 void GotoNextMap(float reinit)
1278 {
1279         //string nextmap;
1280         //float n, nummaps;
1281         //string s;
1282         if (alreadychangedlevel)
1283                 return;
1284         alreadychangedlevel = true;
1285
1286         string nextMap;
1287
1288         nextMap = GetNextMap();
1289         if(nextMap == "")
1290                 error("Everything is broken - cannot find a next map. Please report this to the developers.");
1291         Map_Goto(reinit);
1292 }
1293
1294
1295 /*
1296 ============
1297 IntermissionThink
1298
1299 When the player presses attack or jump, change to the next level
1300 ============
1301 */
1302 .float autoscreenshot;
1303 void IntermissionThink()
1304 {
1305         FixIntermissionClient(self);
1306
1307         float server_screenshot = (autocvar_sv_autoscreenshot && self.cvar_cl_autoscreenshot);
1308         float client_screenshot = (self.cvar_cl_autoscreenshot == 2);
1309
1310         if( (server_screenshot || client_screenshot)
1311                 && ((self.autoscreenshot > 0) && (time > self.autoscreenshot)) )
1312         {
1313                 self.autoscreenshot = -1;
1314                 if(IS_REAL_CLIENT(self)) { stuffcmd(self, sprintf("\nscreenshot screenshots/autoscreenshot/%s-%s.jpg; echo \"^5A screenshot has been taken at request of the server.\"\n", GetMapname(), strftime(false, "%s"))); }
1315                 return;
1316         }
1317
1318         if (time < intermission_exittime)
1319                 return;
1320
1321         if(!mapvote_initialized)
1322                 if (time < intermission_exittime + 10 && !(self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE))
1323                         return;
1324
1325         MapVote_Start();
1326 }
1327
1328 /*
1329 ============
1330 FindIntermission
1331
1332 Returns the entity to view from
1333 ============
1334 */
1335 /*
1336 entity FindIntermission()
1337 {
1338         local   entity spot;
1339         local   float cyc;
1340
1341 // look for info_intermission first
1342         spot = find (world, classname, "info_intermission");
1343         if (spot)
1344         {       // pick a random one
1345                 cyc = random() * 4;
1346                 while (cyc > 1)
1347                 {
1348                         spot = find (spot, classname, "info_intermission");
1349                         if (!spot)
1350                                 spot = find (spot, classname, "info_intermission");
1351                         cyc = cyc - 1;
1352                 }
1353                 return spot;
1354         }
1355
1356 // then look for the start position
1357         spot = find (world, classname, "info_player_start");
1358         if (spot)
1359                 return spot;
1360
1361 // testinfo_player_start is only found in regioned levels
1362         spot = find (world, classname, "testplayerstart");
1363         if (spot)
1364                 return spot;
1365
1366 // then look for the start position
1367         spot = find (world, classname, "info_player_deathmatch");
1368         if (spot)
1369                 return spot;
1370
1371         //objerror ("FindIntermission: no spot");
1372         return world;
1373 }
1374 */
1375
1376 /*
1377 ===============================================================================
1378
1379 RULES
1380
1381 ===============================================================================
1382 */
1383
1384 void DumpStats(float final)
1385 {
1386         float file;
1387         string s;
1388         float to_console;
1389         float to_eventlog;
1390         float to_file;
1391         float i;
1392
1393         to_console = autocvar_sv_logscores_console;
1394         to_eventlog = autocvar_sv_eventlog;
1395         to_file = autocvar_sv_logscores_file;
1396
1397         if(!final)
1398         {
1399                 to_console = true; // always print printstats replies
1400                 to_eventlog = false; // but never print them to the event log
1401         }
1402
1403         if(to_eventlog)
1404                 if(autocvar_sv_eventlog_console)
1405                         to_console = false; // otherwise we get the output twice
1406
1407         if(final)
1408                 s = ":scores:";
1409         else
1410                 s = ":status:";
1411         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1412
1413         if(to_console)
1414                 print(s, "\n");
1415         if(to_eventlog)
1416                 GameLogEcho(s);
1417
1418         file = -1;
1419         if(to_file)
1420         {
1421                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1422                 if(file == -1)
1423                         to_file = false;
1424                 else
1425                         fputs(file, strcat(s, "\n"));
1426         }
1427
1428         s = strcat(":labels:player:", GetPlayerScoreString(world, 0));
1429         if(to_console)
1430                 print(s, "\n");
1431         if(to_eventlog)
1432                 GameLogEcho(s);
1433         if(to_file)
1434                 fputs(file, strcat(s, "\n"));
1435
1436         FOR_EACH_CLIENT(other)
1437         {
1438                 if ((IS_REAL_CLIENT(other)) || (IS_BOT_CLIENT(other) && autocvar_sv_logscores_bots))
1439                 {
1440                         s = strcat(":player:see-labels:", GetPlayerScoreString(other, 0), ":");
1441                         s = strcat(s, ftos(rint(time - other.jointime)), ":");
1442                         if(IS_PLAYER(other) || other.caplayer == 1 || g_lms)
1443                                 s = strcat(s, ftos(other.team), ":");
1444                         else
1445                                 s = strcat(s, "spectator:");
1446
1447                         if(to_console)
1448                                 print(s, other.netname, "\n");
1449                         if(to_eventlog)
1450                                 GameLogEcho(strcat(s, ftos(other.playerid), ":", other.netname));
1451                         if(to_file)
1452                                 fputs(file, strcat(s, other.netname, "\n"));
1453                 }
1454         }
1455
1456         if(teamplay)
1457         {
1458                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1459                 if(to_console)
1460                         print(s, "\n");
1461                 if(to_eventlog)
1462                         GameLogEcho(s);
1463                 if(to_file)
1464                         fputs(file, strcat(s, "\n"));
1465
1466                 for(i = 1; i < 16; ++i)
1467                 {
1468                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1469                         s = strcat(s, ":", ftos(i));
1470                         if(to_console)
1471                                 print(s, "\n");
1472                         if(to_eventlog)
1473                                 GameLogEcho(s);
1474                         if(to_file)
1475                                 fputs(file, strcat(s, "\n"));
1476                 }
1477         }
1478
1479         if(to_console)
1480                 print(":end\n");
1481         if(to_eventlog)
1482                 GameLogEcho(":end");
1483         if(to_file)
1484         {
1485                 fputs(file, ":end\n");
1486                 fclose(file);
1487         }
1488 }
1489
1490 void FixIntermissionClient(entity e)
1491 {
1492         string s;
1493         if(!e.autoscreenshot) // initial call
1494         {
1495                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1496                 e.health = -2342;
1497                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1498                 e.solid = SOLID_NOT;
1499                 e.movetype = MOVETYPE_NONE;
1500                 e.takedamage = DAMAGE_NO;
1501                 if(e.weaponentity)
1502                 {
1503                         e.weaponentity.effects = EF_NODRAW;
1504                         if (e.weaponentity.weaponentity)
1505                                 e.weaponentity.weaponentity.effects = EF_NODRAW;
1506                 }
1507                 if(IS_REAL_CLIENT(e))
1508                 {
1509                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1510                         s = autocvar_sv_intermission_cdtrack;
1511                         if(s != "")
1512                                 stuffcmd(e, strcat("\ncd loop ", s, "\n"));
1513                         msg_entity = e;
1514                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1515                 }
1516         }
1517 }
1518
1519 /*
1520 go to the next level for deathmatch
1521 only called if a time or frag limit has expired
1522 */
1523 void NextLevel()
1524 {
1525         gameover = true;
1526
1527         intermission_running = 1;
1528
1529 // enforce a wait time before allowing changelevel
1530         if(player_count > 0)
1531                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1532         else
1533                 intermission_exittime = -1;
1534
1535         /*
1536         WriteByte (MSG_ALL, SVC_CDTRACK);
1537         WriteByte (MSG_ALL, 3);
1538         WriteByte (MSG_ALL, 3);
1539         // done in FixIntermission
1540         */
1541
1542         //pos = FindIntermission ();
1543
1544         VoteReset();
1545
1546         DumpStats(true);
1547
1548         // send statistics
1549         PlayerStats_GameReport(true);
1550         WeaponStats_Shutdown();
1551
1552         Kill_Notification(NOTIF_ALL, world, MSG_CENTER, 0); // kill all centerprints now
1553
1554         if(autocvar_sv_eventlog)
1555                 GameLogEcho(":gameover");
1556
1557         GameLogClose();
1558
1559         FOR_EACH_PLAYER(other) {
1560                 FixIntermissionClient(other);
1561                 if(other.winning)
1562                         bprint(other.netname, " ^7wins.\n");
1563         }
1564
1565         if(autocvar_g_campaign)
1566                 CampaignPreIntermission();
1567
1568         MUTATOR_CALLHOOK(MatchEnd);
1569
1570         localcmd("\nsv_hook_gameend\n");
1571 }
1572
1573 /*
1574 ============
1575 CheckRules_Player
1576
1577 Exit deathmatch games upon conditions
1578 ============
1579 */
1580 void CheckRules_Player()
1581 {
1582         if (gameover)   // someone else quit the game already
1583                 return;
1584
1585         if(self.deadflag == DEAD_NO)
1586                 self.play_time += frametime;
1587
1588         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1589         //   (div0: and that in CheckRules_World please)
1590 }
1591
1592
1593 float InitiateSuddenDeath()
1594 {
1595         // Check first whether normal overtimes could be added before initiating suddendeath mode
1596         // - for this timelimit_overtime needs to be >0 of course
1597         // - also check the winning condition calculated in the previous frame and only add normal overtime
1598         //   again, if at the point at which timelimit would be extended again, still no winner was found
1599         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1600         {
1601                 return 1; // need to call InitiateOvertime later
1602         }
1603         else
1604         {
1605                 if(!checkrules_suddendeathend)
1606                 {
1607                         if(autocvar_g_campaign)
1608                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1609                         else
1610                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1611                         if(g_race && !g_race_qualifying)
1612                                 race_StartCompleting();
1613                 }
1614                 return 0;
1615         }
1616 }
1617
1618 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1619 {
1620         ++checkrules_overtimesadded;
1621         //add one more overtime by simply extending the timelimit
1622         float tl;
1623         tl = autocvar_timelimit;
1624         tl += autocvar_timelimit_overtime;
1625         cvar_set("timelimit", ftos(tl));
1626
1627         Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1628 }
1629
1630 float GetWinningCode(float fraglimitreached, float equality)
1631 {
1632         if(autocvar_g_campaign == 1)
1633                 if(fraglimitreached)
1634                         return WINNING_YES;
1635                 else
1636                         return WINNING_NO;
1637
1638         else
1639                 if(equality)
1640                         if(fraglimitreached)
1641                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1642                         else
1643                                 return WINNING_NEVER;
1644                 else
1645                         if(fraglimitreached)
1646                                 return WINNING_YES;
1647                         else
1648                                 return WINNING_NO;
1649 }
1650
1651 // set the .winning flag for exactly those players with a given field value
1652 void SetWinners(.float field, float value)
1653 {
1654         entity head;
1655         FOR_EACH_PLAYER(head)
1656                 head.winning = (head.field == value);
1657 }
1658
1659 // set the .winning flag for those players with a given field value
1660 void AddWinners(.float field, float value)
1661 {
1662         entity head;
1663         FOR_EACH_PLAYER(head)
1664                 if(head.field == value)
1665                         head.winning = 1;
1666 }
1667
1668 // clear the .winning flags
1669 void ClearWinners(void)
1670 {
1671         entity head;
1672         FOR_EACH_PLAYER(head)
1673                 head.winning = 0;
1674 }
1675
1676 // Onslaught winning condition:
1677 // game terminates if only one team has a working generator (or none)
1678 float WinningCondition_Onslaught()
1679 {
1680         entity head;
1681         float t1, t2, t3, t4;
1682
1683         WinningConditionHelper(); // set worldstatus
1684
1685         if(warmup_stage)
1686                 return WINNING_NO;
1687
1688         // first check if the game has ended
1689         t1 = t2 = t3 = t4 = 0;
1690         head = find(world, classname, "onslaught_generator");
1691         while (head)
1692         {
1693                 if (head.health > 0)
1694                 {
1695                         if (head.team == NUM_TEAM_1) t1 = 1;
1696                         if (head.team == NUM_TEAM_2) t2 = 1;
1697                         if (head.team == NUM_TEAM_3) t3 = 1;
1698                         if (head.team == NUM_TEAM_4) t4 = 1;
1699                 }
1700                 head = find(head, classname, "onslaught_generator");
1701         }
1702         if (t1 + t2 + t3 + t4 < 2)
1703         {
1704                 // game over, only one team remains (or none)
1705                 ClearWinners();
1706                 if (t1) SetWinners(team, NUM_TEAM_1);
1707                 if (t2) SetWinners(team, NUM_TEAM_2);
1708                 if (t3) SetWinners(team, NUM_TEAM_3);
1709                 if (t4) SetWinners(team, NUM_TEAM_4);
1710                 dprint("Have a winner, ending game.\n");
1711                 return WINNING_YES;
1712         }
1713
1714         // Two or more teams remain
1715         return WINNING_NO;
1716 }
1717
1718 // Assault winning condition: If the attackers triggered a round end (by fulfilling all objectives)
1719 // they win. Otherwise the defending team wins once the timelimit passes.
1720 void assault_new_round();
1721 float WinningCondition_Assault()
1722 {
1723         float status;
1724
1725         WinningConditionHelper(); // set worldstatus
1726
1727         status = WINNING_NO;
1728         // as the timelimit has not yet passed just assume the defending team will win
1729         if(assault_attacker_team == NUM_TEAM_1)
1730         {
1731                 SetWinners(team, NUM_TEAM_2);
1732         }
1733         else
1734         {
1735                 SetWinners(team, NUM_TEAM_1);
1736         }
1737
1738         entity ent;
1739         ent = find(world, classname, "target_assault_roundend");
1740         if(ent)
1741         {
1742                 if(ent.winning) // round end has been triggered by attacking team
1743                 {
1744                         bprint("ASSAULT: round completed...\n");
1745                         SetWinners(team, assault_attacker_team);
1746
1747                         TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 666 - TeamScore_AddToTeam(assault_attacker_team, ST_ASSAULT_OBJECTIVES, 0));
1748
1749                         if(ent.cnt == 1 || autocvar_g_campaign) // this was the second round
1750                         {
1751                                 status = WINNING_YES;
1752                         }
1753                         else
1754                         {
1755                                 entity oldself;
1756                                 oldself = self;
1757                                 self = ent;
1758                                 assault_new_round();
1759                                 self = oldself;
1760                         }
1761                 }
1762         }
1763
1764         return status;
1765 }
1766
1767 // LMS winning condition: game terminates if and only if there's at most one
1768 // one player who's living lives. Top two scores being equal cancels the time
1769 // limit.
1770 float WinningCondition_LMS()
1771 {
1772         entity head, head2;
1773         float have_player;
1774         float have_players;
1775         float l;
1776
1777         have_player = false;
1778         have_players = false;
1779         l = LMS_NewPlayerLives();
1780
1781         head = find(world, classname, "player");
1782         if(head)
1783                 have_player = true;
1784         head2 = find(head, classname, "player");
1785         if(head2)
1786                 have_players = true;
1787
1788         if(have_player)
1789         {
1790                 // we have at least one player
1791                 if(have_players)
1792                 {
1793                         // two or more active players - continue with the game
1794                 }
1795                 else
1796                 {
1797                         // exactly one player?
1798
1799                         ClearWinners();
1800                         SetWinners(winning, 0); // NOTE: exactly one player is still "player", so this works out
1801
1802                         if(l)
1803                         {
1804                                 // game still running (that is, nobody got removed from the game by a frag yet)? then continue
1805                                 return WINNING_NO;
1806                         }
1807                         else
1808                         {
1809                                 // a winner!
1810                                 // and assign him his first place
1811                                 PlayerScore_Add(head, SP_LMS_RANK, 1);
1812                                 return WINNING_YES;
1813                         }
1814                 }
1815         }
1816         else
1817         {
1818                 // nobody is playing at all...
1819                 if(l)
1820                 {
1821                         // wait for players...
1822                 }
1823                 else
1824                 {
1825                         // SNAFU (maybe a draw game?)
1826                         ClearWinners();
1827                         dprint("No players, ending game.\n");
1828                         return WINNING_YES;
1829                 }
1830         }
1831
1832         // When we get here, we have at least two players who are actually LIVING,
1833         // now check if the top two players have equal score.
1834         WinningConditionHelper();
1835
1836         ClearWinners();
1837         if(WinningConditionHelper_winner)
1838                 WinningConditionHelper_winner.winning = true;
1839         if(WinningConditionHelper_topscore == WinningConditionHelper_secondscore)
1840                 return WINNING_NEVER;
1841
1842         // Top two have different scores? Way to go for our beloved TIMELIMIT!
1843         return WINNING_NO;
1844 }
1845
1846 void ShuffleMaplist()
1847 {
1848         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1849 }
1850
1851 float leaderfrags;
1852 float WinningCondition_Scores(float limit, float leadlimit)
1853 {
1854         float limitreached;
1855
1856         // TODO make everything use THIS winning condition (except LMS)
1857         WinningConditionHelper();
1858
1859         if(teamplay)
1860         {
1861                 team1_score = TeamScore_GetCompareValue(NUM_TEAM_1);
1862                 team2_score = TeamScore_GetCompareValue(NUM_TEAM_2);
1863                 team3_score = TeamScore_GetCompareValue(NUM_TEAM_3);
1864                 team4_score = TeamScore_GetCompareValue(NUM_TEAM_4);
1865         }
1866
1867         ClearWinners();
1868         if(WinningConditionHelper_winner)
1869                 WinningConditionHelper_winner.winning = 1;
1870         if(WinningConditionHelper_winnerteam >= 0)
1871                 SetWinners(team, WinningConditionHelper_winnerteam);
1872
1873         if(WinningConditionHelper_lowerisbetter)
1874         {
1875                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1876                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1877                 limit = -limit;
1878         }
1879
1880         if(WinningConditionHelper_zeroisworst)
1881                 leadlimit = 0; // not supported in this mode
1882
1883         if(g_dm || g_tdm || g_ca || g_freezetag || (g_race && !g_race_qualifying) || g_nexball)
1884         // these modes always score in increments of 1, thus this makes sense
1885         {
1886                 if(leaderfrags != WinningConditionHelper_topscore)
1887                 {
1888                         leaderfrags = WinningConditionHelper_topscore;
1889
1890                         if (limit)
1891                         if (leaderfrags == limit - 1)
1892                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1893                         else if (leaderfrags == limit - 2)
1894                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1895                         else if (leaderfrags == limit - 3)
1896                                 Send_Notification(NOTIF_ALL, world, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1897                 }
1898         }
1899
1900         limitreached = false;
1901         if(limit)
1902                 if(WinningConditionHelper_topscore >= limit)
1903                         limitreached = true;
1904         if(leadlimit)
1905         {
1906                 float leadlimitreached;
1907                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1908                 if(autocvar_leadlimit_and_fraglimit)
1909                         limitreached = (limitreached && leadlimitreached);
1910                 else
1911                         limitreached = (limitreached || leadlimitreached);
1912         }
1913
1914         if(limit)
1915                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1916
1917         return GetWinningCode(
1918                 WinningConditionHelper_topscore && limitreached,
1919                 WinningConditionHelper_equality
1920         );
1921 }
1922
1923 float WinningCondition_Race(float fraglimit)
1924 {
1925         float wc;
1926         entity p;
1927         float n, c;
1928
1929         n = 0;
1930         c = 0;
1931         FOR_EACH_PLAYER(p)
1932         {
1933                 ++n;
1934                 if(p.race_completed)
1935                         ++c;
1936         }
1937         if(n && (n == c))
1938                 return WINNING_YES;
1939         wc = WinningCondition_Scores(fraglimit, 0);
1940
1941         // ALWAYS initiate overtime, unless EVERYONE has finished the race!
1942         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1943         // do NOT support equality when the laps are all raced!
1944                 return WINNING_STARTSUDDENDEATHOVERTIME;
1945         else
1946                 return WINNING_NEVER;
1947 }
1948
1949 float WinningCondition_QualifyingThenRace(float limit)
1950 {
1951         float wc;
1952         wc = WinningCondition_Scores(limit, 0);
1953
1954         // NEVER initiate overtime
1955         if(wc == WINNING_YES || wc == WINNING_STARTSUDDENDEATHOVERTIME)
1956         {
1957                 return WINNING_YES;
1958         }
1959
1960         return wc;
1961 }
1962
1963 float WinningCondition_RanOutOfSpawns()
1964 {
1965         entity head;
1966
1967         if(have_team_spawns <= 0)
1968                 return WINNING_NO;
1969
1970         if(autocvar_g_spawn_useallspawns <= 0)
1971                 return WINNING_NO;
1972
1973         if(!some_spawn_has_been_used)
1974                 return WINNING_NO;
1975
1976         team1_score = team2_score = team3_score = team4_score = 0;
1977
1978         FOR_EACH_PLAYER(head) if(head.deadflag == DEAD_NO)
1979         {
1980                 if(head.team == NUM_TEAM_1)
1981                         team1_score = 1;
1982                 else if(head.team == NUM_TEAM_2)
1983                         team2_score = 1;
1984                 else if(head.team == NUM_TEAM_3)
1985                         team3_score = 1;
1986                 else if(head.team == NUM_TEAM_4)
1987                         team4_score = 1;
1988         }
1989
1990         for(head = world; (head = find(head, classname, "info_player_deathmatch")) != world; )
1991         {
1992                 if(head.team == NUM_TEAM_1)
1993                         team1_score = 1;
1994                 else if(head.team == NUM_TEAM_2)
1995                         team2_score = 1;
1996                 else if(head.team == NUM_TEAM_3)
1997                         team3_score = 1;
1998                 else if(head.team == NUM_TEAM_4)
1999                         team4_score = 1;
2000         }
2001
2002         ClearWinners();
2003         if(team1_score + team2_score + team3_score + team4_score == 0)
2004         {
2005                 checkrules_equality = true;
2006                 return WINNING_YES;
2007         }
2008         else if(team1_score + team2_score + team3_score + team4_score == 1)
2009         {
2010                 float t, i;
2011                 if(team1_score)
2012                         t = NUM_TEAM_1;
2013                 else if(team2_score)
2014                         t = NUM_TEAM_2;
2015                 else if(team3_score)
2016                         t = NUM_TEAM_3;
2017                 else // if(team4_score)
2018                         t = NUM_TEAM_4;
2019                 CheckAllowedTeams(world);
2020                 for(i = 0; i < MAX_TEAMSCORE; ++i)
2021                 {
2022                         if(t != NUM_TEAM_1) if(c1 >= 0) TeamScore_AddToTeam(NUM_TEAM_1, i, -1000);
2023                         if(t != NUM_TEAM_2) if(c2 >= 0) TeamScore_AddToTeam(NUM_TEAM_2, i, -1000);
2024                         if(t != NUM_TEAM_3) if(c3 >= 0) TeamScore_AddToTeam(NUM_TEAM_3, i, -1000);
2025                         if(t != NUM_TEAM_4) if(c4 >= 0) TeamScore_AddToTeam(NUM_TEAM_4, i, -1000);
2026                 }
2027
2028                 AddWinners(team, t);
2029                 return WINNING_YES;
2030         }
2031         else
2032                 return WINNING_NO;
2033 }
2034
2035 /*
2036 ============
2037 CheckRules_World
2038
2039 Exit deathmatch games upon conditions
2040 ============
2041 */
2042 void ReadyRestart();
2043 void CheckRules_World()
2044 {
2045         float timelimit;
2046         float fraglimit;
2047         float leadlimit;
2048
2049         VoteThink();
2050         MapVote_Think();
2051
2052         SetDefaultAlpha();
2053
2054         if (gameover)   // someone else quit the game already
2055         {
2056                 if(player_count == 0) // Nobody there? Then let's go to the next map
2057                         MapVote_Start();
2058                         // this will actually check the player count in the next frame
2059                         // again, but this shouldn't hurt
2060                 return;
2061         }
2062
2063         timelimit = autocvar_timelimit * 60;
2064         fraglimit = autocvar_fraglimit;
2065         leadlimit = autocvar_leadlimit;
2066
2067         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
2068         {
2069                 if(timelimit > 0)
2070                         timelimit = 0; // timelimit is not made for warmup
2071                 if(fraglimit > 0)
2072                         fraglimit = 0; // no fraglimit for now
2073                 leadlimit = 0; // no leadlimit for now
2074         }
2075
2076         if(timelimit > 0)
2077         {
2078                 timelimit += game_starttime;
2079         }
2080         else if (timelimit < 0)
2081         {
2082                 // endmatch
2083                 NextLevel();
2084                 return;
2085         }
2086
2087         if(g_onslaught)
2088                 timelimit = 0; // ONS has its own overtime rule
2089
2090         float wantovertime;
2091         wantovertime = 0;
2092
2093         if(timelimit > game_starttime)
2094                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
2095         else
2096                 game_completion_ratio = 0;
2097
2098         if(checkrules_suddendeathend)
2099         {
2100                 if(!checkrules_suddendeathwarning)
2101                 {
2102                         checkrules_suddendeathwarning = true;
2103                         if(g_race && !g_race_qualifying)
2104                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_RACE_FINISHLAP);
2105                         else
2106                                 Send_Notification(NOTIF_ALL, world, MSG_CENTER, CENTER_OVERTIME_FRAG);
2107                 }
2108         }
2109         else
2110         {
2111                 if (timelimit && time >= timelimit)
2112                 {
2113                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
2114                         {
2115                                 float totalplayers;
2116                                 float playerswithlaps;
2117                                 float readyplayers;
2118                                 entity head;
2119                                 totalplayers = playerswithlaps = readyplayers = 0;
2120                                 FOR_EACH_PLAYER(head)
2121                                 {
2122                                         ++totalplayers;
2123                                         if(PlayerScore_Add(head, SP_RACE_FASTEST, 0))
2124                                                 ++playerswithlaps;
2125                                         if(head.ready)
2126                                                 ++readyplayers;
2127                                 }
2128
2129                                 // at least 2 of the players have completed a lap: start the RACE
2130                                 // otherwise, the players should end the qualifying on their own
2131                                 if(readyplayers || playerswithlaps >= 2)
2132                                 {
2133                                         checkrules_suddendeathend = 0;
2134                                         ReadyRestart(); // go to race
2135                                         return;
2136                                 }
2137                                 else
2138                                         wantovertime |= InitiateSuddenDeath();
2139                         }
2140                         else
2141                                 wantovertime |= InitiateSuddenDeath();
2142                 }
2143         }
2144
2145         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
2146         {
2147                 NextLevel();
2148                 return;
2149         }
2150
2151         float checkrules_status;
2152         checkrules_status = WinningCondition_RanOutOfSpawns();
2153         if(checkrules_status == WINNING_YES)
2154         {
2155                 bprint("Hey! Someone ran out of spawns!\n");
2156         }
2157         else if(g_race && !g_race_qualifying && timelimit >= 0)
2158         {
2159                 checkrules_status = WinningCondition_Race(fraglimit);
2160                 //print("WC_RACE yields ", ftos(checkrules_status), "\n");
2161         }
2162         else if(g_race && g_race_qualifying == 2 && timelimit >= 0)
2163         {
2164                 checkrules_status = WinningCondition_QualifyingThenRace(fraglimit);
2165                 //print("WC_QUALIFYING_THEN_RACE yields ", ftos(checkrules_status), "\n");
2166         }
2167         else if(g_assault)
2168         {
2169                 checkrules_status = WinningCondition_Assault(); // TODO remove this?
2170         }
2171         else if(g_lms)
2172         {
2173                 checkrules_status = WinningCondition_LMS();
2174         }
2175         else if (g_onslaught)
2176         {
2177                 checkrules_status = WinningCondition_Onslaught(); // TODO remove this?
2178         }
2179         else
2180         {
2181                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
2182                 //print("WC_SCORES yields ", ftos(checkrules_status), "\n");
2183         }
2184
2185         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
2186         {
2187                 checkrules_status = WINNING_NEVER;
2188                 checkrules_overtimesadded = -1;
2189                 wantovertime |= InitiateSuddenDeath();
2190         }
2191
2192         if(checkrules_status == WINNING_NEVER)
2193                 // equality cases! Nobody wins if the overtime ends in a draw.
2194                 ClearWinners();
2195
2196         if(wantovertime)
2197         {
2198                 if(checkrules_status == WINNING_NEVER)
2199                         InitiateOvertime();
2200                 else
2201                         checkrules_status = WINNING_YES;
2202         }
2203
2204         if(checkrules_suddendeathend)
2205                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
2206                         checkrules_status = WINNING_YES;
2207
2208         if(checkrules_status == WINNING_YES)
2209         {
2210                 //print("WINNING\n");
2211                 NextLevel();
2212         }
2213 }
2214
2215 string GotoMap(string m)
2216 {
2217         m = GameTypeVote_MapInfo_FixName(m);
2218         if (!m)
2219                 return "The map you suggested is not available on this server.";
2220         if (!autocvar_sv_vote_gametype)
2221         if(!MapInfo_CheckMap(m))
2222                 return "The map you suggested does not support the current game mode.";
2223         cvar_set("nextmap", m);
2224         cvar_set("timelimit", "-1");
2225         if(mapvote_initialized || alreadychangedlevel)
2226         {
2227                 if(DoNextMapOverride(0))
2228                         return "Map switch initiated.";
2229                 else
2230                         return "Hm... no. For some reason I like THIS map more.";
2231         }
2232         else
2233                 return "Map switch will happen after scoreboard.";
2234 }
2235
2236
2237 void EndFrame()
2238 {
2239         anticheat_endframe();
2240
2241         float altime;
2242         FOR_EACH_REALCLIENT(self)
2243         {
2244                 entity e = IS_SPEC(self) ? self.enemy : self;
2245                 if(e.typehitsound)
2246                         self.typehit_time = time;
2247                 else if(e.damage_dealt)
2248                 {
2249                         self.hit_time = time;
2250                         self.damage_dealt_total += ceil(e.damage_dealt);
2251                 }
2252         }
2253         altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2254         // add 1 frametime because after this, engine SV_Physics
2255         // increases time by a frametime and then networks the frame
2256         // add another frametime because client shows everything with
2257         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2258         // needed!
2259         FOR_EACH_CLIENT(self)
2260         {
2261                 self.typehitsound = false;
2262                 self.damage_dealt = 0;
2263                 antilag_record(self, altime);
2264         }
2265         FOR_EACH_MONSTER(self)
2266                 antilag_record(self, altime);
2267 }
2268
2269
2270 /*
2271  * RedirectionThink:
2272  * returns true if redirecting
2273  */
2274 float redirection_timeout;
2275 float redirection_nextthink;
2276 float RedirectionThink()
2277 {
2278         float clients_found;
2279
2280         if(redirection_target == "")
2281                 return false;
2282
2283         if(!redirection_timeout)
2284         {
2285                 cvar_set("sv_public", "-2");
2286                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2287                 if(redirection_target == "self")
2288                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2289                 else
2290                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2291         }
2292
2293         if(time < redirection_nextthink)
2294                 return true;
2295
2296         redirection_nextthink = time + 1;
2297
2298         clients_found = 0;
2299         FOR_EACH_REALCLIENT(self)
2300         {
2301                 // TODO add timer
2302                 print("Redirecting: sending connect command to ", self.netname, "\n");
2303                 if(redirection_target == "self")
2304                         stuffcmd(self, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2305                 else
2306                         stuffcmd(self, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2307                 ++clients_found;
2308         }
2309
2310         print("Redirecting: ", ftos(clients_found), " clients left.\n");
2311
2312         if(time > redirection_timeout || clients_found == 0)
2313                 localcmd("\nwait; wait; wait; quit\n");
2314
2315         return true;
2316 }
2317
2318 void TargetMusic_RestoreGame();
2319 void RestoreGame()
2320 {
2321         // Loaded from a save game
2322         // some things then break, so let's work around them...
2323
2324         // Progs DB (capture records)
2325         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2326
2327         // Mapinfo
2328         MapInfo_Shutdown();
2329         MapInfo_Enumerate();
2330         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2331         WeaponStats_Init();
2332
2333         TargetMusic_RestoreGame();
2334 }
2335
2336 void Shutdown()
2337 {
2338         gameover = 2;
2339
2340         if(world_initialized > 0)
2341         {
2342                 world_initialized = 0;
2343                 print("Saving persistent data...\n");
2344                 Ban_SaveBans();
2345
2346                 // playerstats with unfinished match
2347                 PlayerStats_GameReport(false);
2348
2349                 if(!cheatcount_total)
2350                 {
2351                         if(autocvar_sv_db_saveasdump)
2352                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2353                         else
2354                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2355                 }
2356                 if(autocvar_developer)
2357                 {
2358                         if(autocvar_sv_db_saveasdump)
2359                                 db_dump(TemporaryDB, "server-temp.db");
2360                         else
2361                                 db_save(TemporaryDB, "server-temp.db");
2362                 }
2363                 CheatShutdown(); // must be after cheatcount check
2364                 db_close(ServerProgsDB);
2365                 db_close(TemporaryDB);
2366                 print("done!\n");
2367                 // tell the bot system the game is ending now
2368                 bot_endgame();
2369
2370                 WeaponStats_Shutdown();
2371                 MapInfo_Shutdown();
2372         }
2373         else if(world_initialized == 0)
2374         {
2375                 print("NOTE: crashed before even initializing the world, not saving persistent data\n");
2376         }
2377 }