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