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