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