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