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