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