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