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