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