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