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