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