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