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