]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/cl_client.qc
Clean up some for() loops, also replace a few remaining cases of VHF_ISVEHICLE with...
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / cl_client.qc
1 #include "cl_client.qh"
2
3 #include "anticheat.qh"
4 #include "cl_impulse.qh"
5 #include "cl_player.qh"
6 #include "ipban.qh"
7 #include "miscfunctions.qh"
8 #include "portals.qh"
9 #include "teamplay.qh"
10 #include "playerdemo.qh"
11 #include "spawnpoints.qh"
12 #include "g_damage.qh"
13 #include "g_hook.qh"
14 #include "command/common.qh"
15 #include "cheats.qh"
16 #include "g_world.qh"
17 #include "race.qh"
18 #include "antilag.qh"
19 #include "campaign.qh"
20 #include "command/common.qh"
21
22 #include "bot/bot.qh"
23 #include "bot/navigation.qh"
24
25 #include "../common/ent_cs.qh"
26 #include <common/state.qh>
27
28 #include <common/effects/qc/globalsound.qh>
29
30 #include "../common/triggers/teleporters.qh"
31
32 #include "../common/vehicles/all.qh"
33
34 #include "weapons/hitplot.qh"
35 #include "weapons/weaponsystem.qh"
36
37 #include "../common/net_notice.qh"
38 #include "../common/physics/player.qh"
39
40 #include "../common/items/all.qc"
41
42 #include "../common/mutators/mutator/waypoints/all.qh"
43
44 #include "../common/triggers/subs.qh"
45 #include "../common/triggers/triggers.qh"
46 #include "../common/triggers/trigger/secret.qh"
47
48 #include "../common/minigames/sv_minigames.qh"
49
50 #include "../common/items/inventory.qh"
51
52 #include "../common/monsters/sv_monsters.qh"
53
54 #include "../lib/warpzone/server.qh"
55
56 STATIC_METHOD(Client, Add, void(Client this, int _team))
57 {
58     WITHSELF(this, ClientConnect());
59     TRANSMUTE(Player, this);
60     this.frame = 12; // 7
61     this.team = _team;
62     WITHSELF(this, PutClientInServer());
63 }
64
65 void PutObserverInServer(entity this);
66 void ClientDisconnect();
67
68 STATIC_METHOD(Client, Remove, void(Client this))
69 {
70     TRANSMUTE(Observer, this);
71     WITHSELF(this, PutClientInServer());
72     WITHSELF(this, ClientDisconnect());
73 }
74
75 void send_CSQC_teamnagger() {
76         WriteHeader(MSG_BROADCAST, TE_CSQC_TEAMNAGGER);
77 }
78
79 bool ClientData_Send(entity this, entity to, int sf)
80 {
81         assert(to == this.owner, return false);
82
83         entity e = to;
84         if (IS_SPEC(e)) e = e.enemy;
85
86         sf = 0;
87         if (e.race_completed)       sf |= 1; // forced scoreboard
88         if (to.spectatee_status)    sf |= 2; // spectator ent number follows
89         if (e.zoomstate)            sf |= 4; // zoomed
90         if (e.porto_v_angle_held)   sf |= 8; // angles held
91
92         WriteHeader(MSG_ENTITY, ENT_CLIENT_CLIENTDATA);
93         WriteByte(MSG_ENTITY, sf);
94
95         if (sf & 2)
96         {
97                 WriteByte(MSG_ENTITY, to.spectatee_status);
98         }
99         if (sf & 8)
100         {
101                 WriteAngle(MSG_ENTITY, e.v_angle.x);
102                 WriteAngle(MSG_ENTITY, e.v_angle.y);
103         }
104         return true;
105 }
106
107 void ClientData_Attach(entity this)
108 {
109         Net_LinkEntity(this.clientdata = new_pure(clientdata), false, 0, ClientData_Send);
110         this.clientdata.drawonlytoclient = this;
111         this.clientdata.owner = this;
112 }
113
114 void ClientData_Detach(entity this)
115 {
116         remove(this.clientdata);
117         this.clientdata = NULL;
118 }
119
120 void ClientData_Touch(entity e)
121 {
122         e.clientdata.SendFlags = 1;
123
124         // make it spectatable
125         FOREACH_CLIENT(IS_REAL_CLIENT(it) && it != e && IS_SPEC(it) && it.enemy == e, LAMBDA(it.clientdata.SendFlags = 1));
126 }
127
128 .string netname_previous;
129
130 void SetSpectatee(entity player, entity spectatee);
131
132
133 /*
134 =============
135 CheckPlayerModel
136
137 Checks if the argument string can be a valid playermodel.
138 Returns a valid one in doubt.
139 =============
140 */
141 string FallbackPlayerModel;
142 string CheckPlayerModel(string plyermodel) {
143         if(FallbackPlayerModel != cvar_defstring("_cl_playermodel"))
144         {
145                 // note: we cannot summon Don Strunzone here, some player may
146                 // still have the model string set. In case anyone manages how
147                 // to change a cvar default, we'll have a small leak here.
148                 FallbackPlayerModel = strzone(cvar_defstring("_cl_playermodel"));
149         }
150         // only in right path
151         if( substring(plyermodel,0,14) != "models/player/")
152                 return FallbackPlayerModel;
153         // only good file extensions
154         if(substring(plyermodel,-4,4) != ".zym")
155         if(substring(plyermodel,-4,4) != ".dpm")
156         if(substring(plyermodel,-4,4) != ".iqm")
157         if(substring(plyermodel,-4,4) != ".md3")
158         if(substring(plyermodel,-4,4) != ".psk")
159                 return FallbackPlayerModel;
160         // forbid the LOD models
161         if(substring(plyermodel, -9,5) == "_lod1")
162                 return FallbackPlayerModel;
163         if(substring(plyermodel, -9,5) == "_lod2")
164                 return FallbackPlayerModel;
165         if(plyermodel != strtolower(plyermodel))
166                 return FallbackPlayerModel;
167         // also, restrict to server models
168         if(autocvar_sv_servermodelsonly)
169         {
170                 if(!fexists(plyermodel))
171                         return FallbackPlayerModel;
172         }
173         return plyermodel;
174 }
175
176 void setplayermodel(entity e, string modelname)
177 {
178         precache_model(modelname);
179         _setmodel(e, modelname);
180         player_setupanimsformodel(e);
181         if(!autocvar_g_debug_globalsounds)
182                 UpdatePlayerSounds(e);
183 }
184
185 void FixPlayermodel(entity player);
186 /** putting a client as observer in the server */
187 void PutObserverInServer(entity this)
188 {
189     bool mutator_returnvalue = MUTATOR_CALLHOOK(MakePlayerObserver, this);
190         PlayerState_detach(this);
191
192         if (IS_PLAYER(this) && this.health >= 1) {
193         // despawn effect
194                 Send_Effect(EFFECT_SPAWN_NEUTRAL, this.origin, '0 0 0', 1);
195     }
196
197     {
198         entity spot = SelectSpawnPoint(this, true);
199         if (!spot) LOG_FATAL("No spawnpoints for observers?!?");
200         this.angles = spot.angles;
201         this.angles_z = 0;
202         this.fixangle = true;
203         // offset it so that the spectator spawns higher off the ground, looks better this way
204         setorigin(this, spot.origin + STAT(PL_VIEW_OFS, NULL));
205         this.prevorigin = this.origin;
206         if (IS_REAL_CLIENT(this))
207         {
208             msg_entity = this;
209             WriteByte(MSG_ONE, SVC_SETVIEW);
210             WriteEntity(MSG_ONE, this);
211         }
212         // give the spectator some space between walls for MOVETYPE_FLY_WORLDONLY
213         // so that your view doesn't go into the ceiling with MOVETYPE_FLY_WORLDONLY, previously "PL_VIEW_OFS"
214         if(!autocvar_g_debug_globalsounds)
215         {
216                 // needed for player sounds
217                 this.model = "";
218                 FixPlayermodel(this);
219         } 
220         setmodel(this, MDL_Null);
221         setsize(this, STAT(PL_CROUCH_MIN, NULL), STAT(PL_CROUCH_MAX, NULL));
222         this.view_ofs = '0 0 0';
223     }
224
225     RemoveGrapplingHook(this);
226         Portal_ClearAll(this);
227         Unfreeze(this);
228
229         if (this.alivetime)
230         {
231                 if (!warmup_stage)
232                         PS_GR_P_ADDVAL(this, PLAYERSTATS_ALIVETIME, time - this.alivetime);
233                 this.alivetime = 0;
234         }
235
236         if (this.vehicle) vehicles_exit(this.vehicle, VHEF_RELEASE);
237
238         WaypointSprite_PlayerDead(this);
239
240         if (mutator_returnvalue) {
241             // mutator prevents resetting teams+score
242         } else {
243                 this.team = -1;  // move this as it is needed to log the player spectating in eventlog
244         this.frags = FRAGS_SPECTATOR;
245         PlayerScore_Clear(this);  // clear scores when needed
246     }
247
248         if (this.killcount != FRAGS_SPECTATOR)
249         {
250                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_QUIT_SPECTATE, this.netname);
251                 if(!intermission_running)
252                 if(autocvar_g_chat_nospectators == 1 || (!(warmup_stage || gameover) && autocvar_g_chat_nospectators == 2))
253                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_CHAT_NOSPECTATORS);
254
255                 if(this.just_joined == false) {
256                         LogTeamchange(this.playerid, -1, 4);
257                 } else
258                         this.just_joined = false;
259         }
260
261         accuracy_resend(this);
262
263         this.spectatortime = time;
264         this.bot_attack = false;
265     this.hud = HUD_NORMAL;
266         TRANSMUTE(Observer, this);
267         this.iscreature = false;
268         this.teleportable = TELEPORT_SIMPLE;
269         this.damagedbycontents = false;
270         this.health = FRAGS_SPECTATOR;
271         this.takedamage = DAMAGE_NO;
272         this.solid = SOLID_NOT;
273         this.movetype = MOVETYPE_FLY_WORLDONLY; // user preference is controlled by playerprethink
274         this.flags = FL_CLIENT | FL_NOTARGET;
275         this.armorvalue = 666;
276         this.effects = 0;
277         this.armorvalue = autocvar_g_balance_armor_start;
278         this.pauserotarmor_finished = 0;
279         this.pauserothealth_finished = 0;
280         this.pauseregen_finished = 0;
281         this.damageforcescale = 0;
282         this.death_time = 0;
283         this.respawn_flags = 0;
284         this.respawn_time = 0;
285         this.stat_respawn_time = 0;
286         this.alpha = 0;
287         this.scale = 0;
288         this.fade_time = 0;
289         this.pain_frame = 0;
290         this.pain_finished = 0;
291         this.strength_finished = 0;
292         this.invincible_finished = 0;
293         this.superweapons_finished = 0;
294         this.pushltime = 0;
295         this.istypefrag = 0;
296         setthink(this, func_null);
297         this.nextthink = 0;
298         this.hook_time = 0;
299         this.deadflag = DEAD_NO;
300         this.crouch = false;
301         this.revival_time = 0;
302
303         this.items = 0;
304         this.weapons = '0 0 0';
305         this.drawonlytoclient = this;
306
307         this.weaponname = "";
308         this.weaponmodel = "";
309         for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
310         {
311                 this.weaponentities[slot] = NULL;
312         }
313         this.exteriorweaponentity = NULL;
314         this.killcount = FRAGS_SPECTATOR;
315         this.velocity = '0 0 0';
316         this.avelocity = '0 0 0';
317         this.punchangle = '0 0 0';
318         this.punchvector = '0 0 0';
319         this.oldvelocity = this.velocity;
320         this.fire_endtime = -1;
321         this.event_damage = func_null;
322 }
323
324 int player_getspecies(entity this)
325 {
326         get_model_parameters(this.model, this.skin);
327         int s = get_model_parameters_species;
328         get_model_parameters(string_null, 0);
329         if (s < 0) return SPECIES_HUMAN;
330         return s;
331 }
332
333 .float model_randomizer;
334 void FixPlayermodel(entity player)
335 {
336         string defaultmodel = "";
337         int defaultskin = 0;
338         if(autocvar_sv_defaultcharacter)
339         {
340                 if(teamplay)
341                 {
342                         string s = Static_Team_ColorName_Lower(player.team);
343                         if (s != "neutral")
344                         {
345                                 defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", s));
346                                 defaultskin = cvar(strcat("sv_defaultplayerskin_", s));
347                         }
348                 }
349
350                 if(defaultmodel == "")
351                 {
352                         defaultmodel = autocvar_sv_defaultplayermodel;
353                         defaultskin = autocvar_sv_defaultplayerskin;
354                 }
355
356                 int n = tokenize_console(defaultmodel);
357                 if(n > 0)
358                 {
359                         defaultmodel = argv(floor(n * player.model_randomizer));
360                         // However, do NOT randomize if the player-selected model is in the list.
361                         for (int i = 0; i < n; ++i)
362                                 if ((argv(i) == player.playermodel && defaultskin == stof(player.playerskin)) || argv(i) == strcat(player.playermodel, ":", player.playerskin))
363                                         defaultmodel = argv(i);
364                 }
365
366                 int i = strstrofs(defaultmodel, ":", 0);
367                 if(i >= 0)
368                 {
369                         defaultskin = stof(substring(defaultmodel, i+1, -1));
370                         defaultmodel = substring(defaultmodel, 0, i);
371                 }
372         }
373         if(autocvar_sv_defaultcharacterskin && !defaultskin)
374         {
375                 if(teamplay)
376                 {
377                         string s = Static_Team_ColorName_Lower(player.team);
378                         if (s != "neutral")
379                                 defaultskin = cvar(strcat("sv_defaultplayerskin_", s));
380                 }
381
382                 if(!defaultskin)
383                         defaultskin = autocvar_sv_defaultplayerskin;
384         }
385
386         MUTATOR_CALLHOOK(FixPlayermodel, defaultmodel, defaultskin, player);
387         defaultmodel = M_ARGV(0, string);
388         defaultskin = M_ARGV(1, int);
389
390         bool chmdl = false;
391         int oldskin;
392         if(defaultmodel != "")
393         {
394                 if (defaultmodel != player.model)
395                 {
396                         vector m1 = player.mins;
397                         vector m2 = player.maxs;
398                         setplayermodel (player, defaultmodel);
399                         setsize (player, m1, m2);
400                         chmdl = true;
401                 }
402
403                 oldskin = player.skin;
404                 player.skin = defaultskin;
405         } else {
406                 if (player.playermodel != player.model || player.playermodel == "")
407                 {
408                         player.playermodel = CheckPlayerModel(player.playermodel); // this is never "", so no endless loop
409                         vector m1 = player.mins;
410                         vector m2 = player.maxs;
411                         setplayermodel (player, player.playermodel);
412                         setsize (player, m1, m2);
413                         chmdl = true;
414                 }
415
416                 if(!autocvar_sv_defaultcharacterskin)
417                 {
418                         oldskin = player.skin;
419                         player.skin = stof(player.playerskin);
420                 }
421                 else
422                 {
423                         oldskin = player.skin;
424                         player.skin = defaultskin;
425                 }
426         }
427
428         if(chmdl || oldskin != player.skin) // model or skin has changed
429         {
430                 player.species = player_getspecies(player); // update species
431                 if(!autocvar_g_debug_globalsounds)
432                         UpdatePlayerSounds(player); // update skin sounds
433         }
434
435         if(!teamplay)
436                 if(strlen(autocvar_sv_defaultplayercolors))
437                         if(player.clientcolors != stof(autocvar_sv_defaultplayercolors))
438                                 setcolor(player, stof(autocvar_sv_defaultplayercolors));
439 }
440
441
442 /** Called when a client spawns in the server */
443 void PutClientInServer()
444 {ENGINE_EVENT();
445         if (IS_BOT_CLIENT(this)) {
446                 TRANSMUTE(Player, this);
447         } else if (IS_REAL_CLIENT(this)) {
448                 msg_entity = this;
449                 WriteByte(MSG_ONE, SVC_SETVIEW);
450                 WriteEntity(MSG_ONE, this);
451         }
452         if (gameover) {
453                 TRANSMUTE(Observer, this);
454         }
455
456         SetSpectatee(this, NULL);
457
458         // reset player keys
459         this.itemkeys = 0;
460
461         MUTATOR_CALLHOOK(PutClientInServer, this);
462
463         if (IS_OBSERVER(this)) {
464                 PutObserverInServer(this);
465         } else if (IS_PLAYER(this)) {
466                 PlayerState_attach(this);
467                 accuracy_resend(this);
468
469                 if (this.team < 0)
470                         JoinBestTeam(this, false, true);
471
472                 entity spot = SelectSpawnPoint(this, false);
473                 if (!spot) {
474                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_JOIN_NOSPAWNS);
475                         return; // spawn failed
476                 }
477
478                 TRANSMUTE(Player, this);
479                 this.wasplayer = true;
480                 this.iscreature = true;
481                 this.teleportable = TELEPORT_NORMAL;
482                 this.damagedbycontents = true;
483                 this.movetype = MOVETYPE_WALK;
484                 this.solid = SOLID_SLIDEBOX;
485                 this.dphitcontentsmask = DPCONTENTS_BODY | DPCONTENTS_SOLID;
486                 if (autocvar_g_playerclip_collisions)
487                         this.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
488                 if (IS_BOT_CLIENT(this) && autocvar_g_botclip_collisions)
489                         this.dphitcontentsmask |= DPCONTENTS_BOTCLIP;
490                 this.frags = FRAGS_PLAYER;
491                 if (INDEPENDENT_PLAYERS) MAKE_INDEPENDENT_PLAYER(this);
492                 this.flags = FL_CLIENT | FL_PICKUPITEMS;
493                 if (autocvar__notarget)
494                         this.flags |= FL_NOTARGET;
495                 this.takedamage = DAMAGE_AIM;
496                 this.effects = EF_TELEPORT_BIT | EF_RESTARTANIM_BIT;
497                 this.dmg = 2; // WTF
498
499                 if (warmup_stage) {
500                         this.ammo_shells = warmup_start_ammo_shells;
501                         this.ammo_nails = warmup_start_ammo_nails;
502                         this.ammo_rockets = warmup_start_ammo_rockets;
503                         this.ammo_cells = warmup_start_ammo_cells;
504                         this.ammo_plasma = warmup_start_ammo_plasma;
505                         this.ammo_fuel = warmup_start_ammo_fuel;
506                         this.health = warmup_start_health;
507                         this.armorvalue = warmup_start_armorvalue;
508                         this.weapons = WARMUP_START_WEAPONS;
509                 } else {
510                         this.ammo_shells = start_ammo_shells;
511                         this.ammo_nails = start_ammo_nails;
512                         this.ammo_rockets = start_ammo_rockets;
513                         this.ammo_cells = start_ammo_cells;
514                         this.ammo_plasma = start_ammo_plasma;
515                         this.ammo_fuel = start_ammo_fuel;
516                         this.health = start_health;
517                         this.armorvalue = start_armorvalue;
518                         this.weapons = start_weapons;
519                 }
520
521                 this.superweapons_finished = (this.weapons & WEPSET_SUPERWEAPONS) ? time + autocvar_g_balance_superweapons_time : 0;
522
523                 this.items = start_items;
524
525                 this.spawnshieldtime = time + autocvar_g_spawnshieldtime;
526                 this.pauserotarmor_finished = time + autocvar_g_balance_pause_armor_rot_spawn;
527                 this.pauserothealth_finished = time + autocvar_g_balance_pause_health_rot_spawn;
528                 this.pauserotfuel_finished = time + autocvar_g_balance_pause_fuel_rot_spawn;
529                 this.pauseregen_finished = time + autocvar_g_balance_pause_health_regen_spawn;
530                 // extend the pause of rotting if client was reset at the beginning of the countdown
531                 if (!autocvar_sv_ready_restart_after_countdown && time < game_starttime) { // TODO why is this cvar NOTted?
532                         float f = game_starttime - time;
533                         this.spawnshieldtime += f;
534                         this.pauserotarmor_finished += f;
535                         this.pauserothealth_finished += f;
536                         this.pauseregen_finished += f;
537                 }
538                 this.damageforcescale = 2;
539                 this.death_time = 0;
540                 this.respawn_flags = 0;
541                 this.respawn_time = 0;
542                 this.stat_respawn_time = 0;
543                 this.scale = autocvar_sv_player_scale;
544                 this.fade_time = 0;
545                 this.pain_frame = 0;
546                 this.pain_finished = 0;
547                 this.pushltime = 0;
548                 setthink(this, func_null); // players have no think function
549                 this.nextthink = 0;
550                 this.dmg_team = 0;
551                 this.ballistics_density = autocvar_g_ballistics_density_player;
552
553                 this.deadflag = DEAD_NO;
554
555                 this.angles = spot.angles;
556                 this.angles_z = 0; // never spawn tilted even if the spot says to
557                 if (IS_BOT_CLIENT(this))
558                         this.v_angle = this.angles;
559                 this.fixangle = true; // turn this way immediately
560                 this.oldvelocity = this.velocity = '0 0 0';
561                 this.avelocity = '0 0 0';
562                 this.punchangle = '0 0 0';
563                 this.punchvector = '0 0 0';
564
565                 this.strength_finished = 0;
566                 this.invincible_finished = 0;
567                 this.fire_endtime = -1;
568                 this.revival_time = 0;
569                 this.air_finished = time + 12;
570
571                 entity spawnevent = new_pure(spawnevent);
572                 spawnevent.owner = this;
573                 Net_LinkEntity(spawnevent, false, 0.5, SpawnEvent_Send);
574
575                 // Cut off any still running player sounds.
576                 stopsound(this, CH_PLAYER_SINGLE);
577
578                 this.model = "";
579                 FixPlayermodel(this);
580                 this.drawonlytoclient = NULL;
581
582                 this.crouch = false;
583                 this.view_ofs = STAT(PL_VIEW_OFS, NULL);
584                 setsize(this, STAT(PL_MIN, NULL), STAT(PL_MAX, NULL));
585                 this.spawnorigin = spot.origin;
586                 setorigin(this, spot.origin + '0 0 1' * (1 - this.mins.z - 24));
587                 // don't reset back to last position, even if new position is stuck in solid
588                 this.oldorigin = this.origin;
589                 this.prevorigin = this.origin;
590                 this.lastteleporttime = time; // prevent insane speeds due to changing origin
591                 this.conveyor = NULL; // prevent conveyors at the previous location from moving a freshly spawned player
592                 this.hud = HUD_NORMAL;
593
594                 this.event_damage = PlayerDamage;
595
596                 this.bot_attack = true;
597                 this.monster_attack = true;
598
599                 PHYS_INPUT_BUTTON_ATCK(this) = PHYS_INPUT_BUTTON_JUMP(this) = PHYS_INPUT_BUTTON_ATCK2(this) = false;
600
601                 if (this.killcount == FRAGS_SPECTATOR) {
602                         PlayerScore_Clear(this);
603                         this.killcount = 0;
604                 }
605
606                 for (int slot = 0; slot < MAX_WEAPONSLOTS; ++slot)
607                 {
608                         CL_SpawnWeaponentity(this, weaponentities[slot]);
609                 }
610                 this.alpha = default_player_alpha;
611                 this.colormod = '1 1 1' * autocvar_g_player_brightness;
612                 this.exteriorweaponentity.alpha = default_weapon_alpha;
613
614                 this.speedrunning = false;
615
616                 target_voicescript_clear(this);
617
618                 // reset fields the weapons may use
619                 FOREACH(Weapons, true, LAMBDA(
620                         it.wr_resetplayer(it, this);
621                         // reload all reloadable weapons
622                         if (it.spawnflags & WEP_FLAG_RELOADABLE) {
623                                 this.weapon_load[it.m_id] = it.reloading_ammo;
624                         }
625                 ));
626
627                 {
628                         string s = spot.target;
629                         spot.target = string_null;
630                         SUB_UseTargets(spot, this, NULL);
631                         spot.target = s;
632                 }
633
634                 Unfreeze(this);
635
636                 MUTATOR_CALLHOOK(PlayerSpawn, this, spot);
637
638                 if (autocvar_spawn_debug)
639                 {
640                         sprint(this, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
641                         remove(spot); // usefull for checking if there are spawnpoints, that let drop through the floor
642                 }
643
644                 PS(this).m_switchweapon = w_getbestweapon(this);
645                 this.cnt = -1; // W_LastWeapon will not complain
646                 PS(this).m_weapon = WEP_Null;
647                 this.weaponname = "";
648                 PS(this).m_switchingweapon = WEP_Null;
649
650                 if (!warmup_stage && !this.alivetime)
651                         this.alivetime = time;
652
653                 antilag_clear(this, CS(this));
654         }
655 }
656
657 void ClientInit_misc(entity this);
658
659 .float ebouncefactor, ebouncestop; // electro's values
660 // TODO do we need all these fields, or should we stop autodetecting runtime
661 // changes and just have a console command to update this?
662 bool ClientInit_SendEntity(entity this, entity to, int sf)
663 {
664         WriteHeader(MSG_ENTITY, _ENT_CLIENT_INIT);
665         return = true;
666         msg_entity = to;
667         // MSG_INIT replacement
668         // TODO: make easier to use
669         Registry_send_all();
670         W_PROP_reload(MSG_ONE, to);
671         ClientInit_misc(this);
672         MUTATOR_CALLHOOK(Ent_Init);
673 }
674 void ClientInit_misc(entity this)
675 {
676         int channel = MSG_ONE;
677         WriteHeader(channel, ENT_CLIENT_INIT);
678         WriteByte(channel, g_nexball_meter_period * 32);
679         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[0]));
680         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[1]));
681         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[2]));
682         WriteInt24_t(channel, compressShotOrigin(hook_shotorigin[3]));
683         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[0]));
684         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[1]));
685         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[2]));
686         WriteInt24_t(channel, compressShotOrigin(arc_shotorigin[3]));
687
688         if(sv_foginterval && world.fog != "")
689                 WriteString(channel, world.fog);
690         else
691                 WriteString(channel, "");
692         WriteByte(channel, this.count * 255.0); // g_balance_armor_blockpercent
693         WriteByte(channel, serverflags); // client has to know if it should zoom or not
694         WriteCoord(channel, autocvar_g_trueaim_minrange);
695 }
696
697 void ClientInit_CheckUpdate(entity this)
698 {
699         this.nextthink = time;
700         if(this.count != autocvar_g_balance_armor_blockpercent)
701         {
702                 this.count = autocvar_g_balance_armor_blockpercent;
703                 this.SendFlags |= 1;
704         }
705 }
706
707 void ClientInit_Spawn()
708 {
709         entity e = new_pure(clientinit);
710         setthink(e, ClientInit_CheckUpdate);
711         Net_LinkEntity(e, false, 0, ClientInit_SendEntity);
712
713         ClientInit_CheckUpdate(e);
714 }
715
716 /*
717 =============
718 SetNewParms
719 =============
720 */
721 void SetNewParms ()
722 {
723         // initialize parms for a new player
724         parm1 = -(86400 * 366);
725
726         MUTATOR_CALLHOOK(SetNewParms);
727 }
728
729 /*
730 =============
731 SetChangeParms
732 =============
733 */
734 void SetChangeParms ()
735 {ENGINE_EVENT();
736         // save parms for level change
737         parm1 = this.parm_idlesince - time;
738
739         MUTATOR_CALLHOOK(SetChangeParms);
740 }
741
742 /*
743 =============
744 DecodeLevelParms
745 =============
746 */
747 void DecodeLevelParms(entity this)
748 {
749         // load parms
750         this.parm_idlesince = parm1;
751         if (this.parm_idlesince == -(86400 * 366))
752                 this.parm_idlesince = time;
753
754         // whatever happens, allow 60 seconds of idling directly after connect for map loading
755         this.parm_idlesince = max(this.parm_idlesince, time - sv_maxidle + 60);
756
757         MUTATOR_CALLHOOK(DecodeLevelParms);
758 }
759
760 /*
761 =============
762 ClientKill
763
764 Called when a client types 'kill' in the console
765 =============
766 */
767
768 .float clientkill_nexttime;
769 void ClientKill_Now_TeamChange(entity this)
770 {
771         if(this.killindicator_teamchange == -1)
772         {
773                 JoinBestTeam( this, false, true );
774         }
775         else if(this.killindicator_teamchange == -2)
776         {
777                 if(blockSpectators)
778                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
779                 PutObserverInServer(this);
780         }
781         else
782                 WITHSELF(this, SV_ChangeTeam(this.killindicator_teamchange - 1));
783         this.killindicator_teamchange = 0;
784 }
785
786 void ClientKill_Now(entity this)
787 {
788         if(this.vehicle)
789         {
790             vehicles_exit(this.vehicle, VHEF_RELEASE);
791             if(!this.killindicator_teamchange)
792             {
793             this.vehicle_health = -1;
794             Damage(this, this, this, 1 , DEATH_KILL.m_id, this.origin, '0 0 0');
795             }
796         }
797
798         if(this.killindicator && !wasfreed(this.killindicator))
799                 remove(this.killindicator);
800
801         this.killindicator = NULL;
802
803         if(this.killindicator_teamchange)
804                 ClientKill_Now_TeamChange(this);
805
806         if(IS_PLAYER(this))
807                 Damage(this, this, this, 100000, DEATH_KILL.m_id, this.origin, '0 0 0');
808
809         // now I am sure the player IS dead
810 }
811 void KillIndicator_Think(entity this)
812 {
813         if (gameover)
814         {
815                 this.owner.killindicator = NULL;
816                 remove(this);
817                 return;
818         }
819
820         if (this.owner.alpha < 0 && !this.owner.vehicle)
821         {
822                 this.owner.killindicator = NULL;
823                 remove(this);
824                 return;
825         }
826
827         if(this.cnt <= 0)
828         {
829                 ClientKill_Now(this.owner);
830                 return;
831         }
832     else if(g_cts && this.health == 1) // health == 1 means that it's silent
833     {
834         this.nextthink = time + 1;
835         this.cnt -= 1;
836     }
837         else
838         {
839                 if(this.cnt <= 10)
840                         setmodel(this, MDL_NUM(this.cnt));
841                 if(IS_REAL_CLIENT(this.owner))
842                 {
843                         if(this.cnt <= 10)
844                                 { Send_Notification(NOTIF_ONE, this.owner, MSG_ANNCE, Announcer_PickNumber(CNT_KILL, this.cnt)); }
845                 }
846                 this.nextthink = time + 1;
847                 this.cnt -= 1;
848         }
849 }
850
851 float clientkilltime;
852 void ClientKill_TeamChange (entity this, float targetteam) // 0 = don't change, -1 = auto, -2 = spec
853 {
854         float killtime;
855         float starttime;
856
857         if (gameover)
858                 return;
859
860         killtime = autocvar_g_balance_kill_delay;
861
862         if(g_race_qualifying || g_cts)
863                 killtime = 0;
864
865     if(MUTATOR_CALLHOOK(ClientKill, this, killtime))
866         return;
867
868         this.killindicator_teamchange = targetteam;
869
870     if(!this.killindicator)
871         {
872                 if(!IS_DEAD(this))
873                 {
874                         killtime = max(killtime, this.clientkill_nexttime - time);
875                         this.clientkill_nexttime = time + killtime + autocvar_g_balance_kill_antispam;
876                 }
877
878                 if(killtime <= 0 || !IS_PLAYER(this) || IS_DEAD(this))
879                 {
880                         ClientKill_Now(this);
881                 }
882                 else
883                 {
884                         starttime = max(time, clientkilltime);
885
886                         this.killindicator = spawn();
887                         this.killindicator.owner = this;
888                         this.killindicator.scale = 0.5;
889                         setattachment(this.killindicator, this, "");
890                         setorigin(this.killindicator, '0 0 52');
891                         setthink(this.killindicator, KillIndicator_Think);
892                         this.killindicator.nextthink = starttime + (this.lip) * 0.05;
893                         clientkilltime = max(clientkilltime, this.killindicator.nextthink + 0.05);
894                         this.killindicator.cnt = ceil(killtime);
895                         this.killindicator.count = bound(0, ceil(killtime), 10);
896                         //sprint(this, strcat("^1You'll be dead in ", ftos(this.killindicator.cnt), " seconds\n"));
897
898                         FOREACH_ENTITY_ENT(enemy, this,
899                         {
900                                 if(it.classname != "body")
901                                         continue;
902                                 it.killindicator = spawn();
903                                 it.killindicator.owner = it;
904                                 it.killindicator.scale = 0.5;
905                                 setattachment(it.killindicator, it, "");
906                                 setorigin(it.killindicator, '0 0 52');
907                                 setthink(it.killindicator, KillIndicator_Think);
908                                 it.killindicator.nextthink = starttime + (it.lip) * 0.05;
909                                 clientkilltime = max(clientkilltime, it.killindicator.nextthink + 0.05);
910                                 it.killindicator.cnt = ceil(killtime);
911                         });
912                         this.lip = 0;
913                 }
914         }
915         if(this.killindicator)
916         {
917                 if(targetteam == 0) // just die
918                 {
919                         this.killindicator.colormod = '0 0 0';
920                         if(IS_REAL_CLIENT(this))
921                         if(this.killindicator.cnt > 0)
922                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_TEAMCHANGE_SUICIDE, this.killindicator.cnt);
923                 }
924                 else if(targetteam == -1) // auto
925                 {
926                         this.killindicator.colormod = '0 1 0';
927                         if(IS_REAL_CLIENT(this))
928                         if(this.killindicator.cnt > 0)
929                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_TEAMCHANGE_AUTO, this.killindicator.cnt);
930                 }
931                 else if(targetteam == -2) // spectate
932                 {
933                         this.killindicator.colormod = '0.5 0.5 0.5';
934                         if(IS_REAL_CLIENT(this))
935                         if(this.killindicator.cnt > 0)
936                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_TEAMCHANGE_SPECTATE, this.killindicator.cnt);
937                 }
938                 else
939                 {
940                         this.killindicator.colormod = Team_ColorRGB(targetteam);
941                         if(IS_REAL_CLIENT(this))
942                         if(this.killindicator.cnt > 0)
943                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, APP_TEAM_NUM(targetteam, CENTER_TEAMCHANGE), this.killindicator.cnt);
944                 }
945         }
946
947 }
948
949 void ClientKill ()
950 {ENGINE_EVENT();
951         if(gameover) return;
952         if(this.player_blocked) return;
953         if(STAT(FROZEN, this)) return;
954
955         ClientKill_TeamChange(this, 0);
956 }
957
958 void FixClientCvars(entity e)
959 {
960         // send prediction settings to the client
961         stuffcmd(e, "\nin_bindmap 0 0\n");
962         if(autocvar_g_antilag == 3) // client side hitscan
963                 stuffcmd(e, "cl_cmd settemp cl_prydoncursor_notrace 0\n");
964         if(autocvar_sv_gentle)
965                 stuffcmd(e, "cl_cmd settemp cl_gentle 1\n");
966
967         MUTATOR_CALLHOOK(FixClientCvars, e);
968 }
969
970 float PlayerInIDList(entity p, string idlist)
971 {
972         float n, i;
973         string s;
974
975         // NOTE: we do NOT check crypto_idfp_signed here, an unsigned ID is fine too for this
976         if (!p.crypto_idfp)
977                 return 0;
978
979         // this function allows abbreviated player IDs too!
980         n = tokenize_console(idlist);
981         for(i = 0; i < n; ++i)
982         {
983                 s = argv(i);
984                 if(s == substring(p.crypto_idfp, 0, strlen(s)))
985                         return 1;
986         }
987
988         return 0;
989 }
990
991 #ifdef DP_EXT_PRECONNECT
992 /*
993 =============
994 ClientPreConnect
995
996 Called once (not at each match start) when a client begins a connection to the server
997 =============
998 */
999 void ClientPreConnect ()
1000 {ENGINE_EVENT();
1001         if(autocvar_sv_eventlog)
1002         {
1003                 GameLogEcho(sprintf(":connect:%d:%d:%s",
1004                         this.playerid,
1005                         etof(this),
1006                         ((IS_REAL_CLIENT(this)) ? this.netaddress : "bot")
1007                 ));
1008         }
1009 }
1010 #endif
1011
1012 /**
1013 =============
1014 ClientConnect
1015
1016 Called when a client connects to the server
1017 =============
1018 */
1019 void ClientConnect()
1020 {ENGINE_EVENT();
1021         if (Ban_MaybeEnforceBanOnce(this)) return;
1022         assert(!IS_CLIENT(this), return);
1023         this.flags |= FL_CLIENT;
1024         assert(player_count >= 0, player_count = 0);
1025
1026 #ifdef WATERMARK
1027         Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_WATERMARK, WATERMARK);
1028 #endif
1029         this.version_nagtime = time + 10 + random() * 10;
1030         TRANSMUTE(Client, this);
1031
1032         // identify the right forced team
1033         if (autocvar_g_campaign)
1034         {
1035                 if (IS_REAL_CLIENT(this)) // only players, not bots
1036                 {
1037                         switch (autocvar_g_campaign_forceteam)
1038                         {
1039                                 case 1: this.team_forced = NUM_TEAM_1; break;
1040                                 case 2: this.team_forced = NUM_TEAM_2; break;
1041                                 case 3: this.team_forced = NUM_TEAM_3; break;
1042                                 case 4: this.team_forced = NUM_TEAM_4; break;
1043                                 default: this.team_forced = 0;
1044                         }
1045                 }
1046         }
1047         else if (PlayerInIDList(this, autocvar_g_forced_team_red))    this.team_forced = NUM_TEAM_1;
1048         else if (PlayerInIDList(this, autocvar_g_forced_team_blue))   this.team_forced = NUM_TEAM_2;
1049         else if (PlayerInIDList(this, autocvar_g_forced_team_yellow)) this.team_forced = NUM_TEAM_3;
1050         else if (PlayerInIDList(this, autocvar_g_forced_team_pink))   this.team_forced = NUM_TEAM_4;
1051         else switch (autocvar_g_forced_team_otherwise)
1052         {
1053                 default: this.team_forced = 0; break;
1054                 case "red": this.team_forced = NUM_TEAM_1; break;
1055                 case "blue": this.team_forced = NUM_TEAM_2; break;
1056                 case "yellow": this.team_forced = NUM_TEAM_3; break;
1057                 case "pink": this.team_forced = NUM_TEAM_4; break;
1058                 case "spectate":
1059                 case "spectator":
1060                         this.team_forced = -1;
1061                         break;
1062         }
1063         if (!teamplay && this.team_forced > 0) this.team_forced = 0;
1064
1065     {
1066         int id = this.playerid;
1067         this.playerid = 0; // silent
1068             JoinBestTeam(this, false, false); // if the team number is valid, keep it
1069             this.playerid = id;
1070     }
1071
1072         if (autocvar_sv_spectate || autocvar_g_campaign || this.team_forced < 0) {
1073                 TRANSMUTE(Observer, this);
1074         } else {
1075                 if (!teamplay || autocvar_g_balance_teams) {
1076                         TRANSMUTE(Player, this);
1077                         campaign_bots_may_start = true;
1078                 } else {
1079                         TRANSMUTE(Observer, this); // do it anyway
1080                 }
1081         }
1082
1083         PlayerStats_GameReport_AddEvent(sprintf("kills-%d", this.playerid));
1084
1085         // always track bots, don't ask for cl_allow_uidtracking
1086     if (IS_BOT_CLIENT(this)) PlayerStats_GameReport_AddPlayer(this);
1087
1088         if (autocvar_sv_eventlog)
1089                 GameLogEcho(strcat(":join:", ftos(this.playerid), ":", ftos(etof(this)), ":", ((IS_REAL_CLIENT(this)) ? this.netaddress : "bot"), ":", this.netname));
1090
1091         LogTeamchange(this.playerid, this.team, 1);
1092
1093         this.just_joined = true;  // stop spamming the eventlog with additional lines when the client connects
1094
1095         this.netname_previous = strzone(this.netname);
1096
1097         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, ((teamplay && IS_PLAYER(this)) ? APP_TEAM_ENT(this, INFO_JOIN_CONNECT_TEAM) : INFO_JOIN_CONNECT), this.netname);
1098
1099         stuffcmd(this, clientstuff, "\n");
1100         stuffcmd(this, "cl_particles_reloadeffects\n"); // TODO do we still need this?
1101
1102         FixClientCvars(this);
1103
1104         // get version info from player
1105         stuffcmd(this, "cmd clientversion $gameversion\n");
1106
1107         // notify about available teams
1108         if (teamplay)
1109         {
1110                 CheckAllowedTeams(this);
1111                 int t = 0;
1112                 if (c1 >= 0) t |= BIT(0);
1113                 if (c2 >= 0) t |= BIT(1);
1114                 if (c3 >= 0) t |= BIT(2);
1115                 if (c4 >= 0) t |= BIT(3);
1116                 stuffcmd(this, sprintf("set _teams_available %d\n", t));
1117         }
1118         else
1119         {
1120                 stuffcmd(this, "set _teams_available 0\n");
1121         }
1122
1123         bot_relinkplayerlist();
1124
1125         this.spectatortime = time;
1126         if (blockSpectators)
1127         {
1128                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_SPECTATE_WARNING, autocvar_g_maxplayers_spectator_blocktime);
1129         }
1130
1131         this.jointime = time;
1132         this.allowed_timeouts = autocvar_sv_timeout_number;
1133
1134         if (IS_REAL_CLIENT(this))
1135         {
1136                 if (!autocvar_g_campaign)
1137                 {
1138                         this.motd_actived_time = -1;
1139                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_MOTD, getwelcomemessage(this));
1140                 }
1141
1142                 if (g_weaponarena_weapons == WEPSET(TUBA))
1143                         stuffcmd(this, "cl_cmd settemp chase_active 1\n");
1144         }
1145
1146         if (!sv_foginterval && world.fog != "")
1147                 stuffcmd(this, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1148
1149         if (autocvar_sv_teamnagger && !(autocvar_bot_vs_human && (c3==-1 && c4==-1)))
1150                 if (!g_ca && !g_cts && !g_race) // teamnagger is currently bad for ca, race & cts
1151                         send_CSQC_teamnagger();
1152
1153         CSQCMODEL_AUTOINIT(this);
1154
1155         this.model_randomizer = random();
1156
1157         if (IS_REAL_CLIENT(this))
1158                 sv_notice_join(this);
1159
1160         FOREACH_ENTITY_FLOAT(init_for_player_needed, true, {
1161                 it.init_for_player(it, this);
1162         });
1163
1164         MUTATOR_CALLHOOK(ClientConnect, this);
1165 }
1166 /*
1167 =============
1168 ClientDisconnect
1169
1170 Called when a client disconnects from the server
1171 =============
1172 */
1173 .entity chatbubbleentity;
1174 void ReadyCount();
1175 void ClientDisconnect()
1176 {ENGINE_EVENT();
1177         assert(IS_CLIENT(this), return);
1178
1179         PlayerStats_GameReport_FinalizePlayer(this);
1180         if (this.vehicle) vehicles_exit(this.vehicle, VHEF_RELEASE);
1181         if (this.active_minigame) part_minigame(this);
1182         if (IS_PLAYER(this)) Send_Effect(EFFECT_SPAWN_NEUTRAL, this.origin, '0 0 0', 1);
1183
1184         if (autocvar_sv_eventlog)
1185                 GameLogEcho(strcat(":part:", ftos(this.playerid)));
1186
1187         Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_QUIT_DISCONNECT, this.netname);
1188
1189     MUTATOR_CALLHOOK(ClientDisconnect, this);
1190
1191         ClientState_detach(this);
1192
1193         Portal_ClearAll(this);
1194
1195         Unfreeze(this);
1196
1197         RemoveGrapplingHook(this);
1198
1199         // Here, everything has been done that requires this player to be a client.
1200
1201         this.flags &= ~FL_CLIENT;
1202
1203         if (this.chatbubbleentity) remove(this.chatbubbleentity);
1204         if (this.killindicator) remove(this.killindicator);
1205
1206         WaypointSprite_PlayerGone(this);
1207
1208         bot_relinkplayerlist();
1209
1210         if (this.netname_previous) strunzone(this.netname_previous);
1211         if (this.clientstatus) strunzone(this.clientstatus);
1212         if (this.weaponorder_byimpulse) strunzone(this.weaponorder_byimpulse);
1213         if (this.personal) remove(this.personal);
1214
1215         this.playerid = 0;
1216         ReadyCount();
1217         if (vote_called && IS_REAL_CLIENT(this)) VoteCount(false);
1218 }
1219
1220 void ChatBubbleThink(entity this)
1221 {
1222         this.nextthink = time;
1223         if ((this.owner.alpha < 0) || this.owner.chatbubbleentity != this)
1224         {
1225                 if(this.owner) // but why can that ever be NULL?
1226                         this.owner.chatbubbleentity = NULL;
1227                 remove(this);
1228                 return;
1229         }
1230
1231         this.mdl = "";
1232
1233         if ( !IS_DEAD(this.owner) && IS_PLAYER(this.owner) )
1234         {
1235                 if ( this.owner.active_minigame )
1236                         this.mdl = "models/sprites/minigame_busy.iqm";
1237                 else if (PHYS_INPUT_BUTTON_CHAT(this.owner))
1238                         this.mdl = "models/misc/chatbubble.spr";
1239         }
1240
1241         if ( this.model != this.mdl )
1242                 _setmodel(this, this.mdl);
1243
1244 }
1245
1246 void UpdateChatBubble(entity this)
1247 {
1248         if (this.alpha < 0)
1249                 return;
1250         // spawn a chatbubble entity if needed
1251         if (!this.chatbubbleentity)
1252         {
1253                 this.chatbubbleentity = new(chatbubbleentity);
1254                 this.chatbubbleentity.owner = this;
1255                 this.chatbubbleentity.exteriormodeltoclient = this;
1256                 setthink(this.chatbubbleentity, ChatBubbleThink);
1257                 this.chatbubbleentity.nextthink = time;
1258                 setmodel(this.chatbubbleentity, MDL_CHAT); // precision set below
1259                 //setorigin(this.chatbubbleentity, this.origin + '0 0 15' + this.maxs_z * '0 0 1');
1260                 setorigin(this.chatbubbleentity, '0 0 15' + this.maxs_z * '0 0 1');
1261                 setattachment(this.chatbubbleentity, this, "");  // sticks to moving player better, also conserves bandwidth
1262                 this.chatbubbleentity.mdl = this.chatbubbleentity.model;
1263                 //this.chatbubbleentity.model = "";
1264                 this.chatbubbleentity.effects = EF_LOWPRECISION;
1265         }
1266 }
1267
1268
1269 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1270 // added to the model skins
1271 /*void UpdateColorModHack()
1272 {
1273         float c;
1274         c = this.clientcolors & 15;
1275         // LordHavoc: only bothering to support white, green, red, yellow, blue
1276              if (!teamplay) this.colormod = '0 0 0';
1277         else if (c ==  0) this.colormod = '1.00 1.00 1.00';
1278         else if (c ==  3) this.colormod = '0.10 1.73 0.10';
1279         else if (c ==  4) this.colormod = '1.73 0.10 0.10';
1280         else if (c == 12) this.colormod = '1.22 1.22 0.10';
1281         else if (c == 13) this.colormod = '0.10 0.10 1.73';
1282         else this.colormod = '1 1 1';
1283 }*/
1284
1285 void respawn(entity this)
1286 {
1287         if(this.alpha >= 0 && autocvar_g_respawn_ghosts)
1288         {
1289                 this.solid = SOLID_NOT;
1290                 this.takedamage = DAMAGE_NO;
1291                 this.movetype = MOVETYPE_FLY;
1292                 this.velocity = '0 0 1' * autocvar_g_respawn_ghosts_speed;
1293                 this.avelocity = randomvec() * autocvar_g_respawn_ghosts_speed * 3 - randomvec() * autocvar_g_respawn_ghosts_speed * 3;
1294                 this.effects |= CSQCMODEL_EF_RESPAWNGHOST;
1295                 Send_Effect(EFFECT_RESPAWN_GHOST, this.origin, '0 0 0', 1);
1296                 if(autocvar_g_respawn_ghosts_maxtime)
1297                         SUB_SetFade (this, time + autocvar_g_respawn_ghosts_maxtime / 2 + random () * (autocvar_g_respawn_ghosts_maxtime - autocvar_g_respawn_ghosts_maxtime / 2), 1.5);
1298         }
1299
1300         CopyBody(this, 1);
1301
1302         this.effects |= EF_NODRAW; // prevent another CopyBody
1303         WITHSELF(this, PutClientInServer());
1304 }
1305
1306 void play_countdown(entity this, float finished, Sound samp)
1307 {
1308     TC(Sound, samp);
1309         if(IS_REAL_CLIENT(this))
1310                 if(floor(finished - time - frametime) != floor(finished - time))
1311                         if(finished - time < 6)
1312                                 sound (this, CH_INFO, samp, VOL_BASE, ATTEN_NORM);
1313 }
1314
1315 void player_powerups(entity this)
1316 {
1317         // add a way to see what the items were BEFORE all of these checks for the mutator hook
1318         int items_prev = this.items;
1319
1320         if((this.items & IT_USING_JETPACK) && !IS_DEAD(this) && !gameover)
1321                 this.modelflags |= MF_ROCKET;
1322         else
1323                 this.modelflags &= ~MF_ROCKET;
1324
1325         this.effects &= ~(EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT | EF_FLAME | EF_NODEPTHTEST);
1326
1327         if((this.alpha < 0 || IS_DEAD(this)) && !this.vehicle) // don't apply the flags if the player is gibbed
1328                 return;
1329
1330         Fire_ApplyDamage(this);
1331         Fire_ApplyEffect(this);
1332
1333         if (!g_instagib)
1334         {
1335                 if (this.items & ITEM_Strength.m_itemid)
1336                 {
1337                         play_countdown(this, this.strength_finished, SND_POWEROFF);
1338                         this.effects = this.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1339                         if (time > this.strength_finished)
1340                         {
1341                                 this.items = this.items - (this.items & ITEM_Strength.m_itemid);
1342                                 //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_POWERDOWN_STRENGTH, this.netname);
1343                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_POWERDOWN_STRENGTH);
1344                         }
1345                 }
1346                 else
1347                 {
1348                         if (time < this.strength_finished)
1349                         {
1350                                 this.items = this.items | ITEM_Strength.m_itemid;
1351                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_POWERUP_STRENGTH, this.netname);
1352                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_POWERUP_STRENGTH);
1353                         }
1354                 }
1355                 if (this.items & ITEM_Shield.m_itemid)
1356                 {
1357                         play_countdown(this, this.invincible_finished, SND_POWEROFF);
1358                         this.effects = this.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1359                         if (time > this.invincible_finished)
1360                         {
1361                                 this.items = this.items - (this.items & ITEM_Shield.m_itemid);
1362                                 //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_POWERDOWN_SHIELD, this.netname);
1363                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_POWERDOWN_SHIELD);
1364                         }
1365                 }
1366                 else
1367                 {
1368                         if (time < this.invincible_finished)
1369                         {
1370                                 this.items = this.items | ITEM_Shield.m_itemid;
1371                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_POWERUP_SHIELD, this.netname);
1372                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_POWERUP_SHIELD);
1373                         }
1374                 }
1375                 if (this.items & IT_SUPERWEAPON)
1376                 {
1377                         if (!(this.weapons & WEPSET_SUPERWEAPONS))
1378                         {
1379                                 this.superweapons_finished = 0;
1380                                 this.items = this.items - (this.items & IT_SUPERWEAPON);
1381                                 //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_SUPERWEAPON_LOST, this.netname);
1382                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_SUPERWEAPON_LOST);
1383                         }
1384                         else if (this.items & IT_UNLIMITED_SUPERWEAPONS)
1385                         {
1386                                 // don't let them run out
1387                         }
1388                         else
1389                         {
1390                                 play_countdown(this, this.superweapons_finished, SND_POWEROFF);
1391                                 if (time > this.superweapons_finished)
1392                                 {
1393                                         this.items = this.items - (this.items & IT_SUPERWEAPON);
1394                                         this.weapons &= ~WEPSET_SUPERWEAPONS;
1395                                         //Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_SUPERWEAPON_BROKEN, this.netname);
1396                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_SUPERWEAPON_BROKEN);
1397                                 }
1398                         }
1399                 }
1400                 else if(this.weapons & WEPSET_SUPERWEAPONS)
1401                 {
1402                         if (time < this.superweapons_finished || (this.items & IT_UNLIMITED_SUPERWEAPONS))
1403                         {
1404                                 this.items = this.items | IT_SUPERWEAPON;
1405                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_SUPERWEAPON_PICKUP, this.netname);
1406                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_SUPERWEAPON_PICKUP);
1407                         }
1408                         else
1409                         {
1410                                 this.superweapons_finished = 0;
1411                                 this.weapons &= ~WEPSET_SUPERWEAPONS;
1412                         }
1413                 }
1414                 else
1415                 {
1416                         this.superweapons_finished = 0;
1417                 }
1418         }
1419
1420         if(autocvar_g_nodepthtestplayers)
1421                 this.effects = this.effects | EF_NODEPTHTEST;
1422
1423         if(autocvar_g_fullbrightplayers)
1424                 this.effects = this.effects | EF_FULLBRIGHT;
1425
1426         if (time >= game_starttime)
1427         if (time < this.spawnshieldtime)
1428                 this.effects = this.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1429
1430         MUTATOR_CALLHOOK(PlayerPowerups, this, items_prev);
1431 }
1432
1433 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1434 {
1435         if(current > stable)
1436                 return current;
1437         else if(current > stable - 0.25) // when close enough, "snap"
1438                 return stable;
1439         else
1440                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1441 }
1442
1443 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1444 {
1445         if(current < stable)
1446                 return current;
1447         else if(current < stable + 0.25) // when close enough, "snap"
1448                 return stable;
1449         else
1450                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1451 }
1452
1453 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit)
1454 {
1455         if(current > rotstable)
1456         {
1457                 if(rotframetime > 0)
1458                 {
1459                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1460                         current = max(rotstable, current - rotlinear * rotframetime);
1461                 }
1462         }
1463         else if(current < regenstable)
1464         {
1465                 if(regenframetime > 0)
1466                 {
1467                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1468                         current = min(regenstable, current + regenlinear * regenframetime);
1469                 }
1470         }
1471
1472         if(current > limit)
1473                 current = limit;
1474
1475         return current;
1476 }
1477
1478 void player_regen(entity this)
1479 {
1480         float max_mod, regen_mod, rot_mod, limit_mod;
1481         max_mod = regen_mod = rot_mod = limit_mod = 1;
1482
1483         float regen_health = autocvar_g_balance_health_regen;
1484         float regen_health_linear = autocvar_g_balance_health_regenlinear;
1485         float regen_health_rot = autocvar_g_balance_health_rot;
1486         float regen_health_rotlinear = autocvar_g_balance_health_rotlinear;
1487         float regen_health_stable = autocvar_g_balance_health_regenstable;
1488         float regen_health_rotstable = autocvar_g_balance_health_rotstable;
1489         bool mutator_returnvalue = MUTATOR_CALLHOOK(PlayerRegen, this, max_mod, regen_mod, rot_mod, limit_mod, regen_health, regen_health_linear, regen_health_rot,
1490                 regen_health_rotlinear, regen_health_stable, regen_health_rotstable);
1491         max_mod = M_ARGV(1, float);
1492         regen_mod = M_ARGV(2, float);
1493         rot_mod = M_ARGV(3, float);
1494         limit_mod = M_ARGV(4, float);
1495         regen_health = M_ARGV(5, float);
1496         regen_health_linear = M_ARGV(6, float);
1497         regen_health_rot = M_ARGV(7, float);
1498         regen_health_rotlinear = M_ARGV(8, float);
1499         regen_health_stable = M_ARGV(9, float);
1500         regen_health_rotstable = M_ARGV(10, float);
1501
1502
1503         if(!mutator_returnvalue)
1504         if(!STAT(FROZEN, this))
1505         {
1506                 float mina, maxa, limith, limita;
1507                 maxa = autocvar_g_balance_armor_rotstable;
1508                 mina = autocvar_g_balance_armor_regenstable;
1509                 limith = autocvar_g_balance_health_limit;
1510                 limita = autocvar_g_balance_armor_limit;
1511
1512                 regen_health_rotstable = regen_health_rotstable * max_mod;
1513                 regen_health_stable = regen_health_stable * max_mod;
1514                 limith = limith * limit_mod;
1515                 limita = limita * limit_mod;
1516
1517                 this.armorvalue = CalcRotRegen(this.armorvalue, mina, autocvar_g_balance_armor_regen, autocvar_g_balance_armor_regenlinear, regen_mod * frametime * (time > this.pauseregen_finished), maxa, autocvar_g_balance_armor_rot, autocvar_g_balance_armor_rotlinear, rot_mod * frametime * (time > this.pauserotarmor_finished), limita);
1518                 this.health = CalcRotRegen(this.health, regen_health_stable, regen_health, regen_health_linear, regen_mod * frametime * (time > this.pauseregen_finished), regen_health_rotstable, regen_health_rot, regen_health_rotlinear, rot_mod * frametime * (time > this.pauserothealth_finished), limith);
1519         }
1520
1521         // if player rotted to death...  die!
1522         // check this outside above checks, as player may still be able to rot to death
1523         if(this.health < 1)
1524         {
1525                 if(this.vehicle)
1526                         vehicles_exit(this.vehicle, VHEF_RELEASE);
1527                 if(this.event_damage)
1528                         this.event_damage(this, this, this, 1, DEATH_ROT.m_id, this.origin, '0 0 0');
1529         }
1530
1531         if (!(this.items & IT_UNLIMITED_WEAPON_AMMO))
1532         {
1533                 float minf, maxf, limitf;
1534
1535                 maxf = autocvar_g_balance_fuel_rotstable;
1536                 minf = autocvar_g_balance_fuel_regenstable;
1537                 limitf = autocvar_g_balance_fuel_limit;
1538
1539                 this.ammo_fuel = CalcRotRegen(this.ammo_fuel, minf, autocvar_g_balance_fuel_regen, autocvar_g_balance_fuel_regenlinear, frametime * (time > this.pauseregen_finished) * ((this.items & ITEM_JetpackRegen.m_itemid) != 0), maxf, autocvar_g_balance_fuel_rot, autocvar_g_balance_fuel_rotlinear, frametime * (time > this.pauserotfuel_finished), limitf);
1540         }
1541 }
1542
1543 bool zoomstate_set;
1544 void SetZoomState(entity this, float z)
1545 {
1546         if(z != this.zoomstate)
1547         {
1548                 this.zoomstate = z;
1549                 ClientData_Touch(this);
1550         }
1551         zoomstate_set = true;
1552 }
1553
1554 void GetPressedKeys(entity this)
1555 {
1556         MUTATOR_CALLHOOK(GetPressedKeys, this);
1557         int keys = this.pressedkeys;
1558         keys = BITSET(keys, KEY_FORWARD,        this.movement.x > 0);
1559         keys = BITSET(keys, KEY_BACKWARD,       this.movement.x < 0);
1560         keys = BITSET(keys, KEY_RIGHT,          this.movement.y > 0);
1561         keys = BITSET(keys, KEY_LEFT,           this.movement.y < 0);
1562
1563         keys = BITSET(keys, KEY_JUMP,           PHYS_INPUT_BUTTON_JUMP(this));
1564         keys = BITSET(keys, KEY_CROUCH,         PHYS_INPUT_BUTTON_CROUCH(this));
1565         keys = BITSET(keys, KEY_ATCK,           PHYS_INPUT_BUTTON_ATCK(this));
1566         keys = BITSET(keys, KEY_ATCK2,          PHYS_INPUT_BUTTON_ATCK2(this));
1567         this.pressedkeys = keys;
1568 }
1569
1570 /*
1571 ======================
1572 spectate mode routines
1573 ======================
1574 */
1575
1576 void SpectateCopy(entity this, entity spectatee)
1577 {
1578     TC(Client, this); TC(Client, spectatee);
1579
1580         MUTATOR_CALLHOOK(SpectateCopy, spectatee, this);
1581         PS(this) = PS(spectatee);
1582         this.armortype = spectatee.armortype;
1583         this.armorvalue = spectatee.armorvalue;
1584         this.ammo_cells = spectatee.ammo_cells;
1585         this.ammo_plasma = spectatee.ammo_plasma;
1586         this.ammo_shells = spectatee.ammo_shells;
1587         this.ammo_nails = spectatee.ammo_nails;
1588         this.ammo_rockets = spectatee.ammo_rockets;
1589         this.ammo_fuel = spectatee.ammo_fuel;
1590         this.clip_load = spectatee.clip_load;
1591         this.clip_size = spectatee.clip_size;
1592         this.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
1593         this.health = spectatee.health;
1594         this.impulse = 0;
1595         this.items = spectatee.items;
1596         this.last_pickup = spectatee.last_pickup;
1597         this.hit_time = spectatee.hit_time;
1598         this.strength_finished = spectatee.strength_finished;
1599         this.invincible_finished = spectatee.invincible_finished;
1600         this.pressedkeys = spectatee.pressedkeys;
1601         this.weapons = spectatee.weapons;
1602         this.vortex_charge = spectatee.vortex_charge;
1603         this.vortex_chargepool_ammo = spectatee.vortex_chargepool_ammo;
1604         this.hagar_load = spectatee.hagar_load;
1605         this.arc_heat_percent = spectatee.arc_heat_percent;
1606         this.minelayer_mines = spectatee.minelayer_mines;
1607         this.punchangle = spectatee.punchangle;
1608         this.view_ofs = spectatee.view_ofs;
1609         this.velocity = spectatee.velocity;
1610         this.dmg_take = spectatee.dmg_take;
1611         this.dmg_save = spectatee.dmg_save;
1612         this.dmg_inflictor = spectatee.dmg_inflictor;
1613         this.v_angle = spectatee.v_angle;
1614         this.angles = spectatee.v_angle;
1615         STAT(FROZEN, this) = STAT(FROZEN, spectatee);
1616         this.revive_progress = spectatee.revive_progress;
1617         if(!PHYS_INPUT_BUTTON_USE(this))
1618                 this.fixangle = true;
1619         setorigin(this, spectatee.origin);
1620         setsize(this, spectatee.mins, spectatee.maxs);
1621         SetZoomState(this, spectatee.zoomstate);
1622
1623     anticheat_spectatecopy(this, spectatee);
1624         this.hud = spectatee.hud;
1625         if(spectatee.vehicle)
1626     {
1627         this.fixangle = false;
1628         //this.velocity = spectatee.vehicle.velocity;
1629         this.vehicle_health = spectatee.vehicle_health;
1630         this.vehicle_shield = spectatee.vehicle_shield;
1631         this.vehicle_energy = spectatee.vehicle_energy;
1632         this.vehicle_ammo1 = spectatee.vehicle_ammo1;
1633         this.vehicle_ammo2 = spectatee.vehicle_ammo2;
1634         this.vehicle_reload1 = spectatee.vehicle_reload1;
1635         this.vehicle_reload2 = spectatee.vehicle_reload2;
1636
1637         msg_entity = this;
1638
1639         WriteByte (MSG_ONE, SVC_SETVIEWANGLES);
1640             WriteAngle(MSG_ONE,  spectatee.v_angle.x);
1641             WriteAngle(MSG_ONE,  spectatee.v_angle.y);
1642             WriteAngle(MSG_ONE,  spectatee.v_angle.z);
1643
1644         //WriteByte (MSG_ONE, SVC_SETVIEW);
1645         //    WriteEntity(MSG_ONE, this);
1646         //makevectors(spectatee.v_angle);
1647         //setorigin(this, spectatee.origin - v_forward * 400 + v_up * 300);*/
1648     }
1649 }
1650
1651 bool SpectateUpdate(entity this)
1652 {
1653         if(!this.enemy)
1654             return false;
1655
1656         if(!IS_PLAYER(this.enemy) || this == this.enemy)
1657         {
1658                 SetSpectatee(this, NULL);
1659                 return false;
1660         }
1661
1662         SpectateCopy(this, this.enemy);
1663
1664         return true;
1665 }
1666
1667 bool SpectateSet(entity this)
1668 {
1669         if(!IS_PLAYER(this.enemy))
1670                 return false;
1671
1672         msg_entity = this;
1673         WriteByte(MSG_ONE, SVC_SETVIEW);
1674         WriteEntity(MSG_ONE, this.enemy);
1675         this.movetype = MOVETYPE_NONE;
1676         accuracy_resend(this);
1677
1678         if(!SpectateUpdate(this))
1679                 PutObserverInServer(this);
1680
1681         return true;
1682 }
1683
1684 void SetSpectatee(entity this, entity spectatee)
1685 {
1686         entity old_spectatee = this.enemy;
1687
1688         this.enemy = spectatee;
1689
1690         // WEAPONTODO
1691         // these are required to fix the spectator bug with arc
1692         if(old_spectatee && old_spectatee.arc_beam) { old_spectatee.arc_beam.SendFlags |= ARC_SF_SETTINGS; }
1693         if(this.enemy && this.enemy.arc_beam) { this.enemy.arc_beam.SendFlags |= ARC_SF_SETTINGS; }
1694 }
1695
1696 bool Spectate(entity this, entity pl)
1697 {
1698         if(MUTATOR_CALLHOOK(SpectateSet, this, pl))
1699                 return false;
1700         pl = M_ARGV(1, entity);
1701
1702         SetSpectatee(this, pl);
1703         return SpectateSet(this);
1704 }
1705
1706 bool SpectateNext(entity this)
1707 {
1708         other = find(this.enemy, classname, STR_PLAYER);
1709
1710         if (MUTATOR_CALLHOOK(SpectateNext, this, other))
1711                 other = M_ARGV(1, entity);
1712         else if (!other)
1713                 other = find(other, classname, STR_PLAYER);
1714
1715         if(other) { SetSpectatee(this, other); }
1716
1717         return SpectateSet(this);
1718 }
1719
1720 bool SpectatePrev(entity this)
1721 {
1722         // NOTE: chain order is from the highest to the lower entnum (unlike find)
1723         other = findchain(classname, STR_PLAYER);
1724         if (!other) // no player
1725                 return false;
1726
1727         entity first = other;
1728         // skip players until current spectated player
1729         if(this.enemy)
1730         while(other && other != this.enemy)
1731                 other = other.chain;
1732
1733         switch (MUTATOR_CALLHOOK(SpectatePrev, this, other, first))
1734         {
1735                 case MUT_SPECPREV_FOUND:
1736                     other = M_ARGV(1, entity);
1737                     break;
1738                 case MUT_SPECPREV_RETURN:
1739                     other = M_ARGV(1, entity);
1740                     return true;
1741                 case MUT_SPECPREV_CONTINUE:
1742                 default:
1743                 {
1744                         if(other.chain)
1745                                 other = other.chain;
1746                         else
1747                                 other = first;
1748                         break;
1749                 }
1750         }
1751
1752         SetSpectatee(this, other);
1753         return SpectateSet(this);
1754 }
1755
1756 /*
1757 =============
1758 ShowRespawnCountdown()
1759
1760 Update a respawn countdown display.
1761 =============
1762 */
1763 void ShowRespawnCountdown(entity this)
1764 {
1765         float number;
1766         if(!IS_DEAD(this)) // just respawned?
1767                 return;
1768         else
1769         {
1770                 number = ceil(this.respawn_time - time);
1771                 if(number <= 0)
1772                         return;
1773                 if(number <= this.respawn_countdown)
1774                 {
1775                         this.respawn_countdown = number - 1;
1776                         if(ceil(this.respawn_time - (time + 0.5)) == number) // only say it if it is the same number even in 0.5s; to prevent overlapping sounds
1777                                 { Send_Notification(NOTIF_ONE, this, MSG_ANNCE, Announcer_PickNumber(CNT_RESPAWN, number)); }
1778                 }
1779         }
1780 }
1781
1782 void LeaveSpectatorMode(entity this)
1783 {
1784         if(this.caplayer)
1785                 return;
1786         if(nJoinAllowed(this, this))
1787         {
1788                 if(!teamplay || autocvar_g_campaign || autocvar_g_balance_teams || (this.wasplayer && autocvar_g_changeteam_banned) || this.team_forced > 0)
1789                 {
1790                         TRANSMUTE(Player, this);
1791
1792                         if(autocvar_g_campaign || autocvar_g_balance_teams)
1793                                 { JoinBestTeam(this, false, true); }
1794
1795                         if(autocvar_g_campaign)
1796                                 { campaign_bots_may_start = true; }
1797
1798                         Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_PREVENT_JOIN);
1799
1800                         WITHSELF(this, PutClientInServer());
1801
1802                         if(IS_PLAYER(this)) { Send_Notification(NOTIF_ALL, NULL, MSG_INFO, ((teamplay && this.team != -1) ? APP_TEAM_ENT(this, INFO_JOIN_PLAY_TEAM) : INFO_JOIN_PLAY), this.netname); }
1803                 }
1804                 else
1805                         stuffcmd(this, "menu_showteamselect\n");
1806         }
1807         else
1808         {
1809                 // Player may not join because g_maxplayers is set
1810                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_JOIN_PREVENT);
1811         }
1812 }
1813
1814 /**
1815  * Determines whether the player is allowed to join. This depends on cvar
1816  * g_maxplayers, if it isn't used this function always return true, otherwise
1817  * it checks whether the number of currently playing players exceeds g_maxplayers.
1818  * @return int number of free slots for players, 0 if none
1819  */
1820 bool nJoinAllowed(entity this, entity ignore)
1821 {
1822         if(!ignore)
1823         // this is called that way when checking if anyone may be able to join (to build qcstatus)
1824         // so report 0 free slots if restricted
1825         {
1826                 if(autocvar_g_forced_team_otherwise == "spectate")
1827                         return false;
1828                 if(autocvar_g_forced_team_otherwise == "spectator")
1829                         return false;
1830         }
1831
1832         if(this.team_forced < 0)
1833                 return false; // forced spectators can never join
1834
1835         // TODO simplify this
1836         int totalClients = 0;
1837         int currentlyPlaying = 0;
1838         FOREACH_CLIENT(true, LAMBDA(
1839                 if(it != ignore)
1840                         ++totalClients;
1841                 if(IS_REAL_CLIENT(it))
1842                 if(IS_PLAYER(it) || it.caplayer)
1843                         ++currentlyPlaying;
1844         ));
1845
1846         if (!autocvar_g_maxplayers)
1847                 return maxclients - totalClients;
1848
1849         if(currentlyPlaying < autocvar_g_maxplayers)
1850                 return min(maxclients - totalClients, autocvar_g_maxplayers - currentlyPlaying);
1851
1852         return false;
1853 }
1854
1855 /**
1856  * Checks whether the client is an observer or spectator, if so, he will get kicked after
1857  * g_maxplayers_spectator_blocktime seconds
1858  */
1859 void checkSpectatorBlock(entity this)
1860 {
1861         if(IS_SPEC(this) || IS_OBSERVER(this))
1862         if(!this.caplayer)
1863         if(IS_REAL_CLIENT(this))
1864         {
1865                 if( time > (this.spectatortime + autocvar_g_maxplayers_spectator_blocktime) ) {
1866                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_QUIT_KICK_SPECTATING);
1867                         dropclient(this);
1868                 }
1869         }
1870 }
1871
1872 void PrintWelcomeMessage(entity this)
1873 {
1874         if(this.motd_actived_time == 0)
1875         {
1876                 if (autocvar_g_campaign) {
1877                         if ((IS_PLAYER(this) && PHYS_INPUT_BUTTON_INFO(this)) || (!IS_PLAYER(this))) {
1878                                 this.motd_actived_time = time;
1879                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_MOTD, campaign_message);
1880                         }
1881                 } else {
1882                         if (PHYS_INPUT_BUTTON_INFO(this)) {
1883                                 this.motd_actived_time = time;
1884                                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_MOTD, getwelcomemessage(this));
1885                         }
1886                 }
1887         }
1888         else if(this.motd_actived_time > 0) // showing MOTD or campaign message
1889         {
1890                 if (autocvar_g_campaign) {
1891                         if (PHYS_INPUT_BUTTON_INFO(this))
1892                                 this.motd_actived_time = time;
1893                         else if ((time - this.motd_actived_time > 2) && IS_PLAYER(this)) { // hide it some seconds after BUTTON_INFO has been released
1894                                 this.motd_actived_time = 0;
1895                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_MOTD);
1896                         }
1897                 } else {
1898                         if (PHYS_INPUT_BUTTON_INFO(this))
1899                                 this.motd_actived_time = time;
1900                         else if (time - this.motd_actived_time > 2) { // hide it some seconds after BUTTON_INFO has been released
1901                                 this.motd_actived_time = 0;
1902                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_MOTD);
1903                         }
1904                 }
1905         }
1906         else //if(this.motd_actived_time < 0) // just connected, motd is active
1907         {
1908                 if(PHYS_INPUT_BUTTON_INFO(this)) // BUTTON_INFO hides initial MOTD
1909                         this.motd_actived_time = -2; // wait until BUTTON_INFO gets released
1910                 else if(this.motd_actived_time == -2 || IS_PLAYER(this) || IS_SPEC(this))
1911                 {
1912                         // instanctly hide MOTD
1913                         this.motd_actived_time = 0;
1914                         Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_MOTD);
1915                 }
1916         }
1917 }
1918
1919 void ObserverThink(entity this)
1920 {
1921         if ( this.impulse )
1922         {
1923                 MinigameImpulse(this, this.impulse);
1924                 this.impulse = 0;
1925         }
1926         float prefered_movetype;
1927         if (this.flags & FL_JUMPRELEASED) {
1928                 if (PHYS_INPUT_BUTTON_JUMP(this) && !this.version_mismatch) {
1929                         this.flags &= ~FL_JUMPRELEASED;
1930                         this.flags |= FL_SPAWNING;
1931                 } else if(PHYS_INPUT_BUTTON_ATCK(this) && !this.version_mismatch) {
1932                         this.flags &= ~FL_JUMPRELEASED;
1933                         if(SpectateNext(this)) {
1934                                 TRANSMUTE(Spectator, this);
1935                         }
1936                 } else {
1937                         prefered_movetype = ((!PHYS_INPUT_BUTTON_USE(this) ? this.cvar_cl_clippedspectating : !this.cvar_cl_clippedspectating) ? MOVETYPE_FLY_WORLDONLY : MOVETYPE_NOCLIP);
1938                         if (this.movetype != prefered_movetype)
1939                                 this.movetype = prefered_movetype;
1940                 }
1941         } else {
1942                 if (!(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_JUMP(this))) {
1943                         this.flags |= FL_JUMPRELEASED;
1944                         if(this.flags & FL_SPAWNING)
1945                         {
1946                                 this.flags &= ~FL_SPAWNING;
1947                                 LeaveSpectatorMode(this);
1948                                 return;
1949                         }
1950                 }
1951         }
1952 }
1953
1954 void SpectatorThink(entity this)
1955 {
1956         if ( this.impulse )
1957         {
1958                 if(MinigameImpulse(this, this.impulse))
1959                         this.impulse = 0;
1960         }
1961         if (this.flags & FL_JUMPRELEASED) {
1962                 if (PHYS_INPUT_BUTTON_JUMP(this) && !this.version_mismatch) {
1963                         this.flags &= ~FL_JUMPRELEASED;
1964                         this.flags |= FL_SPAWNING;
1965                 } else if(PHYS_INPUT_BUTTON_ATCK(this) || this.impulse == 10 || this.impulse == 15 || this.impulse == 18 || (this.impulse >= 200 && this.impulse <= 209)) {
1966                         this.flags &= ~FL_JUMPRELEASED;
1967                         if(SpectateNext(this)) {
1968                                 TRANSMUTE(Spectator, this);
1969                         } else {
1970                                 TRANSMUTE(Observer, this);
1971                                 WITHSELF(this, PutClientInServer());
1972                         }
1973                         this.impulse = 0;
1974                 } else if(this.impulse == 12 || this.impulse == 16  || this.impulse == 19 || (this.impulse >= 220 && this.impulse <= 229)) {
1975                         this.flags &= ~FL_JUMPRELEASED;
1976                         if(SpectatePrev(this)) {
1977                                 TRANSMUTE(Spectator, this);
1978                         } else {
1979                                 TRANSMUTE(Observer, this);
1980                                 WITHSELF(this, PutClientInServer());
1981                         }
1982                         this.impulse = 0;
1983                 } else if (PHYS_INPUT_BUTTON_ATCK2(this)) {
1984                         this.flags &= ~FL_JUMPRELEASED;
1985                         TRANSMUTE(Observer, this);
1986                         WITHSELF(this, PutClientInServer());
1987                 } else {
1988                         if(!SpectateUpdate(this))
1989                                 PutObserverInServer(this);
1990                 }
1991         } else {
1992                 if (!(PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_ATCK2(this))) {
1993                         this.flags |= FL_JUMPRELEASED;
1994                         if(this.flags & FL_SPAWNING)
1995                         {
1996                                 this.flags &= ~FL_SPAWNING;
1997                                 LeaveSpectatorMode(this);
1998                                 return;
1999                         }
2000                 }
2001                 if(!SpectateUpdate(this))
2002                         PutObserverInServer(this);
2003         }
2004
2005         this.flags |= FL_CLIENT | FL_NOTARGET;
2006 }
2007
2008 void vehicles_enter (entity pl, entity veh);
2009 void PlayerUseKey(entity this)
2010 {
2011         if (!IS_PLAYER(this))
2012                 return;
2013
2014         if(this.vehicle)
2015         {
2016                 if(!gameover)
2017                 {
2018                         vehicles_exit(this.vehicle, VHEF_NORMAL);
2019                         return;
2020                 }
2021         }
2022         else if(autocvar_g_vehicles_enter)
2023         {
2024                 if(!STAT(FROZEN, this))
2025                 if(!IS_DEAD(this))
2026                 if(!gameover)
2027                 {
2028                         entity head, closest_target = NULL;
2029                         head = WarpZone_FindRadius(this.origin, autocvar_g_vehicles_enter_radius, true);
2030
2031                         while(head) // find the closest acceptable target to enter
2032                         {
2033                                 if(IS_VEHICLE(head))
2034                                 if(!IS_DEAD(head))
2035                                 if(!head.owner || ((head.vehicle_flags & VHF_MULTISLOT) && SAME_TEAM(head.owner, this)))
2036                                 if(head.takedamage != DAMAGE_NO)
2037                                 {
2038                                         if(closest_target)
2039                                         {
2040                                                 if(vlen2(this.origin - head.origin) < vlen2(this.origin - closest_target.origin))
2041                                                 { closest_target = head; }
2042                                         }
2043                                         else { closest_target = head; }
2044                                 }
2045
2046                                 head = head.chain;
2047                         }
2048
2049                         if(closest_target) { vehicles_enter(this, closest_target); return; }
2050                 }
2051         }
2052
2053         // a use key was pressed; call handlers
2054         MUTATOR_CALLHOOK(PlayerUseKey, this);
2055 }
2056
2057
2058 /*
2059 =============
2060 PlayerPreThink
2061
2062 Called every frame for each client before the physics are run
2063 =============
2064 */
2065 .float usekeypressed;
2066 .float last_vehiclecheck;
2067 .int items_added;
2068 void PlayerPreThink ()
2069 {ENGINE_EVENT();
2070         WarpZone_PlayerPhysics_FixVAngle(this);
2071
2072     STAT(GAMESTARTTIME, this) = game_starttime;
2073         STAT(ROUNDSTARTTIME, this) = round_starttime;
2074         STAT(ALLOW_OLDVORTEXBEAM, this) = autocvar_g_allow_oldvortexbeam;
2075         STAT(LEADLIMIT, this) = autocvar_leadlimit;
2076
2077         STAT(WEAPONSINMAP, this) = weaponsInMap;
2078
2079         if (frametime) {
2080                 // physics frames: update anticheat stuff
2081                 anticheat_prethink(this);
2082         }
2083
2084         if (blockSpectators && frametime) {
2085                 // WORKAROUND: only use dropclient in server frames (frametime set).
2086                 // Never use it in cl_movement frames (frametime zero).
2087                 checkSpectatorBlock(this);
2088     }
2089
2090         zoomstate_set = false;
2091
2092         // Check for nameless players
2093         if (isInvisibleString(this.netname)) {
2094                 this.netname = strzone(sprintf("Player#%d", this.playerid));
2095                 // stuffcmd(this, strcat("name ", this.netname, "\n")); // maybe?
2096         }
2097         if (this.netname != this.netname_previous) {
2098                 if (autocvar_sv_eventlog) {
2099                         GameLogEcho(strcat(":name:", ftos(this.playerid), ":", this.netname));
2100         }
2101                 if (this.netname_previous) strunzone(this.netname_previous);
2102                 this.netname_previous = strzone(this.netname);
2103         }
2104
2105         // version nagging
2106         if (this.version_nagtime && this.cvar_g_xonoticversion && time > this.version_nagtime) {
2107         this.version_nagtime = 0;
2108         if (strstrofs(this.cvar_g_xonoticversion, "git", 0) >= 0 || strstrofs(this.cvar_g_xonoticversion, "autobuild", 0) >= 0) {
2109             // git client
2110         } else if (strstrofs(autocvar_g_xonoticversion, "git", 0) >= 0 || strstrofs(autocvar_g_xonoticversion, "autobuild", 0) >= 0) {
2111             // git server
2112             Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_VERSION_BETA, autocvar_g_xonoticversion, this.cvar_g_xonoticversion);
2113         } else {
2114             int r = vercmp(this.cvar_g_xonoticversion, autocvar_g_xonoticversion);
2115             if (r < 0) { // old client
2116                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_VERSION_OUTDATED, autocvar_g_xonoticversion, this.cvar_g_xonoticversion);
2117             } else if (r > 0) { // old server
2118                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_VERSION_OLD, autocvar_g_xonoticversion, this.cvar_g_xonoticversion);
2119             }
2120         }
2121     }
2122
2123         // GOD MODE info
2124         if (!(this.flags & FL_GODMODE) && this.max_armorvalue)
2125         {
2126                 Send_Notification(NOTIF_ONE_ONLY, this, MSG_INFO, INFO_GODMODE_OFF, this.max_armorvalue);
2127                 this.max_armorvalue = 0;
2128         }
2129
2130         if (STAT(FROZEN, this) == 2)
2131         {
2132                 this.revive_progress = bound(0, this.revive_progress + frametime * this.revive_speed, 1);
2133                 this.health = max(1, this.revive_progress * start_health);
2134                 this.iceblock.alpha = bound(0.2, 1 - this.revive_progress, 1);
2135
2136                 if (this.revive_progress >= 1)
2137                         Unfreeze(this);
2138         }
2139         else if (STAT(FROZEN, this) == 3)
2140         {
2141                 this.revive_progress = bound(0, this.revive_progress - frametime * this.revive_speed, 1);
2142                 this.health = max(0, autocvar_g_nades_ice_health + (start_health-autocvar_g_nades_ice_health) * this.revive_progress );
2143
2144                 if (this.health < 1)
2145                 {
2146                         if (this.vehicle)
2147                                 vehicles_exit(this.vehicle, VHEF_RELEASE);
2148                         if(this.event_damage)
2149                                 this.event_damage(this, this, this.frozen_by, 1, DEATH_NADE_ICE_FREEZE.m_id, this.origin, '0 0 0');
2150                 }
2151                 else if (this.revive_progress <= 0)
2152                         Unfreeze(this);
2153         }
2154
2155         MUTATOR_CALLHOOK(PlayerPreThink, this);
2156
2157         if(autocvar_g_vehicles_enter && (time > this.last_vehiclecheck) && !gameover && !this.vehicle)
2158         if(IS_PLAYER(this) && !STAT(FROZEN, this) && !IS_DEAD(this))
2159         {
2160                 FOREACH_ENTITY_RADIUS(this.origin, autocvar_g_vehicles_enter_radius, IS_VEHICLE(it),
2161                 {
2162                         if(!IS_DEAD(it) && it.takedamage != DAMAGE_NO)
2163                         if((it.vehicle_flags & VHF_MULTISLOT) && SAME_TEAM(it.owner, this))
2164                         {
2165                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_VEHICLE_ENTER_GUNNER);
2166                         }
2167                         else if(!it.owner)
2168                         {
2169                                 if(!it.team || SAME_TEAM(this, it))
2170                                         Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_VEHICLE_ENTER);
2171                         }
2172                         else if(autocvar_g_vehicles_steal)
2173                         {
2174                                 Send_Notification(NOTIF_ONE, this, MSG_CENTER, CENTER_VEHICLE_ENTER_STEAL);
2175                         }
2176                 });
2177
2178                 this.last_vehiclecheck = time + 1;
2179         }
2180
2181         if(!this.cvar_cl_newusekeysupported) // FIXME remove this - it was a stupid idea to begin with, we can JUST use the button
2182         {
2183                 if(PHYS_INPUT_BUTTON_USE(this) && !this.usekeypressed)
2184                         PlayerUseKey(this);
2185                 this.usekeypressed = PHYS_INPUT_BUTTON_USE(this);
2186         }
2187
2188         if (IS_REAL_CLIENT(this))
2189                 PrintWelcomeMessage(this);
2190
2191         if (IS_PLAYER(this)) {
2192                 CheckRules_Player(this);
2193
2194                 if (intermission_running) {
2195                         IntermissionThink(this);
2196                         return;
2197                 }
2198
2199                 if (timeout_status == TIMEOUT_ACTIVE) {
2200             // don't allow the player to turn around while game is paused
2201                         // FIXME turn this into CSQC stuff
2202                         this.v_angle = this.lastV_angle;
2203                         this.angles = this.lastV_angle;
2204                         this.fixangle = true;
2205                 }
2206
2207                 if (frametime) player_powerups(this);
2208
2209                 if (IS_DEAD(this)) {
2210                         if (this.personal && g_race_qualifying) {
2211                                 if (time > this.respawn_time) {
2212                                         STAT(RESPAWN_TIME, this) = this.respawn_time = time + 1; // only retry once a second
2213                                         respawn(this);
2214                                         this.impulse = CHIMPULSE_SPEEDRUN.impulse;
2215                                 }
2216                         } else {
2217                                 if (frametime) player_anim(this);
2218                                 bool button_pressed = (PHYS_INPUT_BUTTON_ATCK(this) || PHYS_INPUT_BUTTON_JUMP(this) || PHYS_INPUT_BUTTON_ATCK2(this) || PHYS_INPUT_BUTTON_HOOK(this) || PHYS_INPUT_BUTTON_USE(this));
2219
2220                                 if (this.deadflag == DEAD_DYING) {
2221                                         if ((this.respawn_flags & RESPAWN_FORCE) && !(this.respawn_time < this.respawn_time_max)) {
2222                                                 this.deadflag = DEAD_RESPAWNING;
2223                                         } else if (!button_pressed) {
2224                                                 this.deadflag = DEAD_DEAD;
2225                     }
2226                                 } else if (this.deadflag == DEAD_DEAD) {
2227                                         if (button_pressed) {
2228                                                 this.deadflag = DEAD_RESPAWNABLE;
2229                                         } else if (time >= this.respawn_time_max && (this.respawn_flags & RESPAWN_FORCE)) {
2230                                                 this.deadflag = DEAD_RESPAWNING;
2231                     }
2232                                 } else if (this.deadflag == DEAD_RESPAWNABLE) {
2233                                         if (!button_pressed) {
2234                                                 this.deadflag = DEAD_RESPAWNING;
2235                     }
2236                                 } else if (this.deadflag == DEAD_RESPAWNING) {
2237                                         if (time > this.respawn_time) {
2238                                                 this.respawn_time = time + 1; // only retry once a second
2239                                                 this.respawn_time_max = this.respawn_time;
2240                                                 respawn(this);
2241                                         }
2242                                 }
2243
2244                                 ShowRespawnCountdown(this);
2245
2246                                 if (this.respawn_flags & RESPAWN_SILENT)
2247                                         STAT(RESPAWN_TIME, this) = 0;
2248                                 else if ((this.respawn_flags & RESPAWN_FORCE) && this.respawn_time < this.respawn_time_max)
2249                                 {
2250                                         if (time < this.respawn_time)
2251                                                 STAT(RESPAWN_TIME, this) = this.respawn_time;
2252                                         else if (this.deadflag != DEAD_RESPAWNING)
2253                                                 STAT(RESPAWN_TIME, this) = -this.respawn_time_max;
2254                                 }
2255                                 else
2256                                         STAT(RESPAWN_TIME, this) = this.respawn_time;
2257                         }
2258
2259                         // if respawning, invert stat_respawn_time to indicate this, the client translates it
2260                         if (this.deadflag == DEAD_RESPAWNING && STAT(RESPAWN_TIME, this) > 0)
2261                                 STAT(RESPAWN_TIME, this) *= -1;
2262
2263                         return;
2264                 }
2265
2266                 this.prevorigin = this.origin;
2267
2268                 bool do_crouch = PHYS_INPUT_BUTTON_CROUCH(this);
2269         .entity weaponentity = weaponentities[0]; // TODO: unhardcode
2270                 if (this.hook.state) {
2271                         do_crouch = false;
2272                 } else if (this.vehicle) {
2273                         do_crouch = false;
2274                 } else if (STAT(FROZEN, this)) {
2275                         do_crouch = false;
2276         } else if ((PS(this).m_weapon == WEP_SHOTGUN || PS(this).m_weapon == WEP_SHOCKWAVE) && this.(weaponentity).wframe == WFRAME_FIRE2 && time < this.(weaponentity).weapon_nextthink) {
2277                     // WEAPONTODO: predict
2278                         do_crouch = false;
2279         }
2280
2281                 if (do_crouch) {
2282                         if (!this.crouch) {
2283                                 this.crouch = true;
2284                                 this.view_ofs = STAT(PL_CROUCH_VIEW_OFS, this);
2285                                 setsize(this, STAT(PL_CROUCH_MIN, this), STAT(PL_CROUCH_MAX, this));
2286                                 // setanim(this, this.anim_duck, false, true, true); // this anim is BROKEN anyway
2287                         }
2288                 } else if (this.crouch) {
2289             tracebox(this.origin, STAT(PL_MIN, this), STAT(PL_MAX, this), this.origin, false, this);
2290             if (!trace_startsolid) {
2291                 this.crouch = false;
2292                 this.view_ofs = STAT(PL_VIEW_OFS, this);
2293                 setsize(this, STAT(PL_MIN, this), STAT(PL_MAX, this));
2294             }
2295                 }
2296
2297                 FixPlayermodel(this);
2298
2299                 // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
2300                 //if(frametime)
2301                 {
2302                         this.items &= ~this.items_added;
2303
2304                         W_WeaponFrame(this);
2305
2306                         this.items_added = 0;
2307                         if (this.items & ITEM_Jetpack.m_itemid && (this.items & ITEM_JetpackRegen.m_itemid || this.ammo_fuel >= 0.01))
2308                 this.items_added |= IT_FUEL;
2309
2310                         this.items |= this.items_added;
2311                 }
2312
2313                 player_regen(this);
2314
2315                 // WEAPONTODO: Add a weapon request for this
2316                 // rot vortex charge to the charge limit
2317                 if (WEP_CVAR(vortex, charge_rot_rate) && this.vortex_charge > WEP_CVAR(vortex, charge_limit) && this.vortex_charge_rottime < time)
2318                         this.vortex_charge = bound(WEP_CVAR(vortex, charge_limit), this.vortex_charge - WEP_CVAR(vortex, charge_rot_rate) * frametime / W_TICSPERFRAME, 1);
2319
2320                 if (frametime) player_anim(this);
2321
2322                 // secret status
2323                 secrets_setstatus(this);
2324
2325                 // monsters status
2326                 monsters_setstatus(this);
2327
2328                 this.dmg_team = max(0, this.dmg_team - autocvar_g_teamdamage_resetspeed * frametime);
2329         }
2330         else if (gameover) {
2331                 if (intermission_running) IntermissionThink(this);
2332                 return;
2333         }
2334         else if (IS_OBSERVER(this)) {
2335                 ObserverThink(this);
2336         }
2337         else if (IS_SPEC(this)) {
2338                 SpectatorThink(this);
2339         }
2340
2341         // WEAPONTODO: Add weapon request for this
2342         if (!zoomstate_set) {
2343                 SetZoomState(this,
2344                         PHYS_INPUT_BUTTON_ZOOM(this) || PHYS_INPUT_BUTTON_ZOOMSCRIPT(this)
2345                         || (PHYS_INPUT_BUTTON_ATCK2(this) && PS(this).m_weapon == WEP_VORTEX)
2346                         || (PHYS_INPUT_BUTTON_ATCK2(this) && PS(this).m_weapon == WEP_RIFLE && WEP_CVAR(rifle, secondary) == 0)
2347                 );
2348     }
2349
2350         int oldspectatee_status = this.spectatee_status;
2351         if (IS_SPEC(this)) {
2352                 this.spectatee_status = etof(this.enemy);
2353         } else if (IS_OBSERVER(this)) {
2354                 this.spectatee_status = etof(this);
2355         } else {
2356                 this.spectatee_status = 0;
2357     }
2358         if (this.spectatee_status != oldspectatee_status) {
2359                 ClientData_Touch(this);
2360                 if (g_race || g_cts) race_InitSpectator();
2361         }
2362
2363         if (this.teamkill_soundtime && time > this.teamkill_soundtime)
2364         {
2365                 this.teamkill_soundtime = 0;
2366
2367                 entity e = this.teamkill_soundsource;
2368                 entity oldpusher = e.pusher;
2369                 e.pusher = this;
2370                 PlayerSound(e, playersound_teamshoot, CH_VOICE, VOICETYPE_LASTATTACKER_ONLY);
2371                 e.pusher = oldpusher;
2372         }
2373
2374         if (this.taunt_soundtime && time > this.taunt_soundtime) {
2375                 this.taunt_soundtime = 0;
2376                 PlayerSound(this, playersound_taunt, CH_VOICE, VOICETYPE_AUTOTAUNT);
2377         }
2378
2379         target_voicescript_next(this);
2380
2381         // WEAPONTODO: Move into weaponsystem somehow
2382         // if a player goes unarmed after holding a loaded weapon, empty his clip size and remove the crosshair ammo ring
2383         if (PS(this).m_weapon == WEP_Null)
2384                 this.clip_load = this.clip_size = 0;
2385 }
2386
2387 void DrownPlayer(entity this)
2388 {
2389         if(IS_DEAD(this))
2390                 return;
2391
2392         if (this.waterlevel != WATERLEVEL_SUBMERGED)
2393         {
2394                 if(this.air_finished < time)
2395                         PlayerSound(this, playersound_gasp, CH_PLAYER, VOICETYPE_PLAYERSOUND);
2396                 this.air_finished = time + autocvar_g_balance_contents_drowndelay;
2397                 this.dmg = 2;
2398         }
2399         else if (this.air_finished < time)
2400         {       // drown!
2401                 if (this.pain_finished < time)
2402                 {
2403                         Damage (this, NULL, NULL, autocvar_g_balance_contents_playerdamage_drowning * autocvar_g_balance_contents_damagerate, DEATH_DROWN.m_id, this.origin, '0 0 0');
2404                         this.pain_finished = time + 0.5;
2405                 }
2406         }
2407 }
2408
2409 /*
2410 =============
2411 PlayerPostThink
2412
2413 Called every frame for each client after the physics are run
2414 =============
2415 */
2416 .float idlekick_lasttimeleft;
2417 void PlayerPostThink ()
2418 {ENGINE_EVENT();
2419         if (sv_maxidle > 0)
2420         if (frametime) // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2421         if (IS_REAL_CLIENT(this))
2422         if (IS_PLAYER(this) || sv_maxidle_spectatorsareidle)
2423         {
2424                 if (time - this.parm_idlesince < 1) // instead of (time == this.parm_idlesince) to support sv_maxidle <= 10
2425                 {
2426                         if (this.idlekick_lasttimeleft)
2427                         {
2428                                 this.idlekick_lasttimeleft = 0;
2429                                 Kill_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CPID_IDLING);
2430                         }
2431                 }
2432                 else
2433                 {
2434                         float timeleft = ceil(sv_maxidle - (time - this.parm_idlesince));
2435                         if (timeleft == min(10, sv_maxidle - 1)) { // - 1 to support sv_maxidle <= 10
2436                                 if (!this.idlekick_lasttimeleft)
2437                                         Send_Notification(NOTIF_ONE_ONLY, this, MSG_CENTER, CENTER_DISCONNECT_IDLING, timeleft);
2438                         }
2439                         if (timeleft <= 0) {
2440                                 Send_Notification(NOTIF_ALL, NULL, MSG_INFO, INFO_QUIT_KICK_IDLING, this.netname);
2441                                 dropclient(this);
2442                                 return;
2443                         }
2444                         else if (timeleft <= 10) {
2445                                 if (timeleft != this.idlekick_lasttimeleft) {
2446                                     Send_Notification(NOTIF_ONE, this, MSG_ANNCE, Announcer_PickNumber(CNT_IDLE, timeleft));
2447                 }
2448                                 this.idlekick_lasttimeleft = timeleft;
2449                         }
2450                 }
2451         }
2452
2453         CheatFrame(this);
2454
2455         //CheckPlayerJump();
2456
2457         if (IS_PLAYER(this)) {
2458                 DrownPlayer(this);
2459                 CheckRules_Player(this);
2460                 UpdateChatBubble(this);
2461                 if (this.impulse) ImpulseCommands(this);
2462                 if (intermission_running) return; // intermission or finale
2463                 GetPressedKeys(this);
2464         }
2465
2466         if (this.waypointsprite_attachedforcarrier) {
2467             vector v = healtharmor_maxdamage(this.health, this.armorvalue, autocvar_g_balance_armor_blockpercent, DEATH_WEAPON.m_id);
2468                 WaypointSprite_UpdateHealth(this.waypointsprite_attachedforcarrier, '1 0 0' * v);
2469     }
2470
2471         playerdemo_write(this);
2472
2473         CSQCMODEL_AUTOUPDATE(this);
2474 }