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