]> git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/g_world.qc
Some more defs.qh cleanup, update gameplay hash (again)
[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 <server/g_damage.qh>
16 #include "ipban.qh"
17 #include "mapvoting.qh"
18 #include <server/mutators/_mod.qh>
19 #include "race.qh"
20 #include "scores.qh"
21 #include "scores_rules.qh"
22 #include "spawnpoints.qh"
23 #include "teamplay.qh"
24 #include "weapons/weaponstats.qh"
25 #include "../common/constants.qh"
26 #include <common/net_linked.qh>
27 #include "../common/deathtypes/all.qh"
28 #include <common/gamemodes/_mod.qh>
29 #include "../common/gamemodes/sv_rules.qh"
30 #include "../common/mapinfo.qh"
31 #include "../common/monsters/_mod.qh"
32 #include "../common/monsters/sv_monsters.qh"
33 #include "../common/vehicles/all.qh"
34 #include "../common/notifications/all.qh"
35 #include "../common/physics/player.qh"
36 #include "../common/playerstats.qh"
37 #include "../common/stats.qh"
38 #include "../common/teams.qh"
39 #include "../common/mapobjects/trigger/secret.qh"
40 #include "../common/mapobjects/target/music.qh"
41 #include "../common/util.qh"
42 #include "../common/items/_mod.qh"
43 #include <common/weapons/_all.qh>
44 #include "../common/state.qh"
45
46 const float LATENCY_THINKRATE = 10;
47 .float latency_sum;
48 .float latency_cnt;
49 .float latency_time;
50 entity pingplreport;
51 void PingPLReport_Think(entity this)
52 {
53         float delta;
54         entity e;
55
56         delta = 3 / maxclients;
57         if(delta < sys_frametime)
58                 delta = 0;
59         this.nextthink = time + delta;
60
61         e = edict_num(this.cnt + 1);
62         if(IS_CLIENT(e) && IS_REAL_CLIENT(e))
63         {
64                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
65                 WriteByte(MSG_BROADCAST, this.cnt);
66                 WriteShort(MSG_BROADCAST, bound(1, CS(e).ping, 65535));
67                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_packetloss * 255), 255));
68                 WriteByte(MSG_BROADCAST, min(ceil(CS(e).ping_movementloss * 255), 255));
69
70                 // record latency times for clients throughout the match so we can report it to playerstats
71                 if(time > (CS(e).latency_time + LATENCY_THINKRATE))
72                 {
73                         CS(e).latency_sum += CS(e).ping;
74                         CS(e).latency_cnt += 1;
75                         CS(e).latency_time = time;
76                         //print("sum: ", ftos(CS(e).latency_sum), ", cnt: ", ftos(CS(e).latency_cnt), ", avg: ", ftos(CS(e).latency_sum / CS(e).latency_cnt), ".\n");
77                 }
78         }
79         else
80         {
81                 WriteHeader(MSG_BROADCAST, TE_CSQC_PINGPLREPORT);
82                 WriteByte(MSG_BROADCAST, this.cnt);
83                 WriteShort(MSG_BROADCAST, 0);
84                 WriteByte(MSG_BROADCAST, 0);
85                 WriteByte(MSG_BROADCAST, 0);
86         }
87         this.cnt = (this.cnt + 1) % maxclients;
88 }
89 void PingPLReport_Spawn()
90 {
91         pingplreport = new_pure(pingplreport);
92         setthink(pingplreport, PingPLReport_Think);
93         pingplreport.nextthink = time;
94 }
95
96 const float SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS = 1;
97 string redirection_target;
98 float world_initialized;
99
100 void SetDefaultAlpha()
101 {
102         if (!MUTATOR_CALLHOOK(SetDefaultAlpha))
103         {
104                 default_player_alpha = autocvar_g_player_alpha;
105                 if(default_player_alpha == 0)
106                         default_player_alpha = 1;
107                 default_weapon_alpha = default_player_alpha;
108         }
109 }
110
111 void GotoFirstMap(entity this)
112 {
113         float n;
114         if(autocvar__sv_init)
115         {
116                 // cvar_set("_sv_init", "0");
117                 // we do NOT set this to 0 any more, so someone "accidentally" changing
118                 // to this "init" map on a dedicated server will cause no permanent
119                 // harm
120                 if(autocvar_g_maplist_shuffle)
121                         ShuffleMaplist();
122                 n = tokenizebyseparator(autocvar_g_maplist, " ");
123                 cvar_set("g_maplist_index", ftos(n - 1)); // jump to map 0 in GotoNextMap
124
125                 MapInfo_Enumerate();
126                 MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
127
128                 if(!DoNextMapOverride(1))
129                         GotoNextMap(1);
130
131                 return;
132         }
133
134         if(time < 5)
135         {
136                 this.nextthink = time;
137         }
138         else
139         {
140                 this.nextthink = time + 1;
141                 LOG_INFO("Waiting for _sv_init being set to 1 by initialization scripts...");
142         }
143 }
144
145 void cvar_changes_init()
146 {
147         float h;
148         string k, v, d;
149         float n, i, adding, pureadding;
150
151         strfree(cvar_changes);
152         strfree(cvar_purechanges);
153         cvar_purechanges_count = 0;
154
155         h = buf_create();
156         buf_cvarlist(h, "", "_"); // exclude all _ cvars as they are temporary
157         n = buf_getsize(h);
158
159         adding = true;
160         pureadding = true;
161
162         for(i = 0; i < n; ++i)
163         {
164                 k = bufstr_get(h, i);
165
166 #define BADPREFIX(p) if(substring(k, 0, strlen(p)) == p) continue
167 #define BADPRESUFFIX(p,s) if(substring(k, 0, strlen(p)) == p && substring(k, -strlen(s), -1) == s) continue
168 #define BADCVAR(p) if(k == p) continue
169
170                 // general excludes and namespaces for server admin used cvars
171                 BADPREFIX("help_"); // PN's server has this listed as changed, let's not rat him out for THAT
172
173                 // internal
174                 BADPREFIX("csqc_");
175                 BADPREFIX("cvar_check_");
176                 BADCVAR("gamecfg");
177                 BADCVAR("g_configversion");
178                 BADCVAR("halflifebsp");
179                 BADCVAR("sv_mapformat_is_quake2");
180                 BADCVAR("sv_mapformat_is_quake3");
181                 BADPREFIX("sv_world");
182
183                 // client
184                 BADPREFIX("chase_");
185                 BADPREFIX("cl_");
186                 BADPREFIX("con_");
187                 BADPREFIX("scoreboard_");
188                 BADPREFIX("g_campaign");
189                 BADPREFIX("g_waypointsprite_");
190                 BADPREFIX("gl_");
191                 BADPREFIX("joy");
192                 BADPREFIX("hud_");
193                 BADPREFIX("m_");
194                 BADPREFIX("menu_");
195                 BADPREFIX("net_slist_");
196                 BADPREFIX("r_");
197                 BADPREFIX("sbar_");
198                 BADPREFIX("scr_");
199                 BADPREFIX("snd_");
200                 BADPREFIX("show");
201                 BADPREFIX("sensitivity");
202                 BADPREFIX("userbind");
203                 BADPREFIX("v_");
204                 BADPREFIX("vid_");
205                 BADPREFIX("crosshair");
206                 BADCVAR("mod_q3bsp_lightmapmergepower");
207                 BADCVAR("mod_q3bsp_nolightmaps");
208                 BADCVAR("fov");
209                 BADCVAR("mastervolume");
210                 BADCVAR("volume");
211                 BADCVAR("bgmvolume");
212                 BADCVAR("in_pitch_min");
213                 BADCVAR("in_pitch_max");
214
215                 // private
216                 BADCVAR("developer");
217                 BADCVAR("log_dest_udp");
218                 BADCVAR("net_address");
219                 BADCVAR("net_address_ipv6");
220                 BADCVAR("port");
221                 BADCVAR("savedgamecfg");
222                 BADCVAR("serverconfig");
223                 BADCVAR("sv_autoscreenshot");
224                 BADCVAR("sv_heartbeatperiod");
225                 BADCVAR("sv_vote_master_password");
226                 BADCVAR("sys_colortranslation");
227                 BADCVAR("sys_specialcharactertranslation");
228                 BADCVAR("timeformat");
229                 BADCVAR("timestamps");
230                 BADCVAR("g_require_stats");
231                 BADPREFIX("developer_");
232                 BADPREFIX("g_ban_");
233                 BADPREFIX("g_banned_list");
234                 BADPREFIX("g_require_stats_");
235                 BADPREFIX("g_chat_flood_");
236                 BADPREFIX("g_ghost_items");
237                 BADPREFIX("g_playerstats_");
238                 BADPREFIX("g_voice_flood_");
239                 BADPREFIX("log_file");
240                 BADPREFIX("quit_");
241                 BADPREFIX("rcon_");
242                 BADPREFIX("sv_allowdownloads");
243                 BADPREFIX("sv_autodemo");
244                 BADPREFIX("sv_curl_");
245                 BADPREFIX("sv_eventlog");
246                 BADPREFIX("sv_logscores_");
247                 BADPREFIX("sv_master");
248                 BADPREFIX("sv_weaponstats_");
249                 BADPREFIX("sv_waypointsprite_");
250                 BADCVAR("rescan_pending");
251
252                 // these can contain player IDs, so better hide
253                 BADPREFIX("g_forced_team_");
254                 BADCVAR("sv_muteban_list");
255                 BADCVAR("sv_voteban_list");
256                 BADCVAR("sv_allow_customplayermodels_idlist");
257                 BADCVAR("sv_allow_customplayermodels_speciallist");
258
259                 // mapinfo
260                 BADCVAR("fraglimit");
261                 BADCVAR("g_arena");
262                 BADCVAR("g_assault");
263                 BADCVAR("g_ca");
264                 BADCVAR("g_ca_teams");
265                 BADCVAR("g_conquest");
266                 BADCVAR("g_conquest_teams");
267                 BADCVAR("g_ctf");
268                 BADCVAR("g_cts");
269                 BADCVAR("g_dotc");
270                 BADCVAR("g_dm");
271                 BADCVAR("g_domination");
272                 BADCVAR("g_domination_default_teams");
273                 BADCVAR("g_duel");
274                 BADCVAR("g_duel_not_dm_maps");
275                 BADCVAR("g_freezetag");
276                 BADCVAR("g_freezetag_teams");
277                 BADCVAR("g_invasion_teams");
278                 BADCVAR("g_invasion_type");
279                 BADCVAR("g_jailbreak");
280                 BADCVAR("g_jailbreak_teams");
281                 BADCVAR("g_keepaway");
282                 BADCVAR("g_keyhunt");
283                 BADCVAR("g_keyhunt_teams");
284                 BADCVAR("g_lms");
285                 BADCVAR("g_nexball");
286                 BADCVAR("g_onslaught");
287                 BADCVAR("g_race");
288                 BADCVAR("g_race_laps_limit");
289                 BADCVAR("g_race_qualifying_timelimit");
290                 BADCVAR("g_race_qualifying_timelimit_override");
291                 BADCVAR("g_runematch");
292                 BADCVAR("g_shootfromeye");
293                 BADCVAR("g_snafu");
294                 BADCVAR("g_survival");
295                 BADCVAR("g_survival_not_dm_maps");
296                 BADCVAR("g_tdm");
297                 BADCVAR("g_tdm_on_dm_maps");
298                 BADCVAR("g_tdm_teams");
299                 BADCVAR("g_vip");
300                 BADCVAR("leadlimit");
301                 BADCVAR("nextmap");
302                 BADCVAR("teamplay");
303                 BADCVAR("timelimit");
304                 BADCVAR("g_mapinfo_settemp_acl");
305                 BADCVAR("g_mapinfo_ignore_warnings");
306                 BADCVAR("g_maplist_ignore_sizes");
307                 BADCVAR("g_maplist_sizes_count_bots");
308
309                 // long
310                 BADCVAR("hostname");
311                 BADCVAR("g_maplist");
312                 BADCVAR("g_maplist_mostrecent");
313                 BADCVAR("sv_motd");
314
315                 v = cvar_string(k);
316                 d = cvar_defstring(k);
317                 if(v == d)
318                         continue;
319
320                 if(adding)
321                 {
322                         cvar_changes = strcat(cvar_changes, k, " \"", v, "\" // \"", d, "\"\n");
323                         if(strlen(cvar_changes) > 16384)
324                         {
325                                 cvar_changes = "// too many settings have been changed to show them here\n";
326                                 adding = 0;
327                         }
328                 }
329
330                 // now check if the changes are actually gameplay relevant
331
332                 // does nothing gameplay relevant
333                 BADCVAR("captureleadlimit_override");
334                 BADCVAR("condump_stripcolors");
335                 BADCVAR("gameversion");
336                 BADCVAR("fs_gamedir");
337                 BADCVAR("g_allow_oldvortexbeam");
338                 BADCVAR("g_balance_kill_delay");
339                 BADCVAR("g_buffs_pickup_anyway");
340                 BADCVAR("g_buffs_randomize");
341                 BADCVAR("g_buffs_randomize_teamplay");
342                 BADCVAR("g_campcheck_distance");
343                 BADCVAR("g_chatsounds");
344                 BADCVAR("g_ca_point_leadlimit");
345                 BADCVAR("g_ca_point_limit");
346                 BADCVAR("g_ctf_captimerecord_always");
347                 BADCVAR("g_ctf_flag_glowtrails");
348                 BADCVAR("g_ctf_dynamiclights");
349                 BADCVAR("g_ctf_flag_pickup_verbosename");
350                 BADPRESUFFIX("g_ctf_flag_", "_model");
351                 BADPRESUFFIX("g_ctf_flag_", "_skin");
352                 BADCVAR("g_domination_point_leadlimit");
353                 BADCVAR("g_forced_respawn");
354                 BADCVAR("g_freezetag_point_leadlimit");
355                 BADCVAR("g_freezetag_point_limit");
356                 BADCVAR("g_glowtrails");
357                 BADCVAR("g_hats");
358                 BADCVAR("g_casings");
359                 BADCVAR("g_invasion_point_limit");
360                 BADCVAR("g_jump_grunt");
361                 BADCVAR("g_keepaway_ballcarrier_effects");
362                 BADCVAR("g_keepawayball_effects");
363                 BADCVAR("g_keyhunt_point_leadlimit");
364                 BADCVAR("g_nexball_goalleadlimit");
365                 BADCVAR("g_new_toys_autoreplace");
366                 BADCVAR("g_new_toys_use_pickupsound");
367                 BADCVAR("g_physics_predictall");
368                 BADCVAR("g_piggyback");
369                 BADCVAR("g_playerclip_collisions");
370                 BADCVAR("g_spawn_alloweffects");
371                 BADCVAR("g_tdm_point_leadlimit");
372                 BADCVAR("g_tdm_point_limit");
373                 BADCVAR("leadlimit_and_fraglimit");
374                 BADCVAR("leadlimit_override");
375                 BADCVAR("pausable");
376                 BADCVAR("sv_announcer");
377                 BADCVAR("sv_checkforpacketsduringsleep");
378                 BADCVAR("sv_damagetext");
379                 BADCVAR("sv_db_saveasdump");
380                 BADCVAR("sv_intermission_cdtrack");
381                 BADCVAR("sv_mapchange_delay");
382                 BADCVAR("sv_minigames");
383                 BADCVAR("sv_namechangetimer");
384                 BADCVAR("sv_precacheplayermodels");
385                 BADCVAR("sv_radio");
386                 BADCVAR("sv_stepheight");
387                 BADCVAR("sv_timeout");
388                 BADCVAR("sv_weapons_modeloverride");
389                 BADCVAR("w_prop_interval");
390                 BADPREFIX("chat_");
391                 BADPREFIX("crypto_");
392                 BADPREFIX("gameversion_");
393                 BADPREFIX("g_chat_");
394                 BADPREFIX("g_ctf_captimerecord_");
395                 BADPREFIX("g_hats_");
396                 BADPREFIX("g_maplist_");
397                 BADPREFIX("g_mod_");
398                 BADPREFIX("g_respawn_");
399                 BADPREFIX("net_");
400                 BADPREFIX("notification_");
401                 BADPREFIX("prvm_");
402                 BADPREFIX("skill_");
403                 BADPREFIX("sv_allow_");
404                 BADPREFIX("sv_cullentities_");
405                 BADPREFIX("sv_maxidle_");
406                 BADPREFIX("sv_minigames_");
407                 BADPREFIX("sv_radio_");
408                 BADPREFIX("sv_timeout_");
409                 BADPREFIX("sv_vote_");
410                 BADPREFIX("timelimit_");
411
412                 // allowed changes to server admins (please sync this to server.cfg)
413                 // vi commands:
414                 //   :/"impure"/,$d
415                 //   :g!,^\/\/[^ /],d
416                 //   :%s,//\([^ ]*\).*,BADCVAR("\1");,
417                 //   :%!sort
418                 // yes, this does contain some redundant stuff, don't really care
419                 BADPREFIX("bot_ai_");
420                 BADCVAR("bot_config_file");
421                 BADCVAR("bot_number");
422                 BADCVAR("bot_prefix");
423                 BADCVAR("bot_suffix");
424                 BADCVAR("capturelimit_override");
425                 BADCVAR("fraglimit_override");
426                 BADCVAR("gametype");
427                 BADCVAR("g_antilag");
428                 BADCVAR("g_balance_teams");
429                 BADCVAR("g_balance_teams_prevent_imbalance");
430                 BADCVAR("g_balance_teams_scorefactor");
431                 BADCVAR("g_ban_sync_trusted_servers");
432                 BADCVAR("g_ban_sync_uri");
433                 BADCVAR("g_buffs");
434                 BADCVAR("g_ca_teams_override");
435                 BADCVAR("g_ctf_fullbrightflags");
436                 BADCVAR("g_ctf_ignore_frags");
437                 BADCVAR("g_ctf_leaderboard");
438                 BADCVAR("g_domination_point_limit");
439                 BADCVAR("g_domination_teams_override");
440                 BADCVAR("g_freezetag_teams_override");
441                 BADCVAR("g_friendlyfire");
442                 BADCVAR("g_fullbrightitems");
443                 BADCVAR("g_fullbrightplayers");
444                 BADCVAR("g_keyhunt_point_limit");
445                 BADCVAR("g_keyhunt_teams_override");
446                 BADCVAR("g_lms_lives_override");
447                 BADCVAR("g_maplist");
448                 BADCVAR("g_maxplayers");
449                 BADCVAR("g_mirrordamage");
450                 BADCVAR("g_nexball_goallimit");
451                 BADCVAR("g_norecoil");
452                 BADCVAR("g_physics_clientselect");
453                 BADCVAR("g_pinata");
454                 BADCVAR("g_powerups");
455                 BADCVAR("g_player_brightness");
456                 BADCVAR("g_rocket_flying");
457                 BADCVAR("g_rocket_flying_disabledelays");
458                 BADCVAR("g_spawnshieldtime");
459                 BADCVAR("g_start_delay");
460                 BADCVAR("g_superspectate");
461                 BADCVAR("g_tdm_teams_override");
462                 BADCVAR("g_warmup");
463                 BADCVAR("g_weapon_stay"); BADPRESUFFIX("g_", "_weapon_stay");
464                 BADCVAR("hostname");
465                 BADCVAR("log_file");
466                 BADCVAR("maxplayers");
467                 BADCVAR("minplayers");
468                 BADCVAR("minplayers_per_team");
469                 BADCVAR("net_address");
470                 BADCVAR("port");
471                 BADCVAR("rcon_password");
472                 BADCVAR("rcon_restricted_commands");
473                 BADCVAR("rcon_restricted_password");
474                 BADCVAR("skill");
475                 BADCVAR("sv_adminnick");
476                 BADCVAR("sv_autoscreenshot");
477                 BADCVAR("sv_autotaunt");
478                 BADCVAR("sv_curl_defaulturl");
479                 BADCVAR("sv_defaultcharacter");
480                 BADCVAR("sv_defaultcharacterskin");
481                 BADCVAR("sv_defaultplayercolors");
482                 BADCVAR("sv_defaultplayermodel");
483                 BADCVAR("sv_defaultplayerskin");
484                 BADCVAR("sv_maxidle");
485                 BADCVAR("sv_maxrate");
486                 BADCVAR("sv_motd");
487                 BADCVAR("sv_public");
488                 BADCVAR("sv_ready_restart");
489                 BADCVAR("sv_status_privacy");
490                 BADCVAR("sv_taunt");
491                 BADCVAR("sv_vote_call");
492                 BADCVAR("sv_vote_commands");
493                 BADCVAR("sv_vote_majority_factor");
494                 BADCVAR("sv_vote_master");
495                 BADCVAR("sv_vote_master_commands");
496                 BADCVAR("sv_vote_master_password");
497                 BADCVAR("sv_vote_simple_majority_factor");
498                 BADCVAR("teamplay_mode");
499                 BADCVAR("timelimit_override");
500                 BADPREFIX("g_warmup_");
501                 BADPREFIX("sv_info_");
502                 BADPREFIX("sv_ready_restart_");
503
504                 // mutators that announce themselves properly to the server browser
505                 BADCVAR("g_instagib");
506                 BADCVAR("g_new_toys");
507                 BADCVAR("g_nix");
508                 BADCVAR("g_grappling_hook");
509                 BADCVAR("g_jetpack");
510
511                 // temporary for testing
512                 // TODO remove before 0.8.3 release
513                 BADCVAR("g_ca_weaponarena");
514                 BADCVAR("g_freezetag_weaponarena");
515                 BADCVAR("g_lms_weaponarena");
516                 BADCVAR("g_ctf_stalemate_time");
517
518                 if(cvar_string("g_mod_balance") == "Testing")
519                 {
520                         // (temporary) while using the Testing balance, any weapon balance cvars are allowed to be changed
521                         BADPREFIX("g_balance_");
522                 }
523
524 #undef BADPRESUFFIX
525 #undef BADPREFIX
526 #undef BADCVAR
527
528                 if(pureadding)
529                 {
530                         cvar_purechanges = strcat(cvar_purechanges, k, " \"", v, "\" // \"", d, "\"\n");
531                         if(strlen(cvar_purechanges) > 16384)
532                         {
533                                 cvar_purechanges = "// too many settings have been changed to show them here\n";
534                                 pureadding = 0;
535                         }
536                 }
537                 ++cvar_purechanges_count;
538                 // WARNING: this variable is used for the server list
539                 // NEVER dare to skip this code!
540                 // Hacks to intentionally appearing as "pure server" even though you DO have
541                 // modified settings may be punished by removal from the server list.
542                 // You can do to the variables cvar_changes and cvar_purechanges all you want,
543                 // though.
544         }
545         buf_del(h);
546         if(cvar_changes == "")
547                 cvar_changes = "// this server runs at default server settings\n";
548         else
549                 cvar_changes = strcat("// this server runs at modified server settings:\n", cvar_changes);
550         cvar_changes = strzone(cvar_changes);
551         if(cvar_purechanges == "")
552                 cvar_purechanges = "// this server runs at default gameplay settings\n";
553         else
554                 cvar_purechanges = strcat("// this server runs at modified gameplay settings:\n", cvar_purechanges);
555         cvar_purechanges = strzone(cvar_purechanges);
556 }
557
558 entity randomseed;
559 bool RandomSeed_Send(entity this, entity to, int sf)
560 {
561         WriteHeader(MSG_ENTITY, ENT_CLIENT_RANDOMSEED);
562         WriteShort(MSG_ENTITY, this.cnt);
563         return true;
564 }
565 void RandomSeed_Think(entity this)
566 {
567         this.cnt = bound(0, floor(random() * 65536), 65535);
568         this.nextthink = time + 5;
569
570         this.SendFlags |= 1;
571 }
572 void RandomSeed_Spawn()
573 {
574         randomseed = new_pure(randomseed);
575         setthink(randomseed, RandomSeed_Think);
576         Net_LinkEntity(randomseed, false, 0, RandomSeed_Send);
577
578         getthink(randomseed)(randomseed); // sets random seed and nextthink
579 }
580
581 spawnfunc(__init_dedicated_server)
582 {
583         // handler for _init/_init map (only for dedicated server initialization)
584
585         world_initialized = -1; // don't complain
586
587         delete_fn = remove_unsafely;
588
589         entity e = spawn();
590         setthink(e, GotoFirstMap);
591         e.nextthink = time; // this is usually 1 at this point
592
593         e = new(info_player_deathmatch);  // safeguard against player joining
594
595     // assign reflectively to avoid "assignment to world" warning
596     for (int i = 0, n = numentityfields(); i < n; ++i) {
597         string k = entityfieldname(i);
598         if (k == "classname") {
599             // safeguard against various stuff ;)
600             putentityfieldstring(i, this, "worldspawn");
601             break;
602         }
603     }
604
605         // needs to be done so early because of the constants they create
606         static_init();
607         static_init_late();
608         static_init_precache();
609
610         IL_PUSH(g_spawnpoints, e); // just incase
611
612         MapInfo_Enumerate();
613         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 0);
614 }
615
616 void __init_dedicated_server_shutdown() {
617         MapInfo_Shutdown();
618 }
619
620 STATIC_INIT_EARLY(maxclients)
621 {
622         maxclients = 0;
623         for (entity head = nextent(NULL); head; head = nextent(head)) {
624                 ++maxclients;
625         }
626 }
627
628 void default_delayedinit(entity this)
629 {
630         if(!scores_initialized)
631                 ScoreRules_generic();
632 }
633
634 void InitGameplayMode()
635 {
636         VoteReset();
637
638         // find out good world mins/maxs bounds, either the static bounds found by looking for solid, or the mapinfo specified bounds
639         get_mi_min_max(1);
640         // assign reflectively to avoid "assignment to world" warning
641         int done = 0; for (int i = 0, n = numentityfields(); i < n; ++i) {
642             string k = entityfieldname(i); vector v = (k == "mins") ? mi_min : (k == "maxs") ? mi_max : '0 0 0';
643             if (v) {
644             putentityfieldstring(i, world, sprintf("%v", v));
645             if (++done == 2) break;
646         }
647         }
648         // currently, NetRadiant's limit is 131072 qu for each side
649         // distance from one corner of a 131072qu cube to the opposite corner is approx. 227023 qu
650         // set the distance according to map size but don't go over the limit to avoid issues with float precision
651         // in case somebody makes extremely large maps
652         max_shot_distance = min(230000, vlen(world.maxs - world.mins));
653
654         MapInfo_LoadMapSettings(mapname);
655         GameRules_teams(false);
656
657         if (!cvar_value_issafe(world.fog))
658         {
659                 LOG_INFO("The current map contains a potentially harmful fog setting, ignored");
660                 world.fog = string_null;
661         }
662         if(MapInfo_Map_fog != "")
663         {
664                 if(MapInfo_Map_fog == "none")
665                         world.fog = string_null;
666                 else
667                         world.fog = strzone(MapInfo_Map_fog);
668         }
669         clientstuff = strzone(MapInfo_Map_clientstuff);
670
671         MapInfo_ClearTemps();
672
673         gamemode_name = MapInfo_Type_ToText(MapInfo_LoadedGametype);
674
675         cache_mutatormsg = strzone("");
676         cache_lastmutatormsg = strzone("");
677
678         InitializeEntity(NULL, default_delayedinit, INITPRIO_GAMETYPE_FALLBACK);
679 }
680
681 void Map_MarkAsRecent(string m);
682 float world_already_spawned;
683 spawnfunc(worldspawn)
684 {
685         server_is_dedicated = boolean(stof(cvar_defstring("is_dedicated")));
686
687         bool wantrestart = false;
688         {
689                 if (!server_is_dedicated)
690                 {
691                         // force unloading of server pk3 files when starting a listen server
692                         // localcmd("\nfs_rescan\n"); // FIXME: does more harm than good, has unintended side effects. What we really want is to unload temporary pk3s only
693                         // restore csqc_progname too
694                         string expect = "csprogs.dat";
695                         wantrestart = cvar_string("csqc_progname") != expect;
696                         cvar_set("csqc_progname", expect);
697                 }
698                 else
699                 {
700                         // Try to use versioned csprogs from pk3
701                         // Only ever use versioned csprogs.dat files on dedicated servers;
702                         // we need to reset csqc_progname on clients ourselves, and it's easier if the client's release name is constant
703                         string pk3csprogs = "csprogs-" WATERMARK ".dat";
704                         // This always works; fall back to it if a versioned csprogs.dat is suddenly missing
705                         string select = "csprogs.dat";
706                         if (fexists(pk3csprogs)) select = pk3csprogs;
707                         if (cvar_string("csqc_progname") != select)
708                         {
709                                 cvar_set("csqc_progname", select);
710                                 wantrestart = true;
711                         }
712                         // Check for updates on startup
713                         // We do it this way for atomicity so that connecting clients still match the server progs and don't disconnect
714                         int sentinel = fopen("progs.txt", FILE_READ);
715                         if (sentinel >= 0)
716                         {
717                                 string switchversion = fgets(sentinel);
718                                 fclose(sentinel);
719                                 if (switchversion != "" && switchversion != WATERMARK)
720                                 {
721                                         LOG_INFOF("Switching progs: " WATERMARK " -> %s", switchversion);
722                                         // if it doesn't exist, assume either:
723                                         //   a) the current program was overwritten
724                                         //   b) this is a client only update
725                                         string newprogs = sprintf("progs-%s.dat", switchversion);
726                                         if (fexists(newprogs))
727                                         {
728                                                 cvar_set("sv_progs", newprogs);
729                                                 wantrestart = true;
730                                         }
731                                         string newcsprogs = sprintf("csprogs-%s.dat", switchversion);
732                                         if (fexists(newcsprogs))
733                                         {
734                                                 cvar_set("csqc_progname", newcsprogs);
735                                                 wantrestart = true;
736                                         }
737                                 }
738                         }
739                 }
740                 if (wantrestart)
741                 {
742                         LOG_INFO("Restart requested");
743                         changelevel(mapname);
744                         // let initialization continue, shutdown depends on it
745                 }
746         }
747
748         if(world_already_spawned)
749                 error("world already spawned - you may have EXACTLY ONE worldspawn!");
750         world_already_spawned = true;
751
752         delete_fn = remove_safely; // during spawning, watch what you remove!
753
754         cvar_changes_init(); // do this very early now so it REALLY matches the server config
755
756         // needs to be done so early because of the constants they create
757         static_init();
758
759         ServerProgsDB = db_load(strcat("server.db", autocvar_sessionid));
760
761         TemporaryDB = db_create();
762
763         // 0 normal
764         lightstyle(0, "m");
765
766         // 1 FLICKER (first variety)
767         lightstyle(1, "mmnmmommommnonmmonqnmmo");
768
769         // 2 SLOW STRONG PULSE
770         lightstyle(2, "abcdefghijklmnopqrstuvwxyzyxwvutsrqponmlkjihgfedcba");
771
772         // 3 CANDLE (first variety)
773         lightstyle(3, "mmmmmaaaaammmmmaaaaaabcdefgabcdefg");
774
775         // 4 FAST STROBE
776         lightstyle(4, "mamamamamama");
777
778         // 5 GENTLE PULSE 1
779         lightstyle(5,"jklmnopqrstuvwxyzyxwvutsrqponmlkj");
780
781         // 6 FLICKER (second variety)
782         lightstyle(6, "nmonqnmomnmomomno");
783
784         // 7 CANDLE (second variety)
785         lightstyle(7, "mmmaaaabcdefgmmmmaaaammmaamm");
786
787         // 8 CANDLE (third variety)
788         lightstyle(8, "mmmaaammmaaammmabcdefaaaammmmabcdefmmmaaaa");
789
790         // 9 SLOW STROBE (fourth variety)
791         lightstyle(9, "aaaaaaaazzzzzzzz");
792
793         // 10 FLUORESCENT FLICKER
794         lightstyle(10, "mmamammmmammamamaaamammma");
795
796         // 11 SLOW PULSE NOT FADE TO BLACK
797         lightstyle(11, "abcdefghijklmnopqrrqponmlkjihgfedcba");
798
799         // styles 32-62 are assigned by the spawnfunc_light program for switchable lights
800
801         // 63 testing
802         lightstyle(63, "a");
803
804         if(autocvar_g_campaign)
805                 CampaignPreInit();
806
807         Map_MarkAsRecent(mapname);
808
809         PlayerStats_GameReport_Init(); // we need this to be initiated before InitGameplayMode
810
811         InitGameplayMode();
812         static_init_late();
813         static_init_precache();
814         readlevelcvars();
815         GrappleHookInit();
816
817         GameRules_limit_fallbacks();
818
819         if(warmup_limit == 0)
820                 warmup_limit = (autocvar_timelimit > 0) ? autocvar_timelimit * 60 : autocvar_timelimit;
821
822         player_count = 0;
823         bot_waypoints_for_items = autocvar_g_waypoints_for_items;
824         if(bot_waypoints_for_items == 1)
825                 if(this.spawnflags & SPAWNFLAG_NO_WAYPOINTS_FOR_ITEMS)
826                         bot_waypoints_for_items = 0;
827
828         WaypointSprite_Init();
829
830         GameLogInit(); // prepare everything
831         // NOTE for matchid:
832         // changing the logic generating it is okay. But:
833         // it HAS to stay <= 64 chars
834         // character set: ASCII 33-126 without the following characters: : ; ' " \ $
835         if(autocvar_sv_eventlog)
836         {
837                 string s = sprintf("%s.%s.%06d", itos(autocvar_sv_eventlog_files_counter), strftime(false, "%s"), floor(random() * 1000000));
838                 matchid = strzone(s);
839
840                 GameLogEcho(strcat(":gamestart:", GetGametype(), "_", GetMapname(), ":", s));
841                 s = ":gameinfo:mutators:LIST";
842
843                 MUTATOR_CALLHOOK(BuildMutatorsString, s);
844                 s = M_ARGV(0, string);
845
846                 // initialiation stuff, not good in the mutator system
847                 if(!autocvar_g_use_ammunition)
848                         s = strcat(s, ":no_use_ammunition");
849
850                 // initialiation stuff, not good in the mutator system
851                 if(autocvar_g_pickup_items == 0)
852                         s = strcat(s, ":no_pickup_items");
853                 if(autocvar_g_pickup_items > 0)
854                         s = strcat(s, ":pickup_items");
855
856                 // initialiation stuff, not good in the mutator system
857                 if(autocvar_g_weaponarena != "0")
858                         s = strcat(s, ":", autocvar_g_weaponarena, " arena");
859
860                 // TODO to mutator system
861                 if(autocvar_g_norecoil)
862                         s = strcat(s, ":norecoil");
863
864                 // TODO to mutator system
865                 if(autocvar_g_powerups == 0)
866                         s = strcat(s, ":no_powerups");
867                 if(autocvar_g_powerups > 0)
868                         s = strcat(s, ":powerups");
869
870                 GameLogEcho(s);
871                 GameLogEcho(":gameinfo:end");
872         }
873         else
874                 matchid = strzone(ftos(random()));
875
876         cvar_set("nextmap", "");
877
878         SetDefaultAlpha();
879
880         if(autocvar_g_campaign)
881                 CampaignPostInit();
882
883         Ban_LoadBans();
884
885         MapInfo_Enumerate();
886         MapInfo_FilterGametype(MapInfo_CurrentGametype(), MapInfo_CurrentFeatures(), MapInfo_RequiredFlags(), MapInfo_ForbiddenFlags(), 1);
887
888         if(fexists(strcat("scripts/", mapname, ".arena")))
889                 cvar_settemp("sv_q3acompat_machineshotgunswap", "1");
890
891         if(fexists(strcat("scripts/", mapname, ".defi")))
892                 cvar_settemp("sv_q3defragcompat", "1");
893
894         if(whichpack(strcat("maps/", mapname, ".cfg")) != "")
895         {
896                 int fd = fopen(strcat("maps/", mapname, ".cfg"), FILE_READ);
897                 if(fd != -1)
898                 {
899                         string s;
900                         while((s = fgets(fd)))
901                         {
902                                 int l = tokenize_console(s);
903                                 if(l < 2)
904                                         continue;
905                                 if(argv(0) == "cd")
906                                 {
907                                         string trackname = argv(2);
908                                         LOG_INFO("Found ^1UNSUPPORTED^7 cd loop command in .cfg file; put this line in mapinfo instead:");
909                                         LOG_INFO("  cdtrack ", trackname);
910                                         if (cvar_value_issafe(trackname))
911                                         {
912                                                 string newstuff = strcat(clientstuff, "cd loop \"", trackname, "\"\n");
913                                                 strcpy(clientstuff, newstuff);
914                                         }
915                                 }
916                                 else if(argv(0) == "fog")
917                                 {
918                                         LOG_INFO("Found ^1UNSUPPORTED^7 fog command in .cfg file; put this line in worldspawn in the .map/.bsp/.ent file instead:");
919                                         LOG_INFO("  \"fog\" \"", s, "\"");
920                                 }
921                                 else if(argv(0) == "set")
922                                 {
923                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
924                                         LOG_INFO("  clientsettemp_for_type all ", argv(1), " ", argv(2));
925                                 }
926                                 else if(argv(0) != "//")
927                                 {
928                                         LOG_INFO("Found ^1UNSUPPORTED^7 set command in .cfg file; put this line in mapinfo instead:");
929                                         LOG_INFO("  clientsettemp_for_type all ", argv(0), " ", argv(1));
930                                 }
931                         }
932                         fclose(fd);
933                 }
934         }
935
936         WeaponStats_Init();
937
938         Nagger_Init();
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 }