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