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