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