]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/cl_client.qc
cvar for enabling/disabling playerclips on a map (useful on eg defrag maps with ...
[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                         defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", Team_ColorNameLowerCase(self.team)));
699                         defaultskin = cvar(strcat("sv_defaultplayerskin_", Team_ColorNameLowerCase(self.team)));
700                 }
701
702                 if(defaultmodel == "")
703                 {
704                         defaultmodel = cvar_string("sv_defaultplayermodel");
705                         defaultskin = cvar("sv_defaultplayerskin");
706                 }
707         }
708
709         if(self.modelindex == 0 && self.deadflag == DEAD_NO)
710         {
711                 if(self.model != "")
712                         bprint("\{1}^1Player ", self.netname, "^1 has a zero modelindex, trying to fix...\n");
713                 self.model = ""; // force the != checks to return true
714         }
715
716         if(defaultmodel != "")
717         {
718                 if (defaultmodel != self.model)
719                 {
720                         m1 = self.mins;
721                         m2 = self.maxs;
722                         setmodel_lod (self, defaultmodel);
723                         setsize (self, m1, m2);
724                         chmdl = TRUE;
725                 }
726
727                 oldskin = self.skinindex;
728                 self.skinindex = defaultskin;
729         } else {
730                 if (self.playermodel != self.model || self.playermodel == "")
731                 {
732                         self.playermodel = CheckPlayerModel(self.playermodel); // this is never "", so no endless loop
733                         m1 = self.mins;
734                         m2 = self.maxs;
735                         setmodel_lod (self, self.playermodel);
736                         setsize (self, m1, m2);
737                         chmdl = TRUE;
738                 }
739
740                 oldskin = self.skinindex;
741                 self.skinindex = RestrictSkin(stof(self.playerskin));
742         }
743
744         if(chmdl || oldskin != self.skinindex)
745                 self.species = player_getspecies(); // model or skin has changed
746
747         if(!teams_matter)
748                 if(strlen(cvar_string("sv_defaultplayercolors")))
749                         if(self.clientcolors != cvar("sv_defaultplayercolors"))
750                                 setcolor(self, cvar("sv_defaultplayercolors"));
751 }
752
753 void PlayerTouchExplode(entity p1, entity p2)
754 {
755         vector org;
756         org = (p1.origin + p2.origin) * 0.5;
757         org_z += (p1.mins_z + p2.mins_z) * 0.5;
758
759         te_explosion(org);
760
761         entity e;
762         e = spawn();
763         setorigin(e, org);
764         RadiusDamage(e, world, g_touchexplode_damage, g_touchexplode_edgedamage, g_touchexplode_radius, world, g_touchexplode_force, DEATH_TOUCHEXPLODE, world);
765         remove(e);
766 }
767
768 /*
769 =============
770 PutClientInServer
771
772 Called when a client spawns in the server
773 =============
774 */
775 //void() ctf_playerchanged;
776 void PutClientInServer (void)
777 {
778         if(clienttype(self) == CLIENTTYPE_BOT)
779         {
780                 self.classname = "player";
781         }
782         else if(clienttype(self) == CLIENTTYPE_REAL)
783         {
784                 msg_entity = self;
785                 WriteByte(MSG_ONE, SVC_SETVIEW);
786                 WriteEntity(MSG_ONE, self);
787         }
788
789         // player is dead and becomes observer
790         // FIXME fix LMS scoring for new system
791         if(g_lms)
792         {
793                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
794                         self.classname = "observer";
795         }
796
797         if(g_arena || (g_ca && !allowed_to_spawn))
798         if(!self.spawned)
799                 self.classname = "observer";
800
801         if(gameover)
802                 self.classname = "observer";
803
804         if(self.classname == "player" && (!g_ca || (g_ca && allowed_to_spawn))) {
805                 entity spot, oldself;
806                 float j;
807
808                 if(self.team < 0)
809                         JoinBestTeam(self, FALSE, TRUE);
810
811                 race_PreSpawn();
812
813                 spot = SelectSpawnPoint (FALSE);
814                 if(!spot)
815                 {
816                         centerprint(self, "Sorry, no spawnpoints available!\nHope your team can fix it...");
817                         return; // spawn failed
818                 }
819
820                 RemoveGrapplingHook(self); // Wazat's Grappling Hook
821
822                 self.classname = "player";
823                 self.wasplayer = TRUE;
824                 self.iscreature = TRUE;
825                 self.movetype = MOVETYPE_WALK;
826                 self.solid = SOLID_SLIDEBOX;
827                 if(cvar("g_playerclip_collisions"))
828                         self.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY | DPCONTENTS_PLAYERCLIP;
829                 else
830                         self.dphitcontentsmask = DPCONTENTS_SOLID | DPCONTENTS_BODY;
831                 self.frags = FRAGS_PLAYER;
832                 if(independent_players)
833                         MAKE_INDEPENDENT_PLAYER(self);
834                 self.flags = FL_CLIENT;
835                 self.takedamage = DAMAGE_AIM;
836                 if(g_minstagib)
837                         self.effects = EF_FULLBRIGHT;
838                 else
839                         self.effects = 0;
840                 self.air_finished = time + 12;
841                 self.dmg = 2;
842
843                 if(inWarmupStage)
844                 {
845                         self.ammo_shells = warmup_start_ammo_shells;
846                         self.ammo_nails = warmup_start_ammo_nails;
847                         self.ammo_rockets = warmup_start_ammo_rockets;
848                         self.ammo_cells = warmup_start_ammo_cells;
849                         self.ammo_fuel = warmup_start_ammo_fuel;
850                         self.health = warmup_start_health;
851                         self.armorvalue = warmup_start_armorvalue;
852                         self.weapons = warmup_start_weapons;
853                 }
854                 else
855                 {
856                         self.ammo_shells = start_ammo_shells;
857                         self.ammo_nails = start_ammo_nails;
858                         self.ammo_rockets = start_ammo_rockets;
859                         self.ammo_cells = start_ammo_cells;
860                         self.ammo_fuel = start_ammo_fuel;
861                         self.health = start_health;
862                         self.armorvalue = start_armorvalue;
863                         self.weapons = start_weapons;
864                 }
865
866                 if(g_weaponarena_random)
867                         self.weapons = randombits(self.weapons, g_weaponarena_random, FALSE);
868
869                 self.items = start_items;
870                 self.switchweapon = w_getbestweapon(self);
871                 self.cnt = self.switchweapon;
872                 self.weapon = 0;
873                 self.jump_interval = time;
874
875                 self.spawnshieldtime = time + cvar("g_spawnshieldtime");
876                 self.pauserotarmor_finished = time + cvar("g_balance_pause_armor_rot_spawn");
877                 self.pauserothealth_finished = time + cvar("g_balance_pause_health_rot_spawn");
878                 self.pauserotfuel_finished = time + cvar("g_balance_pause_fuel_rot_spawn");
879                 self.pauseregen_finished = time + cvar("g_balance_pause_health_regen_spawn");
880                 //extend the pause of rotting if client was reset at the beginning of the countdown
881                 if(!cvar("sv_ready_restart_after_countdown") && time < game_starttime) { // TODO why is this cvar NOTted?
882                         self.spawnshieldtime += game_starttime - time;
883                         self.pauserotarmor_finished += game_starttime - time;
884                         self.pauserothealth_finished += game_starttime - time;
885                         self.pauseregen_finished += game_starttime - time;
886                 }
887                 self.damageforcescale = 2;
888                 self.death_time = 0;
889                 self.dead_frame = 0;
890                 self.alpha = 0;
891                 self.scale = 0;
892                 self.fade_time = 0;
893                 self.pain_frame = 0;
894                 self.pain_finished = 0;
895                 self.strength_finished = 0;
896                 self.invincible_finished = 0;
897                 self.pushltime = 0;
898                 // players have no think function
899                 self.think = SUB_Null;
900                 self.nextthink = 0;
901                 self.hook_time = 0;
902                 self.dmg_team = 0;
903
904                 self.metertime = 0;
905
906                 self.runes = 0;
907
908                 self.deadflag = DEAD_NO;
909
910                 self.angles = spot.angles;
911
912                 self.angles_z = 0; // never spawn tilted even if the spot says to
913                 self.fixangle = TRUE; // turn this way immediately
914                 self.velocity = '0 0 0';
915                 self.avelocity = '0 0 0';
916                 self.punchangle = '0 0 0';
917                 self.punchvector = '0 0 0';
918                 self.oldvelocity = self.velocity;
919                 self.fire_endtime = -1;
920
921                 msg_entity = self;
922                 WRITESPECTATABLE_MSG_ONE({
923                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
924                         WriteByte(MSG_ONE, TE_CSQC_SPAWN);
925                 });
926
927                 if(sv_loddistance1)
928                         SetCustomizer(self, Client_customizeentityforclient, Client_uncustomizeentityforclient);
929
930                 self.model = "";
931                 FixPlayermodel();
932
933                 self.crouch = FALSE;
934                 self.view_ofs = PL_VIEW_OFS;
935                 setsize (self, PL_MIN, PL_MAX);
936                 self.spawnorigin = spot.origin;
937                 setorigin (self, spot.origin + '0 0 1' * (1 - self.mins_z - 24));
938                 // don't reset back to last position, even if new position is stuck in solid
939                 self.oldorigin = self.origin;
940                 self.prevorigin = self.origin;
941                 self.lastrocket = world; // stop rocket guiding, no revenge from the grave!
942
943                 if(g_arena)
944                 {
945                         Spawnqueue_Remove(self);
946                         Spawnqueue_Mark(self);
947                 }
948
949                 else if(g_ca)
950                         self.caplayer = 1;
951
952                 self.event_damage = PlayerDamage;
953
954                 self.bot_attack = TRUE;
955
956                 self.statdraintime = time + 5;
957                 self.BUTTON_ATCK = self.BUTTON_JUMP = self.BUTTON_ATCK2 = 0;
958
959                 if(self.killcount == -666) {
960                         PlayerScore_Clear(self);
961                         self.killcount = 0;
962                 }
963
964                 self.cnt = WEP_LASER;
965                 self.nixnex_lastchange_id = -1;
966
967                 CL_SpawnWeaponentity();
968                 self.alpha = default_player_alpha;
969                 self.colormod = '1 1 1' * cvar("g_player_brightness");
970                 self.exteriorweaponentity.alpha = default_weapon_alpha;
971
972                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
973                 self.lms_traveled_distance = 0;
974                 self.speedrunning = FALSE;
975
976                 race_PostSpawn(spot);
977
978                 if(cvar("spawn_debug"))
979                 {
980                         sprint(self, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
981                         remove(spot);   // usefull for checking if there are spawnpoints, that let drop through the floor
982                 }
983
984                 //stuffcmd(self, "chase_active 0");
985                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
986
987                 if (cvar("g_spawnsound"))
988                         sound (self, CHAN_TRIGGER, "misc/spawn.wav", VOL_BASE, ATTN_NORM);
989
990                 if(g_assault) {
991                         if(self.team == assault_attacker_team)
992                                 centerprint(self, "You are attacking!");
993                         else
994                                 centerprint(self, "You are defending!");
995                 }
996
997                 target_voicescript_clear(self);
998
999                 // reset fields the weapons may use
1000         for (j = WEP_FIRST; j <= WEP_LAST; ++j)
1001             weapon_action(j, WR_RESETPLAYER);
1002
1003                 oldself = self;
1004                 self = spot;
1005                         activator = oldself;
1006                                 SUB_UseTargets();
1007                         activator = world;
1008                 self = oldself;
1009         } else if(self.classname == "observer" || (g_ca && !allowed_to_spawn)) {
1010                 PutObserverInServer ();
1011         }
1012
1013         //if(g_ctf)
1014         //      ctf_playerchanged();
1015 }
1016
1017 float ClientInit_SendEntity(entity to, float sf)
1018 {
1019         float i;
1020         WriteByte(MSG_ENTITY, ENT_CLIENT_INIT);
1021         WriteByte(MSG_ENTITY, g_nexball_meter_period * 32);
1022         for(i = 1; i <= 24; ++i)
1023                 WriteByte(MSG_ENTITY, (get_weaponinfo(i)).impulse + 1);
1024         WriteCoord(MSG_ENTITY, hook_shotorigin_x);
1025         WriteCoord(MSG_ENTITY, hook_shotorigin_y);
1026         WriteCoord(MSG_ENTITY, hook_shotorigin_z);
1027
1028         if(sv_foginterval && world.fog != "")
1029                 WriteString(MSG_ENTITY, world.fog);
1030         else
1031                 WriteString(MSG_ENTITY, "");
1032         WriteByte(MSG_ENTITY, cvar("g_balance_armor_blockpercent") * 255.0);
1033         WriteByte(MSG_ENTITY, cvar("g_balance_weaponswitchdelay") * 255.0);
1034         return TRUE;
1035 }
1036
1037 void ClientInit_Spawn()
1038 {
1039         Net_LinkEntity(spawn(), FALSE, 0, ClientInit_SendEntity);
1040 }
1041
1042 /*
1043 =============
1044 SetNewParms
1045 =============
1046 */
1047 void SetNewParms (void)
1048 {
1049         // initialize parms for a new player
1050         parm1 = -(86400 * 366);
1051 }
1052
1053 /*
1054 =============
1055 SetChangeParms
1056 =============
1057 */
1058 void SetChangeParms (void)
1059 {
1060         // save parms for level change
1061         parm1 = self.parm_idlesince - time;
1062 }
1063
1064 /*
1065 =============
1066 DecodeLevelParms
1067 =============
1068 */
1069 void DecodeLevelParms (void)
1070 {
1071         // load parms
1072         self.parm_idlesince = parm1;
1073         if(self.parm_idlesince == -(86400 * 366))
1074                 self.parm_idlesince = time;
1075
1076         // whatever happens, allow 60 seconds of idling directly after connect for map loading
1077         self.parm_idlesince = max(self.parm_idlesince, time - sv_maxidle + 60);
1078 }
1079
1080 /*
1081 =============
1082 ClientKill
1083
1084 Called when a client types 'kill' in the console
1085 =============
1086 */
1087
1088 void ClientKill_Now_TeamChange()
1089 {
1090         if(self.killindicator_teamchange == -1)
1091         {
1092                 self.team = -1;
1093                 JoinBestTeam( self, FALSE, FALSE );
1094         }
1095         else
1096                 SV_ChangeTeam(self.killindicator_teamchange - 1);
1097 }
1098
1099 void ClientKill_Now()
1100 {
1101         if(self.killindicator_teamchange)
1102                 ClientKill_Now_TeamChange();
1103
1104         // in any case:
1105         Damage(self, self, self, 100000, DEATH_KILL, self.origin, '0 0 0');
1106
1107         if(self.killindicator)
1108         {
1109                 dprint("Cleaned up after a leaked kill indicator.\n");
1110                 remove(self.killindicator);
1111                 self.killindicator = world;
1112         }
1113 }
1114 void KillIndicator_Think()
1115 {
1116         if (!self.owner.modelindex)
1117         {
1118                 self.owner.killindicator = world;
1119                 remove(self);
1120                 return;
1121         }
1122
1123         if(self.cnt <= 0)
1124         {
1125                 self = self.owner;
1126                 ClientKill_Now(); // no oldself needed
1127                 return;
1128         }
1129         else
1130         {
1131                 if(self.cnt <= 10)
1132                         setmodel(self, strcat("models/sprites/", ftos(self.cnt), ".spr32"));
1133                 if(clienttype(self.owner) == CLIENTTYPE_REAL)
1134                 {
1135                         if(self.cnt <= 10)
1136                                 announce(self.owner, strcat("announcer/robotic/", ftos(self.cnt), ".wav"));
1137                         if(self.owner.killindicator_teamchange)
1138                         {
1139                                 if(self.owner.killindicator_teamchange == -1)
1140                                         centerprint(self.owner, strcat("Changing team in ", ftos(self.cnt), " seconds"));
1141                                 else
1142                                         centerprint(self.owner, strcat("Changing to ", ColoredTeamName(self.owner.killindicator_teamchange), " in ", ftos(self.cnt), " seconds"));
1143                         }
1144                         else
1145                                 centerprint(self.owner, strcat("^1Suicide in ", ftos(self.cnt), " seconds"));
1146                 }
1147                 self.nextthink = time + 1;
1148                 self.cnt -= 1;
1149         }
1150 }
1151
1152 void ClientKill_TeamChange (float targetteam) // 0 = don't change, -1 = auto
1153 {
1154         float killtime;
1155         entity e;
1156         killtime = cvar("g_balance_kill_delay");
1157
1158         if(g_race_qualifying)
1159                 killtime = 0;
1160
1161         self.killindicator_teamchange = targetteam;
1162
1163         if(!self.killindicator)
1164         {
1165                 if(killtime <= 0 || !self.modelindex || self.deadflag != DEAD_NO)
1166                 {
1167                         ClientKill_Now();
1168                 }
1169                 else
1170                 {
1171                         self.killindicator = spawn();
1172                         self.killindicator.owner = self;
1173                         self.killindicator.scale = 0.5;
1174                         setattachment(self.killindicator, self, "");
1175                         setorigin(self.killindicator, '0 0 52');
1176                         self.killindicator.think = KillIndicator_Think;
1177                         self.killindicator.nextthink = time + (self.lip) * 0.05;
1178                         self.killindicator.cnt = ceil(killtime);
1179                         self.killindicator.count = bound(0, ceil(killtime), 10);
1180                         sprint(self, strcat("^1You'll be dead in ", ftos(self.killindicator.cnt), " seconds\n"));
1181
1182                         for(e = world; (e = find(e, classname, "body")) != world; )
1183                         {
1184                                 if(e.enemy != self)
1185                                         continue;
1186                                 e.killindicator = spawn();
1187                                 e.killindicator.owner = e;
1188                                 e.killindicator.scale = 0.5;
1189                                 setattachment(e.killindicator, e, "");
1190                                 setorigin(e.killindicator, '0 0 52');
1191                                 e.killindicator.think = KillIndicator_Think;
1192                                 e.killindicator.nextthink = time + (e.lip) * 0.05;
1193                                 e.killindicator.cnt = ceil(killtime);
1194                         }
1195                         self.lip = 0;
1196                 }
1197         }
1198         if(self.killindicator)
1199         {
1200                 if(targetteam)
1201                         self.killindicator.colormod = TeamColor(targetteam);
1202                 else
1203                         self.killindicator.colormod = '0 0 0';
1204         }
1205 }
1206
1207 void ClientKill (void)
1208 {
1209         ClientKill_TeamChange(0);
1210 }
1211
1212 void DoTeamChange(float destteam)
1213 {
1214         float t, c0;
1215         if(!teams_matter)
1216         {
1217                 if(destteam >= 0)
1218                         SetPlayerColors(self, destteam);
1219                 return;
1220         }
1221         if(self.classname == "player")
1222         if(destteam == -1)
1223         {
1224                 CheckAllowedTeams(self);
1225                 t = FindSmallestTeam(self, TRUE);
1226                 switch(self.team)
1227                 {
1228                         case COLOR_TEAM1: c0 = c1; break;
1229                         case COLOR_TEAM2: c0 = c2; break;
1230                         case COLOR_TEAM3: c0 = c3; break;
1231                         case COLOR_TEAM4: c0 = c4; break;
1232                         default:          c0 = 999;
1233                 }
1234                 switch(t)
1235                 {
1236                         case 1:
1237                                 if(c0 > c1)
1238                                         destteam = COLOR_TEAM1;
1239                                 break;
1240                         case 2:
1241                                 if(c0 > c2)
1242                                         destteam = COLOR_TEAM2;
1243                                 break;
1244                         case 3:
1245                                 if(c0 > c3)
1246                                         destteam = COLOR_TEAM3;
1247                                 break;
1248                         case 4:
1249                                 if(c0 > c4)
1250                                         destteam = COLOR_TEAM4;
1251                                 break;
1252                 }
1253                 if(destteam == -1)
1254                         return;
1255         }
1256         if(destteam == self.team && destteam >= 0 && !self.killindicator)
1257                 return;
1258         ClientKill_TeamChange(destteam);
1259 }
1260
1261 void FixClientCvars(entity e)
1262 {
1263         // send prediction settings to the client
1264         stuffcmd(e, "\nin_bindmap 0 0\n");
1265         if(g_race || g_cts)
1266                 stuffcmd(e, "cl_cmd settemp cl_movecliptokeyboard 2\n");
1267         /*
1268          * we no longer need to stuff this. Remove this comment block if you feel
1269          * 2.3 and higher (or was it 2.2.3?) don't need these any more
1270         stuffcmd(e, strcat("cl_gravity ", ftos(cvar("sv_gravity")), "\n"));
1271         stuffcmd(e, strcat("cl_movement_accelerate ", ftos(cvar("sv_accelerate")), "\n"));
1272         stuffcmd(e, strcat("cl_movement_friction ", ftos(cvar("sv_friction")), "\n"));
1273         stuffcmd(e, strcat("cl_movement_maxspeed ", ftos(cvar("sv_maxspeed")), "\n"));
1274         stuffcmd(e, strcat("cl_movement_airaccelerate ", ftos(cvar("sv_airaccelerate")), "\n"));
1275         stuffcmd(e, strcat("cl_movement_maxairspeed ", ftos(cvar("sv_maxairspeed")), "\n"));
1276         stuffcmd(e, strcat("cl_movement_stopspeed ", ftos(cvar("sv_stopspeed")), "\n"));
1277         stuffcmd(e, strcat("cl_movement_jumpvelocity ", ftos(cvar("sv_jumpvelocity")), "\n"));
1278         stuffcmd(e, strcat("cl_movement_stepheight ", ftos(cvar("sv_stepheight")), "\n"));
1279         stuffcmd(e, strcat("set cl_movement_friction_on_land ", ftos(cvar("sv_friction_on_land")), "\n"));
1280         stuffcmd(e, strcat("set cl_movement_airaccel_qw ", ftos(cvar("sv_airaccel_qw")), "\n"));
1281         stuffcmd(e, strcat("set cl_movement_airaccel_sideways_friction ", ftos(cvar("sv_airaccel_sideways_friction")), "\n"));
1282         stuffcmd(e, "cl_movement_edgefriction 1\n");
1283          */
1284 }
1285
1286 /*
1287 =============
1288 ClientConnect
1289
1290 Called when a client connects to the server
1291 =============
1292 */
1293 //void ctf_clientconnect();
1294 string ColoredTeamName(float t);
1295 void DecodeLevelParms (void);
1296 //void dom_player_join_team(entity pl);
1297 void ClientConnect (void)
1298 {
1299         float t;
1300
1301         if(self.flags & FL_CLIENT)
1302         {
1303                 print("Warning: ClientConnect, but already connected!\n");
1304                 return;
1305         }
1306
1307         if(Ban_MaybeEnforceBan(self))
1308                 return;
1309
1310         DecodeLevelParms();
1311
1312         self.classname = "player_joining";
1313
1314         self.flags = FL_CLIENT;
1315         self.version_nagtime = time + 10 + random() * 10;
1316
1317         if(player_count<0)
1318         {
1319                 dprint("BUG player count is lower than zero, this cannot happen!\n");
1320                 player_count = 0;
1321         }
1322
1323         PlayerScore_Attach(self);
1324         ClientData_Attach();
1325
1326         bot_clientconnect();
1327         
1328         playerdemo_init();
1329
1330         race_PreSpawnObserver();
1331
1332         //if(g_domination)
1333         //      dom_player_join_team(self);
1334
1335         JoinBestTeam(self, FALSE, FALSE); // if the team number is valid, keep it
1336
1337         if((cvar("sv_spectate") == 1 && !g_lms) || cvar("g_campaign")) {
1338                 self.classname = "observer";
1339         } else {
1340                 if(teams_matter)
1341                 {
1342                         if(cvar("g_balance_teams") || cvar("g_balance_teams_force"))
1343                         {
1344                                 self.classname = "player";
1345                                 campaign_bots_may_start = 1;
1346                         }
1347                         else
1348                         {
1349                                 self.classname = "observer"; // do it anyway
1350                         }
1351                 }
1352                 else
1353                 {
1354                         self.classname = "player";
1355                         campaign_bots_may_start = 1;
1356                 }
1357         }
1358
1359         self.playerid = (playerid_last = playerid_last + 1);
1360
1361         if(cvar("sv_eventlog"))
1362                 GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":", ((clienttype(self) == CLIENTTYPE_REAL) ? self.netaddress : "bot"), ":", self.netname));
1363
1364         LogTeamchange(self.playerid, self.team, 1);
1365
1366         self.just_joined = TRUE;  // stop spamming the eventlog with additional lines when the client connects
1367
1368         self.netname_previous = strzone(self.netname);
1369
1370         bprint("^4", self.netname, "^4 connected");
1371
1372         if(g_domination || g_ctf)
1373                 bprint(" and joined the ", ColoredTeamName(self.team));
1374
1375         bprint("\n");
1376
1377         self.welcomemessage_time = 0;
1378
1379         stuffcmd(self, strcat(clientstuff, "\n"));
1380         stuffcmd(self, strcat("exec maps/", mapname, ".cfg\n"));
1381         stuffcmd(self, "cl_particles_reloadeffects\n");
1382
1383         FixClientCvars(self);
1384
1385         // spawnfunc_waypoint sprites
1386         WaypointSprite_InitClient(self);
1387
1388         // Wazat's grappling hook
1389         SetGrappleHookBindings();
1390
1391         // get autoswitch state from player when he toggles it
1392         stuffcmd(self, "alias autoswitch \"set cl_autoswitch $1 ; cmd autoswitch $1\"\n"); // default.cfg-ed in 2.4.1
1393
1394         // get version info from player
1395         stuffcmd(self, "cmd clientversion $gameversion\n");
1396
1397         // get other cvars from player
1398         GetCvars(0);
1399
1400         // set cvar for team scoreboard
1401         stuffcmd(self, strcat("set teamplay ", ftos(teamplay), "\n"));
1402
1403         // notify about available teams
1404         if(teams_matter)
1405         {
1406                 CheckAllowedTeams(self);
1407                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1408                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1409         }
1410         else
1411                 stuffcmd(self, "set _teams_available 0\n");
1412
1413         stuffcmd(self, strcat("set gametype ", ftos(game), "\n"));
1414
1415         if(g_arena || g_ca)
1416         {
1417                 self.classname = "observer";
1418                 if(g_arena)
1419                         Spawnqueue_Insert(self);
1420         }
1421         /*else if(g_ctf)
1422         {
1423                 ctf_clientconnect();
1424         }*/
1425
1426         if(teams_matter || sv_cheats)
1427                 attach_entcs();
1428
1429         bot_relinkplayerlist();
1430
1431         self.spectatortime = time;
1432         if(blockSpectators)
1433         {
1434                 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"));
1435         }
1436
1437         self.jointime = time;
1438         self.allowedTimeouts = cvar("sv_timeout_number");
1439
1440         if(clienttype(self) == CLIENTTYPE_REAL)
1441         {
1442                 if(cvar("g_bugrigs") || g_weaponarena == WEPBIT_TUBA)
1443                         stuffcmd(self, "cl_cmd settemp chase_active 1\n");
1444         }
1445
1446         if(g_lms)
1447         {
1448                 if(PlayerScore_Add(self, SP_LMS_LIVES, LMS_NewPlayerLives()) <= 0)
1449                 {
1450                         PlayerScore_Add(self, SP_LMS_RANK, 666);
1451                         self.frags = FRAGS_SPECTATOR;
1452                 }
1453         }
1454
1455         if(!sv_foginterval && world.fog != "")
1456                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1457
1458         SoundEntity_Attach(self);
1459
1460         if(cvar("g_hitplots") || strstrofs(strcat(" ", cvar_string("g_hitplots_individuals"), " "), strcat(" ", self.netaddress, " "), 0) >= 0)
1461         {
1462                 self.hitplotfh = fopen(strcat("hits-", matchid, "-", self.netaddress, "-", ftos(self.playerid), ".plot"), FILE_WRITE);
1463                 fputs(self.hitplotfh, strcat("#name ", self.netname, "\n"));
1464         }
1465         else
1466                 self.hitplotfh = -1;
1467
1468         if(g_race || g_cts) {
1469                 string rr;
1470                 if(g_cts)
1471                         rr = CTS_RECORD;
1472                 else
1473                         rr = RACE_RECORD;
1474                 t = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "time")));
1475
1476                 race_send_recordtime(t, MSG_ONE);
1477                 race_send_speedaward(MSG_ONE);
1478
1479                 speedaward_alltimebest = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/speed")));
1480                 speedaward_alltimebest_holder = db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/netname"));
1481                 race_send_speedaward_alltimebest(MSG_ONE);
1482         }
1483         else if(cvar("sv_teamnagger") && !g_ca) // teamnagger is currently bad for ca
1484                 send_CSQC_teamnagger();
1485 }
1486
1487 /*
1488 =============
1489 ClientDisconnect
1490
1491 Called when a client disconnects from the server
1492 =============
1493 */
1494 .entity chatbubbleentity;
1495 .entity teambubbleentity;
1496 void ReadyCount();
1497 void ClientDisconnect (void)
1498 {
1499         if not(self.flags & FL_CLIENT)
1500         {
1501                 print("Warning: ClientDisconnect without ClientConnect\n");
1502                 return;
1503         }
1504
1505         if(self.hitplotfh >= 0)
1506         {
1507                 fclose(self.hitplotfh);
1508                 self.hitplotfh = -1;
1509         }
1510
1511         playerdemo_shutdown();
1512
1513         bot_clientdisconnect();
1514
1515         if(self.entcs)
1516                 detach_entcs();
1517
1518         if(cvar("sv_eventlog"))
1519                 GameLogEcho(strcat(":part:", ftos(self.playerid)));
1520         bprint ("^4",self.netname);
1521         bprint ("^4 disconnected\n");
1522
1523         SoundEntity_Detach(self);
1524
1525         DropAllRunes(self);
1526         kh_Key_DropAll(self, TRUE);
1527
1528         Portal_ClearAll(self);
1529
1530         if(self.flagcarried)
1531                 DropFlag(self.flagcarried, world, world);
1532         if(self.ballcarried)
1533                 DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
1534
1535         // Here, everything has been done that requires this player to be a client.
1536
1537         self.flags &~= FL_CLIENT;
1538
1539         if (self.chatbubbleentity)
1540                 remove (self.chatbubbleentity);
1541
1542         if (self.teambubbleentity)
1543                 remove (self.teambubbleentity);
1544
1545         if (self.killindicator)
1546                 remove (self.killindicator);
1547
1548         WaypointSprite_PlayerGone();
1549
1550         bot_relinkplayerlist();
1551
1552         // remove laserdot
1553         if(self.weaponentity)
1554                 if(self.weaponentity.lasertarget)
1555                         remove(self.weaponentity.lasertarget);
1556
1557         if(g_arena)
1558         {
1559                 Spawnqueue_Unmark(self);
1560                 Spawnqueue_Remove(self);
1561         }
1562
1563         ClientData_Detach();
1564         PlayerScore_Detach(self);
1565
1566         if(self.netname_previous)
1567                 strunzone(self.netname_previous);
1568         if(self.clientstatus)
1569                 strunzone(self.clientstatus);
1570
1571         ClearPlayerSounds();
1572
1573         if(self.personal)
1574                 remove(self.personal);
1575
1576         self.playerid = 0;
1577         ReadyCount();
1578
1579         // free cvars
1580         GetCvars(-1);
1581 }
1582
1583 .float BUTTON_CHAT;
1584 void ChatBubbleThink()
1585 {
1586         self.nextthink = time;
1587         if (!self.owner.modelindex || self.owner.chatbubbleentity != self)
1588         {
1589                 if(self.owner) // but why can that ever be world?
1590                         self.owner.chatbubbleentity = world;
1591                 remove(self);
1592                 return;
1593         }
1594         if ((self.owner.BUTTON_CHAT && !self.owner.deadflag)
1595 #ifdef TETRIS
1596                 || self.owner.tetris_on
1597 #endif
1598         )
1599                 self.model = self.mdl;
1600         else
1601                 self.model = "";
1602 };
1603
1604 void UpdateChatBubble()
1605 {
1606         if (!self.modelindex)
1607                 return;
1608         // spawn a chatbubble entity if needed
1609         if (!self.chatbubbleentity)
1610         {
1611                 self.chatbubbleentity = spawn();
1612                 self.chatbubbleentity.owner = self;
1613                 self.chatbubbleentity.exteriormodeltoclient = self;
1614                 self.chatbubbleentity.think = ChatBubbleThink;
1615                 self.chatbubbleentity.nextthink = time;
1616                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1617                 //setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1618                 setorigin(self.chatbubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1619                 setattachment(self.chatbubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1620                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1621                 self.chatbubbleentity.model = "";
1622                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1623         }
1624 }
1625
1626
1627 void TeamBubbleThink()
1628 {
1629         self.nextthink = time;
1630         if (!self.owner.modelindex || self.owner.teambubbleentity != self)
1631         {
1632                 if(self.owner) // but why can that ever be world?
1633                         self.owner.teambubbleentity = world;
1634                 remove(self);
1635                 return;
1636         }
1637 //      setorigin(self, self.owner.origin + '0 0 15' + self.owner.maxs_z * '0 0 1');  // bandwidth hog. setattachment does this now
1638         if (self.owner.BUTTON_CHAT || self.owner.deadflag || self.owner.killindicator)
1639                 self.model = "";
1640         else
1641                 self.model = self.mdl;
1642
1643 };
1644
1645 float TeamBubble_customizeentityforclient()
1646 {
1647         return (self.owner != other && self.owner.team == other.team && other.killcount > -666);
1648 }
1649
1650 void UpdateTeamBubble()
1651 {
1652         if (!self.modelindex || !teams_matter)
1653                 return;
1654         // spawn a teambubble entity if needed
1655         if (!self.teambubbleentity && teams_matter)
1656         {
1657                 self.teambubbleentity = spawn();
1658                 self.teambubbleentity.owner = self;
1659                 self.teambubbleentity.exteriormodeltoclient = self;
1660                 self.teambubbleentity.think = TeamBubbleThink;
1661                 self.teambubbleentity.nextthink = time;
1662                 setmodel(self.teambubbleentity, "models/misc/teambubble.spr"); // precision set below
1663 //              setorigin(self.teambubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1664                 setorigin(self.teambubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1665                 setattachment(self.teambubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1666                 self.teambubbleentity.mdl = self.teambubbleentity.model;
1667                 self.teambubbleentity.model = self.teambubbleentity.mdl;
1668                 self.teambubbleentity.customizeentityforclient = TeamBubble_customizeentityforclient;
1669                 self.teambubbleentity.effects = EF_LOWPRECISION;
1670         }
1671 }
1672
1673 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1674 // added to the model skins
1675 /*void UpdateColorModHack()
1676 {
1677         local float c;
1678         c = self.clientcolors & 15;
1679         // LordHavoc: only bothering to support white, green, red, yellow, blue
1680              if (!teams_matter) self.colormod = '0 0 0';
1681         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1682         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1683         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1684         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1685         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1686         else self.colormod = '1 1 1';
1687 };*/
1688
1689 void respawn(void)
1690 {
1691         CopyBody(1);
1692         self.effects |= EF_NODRAW; // prevent another CopyBody
1693         PutClientInServer();
1694 }
1695
1696 void play_countdown(float finished, string samp)
1697 {
1698         if(clienttype(self) == CLIENTTYPE_REAL)
1699                 if(floor(finished - time - frametime) != floor(finished - time))
1700                         if(finished - time < 6)
1701                                 sound (self, CHAN_AUTO, samp, VOL_BASE, ATTN_NORM);
1702 }
1703
1704 /**
1705  * When sv_timeout is used this function returs strings like
1706  * "Timeout begins in 2 seconds!\n" or "Timeout ends in 23 seconds!\n".
1707  * Called by centerprint functions
1708  * @param addOneSecond boolean, set to 1 if the welcome-message centerprint asks for the text
1709  */
1710 string getTimeoutText(float addOneSecond) {
1711         if (!cvar("sv_timeout") || !timeoutStatus)
1712                 return "";
1713
1714         local string retStr;
1715         if (timeoutStatus == 1) {
1716                 if (addOneSecond == 1) {
1717                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime + 1), " seconds!\n");
1718                 }
1719                 else {
1720                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime), " seconds!\n");
1721                 }
1722                 return retStr;
1723         }
1724         else if (timeoutStatus == 2) {
1725                 if (addOneSecond) {
1726                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime + 1), " seconds!\n");
1727                         //don't show messages like "Timeout ends in 0 seconds"...
1728                         if ((remainingTimeoutTime + 1) > 0)
1729                                 return retStr;
1730                         else
1731                                 return "";
1732                 }
1733                 else {
1734                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime), " seconds!\n");
1735                         //don't show messages like "Timeout ends in 0 seconds"...
1736                         if (remainingTimeoutTime > 0)
1737                                 return retStr;
1738                         else
1739                                 return "";
1740                 }
1741         }
1742         else return "";
1743 }
1744
1745 void player_powerups (void)
1746 {
1747         if((self.items & IT_USING_JETPACK) && !self.deadflag)
1748         {
1749                 SoundEntity_StartSound(self, CHAN_PLAYER, "misc/jetpack_fly.wav", VOL_BASE, cvar("g_jetpack_attenuation"));
1750                 self.modelflags |= MF_ROCKET;
1751         }
1752         else
1753         {
1754                 SoundEntity_StopSound(self, CHAN_PLAYER);
1755                 self.modelflags &~= MF_ROCKET;
1756         }
1757
1758         self.effects &~= (EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT | EF_FLAME | EF_NODEPTHTEST);
1759
1760         if(!self.modelindex || self.deadflag) // don't apply the flags if the player is gibbed
1761                 return;
1762         
1763         Fire_ApplyDamage(self);
1764         Fire_ApplyEffect(self);
1765
1766         if (g_minstagib)
1767         {
1768                 self.effects |= EF_FULLBRIGHT;
1769
1770                 if (self.items & IT_STRENGTH)
1771                 {
1772                         play_countdown(self.strength_finished, "misc/poweroff.wav");
1773                         if (time > self.strength_finished)
1774                         {
1775                                 self.alpha = default_player_alpha;
1776                                 self.exteriorweaponentity.alpha = default_weapon_alpha;
1777                                 self.items &~= IT_STRENGTH;
1778                                 sprint(self, "^3Invisibility has worn off\n");
1779                         }
1780                 }
1781                 else
1782                 {
1783                         if (time < self.strength_finished)
1784                         {
1785                                 self.alpha = g_minstagib_invis_alpha;
1786                                 self.exteriorweaponentity.alpha = g_minstagib_invis_alpha;
1787                                 self.items |= IT_STRENGTH;
1788                                 sprint(self, "^3You are invisible\n");
1789                         }
1790                 }
1791
1792                 if (self.items & IT_INVINCIBLE)
1793                 {
1794                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
1795                         if (time > self.invincible_finished && cvar("g_balance_powerup_timer"))
1796                         {
1797                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1798                                 sprint(self, "^3Speed has worn off\n");
1799                         }
1800                 }
1801                 else
1802                 {
1803                         if (time < self.invincible_finished)
1804                         {
1805                                 self.items = self.items | IT_INVINCIBLE;
1806                                 sprint(self, "^3You are on speed\n");
1807                         }
1808                 }
1809                 return;
1810         }
1811
1812         if (self.items & IT_STRENGTH)
1813         {
1814                 play_countdown(self.strength_finished, "misc/poweroff.wav");
1815                 self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1816                 if (time > self.strength_finished && cvar("g_balance_powerup_timer"))
1817                 {
1818                         self.items = self.items - (self.items & IT_STRENGTH);
1819                         sprint(self, "^3Strength has worn off\n");
1820                 }
1821         }
1822         else
1823         {
1824                 if (time < self.strength_finished)
1825                 {
1826                         self.items = self.items | IT_STRENGTH;
1827                         sprint(self, "^3Strength infuses your weapons with devastating power\n");
1828                 }
1829         }
1830         if (self.items & IT_INVINCIBLE)
1831         {
1832                 play_countdown(self.invincible_finished, "misc/poweroff.wav");
1833                 self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1834                 if (time > self.invincible_finished && cvar("g_balance_powerup_timer"))
1835                 {
1836                         self.items = self.items - (self.items & IT_INVINCIBLE);
1837                         sprint(self, "^3Shield has worn off\n");
1838                 }
1839         }
1840         else
1841         {
1842                 if (time < self.invincible_finished)
1843                 {
1844                         self.items = self.items | IT_INVINCIBLE;
1845                         sprint(self, "^3Shield surrounds you\n");
1846                 }
1847         }
1848
1849         if(cvar("g_nodepthtestplayers"))
1850                 self.effects = self.effects | EF_NODEPTHTEST;
1851
1852         if(cvar("g_fullbrightplayers"))
1853                 self.effects = self.effects | EF_FULLBRIGHT;
1854
1855         // midair gamemode: damage only while in the air
1856         // if in midair mode, being on ground grants temporary invulnerability
1857         // (this is so that multishot weapon don't clear the ground flag on the
1858         // first damage in the frame, leaving the player vulnerable to the
1859         // remaining hits in the same frame)
1860         if (self.flags & FL_ONGROUND)
1861         if (g_midair)
1862                 self.spawnshieldtime = max(self.spawnshieldtime, time + cvar("g_midair_shieldtime"));
1863
1864         if (time >= game_starttime)
1865         if (time < self.spawnshieldtime)
1866                 self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1867 }
1868
1869 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
1870 {
1871         if(current > stable)
1872                 return current;
1873         else if(current > stable - 0.25) // when close enough, "snap"
1874                 return stable;
1875         else
1876                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
1877 }
1878
1879 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
1880 {
1881         if(current < stable)
1882                 return current;
1883         else if(current < stable + 0.25) // when close enough, "snap"
1884                 return stable;
1885         else
1886                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
1887 }
1888
1889 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit)
1890 {
1891         if(current > rotstable)
1892         {
1893                 if(rotframetime > 0)
1894                 {
1895                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
1896                         current = max(rotstable, current - rotlinear * rotframetime);
1897                 }
1898         }
1899         else if(current < regenstable)
1900         {
1901                 if(regenframetime > 0)
1902                 {
1903                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
1904                         current = min(regenstable, current + regenlinear * regenframetime);
1905                 }
1906         }
1907
1908         if(current > limit)
1909                 current = limit;
1910
1911         return current;
1912 }
1913
1914 void player_regen (void)
1915 {
1916         float minh, mina, minf, maxh, maxa, maxf, limith, limita, limitf, max_mod, regen_mod, rot_mod, limit_mod;
1917         maxh = cvar("g_balance_health_rotstable");
1918         maxa = cvar("g_balance_armor_rotstable");
1919         maxf = cvar("g_balance_fuel_rotstable");
1920         minh = cvar("g_balance_health_regenstable");
1921         mina = cvar("g_balance_armor_regenstable");
1922         minf = cvar("g_balance_fuel_regenstable");
1923         limith = cvar("g_balance_health_limit");
1924         limita = cvar("g_balance_armor_limit");
1925         limitf = cvar("g_balance_fuel_limit");
1926
1927         max_mod = regen_mod = rot_mod = limit_mod = 1;
1928
1929         if (self.runes & RUNE_REGEN)
1930         {
1931                 if (self.runes & CURSE_VENOM) // do we have both rune/curse?
1932                 {
1933                         regen_mod = cvar("g_balance_rune_regen_combo_regenrate");
1934                         max_mod = cvar("g_balance_rune_regen_combo_hpmod");
1935                         limit_mod = cvar("g_balance_rune_regen_combo_limitmod");
1936                 }
1937                 else
1938                 {
1939                         regen_mod = cvar("g_balance_rune_regen_regenrate");
1940                         max_mod = cvar("g_balance_rune_regen_hpmod");
1941                         limit_mod = cvar("g_balance_rune_regen_limitmod");
1942                 }
1943         }
1944         else if (self.runes & CURSE_VENOM)
1945         {
1946                 max_mod = cvar("g_balance_curse_venom_hpmod");
1947                 if (self.runes & RUNE_REGEN) // do we have both rune/curse?
1948                         rot_mod = cvar("g_balance_rune_regen_combo_rotrate");
1949                 else
1950                         rot_mod = cvar("g_balance_curse_venom_rotrate");
1951                 limit_mod = cvar("g_balance_curse_venom_limitmod");
1952                 //if (!self.runes & RUNE_REGEN)
1953                 //      rot_mod = cvar("g_balance_curse_venom_rotrate");
1954         }
1955         maxh = maxh * max_mod;
1956         //maxa = maxa * max_mod;
1957         //maxf = maxf * max_mod;
1958         minh = minh * max_mod;
1959         //mina = mina * max_mod;
1960         //minf = minf * max_mod;
1961         limith = limith * limit_mod;
1962         limita = limita * limit_mod;
1963         //limitf = limitf * limit_mod;
1964
1965         if(g_lms && g_ca)
1966                 rot_mod = 0;
1967
1968         if (!g_minstagib && !g_ca && (!g_lms || cvar("g_lms_regenerate")))
1969         {
1970                 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);
1971                 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);
1972
1973                 // if player rotted to death...  die!
1974                 if(self.health < 1)
1975                         self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
1976         }
1977
1978         if not(self.items & IT_UNLIMITED_WEAPON_AMMO)
1979                 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);
1980 }
1981
1982 float zoomstate_set;
1983 void SetZoomState(float z)
1984 {
1985         if(z != self.zoomstate)
1986         {
1987                 self.zoomstate = z;
1988                 ClientData_Touch(self);
1989         }
1990         zoomstate_set = 1;
1991 }
1992
1993 void GetPressedKeys(void) {
1994         if (self.movement_x > 0) // get if movement keys are pressed
1995         {       // forward key pressed
1996                 self.pressedkeys |= KEY_FORWARD;
1997                 self.pressedkeys &~= KEY_BACKWARD;
1998         }
1999         else if (self.movement_x < 0)
2000         {       // backward key pressed
2001                 self.pressedkeys |= KEY_BACKWARD;
2002                 self.pressedkeys &~= KEY_FORWARD;
2003         }
2004         else
2005         {       // no x input
2006                 self.pressedkeys &~= KEY_FORWARD;
2007                 self.pressedkeys &~= KEY_BACKWARD;
2008         }
2009
2010         if (self.movement_y > 0)
2011         {       // right key pressed
2012                 self.pressedkeys |= KEY_RIGHT;
2013                 self.pressedkeys &~= KEY_LEFT;
2014         }
2015         else if (self.movement_y < 0)
2016         {       // left key pressed
2017                 self.pressedkeys |= KEY_LEFT;
2018                 self.pressedkeys &~= KEY_RIGHT;
2019         }
2020         else
2021         {       // no y input
2022                 self.pressedkeys &~= KEY_RIGHT;
2023                 self.pressedkeys &~= KEY_LEFT;
2024         }
2025
2026         if (self.BUTTON_JUMP) // get if jump and crouch keys are pressed
2027                 self.pressedkeys |= KEY_JUMP;
2028         else
2029                 self.pressedkeys &~= KEY_JUMP;
2030         if (self.BUTTON_CROUCH)
2031                 self.pressedkeys |= KEY_CROUCH;
2032         else
2033                 self.pressedkeys &~= KEY_CROUCH;
2034 }
2035
2036 void update_stats (float number, float hit, float fired) {
2037 // self.stat_hit   = number + ((number==0) ? 1 : 64) * hit   * sv_accuracy_data_share;
2038 // self.stat_fired = number + ((number==0) ? 1 : 64) * fired * sv_accuracy_data_share;
2039
2040         if(number) {
2041                 self.stat_hit = number + 64 * hit * sv_accuracy_data_share;
2042                 self.stat_fired = number + 64 * fired * sv_accuracy_data_share;
2043         } else {
2044                 self.stat_hit = hit * sv_accuracy_data_share;
2045                 self.stat_fired = fired * sv_accuracy_data_share;
2046         }
2047 }
2048
2049 /*
2050 ======================
2051 spectate mode routines
2052 ======================
2053 */
2054
2055 .float weapon_count;
2056 void SpectateCopy(entity spectatee) {
2057         if(spectatee.weapon_count < WEP_LAST) {
2058                 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]));
2059                 spectatee.weapon_count ++;
2060         } else
2061                 update_stats (0, spectatee.cvar_cl_accuracy_data_share * spectatee.stat_hit, spectatee.cvar_cl_accuracy_data_share * spectatee.stat_fired);
2062
2063         self.kh_state = spectatee.kh_state;
2064         self.armortype = spectatee.armortype;
2065         self.armorvalue = spectatee.armorvalue;
2066         self.ammo_cells = spectatee.ammo_cells;
2067         self.ammo_shells = spectatee.ammo_shells;
2068         self.ammo_nails = spectatee.ammo_nails;
2069         self.ammo_rockets = spectatee.ammo_rockets;
2070         self.ammo_fuel = spectatee.ammo_fuel;
2071         self.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
2072         self.health = spectatee.health;
2073         self.impulse = 0;
2074         self.items = spectatee.items;
2075         self.metertime = spectatee.metertime;
2076         self.strength_finished = spectatee.strength_finished;
2077         self.invincible_finished = spectatee.invincible_finished;
2078         self.pressedkeys = spectatee.pressedkeys;
2079         self.weapons = spectatee.weapons;
2080         self.switchweapon = spectatee.switchweapon;
2081         self.weapon = spectatee.weapon;
2082         self.punchangle = spectatee.punchangle;
2083         self.view_ofs = spectatee.view_ofs;
2084         self.v_angle = spectatee.v_angle;
2085         self.velocity = spectatee.velocity;
2086         self.dmg_take = spectatee.dmg_take;
2087         self.dmg_save = spectatee.dmg_save;
2088         self.dmg_inflictor = spectatee.dmg_inflictor;
2089         self.angles = spectatee.v_angle;
2090         self.fixangle = TRUE;
2091         setorigin(self, spectatee.origin);
2092         setsize(self, spectatee.mins, spectatee.maxs);
2093         SetZoomState(spectatee.zoomstate);
2094 }
2095
2096 float SpectateUpdate() {
2097         if(!self.enemy)
2098                 return 0;
2099
2100         if (self == self.enemy)
2101                 return 0;
2102
2103         if(self.enemy.classname != "player")
2104                 return 0;
2105
2106         SpectateCopy(self.enemy);
2107
2108         return 1;
2109 }
2110
2111 float SpectateNext() {
2112         other = find(self.enemy, classname, "player");
2113
2114         if (!other)
2115                 other = find(other, classname, "player");
2116
2117         if (other)
2118                 self.enemy = other;
2119
2120         if(self.enemy.classname == "player") {
2121                 msg_entity = self;
2122                 WriteByte(MSG_ONE, SVC_SETVIEW);
2123                 WriteEntity(MSG_ONE, self.enemy);
2124                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
2125                 self.movetype = MOVETYPE_NONE;
2126
2127                 self.enemy.weapon_count = 0;
2128
2129                 if(!SpectateUpdate())
2130                         PutObserverInServer();
2131
2132                 return 1;
2133         } else {
2134                 return 0;
2135         }
2136 }
2137
2138 /*
2139 =============
2140 ShowRespawnCountdown()
2141
2142 Update a respawn countdown display.
2143 =============
2144 */
2145 void ShowRespawnCountdown()
2146 {
2147         float number;
2148         if(self.deadflag == DEAD_NO) // just respawned?
2149                 return;
2150         else
2151         {
2152                 number = ceil(self.death_time - time);
2153                 if(number <= 0)
2154                         return;
2155                 if(number <= self.respawn_countdown)
2156                 {
2157                         self.respawn_countdown = number - 1;
2158                         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
2159                                 announce(self, strcat("announcer/robotic/", ftos(number), ".wav"));
2160                 }
2161         }
2162 }
2163
2164 void LeaveSpectatorMode()
2165 {
2166         if(isJoinAllowed()) {
2167                 if(!teams_matter || cvar("g_campaign") || cvar("g_balance_teams") || (self.wasplayer && cvar("g_changeteam_banned"))) {
2168                         self.classname = "player";
2169
2170                         if(cvar("g_campaign") || cvar("g_balance_teams") || cvar("g_balance_teams_force"))
2171                                 JoinBestTeam(self, FALSE, TRUE);
2172
2173                         if(cvar("g_campaign"))
2174                                 campaign_bots_may_start = 1;
2175
2176                         self.stat_count = WEP_LAST;
2177
2178                         PutClientInServer();
2179
2180                         if(self.classname == "player")
2181                                 bprint ("^4", self.netname, "^4 is playing now\n");
2182
2183                         if(!cvar("g_campaign"))
2184                                 centerprint(self,""); // clear MOTD
2185
2186                         return;
2187                 } else {
2188                         if (g_ca && self.caplayer) {
2189                         }       // do nothing
2190                         else
2191                                 stuffcmd(self,"menu_showteamselect\n");
2192                         return;
2193                 }
2194         }
2195         else {
2196                 //player may not join because of g_maxplayers is set
2197                 centerprint_atprio(self, CENTERPRIO_MAPVOTE, PREVENT_JOIN_TEXT);
2198         }
2199 }
2200
2201 /**
2202  * Determines whether the player is allowed to join. This depends on cvar
2203  * g_maxplayers, if it isn't used this function always return TRUE, otherwise
2204  * it checks whether the number of currently playing players exceeds g_maxplayers.
2205  * @return bool TRUE if the player is allowed to join, false otherwise
2206  */
2207 float isJoinAllowed() {
2208         if (!cvar("g_maxplayers"))
2209                 return TRUE;
2210
2211         local entity e;
2212         local float currentlyPlaying;
2213         FOR_EACH_REALPLAYER(e) {
2214                 if(e.classname == "player")
2215                         currentlyPlaying += 1;
2216         }
2217         if(currentlyPlaying < cvar("g_maxplayers"))
2218                 return TRUE;
2219
2220         return FALSE;
2221 }
2222
2223 /**
2224  * Checks whether the client is an observer or spectator, if so, he will get kicked after
2225  * g_maxplayers_spectator_blocktime seconds
2226  */
2227 void checkSpectatorBlock() {
2228         if(self.classname == "spectator" || self.classname == "observer") {
2229                 if( time > (self.spectatortime + cvar("g_maxplayers_spectator_blocktime")) ) {
2230                         sprint(self, "^7You were kicked from the server because you are spectator and spectators aren't allowed at the moment.\n");
2231                         dropclient(self);
2232                 }
2233         }
2234 }
2235
2236 float vercmp_recursive(string v1, string v2)
2237 {
2238         float dot1, dot2;
2239         string s1, s2;
2240         float r;
2241
2242         dot1 = strstrofs(v1, ".", 0);
2243         dot2 = strstrofs(v2, ".", 0);
2244         if(dot1 == -1)
2245                 s1 = v1;
2246         else
2247                 s1 = substring(v1, 0, dot1);
2248         if(dot2 == -1)
2249                 s2 = v2;
2250         else
2251                 s2 = substring(v2, 0, dot2);
2252
2253         r = stof(s1) - stof(s2);
2254         if(r != 0)
2255                 return r;
2256
2257         r = strcasecmp(s1, s2);
2258         if(r != 0)
2259                 return r;
2260
2261         if(dot1 == -1)
2262                 if(dot2 == -1)
2263                         return 0;
2264                 else
2265                         return -1;
2266         else
2267                 if(dot2 == -1)
2268                         return 1;
2269                 else
2270                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
2271 }
2272
2273 float vercmp(string v1, string v2)
2274 {
2275         if(strcasecmp(v1, v2) == 0) // early out check
2276                 return 0;
2277         return vercmp_recursive(v1, v2);
2278 }
2279
2280 void ObserverThink()
2281 {
2282         if (self.flags & FL_JUMPRELEASED) {
2283                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2284                         self.welcomemessage_time = 0;
2285                         self.flags &~= FL_JUMPRELEASED;
2286                         self.flags |= FL_SPAWNING;
2287                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
2288                         self.welcomemessage_time = 0;
2289                         self.flags &~= FL_JUMPRELEASED;
2290                         if(SpectateNext() == 1) {
2291                                 self.classname = "spectator";
2292                         }
2293                 }
2294         } else {
2295                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
2296                         self.flags |= FL_JUMPRELEASED;
2297                         if(self.flags & FL_SPAWNING)
2298                         {
2299                                 self.flags &~= FL_SPAWNING;
2300                                 LeaveSpectatorMode();
2301                                 return;
2302                         }
2303                 }
2304         }
2305         PrintWelcomeMessage(self);
2306 }
2307
2308 void SpectatorThink()
2309 {
2310         if (self.flags & FL_JUMPRELEASED) {
2311                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2312                         self.welcomemessage_time = 0;
2313                         self.flags &~= FL_JUMPRELEASED;
2314                         self.flags |= FL_SPAWNING;
2315                 } else if(self.BUTTON_ATCK) {
2316                         self.welcomemessage_time = 0;
2317                         self.flags &~= FL_JUMPRELEASED;
2318                         if(SpectateNext() == 1) {
2319                                 self.classname = "spectator";
2320                         } else {
2321                                 self.classname = "observer";
2322                                 self.stat_count = WEP_LAST;
2323                                 PutClientInServer();
2324                         }
2325                 } else if (self.BUTTON_ATCK2) {
2326                         self.welcomemessage_time = 0;
2327                         self.flags &~= FL_JUMPRELEASED;
2328                         self.classname = "observer";
2329                         self.stat_count = WEP_LAST;
2330                         PutClientInServer();
2331                 } else {
2332                         if(!SpectateUpdate())
2333                                 PutObserverInServer();
2334                 }
2335         } else {
2336                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
2337                         self.flags |= FL_JUMPRELEASED;
2338                         if(self.flags & FL_SPAWNING)
2339                         {
2340                                 self.flags &~= FL_SPAWNING;
2341                                 LeaveSpectatorMode();
2342                                 return;
2343                         }
2344                 }
2345         }
2346
2347         PrintWelcomeMessage(self);
2348         self.flags |= FL_CLIENT | FL_NOTARGET;
2349 }
2350
2351 .float touchexplode_time;
2352
2353 /*
2354 =============
2355 PlayerPreThink
2356
2357 Called every frame for each client before the physics are run
2358 =============
2359 */
2360 void() ctf_setstatus;
2361 void() nexball_setstatus;
2362 .float items_added;
2363 void PlayerPreThink (void)
2364 {
2365         self.stat_game_starttime = game_starttime;
2366         self.stat_allow_oldnexbeam = cvar("g_allow_oldnexbeam");
2367         self.stat_leadlimit = cvar("leadlimit");
2368
2369         if(blockSpectators && frametime)
2370                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2371                 checkSpectatorBlock();
2372
2373         zoomstate_set = 0;
2374
2375         if(self.netname_previous != self.netname)
2376         {
2377                 if(cvar("sv_eventlog"))
2378                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname));
2379                 if(self.netname_previous)
2380                         strunzone(self.netname_previous);
2381                 self.netname_previous = strzone(self.netname);
2382         }
2383
2384         // version nagging
2385         if(self.version_nagtime)
2386                 if(self.cvar_g_nexuizversion)
2387                         if(time > self.version_nagtime)
2388                         {
2389                                 if(strstr(self.cvar_g_nexuizversion, "svn", 0) < 0)
2390                                 {
2391                                         if(strstr(cvar_string("g_nexuizversion"), "svn", 0) >= 0)
2392                                         {
2393                                                 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");
2394                                                 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"));
2395                                         }
2396                                         else
2397                                         {
2398                                                 float r;
2399                                                 r = vercmp(self.cvar_g_nexuizversion, cvar_string("g_nexuizversion"));
2400                                                 if(r < 0)
2401                                                 {
2402                                                         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");
2403                                                         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"));
2404                                                 }
2405                                                 else if(r > 0)
2406                                                 {
2407                                                         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");
2408                                                         sprint(self, strcat("\{1}^1NOTE: ^7the server is running ^3Nexuiz ", cvar_string("g_nexuizversion"), "^7, you have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1\n"));
2409                                                 }
2410                                         }
2411                                 }
2412                                 self.version_nagtime = 0;
2413                         }
2414
2415         // GOD MODE info
2416         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
2417         {
2418                 sprint(self, strcat("godmode saved you ", ftos(self.max_armorvalue), " units of damage, cheater!\n"));
2419                 self.max_armorvalue = 0;
2420         }
2421
2422 #ifdef TETRIS
2423         if (TetrisPreFrame())
2424                 return;
2425 #endif
2426
2427         if(self.classname == "player") {
2428 //              if(self.netname == "Wazat")
2429 //                      bprint(self.classname, "\n");
2430
2431                 CheckRules_Player();
2432
2433                 PrintWelcomeMessage(self);
2434
2435                 if (intermission_running)
2436                 {
2437                         IntermissionThink ();   // otherwise a button could be missed between
2438                         return;                                 // the think tics
2439                 }
2440
2441                 if(self.teleport_time)
2442                 if(time > self.teleport_time)
2443                 {
2444                         self.teleport_time = 0;
2445                         self.effects = self.effects - (self.effects & EF_NODRAW);
2446                 }
2447
2448                 Nixnex_GiveCurrentWeapon();
2449
2450                 if(frametime > 0) // don't do this in cl_movement frames, just in server ticks
2451                         UpdateSelectedPlayer();
2452
2453                 //don't allow the player to turn around while game is paused!
2454                 if(timeoutStatus == 2) {
2455                         self.v_angle = self.lastV_angle;
2456                         self.angles = self.lastV_angle;
2457                         self.fixangle = TRUE;
2458                 }
2459
2460                 if(frametime)
2461                 {
2462                         if(cvar("gameversion") >= 20600) // only do this for 2.6 and above FIXME remove this check when making 2.6
2463                                 self.glowmod = colormapPaletteColor(self.clientcolors & 0x0F, TRUE) * 2;
2464                         player_powerups();
2465                 }
2466
2467                 if (self.deadflag != DEAD_NO)
2468                 {
2469                         float button_pressed, force_respawn;
2470                         if(self.personal && g_race_qualifying)
2471                         {
2472                                 if(time > self.death_time)
2473                                 {
2474                                         self.death_time = time + 1; // only retry once a second
2475                                         respawn();
2476                                         self.impulse = 141;
2477                                 }
2478                         }
2479                         else
2480                         {
2481                                 if(frametime)
2482                                         player_anim();
2483                                 button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2484                                 force_respawn = (g_lms || (g_ca) || cvar("g_forced_respawn"));
2485                                 if (self.deadflag == DEAD_DYING)
2486                                 {
2487                                         if(force_respawn)
2488                                                 self.deadflag = DEAD_RESPAWNING;
2489                                         else if(!button_pressed)
2490                                                 self.deadflag = DEAD_DEAD;
2491                                 }
2492                                 else if (self.deadflag == DEAD_DEAD)
2493                                 {
2494                                         if(button_pressed)
2495                                                 self.deadflag = DEAD_RESPAWNABLE;
2496                                 }
2497                                 else if (self.deadflag == DEAD_RESPAWNABLE)
2498                                 {
2499                                         if(!button_pressed)
2500                                                 self.deadflag = DEAD_RESPAWNING;
2501                                 }
2502                                 else if (self.deadflag == DEAD_RESPAWNING)
2503                                 {
2504                                         if(time > self.death_time)
2505                                         {
2506                                                 self.death_time = time + 1; // only retry once a second
2507                                                 respawn();
2508                                         }
2509                                 }
2510                                 ShowRespawnCountdown();
2511                         }
2512                         return;
2513                 }
2514
2515                 if(g_touchexplode)
2516                 if(time > self.touchexplode_time)
2517                 if(self.classname == "player")
2518                 if(self.deadflag == DEAD_NO)
2519                 if not(IS_INDEPENDENT_PLAYER(self))
2520                 FOR_EACH_PLAYER(other) if(self != other)
2521                 {
2522                         if(time > other.touchexplode_time)
2523                         if(other.classname == "player")
2524                         if(other.deadflag == DEAD_NO)
2525                         if not(IS_INDEPENDENT_PLAYER(other))
2526                         if(boxesoverlap(self.absmin, self.absmax, other.absmin, other.absmax))
2527                         {
2528                                 PlayerTouchExplode(self, other);
2529                                 self.touchexplode_time = other.touchexplode_time = time + 0.2;
2530                         }
2531                 }
2532
2533                 if(g_lms && !self.deadflag && cvar("g_lms_campcheck_interval"))
2534                 {
2535                         vector dist;
2536
2537                         // calculate player movement (in 2 dimensions only, so jumping on one spot doesn't count as movement)
2538                         dist = self.prevorigin - self.origin;
2539                         dist_z = 0;
2540                         self.lms_traveled_distance += fabs(vlen(dist));
2541
2542                         if((cvar("g_campaign") && !campaign_bots_may_start) || (time < game_starttime))
2543                         {
2544                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
2545                                 self.lms_traveled_distance = 0;
2546                         }
2547
2548                         if(time > self.lms_nextcheck)
2549                         {
2550                                 //sprint(self, "distance: ", ftos(self.lms_traveled_distance), "\n");
2551                                 if(self.lms_traveled_distance < cvar("g_lms_campcheck_distance"))
2552                                 {
2553                                         centerprint(self, cvar_string("g_lms_campcheck_message"));
2554                                         // FIXME KadaverJack: gibbing player here causes playermodel to bounce around, instead of eye.md3
2555                                         // I wasn't able to find out WHY that happens, so I put a workaround in place that shall prevent players from being gibbed :(
2556                                         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');
2557                                 }
2558                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval");
2559                                 self.lms_traveled_distance = 0;
2560                         }
2561                 }
2562
2563                 self.prevorigin = self.origin;
2564
2565                 if ((self.BUTTON_CROUCH && !self.hook.state) || self.health <= g_bloodloss)
2566                 {
2567                         if (!self.crouch)
2568                         {
2569                                 self.crouch = TRUE;
2570                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2571                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2572                                 setanim(self, self.anim_duck, FALSE, TRUE, TRUE);
2573                         }
2574                 }
2575                 else
2576                 {
2577                         if (self.crouch)
2578                         {
2579                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, FALSE, self);
2580                                 if (!trace_startsolid)
2581                                 {
2582                                         self.crouch = FALSE;
2583                                         self.view_ofs = PL_VIEW_OFS;
2584                                         setsize (self, PL_MIN, PL_MAX);
2585                                 }
2586                         }
2587                 }
2588
2589                 if(self.health <= g_bloodloss && self.deadflag == DEAD_NO)
2590                 {
2591                         if(self.bloodloss_timer < time)
2592                         {
2593                                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
2594                                 self.bloodloss_timer = time + 0.5 + random() * 0.5;
2595                         }
2596                 }
2597
2598                 FixPlayermodel();
2599
2600                 GrapplingHookFrame();
2601
2602                 // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
2603                 //if(frametime)
2604                 {
2605                         self.items &~= self.items_added;
2606
2607                         W_WeaponFrame();
2608
2609                         self.items_added = 0;
2610                         if(self.items & IT_JETPACK)
2611                                 if(self.items & IT_FUEL_REGEN || self.ammo_fuel >= 0.01)
2612                                         self.items_added |= IT_FUEL;
2613
2614                         self.items |= self.items_added;
2615                 }
2616
2617                 player_regen();
2618                 if(frametime)
2619                         player_anim();
2620
2621                 if (g_minstagib)
2622                         minstagib_ammocheck();
2623
2624                 ctf_setstatus();
2625                 nexball_setstatus();
2626
2627                 self.dmg_team = max(0, self.dmg_team - cvar("g_teamdamage_resetspeed") * frametime);
2628
2629                 //self.angles_y=self.v_angle_y + 90;   // temp
2630         } else if(gameover) {
2631                 if (intermission_running)
2632                         IntermissionThink ();   // otherwise a button could be missed between
2633                 return;
2634         } else if(self.classname == "observer") {
2635                 ObserverThink();
2636         } else if(self.classname == "spectator") {
2637                 SpectatorThink();
2638         }
2639
2640         if(!zoomstate_set)
2641                 SetZoomState(self.BUTTON_ZOOM || (self.BUTTON_ATCK2 && self.weapon == WEP_NEX));
2642
2643         float oldspectatee_status;
2644         oldspectatee_status = self.spectatee_status;
2645         if(self.classname == "spectator")
2646                 self.spectatee_status = num_for_edict(self.enemy);
2647         else if(self.classname == "observer")
2648                 self.spectatee_status = num_for_edict(self);
2649         else
2650                 self.spectatee_status = 0;
2651         if(self.spectatee_status != oldspectatee_status)
2652         {
2653                 ClientData_Touch(self);
2654                 if(g_race || g_cts)
2655                         race_InitSpectator();
2656         }
2657
2658         if(self.teamkill_soundtime)
2659         if(time > self.teamkill_soundtime)
2660         {
2661                 self.teamkill_soundtime = 0;
2662
2663                 entity oldpusher, oldself;
2664
2665                 oldself = self; self = self.teamkill_soundsource;
2666                 oldpusher = self.pusher; self.pusher = oldself;
2667
2668                 PlayerSound(playersound_teamshoot, CHAN_VOICE, VOICETYPE_LASTATTACKER_ONLY);
2669
2670                 self.pusher = oldpusher;
2671                 self = oldself;
2672         }
2673
2674         if(self.taunt_soundtime)
2675         if(time > self.taunt_soundtime)
2676         {
2677                 self.taunt_soundtime = 0;
2678                 PlayerSound(playersound_taunt, CHAN_VOICE, VOICETYPE_AUTOTAUNT);
2679         }
2680
2681         target_voicescript_next(self);
2682 }
2683
2684 // on dragger:
2685 .entity dragentity;
2686 .float draggravity;
2687 .float dragspeed; // speed of mouse wheel action
2688 .float dragdistance; // distance of dragentity's draglocalvector from view_ofs
2689 .vector draglocalvector; // local attachment vector of the dragentity
2690 .float draglocalangle;
2691 // on draggee:
2692 .entity draggedby;
2693 .float dragmovetype;
2694 void Drag_Begin(entity dragger, entity draggee, vector touchpoint)
2695 {
2696         float tagscale;
2697
2698         draggee.dragmovetype = draggee.movetype;
2699         draggee.draggravity = draggee.gravity;
2700         draggee.movetype = MOVETYPE_WALK;
2701         draggee.gravity = 0.00001;
2702         draggee.flags &~= FL_ONGROUND;
2703         draggee.draggedby = dragger;
2704
2705         dragger.dragentity = draggee;
2706
2707         dragger.dragdistance = vlen(touchpoint - dragger.origin - dragger.view_ofs);
2708         dragger.draglocalangle = draggee.angles_y - dragger.v_angle_y;
2709         touchpoint = touchpoint - gettaginfo(draggee, 0);
2710         tagscale = pow(vlen(v_forward), -2);
2711         dragger.draglocalvector_x = touchpoint * v_forward * tagscale;
2712         dragger.draglocalvector_y = touchpoint * v_right * tagscale;
2713         dragger.draglocalvector_z = touchpoint * v_up * tagscale;
2714
2715         dragger.dragspeed = 64;
2716 }
2717
2718 void Drag_Finish(entity dragger)
2719 {
2720         entity draggee;
2721         draggee = dragger.dragentity;
2722         if(dragger)
2723                 dragger.dragentity = world;
2724         draggee.draggedby = world;
2725         draggee.movetype = draggee.dragmovetype;
2726         draggee.gravity = draggee.draggravity;
2727
2728         switch(draggee.movetype)
2729         {
2730                 case MOVETYPE_TOSS:
2731                 case MOVETYPE_WALK:
2732                 case MOVETYPE_STEP:
2733                 case MOVETYPE_FLYMISSILE:
2734                 case MOVETYPE_BOUNCE:
2735                 case MOVETYPE_BOUNCEMISSILE:
2736                 case MOVETYPE_PHYSICS:
2737                         break;
2738                 default:
2739                         draggee.velocity = '0 0 0';
2740                         break;
2741         }
2742
2743         if((draggee.flags & FL_ITEM) && (vlen(draggee.velocity) < 32))
2744         {
2745                 draggee.velocity = '0 0 0';
2746                 draggee.flags |= FL_ONGROUND; // floating items are FUN
2747         }
2748 }
2749
2750 float Drag_IsDraggable(entity draggee)
2751 {
2752         // TODO add more checks for bad stuff here
2753         if(draggee.classname == "func_bobbing")
2754                 return FALSE;
2755         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)
2756                 return FALSE;
2757         if(draggee.classname == "plat")
2758                 return FALSE;
2759         if(draggee.classname == "func_button")
2760                 return FALSE;
2761         if(draggee.model == "")
2762                 return FALSE;
2763         if(draggee.classname == "spectator")
2764                 return FALSE;
2765         if(draggee.classname == "observer")
2766                 return FALSE;
2767         if(draggee.classname == "exteriorweaponentity")
2768                 return FALSE;
2769
2770         return TRUE;
2771 }
2772
2773 float Drag_MayChangeAngles(entity draggee)
2774 {
2775         // TODO add more checks for bad stuff here
2776         if(substring(draggee.model, 0, 1) == "*")
2777                 return FALSE;
2778         return TRUE;
2779 }
2780
2781 void Drag_MoveForward(entity dragger)
2782 {
2783         dragger.dragdistance += dragger.dragspeed;
2784 }
2785
2786 void Drag_SetSpeed(entity dragger, float s)
2787 {
2788         dragger.dragspeed = pow(2, s);
2789 }
2790
2791 void Drag_MoveBackward(entity dragger)
2792 {
2793         dragger.dragdistance = max(0, dragger.dragdistance - dragger.dragspeed);
2794 }
2795
2796 void Drag_Update(entity dragger)
2797 {
2798         vector curorigin, neworigin, goodvelocity;
2799         float f;
2800         entity draggee;
2801
2802         draggee = dragger.dragentity;
2803         draggee.flags &~= FL_ONGROUND;
2804
2805         curorigin = gettaginfo(draggee, 0);
2806         curorigin = curorigin + v_forward * dragger.draglocalvector_x + v_right * dragger.draglocalvector_y + v_up * dragger.draglocalvector_z;
2807         makevectors(dragger.v_angle);
2808         neworigin = dragger.origin + dragger.view_ofs + v_forward * dragger.dragdistance;
2809         goodvelocity = (neworigin - curorigin) * (1 / frametime);
2810
2811         while(draggee.angles_y - dragger.v_angle_y - dragger.draglocalangle > 180)
2812                 dragger.draglocalangle += 360;
2813         while(draggee.angles_y - dragger.v_angle_y - dragger.draglocalangle <= -180)
2814                 dragger.draglocalangle -= 360;
2815
2816         f = min(frametime * 10, 1);
2817         draggee.velocity = draggee.velocity * (1 - f) + goodvelocity * f;
2818
2819         if(Drag_MayChangeAngles(draggee))
2820                 draggee.angles_y = draggee.angles_y * (1 - f) + (dragger.v_angle_y + dragger.draglocalangle) * f;
2821
2822         draggee.ltime = max(servertime + serverframetime, draggee.ltime); // fixes func_train breakage
2823
2824         te_lightning1(dragger, dragger.origin + dragger.view_ofs, curorigin);
2825 }
2826
2827 float Drag_CanDrag(entity dragger)
2828 {
2829         return (dragger.deadflag == DEAD_NO) || (dragger.classname == "player");
2830 }
2831
2832 float Drag_IsDragging(entity dragger)
2833 {
2834         if(!dragger.dragentity)
2835                 return FALSE;
2836         if(wasfreed(dragger.dragentity) || dragger.dragentity.draggedby != dragger)
2837         {
2838                 dragger.dragentity = world;
2839                 return FALSE;
2840         }
2841         if(!Drag_CanDrag(dragger) || !Drag_IsDraggable(dragger.dragentity))
2842         {
2843                 Drag_Finish(dragger);
2844                 return FALSE;
2845         }
2846         return TRUE;
2847 }
2848
2849 void Drag_MoveDrag(entity from, entity to)
2850 {
2851         if(from.draggedby)
2852         {
2853                 to.draggedby = from.draggedby;
2854                 to.draggedby.dragentity = to;
2855                 from.draggedby = world;
2856         }
2857 }
2858
2859 /*
2860 =============
2861 PlayerPostThink
2862
2863 Called every frame for each client after the physics are run
2864 =============
2865 */
2866 .float idlekick_lasttimeleft;
2867 void PlayerPostThink (void)
2868 {
2869         // Savage: Check for nameless players
2870         if (strlen(self.netname) < 1) {
2871                 self.netname = "Player";
2872                 stuffcmd(self, "seta _cl_name Player\n");
2873         }
2874
2875         // send the clients accuracy stats to the client
2876         if(self.stat_count > 0)
2877         if(frametime)
2878         {
2879                 self.stat_hit = self.stat_count + 64 * floor(self.(stats_hit[self.stat_count - 1]));
2880                 self.stat_fired = self.stat_count + 64 * floor(self.(stats_fired[self.stat_count - 1]));
2881                 self.stat_count -= 1;
2882         }
2883
2884         if(sv_maxidle && frametime)
2885         {
2886                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2887                 float timeleft;
2888                 timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
2889                 if(timeleft <= 0)
2890                 {
2891                         bprint("^3", self.netname, "^3 was kicked for idling.\n");
2892                         announce(self, "announcer/robotic/terminated.wav");
2893                         dropclient(self);
2894                         return;
2895                 }
2896                 else if(timeleft <= 10)
2897                 {
2898                         if(timeleft != self.idlekick_lasttimeleft)
2899                         {
2900                                 centerprint_atprio(self, CENTERPRIO_IDLEKICK, strcat("^3Stop idling!\n^3Disconnecting in ", ftos(timeleft), "..."));
2901                                 announce(self, strcat("announcer/robotic/", ftos(timeleft), ".wav"));
2902                         }
2903                 }
2904                 else
2905                 {
2906                         centerprint_expire(self, CENTERPRIO_IDLEKICK);
2907                 }
2908                 self.idlekick_lasttimeleft = timeleft;
2909         }
2910
2911 #ifdef TETRIS
2912         if(self.impulse == 100)
2913                 ImpulseCommands();
2914         if (TetrisPostFrame())
2915                 return;
2916 #endif
2917
2918         if(sv_cheats || self.maycheat)
2919                 if(Drag_CanDrag(self))
2920                         if(self.BUTTON_DRAG)
2921                                 if(!self.dragentity)
2922                                         if(self.cursor_trace_ent)
2923                                                 if(Drag_IsDraggable(self.cursor_trace_ent))
2924                                                 {
2925                                                         if(self.cursor_trace_ent.draggedby)
2926                                                                 Drag_Finish(self.cursor_trace_ent.draggedby);
2927                                                         if(self.cursor_trace_ent.tag_entity)
2928                                                                 detach_sameorigin(self.cursor_trace_ent);
2929                                                         Drag_Begin(self, self.cursor_trace_ent, self.cursor_trace_endpos);
2930                                                 }
2931
2932         if(Drag_IsDragging(self))
2933         {
2934                 if(self.BUTTON_DRAG)
2935                 {
2936                         if(self.impulse == 10 || self.impulse == 15 || self.impulse == 18)
2937                         {
2938                                 Drag_MoveForward(self);
2939                                 self.impulse = 0;
2940                         }
2941                         else if(self.impulse == 12 || self.impulse == 16 || self.impulse == 19)
2942                         {
2943                                 Drag_MoveBackward(self);
2944                                 self.impulse = 0;
2945                         }
2946                         else if(self.impulse >= 1 && self.impulse <= 9)
2947                         {
2948                                 Drag_SetSpeed(self, self.impulse - 1);
2949                         }
2950                         else if(self.impulse == 14)
2951                         {
2952                                 Drag_SetSpeed(self, 9);
2953                         }
2954
2955                         if(frametime)
2956                                 Drag_Update(self);
2957                 }
2958                 else
2959                 {
2960                         Drag_Finish(self);
2961                 }
2962         }
2963
2964         if(self.classname == "player") {
2965                 CheckRules_Player();
2966                 UpdateChatBubble();
2967                 UpdateTeamBubble();
2968                 if (self.impulse)
2969                         ImpulseCommands();
2970                 if (intermission_running)
2971                         return;         // intermission or finale
2972
2973                 GetPressedKeys();
2974         } else if (self.classname == "observer") {
2975                 //do nothing
2976         } else if (self.classname == "spectator") {
2977                 //do nothing
2978         }
2979
2980         /*
2981         float i;
2982         for(i = 0; i < 1000; ++i)
2983         {
2984                 vector end;
2985                 end = self.origin + '0 0 1024' + 512 * randomvec();
2986                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
2987                 if(trace_fraction < 1)
2988                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
2989                 {
2990                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
2991                         break;
2992                 }
2993         }
2994         */
2995
2996         Arena_Warmup();
2997
2998         //pointparticles(particleeffectnum("machinegun_impact"), self.origin + self.view_ofs + '0 0 7', '0 0 0', 1);
2999
3000         if(self.waypointsprite_attachedforcarrier)
3001                 WaypointSprite_UpdateHealth(self.waypointsprite_attachedforcarrier, '1 0 0' * healtharmor_maxdamage(self.health, self.armorvalue, cvar("g_balance_armor_blockpercent")));
3002         
3003         playerdemo_write();
3004 }