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