remove unwanted access to "neutral" team cvars
[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         race_PreSpawnObserver();
1336
1337         //if(g_domination)
1338         //      dom_player_join_team(self);
1339
1340         JoinBestTeam(self, FALSE, FALSE); // if the team number is valid, keep it
1341
1342         if((cvar("sv_spectate") == 1 && !g_lms) || cvar("g_campaign")) {
1343                 self.classname = "observer";
1344         } else {
1345                 if(teams_matter)
1346                 {
1347                         if(cvar("g_balance_teams") || cvar("g_balance_teams_force"))
1348                         {
1349                                 self.classname = "player";
1350                                 campaign_bots_may_start = 1;
1351                         }
1352                         else
1353                         {
1354                                 self.classname = "observer"; // do it anyway
1355                         }
1356                 }
1357                 else
1358                 {
1359                         self.classname = "player";
1360                         campaign_bots_may_start = 1;
1361                 }
1362         }
1363
1364         self.playerid = (playerid_last = playerid_last + 1);
1365
1366         if(cvar("sv_eventlog"))
1367                 GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":", ((clienttype(self) == CLIENTTYPE_REAL) ? self.netaddress : "bot"), ":", self.netname));
1368
1369         LogTeamchange(self.playerid, self.team, 1);
1370
1371         self.just_joined = TRUE;  // stop spamming the eventlog with additional lines when the client connects
1372
1373         self.netname_previous = strzone(self.netname);
1374
1375         bprint("^4", self.netname, "^4 connected");
1376
1377         if(g_domination || g_ctf)
1378                 bprint(" and joined the ", ColoredTeamName(self.team));
1379
1380         bprint("\n");
1381
1382         self.welcomemessage_time = 0;
1383
1384         stuffcmd(self, strcat(clientstuff, "\n"));
1385         stuffcmd(self, strcat("exec maps/", mapname, ".cfg\n"));
1386         stuffcmd(self, "cl_particles_reloadeffects\n");
1387
1388         FixClientCvars(self);
1389
1390         // spawnfunc_waypoint sprites
1391         WaypointSprite_InitClient(self);
1392
1393         // Wazat's grappling hook
1394         SetGrappleHookBindings();
1395
1396         // get autoswitch state from player when he toggles it
1397         stuffcmd(self, "alias autoswitch \"set cl_autoswitch $1 ; cmd autoswitch $1\"\n"); // default.cfg-ed in 2.4.1
1398
1399         // get version info from player
1400         stuffcmd(self, "cmd clientversion $gameversion\n");
1401
1402         // get other cvars from player
1403         GetCvars(0);
1404
1405         // set cvar for team scoreboard
1406         stuffcmd(self, strcat("set teamplay ", ftos(teamplay), "\n"));
1407
1408         // notify about available teams
1409         if(teams_matter)
1410         {
1411                 CheckAllowedTeams(self);
1412                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1413                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1414         }
1415         else
1416                 stuffcmd(self, "set _teams_available 0\n");
1417
1418         stuffcmd(self, strcat("set gametype ", ftos(game), "\n"));
1419
1420         if(g_arena || g_ca)
1421         {
1422                 self.classname = "observer";
1423                 if(g_arena)
1424                         Spawnqueue_Insert(self);
1425         }
1426         /*else if(g_ctf)
1427         {
1428                 ctf_clientconnect();
1429         }*/
1430
1431         if(teams_matter || sv_cheats)
1432                 attach_entcs();
1433
1434         bot_relinkplayerlist();
1435
1436         self.spectatortime = time;
1437         if(blockSpectators)
1438         {
1439                 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"));
1440         }
1441
1442         self.jointime = time;
1443         self.allowedTimeouts = cvar("sv_timeout_number");
1444
1445         if(clienttype(self) == CLIENTTYPE_REAL)
1446         {
1447                 if(cvar("g_bugrigs") || g_weaponarena == WEPBIT_TUBA)
1448                         stuffcmd(self, "cl_cmd settemp chase_active 1\n");
1449         }
1450
1451         if(g_lms)
1452         {
1453                 if(PlayerScore_Add(self, SP_LMS_LIVES, LMS_NewPlayerLives()) <= 0)
1454                 {
1455                         PlayerScore_Add(self, SP_LMS_RANK, 666);
1456                         self.frags = FRAGS_SPECTATOR;
1457                 }
1458         }
1459
1460         if(!sv_foginterval && world.fog != "")
1461                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1462
1463         SoundEntity_Attach(self);
1464
1465         if(cvar("g_hitplots") || strstrofs(strcat(" ", cvar_string("g_hitplots_individuals"), " "), strcat(" ", self.netaddress, " "), 0) >= 0)
1466         {
1467                 self.hitplotfh = fopen(strcat("hits-", matchid, "-", self.netaddress, "-", ftos(self.playerid), ".plot"), FILE_WRITE);
1468                 fputs(self.hitplotfh, strcat("#name ", self.netname, "\n"));
1469         }
1470         else
1471                 self.hitplotfh = -1;
1472
1473         if(g_race || g_cts) {
1474                 string rr;
1475                 if(g_cts)
1476                         rr = CTS_RECORD;
1477                 else
1478                         rr = RACE_RECORD;
1479                 t = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "time")));
1480
1481                 race_send_recordtime(t, MSG_ONE);
1482                 race_send_speedaward(MSG_ONE);
1483
1484                 speedaward_alltimebest = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/speed")));
1485                 speedaward_alltimebest_holder = db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/netname"));
1486                 race_send_speedaward_alltimebest(MSG_ONE);
1487         }
1488         else if(cvar("sv_teamnagger") && !g_ca) // teamnagger is currently bad for ca
1489                 send_CSQC_teamnagger();
1490 }
1491
1492 /*
1493 =============
1494 ClientDisconnect
1495
1496 Called when a client disconnects from the server
1497 =============
1498 */
1499 .entity chatbubbleentity;
1500 .entity teambubbleentity;
1501 void ReadyCount();
1502 void ClientDisconnect (void)
1503 {
1504         if not(self.flags & FL_CLIENT)
1505         {
1506                 print("Warning: ClientDisconnect without ClientConnect\n");
1507                 return;
1508         }
1509
1510         if(self.hitplotfh >= 0)
1511         {
1512                 fclose(self.hitplotfh);
1513                 self.hitplotfh = -1;
1514         }
1515
1516         playerdemo_shutdown();
1517
1518         bot_clientdisconnect();
1519
1520         if(self.entcs)
1521                 detach_entcs();
1522
1523         if(cvar("sv_eventlog"))
1524                 GameLogEcho(strcat(":part:", ftos(self.playerid)));
1525         bprint ("^4",self.netname);
1526         bprint ("^4 disconnected\n");
1527
1528         SoundEntity_Detach(self);
1529
1530         DropAllRunes(self);
1531         kh_Key_DropAll(self, TRUE);
1532
1533         Portal_ClearAll(self);
1534
1535         if(self.flagcarried)
1536                 DropFlag(self.flagcarried, world, world);
1537         if(self.ballcarried)
1538                 DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
1539
1540         // Here, everything has been done that requires this player to be a client.
1541
1542         self.flags &~= FL_CLIENT;
1543
1544         if (self.chatbubbleentity)
1545                 remove (self.chatbubbleentity);
1546
1547         if (self.teambubbleentity)
1548                 remove (self.teambubbleentity);
1549
1550         if (self.killindicator)
1551                 remove (self.killindicator);
1552
1553         WaypointSprite_PlayerGone();
1554
1555         bot_relinkplayerlist();
1556
1557         // remove laserdot
1558         if(self.weaponentity)
1559                 if(self.weaponentity.lasertarget)
1560                         remove(self.weaponentity.lasertarget);
1561
1562         if(g_arena)
1563         {
1564                 Spawnqueue_Unmark(self);
1565                 Spawnqueue_Remove(self);
1566         }
1567
1568         ClientData_Detach();
1569         PlayerScore_Detach(self);
1570
1571         if(self.netname_previous)
1572                 strunzone(self.netname_previous);
1573         if(self.clientstatus)
1574                 strunzone(self.clientstatus);
1575
1576         ClearPlayerSounds();
1577
1578         if(self.personal)
1579                 remove(self.personal);
1580
1581         self.playerid = 0;
1582         ReadyCount();
1583
1584         // free cvars
1585         GetCvars(-1);
1586 }
1587
1588 .float BUTTON_CHAT;
1589 void ChatBubbleThink()
1590 {
1591         self.nextthink = time;
1592         if (!self.owner.modelindex || self.owner.chatbubbleentity != self)
1593         {
1594                 if(self.owner) // but why can that ever be world?
1595                         self.owner.chatbubbleentity = world;
1596                 remove(self);
1597                 return;
1598         }
1599         if ((self.owner.BUTTON_CHAT && !self.owner.deadflag)
1600 #ifdef TETRIS
1601                 || self.owner.tetris_on
1602 #endif
1603         )
1604                 self.model = self.mdl;
1605         else
1606                 self.model = "";
1607 };
1608
1609 void UpdateChatBubble()
1610 {
1611         if (!self.modelindex)
1612                 return;
1613         // spawn a chatbubble entity if needed
1614         if (!self.chatbubbleentity)
1615         {
1616                 self.chatbubbleentity = spawn();
1617                 self.chatbubbleentity.owner = self;
1618                 self.chatbubbleentity.exteriormodeltoclient = self;
1619                 self.chatbubbleentity.think = ChatBubbleThink;
1620                 self.chatbubbleentity.nextthink = time;
1621                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1622                 //setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1623                 setorigin(self.chatbubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1624                 setattachment(self.chatbubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1625                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1626                 self.chatbubbleentity.model = "";
1627                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1628         }
1629 }
1630
1631
1632 void TeamBubbleThink()
1633 {
1634         self.nextthink = time;
1635         if (!self.owner.modelindex || self.owner.teambubbleentity != self)
1636         {
1637                 if(self.owner) // but why can that ever be world?
1638                         self.owner.teambubbleentity = world;
1639                 remove(self);
1640                 return;
1641         }
1642 //      setorigin(self, self.owner.origin + '0 0 15' + self.owner.maxs_z * '0 0 1');  // bandwidth hog. setattachment does this now
1643         if (self.owner.BUTTON_CHAT || self.owner.deadflag || self.owner.killindicator)
1644                 self.model = "";
1645         else
1646                 self.model = self.mdl;
1647
1648 };
1649
1650 float TeamBubble_customizeentityforclient()
1651 {
1652         return (self.owner != other && self.owner.team == other.team && other.killcount > -666);
1653 }
1654
1655 void UpdateTeamBubble()
1656 {
1657         if (!self.modelindex || !teams_matter)
1658                 return;
1659         // spawn a teambubble entity if needed
1660         if (!self.teambubbleentity && teams_matter)
1661         {
1662                 self.teambubbleentity = spawn();
1663                 self.teambubbleentity.owner = self;
1664                 self.teambubbleentity.exteriormodeltoclient = self;
1665                 self.teambubbleentity.think = TeamBubbleThink;
1666                 self.teambubbleentity.nextthink = time;
1667                 setmodel(self.teambubbleentity, "models/misc/teambubble.spr"); // precision set below
1668 //              setorigin(self.teambubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1669                 setorigin(self.teambubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1670                 setattachment(self.teambubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1671                 self.teambubbleentity.mdl = self.teambubbleentity.model;
1672                 self.teambubbleentity.model = self.teambubbleentity.mdl;
1673                 self.teambubbleentity.customizeentityforclient = TeamBubble_customizeentityforclient;
1674                 self.teambubbleentity.effects = EF_LOWPRECISION;
1675         }
1676 }
1677
1678 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1679 // added to the model skins
1680 /*void UpdateColorModHack()
1681 {
1682         local float c;
1683         c = self.clientcolors & 15;
1684         // LordHavoc: only bothering to support white, green, red, yellow, blue
1685              if (!teams_matter) self.colormod = '0 0 0';
1686         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1687         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1688         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1689         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1690         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1691         else self.colormod = '1 1 1';
1692 };*/
1693
1694 void respawn(void)
1695 {
1696         CopyBody(1);
1697         self.effects |= EF_NODRAW; // prevent another CopyBody
1698         PutClientInServer();
1699 }
1700
1701 void play_countdown(float finished, string samp)
1702 {
1703         if(clienttype(self) == CLIENTTYPE_REAL)
1704                 if(floor(finished - time - frametime) != floor(finished - time))
1705                         if(finished - time < 6)
1706                                 sound (self, CHAN_AUTO, samp, VOL_BASE, ATTN_NORM);
1707 }
1708
1709 /**
1710  * When sv_timeout is used this function returs strings like
1711  * "Timeout begins in 2 seconds!\n" or "Timeout ends in 23 seconds!\n".
1712  * Called by centerprint functions
1713  * @param addOneSecond boolean, set to 1 if the welcome-message centerprint asks for the text
1714  */
1715 string getTimeoutText(float addOneSecond) {
1716         if (!cvar("sv_timeout") || !timeoutStatus)
1717                 return "";
1718
1719         local string retStr;
1720         if (timeoutStatus == 1) {
1721                 if (addOneSecond == 1) {
1722                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime + 1), " seconds!\n");
1723                 }
1724                 else {
1725                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime), " seconds!\n");
1726                 }
1727                 return retStr;
1728         }
1729         else if (timeoutStatus == 2) {
1730                 if (addOneSecond) {
1731                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime + 1), " seconds!\n");
1732                         //don't show messages like "Timeout ends in 0 seconds"...
1733                         if ((remainingTimeoutTime + 1) > 0)
1734                                 return retStr;
1735                         else
1736                                 return "";
1737                 }
1738                 else {
1739                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime), " seconds!\n");
1740                         //don't show messages like "Timeout ends in 0 seconds"...
1741                         if (remainingTimeoutTime > 0)
1742                                 return retStr;
1743                         else
1744                                 return "";
1745                 }
1746         }
1747         else return "";
1748 }
1749
1750 void player_powerups (void)
1751 {
1752         if((self.items & IT_USING_JETPACK) && !self.deadflag)
1753         {
1754                 SoundEntity_StartSound(self, CHAN_PLAYER, "misc/jetpack_fly.wav", VOL_BASE, cvar("g_jetpack_attenuation"));
1755                 self.modelflags |= MF_ROCKET;
1756         }
1757         else
1758         {
1759                 SoundEntity_StopSound(self, CHAN_PLAYER);
1760                 self.modelflags &~= MF_ROCKET;
1761         }
1762
1763         self.effects &~= (EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT | EF_FLAME | EF_NODEPTHTEST);
1764
1765         if(!self.modelindex || self.deadflag) // don't apply the flags if the player is gibbed
1766                 return;
1767         
1768         Fire_ApplyDamage(self);
1769         Fire_ApplyEffect(self);
1770
1771         if (g_minstagib)
1772         {
1773                 self.effects |= EF_FULLBRIGHT;
1774
1775                 if (self.items & IT_STRENGTH)
1776                 {
1777                         play_countdown(self.strength_finished, "misc/poweroff.wav");
1778                         if (time > self.strength_finished)
1779                         {
1780                                 self.alpha = default_player_alpha;
1781                                 self.exteriorweaponentity.alpha = default_weapon_alpha;
1782                                 self.items &~= IT_STRENGTH;
1783                                 sprint(self, "^3Invisibility has worn off\n");
1784                         }
1785                 }
1786                 else
1787                 {
1788                         if (time < self.strength_finished)
1789                         {
1790                                 self.alpha = g_minstagib_invis_alpha;
1791                                 self.exteriorweaponentity.alpha = g_minstagib_invis_alpha;
1792                                 self.items |= IT_STRENGTH;
1793                                 sprint(self, "^3You are invisible\n");
1794                         }
1795                 }
1796
1797                 if (self.items & IT_INVINCIBLE)
1798                 {
1799                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
1800                         if (time > self.invincible_finished && cvar("g_balance_powerup_timer"))
1801                         {
1802                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1803                                 sprint(self, "^3Speed has worn off\n");
1804                         }
1805                 }
1806                 else
1807                 {
1808                         if (time < self.invincible_finished)
1809                         {
1810                                 self.items = self.items | IT_INVINCIBLE;
1811                                 sprint(self, "^3You are on speed\n");
1812                         }
1813                 }
1814                 return;
1815         }
1816
1817         if (self.items & IT_STRENGTH)
1818         {
1819                 play_countdown(self.strength_finished, "misc/poweroff.wav");
1820                 self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1821                 if (time > self.strength_finished && cvar("g_balance_powerup_timer"))
1822                 {
1823                         self.items = self.items - (self.items & IT_STRENGTH);
1824                         sprint(self, "^3Strength has worn off\n");
1825                 }
1826         }
1827         else
1828         {
1829                 if (time < self.strength_finished)
1830                 {
1831                         self.items = self.items | IT_STRENGTH;
1832                         sprint(self, "^3Strength infuses your weapons with devastating power\n");
1833                 }
1834         }
1835         if (self.items & IT_INVINCIBLE)
1836         {
1837                 play_countdown(self.invincible_finished, "misc/poweroff.wav");
1838                 self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1839                 if (time > self.invincible_finished && cvar("g_balance_powerup_timer"))
1840                 {
1841                         self.items = self.items - (self.items & IT_INVINCIBLE);
1842                         sprint(self, "^3Shield has worn off\n");
1843                 }
1844         }
1845         else
1846         {
1847                 if (time < self.invincible_finished)
1848                 {
1849                         self.items = self.items | IT_INVINCIBLE;
1850                         sprint(self, "^3Shield surrounds you\n");
1851                 }
1852         }
1853
1854         if(cvar("g_nodepthtestplayers"))
1855                 self.effects = self.effects | EF_NODEPTHTEST;
1856
1857         if(cvar("g_fullbrightplayers"))
1858                 self.effects = self.effects | EF_FULLBRIGHT;
1859
1860         // midair gamemode: damage only while in the air
1861         // if in midair mode, being on ground grants temporary invulnerability
1862         // (this is so that multishot weapon don't clear the ground flag on the
1863         // first damage in the frame, leaving the player vulnerable to the
1864         // remaining hits in the same frame)
1865         if (self.flags & FL_ONGROUND)
1866         if (g_midair)
1867                 self.spawnshieldtime = max(self.spawnshieldtime, time + cvar("g_midair_shieldtime"));
1868
1869         if (time >= game_starttime)
1870         if (time < self.spawnshieldtime)
1871                 self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1872 }
1873
1874 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1875 {
1876         if(current > stable)
1877                 return current;
1878         else if(current > stable - 0.25) // when close enough, "snap"
1879                 return stable;
1880         else
1881                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1882 }
1883
1884 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1885 {
1886         if(current < stable)
1887                 return current;
1888         else if(current < stable + 0.25) // when close enough, "snap"
1889                 return stable;
1890         else
1891                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1892 }
1893
1894 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit)
1895 {
1896         if(current > rotstable)
1897         {
1898                 if(rotframetime > 0)
1899                 {
1900                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1901                         current = max(rotstable, current - rotlinear * rotframetime);
1902                 }
1903         }
1904         else if(current < regenstable)
1905         {
1906                 if(regenframetime > 0)
1907                 {
1908                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1909                         current = min(regenstable, current + regenlinear * regenframetime);
1910                 }
1911         }
1912
1913         if(current > limit)
1914                 current = limit;
1915
1916         return current;
1917 }
1918
1919 void player_regen (void)
1920 {
1921         float minh, mina, minf, maxh, maxa, maxf, limith, limita, limitf, max_mod, regen_mod, rot_mod, limit_mod;
1922         maxh = cvar("g_balance_health_rotstable");
1923         maxa = cvar("g_balance_armor_rotstable");
1924         maxf = cvar("g_balance_fuel_rotstable");
1925         minh = cvar("g_balance_health_regenstable");
1926         mina = cvar("g_balance_armor_regenstable");
1927         minf = cvar("g_balance_fuel_regenstable");
1928         limith = cvar("g_balance_health_limit");
1929         limita = cvar("g_balance_armor_limit");
1930         limitf = cvar("g_balance_fuel_limit");
1931
1932         max_mod = regen_mod = rot_mod = limit_mod = 1;
1933
1934         if (self.runes & RUNE_REGEN)
1935         {
1936                 if (self.runes & CURSE_VENOM) // do we have both rune/curse?
1937                 {
1938                         regen_mod = cvar("g_balance_rune_regen_combo_regenrate");
1939                         max_mod = cvar("g_balance_rune_regen_combo_hpmod");
1940                         limit_mod = cvar("g_balance_rune_regen_combo_limitmod");
1941                 }
1942                 else
1943                 {
1944                         regen_mod = cvar("g_balance_rune_regen_regenrate");
1945                         max_mod = cvar("g_balance_rune_regen_hpmod");
1946                         limit_mod = cvar("g_balance_rune_regen_limitmod");
1947                 }
1948         }
1949         else if (self.runes & CURSE_VENOM)
1950         {
1951                 max_mod = cvar("g_balance_curse_venom_hpmod");
1952                 if (self.runes & RUNE_REGEN) // do we have both rune/curse?
1953                         rot_mod = cvar("g_balance_rune_regen_combo_rotrate");
1954                 else
1955                         rot_mod = cvar("g_balance_curse_venom_rotrate");
1956                 limit_mod = cvar("g_balance_curse_venom_limitmod");
1957                 //if (!self.runes & RUNE_REGEN)
1958                 //      rot_mod = cvar("g_balance_curse_venom_rotrate");
1959         }
1960         maxh = maxh * max_mod;
1961         //maxa = maxa * max_mod;
1962         //maxf = maxf * max_mod;
1963         minh = minh * max_mod;
1964         //mina = mina * max_mod;
1965         //minf = minf * max_mod;
1966         limith = limith * limit_mod;
1967         limita = limita * limit_mod;
1968         //limitf = limitf * limit_mod;
1969
1970         if(g_lms && g_ca)
1971                 rot_mod = 0;
1972
1973         if (!g_minstagib && !g_ca && (!g_lms || cvar("g_lms_regenerate")))
1974         {
1975                 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);
1976                 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);
1977
1978                 // if player rotted to death...  die!
1979                 if(self.health < 1)
1980                         self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
1981         }
1982
1983         if not(self.items & IT_UNLIMITED_WEAPON_AMMO)
1984                 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);
1985 }
1986
1987 float zoomstate_set;
1988 void SetZoomState(float z)
1989 {
1990         if(z != self.zoomstate)
1991         {
1992                 self.zoomstate = z;
1993                 ClientData_Touch(self);
1994         }
1995         zoomstate_set = 1;
1996 }
1997
1998 void GetPressedKeys(void) {
1999         if (self.movement_x > 0) // get if movement keys are pressed
2000         {       // forward key pressed
2001                 self.pressedkeys |= KEY_FORWARD;
2002                 self.pressedkeys &~= KEY_BACKWARD;
2003         }
2004         else if (self.movement_x < 0)
2005         {       // backward key pressed
2006                 self.pressedkeys |= KEY_BACKWARD;
2007                 self.pressedkeys &~= KEY_FORWARD;
2008         }
2009         else
2010         {       // no x input
2011                 self.pressedkeys &~= KEY_FORWARD;
2012                 self.pressedkeys &~= KEY_BACKWARD;
2013         }
2014
2015         if (self.movement_y > 0)
2016         {       // right key pressed
2017                 self.pressedkeys |= KEY_RIGHT;
2018                 self.pressedkeys &~= KEY_LEFT;
2019         }
2020         else if (self.movement_y < 0)
2021         {       // left key pressed
2022                 self.pressedkeys |= KEY_LEFT;
2023                 self.pressedkeys &~= KEY_RIGHT;
2024         }
2025         else
2026         {       // no y input
2027                 self.pressedkeys &~= KEY_RIGHT;
2028                 self.pressedkeys &~= KEY_LEFT;
2029         }
2030
2031         if (self.BUTTON_JUMP) // get if jump and crouch keys are pressed
2032                 self.pressedkeys |= KEY_JUMP;
2033         else
2034                 self.pressedkeys &~= KEY_JUMP;
2035         if (self.BUTTON_CROUCH)
2036                 self.pressedkeys |= KEY_CROUCH;
2037         else
2038                 self.pressedkeys &~= KEY_CROUCH;
2039 }
2040
2041 void update_stats (float number, float hit, float fired) {
2042 // self.stat_hit   = number + ((number==0) ? 1 : 64) * hit   * sv_accuracy_data_share;
2043 // self.stat_fired = number + ((number==0) ? 1 : 64) * fired * sv_accuracy_data_share;
2044
2045         if(number) {
2046                 self.stat_hit = number + 64 * hit * sv_accuracy_data_share;
2047                 self.stat_fired = number + 64 * fired * sv_accuracy_data_share;
2048         } else {
2049                 self.stat_hit = hit * sv_accuracy_data_share;
2050                 self.stat_fired = fired * sv_accuracy_data_share;
2051         }
2052 }
2053
2054 /*
2055 ======================
2056 spectate mode routines
2057 ======================
2058 */
2059
2060 .float weapon_count;
2061 void SpectateCopy(entity spectatee) {
2062         if(spectatee.weapon_count < WEP_LAST) {
2063                 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]));
2064                 spectatee.weapon_count ++;
2065         } else
2066                 update_stats (0, spectatee.cvar_cl_accuracy_data_share * spectatee.stat_hit, spectatee.cvar_cl_accuracy_data_share * spectatee.stat_fired);
2067
2068         self.kh_state = spectatee.kh_state;
2069         self.armortype = spectatee.armortype;
2070         self.armorvalue = spectatee.armorvalue;
2071         self.ammo_cells = spectatee.ammo_cells;
2072         self.ammo_shells = spectatee.ammo_shells;
2073         self.ammo_nails = spectatee.ammo_nails;
2074         self.ammo_rockets = spectatee.ammo_rockets;
2075         self.ammo_fuel = spectatee.ammo_fuel;
2076         self.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
2077         self.health = spectatee.health;
2078         self.impulse = 0;
2079         self.items = spectatee.items;
2080         self.metertime = spectatee.metertime;
2081         self.strength_finished = spectatee.strength_finished;
2082         self.invincible_finished = spectatee.invincible_finished;
2083         self.pressedkeys = spectatee.pressedkeys;
2084         self.weapons = spectatee.weapons;
2085         self.switchweapon = spectatee.switchweapon;
2086         self.weapon = spectatee.weapon;
2087         self.punchangle = spectatee.punchangle;
2088         self.view_ofs = spectatee.view_ofs;
2089         self.v_angle = spectatee.v_angle;
2090         self.velocity = spectatee.velocity;
2091         self.dmg_take = spectatee.dmg_take;
2092         self.dmg_save = spectatee.dmg_save;
2093         self.dmg_inflictor = spectatee.dmg_inflictor;
2094         self.angles = spectatee.v_angle;
2095         self.fixangle = TRUE;
2096         setorigin(self, spectatee.origin);
2097         setsize(self, spectatee.mins, spectatee.maxs);
2098         SetZoomState(spectatee.zoomstate);
2099 }
2100
2101 float SpectateUpdate() {
2102         if(!self.enemy)
2103                 return 0;
2104
2105         if (self == self.enemy)
2106                 return 0;
2107
2108         if(self.enemy.classname != "player")
2109                 return 0;
2110
2111         SpectateCopy(self.enemy);
2112
2113         return 1;
2114 }
2115
2116 float SpectateNext() {
2117         other = find(self.enemy, classname, "player");
2118
2119         if (!other)
2120                 other = find(other, classname, "player");
2121
2122         if (other)
2123                 self.enemy = other;
2124
2125         if(self.enemy.classname == "player") {
2126                 msg_entity = self;
2127                 WriteByte(MSG_ONE, SVC_SETVIEW);
2128                 WriteEntity(MSG_ONE, self.enemy);
2129                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
2130                 self.movetype = MOVETYPE_NONE;
2131
2132                 self.enemy.weapon_count = 0;
2133
2134                 if(!SpectateUpdate())
2135                         PutObserverInServer();
2136
2137                 return 1;
2138         } else {
2139                 return 0;
2140         }
2141 }
2142
2143 /*
2144 =============
2145 ShowRespawnCountdown()
2146
2147 Update a respawn countdown display.
2148 =============
2149 */
2150 void ShowRespawnCountdown()
2151 {
2152         float number;
2153         if(self.deadflag == DEAD_NO) // just respawned?
2154                 return;
2155         else
2156         {
2157                 number = ceil(self.death_time - time);
2158                 if(number <= 0)
2159                         return;
2160                 if(number <= self.respawn_countdown)
2161                 {
2162                         self.respawn_countdown = number - 1;
2163                         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
2164                                 announce(self, strcat("announcer/robotic/", ftos(number), ".wav"));
2165                 }
2166         }
2167 }
2168
2169 void LeaveSpectatorMode()
2170 {
2171         if(isJoinAllowed()) {
2172                 if(!teams_matter || cvar("g_campaign") || cvar("g_balance_teams") || (self.wasplayer && cvar("g_changeteam_banned"))) {
2173                         self.classname = "player";
2174
2175                         if(cvar("g_campaign") || cvar("g_balance_teams") || cvar("g_balance_teams_force"))
2176                                 JoinBestTeam(self, FALSE, TRUE);
2177
2178                         if(cvar("g_campaign"))
2179                                 campaign_bots_may_start = 1;
2180
2181                         self.stat_count = WEP_LAST;
2182
2183                         PutClientInServer();
2184
2185                         if(self.classname == "player")
2186                                 bprint ("^4", self.netname, "^4 is playing now\n");
2187
2188                         if(!cvar("g_campaign"))
2189                                 centerprint(self,""); // clear MOTD
2190
2191                         return;
2192                 } else {
2193                         if (g_ca && self.caplayer) {
2194                         }       // do nothing
2195                         else
2196                                 stuffcmd(self,"menu_showteamselect\n");
2197                         return;
2198                 }
2199         }
2200         else {
2201                 //player may not join because of g_maxplayers is set
2202                 centerprint_atprio(self, CENTERPRIO_MAPVOTE, PREVENT_JOIN_TEXT);
2203         }
2204 }
2205
2206 /**
2207  * Determines whether the player is allowed to join. This depends on cvar
2208  * g_maxplayers, if it isn't used this function always return TRUE, otherwise
2209  * it checks whether the number of currently playing players exceeds g_maxplayers.
2210  * @return bool TRUE if the player is allowed to join, false otherwise
2211  */
2212 float isJoinAllowed() {
2213         if (!cvar("g_maxplayers"))
2214                 return TRUE;
2215
2216         local entity e;
2217         local float currentlyPlaying;
2218         FOR_EACH_REALPLAYER(e) {
2219                 if(e.classname == "player")
2220                         currentlyPlaying += 1;
2221         }
2222         if(currentlyPlaying < cvar("g_maxplayers"))
2223                 return TRUE;
2224
2225         return FALSE;
2226 }
2227
2228 /**
2229  * Checks whether the client is an observer or spectator, if so, he will get kicked after
2230  * g_maxplayers_spectator_blocktime seconds
2231  */
2232 void checkSpectatorBlock() {
2233         if(self.classname == "spectator" || self.classname == "observer") {
2234                 if( time > (self.spectatortime + cvar("g_maxplayers_spectator_blocktime")) ) {
2235                         sprint(self, "^7You were kicked from the server because you are spectator and spectators aren't allowed at the moment.\n");
2236                         dropclient(self);
2237                 }
2238         }
2239 }
2240
2241 float vercmp_recursive(string v1, string v2)
2242 {
2243         float dot1, dot2;
2244         string s1, s2;
2245         float r;
2246
2247         dot1 = strstrofs(v1, ".", 0);
2248         dot2 = strstrofs(v2, ".", 0);
2249         if(dot1 == -1)
2250                 s1 = v1;
2251         else
2252                 s1 = substring(v1, 0, dot1);
2253         if(dot2 == -1)
2254                 s2 = v2;
2255         else
2256                 s2 = substring(v2, 0, dot2);
2257
2258         r = stof(s1) - stof(s2);
2259         if(r != 0)
2260                 return r;
2261
2262         r = strcasecmp(s1, s2);
2263         if(r != 0)
2264                 return r;
2265
2266         if(dot1 == -1)
2267                 if(dot2 == -1)
2268                         return 0;
2269                 else
2270                         return -1;
2271         else
2272                 if(dot2 == -1)
2273                         return 1;
2274                 else
2275                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
2276 }
2277
2278 float vercmp(string v1, string v2)
2279 {
2280         if(strcasecmp(v1, v2) == 0) // early out check
2281                 return 0;
2282         return vercmp_recursive(v1, v2);
2283 }
2284
2285 void ObserverThink()
2286 {
2287         if (self.flags & FL_JUMPRELEASED) {
2288                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2289                         self.welcomemessage_time = 0;
2290                         self.flags &~= FL_JUMPRELEASED;
2291                         self.flags |= FL_SPAWNING;
2292                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
2293                         self.welcomemessage_time = 0;
2294                         self.flags &~= FL_JUMPRELEASED;
2295                         if(SpectateNext() == 1) {
2296                                 self.classname = "spectator";
2297                         }
2298                 }
2299         } else {
2300                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
2301                         self.flags |= FL_JUMPRELEASED;
2302                         if(self.flags & FL_SPAWNING)
2303                         {
2304                                 self.flags &~= FL_SPAWNING;
2305                                 LeaveSpectatorMode();
2306                                 return;
2307                         }
2308                 }
2309         }
2310         PrintWelcomeMessage(self);
2311 }
2312
2313 void SpectatorThink()
2314 {
2315         if (self.flags & FL_JUMPRELEASED) {
2316                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2317                         self.welcomemessage_time = 0;
2318                         self.flags &~= FL_JUMPRELEASED;
2319                         self.flags |= FL_SPAWNING;
2320                 } else if(self.BUTTON_ATCK) {
2321                         self.welcomemessage_time = 0;
2322                         self.flags &~= FL_JUMPRELEASED;
2323                         if(SpectateNext() == 1) {
2324                                 self.classname = "spectator";
2325                         } else {
2326                                 self.classname = "observer";
2327                                 self.stat_count = WEP_LAST;
2328                                 PutClientInServer();
2329                         }
2330                 } else if (self.BUTTON_ATCK2) {
2331                         self.welcomemessage_time = 0;
2332                         self.flags &~= FL_JUMPRELEASED;
2333                         self.classname = "observer";
2334                         self.stat_count = WEP_LAST;
2335                         PutClientInServer();
2336                 } else {
2337                         if(!SpectateUpdate())
2338                                 PutObserverInServer();
2339                 }
2340         } else {
2341                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
2342                         self.flags |= FL_JUMPRELEASED;
2343                         if(self.flags & FL_SPAWNING)
2344                         {
2345                                 self.flags &~= FL_SPAWNING;
2346                                 LeaveSpectatorMode();
2347                                 return;
2348                         }
2349                 }
2350         }
2351
2352         PrintWelcomeMessage(self);
2353         self.flags |= FL_CLIENT | FL_NOTARGET;
2354 }
2355
2356 .float touchexplode_time;
2357
2358 /*
2359 =============
2360 PlayerPreThink
2361
2362 Called every frame for each client before the physics are run
2363 =============
2364 */
2365 void() ctf_setstatus;
2366 void() nexball_setstatus;
2367 .float items_added;
2368 void PlayerPreThink (void)
2369 {
2370         self.stat_game_starttime = game_starttime;
2371         self.stat_allow_oldnexbeam = cvar("g_allow_oldnexbeam");
2372         self.stat_leadlimit = cvar("leadlimit");
2373
2374         if(blockSpectators && frametime)
2375                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2376                 checkSpectatorBlock();
2377
2378         zoomstate_set = 0;
2379
2380         if(self.netname_previous != self.netname)
2381         {
2382                 if(cvar("sv_eventlog"))
2383                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname));
2384                 if(self.netname_previous)
2385                         strunzone(self.netname_previous);
2386                 self.netname_previous = strzone(self.netname);
2387         }
2388
2389         // version nagging
2390         if(self.version_nagtime)
2391                 if(self.cvar_g_nexuizversion)
2392                         if(time > self.version_nagtime)
2393                         {
2394                                 if(strstr(self.cvar_g_nexuizversion, "svn", 0) < 0)
2395                                 {
2396                                         if(strstr(cvar_string("g_nexuizversion"), "svn", 0) >= 0)
2397                                         {
2398                                                 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");
2399                                                 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"));
2400                                         }
2401                                         else
2402                                         {
2403                                                 float r;
2404                                                 r = vercmp(self.cvar_g_nexuizversion, cvar_string("g_nexuizversion"));
2405                                                 if(r < 0)
2406                                                 {
2407                                                         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");
2408                                                         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"));
2409                                                 }
2410                                                 else if(r > 0)
2411                                                 {
2412                                                         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");
2413                                                         sprint(self, strcat("\{1}^1NOTE: ^7the server is running ^3Nexuiz ", cvar_string("g_nexuizversion"), "^7, you have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1\n"));
2414                                                 }
2415                                         }
2416                                 }
2417                                 self.version_nagtime = 0;
2418                         }
2419
2420         // GOD MODE info
2421         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
2422         {
2423                 sprint(self, strcat("godmode saved you ", ftos(self.max_armorvalue), " units of damage, cheater!\n"));
2424                 self.max_armorvalue = 0;
2425         }
2426
2427 #ifdef TETRIS
2428         if (TetrisPreFrame())
2429                 return;
2430 #endif
2431
2432         if(self.classname == "player") {
2433 //              if(self.netname == "Wazat")
2434 //                      bprint(self.classname, "\n");
2435
2436                 CheckRules_Player();
2437
2438                 PrintWelcomeMessage(self);
2439
2440                 if (intermission_running)
2441                 {
2442                         IntermissionThink ();   // otherwise a button could be missed between
2443                         return;                                 // the think tics
2444                 }
2445
2446                 if(self.teleport_time)
2447                 if(time > self.teleport_time)
2448                 {
2449                         self.teleport_time = 0;
2450                         self.effects = self.effects - (self.effects & EF_NODRAW);
2451                 }
2452
2453                 Nixnex_GiveCurrentWeapon();
2454
2455                 if(frametime > 0) // don't do this in cl_movement frames, just in server ticks
2456                         UpdateSelectedPlayer();
2457
2458                 //don't allow the player to turn around while game is paused!
2459                 if(timeoutStatus == 2) {
2460                         self.v_angle = self.lastV_angle;
2461                         self.angles = self.lastV_angle;
2462                         self.fixangle = TRUE;
2463                 }
2464
2465                 if(frametime)
2466                 {
2467                         if(cvar("gameversion") >= 20600) // only do this for 2.6 and above FIXME remove this check when making 2.6
2468                                 self.glowmod = colormapPaletteColor(self.clientcolors & 0x0F, TRUE) * 2;
2469                         player_powerups();
2470                 }
2471
2472                 if (self.deadflag != DEAD_NO)
2473                 {
2474                         float button_pressed, force_respawn;
2475                         if(self.personal && g_race_qualifying)
2476                         {
2477                                 if(time > self.death_time)
2478                                 {
2479                                         self.death_time = time + 1; // only retry once a second
2480                                         respawn();
2481                                         self.impulse = 141;
2482                                 }
2483                         }
2484                         else
2485                         {
2486                                 if(frametime)
2487                                         player_anim();
2488                                 button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2489                                 force_respawn = (g_lms || (g_ca) || cvar("g_forced_respawn"));
2490                                 if (self.deadflag == DEAD_DYING)
2491                                 {
2492                                         if(force_respawn)
2493                                                 self.deadflag = DEAD_RESPAWNING;
2494                                         else if(!button_pressed)
2495                                                 self.deadflag = DEAD_DEAD;
2496                                 }
2497                                 else if (self.deadflag == DEAD_DEAD)
2498                                 {
2499                                         if(button_pressed)
2500                                                 self.deadflag = DEAD_RESPAWNABLE;
2501                                 }
2502                                 else if (self.deadflag == DEAD_RESPAWNABLE)
2503                                 {
2504                                         if(!button_pressed)
2505                                                 self.deadflag = DEAD_RESPAWNING;
2506                                 }
2507                                 else if (self.deadflag == DEAD_RESPAWNING)
2508                                 {
2509                                         if(time > self.death_time)
2510                                         {
2511                                                 self.death_time = time + 1; // only retry once a second
2512                                                 respawn();
2513                                         }
2514                                 }
2515                                 ShowRespawnCountdown();
2516                         }
2517                         return;
2518                 }
2519
2520                 if(g_touchexplode)
2521                 if(time > self.touchexplode_time)
2522                 if(self.classname == "player")
2523                 if(self.deadflag == DEAD_NO)
2524                 if not(IS_INDEPENDENT_PLAYER(self))
2525                 FOR_EACH_PLAYER(other) if(self != other)
2526                 {
2527                         if(time > other.touchexplode_time)
2528                         if(other.classname == "player")
2529                         if(other.deadflag == DEAD_NO)
2530                         if not(IS_INDEPENDENT_PLAYER(other))
2531                         if(boxesoverlap(self.absmin, self.absmax, other.absmin, other.absmax))
2532                         {
2533                                 PlayerTouchExplode(self, other);
2534                                 self.touchexplode_time = other.touchexplode_time = time + 0.2;
2535                         }
2536                 }
2537
2538                 if(g_lms && !self.deadflag && cvar("g_lms_campcheck_interval"))
2539                 {
2540                         vector dist;
2541
2542                         // calculate player movement (in 2 dimensions only, so jumping on one spot doesn't count as movement)
2543                         dist = self.prevorigin - self.origin;
2544                         dist_z = 0;
2545                         self.lms_traveled_distance += fabs(vlen(dist));
2546
2547                         if((cvar("g_campaign") && !campaign_bots_may_start) || (time < game_starttime))
2548                         {
2549                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
2550                                 self.lms_traveled_distance = 0;
2551                         }
2552
2553                         if(time > self.lms_nextcheck)
2554                         {
2555                                 //sprint(self, "distance: ", ftos(self.lms_traveled_distance), "\n");
2556                                 if(self.lms_traveled_distance < cvar("g_lms_campcheck_distance"))
2557                                 {
2558                                         centerprint(self, cvar_string("g_lms_campcheck_message"));
2559                                         // FIXME KadaverJack: gibbing player here causes playermodel to bounce around, instead of eye.md3
2560                                         // I wasn't able to find out WHY that happens, so I put a workaround in place that shall prevent players from being gibbed :(
2561                                         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');
2562                                 }
2563                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval");
2564                                 self.lms_traveled_distance = 0;
2565                         }
2566                 }
2567
2568                 self.prevorigin = self.origin;
2569
2570                 if ((self.BUTTON_CROUCH && !self.hook.state) || self.health <= g_bloodloss)
2571                 {
2572                         if (!self.crouch)
2573                         {
2574                                 self.crouch = TRUE;
2575                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2576                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2577                                 setanim(self, self.anim_duck, FALSE, TRUE, TRUE);
2578                         }
2579                 }
2580                 else
2581                 {
2582                         if (self.crouch)
2583                         {
2584                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, FALSE, self);
2585                                 if (!trace_startsolid)
2586                                 {
2587                                         self.crouch = FALSE;
2588                                         self.view_ofs = PL_VIEW_OFS;
2589                                         setsize (self, PL_MIN, PL_MAX);
2590                                 }
2591                         }
2592                 }
2593
2594                 if(self.health <= g_bloodloss && self.deadflag == DEAD_NO)
2595                 {
2596                         if(self.bloodloss_timer < time)
2597                         {
2598                                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
2599                                 self.bloodloss_timer = time + 0.5 + random() * 0.5;
2600                         }
2601                 }
2602
2603                 FixPlayermodel();
2604
2605                 GrapplingHookFrame();
2606
2607                 // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
2608                 //if(frametime)
2609                 {
2610                         self.items &~= self.items_added;
2611
2612                         W_WeaponFrame();
2613
2614                         self.items_added = 0;
2615                         if(self.items & IT_JETPACK)
2616                                 if(self.items & IT_FUEL_REGEN || self.ammo_fuel >= 0.01)
2617                                         self.items_added |= IT_FUEL;
2618
2619                         self.items |= self.items_added;
2620                 }
2621
2622                 player_regen();
2623                 if(frametime)
2624                         player_anim();
2625
2626                 if (g_minstagib)
2627                         minstagib_ammocheck();
2628
2629                 ctf_setstatus();
2630                 nexball_setstatus();
2631
2632                 self.dmg_team = max(0, self.dmg_team - cvar("g_teamdamage_resetspeed") * frametime);
2633
2634                 //self.angles_y=self.v_angle_y + 90;   // temp
2635         } else if(gameover) {
2636                 if (intermission_running)
2637                         IntermissionThink ();   // otherwise a button could be missed between
2638                 return;
2639         } else if(self.classname == "observer") {
2640                 ObserverThink();
2641         } else if(self.classname == "spectator") {
2642                 SpectatorThink();
2643         }
2644
2645         if(!zoomstate_set)
2646                 SetZoomState(self.BUTTON_ZOOM || (self.BUTTON_ATCK2 && self.weapon == WEP_NEX));
2647
2648         float oldspectatee_status;
2649         oldspectatee_status = self.spectatee_status;
2650         if(self.classname == "spectator")
2651                 self.spectatee_status = num_for_edict(self.enemy);
2652         else if(self.classname == "observer")
2653                 self.spectatee_status = num_for_edict(self);
2654         else
2655                 self.spectatee_status = 0;
2656         if(self.spectatee_status != oldspectatee_status)
2657         {
2658                 ClientData_Touch(self);
2659                 if(g_race || g_cts)
2660                         race_InitSpectator();
2661         }
2662
2663         if(self.teamkill_soundtime)
2664         if(time > self.teamkill_soundtime)
2665         {
2666                 self.teamkill_soundtime = 0;
2667
2668                 entity oldpusher, oldself;
2669
2670                 oldself = self; self = self.teamkill_soundsource;
2671                 oldpusher = self.pusher; self.pusher = oldself;
2672
2673                 PlayerSound(playersound_teamshoot, CHAN_VOICE, VOICETYPE_LASTATTACKER_ONLY);
2674
2675                 self.pusher = oldpusher;
2676                 self = oldself;
2677         }
2678
2679         if(self.taunt_soundtime)
2680         if(time > self.taunt_soundtime)
2681         {
2682                 self.taunt_soundtime = 0;
2683                 PlayerSound(playersound_taunt, CHAN_VOICE, VOICETYPE_AUTOTAUNT);
2684         }
2685
2686         target_voicescript_next(self);
2687 }
2688
2689 // on dragger:
2690 .entity dragentity;
2691 .float draggravity;
2692 .float dragspeed; // speed of mouse wheel action
2693 .float dragdistance; // distance of dragentity's draglocalvector from view_ofs
2694 .vector draglocalvector; // local attachment vector of the dragentity
2695 .float draglocalangle;
2696 // on draggee:
2697 .entity draggedby;
2698 .float dragmovetype;
2699 void Drag_Begin(entity dragger, entity draggee, vector touchpoint)
2700 {
2701         float tagscale;
2702
2703         draggee.dragmovetype = draggee.movetype;
2704         draggee.draggravity = draggee.gravity;
2705         draggee.movetype = MOVETYPE_WALK;
2706         draggee.gravity = 0.00001;
2707         draggee.flags &~= FL_ONGROUND;
2708         draggee.draggedby = dragger;
2709
2710         dragger.dragentity = draggee;
2711
2712         dragger.dragdistance = vlen(touchpoint - dragger.origin - dragger.view_ofs);
2713         dragger.draglocalangle = draggee.angles_y - dragger.v_angle_y;
2714         touchpoint = touchpoint - gettaginfo(draggee, 0);
2715         tagscale = pow(vlen(v_forward), -2);
2716         dragger.draglocalvector_x = touchpoint * v_forward * tagscale;
2717         dragger.draglocalvector_y = touchpoint * v_right * tagscale;
2718         dragger.draglocalvector_z = touchpoint * v_up * tagscale;
2719
2720         dragger.dragspeed = 64;
2721 }
2722
2723 void Drag_Finish(entity dragger)
2724 {
2725         entity draggee;
2726         draggee = dragger.dragentity;
2727         if(dragger)
2728                 dragger.dragentity = world;
2729         draggee.draggedby = world;
2730         draggee.movetype = draggee.dragmovetype;
2731         draggee.gravity = draggee.draggravity;
2732
2733         switch(draggee.movetype)
2734         {
2735                 case MOVETYPE_TOSS:
2736                 case MOVETYPE_WALK:
2737                 case MOVETYPE_STEP:
2738                 case MOVETYPE_FLYMISSILE:
2739                 case MOVETYPE_BOUNCE:
2740                 case MOVETYPE_BOUNCEMISSILE:
2741                 case MOVETYPE_PHYSICS:
2742                         break;
2743                 default:
2744                         draggee.velocity = '0 0 0';
2745                         break;
2746         }
2747
2748         if((draggee.flags & FL_ITEM) && (vlen(draggee.velocity) < 32))
2749         {
2750                 draggee.velocity = '0 0 0';
2751                 draggee.flags |= FL_ONGROUND; // floating items are FUN
2752         }
2753 }
2754
2755 float Drag_IsDraggable(entity draggee)
2756 {
2757         // TODO add more checks for bad stuff here
2758         if(draggee.classname == "func_bobbing")
2759                 return FALSE;
2760         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)
2761                 return FALSE;
2762         if(draggee.classname == "plat")
2763                 return FALSE;
2764         if(draggee.classname == "func_button")
2765                 return FALSE;
2766         if(draggee.model == "")
2767                 return FALSE;
2768         if(draggee.classname == "spectator")
2769                 return FALSE;
2770         if(draggee.classname == "observer")
2771                 return FALSE;
2772         if(draggee.classname == "exteriorweaponentity")
2773                 return FALSE;
2774
2775         return TRUE;
2776 }
2777
2778 float Drag_MayChangeAngles(entity draggee)
2779 {
2780         // TODO add more checks for bad stuff here
2781         if(substring(draggee.model, 0, 1) == "*")
2782                 return FALSE;
2783         return TRUE;
2784 }
2785
2786 void Drag_MoveForward(entity dragger)
2787 {
2788         dragger.dragdistance += dragger.dragspeed;
2789 }
2790
2791 void Drag_SetSpeed(entity dragger, float s)
2792 {
2793         dragger.dragspeed = pow(2, s);
2794 }
2795
2796 void Drag_MoveBackward(entity dragger)
2797 {
2798         dragger.dragdistance = max(0, dragger.dragdistance - dragger.dragspeed);
2799 }
2800
2801 void Drag_Update(entity dragger)
2802 {
2803         vector curorigin, neworigin, goodvelocity;
2804         float f;
2805         entity draggee;
2806
2807         draggee = dragger.dragentity;
2808         draggee.flags &~= FL_ONGROUND;
2809
2810         curorigin = gettaginfo(draggee, 0);
2811         curorigin = curorigin + v_forward * dragger.draglocalvector_x + v_right * dragger.draglocalvector_y + v_up * dragger.draglocalvector_z;
2812         makevectors(dragger.v_angle);
2813         neworigin = dragger.origin + dragger.view_ofs + v_forward * dragger.dragdistance;
2814         goodvelocity = (neworigin - curorigin) * (1 / frametime);
2815
2816         while(draggee.angles_y - dragger.v_angle_y - dragger.draglocalangle > 180)
2817                 dragger.draglocalangle += 360;
2818         while(draggee.angles_y - dragger.v_angle_y - dragger.draglocalangle <= -180)
2819                 dragger.draglocalangle -= 360;
2820
2821         f = min(frametime * 10, 1);
2822         draggee.velocity = draggee.velocity * (1 - f) + goodvelocity * f;
2823
2824         if(Drag_MayChangeAngles(draggee))
2825                 draggee.angles_y = draggee.angles_y * (1 - f) + (dragger.v_angle_y + dragger.draglocalangle) * f;
2826
2827         draggee.ltime = max(servertime + serverframetime, draggee.ltime); // fixes func_train breakage
2828
2829         te_lightning1(dragger, dragger.origin + dragger.view_ofs, curorigin);
2830 }
2831
2832 float Drag_CanDrag(entity dragger)
2833 {
2834         return (dragger.deadflag == DEAD_NO) || (dragger.classname == "player");
2835 }
2836
2837 float Drag_IsDragging(entity dragger)
2838 {
2839         if(!dragger.dragentity)
2840                 return FALSE;
2841         if(wasfreed(dragger.dragentity) || dragger.dragentity.draggedby != dragger)
2842         {
2843                 dragger.dragentity = world;
2844                 return FALSE;
2845         }
2846         if(!Drag_CanDrag(dragger) || !Drag_IsDraggable(dragger.dragentity))
2847         {
2848                 Drag_Finish(dragger);
2849                 return FALSE;
2850         }
2851         return TRUE;
2852 }
2853
2854 void Drag_MoveDrag(entity from, entity to)
2855 {
2856         if(from.draggedby)
2857         {
2858                 to.draggedby = from.draggedby;
2859                 to.draggedby.dragentity = to;
2860                 from.draggedby = world;
2861         }
2862 }
2863
2864 /*
2865 =============
2866 PlayerPostThink
2867
2868 Called every frame for each client after the physics are run
2869 =============
2870 */
2871 .float idlekick_lasttimeleft;
2872 void PlayerPostThink (void)
2873 {
2874         // Savage: Check for nameless players
2875         if (strlen(self.netname) < 1) {
2876                 self.netname = "Player";
2877                 stuffcmd(self, "seta _cl_name Player\n");
2878         }
2879
2880         // send the clients accuracy stats to the client
2881         if(self.stat_count > 0)
2882         if(frametime)
2883         {
2884                 self.stat_hit = self.stat_count + 64 * floor(self.(stats_hit[self.stat_count - 1]));
2885                 self.stat_fired = self.stat_count + 64 * floor(self.(stats_fired[self.stat_count - 1]));
2886                 self.stat_count -= 1;
2887         }
2888
2889         if(sv_maxidle && frametime)
2890         {
2891                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2892                 float timeleft;
2893                 timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
2894                 if(timeleft <= 0)
2895                 {
2896                         bprint("^3", self.netname, "^3 was kicked for idling.\n");
2897                         announce(self, "announcer/robotic/terminated.wav");
2898                         dropclient(self);
2899                         return;
2900                 }
2901                 else if(timeleft <= 10)
2902                 {
2903                         if(timeleft != self.idlekick_lasttimeleft)
2904                         {
2905                                 centerprint_atprio(self, CENTERPRIO_IDLEKICK, strcat("^3Stop idling!\n^3Disconnecting in ", ftos(timeleft), "..."));
2906                                 announce(self, strcat("announcer/robotic/", ftos(timeleft), ".wav"));
2907                         }
2908                 }
2909                 else
2910                 {
2911                         centerprint_expire(self, CENTERPRIO_IDLEKICK);
2912                 }
2913                 self.idlekick_lasttimeleft = timeleft;
2914         }
2915
2916 #ifdef TETRIS
2917         if(self.impulse == 100)
2918                 ImpulseCommands();
2919         if (TetrisPostFrame())
2920                 return;
2921 #endif
2922
2923         if(sv_cheats || self.maycheat)
2924                 if(Drag_CanDrag(self))
2925                         if(self.BUTTON_DRAG)
2926                                 if(!self.dragentity)
2927                                         if(self.cursor_trace_ent)
2928                                                 if(Drag_IsDraggable(self.cursor_trace_ent))
2929                                                 {
2930                                                         if(self.cursor_trace_ent.draggedby)
2931                                                                 Drag_Finish(self.cursor_trace_ent.draggedby);
2932                                                         if(self.cursor_trace_ent.tag_entity)
2933                                                                 detach_sameorigin(self.cursor_trace_ent);
2934                                                         Drag_Begin(self, self.cursor_trace_ent, self.cursor_trace_endpos);
2935                                                 }
2936
2937         if(Drag_IsDragging(self))
2938         {
2939                 if(self.BUTTON_DRAG)
2940                 {
2941                         if(self.impulse == 10 || self.impulse == 15 || self.impulse == 18)
2942                         {
2943                                 Drag_MoveForward(self);
2944                                 self.impulse = 0;
2945                         }
2946                         else if(self.impulse == 12 || self.impulse == 16 || self.impulse == 19)
2947                         {
2948                                 Drag_MoveBackward(self);
2949                                 self.impulse = 0;
2950                         }
2951                         else if(self.impulse >= 1 && self.impulse <= 9)
2952                         {
2953                                 Drag_SetSpeed(self, self.impulse - 1);
2954                         }
2955                         else if(self.impulse == 14)
2956                         {
2957                                 Drag_SetSpeed(self, 9);
2958                         }
2959
2960                         if(frametime)
2961                                 Drag_Update(self);
2962                 }
2963                 else
2964                 {
2965                         Drag_Finish(self);
2966                 }
2967         }
2968
2969         if(self.classname == "player") {
2970                 CheckRules_Player();
2971                 UpdateChatBubble();
2972                 UpdateTeamBubble();
2973                 if (self.impulse)
2974                         ImpulseCommands();
2975                 if (intermission_running)
2976                         return;         // intermission or finale
2977
2978                 GetPressedKeys();
2979         } else if (self.classname == "observer") {
2980                 //do nothing
2981         } else if (self.classname == "spectator") {
2982                 //do nothing
2983         }
2984
2985         /*
2986         float i;
2987         for(i = 0; i < 1000; ++i)
2988         {
2989                 vector end;
2990                 end = self.origin + '0 0 1024' + 512 * randomvec();
2991                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
2992                 if(trace_fraction < 1)
2993                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
2994                 {
2995                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
2996                         break;
2997                 }
2998         }
2999         */
3000
3001         Arena_Warmup();
3002
3003         //pointparticles(particleeffectnum("machinegun_impact"), self.origin + self.view_ofs + '0 0 7', '0 0 0', 1);
3004
3005         if(self.waypointsprite_attachedforcarrier)
3006                 WaypointSprite_UpdateHealth(self.waypointsprite_attachedforcarrier, '1 0 0' * healtharmor_maxdamage(self.health, self.armorvalue, cvar("g_balance_armor_blockpercent")));
3007         
3008         playerdemo_write();
3009 }