]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Consider g_norecoil an acceptable change
[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 "mutators/_mod.qh"
17 #include "race.qh"
18 #include "scores.qh"
19 #include "teamplay.qh"
20 #include "weapons/weaponstats.qh"
21 #include "../common/constants.qh"
22 #include "../common/deathtypes/all.qh"
23 #include "../common/mapinfo.qh"
24 #include "../common/monsters/_mod.qh"
25 #include "../common/monsters/sv_monsters.qh"
26 #include "../common/vehicles/all.qh"
27 #include "../common/notifications/all.qh"
28 #include "../common/physics/player.qh"
29 #include "../common/playerstats.qh"
30 #include "../common/stats.qh"
31 #include "../common/teams.qh"
32 #include "../common/triggers/trigger/secret.qh"
33 #include "../common/triggers/target/music.qh"
34 #include "../common/util.qh"
35 #include "../common/items/_mod.qh"
36 #include <common/weapons/_all.qh>
37 #include "../common/state.qh"
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(entity this)
45 {
46         float delta;
47         entity e;
48
49         delta = 3 / maxclients;
50         if(delta < sys_frametime)
51                 delta = 0;
52         this.nextthink = time + delta;
53
54         e = edict_num(this.cnt + 1);
55         if(IS_REAL_CLIENT(e))
56         {
57                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
58                 WriteByte(MSG_BROADCAST, this.cnt);
59                 WriteShort(MSG_BROADCAST, bound(1, e.ping, 65535));
60                 WriteByte(MSG_BROADCAST, min(ceil(e.ping_packetloss * 255), 255));
61                 WriteByte(MSG_BROADCAST, min(ceil(e.ping_movementloss * 255), 255));
62
63                 // record latency times for clients throughout the match so we can report it to playerstats
64                 if(time > (e.latency_time + LATENCY_THINKRATE))
65                 {
66                         e.latency_sum += e.ping;
67                         e.latency_cnt += 1;
68                         e.latency_time = time;
69                         //print("sum: ", ftos(e.latency_sum), ", cnt: ", ftos(e.latency_cnt), ", avg: ", ftos(e.latency_sum / e.latency_cnt), ".\n");
70                 }
71         }
72         else
73         {
74                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
75                 WriteByte(MSG_BROADCAST, this.cnt);
76                 WriteShort(MSG_BROADCAST, 0);
77                 WriteByte(MSG_BROADCAST, 0);
78                 WriteByte(MSG_BROADCAST, 0);
79         }
80         this.cnt = (this.cnt + 1) % maxclients;
81 }
82 void PingPLReport_Spawn()
83 {
84         pingplreport = new_pure(pingplreport);
85         setthink(pingplreport, PingPLReport_Think);
86         pingplreport.nextthink = time;
87 }
88
89 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
90 string redirection_target;
91 float world_initialized;
92
93 string GetGametype();
94 void ShuffleMaplist();
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...\n");
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         if(cvar_changes)
148                 strunzone(cvar_changes);
149         cvar_changes = string_null;
150         if(cvar_purechanges)
151                 strunzone(cvar_purechanges);
152         cvar_purechanges = string_null;
153         cvar_purechanges_count = 0;
154
155         h = buf_create();
156         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
157         n = buf_getsize(h);
158
159         adding = true;
160         pureadding = true;
161
162         for(i = 0; i < n; ++i)
163         {
164                 k = bufstr_get(h, i);
165
166 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
167 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
168 #define BADCVAR(p) if(k == p) continue
169
170                 // general excludes and namespaces for server admin used cvars
171                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
172
173                 // internal
174                 BADPREFIX("csqc_");
175                 BADPREFIX("cvar_check_");
176                 BADCVAR("gamecfg");
177                 BADCVAR("g_configversion");
178                 BADCVAR("g_maplist_index");
179                 BADCVAR("halflifebsp");
180                 BADCVAR("sv_mapformat_is_quake2");
181                 BADCVAR("sv_mapformat_is_quake3");
182                 BADPREFIX("sv_world");
183
184                 // client
185                 BADPREFIX("chase_");
186                 BADPREFIX("cl_");
187                 BADPREFIX("con_");
188                 BADPREFIX("scoreboard_");
189                 BADPREFIX("g_campaign");
190                 BADPREFIX("g_waypointsprite_");
191                 BADPREFIX("gl_");
192                 BADPREFIX("joy");
193                 BADPREFIX("hud_");
194                 BADPREFIX("m_");
195                 BADPREFIX("menu_");
196                 BADPREFIX("net_slist_");
197                 BADPREFIX("r_");
198                 BADPREFIX("sbar_");
199                 BADPREFIX("scr_");
200                 BADPREFIX("snd_");
201                 BADPREFIX("show");
202                 BADPREFIX("sensitivity");
203                 BADPREFIX("userbind");
204                 BADPREFIX("v_");
205                 BADPREFIX("vid_");
206                 BADPREFIX("crosshair");
207                 BADCVAR("mod_q3bsp_lightmapmergepower");
208                 BADCVAR("mod_q3bsp_nolightmaps");
209                 BADCVAR("fov");
210                 BADCVAR("mastervolume");
211                 BADCVAR("volume");
212                 BADCVAR("bgmvolume");
213
214                 // private
215                 BADCVAR("developer");
216                 BADCVAR("log_dest_udp");
217                 BADCVAR("net_address");
218                 BADCVAR("net_address_ipv6");
219                 BADCVAR("port");
220                 BADCVAR("savedgamecfg");
221                 BADCVAR("serverconfig");
222                 BADCVAR("sv_autoscreenshot");
223                 BADCVAR("sv_heartbeatperiod");
224                 BADCVAR("sv_vote_master_password");
225                 BADCVAR("sys_colortranslation");
226                 BADCVAR("sys_specialcharactertranslation");
227                 BADCVAR("timeformat");
228                 BADCVAR("timestamps");
229                 BADPREFIX("developer_");
230                 BADPREFIX("g_ban_");
231                 BADPREFIX("g_banned_list");
232                 BADPREFIX("g_chat_flood_");
233                 BADPREFIX("g_ghost_items");
234                 BADPREFIX("g_playerstats_");
235                 BADPREFIX("g_voice_flood_");
236                 BADPREFIX("log_file");
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
251                 // mapinfo
252                 BADCVAR("fraglimit");
253                 BADCVAR("g_assault");
254                 BADCVAR("g_ca");
255                 BADCVAR("g_ca_teams");
256                 BADCVAR("g_ctf");
257                 BADCVAR("g_cts");
258                 BADCVAR("g_dm");
259                 BADCVAR("g_domination");
260                 BADCVAR("g_domination_default_teams");
261                 BADCVAR("g_freezetag");
262                 BADCVAR("g_freezetag_teams");
263                 BADCVAR("g_invasion_teams");
264                 BADCVAR("g_keepaway");
265                 BADCVAR("g_keyhunt");
266                 BADCVAR("g_keyhunt_teams");
267                 BADCVAR("g_lms");
268                 BADCVAR("g_nexball");
269                 BADCVAR("g_onslaught");
270                 BADCVAR("g_race");
271                 BADCVAR("g_race_laps_limit");
272                 BADCVAR("g_race_qualifying_timelimit");
273                 BADCVAR("g_race_qualifying_timelimit_override");
274                 BADCVAR("g_tdm");
275                 BADCVAR("g_tdm_teams");
276                 BADCVAR("leadlimit");
277                 BADCVAR("nextmap");
278                 BADCVAR("teamplay");
279                 BADCVAR("timelimit");
280
281                 // long
282                 BADCVAR("hostname");
283                 BADCVAR("g_maplist");
284                 BADCVAR("g_maplist_mostrecent");
285                 BADCVAR("sv_motd");
286
287                 v = cvar_string(k);
288                 d = cvar_defstring(k);
289                 if(v == d)
290                         continue;
291
292                 if(adding)
293                 {
294                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
295                         if(strlen(cvar_changes) > 16384)
296                         {
297                                 cvar_changes = "// too many settings have been changed to show them here\n";
298                                 adding = 0;
299                         }
300                 }
301
302                 // now check if the changes are actually gameplay relevant
303
304                 // does nothing gameplay relevant
305                 BADCVAR("captureleadlimit_override");
306                 BADCVAR("gameversion");
307                 BADCVAR("g_allow_oldvortexbeam");
308                 BADCVAR("g_balance_kill_delay");
309                 BADCVAR("g_campcheck_distance");
310                 BADCVAR("g_ca_point_leadlimit");
311                 BADCVAR("g_ca_point_limit");
312                 BADCVAR("g_ctf_captimerecord_always");
313                 BADCVAR("g_ctf_flag_glowtrails");
314                 BADCVAR("g_ctf_flag_pickup_verbosename");
315                 BADCVAR("g_domination_point_leadlimit");
316                 BADCVAR("g_forced_respawn");
317                 BADCVAR("g_freezetag_point_leadlimit");
318                 BADCVAR("g_freezetag_point_limit");
319                 BADCVAR("g_hats");
320                 BADCVAR("g_invasion_point_limit");
321                 BADCVAR("g_keyhunt_point_leadlimit");
322                 BADCVAR("g_nexball_goalleadlimit");
323                 BADCVAR("g_new_toys_use_pickupsound");
324                 BADCVAR("g_physics_predictall");
325                 BADCVAR("g_tdm_point_leadlimit");
326                 BADCVAR("g_tdm_point_limit");
327                 BADCVAR("leadlimit_and_fraglimit");
328                 BADCVAR("leadlimit_override");
329                 BADCVAR("pausable");
330                 BADCVAR("sv_checkforpacketsduringsleep");
331                 BADCVAR("sv_intermission_cdtrack");
332                 BADCVAR("sv_minigames");
333                 BADCVAR("sv_namechangetimer");
334                 BADCVAR("sv_precacheplayermodels");
335                 BADCVAR("sv_timeout");
336                 BADPREFIX("crypto_");
337                 BADPREFIX("gameversion_");
338                 BADPREFIX("g_chat_");
339                 BADPREFIX("g_ctf_captimerecord_");
340                 BADPREFIX("g_maplist_votable_");
341                 BADPREFIX("g_mod_");
342                 BADPREFIX("g_respawn_");
343                 BADPREFIX("net_");
344                 BADPREFIX("prvm_");
345                 BADPREFIX("skill_");
346                 BADPREFIX("sv_allow_");
347                 BADPREFIX("sv_cullentities_");
348                 BADPREFIX("sv_maxidle_");
349                 BADPREFIX("sv_minigames_");
350                 BADPREFIX("sv_radio_");
351                 BADPREFIX("sv_timeout_");
352                 BADPREFIX("sv_vote_");
353                 BADPREFIX("timelimit_");
354
355                 // allowed changes to server admins (please sync this to server.cfg)
356                 // vi commands:
357                 //   :/"impure"/,$d
358                 //   :g!,^\/\/[^ /],d
359                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
360                 //   :%!sort
361                 // yes, this does contain some redundant stuff, don't really care
362                 BADCVAR("bot_config_file");
363                 BADCVAR("bot_number");
364                 BADCVAR("bot_prefix");
365                 BADCVAR("bot_suffix");
366                 BADCVAR("capturelimit_override");
367                 BADCVAR("fraglimit_override");
368                 BADCVAR("gametype");
369                 BADCVAR("g_antilag");
370                 BADCVAR("g_balance_teams");
371                 BADCVAR("g_balance_teams_prevent_imbalance");
372                 BADCVAR("g_balance_teams_scorefactor");
373                 BADCVAR("g_ban_sync_trusted_servers");
374                 BADCVAR("g_ban_sync_uri");
375                 BADCVAR("g_buffs");
376                 BADCVAR("g_ca_teams_override");
377                 BADCVAR("g_ctf_ignore_frags");
378                 BADCVAR("g_domination_point_limit");
379                 BADCVAR("g_domination_teams_override");
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_norecoil");
399                 BADCVAR("g_powerups");
400                 BADCVAR("g_spawnshieldtime");
401                 BADCVAR("g_start_delay");
402                 BADCVAR("g_superspectate");
403                 BADCVAR("g_tdm_teams_override");
404                 BADCVAR("g_warmup");
405                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
406                 BADCVAR("hostname");
407                 BADCVAR("log_file");
408                 BADCVAR("maxplayers");
409                 BADCVAR("minplayers");
410                 BADCVAR("net_address");
411                 BADCVAR("port");
412                 BADCVAR("rcon_password");
413                 BADCVAR("rcon_restricted_commands");
414                 BADCVAR("rcon_restricted_password");
415                 BADCVAR("skill");
416                 BADCVAR("sv_adminnick");
417                 BADCVAR("sv_autoscreenshot");
418                 BADCVAR("sv_autotaunt");
419                 BADCVAR("sv_curl_defaulturl");
420                 BADCVAR("sv_defaultcharacter");
421                 BADCVAR("sv_defaultcharacterskin");
422                 BADCVAR("sv_defaultplayercolors");
423                 BADCVAR("sv_defaultplayermodel");
424                 BADCVAR("sv_defaultplayerskin");
425                 BADCVAR("sv_maxidle");
426                 BADCVAR("sv_maxrate");
427                 BADCVAR("sv_motd");
428                 BADCVAR("sv_public");
429                 BADCVAR("sv_ready_restart");
430                 BADCVAR("sv_status_privacy");
431                 BADCVAR("sv_taunt");
432                 BADCVAR("sv_vote_call");
433                 BADCVAR("sv_vote_commands");
434                 BADCVAR("sv_vote_majority_factor");
435                 BADCVAR("sv_vote_master");
436                 BADCVAR("sv_vote_master_commands");
437                 BADCVAR("sv_vote_master_password");
438                 BADCVAR("sv_vote_simple_majority_factor");
439                 BADCVAR("teamplay_mode");
440                 BADCVAR("timelimit_override");
441                 BADPREFIX("g_warmup_");
442                 BADPREFIX("sv_ready_restart_");
443
444                 // mutators that announce themselves properly to the server browser
445                 BADCVAR("g_instagib");
446                 BADCVAR("g_new_toys");
447                 BADCVAR("g_nix");
448                 BADCVAR("g_grappling_hook");
449                 BADCVAR("g_jetpack");
450
451 #undef BADPRESUFFIX
452 #undef BADPREFIX
453 #undef BADCVAR
454
455                 if(pureadding)
456                 {
457                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
458                         if(strlen(cvar_purechanges) > 16384)
459                         {
460                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
461                                 pureadding = 0;
462                         }
463                 }
464                 ++cvar_purechanges_count;
465                 // WARNING: this variable is used for the server list
466                 // NEVER dare to skip this code!
467                 // Hacks to intentionally appearing as "pure server" even though you DO have
468                 // modified settings may be punished by removal from the server list.
469                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
470                 // though.
471         }
472         buf_del(h);
473         if(cvar_changes == "")
474                 cvar_changes = "// this server runs at default server settings\n";
475         else
476                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
477         cvar_changes = strzone(cvar_changes);
478         if(cvar_purechanges == "")
479                 cvar_purechanges = "// this server runs at default gameplay settings\n";
480         else
481                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
482         cvar_purechanges = strzone(cvar_purechanges);
483 }
484
485 void detect_maptype()
486 {
487 #if 0
488         vector o, v;
489         float i;
490
491         for (;;)
492         {
493                 o = world.mins;
494                 o.x += random() * (world.maxs.x - world.mins.x);
495                 o.y += random() * (world.maxs.y - world.mins.y);
496                 o.z += random() * (world.maxs.z - world.mins.z);
497
498                 tracebox(o, STAT(PL_MIN, NULL), STAT(PL_MAX, NULL), o - '0 0 32768', MOVE_WORLDONLY, NULL);
499                 if(trace_fraction == 1)
500                         continue;
501
502                 v = trace_endpos;
503
504                 for(i = 0; i < 64; i += 4)
505                 {
506                         tracebox(o, '-1 -1 -1' * i, '1 1 1' * i, o - '0 0 32768', MOVE_WORLDONLY, NULL);
507         if(trace_fraction == 1)
508                 continue;
509                         LOG_INFO(ftos(i), " -> ", vtos(trace_endpos), "\n");
510                 }
511
512                 break;
513         }
514 #endif
515 }
516
517 entity randomseed;
518 bool RandomSeed_Send(entity this, entity to, int sf)
519 {
520         WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
521         WriteShort(MSG_ENTITY, this.cnt);
522         return true;
523 }
524 void RandomSeed_Think(entity this)
525 {
526         this.cnt = bound(0, floor(random() * 65536), 65535);
527         this.nextthink = time + 5;
528
529         this.SendFlags |= 1;
530 }
531 void RandomSeed_Spawn()
532 {
533         randomseed = new_pure(randomseed);
534         setthink(randomseed, RandomSeed_Think);
535         Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
536
537         getthink(randomseed)(randomseed); // sets random seed and nextthink
538 }
539
540 spawnfunc(__init_dedicated_server)
541 {
542         // handler for _init/_init map (only for dedicated server initialization)
543
544         world_initialized = -1; // don't complain
545         cvar = cvar_normal;
546         cvar_string = cvar_string_normal;
547         cvar_set = cvar_set_normal;
548
549         delete_fn = remove_unsafely;
550
551         entity e = spawn();
552         setthink(e, GotoFirstMap);
553         e.nextthink = time; // this is usually 1 at this point
554
555         e = new(info_player_deathmatch);  // safeguard against player joining
556
557         this.classname = "worldspawn"; // safeguard against various stuff ;)
558
559         // needs to be done so early because of the constants they create
560         static_init();
561         static_init_late();
562         static_init_precache();
563
564         IL_PUSH(g_spawnpoints, e); // just incase
565
566         MapInfo_Enumerate();
567         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
568 }
569
570 void __init_dedicated_server_shutdown() {
571         MapInfo_Shutdown();
572 }
573
574 void SetLimits(int fraglimit_override, int leadlimit_override, float timelimit_override, float qualifying_override)
575 {
576         if(!autocvar_g_campaign)
577         {
578                 if(fraglimit_override >= 0) cvar_set("fraglimit", ftos(fraglimit_override));
579                 if(timelimit_override >= 0) cvar_set("timelimit", ftos(timelimit_override));
580                 if(leadlimit_override >= 0) cvar_set("leadlimit", ftos(leadlimit_override));
581                 if(qualifying_override >= 0) cvar_set("g_race_qualifying_timelimit", ftos(qualifying_override));
582         }
583         limits_are_set = true;
584 }
585
586 void Map_MarkAsRecent(string m);
587 float world_already_spawned;
588 void Nagger_Init();
589 void ClientInit_Spawn();
590 void WeaponStats_Init();
591 void WeaponStats_Shutdown();
592 spawnfunc(worldspawn)
593 {
594         server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
595
596     bool wantrestart = false;
597         {
598                 if (!server_is_dedicated)
599                 {
600                         // force unloading of server pk3 files when starting a listen server
601                         // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
602                         // restore csqc_progname too
603                         string expect = "csprogs.dat";
604                         wantrestart = cvar_string_normal("csqc_progname") != expect;
605                         cvar_set_normal("csqc_progname", expect);
606                 }
607                 else
608                 {
609                         // Try to use versioned csprogs from pk3
610                         // Only ever use versioned csprogs.dat files on dedicated servers;
611                         // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
612                         string pk3csprogs = "csprogs-" WATERMARK ".dat";
613                         // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
614                         string select = "csprogs.dat";
615                         if (fexists(pk3csprogs)) select = pk3csprogs;
616                         if (cvar_string_normal("csqc_progname") != select)
617                         {
618                                 cvar_set_normal("csqc_progname", select);
619                                 wantrestart = true;
620                         }
621                         // Check for updates on startup
622                         // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
623                         int sentinel = fopen("progs.txt", FILE_READ);
624                         if (sentinel >= 0)
625                         {
626                                 string switchversion = fgets(sentinel);
627                                 fclose(sentinel);
628                                 if (switchversion != "" && switchversion != WATERMARK)
629                                 {
630                                         LOG_INFOF("Switching progs: " WATERMARK " -> %s\n", switchversion);
631                                         // if it doesn't exist, assume either:
632                                         //   a) the current program was overwritten
633                                         //   b) this is a client only update
634                                         string newprogs = sprintf("progs-%s.dat", switchversion);
635                                         if (fexists(newprogs))
636                                         {
637                                                 cvar_set_normal("sv_progs", newprogs);
638                                                 wantrestart = true;
639                                         }
640                                         string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
641                                         if (fexists(newcsprogs))
642                                         {
643                                                 cvar_set_normal("csqc_progname", newcsprogs);
644                                                 wantrestart = true;
645                                         }
646                                 }
647                         }
648                 }
649                 if (wantrestart)
650                 {
651                         LOG_INFOF("Restart requested\n");
652                         changelevel(mapname);
653                         // let initialization continue, shutdown depends on it
654                 }
655         }
656
657         cvar = cvar_normal;
658         cvar_string = cvar_string_normal;
659         cvar_set = cvar_set_normal;
660
661         if(world_already_spawned)
662                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
663         world_already_spawned = true;
664
665         delete_fn = remove_safely; // during spawning, watch what you remove!
666
667         cvar_changes_init(); // do this very early now so it REALLY matches the server config
668
669         maxclients = 0;
670         for (entity head = nextent(NULL); head; head = nextent(head))
671         {
672                 ++maxclients;
673         }
674
675         // needs to be done so early because of the constants they create
676         static_init();
677
678         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
679
680         TemporaryDB = db_create();
681
682         // 0 normal
683         lightstyle(0, "m");
684
685         // 1 FLICKER (first variety)
686         lightstyle(1, "mmnmmommommnonmmonqnmmo");
687
688         // 2 SLOW STRONG PULSE
689         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
690
691         // 3 CANDLE (first variety)
692         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
693
694         // 4 FAST STROBE
695         lightstyle(4, "mamamamamama");
696
697         // 5 GENTLE PULSE 1
698         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
699
700         // 6 FLICKER (second variety)
701         lightstyle(6, "nmonqnmomnmomomno");
702
703         // 7 CANDLE (second variety)
704         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
705
706         // 8 CANDLE (third variety)
707         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
708
709         // 9 SLOW STROBE (fourth variety)
710         lightstyle(9, "aaaaaaaazzzzzzzz");
711
712         // 10 FLUORESCENT FLICKER
713         lightstyle(10, "mmamammmmammamamaaamammma");
714
715         // 11 SLOW PULSE NOT FADE TO BLACK
716         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
717
718         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
719
720         // 63 testing
721         lightstyle(63, "a");
722
723         if(autocvar_g_campaign)
724                 CampaignPreInit();
725
726         Map_MarkAsRecent(mapname);
727
728         PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
729
730         InitGameplayMode();
731         static_init_late();
732         static_init_precache();
733         readlevelcvars();
734         GrappleHookInit();
735
736         if(!limits_are_set)
737                 SetLimits(autocvar_fraglimit_override, autocvar_leadlimit_override, autocvar_timelimit_override, -1);
738
739         if(warmup_limit == 0)
740                 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
741
742         player_count = 0;
743         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
744         if(bot_waypoints_for_items == 1)
745                 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
746                         bot_waypoints_for_items = 0;
747
748         precache();
749
750         WaypointSprite_Init();
751
752         GameLogInit(); // prepare everything
753         // NOTE for matchid:
754         // changing the logic generating it is okay. But:
755         // it HAS to stay <= 64 chars
756         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
757         if(autocvar_sv_eventlog)
758         {
759                 string s = sprintf("%d.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
760                 matchid = strzone(s);
761
762                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
763                 s = ":gameinfo:mutators:LIST";
764
765                 MUTATOR_CALLHOOK(BuildMutatorsString, s);
766                 s = M_ARGV(0, string);
767
768                 // initialiation stuff, not good in the mutator system
769                 if(!autocvar_g_use_ammunition)
770                         s = strcat(s, ":no_use_ammunition");
771
772                 // initialiation stuff, not good in the mutator system
773                 if(autocvar_g_pickup_items == 0)
774                         s = strcat(s, ":no_pickup_items");
775                 if(autocvar_g_pickup_items > 0)
776                         s = strcat(s, ":pickup_items");
777
778                 // initialiation stuff, not good in the mutator system
779                 if(autocvar_g_weaponarena != "0")
780                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
781
782                 // TODO to mutator system
783                 if(autocvar_g_norecoil)
784                         s = strcat(s, ":norecoil");
785
786                 // TODO to mutator system
787                 if(autocvar_g_powerups == 0)
788                         s = strcat(s, ":no_powerups");
789                 if(autocvar_g_powerups > 0)
790                         s = strcat(s, ":powerups");
791
792                 GameLogEcho(s);
793                 GameLogEcho(":gameinfo:end");
794         }
795         else
796                 matchid = strzone(ftos(random()));
797
798         cvar_set("nextmap", "");
799
800         SetDefaultAlpha();
801
802         if(autocvar_g_campaign)
803                 CampaignPostInit();
804
805         Ban_LoadBans();
806
807         MapInfo_Enumerate();
808         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
809
810         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
811         {
812                 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
813                 if(fd != -1)
814                 {
815                         string s;
816                         while((s = fgets(fd)))
817                         {
818                                 int l = tokenize_console(s);
819                                 if(l < 2)
820                                         continue;
821                                 if(argv(0) == "cd")
822                                 {
823                                         LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:\n");
824                                         LOG_INFO("  cdtrack ", argv(2), "\n");
825                                 }
826                                 else if(argv(0) == "fog")
827                                 {
828                                         LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:\n");
829                                         LOG_INFO("  \"fog\" \"", s, "\"\n");
830                                 }
831                                 else if(argv(0) == "set")
832                                 {
833                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
834                                         LOG_INFO("  clientsettemp_for_type all ", argv(1), " ", argv(2), "\n");
835                                 }
836                                 else if(argv(0) != "//")
837                                 {
838                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:\n");
839                                         LOG_INFO("  clientsettemp_for_type all ", argv(0), " ", argv(1), "\n");
840                                 }
841                         }
842                         fclose(fd);
843                 }
844         }
845
846         WeaponStats_Init();
847
848         Nagger_Init();
849
850         next_pingtime = time + 5;
851
852         detect_maptype();
853
854         // set up information replies for clients and server to use
855         maplist_reply = strzone(getmaplist());
856         lsmaps_reply = strzone(getlsmaps());
857         monsterlist_reply = strzone(getmonsterlist());
858         for(int i = 0; i < 10; ++i)
859         {
860                 string s = getrecords(i);
861                 if (s)
862                         records_reply[i] = strzone(s);
863         }
864         ladder_reply = strzone(getladder());
865         rankings_reply = strzone(getrankings());
866
867         // begin other init
868         ClientInit_Spawn();
869         RandomSeed_Spawn();
870         PingPLReport_Spawn();
871
872         CheatInit();
873
874         if (!wantrestart) localcmd("\n_sv_hook_gamestart ", GetGametype(), "\n");
875
876         // fill sv_curl_serverpackages from .serverpackage files
877         if (autocvar_sv_curl_serverpackages_auto)
878         {
879                 string s = "csprogs-" WATERMARK ".txt";
880                 // remove automatically managed files from the list to prevent duplicates
881                 for (int i = 0, n = tokenize_console(cvar_string("sv_curl_serverpackages")); i < n; ++i)
882                 {
883                         string pkg = argv(i);
884                         if (startsWith(pkg, "csprogs-")) continue;
885                         if (endsWith(pkg, "-serverpackage.txt")) continue;
886                         if (endsWith(pkg, ".serverpackage")) continue;  // OLD legacy
887                         s = cons(s, pkg);
888                 }
889                 // add automatically managed files to the list
890                 #define X(match) MACRO_BEGIN { \
891                         int fd = search_begin(match, true, false); \
892                         if (fd >= 0) \
893                         { \
894                                 for (int i = 0, j = search_getsize(fd); i < j; ++i) \
895                                 { \
896                                         s = cons(s, search_getfilename(fd, i)); \
897                                 } \
898                                 search_end(fd); \
899                         } \
900                 } MACRO_END
901                 X("*-serverpackage.txt");
902                 X("*.serverpackage");
903                 #undef X
904                 cvar_set("sv_curl_serverpackages", s);
905         }
906
907         // MOD AUTHORS: change this, and possibly remove a few of the blocks below to ignore certain changes
908         modname = "Xonotic";
909         // physics/balance/config changes that count as mod
910         if(cvar_string("g_mod_physics") != cvar_defstring("g_mod_physics"))
911                 modname = cvar_string("g_mod_physics");
912         if(cvar_string("g_mod_balance") != cvar_defstring("g_mod_balance"))
913                 modname = cvar_string("g_mod_balance");
914         if(cvar_string("g_mod_config") != cvar_defstring("g_mod_config"))
915                 modname = cvar_string("g_mod_config");
916         // extra mutators that deserve to count as mod
917         MUTATOR_CALLHOOK(SetModname);
918
919         // save it for later
920         modname = strzone(modname);
921
922         WinningConditionHelper(this); // set worldstatus
923
924         world_initialized = 1;
925 }
926
927 spawnfunc(light)
928 {
929         //makestatic (this); // Who the f___ did that?
930         delete(this);
931 }
932
933 string GetGametype()
934 {
935         return MapInfo_Type_ToString(MapInfo_LoadedGametype);
936 }
937
938 string GetMapname()
939 {
940         return mapname;
941 }
942
943 float Map_Count, Map_Current;
944 string Map_Current_Name;
945
946 // NOTE: this now expects the map list to be already tokenized and the count in Map_Count
947 float GetMaplistPosition()
948 {
949         float pos, idx;
950         string map;
951
952         map = GetMapname();
953         idx = autocvar_g_maplist_index;
954
955         if(idx >= 0)
956                 if(idx < Map_Count)
957                         if(map == argv(idx))
958                                 return idx;
959
960         for(pos = 0; pos < Map_Count; ++pos)
961                 if(map == argv(pos))
962                         return pos;
963
964         // resume normal maplist rotation if current map is not in g_maplist
965         return idx;
966 }
967
968 float MapHasRightSize(string map)
969 {
970         float fh;
971         if(currentbots || autocvar_bot_number || player_count < autocvar_minplayers)
972         if(autocvar_g_maplist_check_waypoints)
973         {
974                 LOG_TRACE("checkwp "); LOG_TRACE(map);
975                 if(!fexists(strcat("maps/", map, ".waypoints")))
976                 {
977                         LOG_TRACE(": no waypoints");
978                         return false;
979                 }
980                 LOG_TRACE(": has waypoints");
981         }
982
983         // open map size restriction file
984         LOG_TRACE("opensize "); LOG_TRACE(map);
985         fh = fopen(strcat("maps/", map, ".sizes"), FILE_READ);
986         if(fh >= 0)
987         {
988                 float mapmin, mapmax;
989                 LOG_TRACE(": ok, ");
990                 mapmin = stof(fgets(fh));
991                 mapmax = stof(fgets(fh));
992                 fclose(fh);
993                 if(player_count < mapmin)
994                 {
995                         LOG_TRACE("not enough");
996                         return false;
997                 }
998                 if(player_count > mapmax)
999                 {
1000                         LOG_TRACE("too many");
1001                         return false;
1002                 }
1003                 LOG_TRACE("right size");
1004                 return true;
1005         }
1006         LOG_TRACE(": not found");
1007         return true;
1008 }
1009
1010 string Map_Filename(float position)
1011 {
1012         return strcat("maps/", argv(position), ".bsp");
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                 LOG_DEBUG( "Couldn't select '", filename, "'..." );
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         LOG_TRACE("Trying MaplistMethod_Iterate");
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         LOG_TRACE("Trying MaplistMethod_Repeat");
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         LOG_TRACE("Trying MaplistMethod_Random");
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         LOG_TRACE("Trying MaplistMethod_Shuffle");
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                 LOG_TRACE("SHUFFLE: insert pos = ", ftos(insertpos));
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(entity this)
1304 {
1305         FixIntermissionClient(this);
1306         CSQCMODEL_AUTOUPDATE(this); // PlayerPostThink returns before calling this during intermission, so run it here
1307
1308         float server_screenshot = (autocvar_sv_autoscreenshot && this.cvar_cl_autoscreenshot);
1309         float client_screenshot = (this.cvar_cl_autoscreenshot == 2);
1310
1311         if( (server_screenshot || client_screenshot)
1312                 && ((this.autoscreenshot > 0) && (time > this.autoscreenshot)) )
1313         {
1314                 this.autoscreenshot = -1;
1315                 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"))); }
1316                 return;
1317         }
1318
1319         if (time < intermission_exittime)
1320                 return;
1321
1322         if(!mapvote_initialized)
1323                 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)))
1324                         return;
1325
1326         MapVote_Start();
1327 }
1328
1329 /*
1330 ============
1331 FindIntermission
1332
1333 Returns the entity to view from
1334 ============
1335 */
1336 /*
1337 entity FindIntermission()
1338 {
1339         local   entity spot;
1340         local   float cyc;
1341
1342 // look for info_intermission first
1343         spot = find(NULL, classname, "info_intermission");
1344         if (spot)
1345         {       // pick a random one
1346                 cyc = random() * 4;
1347                 while (cyc > 1)
1348                 {
1349                         spot = find(spot, classname, "info_intermission");
1350                         if (!spot)
1351                                 spot = find(spot, classname, "info_intermission");
1352                         cyc = cyc - 1;
1353                 }
1354                 return spot;
1355         }
1356
1357 // then look for the start position
1358         spot = find(NULL, classname, "info_player_start");
1359         if (spot)
1360                 return spot;
1361
1362 // testinfo_player_start is only found in regioned levels
1363         spot = find(NULL, classname, "testplayerstart");
1364         if (spot)
1365                 return spot;
1366
1367 // then look for the start position
1368         spot = find(NULL, classname, "info_player_deathmatch");
1369         if (spot)
1370                 return spot;
1371
1372         //objerror ("FindIntermission: no spot");
1373         return NULL;
1374 }
1375 */
1376
1377 /*
1378 ===============================================================================
1379
1380 RULES
1381
1382 ===============================================================================
1383 */
1384
1385 void DumpStats(float final)
1386 {
1387         float file;
1388         string s;
1389         float to_console;
1390         float to_eventlog;
1391         float to_file;
1392         float i;
1393
1394         to_console = autocvar_sv_logscores_console;
1395         to_eventlog = autocvar_sv_eventlog;
1396         to_file = autocvar_sv_logscores_file;
1397
1398         if(!final)
1399         {
1400                 to_console = true; // always print printstats replies
1401                 to_eventlog = false; // but never print them to the event log
1402         }
1403
1404         if(to_eventlog)
1405                 if(autocvar_sv_eventlog_console)
1406                         to_console = false; // otherwise we get the output twice
1407
1408         if(final)
1409                 s = ":scores:";
1410         else
1411                 s = ":status:";
1412         s = strcat(s, GetGametype(), "_", GetMapname(), ":", ftos(rint(time)));
1413
1414         if(to_console)
1415                 LOG_INFO(s, "\n");
1416         if(to_eventlog)
1417                 GameLogEcho(s);
1418
1419         file = -1;
1420         if(to_file)
1421         {
1422                 file = fopen(autocvar_sv_logscores_filename, FILE_APPEND);
1423                 if(file == -1)
1424                         to_file = false;
1425                 else
1426                         fputs(file, strcat(s, "\n"));
1427         }
1428
1429         s = strcat(":labels:player:", GetPlayerScoreString(NULL, 0));
1430         if(to_console)
1431                 LOG_INFO(s, "\n");
1432         if(to_eventlog)
1433                 GameLogEcho(s);
1434         if(to_file)
1435                 fputs(file, strcat(s, "\n"));
1436
1437         FOREACH_CLIENT(IS_REAL_CLIENT(it) || (IS_BOT_CLIENT(it) && autocvar_sv_logscores_bots), LAMBDA(
1438                 s = strcat(":player:see-labels:", GetPlayerScoreString(it, 0), ":");
1439                 s = strcat(s, ftos(rint(time - it.jointime)), ":");
1440                 if(IS_PLAYER(it) || MUTATOR_CALLHOOK(GetPlayerStatus, it))
1441                         s = strcat(s, ftos(it.team), ":");
1442                 else
1443                         s = strcat(s, "spectator:");
1444
1445                 if(to_console)
1446                         LOG_INFO(s, it.netname, "\n");
1447                 if(to_eventlog)
1448                         GameLogEcho(strcat(s, ftos(it.playerid), ":", it.netname));
1449                 if(to_file)
1450                         fputs(file, strcat(s, it.netname, "\n"));
1451         ));
1452
1453         if(teamplay)
1454         {
1455                 s = strcat(":labels:teamscores:", GetTeamScoreString(0, 0));
1456                 if(to_console)
1457                         LOG_INFO(s, "\n");
1458                 if(to_eventlog)
1459                         GameLogEcho(s);
1460                 if(to_file)
1461                         fputs(file, strcat(s, "\n"));
1462
1463                 for(i = 1; i < 16; ++i)
1464                 {
1465                         s = strcat(":teamscores:see-labels:", GetTeamScoreString(i, 0));
1466                         s = strcat(s, ":", ftos(i));
1467                         if(to_console)
1468                                 LOG_INFO(s, "\n");
1469                         if(to_eventlog)
1470                                 GameLogEcho(s);
1471                         if(to_file)
1472                                 fputs(file, strcat(s, "\n"));
1473                 }
1474         }
1475
1476         if(to_console)
1477                 LOG_INFO(":end\n");
1478         if(to_eventlog)
1479                 GameLogEcho(":end");
1480         if(to_file)
1481         {
1482                 fputs(file, ":end\n");
1483                 fclose(file);
1484         }
1485 }
1486
1487 void FixIntermissionClient(entity e)
1488 {
1489         if(!e.autoscreenshot) // initial call
1490         {
1491                 e.autoscreenshot = time + 0.8;  // used for autoscreenshot
1492                 e.health = -2342;
1493                 // first intermission phase; voting phase has positive health (used to decide whether to send SVC_FINALE or not)
1494                 e.solid = SOLID_NOT;
1495                 set_movetype(e, MOVETYPE_NONE);
1496                 e.takedamage = DAMAGE_NO;
1497                 for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
1498                 {
1499                     .entity weaponentity = weaponentities[slot];
1500                         if(e.(weaponentity))
1501                         {
1502                                 e.(weaponentity).effects = EF_NODRAW;
1503                                 if (e.(weaponentity).weaponchild)
1504                                         e.(weaponentity).weaponchild.effects = EF_NODRAW;
1505                         }
1506                 }
1507                 if(IS_REAL_CLIENT(e))
1508                 {
1509                         stuffcmd(e, "\nscr_printspeed 1000000\n");
1510                         RandomSelection_Init();
1511                         FOREACH_WORD(autocvar_sv_intermission_cdtrack, true, LAMBDA(
1512                                 RandomSelection_AddString(it, 1, 1);
1513                         ));
1514                         if (RandomSelection_chosen_string != "")
1515                         {
1516                                 stuffcmd(e, sprintf("\ncd loop %s\n", RandomSelection_chosen_string));
1517                         }
1518                         msg_entity = e;
1519                         WriteByte(MSG_ONE, SVC_INTERMISSION);
1520                 }
1521         }
1522 }
1523
1524 /*
1525 go to the next level for deathmatch
1526 only called if a time or frag limit has expired
1527 */
1528 void NextLevel()
1529 {
1530         gameover = true;
1531
1532         intermission_running = 1;
1533
1534 // enforce a wait time before allowing changelevel
1535         if(player_count > 0)
1536                 intermission_exittime = time + autocvar_sv_mapchange_delay;
1537         else
1538                 intermission_exittime = -1;
1539
1540         /*
1541         WriteByte (MSG_ALL, SVC_CDTRACK);
1542         WriteByte (MSG_ALL, 3);
1543         WriteByte (MSG_ALL, 3);
1544         // done in FixIntermission
1545         */
1546
1547         //pos = FindIntermission ();
1548
1549         VoteReset();
1550
1551         DumpStats(true);
1552
1553         // send statistics
1554         PlayerStats_GameReport(true);
1555         WeaponStats_Shutdown();
1556
1557         Kill_Notification(NOTIF_ALL, NULL, MSG_CENTER, CPID_Null); // kill all centerprints now
1558
1559         if(autocvar_sv_eventlog)
1560                 GameLogEcho(":gameover");
1561
1562         GameLogClose();
1563
1564         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1565                 FixIntermissionClient(it);
1566                 if(it.winning)
1567                         bprint(it.netname, " ^7wins.\n");
1568         ));
1569
1570         target_music_kill();
1571
1572         if(autocvar_g_campaign)
1573                 CampaignPreIntermission();
1574
1575         MUTATOR_CALLHOOK(MatchEnd);
1576
1577         localcmd("\nsv_hook_gameend\n");
1578 }
1579
1580 /*
1581 ============
1582 CheckRules_Player
1583
1584 Exit deathmatch games upon conditions
1585 ============
1586 */
1587 void CheckRules_Player(entity this)
1588 {
1589         if (gameover)   // someone else quit the game already
1590                 return;
1591
1592         if(!IS_DEAD(this))
1593                 this.play_time += frametime;
1594
1595         // fixme: don't check players; instead check spawnfunc_dom_team and spawnfunc_ctf_team entities
1596         //   (div0: and that in CheckRules_World please)
1597 }
1598
1599
1600 float InitiateSuddenDeath()
1601 {
1602         // Check first whether normal overtimes could be added before initiating suddendeath mode
1603         // - for this timelimit_overtime needs to be >0 of course
1604         // - also check the winning condition calculated in the previous frame and only add normal overtime
1605         //   again, if at the point at which timelimit would be extended again, still no winner was found
1606         if (!autocvar_g_campaign && (checkrules_overtimesadded >= 0) && (checkrules_overtimesadded < autocvar_timelimit_overtimes || autocvar_timelimit_overtimes < 0) && autocvar_timelimit_overtime && !(g_race && !g_race_qualifying))
1607         {
1608                 return 1; // need to call InitiateOvertime later
1609         }
1610         else
1611         {
1612                 if(!checkrules_suddendeathend)
1613                 {
1614                         if(autocvar_g_campaign)
1615                                 checkrules_suddendeathend = time; // no suddendeath in campaign
1616                         else
1617                                 checkrules_suddendeathend = time + 60 * autocvar_timelimit_suddendeath;
1618                         if(g_race && !g_race_qualifying)
1619                                 race_StartCompleting();
1620                 }
1621                 return 0;
1622         }
1623 }
1624
1625 void InitiateOvertime() // ONLY call this if InitiateSuddenDeath returned true
1626 {
1627         ++checkrules_overtimesadded;
1628         //add one more overtime by simply extending the timelimit
1629         float tl;
1630         tl = autocvar_timelimit;
1631         tl += autocvar_timelimit_overtime;
1632         cvar_set("timelimit", ftos(tl));
1633
1634         Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_TIME, autocvar_timelimit_overtime * 60);
1635 }
1636
1637 float GetWinningCode(float fraglimitreached, float equality)
1638 {
1639         if(autocvar_g_campaign == 1)
1640                 if(fraglimitreached)
1641                         return WINNING_YES;
1642                 else
1643                         return WINNING_NO;
1644
1645         else
1646                 if(equality)
1647                         if(fraglimitreached)
1648                                 return WINNING_STARTSUDDENDEATHOVERTIME;
1649                         else
1650                                 return WINNING_NEVER;
1651                 else
1652                         if(fraglimitreached)
1653                                 return WINNING_YES;
1654                         else
1655                                 return WINNING_NO;
1656 }
1657
1658 // set the .winning flag for exactly those players with a given field value
1659 void SetWinners(.float field, float value)
1660 {
1661         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(it.winning = (it.(field) == value)));
1662 }
1663
1664 // set the .winning flag for those players with a given field value
1665 void AddWinners(.float field, float value)
1666 {
1667         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1668                 if(it.(field) == value)
1669                         it.winning = 1;
1670         ));
1671 }
1672
1673 // clear the .winning flags
1674 void ClearWinners()
1675 {
1676         FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(it.winning = 0));
1677 }
1678
1679 void ShuffleMaplist()
1680 {
1681         cvar_set("g_maplist", shufflewords(autocvar_g_maplist));
1682 }
1683
1684 float leaderfrags;
1685 float WinningCondition_Scores(float limit, float leadlimit)
1686 {
1687         float limitreached;
1688
1689         // TODO make everything use THIS winning condition (except LMS)
1690         WinningConditionHelper(NULL);
1691
1692         if(teamplay)
1693         {
1694                 team1_score = TeamScore_GetCompareValue(NUM_TEAM_1);
1695                 team2_score = TeamScore_GetCompareValue(NUM_TEAM_2);
1696                 team3_score = TeamScore_GetCompareValue(NUM_TEAM_3);
1697                 team4_score = TeamScore_GetCompareValue(NUM_TEAM_4);
1698         }
1699
1700         ClearWinners();
1701         if(WinningConditionHelper_winner)
1702                 WinningConditionHelper_winner.winning = 1;
1703         if(WinningConditionHelper_winnerteam >= 0)
1704                 SetWinners(team, WinningConditionHelper_winnerteam);
1705
1706         if(WinningConditionHelper_lowerisbetter)
1707         {
1708                 WinningConditionHelper_topscore = -WinningConditionHelper_topscore;
1709                 WinningConditionHelper_secondscore = -WinningConditionHelper_secondscore;
1710                 limit = -limit;
1711         }
1712
1713         if(WinningConditionHelper_zeroisworst)
1714                 leadlimit = 0; // not supported in this mode
1715
1716         if(MUTATOR_CALLHOOK(Scores_CountFragsRemaining))
1717         // these modes always score in increments of 1, thus this makes sense
1718         {
1719                 if(leaderfrags != WinningConditionHelper_topscore)
1720                 {
1721                         leaderfrags = WinningConditionHelper_topscore;
1722
1723                         if (limit)
1724                         if (leaderfrags == limit - 1)
1725                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_1);
1726                         else if (leaderfrags == limit - 2)
1727                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_2);
1728                         else if (leaderfrags == limit - 3)
1729                                 Send_Notification(NOTIF_ALL, NULL, MSG_ANNCE, ANNCE_REMAINING_FRAG_3);
1730                 }
1731         }
1732
1733         limitreached = false;
1734         if(limit)
1735                 if(WinningConditionHelper_topscore >= limit)
1736                         limitreached = true;
1737         if(leadlimit)
1738         {
1739                 float leadlimitreached;
1740                 leadlimitreached = (WinningConditionHelper_topscore - WinningConditionHelper_secondscore >= leadlimit);
1741                 if(autocvar_leadlimit_and_fraglimit)
1742                         limitreached = (limitreached && leadlimitreached);
1743                 else
1744                         limitreached = (limitreached || leadlimitreached);
1745         }
1746
1747         if(limit)
1748                 game_completion_ratio = max(game_completion_ratio, bound(0, WinningConditionHelper_topscore / limit, 1));
1749
1750         return GetWinningCode(
1751                 WinningConditionHelper_topscore && limitreached,
1752                 WinningConditionHelper_equality
1753         );
1754 }
1755
1756 float WinningCondition_RanOutOfSpawns()
1757 {
1758         if(have_team_spawns <= 0)
1759                 return WINNING_NO;
1760
1761         if(!autocvar_g_spawn_useallspawns)
1762                 return WINNING_NO;
1763
1764         if(!some_spawn_has_been_used)
1765                 return WINNING_NO;
1766
1767         team1_score = team2_score = team3_score = team4_score = 0;
1768
1769         FOREACH_CLIENT(IS_PLAYER(it) && !IS_DEAD(it), LAMBDA(
1770                 switch(it.team)
1771                 {
1772                         case NUM_TEAM_1: team1_score = 1; break;
1773                         case NUM_TEAM_2: team2_score = 1; break;
1774                         case NUM_TEAM_3: team3_score = 1; break;
1775                         case NUM_TEAM_4: team4_score = 1; break;
1776                 }
1777         ));
1778
1779         IL_EACH(g_spawnpoints, true,
1780         {
1781                 switch(it.team)
1782                 {
1783                         case NUM_TEAM_1: team1_score = 1; break;
1784                         case NUM_TEAM_2: team2_score = 1; break;
1785                         case NUM_TEAM_3: team3_score = 1; break;
1786                         case NUM_TEAM_4: team4_score = 1; break;
1787                 }
1788         });
1789
1790         ClearWinners();
1791         if(team1_score + team2_score + team3_score + team4_score == 0)
1792         {
1793                 checkrules_equality = true;
1794                 return WINNING_YES;
1795         }
1796         else if(team1_score + team2_score + team3_score + team4_score == 1)
1797         {
1798                 float t, i;
1799                 if(team1_score)
1800                         t = NUM_TEAM_1;
1801                 else if(team2_score)
1802                         t = NUM_TEAM_2;
1803                 else if(team3_score)
1804                         t = NUM_TEAM_3;
1805                 else // if(team4_score)
1806                         t = NUM_TEAM_4;
1807                 CheckAllowedTeams(NULL);
1808                 for(i = 0; i < MAX_TEAMSCORE; ++i)
1809                 {
1810                         if(t != NUM_TEAM_1) if(c1 >= 0) TeamScore_AddToTeam(NUM_TEAM_1, i, -1000);
1811                         if(t != NUM_TEAM_2) if(c2 >= 0) TeamScore_AddToTeam(NUM_TEAM_2, i, -1000);
1812                         if(t != NUM_TEAM_3) if(c3 >= 0) TeamScore_AddToTeam(NUM_TEAM_3, i, -1000);
1813                         if(t != NUM_TEAM_4) if(c4 >= 0) TeamScore_AddToTeam(NUM_TEAM_4, i, -1000);
1814                 }
1815
1816                 AddWinners(team, t);
1817                 return WINNING_YES;
1818         }
1819         else
1820                 return WINNING_NO;
1821 }
1822
1823 /*
1824 ============
1825 CheckRules_World
1826
1827 Exit deathmatch games upon conditions
1828 ============
1829 */
1830 void CheckRules_World()
1831 {
1832         float timelimit;
1833         float fraglimit;
1834         float leadlimit;
1835
1836         VoteThink();
1837         MapVote_Think();
1838
1839         SetDefaultAlpha();
1840
1841         if (gameover)   // someone else quit the game already
1842         {
1843                 if(player_count == 0) // Nobody there? Then let's go to the next map
1844                         MapVote_Start();
1845                         // this will actually check the player count in the next frame
1846                         // again, but this shouldn't hurt
1847                 return;
1848         }
1849
1850         timelimit = autocvar_timelimit * 60;
1851         fraglimit = autocvar_fraglimit;
1852         leadlimit = autocvar_leadlimit;
1853
1854         if(warmup_stage || time <= game_starttime) // NOTE: this is <= to prevent problems in the very tic where the game starts
1855         {
1856                 if(timelimit > 0)
1857                         timelimit = 0; // timelimit is not made for warmup
1858                 if(fraglimit > 0)
1859                         fraglimit = 0; // no fraglimit for now
1860                 leadlimit = 0; // no leadlimit for now
1861         }
1862
1863         if(timelimit > 0)
1864         {
1865                 timelimit += game_starttime;
1866         }
1867         else if (timelimit < 0)
1868         {
1869                 // endmatch
1870                 NextLevel();
1871                 return;
1872         }
1873
1874         float wantovertime;
1875         wantovertime = 0;
1876
1877         if(timelimit > game_starttime)
1878                 game_completion_ratio = (time - game_starttime) / (timelimit - game_starttime);
1879         else
1880                 game_completion_ratio = 0;
1881
1882         if(checkrules_suddendeathend)
1883         {
1884                 if(!checkrules_suddendeathwarning)
1885                 {
1886                         checkrules_suddendeathwarning = true;
1887                         if(g_race && !g_race_qualifying)
1888                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_RACE_FINISHLAP);
1889                         else
1890                                 Send_Notification(NOTIF_ALL, NULL, MSG_CENTER, CENTER_OVERTIME_FRAG);
1891                 }
1892         }
1893         else
1894         {
1895                 if (timelimit && time >= timelimit)
1896                 {
1897                         if(g_race && (g_race_qualifying == 2) && timelimit > 0)
1898                         {
1899                                 float totalplayers;
1900                                 float playerswithlaps;
1901                                 float readyplayers;
1902                                 totalplayers = playerswithlaps = readyplayers = 0;
1903                                 FOREACH_CLIENT(IS_PLAYER(it), LAMBDA(
1904                                         ++totalplayers;
1905                                         if(PlayerScore_Add(it, SP_RACE_FASTEST, 0))
1906                                                 ++playerswithlaps;
1907                                         if(it.ready)
1908                                                 ++readyplayers;
1909                                 ));
1910
1911                                 // at least 2 of the players have completed a lap: start the RACE
1912                                 // otherwise, the players should end the qualifying on their own
1913                                 if(readyplayers || playerswithlaps >= 2)
1914                                 {
1915                                         checkrules_suddendeathend = 0;
1916                                         ReadyRestart(); // go to race
1917                                         return;
1918                                 }
1919                                 else
1920                                         wantovertime |= InitiateSuddenDeath();
1921                         }
1922                         else
1923                                 wantovertime |= InitiateSuddenDeath();
1924                 }
1925         }
1926
1927         if (checkrules_suddendeathend && time >= checkrules_suddendeathend)
1928         {
1929                 NextLevel();
1930                 return;
1931         }
1932
1933         int checkrules_status = WinningCondition_RanOutOfSpawns();
1934         if(checkrules_status == WINNING_YES)
1935                 bprint("Hey! Someone ran out of spawns!\n");
1936         else if(MUTATOR_CALLHOOK(CheckRules_World, checkrules_status, timelimit, fraglimit))
1937                 checkrules_status = M_ARGV(0, float);
1938         else
1939                 checkrules_status = WinningCondition_Scores(fraglimit, leadlimit);
1940
1941         if(checkrules_status == WINNING_STARTSUDDENDEATHOVERTIME)
1942         {
1943                 checkrules_status = WINNING_NEVER;
1944                 checkrules_overtimesadded = -1;
1945                 wantovertime |= InitiateSuddenDeath();
1946         }
1947
1948         if(checkrules_status == WINNING_NEVER)
1949                 // equality cases! Nobody wins if the overtime ends in a draw.
1950                 ClearWinners();
1951
1952         if(wantovertime)
1953         {
1954                 if(checkrules_status == WINNING_NEVER)
1955                         InitiateOvertime();
1956                 else
1957                         checkrules_status = WINNING_YES;
1958         }
1959
1960         if(checkrules_suddendeathend)
1961                 if(checkrules_status != WINNING_NEVER || time >= checkrules_suddendeathend)
1962                         checkrules_status = WINNING_YES;
1963
1964         if(checkrules_status == WINNING_YES)
1965         {
1966                 //print("WINNING\n");
1967                 NextLevel();
1968         }
1969 }
1970
1971 string GotoMap(string m)
1972 {
1973         m = GameTypeVote_MapInfo_FixName(m);
1974         if (!m)
1975                 return "The map you suggested is not available on this server.";
1976         if (!autocvar_sv_vote_gametype)
1977         if(!MapInfo_CheckMap(m))
1978                 return "The map you suggested does not support the current game mode.";
1979         cvar_set("nextmap", m);
1980         cvar_set("timelimit", "-1");
1981         if(mapvote_initialized || alreadychangedlevel)
1982         {
1983                 if(DoNextMapOverride(0))
1984                         return "Map switch initiated.";
1985                 else
1986                         return "Hm... no. For some reason I like THIS map more.";
1987         }
1988         else
1989                 return "Map switch will happen after scoreboard.";
1990 }
1991
1992 bool autocvar_sv_gameplayfix_multiplethinksperframe;
1993 void RunThink(entity this)
1994 {
1995         // don't let things stay in the past.
1996         // it is possible to start that way by a trigger with a local time.
1997         if(this.nextthink <= 0 || this.nextthink > time + frametime)
1998                 return;
1999
2000         float oldtime = time; // do we need to save this?
2001
2002         for (int iterations = 0; iterations < 128 && !wasfreed(this); iterations++)
2003         {
2004                 time = max(oldtime, this.nextthink);
2005                 this.nextthink = 0;
2006
2007                 if(getthink(this))
2008                         getthink(this)(this);
2009                 // mods often set nextthink to time to cause a think every frame,
2010                 // we don't want to loop in that case, so exit if the new nextthink is
2011                 // <= the time the qc was told, also exit if it is past the end of the
2012                 // frame
2013                 if(this.nextthink <= time || this.nextthink > oldtime + frametime || !autocvar_sv_gameplayfix_multiplethinksperframe)
2014                         break;
2015         }
2016
2017         time = oldtime;
2018 }
2019
2020 bool autocvar_sv_freezenonclients;
2021 bool autocvar_sv_gameplayfix_delayprojectiles;
2022 void Physics_Frame()
2023 {
2024         if(autocvar_sv_freezenonclients)
2025                 return;
2026
2027         FOREACH_ENTITY_FLOAT(pure_data, false,
2028         {
2029                 if(IS_CLIENT(it) || it.classname == "" || it.move_movetype == MOVETYPE_PUSH || it.move_movetype == MOVETYPE_FAKEPUSH || it.move_movetype == MOVETYPE_PHYSICS)
2030                         continue;
2031
2032                 set_movetype(it, it.move_movetype);
2033
2034                 if(it.move_movetype == MOVETYPE_NONE)
2035                         continue;
2036
2037                 if(it.move_qcphysics)
2038                         Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2039
2040                 if(it.movetype >= MOVETYPE_USER_FIRST && it.movetype <= MOVETYPE_USER_LAST) // these cases have no think handling
2041                 {
2042                         // handle thinking here
2043                         if (getthink(it) && it.nextthink > 0 && it.nextthink <= time + frametime)
2044                                 RunThink(it);
2045                 }
2046         });
2047
2048         if(autocvar_sv_gameplayfix_delayprojectiles >= 0)
2049                 return;
2050
2051         FOREACH_ENTITY_FLOAT(move_qcphysics, true,
2052         {
2053                 if(IS_CLIENT(it) || is_pure(it) || it.classname == "" || it.move_movetype == MOVETYPE_NONE)
2054                         continue;
2055                 Movetype_Physics_NoMatchTicrate(it, PHYS_INPUT_TIMELENGTH, false);
2056         });
2057 }
2058
2059 void systems_update();
2060 void EndFrame()
2061 {
2062         anticheat_endframe();
2063
2064         Physics_Frame();
2065
2066         FOREACH_CLIENT(IS_REAL_CLIENT(it), {
2067                 entity e = IS_SPEC(it) ? it.enemy : it;
2068                 if (e.typehitsound) {
2069                         it.typehit_time = time;
2070                 } else if (e.damage_dealt) {
2071                         it.hit_time = time;
2072                         it.damage_dealt_total += ceil(e.damage_dealt);
2073                 }
2074         });
2075         // add 1 frametime because after this, engine SV_Physics
2076         // increases time by a frametime and then networks the frame
2077         // add another frametime because client shows everything with
2078         // 1 frame of lag (cl_nolerp 0). The last +1 however should not be
2079         // needed!
2080         float altime = time + frametime * (1 + autocvar_g_antilag_nudge);
2081         FOREACH_CLIENT(true, {
2082                 it.typehitsound = false;
2083                 it.damage_dealt = 0;
2084                 antilag_record(it, CS(it), altime);
2085         });
2086         IL_EACH(g_monsters, true,
2087         {
2088                 antilag_record(it, it, altime);
2089         });
2090         FOREACH_CLIENT(PS(it), {
2091                 PlayerState s = PS(it);
2092                 s.ps_push(s, it);
2093         });
2094         systems_update();
2095         IL_ENDFRAME();
2096 }
2097
2098
2099 /*
2100  * RedirectionThink:
2101  * returns true if redirecting
2102  */
2103 float redirection_timeout;
2104 float redirection_nextthink;
2105 float RedirectionThink()
2106 {
2107         float clients_found;
2108
2109         if(redirection_target == "")
2110                 return false;
2111
2112         if(!redirection_timeout)
2113         {
2114                 cvar_set("sv_public", "-2");
2115                 redirection_timeout = time + 0.6; // this will only try twice... should be able to keep more clients
2116                 if(redirection_target == "self")
2117                         bprint("^3SERVER NOTICE:^7 restarting the server\n");
2118                 else
2119                         bprint("^3SERVER NOTICE:^7 redirecting everyone to ", redirection_target, "\n");
2120         }
2121
2122         if(time < redirection_nextthink)
2123                 return true;
2124
2125         redirection_nextthink = time + 1;
2126
2127         clients_found = 0;
2128         FOREACH_CLIENT(IS_REAL_CLIENT(it), LAMBDA(
2129                 // TODO add timer
2130                 LOG_INFO("Redirecting: sending connect command to ", it.netname, "\n");
2131                 if(redirection_target == "self")
2132                         stuffcmd(it, "\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " reconnect\n");
2133                 else
2134                         stuffcmd(it, strcat("\ndisconnect; defer ", ftos(autocvar_quit_and_redirect_timer), " \"connect ", redirection_target, "\"\n"));
2135                 ++clients_found;
2136         ));
2137
2138         LOG_INFO("Redirecting: ", ftos(clients_found), " clients left.\n");
2139
2140         if(time > redirection_timeout || clients_found == 0)
2141                 localcmd("\nwait; wait; wait; quit\n");
2142
2143         return true;
2144 }
2145
2146 void TargetMusic_RestoreGame();
2147 void RestoreGame()
2148 {
2149         // Loaded from a save game
2150         // some things then break, so let's work around them...
2151
2152         // Progs DB (capture records)
2153         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
2154
2155         // Mapinfo
2156         MapInfo_Shutdown();
2157         MapInfo_Enumerate();
2158         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
2159         WeaponStats_Init();
2160
2161         TargetMusic_RestoreGame();
2162 }
2163
2164 void Shutdown()
2165 {
2166         gameover = 2;
2167
2168         if(world_initialized > 0)
2169         {
2170                 world_initialized = 0;
2171                 LOG_TRACE("Saving persistent data...");
2172                 Ban_SaveBans();
2173
2174                 // playerstats with unfinished match
2175                 PlayerStats_GameReport(false);
2176
2177                 if(!cheatcount_total)
2178                 {
2179                         if(autocvar_sv_db_saveasdump)
2180                                 db_dump(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2181                         else
2182                                 db_save(ServerProgsDB, strcat("server.db", autocvar_sessionid));
2183                 }
2184                 if(autocvar_developer)
2185                 {
2186                         if(autocvar_sv_db_saveasdump)
2187                                 db_dump(TemporaryDB, "server-temp.db");
2188                         else
2189                                 db_save(TemporaryDB, "server-temp.db");
2190                 }
2191                 CheatShutdown(); // must be after cheatcount check
2192                 db_close(ServerProgsDB);
2193                 db_close(TemporaryDB);
2194                 LOG_TRACE("Saving persistent data... done!");
2195                 // tell the bot system the game is ending now
2196                 bot_endgame();
2197
2198                 WeaponStats_Shutdown();
2199                 MapInfo_Shutdown();
2200         }
2201         else if(world_initialized == 0)
2202         {
2203                 LOG_INFO("NOTE: crashed before even initializing the world, not saving persistent data\n");
2204         }
2205         else
2206         {
2207                 __init_dedicated_server_shutdown();
2208         }
2209 }