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