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