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