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