]> icculus.org git repositories - divverent/nexuiz.git/blob - data/qcsrc/server/cl_client.qc
add foginterval to the csqc message
[divverent/nexuiz.git] / data / qcsrc / server / cl_client.qc
1 // let's abuse an existing field
2 #define SPAWNPOINT_SCORE frags
3
4 .float wantswelcomemessage;
5 .string netname_previous;
6
7 void spawnfunc_info_player_survivor (void)
8 {
9         spawnfunc_info_player_deathmatch();
10 }
11
12 void spawnfunc_info_player_start (void)
13 {
14         spawnfunc_info_player_deathmatch();
15 }
16
17 void spawnfunc_info_player_deathmatch (void)
18 {
19         self.classname = "info_player_deathmatch";
20         relocate_spawnpoint();
21 }
22
23 void spawnpoint_use()
24 {
25         if(teams_matter)
26         if(have_team_spawns)
27         {
28                 self.team = activator.team;
29                 some_spawn_has_been_used = 1;
30         }
31 };
32
33 // Returns:
34 //   -1 if a spawn can't be used
35 //   otherwise, a weight of the spawnpoint
36 float Spawn_Score(entity spot, entity playerlist, float teamcheck)
37 {
38         float shortest, thisdist;
39         entity player;
40
41         // filter out spots for the wrong team
42         if(teamcheck)
43         if(spot.team != teamcheck)
44                 return -1;
45
46         if(race_spawns)
47                 if(spot.target == "")
48                         return -1;
49
50         // filter out spots for assault
51         if(spot.target != "") {
52                 local entity ent;
53                 float good;
54                 ent = find(world, targetname, spot.target);
55                 while(ent) {
56                         if(ent.classname == "target_objective")
57                         {
58                                 if(ent.health < 0 || ent.health >= ASSAULT_VALUE_INACTIVE)
59                                         return -1;
60                                 good = 1;
61                         }
62                         else if(ent.classname == "trigger_race_checkpoint")
63                         {
64                                 if(self.classname == "player") // spectators may spawn everywhere
65                                 {
66                                         if(g_race_qualifying)
67                                         {
68                                                 // spawn at first
69                                                 if(ent.race_checkpoint != 0)
70                                                         return -1;
71                                                 if(spot.race_place != race_lowest_place_spawn)
72                                                         return -1;
73                                         }
74                                         else
75                                         {
76                                                 if(ent.race_checkpoint != race_PreviousCheckpoint(self.race_checkpoint))
77                                                         return -1;
78                                                 float pl;
79                                                 pl = self.race_place;
80                                                 if(pl > race_highest_place_spawn)
81                                                         pl = 0;
82                                                 if(spot.race_place != pl)
83                                                         return -1;
84                                         }
85                                 }
86                                 good = 1;
87                         }
88                         else
89                         {
90                         }
91                         ent = find(ent, targetname, spot.target);
92                 }
93
94                 if(!good)
95                         return -1;
96         }
97
98         player = playerlist;
99         shortest = vlen(world.maxs - world.mins);
100         for(player = playerlist; player; player = player.chain)
101                 if (player != self)
102                 {
103                         thisdist = vlen(player.origin - spot.origin);
104                         if (thisdist < shortest)
105                                 shortest = thisdist;
106                 }
107         return shortest;
108 }
109
110 float spawn_allbad;
111 float spawn_allgood;
112 entity Spawn_FilterOutBadSpots(entity firstspot, entity playerlist, float mindist, float teamcheck)
113 {
114         local entity spot, spotlist, spotlistend;
115         spawn_allgood = TRUE;
116         spawn_allbad = TRUE;
117
118         spotlist = world;
119         spotlistend = world;
120
121         for(spot = firstspot; spot; spot = spot.chain)
122         {
123                 spot.SPAWNPOINT_SCORE = Spawn_Score(spot, playerlist, teamcheck);
124
125                 if(cvar("spawn_debugview"))
126                 {
127                         setmodel(spot, "models/runematch/rune.mdl");
128                         if(spot.SPAWNPOINT_SCORE < mindist)
129                         {
130                                 spot.colormod = '1 0 0';
131                                 spot.scale = 1;
132                         }
133                         else
134                         {
135                                 spot.colormod = '0 1 0';
136                                 spot.scale = spot.SPAWNPOINT_SCORE / mindist;
137                         }
138                 }
139
140                 if(spot.SPAWNPOINT_SCORE >= 0) // spawning allowed here
141                 {
142                         if(spot.SPAWNPOINT_SCORE < mindist)
143                         {
144                                 // too short distance
145                                 spawn_allgood = FALSE;
146                         }
147                         else 
148                         {
149                                 // perfect
150                                 spawn_allbad = FALSE;
151
152                                 if(spotlistend)
153                                         spotlistend.chain = spot;
154                                 spotlistend = spot;
155                                 if(!spotlist)
156                                         spotlist = spot;
157
158                                 /*
159                                 if(teamcheck)
160                                 if(spot.team != teamcheck)
161                                         error("invalid spawn added");
162
163                                 print("added ", etos(spot), "\n");
164                                 */
165                         }
166                 }
167         }
168         if(spotlistend)
169                 spotlistend.chain = world;
170
171         /*
172                 entity e;
173                 if(teamcheck)
174                         for(e = spotlist; e; e = e.chain)
175                         {
176                                 print("seen ", etos(e), "\n");
177                                 if(e.team != teamcheck)
178                                         error("invalid spawn found");
179                         }
180         */
181
182         return spotlist;
183 }
184
185 entity Spawn_WeightedPoint(entity firstspot, float lower, float upper, float exponent)
186 {
187         // weight of a point: bound(lower, mindisttoplayer, upper)^exponent
188         // multiplied by spot.cnt (useful if you distribute many spawnpoints in a small area)
189         local entity spot;
190
191         RandomSelection_Init();
192         for(spot = firstspot; spot; spot = spot.chain)
193                 RandomSelection_Add(spot, 0, pow(bound(lower, spot.SPAWNPOINT_SCORE, upper), exponent) * spot.cnt, spot.SPAWNPOINT_SCORE >= lower);
194
195         return RandomSelection_chosen_ent;
196 }
197
198 /*
199 =============
200 SelectSpawnPoint
201
202 Finds a point to respawn
203 =============
204 */
205 entity SelectSpawnPoint (float anypoint)
206 {
207         local float teamcheck;
208         local entity firstspot_new;
209         local entity spot, firstspot, playerlist;
210
211         spot = find (world, classname, "testplayerstart");
212         if (spot)
213                 return spot;
214
215         teamcheck = 0;
216
217         if(!anypoint && have_team_spawns)
218                 teamcheck = self.team;
219
220         // get the list of players
221         playerlist = findchain(classname, "player");
222         // get the entire list of spots
223         firstspot = findchain(classname, "info_player_deathmatch");
224         // filter out the bad ones
225         // (note this returns the original list if none survived)
226         firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, 100, teamcheck);
227         if(!firstspot_new)
228                 firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, -1, teamcheck);
229         firstspot = firstspot_new;
230
231         // there is 50/50 chance of choosing a random spot or the furthest spot
232         // (this means that roughly every other spawn will be furthest, so you
233         // usually won't get fragged at spawn twice in a row)
234         if (arena_roundbased)
235         {
236                 firstspot_new = Spawn_FilterOutBadSpots(firstspot, playerlist, 800, teamcheck);
237                 if(firstspot_new)
238                         firstspot = firstspot_new;
239                 spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
240         }
241         else if (random() > cvar("g_spawn_furthest"))
242                 spot = Spawn_WeightedPoint(firstspot, 1, 1, 1);
243         else
244                 spot = Spawn_WeightedPoint(firstspot, 1, 5000, 5); // chooses a far far away spawnpoint
245
246         if(cvar("spawn_debugview"))
247         {
248                 print("spot mindistance: ", ftos(spot.SPAWNPOINT_SCORE), "\n");
249
250                 entity e;
251                 if(teamcheck)
252                         for(e = firstspot; e; e = e.chain)
253                                 if(e.team != teamcheck)
254                                         error("invalid spawn found");
255         }
256
257         if (!spot)
258         {
259                 if(cvar("spawn_debug"))
260                         GotoNextMap();
261                 else
262                 {
263                         if(some_spawn_has_been_used)
264                                 return world; // team can't spawn any more, because of actions of other team
265                         else
266                                 error("Cannot find a spawn point - please fix the map!");
267                 }
268         }
269
270         return spot;
271 }
272
273 /*
274 =============
275 CheckPlayerModel
276
277 Checks if the argument string can be a valid playermodel.
278 Returns a valid one in doubt.
279 =============
280 */
281 string FallbackPlayerModel = "models/player/marine.zym";
282 string CheckPlayerModel(string plyermodel) {
283         if(strlen(plyermodel) < 4)
284                 return FallbackPlayerModel;
285         if( substring(plyermodel,0,14) != "models/player/")
286                 return FallbackPlayerModel;
287         else if(cvar("sv_servermodelsonly"))
288         {
289                 if(substring(plyermodel,strlen(plyermodel)-4,4) != ".zym")
290                 if(substring(plyermodel,strlen(plyermodel)-4,4) != ".dpm")
291                 if(substring(plyermodel,strlen(plyermodel)-4,4) != ".md3")
292                 if(substring(plyermodel,strlen(plyermodel)-4,4) != ".psk")
293                         return FallbackPlayerModel;
294                 if(plyermodel != strtolower(plyermodel))
295                         return FallbackPlayerModel;
296                 if(!fexists(plyermodel))
297                         return FallbackPlayerModel;
298         }
299         return plyermodel;
300 }
301
302 /*
303 =============
304 Client_customizeentityforclient
305
306 LOD reduction
307 =============
308 */
309 float Client_customizeentityforclient()
310 {
311 #ifdef ALLOW_VARIABLE_LOD
312         // self: me
313         // other: the player viewing me
314         float distance;
315         float f;
316
317         if(self.flags & FL_NOTARGET) // we don't need LOD for spectators
318                 return TRUE;
319
320         if(other.cvar_cl_playerdetailreduction <= 0)
321         {
322                 if(other.cvar_cl_playerdetailreduction <= -2)
323                         self.modelindex = self.modelindex_lod2;
324                 else if(other.cvar_cl_playerdetailreduction <= -1)
325                         self.modelindex = self.modelindex_lod1;
326                 else
327                         self.modelindex = self.modelindex_lod0;
328         }
329         else
330         {
331                 distance = vlen(self.origin - other.origin);
332                 f = (distance + 100.0) * other.cvar_cl_playerdetailreduction;
333                 if(f > 10000)
334                         self.modelindex = self.modelindex_lod2;
335                 else if(f > 5000)
336                         self.modelindex = self.modelindex_lod1;
337                 else
338                         self.modelindex = self.modelindex_lod0;
339         }
340 #endif
341
342         return TRUE;
343 }
344
345 void UpdatePlayerSounds();
346 void setmodel_lod(entity e, string modelname)
347 {
348 #ifdef ALLOW_VARIABLE_LOD
349         string s;
350
351         // FIXME: this only supports 3-letter extensions
352         s = strcat(substring(modelname, 0, strlen(modelname) - 4), "_1", substring(modelname, 0, strlen(modelname) - 4));
353         if(fexists(s))
354         {
355                 precache_model(s);
356                 setmodel(e, s); // players have high precision
357                 self.modelindex_lod1 = self.modelindex;
358         }
359         else
360                 self.modelindex_lod1 = -1;
361
362         s = strcat(substring(modelname, 0, strlen(modelname) - 4), "_2", substring(modelname, 0, strlen(modelname) - 4));
363         if(fexists(s))
364         {
365                 precache_model(s);
366                 setmodel(e, s); // players have high precision
367                 self.modelindex_lod2 = self.modelindex;
368         }
369         else
370                 self.modelindex_lod2 = -1;
371
372         precache_model(modelname);
373         setmodel(e, modelname); // players have high precision
374         self.modelindex_lod0 = self.modelindex;
375
376         if(self.modelindex_lod1 < 0)
377                 self.modelindex_lod1 = self.modelindex;
378
379         if(self.modelindex_lod2 < 0)
380                 self.modelindex_lod2 = self.modelindex;
381 #else
382         precache_model(modelname);
383         setmodel(e, modelname); // players have high precision
384 #endif
385         player_setupanimsformodel();
386         UpdatePlayerSounds();
387 }
388
389 /*
390 =============
391 PutObserverInServer
392
393 putting a client as observer in the server
394 =============
395 */
396 void PutObserverInServer (void)
397 {
398         entity  spot;
399
400         race_PreSpawnObserver();
401
402         spot = SelectSpawnPoint (TRUE);
403         if(!spot)
404                 error("No spawnpoints for observers?!?\n");
405         RemoveGrapplingHook(self); // Wazat's Grappling Hook
406
407         if(clienttype(self) == CLIENTTYPE_REAL)
408         {
409                 msg_entity = self;
410                 WriteByte(MSG_ONE, SVC_SETVIEW);
411                 WriteEntity(MSG_ONE, self);
412         }
413
414         DropAllRunes(self);
415         kh_Key_DropAll(self, TRUE);
416
417         Portal_ClearAll(self);
418
419         if(self.flagcarried)
420                 DropFlag(self.flagcarried, 0);
421
422         WaypointSprite_PlayerDead();
423         
424         if(self.killcount != -666)
425         {
426                 if(g_lms)
427                 {
428                         if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
429                                 bprint ("^4", self.netname, "^4 has no more lives left\n");
430                         else
431                                 bprint ("^4", self.netname, "^4 is spectating now\n"); // TODO turn this into a proper forfeit?
432                 }
433                 else
434                         bprint ("^4", self.netname, "^4 is spectating now\n");
435         }
436
437         PlayerScore_Clear(self); // clear scores when needed
438
439         self.spectatortime = time;
440         
441         self.classname = "observer";
442         self.health = -666;
443         self.takedamage = DAMAGE_NO;
444         self.solid = SOLID_NOT;
445         self.movetype = MOVETYPE_NOCLIP;
446         self.flags = FL_CLIENT | FL_NOTARGET;
447         self.armorvalue = 666;
448         self.effects = 0;
449         self.armorvalue = cvar("g_balance_armor_start");
450         self.pauserotarmor_finished = 0;
451         self.pauserothealth_finished = 0;
452         self.pauseregen_finished = 0;
453         self.damageforcescale = 0;
454         self.death_time = 0;
455         self.dead_frame = 0;
456         self.alpha = 0;
457         self.scale = 0;
458         self.fade_time = 0;
459         self.pain_frame = 0;
460         self.pain_finished = 0;
461         self.strength_finished = 0;
462         self.invincible_finished = 0;
463         self.pushltime = 0;
464         self.think = SUB_Null;
465         self.nextthink = 0;
466         self.hook_time = 0;
467         self.runes = 0;
468         self.deadflag = DEAD_NO;
469         self.angles = spot.angles;
470         self.angles_z = 0;
471         self.fixangle = TRUE;
472         self.crouch = FALSE;
473
474         self.view_ofs = PL_VIEW_OFS;
475         setorigin (self, spot.origin);
476         setsize (self, '0 0 0', '0 0 0');
477         self.oldorigin = self.origin;
478         self.items = 0;
479         self.weapons = 0;
480         self.model = "";
481         self.modelindex = 0;
482         self.weapon = 0;
483         self.weaponmodel = "";
484         self.weaponentity = world;
485         self.killcount = -666;
486         self.velocity = '0 0 0';
487         self.avelocity = '0 0 0';
488         self.punchangle = '0 0 0';
489         self.punchvector = '0 0 0';
490         self.oldvelocity = self.velocity;
491         self.customizeentityforclient = Client_customizeentityforclient;
492         self.wantswelcomemessage = 1;
493
494         if(g_arena)
495         {
496                 if(self.version_mismatch)
497                 {
498                         Spawnqueue_Unmark(self);
499                         Spawnqueue_Remove(self);
500                 }
501                 else
502                 {
503                         Spawnqueue_Insert(self);
504                 }
505         }
506         else if(g_lms)
507         {
508                 // Only if the player cannot play at all
509                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) == 666)
510                         self.frags = -666;
511                 else
512                         self.frags = -667;
513         }
514         else
515                 self.frags = -666;
516 }
517
518 float RestrictSkin(float s)
519 {
520         if(!teams_matter)
521                 return s;
522         if(s == 6)
523                 return 6;
524         return mod(s, 3);
525 }
526
527 void FixPlayermodel()
528 {
529         local string defaultmodel;
530         local float defaultskin;
531         local vector m1, m2;
532
533         defaultmodel = "";
534
535         if(cvar("sv_defaultcharacter") == 1) {
536                 defaultskin = 0;
537
538                 if(teams_matter)
539                 {
540                         defaultmodel = cvar_string(strcat("sv_defaultplayermodel_", Team_ColorNameLowerCase(self.team)));
541                         defaultskin = cvar(strcat("sv_defaultplayerskin_", Team_ColorNameLowerCase(self.team)));
542                 }
543
544                 if(defaultmodel == "")
545                 {
546                         defaultmodel = cvar_string("sv_defaultplayermodel");
547                         defaultskin = cvar("sv_defaultplayerskin");
548                 }
549         }
550
551         if(defaultmodel != "")
552         {
553                 if (defaultmodel != self.model)
554                 {
555                         m1 = self.mins;
556                         m2 = self.maxs;
557                         setmodel_lod (self, defaultmodel);
558                         setsize (self, m1, m2);
559                 }
560
561                 self.skin = defaultskin;
562         } else {
563                 if (self.playermodel != self.model)
564                 {
565                         self.playermodel = CheckPlayerModel(self.playermodel);
566                         m1 = self.mins;
567                         m2 = self.maxs;
568                         setmodel_lod (self, self.playermodel);
569                         setsize (self, m1, m2);
570                 }
571
572                 self.skin = RestrictSkin(stof(self.playerskin));
573         }
574
575         if(!teams_matter)
576                 if(strlen(cvar_string("sv_defaultplayercolors")))
577                         if(self.clientcolors != cvar("sv_defaultplayercolors"))
578                                 setcolor(self, cvar("sv_defaultplayercolors"));
579 }
580
581 /*
582 =============
583 PutClientInServer
584
585 Called when a client spawns in the server
586 =============
587 */
588 //void() ctf_playerchanged;
589 void PutClientInServer (void)
590 {
591         if(clienttype(self) == CLIENTTYPE_BOT)
592         {
593                 self.classname = "player";
594         }
595         else if(clienttype(self) == CLIENTTYPE_REAL)
596         {
597                 msg_entity = self;
598                 WriteByte(MSG_ONE, SVC_SETVIEW);
599                 WriteEntity(MSG_ONE, self);
600         }
601
602         // player is dead and becomes observer
603         // FIXME fix LMS scoring for new system
604         if(g_lms)
605         {
606                 if(PlayerScore_Add(self, SP_LMS_RANK, 0) > 0)
607                         self.classname = "observer";
608         }
609
610         if(g_arena)
611         if(!self.spawned)
612                 self.classname = "observer";
613
614         if(self.classname == "player") {
615                 entity  spot;
616
617                 race_PreSpawn();
618
619                 spot = SelectSpawnPoint (FALSE);
620                 if(!spot)
621                 {
622                         centerprint(self, "Sorry, no spawnpoints available!\nHope your team can fix it...");
623                         return; // spawn failed
624                 }
625
626                 RemoveGrapplingHook(self); // Wazat's Grappling Hook
627
628                 self.classname = "player";
629                 self.iscreature = TRUE;
630                 self.movetype = MOVETYPE_WALK;
631                 self.solid = SOLID_SLIDEBOX;
632                 if(independent_players)
633                         MAKE_INDEPENDENT_PLAYER(self);
634                 self.flags = FL_CLIENT;
635                 self.takedamage = DAMAGE_AIM;
636                 if(g_minstagib)
637                         self.effects = EF_FULLBRIGHT;
638                 else
639                         self.effects = 0;
640                 self.air_finished = time + 12;
641                 self.dmg = 2;
642
643                 if(inWarmupStage)
644                 {
645                         self.ammo_shells = warmup_start_ammo_shells;
646                         self.ammo_nails = warmup_start_ammo_nails;
647                         self.ammo_rockets = warmup_start_ammo_rockets;
648                         self.ammo_cells = warmup_start_ammo_cells;
649                         self.health = warmup_start_health;
650                         self.armorvalue = warmup_start_armorvalue;
651                         self.weapons = warmup_start_weapons;
652                 }
653                 else
654                 {
655                         self.ammo_shells = start_ammo_shells;
656                         self.ammo_nails = start_ammo_nails;
657                         self.ammo_rockets = start_ammo_rockets;
658                         self.ammo_cells = start_ammo_cells;
659                         self.health = start_health;
660                         self.armorvalue = start_armorvalue;
661                         self.weapons = start_weapons;
662                 }
663                 self.items = start_items;
664                 self.switchweapon = w_getbestweapon(self);
665                 self.cnt = self.switchweapon;
666                 self.weapon = 0;
667                 self.jump_interval = time;
668
669                 self.spawnshieldtime = time + cvar("g_spawnshieldtime");
670                 self.pauserotarmor_finished = time + cvar("g_balance_pause_armor_rot_spawn");
671                 self.pauserothealth_finished = time + cvar("g_balance_pause_health_rot_spawn");
672                 self.pauseregen_finished = time + cvar("g_balance_pause_health_regen_spawn");
673                 //extend the pause of rotting if client was reset at the beginning of the countdown
674                 if(!cvar("sv_ready_restart_after_countdown") && time < restart_countdown) {
675                         self.spawnshieldtime += RESTART_COUNTDOWN;
676                         self.pauserotarmor_finished += RESTART_COUNTDOWN;
677                         self.pauserothealth_finished += RESTART_COUNTDOWN;
678                         self.pauseregen_finished += RESTART_COUNTDOWN;
679                 }
680                 self.damageforcescale = 2;
681                 self.death_time = 0;
682                 self.dead_frame = 0;
683                 self.alpha = 0;
684                 self.scale = 0;
685                 self.fade_time = 0;
686                 self.pain_frame = 0;
687                 self.pain_finished = 0;
688                 self.strength_finished = 0;
689                 self.invincible_finished = 0;
690                 self.pushltime = 0;
691                 //self.speed_finished = 0;
692                 //self.slowmo_finished = 0;
693                 // players have no think function
694                 self.think = SUB_Null;
695                 self.nextthink = 0;
696                 self.hook_time = 0;
697
698                 self.runes = 0;
699
700                 self.deadflag = DEAD_NO;
701
702                 self.angles = spot.angles;
703
704                 self.angles_z = 0; // never spawn tilted even if the spot says to
705                 self.fixangle = TRUE; // turn this way immediately
706                 self.velocity = '0 0 0';
707                 self.avelocity = '0 0 0';
708                 self.punchangle = '0 0 0';
709                 self.punchvector = '0 0 0';
710                 self.oldvelocity = self.velocity;
711
712                 msg_entity = self;
713                 WRITESPECTATABLE_MSG_ONE({
714                         WriteByte(MSG_ONE, SVC_TEMPENTITY);
715                         WriteByte(MSG_ONE, TE_CSQC_SPAWN);
716                 });
717
718                 self.customizeentityforclient = Client_customizeentityforclient;
719
720                 self.model = "";
721                 FixPlayermodel();
722
723                 self.crouch = FALSE;
724                 self.view_ofs = PL_VIEW_OFS;
725                 setsize (self, PL_MIN, PL_MAX);
726                 self.spawnorigin = spot.origin;
727                 setorigin (self, spot.origin + '0 0 1' * (1 - self.mins_z - 24));
728                 // don't reset back to last position, even if new position is stuck in solid
729                 self.oldorigin = self.origin;
730
731                 if(g_arena)
732                 {
733                         Spawnqueue_Remove(self);
734                         Spawnqueue_Mark(self);
735                 }
736
737                 self.event_damage = PlayerDamage;
738
739                 self.bot_attack = TRUE;
740
741                 self.statdraintime = time + 5;
742                 self.BUTTON_ATCK = self.BUTTON_JUMP = self.BUTTON_ATCK2 = 0;
743
744                 if(self.killcount == -666) {
745                         PlayerScore_Clear(self);
746                         self.killcount = 0;
747                         self.frags = 0;
748                 }
749
750                 self.cnt = WEP_LASER;
751                 self.nixnex_lastchange_id = -1;
752
753                 CL_SpawnWeaponentity();
754                 self.alpha = default_player_alpha;
755                 self.colormod = '1 1 1' * cvar("g_player_brightness");
756                 self.exteriorweaponentity.alpha = default_weapon_alpha;
757
758                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
759                 self.lms_traveled_distance = 0;
760                 self.speedrunning = FALSE;
761
762                 race_PostSpawn(spot);
763
764                 if(cvar("spawn_debug"))
765                 {
766                         sprint(self, strcat("spawnpoint origin:  ", vtos(spot.origin), "\n"));
767                         remove(spot);   // usefull for checking if there are spawnpoints, that let drop through the floor
768                 }
769
770                 //stuffcmd(self, "chase_active 0");
771                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
772
773                 if (cvar("g_spawnsound"))
774                         sound (self, CHAN_TRIGGER, "misc/spawn.wav", VOL_BASE, ATTN_NORM);
775
776                 if(g_assault) {
777                         if(self.team == assault_attacker_team)
778                                 centerprint(self, "You are attacking!\n");
779                         else
780                                 centerprint(self, "You are defending!\n");
781                 }
782
783         } else if(self.classname == "observer") {
784                 PutObserverInServer ();
785         }
786
787         //if(g_ctf)
788         //      ctf_playerchanged();
789 }
790
791 /*
792 =============
793 SendCSQCInfo
794
795 Send whatever CSQC needs NOW and cannot wait for SendServerInfo to happen...
796 =============
797 */
798 void SendCSQCInfo(void)
799 {
800         float i;
801         if(clienttype(self) != CLIENTTYPE_REAL)
802                 return;
803         msg_entity = self;
804         WriteByte(MSG_ONE, SVC_TEMPENTITY);
805         WriteByte(MSG_ONE, TE_CSQC_INIT);
806         WriteShort(MSG_ONE, CSQC_REVISION);
807         WriteByte(MSG_ONE, maxclients);
808         for(i = 1; i <= 24; ++i)
809                 WriteByte(MSG_ONE, (get_weaponinfo(i)).impulse + 1);
810 }
811
812 /*
813 =============
814 SetNewParms
815 =============
816 */
817 void SetNewParms (void)
818 {
819         // initialize parms for a new player
820         parm1 = -(86400 * 366);
821 }
822
823 /*
824 =============
825 SetChangeParms
826 =============
827 */
828 void SetChangeParms (void)
829 {
830         // save parms for level change
831         parm1 = self.parm_idlesince - time;
832 }
833
834 /*
835 =============
836 DecodeLevelParms
837 =============
838 */
839 void DecodeLevelParms (void)
840 {
841         // load parms
842         self.parm_idlesince = parm1;
843         if(self.parm_idlesince == -(86400 * 366))
844                 self.parm_idlesince = time;
845 }
846
847 /*
848 =============
849 ClientKill
850
851 Called when a client types 'kill' in the console
852 =============
853 */
854
855 void ClientKill_Now_TeamChange()
856 {
857         if(self.killindicator_teamchange == -1)
858         {
859                 self.team = -1;
860                 JoinBestTeam( self, FALSE, FALSE );
861         }
862         else
863         {
864                 SV_ChangeTeam(self.killindicator_teamchange - 1);
865         }
866 }
867
868 void ClientKill_Now()
869 {
870         if(self.killindicator_teamchange)
871                 ClientKill_Now_TeamChange();
872
873         // in any case:
874         Damage(self, self, self, 100000, DEATH_KILL, self.origin, '0 0 0');
875
876         if(self.killindicator)
877         {
878                 dprint("Cleaned up after a leaked kill indicator.\n");
879                 remove(self.killindicator);
880                 self.killindicator = world;
881         }
882 }
883 void KillIndicator_Think()
884 {
885         if (!self.owner.modelindex)
886         {
887                 self.owner.killindicator = world;
888                 remove(self);
889                 return;
890         }
891
892         if(self.cnt <= 0)
893         {
894                 self = self.owner;
895                 ClientKill_Now(); // no oldself needed
896                 return;
897         }
898         else
899         {
900                 if(self.cnt <= 10)
901                         setmodel(self, strcat("models/sprites/", ftos(self.cnt), ".spr32"));
902                 if(clienttype(self.owner) == CLIENTTYPE_REAL)
903                 {
904                         if(self.cnt <= 10)
905                                 announce(self.owner, strcat("announcer/robotic/", ftos(self.cnt), ".ogg"));
906                         if(self.owner.killindicator_teamchange)
907                         {
908                                 if(self.owner.killindicator_teamchange == -1)
909                                         centerprint(self.owner, strcat("Changing team in ", ftos(self.cnt), " seconds"));
910                                 else
911                                         centerprint(self.owner, strcat("Changing to ", ColoredTeamName(self.owner.killindicator_teamchange), " in ", ftos(self.cnt), " seconds"));
912                         }
913                         else
914                                 centerprint(self.owner, strcat("^1Suicide in ", ftos(self.cnt), " seconds"));
915                 }
916                 self.nextthink = time + 1;
917                 self.cnt -= 1;
918         }
919 }
920
921 void ClientKill_TeamChange (float targetteam) // 0 = don't change, -1 = auto
922 {
923         float killtime;
924         entity e;
925         killtime = cvar("g_balance_kill_delay");
926
927         self.killindicator_teamchange = targetteam;
928
929         if(!self.killindicator)
930         {
931                 if(killtime <= 0 || !self.modelindex || self.deadflag != DEAD_NO)
932                 {
933                         ClientKill_Now();
934                 }
935                 else
936                 {
937                         self.killindicator = spawn();
938                         self.killindicator.owner = self;
939                         self.killindicator.scale = 0.5;
940                         setattachment(self.killindicator, self, "");
941                         setorigin(self.killindicator, '0 0 52');
942                         self.killindicator.think = KillIndicator_Think;
943                         self.killindicator.nextthink = time + (self.lip) * 0.05;
944                         self.killindicator.cnt = ceil(killtime);
945                         self.killindicator.count = bound(0, ceil(killtime), 10);
946                         sprint(self, strcat("^1You'll be dead in ", ftos(self.killindicator.cnt), " seconds\n"));
947
948                         for(e = world; (e = find(e, classname, "body")) != world; )
949                         {
950                                 if(e.enemy != self)
951                                         continue;
952                                 e.killindicator = spawn();
953                                 e.killindicator.owner = e;
954                                 e.killindicator.scale = 0.5;
955                                 setattachment(e.killindicator, e, "");
956                                 setorigin(e.killindicator, '0 0 52');
957                                 e.killindicator.think = KillIndicator_Think;
958                                 e.killindicator.nextthink = time + (e.lip) * 0.05;
959                                 e.killindicator.cnt = ceil(killtime);
960                         }
961                         self.lip = 0;
962                 }
963         }
964         if(self.killindicator)
965         {
966                 if(targetteam)
967                         self.killindicator.colormod = TeamColor(targetteam);
968                 else
969                         self.killindicator.colormod = '0 0 0';
970         }
971 }
972
973 void ClientKill (void)
974 {
975         ClientKill_TeamChange(0);
976 }
977
978 void DoTeamChange(float destteam)
979 {
980         float t, c0;
981         if(!cvar("teamplay"))
982         {
983                 if(destteam >= 0)
984                         SetPlayerColors(self, destteam);
985                 return;
986         }
987         if(self.classname == "player")
988         if(destteam == -1)
989         {
990                 CheckAllowedTeams(self);
991                 t = FindSmallestTeam(self, TRUE);
992                 switch(self.team)
993                 {
994                         case COLOR_TEAM1: c0 = c1; break;
995                         case COLOR_TEAM2: c0 = c2; break;
996                         case COLOR_TEAM3: c0 = c3; break;
997                         case COLOR_TEAM4: c0 = c4; break;
998                         default:          c0 = 999;
999                 }
1000                 switch(t)
1001                 {
1002                         case 1:
1003                                 if(c0 > c1)
1004                                         destteam = COLOR_TEAM1;
1005                                 break;
1006                         case 2:
1007                                 if(c0 > c2)
1008                                         destteam = COLOR_TEAM2;
1009                                 break;
1010                         case 3:
1011                                 if(c0 > c3)
1012                                         destteam = COLOR_TEAM3;
1013                                 break;
1014                         case 4:
1015                                 if(c0 > c4)
1016                                         destteam = COLOR_TEAM4;
1017                                 break;
1018                 }
1019                 if(destteam == -1)
1020                         return;
1021         }
1022         if(destteam == self.team && !self.killindicator)
1023                 return;
1024         ClientKill_TeamChange(destteam);
1025 }
1026
1027 void FixClientCvars(entity e)
1028 {
1029         // send prediction settings to the client
1030         stuffcmd(e, "\nin_bindmap 0 0\n");
1031         /*
1032          * we no longer need to stuff this. Remove this comment block if you feel 
1033          * 2.3 and higher (or was it 2.2.3?) don't need these any more
1034         stuffcmd(e, strcat("cl_gravity ", ftos(cvar("sv_gravity")), "\n"));
1035         stuffcmd(e, strcat("cl_movement_accelerate ", ftos(cvar("sv_accelerate")), "\n"));
1036         stuffcmd(e, strcat("cl_movement_friction ", ftos(cvar("sv_friction")), "\n"));
1037         stuffcmd(e, strcat("cl_movement_maxspeed ", ftos(cvar("sv_maxspeed")), "\n"));
1038         stuffcmd(e, strcat("cl_movement_airaccelerate ", ftos(cvar("sv_airaccelerate")), "\n"));
1039         stuffcmd(e, strcat("cl_movement_maxairspeed ", ftos(cvar("sv_maxairspeed")), "\n"));
1040         stuffcmd(e, strcat("cl_movement_stopspeed ", ftos(cvar("sv_stopspeed")), "\n"));
1041         stuffcmd(e, strcat("cl_movement_jumpvelocity ", ftos(cvar("sv_jumpvelocity")), "\n"));
1042         stuffcmd(e, strcat("cl_movement_stepheight ", ftos(cvar("sv_stepheight")), "\n"));
1043         stuffcmd(e, strcat("set cl_movement_friction_on_land ", ftos(cvar("sv_friction_on_land")), "\n"));
1044         stuffcmd(e, strcat("set cl_movement_airaccel_qw ", ftos(cvar("sv_airaccel_qw")), "\n"));
1045         stuffcmd(e, strcat("set cl_movement_airaccel_sideways_friction ", ftos(cvar("sv_airaccel_sideways_friction")), "\n"));
1046         stuffcmd(e, "cl_movement_edgefriction 1\n");
1047          */
1048 }
1049
1050 .float fog_set;
1051 void SendFog()
1052 {
1053         if(world.fog) // NOT string_null!
1054         {
1055                 if(!self.fog_set)
1056                 {
1057                         if(sv_foginterval)
1058                         {
1059                                 msg_entity = self;
1060                                 WriteByte(MSG_ONE, SVC_TEMPENTITY);
1061                                 WriteByte(MSG_ONE, TE_CSQC_FOG);
1062                                 WriteCoord(MSG_ONE, sv_foginterval);
1063                                 WriteString(MSG_ONE, world.fog);
1064                         }
1065                         else
1066                                 // set it once
1067                                 stuffcmd(self, strcat("\nfog ", world.fog, "\nr_fog_exp2 0\nr_drawfog 1\n"));
1068                 }
1069                 self.fog_set = 1;
1070         }
1071 }
1072
1073 /*
1074 =============
1075 ClientConnect
1076
1077 Called when a client connects to the server
1078 =============
1079 */
1080 //void ctf_clientconnect();
1081 string ColoredTeamName(float t);
1082 void DecodeLevelParms (void);
1083 //void dom_player_join_team(entity pl);
1084 void ClientConnect (void)
1085 {
1086         local string s;
1087
1088         if(self.flags & FL_CLIENT)
1089         {
1090                 print("Warning: ClientConnect, but already connected!\n");
1091                 return;
1092         }
1093
1094         if(Ban_MaybeEnforceBan(self))
1095                 return;
1096
1097         DecodeLevelParms();
1098
1099         self.classname = "player_joining";
1100
1101         self.flags = self.flags | FL_CLIENT;
1102         self.version_nagtime = time + 10 + random() * 10;
1103
1104         if(player_count<0)
1105         {
1106                 dprint("BUG player count is lower than zero, this cannot happen!\n");
1107                 player_count = 0;
1108         }
1109
1110         PlayerScore_Attach(self);
1111
1112         bot_clientconnect();
1113
1114         race_PreSpawnObserver();
1115
1116         //if(g_domination)
1117         //      dom_player_join_team(self);
1118
1119         //JoinBestTeam(self, FALSE, FALSE);
1120         //
1121         if((cvar("sv_spectate") == 1 && !g_lms) || cvar("g_campaign")) {
1122                 self.classname = "observer";
1123         } else {
1124                 self.classname = "player";
1125                 campaign_bots_may_start = 1;
1126         }
1127
1128         self.playerid = (playerid_last = playerid_last + 1);
1129         if(cvar("sv_eventlog"))
1130         {
1131                 if(clienttype(self) == CLIENTTYPE_REAL)
1132                         GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":", self.netaddress, ":", self.netname));
1133                 else
1134                         GameLogEcho(strcat(":join:", ftos(self.playerid), ":", ftos(num_for_edict(self)), ":bot:", self.netname));
1135                 s = strcat(":team:", ftos(self.playerid), ":");
1136                 s = strcat(s, ftos(self.team));
1137                 GameLogEcho(s);
1138         }
1139         self.netname_previous = strzone(self.netname);
1140
1141         //stuffcmd(self, "set tmpviewsize $viewsize \n");
1142
1143         bprint ("^4",self.netname);
1144         bprint ("^4 connected");
1145
1146         if(g_domination || g_ctf)
1147         {
1148                 bprint(" and joined the ");
1149                 bprint(ColoredTeamName(self.team));
1150         }
1151
1152         bprint("\n");
1153
1154         self.welcomemessage_time = 0;
1155
1156         stuffcmd(self, strcat(clientstuff, "\n"));
1157         stuffcmd(self, strcat("exec maps/", mapname, ".cfg\n"));
1158         stuffcmd(self, "cl_particles_reloadeffects\n");
1159
1160         FixClientCvars(self);
1161
1162         // spawnfunc_waypoint sprites
1163         WaypointSprite_InitClient(self);
1164
1165         // Wazat's grappling hook
1166         SetGrappleHookBindings();
1167
1168         // get autoswitch state from player when he toggles it
1169         stuffcmd(self, "alias autoswitch \"set cl_autoswitch $1 ; cmd autoswitch $1\"\n"); // default.cfg-ed in 2.4.1
1170
1171         // get version info from player
1172         stuffcmd(self, "cmd clientversion $gameversion\n");
1173
1174         // get other cvars from player
1175         GetCvars(0);
1176
1177         // set cvar for team scoreboard
1178         if (teams_matter)
1179         {
1180                 local float t;
1181                 t = cvar("teamplay");
1182                 // we have to stuff the correct teamplay value because if this is a listen server, this changes the teamplay mode of the server itself, which is bad
1183                 stuffcmd(self, strcat("set teamplay ", ftos(t), "\n"));
1184         }
1185         else
1186                 stuffcmd(self, "set teamplay 0\n");
1187
1188         // notify about available teams
1189         if(teamplay)
1190         {
1191                 CheckAllowedTeams(self);
1192                 t = 0; if(c1 >= 0) t |= 1; if(c2 >= 0) t |= 2; if(c3 >= 0) t |= 4; if(c4 >= 0) t |= 8;
1193                 stuffcmd(self, strcat("set _teams_available ", ftos(t), "\n"));
1194         }
1195         else
1196                 stuffcmd(self, "set _teams_available 0\n");
1197
1198         stuffcmd(self, strcat("set gametype ", ftos(game), "\n"));
1199
1200         if(g_arena)
1201         {
1202                 self.classname = "observer";
1203                 Spawnqueue_Insert(self);
1204         }
1205         /*else if(g_ctf)
1206         {
1207                 ctf_clientconnect();
1208         }*/
1209
1210         if(entcs_start)
1211                 attach_entcs();
1212
1213         bot_relinkplayerlist();
1214
1215         self.spectatortime = time;
1216         if(blockSpectators)
1217         {
1218                 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"));
1219         }
1220
1221         self.jointime = time;
1222         self.allowedTimeouts = cvar("sv_timeout_number");
1223
1224         if(clienttype(self) == CLIENTTYPE_REAL)
1225         {
1226                 sprint(self, strcat("nexuiz-csqc protocol ", ftos(CSQC_REVISION), "\n"));
1227                 SendCSQCInfo();
1228                 msg_entity = self;
1229                 if(mapvote_initialized && !cvar("g_maplist_textonly"))
1230                 {
1231                         MapVote_SendData(MSG_ONE);
1232                         MapVote_UpdateData(MSG_ONE);
1233                 }
1234                 ScoreInfo_Write(MSG_ONE);
1235         }
1236
1237         if(inWarmupStage)
1238         {
1239                 msg_entity = self;
1240                 WriteByte(MSG_ONE, SVC_TEMPENTITY);
1241                 WriteByte(MSG_ONE, TE_CSQC_WARMUP);
1242                 WriteByte(MSG_ONE, 1);
1243         }
1244
1245         if(g_lms)
1246         {
1247                 if(PlayerScore_Add(self, SP_LMS_LIVES, LMS_NewPlayerLives()) <= 0)
1248                 {
1249                         PlayerScore_Add(self, SP_LMS_RANK, 666);
1250                         self.frags = -666; // FIXME do we still need this?
1251                 }
1252         }
1253
1254         SendFog();
1255 }
1256
1257 /*
1258 =============
1259 ClientDisconnect
1260
1261 Called when a client disconnects from the server
1262 =============
1263 */
1264 .entity chatbubbleentity;
1265 .entity teambubbleentity;
1266 void ReadyCount();
1267 //void() ctf_clientdisconnect;
1268 void ClientDisconnect (void)
1269 {
1270         float save;
1271
1272         if not(self.flags & FL_CLIENT)
1273         {
1274                 print("Warning: ClientDisconnect without ClientConnect\n");
1275                 return;
1276         }
1277
1278         bot_clientdisconnect();
1279
1280         if(entcs_start)
1281                 detach_entcs();
1282         
1283         if(cvar("sv_eventlog"))
1284                 GameLogEcho(strcat(":part:", ftos(self.playerid)));
1285         bprint ("^4",self.netname);
1286         bprint ("^4 disconnected\n");
1287
1288         if (self.chatbubbleentity)
1289         {
1290                 remove (self.chatbubbleentity);
1291                 self.chatbubbleentity = world;
1292         }
1293
1294         if (self.teambubbleentity)
1295         {
1296                 remove (self.teambubbleentity);
1297                 self.teambubbleentity = world;
1298         }
1299
1300         if (self.killindicator)
1301         {
1302                 remove (self.killindicator);
1303                 self.killindicator = world;
1304         }
1305
1306         WaypointSprite_PlayerGone();
1307
1308         DropAllRunes(self);
1309         kh_Key_DropAll(self, TRUE);
1310
1311         Portal_ClearAll(self);
1312
1313         if(self.flagcarried)
1314                 DropFlag(self.flagcarried, 0);
1315
1316         save = self.flags;
1317         self.flags = self.flags - (self.flags & FL_CLIENT);
1318         bot_relinkplayerlist();
1319         self.flags = save;
1320
1321         // remove laserdot
1322         if(self.weaponentity)
1323                 if(self.weaponentity.lasertarget)
1324                         remove(self.weaponentity.lasertarget);
1325
1326         if(g_arena)
1327         {
1328                 Spawnqueue_Unmark(self);
1329                 Spawnqueue_Remove(self);
1330         }
1331         /*if(g_ctf)
1332         {
1333                 ctf_clientdisconnect();
1334         }
1335         */
1336
1337         PlayerScore_Detach(self);
1338
1339         if(self.netname_previous)
1340                 strunzone(self.netname_previous);
1341
1342         ClearPlayerSounds();
1343
1344         // free cvars
1345         GetCvars(-1);
1346         self.playerid = 0;
1347
1348         ReadyCount();
1349 }
1350
1351 .float BUTTON_CHAT;
1352 void ChatBubbleThink()
1353 {
1354         self.nextthink = time;
1355         if (!self.owner.modelindex || self.owner.chatbubbleentity != self)
1356         {
1357                 self.owner.chatbubbleentity = world;
1358                 remove(self);
1359                 return;
1360         }
1361         setorigin(self, self.owner.origin + '0 0 15' + self.owner.maxs_z * '0 0 1');
1362         if (self.owner.BUTTON_CHAT && !self.owner.deadflag)
1363                 self.model = self.mdl;
1364         else
1365                 self.model = "";
1366 };
1367
1368 void UpdateChatBubble()
1369 {
1370         if (!self.modelindex)
1371                 return;
1372         // spawn a chatbubble entity if needed
1373         if (!self.chatbubbleentity)
1374         {
1375                 self.chatbubbleentity = spawn();
1376                 self.chatbubbleentity.owner = self;
1377                 self.chatbubbleentity.exteriormodeltoclient = self;
1378                 self.chatbubbleentity.think = ChatBubbleThink;
1379                 self.chatbubbleentity.nextthink = time;
1380                 setmodel(self.chatbubbleentity, "models/misc/chatbubble.spr"); // precision set below
1381                 setorigin(self.chatbubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1382                 self.chatbubbleentity.mdl = self.chatbubbleentity.model;
1383                 self.chatbubbleentity.model = "";
1384                 self.chatbubbleentity.effects = EF_LOWPRECISION;
1385         }
1386 }
1387
1388
1389 void TeamBubbleThink()
1390 {
1391         self.nextthink = time;
1392         if (!self.owner.modelindex || self.owner.teambubbleentity != self)
1393         {
1394                 self.owner.teambubbleentity = world;
1395                 remove(self);
1396                 return;
1397         }
1398 //      setorigin(self, self.owner.origin + '0 0 15' + self.owner.maxs_z * '0 0 1');  // bandwidth hog. setattachment does this now
1399         if (self.owner.BUTTON_CHAT || self.owner.deadflag || self.owner.killindicator)
1400                 self.model = "";
1401         else
1402                 self.model = self.mdl;
1403
1404 };
1405
1406 float TeamBubble_customizeentityforclient()
1407 {
1408         return (self.owner != other && self.owner.team == other.team && other.killcount > -666);
1409 }
1410
1411 void UpdateTeamBubble()
1412 {
1413         if (!self.modelindex || !cvar("teamplay"))
1414                 return;
1415         // spawn a teambubble entity if needed
1416         if (!self.teambubbleentity && cvar("teamplay"))
1417         {
1418                 self.teambubbleentity = spawn();
1419                 self.teambubbleentity.owner = self;
1420                 self.teambubbleentity.exteriormodeltoclient = self;
1421                 self.teambubbleentity.think = TeamBubbleThink;
1422                 self.teambubbleentity.nextthink = time;
1423                 setmodel(self.teambubbleentity, "models/misc/teambubble.spr"); // precision set below
1424 //              setorigin(self.teambubbleentity, self.origin + '0 0 15' + self.maxs_z * '0 0 1');
1425                 setorigin(self.teambubbleentity, self.teambubbleentity.origin + '0 0 15' + self.maxs_z * '0 0 1');
1426                 setattachment(self.teambubbleentity, self, "");  // sticks to moving player better, also conserves bandwidth
1427                 self.teambubbleentity.mdl = self.teambubbleentity.model;
1428                 self.teambubbleentity.model = self.teambubbleentity.mdl;
1429                 self.teambubbleentity.customizeentityforclient = TeamBubble_customizeentityforclient;
1430                 self.teambubbleentity.effects = EF_LOWPRECISION;
1431         }
1432 }
1433
1434 // LordHavoc: this hack will be removed when proper _pants/_shirt layers are
1435 // added to the model skins
1436 /*void UpdateColorModHack()
1437 {
1438         local float c;
1439         c = self.clientcolors & 15;
1440         // LordHavoc: only bothering to support white, green, red, yellow, blue
1441              if (teamplay == 0) self.colormod = '0 0 0';
1442         else if (c ==  0) self.colormod = '1.00 1.00 1.00';
1443         else if (c ==  3) self.colormod = '0.10 1.73 0.10';
1444         else if (c ==  4) self.colormod = '1.73 0.10 0.10';
1445         else if (c == 12) self.colormod = '1.22 1.22 0.10';
1446         else if (c == 13) self.colormod = '0.10 0.10 1.73';
1447         else self.colormod = '1 1 1';
1448 };*/
1449
1450 void respawn(void)
1451 {
1452         CopyBody(1);
1453         self.effects |= EF_NODRAW; // prevent another CopyBody
1454         PutClientInServer();
1455 }
1456
1457 /**
1458  * When sv_timeout is used this function returs strings like
1459  * "Timeout begins in 2 seconds!\n" or "Timeout ends in 23 seconds!\n".
1460  * Called by centerprint functions
1461  * @param addOneSecond boolean, set to 1 if the welcome-message centerprint asks for the text
1462  */
1463 string getTimeoutText(float addOneSecond) {
1464         if (!cvar("sv_timeout") || !timeoutStatus)
1465                 return "";
1466
1467         local string retStr;
1468         if (timeoutStatus == 1) {
1469                 if (addOneSecond == 1) {
1470                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime + 1), " seconds!\n");
1471                 }
1472                 else {
1473                         retStr = strcat("Timeout begins in ", ftos(remainingLeadTime), " seconds!\n");
1474                 }
1475                 return retStr;
1476         }
1477         else if (timeoutStatus == 2) {
1478                 if (addOneSecond) {
1479                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime + 1), " seconds!\n");
1480                         //don't show messages like "Timeout ends in 0 seconds"...
1481                         if ((remainingTimeoutTime + 1) > 0)
1482                                 return retStr;
1483                         else
1484                                 return "";
1485                 }
1486                 else {
1487                         retStr = strcat("Timeout ends in ", ftos(remainingTimeoutTime), " seconds!\n");
1488                         //don't show messages like "Timeout ends in 0 seconds"...
1489                         if (remainingTimeoutTime > 0)
1490                                 return retStr;
1491                         else
1492                                 return "";
1493                 }
1494         }
1495         else return "";
1496 }
1497
1498 void player_powerups (void)
1499 {
1500         if (g_minstagib)
1501         {
1502                 if (self.items & IT_STRENGTH)
1503                 {
1504                         if (time > self.strength_finished)
1505                         {
1506                                 if (g_minstagib_invis_alpha > 0)
1507                                 {
1508                                         self.alpha = default_player_alpha;
1509                                         self.exteriorweaponentity.alpha = default_weapon_alpha;
1510                                         self.effects = self.effects | EF_FULLBRIGHT;
1511                                 }
1512                                 else
1513                                 {
1514                                         self.effects -= self.effects & EF_NODRAW;
1515                                 }
1516                                 self.items = self.items - (self.items & IT_STRENGTH);
1517                                 sprint(self, "^3Invisibility has worn off\n");
1518                         }
1519                 }
1520                 else
1521                 {
1522                         if (time < self.strength_finished)
1523                         {
1524                                 if (g_minstagib_invis_alpha > 0)
1525                                 {
1526                                         self.alpha = g_minstagib_invis_alpha;
1527                                         self.exteriorweaponentity.alpha = g_minstagib_invis_alpha;
1528                                         self.effects -= self.effects & EF_FULLBRIGHT;
1529                                 }
1530                                 else
1531                                 {
1532                                         self.effects = self.effects | EF_NODRAW;
1533                                 }
1534                                 self.items = self.items | IT_STRENGTH;
1535                                 sprint(self, "^3You are invisible\n");
1536                         }
1537                 }
1538
1539                 if (self.items & IT_INVINCIBLE)
1540                 {
1541                         if (time > self.invincible_finished)
1542                         {
1543                                 self.items = self.items - (self.items & IT_INVINCIBLE);
1544                                 sprint(self, "^3Speed has worn off\n");
1545                         }
1546                 }
1547                 else
1548                 {
1549                         if (time < self.invincible_finished)
1550                         {
1551                                 self.items = self.items | IT_INVINCIBLE;
1552                                 sprint(self, "^3You are on speed\n");
1553                         }
1554                 }
1555                 return;
1556         }
1557
1558         self.effects = self.effects - (self.effects & (EF_RED | EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT));
1559         if (self.items & IT_STRENGTH)
1560         {
1561                 self.effects = self.effects | (EF_BLUE | EF_ADDITIVE | EF_FULLBRIGHT);
1562                 if (time > self.strength_finished)
1563                 {
1564                         self.items = self.items - (self.items & IT_STRENGTH);
1565                         sprint(self, "^3Strength has worn off\n");
1566                 }
1567         }
1568         else
1569         {
1570                 if (time < self.strength_finished)
1571                 {
1572                         self.items = self.items | IT_STRENGTH;
1573                         sprint(self, "^3Strength infuses your weapons with devastating power\n");
1574                 }
1575         }
1576         if (self.items & IT_INVINCIBLE)
1577         {
1578                 self.effects = self.effects | (EF_RED | EF_ADDITIVE | EF_FULLBRIGHT);
1579                 if (time > self.invincible_finished)
1580                 {
1581                         self.items = self.items - (self.items & IT_INVINCIBLE);
1582                         sprint(self, "^3Shield has worn off\n");
1583                 }
1584         }
1585         else
1586         {
1587                 if (time < self.invincible_finished)
1588                 {
1589                         self.items = self.items | IT_INVINCIBLE;
1590                         sprint(self, "^3Shield surrounds you\n");
1591                 }
1592         }
1593
1594         if (cvar("g_fullbrightplayers"))
1595                 self.effects = self.effects | EF_FULLBRIGHT;
1596
1597         // midair gamemode: damage only while in the air
1598         // if in midair mode, being on ground grants temporary invulnerability
1599         // (this is so that multishot weapon don't clear the ground flag on the
1600         // first damage in the frame, leaving the player vulnerable to the
1601         // remaining hits in the same frame)
1602         if (self.flags & FL_ONGROUND)
1603         if (g_midair)
1604                 self.spawnshieldtime = max(self.spawnshieldtime, time + cvar("g_midair_shieldtime"));
1605
1606         if (time > restart_countdown)
1607         if (time < self.spawnshieldtime)
1608                 self.effects = self.effects | (EF_ADDITIVE | EF_FULLBRIGHT);
1609 }
1610
1611 float CalcRegen(float current, float stable, float regenfactor)
1612 {
1613         if(current > stable)
1614                 return current;
1615         else if(current > stable - 0.25) // when close enough, "snap"
1616                 return stable;
1617         else
1618                 return min(stable, current + (stable - current) * regenfactor * frametime);
1619 }
1620
1621 void player_regen (void)
1622 {
1623         float maxh, maxa, limith, limita, max_mod, regen_mod, rot_mod, limit_mod;
1624         maxh = cvar("g_balance_health_stable");
1625         maxa = cvar("g_balance_armor_stable");
1626         limith = cvar("g_balance_health_limit");
1627         limita = cvar("g_balance_armor_limit");
1628
1629         if (g_minstagib || (g_lms && !cvar("g_lms_regenerate")))
1630                 return;
1631
1632         max_mod = regen_mod = rot_mod = limit_mod = 1;
1633
1634         if (self.runes & RUNE_REGEN)
1635         {
1636                 if (self.runes & CURSE_VENOM) // do we have both rune/curse?
1637                 {
1638                         regen_mod = cvar("g_balance_rune_regen_combo_regenrate");
1639                         max_mod = cvar("g_balance_rune_regen_combo_hpmod");
1640                         limit_mod = cvar("g_balance_rune_regen_combo_limitmod");
1641                 }
1642                 else
1643                 {
1644                         regen_mod = cvar("g_balance_rune_regen_regenrate");
1645                         max_mod = cvar("g_balance_rune_regen_hpmod");
1646                         limit_mod = cvar("g_balance_rune_regen_limitmod");
1647                 }
1648         }
1649         else if (self.runes & CURSE_VENOM)
1650         {
1651                 max_mod = cvar("g_balance_curse_venom_hpmod");
1652                 if (self.runes & RUNE_REGEN) // do we have both rune/curse?
1653                         rot_mod = cvar("g_balance_rune_regen_combo_rotrate");
1654                 else
1655                         rot_mod = cvar("g_balance_curse_venom_rotrate");
1656                 limit_mod = cvar("g_balance_curse_venom_limitmod");
1657                 //if (!self.runes & RUNE_REGEN)
1658                 //      rot_mod = cvar("g_balance_curse_venom_rotrate");
1659         }
1660         maxh = maxh * max_mod;
1661         //maxa = maxa * max_mod;
1662         limith = limith * limit_mod;
1663         limita = limita * limit_mod;
1664
1665         if (self.armorvalue > maxa)
1666         {
1667                 if (time > self.pauserotarmor_finished)
1668                 {
1669                         self.armorvalue = max(maxa, self.armorvalue + (maxa - self.armorvalue) * cvar("g_balance_armor_rot") * frametime);
1670                         self.armorvalue = max(maxa, self.armorvalue - cvar("g_balance_armor_rotlinear") * frametime);
1671                 }
1672         }
1673         else if (self.armorvalue < maxa)
1674         {
1675                 if (time > self.pauseregen_finished)
1676                 {
1677                         self.armorvalue = CalcRegen(self.armorvalue, maxa, cvar("g_balance_armor_regen"));
1678                         self.armorvalue = min(maxa, self.armorvalue + cvar("g_balance_armor_regenlinear") * frametime);
1679                 }
1680         }
1681         if (self.health > maxh)
1682         {
1683                 if (time > self.pauserothealth_finished)
1684                 {
1685                         self.health = max(maxh, self.health + (maxh - self.health) * rot_mod*cvar("g_balance_health_rot") * frametime);
1686                         self.health = max(maxh, self.health - rot_mod*cvar("g_balance_health_rotlinear") * frametime);
1687                 }
1688         }
1689         else if (self.health < maxh)
1690         {
1691                 if (time > self.pauseregen_finished)
1692                 {
1693                         self.health = CalcRegen(self.health, maxh, regen_mod * cvar("g_balance_health_regen"));
1694                         self.health = min(maxh, self.health + regen_mod*cvar("g_balance_health_regenlinear") * frametime);
1695                 }
1696         }
1697
1698         if (self.health > limith)
1699                 self.health = limith;
1700         if (self.armorvalue > limita)
1701                 self.armorvalue = limita;
1702
1703         // if player rotted to death...  die!
1704         if(self.health < 1)
1705                 self.event_damage(self, self, 1, DEATH_ROT, self.origin, '0 0 0');
1706 }
1707
1708 .float zoomstate;
1709 float zoomstate_set;
1710 void SetZoomState(float z)
1711 {
1712         if(z != self.zoomstate)
1713         {
1714                 msg_entity = self;
1715                 WriteByte(MSG_ONE, SVC_TEMPENTITY);
1716                 WriteByte(MSG_ONE, TE_CSQC_ZOOMNOTIFY);
1717                 WriteByte(MSG_ONE, z);
1718                 self.zoomstate = z;
1719         }
1720         zoomstate_set = 1;
1721 }
1722
1723 /*
1724 ======================
1725 spectate mode routines
1726 ======================
1727 */
1728 void SpectateCopy(entity spectatee) {
1729         self.armortype = spectatee.armortype;
1730         self.armorvalue = spectatee.armorvalue;
1731         self.currentammo = spectatee.currentammo;
1732         self.effects = spectatee.effects;
1733         self.health = spectatee.health;
1734         self.impulse = 0;
1735         self.items = spectatee.items;
1736         self.weapons = spectatee.weapons;
1737         self.punchangle = spectatee.punchangle;
1738         self.view_ofs = spectatee.view_ofs;
1739         self.v_angle = spectatee.v_angle;
1740         self.velocity = spectatee.velocity;
1741         self.dmg_take = spectatee.dmg_take;
1742         self.dmg_save = spectatee.dmg_save;
1743         self.dmg_inflictor = spectatee.dmg_inflictor;
1744         self.angles = spectatee.v_angle;
1745         self.fixangle = TRUE;
1746         setorigin(self, spectatee.origin);
1747         setsize(self, spectatee.mins, spectatee.maxs);
1748         SetZoomState(spectatee.zoomstate);
1749 }
1750
1751 float SpectateUpdate() {
1752         if(!self.enemy)
1753                 return 0;
1754
1755         if (self == self.enemy)
1756                 return 0;
1757         
1758         if(self.enemy.flags & FL_NOTARGET)
1759                 return 0;
1760
1761         SpectateCopy(self.enemy);
1762
1763         return 1;
1764 }
1765
1766 float SpectateNext() {
1767         other = find(self.enemy, classname, "player");
1768         if (!other) {
1769                 other = find(other, classname, "player");
1770         }
1771         if (other) {
1772                 self.enemy = other;
1773         }
1774         if(self.enemy.classname == "player") {
1775                 msg_entity = self;
1776                 WriteByte(MSG_ONE, SVC_SETVIEW);
1777                 WriteEntity(MSG_ONE, self.enemy);
1778                 self.wantswelcomemessage = 1;
1779                 //stuffcmd(self, "set viewsize $tmpviewsize \n");
1780                 if(!SpectateUpdate())
1781                         PutObserverInServer();
1782                 return 1;
1783         } else {
1784                 return 0;
1785         }
1786 }
1787
1788 /*
1789 =============
1790 ShowRespawnCountdown()
1791
1792 Update a respawn countdown display.
1793 =============
1794 */
1795 void ShowRespawnCountdown()
1796 {
1797         float number;
1798         if(self.deadflag == DEAD_NO) // just respawned?
1799                 return;
1800         else
1801         {
1802                 number = ceil(self.death_time - time);
1803                 if(number <= 0)
1804                         return;
1805                 if(number <= self.respawn_countdown)
1806                 {
1807                         self.respawn_countdown = number - 1;
1808                         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
1809                                 announce(self, strcat("announcer/robotic/", ftos(number), ".ogg"));
1810                 }
1811         }
1812 }
1813
1814 void LeaveSpectatorMode()
1815 {
1816         if(isJoinAllowed()) {
1817                 if(!cvar("teamplay") || cvar("g_campaign") || cvar("g_balance_teams")) {
1818                         self.classname = "player";
1819                         if(cvar("g_campaign") || cvar("g_balance_teams") || cvar("g_balance_teams_force"))
1820                                 JoinBestTeam(self, FALSE, TRUE);
1821                         if(cvar("g_campaign"))
1822                                 campaign_bots_may_start = 1;
1823                         PutClientInServer();
1824                         if(!(self.flags & FL_NOTARGET))
1825                                 bprint ("^4", self.netname, "^4 is playing now\n");
1826                         centerprint(self,"");
1827                         return;
1828                 } else {
1829                         stuffcmd(self,"menu_showteamselect\n");
1830                         return;
1831                 }
1832         }
1833         else {
1834                 //player may not join because of g_maxplayers is set
1835                 centerprint_atprio(self, CENTERPRIO_MAPVOTE, PREVENT_JOIN_TEXT);
1836         }
1837 }
1838
1839 /**
1840  * Determines whether the player is allowed to join. This depends on cvar
1841  * g_maxplayers, if it isn't used this function always return TRUE, otherwise
1842  * it checks whether the number of currently playing players exceeds g_maxplayers.
1843  * @return bool TRUE if the player is allowed to join, false otherwise
1844  */
1845 float isJoinAllowed() {
1846         if (!cvar("g_maxplayers"))
1847                 return TRUE;
1848
1849         local entity e;
1850         local float currentlyPlaying;
1851         FOR_EACH_REALPLAYER(e) {
1852                 if(e.classname == "player")
1853                         currentlyPlaying += 1;
1854         }
1855         if(currentlyPlaying < cvar("g_maxplayers"))
1856                 return TRUE;
1857
1858         return FALSE;
1859 }
1860
1861 /**
1862  * Checks whether the client is an observer or spectator, if so, he will get kicked after
1863  * g_maxplayers_spectator_blocktime seconds
1864  */
1865 void checkSpectatorBlock() {
1866         if(self.classname == "spectator" || self.classname == "observer") {
1867                 if( time > (self.spectatortime + cvar("g_maxplayers_spectator_blocktime")) ) {
1868                         sprint(self, "^7You were kicked from the server because you are spectator and spectators aren't allowed at the moment.\n");
1869                         dropclient(self);
1870                 }
1871         }
1872 }
1873
1874 float vercmp_recursive(string v1, string v2)
1875 {
1876         float dot1, dot2;
1877         string s1, s2;
1878         float r;
1879
1880         dot1 = strstrofs(v1, ".", 0);
1881         dot2 = strstrofs(v2, ".", 0);
1882         if(dot1 == -1)
1883                 s1 = v1;
1884         else
1885                 s1 = substring(v1, 0, dot1);
1886         if(dot2 == -1)
1887                 s2 = v2;
1888         else
1889                 s2 = substring(v2, 0, dot2);
1890
1891         r = stof(s1) - stof(s2);
1892         if(r != 0)
1893                 return r;
1894
1895         r = strcasecmp(s1, s2);
1896         if(r != 0)
1897                 return r;
1898
1899         if(dot1 == -1)
1900                 if(dot2 == -1)
1901                         return 0;
1902                 else
1903                         return -1;
1904         else
1905                 if(dot2 == -1)
1906                         return 1;
1907                 else
1908                         return vercmp_recursive(substring(v1, dot1 + 1, 999), substring(v2, dot2 + 1, 999));
1909 }
1910
1911 float vercmp(string v1, string v2)
1912 {
1913         if(strcasecmp(v1, v2) == 0) // early out check
1914                 return 0;
1915         return vercmp_recursive(v1, v2);
1916 }
1917
1918 void ObserverThink()
1919 {
1920         if (self.flags & FL_JUMPRELEASED) {
1921                 if (self.BUTTON_JUMP && !self.version_mismatch) {
1922                         self.welcomemessage_time = 0;
1923                         self.flags = self.flags - FL_JUMPRELEASED;
1924                         LeaveSpectatorMode();
1925                         return;
1926                 } else if(self.BUTTON_ATCK && !self.version_mismatch) {
1927                         self.welcomemessage_time = 0;
1928                         self.flags = self.flags - FL_JUMPRELEASED;
1929                         if(SpectateNext() == 1) {
1930                                 self.classname = "spectator";
1931                         }
1932                 }
1933         } else {
1934                 if (!(self.BUTTON_ATCK || self.BUTTON_JUMP)) {
1935                         self.flags = self.flags | FL_JUMPRELEASED;
1936                 }
1937         }
1938         if(self.BUTTON_ZOOM)
1939                 self.wantswelcomemessage = 0;
1940         if(self.wantswelcomemessage)
1941                 PrintWelcomeMessage(self);
1942 }
1943
1944 void SpectatorThink()
1945 {
1946         if (self.flags & FL_JUMPRELEASED) {
1947                 if (self.BUTTON_JUMP && !self.version_mismatch) {
1948                         self.welcomemessage_time = 0;
1949                         self.flags = self.flags - FL_JUMPRELEASED;
1950                         LeaveSpectatorMode();
1951                         return;
1952                 } else if(self.BUTTON_ATCK) {
1953                         self.welcomemessage_time = 0;
1954                         self.flags = self.flags - FL_JUMPRELEASED;
1955                         if(SpectateNext() == 1) {
1956                                 self.classname = "spectator";
1957                         } else {
1958                                 self.classname = "observer";
1959                                 PutClientInServer();
1960                         }
1961                 } else if (self.BUTTON_ATCK2) {
1962                         self.welcomemessage_time = 0;
1963                         self.flags = self.flags - FL_JUMPRELEASED;
1964                         self.classname = "observer";
1965                         PutClientInServer();
1966                 } else {
1967                         if(!SpectateUpdate())
1968                                 PutObserverInServer();
1969                 }
1970         } else {
1971                 if (!(self.BUTTON_ATCK || self.BUTTON_ATCK2)) {
1972                         self.flags = self.flags | FL_JUMPRELEASED;
1973                 }
1974         }
1975         if(self.BUTTON_ZOOM)
1976                 self.wantswelcomemessage = 0;
1977         if(self.wantswelcomemessage)
1978                 PrintWelcomeMessage(self);
1979         self.flags = self.flags | FL_CLIENT | FL_NOTARGET;
1980 }
1981
1982 /*
1983 =============
1984 PlayerPreThink
1985
1986 Called every frame for each client before the physics are run
1987 =============
1988 */
1989 void() ctf_setstatus;
1990 .float vote_nagtime;
1991 .float spectatee_status;
1992 void PlayerPreThink (void)
1993 {
1994         self.stat_sys_ticrate = cvar("sys_ticrate");
1995         if(blockSpectators)
1996                 checkSpectatorBlock();
1997         
1998         zoomstate_set = 0;
1999
2000         if(self.netname_previous != self.netname)
2001         {
2002                 if(cvar("sv_eventlog"))
2003                         GameLogEcho(strcat(":name:", ftos(self.playerid), ":", self.netname));
2004                 if(self.netname_previous)
2005                         strunzone(self.netname_previous);
2006                 self.netname_previous = strzone(self.netname);
2007         }
2008
2009         // version nagging
2010         if(self.version_nagtime)
2011                 if(self.cvar_g_nexuizversion)
2012                         if(time > self.version_nagtime)
2013                         {
2014                                 if(strstr(self.cvar_g_nexuizversion, "svn", 0) < 0)
2015                                 {
2016                                         if(strstr(cvar_string("g_nexuizversion"), "svn", 0) >= 0)
2017                                         {
2018                                                 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");
2019                                                 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"));
2020                                         }
2021                                         else
2022                                         {
2023                                                 float r;
2024                                                 r = vercmp(self.cvar_g_nexuizversion, cvar_string("g_nexuizversion"));
2025                                                 if(r < 0)
2026                                                 {
2027                                                         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");
2028                                                         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"));
2029                                                 }
2030                                                 else if(r > 0)
2031                                                 {
2032                                                         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");
2033                                                         sprint(self, strcat("\{1}^1NOTE: ^7the server is running ^3Nexuiz ", cvar_string("g_nexuizversion"), "^7, you have ^3Nexuiz ", self.cvar_g_nexuizversion, "^1\n"));
2034                                                 }
2035                                         }
2036                                 }
2037                                 self.version_nagtime = 0;
2038                         }
2039
2040         // vote nagging
2041         if(self.cvar_scr_centertime)
2042                 if(time > self.vote_nagtime)
2043                 {
2044                         VoteNag();
2045                         self.vote_nagtime = time + self.cvar_scr_centertime * 0.6;
2046                 }
2047
2048         // GOD MODE info
2049         if(!(self.flags & FL_GODMODE)) if(self.max_armorvalue)
2050         {
2051                 sprint(self, strcat("godmode saved you ", ftos(self.max_armorvalue), " units of damage, cheater!\n"));
2052                 self.max_armorvalue = 0;
2053         }
2054
2055         if(frametime)
2056         {
2057                 antilag_record(self);
2058
2059                 SendFog();
2060         }
2061
2062         if(self.classname == "player") {
2063 //              if(self.netname == "Wazat")
2064 //                      bprint(self.classname, "\n");
2065
2066                 CheckRules_Player();
2067
2068                 if(self.BUTTON_INFO)
2069                         PrintWelcomeMessage(self);
2070
2071                 if(g_lms || !cvar("sv_spectate"))
2072                 if((time - self.jointime) <= cvar("welcome_message_time"))
2073                         PrintWelcomeMessage(self);
2074
2075                 if (intermission_running)
2076                 {
2077                         IntermissionThink ();   // otherwise a button could be missed between
2078                         return;                                 // the think tics
2079                 }
2080
2081                 if(self.teleport_time)
2082                 if(time > self.teleport_time)
2083                 {
2084                         self.teleport_time = 0;
2085                         self.effects = self.effects - (self.effects & EF_NODRAW);
2086                         if(self.weaponentity)
2087                                 self.weaponentity.flags = self.weaponentity.flags - (self.weaponentity.flags & EF_NODRAW);
2088                 }
2089
2090                 Nixnex_GiveCurrentWeapon();
2091
2092                 if(frametime > 0) // don't do this in cl_movement frames, just in server ticks
2093                         UpdateSelectedPlayer();
2094
2095                 //don't allow the player to turn around while game is paused!
2096                 if(timeoutStatus == 2) {
2097                         self.v_angle = self.lastV_angle;
2098                         self.angles = self.lastV_angle;
2099                         self.fixangle = TRUE;
2100                 }
2101
2102                 if (self.deadflag != DEAD_NO)
2103                 {
2104                         float button_pressed, force_respawn;
2105                         player_anim();
2106                         button_pressed = (self.BUTTON_ATCK || self.BUTTON_JUMP || self.BUTTON_ATCK2 || self.BUTTON_HOOK || self.BUTTON_USE);
2107                         force_respawn = (g_lms || cvar("g_forced_respawn"));
2108                         if (self.deadflag == DEAD_DYING)
2109                         {
2110                                 if(force_respawn)
2111                                         self.deadflag = DEAD_RESPAWNING;
2112                                 else if(!button_pressed)
2113                                         self.deadflag = DEAD_DEAD;
2114                         }
2115                         else if (self.deadflag == DEAD_DEAD)
2116                         {
2117                                 if(button_pressed)
2118                                         self.deadflag = DEAD_RESPAWNABLE;
2119                         }
2120                         else if (self.deadflag == DEAD_RESPAWNABLE)
2121                         {
2122                                 if(!button_pressed)
2123                                         self.deadflag = DEAD_RESPAWNING;
2124                         }
2125                         else if (self.deadflag == DEAD_RESPAWNING)
2126                         {
2127                                 if(time > self.death_time)
2128                                 {
2129                                         self.death_time = time + 1; // only retry once a second
2130                                         respawn();
2131                                 }
2132                         }
2133                         ShowRespawnCountdown();
2134                         return;
2135                 }
2136
2137                 if(g_lms && !self.deadflag && cvar("g_lms_campcheck_interval"))
2138                 {
2139                         vector dist;
2140
2141                         // calculate player movement (in 2 dimensions only, so jumping on one spot doesn't count as movement)
2142                         dist = self.oldorigin - self.origin;
2143                         dist_z = 0;
2144                         self.lms_traveled_distance += fabs(vlen(dist));
2145
2146                         if((cvar("g_campaign") && !campaign_bots_may_start) || (time < restart_countdown))
2147                         {
2148                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval")*2;
2149                                 self.lms_traveled_distance = 0;
2150                         }
2151
2152                         if(time > self.lms_nextcheck)
2153                         {
2154                                 //sprint(self, "distance: ", ftos(self.lms_traveled_distance), "\n");
2155                                 if(self.lms_traveled_distance < cvar("g_lms_campcheck_distance"))
2156                                 {
2157                                         centerprint(self, cvar_string("g_lms_campcheck_message"));
2158                                         // FIXME KadaverJack: gibbing player here causes playermodel to bounce around, instead of eye.md3
2159                                         // I wasn't able to find out WHY that happens, so I put a workaround in place that shall prevent players from being gibbed :(
2160                                         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');
2161                                 }
2162                                 self.lms_nextcheck = time + cvar("g_lms_campcheck_interval");
2163                                 self.lms_traveled_distance = 0;
2164                         }
2165                 }
2166
2167                 if (self.BUTTON_CROUCH && !self.hook.state)
2168                 {
2169                         if (!self.crouch)
2170                         {
2171                                 self.crouch = TRUE;
2172                                 self.view_ofs = PL_CROUCH_VIEW_OFS;
2173                                 setsize (self, PL_CROUCH_MIN, PL_CROUCH_MAX);
2174                                 player_setanim(self.anim_duck, FALSE, TRUE, TRUE);
2175                         }
2176                 }
2177                 else
2178                 {
2179                         if (self.crouch)
2180                         {
2181                                 tracebox(self.origin, PL_MIN, PL_MAX, self.origin, FALSE, self);
2182                                 if (!trace_startsolid)
2183                                 {
2184                                         self.crouch = FALSE;
2185                                         self.view_ofs = PL_VIEW_OFS;
2186                                         setsize (self, PL_MIN, PL_MAX);
2187                                 }
2188                         }
2189                 }
2190
2191                 FixPlayermodel();
2192
2193                 GrapplingHookFrame();
2194
2195                 W_WeaponFrame();
2196
2197                 player_powerups();
2198                 player_regen();
2199                 player_anim();
2200
2201                 if (g_minstagib)
2202                         minstagib_ammocheck();
2203
2204                 ctf_setstatus();
2205                 kh_setstatus();
2206
2207                 //self.angles_y=self.v_angle_y + 90;   // temp
2208
2209                 //if (TetrisPreFrame()) return;
2210         } else if(gameover) {
2211                 if (intermission_running)
2212                         IntermissionThink ();   // otherwise a button could be missed between
2213                 return;
2214         } else if(self.classname == "observer") {
2215                 ObserverThink();
2216         } else if(self.classname == "spectator") {
2217                 SpectatorThink();
2218         }
2219
2220         if(!zoomstate_set)
2221                 SetZoomState(self.BUTTON_ZOOM || (self.BUTTON_ATCK2 && self.weapon == WEP_NEX));
2222
2223         float oldspectatee_status;
2224         oldspectatee_status = self.spectatee_status;
2225         if(self.classname == "spectator")
2226                 self.spectatee_status = num_for_edict(self.enemy);
2227         else if(self.classname == "observer")
2228                 self.spectatee_status = num_for_edict(self);
2229         else
2230                 self.spectatee_status = 0;
2231         if(self.spectatee_status != oldspectatee_status)
2232         {
2233                 msg_entity = self;
2234                 WriteByte(MSG_ONE, SVC_TEMPENTITY);
2235                 WriteByte(MSG_ONE, TE_CSQC_SPECTATING);
2236                 WriteByte(MSG_ONE, self.spectatee_status);
2237                 if(g_race)
2238                         race_InitSpectator();
2239         }
2240 }
2241
2242
2243 /*
2244 =============
2245 PlayerPostThink
2246
2247 Called every frame for each client after the physics are run
2248 =============
2249 */
2250 .float idlekick_lasttimeleft;
2251 .float race_penalty;
2252 .float race_penalty_nagged;
2253 void PlayerPostThink (void)
2254 {
2255         // Savage: Check for nameless players
2256         if (strlen(self.netname) < 1) {
2257                 self.netname = "Player";
2258                 stuffcmd(self, "seta _cl_name Player\n");
2259         }
2260
2261         if(sv_maxidle)
2262         {
2263                 float timeleft;
2264                 timeleft = ceil(sv_maxidle - (time - self.parm_idlesince));
2265                 if(timeleft <= 0)
2266                 {
2267                         bprint("^3", self.netname, "^3 was kicked for idling.\n");
2268                         announce(self, "announcer/robotic/terminated.ogg");
2269                         dropclient(self);
2270                         return;
2271                 }
2272                 else if(timeleft <= 10)
2273                 {
2274                         if(timeleft != self.idlekick_lasttimeleft)
2275                         {
2276                                 centerprint_atprio(self, CENTERPRIO_IDLEKICK, strcat("^3Stop idling!\n^3Disconnecting in ", ftos(timeleft), "..."));
2277                                 announce(self, strcat("announcer/robotic/", ftos(timeleft), ".ogg"));
2278                         }
2279                 }
2280                 else
2281                 {
2282                         centerprint_expire(self, CENTERPRIO_IDLEKICK);
2283                 }
2284                 self.idlekick_lasttimeleft = timeleft;
2285         }
2286
2287         if(self.classname == "player") {
2288                 CheckRules_Player();
2289                 UpdateChatBubble();
2290                 UpdateTeamBubble();
2291                 if (self.impulse)
2292                         ImpulseCommands();
2293                 if (intermission_running)
2294                         return;         // intermission or finale
2295
2296                 //PrintWelcomeMessage(self);
2297                 //if (TetrisPostFrame()) return;
2298
2299                 // restart countdown
2300                 if (restart_countdown) {
2301                         if(time < restart_countdown) {
2302                                 if (!cvar("sv_ready_restart_after_countdown"))
2303                                 {
2304                                         if(self.movement != '0 0 0' && g_race && !g_race_qualifying)
2305                                         {
2306                                                 if(time < restart_countdown - 2)
2307                                                 {
2308                                                         if(!self.race_penalty_nagged)
2309                                                         {
2310                                                                 centerprint_atprio(self, CENTERPRIO_IDLEKICK, "^1DO NOT MOVE DURING THE COUNTDOWN.");
2311                                                                 self.race_penalty_nagged = 1;
2312                                                         }
2313                                                 }
2314                                                 else if(!self.race_penalty)
2315                                                 {
2316                                                         centerprint_atprio(self, CENTERPRIO_IDLEKICK, "^1FIVE SECONDS PENALTY.");
2317                                                         self.race_penalty = time + 5;
2318                                                 }
2319                                         }
2320                                         self.movetype = MOVETYPE_NONE;          
2321                                         self.velocity = '0 0 0';
2322                                         self.avelocity = '0 0 0';
2323                                         self.movement = '0 0 0';
2324                                 }
2325                         }
2326                         else if (time < self.race_penalty)
2327                         {
2328                                 self.movetype = MOVETYPE_NONE;          
2329                                 self.velocity = '0 0 0';
2330                                 self.avelocity = '0 0 0';
2331                                 self.movement = '0 0 0';
2332                         }
2333                         else
2334                         {
2335                                 //allow the player to move again if sv_ready_restart_after_countdown is not used and countdown is over
2336                                 if (!cvar("sv_ready_restart_after_countdown"))
2337                                 {
2338                                         if(self.movetype == MOVETYPE_NONE)
2339                                         {
2340                                                 self.movetype = MOVETYPE_WALK;
2341                                         }
2342                                         self.race_penalty = 0;
2343                                         self.race_penalty_nagged = 0;
2344                                 }
2345                         }
2346                 }
2347                 
2348         } else if (self.classname == "observer") {
2349                 //do nothing
2350         } else if (self.classname == "spectator") {
2351                 //do nothing
2352         }
2353
2354         /*
2355         float i;
2356         for(i = 0; i < 1000; ++i)
2357         {
2358                 vector end;
2359                 end = self.origin + '0 0 1024' + 512 * randomvec();
2360                 tracebox(self.origin, self.mins, self.maxs, end, MOVE_NORMAL, self);
2361                 if(trace_fraction < 1)
2362                 if(!(trace_dphitq3surfaceflags & Q3SURFACEFLAG_NOIMPACT))
2363                 {
2364                         print("I HIT SOLID: ", vtos(self.origin), " -> ", vtos(end), "\n");
2365                         break;
2366                 }
2367         }
2368         */
2369
2370         Arena_Warmup();
2371 }