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