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