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