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