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