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