]> de.git.xonotic.org Git - xonotic/xonotic-data.pk3dir.git/blob - qcsrc/server/cl_client.qc
Merge branch 'master' into mirceakitsune/sandbox
[xonotic/xonotic-data.pk3dir.git] / qcsrc / server / cl_client.qc
1 void race_send_recordtime(float msg);
2 void race_SendRankings(float pos, float prevpos, float del, float msg);
3
4 void send_CSQC_teamnagger() {
5         WriteByte(MSG_BROADCAST, SVC_TEMPENTITY);
6         WriteByte(MSG_BROADCAST, TE_CSQC_TEAMNAGGER);
7 }
8
9 void Announce(string snd) {
10         WriteByte(MSG_ALL, SVC_TEMPENTITY);
11         WriteByte(MSG_ALL, TE_CSQC_ANNOUNCE);
12         WriteString(MSG_ALL, snd);
13 }
14
15 void AnnounceTo(entity e, string snd) {
16         if (clienttype(e) == CLIENTTYPE_REAL)
17         {
18                 msg_entity = e;
19                 WriteByte(MSG_ONE, SVC_TEMPENTITY);
20                 WriteByte(MSG_ONE, TE_CSQC_ANNOUNCE);
21                 WriteString(MSG_ONE, snd);
22         }
23 }
24
25 float ClientData_Send(entity to, float sf)
26 {
27         if(to != self.owner)
28         {
29                 error("wtf");
30                 return FALSE;
31         }
32
33         entity e;
34
35         e = to;
36         if(to.classname == "spectator")
37                 e = to.enemy;
38
39         sf = 0;
40
41         if(e.race_completed)
42                 sf |= 1; // forced scoreboard
43         if(to.spectatee_status)
44                 sf |= 2; // spectator ent number follows
45         if(e.zoomstate)
46                 sf |= 4; // zoomed
47         if(e.porto_v_angle_held)
48                 sf |= 8; // angles held
49
50         WriteByte(MSG_ENTITY, ENT_CLIENT_CLIENTDATA);
51         WriteByte(MSG_ENTITY, sf);
52
53         if(sf & 2)
54                 WriteByte(MSG_ENTITY, to.spectatee_status);
55
56         if(sf & 8)
57         {
58                 WriteAngle(MSG_ENTITY, e.v_angle_x);
59                 WriteAngle(MSG_ENTITY, e.v_angle_y);
60         }
61
62         return TRUE;
63 }
64
65 void ClientData_Attach()
66 {
67         Net_LinkEntity(self.clientdata = spawn(), FALSE, 0, ClientData_Send);
68         self.clientdata.drawonlytoclient = self;
69         self.clientdata.owner = self;
70 }
71
72 void ClientData_Detach()
73 {
74         remove(self.clientdata);
75         self.clientdata = world;
76 }
77
78 void ClientData_Touch(entity e)
79 {
80         e.clientdata.SendFlags = 1;
81
82         // make it spectatable
83         entity e2;
84         FOR_EACH_REALCLIENT(e2)
85         {
86                 if(e2 != e)
87                         if(e2.classname == "spectator")
88                                 if(e2.enemy == e)
89                                         e2.clientdata.SendFlags = 1;
90         }
91 }
92
93
94 .vector spawnpoint_score;
95 .string netname_previous;
96
97 void spawnfunc_info_player_survivor (void)
98 {
99         spawnfunc_info_player_deathmatch();
100 }
101
102 void spawnfunc_info_player_start (void)
103 {
104         spawnfunc_info_player_deathmatch();
105 }
106
107 void spawnfunc_info_player_deathmatch (void)
108 {
109         self.classname = "info_player_deathmatch";
110         relocate_spawnpoint();
111 }
112
113 void spawnpoint_use()
114 {
115         if(teamplay)
116         if(have_team_spawns > 0)
117         {
118                 self.team = activator.team;
119                 some_spawn_has_been_used = 1;
120         }
121 }
122
123 // Returns:
124 //   _x: prio (-1 if unusable)
125 //   _y: weight
126 vector Spawn_Score(entity spot, entity playerlist, float teamcheck, float anypoint)
127 {
128         float shortest, thisdist;
129         float prio;
130         entity player;
131
132         prio = 0;
133
134         // filter out spots for the wrong team
135         if(teamcheck >= 0)
136                 if(spot.team != teamcheck)
137                         return '-1 0 0';
138
139         if(race_spawns)
140                 if(spot.target == "")
141                         return '-1 0 0';
142
143         if(clienttype(self) == CLIENTTYPE_REAL)
144         {
145                 if(spot.restriction == 1)
146                         return '-1 0 0';
147         }
148         else
149         {
150                 if(spot.restriction == 2)
151                         return '-1 0 0';
152         }
153
154         // filter out spots for assault
155         if(spot.target != "") {
156                 entity ent;
157                 float good, found;
158
159                 found = 0;
160                 good = 0;
161                 for(ent = world; (ent = find(ent, targetname, spot.target)); )
162                 {
163                         ++found;
164                         if(ent.classname == "target_objective")
165                         {
166                                 if(ent.health < 0 || ent.health >= ASSAULT_VALUE_INACTIVE)
167                                         continue;
168                         }
169                         else if(ent.classname == "trigger_race_checkpoint")
170                         {
171                                 if(!anypoint) // spectators may spawn everywhere
172                                 {
173                                         if(g_race_qualifying)
174                                         {
175                                                 // spawn at first
176                                                 if(ent.race_checkpoint != 0)
177                                                         continue;
178                                                 if(spot.race_place != race_lowest_place_spawn)
179                                                         continue;
180                                         }
181                                         else
182                                         {
183                                                 if(ent.race_checkpoint != self.race_respawn_checkpoint)
184                                                         continue;
185                                                 // try reusing the previous spawn
186                                                 if(ent == self.race_respawn_spotref || spot == self.race_respawn_spotref)
187                                                         prio += 1;
188                                                 if(ent.race_checkpoint == 0)
189                                                 {
190                                                         float pl;
191                                                         pl = self.race_place;
192                                                         if(pl > race_highest_place_spawn)
193                                                                 pl = 0;
194                                                         if(pl == 0 && !self.race_started)
195                                                                 pl = race_highest_place_spawn; // use last place if he has not even touched finish yet
196                                                         if(spot.race_place != pl)
197                                                                 continue;
198                                                 }
199                                         }
200                                 }
201                         }
202                         ++good;
203                 }
204
205                 if(!found)
206                 {
207                         dprint("WARNING: spawnpoint at ", vtos(spot.origin), " could not find its target ", spot.target, "\n");
208                         return '-1 0 0';
209                 }
210
211                 if(good < found) // at least one was bad
212                         return '-1 0 0';
213         }
214
215         player = playerlist;
216         shortest = vlen(world.maxs - world.mins);
217         for(player = playerlist; player; player = player.chain)
218                 if (player != self)
219                 {
220                         thisdist = vlen(player.origin - spot.origin);
221                         if (thisdist < shortest)
222                                 shortest = thisdist;
223                 }
224         return prio * '1 0 0' + shortest * '0 1 0';
225 }
226
227 float spawn_allbad;
228 float spawn_allgood;
229 entity Spawn_FilterOutBadSpots(entity firstspot, entity playerlist, float mindist, float teamcheck, float anypoint)
230 {
231         entity spot, spotlist, spotlistend;
232         spawn_allgood = TRUE;
233         spawn_allbad = TRUE;
234
235         spotlist = world;
236         spotlistend = world;
237
238         for(spot = firstspot; spot; spot = spot.chain)
239         {
240                 spot.spawnpoint_score = Spawn_Score(spot, playerlist, teamcheck, anypoint);
241
242                 if(autocvar_spawn_debugview)
243                 {
244                         setmodel(spot, "models/runematch/rune.mdl");
245                         if(spot.spawnpoint_score_y < mindist)
246                         {
247                                 spot.colormod = '1 0 0';
248                                 spot.scale = 1;
249                         }
250                         else
251                         {
252                                 spot.colormod = '0 1 0';
253                                 spot.scale = spot.spawnpoint_score_y / mindist;
254                         }
255                 }
256
257                 if(spot.spawnpoint_score_x >= 0) // spawning allowed here
258                 {
259                         if(spot.spawnpoint_score_y < mindist)
260                         {
261                                 // too short distance
262                                 spawn_allgood = FALSE;
263                         }
264                         else
265                         {
266                                 // perfect
267                                 spawn_allbad = FALSE;
268
269                                 if(spotlistend)
270                                         spotlistend.chain = spot;
271                                 spotlistend = spot;
272                                 if(!spotlist)
273                                         spotlist = spot;
274
275                                 /*
276                                 if(teamcheck >= 0)
277                                 if(spot.team != teamcheck)
278                                         error("invalid spawn added");
279
280                                 print("added ", etos(spot), "\n");
281                                 */
282                         }
283                 }
284         }
285         if(spotlistend)
286                 spotlistend.chain = world;
287
288         /*
289                 entity e;
290                 if(teamcheck >= 0)
291                         for(e = spotlist; e; e = e.chain)
292                         {
293                                 print("seen ", etos(e), "\n");
294                                 if(e.team != teamcheck)
295                                         error("invalid spawn found");
296                         }
297         */
298
299         return spotlist;
300 }
301
302 entity Spawn_WeightedPoint(entity firstspot, float lower, float upper, float exponent)
303 {
304         // weight of a point: bound(lower, mindisttoplayer, upper)^exponent
305         // multiplied by spot.cnt (useful if you distribute many spawnpoints in a small area)
306         entity spot;
307
308         RandomSelection_Init();
309         for(spot = firstspot; spot; spot = spot.chain)
310                 RandomSelection_Add(spot, 0, string_null, pow(bound(lower, spot.spawnpoint_score_y, upper), exponent) * spot.cnt, (spot.spawnpoint_score_y >= lower) * 0.5 + spot.spawnpoint_score_x);
311
312         return RandomSelection_chosen_ent;
313 }
314
315 /*
316 =============
317 SelectSpawnPoint
318
319 Finds a point to respawn
320 =============
321 */
322 entity SelectSpawnPoint (float anypoint)
323 {
324         float teamcheck;
325         entity firstspot_new;
326         entity spot, firstspot, playerlist;
327
328         spot = find (world, classname, "testplayerstart");
329         if (spot)
330                 return spot;
331
332         if(anypoint || autocvar_g_spawn_useallspawns)
333                 teamcheck = -1;
334         else if(have_team_spawns > 0)
335         {
336                 if(have_team_spawns_forteam[self.team] == 0)
337                 {
338                         // we request a spawn for a team, and we have team
339                         // spawns, but that team has no spawns?
340                         if(have_team_spawns_forteam[0])
341                                 // try noteam spawns
342                                 teamcheck = 0;
343                         else
344                                 // if not, any spawn has to do
345                                 teamcheck = -1;
346                 }
347                 else
348                         teamcheck = self.team; // MUST be team
349         }
350         else if(have_team_spawns == 0 && have_team_spawns_forteam[0])
351                 teamcheck = 0; // MUST be noteam
352         else
353                 teamcheck = -1;
354                 // if we get here, we either require team spawns but have none, or we require non-team spawns and have none; use any spawn then
355
356
357         // get the list of players
358         playerlist = findchain(classname, "player");
359         // get the entire list of spots
360         firstspot = findchain(classname, "info_player_deathmatch");
361         // filter out the bad ones
362         // (note this returns the original list if none survived)
363         if(anypoint)
364         {
365                 spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
366         }
367         else
368         {
369                 firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, 100, teamcheck, anypoint);
370                 if(!firstspot_new)
371                         firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, -1, teamcheck, anypoint);
372                 firstspot = firstspot_new;
373
374                 // there is 50/50 chance of choosing a random spot or the furthest spot
375                 // (this means that roughly every other spawn will be furthest, so you
376                 // usually won't get fragged at spawn twice in a row)
377                 if (arena_roundbased && !g_ca)
378                 {
379                         firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, 800, teamcheck, anypoint);
380                         if(firstspot_new)
381                                 firstspot = firstspot_new;
382                         spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
383                 }
384                 else if (random() > autocvar_g_spawn_furthest)
385                         spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
386                 else
387                         spot = Spawn_WeightedPoint(firstspot, 1, 5000, 5); // chooses a far far away spawnpoint
388         }
389
390         if(autocvar_spawn_debugview)
391         {
392                 print("spot mindistance: ", vtos(spot.spawnpoint_score), "\n");
393
394                 entity e;
395                 if(teamcheck >= 0)
396                         for(e = firstspot; e; e = e.chain)
397                                 if(e.team != teamcheck)
398                                         error("invalid spawn found");
399         }
400
401         if (!spot)
402         {
403                 if(autocvar_spawn_debug)
404                         GotoNextMap();
405                 else
406                 {
407                         if(some_spawn_has_been_used)
408                                 return world; // team can't spawn any more, because of actions of other team
409                         else
410                                 error("Cannot find a spawn point - please fix the map!");
411                 }
412         }
413
414         return spot;
415 }
416
417 /*
418 =============
419 CheckPlayerModel
420
421 Checks if the argument string can be a valid playermodel.
422 Returns a valid one in doubt.
423 =============
424 */
425 string FallbackPlayerModel;
426 string CheckPlayerModel(string plyermodel) {
427         if(FallbackPlayerModel != cvar_defstring("_cl_playermodel"))
428         {
429                 // note: we cannot summon Don Strunzone here, some player may
430                 // still have the model string set. In case anyone manages how
431                 // to change a cvar default, we'll have a small leak here.
432                 FallbackPlayerModel = strzone(cvar_defstring("_cl_playermodel"));
433         }
434         if(strlen(plyermodel) < 4)
435                 return FallbackPlayerModel;
436         if( substring(plyermodel,0,14) != "models/player/")
437                 return FallbackPlayerModel;
438         else if(autocvar_sv_servermodelsonly)
439         {
440                 if(substring(plyermodel,-4,4) != ".zym")
441                 if(substring(plyermodel,-4,4) != ".dpm")
442                 if(substring(plyermodel,-4,4) != ".iqm")
443                 if(substring(plyermodel,-4,4) != ".md3")
444                 if(substring(plyermodel,-4,4) != ".psk")
445                         return FallbackPlayerModel;
446                 // forbid the LOD models
447                 if(substring(plyermodel, -9,5) == "_lod1")
448                         return FallbackPlayerModel;
449                 if(substring(plyermodel, -9,5) == "_lod2")
450                         return FallbackPlayerModel;
451                 if(plyermodel != strtolower(plyermodel))
452                         return FallbackPlayerModel;
453                 if(!fexists(plyermodel))
454                         return FallbackPlayerModel;
455         }
456         return plyermodel;
457 }
458
459 /*
460 =============
461 Client_customizeentityforclient
462
463 LOD reduction
464 =============
465 */
466 void Client_uncustomizeentityforclient()
467 {
468         if(self.modelindex == 0) // no need to uncustomize then
469                 return;
470         self.modelindex = self.modelindex_lod0;
471         self.skin = self.skinindex;
472 }
473
474 float Client_customizeentityforclient()
475 {
476         entity modelsource;
477
478         if(self.modelindex == 0)
479                 return TRUE;
480
481         // forcemodel stuff
482
483 #ifdef PROFILING
484         float t0;
485         t0 = gettime(GETTIME_HIRES); // reference
486 #endif
487
488         modelsource = self;
489
490 #ifdef ALLOW_FORCEMODELS
491         if(other.cvar_cl_forceplayermodelsfromxonotic)
492                 if not(self.modelindex_lod0_from_xonotic)
493                         modelsource = other;
494         if(other.cvar_cl_forceplayermodels && sv_clforceplayermodels)
495                 modelsource = other;
496 #endif
497
498         self.skin = modelsource.skinindex;
499
500 #if 0
501         if(modelsource == self)
502                 self.skin = modelsource.skinindex;
503         else
504                 self.skin = mod(modelsource.skinindex, 3); // forbid the fbskins as forced skins
505 #endif
506
507         // self: me
508         // other: the player viewing me
509         float distance;
510         float f;
511
512         if(other.cvar_cl_playerdetailreduction <= 0)
513         {
514                 if(other.cvar_cl_playerdetailreduction <= -2)
515                         self.modelindex = modelsource.modelindex_lod2;
516                 else if(other.cvar_cl_playerdetailreduction <= -1)
517                         self.modelindex = modelsource.modelindex_lod1;
518                 else
519                         self.modelindex = modelsource.modelindex_lod0;
520         }
521         else
522         {
523                 distance = vlen(self.origin - other.origin);
524                 f = (distance + 100.0) * other.cvar_cl_playerdetailreduction;
525                 if(f > sv_loddistance2)
526                         self.modelindex = modelsource.modelindex_lod2;
527                 else if(f > sv_loddistance1)
528                         self.modelindex = modelsource.modelindex_lod1;
529                 else
530                         self.modelindex = modelsource.modelindex_lod0;
531         }
532
533 #ifdef PROFILING
534         float t1;
535         t1 = gettime(GETTIME_HIRES); // reference
536         client_cefc_accumulator += (t1 - t0);
537 #endif
538
539         return TRUE;
540 }
541
542 void setmodel_lod(entity e, string modelname)
543 {
544         string s;
545
546         if(sv_loddistance1)
547         {
548                 // FIXME: this only supports 3-letter extensions
549                 s = strcat(substring(modelname, 0, strlen(modelname)-4), "_lod1", substring(modelname, -4, 4));
550                 if(fexists(s))
551                 {
552                         setmodel(e, s); // players have high precision
553                         self.modelindex_lod1 = self.modelindex;
554                 }
555                 else
556                         self.modelindex_lod1 = -1;
557
558                 s = strcat(substring(modelname, 0, strlen(modelname)-4), "_lod2", substring(modelname, -4, 4));
559                 if(fexists(s))
560                 {
561                         setmodel(e, s); // players have high precision
562                         self.modelindex_lod2 = self.modelindex;
563                 }
564                 else
565                         self.modelindex_lod2 = -1;
566
567                 precache_model(modelname);
568                 setmodel(e, modelname); // players have high precision
569                 self.modelindex_lod0 = self.modelindex;
570
571                 if(self.modelindex_lod1 < 0)
572                         self.modelindex_lod1 = self.modelindex;
573
574                 if(self.modelindex_lod2 < 0)
575                         self.modelindex_lod2 = self.modelindex;
576         }
577         else
578         {
579                 precache_model(modelname);
580                 setmodel(e, modelname); // players have high precision
581                 self.modelindex_lod0 = self.modelindex;
582                         // save it for possible player model forcing
583         }
584
585         s = whichpack(self.model);
586         self.modelindex_lod0_from_xonotic = ((s == "") || (substring(s, 0, 4) == "data"));
587
588         player_setupanimsformodel();
589         UpdatePlayerSounds();
590 }
591
592 /*
593 =============
594 PutObserverInServer
595
596 putting a client as observer in the server
597 =============
598 */
599 void FixPlayermodel();
600 void PutObserverInServer (void)
601 {
602         entity  spot;
603     self.hud = HUD_NORMAL;
604         race_PreSpawnObserver();
605
606         spot = SelectSpawnPoint (TRUE);
607         if(!spot)
608                 error("No spawnpoints for observers?!?\n");
609         RemoveGrapplingHook(self); // Wazat's Grappling Hook
610
611         if(clienttype(self) == CLIENTTYPE_REAL)
612         {
613                 msg_entity = self;
614                 WriteByte(MSG_ONE, SVC_SETVIEW);
615                 WriteEntity(MSG_ONE, self);
616         }
617
618         DropAllRunes(self);
619         MUTATOR_CALLHOOK(MakePlayerObserver);
620
621         if (g_minstagib)
622                 minstagib_stop_countdown();
623
624         Portal_ClearAll(self);
625
626         if(self.alivetime)
627         {
628                 PlayerStats_Event(self, PLAYERSTATS_ALIVETIME, time - self.alivetime);
629                 self.alivetime = 0;
630         }
631
632         if(self.vehicle)
633             vehicles_exit(VHEF_RELESE);
634
635         if(self.flagcarried)
636                 DropFlag(self.flagcarried, world, world);
637
638         if(self.ballcarried && g_nexball)
639                 DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
640
641         WaypointSprite_PlayerDead();
642
643         if not(g_ca)  // don't reset teams when moving a ca player to the spectators
644                 self.team = -1;  // move this as it is needed to log the player spectating in eventlog
645
646         if(self.killcount != -666) {
647                 if(g_lms) {
648                         if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
649                                 bprint ("^4", self.netname, "^4 has no more lives left\n");
650                         else
651                                 bprint ("^4", self.netname, "^4 is spectating now\n"); // TODO turn this into a proper forfeit?
652                 } else
653                         bprint ("^4", self.netname, "^4 is spectating now\n");
654
655                 if(self.just_joined == FALSE) {
656                         LogTeamchange(self.playerid, -1, 4);
657                 } else
658                         self.just_joined = FALSE;
659         }
660
661         PlayerScore_Clear(self); // clear scores when needed
662
663         accuracy_resend(self);
664
665         self.spectatortime = time;
666         
667         self.classname = "observer";
668         self.iscreature = FALSE;
669         self.damagedbycontents = FALSE;
670         self.health = -666;
671         self.takedamage = DAMAGE_NO;
672         self.solid = SOLID_NOT;
673         self.movetype = MOVETYPE_FLY_WORLDONLY; //(self.cvar_cl_clippedspectating ? MOVETYPE_NOCLIP : MOVETYPE_FLY); // it's too early for this anyway, lets just set it in playerprethink
674         self.flags = FL_CLIENT | FL_NOTARGET;
675         self.armorvalue = 666;
676         self.effects = 0;
677         self.armorvalue = autocvar_g_balance_armor_start;
678         self.pauserotarmor_finished = 0;
679         self.pauserothealth_finished = 0;
680         self.pauseregen_finished = 0;
681         self.damageforcescale = 0;
682         self.death_time = 0;
683         self.dead_frame = 0;
684         self.alpha = 0;
685         self.scale = 0;
686         self.fade_time = 0;
687         self.pain_frame = 0;
688         self.pain_finished = 0;
689         self.strength_finished = 0;
690         self.invincible_finished = 0;
691         self.pushltime = 0;
692         self.think = SUB_Null;
693         self.nextthink = 0;
694         self.hook_time = 0;
695         self.runes = 0;
696         self.deadflag = DEAD_NO;
697         self.angles = spot.angles;
698         self.angles_z = 0;
699         self.fixangle = TRUE;
700         self.crouch = FALSE;
701
702         self.view_ofs = '0 0 0'; // so that your view doesn't go into the ceiling with MOVETYPE_FLY_WORLDONLY, previously "PL_VIEW_OFS"
703         setorigin (self, spot.origin);
704         setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX); // give the spectator some space between walls for MOVETYPE_FLY_WORLDONLY
705         self.prevorigin = self.origin;
706         self.items = 0;
707         self.weapons = 0;
708         self.model = "";
709         FixPlayermodel();
710         self.model = "";
711         self.modelindex = 0;
712         self.weapon = 0;
713         self.weaponname = "";
714         self.switchingweapon = 0;
715         self.weaponmodel = "";
716         self.weaponentity = world;
717         self.exteriorweaponentity = world;
718         self.killcount = -666;
719         self.velocity = '0 0 0';
720         self.avelocity = '0 0 0';
721         self.punchangle = '0 0 0';
722         self.punchvector = '0 0 0';
723         self.oldvelocity = self.velocity;
724         self.fire_endtime = -1;
725
726         if(sv_loddistance1)
727                 SetCustomizer(self, Client_customizeentityforclient, Client_uncustomizeentityforclient);
728
729         if(g_arena)
730         {
731                 if(self.version_mismatch)
732                 {
733                         Spawnqueue_Unmark(self);
734                         Spawnqueue_Remove(self);
735                 }
736                 else
737                 {
738                         Spawnqueue_Insert(self);
739                 }
740         }
741         else if(g_lms)
742         {
743                 // Only if the player cannot play at all
744                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) == 666)
745                         self.frags = FRAGS_SPECTATOR;
746                 else
747                         self.frags = FRAGS_LMS_LOSER;
748         }
749         else if(g_ca)
750         {
751                 if(self.caplayer)
752                         self.frags = FRAGS_LMS_LOSER;
753                 else
754                         self.frags = FRAGS_SPECTATOR;
755         }
756         else
757                 self.frags = FRAGS_SPECTATOR;
758 }
759
760 .float model_randomizer;
761 void FixPlayermodel()
762 {
763         string defaultmodel;
764         float defaultskin, chmdl, oldskin, n, i;
765         vector m1, m2;
766
767         defaultmodel = "";
768
769         if(autocvar_sv_defaultcharacter == 1)
770         {
771                 defaultskin = 0;
772
773                 if(teamplay)
774                 {
775                         string s;
776                         s = Team_ColorNameLowerCase(self.team);
777                         if(s != "neutral")
778                         {
779                                 defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", s));
780                                 defaultskin = cvar(strcat("sv_defaultplayerskin_", s));
781                         }
782                 }
783
784                 if(defaultmodel == "")
785                 {
786                         defaultmodel = autocvar_sv_defaultplayermodel;
787                         defaultskin = autocvar_sv_defaultplayerskin;
788                 }
789
790                 n = tokenize_console(defaultmodel);
791                 if(n > 0)
792                         defaultmodel = argv(floor(n * self.model_randomizer));
793
794                 i = strstrofs(defaultmodel, ":", 0);
795                 if(i >= 0)
796                 {
797                         defaultskin = stof(substring(defaultmodel, i+1, -1));
798                         defaultmodel = substring(defaultmodel, 0, i);
799                 }
800         }
801
802         if(self.modelindex == 0 && self.deadflag == DEAD_NO)
803         {
804                 if(self.model != "")
805                         bprint("\{1}^1Player ", self.netname, "^1 has a zero modelindex, trying to fix...\n");
806                 self.model = ""; // force the != checks to return true
807         }
808
809         if(defaultmodel != "")
810         {
811                 if (defaultmodel != self.model)
812                 {
813                         m1 = self.mins;
814                         m2 = self.maxs;
815                         setmodel_lod (self, defaultmodel);
816                         setsize (self, m1, m2);
817                         chmdl = TRUE;
818                 }
819
820                 oldskin = self.skinindex;
821                 self.skinindex = defaultskin;
822         } else {
823                 if (self.playermodel != self.model || self.playermodel == "")
824                 {
825                         self.playermodel = CheckPlayerModel(self.playermodel); // this is never "", so no endless loop
826                         m1 = self.mins;
827                         m2 = self.maxs;
828                         setmodel_lod (self, self.playermodel);
829                         setsize (self, m1, m2);
830                         chmdl = TRUE;
831                 }
832
833                 oldskin = self.skinindex;
834                 self.skinindex = stof(self.playerskin);
835         }
836
837         if(chmdl || oldskin != self.skinindex)
838                 self.species = player_getspecies(); // model or skin has changed
839
840         if(!teamplay)
841                 if(strlen(autocvar_sv_defaultplayercolors))
842                         if(self.clientcolors != stof(autocvar_sv_defaultplayercolors))
843                                 setcolor(self, stof(autocvar_sv_defaultplayercolors));
844 }
845
846 void PlayerTouchExplode(entity p1, entity p2)
847 {
848         vector org;
849         org = (p1.origin + p2.origin) * 0.5;
850         org_z += (p1.mins_z + p2.mins_z) * 0.5;
851
852         te_explosion(org);
853
854         entity e;
855         e = spawn();
856         setorigin(e, org);
857         RadiusDamage(e, world, g_touchexplode_damage, g_touchexplode_edgedamage, g_touchexplode_radius, world, g_touchexplode_force, DEATH_TOUCHEXPLODE, world);
858         remove(e);
859 }
860
861 /*
862 =============
863 PutClientInServer
864
865 Called when a client spawns in the server
866 =============
867 */
868 //void() ctf_playerchanged;
869 void PutClientInServer (void)
870 {
871         if(clienttype(self) == CLIENTTYPE_BOT)
872         {
873                 self.classname = "player";
874         }
875         else if(clienttype(self) == CLIENTTYPE_REAL)
876         {
877                 msg_entity = self;
878                 WriteByte(MSG_ONE, SVC_SETVIEW);
879                 WriteEntity(MSG_ONE, self);
880         }
881         
882         // reset player keys
883         self.itemkeys = 0;
884
885         // player is dead and becomes observer
886         // FIXME fix LMS scoring for new system
887         if(g_lms)
888         {
889                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
890                         self.classname = "observer";
891         }
892
893         if(g_arena || (g_ca && !allowed_to_spawn))
894         if(!self.spawned)
895                 self.classname = "observer";
896
897         if(gameover)
898                 self.classname = "observer";
899
900         if(self.classname == "player" && (!g_ca || (g_ca && allowed_to_spawn))) {
901                 entity spot, oldself;
902                 float j;
903
904                 accuracy_resend(self);
905
906                 if(self.team < 0)
907                         JoinBestTeam(self, FALSE, TRUE);
908
909                 race_PreSpawn();
910
911                 spot = SelectSpawnPoint (FALSE);
912                 if(!spot)
913                 {
914                         centerprint(self, "Sorry, no spawnpoints available!\nHope your team can fix it...");
915                         return; // spawn failed
916                 }
917
918                 RemoveGrapplingHook(self); // Wazat's Grappling Hook
919
920                 self.classname = "player";
921                 self.wasplayer = TRUE;
922                 self.iscreature = TRUE;
923                 self.damagedbycontents = TRUE;
924                 self.movetype = MOVETYPE_WALK;
925                 self.solid = SOLID_SLIDEBOX;
926                 self.dphitcontentsmask = DPCONTENTS_BODY | DPCONTENTS_SOLID;
927                 if(autocvar_g_playerclip_collisions)
928                         self.dphitcontentsmask |= DPCONTENTS_PLAYERCLIP;
929                 if(clienttype(self) == CLIENTTYPE_BOT && autocvar_g_botclip_collisions)
930                         self.dphitcontentsmask |= DPCONTENTS_BOTCLIP;
931                 self.frags = FRAGS_PLAYER;
932                 if(INDEPENDENT_PLAYERS)
933                         MAKE_INDEPENDENT_PLAYER(self);
934                 self.flags = FL_CLIENT;
935                 if(autocvar__notarget)
936                         self.flags |= FL_NOTARGET;
937                 self.takedamage = DAMAGE_AIM;
938                 if(g_minstagib)
939                         self.effects = EF_FULLBRIGHT;
940                 else
941                         self.effects = 0;
942                 self.air_finished = time + 12;
943                 self.dmg = 2;
944                 if(autocvar_g_balance_nex_charge)
945                 {
946                         if(autocvar_g_balance_nex_secondary_chargepool)
947                                 self.nex_chargepool_ammo = 1;
948                         self.nex_charge = autocvar_g_balance_nex_charge_start;
949                 }
950
951                 if(inWarmupStage)
952                 {
953                         self.ammo_shells = warmup_start_ammo_shells;
954                         self.ammo_nails = warmup_start_ammo_nails;
955                         self.ammo_rockets = warmup_start_ammo_rockets;
956                         self.ammo_cells = warmup_start_ammo_cells;
957                         self.ammo_fuel = warmup_start_ammo_fuel;
958                         self.health = warmup_start_health;
959                         self.armorvalue = warmup_start_armorvalue;
960                         self.weapons = warmup_start_weapons;
961                 }
962                 else
963                 {
964                         self.ammo_shells = start_ammo_shells;
965                         self.ammo_nails = start_ammo_nails;
966                         self.ammo_rockets = start_ammo_rockets;
967                         self.ammo_cells = start_ammo_cells;
968                         self.ammo_fuel = start_ammo_fuel;
969                         self.health = start_health;
970                         self.armorvalue = start_armorvalue;
971                         self.weapons = start_weapons;
972                 }
973
974                 if(g_weaponarena_random)
975                 {
976                         if(g_weaponarena_random_with_laser)
977                                 self.weapons &~= WEPBIT_LASER;
978                         self.weapons = randombits(self.weapons, g_weaponarena_random, FALSE);
979                         if(g_weaponarena_random_with_laser)
980                                 self.weapons |= WEPBIT_LASER;
981                 }
982
983                 self.items = start_items;
984                 self.jump_interval = time;
985
986                 self.spawnshieldtime = time + autocvar_g_spawnshieldtime;
987                 self.pauserotarmor_finished = time + autocvar_g_balance_pause_armor_rot_spawn;
988                 self.pauserothealth_finished = time + autocvar_g_balance_pause_health_rot_spawn;
989                 self.pauserotfuel_finished = time + autocvar_g_balance_pause_fuel_rot_spawn;
990                 self.pauseregen_finished = time + autocvar_g_balance_pause_health_regen_spawn;
991                 //extend the pause of rotting if client was reset at the beginning of the countdown
992                 if(!autocvar_sv_ready_restart_after_countdown && time < game_starttime) { // TODO why is this cvar NOTted?
993                         self.spawnshieldtime += game_starttime - time;
994                         self.pauserotarmor_finished += game_starttime - time;
995                         self.pauserothealth_finished += game_starttime - time;
996                         self.pauseregen_finished += game_starttime - time;
997                 }
998                 self.damageforcescale = 2;
999                 self.death_time = 0;
1000                 self.dead_frame = 0;
1001                 self.alpha = 0;
1002                 self.scale = 0;
1003                 self.fade_time = 0;
1004                 self.pain_frame = 0;
1005                 self.pain_finished = 0;
1006                 self.strength_finished = 0;
1007                 self.invincible_finished = 0;
1008                 self.pushltime = 0;
1009                 // players have no think function
1010                 self.think = SUB_Null;
1011                 self.nextthink = 0;
1012                 self.hook_time = 0;
1013                 self.dmg_team = 0;
1014                 self.ballistics_density = autocvar_g_ballistics_density_player;
1015
1016                 self.metertime = 0;
1017
1018                 self.runes = 0;
1019
1020                 self.deadflag = DEAD_NO;
1021
1022                 self.angles = spot.angles;
1023
1024                 self.angles_z = 0; // never spawn tilted even if the spot says to
1025                 self.fixangle = TRUE; // turn this way immediately
1026                 self.velocity = '0 0 0';
1027                 self.avelocity = '0 0 0';
1028                 self.punchangle = '0 0 0';
1029                 self.punchvector = '0 0 0';
1030                 self.oldvelocity = self.velocity;
1031                 self.fire_endtime = -1;
1032
1033                 msg_entity = self;
1034                 WRITESPECTATABLE_MSG_ONE({
1035                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
1036                         WriteByte(MSG_ONE, TE_CSQC_SPAWN);
1037                 });
1038
1039                 if(sv_loddistance1)
1040                         SetCustomizer(self, Client_customizeentityforclient, Client_uncustomizeentityforclient);
1041
1042                 self.model = "";
1043                 FixPlayermodel();
1044
1045                 self.crouch = FALSE;
1046                 self.view_ofs = PL_VIEW_OFS;
1047                 setsize (self, PL_MIN, PL_MAX);
1048                 self.spawnorigin = spot.origin;
1049                 setorigin (self, spot.origin + '0 0 1' * (1 - self.mins_z - 24));
1050                 // don't reset back to last position, even if new position is stuck in solid
1051                 self.oldorigin = self.origin;
1052                 self.prevorigin = self.origin;
1053                 self.lastrocket = world; // stop rocket guiding, no revenge from the grave!
1054                 self.lastteleporttime = time; // prevent insane speeds due to changing origin
1055         self.hud = HUD_NORMAL;
1056         
1057                 if(g_arena)
1058                 {
1059                         Spawnqueue_Remove(self);
1060                         Spawnqueue_Mark(self);
1061                 }
1062
1063                 else if(g_ca)
1064                         self.caplayer = 1;
1065
1066                 self.event_damage = PlayerDamage;
1067
1068                 self.bot_attack = TRUE;
1069
1070                 self.statdraintime = time + 5;
1071                 self.BUTTON_ATCK = self.BUTTON_JUMP = self.BUTTON_ATCK2 = 0;
1072
1073                 if(self.killcount == -666) {
1074                         PlayerScore_Clear(self);
1075                         self.killcount = 0;
1076                 }
1077
1078                 CL_SpawnWeaponentity();
1079                 self.alpha = default_player_alpha;
1080                 self.colormod = '1 1 1' * autocvar_g_player_brightness;
1081                 self.exteriorweaponentity.alpha = default_weapon_alpha;
1082
1083                 self.lms_nextcheck = time + autocvar_g_lms_campcheck_interval*2;
1084                 self.lms_traveled_distance = 0;
1085                 self.speedrunning = FALSE;
1086
1087                 race_PostSpawn(spot);
1088
1089                 if(autocvar_spawn_debug)
1090                 {
1091                         sprint(self, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
1092                         remove(spot);   // usefull for checking if there are spawnpoints, that let drop through the floor
1093                 }
1094
1095                 //stuffcmd(self, "chase_active 0");
1096                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
1097
1098                 if (autocvar_g_spawnsound)
1099                         sound (self, CH_TRIGGER, "misc/spawn.wav", VOL_BASE, ATTN_NORM);
1100
1101                 if(g_assault) {
1102                         if(self.team == assault_attacker_team)
1103                                 centerprint(self, "You are attacking!");
1104                         else
1105                                 centerprint(self, "You are defending!");
1106                 }
1107
1108                 target_voicescript_clear(self);
1109
1110                 // reset fields the weapons may use
1111                 for (j = WEP_FIRST; j <= WEP_LAST; ++j)
1112                 {
1113                         weapon_action(j, WR_RESETPLAYER);
1114
1115                         // all weapons must be fully loaded when we spawn
1116                         entity e;
1117                         e = get_weaponinfo(j);
1118                         if(e.spawnflags & WEP_FLAG_RELOADABLE) // prevent accessing undefined cvars
1119                                 self.(weapon_load[j]) = cvar(strcat("g_balance_", e.netname, "_reload_ammo"));
1120                 }
1121
1122                 oldself = self;
1123                 self = spot;
1124                         activator = oldself;
1125                                 string s;
1126                                 s = self.target;
1127                                 self.target = string_null;
1128                                 SUB_UseTargets();
1129                                 self.target = s;
1130                         activator = world;
1131                 self = oldself;
1132
1133                 MUTATOR_CALLHOOK(PlayerSpawn);
1134
1135                 self.switchweapon = w_getbestweapon(self);
1136                 self.cnt = -1; // W_LastWeapon will not complain
1137                 self.weapon = 0;
1138                 self.weaponname = "";
1139                 self.switchingweapon = 0;
1140
1141                 if(!self.alivetime)
1142                         self.alivetime = time;
1143         } else if(self.classname == "observer" || (g_ca && !allowed_to_spawn)) {
1144                 PutObserverInServer ();
1145         }
1146
1147         //if(g_ctf)
1148         //      ctf_playerchanged();
1149 }
1150
1151 .float ebouncefactor, ebouncestop; // electro's values
1152 // TODO do we need all these fields, or should we stop autodetecting runtime
1153 // changes and just have a console command to update this?
1154 float ClientInit_SendEntity(entity to, float sf)
1155 {
1156         WriteByte(MSG_ENTITY, ENT_CLIENT_INIT);
1157         WriteByte(MSG_ENTITY, g_nexball_meter_period * 32);
1158         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[0]));
1159         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[1]));
1160         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[2]));
1161         WriteInt24_t(MSG_ENTITY, compressShotOrigin(hook_shotorigin[3]));
1162         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[0]));
1163         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[1]));
1164         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[2]));
1165         WriteInt24_t(MSG_ENTITY, compressShotOrigin(electro_shotorigin[3]));
1166         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[0]));
1167         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[1]));
1168         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[2]));
1169         WriteInt24_t(MSG_ENTITY, compressShotOrigin(gauntlet_shotorigin[3]));
1170         if(sv_foginterval && world.fog != "")
1171                 WriteString(MSG_ENTITY, world.fog);
1172         else
1173                 WriteString(MSG_ENTITY, "");
1174         WriteByte(MSG_ENTITY, self.count * 255.0); // g_balance_armor_blockpercent
1175         WriteByte(MSG_ENTITY, self.cnt * 255.0); // g_balance_weaponswitchdelay
1176         WriteCoord(MSG_ENTITY, self.bouncefactor); // g_balance_grenadelauncher_bouncefactor
1177         WriteCoord(MSG_ENTITY, self.bouncestop); // g_balance_grenadelauncher_bouncestop
1178         WriteCoord(MSG_ENTITY, self.ebouncefactor); // g_balance_grenadelauncher_bouncefactor
1179         WriteCoord(MSG_ENTITY, self.ebouncestop); // g_balance_grenadelauncher_bouncestop
1180         WriteByte(MSG_ENTITY, autocvar_g_balance_nex_secondary); // client has to know if it should zoom or not
1181         WriteByte(MSG_ENTITY, autocvar_g_balance_rifle_secondary); // client has to know if it should zoom or not
1182         WriteByte(MSG_ENTITY, serverflags); // client has to know if it should zoom or not
1183         WriteByte(MSG_ENTITY, autocvar_g_balance_minelayer_limit); // minelayer max mines
1184         WriteByte(MSG_ENTITY, autocvar_g_balance_hagar_secondary_load_max); // hagar max loadable rockets
1185         WriteCoord(MSG_ENTITY, autocvar_g_trueaim_minrange);
1186         return TRUE;
1187 }
1188
1189 void ClientInit_CheckUpdate()
1190 {
1191         self.nextthink = time;
1192         if(self.count != autocvar_g_balance_armor_blockpercent)
1193         {
1194                 self.count = autocvar_g_balance_armor_blockpercent;
1195                 self.SendFlags |= 1;
1196         }
1197         if(self.cnt != autocvar_g_balance_weaponswitchdelay)
1198         {
1199                 self.cnt = autocvar_g_balance_weaponswitchdelay;
1200                 self.SendFlags |= 1;
1201         }
1202         if(self.bouncefactor != autocvar_g_balance_grenadelauncher_bouncefactor)
1203         {
1204                 self.bouncefactor = autocvar_g_balance_grenadelauncher_bouncefactor;
1205                 self.SendFlags |= 1;
1206         }
1207         if(self.bouncestop != autocvar_g_balance_grenadelauncher_bouncestop)
1208         {
1209                 self.bouncestop = autocvar_g_balance_grenadelauncher_bouncestop;
1210                 self.SendFlags |= 1;
1211         }
1212         if(self.ebouncefactor != autocvar_g_balance_electro_secondary_bouncefactor)
1213         {
1214                 self.ebouncefactor = autocvar_g_balance_electro_secondary_bouncefactor;
1215                 self.SendFlags |= 1;
1216         }
1217         if(self.ebouncestop != autocvar_g_balance_electro_secondary_bouncestop)
1218         {
1219                 self.ebouncestop = autocvar_g_balance_electro_secondary_bouncestop;
1220                 self.SendFlags |= 1;
1221         }
1222 }
1223
1224 void ClientInit_Spawn()
1225 {
1226         entity o;
1227         entity e;
1228         e = spawn();
1229         e.classname = "clientinit";
1230         e.think = ClientInit_CheckUpdate;
1231         Net_LinkEntity(e, FALSE, 0, ClientInit_SendEntity);
1232
1233         o = self;
1234         self = e;
1235         ClientInit_CheckUpdate();
1236         self = o;
1237 }
1238
1239 /*
1240 =============
1241 SetNewParms
1242 =============
1243 */
1244 void SetNewParms (void)
1245 {
1246         // initialize parms for a new player
1247         parm1 = -(86400 * 366);
1248 }
1249
1250 /*
1251 =============
1252 SetChangeParms
1253 =============
1254 */
1255 void SetChangeParms (void)
1256 {
1257         // save parms for level change
1258         parm1 = self.parm_idlesince - time;
1259 }
1260
1261 /*
1262 =============
1263 DecodeLevelParms
1264 =============
1265 */
1266 void DecodeLevelParms (void)
1267 {
1268         // load parms
1269         self.parm_idlesince = parm1;
1270         if(self.parm_idlesince == -(86400 * 366))
1271                 self.parm_idlesince = time;
1272
1273         // whatever happens, allow 60 seconds of idling directly after connect for map loading
1274         self.parm_idlesince = max(self.parm_idlesince, time - sv_maxidle + 60);
1275 }
1276
1277 /*
1278 =============
1279 ClientKill
1280
1281 Called when a client types 'kill' in the console
1282 =============
1283 */
1284
1285 .float clientkill_nexttime;
1286 void ClientKill_Now_TeamChange()
1287 {
1288         if(self.killindicator_teamchange == -1)
1289         {
1290                 self.team = -1;
1291                 JoinBestTeam( self, FALSE, FALSE );
1292         }
1293         else if(self.killindicator_teamchange == -2)
1294         {
1295                 if(g_ca)
1296                         self.caplayer = 0;
1297                 if(blockSpectators)
1298                         sprint(self, strcat("^7You have to become a player within the next ", ftos(autocvar_g_maxplayers_spectator_blocktime), " seconds, otherwise you will be kicked, because spectators aren't allowed at this time!\n"));
1299                 PutObserverInServer();
1300         }
1301         else
1302                 SV_ChangeTeam(self.killindicator_teamchange - 1);
1303 }
1304
1305 void ClientKill_Now()
1306 {
1307         if(self.vehicle)
1308         {
1309             vehicles_exit(VHEF_RELESE);
1310             if(!self.killindicator_teamchange)
1311             {
1312             self.vehicle_health = -1;
1313             Damage(self, self, self, 1 , DEATH_KILL, self.origin, '0 0 0');             
1314             }
1315         }
1316
1317         if(self.killindicator && !wasfreed(self.killindicator))
1318                 remove(self.killindicator);
1319
1320         self.killindicator = world;
1321
1322         if(self.killindicator_teamchange)
1323                 ClientKill_Now_TeamChange();
1324
1325         // in any case:
1326         Damage(self, self, self, 100000, DEATH_KILL, self.origin, '0 0 0');
1327
1328         // now I am sure the player IS dead
1329 }
1330 void KillIndicator_Think()
1331 {
1332         if (gameover)
1333         {
1334                 self.owner.killindicator = world;
1335                 remove(self);
1336                 return;
1337         }
1338
1339         if (!self.owner.modelindex)
1340         {
1341                 self.owner.killindicator = world;
1342                 remove(self);
1343                 return;
1344         }
1345
1346         if(self.cnt <= 0)
1347         {
1348                 self = self.owner;
1349                 ClientKill_Now(); // no oldself needed
1350                 return;
1351         }
1352     else if(g_cts && self.health == 1) // health == 1 means that it's silent
1353     {
1354         self.nextthink = time + 1;
1355         self.cnt -= 1;
1356     }
1357         else
1358         {
1359                 if(self.cnt <= 10)
1360                         setmodel(self, strcat("models/sprites/", ftos(self.cnt), ".spr32"));
1361                 if(clienttype(self.owner) == CLIENTTYPE_REAL)
1362                 {
1363                         if(self.cnt <= 10)
1364                                 AnnounceTo(self.owner, strcat(ftos(self.cnt), ""));
1365                 }
1366                 self.nextthink = time + 1;
1367                 self.cnt -= 1;
1368         }
1369 }
1370
1371 float clientkilltime;
1372 void ClientKill_TeamChange (float targetteam) // 0 = don't change, -1 = auto, -2 = spec
1373 {
1374         float killtime;
1375         float starttime;
1376         entity e;
1377
1378         if (gameover)
1379                 return;
1380
1381         killtime = autocvar_g_balance_kill_delay;
1382
1383         if(g_race_qualifying || g_cts)
1384                 killtime = 0;
1385
1386     if(g_cts && self.killindicator && self.killindicator.health == 1) // self.killindicator.health == 1 means that the kill indicator was spawned by CTS_ClientKill
1387     {
1388                 remove(self.killindicator);
1389                 self.killindicator = world;
1390
1391         ClientKill_Now(); // allow instant kill in this case
1392         return;
1393     }
1394
1395         self.killindicator_teamchange = targetteam;
1396
1397     if(!self.killindicator)
1398         {
1399                 if(self.modelindex && self.deadflag == DEAD_NO)
1400                 {
1401                         killtime = max(killtime, self.clientkill_nexttime - time);
1402                         self.clientkill_nexttime = time + killtime + autocvar_g_balance_kill_antispam;
1403                 }
1404
1405                 if(killtime <= 0 || !self.modelindex || self.deadflag != DEAD_NO)
1406                 {
1407                         ClientKill_Now();
1408                 }
1409                 else
1410                 {
1411                         starttime = max(time, clientkilltime);
1412
1413                         self.killindicator = spawn();
1414                         self.killindicator.owner = self;
1415                         self.killindicator.scale = 0.5;
1416                         setattachment(self.killindicator, self, "");
1417                         setorigin(self.killindicator, '0 0 52');
1418                         self.killindicator.think = KillIndicator_Think;
1419                         self.killindicator.nextthink = starttime + (self.lip) * 0.05;
1420                         clientkilltime = max(clientkilltime, self.killindicator.nextthink + 0.05);
1421                         self.killindicator.cnt = ceil(killtime);
1422                         self.killindicator.count = bound(0, ceil(killtime), 10);
1423                         //sprint(self, strcat("^1You'll be dead in ", ftos(self.killindicator.cnt), " seconds\n"));
1424
1425                         for(e = world; (e = find(e, classname, "body")) != world; )
1426                         {
1427                                 if(e.enemy != self)
1428                                         continue;
1429                                 e.killindicator = spawn();
1430                                 e.killindicator.owner = e;
1431                                 e.killindicator.scale = 0.5;
1432                                 setattachment(e.killindicator, e, "");
1433                                 setorigin(e.killindicator, '0 0 52');
1434                                 e.killindicator.think = KillIndicator_Think;
1435                                 e.killindicator.nextthink = starttime + (e.lip) * 0.05;
1436                                 clientkilltime = max(clientkilltime, e.killindicator.nextthink + 0.05);
1437                                 e.killindicator.cnt = ceil(killtime);
1438                         }
1439                         self.lip = 0;
1440                 }
1441         }
1442         if(self.killindicator)
1443         {
1444                 if(targetteam == 0) // just die
1445                 {
1446                         self.killindicator.colormod = '0 0 0';
1447                         if(clienttype(self) == CLIENTTYPE_REAL)
1448                         if(self.killindicator.cnt > 0)
1449                                 Send_CSQC_Centerprint_Generic(self, CPID_TEAMCHANGE, "^1Suicide in %d seconds", 1, self.killindicator.cnt);
1450                 }
1451                 else if(targetteam == -1) // auto
1452                 {
1453                         self.killindicator.colormod = '0 1 0';
1454                         if(clienttype(self) == CLIENTTYPE_REAL)
1455                         if(self.killindicator.cnt > 0)
1456                                 Send_CSQC_Centerprint_Generic(self, CPID_TEAMCHANGE, "Changing team in %d seconds", 1, self.killindicator.cnt);
1457                 }
1458                 else if(targetteam == -2) // spectate
1459                 {
1460                         self.killindicator.colormod = '0.5 0.5 0.5';
1461                         if(clienttype(self) == CLIENTTYPE_REAL)
1462                         if(self.killindicator.cnt > 0)
1463                                 Send_CSQC_Centerprint_Generic(self, CPID_TEAMCHANGE, "Spectating in %d seconds", 1, self.killindicator.cnt);
1464                 }
1465                 else
1466                 {
1467                         self.killindicator.colormod = TeamColor(targetteam);
1468                         if(clienttype(self) == CLIENTTYPE_REAL)
1469                         if(self.killindicator.cnt > 0)
1470                                 Send_CSQC_Centerprint_Generic(self, CPID_TEAMCHANGE, strcat("Changing to ", ColoredTeamName(targetteam), " in %d seconds"), 1, self.killindicator.cnt);
1471                 }
1472         }
1473
1474 }
1475
1476 void ClientKill (void)
1477 {
1478         if (gameover)
1479                 return;
1480
1481         if((g_arena || g_ca) && ((champion && champion.classname == "player" && player_count > 1) || player_count == 1)) // don't allow a kill in this case either
1482         {
1483                 // do nothing
1484         }
1485     else if(self.freezetag_frozen)
1486     {
1487         // do nothing
1488     }
1489         else
1490                 ClientKill_TeamChange(0);
1491 }
1492
1493 void CTS_ClientKill (entity e) // silent version of ClientKill, used when player finishes a CTS run. Useful to prevent cheating by running back to the start line and starting out with more speed
1494 {
1495     e.killindicator = spawn();
1496     e.killindicator.owner = e;
1497     e.killindicator.think = KillIndicator_Think;
1498     e.killindicator.nextthink = time + (e.lip) * 0.05;
1499     e.killindicator.cnt = ceil(autocvar_g_cts_finish_kill_delay);
1500     e.killindicator.health = 1; // this is used to indicate that it should be silent
1501     e.lip = 0;
1502 }
1503
1504 void FixClientCvars(entity e)
1505 {
1506         // send prediction settings to the client
1507         stuffcmd(e, "\nin_bindmap 0 0\n");
1508         if(g_race || g_cts)
1509                 stuffcmd(e, "cl_cmd settemp cl_movecliptokeyboard 2\n");
1510         if(autocvar_g_antilag == 3) // client side hitscan
1511                 stuffcmd(e, "cl_cmd settemp cl_prydoncursor_notrace 0\n");
1512         if(sv_gentle)
1513                 stuffcmd(e, "cl_cmd settemp cl_gentle 1\n");
1514         /*
1515          * we no longer need to stuff this. Remove this comment block if you feel
1516          * 2.3 and higher (or was it 2.2.3?) don't need these any more
1517         stuffcmd(e, strcat("cl_gravity ", ftos(autocvar_sv_gravity), "\n"));
1518         stuffcmd(e, strcat("cl_movement_accelerate ", ftos(autocvar_sv_accelerate), "\n"));
1519         stuffcmd(e, strcat("cl_movement_friction ", ftos(autocvar_sv_friction), "\n"));
1520         stuffcmd(e, strcat("cl_movement_maxspeed ", ftos(autocvar_sv_maxspeed), "\n"));
1521         stuffcmd(e, strcat("cl_movement_airaccelerate ", ftos(autocvar_sv_airaccelerate), "\n"));
1522         stuffcmd(e, strcat("cl_movement_maxairspeed ", ftos(autocvar_sv_maxairspeed), "\n"));
1523         stuffcmd(e, strcat("cl_movement_stopspeed ", ftos(autocvar_sv_stopspeed), "\n"));
1524         stuffcmd(e, strcat("cl_movement_jumpvelocity ", ftos(autocvar_sv_jumpvelocity), "\n"));
1525         stuffcmd(e, strcat("cl_movement_stepheight ", ftos(autocvar_sv_stepheight), "\n"));
1526         stuffcmd(e, strcat("set cl_movement_friction_on_land ", ftos(autocvar_sv_friction_on_land), "\n"));
1527         stuffcmd(e, strcat("set cl_movement_airaccel_qw ", ftos(autocvar_sv_airaccel_qw), "\n"));
1528         stuffcmd(e, strcat("set cl_movement_airaccel_sideways_friction ", ftos(autocvar_sv_airaccel_sideways_friction), "\n"));
1529         stuffcmd(e, "cl_movement_edgefriction 1\n");
1530          */
1531 }
1532
1533 float PlayerInIDList(entity p, string idlist)
1534 {
1535         float n, i;
1536         string s;
1537
1538         // NOTE: we do NOT check crypto_keyfp here, an unsigned ID is fine too for this
1539         if not(p.crypto_idfp)
1540                 return 0;
1541
1542         // this function allows abbreviated player IDs too!
1543         n = tokenize_console(idlist);
1544         for(i = 0; i < n; ++i)
1545         {
1546                 s = argv(i);
1547                 if(s == substring(p.crypto_idfp, 0, strlen(s)))
1548                         return 1;
1549         }
1550
1551         return 0;
1552 }
1553
1554 /*
1555 =============
1556 ClientConnect
1557
1558 Called when a client connects to the server
1559 =============
1560 */
1561 //void ctf_clientconnect();
1562 string ColoredTeamName(float t);
1563 void DecodeLevelParms (void);
1564 //void dom_player_join_team(entity pl);
1565 void set_dom_state(entity e);
1566 void ClientConnect (void)
1567 {
1568         float t;
1569
1570         if(self.flags & FL_CLIENT)
1571         {
1572                 print("Warning: ClientConnect, but already connected!\n");
1573                 return;
1574         }
1575
1576         if(Ban_MaybeEnforceBan(self))
1577                 return;
1578
1579         DecodeLevelParms();
1580
1581 #ifdef WATERMARK
1582         sprint(self, strcat("^4SVQC Build information: ^1", WATERMARK(), "\n"));
1583 #endif
1584
1585         self.classname = "player_joining";
1586
1587         self.flags = FL_CLIENT;
1588         self.version_nagtime = time + 10 + random() * 10;
1589
1590         if(player_count<0)
1591         {
1592                 dprint("BUG player count is lower than zero, this cannot happen!\n");
1593                 player_count = 0;
1594         }
1595
1596         PlayerScore_Attach(self);
1597         ClientData_Attach();
1598         accuracy_init(self);
1599
1600         bot_clientconnect();
1601
1602         playerdemo_init();
1603
1604         anticheat_init();
1605
1606         race_PreSpawnObserver();
1607
1608         //if(g_domination)
1609         //      dom_player_join_team(self);
1610
1611         // identify the right forced team
1612         if(autocvar_g_campaign)
1613         {
1614                 if(clienttype(self) == CLIENTTYPE_REAL) // only players, not bots
1615                 {
1616                         switch(autocvar_g_campaign_forceteam)
1617                         {
1618                                 case 1: self.team_forced = COLOR_TEAM1; break;
1619                                 case 2: self.team_forced = COLOR_TEAM2; break;
1620                                 case 3: self.team_forced = COLOR_TEAM3; break;
1621                                 case 4: self.team_forced = COLOR_TEAM4; break;
1622                                 default: self.team_forced = 0;
1623                         }
1624                 }
1625         }
1626         else if(PlayerInIDList(self, autocvar_g_forced_team_red))
1627                 self.team_forced = COLOR_TEAM1;
1628         else if(PlayerInIDList(self, autocvar_g_forced_team_blue))
1629                 self.team_forced = COLOR_TEAM2;
1630         else if(PlayerInIDList(self, autocvar_g_forced_team_yellow))
1631                 self.team_forced = COLOR_TEAM3;
1632         else if(PlayerInIDList(self, autocvar_g_forced_team_pink))
1633                 self.team_forced = COLOR_TEAM4;
1634         else if(autocvar_g_forced_team_otherwise == "red")
1635                 self.team_forced = COLOR_TEAM1;
1636         else if(autocvar_g_forced_team_otherwise == "blue")
1637                 self.team_forced = COLOR_TEAM2;
1638         else if(autocvar_g_forced_team_otherwise == "yellow")
1639                 self.team_forced = COLOR_TEAM3;
1640         else if(autocvar_g_forced_team_otherwise == "pink")
1641                 self.team_forced = COLOR_TEAM4;
1642         else if(autocvar_g_forced_team_otherwise == "spectate")
1643                 self.team_forced = -1;
1644         else if(autocvar_g_forced_team_otherwise == "spectator")
1645                 self.team_forced = -1;
1646         else
1647                 self.team_forced = 0;
1648
1649         if(!teamplay)
1650                 if(self.team_forced > 0)
1651                         self.team_forced = 0;
1652
1653         JoinBestTeam(self, FALSE, FALSE); // if the team number is valid, keep it
1654
1655         if((autocvar_sv_spectate == 1 && !g_lms) || autocvar_g_campaign || self.team_forced < 0) {
1656                 self.classname = "observer";
1657         } else {
1658                 if(teamplay)
1659                 {
1660                         if(autocvar_g_balance_teams || autocvar_g_balance_teams_force)
1661                         {
1662                                 self.classname = "player";
1663                                 campaign_bots_may_start = 1;
1664                         }
1665                         else
1666                         {
1667                                 self.classname = "observer"; // do it anyway
1668                         }
1669                 }
1670                 else
1671                 {
1672                         self.classname = "player";
1673                         campaign_bots_may_start = 1;
1674                 }
1675         }
1676
1677         self.playerid = (playerid_last = playerid_last + 1);
1678
1679         PlayerStats_AddEvent(sprintf("kills-%d", self.playerid));
1680
1681     if(clienttype(self) == CLIENTTYPE_BOT)
1682         PlayerStats_AddPlayer(self);
1683
1684         if(autocvar_sv_eventlog)
1685                 GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":", ((clienttype(self) == CLIENTTYPE_REAL) ? self.netaddress : "bot"), ":", self.netname));
1686
1687         LogTeamchange(self.playerid, self.team, 1);
1688
1689         self.just_joined = TRUE;  // stop spamming the eventlog with additional lines when the client connects
1690
1691         self.netname_previous = strzone(self.netname);
1692
1693         bprint("^4", self.netname, "^4 connected");
1694
1695         if(self.classname != "observer" && (g_domination || g_ctf))
1696                 bprint(" and joined the ", ColoredTeamName(self.team));
1697
1698         bprint("\n");
1699
1700         stuffcmd(self, strcat(clientstuff, "\n"));
1701         stuffcmd(self, "cl_particles_reloadeffects\n"); // TODO do we still need this?
1702
1703         FixClientCvars(self);
1704
1705         // spawnfunc_waypoint sprites
1706         WaypointSprite_InitClient(self);
1707
1708         // Wazat's grappling hook
1709         SetGrappleHookBindings();
1710
1711         // get version info from player
1712         stuffcmd(self, "cmd clientversion $gameversion\n");
1713
1714         // get other cvars from player
1715         GetCvars(0);
1716
1717         // notify about available teams
1718         if(teamplay)
1719         {
1720                 CheckAllowedTeams(self);
1721                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1722                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1723         }
1724         else
1725                 stuffcmd(self, "set _teams_available 0\n");
1726
1727         stuffcmd(self, strcat("set gametype ", ftos(game), "\n"));
1728
1729         if(g_arena || g_ca)
1730         {
1731                 self.classname = "observer";
1732                 if(g_arena)
1733                         Spawnqueue_Insert(self);
1734         }
1735         /*else if(g_ctf)
1736         {
1737                 ctf_clientconnect();
1738         }*/
1739
1740         attach_entcs();
1741
1742         bot_relinkplayerlist();
1743
1744         self.spectatortime = time;
1745         if(blockSpectators)
1746         {
1747                 sprint(self, strcat("^7You have to become a player within the next ", ftos(autocvar_g_maxplayers_spectator_blocktime), " seconds, otherwise you will be kicked, because spectators aren't allowed at this time!\n"));
1748         }
1749
1750         self.jointime = time;
1751         self.allowedTimeouts = autocvar_sv_timeout_number;
1752
1753         if(clienttype(self) == CLIENTTYPE_REAL)
1754         {
1755                 if(autocvar_g_bugrigs || g_weaponarena == WEPBIT_TUBA)
1756                         stuffcmd(self, "cl_cmd settemp chase_active 1\n");
1757         }
1758
1759         if(g_lms)
1760         {
1761                 if(PlayerScore_Add(self, SP_LMS_LIVES, LMS_NewPlayerLives()) <= 0)
1762                 {
1763                         PlayerScore_Add(self, SP_LMS_RANK, 666);
1764                         self.frags = FRAGS_SPECTATOR;
1765                 }
1766         }
1767
1768         if(!sv_foginterval && world.fog != "")
1769                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1770
1771         SoundEntity_Attach(self);
1772
1773         if(autocvar_g_hitplots || strstrofs(strcat(" ", autocvar_g_hitplots_individuals, " "), strcat(" ", self.netaddress, " "), 0) >= 0)
1774         {
1775                 self.hitplotfh = fopen(strcat("hits-", matchid, "-", self.netaddress, "-", ftos(self.playerid), ".plot"), FILE_WRITE);
1776                 fputs(self.hitplotfh, strcat("#name ", self.netname, "\n"));
1777         }
1778         else
1779                 self.hitplotfh = -1;
1780
1781         if(g_race || g_cts) {
1782                 string rr;
1783                 if(g_cts)
1784                         rr = CTS_RECORD;
1785                 else
1786                         rr = RACE_RECORD;
1787                 t = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "time")));
1788
1789                 msg_entity = self;
1790                 race_send_recordtime(MSG_ONE);
1791                 race_send_speedaward(MSG_ONE);
1792
1793                 speedaward_alltimebest = stof(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/speed")));
1794                 speedaward_alltimebest_holder = uid2name(db_get(ServerProgsDB, strcat(GetMapname(), rr, "speed/crypto_idfp")));
1795                 race_send_speedaward_alltimebest(MSG_ONE);
1796
1797                 float i;
1798                 for (i = 1; i <= RANKINGS_CNT; ++i) {
1799                         race_SendRankings(i, 0, 0, MSG_ONE);
1800                 }
1801         }
1802         else if(autocvar_sv_teamnagger && !(autocvar_bot_vs_human && (c3==-1 && c4==-1)) && !g_ca) // teamnagger is currently bad for ca
1803                 send_CSQC_teamnagger();
1804
1805         if (g_domination)
1806                 set_dom_state(self);
1807
1808         CheatInitClient();
1809
1810         if(!autocvar_g_campaign)
1811                 Send_CSQC_Centerprint_Generic(self, CPID_MOTD, getwelcomemessage(), autocvar_welcome_message_time, 0);
1812
1813         self.model_randomizer = random();
1814 }
1815
1816 /*
1817 =============
1818 ClientDisconnect
1819
1820 Called when a client disconnects from the server
1821 =============
1822 */
1823 .entity chatbubbleentity;
1824 void ReadyCount();
1825 void ClientDisconnect (void)
1826 {
1827         if(self.vehicle)
1828             vehicles_exit(VHEF_RELESE);
1829
1830         if not(self.flags & FL_CLIENT)
1831         {
1832                 print("Warning: ClientDisconnect without ClientConnect\n");
1833                 return;
1834         }
1835
1836         PlayerStats_AddGlobalInfo(self);
1837
1838         CheatShutdownClient();
1839
1840         if(self.hitplotfh >= 0)
1841         {
1842                 fclose(self.hitplotfh);
1843                 self.hitplotfh = -1;
1844         }
1845
1846         anticheat_report();
1847         anticheat_shutdown();
1848
1849         playerdemo_shutdown();
1850
1851         bot_clientdisconnect();
1852
1853         if(self.entcs)
1854                 detach_entcs();
1855
1856         if(autocvar_sv_eventlog)
1857                 GameLogEcho(strcat(":part:", ftos(self.playerid)));
1858         bprint ("^4",self.netname);
1859         bprint ("^4 disconnected\n");
1860
1861         SoundEntity_Detach(self);
1862
1863         DropAllRunes(self);
1864         MUTATOR_CALLHOOK(ClientDisconnect);
1865
1866         Portal_ClearAll(self);
1867
1868         RemoveGrapplingHook(self);
1869         if(self.flagcarried)
1870                 DropFlag(self.flagcarried, world, world);
1871         if(self.ballcarried && g_nexball)
1872                 DropBall(self.ballcarried, self.origin + self.ballcarried.origin, self.velocity);
1873
1874         // Here, everything has been done that requires this player to be a client.
1875
1876         self.flags &~= FL_CLIENT;
1877
1878         if (self.chatbubbleentity)
1879                 remove (self.chatbubbleentity);
1880
1881         if (self.killindicator)
1882                 remove (self.killindicator);
1883
1884         WaypointSprite_PlayerGone();
1885
1886         bot_relinkplayerlist();
1887
1888         if(g_arena)
1889         {
1890                 Spawnqueue_Unmark(self);
1891                 Spawnqueue_Remove(self);
1892         }
1893
1894         accuracy_free(self);
1895         ClientData_Detach();
1896         PlayerScore_Detach(self);
1897
1898         if(self.netname_previous)
1899                 strunzone(self.netname_previous);
1900         if(self.clientstatus)
1901                 strunzone(self.clientstatus);
1902         if(self.weaponorder_byimpulse)
1903                 strunzone(self.weaponorder_byimpulse);
1904
1905         ClearPlayerSounds();
1906
1907         if(self.personal)
1908                 remove(self.personal);
1909
1910         self.playerid = 0;
1911         ReadyCount();
1912
1913         // free cvars
1914         GetCvars(-1);
1915 }
1916
1917 .float BUTTON_CHAT;
1918 void ChatBubbleThink()
1919 {
1920         self.nextthink = time;
1921         if (!self.owner.modelindex || self.owner.chatbubbleentity != self)
1922         {
1923                 if(self.owner) // but why can that ever be world?
1924                         self.owner.chatbubbleentity = world;
1925                 remove(self);
1926                 return;
1927         }
1928         if ((self.owner.BUTTON_CHAT && !self.owner.deadflag)
1929 #ifdef TETRIS
1930                 || self.owner.tetris_on
1931 #endif
1932         )
1933                 self.model = self.mdl;
1934         else
1935                 self.model = "";
1936 }
1937
1938 void UpdateChatBubble()
1939 {
1940         if (!self.modelindex)
1941                 return;
1942         // spawn a chatbubble entity if needed
1943         if (!self.chatbubbleentity)
1944         {
1945                 self.chatbubbleentity = spawn();
1946                 self.chatbubbleentity.owner = self;
1947                 self.chatbubbleentity.exteriormodeltoclient = self;
1948                 self.chatbubbleentity.think = ChatBubbleThink;
1949                 self.chatbubbleentity.nextthink = time;
1950                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1951                 //setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1952                 setorigin(self.chatbubbleentity, '0 0 15' + self.maxs_z * '0 0 1');
1953                 setattachment(self.chatbubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1954                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1955                 self.chatbubbleentity.model = "";
1956                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1957         }
1958 }
1959
1960
1961 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1962 // added to the model skins
1963 /*void UpdateColorModHack()
1964 {
1965         float c;
1966         c = self.clientcolors & 15;
1967         // LordHavoc: only bothering to support white, green, red, yellow, blue
1968              if (!teamplay) self.colormod = '0 0 0';
1969         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1970         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1971         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1972         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1973         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1974         else self.colormod = '1 1 1';
1975 }*/
1976
1977 .float oldcolormap;
1978 void respawn(void)
1979 {
1980         if(self.modelindex != 0 && autocvar_g_respawn_ghosts)
1981         {
1982                 self.solid = SOLID_NOT;
1983                 self.takedamage = DAMAGE_NO;
1984                 self.movetype = MOVETYPE_FLY;
1985                 self.velocity = '0 0 1' * autocvar_g_respawn_ghosts_speed;
1986                 self.avelocity = randomvec() * autocvar_g_respawn_ghosts_speed * 3 - randomvec() * autocvar_g_respawn_ghosts_speed * 3;
1987                 self.effects |= EF_ADDITIVE;
1988                 self.oldcolormap = self.colormap;
1989                 self.colormap = 0; // this originally was 512, but raises a warning in the engine, so get rid of it
1990                 pointparticles(particleeffectnum("respawn_ghost"), self.origin, '0 0 0', 1);
1991                 if(autocvar_g_respawn_ghosts_maxtime)
1992                         SUB_SetFade (self, time + autocvar_g_respawn_ghosts_maxtime / 2 + random () * (autocvar_g_respawn_ghosts_maxtime - autocvar_g_respawn_ghosts_maxtime / 2), 1.5);
1993         }
1994
1995         CopyBody(1);
1996         self.effects |= EF_NODRAW; // prevent another CopyBody
1997         if(self.oldcolormap)
1998         {
1999                 self.colormap = self.oldcolormap;
2000                 self.oldcolormap = 0;
2001         }
2002         PutClientInServer();
2003 }
2004
2005 void play_countdown(float finished, string samp)
2006 {
2007         if(clienttype(self) == CLIENTTYPE_REAL)
2008                 if(floor(finished - time - frametime) != floor(finished - time))
2009                         if(finished - time < 6)
2010                                 sound (self, CH_INFO, samp, VOL_BASE, ATTN_NORM);
2011 }
2012
2013 void player_powerups (void)
2014 {
2015         // add a way to see what the items were BEFORE all of these checks for the mutator hook
2016         olditems = self.items;
2017
2018         if((self.items & IT_USING_JETPACK) && !self.deadflag)
2019         {
2020                 SoundEntity_StartSound(self, CH_TRIGGER_SINGLE, "misc/jetpack_fly.wav", VOL_BASE, autocvar_g_jetpack_attenuation);
2021                 self.modelflags |= MF_ROCKET;
2022         }
2023         else
2024         {
2025                 SoundEntity_StopSound(self, CH_TRIGGER_SINGLE);
2026                 self.modelflags &~= MF_ROCKET;
2027         }
2028
2029         self.effects &~= (EF_DIMLIGHT | EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT | EF_FLAME | EF_NODEPTHTEST);
2030
2031         if(!self.modelindex || self.deadflag) // don't apply the flags if the player is gibbed
2032                 return;
2033
2034         Fire_ApplyDamage(self);
2035         Fire_ApplyEffect(self);
2036
2037         if (g_minstagib)
2038         {
2039                 self.effects |= EF_FULLBRIGHT;
2040
2041                 if (self.items & IT_STRENGTH)
2042                 {
2043                         play_countdown(self.strength_finished, "misc/poweroff.wav");
2044                         if (time > self.strength_finished)
2045                         {
2046                                 self.alpha = default_player_alpha;
2047                                 self.exteriorweaponentity.alpha = default_weapon_alpha;
2048                                 self.items &~= IT_STRENGTH;
2049                                 sprint(self, "^3Invisibility has worn off\n");
2050                         }
2051                 }
2052                 else
2053                 {
2054                         if (time < self.strength_finished)
2055                         {
2056                                 self.alpha = g_minstagib_invis_alpha;
2057                                 self.exteriorweaponentity.alpha = g_minstagib_invis_alpha;
2058                                 self.items |= IT_STRENGTH;
2059                                 sprint(self, "^3You are invisible\n");
2060                         }
2061                 }
2062
2063                 if (self.items & IT_INVINCIBLE)
2064                 {
2065                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
2066                         if (time > self.invincible_finished && autocvar_g_balance_powerup_timer)
2067                         {
2068                                 self.items = self.items - (self.items & IT_INVINCIBLE);
2069                                 sprint(self, "^3Speed has worn off\n");
2070                         }
2071                 }
2072                 else
2073                 {
2074                         if (time < self.invincible_finished)
2075                         {
2076                                 self.items = self.items | IT_INVINCIBLE;
2077                                 sprint(self, "^3You are on speed\n");
2078                         }
2079                 }
2080         }
2081         else // if we're not in minstagib, continue. I added this else to replace the "return" which was here that broke the callhook for this function -- This code is nasty.
2082         {
2083                 if (self.items & IT_STRENGTH)
2084                 {
2085                         play_countdown(self.strength_finished, "misc/poweroff.wav");
2086                         self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
2087                         if (time > self.strength_finished && autocvar_g_balance_powerup_timer)
2088                         {
2089                                 self.items = self.items - (self.items & IT_STRENGTH);
2090                                 sprint(self, "^3Strength has worn off\n");
2091                         }
2092                 }
2093                 else
2094                 {
2095                         if (time < self.strength_finished)
2096                         {
2097                                 self.items = self.items | IT_STRENGTH;
2098                                 sprint(self, "^3Strength infuses your weapons with devastating power\n");
2099                         }
2100                 }
2101                 if (self.items & IT_INVINCIBLE)
2102                 {
2103                         play_countdown(self.invincible_finished, "misc/poweroff.wav");
2104                         self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
2105                         if (time > self.invincible_finished && autocvar_g_balance_powerup_timer)
2106                         {
2107                                 self.items = self.items - (self.items & IT_INVINCIBLE);
2108                                 sprint(self, "^3Shield has worn off\n");
2109                         }
2110                 }
2111                 else
2112                 {
2113                         if (time < self.invincible_finished)
2114                         {
2115                                 self.items = self.items | IT_INVINCIBLE;
2116                                 sprint(self, "^3Shield surrounds you\n");
2117                         }
2118                 }
2119
2120                 if(autocvar_g_nodepthtestplayers)
2121                         self.effects = self.effects | EF_NODEPTHTEST;
2122
2123                 if(autocvar_g_fullbrightplayers)
2124                         self.effects = self.effects | EF_FULLBRIGHT;
2125
2126                 // midair gamemode: damage only while in the air
2127                 // if in midair mode, being on ground grants temporary invulnerability
2128                 // (this is so that multishot weapon don't clear the ground flag on the
2129                 // first damage in the frame, leaving the player vulnerable to the
2130                 // remaining hits in the same frame)
2131                 if (self.flags & FL_ONGROUND)
2132                 if (g_midair)
2133                         self.spawnshieldtime = max(self.spawnshieldtime, time + autocvar_g_midair_shieldtime);
2134
2135                 if (time >= game_starttime)
2136                 if (time < self.spawnshieldtime)
2137                         self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
2138         }
2139
2140         MUTATOR_CALLHOOK(PlayerPowerups);
2141 }
2142
2143 float CalcRegen(float current, float stable, float regenfactor, float regenframetime)
2144 {
2145         if(current > stable)
2146                 return current;
2147         else if(current > stable - 0.25) // when close enough, "snap"
2148                 return stable;
2149         else
2150                 return min(stable, current + (stable - current) * regenfactor * regenframetime);
2151 }
2152
2153 float CalcRot(float current, float stable, float rotfactor, float rotframetime)
2154 {
2155         if(current < stable)
2156                 return current;
2157         else if(current < stable + 0.25) // when close enough, "snap"
2158                 return stable;
2159         else
2160                 return max(stable, current + (stable - current) * rotfactor * rotframetime);
2161 }
2162
2163 float CalcRotRegen(float current, float regenstable, float regenfactor, float regenlinear, float regenframetime, float rotstable, float rotfactor, float rotlinear, float rotframetime, float limit)
2164 {
2165         if(current > rotstable)
2166         {
2167                 if(rotframetime > 0)
2168                 {
2169                         current = CalcRot(current, rotstable, rotfactor, rotframetime);
2170                         current = max(rotstable, current - rotlinear * rotframetime);
2171                 }
2172         }
2173         else if(current < regenstable)
2174         {
2175                 if(regenframetime > 0)
2176                 {
2177                         current = CalcRegen(current, regenstable, regenfactor, regenframetime);
2178                         current = min(regenstable, current + regenlinear * regenframetime);
2179                 }
2180         }
2181
2182         if(current > limit)
2183                 current = limit;
2184
2185         return current;
2186 }
2187
2188 void player_regen (void)
2189 {
2190         float minh, mina, minf, maxh, maxa, maxf, limith, limita, limitf, max_mod, regen_mod, rot_mod, limit_mod;
2191         maxh = autocvar_g_balance_health_rotstable;
2192         maxa = autocvar_g_balance_armor_rotstable;
2193         maxf = autocvar_g_balance_fuel_rotstable;
2194         minh = autocvar_g_balance_health_regenstable;
2195         mina = autocvar_g_balance_armor_regenstable;
2196         minf = autocvar_g_balance_fuel_regenstable;
2197         limith = autocvar_g_balance_health_limit;
2198         limita = autocvar_g_balance_armor_limit;
2199         limitf = autocvar_g_balance_fuel_limit;
2200
2201         max_mod = regen_mod = rot_mod = limit_mod = 1;
2202
2203         if (self.runes & RUNE_REGEN)
2204         {
2205                 if (self.runes & CURSE_VENOM) // do we have both rune/curse?
2206                 {
2207                         regen_mod = autocvar_g_balance_rune_regen_combo_regenrate;
2208                         max_mod = autocvar_g_balance_rune_regen_combo_hpmod;
2209                         limit_mod = autocvar_g_balance_rune_regen_combo_limitmod;
2210                 }
2211                 else
2212                 {
2213                         regen_mod = autocvar_g_balance_rune_regen_regenrate;
2214                         max_mod = autocvar_g_balance_rune_regen_hpmod;
2215                         limit_mod = autocvar_g_balance_rune_regen_limitmod;
2216                 }
2217         }
2218         else if (self.runes & CURSE_VENOM)
2219         {
2220                 max_mod = autocvar_g_balance_curse_venom_hpmod;
2221                 if (self.runes & RUNE_REGEN) // do we have both rune/curse?
2222                         rot_mod = autocvar_g_balance_rune_regen_combo_rotrate;
2223                 else
2224                         rot_mod = autocvar_g_balance_curse_venom_rotrate;
2225                 limit_mod = autocvar_g_balance_curse_venom_limitmod;
2226                 //if (!self.runes & RUNE_REGEN)
2227                 //      rot_mod = autocvar_g_balance_curse_venom_rotrate;
2228         }
2229         maxh = maxh * max_mod;
2230         //maxa = maxa * max_mod;
2231         //maxf = maxf * max_mod;
2232         minh = minh * max_mod;
2233         //mina = mina * max_mod;
2234         //minf = minf * max_mod;
2235         limith = limith * limit_mod;
2236         limita = limita * limit_mod;
2237         //limitf = limitf * limit_mod;
2238
2239         if(g_lms && g_ca)
2240                 rot_mod = 0;
2241
2242         if (!g_minstagib && !g_ca && (!g_lms || autocvar_g_lms_regenerate))
2243         {
2244                 self.armorvalue = CalcRotRegen(self.armorvalue, mina, autocvar_g_balance_armor_regen, autocvar_g_balance_armor_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished), maxa, autocvar_g_balance_armor_rot, autocvar_g_balance_armor_rotlinear, rot_mod * frametime * (time > self.pauserotarmor_finished), limita);
2245                 self.health = CalcRotRegen(self.health, minh, autocvar_g_balance_health_regen, autocvar_g_balance_health_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished), maxh, autocvar_g_balance_health_rot, autocvar_g_balance_health_rotlinear, rot_mod * frametime * (time > self.pauserothealth_finished), limith);
2246
2247                 // if player rotted to death...  die!
2248                 if(self.health < 1)
2249                         self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
2250         }
2251
2252         if not(self.items & IT_UNLIMITED_WEAPON_AMMO)
2253                 self.ammo_fuel = CalcRotRegen(self.ammo_fuel, minf, autocvar_g_balance_fuel_regen, autocvar_g_balance_fuel_regenlinear, regen_mod * frametime * (time > self.pauseregen_finished) * (self.items & IT_FUEL_REGEN != 0), maxf, autocvar_g_balance_fuel_rot, autocvar_g_balance_fuel_rotlinear, rot_mod * frametime * (time > self.pauserotfuel_finished), limitf);
2254 }
2255
2256 float zoomstate_set;
2257 void SetZoomState(float z)
2258 {
2259         if(z != self.zoomstate)
2260         {
2261                 self.zoomstate = z;
2262                 ClientData_Touch(self);
2263         }
2264         zoomstate_set = 1;
2265 }
2266
2267 void GetPressedKeys(void) {
2268         MUTATOR_CALLHOOK(GetPressedKeys);
2269         if (self.movement_x > 0) // get if movement keys are pressed
2270         {       // forward key pressed
2271                 self.pressedkeys |= KEY_FORWARD;
2272                 self.pressedkeys &~= KEY_BACKWARD;
2273         }
2274         else if (self.movement_x < 0)
2275         {       // backward key pressed
2276                 self.pressedkeys |= KEY_BACKWARD;
2277                 self.pressedkeys &~= KEY_FORWARD;
2278         }
2279         else
2280         {       // no x input
2281                 self.pressedkeys &~= KEY_FORWARD;
2282                 self.pressedkeys &~= KEY_BACKWARD;
2283         }
2284
2285         if (self.movement_y > 0)
2286         {       // right key pressed
2287                 self.pressedkeys |= KEY_RIGHT;
2288                 self.pressedkeys &~= KEY_LEFT;
2289         }
2290         else if (self.movement_y < 0)
2291         {       // left key pressed
2292                 self.pressedkeys |= KEY_LEFT;
2293                 self.pressedkeys &~= KEY_RIGHT;
2294         }
2295         else
2296         {       // no y input
2297                 self.pressedkeys &~= KEY_RIGHT;
2298                 self.pressedkeys &~= KEY_LEFT;
2299         }
2300
2301         if (self.BUTTON_JUMP) // get if jump and crouch keys are pressed
2302                 self.pressedkeys |= KEY_JUMP;
2303         else
2304                 self.pressedkeys &~= KEY_JUMP;
2305         if (self.BUTTON_CROUCH)
2306                 self.pressedkeys |= KEY_CROUCH;
2307         else
2308                 self.pressedkeys &~= KEY_CROUCH;
2309 }
2310
2311 /*
2312 ======================
2313 spectate mode routines
2314 ======================
2315 */
2316
2317 void SpectateCopy(entity spectatee) {
2318         other = spectatee;
2319         MUTATOR_CALLHOOK(SpectateCopy);
2320         self.armortype = spectatee.armortype;
2321         self.armorvalue = spectatee.armorvalue;
2322         self.ammo_cells = spectatee.ammo_cells;
2323         self.ammo_shells = spectatee.ammo_shells;
2324         self.ammo_nails = spectatee.ammo_nails;
2325         self.ammo_rockets = spectatee.ammo_rockets;
2326         self.ammo_fuel = spectatee.ammo_fuel;
2327         self.clip_load = spectatee.clip_load;
2328         self.clip_size = spectatee.clip_size;
2329         self.effects = spectatee.effects & EFMASK_CHEAP; // eat performance
2330         self.health = spectatee.health;
2331         self.impulse = 0;
2332         self.items = spectatee.items;
2333         self.last_pickup = spectatee.last_pickup;
2334         self.hit_time = spectatee.hit_time;
2335         self.metertime = spectatee.metertime;
2336         self.strength_finished = spectatee.strength_finished;
2337         self.invincible_finished = spectatee.invincible_finished;
2338         self.pressedkeys = spectatee.pressedkeys;
2339         self.weapons = spectatee.weapons;
2340         self.switchweapon = spectatee.switchweapon;
2341         self.switchingweapon = spectatee.switchingweapon;
2342         self.weapon = spectatee.weapon;
2343         self.nex_charge = spectatee.nex_charge;
2344         self.nex_chargepool_ammo = spectatee.nex_chargepool_ammo;
2345         self.hagar_load = spectatee.hagar_load;
2346         self.minelayer_mines = spectatee.minelayer_mines;
2347         self.punchangle = spectatee.punchangle;
2348         self.view_ofs = spectatee.view_ofs;
2349         self.v_angle = spectatee.v_angle;
2350         self.velocity = spectatee.velocity;
2351         self.dmg_take = spectatee.dmg_take;
2352         self.dmg_save = spectatee.dmg_save;
2353         self.dmg_inflictor = spectatee.dmg_inflictor;
2354         self.angles = spectatee.v_angle;
2355         if(!self.BUTTON_USE)
2356                 self.fixangle = TRUE;
2357         setorigin(self, spectatee.origin);
2358         setsize(self, spectatee.mins, spectatee.maxs);
2359         SetZoomState(spectatee.zoomstate);
2360
2361         anticheat_spectatecopy(spectatee);
2362
2363         //self.vehicle = spectatee.vehicle;
2364
2365         self.hud = spectatee.hud;
2366         if(spectatee.vehicle)
2367     {
2368         setorigin(self, spectatee.origin);
2369         self.velocity = spectatee.vehicle.velocity;
2370         self.v_angle += spectatee.vehicle.angles;
2371         //self.v_angle_x *= -1;
2372         self.vehicle_health = spectatee.vehicle_health;
2373         self.vehicle_shield = spectatee.vehicle_shield;
2374         self.vehicle_energy = spectatee.vehicle_energy;
2375         self.vehicle_ammo1 = spectatee.vehicle_ammo1;
2376         self.vehicle_ammo2 = spectatee.vehicle_ammo2;
2377         self.vehicle_reload1 = spectatee.vehicle_reload1;
2378         self.vehicle_reload2 = spectatee.vehicle_reload2;
2379         
2380         msg_entity = self;
2381         WriteByte (MSG_ONE, SVC_SETVIEWPORT);
2382         WriteEntity(MSG_ONE, spectatee);
2383         //self.tur_head = spectatee.vehicle.vehicle_viewport;
2384     }
2385 }
2386
2387 float SpectateUpdate() {
2388         if(!self.enemy)
2389             return 0;           
2390
2391         if (self == self.enemy)
2392                 return 0;
2393
2394         if(self.enemy.classname != "player")
2395                 return 0;
2396
2397         SpectateCopy(self.enemy);
2398
2399         return 1;
2400 }
2401
2402
2403 // Returns next available player to spectate if g_ca_spectate_enemies == 0
2404 entity CA_SpectateNext(entity start) {
2405         if (start.team == self.team) {
2406                 return start;
2407         }
2408         
2409         other = start;
2410         // continue from current player
2411         while(other && other.team != self.team) {
2412                 other = find(other, classname, "player");
2413         }
2414         
2415         if (!other) {
2416                 // restart from begining
2417                 other = find(other, classname, "player");
2418                 while(other && other.team != self.team) {
2419                         other = find(other, classname, "player");
2420                 }
2421         }
2422         
2423         return other;
2424 }
2425
2426 float SpectateNext() {
2427         other = find(self.enemy, classname, "player");
2428         if (g_ca && !autocvar_g_ca_spectate_enemies && self.caplayer) {
2429                 // CA and ca players when spectating enemies is forbidden
2430                 other = CA_SpectateNext(other);
2431         } else {
2432                 // other modes and ca spectators or spectating enemies is allowed
2433                 if (!other)
2434                         other = find(other, classname, "player");
2435         }
2436         
2437         if (other)
2438                 self.enemy = other;
2439
2440         if(self.enemy.classname == "player") {
2441             if(self.enemy.vehicle)
2442             {      
2443             msg_entity = self;
2444             WriteByte(MSG_ONE, SVC_SETVIEWPORT);
2445             WriteEntity(MSG_ONE, self.enemy);
2446             //stuffcmd(self, "set viewsize $tmpviewsize \n");
2447             self.movetype = MOVETYPE_NONE;
2448             accuracy_resend(self);
2449             }
2450             else 
2451             {           
2452             msg_entity = self;
2453             WriteByte(MSG_ONE, SVC_SETVIEW);
2454             WriteEntity(MSG_ONE, self.enemy);
2455             //stuffcmd(self, "set viewsize $tmpviewsize \n");
2456             self.movetype = MOVETYPE_NONE;
2457             accuracy_resend(self);
2458
2459             if(!SpectateUpdate())
2460                 PutObserverInServer();
2461         }
2462         return 1;
2463         } else {
2464                 return 0;
2465         }
2466 }
2467
2468 /*
2469 =============
2470 ShowRespawnCountdown()
2471
2472 Update a respawn countdown display.
2473 =============
2474 */
2475 void ShowRespawnCountdown()
2476 {
2477         float number;
2478         if(self.deadflag == DEAD_NO) // just respawned?
2479                 return;
2480         else
2481         {
2482                 number = ceil(self.death_time - time);
2483                 if(number <= 0)
2484                         return;
2485                 if(number <= self.respawn_countdown)
2486                 {
2487                         self.respawn_countdown = number - 1;
2488                         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
2489                                 AnnounceTo(self, strcat(ftos(number), ""));
2490                 }
2491         }
2492 }
2493
2494 .float prevent_join_msgtime;
2495 void LeaveSpectatorMode()
2496 {
2497         if(nJoinAllowed(1)) {
2498                 if(!teamplay || autocvar_g_campaign || autocvar_g_balance_teams || (self.wasplayer && autocvar_g_changeteam_banned) || self.team_forced > 0) {
2499                         self.classname = "player";
2500
2501                         if(autocvar_g_campaign || autocvar_g_balance_teams || autocvar_g_balance_teams_force)
2502                                 JoinBestTeam(self, FALSE, TRUE);
2503
2504                         if(autocvar_g_campaign)
2505                                 campaign_bots_may_start = 1;
2506
2507                         PutClientInServer();
2508
2509                         if(self.classname == "player")
2510                                 bprint ("^4", self.netname, "^4 is playing now\n");
2511
2512                         if(!autocvar_g_campaign)
2513                         if (time < self.jointime + autocvar_welcome_message_time)
2514                                 Send_CSQC_Centerprint_Generic_Expire(self, CPID_MOTD); // clear MOTD
2515
2516                         if (self.prevent_join_msgtime)
2517                         {
2518                                 Send_CSQC_Centerprint_Generic_Expire(self, CPID_PREVENT_JOIN);
2519                                 self.prevent_join_msgtime = 0;
2520                         }
2521
2522                         return;
2523                 } else {
2524                         if (g_ca && self.caplayer) {
2525                         }       // do nothing
2526                         else
2527                                 stuffcmd(self,"menu_showteamselect\n");
2528                         return;
2529                 }
2530         }
2531         else {
2532                 //player may not join because of g_maxplayers is set
2533                 if (time - self.prevent_join_msgtime > 2)
2534                 {
2535                         Send_CSQC_Centerprint_Generic(self, CPID_PREVENT_JOIN, PREVENT_JOIN_TEXT, 0, 0);
2536                         self.prevent_join_msgtime = time;
2537                 }
2538         }
2539 }
2540
2541 /**
2542  * Determines whether the player is allowed to join. This depends on cvar
2543  * g_maxplayers, if it isn't used this function always return TRUE, otherwise
2544  * it checks whether the number of currently playing players exceeds g_maxplayers.
2545  * @return int number of free slots for players, 0 if none
2546  */
2547 float nJoinAllowed(float includeMe) {
2548         if(self.team_forced < 0)
2549                 return FALSE; // forced spectators can never join
2550
2551         // TODO simplify this
2552         entity e;
2553
2554         float totalClients;
2555         FOR_EACH_CLIENT(e)
2556                 totalClients += 1;
2557
2558         if (!autocvar_g_maxplayers)
2559                 return maxclients - totalClients + includeMe;
2560
2561         float currentlyPlaying;
2562         FOR_EACH_REALPLAYER(e)
2563                 currentlyPlaying += 1;
2564
2565         if(currentlyPlaying < autocvar_g_maxplayers)
2566                 return min(maxclients - totalClients + includeMe, autocvar_g_maxplayers - currentlyPlaying);
2567
2568         return 0;
2569 }
2570
2571 /**
2572  * Checks whether the client is an observer or spectator, if so, he will get kicked after
2573  * g_maxplayers_spectator_blocktime seconds
2574  */
2575 void checkSpectatorBlock() {
2576         if(self.classname == "spectator" || self.classname == "observer") {
2577                 if( time > (self.spectatortime + autocvar_g_maxplayers_spectator_blocktime) ) {
2578                         sprint(self, "^7You were kicked from the server because you are spectator and spectators aren't allowed at the moment.\n");
2579                         dropclient(self);
2580                 }
2581         }
2582 }
2583
2584 .float motd_actived_time; // used for both motd and campaign_message
2585 void PrintWelcomeMessage()
2586 {
2587         if (self.motd_actived_time == 0) { // is there already a message showing?
2588                 if (autocvar_g_campaign) {
2589                         if ((self.classname == "player" && self.BUTTON_INFO) || (self.classname != "player")) {
2590                                 self.motd_actived_time = time;
2591                                 Send_CSQC_Centerprint_Generic(self, CPID_MOTD, campaign_message, -1, 0);
2592                         }
2593                 } else {
2594                         if ((time - self.jointime > autocvar_welcome_message_time) && self.BUTTON_INFO) {
2595                                 self.motd_actived_time = time;
2596                                 Send_CSQC_Centerprint_Generic(self, CPID_MOTD, getwelcomemessage(), -1, 0);
2597                         }
2598                 }
2599         } else { // showing MOTD or campaign message
2600                 if (autocvar_g_campaign) {
2601                         if (self.BUTTON_INFO)
2602                                 self.motd_actived_time = time;
2603                         else if ((time - self.motd_actived_time > 2) && self.classname == "player") { // hide it some seconds after BUTTON_INFO has been released
2604                                 self.motd_actived_time = 0;
2605                                 Send_CSQC_Centerprint_Generic_Expire(self, CPID_MOTD);
2606                         }
2607                 } else {
2608                         if ((time - self.jointime) > autocvar_welcome_message_time) {
2609                                 if (self.BUTTON_INFO)
2610                                         self.motd_actived_time = time;
2611                                 else if (time - self.motd_actived_time > 2) { // hide it some seconds after BUTTON_INFO has been released
2612                                         self.motd_actived_time = 0;
2613                                         Send_CSQC_Centerprint_Generic_Expire(self, CPID_MOTD);
2614                                 }
2615                         }
2616                 }
2617         }
2618 }
2619
2620 void ObserverThink()
2621 {
2622         float prefered_movetype;
2623         if (self.flags & FL_JUMPRELEASED) {
2624                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2625                         self.flags &~= FL_JUMPRELEASED;
2626                         self.flags |= FL_SPAWNING;
2627                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
2628                         self.flags &~= FL_JUMPRELEASED;
2629                         if(SpectateNext() == 1) {
2630                                 self.classname = "spectator";
2631                         }
2632                 } else {
2633                         prefered_movetype = ((!self.BUTTON_USE ? self.cvar_cl_clippedspectating : !self.cvar_cl_clippedspectating) ? MOVETYPE_FLY_WORLDONLY : MOVETYPE_NOCLIP);
2634                         if (self.movetype != prefered_movetype)
2635                                 self.movetype = prefered_movetype;
2636                 }
2637         } else {
2638                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
2639                         self.flags |= FL_JUMPRELEASED;
2640                         if(self.flags & FL_SPAWNING)
2641                         {
2642                                 self.flags &~= FL_SPAWNING;
2643                                 LeaveSpectatorMode();
2644                                 return;
2645                         }
2646                 }
2647         }
2648
2649         PrintWelcomeMessage();
2650 }
2651
2652 void SpectatorThink()
2653 {
2654         if (self.flags & FL_JUMPRELEASED) {
2655                 if (self.BUTTON_JUMP && !self.version_mismatch) {
2656                         self.flags &~= FL_JUMPRELEASED;
2657                         self.flags |= FL_SPAWNING;
2658                 } else if(self.BUTTON_ATCK) {
2659                         self.flags &~= FL_JUMPRELEASED;
2660                         if(SpectateNext() == 1) {
2661                                 self.classname = "spectator";
2662                         } else {
2663                                 self.classname = "observer";
2664                                 PutClientInServer();
2665                         }
2666                 } else if (self.BUTTON_ATCK2) {
2667                         self.flags &~= FL_JUMPRELEASED;
2668                         self.classname = "observer";
2669                         PutClientInServer();
2670                 } else {
2671                         if(!SpectateUpdate())
2672                                 PutObserverInServer();
2673                 }
2674         } else {
2675                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
2676                         self.flags |= FL_JUMPRELEASED;
2677                         if(self.flags & FL_SPAWNING)
2678                         {
2679                                 self.flags &~= FL_SPAWNING;
2680                                 LeaveSpectatorMode();
2681                                 return;
2682                         }
2683                 }
2684                 if(!SpectateUpdate())
2685                         PutObserverInServer();
2686         }
2687
2688         PrintWelcomeMessage();
2689         self.flags |= FL_CLIENT | FL_NOTARGET;
2690 }
2691
2692 float ctf_usekey();
2693 void PlayerUseKey()
2694 {
2695         if(self.classname != "player")
2696                 return;
2697
2698         if(self.vehicle)
2699         {
2700         vehicles_exit(VHEF_NORMAL);
2701         return;
2702         }
2703         
2704         // a use key was pressed; call handlers
2705         if(ctf_usekey())
2706                 return;
2707
2708         MUTATOR_CALLHOOK(PlayerUseKey);
2709 }
2710
2711 .float touchexplode_time;
2712
2713 /*
2714 =============
2715 PlayerPreThink
2716
2717 Called every frame for each client before the physics are run
2718 =============
2719 */
2720 .float usekeypressed;
2721 void() ctf_setstatus;
2722 void() nexball_setstatus;
2723 .float items_added;
2724 void PlayerPreThink (void)
2725 {
2726         WarpZone_PlayerPhysics_FixVAngle();
2727
2728         self.stat_game_starttime = game_starttime;
2729         self.stat_allow_oldnexbeam = autocvar_g_allow_oldnexbeam;
2730         self.stat_leadlimit = autocvar_leadlimit;
2731
2732         if(frametime)
2733         {
2734                 // physics frames: update anticheat stuff
2735                 anticheat_prethink();
2736         }
2737
2738         if(blockSpectators && frametime)
2739                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
2740                 checkSpectatorBlock();
2741
2742         zoomstate_set = 0;
2743
2744         if(self.netname_previous != self.netname)
2745         {
2746                 if(autocvar_sv_eventlog)
2747                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname));
2748                 if(self.netname_previous)
2749                         strunzone(self.netname_previous);
2750                 self.netname_previous = strzone(self.netname);
2751         }
2752
2753         // version nagging
2754         if(self.version_nagtime)
2755                 if(self.cvar_g_xonoticversion)
2756                         if(time > self.version_nagtime)
2757                         {
2758                                 // don't notify git users
2759                                 if(strstr(self.cvar_g_xonoticversion, "git", 0) < 0 && strstr(self.cvar_g_xonoticversion, "autobuild", 0) < 0)
2760                                 {
2761                                         if(strstr(autocvar_g_xonoticversion, "git", 0) >= 0 || strstr(autocvar_g_xonoticversion, "autobuild", 0) >= 0)
2762                                         {
2763                                                 // notify release users if connecting to git
2764                                                 dprint("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Xonotic ", autocvar_g_xonoticversion, " (beta)^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n");
2765                                                 sprint(self, strcat("\{1}^1NOTE: ^7the server is running ^3Xonotic ", autocvar_g_xonoticversion, " (beta)^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n"));
2766                                         }
2767                                         else
2768                                         {
2769                                                 float r;
2770                                                 r = vercmp(self.cvar_g_xonoticversion, autocvar_g_xonoticversion);
2771                                                 if(r < 0)
2772                                                 {
2773                                                         // give users new version
2774                                                         dprint("^1NOTE^7 to ", self.netname, "^7 - ^3Xonotic ", autocvar_g_xonoticversion, "^7 is out, and you still have ^3Xonotic ", self.cvar_g_xonoticversion, "^1 - get the update from ^4http://www.xonotic.org/^1!\n");
2775                                                         sprint(self, strcat("\{1}^1NOTE: ^3Xonotic ", autocvar_g_xonoticversion, "^7 is out, and you still have ^3Xonotic ", self.cvar_g_xonoticversion, "^1 - get the update from ^4http://www.xonotic.org/^1!\n"));
2776                                                 }
2777                                                 else if(r > 0)
2778                                                 {
2779                                                         // notify users about old server version
2780                                                         print("^1NOTE^7 to ", self.netname, "^7 - the server is running ^3Xonotic ", autocvar_g_xonoticversion, "^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n");
2781                                                         sprint(self, strcat("\{1}^1NOTE: ^7the server is running ^3Xonotic ", autocvar_g_xonoticversion, "^7, you have ^3Xonotic ", self.cvar_g_xonoticversion, "^1\n"));
2782                                                 }
2783                                         }
2784                                 }
2785                                 self.version_nagtime = 0;
2786                         }
2787
2788         // GOD MODE info
2789         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
2790         {
2791                 sprint(self, strcat("godmode saved you ", ftos(self.max_armorvalue), " units of damage, cheater!\n"));
2792                 self.max_armorvalue = 0;
2793         }
2794
2795 #ifdef TETRIS
2796         if (TetrisPreFrame())
2797                 return;
2798 #endif
2799
2800         MUTATOR_CALLHOOK(PlayerPreThink);
2801
2802         if(!self.cvar_cl_newusekeysupported) // FIXME remove this - it was a stupid idea to begin with, we can JUST use the button
2803         {
2804                 if(self.BUTTON_USE && !self.usekeypressed)
2805                         PlayerUseKey();
2806                 self.usekeypressed = self.BUTTON_USE;
2807         }
2808
2809         PrintWelcomeMessage();
2810
2811         if(self.classname == "player") {
2812 //              if(self.netname == "Wazat")
2813 //                      bprint(self.classname, "\n");
2814
2815                 CheckRules_Player();
2816
2817                 if (intermission_running)
2818                 {
2819                         IntermissionThink ();   // otherwise a button could be missed between
2820                         return;                                 // the think tics
2821                 }
2822
2823                 //don't allow the player to turn around while game is paused!
2824                 if(timeoutStatus == 2) {
2825                         // FIXME turn this into CSQC stuff
2826                         self.v_angle = self.lastV_angle;
2827                         self.angles = self.lastV_angle;
2828                         self.fixangle = TRUE;
2829                 }
2830
2831                 if(frametime)
2832                 {
2833                         if(self.health <= 0 && autocvar_g_deathglow)
2834                         {
2835                                 if(self.glowmod_x > 0)
2836                                         self.glowmod_x -= autocvar_g_deathglow * frametime;
2837                                 else
2838                                         self.glowmod_x = -1;
2839                                 if(self.glowmod_y > 0)
2840                                         self.glowmod_y -= autocvar_g_deathglow * frametime;
2841                                 else
2842                                         self.glowmod_y = -1;
2843                                 if(self.glowmod_z > 0)
2844                                         self.glowmod_z -= autocvar_g_deathglow * frametime;
2845                                 else
2846                                         self.glowmod_z = -1;
2847                         }
2848                         else
2849                         {
2850                                 // set weapon and player glowmod
2851                                 self.glowmod = colormapPaletteColor(self.clientcolors & 0x0F, TRUE) * 2;
2852
2853                                 if(self.weapon == WEP_NEX && autocvar_g_balance_nex_charge)
2854                                 {
2855                                         self.weaponentity_glowmod_x = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_red_half * min(1, self.nex_charge / autocvar_g_balance_nex_charge_animlimit);
2856                                         self.weaponentity_glowmod_y = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_green_half * min(1, self.nex_charge / autocvar_g_balance_nex_charge_animlimit);
2857                                         self.weaponentity_glowmod_z = autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_blue_half * min(1, self.nex_charge / autocvar_g_balance_nex_charge_animlimit);
2858
2859                                         if(self.nex_charge > autocvar_g_balance_nex_charge_animlimit)
2860                                         {
2861                                                 self.weaponentity_glowmod_x = self.weaponentity_glowmod_x + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_red_full * (self.nex_charge - autocvar_g_balance_nex_charge_animlimit) / (1 - autocvar_g_balance_nex_charge_animlimit);
2862                                                 self.weaponentity_glowmod_y = self.weaponentity_glowmod_y + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_green_full * (self.nex_charge - autocvar_g_balance_nex_charge_animlimit) / (1 - autocvar_g_balance_nex_charge_animlimit);
2863                                                 self.weaponentity_glowmod_z = self.weaponentity_glowmod_z + autocvar_g_weapon_charge_colormod_hdrmultiplier * autocvar_g_weapon_charge_colormod_blue_full * (self.nex_charge - autocvar_g_balance_nex_charge_animlimit) / (1 - autocvar_g_balance_nex_charge_animlimit);
2864                                         }
2865                                 }
2866                                 else
2867                                         self.weaponentity_glowmod = self.glowmod;
2868                         }
2869                         player_powerups();
2870                 }
2871
2872                 if (g_minstagib)
2873                         minstagib_ammocheck();
2874
2875                 if (self.deadflag != DEAD_NO)
2876                 {
2877                         float button_pressed, force_respawn;
2878                         if(self.personal && g_race_qualifying)
2879                         {
2880                                 if(time > self.death_time)
2881                                 {
2882                                         self.death_time = time + 1; // only retry once a second
2883                                         respawn();
2884                                         self.impulse = 141;
2885                                 }
2886                         }
2887                         else
2888                         {
2889                                 if(frametime)
2890                                         player_anim();
2891                                 button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2892                                 force_respawn = (g_lms || g_ca || g_cts || autocvar_g_forced_respawn);
2893                                 if (self.deadflag == DEAD_DYING)
2894                                 {
2895                                         if(force_respawn)
2896                                                 self.deadflag = DEAD_RESPAWNING;
2897                                         else if(!button_pressed)
2898                                                 self.deadflag = DEAD_DEAD;
2899                                 }
2900                                 else if (self.deadflag == DEAD_DEAD)
2901                                 {
2902                                         if(button_pressed)
2903                                                 self.deadflag = DEAD_RESPAWNABLE;
2904                                 }
2905                                 else if (self.deadflag == DEAD_RESPAWNABLE)
2906                                 {
2907                                         if(!button_pressed)
2908                                                 self.deadflag = DEAD_RESPAWNING;
2909                                 }
2910                                 else if (self.deadflag == DEAD_RESPAWNING)
2911                                 {
2912                                         if(time > self.death_time)
2913                                         {
2914                                                 self.death_time = time + 1; // only retry once a second
2915                                                 respawn();
2916                                         }
2917                                 }
2918                                 ShowRespawnCountdown();
2919                         }
2920                         return;
2921                 }
2922                 // FIXME from now on self.deadflag is always 0 (and self.health is never < 1)
2923                 // so (self.deadflag == DEAD_NO) is always true in the code below
2924
2925                 if(g_touchexplode)
2926                 if(time > self.touchexplode_time)
2927                 if(self.classname == "player")
2928                 if(self.deadflag == DEAD_NO)
2929                 if not(IS_INDEPENDENT_PLAYER(self))
2930                 FOR_EACH_PLAYER(other) if(self != other)
2931                 {
2932                         if(time > other.touchexplode_time)
2933                         if(other.deadflag == DEAD_NO)
2934                         if not(IS_INDEPENDENT_PLAYER(other))
2935                         if(boxesoverlap(self.absmin, self.absmax, other.absmin, other.absmax))
2936                         {
2937                                 PlayerTouchExplode(self, other);
2938                                 self.touchexplode_time = other.touchexplode_time = time + 0.2;
2939                         }
2940                 }
2941
2942                 if(g_lms && !self.deadflag && autocvar_g_lms_campcheck_interval)
2943                 {
2944                         vector dist;
2945
2946                         // calculate player movement (in 2 dimensions only, so jumping on one spot doesn't count as movement)
2947                         dist = self.prevorigin - self.origin;
2948                         dist_z = 0;
2949                         self.lms_traveled_distance += fabs(vlen(dist));
2950
2951                         if((autocvar_g_campaign && !campaign_bots_may_start) || (time < game_starttime))
2952                         {
2953                                 self.lms_nextcheck = time + autocvar_g_lms_campcheck_interval*2;
2954                                 self.lms_traveled_distance = 0;
2955                         }
2956
2957                         if(time > self.lms_nextcheck)
2958                         {
2959                                 //sprint(self, "distance: ", ftos(self.lms_traveled_distance), "\n");
2960                                 if(self.lms_traveled_distance < autocvar_g_lms_campcheck_distance)
2961                                 {
2962                                         centerprint(self, autocvar_g_lms_campcheck_message);
2963                                         // FIXME KadaverJack: gibbing player here causes playermodel to bounce around, instead of eye.md3
2964                                         // I wasn't able to find out WHY that happens, so I put a workaround in place that shall prevent players from being gibbed :(
2965                                         Damage(self, self, self, bound(0, autocvar_g_lms_campcheck_damage, self.health + self.armorvalue * autocvar_g_balance_armor_blockpercent + 5), DEATH_CAMP, self.origin, '0 0 0');
2966                                 }
2967                                 self.lms_nextcheck = time + autocvar_g_lms_campcheck_interval;
2968                                 self.lms_traveled_distance = 0;
2969                         }
2970                 }
2971
2972                 self.prevorigin = self.origin;
2973
2974                 if (((self.BUTTON_CROUCH && !self.hook.state) || self.health <= g_bloodloss) && self.animstate_startframe != self.anim_melee_x) // prevent crouching if using melee attack
2975                 {
2976                         if (!self.crouch)
2977                         {
2978                                 self.crouch = TRUE;
2979                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2980                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2981                                 // setanim(self, self.anim_duck, FALSE, TRUE, TRUE); // this anim is BROKEN anyway
2982                         }
2983                 }
2984                 else
2985                 {
2986                         if (self.crouch)
2987                         {
2988                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, FALSE, self);
2989                                 if (!trace_startsolid)
2990                                 {
2991                                         self.crouch = FALSE;
2992                                         self.view_ofs = PL_VIEW_OFS;
2993                                         setsize (self, PL_MIN, PL_MAX);
2994                                 }
2995                         }
2996                 }
2997
2998                 if(self.health <= g_bloodloss && self.deadflag == DEAD_NO)
2999                 {
3000                         if(self.bloodloss_timer < time)
3001                         {
3002                                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
3003                                 self.bloodloss_timer = time + 0.5 + random() * 0.5;
3004                         }
3005                 }
3006
3007                 FixPlayermodel();
3008
3009                 GrapplingHookFrame();
3010
3011                 // LordHavoc: allow firing on move frames (sub-ticrate), this gives better timing on slow servers
3012                 //if(frametime)
3013                 {
3014                         self.items &~= self.items_added;
3015
3016                         W_WeaponFrame();
3017
3018                         self.items_added = 0;
3019                         if(self.items & IT_JETPACK)
3020                                 if(self.items & IT_FUEL_REGEN || self.ammo_fuel >= 0.01)
3021                                         self.items_added |= IT_FUEL;
3022
3023                         self.items |= self.items_added;
3024                 }
3025
3026                 player_regen();
3027
3028                 // rot nex charge to the charge limit
3029                 if(autocvar_g_balance_nex_charge_rot_rate && self.nex_charge > autocvar_g_balance_nex_charge_limit && self.nex_charge_rottime < time)
3030                         self.nex_charge = bound(autocvar_g_balance_nex_charge_limit, self.nex_charge - autocvar_g_balance_nex_charge_rot_rate * frametime / W_TICSPERFRAME, 1);
3031
3032                 if(frametime)
3033                         player_anim();
3034
3035                 if(g_ctf)
3036                         ctf_setstatus();
3037
3038                 if(g_nexball)
3039                         nexball_setstatus();
3040                 
3041                 // secret status
3042                 secrets_setstatus();
3043                 
3044                 self.dmg_team = max(0, self.dmg_team - autocvar_g_teamdamage_resetspeed * frametime);
3045
3046                 //self.angles_y=self.v_angle_y + 90;   // temp
3047         } else if(gameover) {
3048                 if (intermission_running)
3049                         IntermissionThink ();   // otherwise a button could be missed between
3050                 return;
3051         } else if(self.classname == "observer") {
3052                 ObserverThink();
3053         } else if(self.classname == "spectator") {
3054                 SpectatorThink();
3055         }
3056
3057         if(!zoomstate_set)
3058                 SetZoomState(self.BUTTON_ZOOM || self.BUTTON_ZOOMSCRIPT || (self.BUTTON_ATCK2 && self.weapon == WEP_NEX) || (self.BUTTON_ATCK2 && self.weapon == WEP_RIFLE && autocvar_g_balance_rifle_secondary == 0));
3059
3060         float oldspectatee_status;
3061         oldspectatee_status = self.spectatee_status;
3062         if(self.classname == "spectator")
3063                 self.spectatee_status = num_for_edict(self.enemy);
3064         else if(self.classname == "observer")
3065                 self.spectatee_status = num_for_edict(self);
3066         else
3067                 self.spectatee_status = 0;
3068         if(self.spectatee_status != oldspectatee_status)
3069         {
3070                 ClientData_Touch(self);
3071                 if(g_race || g_cts)
3072                         race_InitSpectator();
3073         }
3074
3075         if(self.teamkill_soundtime)
3076         if(time > self.teamkill_soundtime)
3077         {
3078                 self.teamkill_soundtime = 0;
3079
3080                 entity oldpusher, oldself;
3081
3082                 oldself = self; self = self.teamkill_soundsource;
3083                 oldpusher = self.pusher; self.pusher = oldself;
3084
3085                 PlayerSound(playersound_teamshoot, CH_VOICE, VOICETYPE_LASTATTACKER_ONLY);
3086
3087                 self.pusher = oldpusher;
3088                 self = oldself;
3089         }
3090
3091         if(self.taunt_soundtime)
3092         if(time > self.taunt_soundtime)
3093         {
3094                 self.taunt_soundtime = 0;
3095                 PlayerSound(playersound_taunt, CH_VOICE, VOICETYPE_AUTOTAUNT);
3096         }
3097
3098         target_voicescript_next(self);
3099
3100         // if a player goes unarmed after holding a loaded weapon, empty his clip size and remove the crosshair ammo ring
3101         if(!self.weapon)
3102                 self.clip_load = self.clip_size = 0;
3103 }
3104
3105 float isInvisibleString(string s)
3106 {
3107         float i, n, c;
3108         s = strdecolorize(s);
3109         for((i = 0), (n = strlen(s)); i < n; ++i)
3110         {
3111                 c = str2chr(s, i);
3112                 switch(c)
3113                 {
3114                         case 0:
3115                         case 32: // space
3116                                 break;
3117                         case 192: // charmap space
3118                                 if (!autocvar_utf8_enable)
3119                                         break;
3120                                 return FALSE;
3121                         case 160: // space in unicode fonts
3122                         case 0xE000 + 192: // utf8 charmap space
3123                                 if (autocvar_utf8_enable)
3124                                         break;
3125                         default:
3126                                 return FALSE;
3127                 }
3128         }
3129         return TRUE;
3130 }
3131
3132 /*
3133 =============
3134 PlayerPostThink
3135
3136 Called every frame for each client after the physics are run
3137 =============
3138 */
3139 .float idlekick_lasttimeleft;
3140 .entity showheadshotbbox;
3141 void showheadshotbbox_think()
3142 {
3143         if(self.owner.showheadshotbbox != self)
3144         {
3145                 remove(self);
3146                 return;
3147         }
3148         self.nextthink = time;
3149         setorigin(self, self.owner.origin);
3150         setsize(self, GetHeadshotMins(self.owner), GetHeadshotMaxs(self.owner));
3151 }
3152 void PlayerPostThink (void)
3153 {
3154         // Savage: Check for nameless players
3155         if (isInvisibleString(self.netname)) {
3156                 self.netname = "Player";
3157                 stuffcmd(self, strcat("name ", self.netname, substring(ftos(random()), 2, -1), "\n"));
3158         }
3159
3160         if(sv_maxidle && frametime)
3161         {
3162                 // WORKAROUND: only use dropclient in server frames (frametime set). Never use it in cl_movement frames (frametime zero).
3163                 float timeleft;
3164                 if (time - self.parm_idlesince < 1) // instead of (time == self.parm_idlesince) to support sv_maxidle <= 10
3165                 {
3166                         if(self.idlekick_lasttimeleft)
3167                         {
3168                                 Send_CSQC_Centerprint_Generic_Expire(self, CPID_DISCONNECT_IDLING);
3169                                 self.idlekick_lasttimeleft = 0;
3170                         }
3171                         return;
3172                 }
3173                 timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
3174                 if(timeleft == min(10, sv_maxidle - 1)) // - 1 to support sv_maxidle <= 10
3175                 {
3176                         if(!self.idlekick_lasttimeleft)
3177                                 Send_CSQC_Centerprint_Generic(self, CPID_DISCONNECT_IDLING, "^3Stop idling!\n^3Disconnecting in %d seconds...", 1, timeleft);
3178                 }
3179                 if(timeleft <= 0)
3180                 {
3181                         bprint("^3", self.netname, "^3 was kicked for idling.\n");
3182                         AnnounceTo(self, "terminated");
3183                         dropclient(self);
3184                         return;
3185                 }
3186                 else if(timeleft <= 10)
3187                 {
3188                         if(timeleft != self.idlekick_lasttimeleft)
3189                                 AnnounceTo(self, ftos(timeleft));
3190                         self.idlekick_lasttimeleft = timeleft;
3191                 }
3192         }
3193
3194 #ifdef TETRIS
3195         if(self.impulse == 100)
3196                 ImpulseCommands();
3197         if (TetrisPostFrame())
3198                 return;
3199 #endif
3200
3201         CheatFrame();
3202
3203         //CheckPlayerJump();
3204
3205         if(self.classname == "player") {
3206                 CheckRules_Player();
3207                 UpdateChatBubble();
3208                 if (self.impulse)
3209                         ImpulseCommands();
3210                 if (intermission_running)
3211                         return;         // intermission or finale
3212                 GetPressedKeys();
3213         } else if (self.classname == "observer") {
3214                 //do nothing
3215         } else if (self.classname == "spectator") {
3216                 //do nothing
3217         }
3218         
3219         /*
3220         float i;
3221         for(i = 0; i < 1000; ++i)
3222         {
3223                 vector end;
3224                 end = self.origin + '0 0 1024' + 512 * randomvec();
3225                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
3226                 if(trace_fraction < 1)
3227                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
3228                 {
3229                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
3230                         break;
3231                 }
3232         }
3233         */
3234
3235         Arena_Warmup();
3236
3237         //pointparticles(particleeffectnum("machinegun_impact"), self.origin + self.view_ofs + '0 0 7', '0 0 0', 1);
3238
3239         if(self.waypointsprite_attachedforcarrier)
3240                 WaypointSprite_UpdateHealth(self.waypointsprite_attachedforcarrier, '1 0 0' * healtharmor_maxdamage(self.health, self.armorvalue, autocvar_g_balance_armor_blockpercent));
3241
3242         if(self.classname == "player" && self.deadflag == DEAD_NO && autocvar_r_showbboxes)
3243         {
3244                 if(!self.showheadshotbbox)
3245                 {
3246                         self.showheadshotbbox = spawn();
3247                         self.showheadshotbbox.classname = "headshotbbox";
3248                         self.showheadshotbbox.owner = self;
3249                         self.showheadshotbbox.think = showheadshotbbox_think;
3250                         self.showheadshotbbox.nextthink = time;
3251                         self = self.showheadshotbbox;
3252                         self.think();
3253                         self = self.owner;
3254                 }
3255         }
3256         else
3257         {
3258                 if(self.showheadshotbbox)
3259                         if(self.showheadshotbbox && !wasfreed(self.showheadshotbbox))
3260                 remove(self.showheadshotbbox);
3261         }
3262
3263         playerdemo_write();
3264
3265         if((g_cts || g_race) && self.cvar_cl_allow_uidtracking == 1 && self.cvar_cl_allow_uid2name == 1)
3266         {
3267                 if(!self.stored_netname)
3268                         self.stored_netname = strzone(uid2name(self.crypto_idfp));
3269                 if(self.stored_netname != self.netname)
3270                 {
3271                         db_put(ServerProgsDB, strcat("/uid2name/", self.crypto_idfp), self.netname);
3272                         strunzone(self.stored_netname);
3273                         self.stored_netname = strzone(self.netname);
3274                 }
3275         }
3276
3277         /*
3278         if(g_race)
3279                 dprint(sprintf("%f %.6f\n", time, race_GetFractionalLapCount(self)));
3280         */
3281 }