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