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