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