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