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