]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/cl_client.qc
add detection code for generic speedhacks, old and new strafebot, div0 spectator...
[divverent/nexuiz.git] / data / qcsrc / server / cl_client.qc
1 void race_send_recordtime(float t, float msg);
2
3 void send_CSQC_teamnagger() {
4         WriteByte(0, SVC_TEMPENTITY);
5         WriteByte(0, TE_CSQC_TEAMNAGGER);
6 }
7
8 float ClientData_Send(entity to, float sf)
9 {
10         if(to != self.owner)
11         {
12                 error("wtf");
13                 return FALSE;
14         }
15
16         entity e;
17
18         e = to;
19         if(to.classname == "spectator")
20                 e = to.enemy;
21
22         sf = 0;
23
24         if(e.race_completed)
25                 sf |= 1; // forced scoreboard
26         if(to.spectatee_status)
27                 sf |= 2; // spectator ent number follows
28         if(e.zoomstate)
29                 sf |= 4; // zoomed
30         if(e.porto_v_angle_held)
31                 sf |= 8; // angles held
32
33         WriteByte(MSG_ENTITY, ENT_CLIENT_CLIENTDATA);
34         WriteByte(MSG_ENTITY, sf);
35
36         if(sf & 2)
37                 WriteByte(MSG_ENTITY, to.spectatee_status);
38
39         if(sf & 8)
40         {
41                 WriteAngle(MSG_ENTITY, e.v_angle_x);
42                 WriteAngle(MSG_ENTITY, e.v_angle_y);
43         }
44
45         return TRUE;
46 }
47
48 void ClientData_Attach()
49 {
50         Net_LinkEntity(self.clientdata = spawn(), FALSE, 0, ClientData_Send);
51         self.clientdata.drawonlytoclient = self;
52         self.clientdata.owner = self;
53 }
54
55 void ClientData_Detach()
56 {
57         remove(self.clientdata);
58         self.clientdata = world;
59 }
60
61 void ClientData_Touch(entity e)
62 {
63         e.clientdata.SendFlags = 1;
64
65         // make it spectatable
66         entity e2;
67         FOR_EACH_REALCLIENT(e2)
68         {
69                 if(e2 != e)
70                         if(e2.classname == "spectator")
71                                 if(e2.enemy == e)
72                                         e2.clientdata.SendFlags = 1;
73         }
74 }
75
76
77 #define SPAWNPOINT_SCORE frags
78
79 .string netname_previous;
80
81 void spawnfunc_info_player_survivor (void)
82 {
83         spawnfunc_info_player_deathmatch();
84 }
85
86 void spawnfunc_info_player_start (void)
87 {
88         spawnfunc_info_player_deathmatch();
89 }
90
91 void spawnfunc_info_player_deathmatch (void)
92 {
93         self.classname = "info_player_deathmatch";
94         relocate_spawnpoint();
95 }
96
97 void spawnpoint_use()
98 {
99         if(teams_matter)
100         if(have_team_spawns > 0)
101         {
102                 self.team = activator.team;
103                 some_spawn_has_been_used = 1;
104         }
105 };
106
107 // Returns:
108 //   -1 if a spawn can't be used
109 //   otherwise, a weight of the spawnpoint
110 float Spawn_Score(entity spot, entity playerlist, float teamcheck)
111 {
112         float shortest, thisdist;
113         entity player;
114
115         // filter out spots for the wrong team
116         if(teamcheck)
117         if(spot.team != teamcheck)
118                 return -1;
119
120         if(race_spawns)
121                 if(spot.target == "")
122                         return -1;
123
124         if(clienttype(self) == CLIENTTYPE_REAL)
125         {
126                 if(spot.restriction == 1)
127                         return -1;
128         }
129         else
130         {
131                 if(spot.restriction == 2)
132                         return -1;
133         }
134
135         // filter out spots for assault
136         if(spot.target != "") {
137                 local entity ent;
138                 float good, found;
139                 ent = find(world, targetname, spot.target);
140                 while(ent) {
141                         if(ent.classname == "target_objective")
142                         {
143                                 found = 1;
144                                 if(ent.health < 0 || ent.health >= ASSAULT_VALUE_INACTIVE)
145                                         return -1;
146                                 good = 1;
147                         }
148                         else if(ent.classname == "trigger_race_checkpoint")
149                         {
150                                 found = 1;
151                                 if(self.classname == "player") // spectators may spawn everywhere
152                                 {
153                                         if(g_race_qualifying)
154                                         {
155                                                 // spawn at first
156                                                 if(ent.race_checkpoint != 0)
157                                                         return -1;
158                                                 if(spot.race_place != race_lowest_place_spawn)
159                                                         return -1;
160                                         }
161                                         else
162                                         {
163                                                 if(ent.race_checkpoint != race_PreviousCheckpoint(self.race_checkpoint))
164                                                         return -1;
165                                                 float pl;
166                                                 pl = self.race_place;
167                                                 if(pl > race_highest_place_spawn)
168                                                         pl = 0;
169                                                 if(spot.race_place != pl)
170                                                         return -1;
171                                         }
172                                 }
173                                 good = 1;
174                         }
175                         ent = find(ent, targetname, spot.target);
176                 }
177
178                 if(found && !good)
179                         return -1;
180         }
181
182         player = playerlist;
183         shortest = vlen(world.maxs - world.mins);
184         for(player = playerlist; player; player = player.chain)
185                 if (player != self)
186                 {
187                         thisdist = vlen(player.origin - spot.origin);
188                         if (thisdist < shortest)
189                                 shortest = thisdist;
190                 }
191         return shortest;
192 }
193
194 float spawn_allbad;
195 float spawn_allgood;
196 entity Spawn_FilterOutBadSpots(entity firstspot, entity playerlist, float mindist, float teamcheck)
197 {
198         local entity spot, spotlist, spotlistend;
199         spawn_allgood = TRUE;
200         spawn_allbad = TRUE;
201
202         spotlist = world;
203         spotlistend = world;
204
205         for(spot = firstspot; spot; spot = spot.chain)
206         {
207                 spot.SPAWNPOINT_SCORE = Spawn_Score(spot, playerlist, teamcheck);
208
209                 if(cvar("spawn_debugview"))
210                 {
211                         setmodel(spot, "models/runematch/rune.mdl");
212                         if(spot.SPAWNPOINT_SCORE < mindist)
213                         {
214                                 spot.colormod = '1 0 0';
215                                 spot.scale = 1;
216                         }
217                         else
218                         {
219                                 spot.colormod = '0 1 0';
220                                 spot.scale = spot.SPAWNPOINT_SCORE / mindist;
221                         }
222                 }
223
224                 if(spot.SPAWNPOINT_SCORE >= 0) // spawning allowed here
225                 {
226                         if(spot.SPAWNPOINT_SCORE < mindist)
227                         {
228                                 // too short distance
229                                 spawn_allgood = FALSE;
230                         }
231                         else
232                         {
233                                 // perfect
234                                 spawn_allbad = FALSE;
235
236                                 if(spotlistend)
237                                         spotlistend.chain = spot;
238                                 spotlistend = spot;
239                                 if(!spotlist)
240                                         spotlist = spot;
241
242                                 /*
243                                 if(teamcheck)
244                                 if(spot.team != teamcheck)
245                                         error("invalid spawn added");
246
247                                 print("added ", etos(spot), "\n");
248                                 */
249                         }
250                 }
251         }
252         if(spotlistend)
253                 spotlistend.chain = world;
254
255         /*
256                 entity e;
257                 if(teamcheck)
258                         for(e = spotlist; e; e = e.chain)
259                         {
260                                 print("seen ", etos(e), "\n");
261                                 if(e.team != teamcheck)
262                                         error("invalid spawn found");
263                         }
264         */
265
266         return spotlist;
267 }
268
269 entity Spawn_WeightedPoint(entity firstspot, float lower, float upper, float exponent)
270 {
271         // weight of a point: bound(lower, mindisttoplayer, upper)^exponent
272         // multiplied by spot.cnt (useful if you distribute many spawnpoints in a small area)
273         local entity spot;
274
275         RandomSelection_Init();
276         for(spot = firstspot; spot; spot = spot.chain)
277                 RandomSelection_Add(spot, 0, string_null, pow(bound(lower, spot.SPAWNPOINT_SCORE, upper), exponent) * spot.cnt, spot.SPAWNPOINT_SCORE >= lower);
278
279         return RandomSelection_chosen_ent;
280 }
281
282 /*
283 =============
284 SelectSpawnPoint
285
286 Finds a point to respawn
287 =============
288 */
289 entity SelectSpawnPoint (float anypoint)
290 {
291         local float teamcheck;
292         local entity firstspot_new;
293         local entity spot, firstspot, playerlist;
294
295         spot = find (world, classname, "testplayerstart");
296         if (spot)
297                 return spot;
298
299         teamcheck = 0;
300
301         if(!anypoint && have_team_spawns > 0)
302                 teamcheck = self.team;
303
304         // get the list of players
305         playerlist = findchain(classname, "player");
306         // get the entire list of spots
307         firstspot = findchain(classname, "info_player_deathmatch");
308         // filter out the bad ones
309         // (note this returns the original list if none survived)
310         if(anypoint)
311         {
312                 spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
313         }
314         else
315         {
316                 firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, 100, teamcheck);
317                 if(!firstspot_new)
318                         firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, -1, teamcheck);
319                 firstspot = firstspot_new;
320
321                 // there is 50/50 chance of choosing a random spot or the furthest spot
322                 // (this means that roughly every other spawn will be furthest, so you
323                 // usually won't get fragged at spawn twice in a row)
324                 if (arena_roundbased && !g_ca)
325                 {
326                         firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, 800, teamcheck);
327                         if(firstspot_new)
328                                 firstspot = firstspot_new;
329                         spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
330                 }
331                 else if (random() > cvar("g_spawn_furthest"))
332                         spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
333                 else
334                         spot = Spawn_WeightedPoint(firstspot, 1, 5000, 5); // chooses a far far away spawnpoint
335         }
336
337         if(cvar("spawn_debugview"))
338         {
339                 print("spot mindistance: ", ftos(spot.SPAWNPOINT_SCORE), "\n");
340
341                 entity e;
342                 if(teamcheck)
343                         for(e = firstspot; e; e = e.chain)
344                                 if(e.team != teamcheck)
345                                         error("invalid spawn found");
346         }
347
348         if (!spot)
349         {
350                 if(cvar("spawn_debug"))
351                         GotoNextMap();
352                 else
353                 {
354                         if(some_spawn_has_been_used)
355                                 return world; // team can't spawn any more, because of actions of other team
356                         else
357                                 error("Cannot find a spawn point - please fix the map!");
358                 }
359         }
360
361         return spot;
362 }
363
364 /*
365 =============
366 CheckPlayerModel
367
368 Checks if the argument string can be a valid playermodel.
369 Returns a valid one in doubt.
370 =============
371 */
372 string FallbackPlayerModel = "models/player/marine.zym";
373 string CheckPlayerModel(string plyermodel) {
374         if(strlen(plyermodel) < 4)
375                 return FallbackPlayerModel;
376         if( substring(plyermodel,0,14) != "models/player/")
377                 return FallbackPlayerModel;
378         else if(cvar("sv_servermodelsonly"))
379         {
380                 if(substring(plyermodel,-4,4) != ".zym")
381                 if(substring(plyermodel,-4,4) != ".dpm")
382                 if(substring(plyermodel,-4,4) != ".md3")
383                 if(substring(plyermodel,-4,4) != ".psk")
384                         return FallbackPlayerModel;
385                 // forbid the LOD models
386                 if(substring(plyermodel, -9,5) == "_lod1")
387                         return FallbackPlayerModel;
388                 if(substring(plyermodel, -9,5) == "_lod2")
389                         return FallbackPlayerModel;
390                 if(plyermodel != strtolower(plyermodel))
391                         return FallbackPlayerModel;
392                 if(!fexists(plyermodel))
393                         return FallbackPlayerModel;
394         }
395         return plyermodel;
396 }
397
398 /*
399 =============
400 Client_customizeentityforclient
401
402 LOD reduction
403 =============
404 */
405 void Client_uncustomizeentityforclient()
406 {
407         if(self.modelindex == 0) // no need to uncustomize then
408                 return;
409         self.modelindex = self.modelindex_lod0;
410         self.skin = self.skinindex;
411 }
412
413 float Client_customizeentityforclient()
414 {
415         entity modelsource;
416
417         if(self.modelindex == 0)
418                 return TRUE;
419
420         // forcemodel stuff
421
422 #ifdef PROFILING
423         float t0;
424         t0 = gettime(GETTIME_HIRES); // reference
425 #endif
426
427         modelsource = self;
428
429 #ifdef ALLOW_FORCEMODELS
430         if(other.cvar_cl_forceplayermodelsfromnexuiz)
431                 if not(self.modelindex_lod0_from_nexuiz)
432                         modelsource = other;
433         if(other.cvar_cl_forceplayermodels && sv_clforceplayermodels)
434                 modelsource = other;
435 #endif
436
437         self.skin = modelsource.skinindex;
438
439 #if 0
440         if(modelsource == self)
441                 self.skin = modelsource.skinindex;
442         else
443                 self.skin = mod(modelsource.skinindex, 3); // forbid the fbskins as forced skins
444 #endif
445
446         // self: me
447         // other: the player viewing me
448         float distance;
449         float f;
450
451         if(other.cvar_cl_playerdetailreduction <= 0)
452         {
453                 if(other.cvar_cl_playerdetailreduction <= -2)
454                         self.modelindex = modelsource.modelindex_lod2;
455                 else if(other.cvar_cl_playerdetailreduction <= -1)
456                         self.modelindex = modelsource.modelindex_lod1;
457                 else
458                         self.modelindex = modelsource.modelindex_lod0;
459         }
460         else
461         {
462                 distance = vlen(self.origin - other.origin);
463                 f = (distance + 100.0) * other.cvar_cl_playerdetailreduction;
464                 if(f > sv_loddistance2)
465                         self.modelindex = modelsource.modelindex_lod2;
466                 else if(f > sv_loddistance1)
467                         self.modelindex = modelsource.modelindex_lod1;
468                 else
469                         self.modelindex = modelsource.modelindex_lod0;
470         }
471
472 #ifdef PROFILING
473         float t1;
474         t1 = gettime(GETTIME_HIRES); // reference
475         client_cefc_accumulator += (t1 - t0);
476 #endif
477
478         return TRUE;
479 }
480
481 void UpdatePlayerSounds();
482 void setmodel_lod(entity e, string modelname)
483 {
484         string s;
485
486         if(sv_loddistance1)
487         {
488                 // FIXME: this only supports 3-letter extensions
489                 s = strcat(substring(modelname, 0, strlen(modelname)-4), "_lod1", substring(modelname, -4, 4));
490                 if(fexists(s))
491                 {
492                         setmodel(e, s); // players have high precision
493                         self.modelindex_lod1 = self.modelindex;
494                 }
495                 else
496                         self.modelindex_lod1 = -1;
497
498                 s = strcat(substring(modelname, 0, strlen(modelname)-4), "_lod2", substring(modelname, -4, 4));
499                 if(fexists(s))
500                 {
501                         setmodel(e, s); // players have high precision
502                         self.modelindex_lod2 = self.modelindex;
503                 }
504                 else
505                         self.modelindex_lod2 = -1;
506
507                 precache_model(modelname);
508                 setmodel(e, modelname); // players have high precision
509                 self.modelindex_lod0 = self.modelindex;
510
511                 if(self.modelindex_lod1 < 0)
512                         self.modelindex_lod1 = self.modelindex;
513
514                 if(self.modelindex_lod2 < 0)
515                         self.modelindex_lod2 = self.modelindex;
516         }
517         else
518         {
519                 precache_model(modelname);
520                 setmodel(e, modelname); // players have high precision
521                 self.modelindex_lod0 = self.modelindex;
522                         // save it for possible player model forcing
523         }
524
525         s = whichpack(self.model);
526         self.modelindex_lod0_from_nexuiz = ((s == "") || (substring(s, 0, 4) == "data"));
527
528         player_setupanimsformodel();
529         UpdatePlayerSounds();
530 }
531
532 /*
533 =============
534 PutObserverInServer
535
536 putting a client as observer in the server
537 =============
538 */
539 void FixPlayermodel();
540 void PutObserverInServer (void)
541 {
542         entity  spot;
543
544         race_PreSpawnObserver();
545
546         spot = SelectSpawnPoint (TRUE);
547         if(!spot)
548                 error("No spawnpoints for observers?!?\n");
549         RemoveGrapplingHook(self); // Wazat's Grappling Hook
550
551         if(clienttype(self) == CLIENTTYPE_REAL)
552         {
553                 msg_entity = self;
554                 WriteByte(MSG_ONE, SVC_SETVIEW);
555                 WriteEntity(MSG_ONE, self);
556         }
557
558         DropAllRunes(self);
559         kh_Key_DropAll(self, TRUE);
560
561         Portal_ClearAll(self);
562
563         if(self.flagcarried)
564                 DropFlag(self.flagcarried, world, world);
565
566         if(self.ballcarried)
567                 DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
568
569         WaypointSprite_PlayerDead();
570
571         if not(g_ca)  // don't reset teams when moving a ca player to the spectators
572                 self.team = -1;  // move this as it is needed to log the player spectating in eventlog
573
574         if(self.killcount != -666) {
575                 if(g_lms) {
576                         if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
577                                 bprint ("^4", self.netname, "^4 has no more lives left\n");
578                         else
579                                 bprint ("^4", self.netname, "^4 is spectating now\n"); // TODO turn this into a proper forfeit?
580                 } else
581                         bprint ("^4", self.netname, "^4 is spectating now\n");
582
583                 if(self.just_joined == FALSE) {
584                         LogTeamchange(self.playerid, -1, 4);
585                 } else
586                         self.just_joined = FALSE;
587         }
588
589         PlayerScore_Clear(self); // clear scores when needed
590
591         self.spectatortime = time;
592
593         self.classname = "observer";
594         self.iscreature = FALSE;
595         self.health = -666;
596         self.takedamage = DAMAGE_NO;
597         self.solid = SOLID_NOT;
598         self.movetype = MOVETYPE_NOCLIP;
599         self.flags = FL_CLIENT | FL_NOTARGET;
600         self.armorvalue = 666;
601         self.effects = 0;
602         self.armorvalue = cvar("g_balance_armor_start");
603         self.pauserotarmor_finished = 0;
604         self.pauserothealth_finished = 0;
605         self.pauseregen_finished = 0;
606         self.damageforcescale = 0;
607         self.death_time = 0;
608         self.dead_frame = 0;
609         self.alpha = 0;
610         self.scale = 0;
611         self.fade_time = 0;
612         self.pain_frame = 0;
613         self.pain_finished = 0;
614         self.strength_finished = 0;
615         self.invincible_finished = 0;
616         self.pushltime = 0;
617         self.think = SUB_Null;
618         self.nextthink = 0;
619         self.hook_time = 0;
620         self.runes = 0;
621         self.deadflag = DEAD_NO;
622         self.angles = spot.angles;
623         self.angles_z = 0;
624         self.fixangle = TRUE;
625         self.crouch = FALSE;
626
627         self.view_ofs = PL_VIEW_OFS;
628         setorigin (self, spot.origin);
629         setsize (self, '0 0 0', '0 0 0');
630         self.prevorigin = self.origin;
631         self.items = 0;
632         self.weapons = 0;
633         self.model = "";
634         FixPlayermodel();
635         self.model = "";
636         self.modelindex = 0;
637         self.weapon = 0;
638         self.weaponmodel = "";
639         self.weaponentity = world;
640         self.exteriorweaponentity = world;
641         self.killcount = -666;
642         self.velocity = '0 0 0';
643         self.avelocity = '0 0 0';
644         self.punchangle = '0 0 0';
645         self.punchvector = '0 0 0';
646         self.oldvelocity = self.velocity;
647         self.fire_endtime = -1;
648
649         if(sv_loddistance1)
650                 SetCustomizer(self, Client_customizeentityforclient, Client_uncustomizeentityforclient);
651
652         if(g_arena)
653         {
654                 if(self.version_mismatch)
655                 {
656                         Spawnqueue_Unmark(self);
657                         Spawnqueue_Remove(self);
658                 }
659                 else
660                 {
661                         Spawnqueue_Insert(self);
662                 }
663         }
664         else if(g_lms)
665         {
666                 // Only if the player cannot play at all
667                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) == 666)
668                         self.frags = FRAGS_SPECTATOR;
669                 else
670                         self.frags = FRAGS_LMS_LOSER;
671         }
672         else
673                 self.frags = FRAGS_SPECTATOR;
674 }
675
676 float RestrictSkin(float s)
677 {
678         if(!teams_matter)
679                 return s;
680         if(s == 6)
681                 return 6;
682         return mod(s, 3);
683 }
684
685 void FixPlayermodel()
686 {
687         local string defaultmodel;
688         local float defaultskin, chmdl, oldskin;
689         local vector m1, m2;
690
691         defaultmodel = "";
692
693         if(cvar("sv_defaultcharacter") == 1) {
694                 defaultskin = 0;
695
696                 if(teams_matter)
697                 {
698                         string s;
699                         s = Team_ColorNameLowerCase(self.team);
700                         if(s != "neutral")
701                         {
702                                 defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", s));
703                                 defaultskin = cvar(strcat("sv_defaultplayerskin_", s));
704                         }
705                 }
706
707                 if(defaultmodel == "")
708                 {
709                         defaultmodel = cvar_string("sv_defaultplayermodel");
710                         defaultskin = cvar("sv_defaultplayerskin");
711                 }
712         }
713
714         if(self.modelindex == 0 && self.deadflag == DEAD_NO)
715         {
716                 if(self.model != "")
717                         bprint("\{1}^1Player ", self.netname, "^1 has a zero modelindex, trying to fix...\n");
718                 self.model = ""; // force the != checks to return true
719         }
720
721         if(defaultmodel != "")
722         {
723                 if (defaultmodel != self.model)
724                 {
725                         m1 = self.mins;
726                         m2 = self.maxs;
727                         setmodel_lod (self, defaultmodel);
728                         setsize (self, m1, m2);
729                         chmdl = TRUE;
730                 }
731
732                 oldskin = self.skinindex;
733                 self.skinindex = defaultskin;
734         } else {
735                 if (self.playermodel != self.model || self.playermodel == "")
736                 {
737                         self.playermodel = CheckPlayerModel(self.playermodel); // this is never "", so no endless loop
738                         m1 = self.mins;
739                         m2 = self.maxs;
740                         setmodel_lod (self, self.playermodel);
741                         setsize (self, m1, m2);
742                         chmdl = TRUE;
743                 }
744
745                 oldskin = self.skinindex;
746                 self.skinindex = RestrictSkin(stof(self.playerskin));
747         }
748
749         if(chmdl || oldskin != self.skinindex)
750                 self.species = player_getspecies(); // model or skin has changed
751
752         if(!teams_matter)
753                 if(strlen(cvar_string("sv_defaultplayercolors")))
754                         if(self.clientcolors != cvar("sv_defaultplayercolors"))
755                                 setcolor(self, cvar("sv_defaultplayercolors"));
756 }
757
758 void PlayerTouchExplode(entity p1, entity p2)
759 {
760         vector org;
761         org = (p1.origin + p2.origin) * 0.5;
762         org_z += (p1.mins_z + p2.mins_z) * 0.5;
763
764         te_explosion(org);
765
766         entity e;
767         e = spawn();
768         setorigin(e, org);
769         RadiusDamage(e, world, g_touchexplode_damage, g_touchexplode_edgedamage, g_touchexplode_radius, world, g_touchexplode_force, DEATH_TOUCHEXPLODE, world);
770         remove(e);
771 }
772
773 /*
774 =============
775 PutClientInServer
776
777 Called when a client spawns in the server
778 =============
779 */
780 //void() ctf_playerchanged;
781 void PutClientInServer (void)
782 {
783         if(clienttype(self) == CLIENTTYPE_BOT)
784         {
785                 self.classname = "player";
786         }
787         else if(clienttype(self) == CLIENTTYPE_REAL)
788         {
789                 msg_entity = self;
790                 WriteByte(MSG_ONE, SVC_SETVIEW);
791                 WriteEntity(MSG_ONE, self);
792         }
793
794         // player is dead and becomes observer
795         // FIXME fix LMS scoring for new system
796         if(g_lms)
797         {
798                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
799                         self.classname = "observer";
800         }
801
802         if(g_arena || (g_ca && !allowed_to_spawn))
803         if(!self.spawned)
804                 self.classname = "observer";
805
806         if(gameover)
807                 self.classname = "observer";
808
809         if(self.classname == "player" && (!g_ca || (g_ca && allowed_to_spawn))) {
810                 entity spot, oldself;
811                 float j;
812
813                 if(self.team < 0)
814                         JoinBestTeam(self, FALSE, TRUE);
815
816                 race_PreSpawn();
817
818                 spot = SelectSpawnPoint (FALSE);
819                 if(!spot)
820                 {
821                         centerprint(self, "Sorry, no spawnpoints available!\nHope your team can fix it...");
822                         return; // spawn failed
823                 }
824
825                 RemoveGrapplingHook(self); // Wazat's Grappling Hook
826
827                 self.classname = "player";
828                 self.wasplayer = TRUE;
829                 self.iscreature = TRUE;
830                 self.movetype = MOVETYPE_WALK;
831                 self.solid = SOLID_SLIDEBOX;
832                 if(cvar("g_playerclip_collisions"))
833                         self.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP;
834                 else
835                         self.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY;
836                 self.frags = FRAGS_PLAYER;
837                 if(independent_players)
838                         MAKE_INDEPENDENT_PLAYER(self);
839                 self.flags = FL_CLIENT;
840                 self.takedamage = DAMAGE_AIM;
841                 if(g_minstagib)
842                         self.effects = EF_FULLBRIGHT;
843                 else
844                         self.effects = 0;
845                 self.air_finished = time + 12;
846                 self.dmg = 2;
847
848                 if(inWarmupStage)
849                 {
850                         self.ammo_shells = warmup_start_ammo_shells;
851                         self.ammo_nails = warmup_start_ammo_nails;
852                         self.ammo_rockets = warmup_start_ammo_rockets;
853                         self.ammo_cells = warmup_start_ammo_cells;
854                         self.ammo_fuel = warmup_start_ammo_fuel;
855                         self.health = warmup_start_health;
856                         self.armorvalue = warmup_start_armorvalue;
857                         self.weapons = warmup_start_weapons;
858                 }
859                 else
860                 {
861                         self.ammo_shells = start_ammo_shells;
862                         self.ammo_nails = start_ammo_nails;
863                         self.ammo_rockets = start_ammo_rockets;
864                         self.ammo_cells = start_ammo_cells;
865                         self.ammo_fuel = start_ammo_fuel;
866                         self.health = start_health;
867                         self.armorvalue = start_armorvalue;
868                         self.weapons = start_weapons;
869                 }
870
871                 if(g_weaponarena_random)
872                         self.weapons = randombits(self.weapons, g_weaponarena_random, FALSE);
873
874                 self.items = start_items;
875                 self.switchweapon = w_getbestweapon(self);
876                 self.cnt = self.switchweapon;
877                 self.weapon = 0;
878                 self.jump_interval = time;
879
880                 self.spawnshieldtime = time + cvar("g_spawnshieldtime");
881                 self.pauserotarmor_finished = time + cvar("g_balance_pause_armor_rot_spawn");
882                 self.pauserothealth_finished = time + cvar("g_balance_pause_health_rot_spawn");
883                 self.pauserotfuel_finished = time + cvar("g_balance_pause_fuel_rot_spawn");
884                 self.pauseregen_finished = time + cvar("g_balance_pause_health_regen_spawn");
885                 //extend the pause of rotting if client was reset at the beginning of the countdown
886                 if(!cvar("sv_ready_restart_after_countdown") && time < game_starttime) { // TODO why is this cvar NOTted?
887                         self.spawnshieldtime += game_starttime - time;
888                         self.pauserotarmor_finished += game_starttime - time;
889                         self.pauserothealth_finished += game_starttime - time;
890                         self.pauseregen_finished += game_starttime - time;
891                 }
892                 self.damageforcescale = 2;
893                 self.death_time = 0;
894                 self.dead_frame = 0;
895                 self.alpha = 0;
896                 self.scale = 0;
897                 self.fade_time = 0;
898                 self.pain_frame = 0;
899                 self.pain_finished = 0;
900                 self.strength_finished = 0;
901                 self.invincible_finished = 0;
902                 self.pushltime = 0;
903                 // players have no think function
904                 self.think = SUB_Null;
905                 self.nextthink = 0;
906                 self.hook_time = 0;
907                 self.dmg_team = 0;
908
909                 self.metertime = 0;
910
911                 self.runes = 0;
912
913                 self.deadflag = DEAD_NO;
914
915                 self.angles = spot.angles;
916
917                 self.angles_z = 0; // never spawn tilted even if the spot says to
918                 self.fixangle = TRUE; // turn this way immediately
919                 self.velocity = '0 0 0';
920                 self.avelocity = '0 0 0';
921                 self.punchangle = '0 0 0';
922                 self.punchvector = '0 0 0';
923                 self.oldvelocity = self.velocity;
924                 self.fire_endtime = -1;
925
926                 msg_entity = self;
927                 WRITESPECTATABLE_MSG_ONE({
928                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
929                         WriteByte(MSG_ONE, TE_CSQC_SPAWN);
930                 });
931
932                 if(sv_loddistance1)
933                         SetCustomizer(self, Client_customizeentityforclient, Client_uncustomizeentityforclient);
934
935                 self.model = "";
936                 FixPlayermodel();
937
938                 self.crouch = FALSE;
939                 self.view_ofs = PL_VIEW_OFS;
940                 setsize (self, PL_MIN, PL_MAX);
941                 self.spawnorigin = spot.origin;
942                 setorigin (self, spot.origin + '0 0 1' * (1 - self.mins_z - 24));
943                 // don't reset back to last position, even if new position is stuck in solid
944                 self.oldorigin = self.origin;
945                 self.prevorigin = self.origin;
946                 self.lastrocket = world; // stop rocket guiding, no revenge from the grave!
947
948                 if(g_arena)
949                 {
950                         Spawnqueue_Remove(self);
951                         Spawnqueue_Mark(self);
952                 }
953
954                 else if(g_ca)
955                         self.caplayer = 1;
956
957                 self.event_damage = PlayerDamage;
958
959                 self.bot_attack = TRUE;
960
961                 self.statdraintime = time + 5;
962                 self.BUTTON_ATCK = self.BUTTON_JUMP = self.BUTTON_ATCK2 = 0;
963
964                 if(self.killcount == -666) {
965                         PlayerScore_Clear(self);
966                         self.killcount = 0;
967                 }
968
969                 self.cnt = WEP_LASER;
970                 self.nixnex_lastchange_id = -1;
971
972                 CL_SpawnWeaponentity();
973                 self.alpha = default_player_alpha;
974                 self.colormod = '1 1 1' * cvar("g_player_brightness");
975                 self.exteriorweaponentity.alpha = default_weapon_alpha;
976
977                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
978                 self.lms_traveled_distance = 0;
979                 self.speedrunning = FALSE;
980
981                 race_PostSpawn(spot);
982
983                 if(cvar("spawn_debug"))
984                 {
985                         sprint(self, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
986                         remove(spot);   // usefull for checking if there are spawnpoints, that let drop through the floor
987                 }
988
989                 //stuffcmd(self, "chase_active 0");
990                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
991
992                 if (cvar("g_spawnsound"))
993                         sound (self, CHAN_TRIGGER, "misc/spawn.wav", VOL_BASE, ATTN_NORM);
994
995                 if(g_assault) {
996                         if(self.team == assault_attacker_team)
997                                 centerprint(self, "You are attacking!");
998                         else
999                                 centerprint(self, "You are defending!");
1000                 }
1001
1002                 target_voicescript_clear(self);
1003
1004                 // reset fields the weapons may use
1005         for (j = WEP_FIRST; j <= WEP_LAST; ++j)
1006             weapon_action(j, WR_RESETPLAYER);
1007
1008                 oldself = self;
1009                 self = spot;
1010                         activator = oldself;
1011                                 SUB_UseTargets();
1012                         activator = world;
1013                 self = oldself;
1014         } else if(self.classname == "observer" || (g_ca && !allowed_to_spawn)) {
1015                 PutObserverInServer ();
1016         }
1017
1018         //if(g_ctf)
1019         //      ctf_playerchanged();
1020 }
1021
1022 float ClientInit_SendEntity(entity to, float sf)
1023 {
1024         float i;
1025         WriteByte(MSG_ENTITY, ENT_CLIENT_INIT);
1026         WriteByte(MSG_ENTITY, g_nexball_meter_period * 32);
1027         for(i = 1; i <= 24; ++i)
1028                 WriteByte(MSG_ENTITY, (get_weaponinfo(i)).impulse + 1);
1029         WriteCoord(MSG_ENTITY, hook_shotorigin_x);
1030         WriteCoord(MSG_ENTITY, hook_shotorigin_y);
1031         WriteCoord(MSG_ENTITY, hook_shotorigin_z);
1032
1033         if(sv_foginterval && world.fog != "")
1034                 WriteString(MSG_ENTITY, world.fog);
1035         else
1036                 WriteString(MSG_ENTITY, "");
1037         WriteByte(MSG_ENTITY, cvar("g_balance_armor_blockpercent") * 255.0);
1038         WriteByte(MSG_ENTITY, cvar("g_balance_weaponswitchdelay") * 255.0);
1039         return TRUE;
1040 }
1041
1042 void ClientInit_Spawn()
1043 {
1044         Net_LinkEntity(spawn(), FALSE, 0, ClientInit_SendEntity);
1045 }
1046
1047 /*
1048 =============
1049 SetNewParms
1050 =============
1051 */
1052 void SetNewParms (void)
1053 {
1054         // initialize parms for a new player
1055         parm1 = -(86400 * 366);
1056 }
1057
1058 /*
1059 =============
1060 SetChangeParms
1061 =============
1062 */
1063 void SetChangeParms (void)
1064 {
1065         // save parms for level change
1066         parm1 = self.parm_idlesince - time;
1067 }
1068
1069 /*
1070 =============
1071 DecodeLevelParms
1072 =============
1073 */
1074 void DecodeLevelParms (void)
1075 {
1076         // load parms
1077         self.parm_idlesince = parm1;
1078         if(self.parm_idlesince == -(86400 * 366))
1079                 self.parm_idlesince = time;
1080
1081         // whatever happens, allow 60 seconds of idling directly after connect for map loading
1082         self.parm_idlesince = max(self.parm_idlesince, time - sv_maxidle + 60);
1083 }
1084
1085 /*
1086 =============
1087 ClientKill
1088
1089 Called when a client types 'kill' in the console
1090 =============
1091 */
1092
1093 void ClientKill_Now_TeamChange()
1094 {
1095         if(self.killindicator_teamchange == -1)
1096         {
1097                 self.team = -1;
1098                 JoinBestTeam( self, FALSE, FALSE );
1099         }
1100         else
1101                 SV_ChangeTeam(self.killindicator_teamchange - 1);
1102 }
1103
1104 void ClientKill_Now()
1105 {
1106         if(self.killindicator_teamchange)
1107                 ClientKill_Now_TeamChange();
1108
1109         // in any case:
1110         Damage(self, self, self, 100000, DEATH_KILL, self.origin, '0 0 0');
1111
1112         if(self.killindicator)
1113         {
1114                 dprint("Cleaned up after a leaked kill indicator.\n");
1115                 remove(self.killindicator);
1116                 self.killindicator = world;
1117         }
1118 }
1119 void KillIndicator_Think()
1120 {
1121         if (!self.owner.modelindex)
1122         {
1123                 self.owner.killindicator = world;
1124                 remove(self);
1125                 return;
1126         }
1127
1128         if(self.cnt <= 0)
1129         {
1130                 self = self.owner;
1131                 ClientKill_Now(); // no oldself needed
1132                 return;
1133         }
1134         else
1135         {
1136                 if(self.cnt <= 10)
1137                         setmodel(self, strcat("models/sprites/", ftos(self.cnt), ".spr32"));
1138                 if(clienttype(self.owner) == CLIENTTYPE_REAL)
1139                 {
1140                         if(self.cnt <= 10)
1141                                 announce(self.owner, strcat("announcer/robotic/", ftos(self.cnt), ".wav"));
1142                         if(self.owner.killindicator_teamchange)
1143                         {
1144                                 if(self.owner.killindicator_teamchange == -1)
1145                                         centerprint(self.owner, strcat("Changing team in ", ftos(self.cnt), " seconds"));
1146                                 else
1147                                         centerprint(self.owner, strcat("Changing to ", ColoredTeamName(self.owner.killindicator_teamchange), " in ", ftos(self.cnt), " seconds"));
1148                         }
1149                         else
1150                                 centerprint(self.owner, strcat("^1Suicide in ", ftos(self.cnt), " seconds"));
1151                 }
1152                 self.nextthink = time + 1;
1153                 self.cnt -= 1;
1154         }
1155 }
1156
1157 void ClientKill_TeamChange (float targetteam) // 0 = don't change, -1 = auto
1158 {
1159         float killtime;
1160         entity e;
1161         killtime = cvar("g_balance_kill_delay");
1162
1163         if(g_race_qualifying)
1164                 killtime = 0;
1165
1166         self.killindicator_teamchange = targetteam;
1167
1168         if(!self.killindicator)
1169         {
1170                 if(killtime <= 0 || !self.modelindex || self.deadflag != DEAD_NO)
1171                 {
1172                         ClientKill_Now();
1173                 }
1174                 else
1175                 {
1176                         self.killindicator = spawn();
1177                         self.killindicator.owner = self;
1178                         self.killindicator.scale = 0.5;
1179                         setattachment(self.killindicator, self, "");
1180                         setorigin(self.killindicator, '0 0 52');
1181                         self.killindicator.think = KillIndicator_Think;
1182                         self.killindicator.nextthink = time + (self.lip) * 0.05;
1183                         self.killindicator.cnt = ceil(killtime);
1184                         self.killindicator.count = bound(0, ceil(killtime), 10);
1185                         sprint(self, strcat("^1You'll be dead in ", ftos(self.killindicator.cnt), " seconds\n"));
1186
1187                         for(e = world; (e = find(e, classname, "body")) != world; )
1188                         {
1189                                 if(e.enemy != self)
1190                                         continue;
1191                                 e.killindicator = spawn();
1192                                 e.killindicator.owner = e;
1193                                 e.killindicator.scale = 0.5;
1194                                 setattachment(e.killindicator, e, "");
1195                                 setorigin(e.killindicator, '0 0 52');
1196                                 e.killindicator.think = KillIndicator_Think;
1197                                 e.killindicator.nextthink = time + (e.lip) * 0.05;
1198                                 e.killindicator.cnt = ceil(killtime);
1199                         }
1200                         self.lip = 0;
1201                 }
1202         }
1203         if(self.killindicator)
1204         {
1205                 if(targetteam)
1206                         self.killindicator.colormod = TeamColor(targetteam);
1207                 else
1208                         self.killindicator.colormod = '0 0 0';
1209         }
1210 }
1211
1212 void ClientKill (void)
1213 {
1214         ClientKill_TeamChange(0);
1215 }
1216
1217 void DoTeamChange(float destteam)
1218 {
1219         float t, c0;
1220         if(!teams_matter)
1221         {
1222                 if(destteam >= 0)
1223                         SetPlayerColors(self, destteam);
1224                 return;
1225         }
1226         if(self.classname == "player")
1227         if(destteam == -1)
1228         {
1229                 CheckAllowedTeams(self);
1230                 t = FindSmallestTeam(self, TRUE);
1231                 switch(self.team)
1232                 {
1233                         case COLOR_TEAM1: c0 = c1; break;
1234                         case COLOR_TEAM2: c0 = c2; break;
1235                         case COLOR_TEAM3: c0 = c3; break;
1236                         case COLOR_TEAM4: c0 = c4; break;
1237                         default:          c0 = 999;
1238                 }
1239                 switch(t)
1240                 {
1241                         case 1:
1242                                 if(c0 > c1)
1243                                         destteam = COLOR_TEAM1;
1244                                 break;
1245                         case 2:
1246                                 if(c0 > c2)
1247                                         destteam = COLOR_TEAM2;
1248                                 break;
1249                         case 3:
1250                                 if(c0 > c3)
1251                                         destteam = COLOR_TEAM3;
1252                                 break;
1253                         case 4:
1254                                 if(c0 > c4)
1255                                         destteam = COLOR_TEAM4;
1256                                 break;
1257                 }
1258                 if(destteam == -1)
1259                         return;
1260         }
1261         if(destteam == self.team && destteam >= 0 && !self.killindicator)
1262                 return;
1263         ClientKill_TeamChange(destteam);
1264 }
1265
1266 void FixClientCvars(entity e)
1267 {
1268         // send prediction settings to the client
1269         stuffcmd(e, "\nin_bindmap 0 0\n");
1270         if(g_race || g_cts)
1271                 stuffcmd(e, "cl_cmd settemp cl_movecliptokeyboard 2\n");
1272         /*
1273          * we no longer need to stuff this. Remove this comment block if you feel
1274          * 2.3 and higher (or was it 2.2.3?) don't need these any more
1275         stuffcmd(e, strcat("cl_gravity ", ftos(cvar("sv_gravity")), "\n"));
1276         stuffcmd(e, strcat("cl_movement_accelerate ", ftos(cvar("sv_accelerate")), "\n"));
1277         stuffcmd(e, strcat("cl_movement_friction ", ftos(cvar("sv_friction")), "\n"));
1278         stuffcmd(e, strcat("cl_movement_maxspeed ", ftos(cvar("sv_maxspeed")), "\n"));
1279         stuffcmd(e, strcat("cl_movement_airaccelerate ", ftos(cvar("sv_airaccelerate")), "\n"));
1280         stuffcmd(e, strcat("cl_movement_maxairspeed ", ftos(cvar("sv_maxairspeed")), "\n"));
1281         stuffcmd(e, strcat("cl_movement_stopspeed ", ftos(cvar("sv_stopspeed")), "\n"));
1282         stuffcmd(e, strcat("cl_movement_jumpvelocity ", ftos(cvar("sv_jumpvelocity")), "\n"));
1283         stuffcmd(e, strcat("cl_movement_stepheight ", ftos(cvar("sv_stepheight")), "\n"));
1284         stuffcmd(e, strcat("set cl_movement_friction_on_land ", ftos(cvar("sv_friction_on_land")), "\n"));
1285         stuffcmd(e, strcat("set cl_movement_airaccel_qw ", ftos(cvar("sv_airaccel_qw")), "\n"));
1286         stuffcmd(e, strcat("set cl_movement_airaccel_sideways_friction ", ftos(cvar("sv_airaccel_sideways_friction")), "\n"));
1287         stuffcmd(e, "cl_movement_edgefriction 1\n");
1288          */
1289 }
1290
1291 /*
1292 =============
1293 ClientConnect
1294
1295 Called when a client connects to the server
1296 =============
1297 */
1298 //void ctf_clientconnect();
1299 string ColoredTeamName(float t);
1300 void DecodeLevelParms (void);
1301 //void dom_player_join_team(entity pl);
1302 void ClientConnect (void)
1303 {
1304         float t;
1305
1306         if(self.flags & FL_CLIENT)
1307         {
1308                 print("Warning: ClientConnect, but already connected!\n");
1309                 return;
1310         }
1311
1312         if(Ban_MaybeEnforceBan(self))
1313                 return;
1314
1315         DecodeLevelParms();
1316
1317         self.classname = "player_joining";
1318
1319         self.flags = FL_CLIENT;
1320         self.version_nagtime = time + 10 + random() * 10;
1321
1322         if(player_count<0)
1323         {
1324                 dprint("BUG player count is lower than zero, this cannot happen!\n");
1325                 player_count = 0;
1326         }
1327
1328         PlayerScore_Attach(self);
1329         ClientData_Attach();
1330
1331         bot_clientconnect();
1332
1333         playerdemo_init();
1334
1335         anticheat_init();
1336         
1337         race_PreSpawnObserver();
1338
1339         //if(g_domination)
1340         //      dom_player_join_team(self);
1341
1342         JoinBestTeam(self, FALSE, FALSE); // if the team number is valid, keep it
1343
1344         if((cvar("sv_spectate") == 1 && !g_lms) || cvar("g_campaign")) {
1345                 self.classname = "observer";
1346         } else {
1347                 if(teams_matter)
1348                 {
1349                         if(cvar("g_balance_teams") || cvar("g_balance_teams_force"))
1350                         {
1351                                 self.classname = "player";
1352                                 campaign_bots_may_start = 1;
1353                         }
1354                         else
1355                         {
1356                                 self.classname = "observer"; // do it anyway
1357                         }
1358                 }
1359                 else
1360                 {
1361                         self.classname = "player";
1362                         campaign_bots_may_start = 1;
1363                 }
1364         }
1365
1366         self.playerid = (playerid_last = playerid_last + 1);
1367
1368         if(cvar("sv_eventlog"))
1369                 GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":", ((clienttype(self) == CLIENTTYPE_REAL) ? self.netaddress : "bot"), ":", self.netname));
1370
1371         LogTeamchange(self.playerid, self.team, 1);
1372
1373         self.just_joined = TRUE;  // stop spamming the eventlog with additional lines when the client connects
1374
1375         self.netname_previous = strzone(self.netname);
1376
1377         bprint("^4", self.netname, "^4 connected");
1378
1379         if(g_domination || g_ctf)
1380                 bprint(" and joined the ", ColoredTeamName(self.team));
1381
1382         bprint("\n");
1383
1384         self.welcomemessage_time = 0;
1385
1386         stuffcmd(self, strcat(clientstuff, "\n"));
1387         stuffcmd(self, strcat("exec maps/", mapname, ".cfg\n"));
1388         stuffcmd(self, "cl_particles_reloadeffects\n");
1389
1390         FixClientCvars(self);
1391
1392         // spawnfunc_waypoint sprites
1393         WaypointSprite_InitClient(self);
1394
1395         // Wazat's grappling hook
1396         SetGrappleHookBindings();
1397
1398         // get autoswitch state from player when he toggles it
1399         stuffcmd(self, "alias autoswitch \"set cl_autoswitch $1 ; cmd autoswitch $1\"\n"); // default.cfg-ed in 2.4.1
1400
1401         // get version info from player
1402         stuffcmd(self, "cmd clientversion $gameversion\n");
1403
1404         // get other cvars from player
1405         GetCvars(0);
1406
1407         // set cvar for team scoreboard
1408         stuffcmd(self, strcat("set teamplay ", ftos(teamplay), "\n"));
1409
1410         // notify about available teams
1411         if(teams_matter)
1412         {
1413                 CheckAllowedTeams(self);
1414                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1415                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1416         }
1417         else
1418                 stuffcmd(self, "set _teams_available 0\n");
1419
1420         stuffcmd(self, strcat("set gametype ", ftos(game), "\n"));
1421
1422         if(g_arena || g_ca)
1423         {
1424                 self.classname = "observer";
1425                 if(g_arena)
1426                         Spawnqueue_Insert(self);
1427         }
1428         /*else if(g_ctf)
1429         {
1430                 ctf_clientconnect();
1431         }*/
1432
1433         if(teams_matter || sv_cheats)
1434                 attach_entcs();
1435
1436         bot_relinkplayerlist();
1437
1438         self.spectatortime = time;
1439         if(blockSpectators)
1440         {
1441                 sprint(self, strcat("^7You have to become a player within the next ", ftos(cvar("g_maxplayers_spectator_blocktime")), " seconds, otherwise you will be kicked, because spectators aren't allowed at this time!\n"));
1442         }
1443
1444         self.jointime = time;
1445         self.allowedTimeouts = cvar("sv_timeout_number");
1446
1447         if(clienttype(self) == CLIENTTYPE_REAL)
1448         {
1449                 if(cvar("g_bugrigs") || g_weaponarena == WEPBIT_TUBA)
1450                         stuffcmd(self, "cl_cmd settemp chase_active 1\n");
1451         }
1452
1453         if(g_lms)
1454         {
1455                 if(PlayerScore_Add(self, SP_LMS_LIVES, LMS_NewPlayerLives()) <= 0)
1456                 {
1457                         PlayerScore_Add(self, SP_LMS_RANK, 666);
1458                         self.frags = FRAGS_SPECTATOR;
1459                 }
1460         }
1461
1462         if(!sv_foginterval && world.fog != "")
1463                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1464
1465         SoundEntity_Attach(self);
1466
1467         if(cvar("g_hitplots") || strstrofs(strcat(" ", cvar_string("g_hitplots_individuals"), " "), strcat(" ", self.netaddress, " "), 0) >= 0)
1468         {
1469                 self.hitplotfh = fopen(strcat("hits-", matchid, "-", self.netaddress, "-", ftos(self.playerid), ".plot"), FILE_WRITE);
1470                 fputs(self.hitplotfh, strcat("#name ", self.netname, "\n"));
1471         }
1472         else
1473                 self.hitplotfh = -1;
1474
1475         if(g_race || g_cts) {
1476                 string rr;
1477                 if(g_cts)
1478                         rr = CTS_RECORD;
1479                 else
1480                         rr = RACE_RECORD;
1481                 t = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "time")));
1482
1483                 race_send_recordtime(t, MSG_ONE);
1484                 race_send_speedaward(MSG_ONE);
1485
1486                 speedaward_alltimebest = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/speed")));
1487                 speedaward_alltimebest_holder = db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/netname"));
1488                 race_send_speedaward_alltimebest(MSG_ONE);
1489         }
1490         else if(cvar("sv_teamnagger") && !g_ca) // teamnagger is currently bad for ca
1491                 send_CSQC_teamnagger();
1492 }
1493
1494 /*
1495 =============
1496 ClientDisconnect
1497
1498 Called when a client disconnects from the server
1499 =============
1500 */
1501 .entity chatbubbleentity;
1502 .entity teambubbleentity;
1503 void ReadyCount();
1504 void ClientDisconnect (void)
1505 {
1506         if not(self.flags & FL_CLIENT)
1507         {
1508                 print("Warning: ClientDisconnect without ClientConnect\n");
1509                 return;
1510         }
1511
1512         if(self.hitplotfh >= 0)
1513         {
1514                 fclose(self.hitplotfh);
1515                 self.hitplotfh = -1;
1516         }
1517
1518         anticheat_report();
1519         anticheat_shutdown();
1520
1521         playerdemo_shutdown();
1522
1523         bot_clientdisconnect();
1524
1525         if(self.entcs)
1526                 detach_entcs();
1527
1528         if(cvar("sv_eventlog"))
1529                 GameLogEcho(strcat(":part:", ftos(self.playerid)));
1530         bprint ("^4",self.netname);
1531         bprint ("^4 disconnected\n");
1532
1533         SoundEntity_Detach(self);
1534
1535         DropAllRunes(self);
1536         kh_Key_DropAll(self, TRUE);
1537
1538         Portal_ClearAll(self);
1539
1540         if(self.flagcarried)
1541                 DropFlag(self.flagcarried, world, world);
1542         if(self.ballcarried)
1543                 DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
1544
1545         // Here, everything has been done that requires this player to be a client.
1546
1547         self.flags &~= FL_CLIENT;
1548
1549         if (self.chatbubbleentity)
1550                 remove (self.chatbubbleentity);
1551
1552         if (self.teambubbleentity)
1553                 remove (self.teambubbleentity);
1554
1555         if (self.killindicator)
1556                 remove (self.killindicator);
1557
1558         WaypointSprite_PlayerGone();
1559
1560         bot_relinkplayerlist();
1561
1562         // remove laserdot
1563         if(self.weaponentity)
1564                 if(self.weaponentity.lasertarget)
1565                         remove(self.weaponentity.lasertarget);
1566
1567         if(g_arena)
1568         {
1569                 Spawnqueue_Unmark(self);
1570                 Spawnqueue_Remove(self);
1571         }
1572
1573         ClientData_Detach();
1574         PlayerScore_Detach(self);
1575
1576         if(self.netname_previous)
1577                 strunzone(self.netname_previous);
1578         if(self.clientstatus)
1579                 strunzone(self.clientstatus);
1580
1581         ClearPlayerSounds();
1582
1583         if(self.personal)
1584                 remove(self.personal);
1585
1586         self.playerid = 0;
1587         ReadyCount();
1588
1589         // free cvars
1590         GetCvars(-1);
1591 }
1592
1593 .float BUTTON_CHAT;
1594 void ChatBubbleThink()
1595 {
1596         self.nextthink = time;
1597         if (!self.owner.modelindex || self.owner.chatbubbleentity != self)
1598         {
1599                 if(self.owner) // but why can that ever be world?
1600                         self.owner.chatbubbleentity = world;
1601                 remove(self);
1602                 return;
1603         }
1604         if ((self.owner.BUTTON_CHAT && !self.owner.deadflag)
1605 #ifdef TETRIS
1606                 || self.owner.tetris_on
1607 #endif
1608         )
1609                 self.model = self.mdl;
1610         else
1611                 self.model = "";
1612 };
1613
1614 void UpdateChatBubble()
1615 {
1616         if (!self.modelindex)
1617                 return;
1618         // spawn a chatbubble entity if needed
1619         if (!self.chatbubbleentity)
1620         {
1621                 self.chatbubbleentity = spawn();
1622                 self.chatbubbleentity.owner = self;
1623                 self.chatbubbleentity.exteriormodeltoclient = self;
1624                 self.chatbubbleentity.think = ChatBubbleThink;
1625                 self.chatbubbleentity.nextthink = time;
1626                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1627                 //setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1628                 setorigin(self.chatbubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1629                 setattachment(self.chatbubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1630                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1631                 self.chatbubbleentity.model = "";
1632                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1633         }
1634 }
1635
1636
1637 void TeamBubbleThink()
1638 {
1639         self.nextthink = time;
1640         if (!self.owner.modelindex || self.owner.teambubbleentity != self)
1641         {
1642                 if(self.owner) // but why can that ever be world?
1643                         self.owner.teambubbleentity = world;
1644                 remove(self);
1645                 return;
1646         }
1647 //      setorigin(self, self.owner.origin + '0 0 15' + self.owner.maxs_z * '0 0 1');  // bandwidth hog. setattachment does this now
1648         if (self.owner.BUTTON_CHAT || self.owner.deadflag || self.owner.killindicator)
1649                 self.model = "";
1650         else
1651                 self.model = self.mdl;
1652
1653 };
1654
1655 float TeamBubble_customizeentityforclient()
1656 {
1657         return (self.owner != other && self.owner.team == other.team && other.killcount > -666);
1658 }
1659
1660 void UpdateTeamBubble()
1661 {
1662         if (!self.modelindex || !teams_matter)
1663                 return;
1664         // spawn a teambubble entity if needed
1665         if (!self.teambubbleentity && teams_matter)
1666         {
1667                 self.teambubbleentity = spawn();
1668                 self.teambubbleentity.owner = self;
1669                 self.teambubbleentity.exteriormodeltoclient = self;
1670                 self.teambubbleentity.think = TeamBubbleThink;
1671                 self.teambubbleentity.nextthink = time;
1672                 setmodel(self.teambubbleentity, "models/misc/teambubble.spr"); // precision set below
1673 //              setorigin(self.teambubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1674                 setorigin(self.teambubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1675                 setattachment(self.teambubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1676                 self.teambubbleentity.mdl = self.teambubbleentity.model;
1677                 self.teambubbleentity.model = self.teambubbleentity.mdl;
1678                 self.teambubbleentity.customizeentityforclient = TeamBubble_customizeentityforclient;
1679                 self.teambubbleentity.effects = EF_LOWPRECISION;
1680         }
1681 }
1682
1683 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1684 // added to the model skins
1685 /*void UpdateColorModHack()
1686 {
1687         local float c;
1688         c = self.clientcolors & 15;
1689         // LordHavoc: only bothering to support white, green, red, yellow, blue
1690              if (!teams_matter) self.colormod = '0 0 0';
1691         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1692         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1693         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1694         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1695         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1696         else self.colormod = '1 1 1';
1697 };*/
1698
1699 void respawn(void)
1700 {
1701         CopyBody(1);
1702         self.effects |= EF_NODRAW; // prevent another CopyBody
1703         PutClientInServer();
1704 }
1705
1706 void play_countdown(float finished, string samp)
1707 {
1708         if(clienttype(self) == CLIENTTYPE_REAL)
1709                 if(floor(finished - time - frametime) != floor(finished - time))
1710                         if(finished - time < 6)
1711                                 sound (self, CHAN_AUTO, samp, VOL_BASE, ATTN_NORM);
1712 }
1713
1714 /**
1715  * When sv_timeout is used this function returs strings like
1716  * "Timeout begins in 2 seconds!\n" or "Timeout ends in 23 seconds!\n".
1717  * Called by centerprint functions
1718  * @param addOneSecond boolean, set to 1 if the welcome-message centerprint asks for the text
1719  */
1720 string getTimeoutText(float addOneSecond) {
1721         if (!cvar("sv_timeout") || !timeoutStatus)
1722                 return "";
1723
1724         local string retStr;
1725         if (timeoutStatus == 1) {
1726                 if (addOneSecond == 1) {
1727                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime + 1), " seconds!\n");
1728                 }
1729                 else {
1730                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime), " seconds!\n");
1731                 }
1732                 return retStr;
1733         }
1734         else if (timeoutStatus == 2) {
1735                 if (addOneSecond) {
1736                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime + 1), " seconds!\n");
1737                         //don't show messages like "Timeout ends in 0 seconds"...
1738                         if ((remainingTimeoutTime + 1) > 0)
1739                                 return retStr;
1740                         else
1741                                 return "";
1742                 }
1743                 else {
1744                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime), " seconds!\n");
1745                         //don't show messages like "Timeout ends in 0 seconds"...
1746                         if (remainingTimeoutTime > 0)
1747                                 return retStr;
1748                         else
1749                                 return "";
1750                 }
1751         }
1752         else return "";
1753 }
1754
1755 void player_powerups (void)
1756 {
1757         if((self.items & IT_USING_JETPACK) && !self.deadflag)
1758         {
1759                 SoundEntity_StartSound(self, CHAN_PLAYER, "misc/jetpack_fly.wav", VOL_BASE, cvar("g_jetpack_attenuation"));
1760                 self.modelflags |= MF_ROCKET;
1761         }
1762         else
1763         {
1764                 SoundEntity_StopSound(self, CHAN_PLAYER);
1765                 self.modelflags &~= MF_ROCKET;
1766         }
1767
1768         self.effects &~= (EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT | EF_FLAME | EF_NODEPTHTEST);
1769
1770         if(!self.modelindex || self.deadflag) // don't apply the flags if the player is gibbed
1771                 return;
1772         
1773         Fire_ApplyDamage(self);
1774         Fire_ApplyEffect(self);
1775
1776         if (g_minstagib)
1777         {
1778                 self.effects |= EF_FULLBRIGHT;
1779
1780                 if (self.items & IT_STRENGTH)
1781                 {
1782                         play_countdown(self.strength_finished, "misc/poweroff.wav");
1783                         if (time > self.strength_finished)
1784                         {
1785                                 self.alpha = default_player_alpha;
1786                                 self.exteriorweaponentity.alpha = default_weapon_alpha;
1787                                 self.items &~= IT_STRENGTH;
1788                                 sprint(self, "^3Invisibility has worn off\n");
1789                         }
1790                 }
1791                 else
1792                 {
1793                         if (time < self.strength_finished)
1794                         {
1795                                 self.alpha = g_minstagib_invis_alpha;
1796                                 self.exteriorweaponentity.alpha = g_minstagib_invis_alpha;
1797                                 self.items |= IT_STRENGTH;
1798                                 sprint(self, "^3You are invisible\n");
1799                         }
1800                 }
1801
1802                 if (self.items & IT_INVINCIBLE)
1803                 {
1804                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
1805                         if (time > self.invincible_finished && cvar("g_balance_powerup_timer"))
1806                         {
1807                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1808                                 sprint(self, "^3Speed has worn off\n");
1809                         }
1810                 }
1811                 else
1812                 {
1813                         if (time < self.invincible_finished)
1814                         {
1815                                 self.items = self.items | IT_INVINCIBLE;
1816                                 sprint(self, "^3You are on speed\n");
1817                         }
1818                 }
1819                 return;
1820         }
1821
1822         if (self.items & IT_STRENGTH)
1823         {
1824                 play_countdown(self.strength_finished, "misc/poweroff.wav");
1825                 self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1826                 if (time > self.strength_finished && cvar("g_balance_powerup_timer"))
1827                 {
1828                         self.items = self.items - (self.items & IT_STRENGTH);
1829                         sprint(self, "^3Strength has worn off\n");
1830                 }
1831         }
1832         else
1833         {
1834                 if (time < self.strength_finished)
1835                 {
1836                         self.items = self.items | IT_STRENGTH;
1837                         sprint(self, "^3Strength infuses your weapons with devastating power\n");
1838                 }
1839         }
1840         if (self.items & IT_INVINCIBLE)
1841         {
1842                 play_countdown(self.invincible_finished, "misc/poweroff.wav");
1843                 self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1844                 if (time > self.invincible_finished && cvar("g_balance_powerup_timer"))
1845                 {
1846                         self.items = self.items - (self.items & IT_INVINCIBLE);
1847                         sprint(self, "^3Shield has worn off\n");
1848                 }
1849         }
1850         else
1851         {
1852                 if (time < self.invincible_finished)
1853                 {
1854                         self.items = self.items | IT_INVINCIBLE;
1855                         sprint(self, "^3Shield surrounds you\n");
1856                 }
1857         }
1858
1859         if(cvar("g_nodepthtestplayers"))
1860                 self.effects = self.effects | EF_NODEPTHTEST;
1861
1862         if(cvar("g_fullbrightplayers"))
1863                 self.effects = self.effects | EF_FULLBRIGHT;
1864
1865         // midair gamemode: damage only while in the air
1866         // if in midair mode, being on ground grants temporary invulnerability
1867         // (this is so that multishot weapon don't clear the ground flag on the
1868         // first damage in the frame, leaving the player vulnerable to the
1869         // remaining hits in the same frame)
1870         if (self.flags & FL_ONGROUND)
1871         if (g_midair)
1872                 self.spawnshieldtime = max(self.spawnshieldtime, time + cvar("g_midair_shieldtime"));
1873
1874         if (time >= game_starttime)
1875         if (time < self.spawnshieldtime)
1876                 self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1877 }
1878
1879 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1880 {
1881         if(current > stable)
1882                 return current;
1883         else if(current > stable - 0.25) // when close enough, "snap"
1884                 return stable;
1885         else
1886                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1887 }
1888
1889 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1890 {
1891         if(current < stable)
1892                 return current;
1893         else if(current < stable + 0.25) // when close enough, "snap"
1894                 return stable;
1895         else
1896                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1897 }
1898
1899 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit)
1900 {
1901         if(current > rotstable)
1902         {
1903                 if(rotframetime > 0)
1904                 {
1905                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1906                         current = max(rotstable, current - rotlinear * rotframetime);
1907                 }
1908         }
1909         else if(current < regenstable)
1910         {
1911                 if(regenframetime > 0)
1912                 {
1913                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1914                         current = min(regenstable, current + regenlinear * regenframetime);
1915                 }
1916         }
1917
1918         if(current > limit)
1919                 current = limit;
1920
1921         return current;
1922 }
1923
1924 void player_regen (void)
1925 {
1926         float minh, mina, minf, maxh, maxa, maxf, limith, limita, limitf, max_mod, regen_mod, rot_mod, limit_mod;
1927         maxh = cvar("g_balance_health_rotstable");
1928         maxa = cvar("g_balance_armor_rotstable");
1929         maxf = cvar("g_balance_fuel_rotstable");
1930         minh = cvar("g_balance_health_regenstable");
1931         mina = cvar("g_balance_armor_regenstable");
1932         minf = cvar("g_balance_fuel_regenstable");
1933         limith = cvar("g_balance_health_limit");
1934         limita = cvar("g_balance_armor_limit");
1935         limitf = cvar("g_balance_fuel_limit");
1936
1937         max_mod = regen_mod = rot_mod = limit_mod = 1;
1938
1939         if (self.runes & RUNE_REGEN)
1940         {
1941                 if (self.runes & CURSE_VENOM) // do we have both rune/curse?
1942                 {
1943                         regen_mod = cvar("g_balance_rune_regen_combo_regenrate");
1944                         max_mod = cvar("g_balance_rune_regen_combo_hpmod");
1945                         limit_mod = cvar("g_balance_rune_regen_combo_limitmod");
1946                 }
1947                 else
1948                 {
1949                         regen_mod = cvar("g_balance_rune_regen_regenrate");
1950                         max_mod = cvar("g_balance_rune_regen_hpmod");
1951                         limit_mod = cvar("g_balance_rune_regen_limitmod");
1952                 }
1953         }
1954         else if (self.runes & CURSE_VENOM)
1955         {
1956                 max_mod = cvar("g_balance_curse_venom_hpmod");
1957                 if (self.runes & RUNE_REGEN) // do we have both rune/curse?
1958                         rot_mod = cvar("g_balance_rune_regen_combo_rotrate");
1959                 else
1960                         rot_mod = cvar("g_balance_curse_venom_rotrate");
1961                 limit_mod = cvar("g_balance_curse_venom_limitmod");
1962                 //if (!self.runes & RUNE_REGEN)
1963                 //      rot_mod = cvar("g_balance_curse_venom_rotrate");
1964         }
1965         maxh = maxh * max_mod;
1966         //maxa = maxa * max_mod;
1967         //maxf = maxf * max_mod;
1968         minh = minh * max_mod;
1969         //mina = mina * max_mod;
1970         //minf = minf * max_mod;
1971         limith = limith * limit_mod;
1972         limita = limita * limit_mod;
1973         //limitf = limitf * limit_mod;
1974
1975         if(g_lms && g_ca)
1976                 rot_mod = 0;
1977
1978         if (!g_minstagib && !g_ca && (!g_lms || cvar("g_lms_regenerate")))
1979         {
1980                 self.armorvalue = CalcRotRegen(self.armorvalue, mina, cvar("g_balance_armor_regen"), cvar("g_balance_armor_regenlinear"), regen_mod * frametime * (time > self.pauseregen_finished), maxa, cvar("g_balance_armor_rot"), cvar("g_balance_armor_rotlinear"), rot_mod * frametime * (time > self.pauserotarmor_finished), limita);
1981                 self.health = CalcRotRegen(self.health, minh, cvar("g_balance_health_regen"), cvar("g_balance_health_regenlinear"), regen_mod * frametime * (time > self.pauseregen_finished), maxh, cvar("g_balance_health_rot"), cvar("g_balance_health_rotlinear"), rot_mod * frametime * (time > self.pauserothealth_finished), limith);
1982
1983                 // if player rotted to death...  die!
1984                 if(self.health < 1)
1985                         self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
1986         }
1987
1988         if not(self.items & IT_UNLIMITED_WEAPON_AMMO)
1989                 self.ammo_fuel = CalcRotRegen(self.ammo_fuel, minf, cvar("g_balance_fuel_regen"), cvar("g_balance_fuel_regenlinear"), regen_mod * frametime * (time > self.pauseregen_finished) * (self.items & IT_FUEL_REGEN != 0), maxf, cvar("g_balance_fuel_rot"), cvar("g_balance_fuel_rotlinear"), rot_mod * frametime * (time > self.pauserotfuel_finished), limitf);
1990 }
1991
1992 float zoomstate_set;
1993 void SetZoomState(float z)
1994 {
1995         if(z != self.zoomstate)
1996         {
1997                 self.zoomstate = z;
1998                 ClientData_Touch(self);
1999         }
2000         zoomstate_set = 1;
2001 }
2002
2003 void GetPressedKeys(void) {
2004         if (self.movement_x > 0) // get if movement keys are pressed
2005         {       // forward key pressed
2006                 self.pressedkeys |= KEY_FORWARD;
2007                 self.pressedkeys &~= KEY_BACKWARD;
2008         }
2009         else if (self.movement_x < 0)
2010         {       // backward key pressed
2011                 self.pressedkeys |= KEY_BACKWARD;
2012                 self.pressedkeys &~= KEY_FORWARD;
2013         }
2014         else
2015         {       // no x input
2016                 self.pressedkeys &~= KEY_FORWARD;
2017                 self.pressedkeys &~= KEY_BACKWARD;
2018         }
2019
2020         if (self.movement_y > 0)
2021         {       // right key pressed
2022                 self.pressedkeys |= KEY_RIGHT;
2023                 self.pressedkeys &~= KEY_LEFT;
2024         }
2025         else if (self.movement_y < 0)
2026         {       // left key pressed
2027                 self.pressedkeys |= KEY_LEFT;
2028                 self.pressedkeys &~= KEY_RIGHT;
2029         }
2030         else
2031         {       // no y input
2032                 self.pressedkeys &~= KEY_RIGHT;
2033                 self.pressedkeys &~= KEY_LEFT;
2034         }
2035
2036         if (self.BUTTON_JUMP) // get if jump and crouch keys are pressed
2037                 self.pressedkeys |= KEY_JUMP;
2038         else
2039                 self.pressedkeys &~= KEY_JUMP;
2040         if (self.BUTTON_CROUCH)
2041                 self.pressedkeys |= KEY_CROUCH;
2042         else
2043                 self.pressedkeys &~= KEY_CROUCH;
2044 }
2045
2046 void update_stats (float number, float hit, float fired) {
2047 // self.stat_hit   = number + ((number==0) ? 1 : 64) * hit   * sv_accuracy_data_share;
2048 // self.stat_fired = number + ((number==0) ? 1 : 64) * fired * sv_accuracy_data_share;
2049
2050         if(number) {
2051                 self.stat_hit = number + 64 * hit * sv_accuracy_data_share;
2052                 self.stat_fired = number + 64 * fired * sv_accuracy_data_share;
2053         } else {
2054                 self.stat_hit = hit * sv_accuracy_data_share;
2055                 self.stat_fired = fired * sv_accuracy_data_share;
2056         }
2057 }
2058
2059 /*
2060 ======================
2061 spectate mode routines
2062 ======================
2063 */
2064
2065 .float weapon_count;
2066 void SpectateCopy(entity spectatee) {
2067         if(spectatee.weapon_count < WEP_LAST) {
2068                 update_stats (spectatee.weapon_count, spectatee.cvar_cl_accuracy_data_share * floor(spectatee.stats_hit[spectatee.weapon_count - 1]), spectatee.cvar_cl_accuracy_data_share * floor(spectatee.stats_fired[spectatee.weapon_count - 1]));
2069                 spectatee.weapon_count ++;
2070         } else
2071                 update_stats (0, spectatee.cvar_cl_accuracy_data_share * spectatee.stat_hit, spectatee.cvar_cl_accuracy_data_share * spectatee.stat_fired);
2072
2073         self.kh_state = spectatee.kh_state;
2074         self.armortype = spectatee.armortype;
2075         self.armorvalue = spectatee.armorvalue;
2076         self.ammo_cells = spectatee.ammo_cells;
2077         self.ammo_shells = spectatee.ammo_shells;
2078         self.ammo_nails = spectatee.ammo_nails;
2079         self.ammo_rockets = spectatee.ammo_rockets;
2080         self.ammo_fuel = spectatee.ammo_fuel;
2081         self.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
2082         self.health = spectatee.health;
2083         self.impulse = 0;
2084         self.items = spectatee.items;
2085         self.metertime = spectatee.metertime;
2086         self.strength_finished = spectatee.strength_finished;
2087         self.invincible_finished = spectatee.invincible_finished;
2088         self.pressedkeys = spectatee.pressedkeys;
2089         self.weapons = spectatee.weapons;
2090         self.switchweapon = spectatee.switchweapon;
2091         self.weapon = spectatee.weapon;
2092         self.punchangle = spectatee.punchangle;
2093         self.view_ofs = spectatee.view_ofs;
2094         self.v_angle = spectatee.v_angle;
2095         self.velocity = spectatee.velocity;
2096         self.dmg_take = spectatee.dmg_take;
2097         self.dmg_save = spectatee.dmg_save;
2098         self.dmg_inflictor = spectatee.dmg_inflictor;
2099         self.angles = spectatee.v_angle;
2100         self.fixangle = TRUE;
2101         setorigin(self, spectatee.origin);
2102         setsize(self, spectatee.mins, spectatee.maxs);
2103         SetZoomState(spectatee.zoomstate);
2104
2105         anticheat_spectatecopy(spectatee);
2106 }
2107
2108 float SpectateUpdate() {
2109         if(!self.enemy)
2110                 return 0;
2111
2112         if (self == self.enemy)
2113                 return 0;
2114
2115         if(self.enemy.classname != "player")
2116                 return 0;
2117
2118         SpectateCopy(self.enemy);
2119
2120         return 1;
2121 }
2122
2123 float SpectateNext() {
2124         other = find(self.enemy, classname, "player");
2125
2126         if (!other)
2127                 other = find(other, classname, "player");
2128
2129         if (other)
2130                 self.enemy = other;
2131
2132         if(self.enemy.classname == "player") {
2133                 msg_entity = self;
2134                 WriteByte(MSG_ONE, SVC_SETVIEW);
2135                 WriteEntity(MSG_ONE, self.enemy);
2136                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
2137                 self.movetype = MOVETYPE_NONE;
2138
2139                 self.enemy.weapon_count = 0;
2140
2141                 if(!SpectateUpdate())
2142                         PutObserverInServer();
2143
2144                 return 1;
2145         } else {
2146                 return 0;
2147         }
2148 }
2149
2150 /*
2151 =============
2152 ShowRespawnCountdown()
2153
2154 Update a respawn countdown display.
2155 =============
2156 */
2157 void ShowRespawnCountdown()
2158 {
2159         float number;
2160         if(self.deadflag == DEAD_NO) // just respawned?
2161                 return;
2162         else
2163         {
2164                 number = ceil(self.death_time - time);
2165                 if(number <= 0)
2166                         return;
2167                 if(number <= self.respawn_countdown)
2168                 {
2169                         self.respawn_countdown = number - 1;
2170                         if(ceil(self.death_time - (time + 0.5)) == number) // only say it if it is the same number even in 0.5s; to prevent overlapping sounds
2171                                 announce(self, strcat("announcer/robotic/", ftos(number), ".wav"));
2172                 }
2173         }
2174 }
2175
2176 void LeaveSpectatorMode()
2177 {
2178         if(isJoinAllowed()) {
2179                 if(!teams_matter || cvar("g_campaign") || cvar("g_balance_teams") || (self.wasplayer && cvar("g_changeteam_banned"))) {
2180                         self.classname = "player";
2181
2182                         if(cvar("g_campaign") || cvar("g_balance_teams") || cvar("g_balance_teams_force"))
2183                                 JoinBestTeam(self, FALSE, TRUE);
2184
2185                         if(cvar("g_campaign"))
2186                                 campaign_bots_may_start = 1;
2187
2188                         self.stat_count = WEP_LAST;
2189
2190                         PutClientInServer();
2191
2192                         if(self.classname == "player")
2193                                 bprint ("^4", self.netname, "^4 is playing now\n");
2194
2195                         if(!cvar("g_campaign"))
2196                                 centerprint(self,""); // clear MOTD
2197
2198                         return;
2199                 } else {
2200                         if (g_ca && self.caplayer) {
2201                         }       // do nothing
2202                         else
2203                                 stuffcmd(self,"menu_showteamselect\n");
2204                         return;
2205                 }
2206         }
2207         else {
2208                 //player may not join because of g_maxplayers is set
2209                 centerprint_atprio(self, CENTERPRIO_MAPVOTE, PREVENT_JOIN_TEXT);
2210         }
2211 }
2212
2213 /**
2214  * Determines whether the player is allowed to join. This depends on cvar
2215  * g_maxplayers, if it isn't used this function always return TRUE, otherwise
2216  * it checks whether the number of currently playing players exceeds g_maxplayers.
2217  * @return bool TRUE if the player is allowed to join, false otherwise
2218  */
2219 float isJoinAllowed() {
2220         if (!cvar("g_maxplayers"))
2221                 return TRUE;
2222
2223         local entity e;
2224         local float currentlyPlaying;
2225         FOR_EACH_REALPLAYER(e) {
2226                 if(e.classname == "player")
2227                         currentlyPlaying += 1;
2228         }
2229         if(currentlyPlaying < cvar("g_maxplayers"))
2230                 return TRUE;
2231
2232         return FALSE;
2233 }
2234
2235 /**
2236  * Checks whether the client is an observer or spectator, if so, he will get kicked after
2237  * g_maxplayers_spectator_blocktime seconds
2238  */
2239 void checkSpectatorBlock() {
2240         if(self.classname == "spectator" || self.classname == "observer") {
2241                 if( time > (self.spectatortime + cvar("g_maxplayers_spectator_blocktime")) ) {
2242                         sprint(self, "^7You were kicked from the server because you are spectator and spectators aren't allowed at the moment.\n");
2243                         dropclient(self);
2244                 }
2245         }
2246 }
2247
2248 float vercmp_recursive(string v1, string v2)
2249 {
2250         float dot1, dot2;
2251         string s1, s2;
2252         float r;
2253
2254         dot1 = strstrofs(v1, ".", 0);
2255         dot2 = strstrofs(v2, ".", 0);
2256         if(dot1 == -1)
2257                 s1 = v1;
2258         else
2259                 s1 = substring(v1, 0, dot1);
2260         if(dot2 == -1)
2261                 s2 = v2;
2262         else
2263                 s2 = substring(v2, 0, dot2);
2264
2265         r = stof(s1) - stof(s2);
2266         if(r != 0)
2267                 return r;
2268
2269         r = strcasecmp(s1, s2);
2270         if(r != 0)
2271                 return r;
2272
2273         if(dot1 == -1)
2274                 if(dot2 == -1)
2275                         return 0;
2276                 else
2277                         return -1;
2278         else
2279                 if(dot2 == -1)
2280                         return 1;
2281                 else
2282                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
2283 }
2284
2285 float vercmp(string v1, string v2)
2286 {
2287         if(strcasecmp(v1, v2) == 0) // early out check
2288                 return 0;
2289         return vercmp_recursive(v1, v2);
2290 }
2291
2292 void ObserverThink()
2293 {
2294         if (self.flags & FL_JUMPRELEASED) {
2295                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2296                         self.welcomemessage_time = 0;
2297                         self.flags &~= FL_JUMPRELEASED;
2298                         self.flags |= FL_SPAWNING;
2299                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
2300                         self.welcomemessage_time = 0;
2301                         self.flags &~= FL_JUMPRELEASED;
2302                         if(SpectateNext() == 1) {
2303                                 self.classname = "spectator";
2304                         }
2305                 }
2306         } else {
2307                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
2308                         self.flags |= FL_JUMPRELEASED;
2309                         if(self.flags & FL_SPAWNING)
2310                         {
2311                                 self.flags &~= FL_SPAWNING;
2312                                 LeaveSpectatorMode();
2313                                 return;
2314                         }
2315                 }
2316         }
2317         PrintWelcomeMessage(self);
2318 }
2319
2320 void SpectatorThink()
2321 {
2322         if (self.flags & FL_JUMPRELEASED) {
2323                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2324                         self.welcomemessage_time = 0;
2325                         self.flags &~= FL_JUMPRELEASED;
2326                         self.flags |= FL_SPAWNING;
2327                 } else if(self.BUTTON_ATCK) {
2328                         self.welcomemessage_time = 0;
2329                         self.flags &~= FL_JUMPRELEASED;
2330                         if(SpectateNext() == 1) {
2331                                 self.classname = "spectator";
2332                         } else {
2333                                 self.classname = "observer";
2334                                 self.stat_count = WEP_LAST;
2335                                 PutClientInServer();
2336                         }
2337                 } else if (self.BUTTON_ATCK2) {
2338                         self.welcomemessage_time = 0;
2339                         self.flags &~= FL_JUMPRELEASED;
2340                         self.classname = "observer";
2341                         self.stat_count = WEP_LAST;
2342                         PutClientInServer();
2343                 } else {
2344                         if(!SpectateUpdate())
2345                                 PutObserverInServer();
2346                 }
2347         } else {
2348                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
2349                         self.flags |= FL_JUMPRELEASED;
2350                         if(self.flags & FL_SPAWNING)
2351                         {
2352                                 self.flags &~= FL_SPAWNING;
2353                                 LeaveSpectatorMode();
2354                                 return;
2355                         }
2356                 }
2357         }
2358
2359         PrintWelcomeMessage(self);
2360         self.flags |= FL_CLIENT | FL_NOTARGET;
2361 }
2362
2363 .float touchexplode_time;
2364
2365 /*
2366 =============
2367 PlayerPreThink
2368
2369 Called every frame for each client before the physics are run
2370 =============
2371 */
2372 void() ctf_setstatus;
2373 void() nexball_setstatus;
2374 .float items_added;
2375 void PlayerPreThink (void)
2376 {
2377         self.stat_game_starttime = game_starttime;
2378         self.stat_allow_oldnexbeam = cvar("g_allow_oldnexbeam");
2379         self.stat_leadlimit = cvar("leadlimit");
2380
2381         if(frametime)
2382         {
2383                 // physics frames: update anticheat stuff
2384                 anticheat_prethink();
2385         }
2386
2387         if(blockSpectators && frametime)
2388                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2389                 checkSpectatorBlock();
2390
2391         zoomstate_set = 0;
2392
2393         if(self.netname_previous != self.netname)
2394         {
2395                 if(cvar("sv_eventlog"))
2396                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname));
2397                 if(self.netname_previous)
2398                         strunzone(self.netname_previous);
2399                 self.netname_previous = strzone(self.netname);
2400         }
2401
2402         // version nagging
2403         if(self.version_nagtime)
2404                 if(self.cvar_g_nexuizversion)
2405                         if(time > self.version_nagtime)
2406                         {
2407                                 if(strstr(self.cvar_g_nexuizversion, "svn", 0) < 0)
2408                                 {
2409                                         if(strstr(cvar_string("g_nexuizversion"), "svn", 0) >= 0)
2410                                         {
2411                                                 dprint("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Nexuiz ", cvar_string("g_nexuizversion"), " (beta)^7, you have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1\n");
2412                                                 sprint(self, strcat("\{1}^1NOTE: ^7the server is running ^3Nexuiz ", cvar_string("g_nexuizversion"), " (beta)^7, you have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1\n"));
2413                                         }
2414                                         else
2415                                         {
2416                                                 float r;
2417                                                 r = vercmp(self.cvar_g_nexuizversion, cvar_string("g_nexuizversion"));
2418                                                 if(r < 0)
2419                                                 {
2420                                                         dprint("^1NOTE^7 to ", self.netname, "^7 - ^3Nexuiz ", cvar_string("g_nexuizversion"), "^7 is out, and you still have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1 - get the update from ^4http://www.nexuiz.com/^1!\n");
2421                                                         sprint(self, strcat("\{1}^1NOTE: ^3Nexuiz ", cvar_string("g_nexuizversion"), "^7 is out, and you still have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1 - get the update from ^4http://www.nexuiz.com/^1!\n"));
2422                                                 }
2423                                                 else if(r > 0)
2424                                                 {
2425                                                         dprint("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Nexuiz ", cvar_string("g_nexuizversion"), "^7, you have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1\n");
2426                                                         sprint(self, strcat("\{1}^1NOTE: ^7the server is running ^3Nexuiz ", cvar_string("g_nexuizversion"), "^7, you have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1\n"));
2427                                                 }
2428                                         }
2429                                 }
2430                                 self.version_nagtime = 0;
2431                         }
2432
2433         // GOD MODE info
2434         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
2435         {
2436                 sprint(self, strcat("godmode saved you ", ftos(self.max_armorvalue), " units of damage, cheater!\n"));
2437                 self.max_armorvalue = 0;
2438         }
2439
2440 #ifdef TETRIS
2441         if (TetrisPreFrame())
2442                 return;
2443 #endif
2444
2445         if(self.classname == "player") {
2446 //              if(self.netname == "Wazat")
2447 //                      bprint(self.classname, "\n");
2448
2449                 CheckRules_Player();
2450
2451                 PrintWelcomeMessage(self);
2452
2453                 if (intermission_running)
2454                 {
2455                         IntermissionThink ();   // otherwise a button could be missed between
2456                         return;                                 // the think tics
2457                 }
2458
2459                 if(self.teleport_time)
2460                 if(time > self.teleport_time)
2461                 {
2462                         self.teleport_time = 0;
2463                         self.effects = self.effects - (self.effects & EF_NODRAW);
2464                 }
2465
2466                 Nixnex_GiveCurrentWeapon();
2467
2468                 if(frametime > 0) // don't do this in cl_movement frames, just in server ticks
2469                         UpdateSelectedPlayer();
2470
2471                 //don't allow the player to turn around while game is paused!
2472                 if(timeoutStatus == 2) {
2473                         self.v_angle = self.lastV_angle;
2474                         self.angles = self.lastV_angle;
2475                         self.fixangle = TRUE;
2476                 }
2477
2478                 if(frametime)
2479                 {
2480                         if(cvar("gameversion") >= 20600) // only do this for 2.6 and above FIXME remove this check when making 2.6
2481                                 self.glowmod = colormapPaletteColor(self.clientcolors & 0x0F, TRUE) * 2;
2482                         player_powerups();
2483                 }
2484
2485                 if (self.deadflag != DEAD_NO)
2486                 {
2487                         float button_pressed, force_respawn;
2488                         if(self.personal && g_race_qualifying)
2489                         {
2490                                 if(time > self.death_time)
2491                                 {
2492                                         self.death_time = time + 1; // only retry once a second
2493                                         respawn();
2494                                         self.impulse = 141;
2495                                 }
2496                         }
2497                         else
2498                         {
2499                                 if(frametime)
2500                                         player_anim();
2501                                 button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2502                                 force_respawn = (g_lms || (g_ca) || cvar("g_forced_respawn"));
2503                                 if (self.deadflag == DEAD_DYING)
2504                                 {
2505                                         if(force_respawn)
2506                                                 self.deadflag = DEAD_RESPAWNING;
2507                                         else if(!button_pressed)
2508                                                 self.deadflag = DEAD_DEAD;
2509                                 }
2510                                 else if (self.deadflag == DEAD_DEAD)
2511                                 {
2512                                         if(button_pressed)
2513                                                 self.deadflag = DEAD_RESPAWNABLE;
2514                                 }
2515                                 else if (self.deadflag == DEAD_RESPAWNABLE)
2516                                 {
2517                                         if(!button_pressed)
2518                                                 self.deadflag = DEAD_RESPAWNING;
2519                                 }
2520                                 else if (self.deadflag == DEAD_RESPAWNING)
2521                                 {
2522                                         if(time > self.death_time)
2523                                         {
2524                                                 self.death_time = time + 1; // only retry once a second
2525                                                 respawn();
2526                                         }
2527                                 }
2528                                 ShowRespawnCountdown();
2529                         }
2530                         return;
2531                 }
2532
2533                 if(g_touchexplode)
2534                 if(time > self.touchexplode_time)
2535                 if(self.classname == "player")
2536                 if(self.deadflag == DEAD_NO)
2537                 if not(IS_INDEPENDENT_PLAYER(self))
2538                 FOR_EACH_PLAYER(other) if(self != other)
2539                 {
2540                         if(time > other.touchexplode_time)
2541                         if(other.classname == "player")
2542                         if(other.deadflag == DEAD_NO)
2543                         if not(IS_INDEPENDENT_PLAYER(other))
2544                         if(boxesoverlap(self.absmin, self.absmax, other.absmin, other.absmax))
2545                         {
2546                                 PlayerTouchExplode(self, other);
2547                                 self.touchexplode_time = other.touchexplode_time = time + 0.2;
2548                         }
2549                 }
2550
2551                 if(g_lms && !self.deadflag && cvar("g_lms_campcheck_interval"))
2552                 {
2553                         vector dist;
2554
2555                         // calculate player movement (in 2 dimensions only, so jumping on one spot doesn't count as movement)
2556                         dist = self.prevorigin - self.origin;
2557                         dist_z = 0;
2558                         self.lms_traveled_distance += fabs(vlen(dist));
2559
2560                         if((cvar("g_campaign") && !campaign_bots_may_start) || (time < game_starttime))
2561                         {
2562                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
2563                                 self.lms_traveled_distance = 0;
2564                         }
2565
2566                         if(time > self.lms_nextcheck)
2567                         {
2568                                 //sprint(self, "distance: ", ftos(self.lms_traveled_distance), "\n");
2569                                 if(self.lms_traveled_distance < cvar("g_lms_campcheck_distance"))
2570                                 {
2571                                         centerprint(self, cvar_string("g_lms_campcheck_message"));
2572                                         // FIXME KadaverJack: gibbing player here causes playermodel to bounce around, instead of eye.md3
2573                                         // I wasn't able to find out WHY that happens, so I put a workaround in place that shall prevent players from being gibbed :(
2574                                         Damage(self, self, self, bound(0, cvar("g_lms_campcheck_damage"), self.health + self.armorvalue * cvar("g_balance_armor_blockpercent") + 5), DEATH_CAMP, self.origin, '0 0 0');
2575                                 }
2576                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval");
2577                                 self.lms_traveled_distance = 0;
2578                         }
2579                 }
2580
2581                 self.prevorigin = self.origin;
2582
2583                 if ((self.BUTTON_CROUCH && !self.hook.state) || self.health <= g_bloodloss)
2584                 {
2585                         if (!self.crouch)
2586                         {
2587                                 self.crouch = TRUE;
2588                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2589                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2590                                 setanim(self, self.anim_duck, FALSE, TRUE, TRUE);
2591                         }
2592                 }
2593                 else
2594                 {
2595                         if (self.crouch)
2596                         {
2597                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, FALSE, self);
2598                                 if (!trace_startsolid)
2599                                 {
2600                                         self.crouch = FALSE;
2601                                         self.view_ofs = PL_VIEW_OFS;
2602                                         setsize (self, PL_MIN, PL_MAX);
2603                                 }
2604                         }
2605                 }
2606
2607                 if(self.health <= g_bloodloss && self.deadflag == DEAD_NO)
2608                 {
2609                         if(self.bloodloss_timer < time)
2610                         {
2611                                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
2612                                 self.bloodloss_timer = time + 0.5 + random() * 0.5;
2613                         }
2614                 }
2615
2616                 FixPlayermodel();
2617
2618                 GrapplingHookFrame();
2619
2620                 // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
2621                 //if(frametime)
2622                 {
2623                         self.items &~= self.items_added;
2624
2625                         W_WeaponFrame();
2626
2627                         self.items_added = 0;
2628                         if(self.items & IT_JETPACK)
2629                                 if(self.items & IT_FUEL_REGEN || self.ammo_fuel >= 0.01)
2630                                         self.items_added |= IT_FUEL;
2631
2632                         self.items |= self.items_added;
2633                 }
2634
2635                 player_regen();
2636                 if(frametime)
2637                         player_anim();
2638
2639                 if (g_minstagib)
2640                         minstagib_ammocheck();
2641
2642                 ctf_setstatus();
2643                 nexball_setstatus();
2644
2645                 self.dmg_team = max(0, self.dmg_team - cvar("g_teamdamage_resetspeed") * frametime);
2646
2647                 //self.angles_y=self.v_angle_y + 90;   // temp
2648         } else if(gameover) {
2649                 if (intermission_running)
2650                         IntermissionThink ();   // otherwise a button could be missed between
2651                 return;
2652         } else if(self.classname == "observer") {
2653                 ObserverThink();
2654         } else if(self.classname == "spectator") {
2655                 SpectatorThink();
2656         }
2657
2658         if(!zoomstate_set)
2659                 SetZoomState(self.BUTTON_ZOOM || (self.BUTTON_ATCK2 && self.weapon == WEP_NEX));
2660
2661         float oldspectatee_status;
2662         oldspectatee_status = self.spectatee_status;
2663         if(self.classname == "spectator")
2664                 self.spectatee_status = num_for_edict(self.enemy);
2665         else if(self.classname == "observer")
2666                 self.spectatee_status = num_for_edict(self);
2667         else
2668                 self.spectatee_status = 0;
2669         if(self.spectatee_status != oldspectatee_status)
2670         {
2671                 ClientData_Touch(self);
2672                 if(g_race || g_cts)
2673                         race_InitSpectator();
2674         }
2675
2676         if(self.teamkill_soundtime)
2677         if(time > self.teamkill_soundtime)
2678         {
2679                 self.teamkill_soundtime = 0;
2680
2681                 entity oldpusher, oldself;
2682
2683                 oldself = self; self = self.teamkill_soundsource;
2684                 oldpusher = self.pusher; self.pusher = oldself;
2685
2686                 PlayerSound(playersound_teamshoot, CHAN_VOICE, VOICETYPE_LASTATTACKER_ONLY);
2687
2688                 self.pusher = oldpusher;
2689                 self = oldself;
2690         }
2691
2692         if(self.taunt_soundtime)
2693         if(time > self.taunt_soundtime)
2694         {
2695                 self.taunt_soundtime = 0;
2696                 PlayerSound(playersound_taunt, CHAN_VOICE, VOICETYPE_AUTOTAUNT);
2697         }
2698
2699         target_voicescript_next(self);
2700 }
2701
2702 // on dragger:
2703 .entity dragentity;
2704 .float draggravity;
2705 .float dragspeed; // speed of mouse wheel action
2706 .float dragdistance; // distance of dragentity's draglocalvector from view_ofs
2707 .vector draglocalvector; // local attachment vector of the dragentity
2708 .float draglocalangle;
2709 // on draggee:
2710 .entity draggedby;
2711 .float dragmovetype;
2712 void Drag_Begin(entity dragger, entity draggee, vector touchpoint)
2713 {
2714         float tagscale;
2715
2716         draggee.dragmovetype = draggee.movetype;
2717         draggee.draggravity = draggee.gravity;
2718         draggee.movetype = MOVETYPE_WALK;
2719         draggee.gravity = 0.00001;
2720         draggee.flags &~= FL_ONGROUND;
2721         draggee.draggedby = dragger;
2722
2723         dragger.dragentity = draggee;
2724
2725         dragger.dragdistance = vlen(touchpoint - dragger.origin - dragger.view_ofs);
2726         dragger.draglocalangle = draggee.angles_y - dragger.v_angle_y;
2727         touchpoint = touchpoint - gettaginfo(draggee, 0);
2728         tagscale = pow(vlen(v_forward), -2);
2729         dragger.draglocalvector_x = touchpoint * v_forward * tagscale;
2730         dragger.draglocalvector_y = touchpoint * v_right * tagscale;
2731         dragger.draglocalvector_z = touchpoint * v_up * tagscale;
2732
2733         dragger.dragspeed = 64;
2734 }
2735
2736 void Drag_Finish(entity dragger)
2737 {
2738         entity draggee;
2739         draggee = dragger.dragentity;
2740         if(dragger)
2741                 dragger.dragentity = world;
2742         draggee.draggedby = world;
2743         draggee.movetype = draggee.dragmovetype;
2744         draggee.gravity = draggee.draggravity;
2745
2746         switch(draggee.movetype)
2747         {
2748                 case MOVETYPE_TOSS:
2749                 case MOVETYPE_WALK:
2750                 case MOVETYPE_STEP:
2751                 case MOVETYPE_FLYMISSILE:
2752                 case MOVETYPE_BOUNCE:
2753                 case MOVETYPE_BOUNCEMISSILE:
2754                 case MOVETYPE_PHYSICS:
2755                         break;
2756                 default:
2757                         draggee.velocity = '0 0 0';
2758                         break;
2759         }
2760
2761         if((draggee.flags & FL_ITEM) && (vlen(draggee.velocity) < 32))
2762         {
2763                 draggee.velocity = '0 0 0';
2764                 draggee.flags |= FL_ONGROUND; // floating items are FUN
2765         }
2766 }
2767
2768 float Drag_IsDraggable(entity draggee)
2769 {
2770         // TODO add more checks for bad stuff here
2771         if(draggee.classname == "func_bobbing")
2772                 return FALSE;
2773         if(draggee.classname == "door") // FIXME find out why these must be excluded, or work around the problem (trying to drag these causes like 4 fps)
2774                 return FALSE;
2775         if(draggee.classname == "plat")
2776                 return FALSE;
2777         if(draggee.classname == "func_button")
2778                 return FALSE;
2779         if(draggee.model == "")
2780                 return FALSE;
2781         if(draggee.classname == "spectator")
2782                 return FALSE;
2783         if(draggee.classname == "observer")
2784                 return FALSE;
2785         if(draggee.classname == "exteriorweaponentity")
2786                 return FALSE;
2787
2788         return TRUE;
2789 }
2790
2791 float Drag_MayChangeAngles(entity draggee)
2792 {
2793         // TODO add more checks for bad stuff here
2794         if(substring(draggee.model, 0, 1) == "*")
2795                 return FALSE;
2796         return TRUE;
2797 }
2798
2799 void Drag_MoveForward(entity dragger)
2800 {
2801         dragger.dragdistance += dragger.dragspeed;
2802 }
2803
2804 void Drag_SetSpeed(entity dragger, float s)
2805 {
2806         dragger.dragspeed = pow(2, s);
2807 }
2808
2809 void Drag_MoveBackward(entity dragger)
2810 {
2811         dragger.dragdistance = max(0, dragger.dragdistance - dragger.dragspeed);
2812 }
2813
2814 void Drag_Update(entity dragger)
2815 {
2816         vector curorigin, neworigin, goodvelocity;
2817         float f;
2818         entity draggee;
2819
2820         draggee = dragger.dragentity;
2821         draggee.flags &~= FL_ONGROUND;
2822
2823         curorigin = gettaginfo(draggee, 0);
2824         curorigin = curorigin + v_forward * dragger.draglocalvector_x + v_right * dragger.draglocalvector_y + v_up * dragger.draglocalvector_z;
2825         makevectors(dragger.v_angle);
2826         neworigin = dragger.origin + dragger.view_ofs + v_forward * dragger.dragdistance;
2827         goodvelocity = (neworigin - curorigin) * (1 / frametime);
2828
2829         while(draggee.angles_y - dragger.v_angle_y - dragger.draglocalangle > 180)
2830                 dragger.draglocalangle += 360;
2831         while(draggee.angles_y - dragger.v_angle_y - dragger.draglocalangle <= -180)
2832                 dragger.draglocalangle -= 360;
2833
2834         f = min(frametime * 10, 1);
2835         draggee.velocity = draggee.velocity * (1 - f) + goodvelocity * f;
2836
2837         if(Drag_MayChangeAngles(draggee))
2838                 draggee.angles_y = draggee.angles_y * (1 - f) + (dragger.v_angle_y + dragger.draglocalangle) * f;
2839
2840         draggee.ltime = max(servertime + serverframetime, draggee.ltime); // fixes func_train breakage
2841
2842         te_lightning1(dragger, dragger.origin + dragger.view_ofs, curorigin);
2843 }
2844
2845 float Drag_CanDrag(entity dragger)
2846 {
2847         return (dragger.deadflag == DEAD_NO) || (dragger.classname == "player");
2848 }
2849
2850 float Drag_IsDragging(entity dragger)
2851 {
2852         if(!dragger.dragentity)
2853                 return FALSE;
2854         if(wasfreed(dragger.dragentity) || dragger.dragentity.draggedby != dragger)
2855         {
2856                 dragger.dragentity = world;
2857                 return FALSE;
2858         }
2859         if(!Drag_CanDrag(dragger) || !Drag_IsDraggable(dragger.dragentity))
2860         {
2861                 Drag_Finish(dragger);
2862                 return FALSE;
2863         }
2864         return TRUE;
2865 }
2866
2867 void Drag_MoveDrag(entity from, entity to)
2868 {
2869         if(from.draggedby)
2870         {
2871                 to.draggedby = from.draggedby;
2872                 to.draggedby.dragentity = to;
2873                 from.draggedby = world;
2874         }
2875 }
2876
2877 /*
2878 =============
2879 PlayerPostThink
2880
2881 Called every frame for each client after the physics are run
2882 =============
2883 */
2884 .float idlekick_lasttimeleft;
2885 void PlayerPostThink (void)
2886 {
2887         // Savage: Check for nameless players
2888         if (strlen(self.netname) < 1) {
2889                 self.netname = "Player";
2890                 stuffcmd(self, "seta _cl_name Player\n");
2891         }
2892
2893         // send the clients accuracy stats to the client
2894         if(self.stat_count > 0)
2895         if(frametime)
2896         {
2897                 self.stat_hit = self.stat_count + 64 * floor(self.(stats_hit[self.stat_count - 1]));
2898                 self.stat_fired = self.stat_count + 64 * floor(self.(stats_fired[self.stat_count - 1]));
2899                 self.stat_count -= 1;
2900         }
2901
2902         if(sv_maxidle && frametime)
2903         {
2904                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2905                 float timeleft;
2906                 timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
2907                 if(timeleft <= 0)
2908                 {
2909                         bprint("^3", self.netname, "^3 was kicked for idling.\n");
2910                         announce(self, "announcer/robotic/terminated.wav");
2911                         dropclient(self);
2912                         return;
2913                 }
2914                 else if(timeleft <= 10)
2915                 {
2916                         if(timeleft != self.idlekick_lasttimeleft)
2917                         {
2918                                 centerprint_atprio(self, CENTERPRIO_IDLEKICK, strcat("^3Stop idling!\n^3Disconnecting in ", ftos(timeleft), "..."));
2919                                 announce(self, strcat("announcer/robotic/", ftos(timeleft), ".wav"));
2920                         }
2921                 }
2922                 else
2923                 {
2924                         centerprint_expire(self, CENTERPRIO_IDLEKICK);
2925                 }
2926                 self.idlekick_lasttimeleft = timeleft;
2927         }
2928
2929 #ifdef TETRIS
2930         if(self.impulse == 100)
2931                 ImpulseCommands();
2932         if (TetrisPostFrame())
2933                 return;
2934 #endif
2935
2936         if(sv_cheats || self.maycheat)
2937                 if(Drag_CanDrag(self))
2938                         if(self.BUTTON_DRAG)
2939                                 if(!self.dragentity)
2940                                         if(self.cursor_trace_ent)
2941                                                 if(Drag_IsDraggable(self.cursor_trace_ent))
2942                                                 {
2943                                                         if(self.cursor_trace_ent.draggedby)
2944                                                                 Drag_Finish(self.cursor_trace_ent.draggedby);
2945                                                         if(self.cursor_trace_ent.tag_entity)
2946                                                                 detach_sameorigin(self.cursor_trace_ent);
2947                                                         Drag_Begin(self, self.cursor_trace_ent, self.cursor_trace_endpos);
2948                                                 }
2949
2950         if(Drag_IsDragging(self))
2951         {
2952                 if(self.BUTTON_DRAG)
2953                 {
2954                         if(self.impulse == 10 || self.impulse == 15 || self.impulse == 18)
2955                         {
2956                                 Drag_MoveForward(self);
2957                                 self.impulse = 0;
2958                         }
2959                         else if(self.impulse == 12 || self.impulse == 16 || self.impulse == 19)
2960                         {
2961                                 Drag_MoveBackward(self);
2962                                 self.impulse = 0;
2963                         }
2964                         else if(self.impulse >= 1 && self.impulse <= 9)
2965                         {
2966                                 Drag_SetSpeed(self, self.impulse - 1);
2967                         }
2968                         else if(self.impulse == 14)
2969                         {
2970                                 Drag_SetSpeed(self, 9);
2971                         }
2972
2973                         if(frametime)
2974                                 Drag_Update(self);
2975                 }
2976                 else
2977                 {
2978                         Drag_Finish(self);
2979                 }
2980         }
2981
2982         if(self.classname == "player") {
2983                 CheckRules_Player();
2984                 UpdateChatBubble();
2985                 UpdateTeamBubble();
2986                 if (self.impulse)
2987                         ImpulseCommands();
2988                 if (intermission_running)
2989                         return;         // intermission or finale
2990
2991                 GetPressedKeys();
2992         } else if (self.classname == "observer") {
2993                 //do nothing
2994         } else if (self.classname == "spectator") {
2995                 //do nothing
2996         }
2997
2998         /*
2999         float i;
3000         for(i = 0; i < 1000; ++i)
3001         {
3002                 vector end;
3003                 end = self.origin + '0 0 1024' + 512 * randomvec();
3004                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
3005                 if(trace_fraction < 1)
3006                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
3007                 {
3008                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
3009                         break;
3010                 }
3011         }
3012         */
3013
3014         Arena_Warmup();
3015
3016         //pointparticles(particleeffectnum("machinegun_impact"), self.origin + self.view_ofs + '0 0 7', '0 0 0', 1);
3017
3018         if(self.waypointsprite_attachedforcarrier)
3019                 WaypointSprite_UpdateHealth(self.waypointsprite_attachedforcarrier, '1 0 0' * healtharmor_maxdamage(self.health, self.armorvalue, cvar("g_balance_armor_blockpercent")));
3020         
3021         playerdemo_write();
3022 }