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