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