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