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