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