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