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